Merge branch 'main' into sync-issue-pr-and-more

This commit is contained in:
harryzcy 2023-07-21 01:54:57 -05:00
commit b09412524e
No known key found for this signature in database
GPG Key ID: E3C2287691E40E35
1214 changed files with 15072 additions and 8072 deletions

View File

@ -23,7 +23,8 @@
"Vue.volar",
"ms-azuretools.vscode-docker",
"zixuanchen.vitest-explorer",
"qwtel.sqlite-viewer"
"qwtel.sqlite-viewer",
"GitHub.vscode-pull-request-github"
]
}
},

View File

@ -75,10 +75,10 @@ cpu.out
/yarn.lock
/yarn-error.log
/npm-debug.log*
/public/js
/public/css
/public/fonts
/public/img/webpack
/public/assets/js
/public/assets/css
/public/assets/fonts
/public/assets/img/webpack
/vendor
/web_src/fomantic/node_modules
/web_src/fomantic/build/*

View File

@ -22,13 +22,14 @@ plugins:
- eslint-plugin-wc
env:
es2022: true
es2024: true
node: true
globals:
__webpack_public_path__: true
overrides:
- files: ["web_src/**/*"]
globals:
__webpack_public_path__: true
process: false # https://github.com/webpack/webpack/issues/15833
- files: ["web_src/**/*", "docs/**/*"]
env:
browser: true
@ -155,7 +156,7 @@ rules:
import/no-restricted-paths: [0]
import/no-self-import: [2]
import/no-unassigned-import: [0]
import/no-unresolved: [2, {commonjs: true, ignore: ["\\?.+$"]}]
import/no-unresolved: [2, {commonjs: true, ignore: [\?.+$, ^vitest/]}]
import/no-unused-modules: [2, {unusedExports: true}]
import/no-useless-path-segments: [2, {commonjs: true}]
import/no-webpack-loader-syntax: [2]
@ -419,7 +420,7 @@ rules:
no-restricted-exports: [0]
no-restricted-globals: [2, addEventListener, blur, close, closed, confirm, defaultStatus, defaultstatus, error, event, external, find, focus, frameElement, frames, history, innerHeight, innerWidth, isFinite, isNaN, length, location, locationbar, menubar, moveBy, moveTo, name, onblur, onerror, onfocus, onload, onresize, onunload, open, opener, opera, outerHeight, outerWidth, pageXOffset, pageYOffset, parent, print, removeEventListener, resizeBy, resizeTo, screen, screenLeft, screenTop, screenX, screenY, scroll, scrollbars, scrollBy, scrollTo, scrollX, scrollY, self, status, statusbar, stop, toolbar, top, __dirname, __filename]
no-restricted-imports: [0]
no-restricted-syntax: [2, WithStatement, ForInStatement, LabeledStatement]
no-restricted-syntax: [2, WithStatement, ForInStatement, LabeledStatement, SequenceExpression]
no-return-assign: [0]
no-return-await: [0]
no-script-url: [2]
@ -665,7 +666,6 @@ rules:
unicorn/no-unnecessary-await: [2]
unicorn/no-unreadable-array-destructuring: [0]
unicorn/no-unreadable-iife: [2]
unicorn/no-unsafe-regex: [0]
unicorn/no-unused-properties: [2]
unicorn/no-useless-fallback-in-spread: [2]
unicorn/no-useless-length-check: [2]
@ -692,7 +692,7 @@ rules:
unicorn/prefer-dom-node-remove: [2]
unicorn/prefer-dom-node-text-content: [2]
unicorn/prefer-event-target: [2]
unicorn/prefer-export-from: [2, {ignoreUsedVariables: true}]
unicorn/prefer-export-from: [0]
unicorn/prefer-includes: [2]
unicorn/prefer-json-parse-buffer: [0]
unicorn/prefer-keyboard-event-key: [2]

2
.gitattributes vendored
View File

@ -1,7 +1,7 @@
* text=auto eol=lf
*.tmpl linguist-language=Handlebars
/assets/*.json linguist-generated
/public/img/svg/*.svg linguist-generated
/public/assets/img/svg/*.svg linguist-generated
/templates/swagger/v1_json.tmpl linguist-generated
/vendor/** -text -eol linguist-vendored
/web_src/fomantic/build/** linguist-generated

View File

@ -1,6 +1,6 @@
name: Feature Request
description: Got an idea for a feature that Gitea doesn't have currently? Submit your idea here!
labels: ["kind/feature", "kind/proposal"]
labels: ["kind/proposal"]
body:
- type: markdown
attributes:

View File

@ -15,6 +15,8 @@ on:
value: ${{ jobs.detect.outputs.templates }}
docker:
value: ${{ jobs.detect.outputs.docker }}
swagger:
value: ${{ jobs.detect.outputs.swagger }}
jobs:
detect:
@ -27,6 +29,7 @@ jobs:
actions: ${{ steps.changes.outputs.actions }}
templates: ${{ steps.changes.outputs.templates }}
docker: ${{ steps.changes.outputs.docker }}
swagger: ${{ steps.changes.outputs.swagger }}
steps:
- uses: actions/checkout@v3
- uses: dorny/paths-filter@v2
@ -36,6 +39,7 @@ jobs:
backend:
- "**/*.go"
- "templates/**/*.tmpl"
- "assets/emoji.json"
- "go.mod"
- "go.sum"
- "Makefile"
@ -43,6 +47,7 @@ jobs:
frontend:
- "**/*.js"
- "web_src/**"
- "assets/emoji.json"
- "package.json"
- "package-lock.json"
- "Makefile"
@ -63,3 +68,6 @@ jobs:
- "Dockerfile.rootless"
- "docker/**"
- "Makefile"
swagger:
- "templates/swagger/v1_json.tmpl"

View File

@ -39,6 +39,18 @@ jobs:
- run: make deps-py
- run: make lint-templates
lint-swagger:
if: needs.files-changed.outputs.swagger == 'true'
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 20
- run: make deps-frontend
- run: make lint-swagger
lint-go-windows:
if: needs.files-changed.outputs.backend == 'true' || needs.files-changed.outputs.actions == 'true'
needs: files-changed

8
.gitignore vendored
View File

@ -72,10 +72,10 @@ cpu.out
/yarn.lock
/yarn-error.log
/npm-debug.log*
/public/js
/public/css
/public/fonts
/public/img/webpack
/public/assets/js
/public/assets/css
/public/assets/fonts
/public/assets/img/webpack
/vendor
/web_src/fomantic/node_modules
/web_src/fomantic/build/*

View File

@ -35,6 +35,7 @@ vscode:
- ms-azuretools.vscode-docker
- zixuanchen.vitest-explorer
- qwtel.sqlite-viewer
- GitHub.vscode-pull-request-github
ports:
- name: Gitea

View File

@ -77,16 +77,21 @@ linters-settings:
extra-rules: true
lang-version: "1.20"
depguard:
list-type: denylist
# Check the list against standard lib.
include-go-root: true
packages-with-error-message:
- encoding/json: "use gitea's modules/json instead of encoding/json"
- github.com/unknwon/com: "use gitea's util and replacements"
- io/ioutil: "use os or io instead"
- golang.org/x/exp: "it's experimental and unreliable."
- code.gitea.io/gitea/modules/git/internal: "do not use the internal package, use AddXxx function instead"
- gopkg.in/ini.v1: "do not use the ini package, use gitea's config system instead"
rules:
main:
deny:
- pkg: encoding/json
desc: use gitea's modules/json instead of encoding/json
- pkg: github.com/unknwon/com
desc: use gitea's util and replacements
- pkg: io/ioutil
desc: use os or io instead
- pkg: golang.org/x/exp
desc: it's experimental and unreliable
- pkg: code.gitea.io/gitea/modules/git/internal
desc: do not use the internal package, use AddXxx function instead
- pkg: gopkg.in/ini.v1
desc: do not use the ini package, use gitea's config system instead
issues:
max-issues-per-linter: 0

View File

@ -50,7 +50,7 @@ rules:
declaration-no-important: null
declaration-property-max-values: null
declaration-property-unit-allowed-list: null
declaration-property-unit-disallowed-list: null
declaration-property-unit-disallowed-list: {line-height: [em]}
declaration-property-value-allowed-list: null
declaration-property-value-disallowed-list: null
declaration-property-value-no-unknown: true
@ -84,6 +84,7 @@ rules:
media-feature-name-value-allowed-list: null
media-feature-name-value-no-unknown: true
media-feature-range-notation: null
media-query-no-invalid: true
named-grid-areas-no-invalid: true
no-descending-specificity: null
no-duplicate-at-import-rules: true

View File

@ -4,6 +4,669 @@ 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.20.0](https://github.com/go-gitea/gitea/releases/tag/v1.20.0) - 2023-07-16
* BREAKING
* Fix WORK_DIR for docker (root) image (#25738) (#25811)
* Restrict `[actions].DEFAULT_ACTIONS_URL` to only `github` or `self` (#25581) (#25604)
* Refactor path & config system (#25330) (#25416)
* Fix all possible setting error related storages and added some tests (#23911) (#25244)
* Use a separate admin page to show global stats, remove `actions` stat (#25062)
* Remove the service worker (#25010)
* Remove meta tags `theme-color` and `default-theme` (#24960)
* Use `[git.config]` for reflog cleaning up (#24958)
* Allow all URL schemes in Markdown links by default (#24805)
* Redesign Scoped Access Tokens (#24767)
* Fix team members API endpoint pagination (#24754)
* Rewrite logger system (#24726)
* Increase default LFS auth timeout from 20m to 24h (#24628)
* Rewrite queue (#24505)
* Remove unused setting `time.FORMAT` (#24430)
* Refactor `setting.Other` and remove unused `SHOW_FOOTER_BRANDING` (#24270)
* Correct the access log format (#24085)
* Reserve ".png" suffix for user/org names (#23992)
* Prefer native parser for SSH public key parsing (#23798)
* Editor preview support for external renderers (#23333)
* Add Gitea Profile Readmes (#23260)
* Refactor `ctx` in templates (#23105)
* SECURITY
* Test if container blob is accessible before mounting (#22759) (#25784)
* Set type="password" on all auth_token fields (#22175)
* FEATURES
* Add button on diff header to copy file name, misc diff header tweaks (#24986)
* API endpoint for changing/creating/deleting multiple files (#24887)
* Support changing git config through `app.ini`, use `diff.algorithm=histogram` by default (#24860)
* Add up and down arrows to selected lookup repositories (#24727)
* Add Go package registry (#24687)
* Add status indicator on main home screen for each repo (#24638)
* Support for status check pattern (#24633)
* Implement Cargo HTTP index (#24452)
* Add Debian package registry (#24426)
* Add the ability to pin Issues (#24406)
* Add follow organization and fix the logic of following page (#24345)
* Allow `webp` images as avatars (#24248)
* Support upload `outputs` and use `needs` context on Actions (#24230)
* Allow adding new files to an empty repo (#24164)
* Make wiki title supports dashes and improve wiki name related features (#24143)
* Add monospace toggle button to textarea (#24034)
* Use auto-updating, natively hoverable, localized time elements (#23988)
* Add ntlm authentication support for mail (#23811)
* Add CLI command to register runner tokens (#23762)
* Add Alpine package registry (#23714)
* Expand/Collapse all changed files (#23639)
* Add unset default project column (#23531)
* Add activity feeds API (#23494)
* Add RPM registry (#23380)
* Add meilisearch support (#23136)
* Add API for License templates (#23009)
* Add admin API email endpoints (#22792)
* Add user rename endpoint to admin api (#22789)
* Add API for gitignore templates (#22783)
* Implement actions artifacts (#22738)
* Add RSS Feeds for branches and files (#22719)
* Display when a repo was archived (#22664)
* Add Swift package registry (#22404)
* Add CRAN package registry (#22331)
* Add user webhooks (#21563)
* Implement systemd-notify protocol (#21151)
* Implement Issue Config (#20956)
* Add API to manage issue dependencies (#17935)
* API
* Use correct response code in push mirror creation response in v1_json.tmpl (#25476) (#25571)
* Fix `Permission` in API returned repository struct (#25388) (#25441)
* Add API for Label templates (#24602)
* Filters for GetAllCommits (#24568)
* Add ability to specify '--not' from GetAllCommits (#24409)
* Support uploading file to empty repo by API (#24357)
* Add absent repounits to create/edit repo API (#23500)
* Add login name and source id for admin user searching API (#23376)
* Create a branch directly from commit on the create branch API (#22956)
* ENHANCEMENTS
* Make `add line comment` buttons focusable (#25894) (#25896)
* Always pass 6-digit hex color to monaco (#25780) (#25782)
* Clarify "text-align" CSS helpers, fix clone button padding (#25763) (#25764)
* Hide `add file` button for pull mirrors (#25748) (#25751)
* Allow/fix review (approve/reject) of empty PRs (#25690) (#25732)
* Fix tags header and pretty format numbers (#25624) (#25694)
* Actions list enhancements (#25601) (#25678)
* Fix show more for image on diff page (#25672) (#25673)
* Prevent SVG shrinking (#25652) (#25669)
* Fix UI misalignment on user setting page (#25629) (#25656)
* Use css on labels (#25626) (#25636)
* Read-only checkboxes don't appear and don't entirely act the way one might expect (#25573) (#25602)
* Redirect to package after version deletion (#25594) (#25599)
* Reduce table padding globally (#25568) (#25577)
* Change `Regenerate Secret` button display (#25534) (#25541)
* Fix rerun icon on action view component (#25531) (#25536)
* Move some regexp out of functions (#25430) (#25445)
* Diff page enhancements (#25398) (#25437)
* Various UI fixes (#25264) (#25431)
* Fix label list divider (#25312) (#25372)
* Fix UI on mobile view (#25315) (#25340)
* When viewing a file, hide the add button (#25320) (#25339)
* Show if File is Executable (#25287) (#25300)
* Fix edit OAuth application width (#25262) (#25263)
* Use flex to align SVG and text (#25163) (#25260)
* Revert overflow: overlay (revert #21850) (#25231) (#25239)
* Use inline SVG for built-in OAuth providers (#25171) (#25234)
* Change access token UI to select dropdowns (#25109) (#25230)
* Remove hacky patch for "safari emoji glitch fix" (#25208) (#25211)
* Minor arc-green color tweaks (#25175) (#25205)
* Button and color enhancements (#24989) (#25176)
* Fix mobile navbar and misc cleanups (#25134) (#25169)
* Modify OAuth login ui and fix display name, iconurl related logic (#25030) (#25161)
* Improve notification icon and navbar (#25111) (#25124)
* Add details summary for vertical menus in settings to allow toggling (#25098)
* Don't display `select all issues` checkbox when no issues are available (#25086)
* Use RepositoryList instead of []*Repository (#25074)
* Add ability to set multiple redirect URIs in OAuth application UI (#25072)
* Use git command instead of the ini package to remove the `origin` remote (#25066)
* Remove cancel button from branch protection form (#25063)
* Show file tree by default (#25052)
* Add Progressbar to Milestone Page (#25050)
* Minor UI improvements: logo alignment, auth map editor, auth name display (#25043)
* Allow for PKCE flow without client secret + add docs (#25033)
* Refactor INI package (first step) (#25024)
* Various style fixes (#25008)
* Fix delete user account modal (#25004)
* Refactor diffFileInfo / DiffTreeStore (#24998)
* Add user level action runners (#24995)
* Rename NotifyPullReviewRequest to NotifyPullRequestReviewRequest (#24988)
* Add step start time to `ViewStepLog` (#24980)
* Add dark mode to API Docs (#24971)
* Display file mode for new file and file mode changes (#24966)
* Make the 500 page load themes (#24953)
* Show `bot` label next to username when rendering autor link if the user is a bot (#24943)
* Repo list improvements, fix bold helper classes (#24935)
* Improve queue and logger context (#24924)
* Improve RunMode / dev mode (#24886)
* Improve some Forms (#24878)
* Add show timestamp/seconds and fullscreen options to action page (#24876)
* Fix double border and adjust width for user profile page (#24870)
* Improve Actions CSS (#24864)
* Fix `@font-face` overrides (#24855)
* Remove `In your repositories` link in milestones dashboard (#24853)
* Fix missing yes/no in delete time log modal (#24851)
* Show new pull request button also on subdirectories and files (#24842)
* Make environment-to-ini support loading key value from file (#24832)
* Support wildcard in email domain allow/block list (#24831)
* Use `CommentList` instead of `[]*Comment` (#24828)
* Add RTL rendering support to Markdown (#24816)
* Rework notifications list (#24812)
* Mute repo names in dashboard repo list (#24811)
* Fix max width and margin of comment box on conversation page (#24809)
* Some refactors for issues stats (#24793)
* Rework label colors (#24790)
* Fix OAuth login loading state (#24788)
* Remove duplicated issues options and some more refactors (#24787)
* Decouple the different contexts from each other (#24786)
* Remove background on user dashboard filter bar (#24779)
* Improve and fix bugs surrounding reactions (#24760)
* Make the color of zero-contribution-squares in the activity heatmap more subtle (#24758)
* Fix WEBP image copying (#24743)
* Rework OAuth login buttons, swap github logo to monocolor (#24740)
* Consolidate the two review boxes into one (#24738)
* Unification of registration fields order (#24737)
* Refactor Pull Mirror and fix out-of-sync bugs (#24732)
* Improvements for action detail page (#24718)
* Fix flash of unstyled content in action view page (#24712)
* Don't filter action runs based on state (#24711)
* Optimize actions list by removing an unnecessary `git` call (#24710)
* Support no label/assignee filter and batch clearing labels/assignees (#24707)
* Add icon support for safari (#24697)
* Use standard HTTP library to serve files (#24693)
* Improve button-ghost, remove tertiary button (#24692)
* Only hide tooltip tippy instances (#24688)
* Support migrating storage for actions log via command line (#24679)
* Remove highlight in repo list (#24675)
* Add markdown preview to Submit Review Textarea (#24672)
* Update pin and add pin-slash (#24669)
* Improve empty notifications display (#24668)
* Support SSH for go get (#24664)
* Improve avatar uploading / resizing / compressing, remove Fomantic card module (#24653)
* Only show one tippy at a time (#24648)
* Notification list enhancements, fix striped tables on dark theme (#24639)
* Improve queue & process & stacktrace (#24636)
* Use the type RefName for all the needed places and fix pull mirror sync bugs (#24634)
* Remove fluid on compare diff page (#24627)
* Add a tooltip to the job rerun button (#24617)
* Attach a tooltip to the action status icon (#24614)
* Make the actions control button look like an actual button (#24611)
* Remove unnecessary code (#24610)
* Make repo migration cancelable and fix various bugs (#24605)
* Improve updating Actions tasks (#24600)
* Attach a tooltip to the action control button (#24595)
* Make repository response support HTTP range request (#24592)
* Improve Gitea's web context, decouple "issue template" code into service package (#24590)
* Modify luminance calculation and extract related functions into single files (#24586)
* Simplify template helper functions (#24570)
* Split "modules/context.go" to separate files (#24569)
* Add org visibility label to non-organization's dashboard (#24558)
* Update LDAP filters to include both username and email address (#24547)
* Review fixes and enhancements (#24526)
* Display warning when user try to rename default branch (#24512)
* Fix color for transfer related buttons when having no permission to act (#24510)
* Rework button coloring, add focus and active colors (#24507)
* New webhook trigger for receiving Pull Request review requests (#24481)
* Add goto issue id function (#24479)
* Fix incorrect webhook time and use relative-time to display it (#24477)
* RSS icon fixes (#24476)
* Replace `N/A` with `-` everywhere (#24474)
* Pass 'not' to commit count (#24473)
* Enhance stylelint rule config, remove dead CSS (#24472)
* Remove `font-awesome` and fomantic `icon` module (#24471)
* Improve "new-menu" (#24465)
* Remove fomantic breadcrumb module (#24463)
* Improve template system and panic recovery (#24461)
* Make Issue/PR/projects more compact, misc CSS tweaks (#24459)
* Replace remaining fontawesome dropdown icons with SVG (#24455)
* Remove all direct references to font-awesome (#24448)
* Move links out of translation (#24446)
* Add `ui-monospace` and `SF Mono` to `--fonts-monospace` (#24442)
* Hide 'Mirror Settings' when unneeded, improve hints (#24433)
* Add "Updated" column for admin repositories list (#24429)
* Improve issue list filter (#24425)
* Rework header bar on issue, pull requests and milestone (#24420)
* Improve template helper (#24417)
* Make repo size style matches others (commits/branches/tags) (#24408)
* Support markdown editor for issue template (#24400)
* Improve commit date in commit graph (#24399)
* Start cleaning the messy ".ui.left / .ui.right", improve label list page, fix stackable menu (#24393)
* Merge setting.InitXXX into one function with options (#24389)
* Move `Rename branch` from repo settings page to the page of branches list (#24380)
* Improve protected branch setting page (#24379)
* Display 'Unknown' when runner.version is empty (#24378)
* Display owner of a runner as a tooltip instead of static text (#24377)
* Fix incorrect last online time in runner_edit.tmpl (#24376)
* Fix unclear `IsRepositoryExist` logic (#24374)
* Add custom helm repo name generated from url (#24363)
* Replace placeholders in licenses (#24354)
* Add rerun workflow button and refactor to use SVG octicons (#24350)
* Fix runner button height (#24338)
* Restore bold on repolist (#24337)
* Improve RSS (#24335)
* Refactor "route" related code, fix Safari cookie bug (#24330)
* Alert error message if open dependencies are included in the issues that try to batch close (#24329)
* Add missed column title in runner management page (#24328)
* Automatically select the org when click create repo from org dashboard (#24325)
* Modify width of ui container, fine tune css for settings pages and org header (#24315)
* Fix config list overflow and layout (#24312)
* Improve some modal action buttons (#24289)
* Move code from module to service (#24287)
* Sort users and orgs on explore by recency by default (#24279)
* Allow using localized absolute date times within phrases with place holders and localize issue due date events (#24275)
* Show workflow config error on file view also (#24267)
* Improve template helper functions: string/slice (#24266)
* Use more specific test methods (#24265)
* Add `DumpVar` helper function to help debugging templates (#24262)
* Limit avatar upload to valid image files (#24258)
* Improve emoji and mention matching (#24255)
* Change to vertical navbar layout for secondary navbar for repo/user/admin settings (#24246)
* Refactor config provider (#24245)
* Improve test logger (#24235)
* Default show closed actions list if all actions was closed (#24234)
* Add missing badges in user profile for /projects and /packages (#24232)
* Add repository counter badge to repository tab (#24205)
* Move secrets and runners settings to actions settings (#24200)
* Require at least one unit to be enabled (#24189)
* Use same action status svg icons on actions list as on action page (#24178)
* Use secondary pointing menu for tabs on user/organization home page (#24162)
* Improve Wiki TOC (#24137)
* Refactor locale number (#24134)
* Localize activity heatmap (except tooltip) (#24131)
* Fix duplicate modals when clicking on "remove all" repository button (#24129)
* Add runner check in repo action page (#24124)
* Support triggering workflows by wiki related events (#24119)
* Refactor cookie (#24107)
* Remove untranslatable `on_date` key (#24106)
* Refactor delete_modal_actions template and use it for project column related actions (#24097)
* Improve git log for debugging (#24095)
* Add option to search for users is active join a team (#24093)
* Add PDF rendering via PDFObject (#24086)
* Refactor web route (#24080)
* Make more functions use ctx instead of db.DefaultContext (#24068)
* Make HTML template functions support context (#24056)
* Refactor rename user and rename organization (#24052)
* Localize milestone related time strings (#24051)
* Expand selected file when clicking file tree (#24041)
* Add popup to hashed comments/pull requests/issues in file editing/adding preview tab (#24040)
* Add placeholder and aria attributes to release and wiki edit page (#24031)
* Add new user types `reserved`, `bot`, and `remote` (#24026)
* Allow adding SSH keys even if SSH server is disabled (#24025)
* Use a general approach to access custom/static/builtin assets (#24022)
* Update github.com/google/go-github to v52 (#24004)
* Replace tribute with text-expander-element for textarea (#23985)
* Group template helper functions, remove `Printf`, improve template error messages (#23982)
* Drop "unrolled/render" package (#23965)
* Add job.duration in web ui (#23963)
* Tweak pull request branch delete ui (#23951)
* Merge template functions "dict/Dict/mergeinto" (#23932)
* Use a general Eval function for expressions in templates. (#23927)
* Clean template/helper.go (#23922)
* Actions: Use default branch as ref when a branch/tag delete occurs (#23910)
* Add tooltips for MD editor buttons and add `muted` class for buttons (#23896)
* Improve markdown editor: width, height, preferred (#23895)
* Make Release Download URLs predictable (#23891)
* Remove fomantic ".link" selector and styles (#23888)
* Added close/open button to details page of milestone (#23877)
* Introduce GitHub markdown editor, keep EasyMDE as fallback (#23876)
* Introduce GiteaLocaleNumber custom element to handle number localization on pages. (#23861)
* Make first section on home page full width (#23854)
* Use different SVG for pending and running actions (#23836)
* Display image size for multiarch container images (#23821)
* Improve action log display with control chars (#23820)
* Fix dropdown direction behavior (#23806)
* Fix incorrect/Improve error handle in edit user page (#23805)
* Use clippie module to copy to clipboard (#23801)
* Make minio package support legacy MD5 checksum (#23768)
* Add ONLY_SHOW_RELEVANT_REPOS back, fix explore page bug, make code more strict (#23766)
* Refactor docs (#23752)
* Fix markup background, improve wiki rendering (#23750)
* Make label templates have consistent behavior and priority (#23749)
* Improve LoadUnitConfig to handle invalid or duplicate units (#23736)
* Append `(comment)` when a link points at a comment rather than the whole issue (#23734)
* Clean some legacy files and move some build files (#23699)
* Refactor repo commit list (#23690)
* Refactor internal API for git commands, use meaningful messages instead of "Internal Server Error" (#23687)
* Add aria attributes to interactive time tooltips. (#23661)
* Fix long project name display in issue list and in related dropdown (#23653)
* Use data-tooltip-content for tippy tooltip (#23649)
* Fix new issue/pull request btn margin when it is next to sort (#23647)
* Fine tune more downdrop settings, use SVG for labels, improve Repo Topic Edit form (#23626)
* Allow new file and edit file preview if it has editable extension (#23624)
* Replace a few fontawesome icons with svg (#23602)
* `Publish Review` buttons should indicate why they are disabled (#23598)
* Convert issue list checkboxes to native (#23596)
* Set opaque background on markup and images (#23578)
* Use a general approach to show tooltip, fix temporary tooltip bug (#23574)
* Improve `<SvgIcon>` to make it output `svg` node and optimize performance (#23570)
* Enable color for consistency checks diffs (#23563)
* Fix dropdown icon misalignment when using fomantic icon (#23558)
* Decouple the issue-template code from comment_tab.tmpl (#23556)
* Remove `id="comment-form"` dead code, fix tag (#23555)
* Diff improvements (#23553)
* Sort Python package descriptors by version to mimic PyPI format (#23550)
* Use a general approch to improve a11y for all checkboxes and dropdowns. (#23542)
* Fix long name ui issues and label ui issue (#23541)
* Return `repository` in npm package metadata endpoint (#23539)
* Use `project.IconName` instead of repeated unreadable `if-else` chains (#23538)
* Remove stars in dashboard repo list (#23530)
* Update mini-css-extract-plugin, remove postcss (#23520)
* Change `Close` to either `Close issue` or `Close pull request` (#23506)
* Fix theme-auto loading (#23504)
* Fix tags sort by creation time (descending) on branch/tag dropdowns (#23491)
* Display the version of runner in the runner list (#23490)
* Replace Less with CSS (#23481)
* Fix `.locale.Tr` function not found in delete modal (#23468)
* Allow both fullname and username search when `DEFAULT_SHOW_FULL_NAME` is true (#23463)
* Add project type descriptions in issue badge and improve project icons (#23437)
* Use context for `RepositoryList.LoadAttributes` (#23435)
* Refactor branch/tag selector to Vue SFC (#23421)
* Keep (add if not existing) xmlns attribute for generated SVG images (#23410)
* Refactor dashboard repo list to Vue SFC (#23405)
* Add workflow error notification in ui (#23404)
* Refactor branch/tag selector dropdown (first step) (#23394)
* Reduce duplicate and useless code in options (#23369)
* Convert `<div class="button">` to `<button class="button">` (#23337)
* Add path prefix to ObjectStorage.Iterator (#23332)
* Improve cache context (#23330)
* Move pidfile creation from setting to web cmd package (#23285)
* Fix tags view (#23243)
* Add commit info in action page (#23210)
* Support paste treepath when creating a new file or updating the file name (#23209)
* Allow skipping forks and mirrors from being indexed (#23187)
* Use context parameter in services/repository (#23186)
* Hide target selector if tag exists when creating new release (#23171)
* Improve FindProjects (#23085)
* Clean Path in Options (#23006)
* Add margin top to the top of branches (#23002)
* Remove unnecessary and incorrect `find('.menu').toggle()` (#22987)
* Improve GetBoards and getDefaultBoard (#22981)
* Improve squash merge commit author and co-author with private emails (#22977)
* Add --quiet option to gitea dump (#22969)
* Add pagination for dashboard and user activity feeds (#22937)
* Handle files starting with colons in WalkGitLog (#22935)
* Add "Reviewed by you" filter for pull requests (#22927)
* Parse external request id from request headers, and print it in access log (#22906)
* Replace `repo.namedBlob` by `git.TreeEntry`. (#22898)
* Pull Requests: add button to compare force pushed commits (#22857)
* Fix pull request update showing too many commits with multiple branches (#22856)
* Require approval to run actions for fork pull request (#22803)
* Projects: rename Board to Column in interface and improve consistency (#22767)
* Add user visibility in dashboard navbar (#22747)
* Add .livemd as a markdown extension (#22730)
* Clean up WebAuthn javascript code and remove JQuery code (#22697)
* Merge message template support for rebase without merge commit (#22669)
* Show editorconfig warnings when viewing a malformed editorconfig (#21257)
* Npm packages: set repository link based on the url in package.json (#20379)
* BUGFIXES
* Add support for different Maven POM encoding (#25873) (#25890)
* Fix incorrect repo url when changed the case of ownername (#25733) (#25881)
* Fix empty project displayed in issue sidebar (#25802) (#25854)
* Show correct SSL Mode on "install page" (#25818) (#25838)
* Fix the error message when the token is incorrect (#25701) (#25836)
* Fix incorrect oldest sort in project list (#25806) (#25835)
* For API attachments, use API URL (#25639) (#25814)
* Avoid amending the Rebase and Fast-forward merge if there is no message template (#25779) (#25809)
* Make "install page" respect environment config (#25648) (#25799)
* Fix activity type match in `matchPullRequestEvent` (#25746) (#25796)
* Fix notification list bugs (#25781) (#25787)
* Revert package access change from #23879 (#25707) (#25785)
* Check `ctx.Written()` for `GetActionIssue` (#25698) (#25711)
* Fix position of org follow button (#25688) (#25692)
* Fix the nil pointer when assigning issues to projects (#25665) (#25677)
* Log the real reason when authentication fails (but don't show the user) (#25414) (#25660)
* Fix bug when change user name (#25637) (#25646)
* Make "cancel" buttons have proper type in modal forms (#25618) (#25641)
* Use AfterCommitId to get commit for Viewed functionality (#25529) (#25612)
* Fix bug of branches API with tests(#25578) (#25579)
* Fix content holes in Actions task logs file (#25560) (#25566)
* Fix bugs related to notification endpoints (#25548) (#25562)
* Add Adopt repository event and handler (#25497) (#25518)
* Improve wiki sidebar and TOC (#25460) (#25477)
* Make "dismiss" content shown correctly (#25461) (#25465)
* Change default email domain for LDAP users (#25425) (#25434)
* Fix missing commit message body when the message has leading newlines (#25418) (#25422)
* Fix LDAP sync when Username Attribute is empty (#25278) (#25379)
* Fetch all git data for embedding correct version in docker image (#25361) (#25373)
* Fix incorrect actions ref_name (#25358) (#25367)
* Write absolute AppDataPath to app.ini when installing (#25331) (#25347)
* Fix incorrect config argument position for builtin SSH server (#25341)
* Remove EasyMDE focus outline on text (#25328) (#25332)
* Fix displayed RPM repo url (#25310) (#25313)
* Fix index generation parallelly failure (#25235) (#25269)
* Fix panic when migrating a repo from GitHub with issues (#25246) (#25247)
* Fix task list checkbox toggle to work with YAML front matter (#25184) (#25227)
* Fix compatible for webhook ref type (#25195) (#25223)
* Hide limited users if viewed by anonymous ghost (#25214) (#25220)
* Do not overwrite the log mode when installing (#25203) (#25209)
* Fix fullscreen for action (#25200) (#25207)
* Add `WithPullRequest` for `actionsNotifier` (#25144) (#25197)
* Fix `MilestoneIDs` when querying issues (#25125) (#25141)
* Fix incorrect git ignore rule and add missing license files (#25135) (#25138)
* Remove incorrect element ID on "post-install" page (#25104) (#25129)
* Fix 500 error caused by notifications without an issue such as repo transfers (#25101)
* Help to recover from corrupted levelqueue (#24912)
* Fix 500 error when select `No assignee` filter in issue list page (#24854)
* Add validations.required check to dropdown field (#24849)
* Reenable creating default webhooks. (#24626)
* Fix incorrect user visibility (#24557)
* Fix commits pushed with deploy keys not shown in dashboard (#24521)
* Check length of `LogIndexes` in case it is outdated (#24516)
* Fix incorrect CurrentUser check for docker rootless (#24441)
* Fix some mistakes when using `ignSignIn` (#24415)
* Fix incorrect CORS response in Http Git handler (#24303)
* Fix issue attachment handling (#24202)
* Make mention autocomplete case insensitive in new markdown editor (#24190)
* Use 1.18's aria role for dropdown menus (#24144)
* Fix internal sever error when visiting a PR that bound to the deleted team (#24127)
* Add migration to fix external unit access mode of owner/admin team (#24117)
* Show friendly 500 error page to users and developers (#24110)
* Fix meilisearch not working when searching across multiple repositories (#24109)
* Fix math and mermaid rendering bugs (#24049)
* Remove "inverted" class on creating new label and cancel buttons (#24030)
* Allow repo admins too to delete the repo (#23940)
* Disable editing tags (#23883)
* Fix review conversation reply (#23846)
* Fix incorrect CORS failure detection logic (#23844)
* Remove incorrect HTML self close tag (#23748)
* Fix incorrect `toggle` buttons (#23676)
* Introduce path Clean/Join helper functions (#23495)
* Fix missed migration in #22235 (#23482)
* Do not store user projects as organization projects (#23353)
* Fix incorrect display for comment context menu (#23343)
* Make Ctrl+Enter submit a pending comment (starting review) instead of submitting a single comment (#23245)
* Fix submit button won't refresh in New Repository Fork page (#22994)
* Remove stars when repo goes private (#19904)
* TESTING
* Add unit test for repository collaboration (#25640) (#25658)
* Add missing test case and fix typo in tests (#24915)
* Kd/fix redis unit test (#24650)
* Add owner team permission check test (#24096)
* Test renderReadmeFile (#23185)
* Add default owner team to privated_org and limited_org in unit test (#23109)
* Speed up HasUserStopwatch & GetActiveStopwatch (#23051)
* Remove all package data after tests (#22984)
* TRANSLATION
* Backport locales to v1.20 (#25899)
* Translate untranslated string in issues list (#25759) (#25761)
* Remove broken translations (#25737)
* Show correct naming for 1 comment (#25704) (#25712)
* Add Chinese documentations for Actions (#24902)
* Change `valid_until` translation to `valid_until_date` and include placeholder for the date (#24563)
* Change `add_on` translation to `added_on` and include placeholder for the date (#24562)
* Change `join_on` translation to `joined_on` and include placeholder for the date (#24550)
* Use double quotes consistently in en-US (#24141)
* Clarify Gitea/Crowdin locale behaviors, add tests for LocaleStore, fix some strings with semicolons (#23819)
* Update localization.zh-cn.md (#23448)
* Fix grammar in error message (#23273)
* BUILD
* Correct permissions for `.ssh` and `authorized_keys` (#25721) (#25730)
* Upgrade snap to node 20 (#24990)
* Use Go 1.20 for next release (#24859)
* Ignore build for docs only (#24761)
* Update cron-translations.yml (#24708)
* Update to Alpine 3.18 (#24700)
* Check latest version on CI (#24556)
* Upgrade to Node 20 on CI, enable actions cancellation (#24524)
* Mark `/templates/swagger/v1_json.tmpl` as generated file (#24306)
* Enable forbidigo linter (#24278)
* Introduce lint-md and compliance-docs pipeline (#24021)
* Add eslint-plugin-custom-elements (#23991)
* Update eslints for Vue 3 (#23935)
* Improve backport-locales.go (#23807)
* Don't run unnecessary steps when only docs changed (#23103)
* DOCS
* Docs: rootless docker ssh's default port is 2222 (#25771) (#25772)
* Add documentation about supported workflow trigger events (#25582) (#25589)
* Document creating an API key from the CLI (#25504)
* Use the new download domain replace the old (#25405) (#25409)
* Add Exoscale to installation on cloud provider docs (#25342) (#25346)
* Improve some documents: release version, logging, NFS lock (#25202) (#25204)
* Change branch name from master to main in some documents' links (#25126) (#25140)
* Introduce how to configure cache when starting a Runner with Docker (#25077)
* Docs: remove an extraneous whitespace (#24949)
* Update Asciidoc markup example with safe defaults (#24920)
* Fix \<empty\> in administration/config-cheat-sheet.en-us.md (#24905)
* Rename docs packages title from xxx Packages Repository -> xxx Package Registry (#24895)
* Replace `drone exec` to `act_runner exec` in test README.md (#24791)
* Update packages overview page (#24730)
* Docs for creating a user to run Gitea on Fedora/RHEL/CentOS (#24725)
* Move actions as usage's subdirectory and update comparsion zh-cn version (#24719)
* Document `redis-cluster` explicitly in config (#24717)
* Improve reverse-proxy document and fix nginx config bug (#24616)
* Fix broken `README` link (#24546)
* Update `CONTRIBUTING.md` (#24492)
* Docs for Gitea Actions (#24405)
* Zh-cn support on doc pages (#24166)
* Fix https setup doc zh-cn (#24015)
* Adjust some documentations titles (#23941)
* More specific and unique feed name for NuGet install command template. (#23889)
* Clarify that Gitea requires JavaScript (#23677)
* Rename develop -> development, contribute -> contributing, administer -> administration (#23662)
* Update PR documentation (#23620)
* Add package registry architecture overview (#23445)
* Add gradle samples in maven doc of packages (#23374)
* Improve the frontend guideline (#23298)
* Add document for `webcomponents` (#23261)
* Add Gitea Community Code of Conduct (#23188)
* Avoid Hugo from adding quote to actions url (#23097)
* Improve reverse proxies documentation (#23068)
* Docs: HTTPS configuration for zh-cn (#23039)
* MISC
* Do not prepare oauth2 config if it is not enabled, do not write config in some sub-commands (#25567) (#25576)
* Align language menu icon and fit the footer area (#25556) (#25563)
* Fix sub-command log level (#25537) (#25553)
* Fix admin-dl-horizontal (#25512) (#25535)
* Fix input `line-height` cutting off `g` (#25334) (#25533)
* Clarify the reason why the user can't add a new email if there is a pending activation (#25509) (#25514)
* Improve loadprojects for issue list (#25468) (#25493)
* Use "utf8mb4" for MySQL by default (#25432)
* Show outdated comments in files changed tab (#24936) (#25428)
* Avoid polluting config file when "save" (#25395) (#25406)
* Fix blank dir message when uploading files from web editor (#25391) (#25400)
* Fix issue filters on mobile view (#25368) (#25371)
* Avoid polluting the config (#25345) (#25354)
* Fix action runner last online state on edit page (#25337)
* Remove fomantic inverted variations (#25286) (#25289)
* Show OAuth2 errors to end users (#25261) (#25271)
* Fix profile render when the README.md size is larger than 1024 bytes (#25270)
* Fix strange UI behavior of cancelling dismiss review modal (#25172)
* Update js dependencies (#25137) (#25151)
* Fix swagger documentation for multiple files API endpoint (#25110)
* Fix link to customizing-gitea (#25056)
* Add Link to Stars and Forks Page to Repo List (#24931)
* Improve confusable character string (#24911)
* Fix install page context, make the install page tests really test (#24858)
* Add gitea manager reload-templates command (#24843)
* Create pull request for base after editing file, if not enabled on fork (#24841)
* Fix video width overflow in markdown, and other changes to match img (#24834)
* Support Copy Link for video attachments (#24833)
* Improve accessibility when (re-)viewing files (#24817)
* Update JS dependencies (#24815)
* Bump vm2 from 3.9.17 to 3.9.18 (#24742)
* Add IsErrRepoFilesAlreadyExist check when fork repo (#24678)
* Fix typo in act-runner file (#24652)
* Do not send "registration success email" for external auth sources (#24632)
* Filter get single commit (#24613)
* Make diff view full width again (#24598)
* Add permission check for moving issue action in project view page (#24589)
* Revert "Prevent a user with a different email from accepting the team invite" (#24531)
* Temporarily disable PATs until next release (#24527)
* Clean up polluted styles and remove dead CSS code (#24497)
* Faster git.GetDivergingCommits (#24482)
* Fix test delivery button in repo webhook settings page (#24478)
* Use globally shared HTMLRender (#24436)
* Changelog 1.19.2 (#24365) (#24403)
* Fix layouts of admin table / adapt repo / email test (#24370)
* Gitea Actions add `base_ref`, `head_ref`, `api_url`, `ref_type` fields (#24356)
* Fix 404 error when leaving the last private org team (#24322)
* Improve External Wiki in Repo Header (#24304)
* Updated upgrade script that is informing user that Gitea service has to be running in order to upgrade it (#24260)
* Add run status in action view page (#24223)
* Update JS dependencies (#24218)
* Bump vm2 from 3.9.15 to 3.9.16 (#24089)
* Update github.com/google/go-github to v51 (#23946)
* Show visibility status of email in own profile (#23900)
* Refactor authors dropdown (send get request from frontend to avoid long wait time) (#23890)
* Add self to maintainers (#23644)
* Upgrade to npm lockfile v3 and explicitely set it (#23561)
* Improve indices for `action` table (#23532)
* Update JS dependencies, Require Node.js 16 (#23528)
* Add init file for Ubuntu (#23362)
* Update go.mod dependencies (#23126)
* Use minio/sha256-simd for accelerated SHA256 (#23052)
* More detailed branch delete message (#22696)
* Add tooltips to `Hide comment type` settings where necessary (#21306)
## [1.19.4](https://github.com/go-gitea/gitea/releases/tag/v1.19.4) - 2023-07-04
* SECURITY
* Fix open redirect check for more cases (#25143) (#25155)
* API
* Return `404` in the API if the requested webhooks were not found (#24823) (#24830)
* Fix `organization` field being `null` in `GET /api/v1/teams/{id}` (#24694) (#24696)
* ENHANCEMENTS
* Set `--font-weight-bold` to 600 (#24840)
* Make mailer SMTP check have timed context (#24751) (#24759)
* Do not select line numbers when selecting text from the action run logs (#24594) (#24596)
* BUGFIXES
* Fix bug when change user name (#25637) (#25645)
* Fix task list checkbox toggle to work with YAML front matter (#25184) (#25236)
* Hide limited users if viewed by anonymous ghost (#25214) (#25224)
* Add `WithPullRequest` for `actionsNotifier` (#25144) (#25196)
* Fix parallelly generating index failure with Mysql (#24567) (#25081)
* GitLab migration: Sanitize response for reaction list (#25054) (#25059)
* Fix users cannot visit issue attachment bug (#25019) (#25027)
* Fix missing reference prefix of commits when sync mirror repository (#24994)
* Only validate changed columns when update user (#24867) (#24903)
* Make DeleteIssue use correct context (#24885)
* Fix topics deleted via API not being deleted in org page (#24825) (#24829)
* Fix Actions being enabled accidentally (#24802) (#24810)
* Fix missed table name on iterate lfs meta objects (#24768) (#24774)
* Fix safari cookie session bug (#24772)
* Respect original content when creating secrets (#24745) (#24746)
* Fix Pull Mirror out-of-sync bugs (#24732) (#24733)
* Fix run list broken when trigger user deleted (#24706) (#24709)
* Fix issues list page multiple selection update milestones (#24660) (#24663)
* Fix: release page for empty or non-existing target (#24659)
* Fix close org projects (#24588) (#24591)
* Refresh the refernce of the closed PR when reopening (#24231) (#24587)
* Fix the permission of team's `Actions` unit issue (#24536) (#24545)
* Bump go.etcd.io/bbolt and blevesearch deps (#23062) (#24519)
* Fix new wiki page mirror (#24518)
* Match unqualified references when syncing pulls as well (#23070)
* DOCS
* Change branch name from master to main in some documents' links (#25126) (#25139)
* Remove unnecessary content on docs (#24976) (#25001)
* Unify doc links to use paths relative to doc folder (#24979) (#25000)
* Fix docs documenting invalid `@every` for `OLDER_THAN` cron settings (#24695) (#24698)
* MISC
* Merge different languages for language stats (#24900) (#24921)
* Hiding Secrets options when Actions feature is disabled (#24792)
* Improve decryption failure message (#24573) (#24575)
* Makefile: Use portable !, not GNUish -not, with find(1). (#24565) (#24572)
## [1.19.3](https://github.com/go-gitea/gitea/releases/tag/1.19.3) - 2023-05-03
* SECURITY

View File

@ -473,14 +473,14 @@ https://help.github.com/articles/signing-commits-with-gpg/
## Technical Oversight Committee (TOC)
At the start of 2023, the `Owners` team was dissolved. Instead, the governance charter proposed a technical oversight committee (TOC) which expands the ownership team of the Gitea project from three elected positions to six positions. Three positions would be elected as it has been over the past years, and the other three would consist of appointed members from the Gitea company.
https://blog.gitea.io/2023/02/gitea-quarterly-report-23q1/
https://blog.gitea.com/quarterly-23q1/
When the new community members have been elected, the old members will give up ownership to the newly elected members. For security reasons, TOC members or any account with write access (like a bot) must use 2FA.
https://help.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/
### Current TOC members
- 2023-01-01 ~ 2023-12-31 - https://blog.gitea.io/2023/02/gitea-quarterly-report-23q1/
- 2023-01-01 ~ 2023-12-31 - https://blog.gitea.com/quarterly-23q1/
- Company
- [Jason Song](https://gitea.com/wolfogre) <i@wolfogre.com>
- [Lunny Xiao](https://gitea.com/lunny) <xiaolunwen@gmail.com>

View File

@ -52,3 +52,5 @@ Xinyi Gong <hestergong@gmail.com> (@HesterG)
wxiaoguang <wxiaoguang@gmail.com> (@wxiaoguang)
Gary Moon <gary@garymoon.net> (@garymoon)
Philip Peterson <philip.c.peterson@gmail.com> (@philip-peterson)
Denys Konovalov <kontakt@denyskon.de> (@denyskon)
Punit Inani <punitinani1@gmail.com> (@puni9869)

View File

@ -25,17 +25,17 @@ COMMA := ,
XGO_VERSION := go-1.20.x
AIR_PACKAGE ?= github.com/cosmtrek/air@v1.43.0
AIR_PACKAGE ?= github.com/cosmtrek/air@v1.44.0
EDITORCONFIG_CHECKER_PACKAGE ?= github.com/editorconfig-checker/editorconfig-checker/cmd/editorconfig-checker@2.7.0
GOFUMPT_PACKAGE ?= mvdan.cc/gofumpt@v0.5.0
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.52.2
GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.53.3
GXZ_PAGAGE ?= github.com/ulikunitz/xz/cmd/gxz@v0.5.11
MISSPELL_PACKAGE ?= github.com/client9/misspell/cmd/misspell@v0.3.4
SWAGGER_PACKAGE ?= github.com/go-swagger/go-swagger/cmd/swagger@v0.30.4
SWAGGER_PACKAGE ?= github.com/go-swagger/go-swagger/cmd/swagger@v0.30.5
XGO_PACKAGE ?= src.techknowlogick.com/xgo@latest
GO_LICENSES_PACKAGE ?= github.com/google/go-licenses@v1.6.0
GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@latest
ACTIONLINT_PACKAGE ?= github.com/rhysd/actionlint/cmd/actionlint@latest
GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@v0.2.0
ACTIONLINT_PACKAGE ?= github.com/rhysd/actionlint/cmd/actionlint@v1.6.25
DOCKER_IMAGE ?= gitea/gitea
DOCKER_TAG ?= latest
@ -116,15 +116,15 @@ FOMANTIC_WORK_DIR := web_src/fomantic
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
WEBPACK_DEST := public/assets/js/index.js public/assets/css/index.css
WEBPACK_DEST_ENTRIES := public/assets/js public/assets/css public/assets/fonts public/assets/img/webpack
BINDATA_DEST := modules/public/bindata.go modules/options/bindata.go modules/templates/bindata.go
BINDATA_HASH := $(addsuffix .hash,$(BINDATA_DEST))
GENERATED_GO_DEST := modules/charset/invisible_gen.go modules/charset/ambiguous_gen.go
SVG_DEST_DIR := public/img/svg
SVG_DEST_DIR := public/assets/img/svg
AIR_TMP_DIR := .air
@ -226,6 +226,8 @@ help:
@echo " - test-frontend test frontend files"
@echo " - test-backend test backend files"
@echo " - test-e2e[\#TestSpecificName] test end to end using playwright"
@echo " - update-js update js dependencies"
@echo " - update-py update py dependencies"
@echo " - webpack build webpack files"
@echo " - svg build svg files"
@echo " - fomantic build fomantic files"
@ -358,10 +360,10 @@ lint: lint-frontend lint-backend
lint-fix: lint-frontend-fix lint-backend-fix
.PHONY: lint-frontend
lint-frontend: lint-js lint-css lint-md lint-swagger
lint-frontend: lint-js lint-css
.PHONY: lint-frontend-fix
lint-frontend-fix: lint-js-fix lint-css-fix lint-md lint-swagger
lint-frontend-fix: lint-js-fix lint-css-fix
.PHONY: lint-backend
lint-backend: lint-go lint-go-vet lint-editorconfig
@ -924,13 +926,20 @@ node_modules: package-lock.json
poetry install
@touch .venv
.PHONY: npm-update
npm-update: node-check | node_modules
npx updates -cu
.PHONY: update-js
update-js: node-check | node_modules
npx updates -u -f package.json
rm -rf node_modules package-lock.json
npm install --package-lock
@touch node_modules
.PHONY: update-py
update-py: node-check | node_modules
npx updates -u -f pyproject.toml
rm -rf .venv poetry.lock
poetry install
@touch .venv
.PHONY: fomantic
fomantic:
rm -rf $(FOMANTIC_WORK_DIR)/build

View File

@ -1,6 +1,6 @@
<p align="center">
<a href="https://gitea.io/">
<img alt="Gitea" src="https://raw.githubusercontent.com/go-gitea/gitea/main/public/img/gitea.svg" width="220"/>
<img alt="Gitea" src="https://raw.githubusercontent.com/go-gitea/gitea/main/public/assets/img/gitea.svg" width="220"/>
</a>
</p>
<h1 align="center">Gitea - Git with a cup of tea</h1>
@ -64,7 +64,7 @@ architectures that are supported by Go, including Linux, macOS, and
Windows on x86, amd64, ARM and PowerPC architectures.
You can try it out using [the online demo](https://try.gitea.io/).
This project has been
[forked](https://blog.gitea.io/2016/12/welcome-to-gitea/) from
[forked](https://blog.gitea.com/welcome-to-gitea/) from
[Gogs](https://gogs.io) since November of 2016, but a lot has changed.
## Building

View File

@ -1,6 +1,6 @@
<p align="center">
<a href="https://gitea.io/">
<img alt="Gitea" src="https://raw.githubusercontent.com/go-gitea/gitea/main/public/img/gitea.svg" width="220"/>
<img alt="Gitea" src="https://raw.githubusercontent.com/go-gitea/gitea/main/public/assets/img/gitea.svg" width="220"/>
</a>
</p>
<h1 align="center">Gitea - Git with a cup of tea</h1>

View File

@ -4,6 +4,8 @@ The Gitea maintainers take security seriously.
If you discover a security issue, please bring it to their attention right away!
Previous vulnerabilities are listed at https://about.gitea.com/security.
## Reporting a Vulnerability
Please **DO NOT** file a public issue, instead send your report privately to `security@gitea.io`.

2
assets/emoji.json generated

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -25,7 +25,7 @@ import (
var optionLogVerbose bool
func logVerbose(msg string, args ...interface{}) {
func logVerbose(msg string, args ...any) {
if optionLogVerbose {
log.Printf(msg, args...)
}

View File

@ -25,7 +25,7 @@ import (
const (
gemojiURL = "https://raw.githubusercontent.com/github/gemoji/master/db/emoji.json"
maxUnicodeVersion = 14
maxUnicodeVersion = 15
)
var flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")

View File

@ -69,13 +69,13 @@ async function main() {
const faviconSvg = await readFile(new URL('../assets/favicon.svg', import.meta.url), 'utf8');
await Promise.all([
generate(logoSvg, '../public/img/logo.svg', {size: 32}),
generate(logoSvg, '../public/img/logo.png', {size: 512}),
generate(faviconSvg, '../public/img/favicon.svg', {size: 32}),
generate(faviconSvg, '../public/img/favicon.png', {size: 180}),
generate(logoSvg, '../public/img/avatar_default.png', {size: 200}),
generate(logoSvg, '../public/img/apple-touch-icon.png', {size: 180, bg: true}),
gitea && generate(logoSvg, '../public/img/gitea.svg', {size: 32}),
generate(logoSvg, '../public/assets/img/logo.svg', {size: 32}),
generate(logoSvg, '../public/assets/img/logo.png', {size: 512}),
generate(faviconSvg, '../public/assets/img/favicon.svg', {size: 32}),
generate(faviconSvg, '../public/assets/img/favicon.png', {size: 180}),
generate(logoSvg, '../public/assets/img/avatar_default.png', {size: 200}),
generate(logoSvg, '../public/assets/img/apple-touch-icon.png', {size: 180, bg: true}),
gitea && generate(logoSvg, '../public/assets/img/gitea.svg', {size: 32}),
]);
}

View File

@ -44,7 +44,7 @@ async function processFile(file, {prefix, fullName} = {}) {
],
});
await writeFile(fileURLToPath(new URL(`../public/img/svg/${name}.svg`, import.meta.url)), data);
await writeFile(fileURLToPath(new URL(`../public/assets/img/svg/${name}.svg`, import.meta.url)), data);
}
function processFiles(pattern, opts) {
@ -53,13 +53,13 @@ function processFiles(pattern, opts) {
async function main() {
try {
await mkdir(fileURLToPath(new URL('../public/img/svg', import.meta.url)), {recursive: true});
await mkdir(fileURLToPath(new URL('../public/assets/img/svg', import.meta.url)), {recursive: true});
} catch {}
await Promise.all([
...processFiles('node_modules/@primer/octicons/build/svg/*-16.svg', {prefix: 'octicon'}),
...processFiles('web_src/svg/*.svg'),
...processFiles('public/img/gitea.svg', {fullName: 'gitea-gitea'}),
...processFiles('public/assets/img/gitea.svg', {fullName: 'gitea-gitea'}),
]);
}

View File

@ -63,7 +63,7 @@ Outputs to 'cert.pem' and 'key.pem' and will overwrite existing files.`,
},
}
func publicKey(priv interface{}) interface{} {
func publicKey(priv any) any {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
@ -74,7 +74,7 @@ func publicKey(priv interface{}) interface{} {
}
}
func pemBlockForKey(priv interface{}) *pem.Block {
func pemBlockForKey(priv any) *pem.Block {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
@ -94,7 +94,7 @@ func runCert(c *cli.Context) error {
return err
}
var priv interface{}
var priv any
var err error
switch c.String("ecdsa-curve") {
case "":

View File

@ -106,5 +106,21 @@ func setupConsoleLogger(level log.Level, colorize bool, out io.Writer) {
WriterOption: log.WriterConsoleOption{Stderr: out == os.Stderr},
}
writer := log.NewEventWriterConsole("console-default", writeMode)
log.GetManager().GetLogger(log.DEFAULT).RemoveAllWriters().AddWriters(writer)
log.GetManager().GetLogger(log.DEFAULT).ReplaceAllWriters(writer)
}
// PrepareConsoleLoggerLevel by default, use INFO level for console logger, but some sub-commands (for git/ssh protocol) shouldn't output any log to stdout.
// Any log appears in git stdout pipe will break the git protocol, eg: client can't push and hangs forever.
func PrepareConsoleLoggerLevel(defaultLevel log.Level) func(*cli.Context) error {
return func(c *cli.Context) error {
level := defaultLevel
if c.Bool("quiet") || c.GlobalBoolT("quiet") {
level = log.FATAL
}
if c.Bool("debug") || c.GlobalBool("debug") || c.Bool("verbose") || c.GlobalBool("verbose") {
level = log.TRACE
}
log.SetConsoleLogger(log.DEFAULT, "console-default", level)
return nil
}
}

View File

@ -151,7 +151,7 @@ func setupDoctorDefaultLogger(ctx *cli.Context, colorize bool) {
log.FallbackErrorf("unable to create file log writer: %v", err)
return
}
log.GetManager().GetLogger(log.DEFAULT).RemoveAllWriters().AddWriters(writer)
log.GetManager().GetLogger(log.DEFAULT).ReplaceAllWriters(writer)
}
}

View File

@ -161,7 +161,7 @@ It can be used for backup and capture Gitea server image to send to maintainer`,
},
}
func fatal(format string, args ...interface{}) {
func fatal(format string, args ...any) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
log.Fatal(format, args...)
}
@ -236,7 +236,7 @@ func runDump(ctx *cli.Context) error {
return err
}
var iface interface{}
var iface any
if fileName == "-" {
iface, err = archiver.ByExtension(fmt.Sprintf(".%s", outType))
} else {

View File

@ -22,9 +22,9 @@ import (
"github.com/urfave/cli"
)
// Cmdembedded represents the available extract sub-command.
// CmdEmbedded represents the available extract sub-command.
var (
Cmdembedded = cli.Command{
CmdEmbedded = cli.Command{
Name: "embedded",
Usage: "Extract embedded resources",
Description: "A command for extracting embedded resources, like templates and images",

View File

@ -15,6 +15,7 @@ import (
"time"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/private"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
@ -32,6 +33,7 @@ var (
Name: "hook",
Usage: "Delegate commands to corresponding Git hooks",
Description: "This should only be called by Git",
Before: PrepareConsoleLoggerLevel(log.FATAL),
Subcommands: []cli.Command{
subcmdHookPreReceive,
subcmdHookUpdate,

View File

@ -8,6 +8,7 @@ import (
"fmt"
"strings"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/private"
"github.com/urfave/cli"
@ -17,6 +18,7 @@ import (
var CmdKeys = cli.Command{
Name: "keys",
Usage: "This command queries the Gitea database to get the authorized command for a given ssh key fingerprint",
Before: PrepareConsoleLoggerLevel(log.FATAL),
Action: runKeys,
Flags: []cli.Flag{
cli.StringFlag{

View File

@ -178,7 +178,7 @@ func runAddConnLogger(c *cli.Context) error {
defer cancel()
setup(ctx, c.Bool("debug"))
vals := map[string]interface{}{}
vals := map[string]any{}
mode := "conn"
vals["net"] = "tcp"
if c.IsSet("protocol") {
@ -208,7 +208,7 @@ func runAddFileLogger(c *cli.Context) error {
defer cancel()
setup(ctx, c.Bool("debug"))
vals := map[string]interface{}{}
vals := map[string]any{}
mode := "file"
if c.IsSet("filename") {
vals["filename"] = c.String("filename")
@ -236,7 +236,7 @@ func runAddFileLogger(c *cli.Context) error {
return commonAddLogger(c, mode, vals)
}
func commonAddLogger(c *cli.Context, mode string, vals map[string]interface{}) error {
func commonAddLogger(c *cli.Context, mode string, vals map[string]any) error {
if len(c.String("level")) > 0 {
vals["level"] = log.LevelFromString(c.String("level")).String()
}

View File

@ -30,7 +30,7 @@ import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/services/lfs"
"github.com/golang-jwt/jwt/v4"
"github.com/golang-jwt/jwt/v5"
"github.com/kballard/go-shellquote"
"github.com/urfave/cli"
)
@ -44,6 +44,7 @@ var CmdServ = cli.Command{
Name: "serv",
Usage: "This command should only be called by SSH shell",
Description: "Serv provides access auth for repositories",
Before: PrepareConsoleLoggerLevel(log.FATAL),
Action: runServ,
Flags: []cli.Flag{
cli.BoolFlag{
@ -94,7 +95,7 @@ var (
// 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 {
func fail(ctx context.Context, userMessage, logMsgFmt string, args ...any) error {
if userMessage == "" {
userMessage = "Internal Server Error (no specific error)"
}

View File

@ -35,6 +35,7 @@ var CmdWeb = cli.Command{
Usage: "Start Gitea web server",
Description: `Gitea web server is the only thing you need to run,
and it takes care of all the other things for you`,
Before: PrepareConsoleLoggerLevel(log.INFO),
Action: runWeb,
Flags: []cli.Flag{
cli.StringFlag{
@ -206,11 +207,6 @@ func servePprof() {
}
func runWeb(ctx *cli.Context) error {
if ctx.Bool("verbose") {
setupConsoleLogger(log.TRACE, log.CanColorStdout, os.Stdout)
} else if ctx.Bool("quiet") {
setupConsoleLogger(log.FATAL, log.CanColorStdout, os.Stdout)
}
defer func() {
if panicked := recover(); panicked != nil {
log.Fatal("PANIC: %v\n%s", panicked, log.Stack(2))

View File

@ -5,7 +5,6 @@ package main
import (
"os"
"strings"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
@ -13,9 +12,6 @@ import (
"github.com/urfave/cli"
)
// EnvironmentPrefix environment variables prefixed with this represent ini values to write
const EnvironmentPrefix = "GITEA"
func main() {
app := cli.NewApp()
app.Name = "environment-to-ini"
@ -70,15 +66,6 @@ func main() {
Value: "",
Usage: "Destination file to write to",
},
cli.BoolFlag{
Name: "clear",
Usage: "Clears the matched variables from the environment",
},
cli.StringFlag{
Name: "prefix, p",
Value: EnvironmentPrefix,
Usage: "Environment prefix to look for - will be suffixed by __ (2 underscores)",
},
}
app.Action = runEnvironmentToIni
err := app.Run(os.Args)
@ -88,6 +75,8 @@ func main() {
}
func runEnvironmentToIni(c *cli.Context) error {
// the config system may change the environment variables, so get a copy first, to be used later
env := append([]string{}, os.Environ()...)
setting.InitWorkPathAndCfgProvider(os.Getenv, setting.ArgWorkPathAndCustomConf{
WorkPath: c.String("work-path"),
CustomPath: c.String("custom-path"),
@ -99,9 +88,7 @@ func runEnvironmentToIni(c *cli.Context) error {
log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
}
prefixGitea := c.String("prefix") + "__"
suffixFile := "__FILE"
changed := setting.EnvironmentToConfig(cfg, prefixGitea, suffixFile, os.Environ())
changed := setting.EnvironmentToConfig(cfg, env)
// try to save the config file
destination := c.String("out")
@ -116,19 +103,5 @@ func runEnvironmentToIni(c *cli.Context) error {
}
}
// clear Gitea's specific environment variables if requested
if c.Bool("clear") {
for _, kv := range os.Environ() {
idx := strings.IndexByte(kv, '=')
if idx < 0 {
continue
}
eKey := kv[:idx]
if strings.HasPrefix(eKey, prefixGitea) {
_ = os.Unsetenv(eKey)
}
}
}
return nil
}

View File

@ -16,26 +16,23 @@
;;
;; - _`AppPath`_: This is the absolute path of the running gitea binary.
;; - _`AppWorkPath`_: This refers to "working path" of the `gitea` binary. It is determined by using the first set thing in the following hierarchy:
;; - The "WORK_PATH" option in "app.ini" file
;; - The `--work-path` flag passed to the binary
;; - 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 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:
;; - 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:
;; - The `--custom-path` flag passed to the binary
;; - The environment variable `$GITEA_CUSTOM`
;; - A built-in value set at build time (see building from source)
;; - Otherwise it defaults to _`AppWorkPath`_`/custom`
;; - If any of the above are relative paths then they are made absolute against the
;; the directory of the _`AppWorkPath`_
;; - If any of the above are relative paths then they are made absolute against the directory of the _`AppWorkPath`_
;; - _`CustomConf`_: This is the path to the `app.ini` file.
;; - The `--config` flag passed to the binary
;; - A built-in value set at build time (see building from source)
;; - Otherwise it defaults to _`CustomPath`_`/conf/app.ini`
;; - If any of the above are relative paths then they are made absolute against the
;; the directory of the _`CustomPath`_
;; - If any of the above are relative paths then they are made absolute against the directory of the _`CustomPath`_
;;
;; In addition there is _`StaticRootPath`_ which can be set as a built-in at build time, but will otherwise default to _`AppWorkPath`_
@ -52,6 +49,9 @@ RUN_USER = ; git
;; Application run mode, affects performance and debugging: "dev" or "prod", default is "prod"
;; Mode "dev" makes Gitea easier to develop and debug, values other than "dev" are treated as "prod" which is for production use.
;RUN_MODE = prod
;;
;; The working directory, see the comment of AppWorkPath above
;WORK_PATH =
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@ -193,8 +193,8 @@ RUN_USER = ; git
;; 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
;; Enable SSH Authorized Key Backup when rewriting all keys, default is false
;SSH_AUTHORIZED_KEYS_BACKUP = false
;;
;; Determines which principals to allow
;; - empty: if SSH_TRUSTED_USER_CA_KEYS is empty this will default to off, otherwise will default to email, username.
@ -303,7 +303,10 @@ RUN_USER = ; git
;;
;;
;; LFS authentication secret, change this yourself
LFS_JWT_SECRET =
;LFS_JWT_SECRET =
;;
;; Alternative location to specify LFS authentication secret. You cannot specify both this and LFS_JWT_SECRET, and must pick one
;LFS_JWT_SECRET_URI = file:/etc/gitea/lfs_jwt_secret
;;
;; LFS authentication validity period (in time.Duration), pushes taking longer than this may fail.
;LFS_HTTP_AUTH_EXPIRY = 24h
@ -527,6 +530,9 @@ ENABLE = true
;; This setting is only needed if JWT_SIGNING_ALGORITHM is set to HS256, HS384 or HS512.
;JWT_SECRET =
;;
;; Alternative location to specify OAuth2 authentication secret. You cannot specify both this and JWT_SECRET, and must pick one
;JWT_SECRET_URI = file:/etc/gitea/oauth2_jwt_secret
;;
;; Lifetime of an OAuth2 access token in seconds
;ACCESS_TOKEN_EXPIRATION_TIME = 3600
;;
@ -1194,11 +1200,11 @@ LEVEL = Info
;;
;; All available reactions users can choose on issues/prs and comments.
;; 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
;; For custom reactions, add a tightly cropped square image to public/assets/img/emoji/reaction_name.png
;REACTIONS = +1, -1, laugh, hooray, confused, heart, rocket, eyes
;;
;; 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 add it to this config.
;; By default we support gitea (:gitea:), to add more copy them to public/assets/img/emoji/emoji_name.png and add it to this config.
;; Dont mistake it for Reactions.
;CUSTOM_EMOJIS = gitea, codeberg, gitlab, git, github, gogs
;;
@ -2541,8 +2547,8 @@ LEVEL = Info
;; Enable/Disable actions capabilities
;ENABLED = false
;;
;; Default address to get action plugins, e.g. the default value means downloading from "https://gitea.com/actions/checkout" for "uses: actions/checkout@v3"
;DEFAULT_ACTIONS_URL = https://gitea.com
;; Default platform to get action plugins, `github` for `https://github.com`, `self` for the current Gitea instance.
;DEFAULT_ACTIONS_URL = github
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

View File

@ -2,7 +2,15 @@
if [ ! -d /data/git/.ssh ]; then
mkdir -p /data/git/.ssh
chmod 700 /data/git/.ssh
fi
# Set the correct permissions on the .ssh directory and authorized_keys file,
# or sshd will refuse to use them and lead to clone/push/pull failures.
# It could happen when users have copied their data to a new volume and changed the file permission by accident,
# and it would be very hard to troubleshoot unless users know how to check the logs of sshd which is started by s6.
chmod 700 /data/git/.ssh
if [ -f /data/git/.ssh/authorized_keys ]; then
chmod 600 /data/git/.ssh/authorized_keys
fi
if [ ! -f /data/git/.ssh/environment ]; then

View File

@ -8,7 +8,7 @@
#
# And place the original in /usr/lib/gitea with working files in /data/gitea
GITEA="/app/gitea/gitea"
WORK_DIR="/app/gitea"
WORK_DIR="/data/gitea"
CUSTOM_PATH="/data/gitea"
# Provide docker defaults

View File

@ -15,7 +15,7 @@ If you are planning to contribute you'll want to download and install Hugo on
your local machine.
The installation of Hugo is out of the scope of this document, so please take
the [official install instructions](https://gohugo.io/overview/installing/) to
the [official install instructions](https://gohugo.io/installation/) to
get Hugo up and running.
## Development

View File

@ -46,9 +46,9 @@ directory. There should be some output similar to the following:
Inside the `gitea-dump-1482906742.zip` file, will be the following:
- `app.ini` - Optional copy of configuration file if originally stored outside of the default `custom/` directory
- `app.ini` - Optional copy of configuration file if originally stored outside the default `custom/` directory
- `custom` - All config or customization files in `custom/`.
- `data` - Data directory in <GITEA_WORK_DIR>, except sessions if you are using file session. This directory includes `attachments`, `avatars`, `lfs`, `indexers`, SQLite file if you are using SQLite.
- `data` - Data directory (APP_DATA_PATH), except sessions if you are using file session. This directory includes `attachments`, `avatars`, `lfs`, `indexers`, SQLite file if you are using SQLite.
- `gitea-db.sql` - SQL dump of database
- `gitea-repo.zip` - Complete copy of the repository directory.
- `log/` - Various logs. They are not needed for a recovery or migration.
@ -139,16 +139,6 @@ chown -R git:git /data
The default user in the gitea container is `git` (1000:1000). Please replace `2a83b293548e` with your gitea container id or name.
These are the default paths used in the container:
```text
DEFAULT CONFIGURATION:
CustomPath: /data/gitea (GITEA_CUSTOM)
CustomConf: /data/gitea/conf/app.ini
AppPath: /usr/local/bin/gitea
AppWorkPath: /usr/local/bin
```
### Using Docker-rootless (`restore`)
The restore workflow in Docker-rootless containers differs only in the directories to be used:

View File

@ -47,7 +47,7 @@ for its glob syntax. Here are some examples:
- List all template files, in any virtual directory: `**.tmpl`
- List all mail template files: `templates/mail/**.tmpl`
- List all files inside `public/img`: `public/img/**`
- List all files inside `public/assets/img`: `public/assets/img/**`
Don't forget to use quotes for the patterns, as spaces, `*` and other characters might have
a special meaning for your command shell.
@ -60,8 +60,8 @@ Listing all embedded files with `openid` in their path:
```sh
$ gitea embedded list '**openid**'
public/img/auth/openid_connect.svg
public/img/openid-16x16.png
public/assets/img/auth/openid_connect.svg
public/assets/img/openid-16x16.png
templates/user/auth/finalize_openid.tmpl
templates/user/auth/signin_openid.tmpl
templates/user/auth/signup_openid_connect.tmpl

View File

@ -31,9 +31,9 @@ All global options can be placed at the command level.
- `--help`, `-h`: Show help text and exit. Optional.
- `--version`, `-v`: Show version and exit. Optional. (example: `Gitea version 1.1.0+218-g7b907ed built with: bindata, sqlite`).
- `--custom-path path`, `-C path`: Location of the Gitea custom folder. Optional. (default: `AppWorkPath`/custom or `$GITEA_CUSTOM`).
- `--config path`, `-c path`: Gitea configuration file path. Optional. (default: `custom`/conf/app.ini).
- `--work-path path`, `-w path`: Gitea `AppWorkPath`. Optional. (default: LOCATION_OF_GITEA_BINARY or `$GITEA_WORK_DIR`)
- `--work-path path`, `-w path`: Gitea's work path. Optional. (default: the binary's path or `$GITEA_WORK_DIR`)
- `--custom-path path`, `-C path`: Gitea's custom folder path. Optional. (default: `WorkPath`/custom or `$GITEA_CUSTOM`).
- `--config path`, `-c path`: Gitea configuration file path. Optional. (default: `CustomPath`/conf/app.ini).
NB: The defaults custom-path, config and work-path can also be
changed at build time (if preferred).
@ -108,6 +108,14 @@ Admin operations:
- `--all`, `-A`: Force a password change for all users
- `--exclude username`, `-e username`: Exclude the given user. Can be set multiple times.
- `--unset`: Revoke forced password change for the given users
- `generate-access-token`:
- Options:
- `--username value`, `-u value`: Username. Required.
- `--token-name value`, `-t value`: Token name. Required.
- `--scopes value`: Comma-separated list of scopes. Scopes follow the format `[read|write]:<block>` or `all` where `<block>` is one of the available visual groups you can see when opening the API page showing the available routes (for example `repo`).
- Examples:
- `gitea admin user generate-access-token --username myname --token-name mytoken`
- `gitea admin user generate-access-token --help`
- `regenerate`
- Options:
- `hooks`: Regenerate Git Hooks for all repositories

View File

@ -44,28 +44,27 @@ reported as part of the default configuration when running `gitea --help` or on
- _`AppPath`_: This is the absolute path of the running gitea binary.
- _`AppWorkPath`_: This refers to "working path" of the `gitea` binary. It is determined by using the first set thing in the following hierarchy:
- The `WORK_PATH` option in `app.ini`
- The `--work-path` flag passed to the binary
- 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 directory of the _`AppPath`_
- Otherwise, it defaults to the directory of the _`AppPath`_
- 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:
- The `--custom-path` flag passed to the binary
- The environment variable `$GITEA_CUSTOM`
- A built-in value set at build time (see building from source)
- Otherwise it defaults to _`AppWorkPath`_`/custom`
- Otherwise, it defaults to _`AppWorkPath`_`/custom`
- If any of the above are relative paths then they are made absolute against the
the directory of the _`AppWorkPath`_
- _`CustomConf`_: This is the path to the `app.ini` file.
- The `--config` flag passed to the binary
- A built-in value set at build time (see building from source)
- Otherwise it defaults to _`CustomPath`_`/conf/app.ini`
- If any of the above are relative paths then they are made absolute against the
the directory of the _`CustomPath`_
- Otherwise, it defaults to _`CustomPath`_`/conf/app.ini`
- If any of the above are relative paths then they are made absolute against the directory of the _`CustomPath`_
In addition there is _`StaticRootPath`_ which can be set as a built-in at build time, but will otherwise default to _`AppWorkPath`_
In addition, there is _`StaticRootPath`_ which can be set as a built-in at build time, but will otherwise default to _`AppWorkPath`_
## Overall (`DEFAULT`)
@ -74,6 +73,7 @@ In addition there is _`StaticRootPath`_ which can be set as a built-in at build
This should be a dedicated system (non-user) account. Setting this incorrectly will cause Gitea
to not start.
- `RUN_MODE`: **prod**: Application run mode, affects performance and debugging: `dev` or `prod`, default is `prod`. Mode `dev` makes Gitea easier to develop and debug, values other than `dev` are treated as `prod` which is for production use.
- `WORK_PATH`: **_the-work-path_**: The working directory, see the comment of AppWorkPath above.
## Repository (`repository`)
@ -224,9 +224,9 @@ The following configuration set `Content-Type: application/vnd.android.package-a
- `MAX_DISPLAY_FILE_SIZE`: **8388608**: Max size of files to be displayed (default is 8MiB)
- `REACTIONS`: All available reactions users can choose on issues/prs and comments
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
For custom reactions, add a tightly cropped square image to public/assets/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/assets/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.
@ -336,7 +336,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a
- `SSH_LISTEN_PORT`: **%(SSH\_PORT)s**: Port for the built-in SSH server.
- `SSH_ROOT_PATH`: **~/.ssh**: Root path of SSH directory.
- `SSH_CREATE_AUTHORIZED_KEYS_FILE`: **true**: Gitea will create a authorized_keys file by default when it is not using the internal ssh server. If you intend to use the AuthorizedKeysCommand functionality then you should turn this off.
- `SSH_AUTHORIZED_KEYS_BACKUP`: **true**: Enable SSH Authorized Key Backup when rewriting all keys, default is true.
- `SSH_AUTHORIZED_KEYS_BACKUP`: **false**: Enable SSH Authorized Key Backup when rewriting all keys, default is false.
- `SSH_TRUSTED_USER_CA_KEYS`: **\<empty\>**: Specifies the public keys of certificate authorities that are trusted to sign user certificates for authentication. Multiple keys should be comma separated. E.g.`ssh-<algorithm> <key>` or `ssh-<algorithm> <key1>, ssh-<algorithm> <key2>`. For more information see `TrustedUserCAKeys` in the sshd config man pages. When empty no file will be created and `SSH_AUTHORIZED_PRINCIPALS_ALLOW` will default to `off`.
- `SSH_TRUSTED_USER_CA_KEYS_FILENAME`: **`RUN_USER`/.ssh/gitea-trusted-user-ca-keys.pem**: Absolute path of the `TrustedUserCaKeys` file Gitea will manage. If you're running your own ssh server and you want to use the Gitea managed file you'll also need to modify your sshd_config to point to this file. The official docker image will automatically work without further configuration.
- `SSH_AUTHORIZED_PRINCIPALS_ALLOW`: **off** or **username, email**: \[off, username, email, anything\]: Specify the principals values that users are allowed to use as principal. When set to `anything` no checks are done on the principal string. When set to `off` authorized principal are not allowed to be set.
@ -368,6 +368,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a
- `LFS_START_SERVER`: **false**: Enables Git LFS support.
- `LFS_CONTENT_PATH`: **%(APP_DATA_PATH)s/lfs**: Default LFS content path. (if it is on local storage.) **DEPRECATED** use settings in `[lfs]`.
- `LFS_JWT_SECRET`: **\<empty\>**: LFS authentication secret, change this a unique string.
- `LFS_JWT_SECRET_URI`: **\<empty\>**: Instead of defining LFS_JWT_SECRET in the configuration, this configuration option can be used to give Gitea a path to a file that contains the secret (example value: `file:/etc/gitea/lfs_jwt_secret`)
- `LFS_HTTP_AUTH_EXPIRY`: **24h**: LFS authentication validity period in time.Duration, pushes taking longer than this may fail.
- `LFS_MAX_FILE_SIZE`: **0**: Maximum allowed LFS file size in bytes (Set to 0 for no limit).
- `LFS_LOCKS_PAGING_NUM`: **50**: Maximum number of LFS Locks returned per page.
@ -1097,6 +1098,7 @@ This section only does "set" config, a removed config key from this section won'
- `INVALIDATE_REFRESH_TOKENS`: **false**: Check if refresh token has already been used
- `JWT_SIGNING_ALGORITHM`: **RS256**: Algorithm used to sign OAuth2 tokens. Valid values: \[`HS256`, `HS384`, `HS512`, `RS256`, `RS384`, `RS512`, `ES256`, `ES384`, `ES512`\]
- `JWT_SECRET`: **\<empty\>**: OAuth2 authentication secret for access and refresh tokens, change this to a unique string. This setting is only needed if `JWT_SIGNING_ALGORITHM` is set to `HS256`, `HS384` or `HS512`.
- `JWT_SECRET_URI`: **\<empty\>**: Instead of defining JWT_SECRET in the configuration, this configuration option can be used to give Gitea a path to a file that contains the secret (example value: `file:/etc/gitea/oauth2_jwt_secret`)
- `JWT_SIGNING_PRIVATE_KEY_FILE`: **jwt/private.pem**: Private key file path used to sign OAuth2 tokens. The path is relative to `APP_DATA_PATH`. This setting is only needed if `JWT_SIGNING_ALGORITHM` is set to `RS256`, `RS384`, `RS512`, `ES256`, `ES384` or `ES512`. The file must contain a RSA or ECDSA private key in the PKCS8 format. If no key exists a 4096 bit key will be created for you.
- `MAX_TOKEN_LENGTH`: **32767**: Maximum length of token/cookie to accept from OAuth2 provider
@ -1376,39 +1378,22 @@ PROXY_HOSTS = *.github.com
## Actions (`actions`)
- `ENABLED`: **false**: Enable/Disable actions capabilities
- `DEFAULT_ACTIONS_URL`: **https://gitea.com**: Default address to get action plugins, e.g. the default value means downloading from "<https://gitea.com/actions/checkout>" for "uses: actions/checkout@v3"
- `DEFAULT_ACTIONS_URL`: **github**: Default platform to get action plugins, `github` for `https://github.com`, `self` for the current Gitea instance.
- `STORAGE_TYPE`: **local**: Storage type for actions logs, `local` for local disk or `minio` for s3 compatible object storage service, default is `local` or other name defined with `[storage.xxx]`
- `MINIO_BASE_PATH`: **actions_log/**: Minio base path on the bucket only available when STORAGE_TYPE is `minio`
`DEFAULT_ACTIONS_URL` indicates where should we find the relative path action plugin. i.e. when use an action in a workflow file like
`DEFAULT_ACTIONS_URL` indicates where the Gitea Actions runners should find the actions with relative path.
For example, `uses: actions/checkout@v3` means `https://github.com/actions/checkout@v3` since the value of `DEFAULT_ACTIONS_URL` is `github`.
And it can be changed to `self` to make it `root_url_of_your_gitea/actions/checkout@v3`.
```yaml
name: versions
on:
push:
branches:
- main
- releases/*
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
```
Please note that using `self` is not recommended for most cases, as it could make names globally ambiguous.
Additionally, it requires you to mirror all the actions you need to your Gitea instance, which may not be worth it.
Therefore, please use `self` only if you understand what you are doing.
Now we need to know how to get actions/checkout, this configuration is the default git server to get it. That means we will get the repository via git clone ${DEFAULT_ACTIONS_URL}/actions/checkout and fetch tag v3.
To help people who don't want to mirror these actions in their git instances, the default value is https://gitea.com
To help people run actions totally in their network, they can change the value and copy all necessary action repositories into their git server.
Of course we should support the form in future PRs like
```yaml
steps:
- uses: gitea.com/actions/checkout@v3
```
although Github don't support this form.
In earlier versions (<= 1.19), `DEFAULT_ACTIONS_URL` cound be set to any custom URLs like `https://gitea.com` or `http://your-git-server,https://gitea.com`, and the default value was `https://gitea.com`.
However, later updates removed those options, and now the only options are `github` and `self`, with the default value being `github`.
However, if you want to use actions from other git server, you can use a complete URL in `uses` field, it's supported by Gitea (but not GitHub).
Like `uses: https://gitea.com/actions/checkout@v3` or `uses: http://your-git-server/actions/checkout@v3`.
## Other (`other`)

View File

@ -18,7 +18,7 @@ menu:
# Customizing Gitea
Customizing Gitea is typically done using the `CustomPath` folder - by default this is
the `custom` folder from the running directory, but may be different if your build has
the `custom` folder from the working directory (WorkPath), but may be different if your build has
set this differently. This is the central place to override configuration settings,
templates, etc. You can check the `CustomPath` using `gitea help`. You can also find
the path on the _Configuration_ tab in the _Site Administration_ page. You can override
@ -56,21 +56,22 @@ is set under the "Configuration" tab on the site administration page.
To make Gitea serve custom public files (like pages and images), use the folder
`$GITEA_CUSTOM/public/` as the webroot. Symbolic links will be followed.
At the moment, only files in the `public/assets/` folder are served.
For example, a file `image.png` stored in `$GITEA_CUSTOM/public/`, can be accessed with
For example, a file `image.png` stored in `$GITEA_CUSTOM/public/assets/`, can be accessed with
the url `http://gitea.domain.tld/assets/image.png`.
## Changing the logo
To build a custom logo and/or favicon clone the Gitea source repository, replace `assets/logo.svg` and/or `assets/favicon.svg` and run
`make generate-images`. `assets/favicon.svg` is used for the favicon only. This will update below output files which you can then place in `$GITEA_CUSTOM/public/img` on your server:
`make generate-images`. `assets/favicon.svg` is used for the favicon only. This will update below output files which you can then place in `$GITEA_CUSTOM/public/assets/img` on your server:
- `public/img/logo.svg` - Used for site icon, app icon
- `public/img/logo.png` - Used for Open Graph
- `public/img/avatar_default.png` - Used as the default avatar image
- `public/img/apple-touch-icon.png` - Used on iOS devices for bookmarks
- `public/img/favicon.svg` - Used for favicon
- `public/img/favicon.png` - Used as fallback for browsers that don't support SVG favicons
- `public/assets/img/logo.svg` - Used for site icon, app icon
- `public/assets/img/logo.png` - Used for Open Graph
- `public/assets/img/avatar_default.png` - Used as the default avatar image
- `public/assets/img/apple-touch-icon.png` - Used on iOS devices for bookmarks
- `public/assets/img/favicon.svg` - Used for favicon
- `public/assets/img/favicon.png` - Used as fallback for browsers that don't support SVG favicons
In case the source image is not in vector format, you can attempt to convert a raster image using tools like [this](https://www.aconvert.com/image/png-to-svg/).
@ -102,7 +103,7 @@ Dont forget to restart your Gitea to apply the changes.
If all you want is to add extra links to the top navigation bar or footer, or extra tabs to the repository view, you can put them in `extra_links.tmpl` (links added to the navbar), `extra_links_footer.tmpl` (links added to the left side of footer), and `extra_tabs.tmpl` inside your `$GITEA_CUSTOM/templates/custom/` directory.
For instance, let's say you are in Germany and must add the famously legally-required "Impressum"/about page, listing who is responsible for the site's content:
just place it under your "$GITEA_CUSTOM/public/" directory (for instance `$GITEA_CUSTOM/public/impressum.html`) and put a link to it in either `$GITEA_CUSTOM/templates/custom/extra_links.tmpl` or `$GITEA_CUSTOM/templates/custom/extra_links_footer.tmpl`.
just place it under your "$GITEA_CUSTOM/public/assets/" directory (for instance `$GITEA_CUSTOM/public/assets/impressum.html`) and put a link to it in either `$GITEA_CUSTOM/templates/custom/extra_links.tmpl` or `$GITEA_CUSTOM/templates/custom/extra_links_footer.tmpl`.
To match the current style, the link should have the class name "item", and you can use `{{AppSubUrl}}` to get the base URL:
`<a class="item" href="{{AppSubUrl}}/assets/impressum.html">Impressum</a>`
@ -132,7 +133,7 @@ The data is encoded and sent to the PlantUML server which generates the picture.
demo server at http://www.plantuml.com/plantuml, but if you (or your users) have sensitive data you
can set up your own [PlantUML server](https://plantuml.com/server) instead. To set up PlantUML rendering,
copy JavaScript files from https://gitea.com/davidsvantesson/plantuml-code-highlight and put them in your
`$GITEA_CUSTOM/public` folder. Then add the following to `custom/footer.tmpl`:
`$GITEA_CUSTOM/public/assets/` folder. Then add the following to `custom/footer.tmpl`:
```html
<script>
@ -204,7 +205,7 @@ You can display STL file directly in Gitea by adding:
to the file `templates/custom/footer.tmpl`
You also need to download the content of the library [Madeleine.js](https://github.com/beige90/Madeleine.js) and place it under `$GITEA_CUSTOM/public/` folder.
You also need to download the content of the library [Madeleine.js](https://github.com/beige90/Madeleine.js) and place it under `$GITEA_CUSTOM/public/assets/` folder.
You should end-up with a folder structure similar to:
@ -212,7 +213,8 @@ You should end-up with a folder structure similar to:
$GITEA_CUSTOM/templates
-- custom
`-- footer.tmpl
$GITEA_CUSTOM/public
$GITEA_CUSTOM/public/assets/
-- Madeleine.js
|-- LICENSE
|-- README.md
@ -366,7 +368,7 @@ The list of themes a user can choose from can be configured with the `THEMES` va
To make a custom theme available to all users:
1. Add a CSS file to `$GITEA_CUSTOM/public/css/theme-<theme-name>.css`.
1. Add a CSS file to `$GITEA_CUSTOM/public/assets/css/theme-<theme-name>.css`.
The value of `$GITEA_CUSTOM` of your instance can be queried by calling `gitea help` and looking up the value of "CustomPath".
2. Add `<theme-name>` to the comma-separated list of setting `THEMES` in `app.ini`

View File

@ -43,10 +43,7 @@ For documentation about each of the variables available, refer to the
## Gitea files
- `GITEA_WORK_DIR`: Absolute path of working directory.
- `GITEA_CUSTOM`: Gitea uses `GITEA_WORK_DIR`/custom folder by default. Use this variable
to change _custom_ directory.
- `GOGS_WORK_DIR`: Deprecated, use `GITEA_WORK_DIR`
- `GOGS_CUSTOM`: Deprecated, use `GITEA_CUSTOM`
- `GITEA_CUSTOM`: Gitea uses `WorkPath`/custom folder by default. Use this variable to change _custom_ directory.
## Operating system specifics

View File

@ -191,7 +191,7 @@ And so you could write some CSS:
}
```
Add your stylesheet to your custom directory e.g `custom/public/css/my-style-XXXXX.css` and import it using a custom header file `custom/templates/custom/header.tmpl`:
Add your stylesheet to your custom directory e.g `custom/public/assets/css/my-style-XXXXX.css` and import it using a custom header file `custom/templates/custom/header.tmpl`:
```html
<link rel="stylesheet" href="{{AppSubUrl}}/assets/css/my-style-XXXXX.css" />

View File

@ -218,7 +218,7 @@ REPO_INDEXER_CONN_STR = http://elastic:changeme@localhost:9200
### Building and adding SVGs
SVG icons are built using the `make svg` target which compiles the icon sources defined in `build/generate-svg.js` into the output directory `public/img/svg`. Custom icons can be added in the `web_src/svg` directory.
SVG icons are built using the `make svg` target which compiles the icon sources defined in `build/generate-svg.js` into the output directory `public/assets/img/svg`. Custom icons can be added in the `web_src/svg` directory.
### Building the Logo

View File

@ -59,11 +59,12 @@ https://github.com/loganinak/MigrateGitlabToGogs
## Where does Gitea store what file
- _`AppWorkPath`_
- The `--work-path` flag
- The `WORK_PATH` option in `app.ini`
- Else the `--work-path` flag
- Else Environment variable `GITEA_WORK_DIR`
- Else a built-in value set at build time
- Else the directory that contains the Gitea binary
- `%(APP_DATA_PATH)` (default for database, indexers, etc.)
- `AppDataPath` (default for database, indexers, etc.)
- `APP_DATA_PATH` from `app.ini`
- Else _`AppWorkPath`_`/data`
- _`CustomPath`_ (custom templates)
@ -112,9 +113,6 @@ Gitea's custom templates must be added to the correct location or Gitea will not
The correct path for the template(s) will be relative to the `CustomPath`
1. To find `CustomPath`, look for Custom File Root Path in Site Administration -> Configuration
If that doesn't exist, you can try `echo $GITEA_CUSTOM`
2. If you are still unable to find a path, the default can be [calculated above](#where-does-gitea-store-what-file)
3. Once you have figured out the correct custom path, you can refer to the [customizing Gitea]({{< relref "doc/administration/customizing-gitea.en-us.md" >}}) page to add your template to the correct location.
@ -192,7 +190,7 @@ To add your own theme, currently the only way is to provide a complete theme (no
As an example, let's say our theme is `arc-blue` (this is a real theme, and can be found [in this issue](https://github.com/go-gitea/gitea/issues/6011))
Name the `.css` file `theme-arc-blue.css` and add it to your custom folder in `custom/public/css`
Name the `.css` file `theme-arc-blue.css` and add it to your custom folder in `custom/public/assets/css`
Allow users to use it by adding `arc-blue` to the list of `THEMES` in your `app.ini`

View File

@ -67,7 +67,7 @@ sudo chown 1000:1000 config/ data/
> If you don't give the volume correct permissions, the container may not start.
For a stable release you could use `:latest-rootless`, `:1-rootless` or specify a certain release like `:{{< version >}}-rootless`, but if you'd like to use the latest development version then `:dev-rootless` would be an appropriate tag. If you'd like to run the latest commit from a release branch you can use the `:1.x-dev-rootless` tag, where x is the minor version of Gitea. (e.g. `:1.16-dev-rootless`)
For a stable release you could use `:latest-rootless`, `:1-rootless` or specify a certain release like `:{{< version >}}-rootless`, but if you'd like to use the latest development version then `:nightly-rootless` would be an appropriate tag. If you'd like to run the latest commit from a release branch you can use the `:1.x-nightly-rootless` tag, where x is the minor version of Gitea. (e.g. `:1.16-nightly-rootless`)
## Custom port
@ -119,7 +119,7 @@ services:
- /etc/localtime:/etc/localtime:ro
ports:
- "3000:3000"
- "222:22"
- "2222:2222"
+ depends_on:
+ - db
+
@ -288,7 +288,7 @@ docker-compose up -d
In addition to the environment variables above, any settings in `app.ini` can be set
or overridden with an environment variable of the form: `GITEA__SECTION_NAME__KEY_NAME`.
These settings are applied each time the docker container starts.
These settings are applied each time the docker container starts, and won't be passed into Gitea's sub-processes.
Full information [here](https://github.com/go-gitea/gitea/tree/main/contrib/environment-to-ini).
These environment variables can be passed to the docker container in `docker-compose.yml`.

View File

@ -36,7 +36,7 @@ image as a service. Since there is no database available, one can be initialized
Create a directory like `gitea` and paste the following content into a file named `docker-compose.yml`.
Note that the volume should be owned by the user/group with the UID/GID specified in the config file.
If you don't give the volume correct permissions, the container may not start.
For a stable release you can use `:latest`, `:1` or specify a certain release like `:{{< version >}}`, but if you'd like to use the latest development version of Gitea then you could use the `:dev` tag. If you'd like to run the latest commit from a release branch you can use the `:1.x-dev` tag, where x is the minor version of Gitea. (e.g. `:1.16-dev`)
For a stable release you can use `:latest`, `:1` or specify a certain release like `:{{< version >}}`, but if you'd like to use the latest development version of Gitea then you could use the `:nightly` tag. If you'd like to run the latest commit from a release branch you can use the `:1.x-nightly` tag, where x is the minor version of Gitea. (e.g. `:1.16-nightly`)
```yaml
version: "3"
@ -289,7 +289,7 @@ docker-compose up -d
In addition to the environment variables above, any settings in `app.ini` can be set
or overridden with an environment variable of the form: `GITEA__SECTION_NAME__KEY_NAME`.
These settings are applied each time the docker container starts.
These settings are applied each time the docker container starts, and won't be passed into Gitea's sub-processes.
Full information [here](https://github.com/go-gitea/gitea/tree/master/contrib/environment-to-ini).
These environment variables can be passed to the docker container in `docker-compose.yml`.

View File

@ -31,7 +31,7 @@ Like `uses: https://github.com/actions/checkout@v3` or `uses: http://your_gitea.
### Actions written in Go
Gitea Actions supports writing actions in Go.
See [Creating Go Actions](https://blog.gitea.io/2023/04/creating-go-actions/).
See [Creating Go Actions](https://blog.gitea.com/creating-go-actions/).
## Unsupported workflows syntax

View File

@ -31,7 +31,7 @@ Gitea Actions支持通过URL绝对路径定义actions这意味着您可以使
### 使用Go编写Actions
Gitea Actions支持使用Go编写Actions。
请参阅[创建Go Actions](https://blog.gitea.io/2023/04/creating-go-actions/)。
请参阅[创建Go Actions](https://blog.gitea.com/creating-go-actions/)。
## 不支持的工作流语法

View File

@ -164,3 +164,23 @@ Although we would like to provide more options, our limited manpower means that
However, both Gitea and act runner are completely open source, so anyone can create a new/better implementation.
We support your choice, no matter how you decide.
In case you fork act runner to create your own version: Please contribute the changes back if you can and if you think your changes will help others as well.
## What workflow trigger events does Gitea support?
All events listed in this table are supported events and are compatible with GitHub.
For events supported only by GitHub, see GitHub's [documentation](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows).
| trigger event | activity types |
|-----------------------------|--------------------------------------------------------------------------------------------------------------------------|
| create | not applicable |
| delete | not applicable |
| fork | not applicable |
| gollum | not applicable |
| push | not applicable |
| issues | `opened`, `edited`, `closed`, `reopened`, `assigned`, `unassigned`, `milestoned`, `demilestoned`, `labeled`, `unlabeled` |
| issue_comment | `created`, `edited`, `deleted` |
| pull_request | `opened`, `edited`, `closed`, `reopened`, `assigned`, `unassigned`, `synchronize`, `labeled`, `unlabeled` |
| pull_request_review | `submitted`, `edited` |
| pull_request_review_comment | `created`, `edited` |
| release | `published`, `edited` |
| registry_package | `published` |

View File

@ -164,3 +164,23 @@ defaults:
然而无论您如何决定Gitea 和act runner都是完全开源的所以任何人都可以创建一个新的/更好的实现。
我们支持您的选择,无论您如何决定。
如果您选择分支act runner来创建自己的版本请在您认为您的更改对其他人也有帮助的情况下贡献这些更改。
## Gitea 支持哪些工作流触发事件?
表格中列出的所有事件都是支持的,并且与 GitHub 兼容。
对于仅 GitHub 支持的事件,请参阅 GitHub 的[文档](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows)。
| 触发事件 | 活动类型 |
|-----------------------------|--------------------------------------------------------------------------------------------------------------------------|
| create | 不适用 |
| delete | 不适用 |
| fork | 不适用 |
| gollum | 不适用 |
| push | 不适用 |
| issues | `opened`, `edited`, `closed`, `reopened`, `assigned`, `unassigned`, `milestoned`, `demilestoned`, `labeled`, `unlabeled` |
| issue_comment | `created`, `edited`, `deleted` |
| pull_request | `opened`, `edited`, `closed`, `reopened`, `assigned`, `unassigned`, `synchronize`, `labeled`, `unlabeled` |
| pull_request_review | `submitted`, `edited` |
| pull_request_review_comment | `created`, `edited` |
| release | `published`, `edited` |
| registry_package | `published` |

View File

@ -44,7 +44,7 @@ The following package managers are currently supported:
| [NuGet]({{< relref "doc/usage/packages/nuget.en-us.md" >}}) | .NET | `nuget` |
| [Pub]({{< relref "doc/usage/packages/pub.en-us.md" >}}) | Dart | `dart`, `flutter` |
| [PyPI]({{< relref "doc/usage/packages/pypi.en-us.md" >}}) | Python | `pip`, `twine` |
| [RPM]({{< relref "doc/usage/packages/rpm.en-us.md" >}}) | - | `yum`, `dnf` |
| [RPM]({{< relref "doc/usage/packages/rpm.en-us.md" >}}) | - | `yum`, `dnf`, `zypper` |
| [RubyGems]({{< relref "doc/usage/packages/rubygems.en-us.md" >}}) | Ruby | `gem`, `Bundler` |
| [Swift]({{< relref "doc/usage/packages/rubygems.en-us.md" >}}) | Swift | `swift` |
| [Vagrant]({{< relref "doc/usage/packages/vagrant.en-us.md" >}}) | - | `vagrant` |

View File

@ -44,7 +44,7 @@ menu:
| [NuGet]({{< relref "doc/usage/packages/nuget.zh-cn.md" >}}) | .NET | `nuget` |
| [Pub]({{< relref "doc/usage/packages/pub.zh-cn.md" >}}) | Dart | `dart`, `flutter` |
| [PyPI]({{< relref "doc/usage/packages/pypi.zh-cn.md" >}}) | Python | `pip`, `twine` |
| [RPM]({{< relref "doc/usage/packages/rpm.zh-cn.md" >}}) | - | `yum`, `dnf` |
| [RPM]({{< relref "doc/usage/packages/rpm.zh-cn.md" >}}) | - | `yum`, `dnf`, `zypper` |
| [RubyGems]({{< relref "doc/usage/packages/rubygems.zh-cn.md" >}}) | Ruby | `gem`, `Bundler` |
| [Swift]({{< relref "doc/usage/packages/rubygems.zh-cn.md" >}}) | Swift | `swift` |
| [Vagrant]({{< relref "doc/usage/packages/vagrant.zh-cn.md" >}}) | - | `vagrant` |

View File

@ -22,7 +22,7 @@ Publish [RPM](https://rpm.org/) packages for your user or organization.
## Requirements
To work with the RPM registry, you need to use a package manager like `yum` or `dnf` to consume packages.
To work with the RPM registry, you need to use a package manager like `yum`, `dnf` or `zypper` to consume packages.
The following examples use `dnf`.
@ -79,7 +79,7 @@ The server responds with the following HTTP Status codes.
## Delete a package
To delete a Debian package perform a HTTP DELETE operation. This will delete the package version too if there is no file left.
To delete an RPM package perform a HTTP DELETE operation. This will delete the package version too if there is no file left.
```
DELETE https://gitea.example.com/api/packages/{owner}/rpm/{package_name}/{package_version}/{architecture}

View File

@ -22,7 +22,7 @@ menu:
## 要求
要使用RPM注册表您需要使用像 `yum``dnf` 这样的软件包管理器来消费软件包。
要使用RPM注册表您需要使用像 `yum`, `dnf``zypper` 这样的软件包管理器来消费软件包。
以下示例使用 `dnf`

View File

@ -11,7 +11,7 @@ draft: false
# What is Gitea?
Gitea is a painless self-hosted all-in-one software development service, it includes Git hosting, code review, team collaboration, package registry and CI/CD. It is similar to GitHub, Bitbucket and GitLab.
Gitea was forked from [Gogs](http://gogs.io) originally and almost all the code has been changed. See the [Gitea Announcement](https://blog.gitea.io/2016/12/welcome-to-gitea/)
Gitea was forked from [Gogs](http://gogs.io) originally and almost all the code has been changed. See the [Gitea Announcement](https://blog.gitea.com/welcome-to-gitea/)
blog post to read about the justification for a fork.
## Purpose

View File

@ -10,7 +10,7 @@ draft: false
# A propos de Gitea
Gitea est un service Git auto-hébergé très simple à installer et à utiliser. Il est similaire à GitHub, Bitbucket ou Gitlab. Le développement initial provient sur [Gogs] (http://gogs.io), mais nous l'avons forké puis renommé Gitea. Si vous souhaitez en savoir plus sur les raisons pour lesquelles nous avons fait cela, lisez [cette publication] (https://blog.gitea.io/2016/12/welcome-to-gitea/) sur le blog.
Gitea est un service Git auto-hébergé très simple à installer et à utiliser. Il est similaire à GitHub, Bitbucket ou Gitlab. Le développement initial provient sur [Gogs] (http://gogs.io), mais nous l'avons forké puis renommé Gitea. Si vous souhaitez en savoir plus sur les raisons pour lesquelles nous avons fait cela, lisez [cette publication] (https://blog.gitea.com/welcome-to-gitea/) sur le blog.
## Objectif

View File

@ -10,7 +10,7 @@ draft: false
# 关于Gitea
Gitea 是一个自己托管的Git服务程序。他和GitHub, Bitbucket or Gitlab等比较类似。他是从 [Gogs](http://gogs.io) 发展而来不过我们已经Fork并且命名为Gitea。对于我们Fork的原因可以看 [这里](https://blog.gitea.io/2016/12/welcome-to-gitea/)。
Gitea 是一个自己托管的Git服务程序。他和GitHub, Bitbucket or Gitlab等比较类似。他是从 [Gogs](http://gogs.io) 发展而来不过我们已经Fork并且命名为Gitea。对于我们Fork的原因可以看 [这里](https://blog.gitea.com/welcome-to-gitea/)。
## 目标

View File

@ -11,7 +11,7 @@ draft: false
# 關於 Gitea
Gitea 是一個可自行託管的 Git 服務。你可以拿 GitHub、Bitbucket 或 Gitlab 來比較看看。
Gitea 是從 [Gogs](http://gogs.io) Fork 出來的,請閱讀部落格文章 [Gitea 公告](https://blog.gitea.io/2016/12/welcome-to-gitea/)以了解我們 Fork 的理由。
Gitea 是從 [Gogs](http://gogs.io) Fork 出來的,請閱讀部落格文章 [Gitea 公告](https://blog.gitea.com/welcome-to-gitea/)以了解我們 Fork 的理由。
## 目標

218
go.mod
View File

@ -3,26 +3,26 @@ module code.gitea.io/gitea
go 1.20
require (
code.gitea.io/actions-proto-go v0.3.0
code.gitea.io/actions-proto-go v0.3.1
code.gitea.io/gitea-vet v0.2.2
code.gitea.io/sdk/gitea v0.15.1
codeberg.org/gusted/mcaptcha v0.0.0-20220723083913-4f3072e1d570
gitea.com/go-chi/binding v0.0.0-20230415142243-04b515c6d669
gitea.com/go-chi/cache v0.2.0
gitea.com/go-chi/captcha v0.0.0-20230415143339-2c0754df4384
gitea.com/go-chi/session v0.0.0-20230415140235-3182bcc14852
gitea.com/go-chi/session v0.0.0-20230613035928-39541325faa3
gitea.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96
gitea.com/lunny/levelqueue v0.4.2-0.20220729054728-f020868cc2f7
github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358
github.com/NYTimes/gziphandler v1.1.1
github.com/PuerkitoBio/goquery v1.8.1
github.com/alecthomas/chroma/v2 v2.7.0
github.com/alecthomas/chroma/v2 v2.8.0
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb
github.com/blevesearch/bleve/v2 v2.3.7
github.com/bufbuild/connect-go v1.7.0
github.com/buildkite/terminal-to-html/v3 v3.7.0
github.com/caddyserver/certmagic v0.17.2
github.com/blevesearch/bleve/v2 v2.3.8
github.com/bufbuild/connect-go v1.9.0
github.com/buildkite/terminal-to-html/v3 v3.8.0
github.com/caddyserver/certmagic v0.19.0
github.com/chi-middleware/proxy v1.1.1
github.com/denisenkom/go-mssqldb v0.12.3
github.com/dimiro1/reply v0.0.0-20200315094148-d0136a4c9e21
@ -37,143 +37,141 @@ require (
github.com/felixge/fgprof v0.9.3
github.com/fsnotify/fsnotify v1.6.0
github.com/gliderlabs/ssh v0.3.5
github.com/go-ap/activitypub v0.0.0-20230331173947-f5b96d9450d4
github.com/go-ap/activitypub v0.0.0-20230626173101-16e4163853e3
github.com/go-ap/jsonld v0.0.0-20221030091449-f2a191312c73
github.com/go-chi/chi/v5 v5.0.8
github.com/go-chi/cors v1.2.1
github.com/go-enry/go-enry/v2 v2.8.4
github.com/go-fed/httpsig v1.1.1-0.20201223112313-55836744818e
github.com/go-git/go-billy/v5 v5.4.1
github.com/go-git/go-git/v5 v5.6.1
github.com/go-ldap/ldap/v3 v3.4.4
github.com/go-git/go-git/v5 v5.7.0
github.com/go-ldap/ldap/v3 v3.4.5
github.com/go-sql-driver/mysql v1.7.1
github.com/go-swagger/go-swagger v0.30.4
github.com/go-swagger/go-swagger v0.30.5
github.com/go-testfixtures/testfixtures/v3 v3.9.0
github.com/go-webauthn/webauthn v0.8.2
github.com/go-webauthn/webauthn v0.8.6
github.com/gobwas/glob v0.2.3
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f
github.com/gogs/cron v0.0.0-20171120032916-9f6c956d3e14
github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/google/go-github/v53 v53.0.0
github.com/google/pprof v0.0.0-20230502171905-255e3b9b56de
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/google/go-github/v53 v53.2.0
github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8
github.com/google/uuid v1.3.0
github.com/gorilla/feeds v1.1.1
github.com/gorilla/sessions v1.2.1
github.com/hashicorp/go-version v1.6.0
github.com/hashicorp/golang-lru v0.6.0
github.com/hashicorp/golang-lru/v2 v2.0.4
github.com/huandu/xstrings v1.4.0
github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056
github.com/jhillyerd/enmime v0.11.1
github.com/jhillyerd/enmime v1.0.0
github.com/json-iterator/go v1.1.12
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/keybase/go-crypto v0.0.0-20200123153347-de78d2cb44f4
github.com/klauspost/compress v1.16.5
github.com/klauspost/cpuid/v2 v2.2.4
github.com/klauspost/compress v1.16.7
github.com/klauspost/cpuid/v2 v2.2.5
github.com/lib/pq v1.10.9
github.com/markbates/goth v1.77.0
github.com/mattn/go-isatty v0.0.18
github.com/mattn/go-sqlite3 v1.14.16
github.com/meilisearch/meilisearch-go v0.24.0
github.com/mattn/go-isatty v0.0.19
github.com/mattn/go-sqlite3 v1.14.17
github.com/meilisearch/meilisearch-go v0.25.0
github.com/mholt/archiver/v3 v3.5.1
github.com/microcosm-cc/bluemonday v1.0.24
github.com/minio/minio-go/v7 v7.0.52
github.com/minio/sha256-simd v1.0.0
github.com/microcosm-cc/bluemonday v1.0.25
github.com/minio/minio-go/v7 v7.0.60
github.com/minio/sha256-simd v1.0.1
github.com/msteinert/pam v1.1.0
github.com/nektos/act v0.2.45
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
github.com/niklasfasching/go-org v1.6.5
github.com/oliamb/cutter v0.2.2
github.com/nektos/act v0.2.48
github.com/niklasfasching/go-org v1.7.0
github.com/olivere/elastic/v7 v7.0.32
github.com/opencontainers/go-digest v1.0.0
github.com/opencontainers/image-spec v1.1.0-rc3
github.com/opencontainers/image-spec v1.1.0-rc4
github.com/pkg/errors v0.9.1
github.com/pquerna/otp v1.4.0
github.com/prometheus/client_golang v1.15.1
github.com/prometheus/client_golang v1.16.0
github.com/quasoft/websspi v1.1.2
github.com/redis/go-redis/v9 v9.0.4
github.com/redis/go-redis/v9 v9.0.5
github.com/santhosh-tekuri/jsonschema/v5 v5.3.0
github.com/sassoftware/go-rpmutils v0.2.0
github.com/sergi/go-diff v1.3.1
github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546
github.com/stretchr/testify v1.8.2
github.com/shurcooL/vfsgen v0.0.0-20230704071429-0000e147ea92
github.com/stretchr/testify v1.8.4
github.com/syndtr/goleveldb v1.0.0
github.com/tstranex/u2f v1.0.0
github.com/ulikunitz/xz v0.5.11
github.com/urfave/cli v1.22.13
github.com/xanzy/go-gitlab v0.83.0
github.com/urfave/cli v1.22.14
github.com/xanzy/go-gitlab v0.86.0
github.com/xeipuuv/gojsonschema v1.2.0
github.com/yohcop/openid-go v1.0.1
github.com/yuin/goldmark v1.5.4
github.com/yuin/goldmark-highlighting/v2 v2.0.0-20220924101305-151362477c87
github.com/yuin/goldmark-meta v1.1.0
golang.org/x/crypto v0.9.0
golang.org/x/image v0.7.0
golang.org/x/net v0.10.0
golang.org/x/oauth2 v0.8.0
golang.org/x/sys v0.8.0
golang.org/x/text v0.9.0
golang.org/x/tools v0.8.0
google.golang.org/grpc v1.53.0
google.golang.org/protobuf v1.30.0
golang.org/x/crypto v0.11.0
golang.org/x/image v0.9.0
golang.org/x/net v0.12.0
golang.org/x/oauth2 v0.10.0
golang.org/x/sys v0.10.0
golang.org/x/text v0.11.0
golang.org/x/tools v0.11.0
google.golang.org/grpc v1.56.2
google.golang.org/protobuf v1.31.0
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
gopkg.in/ini.v1 v1.67.0
gopkg.in/yaml.v3 v3.0.1
mvdan.cc/xurls/v2 v2.4.0
mvdan.cc/xurls/v2 v2.5.0
strk.kbt.io/projects/go/libravatar v0.0.0-20191008002943-06d1c002b251
xorm.io/builder v0.3.12
xorm.io/xorm v1.3.3-0.20230623150031-18f8e7a86c75
)
require (
cloud.google.com/go/compute v1.18.0 // indirect
cloud.google.com/go/compute v1.21.0 // indirect
cloud.google.com/go/compute/metadata v0.2.3 // indirect
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 // indirect
github.com/ClickHouse/ch-go v0.55.0 // indirect
github.com/ClickHouse/clickhouse-go/v2 v2.9.1 // indirect
github.com/DataDog/zstd v1.4.5 // indirect
github.com/ClickHouse/ch-go v0.57.0 // indirect
github.com/ClickHouse/clickhouse-go/v2 v2.10.1 // indirect
github.com/DataDog/zstd v1.5.5 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.2.0 // indirect
github.com/Masterminds/semver/v3 v3.2.1 // indirect
github.com/Masterminds/sprig/v3 v3.2.3 // indirect
github.com/Microsoft/go-winio v0.6.1 // indirect
github.com/ProtonMail/go-crypto v0.0.0-20230528122434-6f98819771a1 // indirect
github.com/RoaringBitmap/roaring v1.2.3 // indirect
github.com/ProtonMail/go-crypto v0.0.0-20230710112148-e01326fd72eb // indirect
github.com/RoaringBitmap/roaring v1.3.0 // indirect
github.com/acomagu/bufpipe v1.0.4 // indirect
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bits-and-blooms/bitset v1.7.0 // indirect
github.com/bits-and-blooms/bitset v1.8.0 // indirect
github.com/blevesearch/bleve_index_api v1.0.5 // indirect
github.com/blevesearch/geo v0.1.17 // indirect
github.com/blevesearch/go-porterstemmer v1.0.3 // indirect
github.com/blevesearch/gtreap v0.1.1 // indirect
github.com/blevesearch/mmap-go v1.0.4 // indirect
github.com/blevesearch/scorch_segment_api/v2 v2.1.4 // indirect
github.com/blevesearch/scorch_segment_api/v2 v2.1.5 // indirect
github.com/blevesearch/segment v0.9.1 // indirect
github.com/blevesearch/snowballstem v0.9.0 // indirect
github.com/blevesearch/upsidedown_store_api v1.0.2 // indirect
github.com/blevesearch/vellum v1.0.9 // indirect
github.com/blevesearch/zapx/v11 v11.3.7 // indirect
github.com/blevesearch/zapx/v12 v12.3.7 // indirect
github.com/blevesearch/zapx/v13 v13.3.7 // indirect
github.com/blevesearch/zapx/v14 v14.3.7 // indirect
github.com/blevesearch/zapx/v15 v15.3.10 // indirect
github.com/blevesearch/vellum v1.0.10 // indirect
github.com/blevesearch/zapx/v11 v11.3.9 // indirect
github.com/blevesearch/zapx/v12 v12.3.9 // indirect
github.com/blevesearch/zapx/v13 v13.3.9 // indirect
github.com/blevesearch/zapx/v14 v14.3.9 // indirect
github.com/blevesearch/zapx/v15 v15.3.12 // indirect
github.com/boombuler/barcode v1.0.1 // indirect
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect
github.com/bradfitz/gomemcache v0.0.0-20230611145640-acc696258285 // indirect
github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/cloudflare/circl v1.3.3 // indirect
github.com/couchbase/go-couchbase v0.0.0-20210224140812-5740cd35f448 // indirect
github.com/couchbase/gomemcached v0.1.2 // indirect
github.com/couchbase/goutils v0.0.0-20210118111533-e33d3ffb5401 // indirect
github.com/couchbase/go-couchbase v0.1.1 // indirect
github.com/couchbase/gomemcached v0.2.1 // indirect
github.com/couchbase/goutils v0.1.2 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dlclark/regexp2 v1.9.0 // indirect
github.com/emersion/go-sasl v0.0.0-20200509203442-7bfe0ed36a21 // indirect
github.com/dlclark/regexp2 v1.10.0 // indirect
github.com/emersion/go-sasl v0.0.0-20220912192320-0145f2c60ead // indirect
github.com/fatih/color v1.15.0 // indirect
github.com/felixge/httpsnoop v1.0.3 // indirect
github.com/fxamacker/cbor/v2 v2.4.0 // indirect
@ -182,27 +180,29 @@ require (
github.com/go-enry/go-oniguruma v1.2.1 // indirect
github.com/go-faster/city v1.0.1 // indirect
github.com/go-faster/errors v0.6.1 // indirect
github.com/go-git/gcfg v1.5.0 // indirect
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
github.com/go-openapi/analysis v0.21.4 // indirect
github.com/go-openapi/errors v0.20.3 // indirect
github.com/go-openapi/errors v0.20.4 // indirect
github.com/go-openapi/inflect v0.19.0 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.20.0 // indirect
github.com/go-openapi/jsonpointer v0.19.6 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/loads v0.21.2 // indirect
github.com/go-openapi/runtime v0.25.0 // indirect
github.com/go-openapi/spec v0.20.8 // indirect
github.com/go-openapi/strfmt v0.21.3 // indirect
github.com/go-openapi/swag v0.22.3 // indirect
github.com/go-openapi/validate v0.22.0 // indirect
github.com/go-webauthn/revoke v0.1.9 // indirect
github.com/go-openapi/runtime v0.26.0 // indirect
github.com/go-openapi/spec v0.20.9 // indirect
github.com/go-openapi/strfmt v0.21.7 // indirect
github.com/go-openapi/swag v0.22.4 // indirect
github.com/go-openapi/validate v0.22.1 // indirect
github.com/go-webauthn/x v0.1.4 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/golang/geo v0.0.0-20230421003525-6adc56603217 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/go-tpm v0.3.3 // indirect
github.com/google/go-tpm v0.9.0 // indirect
github.com/gorilla/css v1.0.0 // indirect
github.com/gorilla/handlers v1.5.1 // indirect
github.com/gorilla/mux v1.8.0 // indirect
@ -210,9 +210,9 @@ require (
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-retryablehttp v0.7.2 // indirect
github.com/hashicorp/go-retryablehttp v0.7.4 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/imdario/mergo v0.3.15 // indirect
github.com/imdario/mergo v0.3.16 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/jessevdk/go-flags v1.5.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
@ -221,14 +221,14 @@ require (
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/libdns/libdns v0.2.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/markbates/going v1.0.0 // indirect
github.com/markbates/going v1.0.3 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/mholt/acmez v1.1.0 // indirect
github.com/miekg/dns v1.1.54 // indirect
github.com/mholt/acmez v1.2.0 // indirect
github.com/miekg/dns v1.1.55 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
@ -241,56 +241,56 @@ require (
github.com/oklog/ulid v1.3.1 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/onsi/ginkgo v1.16.5 // indirect
github.com/onsi/gomega v1.18.1 // indirect
github.com/paulmach/orb v0.9.1 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
github.com/pierrec/lz4/v4 v4.1.17 // indirect
github.com/onsi/gomega v1.27.8 // indirect
github.com/paulmach/orb v0.9.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pierrec/lz4/v4 v4.1.18 // indirect
github.com/pjbgf/sha1cd v0.3.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/common v0.42.0 // indirect
github.com/prometheus/procfs v0.9.0 // indirect
github.com/rhysd/actionlint v1.6.24 // indirect
github.com/prometheus/client_model v0.4.0 // indirect
github.com/prometheus/common v0.44.0 // indirect
github.com/prometheus/procfs v0.11.0 // indirect
github.com/rhysd/actionlint v1.6.25 // indirect
github.com/rivo/uniseg v0.4.4 // indirect
github.com/robfig/cron v1.2.0 // indirect
github.com/rogpeppe/go-internal v1.10.0 // indirect
github.com/rogpeppe/go-internal v1.11.0 // indirect
github.com/rs/xid v1.5.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/segmentio/asm v1.2.0 // indirect
github.com/shopspring/decimal v1.3.1 // indirect
github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
github.com/skeema/knownhosts v1.1.0 // indirect
github.com/spf13/afero v1.9.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/shurcooL/httpfs v0.0.0-20230704072500-f1e31cf0ba5c // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/skeema/knownhosts v1.2.0 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.14.0 // indirect
github.com/spf13/viper v1.16.0 // indirect
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
github.com/subosito/gotenv v1.4.1 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
github.com/toqueteos/webbrowser v1.2.0 // indirect
github.com/unknwon/com v1.0.1 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.47.0 // indirect
github.com/valyala/fasthttp v1.48.0 // indirect
github.com/valyala/fastjson v1.6.4 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect
github.com/zeebo/blake3 v0.2.3 // indirect
go.etcd.io/bbolt v1.3.7 // indirect
go.mongodb.org/mongo-driver v1.11.4 // indirect
go.opentelemetry.io/otel v1.15.1 // indirect
go.opentelemetry.io/otel/trace v1.15.1 // indirect
go.mongodb.org/mongo-driver v1.12.0 // indirect
go.opentelemetry.io/otel v1.16.0 // indirect
go.opentelemetry.io/otel/trace v1.16.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.24.0 // indirect
golang.org/x/mod v0.10.0 // indirect
golang.org/x/sync v0.2.0 // indirect
golang.org/x/mod v0.12.0 // indirect
golang.org/x/sync v0.3.0 // indirect
golang.org/x/time v0.3.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect

497
go.sum

File diff suppressed because it is too large Load Diff

45
main.go
View File

@ -47,7 +47,9 @@ func init() {
// ./gitea -h
// ./gitea web help
// ./gitea web -h (due to cli lib limitation, this won't call our cmdHelp, so no extra info)
// ./gitea admin help auth
// ./gitea admin
// ./gitea admin help
// ./gitea admin auth help
// ./gitea -c /tmp/app.ini -h
// ./gitea -c /tmp/app.ini help
// ./gitea help -c /tmp/app.ini
@ -85,28 +87,36 @@ func main() {
app.Description = `By default, Gitea will start serving using the web-server with no argument, which can alternatively be run by running the subcommand "web".`
app.Version = Version + formatBuiltWith()
app.EnableBashCompletion = true
app.Commands = []cli.Command{
// these sub-commands need to use config file
subCmdWithIni := []cli.Command{
cmd.CmdWeb,
cmd.CmdServ,
cmd.CmdHook,
cmd.CmdDump,
cmd.CmdCert,
cmd.CmdAdmin,
cmd.CmdGenerate,
cmd.CmdMigrate,
cmd.CmdKeys,
cmd.CmdConvert,
cmd.CmdDoctor,
cmd.CmdManager,
cmd.Cmdembedded,
cmd.CmdEmbedded,
cmd.CmdMigrateStorage,
cmd.CmdDocs,
cmd.CmdDumpRepository,
cmd.CmdRestoreRepository,
cmd.CmdActions,
cmdHelp, // TODO: the "help" sub-command was used to show the more information for "work path" and "custom config", in the future, it should avoid doing so
}
// these sub-commands do not need the config file, and they do not depend on any path or environment variable.
subCmdStandalone := []cli.Command{
cmd.CmdCert,
cmd.CmdGenerate,
cmd.CmdDocs,
}
// default configuration flags
// shared configuration flags, they are for global and for each sub-command at the same time
// eg: such command is valid: "./gitea --config /tmp/app.ini web --config /tmp/app.ini", while it's discouraged indeed
// keep in mind that the short flags like "-C", "-c" and "-w" are globally polluted, they can't be used for sub-commands anymore.
globalFlags := []cli.Flag{
cli.HelpFlag,
cli.StringFlag{
@ -126,13 +136,15 @@ func main() {
// Set the default to be equivalent to cmdWeb and add the default flags
app.Flags = append(app.Flags, globalFlags...)
app.Flags = append(app.Flags, cmd.CmdWeb.Flags...)
app.Flags = append(app.Flags, cmd.CmdWeb.Flags...) // TODO: the web flags polluted the global flags, they are not really global flags
app.Action = prepareWorkPathAndCustomConf(cmd.CmdWeb.Action)
app.HideHelp = true // use our own help action to show helps (with more information like default config)
app.Commands = append(app.Commands, cmdHelp)
for i := range app.Commands {
prepareSubcommands(&app.Commands[i], globalFlags)
app.Before = cmd.PrepareConsoleLoggerLevel(log.INFO)
for i := range subCmdWithIni {
prepareSubcommands(&subCmdWithIni[i], globalFlags)
}
app.Commands = append(app.Commands, subCmdWithIni...)
app.Commands = append(app.Commands, subCmdStandalone...)
err := app.Run(os.Args)
if err != nil {
@ -156,11 +168,7 @@ func prepareSubcommands(command *cli.Command, defaultFlags []cli.Flag) {
// prepareWorkPathAndCustomConf wraps the Action to prepare the work path and custom config
// It can't use "Before", because each level's sub-command's Before will be called one by one, so the "init" would be done multiple times
func prepareWorkPathAndCustomConf(a any) func(ctx *cli.Context) error {
if a == nil {
return nil
}
action := a.(func(*cli.Context) error)
func prepareWorkPathAndCustomConf(action any) func(ctx *cli.Context) error {
return func(ctx *cli.Context) error {
var args setting.ArgWorkPathAndCustomConf
curCtx := ctx
@ -177,10 +185,11 @@ func prepareWorkPathAndCustomConf(a any) func(ctx *cli.Context) error {
curCtx = curCtx.Parent()
}
setting.InitWorkPathAndCommonConfig(os.Getenv, args)
if ctx.Bool("help") {
if ctx.Bool("help") || action == nil {
// the default behavior of "urfave/cli": "nil action" means "show help"
return cmdHelp.Action.(func(ctx *cli.Context) error)(ctx)
}
return action(ctx)
return action.(func(*cli.Context) error)(ctx)
}
}

View File

@ -31,7 +31,7 @@ func init() {
// ActionArtifact is a file that is stored in the artifact storage.
type ActionArtifact struct {
ID int64 `xorm:"pk autoincr"`
RunID int64 `xorm:"index UNIQUE(runid_name)"` // The run id of the artifact
RunID int64 `xorm:"index unique(runid_name_path)"` // The run id of the artifact
RunnerID int64
RepoID int64 `xorm:"index"`
OwnerID int64
@ -40,27 +40,28 @@ type ActionArtifact struct {
FileSize int64 // The size of the artifact in bytes
FileCompressedSize int64 // The size of the artifact in bytes after gzip compression
ContentEncoding string // The content encoding of the artifact
ArtifactPath string // The path to the artifact when runner uploads it
ArtifactName string `xorm:"UNIQUE(runid_name)"` // The name of the artifact when runner uploads it
Status int64 `xorm:"index"` // The status of the artifact, uploading, expired or need-delete
ArtifactPath string `xorm:"index unique(runid_name_path)"` // The path to the artifact when runner uploads it
ArtifactName string `xorm:"index unique(runid_name_path)"` // The name of the artifact when runner uploads it
Status int64 `xorm:"index"` // The status of the artifact, uploading, expired or need-delete
CreatedUnix timeutil.TimeStamp `xorm:"created"`
UpdatedUnix timeutil.TimeStamp `xorm:"updated index"`
}
// CreateArtifact create a new artifact with task info or get same named artifact in the same run
func CreateArtifact(ctx context.Context, t *ActionTask, artifactName string) (*ActionArtifact, error) {
func CreateArtifact(ctx context.Context, t *ActionTask, artifactName, artifactPath string) (*ActionArtifact, error) {
if err := t.LoadJob(ctx); err != nil {
return nil, err
}
artifact, err := getArtifactByArtifactName(ctx, t.Job.RunID, artifactName)
artifact, err := getArtifactByNameAndPath(ctx, t.Job.RunID, artifactName, artifactPath)
if errors.Is(err, util.ErrNotExist) {
artifact := &ActionArtifact{
RunID: t.Job.RunID,
RunnerID: t.RunnerID,
RepoID: t.RepoID,
OwnerID: t.OwnerID,
CommitSHA: t.CommitSHA,
Status: ArtifactStatusUploadPending,
ArtifactName: artifactName,
ArtifactPath: artifactPath,
RunID: t.Job.RunID,
RunnerID: t.RunnerID,
RepoID: t.RepoID,
OwnerID: t.OwnerID,
CommitSHA: t.CommitSHA,
Status: ArtifactStatusUploadPending,
}
if _, err := db.GetEngine(ctx).Insert(artifact); err != nil {
return nil, err
@ -72,9 +73,9 @@ func CreateArtifact(ctx context.Context, t *ActionTask, artifactName string) (*A
return artifact, nil
}
func getArtifactByArtifactName(ctx context.Context, runID int64, name string) (*ActionArtifact, error) {
func getArtifactByNameAndPath(ctx context.Context, runID int64, name, fpath string) (*ActionArtifact, error) {
var art ActionArtifact
has, err := db.GetEngine(ctx).Where("run_id = ? AND artifact_name = ?", runID, name).Get(&art)
has, err := db.GetEngine(ctx).Where("run_id = ? AND artifact_name = ? AND artifact_path = ?", runID, name, fpath).Get(&art)
if err != nil {
return nil, err
} else if !has {
@ -109,14 +110,42 @@ func ListArtifactsByRunID(ctx context.Context, runID int64) ([]*ActionArtifact,
return arts, db.GetEngine(ctx).Where("run_id=?", runID).Find(&arts)
}
// ListArtifactsByRunIDAndArtifactName returns an artifacts of a run by artifact name
func ListArtifactsByRunIDAndArtifactName(ctx context.Context, runID int64, artifactName string) ([]*ActionArtifact, error) {
arts := make([]*ActionArtifact, 0, 10)
return arts, db.GetEngine(ctx).Where("run_id=? AND artifact_name=?", runID, artifactName).Find(&arts)
}
// ListUploadedArtifactsByRunID returns all uploaded artifacts of a run
func ListUploadedArtifactsByRunID(ctx context.Context, runID int64) ([]*ActionArtifact, error) {
arts := make([]*ActionArtifact, 0, 10)
return arts, db.GetEngine(ctx).Where("run_id=? AND status=?", runID, ArtifactStatusUploadConfirmed).Find(&arts)
}
// ActionArtifactMeta is the meta data of an artifact
type ActionArtifactMeta struct {
ArtifactName string
FileSize int64
}
// ListUploadedArtifactsMeta returns all uploaded artifacts meta of a run
func ListUploadedArtifactsMeta(ctx context.Context, runID int64) ([]*ActionArtifactMeta, error) {
arts := make([]*ActionArtifactMeta, 0, 10)
return arts, db.GetEngine(ctx).Table("action_artifact").
Where("run_id=? AND status=?", runID, ArtifactStatusUploadConfirmed).
GroupBy("artifact_name").
Select("artifact_name, sum(file_size) as file_size").
Find(&arts)
}
// ListArtifactsByRepoID returns all artifacts of a repo
func ListArtifactsByRepoID(ctx context.Context, repoID int64) ([]*ActionArtifact, error) {
arts := make([]*ActionArtifact, 0, 10)
return arts, db.GetEngine(ctx).Where("repo_id=?", repoID).Find(&arts)
}
// ListArtifactsByRunIDAndName returns artifacts by name of a run
func ListArtifactsByRunIDAndName(ctx context.Context, runID int64, name string) ([]*ActionArtifact, error) {
arts := make([]*ActionArtifact, 0, 10)
return arts, db.GetEngine(ctx).Where("run_id=? AND artifact_name=?", runID, name).Find(&arts)
}

View File

@ -36,12 +36,13 @@ type ActionRun struct {
TriggerUser *user_model.User `xorm:"-"`
Ref string
CommitSHA string
IsForkPullRequest bool // If this is triggered by a PR from a forked repository or an untrusted user, we need to check if it is approved and limit permissions when running the workflow.
NeedApproval bool // may need approval if it's a fork pull request
ApprovedBy int64 `xorm:"index"` // who approved
Event webhook_module.HookEventType
EventPayload string `xorm:"LONGTEXT"`
Status Status `xorm:"index"`
IsForkPullRequest bool // If this is triggered by a PR from a forked repository or an untrusted user, we need to check if it is approved and limit permissions when running the workflow.
NeedApproval bool // may need approval if it's a fork pull request
ApprovedBy int64 `xorm:"index"` // who approved
Event webhook_module.HookEventType // the webhook event that causes the workflow to run
EventPayload string `xorm:"LONGTEXT"`
TriggerEvent string // the trigger event defined in the `on` configuration of the triggered workflow
Status Status `xorm:"index"`
Started timeutil.TimeStamp
Stopped timeutil.TimeStamp
Created timeutil.TimeStamp `xorm:"created"`

View File

@ -18,7 +18,7 @@ import (
"code.gitea.io/gitea/modules/util"
runnerv1 "code.gitea.io/actions-proto-go/runner/v1"
lru "github.com/hashicorp/golang-lru"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/nektos/act/pkg/jobparser"
"google.golang.org/protobuf/types/known/timestamppb"
"xorm.io/builder"
@ -57,13 +57,13 @@ type ActionTask struct {
Updated timeutil.TimeStamp `xorm:"updated index"`
}
var successfulTokenTaskCache *lru.Cache
var successfulTokenTaskCache *lru.Cache[string, any]
func init() {
db.RegisterModel(new(ActionTask), func() error {
if setting.SuccessfulTokensCacheSize > 0 {
var err error
successfulTokenTaskCache, err = lru.New(setting.SuccessfulTokensCacheSize)
successfulTokenTaskCache, err = lru.New[string, any](setting.SuccessfulTokensCacheSize)
if err != nil {
return fmt.Errorf("unable to allocate Task cache: %v", err)
}
@ -344,6 +344,9 @@ func UpdateTask(ctx context.Context, task *ActionTask, cols ...string) error {
return err
}
// UpdateTaskByState updates the task by the state.
// It will always update the task if the state is not final, even there is no change.
// So it will update ActionTask.Updated to avoid the task being judged as a zombie task.
func UpdateTaskByState(ctx context.Context, state *runnerv1.TaskState) (*ActionTask, error) {
stepStates := map[int64]*runnerv1.StepState{}
for _, v := range state.Steps {
@ -384,6 +387,12 @@ func UpdateTaskByState(ctx context.Context, state *runnerv1.TaskState) (*ActionT
}, nil); err != nil {
return nil, err
}
} else {
// Force update ActionTask.Updated to avoid the task being judged as a zombie task
task.Updated = timeutil.TimeStampNow()
if err := UpdateTask(ctx, task, "updated"); err != nil {
return nil, err
}
}
if err := task.LoadAttributes(ctx); err != nil {

View File

@ -343,7 +343,7 @@ func getIssueNotification(ctx context.Context, userID, issueID int64) (*Notifica
// NotificationsForUser returns notifications for a given user and status
func NotificationsForUser(ctx context.Context, user *user_model.User, statuses []NotificationStatus, page, perPage int) (notifications NotificationList, err error) {
if len(statuses) == 0 {
return
return nil, nil
}
sess := db.GetEngine(ctx).
@ -372,16 +372,16 @@ func CountUnread(ctx context.Context, userID int64) int64 {
// LoadAttributes load Repo Issue User and Comment if not loaded
func (n *Notification) LoadAttributes(ctx context.Context) (err error) {
if err = n.loadRepo(ctx); err != nil {
return
return err
}
if err = n.loadIssue(ctx); err != nil {
return
return err
}
if err = n.loadUser(ctx); err != nil {
return
return err
}
if err = n.loadComment(ctx); err != nil {
return
return err
}
return err
}

View File

@ -44,7 +44,7 @@ func init() {
// TranslatableMessage represents JSON struct that can be translated with a Locale
type TranslatableMessage struct {
Format string
Args []interface{} `json:"omitempty"`
Args []any `json:"omitempty"`
}
// LoadRepo loads repository of the task

View File

@ -455,9 +455,9 @@ func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *use
// CalculateTrustStatus will calculate the TrustStatus for a commit verification within a repository
// There are several trust models in Gitea
func CalculateTrustStatus(verification *CommitVerification, repoTrustModel repo_model.TrustModelType, isOwnerMemberCollaborator func(*user_model.User) (bool, error), keyMap *map[string]bool) (err error) {
func CalculateTrustStatus(verification *CommitVerification, repoTrustModel repo_model.TrustModelType, isOwnerMemberCollaborator func(*user_model.User) (bool, error), keyMap *map[string]bool) error {
if !verification.Verified {
return
return nil
}
// In the Committer trust model a signature is trusted if it matches the committer
@ -475,7 +475,7 @@ func CalculateTrustStatus(verification *CommitVerification, repoTrustModel repo_
verification.SigningUser.Email == verification.CommittingUser.Email) {
verification.TrustStatus = "trusted"
}
return
return nil
}
// Now we drop to the more nuanced trust models...
@ -490,10 +490,11 @@ func CalculateTrustStatus(verification *CommitVerification, repoTrustModel repo_
verification.SigningUser.Email != verification.CommittingUser.Email) {
verification.TrustStatus = "untrusted"
}
return
return nil
}
// Check we actually have a GPG SigningKey
var err error
if verification.SigningKey != nil {
var isMember bool
if keyMap != nil {

View File

@ -111,7 +111,7 @@ func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) {
func readArmoredSign(r io.Reader) (body io.Reader, err error) {
block, err := armor.Decode(r)
if err != nil {
return
return nil, err
}
if block.Type != openpgp.SignatureType {
return nil, fmt.Errorf("expected '" + openpgp.SignatureType + "', got: " + block.Type)

View File

@ -47,7 +47,7 @@ var sshOpLocker sync.Mutex
// AuthorizedStringForKey creates the authorized keys string appropriate for the provided key
func AuthorizedStringForKey(key *PublicKey) string {
sb := &strings.Builder{}
_ = setting.SSH.AuthorizedKeysCommandTemplateTemplate.Execute(sb, map[string]interface{}{
_ = setting.SSH.AuthorizedKeysCommandTemplateTemplate.Execute(sb, map[string]any{
"AppPath": util.ShellEscape(setting.AppPath),
"AppWorkPath": util.ShellEscape(setting.AppWorkPath),
"CustomConf": util.ShellEscape(setting.CustomConf),
@ -175,7 +175,7 @@ func RewriteAllPublicKeys() error {
// RegeneratePublicKeys regenerates the authorized_keys file
func RegeneratePublicKeys(ctx context.Context, t io.StringWriter) error {
if err := db.GetEngine(ctx).Where("type != ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
if err := db.GetEngine(ctx).Where("type != ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean any) (err error) {
_, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
return err
}); err != nil {

View File

@ -97,7 +97,7 @@ func RewriteAllPrincipalKeys(ctx context.Context) error {
}
func regeneratePrincipalKeys(ctx context.Context, t io.StringWriter) error {
if err := db.GetEngine(ctx).Where("type = ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
if err := db.GetEngine(ctx).Where("type = ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean any) (err error) {
_, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
return err
}); err != nil {

View File

@ -306,9 +306,10 @@ func (code *OAuth2AuthorizationCode) TableName() string {
}
// GenerateRedirectURI generates a redirect URI for a successful authorization request. State will be used if not empty.
func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect *url.URL, err error) {
if redirect, err = url.Parse(code.RedirectURI); err != nil {
return
func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (*url.URL, error) {
redirect, err := url.Parse(code.RedirectURI)
if err != nil {
return nil, err
}
q := redirect.Query()
if state != "" {

View File

@ -15,7 +15,7 @@ import (
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
lru "github.com/hashicorp/golang-lru"
lru "github.com/hashicorp/golang-lru/v2"
)
// ErrAccessTokenNotExist represents a "AccessTokenNotExist" kind of error.
@ -54,7 +54,7 @@ func (err ErrAccessTokenEmpty) Unwrap() error {
return util.ErrInvalidArgument
}
var successfulAccessTokenCache *lru.Cache
var successfulAccessTokenCache *lru.Cache[string, any]
// AccessToken represents a personal access token.
type AccessToken struct {
@ -83,7 +83,7 @@ func init() {
db.RegisterModel(new(AccessToken), func() error {
if setting.SuccessfulTokensCacheSize > 0 {
var err error
successfulAccessTokenCache, err = lru.New(setting.SuccessfulTokensCacheSize)
successfulAccessTokenCache, err = lru.New[string, any](setting.SuccessfulTokensCacheSize)
if err != nil {
return fmt.Errorf("unable to allocate AccessToken cache: %w", err)
}
@ -154,16 +154,16 @@ func GetAccessTokenBySHA(token string) (*AccessToken, error) {
lastEight := token[len(token)-8:]
if id := getAccessTokenIDFromCache(token); id > 0 {
token := &AccessToken{
accessToken := &AccessToken{
TokenLastEight: lastEight,
}
// Re-get the token from the db in case it has been deleted in the intervening period
has, err := db.GetEngine(db.DefaultContext).ID(id).Get(token)
has, err := db.GetEngine(db.DefaultContext).ID(id).Get(accessToken)
if err != nil {
return nil, err
}
if has {
return token, nil
return accessToken, nil
}
successfulAccessTokenCache.Remove(token)
}

View File

@ -52,7 +52,7 @@ func (ctx *Context) Engine() Engine {
}
// Value shadows Value for context.Context but allows us to get ourselves and an Engined object
func (ctx *Context) Value(key interface{}) interface{} {
func (ctx *Context) Value(key any) any {
if key == enginedContextKey {
return ctx
}
@ -163,28 +163,28 @@ func txWithNoCheck(parentCtx context.Context, f func(ctx context.Context) error)
}
// Insert inserts records into database
func Insert(ctx context.Context, beans ...interface{}) error {
func Insert(ctx context.Context, beans ...any) error {
_, err := GetEngine(ctx).Insert(beans...)
return err
}
// Exec executes a sql with args
func Exec(ctx context.Context, sqlAndArgs ...interface{}) (sql.Result, error) {
func Exec(ctx context.Context, sqlAndArgs ...any) (sql.Result, error) {
return GetEngine(ctx).Exec(sqlAndArgs...)
}
// GetByBean filled empty fields of the bean according non-empty fields to query in database.
func GetByBean(ctx context.Context, bean interface{}) (bool, error) {
func GetByBean(ctx context.Context, bean any) (bool, error) {
return GetEngine(ctx).Get(bean)
}
// DeleteByBean deletes all records according non-empty fields of the bean as conditions.
func DeleteByBean(ctx context.Context, bean interface{}) (int64, error) {
func DeleteByBean(ctx context.Context, bean any) (int64, error) {
return GetEngine(ctx).Delete(bean)
}
// DeleteByID deletes the given bean with the given ID
func DeleteByID(ctx context.Context, id int64, bean interface{}) (int64, error) {
func DeleteByID(ctx context.Context, id int64, bean any) (int64, error) {
return GetEngine(ctx).ID(id).NoAutoTime().Delete(bean)
}
@ -203,13 +203,13 @@ func FindIDs(ctx context.Context, tableName, idCol string, cond builder.Cond) ([
// DecrByIDs decreases the given column for entities of the "bean" type with one of the given ids by one
// Timestamps of the entities won't be updated
func DecrByIDs(ctx context.Context, ids []int64, decrCol string, bean interface{}) error {
func DecrByIDs(ctx context.Context, ids []int64, decrCol string, bean any) error {
_, err := GetEngine(ctx).Decr(decrCol).In("id", ids).NoAutoCondition().NoAutoTime().Update(bean)
return err
}
// DeleteBeans deletes all given beans, beans must contain delete conditions.
func DeleteBeans(ctx context.Context, beans ...interface{}) (err error) {
func DeleteBeans(ctx context.Context, beans ...any) (err error) {
e := GetEngine(ctx)
for i := range beans {
if _, err = e.Delete(beans[i]); err != nil {
@ -220,7 +220,7 @@ func DeleteBeans(ctx context.Context, beans ...interface{}) (err error) {
}
// TruncateBeans deletes all given beans, beans may contain delete conditions.
func TruncateBeans(ctx context.Context, beans ...interface{}) (err error) {
func TruncateBeans(ctx context.Context, beans ...any) (err error) {
e := GetEngine(ctx)
for i := range beans {
if _, err = e.Truncate(beans[i]); err != nil {
@ -231,12 +231,12 @@ func TruncateBeans(ctx context.Context, beans ...interface{}) (err error) {
}
// CountByBean counts the number of database records according non-empty fields of the bean as conditions.
func CountByBean(ctx context.Context, bean interface{}) (int64, error) {
func CountByBean(ctx context.Context, bean any) (int64, error) {
return GetEngine(ctx).Count(bean)
}
// TableName returns the table name according a bean object
func TableName(bean interface{}) string {
func TableName(bean any) string {
return x.TableName(bean)
}

View File

@ -25,7 +25,7 @@ import (
var (
x *xorm.Engine
tables []interface{}
tables []any
initFuncs []func() error
// HasEngine specifies if we have a xorm.Engine
@ -34,41 +34,41 @@ var (
// Engine represents a xorm engine or session.
type Engine interface {
Table(tableNameOrBean interface{}) *xorm.Session
Count(...interface{}) (int64, error)
Decr(column string, arg ...interface{}) *xorm.Session
Delete(...interface{}) (int64, error)
Truncate(...interface{}) (int64, error)
Exec(...interface{}) (sql.Result, error)
Find(interface{}, ...interface{}) error
Get(beans ...interface{}) (bool, error)
ID(interface{}) *xorm.Session
In(string, ...interface{}) *xorm.Session
Incr(column string, arg ...interface{}) *xorm.Session
Insert(...interface{}) (int64, error)
Iterate(interface{}, xorm.IterFunc) error
Join(joinOperator string, tablename, condition interface{}, args ...interface{}) *xorm.Session
SQL(interface{}, ...interface{}) *xorm.Session
Where(interface{}, ...interface{}) *xorm.Session
Table(tableNameOrBean any) *xorm.Session
Count(...any) (int64, error)
Decr(column string, arg ...any) *xorm.Session
Delete(...any) (int64, error)
Truncate(...any) (int64, error)
Exec(...any) (sql.Result, error)
Find(any, ...any) error
Get(beans ...any) (bool, error)
ID(any) *xorm.Session
In(string, ...any) *xorm.Session
Incr(column string, arg ...any) *xorm.Session
Insert(...any) (int64, error)
Iterate(any, xorm.IterFunc) error
Join(joinOperator string, tablename, condition any, args ...any) *xorm.Session
SQL(any, ...any) *xorm.Session
Where(any, ...any) *xorm.Session
Asc(colNames ...string) *xorm.Session
Desc(colNames ...string) *xorm.Session
Limit(limit int, start ...int) *xorm.Session
NoAutoTime() *xorm.Session
SumInt(bean interface{}, columnName string) (res int64, err error)
Sync2(...interface{}) error
SumInt(bean any, columnName string) (res int64, err error)
Sync2(...any) error
Select(string) *xorm.Session
NotIn(string, ...interface{}) *xorm.Session
OrderBy(interface{}, ...interface{}) *xorm.Session
Exist(...interface{}) (bool, error)
NotIn(string, ...any) *xorm.Session
OrderBy(any, ...any) *xorm.Session
Exist(...any) (bool, error)
Distinct(...string) *xorm.Session
Query(...interface{}) ([]map[string][]byte, error)
Query(...any) ([]map[string][]byte, error)
Cols(...string) *xorm.Session
Context(ctx context.Context) *xorm.Session
Ping() error
}
// TableInfo returns table's information via an object
func TableInfo(v interface{}) (*schemas.Table, error) {
func TableInfo(v any) (*schemas.Table, error) {
return x.TableInfo(v)
}
@ -78,7 +78,7 @@ func DumpTables(tables []*schemas.Table, w io.Writer, tp ...schemas.DBType) erro
}
// RegisterModel registers model, if initfunc provided, it will be invoked after data model sync
func RegisterModel(bean interface{}, initFunc ...func() error) {
func RegisterModel(bean any, initFunc ...func() error) {
tables = append(tables, bean)
if len(initFuncs) > 0 && initFunc[0] != nil {
initFuncs = append(initFuncs, initFunc[0])
@ -209,14 +209,14 @@ func InitEngineWithMigration(ctx context.Context, migrateFunc func(*xorm.Engine)
}
// NamesToBean return a list of beans or an error
func NamesToBean(names ...string) ([]interface{}, error) {
beans := []interface{}{}
func NamesToBean(names ...string) ([]any, error) {
beans := []any{}
if len(names) == 0 {
beans = append(beans, tables...)
return beans, nil
}
// Need to map provided names to beans...
beanMap := make(map[string]interface{})
beanMap := make(map[string]any)
for _, bean := range tables {
beanMap[strings.ToLower(reflect.Indirect(reflect.ValueOf(bean)).Type().Name())] = bean
@ -224,7 +224,7 @@ func NamesToBean(names ...string) ([]interface{}, error) {
beanMap[strings.ToLower(x.TableName(bean, true))] = bean
}
gotBean := make(map[interface{}]bool)
gotBean := make(map[any]bool)
for _, name := range names {
bean, ok := beanMap[strings.ToLower(strings.TrimSpace(name))]
if !ok {
@ -266,7 +266,7 @@ func DumpDatabase(filePath, dbType string) error {
}
// MaxBatchInsertSize returns the table's max batch insert size
func MaxBatchInsertSize(bean interface{}) int {
func MaxBatchInsertSize(bean any) int {
t, err := x.TableInfo(bean)
if err != nil {
return 50
@ -286,7 +286,7 @@ func DeleteAllRecords(tableName string) error {
}
// GetMaxID will return max id of the table
func GetMaxID(beanOrTableName interface{}) (maxID int64, err error) {
func GetMaxID(beanOrTableName any) (maxID int64, err error) {
_, err = x.Select("MAX(id)").Table(beanOrTableName).Get(&maxID)
return maxID, err
}

View File

@ -25,7 +25,7 @@ func (err ErrCancelled) Error() string {
}
// ErrCancelledf returns an ErrCancelled for the provided format and args
func ErrCancelledf(format string, args ...interface{}) error {
func ErrCancelledf(format string, args ...any) error {
return ErrCancelled{
fmt.Sprintf(format, args...),
}

View File

@ -28,47 +28,47 @@ func NewXORMLogger(showSQL bool) xormlog.Logger {
const stackLevel = 8
// Log a message with defined skip and at logging level
func (l *XORMLogBridge) Log(skip int, level log.Level, format string, v ...interface{}) {
func (l *XORMLogBridge) Log(skip int, level log.Level, format string, v ...any) {
l.logger.Log(skip+1, level, format, v...)
}
// Debug show debug log
func (l *XORMLogBridge) Debug(v ...interface{}) {
func (l *XORMLogBridge) Debug(v ...any) {
l.Log(stackLevel, log.DEBUG, "%s", fmt.Sprint(v...))
}
// Debugf show debug log
func (l *XORMLogBridge) Debugf(format string, v ...interface{}) {
func (l *XORMLogBridge) Debugf(format string, v ...any) {
l.Log(stackLevel, log.DEBUG, format, v...)
}
// Error show error log
func (l *XORMLogBridge) Error(v ...interface{}) {
func (l *XORMLogBridge) Error(v ...any) {
l.Log(stackLevel, log.ERROR, "%s", fmt.Sprint(v...))
}
// Errorf show error log
func (l *XORMLogBridge) Errorf(format string, v ...interface{}) {
func (l *XORMLogBridge) Errorf(format string, v ...any) {
l.Log(stackLevel, log.ERROR, format, v...)
}
// Info show information level log
func (l *XORMLogBridge) Info(v ...interface{}) {
func (l *XORMLogBridge) Info(v ...any) {
l.Log(stackLevel, log.INFO, "%s", fmt.Sprint(v...))
}
// Infof show information level log
func (l *XORMLogBridge) Infof(format string, v ...interface{}) {
func (l *XORMLogBridge) Infof(format string, v ...any) {
l.Log(stackLevel, log.INFO, format, v...)
}
// Warn show warning log
func (l *XORMLogBridge) Warn(v ...interface{}) {
func (l *XORMLogBridge) Warn(v ...any) {
l.Log(stackLevel, log.WARN, "%s", fmt.Sprint(v...))
}
// Warnf show warnning log
func (l *XORMLogBridge) Warnf(format string, v ...interface{}) {
func (l *XORMLogBridge) Warnf(format string, v ...any) {
l.Log(stackLevel, log.WARN, format, v...)
}

View File

@ -20,6 +20,10 @@ const (
SearchOrderByNewest SearchOrderBy = "created_unix DESC"
SearchOrderBySize SearchOrderBy = "size ASC"
SearchOrderBySizeReverse SearchOrderBy = "size DESC"
SearchOrderByGitSize SearchOrderBy = "git_size ASC"
SearchOrderByGitSizeReverse SearchOrderBy = "git_size DESC"
SearchOrderByLFSSize SearchOrderBy = "lfs_size ASC"
SearchOrderByLFSSizeReverse SearchOrderBy = "lfs_size DESC"
SearchOrderByID SearchOrderBy = "id ASC"
SearchOrderByIDReverse SearchOrderBy = "id DESC"
SearchOrderByStars SearchOrderBy = "num_stars ASC"

View File

@ -7,6 +7,7 @@ import (
"context"
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"strconv"
@ -21,6 +22,7 @@ var defaultFileBlockSize int64 = 32 * 1024
type File interface {
io.ReadWriteCloser
io.Seeker
fs.File
}
type file struct {
@ -193,10 +195,26 @@ func (f *file) Close() error {
return nil
}
func (f *file) Stat() (os.FileInfo, error) {
if f.metaID == 0 {
return nil, os.ErrInvalid
}
fileMeta, err := findFileMetaByID(f.ctx, f.metaID)
if err != nil {
return nil, err
}
return fileMeta, nil
}
func timeToFileTimestamp(t time.Time) int64 {
return t.UnixMicro()
}
func fileTimestampToTime(timestamp int64) time.Time {
return time.UnixMicro(timestamp)
}
func (f *file) loadMetaByPath() (*dbfsMeta, error) {
var fileMeta dbfsMeta
if ok, err := db.GetEngine(f.ctx).Where("full_path = ?", f.fullPath).Get(&fileMeta); err != nil {

View File

@ -5,7 +5,10 @@ package dbfs
import (
"context"
"io/fs"
"os"
"path"
"time"
"code.gitea.io/gitea/models/db"
)
@ -100,3 +103,29 @@ func Remove(ctx context.Context, name string) error {
defer f.Close()
return f.delete()
}
var _ fs.FileInfo = (*dbfsMeta)(nil)
func (m *dbfsMeta) Name() string {
return path.Base(m.FullPath)
}
func (m *dbfsMeta) Size() int64 {
return m.FileSize
}
func (m *dbfsMeta) Mode() fs.FileMode {
return os.ModePerm
}
func (m *dbfsMeta) ModTime() time.Time {
return fileTimestampToTime(m.ModifyTimestamp)
}
func (m *dbfsMeta) IsDir() bool {
return false
}
func (m *dbfsMeta) Sys() any {
return nil
}

View File

@ -111,6 +111,19 @@ func TestDbfsBasic(t *testing.T) {
_, err = OpenFile(db.DefaultContext, "test2.txt", os.O_RDONLY)
assert.Error(t, err)
// test stat
f, err = OpenFile(db.DefaultContext, "test/test.txt", os.O_RDWR|os.O_CREATE)
assert.NoError(t, err)
stat, err := f.Stat()
assert.NoError(t, err)
assert.EqualValues(t, "test.txt", stat.Name())
assert.EqualValues(t, 0, stat.Size())
_, err = f.Write([]byte("0123456789"))
assert.NoError(t, err)
stat, err = f.Stat()
assert.NoError(t, err)
assert.EqualValues(t, 10, stat.Size())
}
func TestDbfsReadWrite(t *testing.T) {

View File

@ -318,90 +318,6 @@ func (err ErrFilePathProtected) Unwrap() error {
return util.ErrPermissionDenied
}
// __________ .__
// \______ \____________ ____ ____ | |__
// | | _/\_ __ \__ \ / \_/ ___\| | \
// | | \ | | \// __ \| | \ \___| Y \
// |______ / |__| (____ /___| /\___ >___| /
// \/ \/ \/ \/ \/
// ErrBranchDoesNotExist represents an error that branch with such name does not exist.
type ErrBranchDoesNotExist struct {
BranchName string
}
// IsErrBranchDoesNotExist checks if an error is an ErrBranchDoesNotExist.
func IsErrBranchDoesNotExist(err error) bool {
_, ok := err.(ErrBranchDoesNotExist)
return ok
}
func (err ErrBranchDoesNotExist) Error() string {
return fmt.Sprintf("branch does not exist [name: %s]", err.BranchName)
}
func (err ErrBranchDoesNotExist) Unwrap() error {
return util.ErrNotExist
}
// ErrBranchAlreadyExists represents an error that branch with such name already exists.
type ErrBranchAlreadyExists struct {
BranchName string
}
// IsErrBranchAlreadyExists checks if an error is an ErrBranchAlreadyExists.
func IsErrBranchAlreadyExists(err error) bool {
_, ok := err.(ErrBranchAlreadyExists)
return ok
}
func (err ErrBranchAlreadyExists) Error() string {
return fmt.Sprintf("branch already exists [name: %s]", err.BranchName)
}
func (err ErrBranchAlreadyExists) Unwrap() error {
return util.ErrAlreadyExist
}
// ErrBranchNameConflict represents an error that branch name conflicts with other branch.
type ErrBranchNameConflict struct {
BranchName string
}
// IsErrBranchNameConflict checks if an error is an ErrBranchNameConflict.
func IsErrBranchNameConflict(err error) bool {
_, ok := err.(ErrBranchNameConflict)
return ok
}
func (err ErrBranchNameConflict) Error() string {
return fmt.Sprintf("branch conflicts with existing branch [name: %s]", err.BranchName)
}
func (err ErrBranchNameConflict) Unwrap() error {
return util.ErrAlreadyExist
}
// ErrBranchesEqual represents an error that branch name conflicts with other branch.
type ErrBranchesEqual struct {
BaseBranchName string
HeadBranchName string
}
// IsErrBranchesEqual checks if an error is an ErrBranchesEqual.
func IsErrBranchesEqual(err error) bool {
_, ok := err.(ErrBranchesEqual)
return ok
}
func (err ErrBranchesEqual) Error() string {
return fmt.Sprintf("branches are equal [head: %sm base: %s]", err.HeadBranchName, err.BaseBranchName)
}
func (err ErrBranchesEqual) Unwrap() error {
return util.ErrInvalidArgument
}
// ErrDisallowedToMerge represents an error that a branch is protected and the current user is not allowed to modify it.
type ErrDisallowedToMerge struct {
Reason string

View File

@ -0,0 +1,47 @@
-
id: 1
repo_id: 1
name: 'foo'
commit_id: '65f1bf27bc3bf70f64657658635e66094edbcb4d'
commit_message: 'first commit'
commit_time: 978307100
pusher_id: 1
is_deleted: true
deleted_by_id: 1
deleted_unix: 978307200
-
id: 2
repo_id: 1
name: 'bar'
commit_id: '62fb502a7172d4453f0322a2cc85bddffa57f07a'
commit_message: 'second commit'
commit_time: 978307100
pusher_id: 1
is_deleted: true
deleted_by_id: 99
deleted_unix: 978307200
-
id: 3
repo_id: 1
name: 'branch2'
commit_id: '985f0301dba5e7b34be866819cd15ad3d8f508ee'
commit_message: 'make pull5 outdated'
commit_time: 1579166279
pusher_id: 1
is_deleted: false
deleted_by_id: 0
deleted_unix: 0
-
id: 4
repo_id: 1
name: 'master'
commit_id: '65f1bf27bc3bf70f64657658635e66094edbcb4d'
commit_message: 'Initial commit'
commit_time: 1489927679
pusher_id: 1
is_deleted: false
deleted_by_id: 0
deleted_unix: 0

View File

@ -1,15 +0,0 @@
-
id: 1
repo_id: 1
name: foo
commit: 1213212312313213213132131
deleted_by_id: 1
deleted_unix: 978307200
-
id: 2
repo_id: 1
name: bar
commit: 5655464564554545466464655
deleted_by_id: 99
deleted_unix: 978307200

View File

@ -0,0 +1,49 @@
-
id: 1
repo_id: 5
interval: 3600
enable_prune: false
updated_unix: 0
next_update_unix: 0
lfs_enabled: false
lfs_endpoint: ""
-
id: 2
repo_id: 25
interval: 3600
enable_prune: false
updated_unix: 0
next_update_unix: 0
lfs_enabled: false
lfs_endpoint: ""
-
id: 3
repo_id: 26
interval: 3600
enable_prune: false
updated_unix: 0
next_update_unix: 0
lfs_enabled: false
lfs_endpoint: ""
-
id: 4
repo_id: 27
interval: 3600
enable_prune: false
updated_unix: 0
next_update_unix: 0
lfs_enabled: false
lfs_endpoint: ""
-
id: 5
repo_id: 28
interval: 3600
enable_prune: false
updated_unix: 0
next_update_unix: 0
lfs_enabled: false
lfs_endpoint: ""

View File

@ -81,3 +81,21 @@
uid: 5
org_id: 23
is_public: false
-
id: 15
uid: 1
org_id: 35
is_public: true
-
id: 16
uid: 1
org_id: 36
is_public: true
-
id: 17
uid: 5
org_id: 36
is_public: true

View File

@ -7,6 +7,8 @@
creator_id: 2
board_type: 1
type: 2
created_unix: 1688973030
updated_unix: 1688973030
-
id: 2
@ -17,6 +19,8 @@
creator_id: 3
board_type: 1
type: 2
created_unix: 1688973010
updated_unix: 1688973010
-
id: 3
@ -27,6 +31,8 @@
creator_id: 5
board_type: 1
type: 2
created_unix: 1688973020
updated_unix: 1688973020
-
id: 4
@ -37,3 +43,5 @@
creator_id: 2
board_type: 1
type: 2
created_unix: 1688973000
updated_unix: 1688973000

View File

@ -141,7 +141,7 @@
num_projects: 0
num_closed_projects: 0
is_private: true
is_empty: true
is_empty: false
is_archived: false
is_mirror: true
status: 0

View File

@ -184,3 +184,36 @@
num_members: 1
includes_all_repositories: false
can_create_org_repo: true
-
id: 18
org_id: 35
lower_name: owners
name: Owners
authorize: 4 # owner
num_repos: 0
num_members: 1
includes_all_repositories: false
can_create_org_repo: true
-
id: 19
org_id: 36
lower_name: owners
name: Owners
authorize: 4 # owner
num_repos: 0
num_members: 1
includes_all_repositories: false
can_create_org_repo: true
-
id: 20
org_id: 36
lower_name: team20writepackage
name: team20writepackage
authorize: 1
num_repos: 0
num_members: 1
includes_all_repositories: false
can_create_org_repo: true

View File

@ -273,4 +273,10 @@
id: 46
team_id: 17
type: 9 # package
access_mode: 0
access_mode: 2
-
id: 47
team_id: 20
type: 9 # package
access_mode: 2

View File

@ -105,3 +105,21 @@
org_id: 23
team_id: 17
uid: 5
-
id: 19
org_id: 35
team_id: 18
uid: 1
-
id: 20
org_id: 36
team_id: 19
uid: 1
-
id: 21
org_id: 36
team_id: 20
uid: 5

View File

@ -1258,3 +1258,77 @@
repo_admin_change_team_access: false
theme: ""
keep_activity_private: false
-
id: 35
lower_name: private_org35
name: private_org35
full_name: Private Org 35
email: private_org35@example.com
keep_email_private: false
email_notifications_preference: enabled
passwd: ZogKvWdyEx:password
passwd_hash_algo: dummy
must_change_password: false
login_source: 0
login_name: private_org35
type: 1
salt: ZogKvWdyEx
max_repo_creation: -1
is_active: true
is_admin: false
is_restricted: false
allow_git_hook: false
allow_import_local: false
allow_create_organization: true
prohibit_login: false
avatar: avatar35
avatar_email: private_org35@example.com
use_custom_avatar: false
num_followers: 0
num_following: 0
num_stars: 0
num_repos: 0
num_teams: 1
num_members: 1
visibility: 2
repo_admin_change_team_access: false
theme: ""
keep_activity_private: false
-
id: 36
lower_name: limited_org36
name: limited_org36
full_name: Limited Org 36
email: limited_org36@example.com
keep_email_private: false
email_notifications_preference: enabled
passwd: ZogKvWdyEx:password
passwd_hash_algo: dummy
must_change_password: false
login_source: 0
login_name: limited_org36
type: 1
salt: ZogKvWdyEx
max_repo_creation: -1
is_active: true
is_admin: false
is_restricted: false
allow_git_hook: false
allow_import_local: false
allow_create_organization: true
prohibit_login: false
avatar: avatar22
avatar_email: limited_org36@example.com
use_custom_avatar: false
num_followers: 0
num_following: 0
num_stars: 0
num_repos: 0
num_teams: 2
num_members: 2
visibility: 1
repo_admin_change_team_access: false
theme: ""
keep_activity_private: false

403
models/git/branch.go Normal file
View File

@ -0,0 +1,403 @@
// Copyright 2016 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package git
import (
"context"
"fmt"
"time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder"
)
// ErrBranchNotExist represents an error that branch with such name does not exist.
type ErrBranchNotExist struct {
RepoID int64
BranchName string
}
// IsErrBranchNotExist checks if an error is an ErrBranchDoesNotExist.
func IsErrBranchNotExist(err error) bool {
_, ok := err.(ErrBranchNotExist)
return ok
}
func (err ErrBranchNotExist) Error() string {
return fmt.Sprintf("branch does not exist [repo_id: %d name: %s]", err.RepoID, err.BranchName)
}
func (err ErrBranchNotExist) Unwrap() error {
return util.ErrNotExist
}
// ErrBranchAlreadyExists represents an error that branch with such name already exists.
type ErrBranchAlreadyExists struct {
BranchName string
}
// IsErrBranchAlreadyExists checks if an error is an ErrBranchAlreadyExists.
func IsErrBranchAlreadyExists(err error) bool {
_, ok := err.(ErrBranchAlreadyExists)
return ok
}
func (err ErrBranchAlreadyExists) Error() string {
return fmt.Sprintf("branch already exists [name: %s]", err.BranchName)
}
func (err ErrBranchAlreadyExists) Unwrap() error {
return util.ErrAlreadyExist
}
// ErrBranchNameConflict represents an error that branch name conflicts with other branch.
type ErrBranchNameConflict struct {
BranchName string
}
// IsErrBranchNameConflict checks if an error is an ErrBranchNameConflict.
func IsErrBranchNameConflict(err error) bool {
_, ok := err.(ErrBranchNameConflict)
return ok
}
func (err ErrBranchNameConflict) Error() string {
return fmt.Sprintf("branch conflicts with existing branch [name: %s]", err.BranchName)
}
func (err ErrBranchNameConflict) Unwrap() error {
return util.ErrAlreadyExist
}
// ErrBranchesEqual represents an error that base branch is equal to the head branch.
type ErrBranchesEqual struct {
BaseBranchName string
HeadBranchName string
}
// IsErrBranchesEqual checks if an error is an ErrBranchesEqual.
func IsErrBranchesEqual(err error) bool {
_, ok := err.(ErrBranchesEqual)
return ok
}
func (err ErrBranchesEqual) Error() string {
return fmt.Sprintf("branches are equal [head: %sm base: %s]", err.HeadBranchName, err.BaseBranchName)
}
func (err ErrBranchesEqual) Unwrap() error {
return util.ErrInvalidArgument
}
// Branch represents a branch of a repository
// For those repository who have many branches, stored into database is a good choice
// for pagination, keyword search and filtering
type Branch struct {
ID int64
RepoID int64 `xorm:"UNIQUE(s)"`
Name string `xorm:"UNIQUE(s) NOT NULL"` // git's ref-name is case-sensitive internally, however, in some databases (mssql, mysql, by default), it's case-insensitive at the moment
CommitID string
CommitMessage string `xorm:"TEXT"` // it only stores the message summary (the first line)
PusherID int64
Pusher *user_model.User `xorm:"-"`
IsDeleted bool `xorm:"index"`
DeletedByID int64
DeletedBy *user_model.User `xorm:"-"`
DeletedUnix timeutil.TimeStamp `xorm:"index"`
CommitTime timeutil.TimeStamp // The commit
CreatedUnix timeutil.TimeStamp `xorm:"created"`
UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
}
func (b *Branch) LoadDeletedBy(ctx context.Context) (err error) {
if b.DeletedBy == nil {
b.DeletedBy, err = user_model.GetUserByID(ctx, b.DeletedByID)
if user_model.IsErrUserNotExist(err) {
b.DeletedBy = user_model.NewGhostUser()
err = nil
}
}
return err
}
func (b *Branch) LoadPusher(ctx context.Context) (err error) {
if b.Pusher == nil && b.PusherID > 0 {
b.Pusher, err = user_model.GetUserByID(ctx, b.PusherID)
if user_model.IsErrUserNotExist(err) {
b.Pusher = user_model.NewGhostUser()
err = nil
}
}
return err
}
func init() {
db.RegisterModel(new(Branch))
db.RegisterModel(new(RenamedBranch))
}
func GetBranch(ctx context.Context, repoID int64, branchName string) (*Branch, error) {
var branch Branch
has, err := db.GetEngine(ctx).Where("repo_id=?", repoID).And("name=?", branchName).Get(&branch)
if err != nil {
return nil, err
} else if !has {
return nil, ErrBranchNotExist{
RepoID: repoID,
BranchName: branchName,
}
}
return &branch, nil
}
func AddBranches(ctx context.Context, branches []*Branch) error {
for _, branch := range branches {
if _, err := db.GetEngine(ctx).Insert(branch); err != nil {
return err
}
}
return nil
}
func GetDeletedBranchByID(ctx context.Context, repoID, branchID int64) (*Branch, error) {
var branch Branch
has, err := db.GetEngine(ctx).ID(branchID).Get(&branch)
if err != nil {
return nil, err
} else if !has {
return nil, ErrBranchNotExist{
RepoID: repoID,
}
}
if branch.RepoID != repoID {
return nil, ErrBranchNotExist{
RepoID: repoID,
}
}
if !branch.IsDeleted {
return nil, ErrBranchNotExist{
RepoID: repoID,
}
}
return &branch, nil
}
func DeleteBranches(ctx context.Context, repoID, doerID int64, branchIDs []int64) error {
return db.WithTx(ctx, func(ctx context.Context) error {
branches := make([]*Branch, 0, len(branchIDs))
if err := db.GetEngine(ctx).In("id", branchIDs).Find(&branches); err != nil {
return err
}
for _, branch := range branches {
if err := AddDeletedBranch(ctx, repoID, branch.Name, doerID); err != nil {
return err
}
}
return nil
})
}
// UpdateBranch updates the branch information in the database. If the branch exist, it will update latest commit of this branch information
// If it doest not exist, insert a new record into database
func UpdateBranch(ctx context.Context, repoID, pusherID int64, branchName string, commit *git.Commit) error {
cnt, err := db.GetEngine(ctx).Where("repo_id=? AND name=?", repoID, branchName).
Cols("commit_id, commit_message, pusher_id, commit_time, is_deleted, updated_unix").
Update(&Branch{
CommitID: commit.ID.String(),
CommitMessage: commit.Summary(),
PusherID: pusherID,
CommitTime: timeutil.TimeStamp(commit.Committer.When.Unix()),
IsDeleted: false,
})
if err != nil {
return err
}
if cnt > 0 {
return nil
}
return db.Insert(ctx, &Branch{
RepoID: repoID,
Name: branchName,
CommitID: commit.ID.String(),
CommitMessage: commit.Summary(),
PusherID: pusherID,
CommitTime: timeutil.TimeStamp(commit.Committer.When.Unix()),
})
}
// AddDeletedBranch adds a deleted branch to the database
func AddDeletedBranch(ctx context.Context, repoID int64, branchName string, deletedByID int64) error {
branch, err := GetBranch(ctx, repoID, branchName)
if err != nil {
return err
}
if branch.IsDeleted {
return nil
}
cnt, err := db.GetEngine(ctx).Where("repo_id=? AND name=? AND is_deleted=?", repoID, branchName, false).
Cols("is_deleted, deleted_by_id, deleted_unix").
Update(&Branch{
IsDeleted: true,
DeletedByID: deletedByID,
DeletedUnix: timeutil.TimeStampNow(),
})
if err != nil {
return err
}
if cnt == 0 {
return fmt.Errorf("branch %s not found or has been deleted", branchName)
}
return err
}
func RemoveDeletedBranchByID(ctx context.Context, repoID, branchID int64) error {
_, err := db.GetEngine(ctx).Where("repo_id=? AND id=? AND is_deleted = ?", repoID, branchID, true).Delete(new(Branch))
return err
}
// RemoveOldDeletedBranches removes old deleted branches
func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
// Nothing to do for shutdown or terminate
log.Trace("Doing: DeletedBranchesCleanup")
deleteBefore := time.Now().Add(-olderThan)
_, err := db.GetEngine(ctx).Where("is_deleted=? AND deleted_unix < ?", true, deleteBefore.Unix()).Delete(new(Branch))
if err != nil {
log.Error("DeletedBranchesCleanup: %v", err)
}
}
// RenamedBranch provide renamed branch log
// will check it when a branch can't be found
type RenamedBranch struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX NOT NULL"`
From string
To string
CreatedUnix timeutil.TimeStamp `xorm:"created"`
}
// FindRenamedBranch check if a branch was renamed
func FindRenamedBranch(ctx context.Context, repoID int64, from string) (branch *RenamedBranch, exist bool, err error) {
branch = &RenamedBranch{
RepoID: repoID,
From: from,
}
exist, err = db.GetEngine(ctx).Get(branch)
return branch, exist, err
}
// RenameBranch rename a branch
func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to string, gitAction func(isDefault bool) error) (err error) {
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}
defer committer.Close()
sess := db.GetEngine(ctx)
// 1. update branch in database
if n, err := sess.Where("repo_id=? AND name=?", repo.ID, from).Update(&Branch{
Name: to,
}); err != nil {
return err
} else if n <= 0 {
return ErrBranchNotExist{
RepoID: repo.ID,
BranchName: from,
}
}
// 2. update default branch if needed
isDefault := repo.DefaultBranch == from
if isDefault {
repo.DefaultBranch = to
_, err = sess.ID(repo.ID).Cols("default_branch").Update(repo)
if err != nil {
return err
}
}
// 3. Update protected branch if needed
protectedBranch, err := GetProtectedBranchRuleByName(ctx, repo.ID, from)
if err != nil {
return err
}
if protectedBranch != nil {
// there is a protect rule for this branch
protectedBranch.RuleName = to
_, err = sess.ID(protectedBranch.ID).Cols("branch_name").Update(protectedBranch)
if err != nil {
return err
}
} else {
// some glob protect rules may match this branch
protected, err := IsBranchProtected(ctx, repo.ID, from)
if err != nil {
return err
}
if protected {
return ErrBranchIsProtected
}
}
// 4. Update all not merged pull request base branch name
_, err = sess.Table("pull_request").Where("base_repo_id=? AND base_branch=? AND has_merged=?",
repo.ID, from, false).
Update(map[string]any{"base_branch": to})
if err != nil {
return err
}
// 5. do git action
if err = gitAction(isDefault); err != nil {
return err
}
// 6. insert renamed branch record
renamedBranch := &RenamedBranch{
RepoID: repo.ID,
From: from,
To: to,
}
err = db.Insert(ctx, renamedBranch)
if err != nil {
return err
}
return committer.Commit()
}
// FindRecentlyPushedNewBranches return at most 2 new branches pushed by the user in 6 hours which has no opened PRs created
// except the indicate branch
func FindRecentlyPushedNewBranches(ctx context.Context, repoID, userID int64, excludeBranchName string) (BranchList, error) {
branches := make(BranchList, 0, 2)
subQuery := builder.Select("head_branch").From("pull_request").
InnerJoin("issue", "issue.id = pull_request.issue_id").
Where(builder.Eq{
"pull_request.head_repo_id": repoID,
"issue.is_closed": false,
})
err := db.GetEngine(ctx).
Where("pusher_id=? AND is_deleted=?", userID, false).
And("name <> ?", excludeBranchName).
And("updated_unix >= ?", time.Now().Add(-time.Hour*6).Unix()).
NotIn("name", subQuery).
OrderBy("branch.updated_unix DESC").
Limit(2).
Find(&branches)
return branches, err
}

145
models/git/branch_list.go Normal file
View File

@ -0,0 +1,145 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package git
import (
"context"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/container"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder"
"xorm.io/xorm"
)
type BranchList []*Branch
func (branches BranchList) LoadDeletedBy(ctx context.Context) error {
ids := container.Set[int64]{}
for _, branch := range branches {
if !branch.IsDeleted {
continue
}
ids.Add(branch.DeletedByID)
}
usersMap := make(map[int64]*user_model.User, len(ids))
if err := db.GetEngine(ctx).In("id", ids.Values()).Find(&usersMap); err != nil {
return err
}
for _, branch := range branches {
if !branch.IsDeleted {
continue
}
branch.DeletedBy = usersMap[branch.DeletedByID]
if branch.DeletedBy == nil {
branch.DeletedBy = user_model.NewGhostUser()
}
}
return nil
}
func (branches BranchList) LoadPusher(ctx context.Context) error {
ids := container.Set[int64]{}
for _, branch := range branches {
if branch.PusherID > 0 { // pusher_id maybe zero because some branches are sync by backend with no pusher
ids.Add(branch.PusherID)
}
}
usersMap := make(map[int64]*user_model.User, len(ids))
if err := db.GetEngine(ctx).In("id", ids.Values()).Find(&usersMap); err != nil {
return err
}
for _, branch := range branches {
if branch.PusherID <= 0 {
continue
}
branch.Pusher = usersMap[branch.PusherID]
if branch.Pusher == nil {
branch.Pusher = user_model.NewGhostUser()
}
}
return nil
}
type FindBranchOptions struct {
db.ListOptions
RepoID int64
ExcludeBranchNames []string
IsDeletedBranch util.OptionalBool
OrderBy string
}
func (opts *FindBranchOptions) Cond() builder.Cond {
cond := builder.NewCond()
if opts.RepoID > 0 {
cond = cond.And(builder.Eq{"repo_id": opts.RepoID})
}
if len(opts.ExcludeBranchNames) > 0 {
cond = cond.And(builder.NotIn("name", opts.ExcludeBranchNames))
}
if !opts.IsDeletedBranch.IsNone() {
cond = cond.And(builder.Eq{"is_deleted": opts.IsDeletedBranch.IsTrue()})
}
return cond
}
func CountBranches(ctx context.Context, opts FindBranchOptions) (int64, error) {
return db.GetEngine(ctx).Where(opts.Cond()).Count(&Branch{})
}
func orderByBranches(sess *xorm.Session, opts FindBranchOptions) *xorm.Session {
if !opts.IsDeletedBranch.IsFalse() { // if deleted branch included, put them at the end
sess = sess.OrderBy("is_deleted ASC")
}
if opts.OrderBy == "" {
// the commit_time might be the same, so add the "name" to make sure the order is stable
opts.OrderBy = "commit_time DESC, name ASC"
}
return sess.OrderBy(opts.OrderBy)
}
func FindBranches(ctx context.Context, opts FindBranchOptions) (BranchList, error) {
sess := db.GetEngine(ctx).Where(opts.Cond())
if opts.PageSize > 0 && !opts.IsListAll() {
sess = db.SetSessionPagination(sess, &opts.ListOptions)
}
sess = orderByBranches(sess, opts)
var branches []*Branch
return branches, sess.Find(&branches)
}
func FindBranchNames(ctx context.Context, opts FindBranchOptions) ([]string, error) {
sess := db.GetEngine(ctx).Select("name").Where(opts.Cond())
if opts.PageSize > 0 && !opts.IsListAll() {
sess = db.SetSessionPagination(sess, &opts.ListOptions)
}
sess = orderByBranches(sess, opts)
var branches []string
if err := sess.Table("branch").Find(&branches); err != nil {
return nil, err
}
return branches, nil
}
func FindBranchesByRepoAndBranchName(ctx context.Context, repoBranches map[int64]string) (map[int64]string, error) {
cond := builder.NewCond()
for repoID, branchName := range repoBranches {
cond = cond.Or(builder.And(builder.Eq{"repo_id": repoID}, builder.Eq{"name": branchName}))
}
var branches []*Branch
if err := db.GetEngine(ctx).
Where(cond).Find(&branches); err != nil {
return nil, err
}
branchMap := make(map[int64]string, len(branches))
for _, branch := range branches {
branchMap[branch.RepoID] = branch.CommitID
}
return branchMap, nil
}

View File

@ -11,6 +11,8 @@ import (
issues_model "code.gitea.io/gitea/models/issues"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert"
)
@ -18,24 +20,45 @@ import (
func TestAddDeletedBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.DeletedBranch{ID: 1})
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
assert.Error(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, firstBranch.Name, firstBranch.Commit, firstBranch.DeletedByID))
assert.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, "test", "5655464564554545466464656", int64(1)))
assert.True(t, firstBranch.IsDeleted)
assert.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, firstBranch.Name, firstBranch.DeletedByID))
assert.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, "branch2", int64(1)))
secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo.ID, Name: "branch2"})
assert.True(t, secondBranch.IsDeleted)
commit := &git.Commit{
ID: git.MustIDFromString(secondBranch.CommitID),
CommitMessage: secondBranch.CommitMessage,
Committer: &git.Signature{
When: secondBranch.CommitTime.AsLocalTime(),
},
}
err := git_model.UpdateBranch(db.DefaultContext, repo.ID, secondBranch.PusherID, secondBranch.Name, commit)
assert.NoError(t, err)
}
func TestGetDeletedBranches(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
branches, err := git_model.GetDeletedBranches(db.DefaultContext, repo.ID)
branches, err := git_model.FindBranches(db.DefaultContext, git_model.FindBranchOptions{
ListOptions: db.ListOptions{
ListAll: true,
},
RepoID: repo.ID,
IsDeletedBranch: util.OptionalBoolTrue,
})
assert.NoError(t, err)
assert.Len(t, branches, 2)
}
func TestGetDeletedBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.DeletedBranch{ID: 1})
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
assert.NotNil(t, getDeletedBranch(t, firstBranch))
}
@ -43,18 +66,18 @@ func TestGetDeletedBranch(t *testing.T) {
func TestDeletedBranchLoadUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.DeletedBranch{ID: 1})
secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.DeletedBranch{ID: 2})
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 2})
branch := getDeletedBranch(t, firstBranch)
assert.Nil(t, branch.DeletedBy)
branch.LoadUser(db.DefaultContext)
branch.LoadDeletedBy(db.DefaultContext)
assert.NotNil(t, branch.DeletedBy)
assert.Equal(t, "user1", branch.DeletedBy.Name)
branch = getDeletedBranch(t, secondBranch)
assert.Nil(t, branch.DeletedBy)
branch.LoadUser(db.DefaultContext)
branch.LoadDeletedBy(db.DefaultContext)
assert.NotNil(t, branch.DeletedBy)
assert.Equal(t, "Ghost", branch.DeletedBy.Name)
}
@ -63,22 +86,22 @@ func TestRemoveDeletedBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.DeletedBranch{ID: 1})
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
err := git_model.RemoveDeletedBranchByID(db.DefaultContext, repo.ID, 1)
assert.NoError(t, err)
unittest.AssertNotExistsBean(t, firstBranch)
unittest.AssertExistsAndLoadBean(t, &git_model.DeletedBranch{ID: 2})
unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 2})
}
func getDeletedBranch(t *testing.T, branch *git_model.DeletedBranch) *git_model.DeletedBranch {
func getDeletedBranch(t *testing.T, branch *git_model.Branch) *git_model.Branch {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo.ID, branch.ID)
assert.NoError(t, err)
assert.Equal(t, branch.ID, deletedBranch.ID)
assert.Equal(t, branch.Name, deletedBranch.Name)
assert.Equal(t, branch.Commit, deletedBranch.Commit)
assert.Equal(t, branch.CommitID, deletedBranch.CommitID)
assert.Equal(t, branch.DeletedByID, deletedBranch.DeletedByID)
return deletedBranch
@ -146,8 +169,8 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) {
deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo2.ID, 1)
// Expect no error, and the returned branch is nil.
assert.NoError(t, err)
// Expect error, and the returned branch is nil.
assert.Error(t, err)
assert.Nil(t, deletedBranch)
// Now get the deletedBranch with ID of 1 on repo with ID 1.

View File

@ -1,197 +0,0 @@
// Copyright 2016 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package git
import (
"context"
"fmt"
"time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil"
)
// DeletedBranch struct
type DeletedBranch struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
Name string `xorm:"UNIQUE(s) NOT NULL"`
Commit string `xorm:"UNIQUE(s) NOT NULL"`
DeletedByID int64 `xorm:"INDEX"`
DeletedBy *user_model.User `xorm:"-"`
DeletedUnix timeutil.TimeStamp `xorm:"INDEX created"`
}
func init() {
db.RegisterModel(new(DeletedBranch))
db.RegisterModel(new(RenamedBranch))
}
// AddDeletedBranch adds a deleted branch to the database
func AddDeletedBranch(ctx context.Context, repoID int64, branchName, commit string, deletedByID int64) error {
deletedBranch := &DeletedBranch{
RepoID: repoID,
Name: branchName,
Commit: commit,
DeletedByID: deletedByID,
}
_, err := db.GetEngine(ctx).Insert(deletedBranch)
return err
}
// GetDeletedBranches returns all the deleted branches
func GetDeletedBranches(ctx context.Context, repoID int64) ([]*DeletedBranch, error) {
deletedBranches := make([]*DeletedBranch, 0)
return deletedBranches, db.GetEngine(ctx).Where("repo_id = ?", repoID).Desc("deleted_unix").Find(&deletedBranches)
}
// GetDeletedBranchByID get a deleted branch by its ID
func GetDeletedBranchByID(ctx context.Context, repoID, id int64) (*DeletedBranch, error) {
deletedBranch := &DeletedBranch{}
has, err := db.GetEngine(ctx).Where("repo_id = ?", repoID).And("id = ?", id).Get(deletedBranch)
if err != nil {
return nil, err
}
if !has {
return nil, nil
}
return deletedBranch, nil
}
// RemoveDeletedBranchByID removes a deleted branch from the database
func RemoveDeletedBranchByID(ctx context.Context, repoID, id int64) (err error) {
deletedBranch := &DeletedBranch{
RepoID: repoID,
ID: id,
}
if affected, err := db.GetEngine(ctx).Delete(deletedBranch); err != nil {
return err
} else if affected != 1 {
return fmt.Errorf("remove deleted branch ID(%v) failed", id)
}
return nil
}
// LoadUser loads the user that deleted the branch
// When there's no user found it returns a user_model.NewGhostUser
func (deletedBranch *DeletedBranch) LoadUser(ctx context.Context) {
user, err := user_model.GetUserByID(ctx, deletedBranch.DeletedByID)
if err != nil {
user = user_model.NewGhostUser()
}
deletedBranch.DeletedBy = user
}
// RemoveDeletedBranchByName removes all deleted branches
func RemoveDeletedBranchByName(ctx context.Context, repoID int64, branch string) error {
_, err := db.GetEngine(ctx).Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
return err
}
// RemoveOldDeletedBranches removes old deleted branches
func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
// Nothing to do for shutdown or terminate
log.Trace("Doing: DeletedBranchesCleanup")
deleteBefore := time.Now().Add(-olderThan)
_, err := db.GetEngine(ctx).Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
if err != nil {
log.Error("DeletedBranchesCleanup: %v", err)
}
}
// RenamedBranch provide renamed branch log
// will check it when a branch can't be found
type RenamedBranch struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX NOT NULL"`
From string
To string
CreatedUnix timeutil.TimeStamp `xorm:"created"`
}
// FindRenamedBranch check if a branch was renamed
func FindRenamedBranch(ctx context.Context, repoID int64, from string) (branch *RenamedBranch, exist bool, err error) {
branch = &RenamedBranch{
RepoID: repoID,
From: from,
}
exist, err = db.GetEngine(ctx).Get(branch)
return branch, exist, err
}
// RenameBranch rename a branch
func RenameBranch(ctx context.Context, repo *repo_model.Repository, from, to string, gitAction func(isDefault bool) error) (err error) {
ctx, committer, err := db.TxContext(ctx)
if err != nil {
return err
}
defer committer.Close()
sess := db.GetEngine(ctx)
// 1. update default branch if needed
isDefault := repo.DefaultBranch == from
if isDefault {
repo.DefaultBranch = to
_, err = sess.ID(repo.ID).Cols("default_branch").Update(repo)
if err != nil {
return err
}
}
// 2. Update protected branch if needed
protectedBranch, err := GetProtectedBranchRuleByName(ctx, repo.ID, from)
if err != nil {
return err
}
if protectedBranch != nil {
protectedBranch.RuleName = to
_, err = sess.ID(protectedBranch.ID).Cols("branch_name").Update(protectedBranch)
if err != nil {
return err
}
} else {
protected, err := IsBranchProtected(ctx, repo.ID, from)
if err != nil {
return err
}
if protected {
return ErrBranchIsProtected
}
}
// 3. Update all not merged pull request base branch name
_, err = sess.Table("pull_request").Where("base_repo_id=? AND base_branch=? AND has_merged=?",
repo.ID, from, false).
Update(map[string]interface{}{"base_branch": to})
if err != nil {
return err
}
// 4. do git action
if err = gitAction(isDefault); err != nil {
return err
}
// 5. insert renamed branch record
renamedBranch := &RenamedBranch{
RepoID: repo.ID,
From: from,
To: to,
}
err = db.Insert(ctx, renamedBranch)
if err != nil {
return err
}
return committer.Commit()
}

View File

@ -346,6 +346,53 @@ func GetLatestCommitStatusForPairs(ctx context.Context, repoIDsToLatestCommitSHA
return repoStatuses, nil
}
// GetLatestCommitStatusForRepoCommitIDs returns all statuses with a unique context for a given list of repo-sha pairs
func GetLatestCommitStatusForRepoCommitIDs(ctx context.Context, repoID int64, commitIDs []string) (map[string][]*CommitStatus, error) {
type result struct {
ID int64
Sha string
}
results := make([]result, 0, len(commitIDs))
sess := db.GetEngine(ctx).Table(&CommitStatus{})
// Create a disjunction of conditions for each repoID and SHA pair
conds := make([]builder.Cond, 0, len(commitIDs))
for _, sha := range commitIDs {
conds = append(conds, builder.Eq{"sha": sha})
}
sess = sess.Where(builder.Eq{"repo_id": repoID}.And(builder.Or(conds...))).
Select("max( id ) as id, sha").
GroupBy("context_hash, sha").OrderBy("max( id ) desc")
err := sess.Find(&results)
if err != nil {
return nil, err
}
ids := make([]int64, 0, len(results))
repoStatuses := make(map[string][]*CommitStatus)
for _, result := range results {
ids = append(ids, result.ID)
}
statuses := make([]*CommitStatus, 0, len(ids))
if len(ids) > 0 {
err = db.GetEngine(ctx).In("id", ids).Find(&statuses)
if err != nil {
return nil, err
}
// Group the statuses by repo ID
for _, status := range statuses {
repoStatuses[status.SHA] = append(repoStatuses[status.SHA], status)
}
}
return repoStatuses, nil
}
// FindRepoRecentCommitStatusContexts returns repository's recent commit status contexts
func FindRepoRecentCommitStatusContexts(ctx context.Context, repoID int64, before time.Duration) ([]string, error) {
start := timeutil.TimeStampNow().AddDuration(-before)

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