From d0012c880604e54c563e033d125375c9335277f8 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Tue, 26 Sep 2023 13:58:57 +0800 Subject: [PATCH 01/22] Document the queue item's marshaling behavior (#27271) Close #26843 --- modules/queue/queue.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/queue/queue.go b/modules/queue/queue.go index 1ad7320e31f01..577fd4d4981a6 100644 --- a/modules/queue/queue.go +++ b/modules/queue/queue.go @@ -9,6 +9,8 @@ // - An item can be a simple value, such as an integer, or a more complex structure that has multiple fields. // Usually a item serves as a task or a message. Sets of items will be sent to a queue handler to be processed. // - It's represented as a JSON-marshaled binary slice in the queue +// - Since the item is marshaled by JSON, and JSON doesn't have stable key-order/type support, +// so the decoded handler item may not be the same as the original "pushed" one if you use map/any types, // // 2. Batch: // - A collection of items that are grouped together for processing. Each worker receives a batch of items. From 939d410a932138aee68388cbec0e2a3b5610b4c2 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Tue, 26 Sep 2023 19:59:04 +0800 Subject: [PATCH 02/22] Add missing IconHTML size (#27269) Fix #27223 Regression of #27122 --- templates/user/settings/security/accountlinks.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/user/settings/security/accountlinks.tmpl b/templates/user/settings/security/accountlinks.tmpl index 73b2735650db1..0820844547b90 100644 --- a/templates/user/settings/security/accountlinks.tmpl +++ b/templates/user/settings/security/accountlinks.tmpl @@ -29,7 +29,7 @@
{{$providerData := index $.OAuth2Providers $loginSource.Name}}
- {{$providerData.IconHTML}} + {{$providerData.IconHTML 20}}
From 1f89a45926a05cdeb6781da60d52082cacc340e2 Mon Sep 17 00:00:00 2001 From: delvh Date: Tue, 26 Sep 2023 15:10:29 +0200 Subject: [PATCH 03/22] Fix incorrect change from #27231 (#27275) --- templates/projects/new.tmpl | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/templates/projects/new.tmpl b/templates/projects/new.tmpl index 3618edd41b3f4..711dbe842ac45 100644 --- a/templates/projects/new.tmpl +++ b/templates/projects/new.tmpl @@ -29,7 +29,7 @@
{{ctx.Locale.Tr "repo.projects.template.desc_helper"}}
@@ -43,12 +43,12 @@ {{range $element := .CardTypes}} {{if or (eq $.card_type $element.CardType) (and (not $.PageIsEditProjects) (eq $element.CardType 1))}} -
{{ctx.Locale.Tr ctx.Locale.Translation}}
+
{{ctx.Locale.Tr $element.Translation}}
{{end}} {{end}}
From eab20cb6bd7bcbc1c3fffd5a41f1d1029ed30e27 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 27 Sep 2023 00:56:42 +0800 Subject: [PATCH 04/22] Fix more yaml lint errors (#27284) Fix #27268 --- .yamllint.yaml | 2 -- models/fixtures/access.yml | 1 - models/fixtures/access_token.yml | 8 ++++---- models/fixtures/commit_status_index.yml | 2 +- models/fixtures/public_key.yml | 2 +- models/fixtures/pull_request.yml | 2 +- models/fixtures/reaction.yml | 10 +++++----- models/fixtures/review.yml | 10 +++++----- models/fixtures/team_repo.yml | 2 +- models/fixtures/team_user.yml | 2 +- models/fixtures/watch.yml | 2 +- .../Test_DeleteOrphanedIssueLabels/issue_label.yml | 1 - .../fixtures/Test_DeleteOrphanedIssueLabels/label.yml | 2 +- .../fixtures/Test_RemoveInvalidLabels/label.yml | 1 - .../webauthn_credential.yml | 1 - 15 files changed, 21 insertions(+), 27 deletions(-) diff --git a/.yamllint.yaml b/.yamllint.yaml index c0fce7c301f82..7f0517fb7eb15 100644 --- a/.yamllint.yaml +++ b/.yamllint.yaml @@ -44,5 +44,3 @@ rules: ignore: | .venv node_modules - /models/fixtures - /models/migrations/fixtures diff --git a/models/fixtures/access.yml b/models/fixtures/access.yml index 446502843ef48..1bb6a9a8acc7c 100644 --- a/models/fixtures/access.yml +++ b/models/fixtures/access.yml @@ -135,4 +135,3 @@ user_id: 31 repo_id: 28 mode: 4 - diff --git a/models/fixtures/access_token.yml b/models/fixtures/access_token.yml index 791b3da1c459f..0744255f6645a 100644 --- a/models/fixtures/access_token.yml +++ b/models/fixtures/access_token.yml @@ -2,7 +2,7 @@ id: 1 uid: 1 name: Token A - #token: d2c6c1ba3890b309189a8e618c72a162e4efbf36 + # token: d2c6c1ba3890b309189a8e618c72a162e4efbf36 token_hash: 2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f token_salt: QuSiZr1byZ token_last_eight: e4efbf36 @@ -13,7 +13,7 @@ id: 2 uid: 1 name: Token B - #token: 4c6f36e6cf498e2a448662f915d932c09c5a146c + # token: 4c6f36e6cf498e2a448662f915d932c09c5a146c token_hash: 1a0e32a231ebbd582dc626c1543a42d3c63d4fa76c07c72862721467c55e8f81c923d60700f0528b5f5f443f055559d3a279 token_salt: Lfwopukrq5 token_last_eight: 9c5a146c @@ -24,10 +24,10 @@ id: 3 uid: 2 name: Token A - #token: 90a18faa671dc43924b795806ffe4fd169d28c91 + # token: 90a18faa671dc43924b795806ffe4fd169d28c91 token_hash: d6d404048048812d9e911d93aefbe94fc768d4876fdf75e3bef0bdc67828e0af422846d3056f2f25ec35c51dc92075685ec5 token_salt: 99ArgXKlQQ token_last_eight: 69d28c91 created_unix: 946687980 updated_unix: 946687980 -#commented out tokens so you can see what they are in plaintext + # commented out tokens so you can see what they are in plaintext diff --git a/models/fixtures/commit_status_index.yml b/models/fixtures/commit_status_index.yml index 3f252e87ef092..f63343b042a30 100644 --- a/models/fixtures/commit_status_index.yml +++ b/models/fixtures/commit_status_index.yml @@ -2,4 +2,4 @@ id: 1 repo_id: 1 sha: "1234123412341234123412341234123412341234" - max_index: 5 \ No newline at end of file + max_index: 5 diff --git a/models/fixtures/public_key.yml b/models/fixtures/public_key.yml index 08f5c349a7b3d..ae620ee2d19da 100644 --- a/models/fixtures/public_key.yml +++ b/models/fixtures/public_key.yml @@ -8,4 +8,4 @@ type: 1 created_unix: 1559593109 updated_unix: 1565224552 - login_source_id: 0 \ No newline at end of file + login_source_id: 0 diff --git a/models/fixtures/pull_request.yml b/models/fixtures/pull_request.yml index 396bdba88cbc5..560674c370b81 100644 --- a/models/fixtures/pull_request.yml +++ b/models/fixtures/pull_request.yml @@ -97,4 +97,4 @@ issue_id: 20 index: 1 head_repo_id: 23 - base_repo_id: 23 \ No newline at end of file + base_repo_id: 23 diff --git a/models/fixtures/reaction.yml b/models/fixtures/reaction.yml index 4925935fe6fe6..ee571a73a485e 100644 --- a/models/fixtures/reaction.yml +++ b/models/fixtures/reaction.yml @@ -1,5 +1,5 @@ - - id: 1 #issue reaction + id: 1 # issue reaction type: zzz # not allowed reaction (added before allowed reaction list has changed) issue_id: 1 comment_id: 0 @@ -7,7 +7,7 @@ created_unix: 1573248001 - - id: 2 #issue reaction + id: 2 # issue reaction type: zzz # not allowed reaction (added before allowed reaction list has changed) issue_id: 1 comment_id: 0 @@ -15,7 +15,7 @@ created_unix: 1573248002 - - id: 3 #issue reaction + id: 3 # issue reaction type: eyes # allowed reaction issue_id: 1 comment_id: 0 @@ -23,7 +23,7 @@ created_unix: 1573248003 - - id: 4 #comment reaction + id: 4 # comment reaction type: laugh # allowed reaction issue_id: 1 comment_id: 2 @@ -31,7 +31,7 @@ created_unix: 1573248004 - - id: 5 #comment reaction + id: 5 # comment reaction type: laugh # allowed reaction issue_id: 1 comment_id: 2 diff --git a/models/fixtures/review.yml b/models/fixtures/review.yml index f964c6ac06412..7a8808006849c 100644 --- a/models/fixtures/review.yml +++ b/models/fixtures/review.yml @@ -133,7 +133,7 @@ updated_unix: 946684831 created_unix: 946684831 -- +- id: 16 type: 4 reviewer_id: 20 @@ -142,7 +142,7 @@ updated_unix: 946684832 created_unix: 946684832 -- +- id: 17 type: 1 reviewer_id: 20 @@ -150,11 +150,12 @@ content: "review approved by user20" updated_unix: 946684833 created_unix: 946684833 -- + +- id: 18 type: 4 reviewer_id: 0 - reviewer_team_id: 5 + reviewer_team_id: 5 issue_id: 20 content: "review request for team5" updated_unix: 946684834 @@ -169,4 +170,3 @@ content: "review request for user15" updated_unix: 946684835 created_unix: 946684835 - diff --git a/models/fixtures/team_repo.yml b/models/fixtures/team_repo.yml index a523a90b204d2..8497720892f49 100644 --- a/models/fixtures/team_repo.yml +++ b/models/fixtures/team_repo.yml @@ -62,4 +62,4 @@ id: 11 org_id: 17 team_id: 9 - repo_id: 24 \ No newline at end of file + repo_id: 24 diff --git a/models/fixtures/team_user.yml b/models/fixtures/team_user.yml index a5f1e9fd92aaf..9142fe609ad76 100644 --- a/models/fixtures/team_user.yml +++ b/models/fixtures/team_user.yml @@ -124,7 +124,7 @@ team_id: 20 uid: 5 -- +- id: 22 org_id: 17 team_id: 9 diff --git a/models/fixtures/watch.yml b/models/fixtures/watch.yml index c29f6bb65a889..1950ac99e7f9c 100644 --- a/models/fixtures/watch.yml +++ b/models/fixtures/watch.yml @@ -26,4 +26,4 @@ id: 5 user_id: 11 repo_id: 1 - mode: 3 # auto + mode: 3 # auto diff --git a/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/issue_label.yml b/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/issue_label.yml index 96104ac04a869..b02cb570ecdae 100644 --- a/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/issue_label.yml +++ b/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/issue_label.yml @@ -26,4 +26,3 @@ id: 5 issue_id: 2 label_id: 87 - diff --git a/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/label.yml b/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/label.yml index d651c87d5b0d6..fa9658aa02aeb 100644 --- a/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/label.yml +++ b/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/label.yml @@ -18,7 +18,7 @@ - id: 3 repo_id: 0 - org_id: 3 + org_id: 3 name: orglabel3 color: '#abcdef' num_issues: 0 diff --git a/models/migrations/fixtures/Test_RemoveInvalidLabels/label.yml b/models/migrations/fixtures/Test_RemoveInvalidLabels/label.yml index 094b811d914e4..0f5a3eb50722a 100644 --- a/models/migrations/fixtures/Test_RemoveInvalidLabels/label.yml +++ b/models/migrations/fixtures/Test_RemoveInvalidLabels/label.yml @@ -23,4 +23,3 @@ id: 5 repo_id: 3 org_id: 0 - diff --git a/models/migrations/fixtures/Test_StoreWebauthnCredentialIDAsBytes/webauthn_credential.yml b/models/migrations/fixtures/Test_StoreWebauthnCredentialIDAsBytes/webauthn_credential.yml index c02a76e3742a9..ebb73f44de7aa 100644 --- a/models/migrations/fixtures/Test_StoreWebauthnCredentialIDAsBytes/webauthn_credential.yml +++ b/models/migrations/fixtures/Test_StoreWebauthnCredentialIDAsBytes/webauthn_credential.yml @@ -28,4 +28,3 @@ attestation_type: 'fido-u2f' sign_count: 1 clone_warning: false - From 709c2fad8a5c8f8dd270f9b291343d3a37d665e0 Mon Sep 17 00:00:00 2001 From: silverwind Date: Wed, 27 Sep 2023 02:34:52 +0200 Subject: [PATCH 05/22] Add missed return to actions view fetch (#27289) Should fix: #27213 --- web_src/js/components/RepoActionView.vue | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web_src/js/components/RepoActionView.vue b/web_src/js/components/RepoActionView.vue index da06dd9cb60dd..797869b78cead 100644 --- a/web_src/js/components/RepoActionView.vue +++ b/web_src/js/components/RepoActionView.vue @@ -225,7 +225,8 @@ const sfc = { this.fetchArtifacts(), // refresh artifacts if upload-artifact step done ]); } catch (err) { - if (!(err instanceof TypeError)) throw err; // avoid network error while unloading page + if (err instanceof TypeError) return; // avoid network error while unloading page + throw err; } this.artifacts = artifacts['artifacts'] || []; From 6967c13ad2de927f4d9bad65930db5fb383ca1d4 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 27 Sep 2023 09:15:58 +0800 Subject: [PATCH 06/22] Fix some animation bugs (#27287) Fix #27286 Replace #27279 --- web_src/js/modules/fomantic.js | 72 ++++++++++++++++++++-------------- 1 file changed, 43 insertions(+), 29 deletions(-) diff --git a/web_src/js/modules/fomantic.js b/web_src/js/modules/fomantic.js index 3d4a66c1ea9dd..9b52a5d429844 100644 --- a/web_src/js/modules/fomantic.js +++ b/web_src/js/modules/fomantic.js @@ -25,41 +25,55 @@ export function initGiteaFomantic() { return escape(text, preserveHTML) + svg('octicon-x', 16, `${className.delete} icon`); }; + const transitionNopBehaviors = new Set([ + 'clear queue', 'stop', 'stop all', 'destroy', + 'force repaint', 'repaint', 'reset', + 'looping', 'remove looping', 'disable', 'enable', + 'set duration', 'save conditions', 'restore conditions', + ]); // stand-in for removed transition module - $.fn.transition = function (arg) { - if (arg === 'is supported') return true; - if (arg === 'is animating') return false; - if (arg === 'is inward') return false; - if (arg === 'is outward') return false; - if (arg === 'stop all') return; + $.fn.transition = function (arg0, arg1, arg2) { + if (arg0 === 'is supported') return true; + if (arg0 === 'is animating') return false; + if (arg0 === 'is inward') return false; + if (arg0 === 'is outward') return false; - const isIn = arg?.animation?.endsWith(' in'); - const isOut = arg?.animation?.endsWith(' out'); + let argObj; + if (typeof arg0 === 'string') { + // many behaviors are no-op now. https://fomantic-ui.com/modules/transition.html#/usage + if (transitionNopBehaviors.has(arg0)) return this; + // now, the arg0 is an animation name, the syntax: (animation, duration, complete) + argObj = {animation: arg0, ...(arg1 && {duration: arg1}), ...(arg2 && {onComplete: arg2})}; + } else if (typeof arg0 === 'object') { + argObj = arg0; + } else { + throw new Error(`invalid argument: ${arg0}`); + } - let ret; - if (arg === 'show' || isIn) { - arg?.onStart?.(this); - ret = this.each((_, el) => { + const isAnimationIn = argObj.animation?.startsWith('show') || argObj.animation?.endsWith(' in'); + const isAnimationOut = argObj.animation?.startsWith('hide') || argObj.animation?.endsWith(' out'); + this.each((_, el) => { + let toShow = isAnimationIn; + if (!isAnimationIn && !isAnimationOut) { + // If the animation is not in/out, then it must be a toggle animation. + // Fomantic uses computed styles to check "visibility", but to avoid unnecessary arguments, here it only checks the class. + toShow = this.hasClass('hidden'); // maybe it could also check "!this.hasClass('visible')", leave it to the future until there is a real problem. + } + argObj.onStart?.call(el); + if (toShow) { el.classList.remove('hidden'); - el.classList.add('visible'); - if (isIn) el.classList.add('transition'); - if (arg?.displayType) el.style.setProperty('display', arg.displayType, 'important'); - arg?.onShow?.(this); - }); - arg?.onComplete?.(this); - } else if (arg === 'hide' || isOut) { - arg?.onStart?.(this); - ret = this.each((_, el) => { + el.classList.add('visible', 'transition'); + if (argObj.displayType) el.style.setProperty('display', argObj.displayType, 'important'); + argObj.onShow?.call(el); + } else { el.classList.add('hidden'); - el.classList.remove('visible'); - // don't remove the transition class because fomantic didn't do it either + el.classList.remove('visible'); // don't remove the transition class because the Fomantic animation style is `.hidden.transition`. el.style.removeProperty('display'); - arg?.onHidden?.(this); - }); - arg?.onComplete?.(this); - } - - return ret; + argObj.onHidden?.call(el); + } + argObj.onComplete?.call(el); + }); + return this; }; initFomanticApiPatch(); From c5247eff73ea0be33affb97d666c9d222aabcc37 Mon Sep 17 00:00:00 2001 From: silverwind Date: Wed, 27 Sep 2023 04:05:49 +0200 Subject: [PATCH 07/22] Enable production source maps for index.js, fix CSS sourcemaps (#27291) Previously, the production build never output sourcemaps. Now we emit one file for `index.js` because it is the most likely one where we need to be able to better debug reported issues like https://github.com/go-gitea/gitea/issues/27213. This will currently increase the binary size of gitea by around 700kB which is what the gzipped source map file has. Also, I fixed the CSS sourcemap generation which was broken since the introduction of lightningcss. --- .../content/installation/from-source.en-us.md | 10 +++++++-- .../content/installation/from-source.zh-cn.md | 10 +++++++-- webpack.config.js | 21 ++++++++++++------- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/docs/content/installation/from-source.en-us.md b/docs/content/installation/from-source.en-us.md index ef720f0824698..f6a95e8d0cfe8 100644 --- a/docs/content/installation/from-source.en-us.md +++ b/docs/content/installation/from-source.en-us.md @@ -128,8 +128,6 @@ If pre-built frontend files are present it is possible to only build the backend TAGS="bindata" make backend ``` -Webpack source maps are by default enabled in development builds and disabled in production builds. They can be enabled by setting the `ENABLE_SOURCEMAP=true` environment variable. - ## Test After following the steps above, a `gitea` binary will be available in the working directory. @@ -260,3 +258,11 @@ GOARCH=amd64 \ TAGS="bindata sqlite sqlite_unlock_notify" \ make build ``` + +## Source Maps + +By default, gitea generates reduced source maps for frontend files to conserve space. This can be controlled with the `ENABLE_SOURCEMAP` environment variable: + +- `ENABLE_SOURCEMAP=true` generates all source maps, the default for development builds +- `ENABLE_SOURCEMAP=reduced` generates limited source maps, the default for production builds +- `ENABLE_SOURCEMAP=false` generates no source maps diff --git a/docs/content/installation/from-source.zh-cn.md b/docs/content/installation/from-source.zh-cn.md index 260ccbee3c627..74f76652db529 100644 --- a/docs/content/installation/from-source.zh-cn.md +++ b/docs/content/installation/from-source.zh-cn.md @@ -100,8 +100,6 @@ TAGS="bindata sqlite sqlite_unlock_notify" make build TAGS="bindata" make backend ``` -在开发构建中,默认启用 Webpack 源映射,在生产构建中禁用。可以通过设置`ENABLE_SOURCEMAP=true`环境变量来启用它们。 - ## 测试 按照上述步骤完成后,工作目录中将会有一个`gitea`二进制文件。可以从该目录进行测试,或将其移动到带有测试数据的目录中。当手动从命令行启动 Gitea 时,可以通过按下`Ctrl + C`来停止程序。 @@ -221,3 +219,11 @@ GOARCH=amd64 \ TAGS="bindata sqlite sqlite_unlock_notify" \ make build ``` + +## 源映射 + +默认情况下,gitea 会为前端文件生成精简的源映射以节省空间。 这可以通过“ENABLE_SOURCEMAP”环境变量进行控制: + +- `ENABLE_SOURCEMAP=true` 生成所有源映射,这是开发版本的默认设置 +- `ENABLE_SOURCEMAP=reduced` 生成有限的源映射,这是生产版本的默认设置 +- `ENABLE_SOURCEMAP=false` 不生成源映射 diff --git a/webpack.config.js b/webpack.config.js index f95296c380380..448dc640036c4 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -28,11 +28,15 @@ for (const path of glob('web_src/css/themes/*.css')) { const isProduction = env.NODE_ENV !== 'development'; -let sourceMapEnabled; +// ENABLE_SOURCEMAP accepts the following values: +// true - all enabled, the default in development +// reduced - minimal sourcemaps, the default in production +// false - all disabled +let sourceMaps; if ('ENABLE_SOURCEMAP' in env) { - sourceMapEnabled = env.ENABLE_SOURCEMAP === 'true'; + sourceMaps = ['true', 'false'].includes(env.ENABLE_SOURCEMAP) ? env.ENABLE_SOURCEMAP : 'reduced'; } else { - sourceMapEnabled = !isProduction; + sourceMaps = isProduction ? 'reduced' : 'true'; } const filterCssImport = (url, ...args) => { @@ -105,7 +109,9 @@ export default { css: !LightningCssMinifyPlugin, legalComments: 'none', }), - LightningCssMinifyPlugin && new LightningCssMinifyPlugin(), + LightningCssMinifyPlugin && new LightningCssMinifyPlugin({ + sourceMap: sourceMaps === 'true', + }), ], splitChunks: { chunks: 'async', @@ -143,7 +149,7 @@ export default { { loader: 'css-loader', options: { - sourceMap: sourceMapEnabled, + sourceMap: sourceMaps === 'true', url: {filter: filterCssImport}, import: {filter: filterCssImport}, }, @@ -181,9 +187,10 @@ export default { filename: 'css/[name].css', chunkFilename: 'css/[name].[contenthash:8].css', }), - sourceMapEnabled && (new SourceMapDevToolPlugin({ + sourceMaps !== 'false' && new SourceMapDevToolPlugin({ filename: '[file].[contenthash:8].map', - })), + ...(sourceMaps === 'reduced' && {include: /^js\/index\.js$/}), + }), new MonacoWebpackPlugin({ filename: 'js/monaco-[name].[contenthash:8].worker.js', }), From e59c9e3ecdccac1262ed05d693fb826b03af9de8 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 27 Sep 2023 11:30:03 +0800 Subject: [PATCH 08/22] Fix yaml test (#27297) --- models/fixture_generation.go | 4 +++- models/fixture_test.go | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/models/fixture_generation.go b/models/fixture_generation.go index abf880ee8e2bc..d342919895458 100644 --- a/models/fixture_generation.go +++ b/models/fixture_generation.go @@ -40,7 +40,9 @@ func GetYamlFixturesAccess() (string, error) { 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) - fmt.Fprintf(&b, "\n") + if i < len(accesses)-1 { + fmt.Fprintf(&b, "\n") + } } return b.String(), nil diff --git a/models/fixture_test.go b/models/fixture_test.go index 8a28db8164921..b70fdb536d3eb 100644 --- a/models/fixture_test.go +++ b/models/fixture_test.go @@ -22,12 +22,13 @@ func TestFixtureGeneration(t *testing.T) { if !assert.NoError(t, err) { return } - bytes, err := os.ReadFile(filepath.Join(unittest.FixturesDir(), name+".yml")) + p := filepath.Join(unittest.FixturesDir(), name+".yml") + bytes, err := os.ReadFile(p) if !assert.NoError(t, err) { return } data := string(util.NormalizeEOL(bytes)) - assert.True(t, data == expected, "Differences detected for %s.yml", name) + assert.EqualValues(t, expected, data, "Differences detected for %s", p) } test(GetYamlFixturesAccess, "access") From 5ef5a0ade6a49c0e55697a0adc9bd33ef9c83a48 Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Wed, 27 Sep 2023 13:00:57 +0900 Subject: [PATCH 09/22] Fix divider in subscription page (#27298) the divider should always display in the subscription page. Co-authored-by: techknowlogick --- templates/user/notification/notification_subscriptions.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/user/notification/notification_subscriptions.tmpl b/templates/user/notification/notification_subscriptions.tmpl index 03dbd7c3a75f7..7eb4c8ea446ac 100644 --- a/templates/user/notification/notification_subscriptions.tmpl +++ b/templates/user/notification/notification_subscriptions.tmpl @@ -62,8 +62,8 @@ +
{{if eq (len .Issues) 0}} -
{{ctx.Locale.Tr "notification.no_subscriptions"}} {{else}} {{template "shared/issuelist" dict "." . "listType" "dashboard"}} From ee27b94b2c84f6604cb0428d6c2a5611161aac14 Mon Sep 17 00:00:00 2001 From: silverwind Date: Wed, 27 Sep 2023 06:37:13 +0200 Subject: [PATCH 10/22] Use vitest globals (#27102) Enable [globals](https://vitest.dev/config/#globals) in vitest, reducing the noise in test files. --- .eslintrc.yaml | 4 ++++ package-lock.json | 7 +++++++ package.json | 1 + vitest.config.js | 1 + web_src/js/features/common-issue-list.test.js | 1 - web_src/js/features/repo-code.test.js | 1 - web_src/js/features/repo-findfile.test.js | 1 - web_src/js/modules/fetch.test.js | 1 - web_src/js/modules/toast.test.js | 1 - web_src/js/render/ansi.test.js | 1 - web_src/js/svg.test.js | 1 - web_src/js/utils.test.js | 1 - web_src/js/utils/color.test.js | 1 - web_src/js/utils/match.test.js | 1 - web_src/js/utils/url.test.js | 1 - 15 files changed, 13 insertions(+), 11 deletions(-) diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 8495972640245..689a4f919ca80 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -18,6 +18,7 @@ plugins: - eslint-plugin-regexp - eslint-plugin-sonarjs - eslint-plugin-unicorn + - eslint-plugin-vitest-globals - eslint-plugin-wc env: @@ -45,6 +46,9 @@ overrides: - files: ["*.config.*"] rules: import/no-unused-modules: [0] + - files: ["**/*.test.*", "web_src/js/test/setup.js"] + env: + vitest-globals/env: true - files: ["web_src/js/modules/fetch.js", "web_src/js/standalone/**/*"] rules: no-restricted-syntax: [2, WithStatement, ForInStatement, LabeledStatement, SequenceExpression] diff --git a/package-lock.json b/package-lock.json index 54ab43c117c87..e5fec6aa9655a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -67,6 +67,7 @@ "eslint-plugin-regexp": "1.15.0", "eslint-plugin-sonarjs": "0.21.0", "eslint-plugin-unicorn": "48.0.1", + "eslint-plugin-vitest-globals": "1.4.0", "eslint-plugin-vue": "9.17.0", "eslint-plugin-vue-scoped-css": "2.5.0", "eslint-plugin-wc": "2.0.3", @@ -4963,6 +4964,12 @@ "eslint": ">=8.44.0" } }, + "node_modules/eslint-plugin-vitest-globals": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-vitest-globals/-/eslint-plugin-vitest-globals-1.4.0.tgz", + "integrity": "sha512-WE+YlK9X9s4vf5EaYRU0Scw7WItDZStm+PapFSYlg2ABNtaQ4zIG7wEqpoUB3SlfM+SgkhgmzR0TeJOO5k3/Nw==", + "dev": true + }, "node_modules/eslint-plugin-vue": { "version": "9.17.0", "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-9.17.0.tgz", diff --git a/package.json b/package.json index 94c30030d5aae..fb0ee33998b46 100644 --- a/package.json +++ b/package.json @@ -66,6 +66,7 @@ "eslint-plugin-regexp": "1.15.0", "eslint-plugin-sonarjs": "0.21.0", "eslint-plugin-unicorn": "48.0.1", + "eslint-plugin-vitest-globals": "1.4.0", "eslint-plugin-vue": "9.17.0", "eslint-plugin-vue-scoped-css": "2.5.0", "eslint-plugin-wc": "2.0.3", diff --git a/vitest.config.js b/vitest.config.js index 49f59ba982869..9a6cb4e5606fc 100644 --- a/vitest.config.js +++ b/vitest.config.js @@ -11,6 +11,7 @@ export default defineConfig({ open: false, allowOnly: true, passWithNoTests: true, + globals: true, watch: false, }, plugins: [ diff --git a/web_src/js/features/common-issue-list.test.js b/web_src/js/features/common-issue-list.test.js index 271acc718aab9..da7ea64b7ca58 100644 --- a/web_src/js/features/common-issue-list.test.js +++ b/web_src/js/features/common-issue-list.test.js @@ -1,4 +1,3 @@ -import {test, expect} from 'vitest'; import {parseIssueListQuickGotoLink} from './common-issue-list.js'; test('parseIssueListQuickGotoLink', () => { diff --git a/web_src/js/features/repo-code.test.js b/web_src/js/features/repo-code.test.js index 3bd1973c1f217..0e0062a787f5d 100644 --- a/web_src/js/features/repo-code.test.js +++ b/web_src/js/features/repo-code.test.js @@ -1,4 +1,3 @@ -import {test, expect} from 'vitest'; import {singleAnchorRegex, rangeAnchorRegex} from './repo-code.js'; test('singleAnchorRegex', () => { diff --git a/web_src/js/features/repo-findfile.test.js b/web_src/js/features/repo-findfile.test.js index a90b0bf0a2cab..2d96ed4463ee1 100644 --- a/web_src/js/features/repo-findfile.test.js +++ b/web_src/js/features/repo-findfile.test.js @@ -1,4 +1,3 @@ -import {describe, expect, test} from 'vitest'; import {strSubMatch, calcMatchedWeight, filterRepoFilesWeighted} from './repo-findfile.js'; describe('Repo Find Files', () => { diff --git a/web_src/js/modules/fetch.test.js b/web_src/js/modules/fetch.test.js index ec0377b4d90c4..e4bec3ced9d8b 100644 --- a/web_src/js/modules/fetch.test.js +++ b/web_src/js/modules/fetch.test.js @@ -1,4 +1,3 @@ -import {test, expect} from 'vitest'; import {GET, POST, PATCH, PUT, DELETE} from './fetch.js'; // tests here are only to satisfy the linter for unused functions diff --git a/web_src/js/modules/toast.test.js b/web_src/js/modules/toast.test.js index b5066df0b2889..357f18dbcd61a 100644 --- a/web_src/js/modules/toast.test.js +++ b/web_src/js/modules/toast.test.js @@ -1,4 +1,3 @@ -import {test, expect} from 'vitest'; import {showInfoToast, showErrorToast, showWarningToast} from './toast.js'; test('showInfoToast', async () => { diff --git a/web_src/js/render/ansi.test.js b/web_src/js/render/ansi.test.js index b4793251df58f..5afff71c29f9a 100644 --- a/web_src/js/render/ansi.test.js +++ b/web_src/js/render/ansi.test.js @@ -1,4 +1,3 @@ -import {expect, test} from 'vitest'; import {renderAnsi} from './ansi.js'; test('renderAnsi', () => { diff --git a/web_src/js/svg.test.js b/web_src/js/svg.test.js index 5db2f65ac8d68..06b320c860f00 100644 --- a/web_src/js/svg.test.js +++ b/web_src/js/svg.test.js @@ -1,4 +1,3 @@ -import {expect, test} from 'vitest'; import {svg, SvgIcon, svgParseOuterInner} from './svg.js'; import {createApp, h} from 'vue'; diff --git a/web_src/js/utils.test.js b/web_src/js/utils.test.js index db9b1a14a342f..2754e41c433ec 100644 --- a/web_src/js/utils.test.js +++ b/web_src/js/utils.test.js @@ -1,4 +1,3 @@ -import {expect, test} from 'vitest'; import { basename, extname, isObject, stripTags, parseIssueHref, parseUrl, translateMonth, translateDay, blobToDataURI, diff --git a/web_src/js/utils/color.test.js b/web_src/js/utils/color.test.js index 7d45d191a0919..e129109ef0429 100644 --- a/web_src/js/utils/color.test.js +++ b/web_src/js/utils/color.test.js @@ -1,4 +1,3 @@ -import {test, expect} from 'vitest'; import {useLightTextOnBackground} from './color.js'; test('useLightTextOnBackground', () => { diff --git a/web_src/js/utils/match.test.js b/web_src/js/utils/match.test.js index 5dfbd932f415d..1e30b451d4795 100644 --- a/web_src/js/utils/match.test.js +++ b/web_src/js/utils/match.test.js @@ -1,4 +1,3 @@ -import {test, expect} from 'vitest'; import {matchEmoji, matchMention} from './match.js'; test('matchEmoji', () => { diff --git a/web_src/js/utils/url.test.js b/web_src/js/utils/url.test.js index ef2ffaa5f9963..3dbedec94f1e0 100644 --- a/web_src/js/utils/url.test.js +++ b/web_src/js/utils/url.test.js @@ -1,4 +1,3 @@ -import {expect, test} from 'vitest'; import {pathEscapeSegments} from './url.js'; test('pathEscapeSegments', () => { From 3b2da7e4aeed8e2d070b9ce5c66282b16eeb87f1 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 27 Sep 2023 13:37:48 +0800 Subject: [PATCH 11/22] Redefine the meaning of column is_active to make Actions Registration Token generation easier (#27143) Partially Fix #25041 This PR redefined the meaning of column `is_active` in table `action_runner_token`. Before this PR, `is_active` means whether it has been used by any runner. If it's true, other runner cannot use it to register again. In this PR, `is_active` means whether it's validated to be used to register runner. And if it's true, then it can be used to register runners until it become false. When creating a new `is_active` register token, any previous tokens will be set `is_active` to false. --- models/actions/runner_token.go | 26 ++++++++++++++++++-------- routers/api/actions/runner/runner.go | 6 +++--- routers/private/actions.go | 4 ++-- routers/web/shared/actions/runners.go | 6 +++--- 4 files changed, 26 insertions(+), 16 deletions(-) diff --git a/models/actions/runner_token.go b/models/actions/runner_token.go index fabd6c644c8da..cf4e90f3f1152 100644 --- a/models/actions/runner_token.go +++ b/models/actions/runner_token.go @@ -22,7 +22,7 @@ type ActionRunnerToken struct { Owner *user_model.User `xorm:"-"` RepoID int64 `xorm:"index"` // repo level runner, if orgid also is zero, then it's a global Repo *repo_model.Repository `xorm:"-"` - IsActive bool + IsActive bool // true means it can be used Created timeutil.TimeStamp `xorm:"created"` Updated timeutil.TimeStamp `xorm:"updated"` @@ -57,7 +57,7 @@ func UpdateRunnerToken(ctx context.Context, r *ActionRunnerToken, cols ...string return err } -// NewRunnerToken creates a new runner token +// NewRunnerToken creates a new active runner token and invalidate all old tokens func NewRunnerToken(ctx context.Context, ownerID, repoID int64) (*ActionRunnerToken, error) { token, err := util.CryptoRandomString(40) if err != nil { @@ -66,17 +66,27 @@ func NewRunnerToken(ctx context.Context, ownerID, repoID int64) (*ActionRunnerTo runnerToken := &ActionRunnerToken{ OwnerID: ownerID, RepoID: repoID, - IsActive: false, + IsActive: true, Token: token, } - _, err = db.GetEngine(ctx).Insert(runnerToken) - return runnerToken, err + + return runnerToken, db.WithTx(ctx, func(ctx context.Context) error { + if _, err := db.GetEngine(ctx).Where("owner_id =? AND repo_id = ?", ownerID, repoID).Cols("is_active").Update(&ActionRunnerToken{ + IsActive: false, + }); err != nil { + return err + } + + _, err = db.GetEngine(ctx).Insert(runnerToken) + return err + }) } -// GetUnactivatedRunnerToken returns a unactivated runner token -func GetUnactivatedRunnerToken(ctx context.Context, ownerID, repoID int64) (*ActionRunnerToken, error) { +// GetLastestRunnerToken returns the latest runner token +func GetLastestRunnerToken(ctx context.Context, ownerID, repoID int64) (*ActionRunnerToken, error) { var runnerToken ActionRunnerToken - has, err := db.GetEngine(ctx).Where("owner_id=? AND repo_id=? AND is_active=?", ownerID, repoID, false).OrderBy("id DESC").Get(&runnerToken) + has, err := db.GetEngine(ctx).Where("owner_id=? AND repo_id=?", ownerID, repoID). + OrderBy("id DESC").Get(&runnerToken) if err != nil { return nil, err } else if !has { diff --git a/routers/api/actions/runner/runner.go b/routers/api/actions/runner/runner.go index cb206f5685173..8df6f297ceb96 100644 --- a/routers/api/actions/runner/runner.go +++ b/routers/api/actions/runner/runner.go @@ -47,11 +47,11 @@ func (s *Service) Register( runnerToken, err := actions_model.GetRunnerToken(ctx, req.Msg.Token) if err != nil { - return nil, errors.New("runner token not found") + return nil, errors.New("runner registration token not found") } - if runnerToken.IsActive { - return nil, errors.New("runner token has already been activated") + if !runnerToken.IsActive { + return nil, errors.New("runner registration token has been invalidated, please use the latest one") } labels := req.Msg.Labels diff --git a/routers/private/actions.go b/routers/private/actions.go index 2403b9c41a0b4..74515256da997 100644 --- a/routers/private/actions.go +++ b/routers/private/actions.go @@ -41,8 +41,8 @@ func GenerateActionsRunnerToken(ctx *context.PrivateContext) { }) } - token, err := actions_model.GetUnactivatedRunnerToken(ctx, owner, repo) - if errors.Is(err, util.ErrNotExist) { + token, err := actions_model.GetLastestRunnerToken(ctx, owner, repo) + if errors.Is(err, util.ErrNotExist) || (token != nil && !token.IsActive) { token, err = actions_model.NewRunnerToken(ctx, owner, repo) if err != nil { err := fmt.Sprintf("error while creating runner token: %v", err) diff --git a/routers/web/shared/actions/runners.go b/routers/web/shared/actions/runners.go index 7ff1f3e33f537..cd60e9cbee348 100644 --- a/routers/web/shared/actions/runners.go +++ b/routers/web/shared/actions/runners.go @@ -35,15 +35,15 @@ func RunnersList(ctx *context.Context, opts actions_model.FindRunnerOptions) { // ownid=0,repo_id=0,means this token is used for global var token *actions_model.ActionRunnerToken - token, err = actions_model.GetUnactivatedRunnerToken(ctx, opts.OwnerID, opts.RepoID) - if errors.Is(err, util.ErrNotExist) { + token, err = actions_model.GetLastestRunnerToken(ctx, opts.OwnerID, opts.RepoID) + if errors.Is(err, util.ErrNotExist) || (token != nil && !token.IsActive) { token, err = actions_model.NewRunnerToken(ctx, opts.OwnerID, opts.RepoID) if err != nil { ctx.ServerError("CreateRunnerToken", err) return } } else if err != nil { - ctx.ServerError("GetUnactivatedRunnerToken", err) + ctx.ServerError("GetLastestRunnerToken", err) return } From 9e446dbf0451004f8b24e532ed8dbff180782e78 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Wed, 27 Sep 2023 03:10:58 -0400 Subject: [PATCH 12/22] bump bleve (#27300) Co-authored-by: yp05327 <576951401@qq.com> Co-authored-by: silverwind Co-authored-by: Lunny Xiao --- go.mod | 20 ++++++++++---------- go.sum | 40 ++++++++++++++++++++-------------------- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/go.mod b/go.mod index e69594b118bd5..94ee158cb8037 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,7 @@ require ( github.com/PuerkitoBio/goquery v1.8.1 github.com/alecthomas/chroma/v2 v2.9.1 github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb - github.com/blevesearch/bleve/v2 v2.3.9 + github.com/blevesearch/bleve/v2 v2.3.10 github.com/bufbuild/connect-go v1.10.0 github.com/buildkite/terminal-to-html/v3 v3.9.1 github.com/caddyserver/certmagic v0.19.2 @@ -145,22 +145,22 @@ require ( github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/beorn7/perks v1.0.1 // indirect - github.com/bits-and-blooms/bitset v1.8.0 // indirect - github.com/blevesearch/bleve_index_api v1.0.5 // indirect - github.com/blevesearch/geo v0.1.17 // indirect + github.com/bits-and-blooms/bitset v1.9.0 // indirect + github.com/blevesearch/bleve_index_api v1.0.6 // indirect + github.com/blevesearch/geo v0.1.18 // indirect github.com/blevesearch/go-porterstemmer v1.0.3 // indirect github.com/blevesearch/gtreap v0.1.1 // indirect github.com/blevesearch/mmap-go v1.0.4 // indirect - github.com/blevesearch/scorch_segment_api/v2 v2.1.5 // indirect + github.com/blevesearch/scorch_segment_api/v2 v2.1.6 // indirect github.com/blevesearch/segment v0.9.1 // indirect github.com/blevesearch/snowballstem v0.9.0 // indirect github.com/blevesearch/upsidedown_store_api v1.0.2 // indirect github.com/blevesearch/vellum v1.0.10 // indirect - github.com/blevesearch/zapx/v11 v11.3.9 // indirect - github.com/blevesearch/zapx/v12 v12.3.9 // indirect - github.com/blevesearch/zapx/v13 v13.3.9 // indirect - github.com/blevesearch/zapx/v14 v14.3.9 // indirect - github.com/blevesearch/zapx/v15 v15.3.12 // indirect + github.com/blevesearch/zapx/v11 v11.3.10 // indirect + github.com/blevesearch/zapx/v12 v12.3.10 // indirect + github.com/blevesearch/zapx/v13 v13.3.10 // indirect + github.com/blevesearch/zapx/v14 v14.3.10 // indirect + github.com/blevesearch/zapx/v15 v15.3.13 // indirect github.com/boombuler/barcode v1.0.1 // indirect github.com/bradfitz/gomemcache v0.0.0-20230611145640-acc696258285 // indirect github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a // indirect diff --git a/go.sum b/go.sum index fed5583bbaf0d..44bfa1029f91d 100644 --- a/go.sum +++ b/go.sum @@ -149,18 +149,18 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bits-and-blooms/bitset v1.1.10/go.mod h1:w0XsmFg8qg6cmpTtJ0z3pKgjTDBMMnI/+I2syrE6XBE= github.com/bits-and-blooms/bitset v1.2.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA= -github.com/bits-and-blooms/bitset v1.8.0 h1:FD+XqgOZDUxxZ8hzoBFuV9+cGWY9CslN6d5MS5JVb4c= -github.com/bits-and-blooms/bitset v1.8.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= +github.com/bits-and-blooms/bitset v1.9.0 h1:g1YivPG8jOtrN013Fe8OBXubkiTwvm7/vG2vXz03ANU= +github.com/bits-and-blooms/bitset v1.9.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb h1:m935MPodAbYS46DG4pJSv7WO+VECIWUQ7OJYSoTrMh4= github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb/go.mod h1:PkYb9DJNAwrSvRx5DYA+gUcOIgTGVMNkfSCbZM8cWpI= github.com/blevesearch/bleve/v2 v2.0.5/go.mod h1:ZjWibgnbRX33c+vBRgla9QhPb4QOjD6fdVJ+R1Bk8LM= -github.com/blevesearch/bleve/v2 v2.3.9 h1:pUMvK0mxAexqasZcVj8lazmWnEW5XiV0tASIqANiNTQ= -github.com/blevesearch/bleve/v2 v2.3.9/go.mod h1:1PibElcjlQMQHF9uS9mRv58ODQgj4pCWHA1Wfd+qagU= +github.com/blevesearch/bleve/v2 v2.3.10 h1:z8V0wwGoL4rp7nG/O3qVVLYxUqCbEwskMt4iRJsPLgg= +github.com/blevesearch/bleve/v2 v2.3.10/go.mod h1:RJzeoeHC+vNHsoLR54+crS1HmOWpnH87fL70HAUCzIA= github.com/blevesearch/bleve_index_api v1.0.0/go.mod h1:fiwKS0xLEm+gBRgv5mumf0dhgFr2mDgZah1pqv1c1M4= -github.com/blevesearch/bleve_index_api v1.0.5 h1:Lc986kpC4Z0/n1g3gg8ul7H+lxgOQPcXb9SxvQGu+tw= -github.com/blevesearch/bleve_index_api v1.0.5/go.mod h1:YXMDwaXFFXwncRS8UobWs7nvo0DmusriM1nztTlj1ms= -github.com/blevesearch/geo v0.1.17 h1:AguzI6/5mHXapzB0gE9IKWo+wWPHZmXZoscHcjFgAFA= -github.com/blevesearch/geo v0.1.17/go.mod h1:uRMGWG0HJYfWfFJpK3zTdnnr1K+ksZTuWKhXeSokfnM= +github.com/blevesearch/bleve_index_api v1.0.6 h1:gyUUxdsrvmW3jVhhYdCVL6h9dCjNT/geNU7PxGn37p8= +github.com/blevesearch/bleve_index_api v1.0.6/go.mod h1:YXMDwaXFFXwncRS8UobWs7nvo0DmusriM1nztTlj1ms= +github.com/blevesearch/geo v0.1.18 h1:Np8jycHTZ5scFe7VEPLrDoHnnb9C4j636ue/CGrhtDw= +github.com/blevesearch/geo v0.1.18/go.mod h1:uRMGWG0HJYfWfFJpK3zTdnnr1K+ksZTuWKhXeSokfnM= github.com/blevesearch/go-porterstemmer v1.0.3 h1:GtmsqID0aZdCSNiY8SkuPJ12pD4jI+DdXTAn4YRcHCo= github.com/blevesearch/go-porterstemmer v1.0.3/go.mod h1:angGc5Ht+k2xhJdZi511LtmxuEf0OVpvUUNrwmM1P7M= github.com/blevesearch/gtreap v0.1.1 h1:2JWigFrzDMR+42WGIN/V2p0cUvn4UP3C4Q5nmaZGW8Y= @@ -169,8 +169,8 @@ github.com/blevesearch/mmap-go v1.0.2/go.mod h1:ol2qBqYaOUsGdm7aRMRrYGgPvnwLe6Y+ github.com/blevesearch/mmap-go v1.0.4 h1:OVhDhT5B/M1HNPpYPBKIEJaD0F3Si+CrEKULGCDPWmc= github.com/blevesearch/mmap-go v1.0.4/go.mod h1:EWmEAOmdAS9z/pi/+Toxu99DnsbhG1TIxUoRmJw/pSs= github.com/blevesearch/scorch_segment_api/v2 v2.0.1/go.mod h1:lq7yK2jQy1yQjtjTfU931aVqz7pYxEudHaDwOt1tXfU= -github.com/blevesearch/scorch_segment_api/v2 v2.1.5 h1:1g713kpCQZ8u4a3stRGBfrwVOuGRnmxOVU5MQkUPrHU= -github.com/blevesearch/scorch_segment_api/v2 v2.1.5/go.mod h1:f2nOkKS1HcjgIWZgDAErgBdxmr2eyt0Kn7IY+FU1Xe4= +github.com/blevesearch/scorch_segment_api/v2 v2.1.6 h1:CdekX/Ob6YCYmeHzD72cKpwzBjvkOGegHOqhAkXp6yA= +github.com/blevesearch/scorch_segment_api/v2 v2.1.6/go.mod h1:nQQYlp51XvoSVxcciBjtvuHPIVjlWrN1hX4qwK2cqdc= github.com/blevesearch/segment v0.9.0/go.mod h1:9PfHYUdQCgHktBgvtUOF4x+pc4/l8rdH0u5spnW85UQ= github.com/blevesearch/segment v0.9.1 h1:+dThDy+Lvgj5JMxhmOVlgFfkUtZV2kw49xax4+jTfSU= github.com/blevesearch/segment v0.9.1/go.mod h1:zN21iLm7+GnBHWTao9I+Au/7MBiL8pPFtJBJTsk6kQw= @@ -184,20 +184,20 @@ github.com/blevesearch/vellum v1.0.4/go.mod h1:cMhywHI0de50f7Nj42YgvyD6bFJ2WkNRv github.com/blevesearch/vellum v1.0.10 h1:HGPJDT2bTva12hrHepVT3rOyIKFFF4t7Gf6yMxyMIPI= github.com/blevesearch/vellum v1.0.10/go.mod h1:ul1oT0FhSMDIExNjIxHqJoGpVrBpKCdgDQNxfqgJt7k= github.com/blevesearch/zapx/v11 v11.2.0/go.mod h1:gN/a0alGw1FZt/YGTo1G6Z6XpDkeOfujX5exY9sCQQM= -github.com/blevesearch/zapx/v11 v11.3.9 h1:y3ijS4h4MJdmQ07MHASxat4owAixreK2xdo76w9ncrw= -github.com/blevesearch/zapx/v11 v11.3.9/go.mod h1:jcAYnQwlr+LqD2vLjDWjWiZDXDXGFqPbpPDRTd3XmS4= +github.com/blevesearch/zapx/v11 v11.3.10 h1:hvjgj9tZ9DeIqBCxKhi70TtSZYMdcFn7gDb71Xo/fvk= +github.com/blevesearch/zapx/v11 v11.3.10/go.mod h1:0+gW+FaE48fNxoVtMY5ugtNHHof/PxCqh7CnhYdnMzQ= github.com/blevesearch/zapx/v12 v12.2.0/go.mod h1:fdjwvCwWWwJW/EYTYGtAp3gBA0geCYGLcVTtJEZnY6A= -github.com/blevesearch/zapx/v12 v12.3.9 h1:MXGLlZ03oxXH3DMJTZaBaRj2xb6t4wQVZeZK/wu1M6w= -github.com/blevesearch/zapx/v12 v12.3.9/go.mod h1:QXCMwmOkdLnMDgTN1P4CcuX5F851iUOtOwXbw0HMBYs= +github.com/blevesearch/zapx/v12 v12.3.10 h1:yHfj3vXLSYmmsBleJFROXuO08mS3L1qDCdDK81jDl8s= +github.com/blevesearch/zapx/v12 v12.3.10/go.mod h1:0yeZg6JhaGxITlsS5co73aqPtM04+ycnI6D1v0mhbCs= github.com/blevesearch/zapx/v13 v13.2.0/go.mod h1:o5rAy/lRS5JpAbITdrOHBS/TugWYbkcYZTz6VfEinAQ= -github.com/blevesearch/zapx/v13 v13.3.9 h1:+VAz9V0VmllHXlZV4DCvfYj0nqaZHgF3MeEHwOyRBwQ= -github.com/blevesearch/zapx/v13 v13.3.9/go.mod h1:s+WjNp4WSDtrBVBpa37DUOd7S/Gr/jTZ7ST/MbCVj/0= +github.com/blevesearch/zapx/v13 v13.3.10 h1:0KY9tuxg06rXxOZHg3DwPJBjniSlqEgVpxIqMGahDE8= +github.com/blevesearch/zapx/v13 v13.3.10/go.mod h1:w2wjSDQ/WBVeEIvP0fvMJZAzDwqwIEzVPnCPrz93yAk= github.com/blevesearch/zapx/v14 v14.2.0/go.mod h1:GNgZusc1p4ot040cBQMRGEZobvwjCquiEKYh1xLFK9g= -github.com/blevesearch/zapx/v14 v14.3.9 h1:wuqxATgsTCNHM9xsOFOeFp8H2heZ/gMX/tsl9lRK8U4= -github.com/blevesearch/zapx/v14 v14.3.9/go.mod h1:MWZ4v8AzFBRurhDzkLvokFW8ljcq9Evm27mkWe8OGbM= +github.com/blevesearch/zapx/v14 v14.3.10 h1:SG6xlsL+W6YjhX5N3aEiL/2tcWh3DO75Bnz77pSwwKU= +github.com/blevesearch/zapx/v14 v14.3.10/go.mod h1:qqyuR0u230jN1yMmE4FIAuCxmahRQEOehF78m6oTgns= github.com/blevesearch/zapx/v15 v15.2.0/go.mod h1:MmQceLpWfME4n1WrBFIwplhWmaQbQqLQARpaKUEOs/A= -github.com/blevesearch/zapx/v15 v15.3.12 h1:w/kU9aHyfMDEdwHGZzCiakC3HZ9z5gYlXaALDC4Dct8= -github.com/blevesearch/zapx/v15 v15.3.12/go.mod h1:tx53gDJS/7Oa3Je820cmVurqCuJ4dqdAy1kiDMV/IUo= +github.com/blevesearch/zapx/v15 v15.3.13 h1:6EkfaZiPlAxqXz0neniq35my6S48QI94W/wyhnpDHHQ= +github.com/blevesearch/zapx/v15 v15.3.13/go.mod h1:Turk/TNRKj9es7ZpKK95PS7f6D44Y7fAFy8F4LXQtGg= github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/boombuler/barcode v1.0.1 h1:NDBbPmhS+EqABEs5Kg3n/5ZNjy73Pz7SIV+KCeqyXcs= github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= From 5600504eed2473691b86962be2f9733e6bfce879 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 27 Sep 2023 16:15:12 +0800 Subject: [PATCH 13/22] Fix chinese translation (#27296) Fix translation from #27291 Source Map will be kept as English in Chinese usage habit. --- docs/content/installation/from-source.zh-cn.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/content/installation/from-source.zh-cn.md b/docs/content/installation/from-source.zh-cn.md index 74f76652db529..40a314340c617 100644 --- a/docs/content/installation/from-source.zh-cn.md +++ b/docs/content/installation/from-source.zh-cn.md @@ -220,10 +220,10 @@ TAGS="bindata sqlite sqlite_unlock_notify" \ make build ``` -## 源映射 +## Source Map -默认情况下,gitea 会为前端文件生成精简的源映射以节省空间。 这可以通过“ENABLE_SOURCEMAP”环境变量进行控制: +默认情况下,gitea 会为前端文件生成精简的 Source Map 以节省空间。 这可以通过“ENABLE_SOURCEMAP”环境变量进行控制: -- `ENABLE_SOURCEMAP=true` 生成所有源映射,这是开发版本的默认设置 -- `ENABLE_SOURCEMAP=reduced` 生成有限的源映射,这是生产版本的默认设置 -- `ENABLE_SOURCEMAP=false` 不生成源映射 +- `ENABLE_SOURCEMAP=true` 生成所有Source Map,这是开发版本的默认设置 +- `ENABLE_SOURCEMAP=reduced` 生成有限的Source Map,这是生产版本的默认设置 +- `ENABLE_SOURCEMAP=false` 不生成Source Map From 70f8d10fc5b1a5c8a80e5c05ef6e864154d9b272 Mon Sep 17 00:00:00 2001 From: Nanguan Lin <70063547+lng2020@users.noreply.github.com> Date: Wed, 27 Sep 2023 20:25:38 +0800 Subject: [PATCH 14/22] move the `gitea admin` subcommands into separate files (#27307) As title. Probably it's better to put those sub cmd to different dirs. Will do that in the future. --- cmd/admin.go | 617 +----------------------------------- cmd/admin_auth.go | 109 +++++++ cmd/admin_auth_ldap.go | 10 +- cmd/admin_auth_ldap_test.go | 8 +- cmd/admin_auth_oauth.go | 298 +++++++++++++++++ cmd/admin_auth_stmp.go | 201 ++++++++++++ cmd/admin_regenerate.go | 46 +++ 7 files changed, 670 insertions(+), 619 deletions(-) create mode 100644 cmd/admin_auth.go create mode 100644 cmd/admin_auth_oauth.go create mode 100644 cmd/admin_auth_stmp.go create mode 100644 cmd/admin_regenerate.go diff --git a/cmd/admin.go b/cmd/admin.go index d49dcf13cb0c9..49d0e4ef74aca 100644 --- a/cmd/admin.go +++ b/cmd/admin.go @@ -6,26 +6,13 @@ package cmd import ( "context" - "errors" "fmt" - "net/url" - "os" - "strings" - "text/tabwriter" - asymkey_model "code.gitea.io/gitea/models/asymkey" - auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" repo_module "code.gitea.io/gitea/modules/repository" - "code.gitea.io/gitea/modules/util" - auth_service "code.gitea.io/gitea/services/auth" - "code.gitea.io/gitea/services/auth/source/oauth2" - "code.gitea.io/gitea/services/auth/source/smtp" - repo_service "code.gitea.io/gitea/services/repository" "github.com/urfave/cli/v2" ) @@ -59,28 +46,16 @@ var ( }, } - microcmdRegenHooks = &cli.Command{ - Name: "hooks", - Usage: "Regenerate git-hooks", - Action: runRegenerateHooks, - } - - microcmdRegenKeys = &cli.Command{ - Name: "keys", - Usage: "Regenerate authorized_keys file", - Action: runRegenerateKeys, - } - subcmdAuth = &cli.Command{ Name: "auth", Usage: "Modify external auth providers", Subcommands: []*cli.Command{ microcmdAuthAddOauth, microcmdAuthUpdateOauth, - cmdAuthAddLdapBindDn, - cmdAuthUpdateLdapBindDn, - cmdAuthAddLdapSimpleAuth, - cmdAuthUpdateLdapSimpleAuth, + microcmdAuthAddLdapBindDn, + microcmdAuthUpdateLdapBindDn, + microcmdAuthAddLdapSimpleAuth, + microcmdAuthUpdateLdapSimpleAuth, microcmdAuthAddSMTP, microcmdAuthUpdateSMTP, microcmdAuthList, @@ -88,170 +63,6 @@ var ( }, } - microcmdAuthList = &cli.Command{ - Name: "list", - Usage: "List auth sources", - Action: runListAuth, - Flags: []cli.Flag{ - &cli.IntFlag{ - Name: "min-width", - Usage: "Minimal cell width including any padding for the formatted table", - Value: 0, - }, - &cli.IntFlag{ - Name: "tab-width", - Usage: "width of tab characters in formatted table (equivalent number of spaces)", - Value: 8, - }, - &cli.IntFlag{ - Name: "padding", - Usage: "padding added to a cell before computing its width", - Value: 1, - }, - &cli.StringFlag{ - Name: "pad-char", - Usage: `ASCII char used for padding if padchar == '\\t', the Writer will assume that the width of a '\\t' in the formatted output is tabwidth, and cells are left-aligned independent of align_left (for correct-looking results, tabwidth must correspond to the tab width in the viewer displaying the result)`, - Value: "\t", - }, - &cli.BoolFlag{ - Name: "vertical-bars", - Usage: "Set to true to print vertical bars between columns", - }, - }, - } - - idFlag = &cli.Int64Flag{ - Name: "id", - Usage: "ID of authentication source", - } - - microcmdAuthDelete = &cli.Command{ - Name: "delete", - Usage: "Delete specific auth source", - Flags: []cli.Flag{idFlag}, - Action: runDeleteAuth, - } - - oauthCLIFlags = []cli.Flag{ - &cli.StringFlag{ - Name: "name", - Value: "", - Usage: "Application Name", - }, - &cli.StringFlag{ - Name: "provider", - Value: "", - Usage: "OAuth2 Provider", - }, - &cli.StringFlag{ - Name: "key", - Value: "", - Usage: "Client ID (Key)", - }, - &cli.StringFlag{ - Name: "secret", - Value: "", - Usage: "Client Secret", - }, - &cli.StringFlag{ - Name: "auto-discover-url", - Value: "", - Usage: "OpenID Connect Auto Discovery URL (only required when using OpenID Connect as provider)", - }, - &cli.StringFlag{ - Name: "use-custom-urls", - Value: "false", - Usage: "Use custom URLs for GitLab/GitHub OAuth endpoints", - }, - &cli.StringFlag{ - Name: "custom-tenant-id", - Value: "", - Usage: "Use custom Tenant ID for OAuth endpoints", - }, - &cli.StringFlag{ - Name: "custom-auth-url", - Value: "", - Usage: "Use a custom Authorization URL (option for GitLab/GitHub)", - }, - &cli.StringFlag{ - Name: "custom-token-url", - Value: "", - Usage: "Use a custom Token URL (option for GitLab/GitHub)", - }, - &cli.StringFlag{ - Name: "custom-profile-url", - Value: "", - Usage: "Use a custom Profile URL (option for GitLab/GitHub)", - }, - &cli.StringFlag{ - Name: "custom-email-url", - Value: "", - Usage: "Use a custom Email URL (option for GitHub)", - }, - &cli.StringFlag{ - Name: "icon-url", - Value: "", - Usage: "Custom icon URL for OAuth2 login source", - }, - &cli.BoolFlag{ - Name: "skip-local-2fa", - Usage: "Set to true to skip local 2fa for users authenticated by this source", - }, - &cli.StringSliceFlag{ - Name: "scopes", - Value: nil, - Usage: "Scopes to request when to authenticate against this OAuth2 source", - }, - &cli.StringFlag{ - Name: "required-claim-name", - Value: "", - Usage: "Claim name that has to be set to allow users to login with this source", - }, - &cli.StringFlag{ - Name: "required-claim-value", - Value: "", - Usage: "Claim value that has to be set to allow users to login with this source", - }, - &cli.StringFlag{ - Name: "group-claim-name", - Value: "", - Usage: "Claim name providing group names for this source", - }, - &cli.StringFlag{ - Name: "admin-group", - Value: "", - Usage: "Group Claim value for administrator users", - }, - &cli.StringFlag{ - Name: "restricted-group", - Value: "", - Usage: "Group Claim value for restricted users", - }, - &cli.StringFlag{ - Name: "group-team-map", - Value: "", - Usage: "JSON mapping between groups and org teams", - }, - &cli.BoolFlag{ - Name: "group-team-map-removal", - Usage: "Activate automatic team membership removal depending on groups", - }, - } - - microcmdAuthUpdateOauth = &cli.Command{ - Name: "update-oauth", - Usage: "Update existing Oauth authentication source", - Action: runUpdateOauth, - Flags: append(oauthCLIFlags[:1], append([]cli.Flag{idFlag}, oauthCLIFlags[1:]...)...), - } - - microcmdAuthAddOauth = &cli.Command{ - Name: "add-oauth", - Usage: "Add new Oauth authentication source", - Action: runAddOauth, - Flags: oauthCLIFlags, - } - subcmdSendMail = &cli.Command{ Name: "sendmail", Usage: "Send a message to all users", @@ -275,75 +86,9 @@ var ( }, } - smtpCLIFlags = []cli.Flag{ - &cli.StringFlag{ - Name: "name", - Value: "", - Usage: "Application Name", - }, - &cli.StringFlag{ - Name: "auth-type", - Value: "PLAIN", - Usage: "SMTP Authentication Type (PLAIN/LOGIN/CRAM-MD5) default PLAIN", - }, - &cli.StringFlag{ - Name: "host", - Value: "", - Usage: "SMTP Host", - }, - &cli.IntFlag{ - Name: "port", - Usage: "SMTP Port", - }, - &cli.BoolFlag{ - Name: "force-smtps", - Usage: "SMTPS is always used on port 465. Set this to force SMTPS on other ports.", - Value: true, - }, - &cli.BoolFlag{ - Name: "skip-verify", - Usage: "Skip TLS verify.", - Value: true, - }, - &cli.StringFlag{ - Name: "helo-hostname", - Value: "", - Usage: "Hostname sent with HELO. Leave blank to send current hostname", - }, - &cli.BoolFlag{ - Name: "disable-helo", - Usage: "Disable SMTP helo.", - Value: true, - }, - &cli.StringFlag{ - Name: "allowed-domains", - Value: "", - Usage: "Leave empty to allow all domains. Separate multiple domains with a comma (',')", - }, - &cli.BoolFlag{ - Name: "skip-local-2fa", - Usage: "Skip 2FA to log on.", - Value: true, - }, - &cli.BoolFlag{ - Name: "active", - Usage: "This Authentication Source is Activated.", - Value: true, - }, - } - - microcmdAuthAddSMTP = &cli.Command{ - Name: "add-smtp", - Usage: "Add new SMTP authentication source", - Action: runAddSMTP, - Flags: smtpCLIFlags, - } - - microcmdAuthUpdateSMTP = &cli.Command{ - Name: "update-smtp", - Usage: "Update existing SMTP authentication source", - Action: runUpdateSMTP, - Flags: append(smtpCLIFlags[:1], append([]cli.Flag{idFlag}, smtpCLIFlags[1:]...)...), + idFlag = &cli.Int64Flag{ + Name: "id", + Usage: "ID of authentication source", } ) @@ -420,351 +165,3 @@ func getReleaseCount(ctx context.Context, id int64) (int64, error) { }, ) } - -func runRegenerateHooks(_ *cli.Context) error { - ctx, cancel := installSignals() - defer cancel() - - if err := initDB(ctx); err != nil { - return err - } - return repo_service.SyncRepositoryHooks(graceful.GetManager().ShutdownContext()) -} - -func runRegenerateKeys(_ *cli.Context) error { - ctx, cancel := installSignals() - defer cancel() - - if err := initDB(ctx); err != nil { - return err - } - return asymkey_model.RewriteAllPublicKeys(ctx) -} - -func parseOAuth2Config(c *cli.Context) *oauth2.Source { - var customURLMapping *oauth2.CustomURLMapping - if c.IsSet("use-custom-urls") { - customURLMapping = &oauth2.CustomURLMapping{ - TokenURL: c.String("custom-token-url"), - AuthURL: c.String("custom-auth-url"), - ProfileURL: c.String("custom-profile-url"), - EmailURL: c.String("custom-email-url"), - Tenant: c.String("custom-tenant-id"), - } - } else { - customURLMapping = nil - } - return &oauth2.Source{ - Provider: c.String("provider"), - ClientID: c.String("key"), - ClientSecret: c.String("secret"), - OpenIDConnectAutoDiscoveryURL: c.String("auto-discover-url"), - CustomURLMapping: customURLMapping, - IconURL: c.String("icon-url"), - SkipLocalTwoFA: c.Bool("skip-local-2fa"), - Scopes: c.StringSlice("scopes"), - RequiredClaimName: c.String("required-claim-name"), - RequiredClaimValue: c.String("required-claim-value"), - GroupClaimName: c.String("group-claim-name"), - AdminGroup: c.String("admin-group"), - RestrictedGroup: c.String("restricted-group"), - GroupTeamMap: c.String("group-team-map"), - GroupTeamMapRemoval: c.Bool("group-team-map-removal"), - } -} - -func runAddOauth(c *cli.Context) error { - ctx, cancel := installSignals() - defer cancel() - - if err := initDB(ctx); err != nil { - return err - } - - config := parseOAuth2Config(c) - if config.Provider == "openidConnect" { - discoveryURL, err := url.Parse(config.OpenIDConnectAutoDiscoveryURL) - if err != nil || (discoveryURL.Scheme != "http" && discoveryURL.Scheme != "https") { - return fmt.Errorf("invalid Auto Discovery URL: %s (this must be a valid URL starting with http:// or https://)", config.OpenIDConnectAutoDiscoveryURL) - } - } - - return auth_model.CreateSource(&auth_model.Source{ - Type: auth_model.OAuth2, - Name: c.String("name"), - IsActive: true, - Cfg: config, - }) -} - -func runUpdateOauth(c *cli.Context) error { - if !c.IsSet("id") { - return fmt.Errorf("--id flag is missing") - } - - ctx, cancel := installSignals() - defer cancel() - - if err := initDB(ctx); err != nil { - return err - } - - source, err := auth_model.GetSourceByID(c.Int64("id")) - if err != nil { - return err - } - - oAuth2Config := source.Cfg.(*oauth2.Source) - - if c.IsSet("name") { - source.Name = c.String("name") - } - - if c.IsSet("provider") { - oAuth2Config.Provider = c.String("provider") - } - - if c.IsSet("key") { - oAuth2Config.ClientID = c.String("key") - } - - if c.IsSet("secret") { - oAuth2Config.ClientSecret = c.String("secret") - } - - if c.IsSet("auto-discover-url") { - oAuth2Config.OpenIDConnectAutoDiscoveryURL = c.String("auto-discover-url") - } - - if c.IsSet("icon-url") { - oAuth2Config.IconURL = c.String("icon-url") - } - - if c.IsSet("scopes") { - oAuth2Config.Scopes = c.StringSlice("scopes") - } - - if c.IsSet("required-claim-name") { - oAuth2Config.RequiredClaimName = c.String("required-claim-name") - } - if c.IsSet("required-claim-value") { - oAuth2Config.RequiredClaimValue = c.String("required-claim-value") - } - - if c.IsSet("group-claim-name") { - oAuth2Config.GroupClaimName = c.String("group-claim-name") - } - if c.IsSet("admin-group") { - oAuth2Config.AdminGroup = c.String("admin-group") - } - if c.IsSet("restricted-group") { - oAuth2Config.RestrictedGroup = c.String("restricted-group") - } - if c.IsSet("group-team-map") { - oAuth2Config.GroupTeamMap = c.String("group-team-map") - } - if c.IsSet("group-team-map-removal") { - oAuth2Config.GroupTeamMapRemoval = c.Bool("group-team-map-removal") - } - - // update custom URL mapping - customURLMapping := &oauth2.CustomURLMapping{} - - if oAuth2Config.CustomURLMapping != nil { - customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL - customURLMapping.AuthURL = oAuth2Config.CustomURLMapping.AuthURL - customURLMapping.ProfileURL = oAuth2Config.CustomURLMapping.ProfileURL - customURLMapping.EmailURL = oAuth2Config.CustomURLMapping.EmailURL - customURLMapping.Tenant = oAuth2Config.CustomURLMapping.Tenant - } - if c.IsSet("use-custom-urls") && c.IsSet("custom-token-url") { - customURLMapping.TokenURL = c.String("custom-token-url") - } - - if c.IsSet("use-custom-urls") && c.IsSet("custom-auth-url") { - customURLMapping.AuthURL = c.String("custom-auth-url") - } - - if c.IsSet("use-custom-urls") && c.IsSet("custom-profile-url") { - customURLMapping.ProfileURL = c.String("custom-profile-url") - } - - if c.IsSet("use-custom-urls") && c.IsSet("custom-email-url") { - customURLMapping.EmailURL = c.String("custom-email-url") - } - - if c.IsSet("use-custom-urls") && c.IsSet("custom-tenant-id") { - customURLMapping.Tenant = c.String("custom-tenant-id") - } - - oAuth2Config.CustomURLMapping = customURLMapping - source.Cfg = oAuth2Config - - return auth_model.UpdateSource(source) -} - -func parseSMTPConfig(c *cli.Context, conf *smtp.Source) error { - if c.IsSet("auth-type") { - conf.Auth = c.String("auth-type") - validAuthTypes := []string{"PLAIN", "LOGIN", "CRAM-MD5"} - if !util.SliceContainsString(validAuthTypes, strings.ToUpper(c.String("auth-type"))) { - return errors.New("Auth must be one of PLAIN/LOGIN/CRAM-MD5") - } - conf.Auth = c.String("auth-type") - } - if c.IsSet("host") { - conf.Host = c.String("host") - } - if c.IsSet("port") { - conf.Port = c.Int("port") - } - if c.IsSet("allowed-domains") { - conf.AllowedDomains = c.String("allowed-domains") - } - if c.IsSet("force-smtps") { - conf.ForceSMTPS = c.Bool("force-smtps") - } - if c.IsSet("skip-verify") { - conf.SkipVerify = c.Bool("skip-verify") - } - if c.IsSet("helo-hostname") { - conf.HeloHostname = c.String("helo-hostname") - } - if c.IsSet("disable-helo") { - conf.DisableHelo = c.Bool("disable-helo") - } - if c.IsSet("skip-local-2fa") { - conf.SkipLocalTwoFA = c.Bool("skip-local-2fa") - } - return nil -} - -func runAddSMTP(c *cli.Context) error { - ctx, cancel := installSignals() - defer cancel() - - if err := initDB(ctx); err != nil { - return err - } - - if !c.IsSet("name") || len(c.String("name")) == 0 { - return errors.New("name must be set") - } - if !c.IsSet("host") || len(c.String("host")) == 0 { - return errors.New("host must be set") - } - if !c.IsSet("port") { - return errors.New("port must be set") - } - active := true - if c.IsSet("active") { - active = c.Bool("active") - } - - var smtpConfig smtp.Source - if err := parseSMTPConfig(c, &smtpConfig); err != nil { - return err - } - - // If not set default to PLAIN - if len(smtpConfig.Auth) == 0 { - smtpConfig.Auth = "PLAIN" - } - - return auth_model.CreateSource(&auth_model.Source{ - Type: auth_model.SMTP, - Name: c.String("name"), - IsActive: active, - Cfg: &smtpConfig, - }) -} - -func runUpdateSMTP(c *cli.Context) error { - if !c.IsSet("id") { - return fmt.Errorf("--id flag is missing") - } - - ctx, cancel := installSignals() - defer cancel() - - if err := initDB(ctx); err != nil { - return err - } - - source, err := auth_model.GetSourceByID(c.Int64("id")) - if err != nil { - return err - } - - smtpConfig := source.Cfg.(*smtp.Source) - - if err := parseSMTPConfig(c, smtpConfig); err != nil { - return err - } - - if c.IsSet("name") { - source.Name = c.String("name") - } - - if c.IsSet("active") { - source.IsActive = c.Bool("active") - } - - source.Cfg = smtpConfig - - return auth_model.UpdateSource(source) -} - -func runListAuth(c *cli.Context) error { - ctx, cancel := installSignals() - defer cancel() - - if err := initDB(ctx); err != nil { - return err - } - - authSources, err := auth_model.Sources() - if err != nil { - return err - } - - flags := tabwriter.AlignRight - if c.Bool("vertical-bars") { - flags |= tabwriter.Debug - } - - padChar := byte('\t') - if len(c.String("pad-char")) > 0 { - padChar = c.String("pad-char")[0] - } - - // loop through each source and print - w := tabwriter.NewWriter(os.Stdout, c.Int("min-width"), c.Int("tab-width"), c.Int("padding"), padChar, flags) - fmt.Fprintf(w, "ID\tName\tType\tEnabled\n") - for _, source := range authSources { - fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", source.ID, source.Name, source.Type.String(), source.IsActive) - } - w.Flush() - - return nil -} - -func runDeleteAuth(c *cli.Context) error { - if !c.IsSet("id") { - return fmt.Errorf("--id flag is missing") - } - - ctx, cancel := installSignals() - defer cancel() - - if err := initDB(ctx); err != nil { - return err - } - - source, err := auth_model.GetSourceByID(c.Int64("id")) - if err != nil { - return err - } - - return auth_service.DeleteSource(source) -} diff --git a/cmd/admin_auth.go b/cmd/admin_auth.go new file mode 100644 index 0000000000000..ef826a4893931 --- /dev/null +++ b/cmd/admin_auth.go @@ -0,0 +1,109 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package cmd + +import ( + "fmt" + "os" + "text/tabwriter" + + auth_model "code.gitea.io/gitea/models/auth" + auth_service "code.gitea.io/gitea/services/auth" + + "github.com/urfave/cli/v2" +) + +var ( + microcmdAuthDelete = &cli.Command{ + Name: "delete", + Usage: "Delete specific auth source", + Flags: []cli.Flag{idFlag}, + Action: runDeleteAuth, + } + microcmdAuthList = &cli.Command{ + Name: "list", + Usage: "List auth sources", + Action: runListAuth, + Flags: []cli.Flag{ + &cli.IntFlag{ + Name: "min-width", + Usage: "Minimal cell width including any padding for the formatted table", + Value: 0, + }, + &cli.IntFlag{ + Name: "tab-width", + Usage: "width of tab characters in formatted table (equivalent number of spaces)", + Value: 8, + }, + &cli.IntFlag{ + Name: "padding", + Usage: "padding added to a cell before computing its width", + Value: 1, + }, + &cli.StringFlag{ + Name: "pad-char", + Usage: `ASCII char used for padding if padchar == '\\t', the Writer will assume that the width of a '\\t' in the formatted output is tabwidth, and cells are left-aligned independent of align_left (for correct-looking results, tabwidth must correspond to the tab width in the viewer displaying the result)`, + Value: "\t", + }, + &cli.BoolFlag{ + Name: "vertical-bars", + Usage: "Set to true to print vertical bars between columns", + }, + }, + } +) + +func runListAuth(c *cli.Context) error { + ctx, cancel := installSignals() + defer cancel() + + if err := initDB(ctx); err != nil { + return err + } + + authSources, err := auth_model.Sources() + if err != nil { + return err + } + + flags := tabwriter.AlignRight + if c.Bool("vertical-bars") { + flags |= tabwriter.Debug + } + + padChar := byte('\t') + if len(c.String("pad-char")) > 0 { + padChar = c.String("pad-char")[0] + } + + // loop through each source and print + w := tabwriter.NewWriter(os.Stdout, c.Int("min-width"), c.Int("tab-width"), c.Int("padding"), padChar, flags) + fmt.Fprintf(w, "ID\tName\tType\tEnabled\n") + for _, source := range authSources { + fmt.Fprintf(w, "%d\t%s\t%s\t%t\n", source.ID, source.Name, source.Type.String(), source.IsActive) + } + w.Flush() + + return nil +} + +func runDeleteAuth(c *cli.Context) error { + if !c.IsSet("id") { + return fmt.Errorf("--id flag is missing") + } + + ctx, cancel := installSignals() + defer cancel() + + if err := initDB(ctx); err != nil { + return err + } + + source, err := auth_model.GetSourceByID(c.Int64("id")) + if err != nil { + return err + } + + return auth_service.DeleteSource(source) +} diff --git a/cmd/admin_auth_ldap.go b/cmd/admin_auth_ldap.go index cfa1a232353bd..111bc7955cc11 100644 --- a/cmd/admin_auth_ldap.go +++ b/cmd/admin_auth_ldap.go @@ -132,10 +132,10 @@ var ( ldapSimpleAuthCLIFlags = append(commonLdapCLIFlags, &cli.StringFlag{ Name: "user-dn", - Usage: "The user’s DN.", + Usage: "The user's DN.", }) - cmdAuthAddLdapBindDn = &cli.Command{ + microcmdAuthAddLdapBindDn = &cli.Command{ Name: "add-ldap", Usage: "Add new LDAP (via Bind DN) authentication source", Action: func(c *cli.Context) error { @@ -144,7 +144,7 @@ var ( Flags: ldapBindDnCLIFlags, } - cmdAuthUpdateLdapBindDn = &cli.Command{ + microcmdAuthUpdateLdapBindDn = &cli.Command{ Name: "update-ldap", Usage: "Update existing LDAP (via Bind DN) authentication source", Action: func(c *cli.Context) error { @@ -153,7 +153,7 @@ var ( Flags: append([]cli.Flag{idFlag}, ldapBindDnCLIFlags...), } - cmdAuthAddLdapSimpleAuth = &cli.Command{ + microcmdAuthAddLdapSimpleAuth = &cli.Command{ Name: "add-ldap-simple", Usage: "Add new LDAP (simple auth) authentication source", Action: func(c *cli.Context) error { @@ -162,7 +162,7 @@ var ( Flags: ldapSimpleAuthCLIFlags, } - cmdAuthUpdateLdapSimpleAuth = &cli.Command{ + microcmdAuthUpdateLdapSimpleAuth = &cli.Command{ Name: "update-ldap-simple", Usage: "Update existing LDAP (simple auth) authentication source", Action: func(c *cli.Context) error { diff --git a/cmd/admin_auth_ldap_test.go b/cmd/admin_auth_ldap_test.go index 210a6463c3182..228c9dd3ed27a 100644 --- a/cmd/admin_auth_ldap_test.go +++ b/cmd/admin_auth_ldap_test.go @@ -226,7 +226,7 @@ func TestAddLdapBindDn(t *testing.T) { // Create a copy of command to test app := cli.NewApp() - app.Flags = cmdAuthAddLdapBindDn.Flags + app.Flags = microcmdAuthAddLdapBindDn.Flags app.Action = service.addLdapBindDn // Run it @@ -457,7 +457,7 @@ func TestAddLdapSimpleAuth(t *testing.T) { // Create a copy of command to test app := cli.NewApp() - app.Flags = cmdAuthAddLdapSimpleAuth.Flags + app.Flags = microcmdAuthAddLdapSimpleAuth.Flags app.Action = service.addLdapSimpleAuth // Run it @@ -920,7 +920,7 @@ func TestUpdateLdapBindDn(t *testing.T) { // Create a copy of command to test app := cli.NewApp() - app.Flags = cmdAuthUpdateLdapBindDn.Flags + app.Flags = microcmdAuthUpdateLdapBindDn.Flags app.Action = service.updateLdapBindDn // Run it @@ -1310,7 +1310,7 @@ func TestUpdateLdapSimpleAuth(t *testing.T) { // Create a copy of command to test app := cli.NewApp() - app.Flags = cmdAuthUpdateLdapSimpleAuth.Flags + app.Flags = microcmdAuthUpdateLdapSimpleAuth.Flags app.Action = service.updateLdapSimpleAuth // Run it diff --git a/cmd/admin_auth_oauth.go b/cmd/admin_auth_oauth.go new file mode 100644 index 0000000000000..cc54ac9454b27 --- /dev/null +++ b/cmd/admin_auth_oauth.go @@ -0,0 +1,298 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package cmd + +import ( + "fmt" + "net/url" + + auth_model "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/services/auth/source/oauth2" + + "github.com/urfave/cli/v2" +) + +var ( + oauthCLIFlags = []cli.Flag{ + &cli.StringFlag{ + Name: "name", + Value: "", + Usage: "Application Name", + }, + &cli.StringFlag{ + Name: "provider", + Value: "", + Usage: "OAuth2 Provider", + }, + &cli.StringFlag{ + Name: "key", + Value: "", + Usage: "Client ID (Key)", + }, + &cli.StringFlag{ + Name: "secret", + Value: "", + Usage: "Client Secret", + }, + &cli.StringFlag{ + Name: "auto-discover-url", + Value: "", + Usage: "OpenID Connect Auto Discovery URL (only required when using OpenID Connect as provider)", + }, + &cli.StringFlag{ + Name: "use-custom-urls", + Value: "false", + Usage: "Use custom URLs for GitLab/GitHub OAuth endpoints", + }, + &cli.StringFlag{ + Name: "custom-tenant-id", + Value: "", + Usage: "Use custom Tenant ID for OAuth endpoints", + }, + &cli.StringFlag{ + Name: "custom-auth-url", + Value: "", + Usage: "Use a custom Authorization URL (option for GitLab/GitHub)", + }, + &cli.StringFlag{ + Name: "custom-token-url", + Value: "", + Usage: "Use a custom Token URL (option for GitLab/GitHub)", + }, + &cli.StringFlag{ + Name: "custom-profile-url", + Value: "", + Usage: "Use a custom Profile URL (option for GitLab/GitHub)", + }, + &cli.StringFlag{ + Name: "custom-email-url", + Value: "", + Usage: "Use a custom Email URL (option for GitHub)", + }, + &cli.StringFlag{ + Name: "icon-url", + Value: "", + Usage: "Custom icon URL for OAuth2 login source", + }, + &cli.BoolFlag{ + Name: "skip-local-2fa", + Usage: "Set to true to skip local 2fa for users authenticated by this source", + }, + &cli.StringSliceFlag{ + Name: "scopes", + Value: nil, + Usage: "Scopes to request when to authenticate against this OAuth2 source", + }, + &cli.StringFlag{ + Name: "required-claim-name", + Value: "", + Usage: "Claim name that has to be set to allow users to login with this source", + }, + &cli.StringFlag{ + Name: "required-claim-value", + Value: "", + Usage: "Claim value that has to be set to allow users to login with this source", + }, + &cli.StringFlag{ + Name: "group-claim-name", + Value: "", + Usage: "Claim name providing group names for this source", + }, + &cli.StringFlag{ + Name: "admin-group", + Value: "", + Usage: "Group Claim value for administrator users", + }, + &cli.StringFlag{ + Name: "restricted-group", + Value: "", + Usage: "Group Claim value for restricted users", + }, + &cli.StringFlag{ + Name: "group-team-map", + Value: "", + Usage: "JSON mapping between groups and org teams", + }, + &cli.BoolFlag{ + Name: "group-team-map-removal", + Usage: "Activate automatic team membership removal depending on groups", + }, + } + + microcmdAuthAddOauth = &cli.Command{ + Name: "add-oauth", + Usage: "Add new Oauth authentication source", + Action: runAddOauth, + Flags: oauthCLIFlags, + } + + microcmdAuthUpdateOauth = &cli.Command{ + Name: "update-oauth", + Usage: "Update existing Oauth authentication source", + Action: runUpdateOauth, + Flags: append(oauthCLIFlags[:1], append([]cli.Flag{idFlag}, oauthCLIFlags[1:]...)...), + } +) + +func parseOAuth2Config(c *cli.Context) *oauth2.Source { + var customURLMapping *oauth2.CustomURLMapping + if c.IsSet("use-custom-urls") { + customURLMapping = &oauth2.CustomURLMapping{ + TokenURL: c.String("custom-token-url"), + AuthURL: c.String("custom-auth-url"), + ProfileURL: c.String("custom-profile-url"), + EmailURL: c.String("custom-email-url"), + Tenant: c.String("custom-tenant-id"), + } + } else { + customURLMapping = nil + } + return &oauth2.Source{ + Provider: c.String("provider"), + ClientID: c.String("key"), + ClientSecret: c.String("secret"), + OpenIDConnectAutoDiscoveryURL: c.String("auto-discover-url"), + CustomURLMapping: customURLMapping, + IconURL: c.String("icon-url"), + SkipLocalTwoFA: c.Bool("skip-local-2fa"), + Scopes: c.StringSlice("scopes"), + RequiredClaimName: c.String("required-claim-name"), + RequiredClaimValue: c.String("required-claim-value"), + GroupClaimName: c.String("group-claim-name"), + AdminGroup: c.String("admin-group"), + RestrictedGroup: c.String("restricted-group"), + GroupTeamMap: c.String("group-team-map"), + GroupTeamMapRemoval: c.Bool("group-team-map-removal"), + } +} + +func runAddOauth(c *cli.Context) error { + ctx, cancel := installSignals() + defer cancel() + + if err := initDB(ctx); err != nil { + return err + } + + config := parseOAuth2Config(c) + if config.Provider == "openidConnect" { + discoveryURL, err := url.Parse(config.OpenIDConnectAutoDiscoveryURL) + if err != nil || (discoveryURL.Scheme != "http" && discoveryURL.Scheme != "https") { + return fmt.Errorf("invalid Auto Discovery URL: %s (this must be a valid URL starting with http:// or https://)", config.OpenIDConnectAutoDiscoveryURL) + } + } + + return auth_model.CreateSource(&auth_model.Source{ + Type: auth_model.OAuth2, + Name: c.String("name"), + IsActive: true, + Cfg: config, + }) +} + +func runUpdateOauth(c *cli.Context) error { + if !c.IsSet("id") { + return fmt.Errorf("--id flag is missing") + } + + ctx, cancel := installSignals() + defer cancel() + + if err := initDB(ctx); err != nil { + return err + } + + source, err := auth_model.GetSourceByID(c.Int64("id")) + if err != nil { + return err + } + + oAuth2Config := source.Cfg.(*oauth2.Source) + + if c.IsSet("name") { + source.Name = c.String("name") + } + + if c.IsSet("provider") { + oAuth2Config.Provider = c.String("provider") + } + + if c.IsSet("key") { + oAuth2Config.ClientID = c.String("key") + } + + if c.IsSet("secret") { + oAuth2Config.ClientSecret = c.String("secret") + } + + if c.IsSet("auto-discover-url") { + oAuth2Config.OpenIDConnectAutoDiscoveryURL = c.String("auto-discover-url") + } + + if c.IsSet("icon-url") { + oAuth2Config.IconURL = c.String("icon-url") + } + + if c.IsSet("scopes") { + oAuth2Config.Scopes = c.StringSlice("scopes") + } + + if c.IsSet("required-claim-name") { + oAuth2Config.RequiredClaimName = c.String("required-claim-name") + } + if c.IsSet("required-claim-value") { + oAuth2Config.RequiredClaimValue = c.String("required-claim-value") + } + + if c.IsSet("group-claim-name") { + oAuth2Config.GroupClaimName = c.String("group-claim-name") + } + if c.IsSet("admin-group") { + oAuth2Config.AdminGroup = c.String("admin-group") + } + if c.IsSet("restricted-group") { + oAuth2Config.RestrictedGroup = c.String("restricted-group") + } + if c.IsSet("group-team-map") { + oAuth2Config.GroupTeamMap = c.String("group-team-map") + } + if c.IsSet("group-team-map-removal") { + oAuth2Config.GroupTeamMapRemoval = c.Bool("group-team-map-removal") + } + + // update custom URL mapping + customURLMapping := &oauth2.CustomURLMapping{} + + if oAuth2Config.CustomURLMapping != nil { + customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL + customURLMapping.AuthURL = oAuth2Config.CustomURLMapping.AuthURL + customURLMapping.ProfileURL = oAuth2Config.CustomURLMapping.ProfileURL + customURLMapping.EmailURL = oAuth2Config.CustomURLMapping.EmailURL + customURLMapping.Tenant = oAuth2Config.CustomURLMapping.Tenant + } + if c.IsSet("use-custom-urls") && c.IsSet("custom-token-url") { + customURLMapping.TokenURL = c.String("custom-token-url") + } + + if c.IsSet("use-custom-urls") && c.IsSet("custom-auth-url") { + customURLMapping.AuthURL = c.String("custom-auth-url") + } + + if c.IsSet("use-custom-urls") && c.IsSet("custom-profile-url") { + customURLMapping.ProfileURL = c.String("custom-profile-url") + } + + if c.IsSet("use-custom-urls") && c.IsSet("custom-email-url") { + customURLMapping.EmailURL = c.String("custom-email-url") + } + + if c.IsSet("use-custom-urls") && c.IsSet("custom-tenant-id") { + customURLMapping.Tenant = c.String("custom-tenant-id") + } + + oAuth2Config.CustomURLMapping = customURLMapping + source.Cfg = oAuth2Config + + return auth_model.UpdateSource(source) +} diff --git a/cmd/admin_auth_stmp.go b/cmd/admin_auth_stmp.go new file mode 100644 index 0000000000000..8c65de8a1b66d --- /dev/null +++ b/cmd/admin_auth_stmp.go @@ -0,0 +1,201 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package cmd + +import ( + "errors" + "fmt" + "strings" + + auth_model "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/modules/util" + "code.gitea.io/gitea/services/auth/source/smtp" + + "github.com/urfave/cli/v2" +) + +var ( + smtpCLIFlags = []cli.Flag{ + &cli.StringFlag{ + Name: "name", + Value: "", + Usage: "Application Name", + }, + &cli.StringFlag{ + Name: "auth-type", + Value: "PLAIN", + Usage: "SMTP Authentication Type (PLAIN/LOGIN/CRAM-MD5) default PLAIN", + }, + &cli.StringFlag{ + Name: "host", + Value: "", + Usage: "SMTP Host", + }, + &cli.IntFlag{ + Name: "port", + Usage: "SMTP Port", + }, + &cli.BoolFlag{ + Name: "force-smtps", + Usage: "SMTPS is always used on port 465. Set this to force SMTPS on other ports.", + Value: true, + }, + &cli.BoolFlag{ + Name: "skip-verify", + Usage: "Skip TLS verify.", + Value: true, + }, + &cli.StringFlag{ + Name: "helo-hostname", + Value: "", + Usage: "Hostname sent with HELO. Leave blank to send current hostname", + }, + &cli.BoolFlag{ + Name: "disable-helo", + Usage: "Disable SMTP helo.", + Value: true, + }, + &cli.StringFlag{ + Name: "allowed-domains", + Value: "", + Usage: "Leave empty to allow all domains. Separate multiple domains with a comma (',')", + }, + &cli.BoolFlag{ + Name: "skip-local-2fa", + Usage: "Skip 2FA to log on.", + Value: true, + }, + &cli.BoolFlag{ + Name: "active", + Usage: "This Authentication Source is Activated.", + Value: true, + }, + } + + microcmdAuthAddSMTP = &cli.Command{ + Name: "add-smtp", + Usage: "Add new SMTP authentication source", + Action: runAddSMTP, + Flags: smtpCLIFlags, + } + + microcmdAuthUpdateSMTP = &cli.Command{ + Name: "update-smtp", + Usage: "Update existing SMTP authentication source", + Action: runUpdateSMTP, + Flags: append(smtpCLIFlags[:1], append([]cli.Flag{idFlag}, smtpCLIFlags[1:]...)...), + } +) + +func parseSMTPConfig(c *cli.Context, conf *smtp.Source) error { + if c.IsSet("auth-type") { + conf.Auth = c.String("auth-type") + validAuthTypes := []string{"PLAIN", "LOGIN", "CRAM-MD5"} + if !util.SliceContainsString(validAuthTypes, strings.ToUpper(c.String("auth-type"))) { + return errors.New("Auth must be one of PLAIN/LOGIN/CRAM-MD5") + } + conf.Auth = c.String("auth-type") + } + if c.IsSet("host") { + conf.Host = c.String("host") + } + if c.IsSet("port") { + conf.Port = c.Int("port") + } + if c.IsSet("allowed-domains") { + conf.AllowedDomains = c.String("allowed-domains") + } + if c.IsSet("force-smtps") { + conf.ForceSMTPS = c.Bool("force-smtps") + } + if c.IsSet("skip-verify") { + conf.SkipVerify = c.Bool("skip-verify") + } + if c.IsSet("helo-hostname") { + conf.HeloHostname = c.String("helo-hostname") + } + if c.IsSet("disable-helo") { + conf.DisableHelo = c.Bool("disable-helo") + } + if c.IsSet("skip-local-2fa") { + conf.SkipLocalTwoFA = c.Bool("skip-local-2fa") + } + return nil +} + +func runAddSMTP(c *cli.Context) error { + ctx, cancel := installSignals() + defer cancel() + + if err := initDB(ctx); err != nil { + return err + } + + if !c.IsSet("name") || len(c.String("name")) == 0 { + return errors.New("name must be set") + } + if !c.IsSet("host") || len(c.String("host")) == 0 { + return errors.New("host must be set") + } + if !c.IsSet("port") { + return errors.New("port must be set") + } + active := true + if c.IsSet("active") { + active = c.Bool("active") + } + + var smtpConfig smtp.Source + if err := parseSMTPConfig(c, &smtpConfig); err != nil { + return err + } + + // If not set default to PLAIN + if len(smtpConfig.Auth) == 0 { + smtpConfig.Auth = "PLAIN" + } + + return auth_model.CreateSource(&auth_model.Source{ + Type: auth_model.SMTP, + Name: c.String("name"), + IsActive: active, + Cfg: &smtpConfig, + }) +} + +func runUpdateSMTP(c *cli.Context) error { + if !c.IsSet("id") { + return fmt.Errorf("--id flag is missing") + } + + ctx, cancel := installSignals() + defer cancel() + + if err := initDB(ctx); err != nil { + return err + } + + source, err := auth_model.GetSourceByID(c.Int64("id")) + if err != nil { + return err + } + + smtpConfig := source.Cfg.(*smtp.Source) + + if err := parseSMTPConfig(c, smtpConfig); err != nil { + return err + } + + if c.IsSet("name") { + source.Name = c.String("name") + } + + if c.IsSet("active") { + source.IsActive = c.Bool("active") + } + + source.Cfg = smtpConfig + + return auth_model.UpdateSource(source) +} diff --git a/cmd/admin_regenerate.go b/cmd/admin_regenerate.go new file mode 100644 index 0000000000000..0db505ff9c7ef --- /dev/null +++ b/cmd/admin_regenerate.go @@ -0,0 +1,46 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package cmd + +import ( + asymkey_model "code.gitea.io/gitea/models/asymkey" + "code.gitea.io/gitea/modules/graceful" + repo_service "code.gitea.io/gitea/services/repository" + + "github.com/urfave/cli/v2" +) + +var ( + microcmdRegenHooks = &cli.Command{ + Name: "hooks", + Usage: "Regenerate git-hooks", + Action: runRegenerateHooks, + } + + microcmdRegenKeys = &cli.Command{ + Name: "keys", + Usage: "Regenerate authorized_keys file", + Action: runRegenerateKeys, + } +) + +func runRegenerateHooks(_ *cli.Context) error { + ctx, cancel := installSignals() + defer cancel() + + if err := initDB(ctx); err != nil { + return err + } + return repo_service.SyncRepositoryHooks(graceful.GetManager().ShutdownContext()) +} + +func runRegenerateKeys(_ *cli.Context) error { + ctx, cancel := installSignals() + defer cancel() + + if err := initDB(ctx); err != nil { + return err + } + return asymkey_model.RewriteAllPublicKeys(ctx) +} From e5e1d842c0f2b59b15c05b246a0abd0389f12efa Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Thu, 28 Sep 2023 07:21:31 +0900 Subject: [PATCH 15/22] Fix protected branch icon location (#26576) --- templates/repo/branch/list.tmpl | 16 ++++++++-------- templates/repo/commit_status.tmpl | 2 ++ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/templates/repo/branch/list.tmpl b/templates/repo/branch/list.tmpl index 36d1b628c9df5..f554c851d3692 100644 --- a/templates/repo/branch/list.tmpl +++ b/templates/repo/branch/list.tmpl @@ -19,12 +19,12 @@ - {{if .DefaultBranchBranch.IsProtected}} - {{svg "octicon-shield-lock"}} - {{end}}
+ {{if .DefaultBranchBranch.IsProtected}} + {{svg "octicon-shield-lock"}} + {{end}} {{.DefaultBranchBranch.DBBranch.Name}} - + {{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DefaultBranchBranch.DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DefaultBranchBranch.DBBranch.CommitID)}}

{{svg "octicon-git-commit" 16 "gt-mr-2"}}{{ShortSha .DefaultBranchBranch.DBBranch.CommitID}} · {{RenderCommitMessage $.Context .DefaultBranchBranch.DBBranch.CommitMessage .RepoLink .Repository.ComposeMetas}} · {{ctx.Locale.Tr "org.repo_updated"}} {{TimeSince .DefaultBranchBranch.DBBranch.CommitTime.AsTime ctx.Locale}}{{if .DefaultBranchBranch.DBBranch.Pusher}}  {{template "shared/user/avatarlink" dict "user" .DefaultBranchBranch.DBBranch.Pusher}}{{template "shared/user/namelink" .DefaultBranchBranch.DBBranch.Pusher}}{{end}}

@@ -97,12 +97,12 @@

{{ctx.Locale.Tr "repo.branch.deleted_by" .DBBranch.DeletedBy.Name}} {{TimeSinceUnix .DBBranch.DeletedUnix ctx.Locale}}

{{else}} - {{if .IsProtected}} - {{svg "octicon-shield-lock"}} - {{end}}
+ {{if .IsProtected}} + {{svg "octicon-shield-lock"}} + {{end}} {{.DBBranch.Name}} - + {{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DBBranch.CommitID)}}

{{svg "octicon-git-commit" 16 "gt-mr-2"}}{{ShortSha .DBBranch.CommitID}} · {{RenderCommitMessage $.Context .DBBranch.CommitMessage $.RepoLink $.Repository.ComposeMetas}} · {{ctx.Locale.Tr "org.repo_updated"}} {{TimeSince .DBBranch.CommitTime.AsTime ctx.Locale}}{{if .DBBranch.Pusher}}  {{template "shared/user/avatarlink" dict "user" .DBBranch.Pusher}}  {{template "shared/user/namelink" .DBBranch.Pusher}}{{end}}

diff --git a/templates/repo/commit_status.tmpl b/templates/repo/commit_status.tmpl index ebd8a55f65e38..3dc1da61d3c4e 100644 --- a/templates/repo/commit_status.tmpl +++ b/templates/repo/commit_status.tmpl @@ -1,4 +1,5 @@ + {{if eq .State "pending"}} {{svg "octicon-dot-fill" 18 "commit-status icon text yellow"}} {{end}} @@ -11,3 +12,4 @@ {{if eq .State "failure"}} {{svg "octicon-x" 18 "commit-status icon text red"}} {{end}} + From e74a3b18afdbe9bbf56b8f845c915c13894d15c3 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Thu, 28 Sep 2023 00:22:57 +0000 Subject: [PATCH 16/22] [skip ci] Updated translations via Crowdin --- options/locale/locale_ja-JP.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index b760fb6b4d9cb..940ff5116818e 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -80,6 +80,7 @@ milestones=マイルストーン ok=OK cancel=キャンセル +retry=再試行 rerun=再実行 rerun_all=すべてのジョブを再実行 save=保存 From 673cf6af763fe7fd4301382f7b059b0799fca396 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 28 Sep 2023 09:38:53 +0800 Subject: [PATCH 17/22] make writing main test easier (#27270) This PR removed `unittest.MainTest` the second parameter `TestOptions.GiteaRoot`. Now it detects the root directory by current working directory. --------- Co-authored-by: wxiaoguang --- cmd/main_test.go | 4 +- models/activities/main_test.go | 5 +- models/asymkey/main_test.go | 2 - models/auth/main_test.go | 5 +- models/avatars/main_test.go | 5 +- models/db/main_test.go | 5 +- models/db/paginator/main_test.go | 5 +- models/dbfs/main_test.go | 5 +- models/git/main_test.go | 5 +- models/issues/main_test.go | 5 +- models/main_test.go | 4 +- models/organization/main_test.go | 5 +- models/packages/package_test.go | 5 +- models/perm/access/main_test.go | 5 +- models/project/main_test.go | 2 - models/repo/main_test.go | 5 +- models/system/main_test.go | 5 +- models/unittest/testdb.go | 53 +++++++++++-------- models/user/main_test.go | 5 +- models/webhook/main_test.go | 2 - modules/activitypub/main_test.go | 5 +- modules/indexer/code/indexer_test.go | 5 +- modules/indexer/issues/indexer_test.go | 5 +- modules/indexer/stats/indexer_test.go | 5 +- modules/repository/main_test.go | 5 +- modules/system/appstate_test.go | 4 +- routers/api/v1/repo/main_test.go | 2 - routers/common/errpage_test.go | 5 +- routers/install/routes_test.go | 5 +- routers/private/main_test.go | 5 +- routers/web/admin/main_test.go | 5 +- routers/web/auth/main_test.go | 5 +- routers/web/org/main_test.go | 5 +- routers/web/repo/main_test.go | 5 +- routers/web/repo/setting/main_test.go | 5 +- routers/web/user/main_test.go | 5 +- routers/web/user/setting/main_test.go | 5 +- services/asymkey/main_test.go | 5 +- services/attachment/attachment_test.go | 4 +- services/convert/main_test.go | 5 +- services/feed/action_test.go | 5 +- services/gitdiff/main_test.go | 5 +- services/issue/main_test.go | 5 +- services/mailer/main_test.go | 5 +- services/markup/main_test.go | 4 +- services/migrations/main_test.go | 5 +- services/org/org_test.go | 5 +- services/pull/main_test.go | 5 +- services/release/release_test.go | 5 +- services/repository/archiver/archiver_test.go | 5 +- services/repository/files/content_test.go | 5 +- services/repository/main_test.go | 5 +- services/user/user_test.go | 5 +- services/webhook/main_test.go | 2 - services/wiki/wiki_test.go | 5 +- 55 files changed, 81 insertions(+), 222 deletions(-) diff --git a/cmd/main_test.go b/cmd/main_test.go index 0e32dce564872..a916c61f853d2 100644 --- a/cmd/main_test.go +++ b/cmd/main_test.go @@ -20,9 +20,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: "..", - }) + unittest.MainTest(m) } func makePathOutput(workPath, customPath, customConf string) string { diff --git a/models/activities/main_test.go b/models/activities/main_test.go index 6be54db658b87..43afb84ef15ac 100644 --- a/models/activities/main_test.go +++ b/models/activities/main_test.go @@ -4,7 +4,6 @@ package activities_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -14,7 +13,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/asymkey/main_test.go b/models/asymkey/main_test.go index 701722be12ec8..be71f848d9d8d 100644 --- a/models/asymkey/main_test.go +++ b/models/asymkey/main_test.go @@ -4,7 +4,6 @@ package asymkey import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -12,7 +11,6 @@ import ( func TestMain(m *testing.M) { unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), FixtureFiles: []string{ "gpg_key.yml", "public_key.yml", diff --git a/models/auth/main_test.go b/models/auth/main_test.go index f8cbf3bd54619..d772ea6b1c8b5 100644 --- a/models/auth/main_test.go +++ b/models/auth/main_test.go @@ -4,7 +4,6 @@ package auth_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -17,7 +16,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/avatars/main_test.go b/models/avatars/main_test.go index 6507632717792..c721a7dc2ac1d 100644 --- a/models/avatars/main_test.go +++ b/models/avatars/main_test.go @@ -4,7 +4,6 @@ package avatars_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -15,7 +14,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/db/main_test.go b/models/db/main_test.go index ce48502918573..7d80b400fe53d 100644 --- a/models/db/main_test.go +++ b/models/db/main_test.go @@ -4,7 +4,6 @@ package db_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -14,7 +13,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/db/paginator/main_test.go b/models/db/paginator/main_test.go index b0557bc5a4a9a..47993aed6be66 100644 --- a/models/db/paginator/main_test.go +++ b/models/db/paginator/main_test.go @@ -4,14 +4,11 @@ package paginator import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/dbfs/main_test.go b/models/dbfs/main_test.go index 62db3592bed2a..537ba0935d646 100644 --- a/models/dbfs/main_test.go +++ b/models/dbfs/main_test.go @@ -4,14 +4,11 @@ package dbfs import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/git/main_test.go b/models/git/main_test.go index a8658d70c4cd1..aab1fa9a26f40 100644 --- a/models/git/main_test.go +++ b/models/git/main_test.go @@ -4,7 +4,6 @@ package git_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -15,7 +14,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/issues/main_test.go b/models/issues/main_test.go index 190df027f4f27..ba83ca555240b 100644 --- a/models/issues/main_test.go +++ b/models/issues/main_test.go @@ -4,7 +4,6 @@ package issues_test import ( - "path/filepath" "testing" issues_model "code.gitea.io/gitea/models/issues" @@ -30,7 +29,5 @@ func TestFixturesAreConsistent(t *testing.T) { } func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/main_test.go b/models/main_test.go index c09b661d2c241..600dcc889b7b6 100644 --- a/models/main_test.go +++ b/models/main_test.go @@ -29,7 +29,5 @@ func TestFixturesAreConsistent(t *testing.T) { } func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: "..", - }) + unittest.MainTest(m) } diff --git a/models/organization/main_test.go b/models/organization/main_test.go index bc5bde2565c27..c35898a465dc2 100644 --- a/models/organization/main_test.go +++ b/models/organization/main_test.go @@ -4,7 +4,6 @@ package organization_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -18,7 +17,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/packages/package_test.go b/models/packages/package_test.go index 525a9f08d62c5..7f03151e7745c 100644 --- a/models/packages/package_test.go +++ b/models/packages/package_test.go @@ -4,7 +4,6 @@ package packages_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/db" @@ -20,9 +19,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } func TestHasOwnerPackages(t *testing.T) { diff --git a/models/perm/access/main_test.go b/models/perm/access/main_test.go index 8102cae49647b..0a350dc41eab5 100644 --- a/models/perm/access/main_test.go +++ b/models/perm/access/main_test.go @@ -4,7 +4,6 @@ package access_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -17,7 +16,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/project/main_test.go b/models/project/main_test.go index 816cbeb94a045..f4b2d6fedac24 100644 --- a/models/project/main_test.go +++ b/models/project/main_test.go @@ -4,7 +4,6 @@ package project import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -14,7 +13,6 @@ import ( func TestMain(m *testing.M) { unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), FixtureFiles: []string{ "project.yml", "project_board.yml", diff --git a/models/repo/main_test.go b/models/repo/main_test.go index ff97c7ac9ef88..b49855f2c866d 100644 --- a/models/repo/main_test.go +++ b/models/repo/main_test.go @@ -4,7 +4,6 @@ package repo_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -18,7 +17,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/system/main_test.go b/models/system/main_test.go index e074abc1551a4..6bc27a7cff8b3 100644 --- a/models/system/main_test.go +++ b/models/system/main_test.go @@ -4,7 +4,6 @@ package system_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -16,7 +15,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/unittest/testdb.go b/models/unittest/testdb.go index 1ff0fdc25bda8..6db99cd393e57 100644 --- a/models/unittest/testdb.go +++ b/models/unittest/testdb.go @@ -62,35 +62,46 @@ func InitSettings(extraConfigs ...string) { // TestOptions represents test options type TestOptions struct { - GiteaRootPath string - FixtureFiles []string - SetUp func() error // SetUp will be executed before all tests in this package - TearDown func() error // TearDown will be executed after all tests in this package + FixtureFiles []string + SetUp func() error // SetUp will be executed before all tests in this package + TearDown func() error // TearDown will be executed after all tests in this package } // MainTest a reusable TestMain(..) function for unit tests that need to use a // test database. Creates the test database, and sets necessary settings. -func MainTest(m *testing.M, testOpts *TestOptions) { - setting.CustomPath = filepath.Join(testOpts.GiteaRootPath, "custom") - InitSettings() - - var err error +func MainTest(m *testing.M, testOpts ...*TestOptions) { + searchDir, _ := os.Getwd() + for searchDir != "" { + if _, err := os.Stat(filepath.Join(searchDir, "go.mod")); err == nil { + break // The "go.mod" should be the one for Gitea repository + } + if dir := filepath.Dir(searchDir); dir == searchDir { + searchDir = "" // reaches the root of filesystem + } else { + searchDir = dir + } + } + if searchDir == "" { + panic("The tests should run in a Gitea repository, there should be a 'go.mod' in the root") + } - giteaRoot = testOpts.GiteaRootPath - fixturesDir = filepath.Join(testOpts.GiteaRootPath, "models", "fixtures") + giteaRoot = searchDir + setting.CustomPath = filepath.Join(giteaRoot, "custom") + InitSettings() + fixturesDir = filepath.Join(giteaRoot, "models", "fixtures") var opts FixturesOptions - if len(testOpts.FixtureFiles) == 0 { + if len(testOpts) == 0 || len(testOpts[0].FixtureFiles) == 0 { opts.Dir = fixturesDir } else { - for _, f := range testOpts.FixtureFiles { + for _, f := range testOpts[0].FixtureFiles { if len(f) != 0 { opts.Files = append(opts.Files, filepath.Join(fixturesDir, f)) } } } - if err = CreateTestEngine(opts); err != nil { + if err := CreateTestEngine(opts); err != nil { fatalTestError("Error creating test engine: %v\n", err) } @@ -112,8 +123,8 @@ func MainTest(m *testing.M, testOpts *TestOptions) { fatalTestError("TempDir: %v\n", err) } setting.AppDataPath = appDataPath - setting.AppWorkPath = testOpts.GiteaRootPath - setting.StaticRootPath = testOpts.GiteaRootPath + setting.AppWorkPath = giteaRoot + setting.StaticRootPath = giteaRoot setting.GravatarSource = "https://secure.gravatar.com/avatar/" setting.Attachment.Storage.Path = filepath.Join(setting.AppDataPath, "attachments") @@ -144,7 +155,7 @@ func MainTest(m *testing.M, testOpts *TestOptions) { if err = util.RemoveAll(repoRootPath); err != nil { fatalTestError("util.RemoveAll: %v\n", err) } - if err = CopyDir(filepath.Join(testOpts.GiteaRootPath, "tests", "gitea-repositories-meta"), setting.RepoRootPath); err != nil { + if err = CopyDir(filepath.Join(giteaRoot, "tests", "gitea-repositories-meta"), setting.RepoRootPath); err != nil { fatalTestError("util.CopyDir: %v\n", err) } @@ -171,16 +182,16 @@ func MainTest(m *testing.M, testOpts *TestOptions) { } } - if testOpts.SetUp != nil { - if err := testOpts.SetUp(); err != nil { + if len(testOpts) > 0 && testOpts[0].SetUp != nil { + if err := testOpts[0].SetUp(); err != nil { fatalTestError("set up failed: %v\n", err) } } exitStatus := m.Run() - if testOpts.TearDown != nil { - if err := testOpts.TearDown(); err != nil { + if len(testOpts) > 0 && testOpts[0].TearDown != nil { + if err := testOpts[0].TearDown(); err != nil { fatalTestError("tear down failed: %v\n", err) } } diff --git a/models/user/main_test.go b/models/user/main_test.go index 8833cc73862b7..a626d323a71a5 100644 --- a/models/user/main_test.go +++ b/models/user/main_test.go @@ -4,7 +4,6 @@ package user_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -16,7 +15,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/models/webhook/main_test.go b/models/webhook/main_test.go index 8df569a3ccf49..f19465d50530e 100644 --- a/models/webhook/main_test.go +++ b/models/webhook/main_test.go @@ -4,7 +4,6 @@ package webhook import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -12,7 +11,6 @@ import ( func TestMain(m *testing.M) { unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), FixtureFiles: []string{ "webhook.yml", "hook_task.yml", diff --git a/modules/activitypub/main_test.go b/modules/activitypub/main_test.go index dcd57bb59e5e2..4591f1fa5559d 100644 --- a/modules/activitypub/main_test.go +++ b/modules/activitypub/main_test.go @@ -4,7 +4,6 @@ package activitypub import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -15,7 +14,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go index 2a650646bd927..5b2a97d3d5fec 100644 --- a/modules/indexer/code/indexer_test.go +++ b/modules/indexer/code/indexer_test.go @@ -6,7 +6,6 @@ package code import ( "context" "os" - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -23,9 +22,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } func testIndexer(name string, t *testing.T, indexer internal.Indexer) { diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 7241f6313c891..0ec23164c2808 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -5,7 +5,6 @@ package issues import ( "context" - "path/filepath" "testing" "code.gitea.io/gitea/models/db" @@ -22,9 +21,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } func TestDBSearchIssues(t *testing.T) { diff --git a/modules/indexer/stats/indexer_test.go b/modules/indexer/stats/indexer_test.go index c03151543401c..6f935a20de3d9 100644 --- a/modules/indexer/stats/indexer_test.go +++ b/modules/indexer/stats/indexer_test.go @@ -5,7 +5,6 @@ package stats import ( "context" - "path/filepath" "testing" "time" @@ -23,9 +22,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } func TestRepoStatsIndex(t *testing.T) { diff --git a/modules/repository/main_test.go b/modules/repository/main_test.go index abaae69866308..f81dfcdafbc80 100644 --- a/modules/repository/main_test.go +++ b/modules/repository/main_test.go @@ -4,7 +4,6 @@ package repository import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -13,7 +12,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/modules/system/appstate_test.go b/modules/system/appstate_test.go index 65a6e5000331a..232362cf0c8a7 100644 --- a/modules/system/appstate_test.go +++ b/modules/system/appstate_test.go @@ -4,7 +4,6 @@ package system import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -14,8 +13,7 @@ import ( func TestMain(m *testing.M) { unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - FixtureFiles: []string{""}, // load nothing + FixtureFiles: []string{""}, // load nothing }) } diff --git a/routers/api/v1/repo/main_test.go b/routers/api/v1/repo/main_test.go index bc048505f472f..451f34d72fff7 100644 --- a/routers/api/v1/repo/main_test.go +++ b/routers/api/v1/repo/main_test.go @@ -4,7 +4,6 @@ package repo import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -14,7 +13,6 @@ import ( func TestMain(m *testing.M) { unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", "..", ".."), SetUp: func() error { setting.LoadQueueSettings() return webhook_service.Init() diff --git a/routers/common/errpage_test.go b/routers/common/errpage_test.go index ea9a9e745c139..58a633b2a453a 100644 --- a/routers/common/errpage_test.go +++ b/routers/common/errpage_test.go @@ -9,7 +9,6 @@ import ( "net/http" "net/http/httptest" "net/url" - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -35,7 +34,5 @@ func TestRenderPanicErrorPage(t *testing.T) { } func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/routers/install/routes_test.go b/routers/install/routes_test.go index fcbd052977427..2aa7f5d7b739f 100644 --- a/routers/install/routes_test.go +++ b/routers/install/routes_test.go @@ -5,7 +5,6 @@ package install import ( "net/http/httptest" - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -35,7 +34,5 @@ func TestRoutes(t *testing.T) { } func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/routers/private/main_test.go b/routers/private/main_test.go index 700af6ec8d413..a6bec72b41d56 100644 --- a/routers/private/main_test.go +++ b/routers/private/main_test.go @@ -4,14 +4,11 @@ package private import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/routers/web/admin/main_test.go b/routers/web/admin/main_test.go index ea79830fa1358..e1294ddbb4025 100644 --- a/routers/web/admin/main_test.go +++ b/routers/web/admin/main_test.go @@ -4,14 +4,11 @@ package admin import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } diff --git a/routers/web/auth/main_test.go b/routers/web/auth/main_test.go index 8295515ba9506..b438e5d51886b 100644 --- a/routers/web/auth/main_test.go +++ b/routers/web/auth/main_test.go @@ -4,14 +4,11 @@ package auth import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } diff --git a/routers/web/org/main_test.go b/routers/web/org/main_test.go index 41323a3601eae..92237d6e88472 100644 --- a/routers/web/org/main_test.go +++ b/routers/web/org/main_test.go @@ -4,14 +4,11 @@ package org_test import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } diff --git a/routers/web/repo/main_test.go b/routers/web/repo/main_test.go index e3a09a95bd36d..6e469cf2ed756 100644 --- a/routers/web/repo/main_test.go +++ b/routers/web/repo/main_test.go @@ -4,14 +4,11 @@ package repo import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } diff --git a/routers/web/repo/setting/main_test.go b/routers/web/repo/setting/main_test.go index 5a6fa5621775b..c414b853e510a 100644 --- a/routers/web/repo/setting/main_test.go +++ b/routers/web/repo/setting/main_test.go @@ -4,14 +4,11 @@ package setting import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", "..", ".."), - }) + unittest.MainTest(m) } diff --git a/routers/web/user/main_test.go b/routers/web/user/main_test.go index 925482a1d2ba7..8b6ae69296ba8 100644 --- a/routers/web/user/main_test.go +++ b/routers/web/user/main_test.go @@ -4,14 +4,11 @@ package user import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } diff --git a/routers/web/user/setting/main_test.go b/routers/web/user/setting/main_test.go index c3938b32011c5..e398208d0daab 100644 --- a/routers/web/user/setting/main_test.go +++ b/routers/web/user/setting/main_test.go @@ -4,14 +4,11 @@ package setting import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", "..", ".."), - }) + unittest.MainTest(m) } diff --git a/services/asymkey/main_test.go b/services/asymkey/main_test.go index e7a03861b9cce..3505b26f699a6 100644 --- a/services/asymkey/main_test.go +++ b/services/asymkey/main_test.go @@ -4,7 +4,6 @@ package asymkey import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -14,7 +13,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/services/attachment/attachment_test.go b/services/attachment/attachment_test.go index 35fcef7445c84..77ef1cd37ce81 100644 --- a/services/attachment/attachment_test.go +++ b/services/attachment/attachment_test.go @@ -19,9 +19,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } func TestUploadAttachment(t *testing.T) { diff --git a/services/convert/main_test.go b/services/convert/main_test.go index c2298dcb74a62..363cc4a97f5b6 100644 --- a/services/convert/main_test.go +++ b/services/convert/main_test.go @@ -4,7 +4,6 @@ package convert import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -13,7 +12,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/services/feed/action_test.go b/services/feed/action_test.go index fd84bb675b1c6..e1b071d8f604e 100644 --- a/services/feed/action_test.go +++ b/services/feed/action_test.go @@ -4,7 +4,6 @@ package feed import ( - "path/filepath" "strings" "testing" @@ -20,9 +19,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } func TestRenameRepoAction(t *testing.T) { diff --git a/services/gitdiff/main_test.go b/services/gitdiff/main_test.go index 7f4243576cc97..cd9dcd8cd6fa5 100644 --- a/services/gitdiff/main_test.go +++ b/services/gitdiff/main_test.go @@ -4,7 +4,6 @@ package gitdiff import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -15,7 +14,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/services/issue/main_test.go b/services/issue/main_test.go index 6bce694ccaff3..5dac54183baf4 100644 --- a/services/issue/main_test.go +++ b/services/issue/main_test.go @@ -4,7 +4,6 @@ package issue import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -13,7 +12,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/services/mailer/main_test.go b/services/mailer/main_test.go index e906f4cb6e175..f803c736ca14a 100644 --- a/services/mailer/main_test.go +++ b/services/mailer/main_test.go @@ -4,7 +4,6 @@ package mailer import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -13,7 +12,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/services/markup/main_test.go b/services/markup/main_test.go index ce892435a1aed..89fe3e7e3461a 100644 --- a/services/markup/main_test.go +++ b/services/markup/main_test.go @@ -4,7 +4,6 @@ package markup import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -12,7 +11,6 @@ import ( func TestMain(m *testing.M) { unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - FixtureFiles: []string{"user.yml"}, + FixtureFiles: []string{"user.yml"}, }) } diff --git a/services/migrations/main_test.go b/services/migrations/main_test.go index 42c433fb0031f..d0ec6a3f8d718 100644 --- a/services/migrations/main_test.go +++ b/services/migrations/main_test.go @@ -5,7 +5,6 @@ package migrations import ( - "path/filepath" "testing" "time" @@ -16,9 +15,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } func timePtr(t time.Time) *time.Time { diff --git a/services/org/org_test.go b/services/org/org_test.go index cc22595c6f198..339646795da37 100644 --- a/services/org/org_test.go +++ b/services/org/org_test.go @@ -4,7 +4,6 @@ package org import ( - "path/filepath" "testing" "code.gitea.io/gitea/models" @@ -16,9 +15,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } func TestDeleteOrganization(t *testing.T) { diff --git a/services/pull/main_test.go b/services/pull/main_test.go index f5297354d65d7..efbb63a36ec50 100644 --- a/services/pull/main_test.go +++ b/services/pull/main_test.go @@ -5,7 +5,6 @@ package pull import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -14,7 +13,5 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/services/release/release_test.go b/services/release/release_test.go index 9c652f28d2e37..3f0c67b0e0196 100644 --- a/services/release/release_test.go +++ b/services/release/release_test.go @@ -4,7 +4,6 @@ package release import ( - "path/filepath" "strings" "testing" "time" @@ -22,9 +21,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } func TestRelease_Create(t *testing.T) { diff --git a/services/repository/archiver/archiver_test.go b/services/repository/archiver/archiver_test.go index a1bc355d4e9f3..ff8bb8ca7a9b6 100644 --- a/services/repository/archiver/archiver_test.go +++ b/services/repository/archiver/archiver_test.go @@ -5,7 +5,6 @@ package archiver import ( "errors" - "path/filepath" "testing" "time" @@ -18,9 +17,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } func TestArchive_Basic(t *testing.T) { diff --git a/services/repository/files/content_test.go b/services/repository/files/content_test.go index d591c468399d9..3ad3e3ab98b2a 100644 --- a/services/repository/files/content_test.go +++ b/services/repository/files/content_test.go @@ -4,7 +4,6 @@ package files import ( - "path/filepath" "testing" repo_model "code.gitea.io/gitea/models/repo" @@ -19,9 +18,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", "..", ".."), - }) + unittest.MainTest(m) } func getExpectedReadmeContentsResponse() *api.ContentsResponse { diff --git a/services/repository/main_test.go b/services/repository/main_test.go index 007790f2a9626..7ad1540aee48a 100644 --- a/services/repository/main_test.go +++ b/services/repository/main_test.go @@ -4,14 +4,11 @@ package repository import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } diff --git a/services/user/user_test.go b/services/user/user_test.go index b8f7b9b1a2514..550dafd9c56c0 100644 --- a/services/user/user_test.go +++ b/services/user/user_test.go @@ -5,7 +5,6 @@ package user import ( "fmt" - "path/filepath" "strings" "testing" @@ -22,9 +21,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } func TestDeleteUser(t *testing.T) { diff --git a/services/webhook/main_test.go b/services/webhook/main_test.go index cd34c02b5c561..756b9db23083c 100644 --- a/services/webhook/main_test.go +++ b/services/webhook/main_test.go @@ -4,7 +4,6 @@ package webhook import ( - "path/filepath" "testing" "code.gitea.io/gitea/models/unittest" @@ -19,7 +18,6 @@ func TestMain(m *testing.M) { // for tests, allow only loopback IPs setting.Webhook.AllowedHostList = hostmatcher.MatchBuiltinLoopback unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), SetUp: func() error { setting.LoadQueueSettings() return Init() diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index 81a688b046a7c..e8da176a08d2c 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -5,7 +5,6 @@ package wiki import ( "math/rand" - "path/filepath" "strings" "testing" @@ -20,9 +19,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - GiteaRootPath: filepath.Join("..", ".."), - }) + unittest.MainTest(m) } func TestWebPathSegments(t *testing.T) { From 98f02203f9ed7308686995c2b93e7e35f0c0b412 Mon Sep 17 00:00:00 2001 From: Earl Warren <109468362+earl-warren@users.noreply.github.com> Date: Thu, 28 Sep 2023 04:07:33 +0200 Subject: [PATCH 18/22] fix orphan check for deleted branch (#27310) - Modify the deleted branch orphan check to check for the new table instead. - Regression from 6e19484f4d3bf372212f2da462110a1a8c10cbf2 - Resolves https://codeberg.org/forgejo/forgejo/issues/1522 (cherry picked from commit c1d888686fe445e4edecb9d835c5b3893b574b75) Co-authored-by: Gusted --- modules/doctor/dbconsistency.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/doctor/dbconsistency.go b/modules/doctor/dbconsistency.go index 548687355605b..a0637b8982cf3 100644 --- a/modules/doctor/dbconsistency.go +++ b/modules/doctor/dbconsistency.go @@ -168,9 +168,9 @@ func checkDBConsistency(ctx context.Context, logger log.Logger, autofix bool) er // find protected branches without existing repository genericOrphanCheck("Protected Branches without existing repository", "protected_branch", "repository", "protected_branch.repo_id=repository.id"), - // find deleted branches without existing repository - genericOrphanCheck("Deleted Branches without existing repository", - "deleted_branch", "repository", "deleted_branch.repo_id=repository.id"), + // find branches without existing repository + genericOrphanCheck("Branches without existing repository", + "branch", "repository", "branch.repo_id=repository.id"), // find LFS locks without existing repository genericOrphanCheck("LFS locks without existing repository", "lfs_lock", "repository", "lfs_lock.repo_id=repository.id"), From 15fa0383fb5dd9ad1702dbc34ba7100c0cdbcc8c Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 28 Sep 2023 04:03:08 +0100 Subject: [PATCH 19/22] doctor: delete action entries without existing user (#27292) just extend doctor with a usefully check :) Co-authored-by: techknowlogick --- modules/doctor/dbconsistency.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/doctor/dbconsistency.go b/modules/doctor/dbconsistency.go index a0637b8982cf3..e5fc5785e826c 100644 --- a/modules/doctor/dbconsistency.go +++ b/modules/doctor/dbconsistency.go @@ -189,6 +189,9 @@ func checkDBConsistency(ctx context.Context, logger log.Logger, autofix bool) er // find action without repository genericOrphanCheck("Action entries without existing repository", "action", "repository", "action.repo_id=repository.id"), + // find action without user + genericOrphanCheck("Action entries without existing user", + "action", "user", "action.act_user_id=`user`.id"), // find OAuth2Grant without existing user genericOrphanCheck("Orphaned OAuth2Grant without existing User", "oauth2_grant", "user", "oauth2_grant.user_id=`user`.id"), From 7ea2a910cebaf51cfd13c0941029c404e408ae54 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 28 Sep 2023 12:04:32 +0800 Subject: [PATCH 20/22] Improve branch list UI (#27319) 1. Put the `"octicon-shield-lock"` into the flex container, then it doesn't need a separate flex box 2. Remove some unnecessary `gt-df` helpers 3. Make `btn` button has the same flex behavior as `ui button` ![image](https://github.com/go-gitea/gitea/assets/2114189/60ce75f7-7fac-4157-9c42-91c7dee9300e) ![image](https://github.com/go-gitea/gitea/assets/2114189/ea606baf-6f52-41e1-b964-c4840d3b1529) --- templates/repo/branch/list.tmpl | 22 +++++++++------------- templates/repo/commit_status.tmpl | 2 -- web_src/css/base.css | 1 + web_src/css/modules/button.css | 2 +- 4 files changed, 11 insertions(+), 16 deletions(-) diff --git a/templates/repo/branch/list.tmpl b/templates/repo/branch/list.tmpl index f554c851d3692..370a412efb834 100644 --- a/templates/repo/branch/list.tmpl +++ b/templates/repo/branch/list.tmpl @@ -19,12 +19,10 @@ -
- {{if .DefaultBranchBranch.IsProtected}} - {{svg "octicon-shield-lock"}} - {{end}} +
+ {{if .DefaultBranchBranch.IsProtected}}{{svg "octicon-shield-lock"}}{{end}} {{.DefaultBranchBranch.DBBranch.Name}} - + {{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DefaultBranchBranch.DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DefaultBranchBranch.DBBranch.CommitID)}}

{{svg "octicon-git-commit" 16 "gt-mr-2"}}{{ShortSha .DefaultBranchBranch.DBBranch.CommitID}} · {{RenderCommitMessage $.Context .DefaultBranchBranch.DBBranch.CommitMessage .RepoLink .Repository.ComposeMetas}} · {{ctx.Locale.Tr "org.repo_updated"}} {{TimeSince .DefaultBranchBranch.DBBranch.CommitTime.AsTime ctx.Locale}}{{if .DefaultBranchBranch.DBBranch.Pusher}}  {{template "shared/user/avatarlink" dict "user" .DefaultBranchBranch.DBBranch.Pusher}}{{template "shared/user/namelink" .DefaultBranchBranch.DBBranch.Pusher}}{{end}}

@@ -91,21 +89,19 @@ {{if .DBBranch.IsDeleted}} -
+
{{.DBBranch.Name}} - +

{{ctx.Locale.Tr "repo.branch.deleted_by" .DBBranch.DeletedBy.Name}} {{TimeSinceUnix .DBBranch.DeletedUnix ctx.Locale}}

{{else}} -
- {{if .IsProtected}} - {{svg "octicon-shield-lock"}} - {{end}} +
+ {{if .IsProtected}}{{svg "octicon-shield-lock"}}{{end}} {{.DBBranch.Name}} - + {{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DBBranch.CommitID)}}
-

{{svg "octicon-git-commit" 16 "gt-mr-2"}}{{ShortSha .DBBranch.CommitID}} · {{RenderCommitMessage $.Context .DBBranch.CommitMessage $.RepoLink $.Repository.ComposeMetas}} · {{ctx.Locale.Tr "org.repo_updated"}} {{TimeSince .DBBranch.CommitTime.AsTime ctx.Locale}}{{if .DBBranch.Pusher}}  {{template "shared/user/avatarlink" dict "user" .DBBranch.Pusher}}  {{template "shared/user/namelink" .DBBranch.Pusher}}{{end}}

+

{{svg "octicon-git-commit" 16 "gt-mr-2"}}{{ShortSha .DBBranch.CommitID}} · {{RenderCommitMessage $.Context .DBBranch.CommitMessage $.RepoLink $.Repository.ComposeMetas}} · {{ctx.Locale.Tr "org.repo_updated"}} {{TimeSince .DBBranch.CommitTime.AsTime ctx.Locale}}{{if .DBBranch.Pusher}}  {{template "shared/user/avatarlink" dict "user" .DBBranch.Pusher}}  {{template "shared/user/namelink" .DBBranch.Pusher}}{{end}}

{{end}} diff --git a/templates/repo/commit_status.tmpl b/templates/repo/commit_status.tmpl index 3dc1da61d3c4e..ebd8a55f65e38 100644 --- a/templates/repo/commit_status.tmpl +++ b/templates/repo/commit_status.tmpl @@ -1,5 +1,4 @@ - {{if eq .State "pending"}} {{svg "octicon-dot-fill" 18 "commit-status icon text yellow"}} {{end}} @@ -12,4 +11,3 @@ {{if eq .State "failure"}} {{svg "octicon-x" 18 "commit-status icon text red"}} {{end}} - diff --git a/web_src/css/base.css b/web_src/css/base.css index 5efb0bfae541a..1a4e9d16a1436 100644 --- a/web_src/css/base.css +++ b/web_src/css/base.css @@ -2242,6 +2242,7 @@ table th[data-sortt-desc] .svg { right: 2em; } +.btn, .ui.ui.button, .ui.ui.dropdown, .ui.ui.label, diff --git a/web_src/css/modules/button.css b/web_src/css/modules/button.css index f292231319b08..0d30249c9cce8 100644 --- a/web_src/css/modules/button.css +++ b/web_src/css/modules/button.css @@ -30,7 +30,7 @@ color: var(--color-red); } -/* btn is a plain button without any opinionated styling */ +/* btn is a plain button without any opinionated styling, it only uses flex for vertical alignment like ".ui.button" in base.css */ .btn { background: transparent; From 72c68177ab78d026d25a0a440c35cdbc9723cd98 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 28 Sep 2023 16:43:20 +0800 Subject: [PATCH 21/22] Improve issue history dialog and make poster can delete their own history (#27323) Fix #27313 (see the comment) And some UI improvements: ### Before ![image](https://github.com/go-gitea/gitea/assets/2114189/420a314d-8f34-4e30-a557-f41cf4f0d2f2) ![image](https://github.com/go-gitea/gitea/assets/2114189/60ca0be4-b55e-4e65-be73-fd53e0d4fc36) ### After ![image](https://github.com/go-gitea/gitea/assets/2114189/d354f815-5a0c-4e63-8d59-d03ed344dbea) ![image](https://github.com/go-gitea/gitea/assets/2114189/6ef437a4-aa6f-4917-a260-00625ee71e79) ![image](https://github.com/go-gitea/gitea/assets/2114189/9d88a36c-616b-4dc9-8c6b-76adaad8acf6) --- routers/web/repo/issue_content_history.go | 14 +++++++++----- web_src/css/modules/modal.css | 7 ++++++- web_src/css/repo.css | 2 ++ web_src/js/features/repo-issue-content.js | 7 ++++--- 4 files changed, 21 insertions(+), 9 deletions(-) diff --git a/routers/web/repo/issue_content_history.go b/routers/web/repo/issue_content_history.go index 3dd7725c21506..5c378fe9d79df 100644 --- a/routers/web/repo/issue_content_history.go +++ b/routers/web/repo/issue_content_history.go @@ -11,7 +11,6 @@ import ( "code.gitea.io/gitea/models/avatars" issues_model "code.gitea.io/gitea/models/issues" - "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -91,11 +90,16 @@ func GetContentHistoryList(ctx *context.Context) { // Admins or owners can always delete history revisions. Normal users can only delete own history revisions. func canSoftDeleteContentHistory(ctx *context.Context, issue *issues_model.Issue, comment *issues_model.Comment, history *issues_model.ContentHistory, -) bool { - canSoftDelete := false - if ctx.Repo.IsOwner() { +) (canSoftDelete bool) { + // CanWrite means the doer can manage the issue/PR list + if ctx.Repo.IsOwner() || ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) { canSoftDelete = true - } else if ctx.Repo.CanWrite(unit.TypeIssues) { + } else { + // for read-only users, they could still post issues or comments, + // they should be able to delete the history related to their own issue/comment, a case is: + // 1. the user posts some sensitive data + // 2. then the repo owner edits the post but didn't remove the sensitive data + // 3. the poster wants to delete the edited history revision if comment == nil { // the issue poster or the history poster can soft-delete canSoftDelete = ctx.Doer.ID == issue.PosterID || ctx.Doer.ID == history.PosterID diff --git a/web_src/css/modules/modal.css b/web_src/css/modules/modal.css index 96bc8be8983b5..54a4ef81ca19d 100644 --- a/web_src/css/modules/modal.css +++ b/web_src/css/modules/modal.css @@ -3,13 +3,18 @@ width: fit-content; } -.ui.modal.g-modal-confirm > .inside.close { +.ui.modal.g-modal-confirm > .inside.close.icon { padding: 0; width: 1em; height: 1em; top: 1.2em; } +.ui.modal > .close.icon[height="16"] { + top: 0.7em; /* fomantic uses absolute layout, so if we have special icon size, it needs this trick to align vertically */ + color: var(--color-text-dark); +} + .ui.modal > .header { /* can't use display:flex, because some headers have space-separated elements, eg: delete branch modal */ color: var(--color-text-dark); diff --git a/web_src/css/repo.css b/web_src/css/repo.css index b7b14f740791c..8e751ef88e1f9 100644 --- a/web_src/css/repo.css +++ b/web_src/css/repo.css @@ -2578,12 +2578,14 @@ tbody.commit-list { .comment-diff-data { background: var(--color-code-bg); + min-height: 12em; max-height: calc(100vh - 10.5rem); overflow-y: auto; } .comment-diff-data pre { line-height: 18px; + margin: 1em; white-space: pre-wrap; word-break: break-all; overflow-wrap: break-word; diff --git a/web_src/js/features/repo-issue-content.js b/web_src/js/features/repo-issue-content.js index 3ada166c5b009..7832641687d1c 100644 --- a/web_src/js/features/repo-issue-content.js +++ b/web_src/js/features/repo-issue-content.js @@ -17,14 +17,15 @@ function showContentHistoryDetail(issueBaseUrl, commentId, historyId, itemTitleH ${svg('octicon-x', 16, 'close icon inside')}
${itemTitleHtml}
- -
+
`); $dialog.appendTo($('body')); $dialog.find('.dialog-header-options').dropdown({ From 1f00bc44b276cd3fcb1e880e9b1de90c9bb89e83 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 28 Sep 2023 18:00:26 +0800 Subject: [PATCH 22/22] Fix review UI (#27322) Close #26730 1. The `diff-detail-box` was abused, it shouldn't be used for "DiffFileList/DiffFileTree". 2. Fix the sticky position for various screens. ![image](https://github.com/go-gitea/gitea/assets/2114189/558a5c06-c94c-4e5c-8395-d38473dd21c2) ![image](https://github.com/go-gitea/gitea/assets/2114189/3390fb0e-7dc7-457f-bd0c-398fdb6d24c0) ![image](https://github.com/go-gitea/gitea/assets/2114189/d19dd350-aecf-4909-8ef9-73b09d94560e) --- templates/repo/diff/box.tmpl | 2 +- web_src/css/repo.css | 23 +++++++++-------------- web_src/js/components/DiffFileList.vue | 2 +- web_src/js/components/DiffFileTree.vue | 2 +- 4 files changed, 12 insertions(+), 17 deletions(-) diff --git a/templates/repo/diff/box.tmpl b/templates/repo/diff/box.tmpl index 15766363e747c..94a5a9a295894 100644 --- a/templates/repo/diff/box.tmpl +++ b/templates/repo/diff/box.tmpl @@ -1,5 +1,5 @@
-
+
{{if not .DiffNotAvailable}}