Merge branch 'main' into add-issue-planned-time

This commit is contained in:
stuzer05 2023-04-18 07:16:00 +03:00
commit fc93006f50
No known key found for this signature in database
GPG Key ID: A6ABAAA9268F9F4F
1435 changed files with 33582 additions and 29765 deletions

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,7 @@ plugins:
- eslint-plugin-import
- eslint-plugin-jquery
- eslint-plugin-sonarjs
- eslint-plugin-custom-elements
env:
es2022: true
@ -62,6 +63,19 @@ rules:
consistent-this: [0]
constructor-super: [2]
curly: [0]
custom-elements/expose-class-on-global: [0]
custom-elements/extends-correct-class: [2]
custom-elements/file-name-matches-element: [0]
custom-elements/no-constructor: [2]
custom-elements/no-customized-built-in-elements: [2]
custom-elements/no-dom-traversal-in-attributechangedcallback: [2]
custom-elements/no-dom-traversal-in-connectedcallback: [2]
custom-elements/no-exports-with-element: [2]
custom-elements/no-method-prefixed-with-on: [2]
custom-elements/no-unchecked-define: [0]
custom-elements/one-element-per-file: [0]
custom-elements/tag-name-matches-class: [2]
custom-elements/valid-tag-name: [2]
default-case-last: [2]
default-case: [0]
default-param-last: [0]
@ -164,7 +178,7 @@ rules:
jquery/no-parse-html: [2]
jquery/no-prop: [0]
jquery/no-proxy: [2]
jquery/no-ready: [0]
jquery/no-ready: [2]
jquery/no-serialize: [2]
jquery/no-show: [2]
jquery/no-size: [2]

View File

@ -23,10 +23,6 @@ tasks:
gp sync-await setup
make watch-frontend
openMode: split-right
- name: Run docs
before: sudo bash -c "$(grep 'https://github.com/gohugoio/hugo/releases/download' Makefile | tr -d '\')" # install hugo
command: cd docs && make clean update && hugo server -D -F --baseUrl $(gp url 1313) --liveReloadPort=443 --appendPort=false --bind=0.0.0.0
openMode: split-right
vscode:
extensions:
@ -43,5 +39,3 @@ vscode:
ports:
- name: Gitea
port: 3000
- name: Docs
port: 1313

1
.npmrc
View File

@ -3,3 +3,4 @@ fund=false
update-notifier=false
package-lock=true
save-exact=true
lockfile-version=3

View File

@ -1,12 +1,16 @@
plugins:
- stylelint-declaration-strict-value
ignoreFiles:
- "**/*.go"
overrides:
- files: ["**/*.less"]
customSyntax: postcss-less
- files: ["**/chroma/*", "**/codemirror/*", "**/standalone/*", "**/console/*"]
rules:
scale-unlimited/declaration-strict-value: null
- files: ["**/chroma/*", "**/codemirror/*"]
rules:
block-no-empty: null
rules:
alpha-value-notation: null
@ -84,6 +88,7 @@ rules:
no-invalid-position-at-import-rule: null
no-irregular-whitespace: true
no-unknown-animations: null
no-unknown-custom-properties: null
number-max-precision: null
property-allowed-list: null
property-disallowed-list: null

View File

@ -1,6 +1,7 @@
# GNU makefile proxy script for BSD make
#
# Written and maintained by Mahmoud Al-Qudsi <mqudsi@neosmart.net>
# Copyright NeoSmart Technologies <https://neosmart.net/> 2014-2018
# Copyright NeoSmart Technologies <https://neosmart.net/> 2014-2019
# Obtain updates from <https://github.com/neosmart/gmake-proxy>
#
# Redistribution and use in source and binary forms, with or without
@ -26,26 +27,32 @@
JARG =
GMAKE = "gmake"
#When gmake is called from another make instance, -w is automatically added
#which causes extraneous messages about directory changes to be emitted.
#--no-print-directory silences these messages.
# When gmake is called from another make instance, -w is automatically added
# which causes extraneous messages about directory changes to be emitted.
# Running with --no-print-directory silences these messages.
GARGS = "--no-print-directory"
.if "$(.MAKE.JOBS)" != ""
JARG = -j$(.MAKE.JOBS)
JARG = -j$(.MAKE.JOBS)
.endif
#by default bmake will cd into ./obj first
# bmake prefers out-of-source builds and tries to cd into ./obj (among others)
# where possible. GNU Make doesn't, so override that value.
.OBJDIR: ./
# The GNU convention is to use the lowercased `prefix` variable/macro to
# specify the installation directory. Humor them.
GPREFIX = ""
.if defined(PREFIX) && ! defined(prefix)
GPREFIX = 'prefix = "$(PREFIX)"'
.endif
.BEGIN: .SILENT
which $(GMAKE) || printf "Error: GNU Make is required!\n\n" 1>&2 && false
.PHONY: FRC
$(.TARGETS): FRC
$(GMAKE) $(GARGS) $(.TARGETS:S,.DONE,,) $(JARG)
$(GMAKE) $(GPREFIX) $(GARGS) $(.TARGETS:S,.DONE,,) $(JARG)
.DONE .DEFAULT: .SILENT
$(GMAKE) $(GARGS) $(.TARGETS:S,.DONE,,) $(JARG)
.ERROR: .SILENT
if ! which $(GMAKE) > /dev/null; then \
echo "GNU Make is required!"; \
fi
$(GMAKE) $(GPREFIX) $(GARGS) $(.TARGETS:S,.DONE,,) $(JARG)

View File

@ -4,6 +4,445 @@ This changelog goes through all the changes that have been made in each release
without substantial changes to our git log; to see the highlights of what has
been added to each release, please refer to the [blog](https://blog.gitea.io).
## [1.19.1](https://github.com/go-gitea/gitea/releases/tag/v1.19.1) - 2023-04-12
* BREAKING
* Rename actions unit to `repo.actions` and add docs for it (#23733) (#23881)
* ENHANCEMENTS
* Add card type to org/user level project on creation, edit and view (#24043) (#24066)
* Refactor commit status for Actions jobs (#23786) (#24060)
* Show errors for KaTeX and mermaid on the preview tab (#24009) (#24019)
* Show protected branch rule names again (#23907) (#24018)
* Adjust sticky PR header to cover background (#23956) (#23999)
* Discolor pull request tab labels (#23950) (#23987)
* Treat PRs with agit flow as fork PRs when triggering actions. (#23884) (#23967)
* Left-align review comments (#23937)
* Fix image border-radius (#23886) (#23930)
* Scroll collapsed file into view (#23702) (#23929)
* Fix code view (diff) broken layout (#23096) (#23918)
* Org pages style fixes (#23901) (#23914)
* Fix user profile description rendering (#23882) (#23902)
* Fix review box viewport overflow issue (#23800) (#23898)
* Prefill input values in OAuth settings as intended (#23829) (#23871)
* CSS color tweaks (#23828) (#23842)
* Fix incorrect visibility dropdown list in add/edit user page (#23804) (#23833)
* Add CSS rules for basic colored labels (#23774) (#23777)
* Add creation time in tag list page (#23693) (#23773)
* Fix br display for packages curls (#23737) (#23764)
* Fix issue due date edit toggle bug (#23723) (#23758)
* Improve commit graph page UI alignment (#23751) (#23754)
* Use GitHub Actions compatible globbing for `branches`, `tag`, `path` filter (#22804) (#23740)
* Redirect to project again after editing it (#23326) (#23739)
* Remove row clicking from notification table (#22695) (#23706)
* Remove conflicting CSS rules on notifications, improve notifications table (#23565) (#23621)
* Fix diff tree height and adjust target file style (#23616)
* BUGFIXES
* Improve error logging for LFS (#24072) (#24082)
* Fix custom mailer template on Windows platform (#24081)
* Update the value of `diffEnd` when clicking the `Show More` button in the DiffFileTree (#24069) (#24078)
* Make label templates have consistent behavior and priority (#23749)
* Fix accidental overwriting of LDAP team memberships (#24050) (#24065)
* Fix branch protection priority (#24045) (#24061)
* Use actions job link as commit status URL instead of run link (#24023) (#24032)
* Add actions support to package auth verification (#23729) (#24028)
* Fix protected branch for API (#24013) (#24027)
* Do not escape space between PyPI repository URL and package name… (#23981) (#24008)
* Fix redirect bug when creating issue from a project (#23971) (#23997)
* Set `ref` to fully-formed of the tag when trigger event is `release` (#23944) (#23989)
* Use Get/Set instead of Rename when regenerating session ID (#23975) (#23983)
* Ensure RSS icon is present on all repo tabs (#23904) (#23973)
* Remove `Repository.getFilesChanged` to fix Actions `paths` and `paths-ignore` filter (#23920) (#23969)
* Delete deleted release attachments immediately from storage (#23913) (#23958)
* Use ghost user if package creator does not exist (#23822) (#23915)
* User/Org Feed render description as per web (#23887) (#23906)
* Fix `cases.Title` crash for concurrency (#23885) (#23903)
* Convert .Source.SkipVerify to $cfg.SkipVerify (#23839) (#23899)
* Support "." char as user name for User/Orgs in RSS/ATOM/GPG/KEYS path ... (#23874) (#23878)
* Fix JS error when changing PR's target branch (#23862) (#23864)
* Fix 500 error if there is a name conflict when editing authentication source (#23832) (#23852)
* Fix closed PR also triggers Webhooks and actions (#23782) (#23834)
* Fix checks for `needs` in Actions (#23789) (#23831)
* Fix "Updating branch by merge" bug in "update_branch_by_merge.tmpl" (#23790) (#23825)
* Fix cancel button in the page of project edit not work (#23655) (#23813)
* Don't apply the group filter when listing LDAP group membership if it is empty (#23745) (#23788)
* Fix profile page email display, respect settings (#23747) (#23756)
* Fix project card preview select and template select (#23684) (#23731)
* Check LFS/Packages settings in dump and doctor command (#23631) (#23730)
* Add git dashes separator to some "log" and "diff" commands (#23606) (#23720)
* Create commit status when event is `pull_request_sync` (#23683) (#23691)
* Fix incorrect `HookEventType` of pull request review comments (#23650) (#23678)
* Fix incorrect `show-modal` and `show-panel` class (#23660) (#23663)
* Improve workflow event triggers (#23613) (#23648)
* Introduce path Clean/Join helper functions, partially backport&refactor (#23495) (#23607)
* Fix pagination on `/notifications/watching` (#23564) (#23603)
* Fix submodule is nil panic (#23588) (#23601)
* Polyfill the window.customElements (#23592) (#23595)
* Avoid too long names for actions (#23162) (#23190)
* TRANSLATION
* Backport locales (with manual fixes) (#23808, #23634, #24083)
* BUILD
* Hardcode the path to docker images (#23955) (#23968)
* DOCS
* Update documentation to explain which projects allow Gitea to host static pages (#23993) (#24058)
* Merge `push to create`, `open PR from push`, and `push options` docs articles into one (#23744) (#23959)
* Fix code blocks in the cheat sheet (#23664) (#23669)
* MISC
* Do not crash when parsing an invalid workflow file (#23972) (#23976)
* Remove assertion debug code for show/hide refactoring (#23576) (#23868)
* Add ONLY_SHOW_RELEVANT_REPOS back, fix explore page bug, make code more strict (#23766) (#23791)
* Make minio package support legacy MD5 checksum (#23768) (#23770)
* Improve template error reporting (#23396) (#23600)
## [1.19.0](https://github.com/go-gitea/gitea/releases/tag/v1.19.0) - 2023-03-19
* BREAKING
* Add loading yaml label template files (#22976) (#23232)
* Make issue and code search support camel case for Bleve (#22829)
* Repositories: by default disable all units except code and pulls on forks (#22541)
* Support template for merge message description (#22248)
* Remove ONLY_SHOW_RELEVANT_REPOS setting (#21962)
* Implement actions (#21937)
* Remove deprecated DSA host key from Docker Container (#21522)
* Improve valid user name check (#20136)
* SECURITY
* Return 404 instead of 403 if user can not access the repo (#23155) (#23158)
* Support scoped access tokens (#20908)
* FEATURES
* Add support for commit cross references (#22645)
* Scoped labels (#22585)
* Add Chef package registry (#22554)
* Support asciicast files as new markup (#22448)
* cgo cross-compile for freebsd (#22397)
* Add cron method to gc LFS MetaObjects (#22385)
* Add new captcha: cloudflare turnstile (#22369)
* Enable `@<user>`- completion popup on the release description textarea (#22359)
* make /{username}.png redirect to user/org avatar (#22356)
* Add Conda package registry (#22262)
* Support org/user level projects (#22235)
* Add Mermaid copy button (#22225)
* Add user secrets (#22191)
* Secrets storage with SecretKey encrypted (#22142)
* Preview images for Issue cards in Project Board view (#22112)
* Add support for incoming emails (#22056)
* Add Cargo package registry (#21888)
* Add option to prohibit fork if user reached maximum limit of repositories (#21848)
* Add attention blocks within quote blocks for `Note` and `Warning` (#21711)
* Add Feed for Releases and Tags (#21696)
* Add package registry cleanup rules (#21658)
* Add "Copy" button to file view of raw text (#21629)
* Allow disable sitemap (#21617)
* Add package registry quota limits (#21584)
* Map OIDC groups to Orgs/Teams (#21441)
* Keep languages defined in .gitattributes (#21403)
* Add Webhook authorization header (#20926)
* Supports wildcard protected branch (#20825)
* Copy citation file content, in APA and BibTex format, on repo home page (#19999)
* API
* Match api migration behavior to web behavior (#23552) (#23573)
* Purge API comment (#23451) (#23452)
* User creation API: allow custom "created" timestamps (#22549)
* Add `updated_at` field to PullReview API object (#21812)
* Add API management for issue/pull and comment attachments (#21783)
* Add API endpoint to get latest release (#21267)
* Support system hook API (#14537)
* ENHANCEMENTS
* Add `.patch` to `attachment.ALLOWED_TYPES` (#23580) (#23582)
* Fix sticky header in diff view (#23554) (#23568)
* Refactor merge/update git command calls (#23366) (#23544)
* Fix review comment context menu clipped bug (#23523) (#23543)
* Imrove scroll behavior to hash issuecomment(scroll position, auto expand if file is folded, and on refreshing) (#23513) (#23540)
* Increase horizontal page padding (#23507) (#23537)
* Use octicon-verified for gpg signatures (#23529) (#23536)
* Make time tooltips interactive (#23526) (#23527)
* Replace Less with CSS (#23508)
* Fix 'View File' button in code search (#23478) (#23483)
* Convert GitHub event on actions and fix some pull_request events. (#23037) (#23471)
* Support reflogs (#22451) (#23438)
* Fix actions frontend bugs (pagination, long name alignment) and small simplify (#23370) (#23436)
* Scoped label display and documentation tweaks (#23430) (#23433)
* Add missing tabs to org projects page (#22705) (#23412)
* Fix and move "Use this template" button (#23398) (#23408)
* Handle OpenID discovery URL errors a little nicer when creating/editing sources (#23397) (#23403)
* Rename `canWriteUnit` to `canWriteProjects` (#23386) (#23399)
* Refactor and tidy-up the merge/update branch code (#22568) (#23365)
* Refactor `setting.Database.UseXXX` to methods (#23354) (#23356)
* Fix incorrect project links and use symlink icon for org-wide projects (#23325) (#23336)
* Fix PR view misalignment caused by long name file (#23321) (#23335)
* Scoped labels: don't require holding alt key to remove (#23303) (#23331)
* Add context when rendering labels or emojis (#23281) (#23319)
* Change interactiveBorder to fix popup preview (#23169) (#23314)
* Scoped labels: set aria-disabled on muted Exclusive option for a11y (#23306) (#23311)
* update to mermaid v10 (#23178) (#23299)
* Fix code wrap for unbroken lines (#23268) (#23293)
* Use async await to fix empty quote reply at first time (#23168) (#23256)
* Fix switched citation format (#23250) (#23253)
* Allow `<video>` in MarkDown (#22892) (#23236)
* Order pull request conflict checking by recently updated, for each push (#23220) (#23225)
* Fix Fomantic UI's `touchstart` fastclick, always use `click` for click events (#23065) (#23195)
* Add word-break to sidebar-item-link (#23146) (#23180)
* Add InsecureSkipVerify to Minio Client for Storage (#23166) (#23177)
* Fix height for sticky head on large screen on PR page (#23111) (#23123)
* Change style to improve whitespaces trimming inside inline markdown code (#23093) (#23120)
* Avoid warning for system setting when start up (#23054) (#23116)
* Add accessibility to the menu on the navbar (#23059) (#23095)
* Improve accessibility for issue comments (#22612) (#23083)
* Remove delete button for review comment (#23036)
* Remove dashes between organization member avatars on hover (#23034)
* Use `gt-relative` class instead of the ambiguous `gt-pr` class (#23008)
* handle deprecated settings (#22992)
* Add scopes to API to create token and display them (#22989)
* Improve PR Review Box UI (#22986)
* Improve issues.LoadProject (#22982)
* Add all units to the units permission list in org team members sidebar (#22971)
* Rename `GetUnits` to `LoadUnits` (#22970)
* Rename `repo.GetOwner` to `repo.LoadOwner` (#22967)
* Rename "People" to "Members" in organization page and use a better icon (#22960)
* Fix avatar misalignment (#22955)
* Sort issues and pulls by recently updated in user and organization home (#22925)
* Add `title` to PR file tree items (#22918)
* First step to refactor the `.hide` to `.gt-hidden` (#22916)
* Add tooltip to issue reference (#22913)
* Always show the `command line instructions` button even if there are conflicts (#22909)
* Fix dark-colored description text in arc-green theme (#22908)
* Remove Fomantic-UI's `.hidden` CSS class for menu elements (#22895)
* Move helpers to be prefixed with `gt-` (#22879)
* Move `IsReadmeFile*` from `modules/markup/` to `modules/util` (#22877)
* Highlight focused diff file (#22870)
* Add some headings to repo views (#22869)
* Fix milestone title font problem (#22863)
* Pull Requests: setting to allow edits by maintainers by default, tweak UI (#22862)
* Introduce customized HTML elements, fix incorrect AppUrl usages in templates (#22861)
* Add `/$count` endpoints for NuGet v2 (#22855)
* Remove Fomantic-UI's `.hidden` CSS class for checkbox elements (#22851)
* Fix notification and stopwatch empty states (#22845)
* Always go full width in PR view (#22844)
* Improve AppUrl/ROOT_URL checking (#22836)
* Fix style of actions rerun button (#22835)
* Fix more HTMLURL in templates (#22831)
* Fix inconsistent Filter Project name in issue list (#22827)
* include build info in Prometheus metrics (#22819)
* Make clone URL use current page's host (#22808)
* Refactor legacy strange git operations (#22756)
* Improve error report when user passes a private key (#22726)
* set user dashboard org visibility to basic (#22706)
* Fix diff UI for unexpandable items (#22700)
* Remove 'primary' class from tab counter labels (#22687)
* Add more events details supports for actions (#22680)
* Refactor git command package to improve security and maintainability (#22678)
* Use relative url in actions view (#22675)
* set user visibility class to basic (#22674)
* Add repository setting to enable/disable releases unit (#22671)
* Remove label color from global issue filters (#22660)
* Fix poor alignment of organization description on organization home page (#22656)
* Small refactor for loading PRs (#22652)
* Allow setting access token scope by CLI (#22648)
* Improve accessibility of navigation bar and footer (#22635)
* Fixes accessibility behavior of Watching, Staring and Fork buttons (#22634)
* Fixes accessibility of empty repository commit status (#22632)
* Pull request yaml template support for including commit body in a field (#22629)
* Show migration validation error (#22619)
* set org visibility class to basic in header (#22605)
* Fix cache-control header clearing comment text when editing issue (#22604)
* Add ARIA support for Fomantic UI checkboxes (#22599)
* Add templates to customize text when creating and migrating repositories (#22597)
* Allow setting `redirect_to` cookie on OAuth login (#22594)
* Improve checkbox accessibility a bit by adding the title attribute (#22593)
* Allow issue templates to not render title (#22589)
* Webhooks: for issue close/reopen action, add commit ID that caused it (#22583)
* Fix missing title and filter in issue sidebar project menu (#22557)
* Issues: support setting issue template field values with query (#22545)
* Issues: add Project filter to issues list and search (#22544)
* Pull Requests: add color to approved/reject icon in pull requests list (#22543)
* Mute all links in issue timeline (#22533)
* Dropzone: Add "Copy link" button for new uploads (#22517)
* Support importing comment types (#22510)
* Load asciicast css async (#22502)
* Move delete user to service (#22478)
* Change use of Walk to WalkDir to improve disk performance (#22462)
* Add reply hint to mail text (#22459)
* fix wrong theme class when logged out if default theme is changed (#22408)
* Refactor the setting to make unit test easier (#22405)
* Improve utils of slices (#22379)
* Use context parameter in models/git (#22367)
* Always reuse transaction (#22362)
* Fix unstable emoji sort (#22346)
* Add context cache as a request level cache (#22294)
* Reminder for no more logs to console (#22282)
* Support estimated count with multiple schemas (#22276)
* Move `convert` package to services (#22264)
* Use dynamic package type list (#22263)
* Hide file borders on sticky diff box (#22217)
* Improve notification and stopwatch styles (#22169)
* Fixed Project view .board-column height for tall screens. (#22108)
* Use multi reader instead to concat strings (#22099)
* Use git command instead of exec.Cmd in blame (#22098)
* Fix autofilled text visibility in dark mode (#22088)
* Rename almost all Ctx functions (#22071)
* Rename actions to operations on UI (#22067)
* refactor bind functions based on generics (#22055)
* Support disabling database auto migration (#22053)
* remove duplicated read file code (#22042)
* Use link in UI which returned a relative url but not html_url which contains an absolute url (#21986)
* Skip initing disabled storages (#21985)
* Add doctor command for full GC of LFS (#21978)
* Util type to parse ref name (#21969)
* Replace fmt.Sprintf with hex.EncodeToString (#21960)
* Use random bytes to generate access token (#21959)
* Add index for access_token (#21908)
* Move all remaining colors into CSS variables (#21903)
* Webhook list enhancements (#21893)
* Embed Matrix icon as SVG (#21890)
* Remove useless "Cancel" buttons (#21872)
* fix(web): keep the pages of the navigation in the center (#21867)
* fix(web): reduce page jitter on browsers that support overlay scrollbar (#21850)
* Improvements for Content Copy (#21842)
* Tweak katex options (#21828)
* Show syntax lexer name in file view/blame (#21814)
* Remove `href="javascript:;"` in "save topics (Done)" button (#21813)
* Render number of commits in repo page in a user friendly way (#21786)
* Adjust clone timeout error to suggest increasing timeout (#21769)
* Update message of reach_limit_of_creation (#21757)
* Allow detect whether it's in a database transaction for a context.Context (#21756)
* Add configuration for CORS allowed headers (#21747)
* Move svg html render to modules/svg (#21716)
* Release and Tag List tweaks (#21712)
* Remove template previewer (#21701)
* Clean up formatting on install page (#21668)
* Configure update checker on installation page (#21655)
* Merge db.Iterate and IterateObjects (#21641)
* Add option to enable CAPTCHA validation for login (#21638)
* Allow disable RSS/Atom feed (#21622)
* Use CSS color-scheme instead of invert (#21616)
* Localize time units on activity heatmap (#21570)
* Fix UI column width, button overflow Fomantic's grid (#21559)
* feat: notify doers of a merge when automerging (#21553)
* Split migrations folder (#21549)
* feat: add button to quickly clear merge message (#21548)
* Add `context.Context` to more methods (#21546)
* Add index for hook_task table (#21545)
* Allow disable code tab (#20805)
* BUGFIXES
* Fix template error when reference Project (#23584)
* Fix dropdown icon misalignment when using fomantic icon (#23558) (#23577)
* Fix diff detail buttons wrapping, use tippy for review box (#23271) (#23546)
* Handle missing `README` in create repos API (#23387) (#23510)
* Disable sending email after push a commit to a closed PR (#23462) (#23492)
* Fix aria.js bugs: incorrect role element problem, mobile focus problem, tippy problem (#23450) (#23486)
* Fix due date being wrong on issue list (#23475) (#23477)
* Remove wrongly added column on migration test fixtures (#23456) (#23470)
* Make branches list page operations remember current page (#23420) (#23460)
* Fix missing commit status in PR which from forked repo (#23351) (#23453)
* Show edit/close/delete button on organization wide repositories (#23388) (#23429)
* Preserve file size when creating attachments (#23406) (#23426)
* Fix broken Chroma CSS styles (#23174) (#23402)
* Fix incorrect NotFound conditions in org/projects.go (#23384) (#23395)
* Set `X-Gitea-Debug` header once (#23361) (#23381)
* Pass context to avatar for projects view (#23359) (#23378)
* Fix panic when getting notes by ref (#23372) (#23377)
* Do not recognize text files as audio (#23355) (#23368)
* Fix adding of empty class name (#23352) (#23360)
* Fix various ImageDiff/SVG bugs (#23312) (#23358)
* Fix incorrect display for comment context menu (#23343) (#23344)
* Remove unnecessary space on link (#23334) (#23340)
* Fix incorrect redirect link of delete org project (#23327) (#23339)
* Fix cannot reopen after pushing commits to a closed PR (#23189) (#23324)
* Fix broken code editor diff preview (#23307) (#23320)
* Support sanitising the URL by removing extra slashes in the URL (#21333) (#23300)
* Avoid panic caused by broken payload when creating commit status (#23216) (#23294)
* Fill head commit to in payload when notifying push commits for mirroring (#23215) (#23292)
* Fix various bugs for "install" page (#23194) (#23286)
* Fix GetFilesChangedBetween if the file name may be escaped (#23272) (#23279)
* Revert relative links to absolute links in mail templates (#23267) (#23269)
* Fix commit retrieval by tag (#21804) (#23266)
* Use correct README link to render the README (#23152) (#23264)
* Close the temp file when dumping database to make the temp file can be deleted on Windows (#23249) (#23251)
* Use the correct selector to hide the checkmark of selected labels on clear (#23224) (#23228)
* Fix incorrect checkbox behaviors in the dashboard repolist's filter (#23147) (#23205)
* Properly flush unique queues on startup (#23154) (#23201)
* Pass `--global` when calling `git config --get`, for consistency with `git config --set` (#23157) (#23199)
* Make `gitea serv` respect git binary home (#23138) (#23197)
* Change button text for commenting and closing an issue at the same time (#23135) (#23182)
* Fix DBConsistency checks on MSSQL (#23132) (#23134)
* Show empty repos in Admin Repository Management page (#23114) (#23130)
* Redirect to the commit page after applying patch (#23056) (#23127)
* Fix nil context in RenderMarkdownToHtml (#23092) (#23108)
* Make issue meta dropdown support Enter, confirm before reloading (#23014) (#23102)
* Fix SyncOnCommit always return false in API of push_mirrors (#23088) (#23100)
* Fix commit name in Apply Patch page (#23086) (#23099)
* Fix some more hidden problems (#23074) (#23075)
* Bump golang.org/x/net from 0.4.0 to 0.7.0 (#22980)
* Get rules by id when editing branch protection rule (#22932)
* Fix panic when call api (/repos/{owner}/{repo}/pulls/{index}/files) (#22921)
* Increase Content field size of gpg_import_key to MEDIUMTEXT (#22897)
* Fix hidden commit status on multiple checks (#22889)
* Fix update by rebase being wrongly disabled by protected base branch (#22825)
* Make issue title edit buttons focusable and fix incorrect ajax requests (#22807)
* Fix rerun button of Actions (#22798)
* remove update language in ProfilePost (#22748)
* Do not overwrite empty DefaultBranch (#22708)
* Fix ref to trigger Actions (#22679)
* Fix time to NotifyPullRequestSynchronized (#22650)
* Show all projects, not just repo projects and open/closed projects (#22640)
* Project links should use parent link methods (#22587)
* Fix group filter for ldap source sync (#22506)
* Check quota limits for container uploads (#22450)
* Fix halfCommitter and WithTx (#22366)
* Attempt to fix TestExportUserGPGKeys (#22159)
* Fix heatmap first color being unused (#22157)
* Fix scroll over mermaid frame (#21925)
* Move migration test fixtures to the correct directories (#21901)
* fix(web): add `alt` for logo in home page (#21887)
* Fix webhook attachment text is not set in review comment (#21763)
* Alter package_version.metadata_json to LONGTEXT (#21667)
* Ensure that Webhook tasks are not double delivered (#21558)
* TESTING
* Make CI use a dummy password hasher for all tests (#22983)
* Disable test for incoming email (#22686)
* Move fuzz tests into tests/fuzz (#22376)
* Test views of LFS files (#22196)
* Specify ID in `TestAPITeam` (#22192)
* verify nodeinfo response by schema (#22137)
* Skip GitHub migration tests if the API token is undefined (#21824)
* Add a simple test for external renderer (#20033)
* TRANSLATION
* Use "Title Case" for text "Reference in new issue" (#22936)
* BUILD
* Wrap unless-check in docker manifests (#23079) (#23081)
* Adjust manifest to prevent tagging latest on rcs (#22811)
* update to build with go1.20 (#22732)
* Add Bash and Zsh completion scripts (#22646)
* Add Contributed backport command (#22643)
* Remove deprecated packages & staticcheck fixes (#22012)
* Update to Alpine 3.17 (#21904)
* Fix webpack license warning (#21815)
* DOCS
* Update documentation for the new YAML label file format (#23020) (#23341)
* Update hacking-on-gitea-zh_cn documentation (#23315) (#23323)
* Add basic documentation for labels, including scoped labels (#23304) (#23309)
* Re-add accidentally removed `hacking-on-gitea.zh-cn.md` (#23297) (#23305)
* Fix secrets overview page missing from docs sidebar (#23143) (#23145)
* Add some guidelines for refactoring (#22880)
* Explain that the no-access team unit does not affect public repositories (#22661)
* Fix incorrect Redis URL snippets in the example app.ini (#22573)
* docs: add swagger.json file location to FAQ (#22489)
* Update index.de-de.md (#22363)
* Update Gmail mailer configuration (#22291)
* Add missed reverse proxy authentication documentation (#22250)
* Add plural definitions for German translations (#21802)
* Attempt clarify AppWorkPath etc. (#21656)
* Add some documentation to packages (#21648)
* MISC
* Use `<nav>` instead of `<div>` in the global navbar (#23125) (#23533)
* Do not create commit graph for temporary repos (#23219) (#23229)
* Update button is shown when a Pull Request is marked WIP - Issue #21740 (#22683)
* Add main landmark to templates and adjust titles (#22670)
* Fix error on account activation with wrong passwd (#22609)
* Update JS dependencies (#22538)
* Display unreferenced packages total size in package admin panel (#22498)
* Mobile fix for Project view: Add delay to Sortable.js on mobile, to ensure scrolling is possible. (#22152)
* Update chroma to v2.4.0 (#22000)
* Hide collapse icon in diff with no lines (#21094)
## [1.18.5](https://github.com/go-gitea/gitea/releases/tag/v1.18.5) - 2023-02-21
* ENHANCEMENTS

96
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,96 @@
# Gitea Community Code of Conduct
## About
Online communities include people from many different backgrounds. The Gitea contributors are committed to providing a friendly, safe and welcoming environment for all, regardless of gender identity and expression, sexual orientation, disabilities, neurodiversity, physical appearance, body size, ethnicity, nationality, race, age, religion, or similar personal characteristics.
The first goal of the Code of Conduct is to specify a baseline standard of behavior so that people with different social values and communication styles can talk about Gitea effectively, productively, and respectfully.
The second goal is to provide a mechanism for resolving conflicts in the community when they arise.
The third goal of the Code of Conduct is to make our community welcoming to people from different backgrounds. Diversity is critical to the project; for Gitea to be successful, it needs contributors and users from all backgrounds.
We believe that healthy debate and disagreement are essential to a healthy project and community. However, it is never ok to be disrespectful. We value diverse opinions, but we value respectful behavior more.
## Community values
These are the values to which people in the Gitea community should aspire.
- **Be friendly and welcoming.**
- **Be patient.**
- Remember that people have varying communication styles and that not everyone is using their native language. (Meaning and tone can be lost in translation.)
- **Be thoughtful.**
- Productive communication requires effort. Think about how your words will be interpreted.
- Remember that sometimes it is best to refrain entirely from commenting.
- **Be respectful.**
- In particular, respect differences of opinion.
- **Be charitable.**
- Interpret the arguments of others in good faith, do not seek to disagree.
- When we do disagree, try to understand why.
- **Be constructive.**
- Avoid derailing: stay on topic; if you want to talk about something else, start a new conversation.
- Avoid unconstructive criticism: don't merely decry the current state of affairs; offer—or at least solicit—suggestions as to how things may be improved.
- Avoid snarking (pithy, unproductive, sniping comments)
- Avoid discussing potentially offensive or sensitive issues; this all too often leads to unnecessary conflict.
- Avoid microaggressions (brief and commonplace verbal, behavioral and environmental indignities that communicate hostile, derogatory or negative slights and insults to a person or group).
- **Be responsible.**
- What you say and do matters. Take responsibility for your words and actions, including their consequences, whether intended or otherwise.
People are complicated. You should expect to be misunderstood and to misunderstand others; when this inevitably occurs, resist the urge to be defensive or assign blame. Try not to take offense where no offense was intended. Give people the benefit of the doubt. Even if the intent was to provoke, do not rise to it. It is the responsibility of all parties to de-escalate conflict when it arises.
## Code of Conduct
### Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
### Our Standards
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
### Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject: comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, as well as to ban (temporarily or permanently) any contributor for behaviors that they deem inappropriate, threatening, offensive, or harmful.
### Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
This Code of Conduct also applies outside the project spaces when the Project Stewards have a reasonable belief that an individuals behavior may have a negative impact on the project or its community.
### Conflict Resolution
We do not believe that all conflict is bad; healthy debate and disagreement often yield positive results. However, it is never okay to be disrespectful or to engage in behavior that violates the projects code of conduct.
If you see someone violating the code of conduct, you are encouraged to address the behavior directly with those involved. Many issues can be resolved quickly and easily, and this gives people more control over the outcome of their dispute. If you are unable to resolve the matter for any reason, or if the behavior is threatening or harassing, report it. We are dedicated to providing an environment where participants feel welcome and safe.
Reports should be directed to the Gitea Project Stewards at conduct@gitea.com. It is the Project Stewards duty to receive and address reported violations of the code of conduct. They will then work with a committee consisting of representatives from the technical-oversight-committee.
We will investigate every complaint, but you may not receive a direct response. We will use our discretion in determining when and how to follow up on reported incidents, which may range from not taking action to permanent expulsion from the project and project-sponsored spaces. Under normal circumstances, we will notify the accused of the report and provide them an opportunity to discuss it before any action is taken. If there is a consensus between maintainers that such an endeavor would be useless (i.e. in case of an obvious spammer), we reserve the right to take action without notifying the accused first. The identity of the reporter will be omitted from the details of the report supplied to the accused. In potentially harmful situations, such as ongoing harassment or threats to anyones safety, we may take action without notice.
### Attribution
This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
## Summary
- Treat everyone with respect and kindness.
- Be thoughtful in how you communicate.
- Dont be destructive or inflammatory.
- If you encounter an issue, please mail conduct@gitea.com.

View File

@ -1,5 +1,5 @@
#Build stage
FROM golang:1.20-alpine3.17 AS build-env
FROM docker.io/library/golang:1.20-alpine3.17 AS build-env
ARG GOPROXY
ENV GOPROXY ${GOPROXY:-direct}
@ -23,7 +23,7 @@ RUN if [ -n "${GITEA_VERSION}" ]; then git checkout "${GITEA_VERSION}"; fi \
# Begin env-to-ini build
RUN go build contrib/environment-to-ini/environment-to-ini.go
FROM alpine:3.17
FROM docker.io/library/alpine:3.17
LABEL maintainer="maintainers@gitea.io"
EXPOSE 22 3000

View File

@ -1,5 +1,5 @@
#Build stage
FROM golang:1.20-alpine3.17 AS build-env
FROM docker.io/library/golang:1.20-alpine3.17 AS build-env
ARG GOPROXY
ENV GOPROXY ${GOPROXY:-direct}
@ -23,7 +23,7 @@ RUN if [ -n "${GITEA_VERSION}" ]; then git checkout "${GITEA_VERSION}"; fi \
# Begin env-to-ini build
RUN go build contrib/environment-to-ini/environment-to-ini.go
FROM alpine:3.17
FROM docker.io/library/alpine:3.17
LABEL maintainer="maintainers@gitea.io"
EXPOSE 2222 3000

View File

@ -5,7 +5,6 @@ Kees de Vries <bouwko@gmail.com> (@Bwko)
Kim Carlbäcker <kim.carlbacker@gmail.com> (@bkcsoft)
LefsFlare <nobody@nobody.tld> (@LefsFlarey)
Lunny Xiao <xiaolunwen@gmail.com> (@lunny)
Matthias Loibl <mail@matthiasloibl.com> (@metalmatze)
Rachid Zarouali <nobody@nobody.tld> (@xinity)
Rémy Boulanouar <admin@dblk.org> (@DblK)
Sandro Santilli <strk@kbt.io> (@strk)
@ -45,7 +44,7 @@ Jimmy Praet <jimmy.praet@telenet.be> (@jpraet)
Leon Hofmeister <dev.lh@web.de> (@delvh)
Wim <wim@42.be> (@42wim)
Jason Song <i@wolfogre.com> (@wolfogre)
Yarden Shoham <hrsi88@gmail.com> (@yardenshoham)
Yarden Shoham <git@yardenshoham.com> (@yardenshoham)
Yu Tian <zettat123@gmail.com> (@Zettat123)
Eddie Yang <576951401@qq.com> (@yp05327)
Dong Ge <gedong_1994@163.com> (@sillyguodong)

View File

@ -20,7 +20,7 @@ IMPORT := code.gitea.io/gitea
GO ?= go
SHASUM ?= shasum -a 256
HAS_GO = $(shell hash $(GO) > /dev/null 2>&1 && echo "GO" || echo "NOGO" )
HAS_GO := $(shell hash $(GO) > /dev/null 2>&1 && echo yes)
COMMA := ,
XGO_VERSION := go-1.20.x
@ -29,7 +29,7 @@ AIR_PACKAGE ?= github.com/cosmtrek/air@v1.40.4
EDITORCONFIG_CHECKER_PACKAGE ?= github.com/editorconfig-checker/editorconfig-checker/cmd/editorconfig-checker@2.6.0
ERRCHECK_PACKAGE ?= github.com/kisielk/errcheck@v1.6.2
GOFUMPT_PACKAGE ?= mvdan.cc/gofumpt@v0.4.0
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.0
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.2
GXZ_PAGAGE ?= github.com/ulikunitz/xz/cmd/gxz@v0.5.10
MISSPELL_PACKAGE ?= github.com/client9/misspell/cmd/misspell@v0.3.4
SWAGGER_PACKAGE ?= github.com/go-swagger/go-swagger/cmd/swagger@v0.30.4
@ -41,7 +41,7 @@ DOCKER_IMAGE ?= gitea/gitea
DOCKER_TAG ?= latest
DOCKER_REF := $(DOCKER_IMAGE):$(DOCKER_TAG)
ifeq ($(HAS_GO), GO)
ifeq ($(HAS_GO), yes)
GOPATH ?= $(shell $(GO) env GOPATH)
export PATH := $(GOPATH)/bin:$(PATH)
@ -77,6 +77,7 @@ ifeq ($(RACE_ENABLED),true)
endif
STORED_VERSION_FILE := VERSION
HUGO_VERSION ?= 0.111.3
ifneq ($(DRONE_TAG),)
VERSION ?= $(subst v,,$(DRONE_TAG))
@ -105,7 +106,7 @@ GO_TEST_PACKAGES ?= $(filter-out $(shell $(GO) list code.gitea.io/gitea/models/m
FOMANTIC_WORK_DIR := web_src/fomantic
WEBPACK_SOURCES := $(shell find web_src/js web_src/less -type f)
WEBPACK_SOURCES := $(shell find web_src/js web_src/css -type f)
WEBPACK_CONFIGS := webpack.config.js
WEBPACK_DEST := public/js/index.js public/css/index.css
WEBPACK_DEST_ENTRIES := public/js public/css public/fonts public/img/webpack public/serviceworker.js
@ -130,8 +131,8 @@ TEST_TAGS ?= sqlite sqlite_unlock_notify
TAR_EXCLUDES := .git data indexers queues log node_modules $(EXECUTABLE) $(FOMANTIC_WORK_DIR)/node_modules $(DIST) $(MAKE_EVIDENCE_DIR) $(AIR_TMP_DIR) $(GO_LICENSE_TMP_DIR)
GO_DIRS := cmd tests models modules routers build services tools
WEB_DIRS := web_src/js web_src/less
GO_DIRS := build cmd models modules routers services tests
WEB_DIRS := web_src/js web_src/css
GO_SOURCES := $(wildcard *.go)
GO_SOURCES += $(shell find $(GO_DIRS) -type f -name "*.go" -not -path modules/options/bindata.go -not -path modules/public/bindata.go -not -path modules/templates/bindata.go)
@ -188,11 +189,14 @@ help:
@echo " - clean delete backend and integration files"
@echo " - clean-all delete backend, frontend and integration files"
@echo " - deps install dependencies"
@echo " - deps-docs install docs dependencies"
@echo " - deps-frontend install frontend dependencies"
@echo " - deps-backend install backend dependencies"
@echo " - deps-tools install tool dependencies"
@echo " - lint lint everything"
@echo " - lint-frontend lint frontend files"
@echo " - lint-backend lint backend files"
@echo " - lint-md lint markdown files"
@echo " - checks run various consistency checks"
@echo " - checks-frontend check frontend files"
@echo " - checks-backend check backend files"
@ -216,7 +220,6 @@ help:
@echo " - tidy run go mod tidy"
@echo " - test[\#TestSpecificName] run unit test"
@echo " - test-sqlite[\#TestSpecificName] run integration test for sqlite"
@echo " - pr#<index> build and start gitea from a PR with integration test data loaded"
.PHONY: go-check
go-check:
@ -272,7 +275,7 @@ fmt:
.PHONY: fmt-check
fmt-check: fmt
@diff=$$(git diff $(GO_SOURCES) templates $(WEB_DIRS)); \
@diff=$$(git diff --color=always $(GO_SOURCES) templates $(WEB_DIRS)); \
if [ -n "$$diff" ]; then \
echo "Please run 'make fmt' and commit the result:"; \
echo "$${diff}"; \
@ -308,7 +311,7 @@ $(SWAGGER_SPEC): $(GO_SOURCES_NO_BINDATA)
.PHONY: swagger-check
swagger-check: generate-swagger
@diff=$$(git diff '$(SWAGGER_SPEC)'); \
@diff=$$(git diff --color=always '$(SWAGGER_SPEC)'); \
if [ -n "$$diff" ]; then \
echo "Please run 'make generate-swagger' and commit the result:"; \
echo "$${diff}"; \
@ -339,10 +342,13 @@ checks-backend: tidy-check swagger-check fmt-check misspell-check swagger-valida
lint: lint-frontend lint-backend
.PHONY: lint-frontend
lint-frontend: node_modules
lint-frontend: node_modules lint-md
npx eslint --color --max-warnings=0 --ext js,vue web_src/js build *.config.js docs/assets/js tests/e2e
npx stylelint --color --max-warnings=0 web_src/less
npx stylelint --color --max-warnings=0 web_src/css
npx spectral lint -q -F hint $(SWAGGER_SPEC)
.PHONY: lint-md
lint-md: node_modules
npx markdownlint docs *.md
.PHONY: lint-backend
@ -350,7 +356,7 @@ lint-backend: golangci-lint vet editorconfig-checker
.PHONY: watch
watch:
bash tools/watch.sh
bash build/watch.sh
.PHONY: watch-frontend
watch-frontend: node-check node_modules
@ -413,7 +419,7 @@ vendor: go.mod go.sum
.PHONY: tidy-check
tidy-check: tidy
@diff=$$(git diff go.mod go.sum $(GO_LICENSE_FILE)); \
@diff=$$(git diff --color=always go.mod go.sum $(GO_LICENSE_FILE)); \
if [ -n "$$diff" ]; then \
echo "Please run 'make tidy' and commit the result:"; \
echo "$${diff}"; \
@ -745,7 +751,7 @@ generate-go: $(TAGS_PREREQ)
.PHONY: security-check
security-check:
go run $(GOVULNCHECK_PACKAGE) -v ./...
go run $(GOVULNCHECK_PACKAGE) ./...
$(EXECUTABLE): $(GO_SOURCES) $(TAGS_PREREQ)
CGO_CFLAGS="$(CGO_CFLAGS)" $(GO) build $(GOFLAGS) $(EXTRA_GOFLAGS) -tags '$(TAGS)' -ldflags '-s -w $(LDFLAGS)' -o $@
@ -814,14 +820,17 @@ release-docs: | $(DIST_DIRS) docs
tar -czf $(DIST)/release/gitea-docs-$(VERSION).tar.gz -C ./docs/public .
.PHONY: docs
docs:
@hash hugo > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
curl -sL https://github.com/gohugoio/hugo/releases/download/v0.74.3/hugo_0.74.3_Linux-64bit.tar.gz | tar zxf - -C /tmp && mv /tmp/hugo /usr/bin/hugo && chmod +x /usr/bin/hugo; \
fi
docs: deps-docs
cd docs; make trans-copy clean build-offline;
.PHONY: deps-docs
deps-docs:
@hash hugo > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
curl -sL https://github.com/gohugoio/hugo/releases/download/v$(HUGO_VERSION)/hugo_$(HUGO_VERSION)_Linux-64bit.tar.gz | tar zxf - -C /tmp && mkdir -p ~/go/bin && mv /tmp/hugo ~/go/bin/hugo && chmod +x ~/go/bin/hugo; \
fi
.PHONY: deps
deps: deps-frontend deps-backend
deps: deps-frontend deps-backend deps-tools deps-docs
.PHONY: deps-frontend
deps-frontend: node_modules
@ -829,6 +838,9 @@ deps-frontend: node_modules
.PHONY: deps-backend
deps-backend:
$(GO) mod download
.PHONY: deps-tools
deps-tools:
$(GO) install $(AIR_PACKAGE)
$(GO) install $(EDITORCONFIG_CHECKER_PACKAGE)
$(GO) install $(ERRCHECK_PACKAGE)
@ -881,7 +893,7 @@ svg: node-check | node_modules
.PHONY: svg-check
svg-check: svg
@git add $(SVG_DEST_DIR)
@diff=$$(git diff --cached $(SVG_DEST_DIR)); \
@diff=$$(git diff --color=always --cached $(SVG_DEST_DIR)); \
if [ -n "$$diff" ]; then \
echo "Please run 'make svg' and 'git add $(SVG_DEST_DIR)' and commit the result:"; \
echo "$${diff}"; \
@ -891,7 +903,7 @@ svg-check: svg
.PHONY: lockfile-check
lockfile-check:
npm install --package-lock-only
@diff=$$(git diff package-lock.json); \
@diff=$$(git diff --color=always package-lock.json); \
if [ -n "$$diff" ]; then \
echo "package-lock.json is inconsistent with package.json"; \
echo "Please run 'npm install --package-lock-only' and commit the result:"; \
@ -930,10 +942,6 @@ generate-manpage:
@gzip -9 man/man1/gitea.1 && echo man/man1/gitea.1.gz created
@#TODO A small script that formats config-cheat-sheet.en-us.md nicely for use as a config man page
.PHONY: pr\#%
pr\#%: clean-all
$(GO) run contrib/pr/checkout.go $*
.PHONY: golangci-lint
golangci-lint:
$(GO) run $(GOLANGCI_LINT_PACKAGE) run

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,6 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//go:build vendor
package main

118
build/backport-locales.go Normal file
View File

@ -0,0 +1,118 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//go:build ignore
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"gopkg.in/ini.v1"
)
func main() {
if len(os.Args) != 2 {
println("usage: backport-locales <to-ref>")
println("eg: backport-locales release/v1.19")
os.Exit(1)
}
ini.PrettyFormat = false
mustNoErr := func(err error) {
if err != nil {
panic(err)
}
}
collectInis := func(ref string) map[string]*ini.File {
inis := map[string]*ini.File{}
err := filepath.WalkDir("options/locale", func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || !strings.HasSuffix(d.Name(), ".ini") {
return nil
}
cfg, err := ini.LoadSources(ini.LoadOptions{
IgnoreInlineComment: true,
UnescapeValueCommentSymbols: true,
}, path)
mustNoErr(err)
inis[path] = cfg
fmt.Printf("collecting: %s @ %s\n", path, ref)
return nil
})
mustNoErr(err)
return inis
}
// collect new locales from current working directory
inisNew := collectInis("HEAD")
// switch to the target ref, and collect the old locales
cmd := exec.Command("git", "checkout", os.Args[1])
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
mustNoErr(cmd.Run())
inisOld := collectInis(os.Args[1])
// use old en-US as the base, and copy the new translations to the old locales
enUsOld := inisOld["options/locale/locale_en-US.ini"]
brokenWarned := map[string]bool{}
for path, iniOld := range inisOld {
if iniOld == enUsOld {
continue
}
iniNew := inisNew[path]
if iniNew == nil {
continue
}
for _, secEnUS := range enUsOld.Sections() {
secOld := iniOld.Section(secEnUS.Name())
secNew := iniNew.Section(secEnUS.Name())
for _, keyEnUs := range secEnUS.Keys() {
if secNew.HasKey(keyEnUs.Name()) {
oldStr := secOld.Key(keyEnUs.Name()).String()
newStr := secNew.Key(keyEnUs.Name()).String()
broken := oldStr != "" && strings.Count(oldStr, "%") != strings.Count(newStr, "%")
broken = broken || strings.Contains(oldStr, "\n") || strings.Contains(oldStr, "\n")
if broken {
brokenWarned[secOld.Name()+"."+keyEnUs.Name()] = true
fmt.Println("----")
fmt.Printf("WARNING: skip broken locale: %s , [%s] %s\n", path, secEnUS.Name(), keyEnUs.Name())
fmt.Printf("\told: %s\n", strings.ReplaceAll(oldStr, "\n", "\\n"))
fmt.Printf("\tnew: %s\n", strings.ReplaceAll(newStr, "\n", "\\n"))
continue
}
secOld.Key(keyEnUs.Name()).SetValue(newStr)
}
}
}
mustNoErr(iniOld.SaveTo(path))
}
fmt.Println("========")
for path, iniNew := range inisNew {
for _, sec := range iniNew.Sections() {
for _, key := range sec.Keys() {
str := sec.Key(key.Name()).String()
broken := strings.Contains(str, "\n")
broken = broken || strings.HasPrefix(str, "`") != strings.HasSuffix(str, "`")
broken = broken || strings.HasPrefix(str, "\"`")
broken = broken || strings.HasPrefix(str, "`\"")
broken = broken || strings.Count(str, `"`)%2 == 1
broken = broken || strings.Count(str, "`")%2 == 1
if broken && !brokenWarned[sec.Name()+"."+key.Name()] {
fmt.Printf("WARNING: found broken locale: %s , [%s] %s\n", path, sec.Name(), key.Name())
fmt.Printf("\tstr: %s\n", strings.ReplaceAll(str, "\n", "\\n"))
fmt.Println("----")
}
}
}
}
}

View File

@ -65,7 +65,6 @@ func newFileCollector(fileFilter string, batchSize int) (*fileCollector, error)
"modules",
"routers",
"services",
"tools",
}
co.includePatterns = append(co.includePatterns, regexp.MustCompile(`.*\.go$`))

View File

@ -60,13 +60,13 @@ func main() {
// generate data
buf, err := generate()
if err != nil {
log.Fatal(err)
log.Fatalf("generate err: %v", err)
}
// write
err = os.WriteFile(*flagOut, buf, 0o644)
if err != nil {
log.Fatal(err)
log.Fatalf("WriteFile err: %v", err)
}
}

View File

@ -7,9 +7,10 @@ package main
import (
"encoding/json"
"fmt"
"io/fs"
"os"
goPath "path"
"path"
"path/filepath"
"regexp"
"sort"
@ -27,9 +28,14 @@ type LicenseEntry struct {
}
func main() {
if len(os.Args) != 3 {
fmt.Println("usage: go run generate-go-licenses.go <base-dir> <out-json-file>")
os.Exit(1)
}
base, out := os.Args[1], os.Args[2]
paths := []string{}
var paths []string
err := filepath.WalkDir(base, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
@ -46,28 +52,27 @@ func main() {
sort.Strings(paths)
entries := []LicenseEntry{}
for _, path := range paths {
path := filepath.ToSlash(path)
licenseText, err := os.ReadFile(path)
var entries []LicenseEntry
for _, filePath := range paths {
licenseText, err := os.ReadFile(filePath)
if err != nil {
panic(err)
}
path = strings.Replace(path, base+"/", "", 1)
name := goPath.Dir(path)
pkgPath := filepath.ToSlash(filePath)
pkgPath = strings.TrimPrefix(pkgPath, base+"/")
pkgName := path.Dir(pkgPath)
// There might be a bug somewhere in go-licenses that sometimes interprets the
// root package as "." and sometimes as "code.gitea.io/gitea". Workaround by
// removing both of them for the sake of stable output.
if name == "." || name == "code.gitea.io/gitea" {
if pkgName == "." || pkgName == "code.gitea.io/gitea" {
continue
}
entries = append(entries, LicenseEntry{
Name: name,
Path: path,
Name: pkgName,
Path: pkgPath,
LicenseText: string(licenseText),
})
}

View File

@ -25,14 +25,22 @@ async function processFile(file, {prefix, fullName} = {}) {
if (prefix === 'octicon') name = name.replace(/-[0-9]+$/, ''); // chop of '-16' on octicons
}
// Set the `xmlns` attribute so that the files are displayable in standalone documents
// The svg backend module will strip the attribute during startup for inline display
const {data} = optimize(await readFile(file, 'utf8'), {
plugins: [
{name: 'preset-default'},
{name: 'removeXMLNS'},
{name: 'removeDimensions'},
{name: 'prefixIds', params: {prefix: () => name}},
{name: 'addClassesToSVGElement', params: {classNames: ['svg', name]}},
{name: 'addAttributesToSVGElement', params: {attributes: [{'width': '16'}, {'height': '16'}, {'aria-hidden': 'true'}]}},
{
name: 'addAttributesToSVGElement', params: {
attributes: [
{'xmlns': 'http://www.w3.org/2000/svg'},
{'width': '16'}, {'height': '16'}, {'aria-hidden': 'true'},
]
}
},
],
});

20
build/test-echo.go Normal file
View File

@ -0,0 +1,20 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//go:build ignore
package main
import (
"fmt"
"io"
"os"
)
func main() {
_, err := io.Copy(os.Stdout, os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v", err)
os.Exit(1)
}
}

View File

@ -17,17 +17,10 @@ fi
mv ./options/locale/locale_en-US.ini ./options/
# the "ini" library for locale has many quirks
# * `a="xx"` gets `xx` (no quote)
# * `a=x\"y` gets `x\"y` (no unescaping)
# * `a="x\"y"` gets `"x\"y"` (no unescaping, the quotes are still there)
# * `a='x\"y'` gets `x\"y` (no unescaping, no quote)
# * `a="foo` gets `"foo` (although the quote is not closed)
# * 'a=`foo`' works like single-quote
# crowdin needs the strings to be quoted correctly and doesn't like incomplete quotes
# crowdin always outputs quoted strings if there are quotes in the strings.
# the "ini" library for locale has many quirks, its behavior is different from Crowdin.
# see i18n_test.go for more details
# this script helps to unquote the crowdin outputs for the quirky ini library
# this script helps to unquote the Crowdin outputs for the quirky ini library
# * find all `key="...\"..."` lines
# * remove the leading quote
# * remove the trailing quote

56
cmd/actions.go Normal file
View File

@ -0,0 +1,56 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cmd
import (
"fmt"
"code.gitea.io/gitea/modules/private"
"code.gitea.io/gitea/modules/setting"
"github.com/urfave/cli"
)
var (
// CmdActions represents the available actions sub-commands.
CmdActions = cli.Command{
Name: "actions",
Usage: "",
Description: "Commands for managing Gitea Actions",
Subcommands: []cli.Command{
subcmdActionsGenRunnerToken,
},
}
subcmdActionsGenRunnerToken = cli.Command{
Name: "generate-runner-token",
Usage: "Generate a new token for a runner to use to register with the server",
Action: runGenerateActionsRunnerToken,
Aliases: []string{"grt"},
Flags: []cli.Flag{
cli.StringFlag{
Name: "scope, s",
Value: "",
Usage: "{owner}[/{repo}] - leave empty for a global runner",
},
},
}
)
func runGenerateActionsRunnerToken(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setting.InitProviderFromExistingFile()
setting.LoadCommonSettings()
scope := c.String("scope")
respText, extra := private.GenerateActionsRunnerToken(ctx, scope)
if extra.HasError() {
return handleCliResponseExtra(extra)
}
_, _ = fmt.Printf("%s\n", respText)
return nil
}

View File

@ -7,6 +7,7 @@ package cmd
import (
"errors"
"fmt"
"net/url"
"os"
"strings"
"text/tabwriter"
@ -469,11 +470,19 @@ func runAddOauth(c *cli.Context) error {
return err
}
config := parseOAuth2Config(c)
if config.Provider == "openidConnect" {
discoveryURL, err := url.Parse(config.OpenIDConnectAutoDiscoveryURL)
if err != nil || (discoveryURL.Scheme != "http" && discoveryURL.Scheme != "https") {
return fmt.Errorf("invalid Auto Discovery URL: %s (this must be a valid URL starting with http:// or https://)", config.OpenIDConnectAutoDiscoveryURL)
}
}
return auth_model.CreateSource(&auth_model.Source{
Type: auth_model.OAuth2,
Name: c.String("name"),
IsActive: true,
Cfg: parseOAuth2Config(c),
Cfg: config,
})
}

View File

@ -17,7 +17,7 @@ import (
var CmdConvert = cli.Command{
Name: "convert",
Usage: "Convert the database",
Description: "A command to convert an existing MySQL database from utf8 to utf8mb4",
Description: "A command to convert an existing MySQL database from utf8 to utf8mb4 or MSSQL database from varchar to nvarchar",
Action: runConvert,
}
@ -35,17 +35,22 @@ func runConvert(ctx *cli.Context) error {
log.Info("Log path: %s", setting.Log.RootPath)
log.Info("Configuration file: %s", setting.CustomConf)
if !setting.Database.UseMySQL {
fmt.Println("This command can only be used with a MySQL database")
return nil
switch {
case setting.Database.Type.IsMySQL():
if err := db.ConvertUtf8ToUtf8mb4(); err != nil {
log.Fatal("Failed to convert database from utf8 to utf8mb4: %v", err)
return err
}
fmt.Println("Converted successfully, please confirm your database's character set is now utf8mb4")
case setting.Database.Type.IsMSSQL():
if err := db.ConvertVarcharToNVarchar(); err != nil {
log.Fatal("Failed to convert database from varchar to nvarchar: %v", err)
return err
}
fmt.Println("Converted successfully, please confirm your database's all columns character is NVARCHAR now")
default:
fmt.Println("This command can only be used with a MySQL or MSSQL database")
}
if err := db.ConvertUtf8ToUtf8mb4(); err != nil {
log.Fatal("Failed to convert database from utf8 to utf8mb4: %v", err)
return err
}
fmt.Println("Converted successfully, please confirm your database's character set is now utf8mb4")
return nil
}

View File

@ -112,6 +112,10 @@ It can be used for backup and capture Gitea server image to send to maintainer`,
Name: "verbose, V",
Usage: "Show process details",
},
cli.BoolFlag{
Name: "quiet, q",
Usage: "Only display warnings and errors",
},
cli.StringFlag{
Name: "tempdir, t",
Value: os.TempDir(),
@ -192,12 +196,25 @@ func runDump(ctx *cli.Context) error {
if _, err := setting.CfgProvider.Section("log.console").NewKey("STDERR", "true"); err != nil {
fatal("Setting console logger to stderr failed: %v", err)
}
// Set loglevel to Warn if quiet-mode is requested
if ctx.Bool("quiet") {
if _, err := setting.CfgProvider.Section("log.console").NewKey("LEVEL", "Warn"); err != nil {
fatal("Setting console log-level failed: %v", err)
}
}
if !setting.InstallLock {
log.Error("Is '%s' really the right config path?\n", setting.CustomConf)
return fmt.Errorf("gitea is not initialized")
}
setting.LoadSettings() // cannot access session settings otherwise
verbose := ctx.Bool("verbose")
if verbose && ctx.Bool("quiet") {
return fmt.Errorf("--quiet and --verbose cannot both be set")
}
stdCtx, cancel := installSignals()
defer cancel()
@ -223,7 +240,6 @@ func runDump(ctx *cli.Context) error {
return err
}
verbose := ctx.Bool("verbose")
var iface interface{}
if fileName == "-" {
iface, err = archiver.ByExtension(fmt.Sprintf(".%s", outType))
@ -250,7 +266,9 @@ func runDump(ctx *cli.Context) error {
if ctx.IsSet("skip-lfs-data") && ctx.Bool("skip-lfs-data") {
log.Info("Skip dumping LFS data")
} else if err := storage.LFS.IterateObjects(func(objPath string, object storage.Object) error {
} else if !setting.LFS.StartServer {
log.Info("LFS isn't enabled. Skip dumping LFS data")
} else if err := storage.LFS.IterateObjects("", func(objPath string, object storage.Object) error {
info, err := object.Stat()
if err != nil {
return err
@ -279,7 +297,7 @@ func runDump(ctx *cli.Context) error {
}()
targetDBType := ctx.String("database")
if len(targetDBType) > 0 && targetDBType != setting.Database.Type {
if len(targetDBType) > 0 && targetDBType != setting.Database.Type.String() {
log.Info("Dumping database %s => %s...", setting.Database.Type, targetDBType)
} else {
log.Info("Dumping database...")
@ -351,7 +369,7 @@ func runDump(ctx *cli.Context) error {
if ctx.IsSet("skip-attachment-data") && ctx.Bool("skip-attachment-data") {
log.Info("Skip dumping attachment data")
} else if err := storage.Attachments.IterateObjects(func(objPath string, object storage.Object) error {
} else if err := storage.Attachments.IterateObjects("", func(objPath string, object storage.Object) error {
info, err := object.Stat()
if err != nil {
return err
@ -364,7 +382,9 @@ func runDump(ctx *cli.Context) error {
if ctx.IsSet("skip-package-data") && ctx.Bool("skip-package-data") {
log.Info("Skip dumping package data")
} else if err := storage.Packages.IterateObjects(func(objPath string, object storage.Object) error {
} else if !setting.Packages.Enabled {
log.Info("Packages isn't enabled. Skip dumping package data")
} else if err := storage.Packages.IterateObjects("", func(objPath string, object storage.Object) error {
info, err := object.Stat()
if err != nil {
return err

View File

@ -1,8 +1,6 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//go:build bindata
package cmd
import (
@ -10,9 +8,9 @@ import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"code.gitea.io/gitea/modules/assetfs"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/options"
"code.gitea.io/gitea/modules/public"
@ -89,24 +87,20 @@ var (
},
}
sections map[string]*section
assets []asset
matchedAssetFiles []assetFile
)
type section struct {
Path string
Names func() []string
IsDir func(string) (bool, error)
Asset func(string) ([]byte, error)
}
type asset struct {
Section *section
Name string
Path string
type assetFile struct {
fs *assetfs.LayeredFS
name string
path string
}
func initEmbeddedExtractor(c *cli.Context) error {
// FIXME: there is a bug, if the user runs `gitea embedded` with a different user or root,
// The setting.Init (loadRunModeFrom) will fail and do log.Fatal
// But the console logger has been deleted, so nothing is printed, the user sees nothing and Gitea just exits.
// Silence the console logger
log.DelNamedLogger("console")
log.DelNamedLogger(log.DEFAULT)
@ -115,24 +109,14 @@ func initEmbeddedExtractor(c *cli.Context) error {
setting.InitProviderAllowEmpty()
setting.LoadCommonSettings()
pats, err := getPatterns(c.Args())
patterns, err := compileCollectPatterns(c.Args())
if err != nil {
return err
}
sections := make(map[string]*section, 3)
sections["public"] = &section{Path: "public", Names: public.AssetNames, IsDir: public.AssetIsDir, Asset: public.Asset}
sections["options"] = &section{Path: "options", Names: options.AssetNames, IsDir: options.AssetIsDir, Asset: options.Asset}
sections["templates"] = &section{Path: "templates", Names: templates.BuiltinAssetNames, IsDir: templates.BuiltinAssetIsDir, Asset: templates.BuiltinAsset}
for _, sec := range sections {
assets = append(assets, buildAssetList(sec, pats, c)...)
}
// Sort assets
sort.SliceStable(assets, func(i, j int) bool {
return assets[i].Path < assets[j].Path
})
collectAssetFilesByPattern(c, patterns, "options", options.BuiltinAssets())
collectAssetFilesByPattern(c, patterns, "public", public.BuiltinAssets())
collectAssetFilesByPattern(c, patterns, "templates", templates.BuiltinAssets())
return nil
}
@ -166,8 +150,8 @@ func runListDo(c *cli.Context) error {
return err
}
for _, a := range assets {
fmt.Println(a.Path)
for _, a := range matchedAssetFiles {
fmt.Println(a.path)
}
return nil
@ -178,19 +162,19 @@ func runViewDo(c *cli.Context) error {
return err
}
if len(assets) == 0 {
return fmt.Errorf("No files matched the given pattern")
} else if len(assets) > 1 {
return fmt.Errorf("Too many files matched the given pattern; try to be more specific")
if len(matchedAssetFiles) == 0 {
return fmt.Errorf("no files matched the given pattern")
} else if len(matchedAssetFiles) > 1 {
return fmt.Errorf("too many files matched the given pattern, try to be more specific")
}
data, err := assets[0].Section.Asset(assets[0].Name)
data, err := matchedAssetFiles[0].fs.ReadFile(matchedAssetFiles[0].name)
if err != nil {
return fmt.Errorf("%s: %w", assets[0].Path, err)
return fmt.Errorf("%s: %w", matchedAssetFiles[0].path, err)
}
if _, err = os.Stdout.Write(data); err != nil {
return fmt.Errorf("%s: %w", assets[0].Path, err)
return fmt.Errorf("%s: %w", matchedAssetFiles[0].path, err)
}
return nil
@ -202,7 +186,7 @@ func runExtractDo(c *cli.Context) error {
}
if len(c.Args()) == 0 {
return fmt.Errorf("A list of pattern of files to extract is mandatory (e.g. '**' for all)")
return fmt.Errorf("a list of pattern of files to extract is mandatory (e.g. '**' for all)")
}
destdir := "."
@ -227,7 +211,7 @@ func runExtractDo(c *cli.Context) error {
if err != nil {
return fmt.Errorf("%s: %s", destdir, err)
} else if !fi.IsDir() {
return fmt.Errorf("%s is not a directory.", destdir)
return fmt.Errorf("destination %q is not a directory", destdir)
}
fmt.Printf("Extracting to %s:\n", destdir)
@ -235,23 +219,23 @@ func runExtractDo(c *cli.Context) error {
overwrite := c.Bool("overwrite")
rename := c.Bool("rename")
for _, a := range assets {
for _, a := range matchedAssetFiles {
if err := extractAsset(destdir, a, overwrite, rename); err != nil {
// Non-fatal error
fmt.Fprintf(os.Stderr, "%s: %v", a.Path, err)
fmt.Fprintf(os.Stderr, "%s: %v", a.path, err)
}
}
return nil
}
func extractAsset(d string, a asset, overwrite, rename bool) error {
dest := filepath.Join(d, filepath.FromSlash(a.Path))
func extractAsset(d string, a assetFile, overwrite, rename bool) error {
dest := filepath.Join(d, filepath.FromSlash(a.path))
dir := filepath.Dir(dest)
data, err := a.Section.Asset(a.Name)
data, err := a.fs.ReadFile(a.name)
if err != nil {
return fmt.Errorf("%s: %w", a.Path, err)
return fmt.Errorf("%s: %w", a.path, err)
}
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
@ -272,7 +256,7 @@ func extractAsset(d string, a asset, overwrite, rename bool) error {
return fmt.Errorf("%s already exists, but it's not a regular file", dest)
} else if rename {
if err := util.Rename(dest, dest+".bak"); err != nil {
return fmt.Errorf("Error creating backup for %s: %w", dest, err)
return fmt.Errorf("error creating backup for %s: %w", dest, err)
}
// Attempt to respect file permissions mask (even if user:group will be set anew)
perms = fi.Mode()
@ -293,32 +277,30 @@ func extractAsset(d string, a asset, overwrite, rename bool) error {
return nil
}
func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset {
results := make([]asset, 0, 64)
for _, name := range sec.Names() {
if isdir, err := sec.IsDir(name); !isdir && err == nil {
if sec.Path == "public" &&
strings.HasPrefix(name, "vendor/") &&
!c.Bool("include-vendored") {
continue
}
matchName := sec.Path + "/" + name
for _, g := range globs {
if g.Match(matchName) {
results = append(results, asset{
Section: sec,
Name: name,
Path: sec.Path + "/" + name,
})
break
}
func collectAssetFilesByPattern(c *cli.Context, globs []glob.Glob, path string, layer *assetfs.Layer) {
fs := assetfs.Layered(layer)
files, err := fs.ListAllFiles(".", true)
if err != nil {
log.Error("Error listing files in %q: %v", path, err)
return
}
for _, name := range files {
if path == "public" &&
strings.HasPrefix(name, "vendor/") &&
!c.Bool("include-vendored") {
continue
}
matchName := path + "/" + name
for _, g := range globs {
if g.Match(matchName) {
matchedAssetFiles = append(matchedAssetFiles, assetFile{fs: fs, name: name, path: path + "/" + name})
break
}
}
}
return results
}
func getPatterns(args []string) ([]glob.Glob, error) {
func compileCollectPatterns(args []string) ([]glob.Glob, error) {
if len(args) == 0 {
args = []string{"**"}
}
@ -326,7 +308,7 @@ func getPatterns(args []string) ([]glob.Glob, error) {
for i := range args {
if g, err := glob.Compile(args[i], '/'); err != nil {
return nil, fmt.Errorf("'%s': Invalid glob pattern: %w", args[i], err)
} else {
} else { //nolint:revive
pat[i] = g
}
}

View File

@ -1,29 +0,0 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
//go:build !bindata
package cmd
import (
"fmt"
"os"
"github.com/urfave/cli"
)
// Cmdembedded represents the available extract sub-command.
var (
Cmdembedded = cli.Command{
Name: "embedded",
Usage: "Extract embedded resources",
Description: "A command for extracting embedded resources, like templates and images",
Action: extractorNotImplemented,
}
)
func extractorNotImplemented(c *cli.Context) error {
err := fmt.Errorf("Sorry: the 'embedded' subcommand is not available in builds without bindata")
fmt.Fprintf(os.Stderr, "%s\n", err)
return err
}

View File

@ -6,9 +6,9 @@ package cmd
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
@ -167,11 +167,11 @@ func runHookPreReceive(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("hooks/pre-receive.log", c.Bool("debug"))
setup(ctx, c.Bool("debug"))
if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
if setting.OnlyAllowPushIfGiteaEnvironmentSet {
return fail(`Rejecting changes as Gitea environment not set.
return fail(ctx, `Rejecting changes as Gitea environment not set.
If you are pushing over SSH you must push with a key managed by
Gitea or set your environment appropriately.`, "")
}
@ -257,14 +257,9 @@ Gitea or set your environment appropriately.`, "")
hookOptions.OldCommitIDs = oldCommitIDs
hookOptions.NewCommitIDs = newCommitIDs
hookOptions.RefFullNames = refFullNames
statusCode, msg := private.HookPreReceive(ctx, username, reponame, hookOptions)
switch statusCode {
case http.StatusOK:
// no-op
case http.StatusInternalServerError:
return fail("Internal Server Error", msg)
default:
return fail(msg, "")
extra := private.HookPreReceive(ctx, username, reponame, hookOptions)
if extra.HasError() {
return fail(ctx, extra.UserMsg, "HookPreReceive(batch) failed: %v", extra.Error)
}
count = 0
lastline = 0
@ -285,12 +280,9 @@ Gitea or set your environment appropriately.`, "")
fmt.Fprintf(out, " Checking %d references\n", count)
statusCode, msg := private.HookPreReceive(ctx, username, reponame, hookOptions)
switch statusCode {
case http.StatusInternalServerError:
return fail("Internal Server Error", msg)
case http.StatusForbidden:
return fail(msg, "")
extra := private.HookPreReceive(ctx, username, reponame, hookOptions)
if extra.HasError() {
return fail(ctx, extra.UserMsg, "HookPreReceive(last) failed: %v", extra.Error)
}
} else if lastline > 0 {
fmt.Fprintf(out, "\n")
@ -309,7 +301,7 @@ func runHookPostReceive(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("hooks/post-receive.log", c.Bool("debug"))
setup(ctx, c.Bool("debug"))
// First of all run update-server-info no matter what
if _, _, err := git.NewCommand(ctx, "update-server-info").RunStdString(nil); err != nil {
@ -323,7 +315,7 @@ func runHookPostReceive(c *cli.Context) error {
if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
if setting.OnlyAllowPushIfGiteaEnvironmentSet {
return fail(`Rejecting changes as Gitea environment not set.
return fail(ctx, `Rejecting changes as Gitea environment not set.
If you are pushing over SSH you must push with a key managed by
Gitea or set your environment appropriately.`, "")
}
@ -394,11 +386,11 @@ Gitea or set your environment appropriately.`, "")
hookOptions.OldCommitIDs = oldCommitIDs
hookOptions.NewCommitIDs = newCommitIDs
hookOptions.RefFullNames = refFullNames
resp, err := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
if resp == nil {
resp, extra := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
if extra.HasError() {
_ = dWriter.Close()
hookPrintResults(results)
return fail("Internal Server Error", err)
return fail(ctx, extra.UserMsg, "HookPostReceive failed: %v", extra.Error)
}
wasEmpty = wasEmpty || resp.RepoWasEmpty
results = append(results, resp.Results...)
@ -409,9 +401,9 @@ Gitea or set your environment appropriately.`, "")
if count == 0 {
if wasEmpty && masterPushed {
// We need to tell the repo to reset the default branch to master
err := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
if err != nil {
return fail("Internal Server Error", "SetDefaultBranch failed with Error: %v", err)
extra := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
if extra.HasError() {
return fail(ctx, extra.UserMsg, "SetDefaultBranch failed: %v", extra.Error)
}
}
fmt.Fprintf(out, "Processed %d references in total\n", total)
@ -427,11 +419,11 @@ Gitea or set your environment appropriately.`, "")
fmt.Fprintf(out, " Processing %d references\n", count)
resp, err := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
resp, extra := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
if resp == nil {
_ = dWriter.Close()
hookPrintResults(results)
return fail("Internal Server Error", err)
return fail(ctx, extra.UserMsg, "HookPostReceive failed: %v", extra.Error)
}
wasEmpty = wasEmpty || resp.RepoWasEmpty
results = append(results, resp.Results...)
@ -440,9 +432,9 @@ Gitea or set your environment appropriately.`, "")
if wasEmpty && masterPushed {
// We need to tell the repo to reset the default branch to master
err := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
if err != nil {
return fail("Internal Server Error", "SetDefaultBranch failed with Error: %v", err)
extra := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
if extra.HasError() {
return fail(ctx, extra.UserMsg, "SetDefaultBranch failed: %v", extra.Error)
}
}
_ = dWriter.Close()
@ -485,22 +477,22 @@ func pushOptions() map[string]string {
}
func runHookProcReceive(c *cli.Context) error {
setup("hooks/proc-receive.log", c.Bool("debug"))
ctx, cancel := installSignals()
defer cancel()
setup(ctx, c.Bool("debug"))
if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
if setting.OnlyAllowPushIfGiteaEnvironmentSet {
return fail(`Rejecting changes as Gitea environment not set.
return fail(ctx, `Rejecting changes as Gitea environment not set.
If you are pushing over SSH you must push with a key managed by
Gitea or set your environment appropriately.`, "")
}
return nil
}
ctx, cancel := installSignals()
defer cancel()
if git.CheckGitVersionAtLeast("2.29") != nil {
return fail("Internal Server Error", "git not support proc-receive.")
return fail(ctx, "No proc-receive support", "current git version doesn't support proc-receive.")
}
reader := bufio.NewReader(os.Stdin)
@ -515,7 +507,7 @@ Gitea or set your environment appropriately.`, "")
// H: PKT-LINE(version=1\0push-options...)
// H: flush-pkt
rs, err := readPktLine(reader, pktLineTypeData)
rs, err := readPktLine(ctx, reader, pktLineTypeData)
if err != nil {
return err
}
@ -530,19 +522,19 @@ Gitea or set your environment appropriately.`, "")
index := bytes.IndexByte(rs.Data, byte(0))
if index >= len(rs.Data) {
return fail("Internal Server Error", "pkt-line: format error "+fmt.Sprint(rs.Data))
return fail(ctx, "Protocol: format error", "pkt-line: format error "+fmt.Sprint(rs.Data))
}
if index < 0 {
if len(rs.Data) == 10 && rs.Data[9] == '\n' {
index = 9
} else {
return fail("Internal Server Error", "pkt-line: format error "+fmt.Sprint(rs.Data))
return fail(ctx, "Protocol: format error", "pkt-line: format error "+fmt.Sprint(rs.Data))
}
}
if string(rs.Data[0:index]) != VersionHead {
return fail("Internal Server Error", "Received unsupported version: %s", string(rs.Data[0:index]))
return fail(ctx, "Protocol: version error", "Received unsupported version: %s", string(rs.Data[0:index]))
}
requestOptions = strings.Split(string(rs.Data[index+1:]), " ")
@ -555,17 +547,17 @@ Gitea or set your environment appropriately.`, "")
}
response = append(response, '\n')
_, err = readPktLine(reader, pktLineTypeFlush)
_, err = readPktLine(ctx, reader, pktLineTypeFlush)
if err != nil {
return err
}
err = writeDataPktLine(os.Stdout, response)
err = writeDataPktLine(ctx, os.Stdout, response)
if err != nil {
return err
}
err = writeFlushPktLine(os.Stdout)
err = writeFlushPktLine(ctx, os.Stdout)
if err != nil {
return err
}
@ -588,7 +580,7 @@ Gitea or set your environment appropriately.`, "")
for {
// note: pktLineTypeUnknow means pktLineTypeFlush and pktLineTypeData all allowed
rs, err = readPktLine(reader, pktLineTypeUnknow)
rs, err = readPktLine(ctx, reader, pktLineTypeUnknow)
if err != nil {
return err
}
@ -609,7 +601,7 @@ Gitea or set your environment appropriately.`, "")
if hasPushOptions {
for {
rs, err = readPktLine(reader, pktLineTypeUnknow)
rs, err = readPktLine(ctx, reader, pktLineTypeUnknow)
if err != nil {
return err
}
@ -626,9 +618,9 @@ Gitea or set your environment appropriately.`, "")
}
// 3. run hook
resp, err := private.HookProcReceive(ctx, repoUser, repoName, hookOptions)
if err != nil {
return fail("Internal Server Error", "run proc-receive hook failed :%v", err)
resp, extra := private.HookProcReceive(ctx, repoUser, repoName, hookOptions)
if extra.HasError() {
return fail(ctx, extra.UserMsg, "HookProcReceive failed: %v", extra.Error)
}
// 4. response result to service
@ -649,7 +641,7 @@ Gitea or set your environment appropriately.`, "")
for _, rs := range resp.Results {
if len(rs.Err) > 0 {
err = writeDataPktLine(os.Stdout, []byte("ng "+rs.OriginalRef+" "+rs.Err))
err = writeDataPktLine(ctx, os.Stdout, []byte("ng "+rs.OriginalRef+" "+rs.Err))
if err != nil {
return err
}
@ -657,43 +649,43 @@ Gitea or set your environment appropriately.`, "")
}
if rs.IsNotMatched {
err = writeDataPktLine(os.Stdout, []byte("ok "+rs.OriginalRef))
err = writeDataPktLine(ctx, os.Stdout, []byte("ok "+rs.OriginalRef))
if err != nil {
return err
}
err = writeDataPktLine(os.Stdout, []byte("option fall-through"))
err = writeDataPktLine(ctx, os.Stdout, []byte("option fall-through"))
if err != nil {
return err
}
continue
}
err = writeDataPktLine(os.Stdout, []byte("ok "+rs.OriginalRef))
err = writeDataPktLine(ctx, os.Stdout, []byte("ok "+rs.OriginalRef))
if err != nil {
return err
}
err = writeDataPktLine(os.Stdout, []byte("option refname "+rs.Ref))
err = writeDataPktLine(ctx, os.Stdout, []byte("option refname "+rs.Ref))
if err != nil {
return err
}
if rs.OldOID != git.EmptySHA {
err = writeDataPktLine(os.Stdout, []byte("option old-oid "+rs.OldOID))
err = writeDataPktLine(ctx, os.Stdout, []byte("option old-oid "+rs.OldOID))
if err != nil {
return err
}
}
err = writeDataPktLine(os.Stdout, []byte("option new-oid "+rs.NewOID))
err = writeDataPktLine(ctx, os.Stdout, []byte("option new-oid "+rs.NewOID))
if err != nil {
return err
}
if rs.IsForcePush {
err = writeDataPktLine(os.Stdout, []byte("option forced-update"))
err = writeDataPktLine(ctx, os.Stdout, []byte("option forced-update"))
if err != nil {
return err
}
}
}
err = writeFlushPktLine(os.Stdout)
err = writeFlushPktLine(ctx, os.Stdout)
return err
}
@ -718,7 +710,7 @@ type gitPktLine struct {
Data []byte
}
func readPktLine(in *bufio.Reader, requestType pktLineType) (*gitPktLine, error) {
func readPktLine(ctx context.Context, in *bufio.Reader, requestType pktLineType) (*gitPktLine, error) {
var (
err error
r *gitPktLine
@ -729,33 +721,33 @@ func readPktLine(in *bufio.Reader, requestType pktLineType) (*gitPktLine, error)
for i := 0; i < 4; i++ {
lengthBytes[i], err = in.ReadByte()
if err != nil {
return nil, fail("Internal Server Error", "Pkt-Line: read stdin failed : %v", err)
return nil, fail(ctx, "Protocol: stdin error", "Pkt-Line: read stdin failed : %v", err)
}
}
r = new(gitPktLine)
r.Length, err = strconv.ParseUint(string(lengthBytes), 16, 32)
if err != nil {
return nil, fail("Internal Server Error", "Pkt-Line format is wrong :%v", err)
return nil, fail(ctx, "Protocol: format parse error", "Pkt-Line format is wrong :%v", err)
}
if r.Length == 0 {
if requestType == pktLineTypeData {
return nil, fail("Internal Server Error", "Pkt-Line format is wrong")
return nil, fail(ctx, "Protocol: format data error", "Pkt-Line format is wrong")
}
r.Type = pktLineTypeFlush
return r, nil
}
if r.Length <= 4 || r.Length > 65520 || requestType == pktLineTypeFlush {
return nil, fail("Internal Server Error", "Pkt-Line format is wrong")
return nil, fail(ctx, "Protocol: format length error", "Pkt-Line format is wrong")
}
r.Data = make([]byte, r.Length-4)
for i := range r.Data {
r.Data[i], err = in.ReadByte()
if err != nil {
return nil, fail("Internal Server Error", "Pkt-Line: read stdin failed : %v", err)
return nil, fail(ctx, "Protocol: data error", "Pkt-Line: read stdin failed : %v", err)
}
}
@ -764,19 +756,15 @@ func readPktLine(in *bufio.Reader, requestType pktLineType) (*gitPktLine, error)
return r, nil
}
func writeFlushPktLine(out io.Writer) error {
func writeFlushPktLine(ctx context.Context, out io.Writer) error {
l, err := out.Write([]byte("0000"))
if err != nil {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
if err != nil || l != 4 {
return fail(ctx, "Protocol: write error", "Pkt-Line response failed: %v", err)
}
if l != 4 {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
}
return nil
}
func writeDataPktLine(out io.Writer, data []byte) error {
func writeDataPktLine(ctx context.Context, out io.Writer, data []byte) error {
hexchar := []byte("0123456789abcdef")
hex := func(n uint64) byte {
return hexchar[(n)&15]
@ -790,19 +778,13 @@ func writeDataPktLine(out io.Writer, data []byte) error {
tmp[3] = hex(length)
lr, err := out.Write(tmp)
if err != nil {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
}
if lr != 4 {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
if err != nil || lr != 4 {
return fail(ctx, "Protocol: write error", "Pkt-Line response failed: %v", err)
}
lr, err = out.Write(data)
if err != nil {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
}
if int(length-4) != lr {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
if err != nil || int(length-4) != lr {
return fail(ctx, "Protocol: write error", "Pkt-Line response failed: %v", err)
}
return nil

View File

@ -6,6 +6,7 @@ package cmd
import (
"bufio"
"bytes"
"context"
"strings"
"testing"
@ -14,27 +15,28 @@ import (
func TestPktLine(t *testing.T) {
// test read
ctx := context.Background()
s := strings.NewReader("0000")
r := bufio.NewReader(s)
result, err := readPktLine(r, pktLineTypeFlush)
result, err := readPktLine(ctx, r, pktLineTypeFlush)
assert.NoError(t, err)
assert.Equal(t, pktLineTypeFlush, result.Type)
s = strings.NewReader("0006a\n")
r = bufio.NewReader(s)
result, err = readPktLine(r, pktLineTypeData)
result, err = readPktLine(ctx, r, pktLineTypeData)
assert.NoError(t, err)
assert.Equal(t, pktLineTypeData, result.Type)
assert.Equal(t, []byte("a\n"), result.Data)
// test write
w := bytes.NewBuffer([]byte{})
err = writeFlushPktLine(w)
err = writeFlushPktLine(ctx, w)
assert.NoError(t, err)
assert.Equal(t, []byte("0000"), w.Bytes())
w.Reset()
err = writeDataPktLine(w, []byte("a\nb"))
err = writeDataPktLine(ctx, w, []byte("a\nb"))
assert.NoError(t, err)
assert.Equal(t, []byte("0007a\nb"), w.Bytes())
}

View File

@ -64,11 +64,12 @@ func runKeys(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("keys.log", false)
setup(ctx, false)
authorizedString, err := private.AuthorizedPublicKeyByContent(ctx, content)
if err != nil {
return err
authorizedString, extra := private.AuthorizedPublicKeyByContent(ctx, content)
// do not use handleCliResponseExtra or cli.NewExitError, if it exists immediately, it breaks some tests like Test_CmdKeys
if extra.Error != nil {
return extra.Error
}
fmt.Println(strings.TrimSpace(authorizedString))
return nil

View File

@ -5,7 +5,6 @@ package cmd
import (
"fmt"
"net/http"
"code.gitea.io/gitea/modules/private"
"code.gitea.io/gitea/modules/setting"
@ -43,13 +42,10 @@ func runSendMail(c *cli.Context) error {
}
}
status, message := private.SendEmail(ctx, subject, body, nil)
if status != http.StatusOK {
fmt.Printf("error: %s\n", message)
return nil
respText, extra := private.SendEmail(ctx, subject, body, nil)
if extra.HasError() {
return handleCliResponseExtra(extra)
}
fmt.Printf("Success: %s\n", message)
_, _ = fmt.Printf("Sent %s email(s) to all users\n", respText)
return nil
}

View File

@ -4,8 +4,6 @@
package cmd
import (
"fmt"
"net/http"
"os"
"time"
@ -103,57 +101,34 @@ func runShutdown(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("manager", c.Bool("debug"))
statusCode, msg := private.Shutdown(ctx)
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
return nil
setup(ctx, c.Bool("debug"))
extra := private.Shutdown(ctx)
return handleCliResponseExtra(extra)
}
func runRestart(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("manager", c.Bool("debug"))
statusCode, msg := private.Restart(ctx)
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
return nil
setup(ctx, c.Bool("debug"))
extra := private.Restart(ctx)
return handleCliResponseExtra(extra)
}
func runFlushQueues(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("manager", c.Bool("debug"))
statusCode, msg := private.FlushQueues(ctx, c.Duration("timeout"), c.Bool("non-blocking"))
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
return nil
setup(ctx, c.Bool("debug"))
extra := private.FlushQueues(ctx, c.Duration("timeout"), c.Bool("non-blocking"))
return handleCliResponseExtra(extra)
}
func runProcesses(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("manager", c.Bool("debug"))
statusCode, msg := private.Processes(ctx, os.Stdout, c.Bool("flat"), c.Bool("no-system"), c.Bool("stacktraces"), c.Bool("json"), c.String("cancel"))
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
return nil
setup(ctx, c.Bool("debug"))
extra := private.Processes(ctx, os.Stdout, c.Bool("flat"), c.Bool("no-system"), c.Bool("stacktraces"), c.Bool("json"), c.String("cancel"))
return handleCliResponseExtra(extra)
}

View File

@ -5,7 +5,6 @@ package cmd
import (
"fmt"
"net/http"
"os"
"code.gitea.io/gitea/modules/log"
@ -191,27 +190,25 @@ var (
)
func runRemoveLogger(c *cli.Context) error {
setup("manager", c.Bool("debug"))
ctx, cancel := installSignals()
defer cancel()
setup(ctx, c.Bool("debug"))
group := c.String("group")
if len(group) == 0 {
group = log.DEFAULT
}
name := c.Args().First()
ctx, cancel := installSignals()
defer cancel()
statusCode, msg := private.RemoveLogger(ctx, group, name)
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
return nil
extra := private.RemoveLogger(ctx, group, name)
return handleCliResponseExtra(extra)
}
func runAddSMTPLogger(c *cli.Context) error {
setup("manager", c.Bool("debug"))
ctx, cancel := installSignals()
defer cancel()
setup(ctx, c.Bool("debug"))
vals := map[string]interface{}{}
mode := "smtp"
if c.IsSet("host") {
@ -242,7 +239,10 @@ func runAddSMTPLogger(c *cli.Context) error {
}
func runAddConnLogger(c *cli.Context) error {
setup("manager", c.Bool("debug"))
ctx, cancel := installSignals()
defer cancel()
setup(ctx, c.Bool("debug"))
vals := map[string]interface{}{}
mode := "conn"
vals["net"] = "tcp"
@ -269,7 +269,10 @@ func runAddConnLogger(c *cli.Context) error {
}
func runAddFileLogger(c *cli.Context) error {
setup("manager", c.Bool("debug"))
ctx, cancel := installSignals()
defer cancel()
setup(ctx, c.Bool("debug"))
vals := map[string]interface{}{}
mode := "file"
if c.IsSet("filename") {
@ -299,7 +302,10 @@ func runAddFileLogger(c *cli.Context) error {
}
func runAddConsoleLogger(c *cli.Context) error {
setup("manager", c.Bool("debug"))
ctx, cancel := installSignals()
defer cancel()
setup(ctx, c.Bool("debug"))
vals := map[string]interface{}{}
mode := "console"
if c.IsSet("stderr") && c.Bool("stderr") {
@ -338,28 +344,17 @@ func commonAddLogger(c *cli.Context, mode string, vals map[string]interface{}) e
ctx, cancel := installSignals()
defer cancel()
statusCode, msg := private.AddLogger(ctx, group, name, mode, vals)
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
return nil
extra := private.AddLogger(ctx, group, name, mode, vals)
return handleCliResponseExtra(extra)
}
func runPauseLogging(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("manager", c.Bool("debug"))
statusCode, msg := private.PauseLogging(ctx)
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
setup(ctx, c.Bool("debug"))
userMsg := private.PauseLogging(ctx)
_, _ = fmt.Fprintln(os.Stdout, userMsg)
return nil
}
@ -367,14 +362,9 @@ func runResumeLogging(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("manager", c.Bool("debug"))
statusCode, msg := private.ResumeLogging(ctx)
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
setup(ctx, c.Bool("debug"))
userMsg := private.ResumeLogging(ctx)
_, _ = fmt.Fprintln(os.Stdout, userMsg)
return nil
}
@ -382,28 +372,17 @@ func runReleaseReopenLogging(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("manager", c.Bool("debug"))
statusCode, msg := private.ReleaseReopenLogging(ctx)
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
setup(ctx, c.Bool("debug"))
userMsg := private.ReleaseReopenLogging(ctx)
_, _ = fmt.Fprintln(os.Stdout, userMsg)
return nil
}
func runSetLogSQL(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("manager", c.Bool("debug"))
setup(ctx, c.Bool("debug"))
statusCode, msg := private.SetLogSQL(ctx, !c.Bool("off"))
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
return nil
extra := private.SetLogSQL(ctx, !c.Bool("off"))
return handleCliResponseExtra(extra)
}

View File

@ -72,12 +72,21 @@ var CmdMigrateStorage = cli.Command{
cli.StringFlag{
Name: "minio-base-path",
Value: "",
Usage: "Minio storage basepath on the bucket",
Usage: "Minio storage base path on the bucket",
},
cli.BoolFlag{
Name: "minio-use-ssl",
Usage: "Enable SSL for minio",
},
cli.BoolFlag{
Name: "minio-insecure-skip-verify",
Usage: "Skip SSL verification",
},
cli.StringFlag{
Name: "minio-checksum-algorithm",
Value: "",
Usage: "Minio checksum algorithm (default/md5)",
},
},
}
@ -168,13 +177,15 @@ func runMigrateStorage(ctx *cli.Context) error {
dstStorage, err = storage.NewMinioStorage(
stdCtx,
storage.MinioStorageConfig{
Endpoint: ctx.String("minio-endpoint"),
AccessKeyID: ctx.String("minio-access-key-id"),
SecretAccessKey: ctx.String("minio-secret-access-key"),
Bucket: ctx.String("minio-bucket"),
Location: ctx.String("minio-location"),
BasePath: ctx.String("minio-base-path"),
UseSSL: ctx.Bool("minio-use-ssl"),
Endpoint: ctx.String("minio-endpoint"),
AccessKeyID: ctx.String("minio-access-key-id"),
SecretAccessKey: ctx.String("minio-secret-access-key"),
Bucket: ctx.String("minio-bucket"),
Location: ctx.String("minio-location"),
BasePath: ctx.String("minio-base-path"),
UseSSL: ctx.Bool("minio-use-ssl"),
InsecureSkipVerify: ctx.Bool("minio-insecure-skip-verify"),
ChecksumAlgorithm: ctx.String("minio-checksum-algorithm"),
})
default:
return fmt.Errorf("unsupported storage type: %s", ctx.String("storage"))

View File

@ -4,11 +4,8 @@
package cmd
import (
"errors"
"net/http"
"strings"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/private"
"code.gitea.io/gitea/modules/setting"
@ -60,7 +57,7 @@ func runRestoreRepository(c *cli.Context) error {
if s := c.String("units"); s != "" {
units = strings.Split(s, ",")
}
statusCode, errStr := private.RestoreRepo(
extra := private.RestoreRepo(
ctx,
c.String("repo_dir"),
c.String("owner_name"),
@ -68,10 +65,5 @@ func runRestoreRepository(c *cli.Context) error {
units,
c.Bool("validation"),
)
if statusCode == http.StatusOK {
return nil
}
log.Fatal("Failed to restore repository: %v", errStr)
return errors.New(errStr)
return handleCliResponseExtra(extra)
}

View File

@ -7,7 +7,6 @@ package cmd
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"os/exec"
@ -16,6 +15,7 @@ import (
"strconv"
"strings"
"time"
"unicode"
asymkey_model "code.gitea.io/gitea/models/asymkey"
git_model "code.gitea.io/gitea/models/git"
@ -55,7 +55,7 @@ var CmdServ = cli.Command{
},
}
func setup(logPath string, debug bool) {
func setup(ctx context.Context, debug bool) {
_ = log.DelLogger("console")
if debug {
_ = log.NewLogger(1000, "console", "console", `{"level":"trace","stacktracelevel":"NONE","stderr":true}`)
@ -72,15 +72,15 @@ func setup(logPath string, debug bool) {
// `[repository]` `ROOT` is a relative path and $GITEA_WORK_DIR isn't passed to the SSH connection.
if _, err := os.Stat(setting.RepoRootPath); err != nil {
if os.IsNotExist(err) {
_ = fail("Incorrect configuration, no repository directory.", "Directory `[repository].ROOT` %q was not found, please check if $GITEA_WORK_DIR is passed to the SSH connection or make `[repository].ROOT` an absolute value.", setting.RepoRootPath)
_ = fail(ctx, "Incorrect configuration, no repository directory.", "Directory `[repository].ROOT` %q was not found, please check if $GITEA_WORK_DIR is passed to the SSH connection or make `[repository].ROOT` an absolute value.", setting.RepoRootPath)
} else {
_ = fail("Incorrect configuration, repository directory is inaccessible", "Directory `[repository].ROOT` %q is inaccessible. err: %v", setting.RepoRootPath, err)
_ = fail(ctx, "Incorrect configuration, repository directory is inaccessible", "Directory `[repository].ROOT` %q is inaccessible. err: %v", setting.RepoRootPath, err)
}
return
}
if err := git.InitSimple(context.Background()); err != nil {
_ = fail("Failed to init git", "Failed to init git, err: %v", err)
_ = fail(ctx, "Failed to init git", "Failed to init git, err: %v", err)
}
}
@ -94,32 +94,54 @@ var (
alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
)
func fail(userMessage, logMessage string, args ...interface{}) error {
// fail prints message to stdout, it's mainly used for git serv and git hook commands.
// The output will be passed to git client and shown to user.
func fail(ctx context.Context, userMessage, logMsgFmt string, args ...interface{}) error {
if userMessage == "" {
userMessage = "Internal Server Error (no specific error)"
}
// There appears to be a chance to cause a zombie process and failure to read the Exit status
// if nothing is outputted on stdout.
_, _ = fmt.Fprintln(os.Stdout, "")
_, _ = fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
if len(logMessage) > 0 {
if logMsgFmt != "" {
logMsg := fmt.Sprintf(logMsgFmt, args...)
if !setting.IsProd {
_, _ = fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
_, _ = fmt.Fprintln(os.Stderr, "Gitea:", logMsg)
}
}
ctx, cancel := installSignals()
defer cancel()
if len(logMessage) > 0 {
_ = private.SSHLog(ctx, true, fmt.Sprintf(logMessage+": ", args...))
if userMessage != "" {
if unicode.IsPunct(rune(userMessage[len(userMessage)-1])) {
logMsg = userMessage + " " + logMsg
} else {
logMsg = userMessage + ". " + logMsg
}
}
_ = private.SSHLog(ctx, true, logMsg)
}
return cli.NewExitError("", 1)
}
// handleCliResponseExtra handles the extra response from the cli sub-commands
// If there is a user message it will be printed to stdout
// If the command failed it will return an error (the error will be printed by cli framework)
func handleCliResponseExtra(extra private.ResponseExtra) error {
if extra.UserMsg != "" {
_, _ = fmt.Fprintln(os.Stdout, extra.UserMsg)
}
if extra.HasError() {
return cli.NewExitError(extra.Error, 1)
}
return nil
}
func runServ(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
// FIXME: This needs to internationalised
setup("serv.log", c.Bool("debug"))
setup(ctx, c.Bool("debug"))
if setting.SSH.Disabled {
println("Gitea: SSH has been disabled")
@ -135,18 +157,18 @@ func runServ(c *cli.Context) error {
keys := strings.Split(c.Args()[0], "-")
if len(keys) != 2 || keys[0] != "key" {
return fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
return fail(ctx, "Key ID format error", "Invalid key argument: %s", c.Args()[0])
}
keyID, err := strconv.ParseInt(keys[1], 10, 64)
if err != nil {
return fail("Key ID format error", "Invalid key argument: %s", c.Args()[1])
return fail(ctx, "Key ID parsing error", "Invalid key argument: %s", c.Args()[1])
}
cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
if len(cmd) == 0 {
key, user, err := private.ServNoCommand(ctx, keyID)
if err != nil {
return fail("Internal error", "Failed to check provided key: %v", err)
return fail(ctx, "Key check failed", "Failed to check provided key: %v", err)
}
switch key.Type {
case asymkey_model.KeyTypeDeploy:
@ -164,7 +186,7 @@ func runServ(c *cli.Context) error {
words, err := shellquote.Split(cmd)
if err != nil {
return fail("Error parsing arguments", "Failed to parse arguments: %v", err)
return fail(ctx, "Error parsing arguments", "Failed to parse arguments: %v", err)
}
if len(words) < 2 {
@ -175,7 +197,7 @@ func runServ(c *cli.Context) error {
return nil
}
}
return fail("Too few arguments", "Too few arguments in cmd: %s", cmd)
return fail(ctx, "Too few arguments", "Too few arguments in cmd: %s", cmd)
}
verb := words[0]
@ -187,7 +209,7 @@ func runServ(c *cli.Context) error {
var lfsVerb string
if verb == lfsAuthenticateVerb {
if !setting.LFS.StartServer {
return fail("Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
return fail(ctx, "Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
}
if len(words) > 2 {
@ -200,37 +222,37 @@ func runServ(c *cli.Context) error {
rr := strings.SplitN(repoPath, "/", 2)
if len(rr) != 2 {
return fail("Invalid repository path", "Invalid repository path: %v", repoPath)
return fail(ctx, "Invalid repository path", "Invalid repository path: %v", repoPath)
}
username := strings.ToLower(rr[0])
reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
if alphaDashDotPattern.MatchString(reponame) {
return fail("Invalid repo name", "Invalid repo name: %s", reponame)
return fail(ctx, "Invalid repo name", "Invalid repo name: %s", reponame)
}
if c.Bool("enable-pprof") {
if err := os.MkdirAll(setting.PprofDataPath, os.ModePerm); err != nil {
return fail("Error while trying to create PPROF_DATA_PATH", "Error while trying to create PPROF_DATA_PATH: %v", err)
return fail(ctx, "Error while trying to create PPROF_DATA_PATH", "Error while trying to create PPROF_DATA_PATH: %v", err)
}
stopCPUProfiler, err := pprof.DumpCPUProfileForUsername(setting.PprofDataPath, username)
if err != nil {
return fail("Internal Server Error", "Unable to start CPU profile: %v", err)
return fail(ctx, "Unable to start CPU profiler", "Unable to start CPU profile: %v", err)
}
defer func() {
stopCPUProfiler()
err := pprof.DumpMemProfileForUsername(setting.PprofDataPath, username)
if err != nil {
_ = fail("Internal Server Error", "Unable to dump Mem Profile: %v", err)
_ = fail(ctx, "Unable to dump Mem profile", "Unable to dump Mem Profile: %v", err)
}
}()
}
requestedMode, has := allowedCommands[verb]
if !has {
return fail("Unknown git command", "Unknown git command %s", verb)
return fail(ctx, "Unknown git command", "Unknown git command %s", verb)
}
if verb == lfsAuthenticateVerb {
@ -239,20 +261,13 @@ func runServ(c *cli.Context) error {
} else if lfsVerb == "download" {
requestedMode = perm.AccessModeRead
} else {
return fail("Unknown LFS verb", "Unknown lfs verb %s", lfsVerb)
return fail(ctx, "Unknown LFS verb", "Unknown lfs verb %s", lfsVerb)
}
}
results, err := private.ServCommand(ctx, keyID, username, reponame, requestedMode, verb, lfsVerb)
if err != nil {
if private.IsErrServCommand(err) {
errServCommand := err.(private.ErrServCommand)
if errServCommand.StatusCode != http.StatusInternalServerError {
return fail("Unauthorized", "%s", errServCommand.Error())
}
return fail("Internal Server Error", "%s", errServCommand.Error())
}
return fail("Internal Server Error", "%s", err.Error())
results, extra := private.ServCommand(ctx, keyID, username, reponame, requestedMode, verb, lfsVerb)
if extra.HasError() {
return fail(ctx, extra.UserMsg, "ServCommand failed: %s", extra.Error)
}
// LFS token authentication
@ -274,7 +289,7 @@ func runServ(c *cli.Context) error {
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
if err != nil {
return fail("Internal error", "Failed to sign JWT token: %v", err)
return fail(ctx, "Failed to sign JWT Token", "Failed to sign JWT token: %v", err)
}
tokenAuthentication := &git_model.LFSTokenResponse{
@ -286,7 +301,7 @@ func runServ(c *cli.Context) error {
enc := json.NewEncoder(os.Stdout)
err = enc.Encode(tokenAuthentication)
if err != nil {
return fail("Internal error", "Failed to encode LFS json response: %v", err)
return fail(ctx, "Failed to encode LFS json response", "Failed to encode LFS json response: %v", err)
}
return nil
}
@ -332,13 +347,13 @@ func runServ(c *cli.Context) error {
gitcmd.Env = append(gitcmd.Env, git.CommonCmdServEnvs()...)
if err = gitcmd.Run(); err != nil {
return fail("Internal error", "Failed to execute git command: %v", err)
return fail(ctx, "Failed to execute git command", "Failed to execute git command: %v", err)
}
// Update user key activity.
if results.KeyID > 0 {
if err = private.UpdatePublicKeyInRepo(ctx, results.KeyID, results.RepoID); err != nil {
return fail("Internal error", "UpdatePublicKeyInRepo: %v", err)
return fail(ctx, "Failed to update public key", "UpdatePublicKeyInRepo: %v", err)
}
}

View File

@ -9,6 +9,8 @@ import (
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
_ "net/http/pprof" // Used for debugging if enabled and a web server is running
@ -25,6 +27,9 @@ import (
ini "gopkg.in/ini.v1"
)
// PIDFile could be set from build tag
var PIDFile = "/run/gitea.pid"
// CmdWeb represents the available web sub-command.
var CmdWeb = cli.Command{
Name: "web",
@ -45,7 +50,7 @@ and it takes care of all the other things for you`,
},
cli.StringFlag{
Name: "pid, P",
Value: setting.PIDFile,
Value: PIDFile,
Usage: "Custom pid file path",
},
cli.BoolFlag{
@ -81,6 +86,22 @@ func runHTTPRedirector() {
}
}
func createPIDFile(pidPath string) {
currentPid := os.Getpid()
if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
log.Fatal("Failed to create PID folder: %v", err)
}
file, err := os.Create(pidPath)
if err != nil {
log.Fatal("Failed to create PID file: %v", err)
}
defer file.Close()
if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
log.Fatal("Failed to write PID information: %v", err)
}
}
func runWeb(ctx *cli.Context) error {
if ctx.Bool("verbose") {
_ = log.DelLogger("console")
@ -107,8 +128,7 @@ func runWeb(ctx *cli.Context) error {
// Set pid file setting
if ctx.IsSet("pid") {
setting.PIDFile = ctx.String("pid")
setting.WritePIDFile = true
createPIDFile(ctx.String("pid"))
}
// Perform pre-initialization

View File

@ -1,2 +0,0 @@
#!/bin/sh
su git -c "/home/git/gogs/scripts/gogs_supervisord.sh restart"

View File

@ -16,7 +16,7 @@ import (
"strings"
"syscall"
"github.com/google/go-github/v45/github"
"github.com/google/go-github/v51/github"
"github.com/urfave/cli"
"gopkg.in/yaml.v3"
)

84
contrib/init/ubuntu/gitea Normal file
View File

@ -0,0 +1,84 @@
#!/bin/sh
### BEGIN INIT INFO
# Provides: gitea
# Required-Start: $syslog $network
# Required-Stop: $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: A self-hosted Git service written in Go.
# Description: A self-hosted Git service written in Go.
### END INIT INFO
# Do NOT "set -e"
# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
DESC="Gitea - Git with a cup of tea"
NAME=gitea
SERVICEVERBOSE=yes
PIDFILE=/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
WORKINGDIR=/var/lib/$NAME
DAEMON=/usr/local/bin/$NAME
DAEMON_ARGS="web -c /etc/$NAME/app.ini"
USER=git
STOP_SCHEDULE="${STOP_SCHEDULE:-QUIT/5/TERM/1/KILL/5}"
# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0
do_start()
{
GITEA_ENVS="USER=$USER GITEA_WORK_DIR=$WORKINGDIR HOME=/home/$USER"
GITEA_EXEC="$DAEMON -- $DAEMON_ARGS"
sh -c "start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile \\
--background --chdir $WORKINGDIR --chuid $USER \\
--exec /bin/bash -- -c '/usr/bin/env $GITEA_ENVS $GITEA_EXEC'"
}
do_stop()
{
start-stop-daemon --stop --quiet --retry=$STOP_SCHEDULE --pidfile $PIDFILE --name $NAME --oknodo
rm -f $PIDFILE
}
do_status()
{
if [ -f $PIDFILE ]; then
if kill -0 $(cat "$PIDFILE"); then
echo "$NAME is running, PID is $(cat $PIDFILE)"
else
echo "$NAME process is dead, but pidfile exists"
fi
else
echo "$NAME is not running"
fi
}
case "$1" in
start)
echo "Starting $DESC" "$NAME"
do_start
;;
stop)
echo "Stopping $DESC" "$NAME"
do_stop
;;
status)
do_status
;;
restart)
echo "Restarting $DESC" "$NAME"
do_stop
do_start
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2
exit 2
;;
esac
exit 0

View File

@ -1,2 +0,0 @@
DROP DATABASE IF EXISTS gitea;
CREATE DATABASE IF NOT EXISTS gitea CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

View File

@ -1,267 +0,0 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package main
/*
Checkout a PR and load the tests data into sqlite database
*/
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"runtime"
"strconv"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
gitea_git "code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/markup/external"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/routers"
markup_service "code.gitea.io/gitea/services/markup"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"xorm.io/xorm"
)
var codeFilePath = "contrib/pr/checkout.go"
func runPR() {
log.Printf("[PR] Starting gitea ...\n")
curDir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
setting.SetCustomPathAndConf("", "", "")
setting.InitProviderAllowEmpty()
setting.LoadCommonSettings()
setting.RepoRootPath, err = os.MkdirTemp(os.TempDir(), "repos")
if err != nil {
log.Fatalf("TempDir: %v\n", err)
}
setting.AppDataPath, err = os.MkdirTemp(os.TempDir(), "appdata")
if err != nil {
log.Fatalf("TempDir: %v\n", err)
}
setting.AppWorkPath = curDir
setting.StaticRootPath = curDir
setting.GravatarSource = "https://secure.gravatar.com/avatar/"
setting.AppURL = "http://localhost:8080/"
setting.HTTPPort = "8080"
setting.SSH.Domain = "localhost"
setting.SSH.Port = 3000
setting.InstallLock = true
setting.SecretKey = "9pCviYTWSb"
setting.InternalToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0OTI3OTU5ODN9.OQkH5UmzID2XBdwQ9TAI6Jj2t1X-wElVTjbE7aoN4I8"
curUser, err := user.Current()
if err != nil {
log.Fatal(err)
}
setting.RunUser = curUser.Username
log.Printf("[PR] Loading fixtures data ...\n")
//models.LoadConfigs()
/*
setting.Database.Type = "sqlite3"
setting.Database.Path = ":memory:"
setting.Database.Timeout = 500
*/
dbCfg := setting.CfgProvider.Section("database")
dbCfg.NewKey("DB_TYPE", "sqlite3")
dbCfg.NewKey("PATH", ":memory:")
routers.InitGitServices()
setting.Database.LogSQL = true
// x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
db.InitEngineWithMigration(context.Background(), func(_ *xorm.Engine) error {
return nil
})
db.HasEngine = true
// x.ShowSQL(true)
err = unittest.InitFixtures(
unittest.FixturesOptions{
Dir: path.Join(curDir, "models/fixtures/"),
},
)
if err != nil {
fmt.Printf("Error initializing test database: %v\n", err)
os.Exit(1)
}
unittest.LoadFixtures()
util.RemoveAll(setting.RepoRootPath)
util.RemoveAll(repo_module.LocalCopyPath())
unittest.CopyDir(path.Join(curDir, "tests/gitea-repositories-meta"), setting.RepoRootPath)
log.Printf("[PR] Setting up router\n")
// routers.GlobalInit()
external.RegisterRenderers()
markup.Init(markup_service.ProcessorHelper())
c := routers.NormalRoutes(graceful.GetManager().HammerContext())
log.Printf("[PR] Ready for testing !\n")
log.Printf("[PR] Login with user1, user2, user3, ... with pass: password\n")
/*
log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
if setting.LFS.StartServer {
log.Info("LFS server enabled")
}
if setting.EnablePprof {
go func() {
log.Info("Starting pprof server on localhost:6060")
log.Info("%v", http.ListenAndServe("localhost:6060", nil))
}()
}
*/
// Start the server
http.ListenAndServe(":8080", c)
log.Printf("[PR] Cleaning up ...\n")
/*
if err = util.RemoveAll(setting.Indexer.IssuePath); err != nil {
fmt.Printf("util.RemoveAll: %v\n", err)
os.Exit(1)
}
if err = util.RemoveAll(setting.Indexer.RepoPath); err != nil {
fmt.Printf("Unable to remove repo indexer: %v\n", err)
os.Exit(1)
}
*/
if err = util.RemoveAll(setting.RepoRootPath); err != nil {
log.Fatalf("util.RemoveAll: %v\n", err)
}
if err = util.RemoveAll(setting.AppDataPath); err != nil {
log.Fatalf("util.RemoveAll: %v\n", err)
}
}
func main() {
runPRFlag := flag.Bool("run", false, "Run the PR code")
flag.Parse()
if *runPRFlag {
runPR()
return
}
// To force checkout (e.g. Windows complains about unclean work tree) set env variable FORCE=true
force, err := strconv.ParseBool(os.Getenv("FORCE"))
if err != nil {
force = false
}
// Otherwise checkout PR
if len(os.Args) != 2 {
log.Fatal("Need only one arg: the PR number")
}
pr := os.Args[1]
codeFilePath = filepath.FromSlash(codeFilePath) // Convert to running OS
// Copy this file if it will not exist in the PR branch
dat, err := os.ReadFile(codeFilePath)
if err != nil {
log.Fatalf("Failed to cache this code file : %v", err)
}
repo, err := git.PlainOpen(".")
if err != nil {
log.Fatalf("Failed to open the repo : %v", err)
}
// Find remote upstream
remotes, err := repo.Remotes()
if err != nil {
log.Fatalf("Failed to list remotes of repo : %v", err)
}
remoteUpstream := "origin" // Default
for _, r := range remotes {
if r.Config().URLs[0] == "https://github.com/go-gitea/gitea.git" ||
r.Config().URLs[0] == "https://github.com/go-gitea/gitea" ||
r.Config().URLs[0] == "git@github.com:go-gitea/gitea.git" { // fetch at index 0
remoteUpstream = r.Config().Name
break
}
}
branch := fmt.Sprintf("pr-%s-%d", pr, time.Now().Unix())
branchRef := plumbing.NewBranchReferenceName(branch)
log.Printf("Fetching PR #%s in %s\n", pr, branch)
if runtime.GOOS == "windows" {
// Use git cli command for windows
runCmd("git", "fetch", remoteUpstream, fmt.Sprintf("pull/%s/head:%s", pr, branch))
} else {
ref := fmt.Sprintf("%s%s/head:%s", gitea_git.PullPrefix, pr, branchRef)
err = repo.Fetch(&git.FetchOptions{
RemoteName: remoteUpstream,
RefSpecs: []config.RefSpec{
config.RefSpec(ref),
},
})
if err != nil {
log.Fatalf("Failed to fetch %s from %s : %v", ref, remoteUpstream, err)
}
}
tree, err := repo.Worktree()
if err != nil {
log.Fatalf("Failed to parse git tree : %v", err)
}
log.Printf("Checkout PR #%s in %s\n", pr, branch)
err = tree.Checkout(&git.CheckoutOptions{
Branch: branchRef,
Force: force,
})
if err != nil {
log.Fatalf("Failed to checkout %s : %v", branch, err)
}
// Copy this file if not exist
if _, err := os.Stat(codeFilePath); os.IsNotExist(err) {
err = os.MkdirAll(filepath.Dir(codeFilePath), 0o755)
if err != nil {
log.Fatalf("Failed to duplicate this code file in PR : %v", err)
}
err = os.WriteFile(codeFilePath, dat, 0o644)
if err != nil {
log.Fatalf("Failed to duplicate this code file in PR : %v", err)
}
}
// Force build of js, css, bin, ...
runCmd("make", "build")
// Start with integration test
runCmd("go", "run", "-mod", "vendor", "-tags", "sqlite sqlite_unlock_notify", codeFilePath, "-run")
}
func runCmd(cmd ...string) {
log.Printf("Executing : %s ...\n", cmd)
c := exec.Command(cmd[0], cmd[1:]...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if err := c.Start(); err != nil {
log.Panicln(err)
}
if err := c.Wait(); err != nil {
log.Panicln(err)
}
}

View File

@ -20,7 +20,7 @@
;; - The environment variable `$GITEA_WORK_DIR`
;; - A built-in value set at build time (see building from source)
;; - Otherwise it defaults to the directory of the _`AppPath`_
;; - If any of the above are relative paths then they are made absolute against the
;; - If any of the above are relative paths then they are made absolute against
;; the directory of the _`AppPath`_
;; - _`CustomPath`_: This is the base directory for custom templates and other options.
;; It is determined by using the first set thing in the following hierarchy:
@ -186,8 +186,8 @@ RUN_MODE = ; prod
;; default is the system temporary directory.
;SSH_KEY_TEST_PATH =
;;
;; Path to ssh-keygen, default is 'ssh-keygen' which means the shell is responsible for finding out which one to call.
;SSH_KEYGEN_PATH = ssh-keygen
;; Use `ssh-keygen` to parse public SSH keys. The value is passed to the shell. By default, Gitea does the parsing itself.
;SSH_KEYGEN_PATH =
;;
;; Enable SSH Authorized Key Backup when rewriting all keys, default is true
;SSH_AUTHORIZED_KEYS_BACKUP = true
@ -576,6 +576,22 @@ ROUTER = console
;; The routing level will default to that of the system but individual router level can be set in
;; [log.<mode>.router] LEVEL
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Print request id which parsed from request headers in access log, when access log is enabled.
;; * E.g:
;; * In request Header: X-Request-ID: test-id-123
;; * Configuration in app.ini: REQUEST_ID_HEADERS = X-Request-ID
;; * Print in log: 127.0.0.1:58384 - - [14/Feb/2023:16:33:51 +0800] "test-id-123"
;;
;; If you configure more than one in the .ini file, it will match in the order of configuration,
;; and the first match will be finally printed in the log.
;; * E.g:
;; * In reuqest Header: X-Trace-ID: trace-id-1q2w3e4r
;; * Configuration in app.ini: REQUEST_ID_HEADERS = X-Request-ID, X-Trace-ID, X-Req-ID
;; * Print in log: 127.0.0.1:58384 - - [14/Feb/2023:16:33:51 +0800] "trace-id-1q2w3e4r"
;;
;; REQUEST_ID_HEADERS =
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
@ -587,7 +603,7 @@ ROUTER = console
;ACCESS = file
;;
;; Sets the template used to create the access log.
;ACCESS_LOG_TEMPLATE = {{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"
;ACCESS_LOG_TEMPLATE = {{.Ctx.RemoteHost}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}" "{{.Ctx.Req.UserAgent}}"
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
@ -931,10 +947,10 @@ ROUTER = console
;USE_COMPAT_SSH_URI = false
;;
;; Close issues as long as a commit on any branch marks it as fixed
;; Comma separated list of globally disabled repo units. Allowed values: repo.issues, repo.ext_issues, repo.pulls, repo.wiki, repo.ext_wiki, repo.projects, repo.packages
;; Comma separated list of globally disabled repo units. Allowed values: repo.issues, repo.ext_issues, repo.pulls, repo.wiki, repo.ext_wiki, repo.projects, repo.packages, repo.actions.
;DISABLED_REPO_UNITS =
;;
;; Comma separated list of default new repo units. Allowed values: repo.code, repo.releases, repo.issues, repo.pulls, repo.wiki, repo.projects, repo.packages.
;; Comma separated list of default new repo units. Allowed values: repo.code, repo.releases, repo.issues, repo.pulls, repo.wiki, repo.projects, repo.packages, repo.actions.
;; Note: Code and Releases can currently not be deactivated. If you specify default repo units you should still list them for future compatibility.
;; External wiki and issue tracker can't be enabled by default as it requires additional settings.
;; Disabled repo units will not be added to new repositories regardless if it is in the default list.
@ -977,10 +993,6 @@ ROUTER = console
;; List of file extensions for which lines should be wrapped in the Monaco editor
;; Separate extensions with a comma. To line wrap files without an extension, just put a comma
;LINE_WRAP_EXTENSIONS = .txt,.md,.markdown,.mdown,.mkd,
;;
;; Valid file modes that have a preview API associated with them, such as api/v1/markdown
;; Separate the values by commas. The preview tab in edit mode won't be displayed if the file extension doesn't match
;PREVIEWABLE_FILE_MODES = markdown
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -1226,6 +1238,10 @@ ROUTER = console
;;
;; Whether to enable a Service Worker to cache frontend assets
;USE_SERVICE_WORKER = false
;;
;; Whether to only show relevant repos on the explore page when no keyword is specified and default sorting is used.
;; A repo is considered irrelevant if it's a fork or if it has no metadata (no description, no icon, no topic).
;ONLY_SHOW_RELEVANT_REPOS = false
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -1345,13 +1361,13 @@ ROUTER = console
;; Issue Indexer settings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Issue indexer type, currently support: bleve, db or elasticsearch, default is bleve
;; Issue indexer type, currently support: bleve, db, elasticsearch or meilisearch default is bleve
;ISSUE_INDEXER_TYPE = bleve
;;
;; Issue indexer storage path, available when ISSUE_INDEXER_TYPE is bleve
;ISSUE_INDEXER_PATH = indexers/issues.bleve ; Relative paths will be made absolute against _`AppWorkPath`_.
;;
;; Issue indexer connection string, available when ISSUE_INDEXER_TYPE is elasticsearch
;; Issue indexer connection string, available when ISSUE_INDEXER_TYPE is elasticsearch or meilisearch
;ISSUE_INDEXER_CONN_STR = http://elastic:changeme@localhost:9200
;;
;; Issue indexer name, available when ISSUE_INDEXER_TYPE is elasticsearch
@ -1832,7 +1848,7 @@ ROUTER = console
;ENABLED = true
;;
;; Comma-separated list of allowed file extensions (`.zip`), mime types (`text/plain`) or wildcard type (`image/*`, `audio/*`, `video/*`). Empty value or `*/*` allows all types.
;ALLOWED_TYPES = .csv,.docx,.fodg,.fodp,.fods,.fodt,.gif,.gz,.jpeg,.jpg,.log,.md,.mov,.mp4,.odf,.odg,.odp,.ods,.odt,.pdf,.png,.pptx,.svg,.tgz,.txt,.webm,.xls,.xlsx,.zip
;ALLOWED_TYPES = .csv,.docx,.fodg,.fodp,.fods,.fodt,.gif,.gz,.jpeg,.jpg,.log,.md,.mov,.mp4,.odf,.odg,.odp,.ods,.odt,.patch,.pdf,.png,.pptx,.svg,.tgz,.txt,.webm,.xls,.xlsx,.zip
;;
;; Max size of each file. Defaults to 4MB
;MAX_SIZE = 4
@ -1874,6 +1890,9 @@ ROUTER = console
;;
;; Minio skip SSL verification available when STORAGE_TYPE is `minio`
;MINIO_INSECURE_SKIP_VERIFY = false
;;
;; Minio checksum algorithm: default (for MinIO or AWS S3) or md5 (for Cloudflare or Backblaze)
;MINIO_CHECKSUM_ALGORITHM = default
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -2256,6 +2275,17 @@ ROUTER = console
;PULL = 300
;GC = 60
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Git Reflog timeout in days
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;[git.reflog]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;ENABLED = true
;EXPIRATION = 90
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;[mirror]
@ -2489,6 +2519,8 @@ ROUTER = console
;LIMIT_SIZE_PYPI = -1
;; Maximum size of a RubyGems upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_RUBYGEMS = -1
;; Maximum size of a Swift upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_SWIFT = -1
;; Maximum size of a Vagrant upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
;LIMIT_SIZE_VAGRANT = -1

View File

@ -1,8 +1,8 @@
THEME := themes/gitea
PUBLIC := public
ARCHIVE := https://dl.gitea.io/theme/master.tar.gz
ARCHIVE := https://dl.gitea.com/theme/main.tar.gz
HUGO_PACKAGE := github.com/gohugoio/hugo@v0.82.0
HUGO_PACKAGE := github.com/gohugoio/hugo@v0.111.3
.PHONY: all
all: build

View File

@ -18,7 +18,7 @@ params:
description: Git with a cup of tea
author: The Gitea Authors
website: https://docs.gitea.io
version: 1.18.5
version: 1.19.0
minGoVersion: 1.19
goVersion: 1.20
minNodeVersion: 16
@ -26,6 +26,11 @@ params:
repo: "https://github.com/go-gitea/gitea"
docContentPath: "docs/content"
markup:
tableOfContents:
startLevel: 1
endLevel: 9
outputs:
home:
- HTML

View File

@ -0,0 +1,14 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "Administration"
slug: "administration"
weight: 30
toc: false
draft: false
menu:
sidebar:
name: "Administration"
weight: 20
collapse: true
identifier: "administration"
---

View File

@ -1,13 +1,13 @@
---
date: "2017-08-23T09:00:00+02:00"
title: "Avancé"
slug: "advanced"
slug: "administration"
weight: 30
toc: false
draft: false
menu:
sidebar:
name: "Avancé"
weight: 40
identifier: "advanced"
weight: 20
identifier: "administration"
---

View File

@ -0,0 +1,13 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "运维"
slug: "administration"
weight: 30
toc: false
draft: false
menu:
sidebar:
name: "运维"
weight: 20
identifier: "administration"
---

View File

@ -0,0 +1,13 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "運維"
slug: "administration"
weight: 30
toc: false
draft: false
menu:
sidebar:
name: "運維"
weight: 20
identifier: "administration"
---

View File

@ -2,15 +2,15 @@
date: "2019-12-28"
title: "Adding Legal Pages"
slug: adding-legal-pages
weight: 9
weight: 110
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "Adding Legal Pages"
identifier: "adding-legal-pages"
weight: 9
weight: 110
---
Some jurisdictions (such as EU), requires certain legal pages (e.g. Privacy Policy) to be added to website. Follow these steps to add them to your Gitea instance.

View File

@ -1,13 +1,13 @@
---
date: "2017-01-01T16:00:00+02:00"
title: "Usage: Backup and Restore"
title: "Backup and Restore"
slug: "backup-and-restore"
weight: 11
toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "Backup and Restore"
weight: 11
identifier: "backup-and-restore"

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "备份与恢复"
weight: 11
identifier: "backup-and-restore"

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "備份與還原"
weight: 11
identifier: "backup-and-restore"

View File

@ -2,14 +2,14 @@
date: "2020-01-25T21:00:00-03:00"
title: "Embedded data extraction tool"
slug: "cmd-embedded"
weight: 40
weight: 20
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "Embedded data extraction tool"
weight: 40
weight: 20
identifier: "cmd-embedded"
---
@ -21,7 +21,7 @@ menu:
Gitea's executable contains all the resources required to run: templates, images, style-sheets
and translations. Any of them can be overridden by placing a replacement in a matching path
inside the `custom` directory (see [Customizing Gitea]({{< relref "doc/advanced/customizing-gitea.en-us.md" >}})).
inside the `custom` directory (see [Customizing Gitea]({{< relref "doc/administration/customizing-gitea.en-us.md" >}})).
To obtain a copy of the embedded resources ready for editing, the `embedded` command from the CLI
can be used from the OS shell interface.
@ -85,7 +85,7 @@ The default is the current directory.
The `--custom` flag tells Gitea to extract the files directly into the `custom` directory.
For this to work, the command needs to know the location of the `app.ini` configuration
file (`--config`) and, depending of the configuration, be ran from the directory where
Gitea normally starts. See [Customizing Gitea]({{< relref "doc/advanced/customizing-gitea.en-us.md" >}}) for details.
Gitea normally starts. See [Customizing Gitea]({{< relref "doc/administration/customizing-gitea.en-us.md" >}}) for details.
The `--overwrite` flag allows any existing files in the destination directory to be overwritten.

View File

@ -1,15 +1,15 @@
---
date: "2017-01-01T16:00:00+02:00"
title: "Usage: Command Line"
title: "Gitea Command Line"
slug: "command-line"
weight: 10
weight: 1
toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "Command Line"
weight: 10
weight: 1
identifier: "command-line"
---
@ -551,3 +551,28 @@ Restore-repo restore repository data from disk dir:
- `--owner_name lunny`: Restore destination owner name
- `--repo_name tango`: Restore destination repository name
- `--units <units>`: Which items will be restored, one or more units should be separated as comma. wiki, issues, labels, releases, release_assets, milestones, pull_requests, comments are allowed. Empty means all units.
### actions generate-runner-token
Generate a new token for a runner to use to register with the server
- Options:
- `--scope {owner}[/{repo}]`, `-s {owner}[/{repo}]`: To limit the scope of the runner, no scope means the runner can be used for all repos, but you can also limit it to a specific repo or owner
To register a global runner:
```
gitea actions generate-runner-token
```
To register a runner for a specific organization, in this case `org`:
```
gitea actions generate-runner-token -s org
```
To register a runner for a specific repo, in this case `username/test-repo`:
```
gitea actions generate-runner-token -s username/test-repo
```

View File

@ -2,14 +2,14 @@
date: "2016-12-26T16:00:00+02:00"
title: "Config Cheat Sheet"
slug: "config-cheat-sheet"
weight: 20
weight: 30
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "Config Cheat Sheet"
weight: 20
weight: 30
identifier: "config-cheat-sheet"
---
@ -46,7 +46,7 @@ reported as part of the default configuration when running `gitea --help` or on
- The environment variable `$GITEA_WORK_DIR`
- A built-in value set at build time (see building from source)
- Otherwise it defaults to the directory of the _`AppPath`_
- If any of the above are relative paths then they are made absolute against the
- If any of the above are relative paths then they are made absolute against
the directory of the _`AppPath`_
- _`CustomPath`_: This is the base directory for custom templates and other options.
It is determined by using the first set thing in the following hierarchy:
@ -103,8 +103,8 @@ In addition there is _`StaticRootPath`_ which can be set as a built-in at build
- `DEFAULT_CLOSE_ISSUES_VIA_COMMITS_IN_ANY_BRANCH`: **false**: Close an issue if a commit on a non default branch marks it as closed.
- `ENABLE_PUSH_CREATE_USER`: **false**: Allow users to push local repositories to Gitea and have them automatically created for a user.
- `ENABLE_PUSH_CREATE_ORG`: **false**: Allow users to push local repositories to Gitea and have them automatically created for an org.
- `DISABLED_REPO_UNITS`: **_empty_**: Comma separated list of globally disabled repo units. Allowed values: \[repo.issues, repo.ext_issues, repo.pulls, repo.wiki, repo.ext_wiki, repo.projects\]
- `DEFAULT_REPO_UNITS`: **repo.code,repo.releases,repo.issues,repo.pulls,repo.wiki,repo.projects,repo.packages**: Comma separated list of default new repo units. Allowed values: \[repo.code, repo.releases, repo.issues, repo.pulls, repo.wiki, repo.projects\]. Note: Code and Releases can currently not be deactivated. If you specify default repo units you should still list them for future compatibility. External wiki and issue tracker can't be enabled by default as it requires additional settings. Disabled repo units will not be added to new repositories regardless if it is in the default list.
- `DISABLED_REPO_UNITS`: **_empty_**: Comma separated list of globally disabled repo units. Allowed values: \[repo.issues, repo.ext_issues, repo.pulls, repo.wiki, repo.ext_wiki, repo.projects, repo.packages, repo.actions\]
- `DEFAULT_REPO_UNITS`: **repo.code,repo.releases,repo.issues,repo.pulls,repo.wiki,repo.projects,repo.packages**: Comma separated list of default new repo units. Allowed values: \[repo.code, repo.releases, repo.issues, repo.pulls, repo.wiki, repo.projects, repo.packages, repo.actions\]. Note: Code and Releases can currently not be deactivated. If you specify default repo units you should still list them for future compatibility. External wiki and issue tracker can't be enabled by default as it requires additional settings. Disabled repo units will not be added to new repositories regardless if it is in the default list.
- `DEFAULT_FORK_REPO_UNITS`: **repo.code,repo.pulls**: Comma separated list of default forked repo units. The set of allowed values and rules is the same as `DEFAULT_REPO_UNITS`.
- `PREFIX_ARCHIVE_FILES`: **true**: Prefix archive files by placing them in a directory named after the repository.
- `DISABLE_MIGRATIONS`: **false**: Disable migrating feature.
@ -226,11 +226,13 @@ The following configuration set `Content-Type: application/vnd.android.package-a
Values can be emoji alias (:smile:) or a unicode emoji.
For custom reactions, add a tightly cropped square image to public/img/emoji/reaction_name.png
- `CUSTOM_EMOJIS`: **gitea, codeberg, gitlab, git, github, gogs**: Additional Emojis not defined in the utf8 standard.
By default we support Gitea (:gitea:), to add more copy them to public/img/emoji/emoji_name.png and
By default, we support Gitea (:gitea:), to add more copy them to public/img/emoji/emoji_name.png and
add it to this config.
- `DEFAULT_SHOW_FULL_NAME`: **false**: Whether the full name of the users should be shown where possible. If the full name isn't set, the username will be used.
- `SEARCH_REPO_DESCRIPTION`: **true**: Whether to search within description at repository search on explore page.
- `USE_SERVICE_WORKER`: **false**: Whether to enable a Service Worker to cache frontend assets.
- `ONLY_SHOW_RELEVANT_REPOS`: **false** Whether to only show relevant repos on the explore page when no keyword is specified and default sorting is used.
A repo is considered irrelevant if it's a fork or if it has no metadata (no description, no icon, no topic).
### UI - Admin (`ui.admin`)
@ -343,7 +345,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a
- `SSH_SERVER_MACS`: **hmac-sha2-256-etm@openssh.com, hmac-sha2-256, hmac-sha1**: For the built-in SSH server, choose the MACs to support for SSH connections, for system SSH this setting has no effect
- `SSH_SERVER_HOST_KEYS`: **ssh/gitea.rsa, ssh/gogs.rsa**: For the built-in SSH server, choose the keypairs to offer as the host key. The private key should be at `SSH_SERVER_HOST_KEY` and the public `SSH_SERVER_HOST_KEY.pub`. Relative paths are made absolute relative to the `APP_DATA_PATH`. If no key exists a 4096 bit RSA key will be created for you.
- `SSH_KEY_TEST_PATH`: **/tmp**: Directory to create temporary files in when testing public keys using ssh-keygen, default is the system temporary directory.
- `SSH_KEYGEN_PATH`: **ssh-keygen**: Path to ssh-keygen, default is 'ssh-keygen' which means the shell is responsible for finding out which one to call.
- `SSH_KEYGEN_PATH`: **\<empty\>**: Use `ssh-keygen` to parse public SSH keys. The value is passed to the shell. By default, Gitea does the parsing itself.
- `SSH_EXPOSE_ANONYMOUS`: **false**: Enable exposure of SSH clone URL to anonymous visitors, default is false.
- `SSH_PER_WRITE_TIMEOUT`: **30s**: Timeout for any write to the SSH connections. (Set to
-1 to disable all timeouts.)
@ -456,8 +458,8 @@ relation to port exhaustion.
## Indexer (`indexer`)
- `ISSUE_INDEXER_TYPE`: **bleve**: Issue indexer type, currently supported: `bleve`, `db` or `elasticsearch`.
- `ISSUE_INDEXER_CONN_STR`: ****: Issue indexer connection string, available when ISSUE_INDEXER_TYPE is elasticsearch. i.e. http://elastic:changeme@localhost:9200
- `ISSUE_INDEXER_TYPE`: **bleve**: Issue indexer type, currently supported: `bleve`, `db`, `elasticsearch` or `meilisearch`.
- `ISSUE_INDEXER_CONN_STR`: ****: Issue indexer connection string, available when ISSUE_INDEXER_TYPE is elasticsearch, or meilisearch. i.e. http://elastic:changeme@localhost:9200
- `ISSUE_INDEXER_NAME`: **gitea_issues**: Issue indexer name, available when ISSUE_INDEXER_TYPE is elasticsearch
- `ISSUE_INDEXER_PATH`: **indexers/issues.bleve**: Index file used for issue search; available when ISSUE_INDEXER_TYPE is bleve and elasticsearch. Relative paths will be made absolute against _`AppWorkPath`_.
- The next 4 configuration values are deprecated and should be set in `queue.issue_indexer` however are kept for backwards compatibility:
@ -753,7 +755,7 @@ and
- `FORCE_TRUST_SERVER_CERT`: **false**: If set to `true`, completely ignores server certificate validation errors. This option is unsafe. Consider adding the certificate to the system trust store instead.
- `USER`: **\<empty\>**: Username of mailing user (usually the sender's e-mail address).
- `PASSWD`: **\<empty\>**: Password of mailing user. Use \`your password\` for quoting if you use special characters in the password.
- Please note: authentication is only supported when the SMTP server communication is encrypted with TLS (this can be via `STARTTLS`) or SMTP host is localhost. See [Email Setup]({{< relref "doc/usage/email-setup.en-us.md" >}}) for more information.
- Please note: authentication is only supported when the SMTP server communication is encrypted with TLS (this can be via `STARTTLS`) or SMTP host is localhost. See [Email Setup]({{< relref "doc/administration/email-setup.en-us.md" >}}) for more information.
- `ENABLE_HELO`: **true**: Enable HELO operation.
- `HELO_HOSTNAME`: **(retrieved from system)**: HELO hostname.
- `FROM`: **\<empty\>**: Mail from address, RFC 5322. This can be just an email address, or the "Name" \<email@example.com\> format.
@ -841,7 +843,7 @@ Default templates for project boards:
## Issue and pull request attachments (`attachment`)
- `ENABLED`: **true**: Whether issue and pull request attachments are enabled.
- `ALLOWED_TYPES`: **.csv,.docx,.fodg,.fodp,.fods,.fodt,.gif,.gz,.jpeg,.jpg,.log,.md,.mov,.mp4,.odf,.odg,.odp,.ods,.odt,.pdf,.png,.pptx,.svg,.tgz,.txt,.webm,.xls,.xlsx,.zip**: Comma-separated list of allowed file extensions (`.zip`), mime types (`text/plain`) or wildcard type (`image/*`, `audio/*`, `video/*`). Empty value or `*/*` allows all types.
- `ALLOWED_TYPES`: **.csv,.docx,.fodg,.fodp,.fods,.fodt,.gif,.gz,.jpeg,.jpg,.log,.md,.mov,.mp4,.odf,.odg,.odp,.ods,.odt,.patch,.pdf,.png,.pptx,.svg,.tgz,.txt,.webm,.xls,.xlsx,.zip**: Comma-separated list of allowed file extensions (`.zip`), mime types (`text/plain`) or wildcard type (`image/*`, `audio/*`, `video/*`). Empty value or `*/*` allows all types.
- `MAX_SIZE`: **4**: Maximum size (MB).
- `MAX_FILES`: **5**: Maximum number of attachments that can be uploaded at once.
- `STORAGE_TYPE`: **local**: Storage type for attachments, `local` for local disk or `minio` for s3 compatible object storage service, default is `local` or other name defined with `[storage.xxx]`
@ -855,6 +857,7 @@ Default templates for project boards:
- `MINIO_BASE_PATH`: **attachments/**: Minio base path on the bucket only available when STORAGE_TYPE is `minio`
- `MINIO_USE_SSL`: **false**: Minio enabled ssl only available when STORAGE_TYPE is `minio`
- `MINIO_INSECURE_SKIP_VERIFY`: **false**: Minio skip SSL verification available when STORAGE_TYPE is `minio`
- `MINIO_CHECKSUM_ALGORITHM`: **default**: Minio checksum algorithm: `default` (for MinIO or AWS S3) or `md5` (for Cloudflare or Backblaze)
## Log (`log`)
@ -875,13 +878,19 @@ Default templates for project boards:
- `ENABLE_ACCESS_LOG`: **false**: Creates an access.log in NCSA common log format, or as per the following template
- `ACCESS`: **file**: Logging mode for the access logger, use a comma to separate values. Configure each mode in per mode log subsections `\[log.modename.access\]`. By default the file mode will log to `$ROOT_PATH/access.log`. (If you set this to `,` it will log to the default Gitea logger.)
- `ACCESS_LOG_TEMPLATE`: **`{{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"`**: Sets the template used to create the access log.
- `ACCESS_LOG_TEMPLATE`: **`{{.Ctx.RemoteHost}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}" "{{.Ctx.Req.UserAgent}}"`**: Sets the template used to create the access log.
- The following variables are available:
- `Ctx`: the `context.Context` of the request.
- `Identity`: the SignedUserName or `"-"` if not logged in.
- `Start`: the start time of the request.
- `ResponseWriter`: the responseWriter from the request.
- `RequestID`: the value matching REQUEST_ID_HEADERSdefault: `-`, if not matched.
- You must be very careful to ensure that this template does not throw errors or panics as this template runs outside of the panic/recovery script.
- `REQUEST_ID_HEADERS`: **\<empty\>**: You can configure multiple values that are splited by comma here. It will match in the order of configuration, and the first match will be finally printed in the access log.
- e.g.
- In the Request Header: X-Request-ID: **test-id-123**
- Configuration in app.ini: REQUEST_ID_HEADERS = X-Request-ID
- Print in log: 127.0.0.1:58384 - - [14/Feb/2023:16:33:51 +0800] "**test-id-123**" ...
### Log subsections (`log.name`, `log.name.*`)
@ -988,7 +997,7 @@ Default templates for project boards:
### Extended cron tasks (not enabled by default)
#### Cron - Garbage collect all repositories ('cron.git_gc_repos')
#### Cron - Garbage collect all repositories (`cron.git_gc_repos`)
- `ENABLED`: **false**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
@ -997,42 +1006,42 @@ Default templates for project boards:
- `NOTICE_ON_SUCCESS`: **false**: Set to true to switch on success notices.
- `ARGS`: **\<empty\>**: Arguments for command `git gc`, e.g. `--aggressive --auto`. The default value is same with [git] -> GC_ARGS
#### Cron - Update the '.ssh/authorized_keys' file with Gitea SSH keys ('cron.resync_all_sshkeys')
#### Cron - Update the '.ssh/authorized_keys' file with Gitea SSH keys (`cron.resync_all_sshkeys`)
- `ENABLED`: **false**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
- `NOTICE_ON_SUCCESS`: **false**: Set to true to switch on success notices.
- `SCHEDULE`: **@every 72h**: Cron syntax for scheduling repository archive cleanup, e.g. `@every 1h`.
#### Cron - Resynchronize pre-receive, update and post-receive hooks of all repositories ('cron.resync_all_hooks')
#### Cron - Resynchronize pre-receive, update and post-receive hooks of all repositories (`cron.resync_all_hooks`)
- `ENABLED`: **false**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
- `NOTICE_ON_SUCCESS`: **false**: Set to true to switch on success notices.
- `SCHEDULE`: **@every 72h**: Cron syntax for scheduling repository archive cleanup, e.g. `@every 1h`.
#### Cron - Reinitialize all missing Git repositories for which records exist ('cron.reinit_missing_repos')
#### Cron - Reinitialize all missing Git repositories for which records exist (`cron.reinit_missing_repos`)
- `ENABLED`: **false**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
- `NOTICE_ON_SUCCESS`: **false**: Set to true to switch on success notices.
- `SCHEDULE`: **@every 72h**: Cron syntax for scheduling repository archive cleanup, e.g. `@every 1h`.
#### Cron - Delete all repositories missing their Git files ('cron.delete_missing_repos')
#### Cron - Delete all repositories missing their Git files (`cron.delete_missing_repos`)
- `ENABLED`: **false**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
- `NOTICE_ON_SUCCESS`: **false**: Set to true to switch on success notices.
- `SCHEDULE`: **@every 72h**: Cron syntax for scheduling repository archive cleanup, e.g. `@every 1h`.
#### Cron - Delete generated repository avatars ('cron.delete_generated_repository_avatars')
#### Cron - Delete generated repository avatars (`cron.delete_generated_repository_avatars`)
- `ENABLED`: **false**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
- `NOTICE_ON_SUCCESS`: **false**: Set to true to switch on success notices.
- `SCHEDULE`: **@every 72h**: Cron syntax for scheduling repository archive cleanup, e.g. `@every 1h`.
#### Cron - Delete all old actions from database ('cron.delete_old_actions')
#### Cron - Delete all old actions from database (`cron.delete_old_actions`)
- `ENABLED`: **false**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
@ -1040,7 +1049,7 @@ Default templates for project boards:
- `SCHEDULE`: **@every 168h**: Cron syntax to set how often to check.
- `OLDER_THAN`: **@every 8760h**: any action older than this expression will be deleted from database, suggest using `8760h` (1 year) because that's the max length of heatmap.
#### Cron - Check for new Gitea versions ('cron.update_checker')
#### Cron - Check for new Gitea versions (`cron.update_checker`)
- `ENABLED`: **true**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
@ -1048,7 +1057,7 @@ Default templates for project boards:
- `SCHEDULE`: **@every 168h**: Cron syntax for scheduling a work, e.g. `@every 168h`.
- `HTTP_ENDPOINT`: **https://dl.gitea.io/gitea/version.json**: the endpoint that Gitea will check for newer versions
#### Cron - Delete all old system notices from database ('cron.delete_old_system_notices')
#### Cron - Delete all old system notices from database (`cron.delete_old_system_notices`)
- `ENABLED`: **false**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
@ -1056,7 +1065,7 @@ Default templates for project boards:
- `SCHEDULE`: **@every 168h**: Cron syntax to set how often to check.
- `OLDER_THAN`: **@every 8760h**: any system notice older than this expression will be deleted from database.
#### Cron - Garbage collect LFS pointers in repositories ('cron.gc_lfs')
#### Cron - Garbage collect LFS pointers in repositories (`cron.gc_lfs`)
- `ENABLED`: **false**: Enable service.
- `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED).
@ -1087,6 +1096,11 @@ Default templates for project boards:
- `DISABLE_CORE_PROTECT_NTFS`: **false** Set to true to forcibly set `core.protectNTFS` to false.
- `DISABLE_PARTIAL_CLONE`: **false** Disable the usage of using partial clones for git.
## Git - Reflog settings (`git.reflog`)
- `ENABLED`: **true** Set to true to enable Git to write changes to reflogs in each repo.
- `EXPIRATION`: **90** Reflog entry lifetime, in days. Entries are removed opportunistically by Git.
## Git - Timeout settings (`git.timeout`)
- `DEFAULT`: **360**: Git operations default timeout seconds.
@ -1243,6 +1257,7 @@ Task queue configuration has been moved to `queue.task`. However, the below conf
- `LIMIT_SIZE_PUB`: **-1**: Maximum size of a Pub upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_PYPI`: **-1**: Maximum size of a PyPI upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_RUBYGEMS`: **-1**: Maximum size of a RubyGems upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_SWIFT`: **-1**: Maximum size of a Swift upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
- `LIMIT_SIZE_VAGRANT`: **-1**: Maximum size of a Vagrant upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`)
## Mirror (`mirror`)

View File

@ -2,14 +2,14 @@
date: "2016-12-26T16:00:00+02:00"
title: "配置说明"
slug: "config-cheat-sheet"
weight: 20
weight: 30
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "配置说明"
weight: 20
weight: 30
identifier: "config-cheat-sheet"
---
@ -262,7 +262,22 @@ test01.xls: application/vnd.ms-excel; charset=binary
- `ROOT_PATH`: 日志文件根目录。
- `MODE`: 日志记录模式,默认是为 `console`。如果要写到多个通道,用逗号分隔
- `LEVEL`: 日志级别,默认为`Trace`。
- `LEVEL`: 日志级别,默认为 `Trace`
- `DISABLE_ROUTER_LOG`: 关闭日志中的路由日志。
- `ENABLE_ACCESS_LOG`: 是否开启 Access Log, 默认为 false。
- `ACCESS_LOG_TEMPLATE`: `access.log` 输出内容的模板,默认模板:**`{{.Ctx.RemoteHost}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}" "{{.Ctx.Req.UserAgent}}"`**
模板支持以下参数:
- `Ctx`: 请求上下文。
- `Identity`: 登录用户名,默认: “`-`”。
- `Start`: 请求开始时间。
- `ResponseWriter`:
- `RequestID`: 从请求头中解析得到的与 `REQUEST_ID_HEADERS` 匹配的值,默认: “`-`”。
- 一定要谨慎配置该模板否则可能会引起panic.
- `REQUEST_ID_HEADERS`: 从 Request Header 中匹配指定 Key并将匹配到的值输出到 `access.log` 中(需要在 `ACCESS_LOG_TEMPLATE` 中指定输出位置)。如果在该参数中配置多个 Key 请用逗号分割,程序将按照配置的顺序进行匹配。
- 示例:
- 请求头: X-Request-ID: **test-id-123**
- 配置文件: REQUEST_ID_HEADERS = X-Request-ID
- 日志输出: 127.0.0.1:58384 - - [14/Feb/2023:16:33:51 +0800] "**test-id-123**" ...
## Cron (`cron`)

View File

@ -2,15 +2,15 @@
date: "2017-04-15T14:56:00+02:00"
title: "Customizing Gitea"
slug: "customizing-gitea"
weight: 9
weight: 100
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "Customizing Gitea"
identifier: "customizing-gitea"
weight: 9
weight: 100
---
# Customizing Gitea
@ -84,7 +84,7 @@ directory at the top of this document).
Every single page of Gitea can be changed. Dynamic content is generated using [go templates](https://golang.org/pkg/html/template/),
which can be modified by placing replacements below the `$GITEA_CUSTOM/templates` directory.
To obtain any embedded file (including templates), the [`gitea embedded` tool]({{< relref "doc/advanced/cmd-embedded.en-us.md" >}}) can be used. Alternatively, they can be found in the [`templates`](https://github.com/go-gitea/gitea/tree/main/templates) directory of Gitea source (Note: the example link is from the `main` branch. Make sure to use templates compatible with the release you are using).
To obtain any embedded file (including templates), the [`gitea embedded` tool]({{< relref "doc/administration/cmd-embedded.en-us.md" >}}) can be used. Alternatively, they can be found in the [`templates`](https://github.com/go-gitea/gitea/tree/main/templates) directory of Gitea source (Note: the example link is from the `main` branch. Make sure to use templates compatible with the release you are using).
Be aware that any statement contained inside `{{` and `}}` are Gitea's template syntax and
shouldn't be touched without fully understanding these components.
@ -282,9 +282,22 @@ To add custom .gitignore, add a file with existing [.gitignore rules](https://gi
### Labels
To add a custom label set, add a file that follows the [label format](https://github.com/go-gitea/gitea/blob/main/options/label/Default) to `$GITEA_CUSTOM/options/label`
Starting with Gitea 1.19, you can add a file that follows the [YAML label format](https://github.com/go-gitea/gitea/blob/main/options/label/Advanced.yaml) to `$GITEA_CUSTOM/options/label`:
```yaml
labels:
- name: "foo/bar" # name of the label that will appear in the dropdown
exclusive: true # whether to use the exclusive namespace for scoped labels. scoped delimiter is /
color: aabbcc # hex colour coding
description: Some label # long description of label intent
```
The [legacy file format](https://github.com/go-gitea/gitea/blob/main/options/label/Default) can still be used following the format below, however we strongly recommend using the newer YAML format instead.
`#hex-color label name ; label description`
For more information, see the [labels documentation]({{< relref "doc/usage/labels.en-us.md" >}}).
### Licenses
To add a custom license, add a file with the license text to `$GITEA_CUSTOM/options/license`
@ -341,7 +354,7 @@ To make a custom theme available to all users:
Community themes are listed in [gitea/awesome-gitea#themes](https://gitea.com/gitea/awesome-gitea#themes).
The `arc-green` theme source can be found [here](https://github.com/go-gitea/gitea/blob/main/web_src/less/themes/theme-arc-green.less).
The `arc-green` theme source can be found [here](https://github.com/go-gitea/gitea/blob/main/web_src/css/themes/theme-arc-green.css).
If your custom theme is considered a dark theme, set the global css variable `--is-dark-theme` to `true`.
This allows Gitea to adjust the Monaco code editor's theme accordingly.

View File

@ -2,14 +2,14 @@
date: "2017-04-15T14:56:00+02:00"
title: "自定义 Gitea 配置"
slug: "customizing-gitea"
weight: 9
weight: 100
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "自定义 Gitea 配置"
weight: 9
weight: 100
identifier: "customizing-gitea"
---

View File

@ -1,13 +1,13 @@
---
date: "2019-10-15T10:10:00+05:00"
title: "Usage: Email setup"
title: "Email setup"
slug: "email-setup"
weight: 12
toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "Email setup"
weight: 12
identifier: "email-setup"
@ -58,7 +58,7 @@ Restart Gitea for the configuration changes to take effect.
To send a test email to validate the settings, go to Gitea > Site Administration > Configuration > SMTP Mailer Configuration.
For the full list of options check the [Config Cheat Sheet]({{< relref "doc/advanced/config-cheat-sheet.en-us.md" >}})
For the full list of options check the [Config Cheat Sheet]({{< relref "doc/administration/config-cheat-sheet.en-us.md" >}})
Please note: authentication is only supported when the SMTP server communication is encrypted with TLS or `HOST=localhost`. TLS encryption can be through:
@ -81,7 +81,7 @@ SMTP_ADDR = smtp.gmail.com
SMTP_PORT = 465
FROM = example.user@gmail.com
USER = example.user
PASSWD = ***
PASSWD = `***`
MAILER_TYPE = smtp
IS_TLS_ENABLED = true
```

View File

@ -2,14 +2,14 @@
date: "2017-04-08T11:34:00+02:00"
title: "Environment variables"
slug: "environment-variables"
weight: 20
weight: 10
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "Environment variables"
weight: 20
weight: 10
identifier: "environment-variables"
---

View File

@ -2,14 +2,14 @@
date: "2017-04-08T11:34:00+02:00"
title: "环境变量清单"
slug: "environment-variables"
weight: 20
weight: 10
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "环境变量清单"
weight: 20
weight: 10
identifier: "environment-variables"
---

View File

@ -2,14 +2,14 @@
date: "2018-11-23:00:00+02:00"
title: "External renderers"
slug: "external-renderers"
weight: 40
weight: 60
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "External renderers"
weight: 40
weight: 60
identifier: "external-renderers"
---

View File

@ -1,13 +1,13 @@
---
date: "2018-05-11T11:00:00+02:00"
title: "Usage: Setup fail2ban"
title: "Fail2ban Setup "
slug: "fail2ban-setup"
weight: 16
toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "Fail2ban setup"
weight: 16
identifier: "fail2ban-setup"

View File

@ -1,13 +1,13 @@
---
date: "2022-08-01T00:00:00+00:00"
title: "使用: 设置 Fail2ban"
title: "设置 Fail2ban"
slug: "fail2ban-setup"
weight: 16
toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "设置 Fail2ban"
weight: 16
identifier: "fail2ban-setup"

View File

@ -1,13 +1,13 @@
---
date: "2019-10-06T08:00:00+05:00"
title: "Usage: Git LFS setup"
title: "Git LFS setup"
slug: "git-lfs-setup"
weight: 12
toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "Git LFS setup"
weight: 12
identifier: "git-lfs-setup"

View File

@ -1,13 +1,13 @@
---
date: "2018-06-02T11:00:00+02:00"
title: "Usage: HTTPS setup"
title: "HTTPS setup"
slug: "https-setup"
weight: 12
toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "HTTPS setup"
weight: 12
identifier: "https-setup"
@ -24,7 +24,7 @@ menu:
Before you enable HTTPS, make sure that you have valid SSL/TLS certificates.
You could use self-generated certificates for evaluation and testing. Please run `gitea cert --host [HOST]` to generate a self signed certificate.
If you are using Apache or nginx on the server, it's recommended to check the [reverse proxy guide]({{< relref "doc/usage/reverse-proxies.en-us.md" >}}).
If you are using Apache or nginx on the server, it's recommended to check the [reverse proxy guide]({{< relref "doc/administration/reverse-proxies.en-us.md" >}}).
To use Gitea's built-in HTTPS support, you must change your `app.ini` file:

View File

@ -0,0 +1,101 @@
---
date: "2023-04-09T11:00:00+02:00"
title: "使用: HTTPS配置"
slug: "https-setup"
weight: 12
toc: false
draft: false
menu:
sidebar:
parent: "administration"
name: "HTTPS setup"
weight: 12
identifier: "https-setup"
---
# HTTPS setup to encrypt connections to Gitea
**Table of Contents**
{{< toc >}}
## 使用内置服务器
在启用HTTPS之前确保您拥有有效的SSL/TLS证书。
建议在测试和评估情况下使用自签名证书,请运行 `gitea cert --host [HOST]` 以生成自签名证书
如果您在服务器上使用阿帕奇Apache或Nginx建议参考 [反向代理指南]({{< relref "doc/administration/reverse-proxies.zh-cn.md" >}})。
要使用Gitea内置HTTPS支持您必须编辑`app.ini`文件。
```ini
[server]
PROTOCOL = https
ROOT_URL = https://git.example.com:3000/
HTTP_PORT = 3000
CERT_FILE = cert.pem
KEY_FILE = key.pem
```
请注意,如果您的证书由第三方证书颁发机构签名(即不是自签名的),则 cert.pem 应包含证书链。服务器证书必须是 cert.pem 中的第一个条目,后跟中介(如果有)。不必包含根证书,因为连接客户端必须已经拥有根证书才能建立信任关系。要了解有关配置值的更多信息,请查看 [配置备忘单](../config-cheat-sheet#server-server)。
对于“CERT_FILE”或“KEY_FILE”字段当文件路径是相对路径时文件路径相对于“GITEA_CUSTOM”环境变量。它也可以是绝对路径。
### 设置HTTP重定向
Gitea服务器仅支持监听一个端口要重定向HTTP请求致HTTPS端口您需要启用HTTP重定向服务
```ini
[server]
REDIRECT_OTHER_PORT = true
; Port the redirection service should listen on
PORT_TO_REDIRECT = 3080
```
如果您使用Docker确保端口已配置在 `docker-compose.yml` 文件
## 使用 ACME (默认: Let's Encrypt)
[ACME](https://tools.ietf.org/html/rfc8555) 是一种证书颁发机构标准协议,允许您自动请求和续订 SSL/TLS 证书。[Let`s Encrypt](https://letsencrypt.org/) 是使用此标准的免费公开信任的证书颁发机构服务器。仅实施“HTTP-01”和“TLS-ALPN-01”挑战。为了使 ACME 质询通过并验证您的域所有权“80”端口“HTTP-01”或“443”端口“TLS-ALPN-01”上 gitea 域的外部流量必须由 gitea 实例提供服务。可能需要设置 [HTTP 重定向](#设置http重定向) 和端口转发才能正确路由外部流量。否则到端口“80”的正常流量将自动重定向到 HTTPS。**您必须同意**ACME提供商的服务条款默认为Let's Encrypt的 [服务条款](https://letsencrypt.org/documents/LE-SA-v1.2-2017年11月15日.pdf)。
使用默认 Let's Encrypt 的最小配置如下:
```ini
[server]
PROTOCOL=https
DOMAIN=git.example.com
ENABLE_ACME=true
ACME_ACCEPTTOS=true
ACME_DIRECTORY=https
;; Email can be omitted here and provided manually at first run, after which it is cached
ACME_EMAIL=email@example.com
```
小型配置请使用 [smallstep CA](https://github.com/smallstep/certificates), 点击 [教程](https://smallstep.com/docs/tutorials/acme-challenge) 了解更多信息。
```ini
[server]
PROTOCOL=https
DOMAIN=git.example.com
ENABLE_ACME=true
ACME_ACCEPTTOS=true
ACME_URL=https://ca.example.com/acme/acme/directory
;; Can be omitted if using the system's trust is preferred
;ACME_CA_ROOT=/path/to/root_ca.crt
ACME_DIRECTORY=https
ACME_EMAIL=email@example.com
```
要了解关于配置, 请访问 [配置备忘单](../config-cheat-sheet#server-server)获取更多信息
## 使用反向代理服务器
按照 [reverse proxy guide](../reverse-proxies) 的规则设置你的反向代理服务器
然后,按照下面的向导启用 HTTPS
- [nginx](https://nginx.org/en/docs/http/configuring_https_servers.html)
- [apache2/httpd](https://httpd.apache.org/docs/2.4/ssl/ssl_howto.html)
- [caddy](https://caddyserver.com/docs/tls)
注意:仅在代理层启用 HTTPS 被称为 [TLS 终止代理](https://en.wikipedia.org/wiki/TLS_termination_proxy)。代理服务器接受传入的 TLS 连接,解密内容,然后将现在未加密的内容传递给 Gitea。只要代理和 Gitea 实例在同一台计算机上或在私有网络中的不同计算机上(代理暴露给外部网络),这通常是可以接受的。如果您的 Gitea 实例与代理隔离在公共网络上,或者如果您想要全端到端的加密,您还可以直接在 Gitea 中 [启用内置服务器的 HTTPS 支持](#使用内置服务器),并将连接转发到 HTTPS 上。

View File

@ -1,15 +1,15 @@
---
date: "2019-04-02T17:06:00+01:00"
title: "Advanced: Logging Configuration"
title: "Logging Configuration"
slug: "logging-configuration"
weight: 55
weight: 40
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "Logging Configuration"
weight: 55
weight: 40
identifier: "logging-configuration"
---
@ -304,7 +304,7 @@ log using the value: `ACCESS = ,`
This value represent a go template. It's default value is:
`{{.Ctx.RemoteAddr}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}\" \"{{.Ctx.Req.UserAgent}}"`
`{{.Ctx.RemoteHost}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}" "{{.Ctx.Req.UserAgent}}"`
The template is passed following options:

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "Mail templates"
weight: 45
identifier: "mail-templates"
@ -39,7 +39,7 @@ Currently, the following notification events make use of templates:
| `approve` | The head comment of a approving review for a pull request. |
| `reject` | The head comment of a review requesting changes for a pull request. |
| `code` | A single comment on the code of a pull request. |
| `assigned` | Used was assigned to an issue or pull request. |
| `assigned` | User was assigned to an issue or pull request. |
| `default` | Any action not included in the above categories, or when the corresponding category template is not present. |
The path for the template of a particular message type is:

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "Repository indexer"
weight: 45
identifier: "repo-indexer"

View File

@ -1,13 +1,13 @@
---
date: "2018-05-22T11:00:00+00:00"
title: "Usage: Reverse Proxies"
title: "Reverse Proxies"
slug: "reverse-proxies"
weight: 17
weight: 16
toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "Reverse Proxies"
weight: 16
identifier: "reverse-proxies"
@ -48,7 +48,7 @@ server {
server_name git.example.com;
# Note: Trailing slash
location /git/ {
location /git/ {
# Note: Trailing slash
proxy_pass http://localhost:3000/;
proxy_set_header Host $host;

View File

@ -2,12 +2,12 @@
date: "2018-05-22T11:00:00+00:00"
title: "使用:反向代理"
slug: "reverse-proxies"
weight: 17
weight: 16
toc: false
draft: false
menu:
sidebar:
parent: "usage"
parent: "administration"
name: "反向代理"
weight: 16
identifier: "reverse-proxies"
@ -48,7 +48,7 @@ server {
server_name git.example.com;
# 注意: /git/ 最后需要有一个路径符号
location /git/ {
location /git/ {
# 注意: 反向代理后端 URL 的最后需要有一个路径符号
proxy_pass http://localhost:3000/;
proxy_set_header Host $host;

View File

@ -1,13 +1,13 @@
---
date: "2019-12-31T13:55:00+05:00"
title: "Advanced: Search Engines Indexation"
title: "Search Engines Indexation"
slug: "search-engines-indexation"
weight: 30
weight: 60
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "Search Engines Indexation"
weight: 60
identifier: "search-engines-indexation"
@ -21,7 +21,7 @@ If you don't want your repository to be visible for search engines read further.
## Block search engines indexation using robots.txt
To make Gitea serve a custom `robots.txt` (default: empty 404) for top level installations,
create a file called `robots.txt` in the [`custom` folder or `CustomPath`]({{< relref "doc/advanced/customizing-gitea.en-us.md" >}})
create a file called `robots.txt` in the [`custom` folder or `CustomPath`]({{< relref "doc/administration/customizing-gitea.en-us.md" >}})
Examples on how to configure the `robots.txt` can be found at [https://moz.com/learn/seo/robotstxt](https://moz.com/learn/seo/robotstxt).

View File

@ -2,14 +2,14 @@
date: "2019-08-17T10:20:00+01:00"
title: "GPG Commit Signatures"
slug: "signing"
weight: 20
weight: 50
toc: false
draft: false
menu:
sidebar:
parent: "advanced"
parent: "administration"
name: "GPG Commit Signatures"
weight: 20
weight: 50
identifier: "signing"
---

View File

@ -1,13 +0,0 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "進階"
slug: "advanced"
weight: 30
toc: false
draft: false
menu:
sidebar:
name: "進階"
weight: 40
identifier: "advanced"
---

View File

@ -1,13 +1,13 @@
---
date: "2021-01-22T00:00:00+02:00"
title: "Translation"
slug: "translation"
title: "Contributing"
slug: "contributing"
weight: 35
toc: false
draft: false
menu:
sidebar:
name: "Translation"
name: "Contributing"
weight: 50
identifier: "translation"
identifier: "contributing"
---

View File

@ -1,7 +1,7 @@
---
date: "2021-01-22T00:00:00+02:00"
title: "Übersetzung"
slug: "translation"
slug: "contributing"
weight: 35
toc: false
draft: false
@ -9,5 +9,5 @@ menu:
sidebar:
name: "Übersetzung"
weight: 50
identifier: "translation"
identifier: "contributing"
---

View File

@ -1,13 +1,13 @@
---
date: "2021-01-22T00:00:00+02:00"
title: "翻譯"
slug: "translation"
title: "貢獻"
slug: "contributing"
weight: 35
toc: false
draft: false
menu:
sidebar:
name: "翻譯"
name: "貢獻"
weight: 50
identifier: "translation"
identifier: "contributing"
---

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "developers"
parent: "contributing"
name: "Guidelines for Backend"
weight: 20
identifier: "guidelines-backend"

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "developers"
parent: "contributing"
name: "Guidelines for Frontend"
weight: 20
identifier: "guidelines-frontend"
@ -21,13 +21,13 @@ menu:
## Background
Gitea uses [Less CSS](https://lesscss.org), [Fomantic-UI](https://fomantic-ui.com/introduction/getting-started.html) (based on [jQuery](https://api.jquery.com)) and [Vue3](https://vuejs.org/) for its frontend.
Gitea uses [Fomantic-UI](https://fomantic-ui.com/introduction/getting-started.html) (based on [jQuery](https://api.jquery.com)) and [Vue3](https://vuejs.org/) for its frontend.
The HTML pages are rendered by [Go HTML Template](https://pkg.go.dev/html/template).
The source files can be found in the following directories:
* **Less styles:** `web_src/less/`
* **CSS styles:** `web_src/css/`
* **JavaScript files:** `web_src/js/`
* **Vue components:** `web_src/js/components/`
* **Go HTML templates:** `templates/`
@ -47,6 +47,8 @@ We recommend [Google HTML/CSS Style Guide](https://google.github.io/styleguide/h
7. Clarify variable types, prefer `elem.disabled = true` instead of `elem.setAttribute('disabled', 'anything')`, prefer `$el.prop('checked', var === 'yes')` instead of `$el.prop('checked', var)`.
8. Use semantic elements, prefer `<button class="ui button">` instead of `<div class="ui button">`.
9. Avoid unnecessary `!important` in CSS, add comments to explain why it's necessary if it can't be avoided.
10. Avoid mixing different events in one event listener, prefer to use individual event listeners for every event.
11. Custom event names are recommended to use `ce-` prefix.
### Accessibility / ARIA
@ -109,6 +111,22 @@ However, there are still some special cases, so the current guideline is:
* Vue components are recommended to use `v-if` and `v-show` to show/hide elements.
* Go template code should use Gitea's `.gt-hidden` and `showElem()/hideElem()/toggleElem()`, see more details in `.gt-hidden`'s comment.
### Styles and Attributes in Go HTML Template
It's recommended to use:
```html
<div class="gt-name1 gt-name2 {{if .IsFoo}}gt-foo{{end}}" {{if .IsFoo}}data-foo{{end}}></div>
```
instead of:
```html
<div class="gt-name1 gt-name2{{if .IsFoo}} gt-foo{{end}}"{{if .IsFoo}} data-foo{{end}}></div>
```
to make the code more readable.
### Legacy Code
A lot of legacy code already existed before this document's written. It's recommended to refactor legacy code to follow the guidelines.

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "developers"
parent: "contributing"
name: "Guidelines for Refactoring"
weight: 20
identifier: "guidelines-refactoring"

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "features"
parent: "contributing"
name: "Localization"
weight: 20
identifier: "localization"

View File

@ -0,0 +1,32 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "本地化"
slug: "localization"
weight: 20
toc: false
draft: false
menu:
sidebar:
parent: "contributing"
name: "本地化"
weight: 20
identifier: "localization"
---
# 本地化
Gitea的本地化是通过我们的[Crowdin项目](https://crowdin.com/project/gitea)进行的。
对于对**英语翻译**的更改可以发出pull-request来更改[英语语言环境](https://github.com/go-gitea/gitea/blob/master/options/locale/locale_en-US.ini)中合适的关键字。
有关对**非英语**翻译的更改,请参阅上面的 Crowdin 项目。
## 支持的语言
上述 Crowdin 项目中列出的任何语言一旦翻译了 25% 或更多都将得到支持。
翻译被接受后,它将在下一次 Crowdin 同步后反映在主存储库中,这通常是在任何 PR 合并之后。
在撰写本文时,这意味着更改后的翻译可能要到 Gitea 的下一个版本才会出现。
如果使用开发版本,则在同步更改内容后,它应该会在更新后立即显示。

View File

@ -2,12 +2,12 @@
date: "2016-12-01T16:00:00+02:00"
title: "在地化"
slug: "localization"
weight: 10
weight: 20
toc: false
draft: false
menu:
sidebar:
parent: "features"
parent: "contributing"
name: "在地化"
weight: 20
identifier: "localization"

View File

@ -1,12 +1,12 @@
---
date: "2021-01-22T00:00:00+02:00"
title: "Übersetzungs Richtlinien"
weight: 10
weight: 70
toc: true
draft: false
menu:
sidebar:
parent: "translation"
parent: "contributing"
name: "Übersetzungsrichtlinien"
weight: 70
identifier: "translation-guidelines"

View File

@ -1,12 +1,12 @@
---
date: "2021-01-22T00:00:00+02:00"
title: "Translation Guidelines"
weight: 10
weight: 70
toc: true
draft: false
menu:
sidebar:
parent: "translation"
parent: "contributing"
name: "Translation Guidelines"
weight: 70
identifier: "translation-guidelines"

View File

@ -1,13 +0,0 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "Developers"
slug: "developers"
weight: 40
toc: false
draft: false
menu:
sidebar:
name: "Developers"
weight: 55
identifier: "developers"
---

View File

@ -1,13 +0,0 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "开发者"
slug: "developers"
weight: 40
toc: false
draft: false
menu:
sidebar:
name: "开发者"
weight: 55
identifier: "developers"
---

View File

@ -1,13 +0,0 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "開發人員"
slug: "developers"
weight: 40
toc: false
draft: false
menu:
sidebar:
name: "開發人員"
weight: 55
identifier: "developers"
---

View File

@ -0,0 +1,13 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "Development"
slug: "development"
weight: 40
toc: false
draft: false
menu:
sidebar:
name: "Development"
weight: 40
identifier: "development"
---

View File

@ -1,13 +1,13 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "Advanced"
slug: "advanced"
weight: 30
title: "开发"
slug: "development"
weight: 40
toc: false
draft: false
menu:
sidebar:
name: "Advanced"
name: "开发"
weight: 40
identifier: "advanced"
identifier: "development"
---

View File

@ -1,13 +1,13 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "进阶"
slug: "advanced"
weight: 30
title: "開發"
slug: "development"
weight: 40
toc: false
draft: false
menu:
sidebar:
name: "进阶"
name: "開發"
weight: 40
identifier: "advanced"
identifier: "development"
---

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "developers"
parent: "development"
name: "API Usage"
weight: 40
identifier: "api-usage"

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "developers"
parent: "development"
name: "API 使用指南"
weight: 40
identifier: "api-usage"

View File

@ -7,7 +7,7 @@ toc: false
draft: false
menu:
sidebar:
parent: "developers"
parent: "development"
name: "Hacking on Gitea"
weight: 10
identifier: "hacking-on-gitea"
@ -177,7 +177,7 @@ server as mentioned above.
### Working on JS and CSS
Frontend development should follow [Guidelines for Frontend Development]({{< relref "doc/developers/guidelines-frontend.en-us.md" >}})
Frontend development should follow [Guidelines for Frontend Development]({{< relref "doc/contributing/guidelines-frontend.en-us.md" >}})
To build with frontend resources, either use the `watch-frontend` target mentioned above or just build once:
@ -264,8 +264,8 @@ OpenAPI 3 documentation.
When creating new configuration options, it is not enough to add them to the
`modules/setting` files. You should add information to `custom/conf/app.ini`
and to the
<a href='{{< relref "doc/advanced/config-cheat-sheet.en-us.md" >}}'>configuration cheat sheet</a>
found in `docs/content/doc/advanced/config-cheat-sheet.en-us.md`
<a href='{{< relref "doc/administration/config-cheat-sheet.en-us.md" >}}'>configuration cheat sheet</a>
found in `docs/content/doc/administer/config-cheat-sheet.en-us.md`
### Changing the logo

View File

@ -0,0 +1,349 @@
---
date: "2016-12-01T16:00:00+02:00"
title: "玩转 Gitea"
slug: "hacking-on-gitea"
weight: 10
toc: false
draft: false
menu:
sidebar:
parent: "development"
name: "玩转 Gitea"
weight: 10
identifier: "hacking-on-gitea"
---
# Hacking on Gitea
**目录**
{{< toc >}}
## 快速入门
要获得快速工作的开发环境,您可以使用 Gitpod。
[![在 Gitpod 中打开](/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/go-gitea/gitea)
## 安装 Golang
您需要 [安装 go]( https://golang.org/doc/install ) 并设置您的 go 环境。
接下来,[使用 npm 安装 Node.js](https://nodejs.org/en/download/) ,这是构建
JavaScript 和 CSS 文件的必要工具。最低支持的 Node.js 版本是 {{< min-node-version >}}
并且推荐使用最新的 LTS 版本。
**注意** :当执行需要外部工具的 make 任务时,比如
`make watch-backend`Gitea 会自动下载并构建这些必要的组件。为了能够使用这些,你必须
`"$GOPATH"/bin` 目录加入到可执行路径上。如果你不把go bin目录添加到可执行路径你必须手动
指定可执行程序路径。
**注意2** Go版本 {{< min-go-version >}} 或更高版本是必须的。Gitea 使用 `gofmt`
格式化源代码。然而,`gofmt` 的结果可能因 `go` 的版本而有差异。因此推荐安装我们持续集成使用
的 Go版本。截至上次更新Go 版本应该是 {{< go-version >}}。
## 安装 Make
Gitea 大量使用 `Make` 来自动化任务和改进开发。本指南涵盖了如何安装 Make。
### 在 Linux 上
使用包管理器安装。
在 Ubuntu/Debian 上:
```bash
sudo apt-get install make
```
在 Fedora/RHEL/CentOS 上:
```bash
sudo yum install make
```
### 在 Windows 上
Make 的这三个发行版都可以在 Windows 上运行:
- [单个二进制构建]( http://www.equation.com/servlet/equation.cmd?fa=make )。复制到某处并添加到 `PATH`
- [32 位版本](http://www.equation.com/ftpdir/make/32/make.exe)
- [64 位版本](http://www.equation.com/ftpdir/make/64/make.exe)
- [MinGW-w64](https://www.mingw-w64.org) / [MSYS2](https://www.msys2.org/)。
- MSYS2 是一个工具和库的集合,为您提供一个易于使用的环境来构建、安装和运行本机 Windows 软件,它包括 MinGW-w64。
- 在 MingGW-w64 中,二进制文件称为 `mingw32-make.exe` 而不是 `make.exe`。将 `bin` 文件夹添加到 `PATH`
- 在 MSYS2 中,您可以直接使用 `make`。请参阅 [MSYS2 移植](https://www.msys2.org/wiki/Porting/)。
- 要使用 CGO_ENABLED例如SQLite3编译 Gitea您可能需要使用 [tdm-gcc](https://jmeubank.github.io/tdm-gcc/) 而不是 MSYS2 gcc因为 MSYS2 gcc 标头缺少一些 Windows -只有 CRT 函数像 _beginthread 一样。
- [Chocolatey包管理器]( https://chocolatey.org/packages/make )。运行`choco install make`
**注意** :如果您尝试在 Windows 命令提示符下使用 make 进行构建您可能会遇到问题。建议使用上述提示Git bash 或 MinGW但是如果您只有命令提示符或可能是 PowerShell则可以使用 [set](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/set_1) 命令,例如 `set TAGS=bindata`
## 下载并克隆 Gitea 源代码
获取源代码的推荐方法是使用 `git clone`
```bash
git clone https://github.com/go-gitea/gitea
```
自从go modules出现后不再需要构建 go 项目从 `$GOPATH` 中获取,因此不再推荐使用 `go get` 方法。)
## 派生 Gitea
如上所述下载主要的 Gitea 源代码。然后,派生 [Gitea 仓库](https://github.com/go-gitea/gitea)
并为您的本地仓库切换 git 远程源,或添加另一个远程源:
```bash
# 将原来的 Gitea origin 重命名为 upstream
git remote rename origin upstream
git remote add origin "git@github.com:$GITHUB_USERNAME/gitea.git"
git fetch --all --prune
```
或者:
```bash
# 为我们的 fork 添加新的远程
git remote add "$FORK_NAME" "git@github.com:$GITHUB_USERNAME/gitea.git"
git fetch --all --prune
```
为了能够创建合并请求,应将分叉存储库添加为 Gitea 本地仓库的远程,否则无法推送更改。
## 构建 Gitea基本
看看我们的
<a href='{{ < relref "doc/installation/from-source.en-us.md" > }}'>说明</a>
关于如何 <a href='{{ < relref "doc/installation/from-source.en-us.md" > }}'>从源代码构建</a>
从源代码构建的最简单推荐方法是:
```bash
TAGS="bindata sqlite sqlite_unlock_notify" make build
```
`build` 目标将同时执行 `frontend``backend` 子目标。如果存在 `bindata` 标签,资源文件将被编译成二进制文件。建议在进行前端开发时省略 `bindata` 标签,以便实时反映更改。
有关所有可用的 `make` 目标,请参阅 `make help`。另请参阅 [`.drone.yml`](https://github.com/go-gitea/gitea/blob/main/.drone.yml) 以了解我们的持续集成是如何工作的。
## 持续构建
要在源文件更改时运行并持续构建:
```bash
# 对于前端和后端
make watch
# 或者只看前端文件html/js/css
make watch-frontend
# 或者:只看后端文件 (go)
make watch-backend
```
在 macOS 上,监视所有后端源文件可能会达到默认的打开文件限制,这可以通过当前 shell 的 `ulimit -n 12288` 或所有未来 shell 的 shell 启动文件来增加。
### 格式化、代码分析和拼写检查
我们的持续集成将拒绝未通过代码检查(包括格式检查、代码分析和拼写检查)的 PR。
你应该格式化你的代码:
```bash
make fmt
```
并检查源代码:
```bash
# lint 前端和后端代码
make lint
# 仅 lint 后端代码
make lint-backend
```
**注意** `gofmt` 的结果取决于 `go` 的版本。您应该运行与持续集成相同的 go 版本。
### 处理 JS 和 CSS
前端开发应遵循 [Guidelines for Frontend Development]({{ < 相关参考 "doc/development/guidelines-frontend.en-us.md" > }})
要使用前端资源构建请使用上面提到的“watch-frontend”目标或只构建一次
```bash
make build && ./gitea
```
在提交之前,确保 linters 通过:
```bash
make lint-frontend
```
### 配置本地 ElasticSearch 实例
使用 docker 启动本地 ElasticSearch 实例:
```sh
mkdir -p $(pwd) /data/elasticsearch
sudo chown -R 1000:1000 $(pwd) /data/elasticsearch
docker run --rm --memory= "4g" -p 127.0.0.1:9200:9200 -p 127.0.0.1:9300:9300 -e "discovery.type=single-node" -v "$(pwd)/data /elasticsearch:/usr/share/elasticsearch/data" docker.elastic.co/elasticsearch/elasticsearch:7.16.3
```
配置`app.ini`
```ini
[indexer]
ISSUE_INDEXER_TYPE = elasticsearch
ISSUE_INDEXER_CONN_STR = http://elastic:changeme@localhost:9200
REPO_INDEXER_ENABLED = true
REPO_INDEXER_TYPE = elasticsearch
REPO_INDEXER_CONN_STR = http://elastic:changeme@localhost:9200
```
### 构建和添加 SVGs
SVG 图标是使用 `make svg` 目标构建的,该目标将 `build/generate-svg.js` 中定义的图标源编译到输出目录 `public/img/svg` 中。可以在 `web_src/svg` 目录中添加自定义图标。
### 构建 Logo
Gitea Logo的 PNG 和 SVG 版本是使用 `TAGS="gitea" make generate-images` 目标从单个 SVG 源文件 assets/logo.svg 构建的。要运行它Node.js 和 npm 必须可用。
通过更新 `assets/logo.svg` 并运行 `make generate-images`,同样的过程也可用于从 SVG 源文件生成自定义 Logo PNG。忽略 gitea 编译选项将仅更新用户指定的 LOGO 文件。
### 更新 API
创建新的 API 路由或修改现有的 API 路由时,您**必须**
更新和/或创建 [Swagger](https://swagger.io/docs/specification/2-0/what-is-swagger/)
这些使用 [go-swagger](https://goswagger.io/) 评论的文档。
[规范]( https://goswagger.io/use/spec.html#annotation-syntax )中描述了这些注释的结构。
如果您想了解更多有关 Swagger 结构的信息,可以查看
[Swagger 2.0 文档](https://swagger.io/docs/specification/2-0/basic-structure/)
或与添加新 API 端点的先前 PR 进行比较,例如 [PR #5483](https://github.com/go-gitea/gitea/pull/5843/files#diff-2e0a7b644cf31e1c8ef7d76b444fe3aaR20)
您应该注意不要破坏下游用户依赖的 API。在稳定的 API 上,一般来说添加是可以接受的,但删除
或对 API 进行根本性更改将会被拒绝。
创建或更改 API 端点后,请用以下命令重新生成 Swagger 文档:
```bash
make generate-swagger
```
您应该验证生成的 Swagger 文件并使用以下命令对其进行拼写检查:
```bash
make swagger-validate misspell-check
```
您应该提交更改后的 swagger JSON 文件。持续集成服务器将使用以下方法检查是否已完成:
```bash
make swagger-check
```
**注意** :请注意,您应该使用 Swagger 2.0 文档,而不是 OpenAPI 3 文档。
### 创建新的配置选项
创建新的配置选项时,将它们添加到 `modules/setting` 的对应文件。您应该将信息添加到 `custom/conf/app.ini`
并到 <a href = '{{ < relref "doc/administration/config-cheat-sheet.en-us.md" > }}'>配置备忘单</a>
`docs/content/doc/advanced/config-cheat-sheet.en-us.md` 中找到
### 更改Logo
更改 Gitea Logo SVG 时,您将需要运行并提交结果的:
```bash
make generate-images
```
这将创建必要的 Gitea 图标和其他图标。
### 数据库迁移
如果您对数据库中的任何数据库持久结构进行重大更改
`models/` 目录,您将需要进行新的迁移。可以找到这些
`models/migrations/` 中。您可以确保您的迁移适用于主要
数据库类型使用:
```bash
make test-sqlite-migration # 将 SQLite 切换为适当的数据库
```
## 测试
Gitea 运行两种类型的测试:单元测试和集成测试。
### 单元测试
`go test` 系统中的`*_test.go` 涵盖了单元测试。
您可以设置环境变量 `GITEA_UNIT_TESTS_LOG_SQL=1` 以在详细模式下运行测试时显示所有 SQL 语句(即设置`GOTESTFLAGS=-v` 时)。
```bash
TAGS="bindata sqlite sqlite_unlock_notify" make test # Runs the unit tests
```
### 集成测试
单元测试不会也不能完全单独测试 Gitea。因此我们编写了集成测试但是这些依赖于数据库。
```bash
TAGS="bindata sqlite sqlite_unlock_notify" make build test-sqlite
```
将在 SQLite 环境中运行集成测试。集成测试需要安装 `git lfs`。其他数据库测试可用,但
可能需要适应当地环境。
看看 [`tests/integration/README.md`](https://github.com/go-gitea/gitea/blob/main/tests/integration/README.md) 有关更多信息以及如何运行单个测试。
### 测试 PR
我们的持续集成将测试代码是否通过了单元测试,并且所有支持的数据库都将在 Docker 环境中通过集成测试。
还将测试从几个最新版本的 Gitea 迁移。
请在PR中附带提交适当的单元测试和集成测试。
## 网站文档
该网站的文档位于 `docs/` 中。如果你改变了文档内容,你可以使用以下测试方法进行持续集成:
```bash
# 来自 Gitea 中的 docs 目录
make trans-copy clean build
```
运行此任务依赖于 [Hugo](https://gohugo.io/)。请注意:这可能会生成一些未跟踪的 Git 对象,
需要被清理干净。
## Visual Studio Code
`contrib/ide/vscode` 中为 Visual Studio Code 提供了 `launch.json``tasks.json`。查看
[`contrib/ide/README.md`](https://github.com/go-gitea/gitea/blob/main/contrib/ide/README.md) 了解更多信息。
## Goland
单击 `/main.go` 中函数 `func main()` 上的 `Run Application` 箭头
可以快速启动一个可调试的 Gitea 实例。
`Run/Debug Configuration` 中的 `Output Directory` 必须设置为
gitea 项目目录(包含 `main.go``go.mod`
否则,启动实例的工作目录是 GoLand 的临时目录
并防止 Gitea 在开发环境中加载动态资源(例如:模板)。
要在 GoLand 中使用 SQLite 运行单元测试,请设置 `-tags sqlite,sqlite_unlock_notify`
`运行/调试配置``Go 工具参数` 中。
## 提交 PR
对更改感到满意后,将它们推送并打开拉取请求。它建议您允许 Gitea Managers 和 Owners 修改您的 PR
分支,因为我们需要在合并之前将其更新为 main 和/或可能是能够直接帮助解决问题。
任何 PR 都需要 Gitea 维护者的两次批准,并且需要通过持续集成。看看我们的
[CONTRIBUTING.md](https://github.com/go-gitea/gitea/blob/main/CONTRIBUTING.md)
文档。
如果您需要更多帮助,请访问 [Discord](https://discord.gg/gitea) #Develop 频道
并在那里聊天。
现在,您已准备好 Hacking Gitea。

View File

@ -2,12 +2,12 @@
date: "2019-04-15T17:29:00+08:00"
title: "Integrations"
slug: "integrations"
weight: 40
weight: 65
toc: false
draft: false
menu:
sidebar:
parent: "developers"
parent: "development"
name: "Integrations"
weight: 65
identifier: "integrations"

View File

@ -2,12 +2,12 @@
date: "2019-04-15T17:29:00+08:00"
title: "整合"
slug: "integrations"
weight: 40
weight: 65
toc: false
draft: false
menu:
sidebar:
parent: "developers"
parent: "development"
name: "整合"
weight: 65
identifier: "integrations"

Some files were not shown because too many files have changed in this diff Show More