mirror of
https://github.com/go-gitea/gitea
synced 2024-12-22 03:57:51 +01:00
Merge branch 'main' into lunny/fix_edit_team
This commit is contained in:
commit
c7262d65c7
@ -524,6 +524,7 @@ rules:
|
||||
no-jquery/no-data: [0]
|
||||
no-jquery/no-deferred: [2]
|
||||
no-jquery/no-delegate: [2]
|
||||
no-jquery/no-done-fail: [2]
|
||||
no-jquery/no-each-collection: [0]
|
||||
no-jquery/no-each-util: [0]
|
||||
no-jquery/no-each: [0]
|
||||
@ -538,6 +539,7 @@ rules:
|
||||
no-jquery/no-find-util: [2]
|
||||
no-jquery/no-find: [0]
|
||||
no-jquery/no-fx-interval: [2]
|
||||
no-jquery/no-fx: [2]
|
||||
no-jquery/no-global-eval: [2]
|
||||
no-jquery/no-global-selector: [0]
|
||||
no-jquery/no-grep: [2]
|
||||
@ -642,7 +644,7 @@ rules:
|
||||
no-this-before-super: [2]
|
||||
no-throw-literal: [2]
|
||||
no-undef-init: [2]
|
||||
no-undef: [2, {typeof: true}]
|
||||
no-undef: [2, {typeof: true}] # TODO: disable this rule after tsc passes
|
||||
no-undefined: [0]
|
||||
no-underscore-dangle: [0]
|
||||
no-unexpected-multiline: [2]
|
||||
|
8
.github/workflows/pull-compliance.yml
vendored
8
.github/workflows/pull-compliance.yml
vendored
@ -37,7 +37,7 @@ jobs:
|
||||
python-version: "3.12"
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- run: pip install poetry
|
||||
@ -66,7 +66,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- run: make deps-frontend
|
||||
@ -137,7 +137,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- run: make deps-frontend
|
||||
@ -186,7 +186,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- run: make deps-frontend
|
||||
|
10
.github/workflows/pull-db-tests.yml
vendored
10
.github/workflows/pull-db-tests.yml
vendored
@ -154,12 +154,15 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
# the bitnami mysql image has more options than the official one, it's easier to customize
|
||||
image: bitnami/mysql:8.0
|
||||
env:
|
||||
MYSQL_ALLOW_EMPTY_PASSWORD: true
|
||||
ALLOW_EMPTY_PASSWORD: true
|
||||
MYSQL_DATABASE: testgitea
|
||||
ports:
|
||||
- "3306:3306"
|
||||
options: >-
|
||||
--mount type=tmpfs,destination=/bitnami/mysql/data
|
||||
elasticsearch:
|
||||
image: elasticsearch:7.5.0
|
||||
env:
|
||||
@ -188,7 +191,8 @@ jobs:
|
||||
- name: run migration tests
|
||||
run: make test-mysql-migration
|
||||
- name: run tests
|
||||
run: make integration-test-coverage
|
||||
# run: make integration-test-coverage (at the moment, no coverage is really handled)
|
||||
run: make test-mysql
|
||||
env:
|
||||
TAGS: bindata
|
||||
RACE_ENABLED: true
|
||||
|
2
.github/workflows/pull-e2e-tests.yml
vendored
2
.github/workflows/pull-e2e-tests.yml
vendored
@ -23,7 +23,7 @@ jobs:
|
||||
check-latest: true
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- run: make deps-frontend frontend deps-backend
|
||||
|
2
.github/workflows/release-nightly.yml
vendored
2
.github/workflows/release-nightly.yml
vendored
@ -22,7 +22,7 @@ jobs:
|
||||
check-latest: true
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- run: make deps-frontend deps-backend
|
||||
|
2
.github/workflows/release-tag-rc.yml
vendored
2
.github/workflows/release-tag-rc.yml
vendored
@ -23,7 +23,7 @@ jobs:
|
||||
check-latest: true
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- run: make deps-frontend deps-backend
|
||||
|
2
.github/workflows/release-tag-version.yml
vendored
2
.github/workflows/release-tag-version.yml
vendored
@ -25,7 +25,7 @@ jobs:
|
||||
check-latest: true
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- run: make deps-frontend deps-backend
|
||||
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -28,6 +28,7 @@ _testmain.go
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
*.tsbuildinfo
|
||||
|
||||
*coverage.out
|
||||
coverage.all
|
||||
|
393
CHANGELOG.md
393
CHANGELOG.md
@ -4,6 +4,399 @@ This changelog goes through 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.com).
|
||||
|
||||
## [1.22.4](https://github.com/go-gitea/gitea/releases/tag/v1.22.4) - 2024-11-14
|
||||
|
||||
* SECURITY
|
||||
* Fix basic auth with webauthn (#32531) (#32536)
|
||||
* Refactor internal routers (partial backport, auth token const time comparing) (#32473) (#32479)
|
||||
* PERFORMANCE
|
||||
* Remove transaction for archive download (#32186) (#32520)
|
||||
* BUGFIXES
|
||||
* Fix `missing signature key` error when pulling Docker images with `SERVE_DIRECT` enabled (#32365) (#32397)
|
||||
* Fix get reviewers fails when selecting user without pull request permissions unit (#32415) (#32616)
|
||||
* Fix adding index files to tmp directory (#32360) (#32593)
|
||||
* Fix PR creation on forked repositories via API (#31863) (#32591)
|
||||
* Fix missing menu tabs in organization project view page (#32313) (#32592)
|
||||
* Support HTTP POST requests to `/userinfo`, aligning to OpenID Core specification (#32578) (#32594)
|
||||
* Fix debian package clean up cron job (#32351) (#32590)
|
||||
* Fix GetInactiveUsers (#32540) (#32588)
|
||||
* Allow the actions user to login via the jwt token (#32527) (#32580)
|
||||
* Fix submodule parsing (#32571) (#32577)
|
||||
* Refactor find forks and fix possible bugs that weaken permissions check (#32528) (#32547)
|
||||
* Fix some places that don't respect org full name setting (#32243) (#32550)
|
||||
* Refactor push mirror find and add check for updating push mirror (#32539) (#32549)
|
||||
* Fix basic auth with webauthn (#32531) (#32536)
|
||||
* Fix artifact v4 upload above 8MB (#31664) (#32523)
|
||||
* Fix oauth2 error handle not return immediately (#32514) (#32516)
|
||||
* Fix action not triggered when commit message is too long (#32498) (#32507)
|
||||
* Fix `GetRepoLink` nil pointer dereference on dashboard feed page when repo is deleted with actions enabled (#32501) (#32502)
|
||||
* Fix `missing signature key` error when pulling Docker images with `SERVE_DIRECT` enabled (#32397) (#32397)
|
||||
* Fix the permission check for user search API and limit the number of returned users for `/user/search` (#32310)
|
||||
* Fix SearchIssues swagger docs (#32208) (#32298)
|
||||
* Fix dropdown content overflow (#31610) (#32250)
|
||||
* Disable Oauth check if oauth disabled (#32368) (#32480)
|
||||
* Respect renamed dependencies of Cargo registry (#32430) (#32478)
|
||||
* Fix mermaid diagram height when initially hidden (#32457) (#32464)
|
||||
* Fix broken releases when re-pushing tags (#32435) (#32449)
|
||||
* Only provide the commit summary for Discord webhook push events (#32432) (#32447)
|
||||
* Only query team tables if repository is under org when getting assignees (#32414) (#32426)
|
||||
* Fix created_unix for mirroring (#32342) (#32406)
|
||||
* Respect UI.ExploreDefaultSort setting again (#32357) (#32385)
|
||||
* Fix broken image when editing comment with non-image attachments (#32319) (#32345)
|
||||
* Fix disable 2fa bug (#32320) (#32330)
|
||||
* Always update expiration time when creating an artifact (#32281) (#32285)
|
||||
* Fix null errors on conversation holder (#32258) (#32266) (#32282)
|
||||
* Only rename a user when they should receive a different name (#32247) (#32249)
|
||||
* Fix checkbox bug on private/archive filter (#32236) (#32240)
|
||||
* Add a doctor check to disable the "Actions" unit for mirrors (#32424) (#32497)
|
||||
* Quick fix milestone deadline 9999 (#32423)
|
||||
* Make `show stats` work when only one file changed (#32244) (#32268)
|
||||
* Make `owner/repo/pulls` handlers use "PR reader" permission (#32254) (#32265)
|
||||
* Update scheduled tasks even if changes are pushed by "ActionsUser" (#32246) (#32252)
|
||||
* MISC
|
||||
* Remove unnecessary code: `GetPushMirrorsByRepoID` called on all repo pages (#32560) (#32567)
|
||||
* Improve some sanitizer rules (#32534)
|
||||
* Update nix development environment vor v1.22.x (#32495)
|
||||
* Add warn log when deleting inactive users (#32318) (#32321)
|
||||
* Update github.com/go-enry/go-enry to v2.9.1 (#32295) (#32296)
|
||||
* Warn users when they try to use a non-root-url to sign in/up (#32272) (#32273)
|
||||
|
||||
## [1.22.3](https://github.com/go-gitea/gitea/releases/tag/v1.22.3) - 2024-10-08
|
||||
|
||||
* SECURITY
|
||||
* Fix bug when a token is given public only (#32204) (#32218)
|
||||
* PERFORMANCE
|
||||
* Increase `cacheContextLifetime` to reduce false reports (#32011) (#32023)
|
||||
* Don't join repository when loading action table data (#32127) (#32143)
|
||||
* BUGFIXES
|
||||
* Fix javascript error when an anonymous user visits migration page (#32144) (#32179)
|
||||
* Don't init signing keys if oauth2 provider is disabled (#32177)
|
||||
* Fix wrong status of `Set up Job` when first step is skipped (#32120) (#32125)
|
||||
* Fix bug when deleting a migrated branch (#32075) (#32123)
|
||||
* Truncate commit message during Discord webhook push events (#31970) (#32121)
|
||||
* Allow to set branch protection in an empty repository (#32095) (#32119)
|
||||
* Fix panic when cloning with wrong ssh format. (#32076) (#32118)
|
||||
* Fix rename branch permission bug (#32066) (#32108)
|
||||
* Fix: database not update release when using `git push --tags --force` (#32040) (#32074)
|
||||
* Add missing comment reply handling (#32050) (#32065)
|
||||
* Do not escape relative path in RPM primary index (#32038) (#32054)
|
||||
* Fix `/repos/{owner}/{repo}/pulls/{index}/files` endpoint not populating `previous_filename` (#32017) (#32028)
|
||||
* Support allowed hosts for migrations to work with proxy (#32025) (#32026)
|
||||
* Fix the logic of finding the latest pull review commit ID (#32139) (#32165)
|
||||
* Fix bug in getting merged pull request by commit (#32079) (#32117)
|
||||
* Fix wrong last modify time (#32102) (#32104)
|
||||
* Fix incorrect `/tokens` api (#32085) (#32092)
|
||||
* Handle invalid target when creating releases using API (#31841) (#32043)
|
||||
* Check if the `due_date` is nil when editing issues (#32035) (#32042)
|
||||
* Fix container parallel upload bugs (#32022)
|
||||
* Fixed race condition when deleting documents by repoId in ElasticSearch (#32185) (#32188)
|
||||
* Refactor CSRF protector (#32057) (#32069)
|
||||
* Fix Bug in Issue/pulls list (#32081) (#32115)
|
||||
* Include collaboration repositories on dashboard source/forks/mirrors list (#31946) (#32122)
|
||||
* Add null check for responseData.invalidTopics (#32212) (#32217)
|
||||
* TESTING
|
||||
* Fix mssql ci with a new mssql version on ci (#32094)
|
||||
* MISC
|
||||
* Upgrade some dependencies include minio-go (#32166)
|
||||
* Add bin to Composer Metadata (#32099) (#32106)
|
||||
* Lazy load avatar images (#32051) (#32063)
|
||||
* Upgrade cache to v0.2.1 (#32003) (#32009)
|
||||
|
||||
## [1.22.2](https://github.com/go-gitea/gitea/releases/tag/v1.22.2) - 2024-08-28
|
||||
|
||||
* Security
|
||||
* Replace v-html with v-text in search inputbox (#31966) (#31973)
|
||||
* Fix nuget/conan/container packages upload bugs (#31967) (#31982)
|
||||
* PERFORMANCE
|
||||
* Refactor the usage of batch catfile (#31754) (#31889)
|
||||
* BUGFIXES
|
||||
* Fix overflowing content in action run log (#31842) (#31853)
|
||||
* Scroll images in project issues separately from the remaining issue (#31683) (#31823)
|
||||
* Add `:focus-visible` style to buttons (#31799) (#31819)
|
||||
* Fix the display of project type for deleted projects (#31732) (#31734)
|
||||
* Fix API owner ID should be zero when created repo secret (#31715) (#31811)
|
||||
* Set owner id to zero when GetRegistrationToken for repo (#31725) (#31729)
|
||||
* Fix API endpoint for registration-token (#31722) (#31728)
|
||||
* Add permission check when creating PR (#31033) (#31720)
|
||||
* Don't return 500 if mirror url contains special chars (#31859) (#31895)
|
||||
* Fix agit automerge (#31207) (#31881)
|
||||
* Add CfTurnstileSitekey context data to all captcha templates (#31874) (#31876)
|
||||
* Avoid returning without written ctx when posting PR (#31843) (#31848)
|
||||
* Fix raw wiki links (#31825) (#31845)
|
||||
* Fix panic of ssh public key page after deletion of auth source (#31829) (#31836)
|
||||
* Fixes for unreachable project issues when transfer repository from organization (#31770) (#31828)
|
||||
* Show lock owner instead of repo owner on LFS setting page (#31788) (#31817)
|
||||
* Fix `IsObjectExist` with gogit (#31790) (#31806)
|
||||
* Fix protected branch files detection on pre_receive hook (#31778) (#31796)
|
||||
* Add `TAGS` to `TEST_TAGS` and fix bugs found with gogit (#31791) (#31795)
|
||||
* Rename head branch of pull requests when renaming a branch (#31759) (#31774)
|
||||
* Fix wiki revision pagination (#31760) (#31772)
|
||||
* Bump vue-bar-graph (#31705) (#31753)
|
||||
* Distinguish LFS object errors to ignore missing objects during migration (#31702) (#31745)
|
||||
* Make GetRepositoryByName more safer (#31712) (#31718)
|
||||
* Fix a branch divergence cache bug (#31659) (#31661)
|
||||
* Allow org team names of length 255 in create team form (#31564) (#31603)
|
||||
* Use old behavior for telegram webhook (#31588)
|
||||
* Bug fix for translation in ru (#31892)
|
||||
* Fix actions notify bug (#31866) (#31875)
|
||||
* Fix the component of access token list not mounted (#31824) (#31868)
|
||||
* Add missing repository type filter parameters to pager (#31832) (#31837)
|
||||
* Fix dates displaying in a wrong manner when we're close to the end of… (#31750)
|
||||
* Fix "Filter by commit" Dropdown (#31695) (#31696)
|
||||
* Properly filter issue list given no assignees filter (#31522) (#31685)
|
||||
* Prevent update pull refs manually and will not affect other refs update (#31931)(#31955)
|
||||
* Fix sort order for organization home and user profile page (#31921) (#31922)
|
||||
* Fix search team (#31923) (#31942)
|
||||
* Fix 500 error when state params is set when editing issue/PR by API (#31880) (#31952)
|
||||
* Fix index too many file names bug (#31903) (#31953)
|
||||
* Add lock for parallel maven upload (#31851) (#31954)
|
||||
* MISC
|
||||
* Remove "dsa-1024" testcases from Test_SSHParsePublicKey and Test_calcFingerprint (#31905) (#31914)
|
||||
* Upgrade bleve to 2.4.2 (#31894)
|
||||
* Remove unneccessary uses of `word-break: break-all` (#31637) (#31652)
|
||||
* Return an empty string when a repo has no avatar in the repo API (#31187) (#31567)
|
||||
* Upgrade micromatch to 4.0.8 (#31944)
|
||||
* Update webpack to 5.94.0 (#31941)
|
||||
|
||||
## [1.22.1](https://github.com/go-gitea/gitea/releases/tag/v1.22.1) - 2024-07-04
|
||||
|
||||
* SECURITY
|
||||
* Add replacement module for `mholt/archiver` (#31267) (#31270)
|
||||
* API
|
||||
* Fix missing images in editor preview due to wrong links (#31299) (#31393)
|
||||
* Fix duplicate sub-path for avatars (#31365) (#31368)
|
||||
* Reduce memory usage for chunked artifact uploads to MinIO (#31325) (#31338)
|
||||
* Remove sub-path from container registry realm (#31293) (#31300)
|
||||
* Fix NuGet Package API for $filter with Id equality (#31188) (#31242)
|
||||
* Add an immutable tarball link to archive download headers for Nix (#31139) (#31145)
|
||||
* Add missed return after `ctx.ServerError` (#31130) (#31133)
|
||||
* BUGFIXES
|
||||
* Fix avatar radius problem on the new issue page (#31506) (#31508)
|
||||
* Fix overflow menu flickering on mobile (#31484) (#31488)
|
||||
* Fix poor table column width due to breaking words (#31473) (#31477)
|
||||
* Support relative paths to videos from Wiki pages (#31061) (#31453)
|
||||
* Fix new issue/pr avatar (#31419) (#31424)
|
||||
* Increase max length of org team names from 30 to 255 characters (#31410) (#31421)
|
||||
* Fix line number width in code preview (#31307) (#31316)
|
||||
* Optimize runner-tags layout to enhance visual experience (#31258) (#31263)
|
||||
* Fix overflow on push notification (#31179) (#31238)
|
||||
* Fix overflow on notifications (#31178) (#31237)
|
||||
* Fix overflow in issue card (#31203) (#31225)
|
||||
* Split sanitizer functions and fine-tune some tests (#31192) (#31200)
|
||||
* use correct l10n string (#31487) (#31490)
|
||||
* Fix dropzone JS error when attachment is disabled (#31486)
|
||||
* Fix web notification icon not updated once you read all notifications (#31447) (#31466)
|
||||
* Switch to "Write" tab when edit comment again (#31445) (#31461)
|
||||
* Fix the link for .git-blame-ignore-revs bypass (#31432) (#31442)
|
||||
* Fix the wrong line number in the diff view page when expanded twice. (#31431) (#31440)
|
||||
* Fix labels and projects menu overflow on issue page (#31435) (#31439)
|
||||
* Fix Account Linking UpdateMigrationsByType (#31428) (#31434)
|
||||
* Fix markdown math brackets render problem (#31420) (#31430)
|
||||
* Fix rendered wiki page link (#31398) (#31407)
|
||||
* Fix natural sort (#31384) (#31394)
|
||||
* Allow downloading attachments of draft releases (#31369) (#31380)
|
||||
* Fix repo graph JS (#31377)
|
||||
* Fix incorrect localization `explorer.go` (#31348) (#31350)
|
||||
* Fix hash render end with colon (#31319) (#31346)
|
||||
* Fix line number widths (#31341) (#31343)
|
||||
* Fix navbar `+` menu flashing on page load (#31281) (#31342)
|
||||
* Fix adopt repository has empty object name in database (#31333) (#31335)
|
||||
* Delete legacy cookie before setting new cookie (#31306) (#31317)
|
||||
* Fix some URLs whose sub-path is missing (#31289) (#31292)
|
||||
* Fix admin oauth2 custom URL settings (#31246) (#31247)
|
||||
* Make pasted "img" tag has the same behavior as markdown image (#31235) (#31243)
|
||||
* Fix agit checkout command line hint & fix ShowMergeInstructions checking (#31219) (#31222)
|
||||
* Fix the possible migration failure on 286 with postgres 16 (#31209) (#31218)
|
||||
* Fix branch order (#31174) (#31193)
|
||||
* Fix markup preview (#31158) (#31166)
|
||||
* Fix push multiple branches error with tests (#31151) (#31153)
|
||||
* Fix API repository object format missed (#31118) (#31132)
|
||||
* Fix missing memcache import (#31105) (#31109)
|
||||
* Upgrade `github.com/hashicorp/go-retryablehttp` (#31499)
|
||||
* Fix double border in system status table (#31363) (#31401)
|
||||
* Fix bug filtering issues which have no project (#31337) (#31367)
|
||||
* Fix #31185 try fix lfs download from bitbucket failed (#31201) (#31329)
|
||||
* Add nix flake for dev shell (#30967) (#31310)
|
||||
* Fix and clean up `ConfirmModal` (#31283) (#31291)
|
||||
* Optimize repo-list layout to enhance visual experience (#31272) (#31276)
|
||||
* fixed the dropdown menu for the top New button to expand to the left (#31273) (#31275)
|
||||
* Fix Activity Page Contributors dropdown (#31264) (#31269)
|
||||
* fix: allow actions artifacts storage migration to complete succesfully (#31251) (#31257)
|
||||
* Make blockquote attention recognize more syntaxes (#31240) (#31250)
|
||||
* Remove .segment from .project-column (#31204) (#31239)
|
||||
* Ignore FindRecentlyPushedNewBranches err (#31164) (#31171)
|
||||
* Use vertical layout for multiple code expander buttons (#31122) (#31152)
|
||||
* Remove duplicate `ProxyPreserveHost` in Apache httpd doc (#31143) (#31147)
|
||||
* Improve mobile review ui (#31091) (#31136)
|
||||
* Fix DashboardRepoList margin (#31121) (#31128)
|
||||
* Update pip related commands for docker (#31106) (#31111)
|
||||
|
||||
## [1.22.0](https://github.com/go-gitea/gitea/releases/tag/v1.22.0) - 2024-05-27
|
||||
|
||||
This release stands as a monumental milestone in our development journey with a record-breaking incorporation of [1528](https://github.com/go-gitea/gitea/pulls?q=is%3Apr+milestone%3A1.22.0+is%3Amerged) pull requests. It marks the most extensive update in Gitea's history, showcasing a plethora of new features and infrastructure improvements.
|
||||
|
||||
Noteworthy advancements in this release include the introduction of `HTMX` and `Tailwind`, signaling a strategic shift as we gradually phase out `jquery` and `Fomantic UI`. These changes reflect our commitment to embracing modern technologies and enhancing the user experience.
|
||||
|
||||
Key highlights of this release encompass significant changes categorized under `BREAKING`, `FEATURES`, `ENHANCEMENTS`, and `PERFORMANCE`, each contributing to a more robust and efficient Gitea platform.
|
||||
|
||||
* BREAKING
|
||||
* Improve reverse proxy documents and clarify the AppURL guessing behavior (#31003) (#31020)
|
||||
* Remember log in for a month by default (#30150)
|
||||
* Breaking summary for template refactoring (#29395)
|
||||
* All custom templates need to follow these changes
|
||||
* Recommend/convert to use case-sensitive collation for MySQL/MSSQL (#28662)
|
||||
* Make offline mode as default to not connect external avatar service by default (#28548)
|
||||
* Include public repos in the doer's dashboard for issue search (#28304)
|
||||
* Use restricted sanitizer for repository description (#28141)
|
||||
* Support storage base path as prefix (#27827)
|
||||
* Enhanced auth token / remember me (#27606)
|
||||
* Rename the default themes to `gitea-light`, `gitea-dark`, `gitea-auto` (#27419)
|
||||
* If you didn't see the new themes, please remove the `[ui].THEMES` config option from `app.ini`
|
||||
* Require MySQL 8.0, PostgreSQL 12, MSSQL 2012 (#27337)
|
||||
* FEATURES
|
||||
* Allow everyone to read or write a wiki by a repo unit setting (#30495)
|
||||
* Use raw Wiki links for non-renderable Wiki files (#30273)
|
||||
* Render embedded code preview by permalink in markdown (#30234) (#30249)
|
||||
* Support repo code search without setting up an indexer (#29998)
|
||||
* Support pasting URLs over markdown text (#29566)
|
||||
* Allow to change primary email before account activation (#29412)
|
||||
* Customizable "Open with" applications for repository clone (#29320)
|
||||
* Allow options to disable user deletion from the interface on app.ini (#29275)
|
||||
* Extend issue template YAML engine (#29274)
|
||||
* Add support for `linguist-detectable` and `linguist-documentation` (#29267)
|
||||
* Implement code frequency graph (#29191)
|
||||
* Show commit status for releases (#29149)
|
||||
* Add user blocking (#29028)
|
||||
* Actions Artifacts v4 backend (#28965)
|
||||
* Add merge style `fast-forward-only` (#28954)
|
||||
* Retarget depending pulls when the parent branch is deleted (#28686)
|
||||
* Add global setting on how timestamps should be rendered (#28657)
|
||||
* Implement actions badge SVGs (#28102)
|
||||
* Add skip ci functionality (#28075)
|
||||
* Show latest commit for file (#28067)
|
||||
* Allow to sync tags from the admin dashboard (#28045)
|
||||
* Add Profile Readme for Organisations (#27955)
|
||||
* Implement contributors graph (#27882)
|
||||
* Artifact deletion in actions ui (#27172)
|
||||
* Add API routes to get runner registration token (#27144)
|
||||
* Add support for forking single branch (#25821)
|
||||
* Add support for sha256 repositories (#23894)
|
||||
* Add admin API route for managing user's badges (#23106)
|
||||
* ENHANCEMENTS
|
||||
* Make gitea webhooks openproject compatible (#28435) (#31081)
|
||||
* Support using label names when changing issue labels (#30943) (#30958)
|
||||
* Fix various problems around project board view (#30696) (#30902)
|
||||
* Improve context popup rendering (#30824) (#30829)
|
||||
* Allow to save empty comment (#30706)
|
||||
* Prevent allow/reject reviews on merged/closed PRs (#30686)
|
||||
* Initial support for colorblindness-friendly themes (#30625)
|
||||
* Some NuGet package enhancements (#30280) (#30324)
|
||||
* Markup color and font size fixes (#30282) (#30310)
|
||||
* Show 12 lines in markup code preview (#30255) (#30257)
|
||||
* Add `[other].SHOW_FOOTER_POWERED_BY` setting to hide `Powered by` (#30253)
|
||||
* Pulse page improvements (#30149)
|
||||
* Render code tags in commit messages (#30146)
|
||||
* Prevent re-review and dismiss review actions on closed and merged PRs (#30065)
|
||||
* Cancel previous runs of the same PR automatically (#29961)
|
||||
* Drag-and-drop improvements for projects and issue pins (#29875)
|
||||
* Add default board to new projects, remove uncategorized pseudo-board (#29874)
|
||||
* Prevent layout shift in `<overflow-menu>` items (#29831)
|
||||
* Add skip ci support for pull request title (#29774)
|
||||
* Add more stats tables (#29730)
|
||||
* Update API to return 'source_id' for users (#29718)
|
||||
* Determine fuzziness of bleve indexer by keyword length (#29706)
|
||||
* Expose fuzzy search for issues/pulls (#29701)
|
||||
* Put an edit file button on pull request files to allow a quick operation (#29697)
|
||||
* Fix action runner offline label padding (#29691)
|
||||
* Update allowed attachment types (#29688)
|
||||
* Completely style the webkit autofill (#29683)
|
||||
* Highlight archived labels (#29680)
|
||||
* Add a warning for disallowed email domains (#29658)
|
||||
* Set user's 24h preference from their current OS locale (#29651)
|
||||
* Add setting to disable user features when user login type is not plain (#29615)
|
||||
* Improve natural sort (#29611)
|
||||
* Make wiki default branch name changeable (#29603)
|
||||
* Unify search boxes (#29530)
|
||||
* Add support for API blob upload of release attachments (#29507)
|
||||
* Detect broken git hooks (#29494)
|
||||
* Sync branches to DB immediately when handling git hook calling (#29493)
|
||||
* Allow options to disable user GPG key configuration from the interface on app.ini (#29486)
|
||||
* Allow options to disable user SSH key configuration from the interface on app.ini (#29447)
|
||||
* Use relative links for commits, mentions, and issues in markdown (#29427)
|
||||
* Add `<overflow-menu>`, rename webcomponents (#29400)
|
||||
* Include resource state events in Gitlab downloads (#29382)
|
||||
* Properly migrate target branch change GitLab comment (#29340)
|
||||
* Recolor dark theme to blue shade (#29283)
|
||||
* Partially enable MSSQL case-sensitive collation support (#29238)
|
||||
* Auto-update the system status in the admin dashboard (#29163)
|
||||
* Integrate alpine `noarch` packages into other architectures index (#29137)
|
||||
* Document how the TOC election process works (#29135)
|
||||
* Tweak repo header (#29134)
|
||||
* Make blockquote border size less aggressive (#29124)
|
||||
* Downscale pasted PNG images based on metadata (#29123)
|
||||
* Show `View at this point in history` for every commit (#29122)
|
||||
* Add support for action artifact serve direct (#29120)
|
||||
* Change webhook-type in create-view (#29114)
|
||||
* Drop "@" from the email sender to avoid spam filters (#29109)
|
||||
* Allow non-admin users to delete review requests (#29057)
|
||||
* Improve user search display name (#29002)
|
||||
* Include username in email headers (#28981)
|
||||
* Show whether a PR is WIP inside popups (#28975)
|
||||
* Also match weakly validated ETags (#28957)
|
||||
* Support nuspec manifest download for Nuget packages (#28921)
|
||||
* Fix hardcoded GitHub icon used as migrated release avatar (#28910)
|
||||
* Propagate install_if and provider_priority to APKINDEX (#28899)
|
||||
* Add artifacts v4 JWT to job message and accept it (#28885)
|
||||
* Enable/disable owner and repo projects independently (#28805)
|
||||
* Add non-JS fallback for reaction tooltips (#28785)
|
||||
* Add the ability to see open and closed issues at the same time (#28757)
|
||||
* Move sign-in labels to be above inputs (#28753)
|
||||
* Display the latest sync time for pull mirrors on the repo page (#28712)
|
||||
* Show in Web UI if the file is vendored and generated (#28620)
|
||||
* Add orphaned topic consistency check (#28507)
|
||||
* Add branch protection setting for ignoring stale approvals (#28498)
|
||||
* Add option to set language in admin user view (#28449)
|
||||
* Fix incorrect run order of action jobs (#28367)
|
||||
* Add missing exclusive in advanced label options (#28322)
|
||||
* Added instance-level variables (#28115)
|
||||
* Add edit option for README.md (#28071)
|
||||
* Fix link to `Code` tab on wiki commits (#28041)
|
||||
* Allow to set explore page default sort (#27951)
|
||||
* Improve PR diff view on mobile (#27883)
|
||||
* Properly migrate automatic merge GitLab comments (#27873)
|
||||
* Display issue task list on project cards (#27865)
|
||||
* Add Index to pull_auto_merge.doer_id (#27811)
|
||||
* Fix display member unit in the menu bar if there are no hidden members in public org (#27795)
|
||||
* List all Debian package versions in `Packages` (#27786)
|
||||
* Allow pull requests Manually Merged option to be used by non-admins (#27780)
|
||||
* Only show diff file tree when more than one file changed (#27775)
|
||||
* Show placeholder email in privacy popup (#27770)
|
||||
* Revamp repo header (#27760)
|
||||
* Add `must-change-password` command line parameter (#27626)
|
||||
* Unify password changing and invalidate auth tokens (#27625)
|
||||
* Add border to file tree 'sub-items' and add padding to 'item-file' (#27593)
|
||||
* Add slow SQL query warning (#27545)
|
||||
* Pre-register OAuth application for tea (#27509)
|
||||
* Differentiate between `push` and `pull` `mirror sync in progress` (#27390)
|
||||
* Link to file from its history (#27354)
|
||||
* Add a shortcut to user's profile page to admin user details (#27299)
|
||||
* Doctor: delete action entries without existing user (#27292)
|
||||
* Show total TrackedTime on issue/pull/milestone lists (#26672)
|
||||
* Don't show the new pull request button when the page is not compare pull (#26431)
|
||||
* Add `Hide/Show all checks` button to commit status check (#26284)
|
||||
* Improvements of releases list and tags list (#25859)
|
||||
* PERFORMANCE
|
||||
* Fix package list performance (#30520) (#30616)
|
||||
* Add commit status summary table to reduce query from commit status table (#30223)
|
||||
* Refactor markup/csv: don't read all to memory (#29760)
|
||||
* Lazy load object format with command line and don't do it in OpenRepository (#29712)
|
||||
* Add cache for branch divergence on branch list page (#29577)
|
||||
* Do some performance optimization for issues list and view issue/pull (#29515)
|
||||
* Cache repository default branch commit status to reduce query on commit status table (#29444)
|
||||
* Use `crypto/sha256` (#29386)
|
||||
* Some performance optimization on the dashboard and issues page (#29010)
|
||||
* Add combined index for issue_user.uid and issue_id (#28080)
|
||||
|
||||
## [1.21.11](https://github.com/go-gitea/gitea/releases/tag/v1.21.11) - 2024-04-07
|
||||
|
||||
* SECURITY
|
||||
|
@ -63,3 +63,4 @@ Tim-Niclas Oelschläger <zokki.softwareschmiede@gmail.com> (@zokkis)
|
||||
Yu Liu <1240335630@qq.com> (@HEREYUA)
|
||||
Kemal Zebari <kemalzebra@gmail.com> (@kemzeb)
|
||||
Rowan Bohde <rowan.bohde@gmail.com> (@bohde)
|
||||
hiifong <i@hiif.ong> (@hiifong)
|
||||
|
8
Makefile
8
Makefile
@ -377,12 +377,12 @@ lint-backend-fix: lint-go-fix lint-go-vet lint-editorconfig
|
||||
.PHONY: lint-js
|
||||
lint-js: node_modules
|
||||
npx eslint --color --max-warnings=0 --ext js,ts,vue $(ESLINT_FILES)
|
||||
# npx tsc
|
||||
# npx vue-tsc
|
||||
|
||||
.PHONY: lint-js-fix
|
||||
lint-js-fix: node_modules
|
||||
npx eslint --color --max-warnings=0 --ext js,ts,vue $(ESLINT_FILES) --fix
|
||||
# npx tsc
|
||||
# npx vue-tsc
|
||||
|
||||
.PHONY: lint-css
|
||||
lint-css: node_modules
|
||||
@ -451,6 +451,10 @@ lint-templates: .venv node_modules
|
||||
lint-yaml: .venv
|
||||
@poetry run yamllint .
|
||||
|
||||
.PHONY: tsc
|
||||
tsc:
|
||||
npx vue-tsc
|
||||
|
||||
.PHONY: watch
|
||||
watch:
|
||||
@bash tools/watch.sh
|
||||
|
19
assets/go-licenses.json
generated
19
assets/go-licenses.json
generated
@ -1090,8 +1090,8 @@
|
||||
"licenseText": "MIT License\n\nCopyright (c) 2017 Asher\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
|
||||
},
|
||||
{
|
||||
"name": "github.com/stretchr/testify/assert",
|
||||
"path": "github.com/stretchr/testify/assert/LICENSE",
|
||||
"name": "github.com/stretchr/testify",
|
||||
"path": "github.com/stretchr/testify/LICENSE",
|
||||
"licenseText": "MIT License\n\nCopyright (c) 2012-2020 Mat Ryer, Tyler Bunnell and contributors.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
|
||||
},
|
||||
{
|
||||
@ -1124,6 +1124,16 @@
|
||||
"path": "github.com/valyala/fastjson/LICENSE",
|
||||
"licenseText": "The MIT License (MIT)\n\nCopyright (c) 2018 Aliaksandr Valialkin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n"
|
||||
},
|
||||
{
|
||||
"name": "github.com/wneessen/go-mail",
|
||||
"path": "github.com/wneessen/go-mail/LICENSE",
|
||||
"licenseText": "MIT License\n\nCopyright (c) 2022-2023 The go-mail Authors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
|
||||
},
|
||||
{
|
||||
"name": "github.com/wneessen/go-mail/smtp",
|
||||
"path": "github.com/wneessen/go-mail/smtp/LICENSE",
|
||||
"licenseText": "Copyright (c) 2009 The Go Authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
|
||||
},
|
||||
{
|
||||
"name": "github.com/x448/float16",
|
||||
"path": "github.com/x448/float16/LICENSE",
|
||||
@ -1259,11 +1269,6 @@
|
||||
"path": "google.golang.org/protobuf/LICENSE",
|
||||
"licenseText": "Copyright (c) 2018 The Go Authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
|
||||
},
|
||||
{
|
||||
"name": "gopkg.in/gomail.v2",
|
||||
"path": "gopkg.in/gomail.v2/LICENSE",
|
||||
"licenseText": "The MIT License (MIT)\n\nCopyright (c) 2014 Alexandre Cesaro\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
|
||||
},
|
||||
{
|
||||
"name": "gopkg.in/ini.v1",
|
||||
"path": "gopkg.in/ini.v1/LICENSE",
|
||||
|
14
cmd/serv.go
14
cmd/serv.go
@ -111,12 +111,10 @@ func fail(ctx context.Context, userMessage, logMsgFmt string, args ...any) error
|
||||
if !setting.IsProd {
|
||||
_, _ = fmt.Fprintln(os.Stderr, "Gitea:", logMsg)
|
||||
}
|
||||
if userMessage != "" {
|
||||
if unicode.IsPunct(rune(userMessage[len(userMessage)-1])) {
|
||||
logMsg = userMessage + " " + logMsg
|
||||
} else {
|
||||
logMsg = userMessage + ". " + logMsg
|
||||
}
|
||||
if unicode.IsPunct(rune(userMessage[len(userMessage)-1])) {
|
||||
logMsg = userMessage + " " + logMsg
|
||||
} else {
|
||||
logMsg = userMessage + ". " + logMsg
|
||||
}
|
||||
_ = private.SSHLog(ctx, true, logMsg)
|
||||
}
|
||||
@ -288,10 +286,10 @@ func runServ(c *cli.Context) error {
|
||||
if allowedCommands.Contains(verb) {
|
||||
if allowedCommandsLfs.Contains(verb) {
|
||||
if !setting.LFS.StartServer {
|
||||
return fail(ctx, "Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
|
||||
return fail(ctx, "LFS Server is not enabled", "")
|
||||
}
|
||||
if verb == verbLfsTransfer && !setting.LFS.AllowPureSSH {
|
||||
return fail(ctx, "Unknown git command", "LFS SSH transfer connection denied, pure SSH protocol is disabled")
|
||||
return fail(ctx, "LFS SSH transfer is not enabled", "")
|
||||
}
|
||||
if len(words) > 2 {
|
||||
lfsVerb = words[2]
|
||||
|
@ -1,80 +0,0 @@
|
||||
// Copyright 2020 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//nolint:forbidigo
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"code.gitea.io/gitea/models"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
)
|
||||
|
||||
// To generate derivative fixtures, execute the following from Gitea's repository base dir:
|
||||
// go run -tags 'sqlite sqlite_unlock_notify' contrib/fixtures/fixture_generation.go [fixture...]
|
||||
|
||||
var (
|
||||
generators = []struct {
|
||||
gen func(ctx context.Context) (string, error)
|
||||
name string
|
||||
}{
|
||||
{
|
||||
models.GetYamlFixturesAccess, "access",
|
||||
},
|
||||
}
|
||||
fixturesDir string
|
||||
)
|
||||
|
||||
func main() {
|
||||
pathToGiteaRoot := "."
|
||||
fixturesDir = filepath.Join(pathToGiteaRoot, "models", "fixtures")
|
||||
if err := unittest.CreateTestEngine(unittest.FixturesOptions{
|
||||
Dir: fixturesDir,
|
||||
}); err != nil {
|
||||
fmt.Printf("CreateTestEngine: %+v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := unittest.PrepareTestDatabase(); err != nil {
|
||||
fmt.Printf("PrepareTestDatabase: %+v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
ctx := context.Background()
|
||||
if len(os.Args) == 0 {
|
||||
for _, r := range os.Args {
|
||||
if err := generate(ctx, r); err != nil {
|
||||
fmt.Printf("generate '%s': %+v\n", r, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, g := range generators {
|
||||
if err := generate(ctx, g.name); err != nil {
|
||||
fmt.Printf("generate '%s': %+v\n", g.name, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func generate(ctx context.Context, name string) error {
|
||||
for _, g := range generators {
|
||||
if g.name == name {
|
||||
data, err := g.gen(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
path := filepath.Join(fixturesDir, name+".yml")
|
||||
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
|
||||
return fmt.Errorf("%s: %+v", path, err)
|
||||
}
|
||||
fmt.Printf("%s created.\n", path)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("generator not found")
|
||||
}
|
@ -784,6 +784,10 @@ LEVEL = Info
|
||||
;; Please note that setting this to false will not disable OAuth Basic or Basic authentication using a token
|
||||
;ENABLE_BASIC_AUTHENTICATION = true
|
||||
;;
|
||||
;; Show the password sign-in form (for password-based login), otherwise, only show OAuth2 login methods.
|
||||
;; If you set it to false, maybe it also needs to set ENABLE_BASIC_AUTHENTICATION to false to completely disable password-based authentication.
|
||||
;ENABLE_PASSWORD_SIGNIN_FORM = true
|
||||
;;
|
||||
;; More detail: https://github.com/gogits/gogs/issues/165
|
||||
;ENABLE_REVERSE_PROXY_AUTHENTICATION = false
|
||||
; Enable this to allow reverse proxy authentication for API requests, the reverse proxy is responsible for ensuring that no CSRF is possible.
|
||||
@ -1007,6 +1011,14 @@ LEVEL = Info
|
||||
;; The set of allowed values and rules are the same as DEFAULT_REPO_UNITS.
|
||||
;DEFAULT_FORK_REPO_UNITS = repo.code,repo.pulls
|
||||
;;
|
||||
;; Comma separated list of default mirror repo units.
|
||||
;; The set of allowed values and rules are the same as DEFAULT_REPO_UNITS.
|
||||
;DEFAULT_MIRROR_REPO_UNITS = repo.code,repo.releases,repo.issues,repo.wiki,repo.projects,repo.packages
|
||||
;;
|
||||
;; Comma separated list of default template repo units.
|
||||
;; The set of allowed values and rules are the same as DEFAULT_REPO_UNITS.
|
||||
;DEFAULT_TEMPLATE_REPO_UNITS = repo.code,repo.releases,repo.issues,repo.pulls,repo.wiki,repo.projects,repo.packages
|
||||
;;
|
||||
;; Prefix archive files by placing them in a directory named after the repository
|
||||
;PREFIX_ARCHIVE_FILES = true
|
||||
;;
|
||||
@ -1904,7 +1916,7 @@ LEVEL = Info
|
||||
;ENABLED = true
|
||||
;;
|
||||
;; Comma-separated list of allowed file extensions (`.zip`), mime types (`text/plain`) or wildcard type (`image/*`, `audio/*`, `video/*`). Empty value or `*/*` allows all types.
|
||||
;ALLOWED_TYPES = .csv,.docx,.fodg,.fodp,.fods,.fodt,.gif,.gz,.jpeg,.jpg,.log,.md,.mov,.mp4,.odf,.odg,.odp,.ods,.odt,.patch,.pdf,.png,.pptx,.svg,.tgz,.txt,.webm,.xls,.xlsx,.zip
|
||||
;ALLOWED_TYPES = .avif,.cpuprofile,.csv,.dmp,.docx,.fodg,.fodp,.fods,.fodt,.gif,.gz,.jpeg,.jpg,.json,.jsonc,.log,.md,.mov,.mp4,.odf,.odg,.odp,.ods,.odt,.patch,.pdf,.png,.pptx,.svg,.tgz,.txt,.webm,.webp,.xls,.xlsx,.zip
|
||||
;;
|
||||
;; Max size of each file. Defaults to 2048MB
|
||||
;MAX_SIZE = 2048
|
||||
@ -1936,6 +1948,13 @@ LEVEL = Info
|
||||
;; Minio secretAccessKey to connect only available when STORAGE_TYPE is `minio`
|
||||
;MINIO_SECRET_ACCESS_KEY =
|
||||
;;
|
||||
;; Preferred IAM Endpoint to override Minio's default IAM Endpoint resolution only available when STORAGE_TYPE is `minio`.
|
||||
;; If not provided and STORAGE_TYPE is `minio`, will search for and derive endpoint from known environment variables
|
||||
;; (AWS_CONTAINER_AUTHORIZATION_TOKEN, AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,
|
||||
;; AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_WEB_IDENTITY_TOKEN_FILE, AWS_ROLE_ARN, AWS_ROLE_SESSION_NAME, AWS_REGION),
|
||||
;; or the DefaultIAMRoleEndpoint if not provided otherwise.
|
||||
;MINIO_IAM_ENDPOINT =
|
||||
;;
|
||||
;; Minio bucket to store the attachments only available when STORAGE_TYPE is `minio`
|
||||
;MINIO_BUCKET = gitea
|
||||
;;
|
||||
@ -2642,9 +2661,15 @@ LEVEL = Info
|
||||
;; override the azure blob base path if storage type is azureblob
|
||||
;AZURE_BLOB_BASE_PATH = lfs/
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; settings for Gitea's LFS client (eg: mirroring an upstream lfs endpoint)
|
||||
;;
|
||||
;[lfs_client]
|
||||
;; When mirroring an upstream lfs endpoint, limit the number of pointers in each batch request to this number
|
||||
;; Limit the number of pointers in each batch request to this number
|
||||
;BATCH_SIZE = 20
|
||||
;; Limit the number of concurrent upload/download operations within a batch
|
||||
;BATCH_OPERATION_CONCURRENCY = 8
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
@ -2674,6 +2699,13 @@ LEVEL = Info
|
||||
;; Minio secretAccessKey to connect only available when STORAGE_TYPE is `minio`
|
||||
;MINIO_SECRET_ACCESS_KEY =
|
||||
;;
|
||||
;; Preferred IAM Endpoint to override Minio's default IAM Endpoint resolution only available when STORAGE_TYPE is `minio`.
|
||||
;; If not provided and STORAGE_TYPE is `minio`, will search for and derive endpoint from known environment variables
|
||||
;; (AWS_CONTAINER_AUTHORIZATION_TOKEN, AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE, AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,
|
||||
;; AWS_CONTAINER_CREDENTIALS_FULL_URI, AWS_WEB_IDENTITY_TOKEN_FILE, AWS_ROLE_ARN, AWS_ROLE_SESSION_NAME, AWS_REGION),
|
||||
;; or the DefaultIAMRoleEndpoint if not provided otherwise.
|
||||
;MINIO_IAM_ENDPOINT =
|
||||
;;
|
||||
;; Minio bucket to store the attachments only available when STORAGE_TYPE is `minio`
|
||||
;MINIO_BUCKET = gitea
|
||||
;;
|
||||
|
12
flake.lock
12
flake.lock
@ -5,11 +5,11 @@
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1710146030,
|
||||
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
|
||||
"lastModified": 1726560853,
|
||||
"narHash": "sha256-X6rJYSESBVr3hBoH0WbKE5KvhPU5bloyZ2L4K60/fPQ=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
|
||||
"rev": "c1dfcf08411b08f6b8615f7d8971a2bfa81d5e8a",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -20,11 +20,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1720542800,
|
||||
"narHash": "sha256-ZgnNHuKV6h2+fQ5LuqnUaqZey1Lqqt5dTUAiAnqH0QQ=",
|
||||
"lastModified": 1731139594,
|
||||
"narHash": "sha256-IigrKK3vYRpUu+HEjPL/phrfh7Ox881er1UEsZvw9Q4=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "feb2849fdeb70028c70d73b848214b00d324a497",
|
||||
"rev": "76612b17c0ce71689921ca12d9ffdc9c23ce40b2",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
@ -22,14 +22,13 @@
|
||||
gzip
|
||||
|
||||
# frontend
|
||||
nodejs_20
|
||||
nodejs_22
|
||||
|
||||
# linting
|
||||
python312
|
||||
poetry
|
||||
|
||||
# backend
|
||||
go_1_22
|
||||
gofumpt
|
||||
sqlite
|
||||
];
|
||||
|
10
go.mod
10
go.mod
@ -88,7 +88,7 @@ require (
|
||||
github.com/markbates/goth v1.80.0
|
||||
github.com/mattn/go-isatty v0.0.20
|
||||
github.com/mattn/go-sqlite3 v1.14.24
|
||||
github.com/meilisearch/meilisearch-go v0.29.0
|
||||
github.com/meilisearch/meilisearch-go v0.29.1-0.20241106140435-0bf60fad690a
|
||||
github.com/mholt/archiver/v3 v3.5.1
|
||||
github.com/microcosm-cc/bluemonday v1.0.27
|
||||
github.com/microsoft/go-mssqldb v1.7.2
|
||||
@ -114,6 +114,7 @@ require (
|
||||
github.com/tstranex/u2f v1.0.0
|
||||
github.com/ulikunitz/xz v0.5.12
|
||||
github.com/urfave/cli/v2 v2.27.5
|
||||
github.com/wneessen/go-mail v0.5.2
|
||||
github.com/xanzy/go-gitlab v0.112.0
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
github.com/yohcop/openid-go v1.0.1
|
||||
@ -124,12 +125,12 @@ require (
|
||||
golang.org/x/image v0.21.0
|
||||
golang.org/x/net v0.30.0
|
||||
golang.org/x/oauth2 v0.23.0
|
||||
golang.org/x/sync v0.8.0
|
||||
golang.org/x/sys v0.26.0
|
||||
golang.org/x/text v0.19.0
|
||||
golang.org/x/tools v0.26.0
|
||||
google.golang.org/grpc v1.67.1
|
||||
google.golang.org/protobuf v1.35.1
|
||||
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.5.0
|
||||
@ -221,7 +222,7 @@ require (
|
||||
github.com/go-openapi/validate v0.24.0 // indirect
|
||||
github.com/go-webauthn/x v0.1.15 // indirect
|
||||
github.com/goccy/go-json v0.10.3 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1 // 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
|
||||
@ -316,10 +317,8 @@ require (
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c // indirect
|
||||
golang.org/x/mod v0.21.0 // indirect
|
||||
golang.org/x/sync v0.8.0 // indirect
|
||||
golang.org/x/time v0.7.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20241021214115-324edc3d5d38 // 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
|
||||
)
|
||||
@ -330,6 +329,7 @@ replace github.com/shurcooL/vfsgen => github.com/lunny/vfsgen v0.0.0-20220105142
|
||||
|
||||
replace github.com/nektos/act => gitea.com/gitea/act v0.261.3
|
||||
|
||||
// TODO: the only difference is in `PutObject`: the fork doesn't use `NewVerifyingReader(r, sha256.New(), oid, expectedSize)`, need to figure out why
|
||||
replace github.com/charmbracelet/git-lfs-transfer => gitea.com/gitea/git-lfs-transfer v0.2.0
|
||||
|
||||
// TODO: This could be removed after https://github.com/mholt/archiver/pull/396 merged
|
||||
|
34
go.sum
34
go.sum
@ -98,7 +98,6 @@ github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1L
|
||||
github.com/anchore/archiver/v3 v3.5.2 h1:Bjemm2NzuRhmHy3m0lRe5tNoClB9A4zYyDV58PaB6aA=
|
||||
github.com/anchore/archiver/v3 v3.5.2/go.mod h1:e3dqJ7H78uzsRSEACH1joayhuSyhnonssnDhppzS1L4=
|
||||
github.com/andybalholm/brotli v1.0.1/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
|
||||
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
|
||||
@ -391,8 +390,8 @@ github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f h1:3BSP1Tbs2djlpprl7w
|
||||
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14=
|
||||
github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85 h1:UjoPNDAQ5JPCjlxoJd6K8ALZqSDDhk2ymieAZOVaDg0=
|
||||
github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85/go.mod h1:fR6z1Ie6rtF7kl/vBYMfgD5/G5B1blui7z426/sj2DU=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
|
||||
@ -603,8 +602,8 @@ github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6T
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
|
||||
github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/meilisearch/meilisearch-go v0.29.0 h1:HZ9NEKN59USINQ/DXJge/aaXq8IrsKbXGTdAoBaaDz4=
|
||||
github.com/meilisearch/meilisearch-go v0.29.0/go.mod h1:2cRCAn4ddySUsFfNDLVPod/plRibQsJkXF/4gLhxbOk=
|
||||
github.com/meilisearch/meilisearch-go v0.29.1-0.20241106140435-0bf60fad690a h1:F0y+3QtCG00mr4KueQWuHv1tlIQeNXhH+XAKYLhb3X4=
|
||||
github.com/meilisearch/meilisearch-go v0.29.1-0.20241106140435-0bf60fad690a/go.mod h1:NYOgjEGt/+oExD+NixreBMqxtIB0kCndXOOgpGhoqEs=
|
||||
github.com/mholt/acmez/v2 v2.0.3 h1:CgDBlEwg3QBp6s45tPQmFIBrkRIkBT4rW4orMM6p4sw=
|
||||
github.com/mholt/acmez/v2 v2.0.3/go.mod h1:pQ1ysaDeGrIMvJ9dfJMk5kJNkn7L2sb3UhyrX6Q91cw=
|
||||
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
|
||||
@ -816,6 +815,8 @@ github.com/urfave/cli/v2 v2.27.5/go.mod h1:3Sevf16NykTbInEnD0yKkjDAeZDS0A6bzhBH5
|
||||
github.com/valyala/fastjson v1.6.4 h1:uAUNq9Z6ymTgGhcm0UynUAB6tlbakBrz6CQFax3BXVQ=
|
||||
github.com/valyala/fastjson v1.6.4/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
|
||||
github.com/willf/bitset v1.1.10/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4=
|
||||
github.com/wneessen/go-mail v0.5.2 h1:MZKwgHJoRboLJ+EHMLuHpZc95wo+u1xViL/4XSswDT8=
|
||||
github.com/wneessen/go-mail v0.5.2/go.mod h1:kRroJvEq2hOSEPFRiKjN7Csrz0G1w+RpiGR3b6yo+Ck=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
github.com/xanzy/go-gitlab v0.112.0 h1:6Z0cqEooCvBMfBIHw+CgO4AKGRV8na/9781xOb0+DKw=
|
||||
@ -888,8 +889,10 @@ golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0
|
||||
golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
|
||||
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
|
||||
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
|
||||
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c h1:7dEasQXItcW1xKJ2+gg5VOiBnqWrJc+rq0DPKyvvdbY=
|
||||
@ -902,6 +905,9 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0=
|
||||
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
@ -921,8 +927,10 @@ golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
|
||||
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
|
||||
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
||||
golang.org/x/oauth2 v0.23.0 h1:PbgcYx2W7i4LvjJWEbf0ngHV6qJYr86PkAV3bXdLEbs=
|
||||
@ -935,6 +943,9 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
||||
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@ -967,10 +978,13 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
|
||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
|
||||
@ -978,8 +992,10 @@ golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
|
||||
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24=
|
||||
golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@ -990,7 +1006,9 @@ golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
|
||||
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ=
|
||||
@ -1005,6 +1023,8 @@ golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4f
|
||||
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ=
|
||||
golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
@ -1025,8 +1045,6 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0
|
||||
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=
|
||||
google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
|
||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
@ -1034,8 +1052,6 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE=
|
||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
|
@ -261,6 +261,7 @@ func CancelPreviousJobs(ctx context.Context, repoID int64, ref, workflowID strin
|
||||
}
|
||||
|
||||
// InsertRun inserts a run
|
||||
// The title will be cut off at 255 characters if it's longer than 255 characters.
|
||||
func InsertRun(ctx context.Context, run *ActionRun, jobs []*jobparser.SingleWorkflow) error {
|
||||
ctx, committer, err := db.TxContext(ctx)
|
||||
if err != nil {
|
||||
@ -273,6 +274,7 @@ func InsertRun(ctx context.Context, run *ActionRun, jobs []*jobparser.SingleWork
|
||||
return err
|
||||
}
|
||||
run.Index = index
|
||||
run.Title, _ = util.SplitStringAtByteN(run.Title, 255)
|
||||
|
||||
if err := db.Insert(ctx, run); err != nil {
|
||||
return err
|
||||
@ -399,6 +401,7 @@ func UpdateRun(ctx context.Context, run *ActionRun, cols ...string) error {
|
||||
if len(cols) > 0 {
|
||||
sess.Cols(cols...)
|
||||
}
|
||||
run.Title, _ = util.SplitStringAtByteN(run.Title, 255)
|
||||
affected, err := sess.Update(run)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -252,6 +252,7 @@ func GetRunnerByID(ctx context.Context, id int64) (*ActionRunner, error) {
|
||||
// UpdateRunner updates runner's information.
|
||||
func UpdateRunner(ctx context.Context, r *ActionRunner, cols ...string) error {
|
||||
e := db.GetEngine(ctx)
|
||||
r.Name, _ = util.SplitStringAtByteN(r.Name, 255)
|
||||
var err error
|
||||
if len(cols) == 0 {
|
||||
_, err = e.ID(r.ID).AllCols().Update(r)
|
||||
@ -278,6 +279,7 @@ func CreateRunner(ctx context.Context, t *ActionRunner) error {
|
||||
// Remove OwnerID to avoid confusion; it's not worth returning an error here.
|
||||
t.OwnerID = 0
|
||||
}
|
||||
t.Name, _ = util.SplitStringAtByteN(t.Name, 255)
|
||||
return db.Insert(ctx, t)
|
||||
}
|
||||
|
||||
|
@ -12,6 +12,7 @@ import (
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
webhook_module "code.gitea.io/gitea/modules/webhook"
|
||||
)
|
||||
|
||||
@ -67,6 +68,7 @@ func CreateScheduleTask(ctx context.Context, rows []*ActionSchedule) error {
|
||||
|
||||
// Loop through each schedule row
|
||||
for _, row := range rows {
|
||||
row.Title, _ = util.SplitStringAtByteN(row.Title, 255)
|
||||
// Create new schedule row
|
||||
if err = db.Insert(ctx, row); err != nil {
|
||||
return err
|
||||
|
@ -7,19 +7,17 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"code.gitea.io/gitea/modules/test"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestActionScheduleSpec_Parse(t *testing.T) {
|
||||
// Mock the local timezone is not UTC
|
||||
local := time.Local
|
||||
tz, err := time.LoadLocation("Asia/Shanghai")
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
time.Local = local
|
||||
}()
|
||||
time.Local = tz
|
||||
defer test.MockVariableValue(&time.Local, tz)()
|
||||
|
||||
now, err := time.Parse(time.RFC3339, "2024-07-31T15:47:55+08:00")
|
||||
require.NoError(t, err)
|
||||
|
@ -341,7 +341,7 @@ func UpdateTask(ctx context.Context, task *ActionTask, cols ...string) error {
|
||||
// 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) {
|
||||
func UpdateTaskByState(ctx context.Context, runnerID int64, state *runnerv1.TaskState) (*ActionTask, error) {
|
||||
stepStates := map[int64]*runnerv1.StepState{}
|
||||
for _, v := range state.Steps {
|
||||
stepStates[v.Id] = v
|
||||
@ -360,6 +360,8 @@ func UpdateTaskByState(ctx context.Context, state *runnerv1.TaskState) (*ActionT
|
||||
return nil, err
|
||||
} else if !has {
|
||||
return nil, util.ErrNotExist
|
||||
} else if runnerID != task.RunnerID {
|
||||
return nil, fmt.Errorf("invalid runner for task")
|
||||
}
|
||||
|
||||
if task.Status.IsDone() {
|
||||
|
@ -171,7 +171,10 @@ func (a *Action) TableIndices() []*schemas.Index {
|
||||
cudIndex := schemas.NewIndex("c_u_d", schemas.IndexType)
|
||||
cudIndex.AddColumn("created_unix", "user_id", "is_deleted")
|
||||
|
||||
indices := []*schemas.Index{actUserIndex, repoIndex, cudIndex}
|
||||
cuIndex := schemas.NewIndex("c_u", schemas.IndexType)
|
||||
cuIndex.AddColumn("user_id", "is_deleted")
|
||||
|
||||
indices := []*schemas.Index{actUserIndex, repoIndex, cudIndex, cuIndex}
|
||||
|
||||
return indices
|
||||
}
|
||||
@ -197,7 +200,7 @@ func (a *Action) LoadActUser(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Action) loadRepo(ctx context.Context) {
|
||||
func (a *Action) LoadRepo(ctx context.Context) {
|
||||
if a.Repo != nil {
|
||||
return
|
||||
}
|
||||
@ -247,7 +250,10 @@ func (a *Action) GetActDisplayNameTitle(ctx context.Context) string {
|
||||
|
||||
// GetRepoUserName returns the name of the action repository owner.
|
||||
func (a *Action) GetRepoUserName(ctx context.Context) string {
|
||||
a.loadRepo(ctx)
|
||||
a.LoadRepo(ctx)
|
||||
if a.Repo == nil {
|
||||
return "(non-existing-repo)"
|
||||
}
|
||||
return a.Repo.OwnerName
|
||||
}
|
||||
|
||||
@ -259,7 +265,10 @@ func (a *Action) ShortRepoUserName(ctx context.Context) string {
|
||||
|
||||
// GetRepoName returns the name of the action repository.
|
||||
func (a *Action) GetRepoName(ctx context.Context) string {
|
||||
a.loadRepo(ctx)
|
||||
a.LoadRepo(ctx)
|
||||
if a.Repo == nil {
|
||||
return "(non-existing-repo)"
|
||||
}
|
||||
return a.Repo.Name
|
||||
}
|
||||
|
||||
@ -439,65 +448,13 @@ type GetFeedsOptions struct {
|
||||
Date string // the day we want activity for: YYYY-MM-DD
|
||||
}
|
||||
|
||||
// GetFeeds returns actions according to the provided options
|
||||
func GetFeeds(ctx context.Context, opts GetFeedsOptions) (ActionList, int64, error) {
|
||||
if opts.RequestedUser == nil && opts.RequestedTeam == nil && opts.RequestedRepo == nil {
|
||||
return nil, 0, fmt.Errorf("need at least one of these filters: RequestedUser, RequestedTeam, RequestedRepo")
|
||||
}
|
||||
|
||||
cond, err := activityQueryCondition(ctx, opts)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
actions := make([]*Action, 0, opts.PageSize)
|
||||
var count int64
|
||||
opts.SetDefaultValues()
|
||||
|
||||
if opts.Page < 10 { // TODO: why it's 10 but other values? It's an experience value.
|
||||
sess := db.GetEngine(ctx).Where(cond)
|
||||
sess = db.SetSessionPagination(sess, &opts)
|
||||
|
||||
count, err = sess.Desc("`action`.created_unix").FindAndCount(&actions)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("FindAndCount: %w", err)
|
||||
}
|
||||
} else {
|
||||
// First, only query which IDs are necessary, and only then query all actions to speed up the overall query
|
||||
sess := db.GetEngine(ctx).Where(cond).Select("`action`.id")
|
||||
sess = db.SetSessionPagination(sess, &opts)
|
||||
|
||||
actionIDs := make([]int64, 0, opts.PageSize)
|
||||
if err := sess.Table("action").Desc("`action`.created_unix").Find(&actionIDs); err != nil {
|
||||
return nil, 0, fmt.Errorf("Find(actionsIDs): %w", err)
|
||||
}
|
||||
|
||||
count, err = db.GetEngine(ctx).Where(cond).
|
||||
Table("action").
|
||||
Cols("`action`.id").Count()
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("Count: %w", err)
|
||||
}
|
||||
|
||||
if err := db.GetEngine(ctx).In("`action`.id", actionIDs).Desc("`action`.created_unix").Find(&actions); err != nil {
|
||||
return nil, 0, fmt.Errorf("Find: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := ActionList(actions).LoadAttributes(ctx); err != nil {
|
||||
return nil, 0, fmt.Errorf("LoadAttributes: %w", err)
|
||||
}
|
||||
|
||||
return actions, count, nil
|
||||
}
|
||||
|
||||
// ActivityReadable return whether doer can read activities of user
|
||||
func ActivityReadable(user, doer *user_model.User) bool {
|
||||
return !user.KeepActivityPrivate ||
|
||||
doer != nil && (doer.IsAdmin || user.ID == doer.ID)
|
||||
}
|
||||
|
||||
func activityQueryCondition(ctx context.Context, opts GetFeedsOptions) (builder.Cond, error) {
|
||||
func ActivityQueryCondition(ctx context.Context, opts GetFeedsOptions) (builder.Cond, error) {
|
||||
cond := builder.NewCond()
|
||||
|
||||
if opts.RequestedTeam != nil && opts.RequestedUser == nil {
|
||||
@ -635,7 +592,7 @@ func NotifyWatchers(ctx context.Context, actions ...*Action) error {
|
||||
}
|
||||
|
||||
if repoChanged {
|
||||
act.loadRepo(ctx)
|
||||
act.LoadRepo(ctx)
|
||||
repo = act.Repo
|
||||
|
||||
// check repo owner exist.
|
||||
@ -761,7 +718,7 @@ func DeleteIssueActions(ctx context.Context, repoID, issueID, issueIndex int64)
|
||||
// CountActionCreatedUnixString count actions where created_unix is an empty string
|
||||
func CountActionCreatedUnixString(ctx context.Context) (int64, error) {
|
||||
if setting.Database.Type.IsSQLite3() {
|
||||
return db.GetEngine(ctx).Where(`created_unix = ""`).Count(new(Action))
|
||||
return db.GetEngine(ctx).Where(`created_unix = ''`).Count(new(Action))
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
@ -769,7 +726,7 @@ func CountActionCreatedUnixString(ctx context.Context) (int64, error) {
|
||||
// FixActionCreatedUnixString set created_unix to zero if it is an empty string
|
||||
func FixActionCreatedUnixString(ctx context.Context) (int64, error) {
|
||||
if setting.Database.Type.IsSQLite3() {
|
||||
res, err := db.GetEngine(ctx).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ""`)
|
||||
res, err := db.GetEngine(ctx).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ''`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
@ -201,3 +201,55 @@ func (actions ActionList) LoadIssues(ctx context.Context) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetFeeds returns actions according to the provided options
|
||||
func GetFeeds(ctx context.Context, opts GetFeedsOptions) (ActionList, int64, error) {
|
||||
if opts.RequestedUser == nil && opts.RequestedTeam == nil && opts.RequestedRepo == nil {
|
||||
return nil, 0, fmt.Errorf("need at least one of these filters: RequestedUser, RequestedTeam, RequestedRepo")
|
||||
}
|
||||
|
||||
cond, err := ActivityQueryCondition(ctx, opts)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
actions := make([]*Action, 0, opts.PageSize)
|
||||
var count int64
|
||||
opts.SetDefaultValues()
|
||||
|
||||
if opts.Page < 10 { // TODO: why it's 10 but other values? It's an experience value.
|
||||
sess := db.GetEngine(ctx).Where(cond)
|
||||
sess = db.SetSessionPagination(sess, &opts)
|
||||
|
||||
count, err = sess.Desc("`action`.created_unix").FindAndCount(&actions)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("FindAndCount: %w", err)
|
||||
}
|
||||
} else {
|
||||
// First, only query which IDs are necessary, and only then query all actions to speed up the overall query
|
||||
sess := db.GetEngine(ctx).Where(cond).Select("`action`.id")
|
||||
sess = db.SetSessionPagination(sess, &opts)
|
||||
|
||||
actionIDs := make([]int64, 0, opts.PageSize)
|
||||
if err := sess.Table("action").Desc("`action`.created_unix").Find(&actionIDs); err != nil {
|
||||
return nil, 0, fmt.Errorf("Find(actionsIDs): %w", err)
|
||||
}
|
||||
|
||||
count, err = db.GetEngine(ctx).Where(cond).
|
||||
Table("action").
|
||||
Cols("`action`.id").Count()
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("Count: %w", err)
|
||||
}
|
||||
|
||||
if err := db.GetEngine(ctx).In("`action`.id", actionIDs).Desc("`action`.created_unix").Find(&actions); err != nil {
|
||||
return nil, 0, fmt.Errorf("Find: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := ActionList(actions).LoadAttributes(ctx); err != nil {
|
||||
return nil, 0, fmt.Errorf("LoadAttributes: %w", err)
|
||||
}
|
||||
|
||||
return actions, count, nil
|
||||
}
|
||||
|
@ -42,114 +42,6 @@ func TestAction_GetRepoLink(t *testing.T) {
|
||||
assert.Equal(t, comment.HTMLURL(db.DefaultContext), action.GetCommentHTMLURL(db.DefaultContext))
|
||||
}
|
||||
|
||||
func TestGetFeeds(t *testing.T) {
|
||||
// test with an individual user
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
|
||||
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedUser: user,
|
||||
Actor: user,
|
||||
IncludePrivate: true,
|
||||
OnlyPerformedBy: false,
|
||||
IncludeDeleted: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, actions, 1) {
|
||||
assert.EqualValues(t, 1, actions[0].ID)
|
||||
assert.EqualValues(t, user.ID, actions[0].UserID)
|
||||
}
|
||||
assert.Equal(t, int64(1), count)
|
||||
|
||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedUser: user,
|
||||
Actor: user,
|
||||
IncludePrivate: false,
|
||||
OnlyPerformedBy: false,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, actions, 0)
|
||||
assert.Equal(t, int64(0), count)
|
||||
}
|
||||
|
||||
func TestGetFeedsForRepos(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
privRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
|
||||
pubRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 8})
|
||||
|
||||
// private repo & no login
|
||||
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedRepo: privRepo,
|
||||
IncludePrivate: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, actions, 0)
|
||||
assert.Equal(t, int64(0), count)
|
||||
|
||||
// public repo & no login
|
||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedRepo: pubRepo,
|
||||
IncludePrivate: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, actions, 1)
|
||||
assert.Equal(t, int64(1), count)
|
||||
|
||||
// private repo and login
|
||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedRepo: privRepo,
|
||||
IncludePrivate: true,
|
||||
Actor: user,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, actions, 1)
|
||||
assert.Equal(t, int64(1), count)
|
||||
|
||||
// public repo & login
|
||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedRepo: pubRepo,
|
||||
IncludePrivate: true,
|
||||
Actor: user,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, actions, 1)
|
||||
assert.Equal(t, int64(1), count)
|
||||
}
|
||||
|
||||
func TestGetFeeds2(t *testing.T) {
|
||||
// test with an organization user
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
|
||||
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedUser: org,
|
||||
Actor: user,
|
||||
IncludePrivate: true,
|
||||
OnlyPerformedBy: false,
|
||||
IncludeDeleted: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, actions, 1)
|
||||
if assert.Len(t, actions, 1) {
|
||||
assert.EqualValues(t, 2, actions[0].ID)
|
||||
assert.EqualValues(t, org.ID, actions[0].UserID)
|
||||
}
|
||||
assert.Equal(t, int64(1), count)
|
||||
|
||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedUser: org,
|
||||
Actor: user,
|
||||
IncludePrivate: false,
|
||||
OnlyPerformedBy: false,
|
||||
IncludeDeleted: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, actions, 0)
|
||||
assert.Equal(t, int64(0), count)
|
||||
}
|
||||
|
||||
func TestActivityReadable(t *testing.T) {
|
||||
tt := []struct {
|
||||
desc string
|
||||
@ -227,26 +119,6 @@ func TestNotifyWatchers(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetFeedsCorrupted(t *testing.T) {
|
||||
// Now we will not check for corrupted data in the feeds
|
||||
// users should run doctor to fix their data
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
|
||||
ID: 8,
|
||||
RepoID: 1700,
|
||||
})
|
||||
|
||||
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedUser: user,
|
||||
Actor: user,
|
||||
IncludePrivate: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, actions, 1)
|
||||
assert.Equal(t, int64(1), count)
|
||||
}
|
||||
|
||||
func TestConsistencyUpdateAction(t *testing.T) {
|
||||
if !setting.Database.Type.IsSQLite3() {
|
||||
t.Skip("Test is only for SQLite database.")
|
||||
@ -256,7 +128,7 @@ func TestConsistencyUpdateAction(t *testing.T) {
|
||||
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
|
||||
ID: int64(id),
|
||||
})
|
||||
_, err := db.GetEngine(db.DefaultContext).Exec(`UPDATE action SET created_unix = "" WHERE id = ?`, id)
|
||||
_, err := db.GetEngine(db.DefaultContext).Exec(`UPDATE action SET created_unix = '' WHERE id = ?`, id)
|
||||
assert.NoError(t, err)
|
||||
actions := make([]*activities_model.Action, 0, 1)
|
||||
//
|
||||
@ -322,24 +194,3 @@ func TestDeleteIssueActions(t *testing.T) {
|
||||
assert.NoError(t, activities_model.DeleteIssueActions(db.DefaultContext, issue.RepoID, issue.ID, issue.Index))
|
||||
unittest.AssertCount(t, &activities_model.Action{}, 0)
|
||||
}
|
||||
|
||||
func TestRepoActions(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
_ = db.TruncateBeans(db.DefaultContext, &activities_model.Action{})
|
||||
for i := 0; i < 3; i++ {
|
||||
_ = db.Insert(db.DefaultContext, &activities_model.Action{
|
||||
UserID: 2 + int64(i),
|
||||
ActUserID: 2,
|
||||
RepoID: repo.ID,
|
||||
OpType: activities_model.ActionCommentIssue,
|
||||
})
|
||||
}
|
||||
count, _ := db.Count[activities_model.Action](db.DefaultContext, &db.ListOptions{})
|
||||
assert.EqualValues(t, 3, count)
|
||||
actions, _, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||
RequestedRepo: repo,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, actions, 1)
|
||||
}
|
||||
|
@ -18,6 +18,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
|
||||
"xorm.io/builder"
|
||||
"xorm.io/xorm/schemas"
|
||||
)
|
||||
|
||||
type (
|
||||
@ -50,25 +51,64 @@ const (
|
||||
// Notification represents a notification
|
||||
type Notification struct {
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
UserID int64 `xorm:"INDEX NOT NULL"`
|
||||
RepoID int64 `xorm:"INDEX NOT NULL"`
|
||||
UserID int64 `xorm:"NOT NULL"`
|
||||
RepoID int64 `xorm:"NOT NULL"`
|
||||
|
||||
Status NotificationStatus `xorm:"SMALLINT INDEX NOT NULL"`
|
||||
Source NotificationSource `xorm:"SMALLINT INDEX NOT NULL"`
|
||||
Status NotificationStatus `xorm:"SMALLINT NOT NULL"`
|
||||
Source NotificationSource `xorm:"SMALLINT NOT NULL"`
|
||||
|
||||
IssueID int64 `xorm:"INDEX NOT NULL"`
|
||||
CommitID string `xorm:"INDEX"`
|
||||
IssueID int64 `xorm:"NOT NULL"`
|
||||
CommitID string
|
||||
CommentID int64
|
||||
|
||||
UpdatedBy int64 `xorm:"INDEX NOT NULL"`
|
||||
UpdatedBy int64 `xorm:"NOT NULL"`
|
||||
|
||||
Issue *issues_model.Issue `xorm:"-"`
|
||||
Repository *repo_model.Repository `xorm:"-"`
|
||||
Comment *issues_model.Comment `xorm:"-"`
|
||||
User *user_model.User `xorm:"-"`
|
||||
|
||||
CreatedUnix timeutil.TimeStamp `xorm:"created INDEX NOT NULL"`
|
||||
UpdatedUnix timeutil.TimeStamp `xorm:"updated INDEX NOT NULL"`
|
||||
CreatedUnix timeutil.TimeStamp `xorm:"created NOT NULL"`
|
||||
UpdatedUnix timeutil.TimeStamp `xorm:"updated NOT NULL"`
|
||||
}
|
||||
|
||||
// TableIndices implements xorm's TableIndices interface
|
||||
func (n *Notification) TableIndices() []*schemas.Index {
|
||||
indices := make([]*schemas.Index, 0, 8)
|
||||
usuuIndex := schemas.NewIndex("u_s_uu", schemas.IndexType)
|
||||
usuuIndex.AddColumn("user_id", "status", "updated_unix")
|
||||
indices = append(indices, usuuIndex)
|
||||
|
||||
// Add the individual indices that were previously defined in struct tags
|
||||
userIDIndex := schemas.NewIndex("idx_notification_user_id", schemas.IndexType)
|
||||
userIDIndex.AddColumn("user_id")
|
||||
indices = append(indices, userIDIndex)
|
||||
|
||||
repoIDIndex := schemas.NewIndex("idx_notification_repo_id", schemas.IndexType)
|
||||
repoIDIndex.AddColumn("repo_id")
|
||||
indices = append(indices, repoIDIndex)
|
||||
|
||||
statusIndex := schemas.NewIndex("idx_notification_status", schemas.IndexType)
|
||||
statusIndex.AddColumn("status")
|
||||
indices = append(indices, statusIndex)
|
||||
|
||||
sourceIndex := schemas.NewIndex("idx_notification_source", schemas.IndexType)
|
||||
sourceIndex.AddColumn("source")
|
||||
indices = append(indices, sourceIndex)
|
||||
|
||||
issueIDIndex := schemas.NewIndex("idx_notification_issue_id", schemas.IndexType)
|
||||
issueIDIndex.AddColumn("issue_id")
|
||||
indices = append(indices, issueIDIndex)
|
||||
|
||||
commitIDIndex := schemas.NewIndex("idx_notification_commit_id", schemas.IndexType)
|
||||
commitIDIndex.AddColumn("commit_id")
|
||||
indices = append(indices, commitIDIndex)
|
||||
|
||||
updatedByIndex := schemas.NewIndex("idx_notification_updated_by", schemas.IndexType)
|
||||
updatedByIndex.AddColumn("updated_by")
|
||||
indices = append(indices, updatedByIndex)
|
||||
|
||||
return indices
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
@ -47,7 +47,7 @@ func getUserHeatmapData(ctx context.Context, user *user_model.User, team *organi
|
||||
groupByName = groupBy
|
||||
}
|
||||
|
||||
cond, err := activityQueryCondition(ctx, GetFeedsOptions{
|
||||
cond, err := ActivityQueryCondition(ctx, GetFeedsOptions{
|
||||
RequestedUser: user,
|
||||
RequestedTeam: team,
|
||||
Actor: doer,
|
||||
|
@ -12,6 +12,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"github.com/go-webauthn/webauthn/protocol"
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
)
|
||||
|
||||
@ -89,14 +90,33 @@ func (cred *WebAuthnCredential) AfterLoad() {
|
||||
// WebAuthnCredentialList is a list of *WebAuthnCredential
|
||||
type WebAuthnCredentialList []*WebAuthnCredential
|
||||
|
||||
// newCredentialFlagsFromAuthenticatorFlags is copied from https://github.com/go-webauthn/webauthn/pull/337
|
||||
// to convert protocol.AuthenticatorFlags to webauthn.CredentialFlags
|
||||
func newCredentialFlagsFromAuthenticatorFlags(flags protocol.AuthenticatorFlags) webauthn.CredentialFlags {
|
||||
return webauthn.CredentialFlags{
|
||||
UserPresent: flags.HasUserPresent(),
|
||||
UserVerified: flags.HasUserVerified(),
|
||||
BackupEligible: flags.HasBackupEligible(),
|
||||
BackupState: flags.HasBackupState(),
|
||||
}
|
||||
}
|
||||
|
||||
// ToCredentials will convert all WebAuthnCredentials to webauthn.Credentials
|
||||
func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential {
|
||||
func (list WebAuthnCredentialList) ToCredentials(defaultAuthFlags ...protocol.AuthenticatorFlags) []webauthn.Credential {
|
||||
// TODO: at the moment, Gitea doesn't store or check the flags
|
||||
// so we need to use the default flags from the authenticator to make the login validation pass
|
||||
// In the future, we should:
|
||||
// 1. store the flags when registering the credential
|
||||
// 2. provide the stored flags when converting the credentials (for login)
|
||||
// 3. for old users, still use this fallback to the default flags
|
||||
defAuthFlags := util.OptionalArg(defaultAuthFlags)
|
||||
creds := make([]webauthn.Credential, 0, len(list))
|
||||
for _, cred := range list {
|
||||
creds = append(creds, webauthn.Credential{
|
||||
ID: cred.CredentialID,
|
||||
PublicKey: cred.PublicKey,
|
||||
AttestationType: cred.AttestationType,
|
||||
Flags: newCredentialFlagsFromAuthenticatorFlags(defAuthFlags),
|
||||
Authenticator: webauthn.Authenticator{
|
||||
AAGUID: cred.AAGUID,
|
||||
SignCount: cred.SignCount,
|
||||
|
@ -68,7 +68,8 @@ func CheckCollations(x *xorm.Engine) (*CheckCollationsResult, error) {
|
||||
|
||||
var candidateCollations []string
|
||||
if x.Dialect().URI().DBType == schemas.MYSQL {
|
||||
if _, err = x.SQL("SELECT @@collation_database").Get(&res.DatabaseCollation); err != nil {
|
||||
_, err = x.SQL("SELECT DEFAULT_COLLATION_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?", setting.Database.Name).Get(&res.DatabaseCollation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res.IsCollationCaseSensitive = func(s string) bool {
|
||||
|
@ -134,6 +134,9 @@ func SyncAllTables() error {
|
||||
func InitEngine(ctx context.Context) error {
|
||||
xormEngine, err := newXORMEngine()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "SQLite3 support") {
|
||||
return fmt.Errorf(`sqlite3 requires: -tags sqlite,sqlite_unlock_notify%s%w`, "\n", err)
|
||||
}
|
||||
return fmt.Errorf("failed to connect to database: %w", err)
|
||||
}
|
||||
|
||||
|
@ -1,50 +0,0 @@
|
||||
// Copyright 2020 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
access_model "code.gitea.io/gitea/models/perm/access"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
)
|
||||
|
||||
// GetYamlFixturesAccess returns a string containing the contents
|
||||
// for the access table, as recalculated using repo.RecalculateAccesses()
|
||||
func GetYamlFixturesAccess(ctx context.Context) (string, error) {
|
||||
repos := make([]*repo_model.Repository, 0, 50)
|
||||
if err := db.GetEngine(ctx).Find(&repos); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
for _, repo := range repos {
|
||||
repo.MustOwner(ctx)
|
||||
if err := access_model.RecalculateAccesses(ctx, repo); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
|
||||
accesses := make([]*access_model.Access, 0, 200)
|
||||
if err := db.GetEngine(ctx).OrderBy("user_id, repo_id").Find(&accesses); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
for i, a := range accesses {
|
||||
fmt.Fprintf(&b, "-\n")
|
||||
fmt.Fprintf(&b, " id: %d\n", i+1)
|
||||
fmt.Fprintf(&b, " user_id: %d\n", a.UserID)
|
||||
fmt.Fprintf(&b, " repo_id: %d\n", a.RepoID)
|
||||
fmt.Fprintf(&b, " mode: %d\n", a.Mode)
|
||||
if i < len(accesses)-1 {
|
||||
fmt.Fprintf(&b, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
// Copyright 2020 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestFixtureGeneration(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
test := func(ctx context.Context, gen func(ctx context.Context) (string, error), name string) {
|
||||
expected, err := gen(ctx)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
}
|
||||
p := filepath.Join(unittest.FixturesDir(), name+".yml")
|
||||
bytes, err := os.ReadFile(p)
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
}
|
||||
data := string(util.NormalizeEOL(bytes))
|
||||
assert.EqualValues(t, expected, data, "Differences detected for %s", p)
|
||||
}
|
||||
|
||||
test(db.DefaultContext, GetYamlFixturesAccess, "access")
|
||||
}
|
@ -1,3 +1,22 @@
|
||||
-
|
||||
id: 46
|
||||
attempt: 3
|
||||
runner_id: 1
|
||||
status: 3 # 3 is the status code for "cancelled"
|
||||
started: 1683636528
|
||||
stopped: 1683636626
|
||||
repo_id: 4
|
||||
owner_id: 1
|
||||
commit_sha: c2d72f548424103f01ee1dc02889c1e2bff816b0
|
||||
is_fork_pull_request: 0
|
||||
token_hash: 6d8ef48297195edcc8e22c70b3020eaa06c52976db67d39b4260c64a69a2cc1508825121b7b8394e48e00b1bf8718b2aaaaa
|
||||
token_salt: eeeeeeee
|
||||
token_last_eight: eeeeeeee
|
||||
log_filename: artifact-test2/2f/47.log
|
||||
log_in_storage: 1
|
||||
log_length: 707
|
||||
log_size: 90179
|
||||
log_expired: 0
|
||||
-
|
||||
id: 47
|
||||
job_id: 192
|
||||
|
@ -11,7 +11,7 @@
|
||||
|
||||
id: 2
|
||||
oid: 2eccdb43825d2a49d99d542daa20075cff1d97d9d2349a8977efe9c03661737c
|
||||
size: 107
|
||||
size: 2048
|
||||
repository_id: 54
|
||||
created_unix: 1671607299
|
||||
|
||||
|
@ -129,3 +129,9 @@
|
||||
uid: 2
|
||||
org_id: 35
|
||||
is_public: true
|
||||
|
||||
-
|
||||
id: 23
|
||||
uid: 20
|
||||
org_id: 17
|
||||
is_public: false
|
||||
|
@ -26,7 +26,7 @@
|
||||
fork_id: 0
|
||||
is_template: false
|
||||
template_id: 0
|
||||
size: 8478
|
||||
size: 0
|
||||
is_fsck_enabled: true
|
||||
close_issues_via_commit_in_any_branch: false
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
-
|
||||
id: 1
|
||||
setting_key: 'picture.disable_gravatar'
|
||||
setting_value: 'false'
|
||||
setting_value: 'true'
|
||||
version: 1
|
||||
created: 1653533198
|
||||
updated: 1653533198
|
||||
|
@ -23,9 +23,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar1
|
||||
avatar: ""
|
||||
avatar_email: user1@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -60,8 +60,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar2
|
||||
avatar: ""
|
||||
avatar_email: user2@example.com
|
||||
# cause a random avatar to be generated when referenced for test purposes
|
||||
use_custom_avatar: false
|
||||
num_followers: 2
|
||||
num_following: 1
|
||||
@ -97,9 +98,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar3
|
||||
avatar: ""
|
||||
avatar_email: org3@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -134,9 +135,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar4
|
||||
avatar: ""
|
||||
avatar_email: user4@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 1
|
||||
num_stars: 0
|
||||
@ -171,9 +172,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: false
|
||||
prohibit_login: false
|
||||
avatar: avatar5
|
||||
avatar: ""
|
||||
avatar_email: user5@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -208,9 +209,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar6
|
||||
avatar: ""
|
||||
avatar_email: org6@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -245,9 +246,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar7
|
||||
avatar: ""
|
||||
avatar_email: org7@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -282,9 +283,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar8
|
||||
avatar: ""
|
||||
avatar_email: user8@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 1
|
||||
num_following: 1
|
||||
num_stars: 0
|
||||
@ -319,9 +320,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar9
|
||||
avatar: ""
|
||||
avatar_email: user9@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -332,6 +333,7 @@
|
||||
repo_admin_change_team_access: false
|
||||
theme: ""
|
||||
keep_activity_private: false
|
||||
created_unix: 1730468968
|
||||
|
||||
-
|
||||
id: 10
|
||||
@ -356,9 +358,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar10
|
||||
avatar: ""
|
||||
avatar_email: user10@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 2
|
||||
@ -393,9 +395,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar11
|
||||
avatar: ""
|
||||
avatar_email: user11@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -430,9 +432,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar12
|
||||
avatar: ""
|
||||
avatar_email: user12@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -467,9 +469,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar13
|
||||
avatar: ""
|
||||
avatar_email: user13@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -504,9 +506,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar14
|
||||
avatar: ""
|
||||
avatar_email: user13@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -541,9 +543,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar15
|
||||
avatar: ""
|
||||
avatar_email: user15@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -578,9 +580,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar16
|
||||
avatar: ""
|
||||
avatar_email: user16@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -615,15 +617,15 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar17
|
||||
avatar: ""
|
||||
avatar_email: org17@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
num_repos: 2
|
||||
num_teams: 3
|
||||
num_members: 4
|
||||
num_members: 5
|
||||
visibility: 0
|
||||
repo_admin_change_team_access: false
|
||||
theme: ""
|
||||
@ -652,9 +654,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar18
|
||||
avatar: ""
|
||||
avatar_email: user18@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -689,9 +691,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar19
|
||||
avatar: ""
|
||||
avatar_email: org19@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -726,9 +728,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar20
|
||||
avatar: ""
|
||||
avatar_email: user20@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -763,9 +765,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar21
|
||||
avatar: ""
|
||||
avatar_email: user21@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -800,9 +802,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar22
|
||||
avatar: ""
|
||||
avatar_email: limited_org@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -837,9 +839,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar23
|
||||
avatar: ""
|
||||
avatar_email: privated_org@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -874,9 +876,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar24
|
||||
avatar: ""
|
||||
avatar_email: user24@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -911,9 +913,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar25
|
||||
avatar: ""
|
||||
avatar_email: org25@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -948,9 +950,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar26
|
||||
avatar: ""
|
||||
avatar_email: org26@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -985,9 +987,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar27
|
||||
avatar: ""
|
||||
avatar_email: user27@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1022,9 +1024,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar28
|
||||
avatar: ""
|
||||
avatar_email: user28@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1059,9 +1061,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar29
|
||||
avatar: ""
|
||||
avatar_email: user29@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1096,9 +1098,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar29
|
||||
avatar: ""
|
||||
avatar_email: user30@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1133,9 +1135,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar31
|
||||
avatar: ""
|
||||
avatar_email: user31@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 1
|
||||
num_stars: 0
|
||||
@ -1170,9 +1172,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar32
|
||||
avatar: ""
|
||||
avatar_email: user30@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1207,9 +1209,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar33
|
||||
avatar: ""
|
||||
avatar_email: user33@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 1
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1245,7 +1247,7 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: false
|
||||
prohibit_login: false
|
||||
avatar: avatar34
|
||||
avatar: ""
|
||||
avatar_email: user34@example.com
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
@ -1282,9 +1284,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar35
|
||||
avatar: ""
|
||||
avatar_email: private_org35@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1319,9 +1321,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar22
|
||||
avatar: ""
|
||||
avatar_email: abcde@gitea.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1356,9 +1358,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: true
|
||||
avatar: avatar29
|
||||
avatar: ""
|
||||
avatar_email: user37@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1393,9 +1395,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar38
|
||||
avatar: ""
|
||||
avatar_email: user38@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1430,9 +1432,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar39
|
||||
avatar: ""
|
||||
avatar_email: user39@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1467,9 +1469,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar40
|
||||
avatar: ""
|
||||
avatar_email: user40@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1504,9 +1506,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar41
|
||||
avatar: ""
|
||||
avatar_email: org41@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
@ -1541,9 +1543,9 @@
|
||||
allow_import_local: false
|
||||
allow_create_organization: true
|
||||
prohibit_login: false
|
||||
avatar: avatar42
|
||||
avatar: ""
|
||||
avatar_email: org42@example.com
|
||||
use_custom_avatar: false
|
||||
use_custom_avatar: true
|
||||
num_followers: 0
|
||||
num_following: 0
|
||||
num_stars: 0
|
||||
|
@ -34,6 +34,7 @@ type ProtectedBranch struct {
|
||||
RepoID int64 `xorm:"UNIQUE(s)"`
|
||||
Repo *repo_model.Repository `xorm:"-"`
|
||||
RuleName string `xorm:"'branch_name' UNIQUE(s)"` // a branch name or a glob match to branch name
|
||||
Priority int64 `xorm:"NOT NULL DEFAULT 0"`
|
||||
globRule glob.Glob `xorm:"-"`
|
||||
isPlainName bool `xorm:"-"`
|
||||
CanPush bool `xorm:"NOT NULL DEFAULT false"`
|
||||
@ -413,14 +414,27 @@ func UpdateProtectBranch(ctx context.Context, repo *repo_model.Repository, prote
|
||||
}
|
||||
protectBranch.ApprovalsWhitelistTeamIDs = whitelist
|
||||
|
||||
// Make sure protectBranch.ID is not 0 for whitelists
|
||||
// Looks like it's a new rule
|
||||
if protectBranch.ID == 0 {
|
||||
// as it's a new rule and if priority was not set, we need to calc it.
|
||||
if protectBranch.Priority == 0 {
|
||||
var lowestPrio int64
|
||||
// because of mssql we can not use builder or save xorm syntax, so raw sql it is
|
||||
if _, err := db.GetEngine(ctx).SQL(`SELECT MAX(priority) FROM protected_branch WHERE repo_id = ?`, protectBranch.RepoID).
|
||||
Get(&lowestPrio); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Trace("Create new ProtectedBranch at repo[%d] and detect current lowest priority '%d'", protectBranch.RepoID, lowestPrio)
|
||||
protectBranch.Priority = lowestPrio + 1
|
||||
}
|
||||
|
||||
if _, err = db.GetEngine(ctx).Insert(protectBranch); err != nil {
|
||||
return fmt.Errorf("Insert: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// update the rule
|
||||
if _, err = db.GetEngine(ctx).ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
|
||||
return fmt.Errorf("Update: %v", err)
|
||||
}
|
||||
@ -428,6 +442,24 @@ func UpdateProtectBranch(ctx context.Context, repo *repo_model.Repository, prote
|
||||
return nil
|
||||
}
|
||||
|
||||
func UpdateProtectBranchPriorities(ctx context.Context, repo *repo_model.Repository, ids []int64) error {
|
||||
prio := int64(1)
|
||||
return db.WithTx(ctx, func(ctx context.Context) error {
|
||||
for _, id := range ids {
|
||||
if _, err := db.GetEngine(ctx).
|
||||
ID(id).Where("repo_id = ?", repo.ID).
|
||||
Cols("priority").
|
||||
Update(&ProtectedBranch{
|
||||
Priority: prio,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
prio++
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
|
||||
// the users from newWhitelist which have explicit read or write access to the repo.
|
||||
func updateApprovalWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
|
||||
|
@ -28,6 +28,13 @@ func (rules ProtectedBranchRules) sort() {
|
||||
sort.Slice(rules, func(i, j int) bool {
|
||||
rules[i].loadGlob()
|
||||
rules[j].loadGlob()
|
||||
|
||||
// if priority differ, use that to sort
|
||||
if rules[i].Priority != rules[j].Priority {
|
||||
return rules[i].Priority < rules[j].Priority
|
||||
}
|
||||
|
||||
// now we sort the old way
|
||||
if rules[i].isPlainName != rules[j].isPlainName {
|
||||
return rules[i].isPlainName // plain name comes first, so plain name means "less"
|
||||
}
|
||||
|
@ -75,7 +75,7 @@ func TestBranchRuleMatchPriority(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBranchRuleSort(t *testing.T) {
|
||||
func TestBranchRuleSortLegacy(t *testing.T) {
|
||||
in := []*ProtectedBranch{{
|
||||
RuleName: "b",
|
||||
CreatedUnix: 1,
|
||||
@ -103,3 +103,37 @@ func TestBranchRuleSort(t *testing.T) {
|
||||
}
|
||||
assert.Equal(t, expect, got)
|
||||
}
|
||||
|
||||
func TestBranchRuleSortPriority(t *testing.T) {
|
||||
in := []*ProtectedBranch{{
|
||||
RuleName: "b",
|
||||
CreatedUnix: 1,
|
||||
Priority: 4,
|
||||
}, {
|
||||
RuleName: "b/*",
|
||||
CreatedUnix: 3,
|
||||
Priority: 2,
|
||||
}, {
|
||||
RuleName: "a/*",
|
||||
CreatedUnix: 2,
|
||||
Priority: 1,
|
||||
}, {
|
||||
RuleName: "c",
|
||||
CreatedUnix: 0,
|
||||
Priority: 0,
|
||||
}, {
|
||||
RuleName: "a",
|
||||
CreatedUnix: 4,
|
||||
Priority: 3,
|
||||
}}
|
||||
expect := []string{"c", "a/*", "b/*", "a", "b"}
|
||||
|
||||
pbr := ProtectedBranchRules(in)
|
||||
pbr.sort()
|
||||
|
||||
var got []string
|
||||
for i := range pbr {
|
||||
got = append(got, pbr[i].RuleName)
|
||||
}
|
||||
assert.Equal(t, expect, got)
|
||||
}
|
||||
|
@ -7,6 +7,10 @@ import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@ -76,3 +80,77 @@ func TestBranchRuleMatch(t *testing.T) {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateProtectBranchPriorities(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
// Create some test protected branches with initial priorities
|
||||
protectedBranches := []*ProtectedBranch{
|
||||
{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "master",
|
||||
Priority: 1,
|
||||
},
|
||||
{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "develop",
|
||||
Priority: 2,
|
||||
},
|
||||
{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "feature/*",
|
||||
Priority: 3,
|
||||
},
|
||||
}
|
||||
|
||||
for _, pb := range protectedBranches {
|
||||
_, err := db.GetEngine(db.DefaultContext).Insert(pb)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
// Test updating priorities
|
||||
newPriorities := []int64{protectedBranches[2].ID, protectedBranches[0].ID, protectedBranches[1].ID}
|
||||
err := UpdateProtectBranchPriorities(db.DefaultContext, repo, newPriorities)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify new priorities
|
||||
pbs, err := FindRepoProtectedBranchRules(db.DefaultContext, repo.ID)
|
||||
assert.NoError(t, err)
|
||||
|
||||
expectedPriorities := map[string]int64{
|
||||
"feature/*": 1,
|
||||
"master": 2,
|
||||
"develop": 3,
|
||||
}
|
||||
|
||||
for _, pb := range pbs {
|
||||
assert.Equal(t, expectedPriorities[pb.RuleName], pb.Priority)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewProtectBranchPriority(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
err := UpdateProtectBranch(db.DefaultContext, repo, &ProtectedBranch{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "branch-1",
|
||||
Priority: 1,
|
||||
}, WhitelistOptions{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
newPB := &ProtectedBranch{
|
||||
RepoID: repo.ID,
|
||||
RuleName: "branch-2",
|
||||
// Priority intentionally omitted
|
||||
}
|
||||
|
||||
err = UpdateProtectBranch(db.DefaultContext, repo, newPB, WhitelistOptions{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
savedPB2, err := GetFirstMatchProtectedBranchRule(db.DefaultContext, repo.ID, "branch-2")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(2), savedPB2.Priority)
|
||||
}
|
||||
|
@ -114,6 +114,8 @@ const (
|
||||
|
||||
CommentTypePin // 36 pin Issue
|
||||
CommentTypeUnpin // 37 unpin Issue
|
||||
|
||||
CommentTypeChangeTimeEstimate // 38 Change time estimate
|
||||
)
|
||||
|
||||
var commentStrings = []string{
|
||||
@ -155,6 +157,7 @@ var commentStrings = []string{
|
||||
"pull_cancel_scheduled_merge",
|
||||
"pin",
|
||||
"unpin",
|
||||
"change_time_estimate",
|
||||
}
|
||||
|
||||
func (t CommentType) String() string {
|
||||
@ -1108,7 +1111,7 @@ func FindComments(ctx context.Context, opts *FindCommentsOptions) (CommentList,
|
||||
sess.Join("INNER", "issue", "issue.id = comment.issue_id")
|
||||
}
|
||||
|
||||
if opts.Page != 0 {
|
||||
if opts.Page > 0 {
|
||||
sess = db.SetSessionPagination(sess, opts)
|
||||
}
|
||||
|
||||
|
@ -7,8 +7,8 @@ import (
|
||||
"context"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/renderhelper"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
"code.gitea.io/gitea/modules/markup/markdown"
|
||||
|
||||
"xorm.io/builder"
|
||||
@ -112,14 +112,8 @@ func findCodeComments(ctx context.Context, opts FindCommentsOptions, issue *Issu
|
||||
}
|
||||
|
||||
var err error
|
||||
if comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
|
||||
Ctx: ctx,
|
||||
Repo: issue.Repo,
|
||||
Links: markup.Links{
|
||||
Base: issue.Repo.Link(),
|
||||
},
|
||||
Metas: issue.Repo.ComposeMetas(ctx),
|
||||
}, comment.Content); err != nil {
|
||||
rctx := renderhelper.NewRenderContextRepoComment(ctx, issue.Repo)
|
||||
if comment.RenderedContent, err = markdown.RenderString(rctx, comment.Content); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
@ -147,6 +147,9 @@ type Issue struct {
|
||||
|
||||
// For view issue page.
|
||||
ShowRole RoleDescriptor `xorm:"-"`
|
||||
|
||||
// Time estimate
|
||||
TimeEstimate int64 `xorm:"NOT NULL DEFAULT 0"`
|
||||
}
|
||||
|
||||
var (
|
||||
@ -641,7 +644,7 @@ func (issue *Issue) BlockedByDependencies(ctx context.Context, opts db.ListOptio
|
||||
Where("issue_id = ?", issue.ID).
|
||||
// sort by repo id then created date, with the issues of the same repo at the beginning of the list
|
||||
OrderBy("CASE WHEN issue.repo_id = ? THEN 0 ELSE issue.repo_id END, issue.created_unix DESC", issue.RepoID)
|
||||
if opts.Page != 0 {
|
||||
if opts.Page > 0 {
|
||||
sess = db.SetSessionPagination(sess, &opts)
|
||||
}
|
||||
err = sess.Find(&issueDeps)
|
||||
@ -934,3 +937,28 @@ func insertIssue(ctx context.Context, issue *Issue) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ChangeIssueTimeEstimate changes the plan time of this issue, as the given user.
|
||||
func ChangeIssueTimeEstimate(ctx context.Context, issue *Issue, doer *user_model.User, timeEstimate int64) error {
|
||||
return db.WithTx(ctx, func(ctx context.Context) error {
|
||||
if err := UpdateIssueCols(ctx, &Issue{ID: issue.ID, TimeEstimate: timeEstimate}, "time_estimate"); err != nil {
|
||||
return fmt.Errorf("updateIssueCols: %w", err)
|
||||
}
|
||||
|
||||
if err := issue.LoadRepo(ctx); err != nil {
|
||||
return fmt.Errorf("loadRepo: %w", err)
|
||||
}
|
||||
|
||||
opts := &CreateCommentOptions{
|
||||
Type: CommentTypeChangeTimeEstimate,
|
||||
Doer: doer,
|
||||
Repo: issue.Repo,
|
||||
Issue: issue,
|
||||
Content: fmt.Sprintf("%d", timeEstimate),
|
||||
}
|
||||
if _, err := CreateComment(ctx, opts); err != nil {
|
||||
return fmt.Errorf("createComment: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
@ -21,6 +21,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/references"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"xorm.io/builder"
|
||||
)
|
||||
@ -138,6 +139,7 @@ func ChangeIssueTitle(ctx context.Context, issue *Issue, doer *user_model.User,
|
||||
}
|
||||
defer committer.Close()
|
||||
|
||||
issue.Title, _ = util.SplitStringAtByteN(issue.Title, 255)
|
||||
if err = UpdateIssueCols(ctx, issue, "name"); err != nil {
|
||||
return fmt.Errorf("updateIssueCols: %w", err)
|
||||
}
|
||||
@ -386,6 +388,7 @@ func NewIssueWithIndex(ctx context.Context, doer *user_model.User, opts NewIssue
|
||||
}
|
||||
|
||||
// NewIssue creates new issue with labels for repository.
|
||||
// The title will be cut off at 255 characters if it's longer than 255 characters.
|
||||
func NewIssue(ctx context.Context, repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
|
||||
ctx, committer, err := db.TxContext(ctx)
|
||||
if err != nil {
|
||||
@ -399,6 +402,7 @@ func NewIssue(ctx context.Context, repo *repo_model.Repository, issue *Issue, la
|
||||
}
|
||||
|
||||
issue.Index = idx
|
||||
issue.Title, _ = util.SplitStringAtByteN(issue.Title, 255)
|
||||
|
||||
if err = NewIssueWithIndex(ctx, issue.Poster, NewIssueOptions{
|
||||
Repo: repo,
|
||||
|
@ -105,7 +105,7 @@ func GetIssueWatchers(ctx context.Context, issueID int64, listOptions db.ListOpt
|
||||
And("`user`.prohibit_login = ?", false).
|
||||
Join("INNER", "`user`", "`user`.id = `issue_watch`.user_id")
|
||||
|
||||
if listOptions.Page != 0 {
|
||||
if listOptions.Page > 0 {
|
||||
sess = db.SetSessionPagination(sess, &listOptions)
|
||||
watches := make([]*IssueWatch, 0, listOptions.PageSize)
|
||||
return watches, sess.Find(&watches)
|
||||
|
@ -390,7 +390,7 @@ func GetLabelsByRepoID(ctx context.Context, repoID int64, sortType string, listO
|
||||
sess.Asc("name")
|
||||
}
|
||||
|
||||
if listOptions.Page != 0 {
|
||||
if listOptions.Page > 0 {
|
||||
sess = db.SetSessionPagination(sess, &listOptions)
|
||||
}
|
||||
|
||||
@ -462,7 +462,7 @@ func GetLabelsByOrgID(ctx context.Context, orgID int64, sortType string, listOpt
|
||||
sess.Asc("name")
|
||||
}
|
||||
|
||||
if listOptions.Page != 0 {
|
||||
if listOptions.Page > 0 {
|
||||
sess = db.SetSessionPagination(sess, &listOptions)
|
||||
}
|
||||
|
||||
|
@ -406,7 +406,7 @@ func TestDeleteIssueLabel(t *testing.T) {
|
||||
PosterID: doerID,
|
||||
IssueID: issueID,
|
||||
LabelID: labelID,
|
||||
}, `content=""`)
|
||||
}, `content=''`)
|
||||
label = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID})
|
||||
assert.EqualValues(t, expectedNumIssues, label.NumIssues)
|
||||
assert.EqualValues(t, expectedNumClosedIssues, label.NumClosedIssues)
|
||||
|
@ -84,10 +84,9 @@ func (m *Milestone) BeforeUpdate() {
|
||||
// this object.
|
||||
func (m *Milestone) AfterLoad() {
|
||||
m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
|
||||
if m.DeadlineUnix.Year() == 9999 {
|
||||
if m.DeadlineUnix == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
m.DeadlineString = m.DeadlineUnix.FormatDate()
|
||||
if m.IsClosed {
|
||||
m.IsOverdue = m.ClosedDateUnix >= m.DeadlineUnix
|
||||
|
@ -572,6 +572,7 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, issue *Iss
|
||||
}
|
||||
|
||||
issue.Index = idx
|
||||
issue.Title, _ = util.SplitStringAtByteN(issue.Title, 255)
|
||||
|
||||
if err = NewIssueWithIndex(ctx, issue.Poster, NewIssueOptions{
|
||||
Repo: repo,
|
||||
|
@ -163,7 +163,7 @@ func FindReactions(ctx context.Context, opts FindReactionsOptions) (ReactionList
|
||||
Where(opts.toConds()).
|
||||
In("reaction.`type`", setting.UI.Reactions).
|
||||
Asc("reaction.issue_id", "reaction.comment_id", "reaction.created_unix", "reaction.id")
|
||||
if opts.Page != 0 {
|
||||
if opts.Page > 0 {
|
||||
sess = db.SetSessionPagination(sess, &opts)
|
||||
|
||||
reactions := make([]*Reaction, 0, opts.PageSize)
|
||||
|
@ -96,7 +96,7 @@ func GetUIDsAndStopwatch(ctx context.Context) ([]*UserStopwatch, error) {
|
||||
func GetUserStopwatches(ctx context.Context, userID int64, listOptions db.ListOptions) ([]*Stopwatch, error) {
|
||||
sws := make([]*Stopwatch, 0, 8)
|
||||
sess := db.GetEngine(ctx).Where("stopwatch.user_id = ?", userID)
|
||||
if listOptions.Page != 0 {
|
||||
if listOptions.Page > 0 {
|
||||
sess = db.SetSessionPagination(sess, &listOptions)
|
||||
}
|
||||
|
||||
|
@ -139,7 +139,7 @@ func (opts *FindTrackedTimesOptions) toSession(e db.Engine) db.Engine {
|
||||
|
||||
sess = sess.Where(opts.ToConds())
|
||||
|
||||
if opts.Page != 0 {
|
||||
if opts.Page > 0 {
|
||||
sess = db.SetSessionPagination(sess, opts)
|
||||
}
|
||||
|
||||
|
@ -8,7 +8,6 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
@ -16,11 +15,10 @@ import (
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
"code.gitea.io/gitea/modules/base"
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/testlogger"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
@ -35,35 +33,15 @@ func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (*xorm.Engine, fu
|
||||
ourSkip := 2
|
||||
ourSkip += skip
|
||||
deferFn := testlogger.PrintCurrentTest(t, ourSkip)
|
||||
assert.NoError(t, os.RemoveAll(setting.RepoRootPath))
|
||||
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath))
|
||||
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
|
||||
if err != nil {
|
||||
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
||||
}
|
||||
for _, ownerDir := range ownerDirs {
|
||||
if !ownerDir.Type().IsDir() {
|
||||
continue
|
||||
}
|
||||
repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
|
||||
if err != nil {
|
||||
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
|
||||
}
|
||||
for _, repoDir := range repoDirs {
|
||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
|
||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
|
||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
|
||||
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
|
||||
}
|
||||
}
|
||||
require.NoError(t, unittest.SyncDirs(filepath.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath))
|
||||
|
||||
if err := deleteDB(); err != nil {
|
||||
t.Errorf("unable to reset database: %v", err)
|
||||
t.Fatalf("unable to reset database: %v", err)
|
||||
return nil, deferFn
|
||||
}
|
||||
|
||||
x, err := newXORMEngine()
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
if x != nil {
|
||||
oldDefer := deferFn
|
||||
deferFn = func() {
|
||||
@ -112,39 +90,36 @@ func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (*xorm.Engine, fu
|
||||
}
|
||||
|
||||
func MainTest(m *testing.M) {
|
||||
log.RegisterEventWriter("test", testlogger.NewTestLoggerWriter)
|
||||
testlogger.Init()
|
||||
|
||||
giteaRoot := base.SetupGiteaRoot()
|
||||
if giteaRoot == "" {
|
||||
fmt.Println("Environment variable $GITEA_ROOT not set")
|
||||
os.Exit(1)
|
||||
testlogger.Fatalf("Environment variable $GITEA_ROOT not set\n")
|
||||
}
|
||||
giteaBinary := "gitea"
|
||||
if runtime.GOOS == "windows" {
|
||||
giteaBinary += ".exe"
|
||||
}
|
||||
setting.AppPath = path.Join(giteaRoot, giteaBinary)
|
||||
setting.AppPath = filepath.Join(giteaRoot, giteaBinary)
|
||||
if _, err := os.Stat(setting.AppPath); err != nil {
|
||||
fmt.Printf("Could not find gitea binary at %s\n", setting.AppPath)
|
||||
os.Exit(1)
|
||||
testlogger.Fatalf("Could not find gitea binary at %s\n", setting.AppPath)
|
||||
}
|
||||
|
||||
giteaConf := os.Getenv("GITEA_CONF")
|
||||
if giteaConf == "" {
|
||||
giteaConf = path.Join(filepath.Dir(setting.AppPath), "tests/sqlite.ini")
|
||||
giteaConf = filepath.Join(filepath.Dir(setting.AppPath), "tests/sqlite.ini")
|
||||
fmt.Printf("Environment variable $GITEA_CONF not set - defaulting to %s\n", giteaConf)
|
||||
}
|
||||
|
||||
if !path.IsAbs(giteaConf) {
|
||||
setting.CustomConf = path.Join(giteaRoot, giteaConf)
|
||||
if !filepath.IsAbs(giteaConf) {
|
||||
setting.CustomConf = filepath.Join(giteaRoot, giteaConf)
|
||||
} else {
|
||||
setting.CustomConf = giteaConf
|
||||
}
|
||||
|
||||
tmpDataPath, err := os.MkdirTemp("", "data")
|
||||
if err != nil {
|
||||
fmt.Printf("Unable to create temporary data path %v\n", err)
|
||||
os.Exit(1)
|
||||
testlogger.Fatalf("Unable to create temporary data path %v\n", err)
|
||||
}
|
||||
|
||||
setting.CustomPath = filepath.Join(setting.AppWorkPath, "custom")
|
||||
@ -152,8 +127,7 @@ func MainTest(m *testing.M) {
|
||||
|
||||
unittest.InitSettings()
|
||||
if err = git.InitFull(context.Background()); err != nil {
|
||||
fmt.Printf("Unable to InitFull: %v\n", err)
|
||||
os.Exit(1)
|
||||
testlogger.Fatalf("Unable to InitFull: %v\n", err)
|
||||
}
|
||||
setting.LoadDBSetting()
|
||||
setting.InitLoggersForTest()
|
||||
|
@ -364,6 +364,11 @@ func prepareMigrationTasks() []*migration {
|
||||
newMigration(304, "Add index for release sha1", v1_23.AddIndexForReleaseSha1),
|
||||
newMigration(305, "Add Repository Licenses", v1_23.AddRepositoryLicenses),
|
||||
newMigration(306, "Add BlockAdminMergeOverride to ProtectedBranch", v1_23.AddBlockAdminMergeOverrideBranchProtection),
|
||||
newMigration(307, "Fix milestone deadline_unix when there is no due date", v1_23.FixMilestoneNoDueDate),
|
||||
newMigration(308, "Add index(user_id, is_deleted) for action table", v1_23.AddNewIndexForUserDashboard),
|
||||
newMigration(309, "Improve Notification table indices", v1_23.ImproveNotificationTableIndices),
|
||||
newMigration(310, "Add Priority to ProtectedBranch", v1_23.AddPriorityToProtectedBranch),
|
||||
newMigration(311, "Add TimeEstimate to Issue table", v1_23.AddTimeEstimateColumnToIssueTable),
|
||||
}
|
||||
return preparedMigrations
|
||||
}
|
||||
|
@ -12,6 +12,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
giturl "code.gitea.io/gitea/modules/git/url"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
@ -163,7 +164,9 @@ func migratePushMirrors(x *xorm.Engine) error {
|
||||
|
||||
func getRemoteAddress(ownerName, repoName, remoteName string) (string, error) {
|
||||
repoPath := filepath.Join(setting.RepoRootPath, strings.ToLower(ownerName), strings.ToLower(repoName)+".git")
|
||||
|
||||
if exist, _ := util.IsExist(repoPath); !exist {
|
||||
return "", nil
|
||||
}
|
||||
remoteURL, err := git.GetRemoteAddress(context.Background(), repoPath, remoteName)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("get remote %s's address of %s/%s failed: %v", remoteName, ownerName, repoName, err)
|
||||
|
21
models/migrations/v1_23/v307.go
Normal file
21
models/migrations/v1_23/v307.go
Normal file
@ -0,0 +1,21 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package v1_23 //nolint
|
||||
|
||||
import (
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func FixMilestoneNoDueDate(x *xorm.Engine) error {
|
||||
type Milestone struct {
|
||||
DeadlineUnix timeutil.TimeStamp
|
||||
}
|
||||
// Wednesday, December 1, 9999 12:00:00 AM GMT+00:00
|
||||
_, err := x.Table("milestone").Where("deadline_unix > 253399622400").
|
||||
Cols("deadline_unix").
|
||||
Update(&Milestone{DeadlineUnix: 0})
|
||||
return err
|
||||
}
|
52
models/migrations/v1_23/v308.go
Normal file
52
models/migrations/v1_23/v308.go
Normal file
@ -0,0 +1,52 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package v1_23 //nolint
|
||||
|
||||
import (
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
|
||||
"xorm.io/xorm"
|
||||
"xorm.io/xorm/schemas"
|
||||
)
|
||||
|
||||
type improveActionTableIndicesAction struct {
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
UserID int64 `xorm:"INDEX"` // Receiver user id.
|
||||
OpType int
|
||||
ActUserID int64 // Action user id.
|
||||
RepoID int64
|
||||
CommentID int64 `xorm:"INDEX"`
|
||||
IsDeleted bool `xorm:"NOT NULL DEFAULT false"`
|
||||
RefName string
|
||||
IsPrivate bool `xorm:"NOT NULL DEFAULT false"`
|
||||
Content string `xorm:"TEXT"`
|
||||
CreatedUnix timeutil.TimeStamp `xorm:"created"`
|
||||
}
|
||||
|
||||
// TableName sets the name of this table
|
||||
func (*improveActionTableIndicesAction) TableName() string {
|
||||
return "action"
|
||||
}
|
||||
|
||||
func (a *improveActionTableIndicesAction) TableIndices() []*schemas.Index {
|
||||
repoIndex := schemas.NewIndex("r_u_d", schemas.IndexType)
|
||||
repoIndex.AddColumn("repo_id", "user_id", "is_deleted")
|
||||
|
||||
actUserIndex := schemas.NewIndex("au_r_c_u_d", schemas.IndexType)
|
||||
actUserIndex.AddColumn("act_user_id", "repo_id", "created_unix", "user_id", "is_deleted")
|
||||
|
||||
cudIndex := schemas.NewIndex("c_u_d", schemas.IndexType)
|
||||
cudIndex.AddColumn("created_unix", "user_id", "is_deleted")
|
||||
|
||||
cuIndex := schemas.NewIndex("c_u", schemas.IndexType)
|
||||
cuIndex.AddColumn("user_id", "is_deleted")
|
||||
|
||||
indices := []*schemas.Index{actUserIndex, repoIndex, cudIndex, cuIndex}
|
||||
|
||||
return indices
|
||||
}
|
||||
|
||||
func AddNewIndexForUserDashboard(x *xorm.Engine) error {
|
||||
return x.Sync(new(improveActionTableIndicesAction))
|
||||
}
|
77
models/migrations/v1_23/v309.go
Normal file
77
models/migrations/v1_23/v309.go
Normal file
@ -0,0 +1,77 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package v1_23 //nolint
|
||||
|
||||
import (
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
|
||||
"xorm.io/xorm"
|
||||
"xorm.io/xorm/schemas"
|
||||
)
|
||||
|
||||
type improveNotificationTableIndicesAction struct {
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
UserID int64 `xorm:"NOT NULL"`
|
||||
RepoID int64 `xorm:"NOT NULL"`
|
||||
|
||||
Status uint8 `xorm:"SMALLINT NOT NULL"`
|
||||
Source uint8 `xorm:"SMALLINT NOT NULL"`
|
||||
|
||||
IssueID int64 `xorm:"NOT NULL"`
|
||||
CommitID string
|
||||
CommentID int64
|
||||
|
||||
UpdatedBy int64 `xorm:"NOT NULL"`
|
||||
|
||||
CreatedUnix timeutil.TimeStamp `xorm:"created NOT NULL"`
|
||||
UpdatedUnix timeutil.TimeStamp `xorm:"updated NOT NULL"`
|
||||
}
|
||||
|
||||
// TableName sets the name of this table
|
||||
func (*improveNotificationTableIndicesAction) TableName() string {
|
||||
return "notification"
|
||||
}
|
||||
|
||||
// TableIndices implements xorm's TableIndices interface
|
||||
func (*improveNotificationTableIndicesAction) TableIndices() []*schemas.Index {
|
||||
indices := make([]*schemas.Index, 0, 8)
|
||||
usuuIndex := schemas.NewIndex("u_s_uu", schemas.IndexType)
|
||||
usuuIndex.AddColumn("user_id", "status", "updated_unix")
|
||||
indices = append(indices, usuuIndex)
|
||||
|
||||
// Add the individual indices that were previously defined in struct tags
|
||||
userIDIndex := schemas.NewIndex("idx_notification_user_id", schemas.IndexType)
|
||||
userIDIndex.AddColumn("user_id")
|
||||
indices = append(indices, userIDIndex)
|
||||
|
||||
repoIDIndex := schemas.NewIndex("idx_notification_repo_id", schemas.IndexType)
|
||||
repoIDIndex.AddColumn("repo_id")
|
||||
indices = append(indices, repoIDIndex)
|
||||
|
||||
statusIndex := schemas.NewIndex("idx_notification_status", schemas.IndexType)
|
||||
statusIndex.AddColumn("status")
|
||||
indices = append(indices, statusIndex)
|
||||
|
||||
sourceIndex := schemas.NewIndex("idx_notification_source", schemas.IndexType)
|
||||
sourceIndex.AddColumn("source")
|
||||
indices = append(indices, sourceIndex)
|
||||
|
||||
issueIDIndex := schemas.NewIndex("idx_notification_issue_id", schemas.IndexType)
|
||||
issueIDIndex.AddColumn("issue_id")
|
||||
indices = append(indices, issueIDIndex)
|
||||
|
||||
commitIDIndex := schemas.NewIndex("idx_notification_commit_id", schemas.IndexType)
|
||||
commitIDIndex.AddColumn("commit_id")
|
||||
indices = append(indices, commitIDIndex)
|
||||
|
||||
updatedByIndex := schemas.NewIndex("idx_notification_updated_by", schemas.IndexType)
|
||||
updatedByIndex.AddColumn("updated_by")
|
||||
indices = append(indices, updatedByIndex)
|
||||
|
||||
return indices
|
||||
}
|
||||
|
||||
func ImproveNotificationTableIndices(x *xorm.Engine) error {
|
||||
return x.Sync(&improveNotificationTableIndicesAction{})
|
||||
}
|
16
models/migrations/v1_23/v310.go
Normal file
16
models/migrations/v1_23/v310.go
Normal file
@ -0,0 +1,16 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package v1_23 //nolint
|
||||
|
||||
import (
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func AddPriorityToProtectedBranch(x *xorm.Engine) error {
|
||||
type ProtectedBranch struct {
|
||||
Priority int64 `xorm:"NOT NULL DEFAULT 0"`
|
||||
}
|
||||
|
||||
return x.Sync(new(ProtectedBranch))
|
||||
}
|
16
models/migrations/v1_23/v311.go
Normal file
16
models/migrations/v1_23/v311.go
Normal file
@ -0,0 +1,16 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package v1_23 //nolint
|
||||
|
||||
import (
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func AddTimeEstimateColumnToIssueTable(x *xorm.Engine) error {
|
||||
type Issue struct {
|
||||
TimeEstimate int64 `xorm:"NOT NULL DEFAULT 0"`
|
||||
}
|
||||
|
||||
return x.Sync(new(Issue))
|
||||
}
|
@ -1,564 +0,0 @@
|
||||
// Copyright 2018 The Gitea Authors. All rights reserved.
|
||||
// Copyright 2016 The Gogs Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
git_model "code.gitea.io/gitea/models/git"
|
||||
issues_model "code.gitea.io/gitea/models/issues"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
access_model "code.gitea.io/gitea/models/perm/access"
|
||||
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/setting"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"xorm.io/builder"
|
||||
)
|
||||
|
||||
func AddRepository(ctx context.Context, t *organization.Team, repo *repo_model.Repository) (err error) {
|
||||
if err = organization.AddTeamRepo(ctx, t.OrgID, t.ID, repo.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = organization.IncrTeamRepoNum(ctx, t.ID); err != nil {
|
||||
return fmt.Errorf("update team: %w", err)
|
||||
}
|
||||
|
||||
t.NumRepos++
|
||||
|
||||
if err = access_model.RecalculateTeamAccesses(ctx, repo, 0); err != nil {
|
||||
return fmt.Errorf("recalculateAccesses: %w", err)
|
||||
}
|
||||
|
||||
// Make all team members watch this repo if enabled in global settings
|
||||
if setting.Service.AutoWatchNewRepos {
|
||||
if err = t.LoadMembers(ctx); err != nil {
|
||||
return fmt.Errorf("getMembers: %w", err)
|
||||
}
|
||||
for _, u := range t.Members {
|
||||
if err = repo_model.WatchRepo(ctx, u, repo, true); err != nil {
|
||||
return fmt.Errorf("watchRepo: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// addAllRepositories adds all repositories to the team.
|
||||
// If the team already has some repositories they will be left unchanged.
|
||||
func addAllRepositories(ctx context.Context, t *organization.Team) error {
|
||||
orgRepos, err := organization.GetOrgRepositories(ctx, t.OrgID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get org repos: %w", err)
|
||||
}
|
||||
|
||||
for _, repo := range orgRepos {
|
||||
if !organization.HasTeamRepo(ctx, t.OrgID, t.ID, repo.ID) {
|
||||
if err := AddRepository(ctx, t, repo); err != nil {
|
||||
return fmt.Errorf("AddRepository: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddAllRepositories adds all repositories to the team
|
||||
func AddAllRepositories(ctx context.Context, t *organization.Team) (err error) {
|
||||
ctx, committer, err := db.TxContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer committer.Close()
|
||||
|
||||
if err = addAllRepositories(ctx, t); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return committer.Commit()
|
||||
}
|
||||
|
||||
// RemoveAllRepositories removes all repositories from team and recalculates access
|
||||
func RemoveAllRepositories(ctx context.Context, t *organization.Team) (err error) {
|
||||
if t.IncludesAllRepositories {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, committer, err := db.TxContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer committer.Close()
|
||||
|
||||
if err = removeAllRepositories(ctx, t); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return committer.Commit()
|
||||
}
|
||||
|
||||
// removeAllRepositories removes all repositories from team and recalculates access
|
||||
// Note: Shall not be called if team includes all repositories
|
||||
func removeAllRepositories(ctx context.Context, t *organization.Team) (err error) {
|
||||
e := db.GetEngine(ctx)
|
||||
// Delete all accesses.
|
||||
for _, repo := range t.Repos {
|
||||
if err := access_model.RecalculateTeamAccesses(ctx, repo, t.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove watches from all users and now unaccessible repos
|
||||
for _, user := range t.Members {
|
||||
has, err := access_model.HasAnyUnitAccess(ctx, user.ID, repo)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if has {
|
||||
continue
|
||||
}
|
||||
|
||||
if err = repo_model.WatchRepo(ctx, user, repo, false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove all IssueWatches a user has subscribed to in the repositories
|
||||
if err = issues_model.RemoveIssueWatchersByRepoID(ctx, user.ID, repo.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete team-repo
|
||||
if _, err := e.
|
||||
Where("team_id=?", t.ID).
|
||||
Delete(new(organization.TeamRepo)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
t.NumRepos = 0
|
||||
if _, err = e.ID(t.ID).Cols("num_repos").Update(t); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewTeam creates a record of new team.
|
||||
// It's caller's responsibility to assign organization ID.
|
||||
func NewTeam(ctx context.Context, t *organization.Team) (err error) {
|
||||
if len(t.Name) == 0 {
|
||||
return util.NewInvalidArgumentErrorf("empty team name")
|
||||
}
|
||||
|
||||
if err = organization.IsUsableTeamName(t.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
has, err := db.ExistByID[user_model.User](ctx, t.OrgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !has {
|
||||
return organization.ErrOrgNotExist{ID: t.OrgID}
|
||||
}
|
||||
|
||||
t.LowerName = strings.ToLower(t.Name)
|
||||
has, err = db.Exist[organization.Team](ctx, builder.Eq{
|
||||
"org_id": t.OrgID,
|
||||
"lower_name": t.LowerName,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if has {
|
||||
return organization.ErrTeamAlreadyExist{OrgID: t.OrgID, Name: t.LowerName}
|
||||
}
|
||||
|
||||
ctx, committer, err := db.TxContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer committer.Close()
|
||||
|
||||
if err = db.Insert(ctx, t); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// insert units for team
|
||||
if len(t.Units) > 0 {
|
||||
for _, unit := range t.Units {
|
||||
unit.TeamID = t.ID
|
||||
}
|
||||
if err = db.Insert(ctx, &t.Units); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Add all repositories to the team if it has access to all of them.
|
||||
if t.IncludesAllRepositories {
|
||||
err = addAllRepositories(ctx, t)
|
||||
if err != nil {
|
||||
return fmt.Errorf("addAllRepositories: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Update organization number of teams.
|
||||
if _, err = db.Exec(ctx, "UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
|
||||
return err
|
||||
}
|
||||
return committer.Commit()
|
||||
}
|
||||
|
||||
// UpdateTeam updates information of team.
|
||||
func UpdateTeam(ctx context.Context, t *organization.Team, updateCols ...string) (err error) {
|
||||
if len(t.Name) == 0 {
|
||||
return util.NewInvalidArgumentErrorf("empty team name")
|
||||
}
|
||||
|
||||
if slices.Contains(updateCols, "name") && !slices.Contains(updateCols, "lower_name") {
|
||||
t.LowerName = strings.ToLower(t.Name)
|
||||
updateCols = append(updateCols, "lower_name")
|
||||
}
|
||||
|
||||
authChanged := slices.Contains(updateCols, "authorize")
|
||||
includeAllChanged := slices.Contains(updateCols, "includes_all_repositories")
|
||||
|
||||
if len(t.Description) > 255 {
|
||||
t.Description = t.Description[:255]
|
||||
}
|
||||
|
||||
ctx, committer, err := db.TxContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer committer.Close()
|
||||
|
||||
t.LowerName = strings.ToLower(t.Name)
|
||||
has, err := db.Exist[organization.Team](ctx, builder.Eq{
|
||||
"org_id": t.OrgID,
|
||||
"lower_name": t.LowerName,
|
||||
}.And(builder.Neq{"id": t.ID}),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if has {
|
||||
return organization.ErrTeamAlreadyExist{OrgID: t.OrgID, Name: t.LowerName}
|
||||
}
|
||||
|
||||
sess := db.GetEngine(ctx)
|
||||
if _, err = sess.ID(t.ID).Cols(updateCols...).Update(t); err != nil {
|
||||
return fmt.Errorf("update: %w", err)
|
||||
}
|
||||
|
||||
// update units for team
|
||||
if slices.Contains(updateCols, "units") {
|
||||
for _, unit := range t.Units {
|
||||
unit.TeamID = t.ID
|
||||
}
|
||||
// Delete team-unit.
|
||||
if _, err := sess.
|
||||
Where("team_id=?", t.ID).
|
||||
Delete(new(organization.TeamUnit)); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = sess.Cols("org_id", "team_id", "type", "access_mode").Insert(&t.Units); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Update access for team members if needed.
|
||||
if authChanged {
|
||||
if err = t.LoadRepositories(ctx); err != nil {
|
||||
return fmt.Errorf("LoadRepositories: %w", err)
|
||||
}
|
||||
|
||||
for _, repo := range t.Repos {
|
||||
if err = access_model.RecalculateTeamAccesses(ctx, repo, 0); err != nil {
|
||||
return fmt.Errorf("recalculateTeamAccesses: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add all repositories to the team if it has access to all of them.
|
||||
if includeAllChanged && t.IncludesAllRepositories {
|
||||
err = addAllRepositories(ctx, t)
|
||||
if err != nil {
|
||||
return fmt.Errorf("addAllRepositories: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return committer.Commit()
|
||||
}
|
||||
|
||||
// DeleteTeam deletes given team.
|
||||
// It's caller's responsibility to assign organization ID.
|
||||
func DeleteTeam(ctx context.Context, t *organization.Team) error {
|
||||
ctx, committer, err := db.TxContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer committer.Close()
|
||||
|
||||
if err := t.LoadRepositories(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := t.LoadMembers(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update branch protections
|
||||
{
|
||||
protections := make([]*git_model.ProtectedBranch, 0, 10)
|
||||
err := db.GetEngine(ctx).In("repo_id",
|
||||
builder.Select("id").From("repository").Where(builder.Eq{"owner_id": t.OrgID})).
|
||||
Find(&protections)
|
||||
if err != nil {
|
||||
return fmt.Errorf("findProtectedBranches: %w", err)
|
||||
}
|
||||
for _, p := range protections {
|
||||
if err := git_model.RemoveTeamIDFromProtectedBranch(ctx, p, t.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !t.IncludesAllRepositories {
|
||||
if err := removeAllRepositories(ctx, t); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := db.DeleteBeans(ctx,
|
||||
&organization.Team{ID: t.ID},
|
||||
&organization.TeamUser{OrgID: t.OrgID, TeamID: t.ID},
|
||||
&organization.TeamUnit{TeamID: t.ID},
|
||||
&organization.TeamInvite{TeamID: t.ID},
|
||||
&issues_model.Review{Type: issues_model.ReviewTypeRequest, ReviewerTeamID: t.ID}, // batch delete the binding relationship between team and PR (request review from team)
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, tm := range t.Members {
|
||||
if err := removeInvalidOrgUser(ctx, t.OrgID, tm); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Update organization number of teams.
|
||||
if _, err := db.Exec(ctx, "UPDATE `user` SET num_teams=num_teams-1 WHERE id=?", t.OrgID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return committer.Commit()
|
||||
}
|
||||
|
||||
// AddTeamMember adds new membership of given team to given organization,
|
||||
// the user will have membership to given organization automatically when needed.
|
||||
func AddTeamMember(ctx context.Context, team *organization.Team, user *user_model.User) error {
|
||||
if user_model.IsUserBlockedBy(ctx, user, team.OrgID) {
|
||||
return user_model.ErrBlockedUser
|
||||
}
|
||||
|
||||
isAlreadyMember, err := organization.IsTeamMember(ctx, team.OrgID, team.ID, user.ID)
|
||||
if err != nil || isAlreadyMember {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := organization.AddOrgUser(ctx, team.OrgID, user.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = db.WithTx(ctx, func(ctx context.Context) error {
|
||||
// check in transaction
|
||||
isAlreadyMember, err = organization.IsTeamMember(ctx, team.OrgID, team.ID, user.ID)
|
||||
if err != nil || isAlreadyMember {
|
||||
return err
|
||||
}
|
||||
|
||||
sess := db.GetEngine(ctx)
|
||||
|
||||
if err := db.Insert(ctx, &organization.TeamUser{
|
||||
UID: user.ID,
|
||||
OrgID: team.OrgID,
|
||||
TeamID: team.ID,
|
||||
}); err != nil {
|
||||
return err
|
||||
} else if _, err := sess.Incr("num_members").ID(team.ID).Update(new(organization.Team)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
team.NumMembers++
|
||||
|
||||
// Give access to team repositories.
|
||||
// update exist access if mode become bigger
|
||||
subQuery := builder.Select("repo_id").From("team_repo").
|
||||
Where(builder.Eq{"team_id": team.ID})
|
||||
|
||||
if _, err := sess.Where("user_id=?", user.ID).
|
||||
In("repo_id", subQuery).
|
||||
And("mode < ?", team.AccessMode).
|
||||
SetExpr("mode", team.AccessMode).
|
||||
Update(new(access_model.Access)); err != nil {
|
||||
return fmt.Errorf("update user accesses: %w", err)
|
||||
}
|
||||
|
||||
// for not exist access
|
||||
var repoIDs []int64
|
||||
accessSubQuery := builder.Select("repo_id").From("access").Where(builder.Eq{"user_id": user.ID})
|
||||
if err := sess.SQL(subQuery.And(builder.NotIn("repo_id", accessSubQuery))).Find(&repoIDs); err != nil {
|
||||
return fmt.Errorf("select id accesses: %w", err)
|
||||
}
|
||||
|
||||
accesses := make([]*access_model.Access, 0, 100)
|
||||
for i, repoID := range repoIDs {
|
||||
accesses = append(accesses, &access_model.Access{RepoID: repoID, UserID: user.ID, Mode: team.AccessMode})
|
||||
if (i%100 == 0 || i == len(repoIDs)-1) && len(accesses) > 0 {
|
||||
if err = db.Insert(ctx, accesses); err != nil {
|
||||
return fmt.Errorf("insert new user accesses: %w", err)
|
||||
}
|
||||
accesses = accesses[:0]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// this behaviour may spend much time so run it in a goroutine
|
||||
// FIXME: Update watch repos batchly
|
||||
if setting.Service.AutoWatchNewRepos {
|
||||
// Get team and its repositories.
|
||||
if err := team.LoadRepositories(ctx); err != nil {
|
||||
log.Error("team.LoadRepositories failed: %v", err)
|
||||
}
|
||||
|
||||
// FIXME: in the goroutine, it can't access the "ctx", it could only use db.DefaultContext at the moment
|
||||
go func(repos []*repo_model.Repository) {
|
||||
for _, repo := range repos {
|
||||
if err = repo_model.WatchRepo(db.DefaultContext, user, repo, true); err != nil {
|
||||
log.Error("watch repo failed: %v", err)
|
||||
}
|
||||
}
|
||||
}(team.Repos)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func removeTeamMember(ctx context.Context, team *organization.Team, user *user_model.User) error {
|
||||
e := db.GetEngine(ctx)
|
||||
isMember, err := organization.IsTeamMember(ctx, team.OrgID, team.ID, user.ID)
|
||||
if err != nil || !isMember {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check if the user to delete is the last member in owner team.
|
||||
if team.IsOwnerTeam() && team.NumMembers == 1 {
|
||||
return organization.ErrLastOrgOwner{UID: user.ID}
|
||||
}
|
||||
|
||||
team.NumMembers--
|
||||
|
||||
if err := team.LoadRepositories(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := e.Delete(&organization.TeamUser{
|
||||
UID: user.ID,
|
||||
OrgID: team.OrgID,
|
||||
TeamID: team.ID,
|
||||
}); err != nil {
|
||||
return err
|
||||
} else if _, err = e.
|
||||
ID(team.ID).
|
||||
Cols("num_members").
|
||||
Update(team); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete access to team repositories.
|
||||
for _, repo := range team.Repos {
|
||||
if err := access_model.RecalculateUserAccess(ctx, repo, user.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove watches from now unaccessible
|
||||
if err := ReconsiderWatches(ctx, repo, user); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove issue assignments from now unaccessible
|
||||
if err := ReconsiderRepoIssuesAssignee(ctx, repo, user); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return removeInvalidOrgUser(ctx, team.OrgID, user)
|
||||
}
|
||||
|
||||
func removeInvalidOrgUser(ctx context.Context, orgID int64, user *user_model.User) error {
|
||||
// Check if the user is a member of any team in the organization.
|
||||
if count, err := db.GetEngine(ctx).Count(&organization.TeamUser{
|
||||
UID: user.ID,
|
||||
OrgID: orgID,
|
||||
}); err != nil {
|
||||
return err
|
||||
} else if count == 0 {
|
||||
org, err := organization.GetOrgByID(ctx, orgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return RemoveOrgUser(ctx, org, user)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveTeamMember removes member from given team of given organization.
|
||||
func RemoveTeamMember(ctx context.Context, team *organization.Team, user *user_model.User) error {
|
||||
ctx, committer, err := db.TxContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer committer.Close()
|
||||
if err := removeTeamMember(ctx, team, user); err != nil {
|
||||
return err
|
||||
}
|
||||
return committer.Commit()
|
||||
}
|
||||
|
||||
func ReconsiderRepoIssuesAssignee(ctx context.Context, repo *repo_model.Repository, user *user_model.User) error {
|
||||
if canAssigned, err := access_model.CanBeAssigned(ctx, user, repo, true); err != nil || canAssigned {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := db.GetEngine(ctx).Where(builder.Eq{"assignee_id": user.ID}).
|
||||
In("issue_id", builder.Select("id").From("issue").Where(builder.Eq{"repo_id": repo.ID})).
|
||||
Delete(&issues_model.IssueAssignees{}); err != nil {
|
||||
return fmt.Errorf("Could not delete assignee[%d] %w", user.ID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ReconsiderWatches(ctx context.Context, repo *repo_model.Repository, user *user_model.User) error {
|
||||
if has, err := access_model.HasAnyUnitAccess(ctx, user.ID, repo); err != nil || has {
|
||||
return err
|
||||
}
|
||||
if err := repo_model.WatchRepo(ctx, user, repo, false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove all IssueWatches a user has subscribed to in the repository
|
||||
return issues_model.RemoveIssueWatchersByRepoID(ctx, user.ID, repo.ID)
|
||||
}
|
@ -1,78 +0,0 @@
|
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package organization
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
|
||||
"xorm.io/builder"
|
||||
)
|
||||
|
||||
// MinimalOrg represents a simple organization with only the needed columns
|
||||
type MinimalOrg = Organization
|
||||
|
||||
// GetUserOrgsList returns all organizations the given user has access to
|
||||
func GetUserOrgsList(ctx context.Context, user *user_model.User) ([]*MinimalOrg, error) {
|
||||
schema, err := db.TableInfo(new(user_model.User))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputCols := []string{
|
||||
"id",
|
||||
"name",
|
||||
"full_name",
|
||||
"visibility",
|
||||
"avatar",
|
||||
"avatar_email",
|
||||
"use_custom_avatar",
|
||||
}
|
||||
|
||||
groupByCols := &strings.Builder{}
|
||||
for _, col := range outputCols {
|
||||
fmt.Fprintf(groupByCols, "`%s`.%s,", schema.Name, col)
|
||||
}
|
||||
groupByStr := groupByCols.String()
|
||||
groupByStr = groupByStr[0 : len(groupByStr)-1]
|
||||
|
||||
sess := db.GetEngine(ctx)
|
||||
sess = sess.Select(groupByStr+", count(distinct repo_id) as org_count").
|
||||
Table("user").
|
||||
Join("INNER", "team", "`team`.org_id = `user`.id").
|
||||
Join("INNER", "team_user", "`team`.id = `team_user`.team_id").
|
||||
Join("LEFT", builder.
|
||||
Select("id as repo_id, owner_id as repo_owner_id").
|
||||
From("repository").
|
||||
Where(repo_model.AccessibleRepositoryCondition(user, unit.TypeInvalid)), "`repository`.repo_owner_id = `team`.org_id").
|
||||
Where("`team_user`.uid = ?", user.ID).
|
||||
GroupBy(groupByStr)
|
||||
|
||||
type OrgCount struct {
|
||||
Organization `xorm:"extends"`
|
||||
OrgCount int
|
||||
}
|
||||
|
||||
orgCounts := make([]*OrgCount, 0, 10)
|
||||
|
||||
if err := sess.
|
||||
Asc("`user`.name").
|
||||
Find(&orgCounts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
orgs := make([]*MinimalOrg, len(orgCounts))
|
||||
for i, orgCount := range orgCounts {
|
||||
orgCount.Organization.NumRepos = orgCount.OrgCount
|
||||
orgs[i] = &orgCount.Organization
|
||||
}
|
||||
|
||||
return orgs, nil
|
||||
}
|
@ -22,15 +22,9 @@ import (
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"xorm.io/builder"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
// ________ .__ __ .__
|
||||
// \_____ \_______ _________ ____ |__|____________ _/ |_|__| ____ ____
|
||||
// / | \_ __ \/ ___\__ \ / \| \___ /\__ \\ __\ |/ _ \ / \
|
||||
// / | \ | \/ /_/ > __ \| | \ |/ / / __ \| | | ( <_> ) | \
|
||||
// \_______ /__| \___ (____ /___| /__/_____ \(____ /__| |__|\____/|___| /
|
||||
// \/ /_____/ \/ \/ \/ \/ \/
|
||||
|
||||
// ErrOrgNotExist represents a "OrgNotExist" kind of error.
|
||||
type ErrOrgNotExist struct {
|
||||
ID int64
|
||||
@ -141,8 +135,9 @@ func (org *Organization) LoadTeams(ctx context.Context) ([]*Team, error) {
|
||||
}
|
||||
|
||||
// GetMembers returns all members of organization.
|
||||
func (org *Organization) GetMembers(ctx context.Context) (user_model.UserList, map[int64]bool, error) {
|
||||
func (org *Organization) GetMembers(ctx context.Context, doer *user_model.User) (user_model.UserList, map[int64]bool, error) {
|
||||
return FindOrgMembers(ctx, &FindOrgMembersOpts{
|
||||
Doer: doer,
|
||||
OrgID: org.ID,
|
||||
})
|
||||
}
|
||||
@ -195,16 +190,39 @@ func (org *Organization) CanCreateRepo() bool {
|
||||
// FindOrgMembersOpts represensts find org members conditions
|
||||
type FindOrgMembersOpts struct {
|
||||
db.ListOptions
|
||||
OrgID int64
|
||||
PublicOnly bool
|
||||
Doer *user_model.User
|
||||
IsDoerMember bool
|
||||
OrgID int64
|
||||
}
|
||||
|
||||
func (opts FindOrgMembersOpts) PublicOnly() bool {
|
||||
return opts.Doer == nil || !(opts.IsDoerMember || opts.Doer.IsAdmin)
|
||||
}
|
||||
|
||||
// applyTeamMatesOnlyFilter make sure restricted users only see public team members and there own team mates
|
||||
func (opts FindOrgMembersOpts) applyTeamMatesOnlyFilter(sess *xorm.Session) {
|
||||
if opts.Doer != nil && opts.IsDoerMember && opts.Doer.IsRestricted {
|
||||
teamMates := builder.Select("DISTINCT team_user.uid").
|
||||
From("team_user").
|
||||
Where(builder.In("team_user.team_id", getUserTeamIDsQueryBuilder(opts.OrgID, opts.Doer.ID))).
|
||||
And(builder.Eq{"team_user.org_id": opts.OrgID})
|
||||
|
||||
sess.And(
|
||||
builder.In("org_user.uid", teamMates).
|
||||
Or(builder.Eq{"org_user.is_public": true}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// CountOrgMembers counts the organization's members
|
||||
func CountOrgMembers(ctx context.Context, opts *FindOrgMembersOpts) (int64, error) {
|
||||
sess := db.GetEngine(ctx).Where("org_id=?", opts.OrgID)
|
||||
if opts.PublicOnly {
|
||||
sess.And("is_public = ?", true)
|
||||
if opts.PublicOnly() {
|
||||
sess = sess.And("is_public = ?", true)
|
||||
} else {
|
||||
opts.applyTeamMatesOnlyFilter(sess)
|
||||
}
|
||||
|
||||
return sess.Count(new(OrgUser))
|
||||
}
|
||||
|
||||
@ -440,42 +458,6 @@ func GetUsersWhoCanCreateOrgRepo(ctx context.Context, orgID int64) (map[int64]*u
|
||||
And("team_user.org_id = ?", orgID).Find(&users)
|
||||
}
|
||||
|
||||
// SearchOrganizationsOptions options to filter organizations
|
||||
type SearchOrganizationsOptions struct {
|
||||
db.ListOptions
|
||||
All bool
|
||||
}
|
||||
|
||||
// FindOrgOptions finds orgs options
|
||||
type FindOrgOptions struct {
|
||||
db.ListOptions
|
||||
UserID int64
|
||||
IncludePrivate bool
|
||||
}
|
||||
|
||||
func queryUserOrgIDs(userID int64, includePrivate bool) *builder.Builder {
|
||||
cond := builder.Eq{"uid": userID}
|
||||
if !includePrivate {
|
||||
cond["is_public"] = true
|
||||
}
|
||||
return builder.Select("org_id").From("org_user").Where(cond)
|
||||
}
|
||||
|
||||
func (opts FindOrgOptions) ToConds() builder.Cond {
|
||||
var cond builder.Cond = builder.Eq{"`user`.`type`": user_model.UserTypeOrganization}
|
||||
if opts.UserID > 0 {
|
||||
cond = cond.And(builder.In("`user`.`id`", queryUserOrgIDs(opts.UserID, opts.IncludePrivate)))
|
||||
}
|
||||
if !opts.IncludePrivate {
|
||||
cond = cond.And(builder.Eq{"`user`.visibility": structs.VisibleTypePublic})
|
||||
}
|
||||
return cond
|
||||
}
|
||||
|
||||
func (opts FindOrgOptions) ToOrders() string {
|
||||
return "`user`.name ASC"
|
||||
}
|
||||
|
||||
// HasOrgOrUserVisible tells if the given user can see the given org or user
|
||||
func HasOrgOrUserVisible(ctx context.Context, orgOrUser, user *user_model.User) bool {
|
||||
// If user is nil, it's an anonymous user/request.
|
||||
@ -508,26 +490,15 @@ func HasOrgsVisible(ctx context.Context, orgs []*Organization, user *user_model.
|
||||
return false
|
||||
}
|
||||
|
||||
// GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID
|
||||
// are allowed to create repos.
|
||||
func GetOrgsCanCreateRepoByUserID(ctx context.Context, userID int64) ([]*Organization, error) {
|
||||
orgs := make([]*Organization, 0, 10)
|
||||
|
||||
return orgs, db.GetEngine(ctx).Where(builder.In("id", builder.Select("`user`.id").From("`user`").
|
||||
Join("INNER", "`team_user`", "`team_user`.org_id = `user`.id").
|
||||
Join("INNER", "`team`", "`team`.id = `team_user`.team_id").
|
||||
Where(builder.Eq{"`team_user`.uid": userID}).
|
||||
And(builder.Eq{"`team`.authorize": perm.AccessModeOwner}.Or(builder.Eq{"`team`.can_create_org_repo": true})))).
|
||||
Asc("`user`.name").
|
||||
Find(&orgs)
|
||||
}
|
||||
|
||||
// GetOrgUsersByOrgID returns all organization-user relations by organization ID.
|
||||
func GetOrgUsersByOrgID(ctx context.Context, opts *FindOrgMembersOpts) ([]*OrgUser, error) {
|
||||
sess := db.GetEngine(ctx).Where("org_id=?", opts.OrgID)
|
||||
if opts.PublicOnly {
|
||||
sess.And("is_public = ?", true)
|
||||
if opts.PublicOnly() {
|
||||
sess = sess.And("is_public = ?", true)
|
||||
} else {
|
||||
opts.applyTeamMatesOnlyFilter(sess)
|
||||
}
|
||||
|
||||
if opts.ListOptions.PageSize > 0 {
|
||||
sess = db.SetSessionPagination(sess, opts)
|
||||
|
||||
@ -656,6 +627,15 @@ func (org *Organization) getUserTeamIDs(ctx context.Context, userID int64) ([]in
|
||||
Find(&teamIDs)
|
||||
}
|
||||
|
||||
func getUserTeamIDsQueryBuilder(orgID, userID int64) *builder.Builder {
|
||||
return builder.Select("team.id").From("team").
|
||||
InnerJoin("team_user", "team_user.team_id = team.id").
|
||||
Where(builder.Eq{
|
||||
"team_user.org_id": orgID,
|
||||
"team_user.uid": userID,
|
||||
})
|
||||
}
|
||||
|
||||
// TeamsWithAccessToRepo returns all teams that have given access level to the repository.
|
||||
func (org *Organization) TeamsWithAccessToRepo(ctx context.Context, repoID int64, mode perm.AccessMode) ([]*Team, error) {
|
||||
return GetTeamsWithAccessToRepo(ctx, org.ID, repoID, mode)
|
||||
|
163
models/organization/org_list.go
Normal file
163
models/organization/org_list.go
Normal file
@ -0,0 +1,163 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package organization
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/structs"
|
||||
|
||||
"xorm.io/builder"
|
||||
)
|
||||
|
||||
type OrgList []*Organization
|
||||
|
||||
func (orgs OrgList) LoadTeams(ctx context.Context) (map[int64]TeamList, error) {
|
||||
if len(orgs) == 0 {
|
||||
return map[int64]TeamList{}, nil
|
||||
}
|
||||
|
||||
orgIDs := make([]int64, len(orgs))
|
||||
for i, org := range orgs {
|
||||
orgIDs[i] = org.ID
|
||||
}
|
||||
|
||||
teams, err := GetTeamsByOrgIDs(ctx, orgIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
teamMap := make(map[int64]TeamList, len(orgs))
|
||||
for _, team := range teams {
|
||||
teamMap[team.OrgID] = append(teamMap[team.OrgID], team)
|
||||
}
|
||||
|
||||
return teamMap, nil
|
||||
}
|
||||
|
||||
// SearchOrganizationsOptions options to filter organizations
|
||||
type SearchOrganizationsOptions struct {
|
||||
db.ListOptions
|
||||
All bool
|
||||
}
|
||||
|
||||
// FindOrgOptions finds orgs options
|
||||
type FindOrgOptions struct {
|
||||
db.ListOptions
|
||||
UserID int64
|
||||
IncludePrivate bool
|
||||
}
|
||||
|
||||
func queryUserOrgIDs(userID int64, includePrivate bool) *builder.Builder {
|
||||
cond := builder.Eq{"uid": userID}
|
||||
if !includePrivate {
|
||||
cond["is_public"] = true
|
||||
}
|
||||
return builder.Select("org_id").From("org_user").Where(cond)
|
||||
}
|
||||
|
||||
func (opts FindOrgOptions) ToConds() builder.Cond {
|
||||
var cond builder.Cond = builder.Eq{"`user`.`type`": user_model.UserTypeOrganization}
|
||||
if opts.UserID > 0 {
|
||||
cond = cond.And(builder.In("`user`.`id`", queryUserOrgIDs(opts.UserID, opts.IncludePrivate)))
|
||||
}
|
||||
if !opts.IncludePrivate {
|
||||
cond = cond.And(builder.Eq{"`user`.visibility": structs.VisibleTypePublic})
|
||||
}
|
||||
return cond
|
||||
}
|
||||
|
||||
func (opts FindOrgOptions) ToOrders() string {
|
||||
return "`user`.lower_name ASC"
|
||||
}
|
||||
|
||||
// GetOrgsCanCreateRepoByUserID returns a list of organizations where given user ID
|
||||
// are allowed to create repos.
|
||||
func GetOrgsCanCreateRepoByUserID(ctx context.Context, userID int64) ([]*Organization, error) {
|
||||
orgs := make([]*Organization, 0, 10)
|
||||
|
||||
return orgs, db.GetEngine(ctx).Where(builder.In("id", builder.Select("`user`.id").From("`user`").
|
||||
Join("INNER", "`team_user`", "`team_user`.org_id = `user`.id").
|
||||
Join("INNER", "`team`", "`team`.id = `team_user`.team_id").
|
||||
Where(builder.Eq{"`team_user`.uid": userID}).
|
||||
And(builder.Eq{"`team`.authorize": perm.AccessModeOwner}.Or(builder.Eq{"`team`.can_create_org_repo": true})))).
|
||||
Asc("`user`.name").
|
||||
Find(&orgs)
|
||||
}
|
||||
|
||||
// MinimalOrg represents a simple organization with only the needed columns
|
||||
type MinimalOrg = Organization
|
||||
|
||||
// GetUserOrgsList returns all organizations the given user has access to
|
||||
func GetUserOrgsList(ctx context.Context, user *user_model.User) ([]*MinimalOrg, error) {
|
||||
schema, err := db.TableInfo(new(user_model.User))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputCols := []string{
|
||||
"id",
|
||||
"name",
|
||||
"full_name",
|
||||
"visibility",
|
||||
"avatar",
|
||||
"avatar_email",
|
||||
"use_custom_avatar",
|
||||
}
|
||||
|
||||
selectColumns := &strings.Builder{}
|
||||
for i, col := range outputCols {
|
||||
fmt.Fprintf(selectColumns, "`%s`.%s", schema.Name, col)
|
||||
if i < len(outputCols)-1 {
|
||||
selectColumns.WriteString(", ")
|
||||
}
|
||||
}
|
||||
columnsStr := selectColumns.String()
|
||||
|
||||
var orgs []*MinimalOrg
|
||||
if err := db.GetEngine(ctx).Select(columnsStr).
|
||||
Table("user").
|
||||
Where(builder.In("`user`.`id`", queryUserOrgIDs(user.ID, true))).
|
||||
Find(&orgs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
type orgCount struct {
|
||||
OrgID int64
|
||||
RepoCount int
|
||||
}
|
||||
var orgCounts []orgCount
|
||||
if err := db.GetEngine(ctx).
|
||||
Select("owner_id AS org_id, COUNT(DISTINCT(repository.id)) as repo_count").
|
||||
Table("repository").
|
||||
Join("INNER", "org_user", "owner_id = org_user.org_id").
|
||||
Where("org_user.uid = ?", user.ID).
|
||||
And(builder.Or(
|
||||
builder.Eq{"repository.is_private": false},
|
||||
builder.In("repository.id", builder.Select("repo_id").From("team_repo").
|
||||
InnerJoin("team_user", "team_user.team_id = team_repo.team_id").
|
||||
Where(builder.Eq{"team_user.uid": user.ID})),
|
||||
builder.In("repository.id", builder.Select("repo_id").From("collaboration").
|
||||
Where(builder.Eq{"user_id": user.ID})),
|
||||
)).
|
||||
GroupBy("owner_id").Find(&orgCounts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
orgCountMap := make(map[int64]int, len(orgCounts))
|
||||
for _, orgCount := range orgCounts {
|
||||
orgCountMap[orgCount.OrgID] = orgCount.RepoCount
|
||||
}
|
||||
|
||||
for _, org := range orgs {
|
||||
org.NumRepos = orgCountMap[org.ID]
|
||||
}
|
||||
|
||||
return orgs, nil
|
||||
}
|
73
models/organization/org_list_test.go
Normal file
73
models/organization/org_list_test.go
Normal file
@ -0,0 +1,73 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package organization_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCountOrganizations(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
expected, err := db.GetEngine(db.DefaultContext).Where("type=?", user_model.UserTypeOrganization).Count(&organization.Organization{})
|
||||
assert.NoError(t, err)
|
||||
cnt, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{IncludePrivate: true})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, cnt)
|
||||
}
|
||||
|
||||
func TestFindOrgs(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
orgs, err := db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
|
||||
UserID: 4,
|
||||
IncludePrivate: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, orgs, 1) {
|
||||
assert.EqualValues(t, 3, orgs[0].ID)
|
||||
}
|
||||
|
||||
orgs, err = db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
|
||||
UserID: 4,
|
||||
IncludePrivate: false,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, orgs, 0)
|
||||
|
||||
total, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
|
||||
UserID: 4,
|
||||
IncludePrivate: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, total)
|
||||
}
|
||||
|
||||
func TestGetUserOrgsList(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
orgs, err := organization.GetUserOrgsList(db.DefaultContext, &user_model.User{ID: 4})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, orgs, 1) {
|
||||
assert.EqualValues(t, 3, orgs[0].ID)
|
||||
// repo_id: 3 is in the team, 32 is public, 5 is private with no team
|
||||
assert.EqualValues(t, 2, orgs[0].NumRepos)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOrgListTeams(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
orgs, err := organization.GetUserOrgsList(db.DefaultContext, &user_model.User{ID: 4})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, orgs, 1)
|
||||
teamsMap, err := organization.OrgList(orgs).LoadTeams(db.DefaultContext)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, teamsMap, 1)
|
||||
assert.Len(t, teamsMap[3], 5)
|
||||
}
|
@ -4,6 +4,8 @@
|
||||
package organization_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
@ -103,7 +105,7 @@ func TestUser_GetTeams(t *testing.T) {
|
||||
func TestUser_GetMembers(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
|
||||
members, _, err := org.GetMembers(db.DefaultContext)
|
||||
members, _, err := org.GetMembers(db.DefaultContext, &user_model.User{IsAdmin: true})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, members, 3) {
|
||||
assert.Equal(t, int64(2), members[0].ID)
|
||||
@ -127,15 +129,6 @@ func TestGetOrgByName(t *testing.T) {
|
||||
assert.True(t, organization.IsErrOrgNotExist(err))
|
||||
}
|
||||
|
||||
func TestCountOrganizations(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
expected, err := db.GetEngine(db.DefaultContext).Where("type=?", user_model.UserTypeOrganization).Count(&organization.Organization{})
|
||||
assert.NoError(t, err)
|
||||
cnt, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{IncludePrivate: true})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, cnt)
|
||||
}
|
||||
|
||||
func TestIsOrganizationOwner(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
test := func(orgID, userID int64, expected bool) {
|
||||
@ -180,67 +173,114 @@ func TestIsPublicMembership(t *testing.T) {
|
||||
test(unittest.NonexistentID, unittest.NonexistentID, false)
|
||||
}
|
||||
|
||||
func TestFindOrgs(t *testing.T) {
|
||||
func TestRestrictedUserOrgMembers(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
orgs, err := db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
|
||||
UserID: 4,
|
||||
IncludePrivate: true,
|
||||
restrictedUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{
|
||||
ID: 29,
|
||||
IsRestricted: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, orgs, 1) {
|
||||
assert.EqualValues(t, 3, orgs[0].ID)
|
||||
if !assert.True(t, restrictedUser.IsRestricted) {
|
||||
return // ensure fixtures return restricted user
|
||||
}
|
||||
|
||||
orgs, err = db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
|
||||
UserID: 4,
|
||||
IncludePrivate: false,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, orgs, 0)
|
||||
testCases := []struct {
|
||||
name string
|
||||
opts *organization.FindOrgMembersOpts
|
||||
expectedUIDs []int64
|
||||
}{
|
||||
{
|
||||
name: "restricted user sees public members and teammates",
|
||||
opts: &organization.FindOrgMembersOpts{
|
||||
OrgID: 17, // org17 where user29 is in team9
|
||||
Doer: restrictedUser,
|
||||
IsDoerMember: true,
|
||||
},
|
||||
expectedUIDs: []int64{2, 15, 20, 29}, // Public members (2) + teammates in team9 (15, 20, 29)
|
||||
},
|
||||
{
|
||||
name: "restricted user sees only public members when not member",
|
||||
opts: &organization.FindOrgMembersOpts{
|
||||
OrgID: 3, // org3 where user29 is not a member
|
||||
Doer: restrictedUser,
|
||||
},
|
||||
expectedUIDs: []int64{2, 28}, // Only public members
|
||||
},
|
||||
{
|
||||
name: "non logged in only shows public members",
|
||||
opts: &organization.FindOrgMembersOpts{
|
||||
OrgID: 3,
|
||||
},
|
||||
expectedUIDs: []int64{2, 28}, // Only public members
|
||||
},
|
||||
{
|
||||
name: "non restricted user sees all members",
|
||||
opts: &organization.FindOrgMembersOpts{
|
||||
OrgID: 17,
|
||||
Doer: unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 15}),
|
||||
IsDoerMember: true,
|
||||
},
|
||||
expectedUIDs: []int64{2, 15, 18, 20, 29}, // All members
|
||||
},
|
||||
}
|
||||
|
||||
total, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
|
||||
UserID: 4,
|
||||
IncludePrivate: true,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, 1, total)
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
count, err := organization.CountOrgMembers(db.DefaultContext, tc.opts)
|
||||
assert.NoError(t, err)
|
||||
assert.EqualValues(t, len(tc.expectedUIDs), count)
|
||||
|
||||
members, err := organization.GetOrgUsersByOrgID(db.DefaultContext, tc.opts)
|
||||
assert.NoError(t, err)
|
||||
memberUIDs := make([]int64, 0, len(members))
|
||||
for _, member := range members {
|
||||
memberUIDs = append(memberUIDs, member.UID)
|
||||
}
|
||||
slices.Sort(memberUIDs)
|
||||
assert.EqualValues(t, tc.expectedUIDs, memberUIDs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOrgUsersByOrgID(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
orgUsers, err := organization.GetOrgUsersByOrgID(db.DefaultContext, &organization.FindOrgMembersOpts{
|
||||
ListOptions: db.ListOptions{},
|
||||
OrgID: 3,
|
||||
PublicOnly: false,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, orgUsers, 3) {
|
||||
assert.Equal(t, organization.OrgUser{
|
||||
ID: orgUsers[0].ID,
|
||||
OrgID: 3,
|
||||
UID: 2,
|
||||
IsPublic: true,
|
||||
}, *orgUsers[0])
|
||||
assert.Equal(t, organization.OrgUser{
|
||||
ID: orgUsers[1].ID,
|
||||
OrgID: 3,
|
||||
UID: 4,
|
||||
IsPublic: false,
|
||||
}, *orgUsers[1])
|
||||
assert.Equal(t, organization.OrgUser{
|
||||
ID: orgUsers[2].ID,
|
||||
OrgID: 3,
|
||||
UID: 28,
|
||||
IsPublic: true,
|
||||
}, *orgUsers[2])
|
||||
opts := &organization.FindOrgMembersOpts{
|
||||
Doer: &user_model.User{IsAdmin: true},
|
||||
OrgID: 3,
|
||||
}
|
||||
assert.False(t, opts.PublicOnly())
|
||||
orgUsers, err := organization.GetOrgUsersByOrgID(db.DefaultContext, opts)
|
||||
assert.NoError(t, err)
|
||||
sort.Slice(orgUsers, func(i, j int) bool {
|
||||
return orgUsers[i].ID < orgUsers[j].ID
|
||||
})
|
||||
assert.EqualValues(t, []*organization.OrgUser{{
|
||||
ID: 1,
|
||||
OrgID: 3,
|
||||
UID: 2,
|
||||
IsPublic: true,
|
||||
}, {
|
||||
ID: 2,
|
||||
OrgID: 3,
|
||||
UID: 4,
|
||||
IsPublic: false,
|
||||
}, {
|
||||
ID: 9,
|
||||
OrgID: 3,
|
||||
UID: 28,
|
||||
IsPublic: true,
|
||||
}}, orgUsers)
|
||||
|
||||
opts = &organization.FindOrgMembersOpts{OrgID: 3}
|
||||
assert.True(t, opts.PublicOnly())
|
||||
orgUsers, err = organization.GetOrgUsersByOrgID(db.DefaultContext, opts)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, orgUsers, 2)
|
||||
|
||||
orgUsers, err = organization.GetOrgUsersByOrgID(db.DefaultContext, &organization.FindOrgMembersOpts{
|
||||
ListOptions: db.ListOptions{},
|
||||
OrgID: unittest.NonexistentID,
|
||||
PublicOnly: false,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, orgUsers, 0)
|
||||
|
@ -94,7 +94,7 @@ func TestUserListIsPublicMember(t *testing.T) {
|
||||
func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bool) {
|
||||
org, err := organization.GetOrgByID(db.DefaultContext, orgID)
|
||||
assert.NoError(t, err)
|
||||
_, membersIsPublic, err := org.GetMembers(db.DefaultContext)
|
||||
_, membersIsPublic, err := org.GetMembers(db.DefaultContext, &user_model.User{IsAdmin: true})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, membersIsPublic)
|
||||
}
|
||||
@ -121,7 +121,7 @@ func TestUserListIsUserOrgOwner(t *testing.T) {
|
||||
func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bool) {
|
||||
org, err := organization.GetOrgByID(db.DefaultContext, orgID)
|
||||
assert.NoError(t, err)
|
||||
members, _, err := org.GetMembers(db.DefaultContext)
|
||||
members, _, err := org.GetMembers(db.DefaultContext, &user_model.User{IsAdmin: true})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, organization.IsUserOrgOwner(db.DefaultContext, members, orgID))
|
||||
}
|
||||
|
@ -272,3 +272,8 @@ func IncrTeamRepoNum(ctx context.Context, teamID int64) error {
|
||||
_, err := db.GetEngine(ctx).Incr("num_repos").ID(teamID).Update(new(Team))
|
||||
return err
|
||||
}
|
||||
|
||||
func UpdateTeam(ctx context.Context, t *Team, cols ...string) error {
|
||||
_, err := db.GetEngine(ctx).ID(t.ID).Cols(cols...).Update(t)
|
||||
return err
|
||||
}
|
||||
|
@ -126,3 +126,8 @@ func GetUserRepoTeams(ctx context.Context, orgID, userID, repoID int64) (teams T
|
||||
And("team_repo.repo_id=?", repoID).
|
||||
Find(&teams)
|
||||
}
|
||||
|
||||
func GetTeamsByOrgIDs(ctx context.Context, orgIDs []int64) (TeamList, error) {
|
||||
teams := make([]*Team, 0, 10)
|
||||
return teams, db.GetEngine(ctx).Where(builder.In("org_id", orgIDs)).Find(&teams)
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ import (
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
|
||||
"xorm.io/builder"
|
||||
)
|
||||
@ -83,3 +84,16 @@ func GetTeamsWithAccessToRepo(ctx context.Context, orgID, repoID int64, mode per
|
||||
OrderBy("name").
|
||||
Find(&teams)
|
||||
}
|
||||
|
||||
// GetTeamsWithAccessToRepoUnit returns all teams in an organization that have given access level to the repository special unit.
|
||||
func GetTeamsWithAccessToRepoUnit(ctx context.Context, orgID, repoID int64, mode perm.AccessMode, unitType unit.Type) ([]*Team, error) {
|
||||
teams := make([]*Team, 0, 5)
|
||||
return teams, db.GetEngine(ctx).Where("team_unit.access_mode >= ?", mode).
|
||||
Join("INNER", "team_repo", "team_repo.team_id = team.id").
|
||||
Join("INNER", "team_unit", "team_unit.team_id = team.id").
|
||||
And("team_repo.org_id = ?", orgID).
|
||||
And("team_repo.repo_id = ?", repoID).
|
||||
And("team_unit.type = ?", unitType).
|
||||
OrderBy("name").
|
||||
Find(&teams)
|
||||
}
|
||||
|
31
models/organization/team_repo_test.go
Normal file
31
models/organization/team_repo_test.go
Normal file
@ -0,0 +1,31 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package organization_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/models/organization"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
"code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGetTeamsWithAccessToRepoUnit(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
org41 := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 41})
|
||||
repo61 := unittest.AssertExistsAndLoadBean(t, &repo.Repository{ID: 61})
|
||||
|
||||
teams, err := organization.GetTeamsWithAccessToRepoUnit(db.DefaultContext, org41.ID, repo61.ID, perm.AccessModeRead, unit.TypePullRequests)
|
||||
assert.NoError(t, err)
|
||||
if assert.Len(t, teams, 2) {
|
||||
assert.EqualValues(t, 21, teams[0].ID)
|
||||
assert.EqualValues(t, 22, teams[1].ID)
|
||||
}
|
||||
}
|
@ -197,3 +197,8 @@ func TestUsersInTeamsCount(t *testing.T) {
|
||||
test([]int64{1, 2, 3, 4, 5}, []int64{2, 5}, 2) // userid 2,4
|
||||
test([]int64{1, 2, 3, 4, 5}, []int64{2, 3, 5}, 3) // userid 2,4,5
|
||||
}
|
||||
|
||||
func TestIsUsableTeamName(t *testing.T) {
|
||||
assert.NoError(t, organization.IsUsableTeamName("usable"))
|
||||
assert.True(t, db.IsErrNameReserved(organization.IsUsableTeamName("new")))
|
||||
}
|
||||
|
38
models/packages/arch/search.go
Normal file
38
models/packages/arch/search.go
Normal file
@ -0,0 +1,38 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package arch
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
packages_model "code.gitea.io/gitea/models/packages"
|
||||
arch_module "code.gitea.io/gitea/modules/packages/arch"
|
||||
)
|
||||
|
||||
// GetRepositories gets all available repositories
|
||||
func GetRepositories(ctx context.Context, ownerID int64) ([]string, error) {
|
||||
return packages_model.GetDistinctPropertyValues(
|
||||
ctx,
|
||||
packages_model.TypeArch,
|
||||
ownerID,
|
||||
packages_model.PropertyTypeFile,
|
||||
arch_module.PropertyRepository,
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
// GetArchitectures gets all available architectures for the given repository
|
||||
func GetArchitectures(ctx context.Context, ownerID int64, repository string) ([]string, error) {
|
||||
return packages_model.GetDistinctPropertyValues(
|
||||
ctx,
|
||||
packages_model.TypeArch,
|
||||
ownerID,
|
||||
packages_model.PropertyTypeFile,
|
||||
arch_module.PropertyArchitecture,
|
||||
&packages_model.DistinctPropertyDependency{
|
||||
Name: arch_module.PropertyRepository,
|
||||
Value: repository,
|
||||
},
|
||||
)
|
||||
}
|
@ -13,6 +13,7 @@ import (
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/json"
|
||||
"code.gitea.io/gitea/modules/packages/alpine"
|
||||
"code.gitea.io/gitea/modules/packages/arch"
|
||||
"code.gitea.io/gitea/modules/packages/cargo"
|
||||
"code.gitea.io/gitea/modules/packages/chef"
|
||||
"code.gitea.io/gitea/modules/packages/composer"
|
||||
@ -150,6 +151,8 @@ func GetPackageDescriptor(ctx context.Context, pv *PackageVersion) (*PackageDesc
|
||||
switch p.Type {
|
||||
case TypeAlpine:
|
||||
metadata = &alpine.VersionMetadata{}
|
||||
case TypeArch:
|
||||
metadata = &arch.VersionMetadata{}
|
||||
case TypeCargo:
|
||||
metadata = &cargo.Metadata{}
|
||||
case TypeChef:
|
||||
|
@ -31,6 +31,7 @@ type Type string
|
||||
// List of supported packages
|
||||
const (
|
||||
TypeAlpine Type = "alpine"
|
||||
TypeArch Type = "arch"
|
||||
TypeCargo Type = "cargo"
|
||||
TypeChef Type = "chef"
|
||||
TypeComposer Type = "composer"
|
||||
@ -55,6 +56,7 @@ const (
|
||||
|
||||
var TypeList = []Type{
|
||||
TypeAlpine,
|
||||
TypeArch,
|
||||
TypeCargo,
|
||||
TypeChef,
|
||||
TypeComposer,
|
||||
@ -82,6 +84,8 @@ func (pt Type) Name() string {
|
||||
switch pt {
|
||||
case TypeAlpine:
|
||||
return "Alpine"
|
||||
case TypeArch:
|
||||
return "Arch"
|
||||
case TypeCargo:
|
||||
return "Cargo"
|
||||
case TypeChef:
|
||||
@ -131,6 +135,8 @@ func (pt Type) SVGName() string {
|
||||
switch pt {
|
||||
case TypeAlpine:
|
||||
return "gitea-alpine"
|
||||
case TypeArch:
|
||||
return "gitea-arch"
|
||||
case TypeCargo:
|
||||
return "gitea-cargo"
|
||||
case TypeChef:
|
||||
|
@ -221,6 +221,11 @@ func SearchFiles(ctx context.Context, opts *PackageFileSearchOptions) ([]*Packag
|
||||
return pfs, count, err
|
||||
}
|
||||
|
||||
// HasFiles tests if there are files of packages matching the search options
|
||||
func HasFiles(ctx context.Context, opts *PackageFileSearchOptions) (bool, error) {
|
||||
return db.Exist[PackageFile](ctx, opts.toConds())
|
||||
}
|
||||
|
||||
// CalculateFileSize sums up all blob sizes matching the search options.
|
||||
// It does NOT respect the deduplication of blobs.
|
||||
func CalculateFileSize(ctx context.Context, opts *PackageFileSearchOptions) (int64, error) {
|
||||
|
@ -60,3 +60,6 @@ func ParseAccessMode(permission string, allowed ...AccessMode) AccessMode {
|
||||
}
|
||||
return util.Iif(slices.Contains(allowed, m), m, AccessModeNone)
|
||||
}
|
||||
|
||||
// ErrInvalidAccessMode is returned when an invalid access mode is used
|
||||
var ErrInvalidAccessMode = util.NewInvalidArgumentErrorf("Invalid access mode")
|
||||
|
@ -242,6 +242,7 @@ func GetSearchOrderByBySortType(sortType string) db.SearchOrderBy {
|
||||
}
|
||||
|
||||
// NewProject creates a new Project
|
||||
// The title will be cut off at 255 characters if it's longer than 255 characters.
|
||||
func NewProject(ctx context.Context, p *Project) error {
|
||||
if !IsTemplateTypeValid(p.TemplateType) {
|
||||
p.TemplateType = TemplateTypeNone
|
||||
@ -255,6 +256,8 @@ func NewProject(ctx context.Context, p *Project) error {
|
||||
return util.NewInvalidArgumentErrorf("project type is not valid")
|
||||
}
|
||||
|
||||
p.Title, _ = util.SplitStringAtByteN(p.Title, 255)
|
||||
|
||||
return db.WithTx(ctx, func(ctx context.Context) error {
|
||||
if err := db.Insert(ctx, p); err != nil {
|
||||
return err
|
||||
@ -308,6 +311,7 @@ func UpdateProject(ctx context.Context, p *Project) error {
|
||||
p.CardType = CardTypeTextOnly
|
||||
}
|
||||
|
||||
p.Title, _ = util.SplitStringAtByteN(p.Title, 255)
|
||||
_, err := db.GetEngine(ctx).ID(p.ID).Cols(
|
||||
"title",
|
||||
"description",
|
||||
|
53
models/renderhelper/commit_checker.go
Normal file
53
models/renderhelper/commit_checker.go
Normal file
@ -0,0 +1,53 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
"code.gitea.io/gitea/modules/gitrepo"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
)
|
||||
|
||||
type commitChecker struct {
|
||||
ctx context.Context
|
||||
commitCache map[string]bool
|
||||
gitRepoFacade gitrepo.Repository
|
||||
|
||||
gitRepo *git.Repository
|
||||
gitRepoCloser io.Closer
|
||||
}
|
||||
|
||||
func newCommitChecker(ctx context.Context, gitRepo gitrepo.Repository) *commitChecker {
|
||||
return &commitChecker{ctx: ctx, commitCache: make(map[string]bool), gitRepoFacade: gitRepo}
|
||||
}
|
||||
|
||||
func (c *commitChecker) Close() error {
|
||||
if c != nil && c.gitRepoCloser != nil {
|
||||
return c.gitRepoCloser.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *commitChecker) IsCommitIDExisting(commitID string) bool {
|
||||
exist, inCache := c.commitCache[commitID]
|
||||
if inCache {
|
||||
return exist
|
||||
}
|
||||
|
||||
if c.gitRepo == nil {
|
||||
r, closer, err := gitrepo.RepositoryFromContextOrOpen(c.ctx, c.gitRepoFacade)
|
||||
if err != nil {
|
||||
log.Error("unable to open repository: %s Error: %v", gitrepo.RepoGitURL(c.gitRepoFacade), err)
|
||||
return false
|
||||
}
|
||||
c.gitRepo, c.gitRepoCloser = r, closer
|
||||
}
|
||||
|
||||
exist = c.gitRepo.IsReferenceExist(commitID) // Don't use IsObjectExist since it doesn't support short hashs with gogit edition.
|
||||
c.commitCache[commitID] = exist
|
||||
return exist
|
||||
}
|
27
models/renderhelper/main_test.go
Normal file
27
models/renderhelper/main_test.go
Normal file
@ -0,0 +1,27 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
unittest.MainTest(m, &unittest.TestOptions{
|
||||
FixtureFiles: []string{"repository.yml", "user.yml"},
|
||||
SetUp: func() error {
|
||||
markup.RenderBehaviorForTesting.DisableAdditionalAttributes = true
|
||||
markup.Init(&markup.RenderHelperFuncs{
|
||||
IsUsernameMentionable: func(ctx context.Context, username string) bool {
|
||||
return username == "user2"
|
||||
},
|
||||
})
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
73
models/renderhelper/repo_comment.go
Normal file
73
models/renderhelper/repo_comment.go
Normal file
@ -0,0 +1,73 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
)
|
||||
|
||||
type RepoComment struct {
|
||||
ctx *markup.RenderContext
|
||||
opts RepoCommentOptions
|
||||
|
||||
commitChecker *commitChecker
|
||||
repoLink string
|
||||
}
|
||||
|
||||
func (r *RepoComment) CleanUp() {
|
||||
_ = r.commitChecker.Close()
|
||||
}
|
||||
|
||||
func (r *RepoComment) IsCommitIDExisting(commitID string) bool {
|
||||
return r.commitChecker.IsCommitIDExisting(commitID)
|
||||
}
|
||||
|
||||
func (r *RepoComment) ResolveLink(link string, likeType markup.LinkType) (finalLink string) {
|
||||
switch likeType {
|
||||
case markup.LinkTypeApp:
|
||||
finalLink = r.ctx.ResolveLinkApp(link)
|
||||
default:
|
||||
finalLink = r.ctx.ResolveLinkRelative(r.repoLink, r.opts.CurrentRefPath, link)
|
||||
}
|
||||
return finalLink
|
||||
}
|
||||
|
||||
var _ markup.RenderHelper = (*RepoComment)(nil)
|
||||
|
||||
type RepoCommentOptions struct {
|
||||
DeprecatedRepoName string // it is only a patch for the non-standard "markup" api
|
||||
DeprecatedOwnerName string // it is only a patch for the non-standard "markup" api
|
||||
CurrentRefPath string // eg: "branch/main" or "commit/11223344"
|
||||
}
|
||||
|
||||
func NewRenderContextRepoComment(ctx context.Context, repo *repo_model.Repository, opts ...RepoCommentOptions) *markup.RenderContext {
|
||||
helper := &RepoComment{
|
||||
repoLink: repo.Link(),
|
||||
opts: util.OptionalArg(opts),
|
||||
}
|
||||
rctx := markup.NewRenderContext(ctx)
|
||||
helper.ctx = rctx
|
||||
if repo != nil {
|
||||
helper.repoLink = repo.Link()
|
||||
helper.commitChecker = newCommitChecker(ctx, repo)
|
||||
rctx = rctx.WithMetas(repo.ComposeMetas(ctx))
|
||||
} else {
|
||||
// this is almost dead code, only to pass the incorrect tests
|
||||
helper.repoLink = fmt.Sprintf("%s/%s", helper.opts.DeprecatedOwnerName, helper.opts.DeprecatedRepoName)
|
||||
rctx = rctx.WithMetas(map[string]string{
|
||||
"user": helper.opts.DeprecatedOwnerName,
|
||||
"repo": helper.opts.DeprecatedRepoName,
|
||||
|
||||
"markdownLineBreakStyle": "comment",
|
||||
"markupAllowShortIssuePattern": "true",
|
||||
})
|
||||
}
|
||||
rctx = rctx.WithHelper(helper)
|
||||
return rctx
|
||||
}
|
76
models/renderhelper/repo_comment_test.go
Normal file
76
models/renderhelper/repo_comment_test.go
Normal file
@ -0,0 +1,76 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
"code.gitea.io/gitea/modules/markup/markdown"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestRepoComment(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
t.Run("AutoLink", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoComment(context.Background(), repo1).WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
65f1bf27bc3bf70f64657658635e66094edbcb4d
|
||||
#1
|
||||
@user2
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t,
|
||||
`<p><a href="/user2/repo1/commit/65f1bf27bc3bf70f64657658635e66094edbcb4d" rel="nofollow"><code>65f1bf27bc</code></a><br/>
|
||||
<a href="/user2/repo1/issues/1" class="ref-issue" rel="nofollow">#1</a><br/>
|
||||
<a href="/user2" rel="nofollow">@user2</a></p>
|
||||
`, rendered)
|
||||
})
|
||||
|
||||
t.Run("AbsoluteAndRelative", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoComment(context.Background(), repo1).WithMarkupType(markdown.MarkupName)
|
||||
|
||||
// It is Gitea's old behavior, the relative path is resolved to the repo path
|
||||
// It is different from GitHub, GitHub resolves relative links to current page's path
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
[/test](/test)
|
||||
[./test](./test)
|
||||
![/image](/image)
|
||||
![./image](./image)
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t,
|
||||
`<p><a href="/user2/repo1/test" rel="nofollow">/test</a><br/>
|
||||
<a href="/user2/repo1/test" rel="nofollow">./test</a><br/>
|
||||
<a href="/user2/repo1/image" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/image" alt="/image"/></a><br/>
|
||||
<a href="/user2/repo1/image" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/image" alt="./image"/></a></p>
|
||||
`, rendered)
|
||||
})
|
||||
|
||||
t.Run("WithCurrentRefPath", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoComment(context.Background(), repo1, RepoCommentOptions{CurrentRefPath: "/commit/1234"}).
|
||||
WithMarkupType(markdown.MarkupName)
|
||||
|
||||
// the ref path is only used to render commit message: a commit message is rendered at the commit page with its commit ID path
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
[/test](/test)
|
||||
[./test](./test)
|
||||
![/image](/image)
|
||||
![./image](./image)
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<p><a href="/user2/repo1/test" rel="nofollow">/test</a><br/>
|
||||
<a href="/user2/repo1/commit/1234/test" rel="nofollow">./test</a><br/>
|
||||
<a href="/user2/repo1/image" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/image" alt="/image"/></a><br/>
|
||||
<a href="/user2/repo1/commit/1234/image" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/commit/1234/image" alt="./image"/></a></p>
|
||||
`, rendered)
|
||||
})
|
||||
}
|
77
models/renderhelper/repo_file.go
Normal file
77
models/renderhelper/repo_file.go
Normal file
@ -0,0 +1,77 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path"
|
||||
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
)
|
||||
|
||||
type RepoFile struct {
|
||||
ctx *markup.RenderContext
|
||||
opts RepoFileOptions
|
||||
|
||||
commitChecker *commitChecker
|
||||
repoLink string
|
||||
}
|
||||
|
||||
func (r *RepoFile) CleanUp() {
|
||||
_ = r.commitChecker.Close()
|
||||
}
|
||||
|
||||
func (r *RepoFile) IsCommitIDExisting(commitID string) bool {
|
||||
return r.commitChecker.IsCommitIDExisting(commitID)
|
||||
}
|
||||
|
||||
func (r *RepoFile) ResolveLink(link string, likeType markup.LinkType) string {
|
||||
finalLink := link
|
||||
switch likeType {
|
||||
case markup.LinkTypeApp:
|
||||
finalLink = r.ctx.ResolveLinkApp(link)
|
||||
case markup.LinkTypeDefault:
|
||||
finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "src", r.opts.CurrentRefPath), r.opts.CurrentTreePath, link)
|
||||
case markup.LinkTypeRaw:
|
||||
finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "raw", r.opts.CurrentRefPath), r.opts.CurrentTreePath, link)
|
||||
case markup.LinkTypeMedia:
|
||||
finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "media", r.opts.CurrentRefPath), r.opts.CurrentTreePath, link)
|
||||
}
|
||||
return finalLink
|
||||
}
|
||||
|
||||
var _ markup.RenderHelper = (*RepoFile)(nil)
|
||||
|
||||
type RepoFileOptions struct {
|
||||
DeprecatedRepoName string // it is only a patch for the non-standard "markup" api
|
||||
DeprecatedOwnerName string // it is only a patch for the non-standard "markup" api
|
||||
|
||||
CurrentRefPath string // eg: "branch/main"
|
||||
CurrentTreePath string // eg: "path/to/file" in the repo
|
||||
}
|
||||
|
||||
func NewRenderContextRepoFile(ctx context.Context, repo *repo_model.Repository, opts ...RepoFileOptions) *markup.RenderContext {
|
||||
helper := &RepoFile{opts: util.OptionalArg(opts)}
|
||||
rctx := markup.NewRenderContext(ctx)
|
||||
helper.ctx = rctx
|
||||
if repo != nil {
|
||||
helper.repoLink = repo.Link()
|
||||
helper.commitChecker = newCommitChecker(ctx, repo)
|
||||
rctx = rctx.WithMetas(repo.ComposeDocumentMetas(ctx))
|
||||
} else {
|
||||
// this is almost dead code, only to pass the incorrect tests
|
||||
helper.repoLink = fmt.Sprintf("%s/%s", helper.opts.DeprecatedOwnerName, helper.opts.DeprecatedRepoName)
|
||||
rctx = rctx.WithMetas(map[string]string{
|
||||
"user": helper.opts.DeprecatedOwnerName,
|
||||
"repo": helper.opts.DeprecatedRepoName,
|
||||
|
||||
"markdownLineBreakStyle": "document",
|
||||
})
|
||||
}
|
||||
rctx = rctx.WithHelper(helper)
|
||||
return rctx
|
||||
}
|
122
models/renderhelper/repo_file_test.go
Normal file
122
models/renderhelper/repo_file_test.go
Normal file
@ -0,0 +1,122 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
"code.gitea.io/gitea/modules/markup/markdown"
|
||||
|
||||
_ "code.gitea.io/gitea/modules/markup/orgmode"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestRepoFile(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
t.Run("AutoLink", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(context.Background(), repo1).WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
65f1bf27bc3bf70f64657658635e66094edbcb4d
|
||||
#1
|
||||
@user2
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t,
|
||||
`<p><a href="/user2/repo1/commit/65f1bf27bc3bf70f64657658635e66094edbcb4d" rel="nofollow"><code>65f1bf27bc</code></a>
|
||||
#1
|
||||
<a href="/user2" rel="nofollow">@user2</a></p>
|
||||
`, rendered)
|
||||
})
|
||||
|
||||
t.Run("AbsoluteAndRelative", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(context.Background(), repo1, RepoFileOptions{CurrentRefPath: "branch/main"}).
|
||||
WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
[/test](/test)
|
||||
[./test](./test)
|
||||
![/image](/image)
|
||||
![./image](./image)
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t,
|
||||
`<p><a href="/user2/repo1/src/branch/main/test" rel="nofollow">/test</a>
|
||||
<a href="/user2/repo1/src/branch/main/test" rel="nofollow">./test</a>
|
||||
<a href="/user2/repo1/media/branch/main/image" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/media/branch/main/image" alt="/image"/></a>
|
||||
<a href="/user2/repo1/media/branch/main/image" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/media/branch/main/image" alt="./image"/></a></p>
|
||||
`, rendered)
|
||||
})
|
||||
|
||||
t.Run("WithCurrentRefPath", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(context.Background(), repo1, RepoFileOptions{CurrentRefPath: "/commit/1234"}).
|
||||
WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
[/test](/test)
|
||||
![/image](/image)
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<p><a href="/user2/repo1/src/commit/1234/test" rel="nofollow">/test</a>
|
||||
<a href="/user2/repo1/media/commit/1234/image" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/media/commit/1234/image" alt="/image"/></a></p>
|
||||
`, rendered)
|
||||
})
|
||||
|
||||
t.Run("WithCurrentRefPathByTag", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(context.Background(), repo1, RepoFileOptions{
|
||||
CurrentRefPath: "/commit/1234",
|
||||
CurrentTreePath: "my-dir",
|
||||
}).
|
||||
WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
<img src="LINK">
|
||||
<video src="LINK">
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<a href="/user2/repo1/media/commit/1234/my-dir/LINK" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/media/commit/1234/my-dir/LINK"/></a>
|
||||
<video src="/user2/repo1/media/commit/1234/my-dir/LINK">
|
||||
</video>`, rendered)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRepoFileOrgMode(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
t.Run("Links", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(context.Background(), repo1, RepoFileOptions{
|
||||
CurrentRefPath: "/commit/1234",
|
||||
CurrentTreePath: "my-dir",
|
||||
}).WithRelativePath("my-dir/a.org")
|
||||
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
[[https://google.com/]]
|
||||
[[ImageLink.svg][The Image Desc]]
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<p>
|
||||
<a href="https://google.com/" rel="nofollow">https://google.com/</a>
|
||||
<a href="/user2/repo1/media/commit/1234/my-dir/ImageLink.svg" rel="nofollow">The Image Desc</a></p>
|
||||
`, rendered)
|
||||
})
|
||||
|
||||
t.Run("CodeHighlight", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoFile(context.Background(), repo1, RepoFileOptions{}).WithRelativePath("my-dir/a.org")
|
||||
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
#+begin_src c
|
||||
int a = 1;
|
||||
#+end_src
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<div>
|
||||
<pre><code class="chroma language-c"><span class="kt">int</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span></code></pre>
|
||||
</div>
|
||||
`, rendered)
|
||||
})
|
||||
}
|
80
models/renderhelper/repo_wiki.go
Normal file
80
models/renderhelper/repo_wiki.go
Normal file
@ -0,0 +1,80 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path"
|
||||
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
"code.gitea.io/gitea/modules/markup/markdown"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
)
|
||||
|
||||
type RepoWiki struct {
|
||||
ctx *markup.RenderContext
|
||||
opts RepoWikiOptions
|
||||
|
||||
commitChecker *commitChecker
|
||||
repoLink string
|
||||
}
|
||||
|
||||
func (r *RepoWiki) CleanUp() {
|
||||
_ = r.commitChecker.Close()
|
||||
}
|
||||
|
||||
func (r *RepoWiki) IsCommitIDExisting(commitID string) bool {
|
||||
return r.commitChecker.IsCommitIDExisting(commitID)
|
||||
}
|
||||
|
||||
func (r *RepoWiki) ResolveLink(link string, likeType markup.LinkType) string {
|
||||
finalLink := link
|
||||
switch likeType {
|
||||
case markup.LinkTypeApp:
|
||||
finalLink = r.ctx.ResolveLinkApp(link)
|
||||
case markup.LinkTypeDefault:
|
||||
finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "wiki", r.opts.currentRefPath), r.opts.currentTreePath, link)
|
||||
case markup.LinkTypeMedia:
|
||||
finalLink = r.ctx.ResolveLinkRelative(path.Join(r.repoLink, "wiki/raw", r.opts.currentRefPath), r.opts.currentTreePath, link)
|
||||
case markup.LinkTypeRaw: // wiki doesn't use it
|
||||
}
|
||||
|
||||
return finalLink
|
||||
}
|
||||
|
||||
var _ markup.RenderHelper = (*RepoWiki)(nil)
|
||||
|
||||
type RepoWikiOptions struct {
|
||||
DeprecatedRepoName string // it is only a patch for the non-standard "markup" api
|
||||
DeprecatedOwnerName string // it is only a patch for the non-standard "markup" api
|
||||
|
||||
// these options are not used at the moment because Wiki doesn't support sub-path, nor branch
|
||||
currentRefPath string // eg: "branch/main"
|
||||
currentTreePath string // eg: "path/to/file" in the repo
|
||||
}
|
||||
|
||||
func NewRenderContextRepoWiki(ctx context.Context, repo *repo_model.Repository, opts ...RepoWikiOptions) *markup.RenderContext {
|
||||
helper := &RepoWiki{opts: util.OptionalArg(opts)}
|
||||
rctx := markup.NewRenderContext(ctx).WithMarkupType(markdown.MarkupName)
|
||||
if repo != nil {
|
||||
helper.repoLink = repo.Link()
|
||||
helper.commitChecker = newCommitChecker(ctx, repo)
|
||||
rctx = rctx.WithMetas(repo.ComposeWikiMetas(ctx))
|
||||
} else {
|
||||
// this is almost dead code, only to pass the incorrect tests
|
||||
helper.repoLink = fmt.Sprintf("%s/%s", helper.opts.DeprecatedOwnerName, helper.opts.DeprecatedRepoName)
|
||||
rctx = rctx.WithMetas(map[string]string{
|
||||
"user": helper.opts.DeprecatedOwnerName,
|
||||
"repo": helper.opts.DeprecatedRepoName,
|
||||
|
||||
"markdownLineBreakStyle": "document",
|
||||
"markupAllowShortIssuePattern": "true",
|
||||
})
|
||||
}
|
||||
rctx = rctx.WithHelper(helper)
|
||||
helper.ctx = rctx
|
||||
return rctx
|
||||
}
|
65
models/renderhelper/repo_wiki_test.go
Normal file
65
models/renderhelper/repo_wiki_test.go
Normal file
@ -0,0 +1,65 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
"code.gitea.io/gitea/modules/markup/markdown"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestRepoWiki(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
t.Run("AutoLink", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoWiki(context.Background(), repo1).WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
65f1bf27bc3bf70f64657658635e66094edbcb4d
|
||||
#1
|
||||
@user2
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t,
|
||||
`<p><a href="/user2/repo1/commit/65f1bf27bc3bf70f64657658635e66094edbcb4d" rel="nofollow"><code>65f1bf27bc</code></a>
|
||||
<a href="/user2/repo1/issues/1" class="ref-issue" rel="nofollow">#1</a>
|
||||
<a href="/user2" rel="nofollow">@user2</a></p>
|
||||
`, rendered)
|
||||
})
|
||||
|
||||
t.Run("AbsoluteAndRelative", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoWiki(context.Background(), repo1).WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
[/test](/test)
|
||||
[./test](./test)
|
||||
![/image](/image)
|
||||
![./image](./image)
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t,
|
||||
`<p><a href="/user2/repo1/wiki/test" rel="nofollow">/test</a>
|
||||
<a href="/user2/repo1/wiki/test" rel="nofollow">./test</a>
|
||||
<a href="/user2/repo1/wiki/raw/image" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/wiki/raw/image" alt="/image"/></a>
|
||||
<a href="/user2/repo1/wiki/raw/image" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/wiki/raw/image" alt="./image"/></a></p>
|
||||
`, rendered)
|
||||
})
|
||||
|
||||
t.Run("PathInTag", func(t *testing.T) {
|
||||
rctx := NewRenderContextRepoWiki(context.Background(), repo1).WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
<img src="LINK">
|
||||
<video src="LINK">
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, `<a href="/user2/repo1/wiki/raw/LINK" target="_blank" rel="nofollow noopener"><img src="/user2/repo1/wiki/raw/LINK"/></a>
|
||||
<video src="/user2/repo1/wiki/raw/LINK">
|
||||
</video>`, rendered)
|
||||
})
|
||||
}
|
29
models/renderhelper/simple_document.go
Normal file
29
models/renderhelper/simple_document.go
Normal file
@ -0,0 +1,29 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
)
|
||||
|
||||
type SimpleDocument struct {
|
||||
*markup.SimpleRenderHelper
|
||||
ctx *markup.RenderContext
|
||||
baseLink string
|
||||
}
|
||||
|
||||
func (r *SimpleDocument) ResolveLink(link string, likeType markup.LinkType) string {
|
||||
return r.ctx.ResolveLinkRelative(r.baseLink, "", link)
|
||||
}
|
||||
|
||||
var _ markup.RenderHelper = (*SimpleDocument)(nil)
|
||||
|
||||
func NewRenderContextSimpleDocument(ctx context.Context, baseLink string) *markup.RenderContext {
|
||||
helper := &SimpleDocument{baseLink: baseLink}
|
||||
rctx := markup.NewRenderContext(ctx).WithHelper(helper).WithMetas(markup.ComposeSimpleDocumentMetas())
|
||||
helper.ctx = rctx
|
||||
return rctx
|
||||
}
|
40
models/renderhelper/simple_document_test.go
Normal file
40
models/renderhelper/simple_document_test.go
Normal file
@ -0,0 +1,40 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package renderhelper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
"code.gitea.io/gitea/modules/markup/markdown"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSimpleDocument(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
rctx := NewRenderContextSimpleDocument(context.Background(), "/base").WithMarkupType(markdown.MarkupName)
|
||||
rendered, err := markup.RenderString(rctx, `
|
||||
65f1bf27bc3bf70f64657658635e66094edbcb4d
|
||||
#1
|
||||
@user2
|
||||
|
||||
[/test](/test)
|
||||
[./test](./test)
|
||||
![/image](/image)
|
||||
![./image](./image)
|
||||
`)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t,
|
||||
`<p>65f1bf27bc3bf70f64657658635e66094edbcb4d
|
||||
#1
|
||||
<a href="/base/user2" rel="nofollow">@user2</a></p>
|
||||
<p><a href="/base/test" rel="nofollow">/test</a>
|
||||
<a href="/base/test" rel="nofollow">./test</a>
|
||||
<a href="/base/image" target="_blank" rel="nofollow noopener"><img src="/base/image" alt="/image"/></a>
|
||||
<a href="/base/image" target="_blank" rel="nofollow noopener"><img src="/base/image" alt="./image"/></a></p>
|
||||
`, rendered)
|
||||
}
|
@ -54,21 +54,6 @@ func GetUserFork(ctx context.Context, repoID, userID int64) (*Repository, error)
|
||||
return &forkedRepo, nil
|
||||
}
|
||||
|
||||
// GetForks returns all the forks of the repository
|
||||
func GetForks(ctx context.Context, repo *Repository, listOptions db.ListOptions) ([]*Repository, error) {
|
||||
sess := db.GetEngine(ctx)
|
||||
|
||||
var forks []*Repository
|
||||
if listOptions.Page == 0 {
|
||||
forks = make([]*Repository, 0, repo.NumForks)
|
||||
} else {
|
||||
forks = make([]*Repository, 0, listOptions.PageSize)
|
||||
sess = db.SetSessionPagination(sess, &listOptions)
|
||||
}
|
||||
|
||||
return forks, sess.Find(&forks, &Repository{ForkID: repo.ID})
|
||||
}
|
||||
|
||||
// IncrementRepoForkNum increment repository fork number
|
||||
func IncrementRepoForkNum(ctx context.Context, repoID int64) error {
|
||||
_, err := db.GetEngine(ctx).Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", repoID)
|
||||
|
@ -9,15 +9,13 @@ import (
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/optional"
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
|
||||
"xorm.io/builder"
|
||||
)
|
||||
|
||||
// ErrPushMirrorNotExist mirror does not exist error
|
||||
var ErrPushMirrorNotExist = util.NewNotExistErrorf("PushMirror does not exist")
|
||||
|
||||
// PushMirror represents mirror information of a repository.
|
||||
type PushMirror struct {
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
@ -96,26 +94,46 @@ func DeletePushMirrors(ctx context.Context, opts PushMirrorOptions) error {
|
||||
return util.NewInvalidArgumentErrorf("repoID required and must be set")
|
||||
}
|
||||
|
||||
type findPushMirrorOptions struct {
|
||||
db.ListOptions
|
||||
RepoID int64
|
||||
SyncOnCommit optional.Option[bool]
|
||||
}
|
||||
|
||||
func (opts findPushMirrorOptions) ToConds() builder.Cond {
|
||||
cond := builder.NewCond()
|
||||
if opts.RepoID > 0 {
|
||||
cond = cond.And(builder.Eq{"repo_id": opts.RepoID})
|
||||
}
|
||||
if opts.SyncOnCommit.Has() {
|
||||
cond = cond.And(builder.Eq{"sync_on_commit": opts.SyncOnCommit.Value()})
|
||||
}
|
||||
return cond
|
||||
}
|
||||
|
||||
// GetPushMirrorsByRepoID returns push-mirror information of a repository.
|
||||
func GetPushMirrorsByRepoID(ctx context.Context, repoID int64, listOptions db.ListOptions) ([]*PushMirror, int64, error) {
|
||||
sess := db.GetEngine(ctx).Where("repo_id = ?", repoID)
|
||||
if listOptions.Page != 0 {
|
||||
sess = db.SetSessionPagination(sess, &listOptions)
|
||||
mirrors := make([]*PushMirror, 0, listOptions.PageSize)
|
||||
count, err := sess.FindAndCount(&mirrors)
|
||||
return mirrors, count, err
|
||||
return db.FindAndCount[PushMirror](ctx, findPushMirrorOptions{
|
||||
ListOptions: listOptions,
|
||||
RepoID: repoID,
|
||||
})
|
||||
}
|
||||
|
||||
func GetPushMirrorByIDAndRepoID(ctx context.Context, id, repoID int64) (*PushMirror, bool, error) {
|
||||
var pushMirror PushMirror
|
||||
has, err := db.GetEngine(ctx).Where("id = ?", id).And("repo_id = ?", repoID).Get(&pushMirror)
|
||||
if !has || err != nil {
|
||||
return nil, has, err
|
||||
}
|
||||
mirrors := make([]*PushMirror, 0, 10)
|
||||
count, err := sess.FindAndCount(&mirrors)
|
||||
return mirrors, count, err
|
||||
return &pushMirror, true, nil
|
||||
}
|
||||
|
||||
// GetPushMirrorsSyncedOnCommit returns push-mirrors for this repo that should be updated by new commits
|
||||
func GetPushMirrorsSyncedOnCommit(ctx context.Context, repoID int64) ([]*PushMirror, error) {
|
||||
mirrors := make([]*PushMirror, 0, 10)
|
||||
return mirrors, db.GetEngine(ctx).
|
||||
Where("repo_id = ? AND sync_on_commit = ?", repoID, true).
|
||||
Find(&mirrors)
|
||||
return db.Find[PushMirror](ctx, findPushMirrorOptions{
|
||||
RepoID: repoID,
|
||||
SyncOnCommit: optional.Some(true),
|
||||
})
|
||||
}
|
||||
|
||||
// PushMirrorsIterate iterates all push-mirror repositories.
|
||||
|
@ -156,6 +156,7 @@ func IsReleaseExist(ctx context.Context, repoID int64, tagName string) (bool, er
|
||||
|
||||
// UpdateRelease updates all columns of a release
|
||||
func UpdateRelease(ctx context.Context, rel *Release) error {
|
||||
rel.Title, _ = util.SplitStringAtByteN(rel.Title, 255)
|
||||
_, err := db.GetEngine(ctx).ID(rel.ID).AllCols().Update(rel)
|
||||
return err
|
||||
}
|
||||
|
@ -7,6 +7,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"maps"
|
||||
"net"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
@ -165,10 +166,10 @@ type Repository struct {
|
||||
|
||||
Status RepositoryStatus `xorm:"NOT NULL DEFAULT 0"`
|
||||
|
||||
RenderingMetas map[string]string `xorm:"-"`
|
||||
DocumentRenderingMetas map[string]string `xorm:"-"`
|
||||
Units []*RepoUnit `xorm:"-"`
|
||||
PrimaryLanguage *LanguageStat `xorm:"-"`
|
||||
commonRenderingMetas map[string]string `xorm:"-"`
|
||||
|
||||
Units []*RepoUnit `xorm:"-"`
|
||||
PrimaryLanguage *LanguageStat `xorm:"-"`
|
||||
|
||||
IsFork bool `xorm:"INDEX NOT NULL DEFAULT false"`
|
||||
ForkID int64 `xorm:"INDEX"`
|
||||
@ -473,13 +474,11 @@ func (repo *Repository) MustOwner(ctx context.Context) *user_model.User {
|
||||
return repo.Owner
|
||||
}
|
||||
|
||||
// ComposeMetas composes a map of metas for properly rendering issue links and external issue trackers.
|
||||
func (repo *Repository) ComposeMetas(ctx context.Context) map[string]string {
|
||||
if len(repo.RenderingMetas) == 0 {
|
||||
func (repo *Repository) composeCommonMetas(ctx context.Context) map[string]string {
|
||||
if len(repo.commonRenderingMetas) == 0 {
|
||||
metas := map[string]string{
|
||||
"user": repo.OwnerName,
|
||||
"repo": repo.Name,
|
||||
"mode": "comment",
|
||||
}
|
||||
|
||||
unit, err := repo.GetUnit(ctx, unit.TypeExternalTracker)
|
||||
@ -509,22 +508,34 @@ func (repo *Repository) ComposeMetas(ctx context.Context) map[string]string {
|
||||
metas["org"] = strings.ToLower(repo.OwnerName)
|
||||
}
|
||||
|
||||
repo.RenderingMetas = metas
|
||||
repo.commonRenderingMetas = metas
|
||||
}
|
||||
return repo.RenderingMetas
|
||||
return repo.commonRenderingMetas
|
||||
}
|
||||
|
||||
// ComposeDocumentMetas composes a map of metas for properly rendering documents
|
||||
// ComposeMetas composes a map of metas for properly rendering comments or comment-like contents (commit message)
|
||||
func (repo *Repository) ComposeMetas(ctx context.Context) map[string]string {
|
||||
metas := maps.Clone(repo.composeCommonMetas(ctx))
|
||||
metas["markdownLineBreakStyle"] = "comment"
|
||||
metas["markupAllowShortIssuePattern"] = "true"
|
||||
return metas
|
||||
}
|
||||
|
||||
// ComposeWikiMetas composes a map of metas for properly rendering wikis
|
||||
func (repo *Repository) ComposeWikiMetas(ctx context.Context) map[string]string {
|
||||
// does wiki need the "teams" and "org" from common metas?
|
||||
metas := maps.Clone(repo.composeCommonMetas(ctx))
|
||||
metas["markdownLineBreakStyle"] = "document"
|
||||
metas["markupAllowShortIssuePattern"] = "true"
|
||||
return metas
|
||||
}
|
||||
|
||||
// ComposeDocumentMetas composes a map of metas for properly rendering documents (repo files)
|
||||
func (repo *Repository) ComposeDocumentMetas(ctx context.Context) map[string]string {
|
||||
if len(repo.DocumentRenderingMetas) == 0 {
|
||||
metas := map[string]string{}
|
||||
for k, v := range repo.ComposeMetas(ctx) {
|
||||
metas[k] = v
|
||||
}
|
||||
metas["mode"] = "document"
|
||||
repo.DocumentRenderingMetas = metas
|
||||
}
|
||||
return repo.DocumentRenderingMetas
|
||||
// does document(file) need the "teams" and "org" from common metas?
|
||||
metas := maps.Clone(repo.composeCommonMetas(ctx))
|
||||
metas["markdownLineBreakStyle"] = "document"
|
||||
return metas
|
||||
}
|
||||
|
||||
// GetBaseRepo populates repo.BaseRepo for a fork repository and
|
||||
@ -606,10 +617,7 @@ func (repo *Repository) CanEnableEditor() bool {
|
||||
|
||||
// DescriptionHTML does special handles to description and return HTML string.
|
||||
func (repo *Repository) DescriptionHTML(ctx context.Context) template.HTML {
|
||||
desc, err := markup.RenderDescriptionHTML(&markup.RenderContext{
|
||||
Ctx: ctx,
|
||||
// Don't use Metas to speedup requests
|
||||
}, repo.Description)
|
||||
desc, err := markup.PostProcessDescriptionHTML(markup.NewRenderContext(ctx), repo.Description)
|
||||
if err != nil {
|
||||
log.Error("Failed to render description for %s (ID: %d): %v", repo.Name, repo.ID, err)
|
||||
return template.HTML(markup.SanitizeDescription(repo.Description))
|
||||
|
@ -98,8 +98,7 @@ func (repos RepositoryList) IDs() []int64 {
|
||||
return repoIDs
|
||||
}
|
||||
|
||||
// LoadAttributes loads the attributes for the given RepositoryList
|
||||
func (repos RepositoryList) LoadAttributes(ctx context.Context) error {
|
||||
func (repos RepositoryList) LoadOwners(ctx context.Context) error {
|
||||
if len(repos) == 0 {
|
||||
return nil
|
||||
}
|
||||
@ -107,10 +106,6 @@ func (repos RepositoryList) LoadAttributes(ctx context.Context) error {
|
||||
userIDs := container.FilterSlice(repos, func(repo *Repository) (int64, bool) {
|
||||
return repo.OwnerID, true
|
||||
})
|
||||
repoIDs := make([]int64, len(repos))
|
||||
for i := range repos {
|
||||
repoIDs[i] = repos[i].ID
|
||||
}
|
||||
|
||||
// Load owners.
|
||||
users := make(map[int64]*user_model.User, len(userIDs))
|
||||
@ -123,12 +118,19 @@ func (repos RepositoryList) LoadAttributes(ctx context.Context) error {
|
||||
for i := range repos {
|
||||
repos[i].Owner = users[repos[i].OwnerID]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repos RepositoryList) LoadLanguageStats(ctx context.Context) error {
|
||||
if len(repos) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Load primary language.
|
||||
stats := make(LanguageStatList, 0, len(repos))
|
||||
if err := db.GetEngine(ctx).
|
||||
Where("`is_primary` = ? AND `language` != ?", true, "other").
|
||||
In("`repo_id`", repoIDs).
|
||||
In("`repo_id`", repos.IDs()).
|
||||
Find(&stats); err != nil {
|
||||
return fmt.Errorf("find primary languages: %w", err)
|
||||
}
|
||||
@ -141,10 +143,18 @@ func (repos RepositoryList) LoadAttributes(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadAttributes loads the attributes for the given RepositoryList
|
||||
func (repos RepositoryList) LoadAttributes(ctx context.Context) error {
|
||||
if err := repos.LoadOwners(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return repos.LoadLanguageStats(ctx)
|
||||
}
|
||||
|
||||
// SearchRepoOptions holds the search options
|
||||
type SearchRepoOptions struct {
|
||||
db.ListOptions
|
||||
|
@ -1,13 +1,12 @@
|
||||
// Copyright 2017 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package repo_test
|
||||
package repo
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
@ -20,18 +19,18 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
countRepospts = repo_model.CountRepositoryOptions{OwnerID: 10}
|
||||
countReposptsPublic = repo_model.CountRepositoryOptions{OwnerID: 10, Private: optional.Some(false)}
|
||||
countReposptsPrivate = repo_model.CountRepositoryOptions{OwnerID: 10, Private: optional.Some(true)}
|
||||
countRepospts = CountRepositoryOptions{OwnerID: 10}
|
||||
countReposptsPublic = CountRepositoryOptions{OwnerID: 10, Private: optional.Some(false)}
|
||||
countReposptsPrivate = CountRepositoryOptions{OwnerID: 10, Private: optional.Some(true)}
|
||||
)
|
||||
|
||||
func TestGetRepositoryCount(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
ctx := db.DefaultContext
|
||||
count, err1 := repo_model.CountRepositories(ctx, countRepospts)
|
||||
privateCount, err2 := repo_model.CountRepositories(ctx, countReposptsPrivate)
|
||||
publicCount, err3 := repo_model.CountRepositories(ctx, countReposptsPublic)
|
||||
count, err1 := CountRepositories(ctx, countRepospts)
|
||||
privateCount, err2 := CountRepositories(ctx, countReposptsPrivate)
|
||||
publicCount, err3 := CountRepositories(ctx, countReposptsPublic)
|
||||
assert.NoError(t, err1)
|
||||
assert.NoError(t, err2)
|
||||
assert.NoError(t, err3)
|
||||
@ -42,7 +41,7 @@ func TestGetRepositoryCount(t *testing.T) {
|
||||
func TestGetPublicRepositoryCount(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
count, err := repo_model.CountRepositories(db.DefaultContext, countReposptsPublic)
|
||||
count, err := CountRepositories(db.DefaultContext, countReposptsPublic)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), count)
|
||||
}
|
||||
@ -50,14 +49,14 @@ func TestGetPublicRepositoryCount(t *testing.T) {
|
||||
func TestGetPrivateRepositoryCount(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
count, err := repo_model.CountRepositories(db.DefaultContext, countReposptsPrivate)
|
||||
count, err := CountRepositories(db.DefaultContext, countReposptsPrivate)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(2), count)
|
||||
}
|
||||
|
||||
func TestRepoAPIURL(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10})
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 10})
|
||||
|
||||
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user12/repo10", repo.APIURL())
|
||||
}
|
||||
@ -65,22 +64,22 @@ func TestRepoAPIURL(t *testing.T) {
|
||||
func TestWatchRepo(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3})
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
|
||||
assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, user, repo, true))
|
||||
unittest.AssertExistsAndLoadBean(t, &repo_model.Watch{RepoID: repo.ID, UserID: user.ID})
|
||||
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID})
|
||||
assert.NoError(t, WatchRepo(db.DefaultContext, user, repo, true))
|
||||
unittest.AssertExistsAndLoadBean(t, &Watch{RepoID: repo.ID, UserID: user.ID})
|
||||
unittest.CheckConsistencyFor(t, &Repository{ID: repo.ID})
|
||||
|
||||
assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, user, repo, false))
|
||||
unittest.AssertNotExistsBean(t, &repo_model.Watch{RepoID: repo.ID, UserID: user.ID})
|
||||
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID})
|
||||
assert.NoError(t, WatchRepo(db.DefaultContext, user, repo, false))
|
||||
unittest.AssertNotExistsBean(t, &Watch{RepoID: repo.ID, UserID: user.ID})
|
||||
unittest.CheckConsistencyFor(t, &Repository{ID: repo.ID})
|
||||
}
|
||||
|
||||
func TestMetas(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
repo := &repo_model.Repository{Name: "testRepo"}
|
||||
repo := &Repository{Name: "testRepo"}
|
||||
repo.Owner = &user_model.User{Name: "testOwner"}
|
||||
repo.OwnerName = repo.Owner.Name
|
||||
|
||||
@ -90,16 +89,16 @@ func TestMetas(t *testing.T) {
|
||||
assert.Equal(t, "testRepo", metas["repo"])
|
||||
assert.Equal(t, "testOwner", metas["user"])
|
||||
|
||||
externalTracker := repo_model.RepoUnit{
|
||||
externalTracker := RepoUnit{
|
||||
Type: unit.TypeExternalTracker,
|
||||
Config: &repo_model.ExternalTrackerConfig{
|
||||
Config: &ExternalTrackerConfig{
|
||||
ExternalTrackerFormat: "https://someurl.com/{user}/{repo}/{issue}",
|
||||
},
|
||||
}
|
||||
|
||||
testSuccess := func(expectedStyle string) {
|
||||
repo.Units = []*repo_model.RepoUnit{&externalTracker}
|
||||
repo.RenderingMetas = nil
|
||||
repo.Units = []*RepoUnit{&externalTracker}
|
||||
repo.commonRenderingMetas = nil
|
||||
metas := repo.ComposeMetas(db.DefaultContext)
|
||||
assert.Equal(t, expectedStyle, metas["style"])
|
||||
assert.Equal(t, "testRepo", metas["repo"])
|
||||
@ -118,7 +117,7 @@ func TestMetas(t *testing.T) {
|
||||
externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleRegexp
|
||||
testSuccess(markup.IssueNameStyleRegexp)
|
||||
|
||||
repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3)
|
||||
repo, err := GetRepositoryByID(db.DefaultContext, 3)
|
||||
assert.NoError(t, err)
|
||||
|
||||
metas = repo.ComposeMetas(db.DefaultContext)
|
||||
@ -132,7 +131,7 @@ func TestGetRepositoryByURL(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
t.Run("InvalidPath", func(t *testing.T) {
|
||||
repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, "something")
|
||||
repo, err := GetRepositoryByURL(db.DefaultContext, "something")
|
||||
|
||||
assert.Nil(t, repo)
|
||||
assert.Error(t, err)
|
||||
@ -140,7 +139,7 @@ func TestGetRepositoryByURL(t *testing.T) {
|
||||
|
||||
t.Run("ValidHttpURL", func(t *testing.T) {
|
||||
test := func(t *testing.T, url string) {
|
||||
repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url)
|
||||
repo, err := GetRepositoryByURL(db.DefaultContext, url)
|
||||
|
||||
assert.NotNil(t, repo)
|
||||
assert.NoError(t, err)
|
||||
@ -155,7 +154,7 @@ func TestGetRepositoryByURL(t *testing.T) {
|
||||
|
||||
t.Run("ValidGitSshURL", func(t *testing.T) {
|
||||
test := func(t *testing.T, url string) {
|
||||
repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url)
|
||||
repo, err := GetRepositoryByURL(db.DefaultContext, url)
|
||||
|
||||
assert.NotNil(t, repo)
|
||||
assert.NoError(t, err)
|
||||
@ -173,7 +172,7 @@ func TestGetRepositoryByURL(t *testing.T) {
|
||||
|
||||
t.Run("ValidImplicitSshURL", func(t *testing.T) {
|
||||
test := func(t *testing.T, url string) {
|
||||
repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url)
|
||||
repo, err := GetRepositoryByURL(db.DefaultContext, url)
|
||||
|
||||
assert.NotNil(t, repo)
|
||||
assert.NoError(t, err)
|
||||
@ -200,21 +199,21 @@ func TestComposeSSHCloneURL(t *testing.T) {
|
||||
setting.SSH.Domain = "domain"
|
||||
setting.SSH.Port = 22
|
||||
setting.Repository.UseCompatSSHURI = false
|
||||
assert.Equal(t, "git@domain:user/repo.git", repo_model.ComposeSSHCloneURL("user", "repo"))
|
||||
assert.Equal(t, "git@domain:user/repo.git", ComposeSSHCloneURL("user", "repo"))
|
||||
setting.Repository.UseCompatSSHURI = true
|
||||
assert.Equal(t, "ssh://git@domain/user/repo.git", repo_model.ComposeSSHCloneURL("user", "repo"))
|
||||
assert.Equal(t, "ssh://git@domain/user/repo.git", ComposeSSHCloneURL("user", "repo"))
|
||||
// test SSH_DOMAIN while use non-standard SSH port
|
||||
setting.SSH.Port = 123
|
||||
setting.Repository.UseCompatSSHURI = false
|
||||
assert.Equal(t, "ssh://git@domain:123/user/repo.git", repo_model.ComposeSSHCloneURL("user", "repo"))
|
||||
assert.Equal(t, "ssh://git@domain:123/user/repo.git", ComposeSSHCloneURL("user", "repo"))
|
||||
setting.Repository.UseCompatSSHURI = true
|
||||
assert.Equal(t, "ssh://git@domain:123/user/repo.git", repo_model.ComposeSSHCloneURL("user", "repo"))
|
||||
assert.Equal(t, "ssh://git@domain:123/user/repo.git", ComposeSSHCloneURL("user", "repo"))
|
||||
|
||||
// test IPv6 SSH_DOMAIN
|
||||
setting.Repository.UseCompatSSHURI = false
|
||||
setting.SSH.Domain = "::1"
|
||||
setting.SSH.Port = 22
|
||||
assert.Equal(t, "git@[::1]:user/repo.git", repo_model.ComposeSSHCloneURL("user", "repo"))
|
||||
assert.Equal(t, "git@[::1]:user/repo.git", ComposeSSHCloneURL("user", "repo"))
|
||||
setting.SSH.Port = 123
|
||||
assert.Equal(t, "ssh://git@[::1]:123/user/repo.git", repo_model.ComposeSSHCloneURL("user", "repo"))
|
||||
assert.Equal(t, "ssh://git@[::1]:123/user/repo.git", ComposeSSHCloneURL("user", "repo"))
|
||||
}
|
||||
|
@ -36,6 +36,7 @@ var OrderByMap = map[string]map[string]db.SearchOrderBy{
|
||||
var OrderByFlatMap = map[string]db.SearchOrderBy{
|
||||
"newest": OrderByMap["desc"]["created"],
|
||||
"oldest": OrderByMap["asc"]["created"],
|
||||
"recentupdate": OrderByMap["desc"]["updated"],
|
||||
"leastupdate": OrderByMap["asc"]["updated"],
|
||||
"reversealphabetically": OrderByMap["desc"]["alpha"],
|
||||
"alphabetically": OrderByMap["asc"]["alpha"],
|
||||
|
@ -11,7 +11,6 @@ import (
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/container"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
|
||||
"xorm.io/builder"
|
||||
)
|
||||
@ -110,26 +109,28 @@ func GetRepoAssignees(ctx context.Context, repo *Repository) (_ []*user_model.Us
|
||||
return nil, err
|
||||
}
|
||||
|
||||
additionalUserIDs := make([]int64, 0, 10)
|
||||
if err = e.Table("team_user").
|
||||
Join("INNER", "team_repo", "`team_repo`.team_id = `team_user`.team_id").
|
||||
Join("INNER", "team_unit", "`team_unit`.team_id = `team_user`.team_id").
|
||||
Where("`team_repo`.repo_id = ? AND (`team_unit`.access_mode >= ? OR (`team_unit`.access_mode = ? AND `team_unit`.`type` = ?))",
|
||||
repo.ID, perm.AccessModeWrite, perm.AccessModeRead, unit.TypePullRequests).
|
||||
Distinct("`team_user`.uid").
|
||||
Select("`team_user`.uid").
|
||||
Find(&additionalUserIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
uniqueUserIDs := make(container.Set[int64])
|
||||
uniqueUserIDs.AddMultiple(userIDs...)
|
||||
uniqueUserIDs.AddMultiple(additionalUserIDs...)
|
||||
|
||||
if repo.Owner.IsOrganization() {
|
||||
additionalUserIDs := make([]int64, 0, 10)
|
||||
if err = e.Table("team_user").
|
||||
Join("INNER", "team_repo", "`team_repo`.team_id = `team_user`.team_id").
|
||||
Join("INNER", "team_unit", "`team_unit`.team_id = `team_user`.team_id").
|
||||
Where("`team_repo`.repo_id = ? AND (`team_unit`.access_mode >= ? OR (`team_unit`.access_mode = ? AND `team_unit`.`type` = ?))",
|
||||
repo.ID, perm.AccessModeWrite, perm.AccessModeRead, unit.TypePullRequests).
|
||||
Distinct("`team_user`.uid").
|
||||
Select("`team_user`.uid").
|
||||
Find(&additionalUserIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uniqueUserIDs.AddMultiple(additionalUserIDs...)
|
||||
}
|
||||
|
||||
// Leave a seat for owner itself to append later, but if owner is an organization
|
||||
// and just waste 1 unit is cheaper than re-allocate memory once.
|
||||
users := make([]*user_model.User, 0, len(uniqueUserIDs)+1)
|
||||
if len(userIDs) > 0 {
|
||||
if len(uniqueUserIDs) > 0 {
|
||||
if err = e.In("id", uniqueUserIDs.Values()).
|
||||
Where(builder.Eq{"`user`.is_active": true}).
|
||||
OrderBy(user_model.GetOrderByName()).
|
||||
@ -144,57 +145,6 @@ func GetRepoAssignees(ctx context.Context, repo *Repository) (_ []*user_model.Us
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// GetReviewers get all users can be requested to review:
|
||||
// * for private repositories this returns all users that have read access or higher to the repository.
|
||||
// * for public repositories this returns all users that have read access or higher to the repository,
|
||||
// all repo watchers and all organization members.
|
||||
// TODO: may be we should have a busy choice for users to block review request to them.
|
||||
func GetReviewers(ctx context.Context, repo *Repository, doerID, posterID int64) ([]*user_model.User, error) {
|
||||
// Get the owner of the repository - this often already pre-cached and if so saves complexity for the following queries
|
||||
if err := repo.LoadOwner(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cond := builder.And(builder.Neq{"`user`.id": posterID}).
|
||||
And(builder.Eq{"`user`.is_active": true})
|
||||
|
||||
if repo.IsPrivate || repo.Owner.Visibility == api.VisibleTypePrivate {
|
||||
// This a private repository:
|
||||
// Anyone who can read the repository is a requestable reviewer
|
||||
|
||||
cond = cond.And(builder.In("`user`.id",
|
||||
builder.Select("user_id").From("access").Where(
|
||||
builder.Eq{"repo_id": repo.ID}.
|
||||
And(builder.Gte{"mode": perm.AccessModeRead}),
|
||||
),
|
||||
))
|
||||
|
||||
if repo.Owner.Type == user_model.UserTypeIndividual && repo.Owner.ID != posterID {
|
||||
// as private *user* repos don't generate an entry in the `access` table,
|
||||
// the owner of a private repo needs to be explicitly added.
|
||||
cond = cond.Or(builder.Eq{"`user`.id": repo.Owner.ID})
|
||||
}
|
||||
} else {
|
||||
// This is a "public" repository:
|
||||
// Any user that has read access, is a watcher or organization member can be requested to review
|
||||
cond = cond.And(builder.And(builder.In("`user`.id",
|
||||
builder.Select("user_id").From("access").
|
||||
Where(builder.Eq{"repo_id": repo.ID}.
|
||||
And(builder.Gte{"mode": perm.AccessModeRead})),
|
||||
).Or(builder.In("`user`.id",
|
||||
builder.Select("user_id").From("watch").
|
||||
Where(builder.Eq{"repo_id": repo.ID}.
|
||||
And(builder.In("mode", WatchModeNormal, WatchModeAuto))),
|
||||
).Or(builder.In("`user`.id",
|
||||
builder.Select("uid").From("org_user").
|
||||
Where(builder.Eq{"org_id": repo.OwnerID}),
|
||||
)))))
|
||||
}
|
||||
|
||||
users := make([]*user_model.User, 0, 8)
|
||||
return users, db.GetEngine(ctx).Where(cond).OrderBy(user_model.GetOrderByName()).Find(&users)
|
||||
}
|
||||
|
||||
// GetIssuePostersWithSearch returns users with limit of 30 whose username started with prefix that have authored an issue/pull request for the given repository
|
||||
// If isShowFullName is set to true, also include full name prefix search
|
||||
func GetIssuePostersWithSearch(ctx context.Context, repo *Repository, isPull bool, search string, isShowFullName bool) ([]*user_model.User, error) {
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user