From cbf933eb4e344cc182d70553a14fe778f42422d0 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Wed, 15 Jan 2025 00:31:44 +0000 Subject: [PATCH 01/12] [skip ci] Updated translations via Crowdin --- options/locale/locale_cs-CZ.ini | 1 - options/locale/locale_de-DE.ini | 1 - options/locale/locale_fr-FR.ini | 1 - options/locale/locale_ga-IE.ini | 2 +- options/locale/locale_ja-JP.ini | 1 - options/locale/locale_pt-PT.ini | 6 +++--- options/locale/locale_tr-TR.ini | 1 - options/locale/locale_zh-CN.ini | 1 - options/locale/locale_zh-TW.ini | 1 - 9 files changed, 4 insertions(+), 11 deletions(-) diff --git a/options/locale/locale_cs-CZ.ini b/options/locale/locale_cs-CZ.ini index eb0e0dff97..78e8db160c 100644 --- a/options/locale/locale_cs-CZ.ini +++ b/options/locale/locale_cs-CZ.ini @@ -2155,7 +2155,6 @@ settings.advanced_settings=Pokročilá nastavení settings.wiki_desc=Povolit Wiki repozitáře settings.use_internal_wiki=Používat vestavěnou Wiki settings.default_wiki_branch_name=Výchozí název větve Wiki -settings.default_wiki_everyone_access=Výchozí přístupová práva pro přihlášené uživatele: settings.failed_to_change_default_wiki_branch=Změna výchozí větve wiki se nezdařila. settings.use_external_wiki=Používat externí Wiki settings.external_wiki_url=URL externí Wiki diff --git a/options/locale/locale_de-DE.ini b/options/locale/locale_de-DE.ini index 120b3ea7db..122bc1ec53 100644 --- a/options/locale/locale_de-DE.ini +++ b/options/locale/locale_de-DE.ini @@ -2151,7 +2151,6 @@ settings.advanced_settings=Erweiterte Einstellungen settings.wiki_desc=Repository-Wiki aktivieren settings.use_internal_wiki=Eingebautes Wiki verwenden settings.default_wiki_branch_name=Standardbezeichnung für Wiki-Branch -settings.default_wiki_everyone_access=Standard-Zugriffsberechtigung für angemeldete Benutzer: settings.failed_to_change_default_wiki_branch=Das Ändern des Standard-Wiki-Branches ist fehlgeschlagen. settings.use_external_wiki=Externes Wiki verwenden settings.external_wiki_url=Externe Wiki-URL diff --git a/options/locale/locale_fr-FR.ini b/options/locale/locale_fr-FR.ini index e8c621a1fa..bf31111b6e 100644 --- a/options/locale/locale_fr-FR.ini +++ b/options/locale/locale_fr-FR.ini @@ -2156,7 +2156,6 @@ settings.advanced_settings=Paramètres avancés settings.wiki_desc=Activer le wiki du dépôt settings.use_internal_wiki=Utiliser le wiki interne settings.default_wiki_branch_name=Nom de la branche du Wiki par défaut -settings.default_wiki_everyone_access=Autorisation d’accès par défaut pour les utilisateurs connectés : settings.failed_to_change_default_wiki_branch=Impossible de modifier la branche du wiki par défaut. settings.use_external_wiki=Utiliser un wiki externe settings.external_wiki_url=URL Wiki externe diff --git a/options/locale/locale_ga-IE.ini b/options/locale/locale_ga-IE.ini index 51c3ab20cc..3acdba35b0 100644 --- a/options/locale/locale_ga-IE.ini +++ b/options/locale/locale_ga-IE.ini @@ -1115,6 +1115,7 @@ blame.ignore_revs=Ag déanamh neamhairde de leasuithe i .git-blame- blame.ignore_revs.failed=Theip ar neamhaird a dhéanamh ar leasuithe i .git-blame-ignore-revs. user_search_tooltip=Taispeáint uasmhéid de 30 úsáideoir +tree_path_not_found=Níl cosán %[1]s ann i %[2]s transfer.accept=Glac le hAistriú transfer.accept_desc=Aistriú chuig “%s” @@ -2156,7 +2157,6 @@ settings.advanced_settings=Ardsocruithe settings.wiki_desc=Cumasaigh Stór Vicí settings.use_internal_wiki=Úsáid Vicí Insuite settings.default_wiki_branch_name=Ainm Brainse Réamhshocraithe Vicí -settings.default_wiki_everyone_access=Cead Rochtana Réamhshocraithe d'úsáideoirí sínithe isteach: settings.failed_to_change_default_wiki_branch=Theip ar an brainse réamhshocraithe vicí a athrú. settings.use_external_wiki=Úsáid Vicí Seachtrach settings.external_wiki_url=URL Vicí Seachtrach diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index 7e39db8353..efe365dbfa 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -2145,7 +2145,6 @@ settings.advanced_settings=拡張設定 settings.wiki_desc=Wikiを有効にする settings.use_internal_wiki=ビルトインのWikiを使用する settings.default_wiki_branch_name=デフォルトのWikiブランチ名 -settings.default_wiki_everyone_access=サインインユーザーのデフォルトのアクセス権限: settings.failed_to_change_default_wiki_branch=デフォルトのWikiブランチを変更できませんでした。 settings.use_external_wiki=外部のWikiを使用する settings.external_wiki_url=外部WikiのURL diff --git a/options/locale/locale_pt-PT.ini b/options/locale/locale_pt-PT.ini index a0d0201a37..40f1a13d67 100644 --- a/options/locale/locale_pt-PT.ini +++ b/options/locale/locale_pt-PT.ini @@ -261,7 +261,7 @@ path=Localização sqlite_helper=Localização do ficheiro da base de dados em SQLite3.
Insira um caminho absoluto se corre o Gitea como um serviço. reinstall_error=Está a tentar instalar numa base de dados do Gitea já existente reinstall_confirm_message=Reinstalar com uma base de dados do Gitea já existente pode causar múltiplos problemas. Na maioria dos casos deve usar o seu "app.ini" existente para correr o Gitea. Se souber o que está a fazer, confirme o seguinte: -reinstall_confirm_check_1=Os dados encriptados pela chave secreta (SECRET_KEY) no ficheiro app.ini poderão ser perdidos: utilizadores poderão não ser capazes de iniciar a sessão com autenticação em dois passos (2FA) ou com chaves de utilização única (OTP) e as réplicas poderão deixar de funcionar em condições. Ao marcar esta opção estará a confirmar que o ficheiro app.ini vigente contém a SECRET_KEY certa. +reinstall_confirm_check_1=Os dados encriptados pela chave secreta (SECRET_KEY) no ficheiro app.ini poderão ser perdidos: utilizadores poderão não ser capazes de iniciar a sessão com autenticação em dois passos (2FA) ou com chaves de utilização única (OTP) e as réplicas poderão deixar de funcionar em boas condições. Ao marcar esta opção estará a confirmar que o ficheiro app.ini vigente contém a SECRET_KEY certa. reinstall_confirm_check_2=Os repositórios e as configurações poderão ter de voltar a ser sincronizados. Ao marcar esta opção estará a confirmar que vai voltar a sincronizar manualmente os automatismos para os repositórios e o ficheiro authorized_keys. Estará também a confirmar que vai assegurar que as configurações do repositório e das réplicas estão em condições. reinstall_confirm_check_3=Você confirma que tem a certeza absoluta de que este Gitea está a correr com a localização certa do ficheiro app.ini e que tem a certeza de que tem de voltar a instalar. Você confirma que tomou conhecimento dos riscos acima descritos. err_empty_db_path=A localização da base de dados SQLite3 não pode estar vazia. @@ -1051,7 +1051,7 @@ generate_from=Gerar a partir de repo_desc=Descrição repo_desc_helper=Insira uma descrição curta (opcional) repo_no_desc=Descrição não fornecida -repo_lang=Idiomas +repo_lang=Linguagens repo_gitignore_helper=Escolher modelos .gitignore. repo_gitignore_helper_desc=Escolha os ficheiros que não são para rastrear, a partir de uma lista de modelos de linguagens comuns. Serão incluídos no ficheiro .gitignore, logo à partida, artefactos típicos gerados pelas ferramentas de construção de cada uma das linguagens. issue_labels=Rótulos para as questões @@ -1115,6 +1115,7 @@ blame.ignore_revs=Ignorando as revisões em .git-blame-ignore-revs< blame.ignore_revs.failed=Falhou ao ignorar as revisões em .git-blame-ignore-revs. user_search_tooltip=Mostra um máximo de 30 utilizadores +tree_path_not_found=A localização %[1]s não existe em %[2]s transfer.accept=Aceitar transferência transfer.accept_desc=`Transferir para "%s"` @@ -2156,7 +2157,6 @@ settings.advanced_settings=Configurações avançadas settings.wiki_desc=Habilitar wiki do repositório settings.use_internal_wiki=Usar o wiki integrado settings.default_wiki_branch_name=Nome do ramo predefinido do wiki -settings.default_wiki_everyone_access=Permissão de acesso predefinida para utilizadores registados: settings.failed_to_change_default_wiki_branch=Falhou ao mudar o nome do ramo predefinido do wiki. settings.use_external_wiki=Usar um wiki externo settings.external_wiki_url=URL do wiki externo diff --git a/options/locale/locale_tr-TR.ini b/options/locale/locale_tr-TR.ini index 8840b45a06..f64f4935a4 100644 --- a/options/locale/locale_tr-TR.ini +++ b/options/locale/locale_tr-TR.ini @@ -2080,7 +2080,6 @@ settings.advanced_settings=Gelişmiş Ayarlar settings.wiki_desc=Depo Wiki'sini Etkinkleştir settings.use_internal_wiki=Dahili Wiki Kullan settings.default_wiki_branch_name=Varsayılan Viki Dal Adı -settings.default_wiki_everyone_access=Oturum açmış kullanıcılar için Varsayılan Erişim İzinleri: settings.failed_to_change_default_wiki_branch=Varsayılan viki dalı değiştirilemedi. settings.use_external_wiki=Harici Wiki Kullan settings.external_wiki_url=Harici Wiki bağlantısı diff --git a/options/locale/locale_zh-CN.ini b/options/locale/locale_zh-CN.ini index 3215ea9045..af590a68c1 100644 --- a/options/locale/locale_zh-CN.ini +++ b/options/locale/locale_zh-CN.ini @@ -2151,7 +2151,6 @@ settings.advanced_settings=高级设置 settings.wiki_desc=启用仓库百科 settings.use_internal_wiki=使用内置百科 settings.default_wiki_branch_name=默认百科分支名称 -settings.default_wiki_everyone_access=登录用户的默认访问权限: settings.failed_to_change_default_wiki_branch=更改百科默认分支失败。 settings.use_external_wiki=使用外部百科 settings.external_wiki_url=外部 Wiki 链接 diff --git a/options/locale/locale_zh-TW.ini b/options/locale/locale_zh-TW.ini index eafe060ff4..b6e9e58fda 100644 --- a/options/locale/locale_zh-TW.ini +++ b/options/locale/locale_zh-TW.ini @@ -2142,7 +2142,6 @@ settings.advanced_settings=進階設定 settings.wiki_desc=啟用儲存庫 Wiki settings.use_internal_wiki=使用內建 Wiki settings.default_wiki_branch_name=預設 Wiki 分支名稱 -settings.default_wiki_everyone_access=登入使用者的預設存取權限: settings.failed_to_change_default_wiki_branch=更改預設 Wiki 分支失敗。 settings.use_external_wiki=使用外部 Wiki settings.external_wiki_url=外部 Wiki 連結 From fcd096231ac2deaefbca10a7db1b9b01f1da93d7 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 15 Jan 2025 11:15:47 +0800 Subject: [PATCH 02/12] Simplify context ref name (#33267) --- routers/web/repo/branch.go | 4 ++-- routers/web/repo/commit.go | 6 ----- routers/web/repo/release.go | 4 ---- routers/web/repo/view_file.go | 4 ++-- routers/web/repo/view_home.go | 2 +- services/context/repo.go | 39 ++++++++------------------------ templates/repo/blame.tmpl | 2 +- templates/repo/commit_page.tmpl | 4 +--- templates/repo/commits.tmpl | 17 +++----------- templates/repo/home.tmpl | 21 ++++------------- templates/repo/release/list.tmpl | 2 +- templates/repo/view_file.tmpl | 2 +- 12 files changed, 27 insertions(+), 80 deletions(-) diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go index 51d91b7d6a..5011cbfc77 100644 --- a/routers/web/repo/branch.go +++ b/routers/web/repo/branch.go @@ -193,11 +193,11 @@ func CreateBranch(ctx *context.Context) { if form.CreateTag { target := ctx.Repo.CommitID - if ctx.Repo.IsViewBranch { + if ctx.Repo.RefFullName.IsBranch() { target = ctx.Repo.BranchName } err = release_service.CreateNewTag(ctx, ctx.Doer, ctx.Repo.Repository, target, form.NewBranchName, "") - } else if ctx.Repo.IsViewBranch { + } else if ctx.Repo.RefFullName.IsBranch() { err = repo_service.CreateNewBranch(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, ctx.Repo.BranchName, form.NewBranchName) } else { err = repo_service.CreateNewBranchFromCommit(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, ctx.Repo.CommitID, form.NewBranchName) diff --git a/routers/web/repo/commit.go b/routers/web/repo/commit.go index b5498ccd2c..bad8ca56d1 100644 --- a/routers/web/repo/commit.go +++ b/routers/web/repo/commit.go @@ -390,12 +390,6 @@ func Diff(ctx *context.Context) { } } - ctx.Data["BranchName"], err = commit.GetBranchName() - if err != nil { - ctx.ServerError("commit.GetBranchName", err) - return - } - ctx.HTML(http.StatusOK, tplCommitPage) } diff --git a/routers/web/repo/release.go b/routers/web/repo/release.go index 8909dedbb1..19b83915af 100644 --- a/routers/web/repo/release.go +++ b/routers/web/repo/release.go @@ -148,8 +148,6 @@ func getReleaseInfos(ctx *context.Context, opts *repo_model.FindReleasesOptions) func Releases(ctx *context.Context) { ctx.Data["PageIsReleaseList"] = true ctx.Data["Title"] = ctx.Tr("repo.release.releases") - ctx.Data["IsViewBranch"] = false - ctx.Data["IsViewTag"] = true listOptions := db.ListOptions{ Page: ctx.FormInt("page"), @@ -194,8 +192,6 @@ func Releases(ctx *context.Context) { func TagsList(ctx *context.Context) { ctx.Data["PageIsTagList"] = true ctx.Data["Title"] = ctx.Tr("repo.release.tags") - ctx.Data["IsViewBranch"] = false - ctx.Data["IsViewTag"] = true ctx.Data["CanCreateRelease"] = ctx.Repo.CanWrite(unit.TypeReleases) && !ctx.Repo.Repository.IsArchived namePattern := ctx.FormTrim("q") diff --git a/routers/web/repo/view_file.go b/routers/web/repo/view_file.go index 0b4381edfb..5784297918 100644 --- a/routers/web/repo/view_file.go +++ b/routers/web/repo/view_file.go @@ -232,7 +232,7 @@ func prepareToRenderFile(ctx *context.Context, entry *git.TreeEntry) { ctx.Data["CanEditFile"] = true ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file") } - } else if !ctx.Repo.IsViewBranch { + } else if !ctx.Repo.RefFullName.IsBranch() { ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch") } else if !ctx.Repo.CanWriteToBranch(ctx, ctx.Doer, ctx.Repo.BranchName) { ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit") @@ -305,7 +305,7 @@ func prepareToRenderFile(ctx *context.Context, entry *git.TreeEntry) { ctx.Data["CanDeleteFile"] = true ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file") } - } else if !ctx.Repo.IsViewBranch { + } else if !ctx.Repo.RefFullName.IsBranch() { ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch") } else if !ctx.Repo.CanWriteToBranch(ctx, ctx.Doer, ctx.Repo.BranchName) { ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access") diff --git a/routers/web/repo/view_home.go b/routers/web/repo/view_home.go index 54a58cd8be..ff2ee3c7ec 100644 --- a/routers/web/repo/view_home.go +++ b/routers/web/repo/view_home.go @@ -178,7 +178,7 @@ func prepareHomeSidebarLatestRelease(ctx *context.Context) { } func prepareUpstreamDivergingInfo(ctx *context.Context) { - if !ctx.Repo.Repository.IsFork || !ctx.Repo.IsViewBranch || ctx.Repo.TreePath != "" { + if !ctx.Repo.Repository.IsFork || !ctx.Repo.RefFullName.IsBranch() || ctx.Repo.TreePath != "" { return } upstreamDivergingInfo, err := repo_service.GetUpstreamDivergingInfo(ctx, ctx.Repo.Repository, ctx.Repo.BranchName) diff --git a/services/context/repo.go b/services/context/repo.go index 33a39dced1..6c348b99cb 100644 --- a/services/context/repo.go +++ b/services/context/repo.go @@ -53,20 +53,15 @@ type Repository struct { RepoLink string GitRepo *git.Repository - // these fields indicate the current ref type, for example: ".../src/branch/master" means IsViewBranch=true - IsViewBranch bool - IsViewTag bool - IsViewCommit bool - + // RefFullName is the full ref name that the user is viewing RefFullName git.RefName - BranchName string - TagName string + BranchName string // it is the RefFullName's short name if its type is "branch" + TagName string // it is the RefFullName's short name if its type is "tag" TreePath string - // Commit it is always set to the commit for the branch or tag - Commit *git.Commit - CommitID string - + // Commit it is always set to the commit for the branch or tag, or just the commit that the user is viewing + Commit *git.Commit + CommitID string CommitsCount int64 PullRequest *PullRequest @@ -79,7 +74,7 @@ func (r *Repository) CanWriteToBranch(ctx context.Context, user *user_model.User // CanEnableEditor returns true if repository is editable and user has proper access level. func (r *Repository) CanEnableEditor(ctx context.Context, user *user_model.User) bool { - return r.IsViewBranch && r.CanWriteToBranch(ctx, user, r.BranchName) && r.Repository.CanEnableEditor() && !r.Repository.IsArchived + return r.RefFullName.IsBranch() && r.CanWriteToBranch(ctx, user, r.BranchName) && r.Repository.CanEnableEditor() && !r.Repository.IsArchived } // CanCreateBranch returns true if repository is editable and user has proper access level. @@ -174,15 +169,9 @@ func (r *Repository) GetCommitsCount() (int64, error) { if r.Commit == nil { return 0, nil } - var contextName string - if r.IsViewBranch { - contextName = r.BranchName - } else if r.IsViewTag { - contextName = r.TagName - } else { - contextName = r.CommitID - } - return cache.GetInt64(r.Repository.GetCommitsCountCacheKey(contextName, r.IsViewBranch || r.IsViewTag), func() (int64, error) { + contextName := r.RefFullName.ShortName() + isRef := r.RefFullName.IsBranch() || r.RefFullName.IsTag() + return cache.GetInt64(r.Repository.GetCommitsCountCacheKey(contextName, isRef), func() (int64, error) { return r.Commit.CommitsCount() }) } @@ -798,7 +787,6 @@ func RepoRefByType(detectRefType git.RefType) func(*Context) { // Empty repository does not have reference information. if ctx.Repo.Repository.IsEmpty { // assume the user is viewing the (non-existent) default branch - ctx.Repo.IsViewBranch = true ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch ctx.Repo.RefFullName = git.RefNameFromBranch(ctx.Repo.BranchName) // these variables are used by the template to "add/upload" new files @@ -834,7 +822,6 @@ func RepoRefByType(detectRefType git.RefType) func(*Context) { ctx.ServerError("GetBranchCommit", err) return } - ctx.Repo.IsViewBranch = true } else { // there is a path in request guessLegacyPath := refType == "" if guessLegacyPath { @@ -853,7 +840,6 @@ func RepoRefByType(detectRefType git.RefType) func(*Context) { } if refType == git.RefTypeBranch && ctx.Repo.GitRepo.IsBranchExist(refShortName) { - ctx.Repo.IsViewBranch = true ctx.Repo.BranchName = refShortName ctx.Repo.RefFullName = git.RefNameFromBranch(refShortName) @@ -864,7 +850,6 @@ func RepoRefByType(detectRefType git.RefType) func(*Context) { } ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() } else if refType == git.RefTypeTag && ctx.Repo.GitRepo.IsTagExist(refShortName) { - ctx.Repo.IsViewTag = true ctx.Repo.RefFullName = git.RefNameFromTag(refShortName) ctx.Repo.TagName = refShortName @@ -879,7 +864,6 @@ func RepoRefByType(detectRefType git.RefType) func(*Context) { } ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() } else if git.IsStringLikelyCommitID(ctx.Repo.GetObjectFormat(), refShortName, 7) { - ctx.Repo.IsViewCommit = true ctx.Repo.RefFullName = git.RefNameFromCommit(refShortName) ctx.Repo.CommitID = refShortName @@ -915,13 +899,10 @@ func RepoRefByType(detectRefType git.RefType) func(*Context) { ctx.Data["RefTypeNameSubURL"] = ctx.Repo.RefTypeNameSubURL() ctx.Data["TreePath"] = ctx.Repo.TreePath - ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch ctx.Data["BranchName"] = ctx.Repo.BranchName - ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag ctx.Data["TagName"] = ctx.Repo.TagName - ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit ctx.Data["CommitID"] = ctx.Repo.CommitID ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch() // only used by the branch selector dropdown: AllowCreateNewRef diff --git a/templates/repo/blame.tmpl b/templates/repo/blame.tmpl index f8bd22074f..05f79612bd 100644 --- a/templates/repo/blame.tmpl +++ b/templates/repo/blame.tmpl @@ -18,7 +18,7 @@
{{ctx.Locale.Tr "repo.file_raw"}} - {{if not .IsViewCommit}} + {{if or .RefFullName.IsBranch .RefFullName.IsTag}} {{ctx.Locale.Tr "repo.file_permalink"}} {{end}} {{ctx.Locale.Tr "repo.normal_view"}} diff --git a/templates/repo/commit_page.tmpl b/templates/repo/commit_page.tmpl index bc63db9b62..2e3ddeb228 100644 --- a/templates/repo/commit_page.tmpl +++ b/templates/repo/commit_page.tmpl @@ -54,13 +54,11 @@

- {{/*FIXME: CurrentRefShortName seems not making sense here (old code), - because the "commit page" has no "$.BranchName" info, so only using DefaultBranch should be enough */}} {{template "repo/branch_dropdown" dict "Repository" .Repository "ShowTabBranches" true "CurrentRefType" "branch" - "CurrentRefShortName" (or $.BranchName $.Repository.DefaultBranch) + "CurrentRefShortName" $.Repository.DefaultBranch "RefFormActionTemplate" (print "{RepoLink}/_cherrypick/" .CommitID "/{RefShortName}") }}
diff --git a/templates/repo/commits.tmpl b/templates/repo/commits.tmpl index d80d4ac276..07c6b5f618 100644 --- a/templates/repo/commits.tmpl +++ b/templates/repo/commits.tmpl @@ -5,24 +5,13 @@ {{template "repo/sub_menu" .}}
- {{- /* for /owner/repo/commits/branch/the-name */ -}} - {{- $branchDropdownCurrentRefType := "branch" -}} - {{- $branchDropdownCurrentRefShortName := .BranchName -}} - {{- if .IsViewTag -}} - {{- /* for /owner/repo/commits/tag/the-name */ -}} - {{- $branchDropdownCurrentRefType = "tag" -}} - {{- $branchDropdownCurrentRefShortName = .TagName -}} - {{- else if .IsViewCommit -}} - {{- /* for /owner/repo/commits/commit/000000 */ -}} - {{- $branchDropdownCurrentRefType = "commit" -}} - {{- $branchDropdownCurrentRefShortName = ShortSha .CommitID -}} - {{- end -}} + {{- /* for /owner/repo/commits/{RefType}/{RefShortName} */ -}} {{- template "repo/branch_dropdown" dict "Repository" .Repository "ShowTabBranches" true "ShowTabTags" true - "CurrentRefType" $branchDropdownCurrentRefType - "CurrentRefShortName" $branchDropdownCurrentRefShortName + "CurrentRefType" .RefFullName.RefType + "CurrentRefShortName" .RefFullName.ShortName "CurrentTreePath" .TreePath "RefLinkTemplate" "{RepoLink}/commits/{RefType}/{RefShortName}/{TreePath}" "AllowCreateNewRef" .CanCreateBranch diff --git a/templates/repo/home.tmpl b/templates/repo/home.tmpl index 86ad162908..31a8167b4b 100644 --- a/templates/repo/home.tmpl +++ b/templates/repo/home.tmpl @@ -24,30 +24,19 @@ {{template "repo/sub_menu" .}}
- {{- /* for repo home (default branch) and /owner/repo/src/branch/the-name */ -}} - {{- $branchDropdownCurrentRefType := "branch" -}} - {{- $branchDropdownCurrentRefShortName := .BranchName -}} - {{- if .IsViewTag -}} - {{- /* for /owner/repo/src/tag/the-name */ -}} - {{- $branchDropdownCurrentRefType = "tag" -}} - {{- $branchDropdownCurrentRefShortName = .TagName -}} - {{- else if .IsViewCommit -}} - {{- /* for /owner/repo/src/commit/000000 */ -}} - {{- $branchDropdownCurrentRefType = "commit" -}} - {{- $branchDropdownCurrentRefShortName = ShortSha .CommitID -}} - {{- end -}} + {{- /* for repo home (default branch) and /owner/repo/src/{RefType}/{RefShortName} */ -}} {{- template "repo/branch_dropdown" dict "Repository" .Repository "ShowTabBranches" true "ShowTabTags" true - "CurrentRefType" $branchDropdownCurrentRefType - "CurrentRefShortName" $branchDropdownCurrentRefShortName + "CurrentRefType" .RefFullName.RefType + "CurrentRefShortName" .RefFullName.ShortName "CurrentTreePath" .TreePath "RefLinkTemplate" "{RepoLink}/src/{RefType}/{RefShortName}/{TreePath}" "AllowCreateNewRef" .CanCreateBranch "ShowViewAllRefsEntry" true -}} - {{if and .CanCompareOrPull .IsViewBranch (not .Repository.IsArchived)}} + {{if and .CanCompareOrPull .RefFullName.IsBranch (not .Repository.IsArchived)}} {{$cmpBranch := ""}} {{if ne .Repository.ID .BaseRepo.ID}} {{$cmpBranch = printf "%s/%s:" (.Repository.OwnerName|PathEscape) (.Repository.Name|PathEscape)}} @@ -65,7 +54,7 @@ {{ctx.Locale.Tr "repo.find_file.go_to_file"}} {{end}} - {{if and .CanWriteCode .IsViewBranch (not .Repository.IsMirror) (not .Repository.IsArchived) (not .IsViewFile)}} + {{if and .CanWriteCode .RefFullName.IsBranch (not .Repository.IsMirror) (not .Repository.IsArchived) (not .IsViewFile)}}
diff --git a/templates/repo/view_file.tmpl b/templates/repo/view_file.tmpl index 69c1641613..4907d87301 100644 --- a/templates/repo/view_file.tmpl +++ b/templates/repo/view_file.tmpl @@ -42,7 +42,7 @@ {{if not .ReadmeInList}}
{{ctx.Locale.Tr "repo.file_raw"}} - {{if not .IsViewCommit}} + {{if or .RefFullName.IsBranch .RefFullName.IsTag}} {{ctx.Locale.Tr "repo.file_permalink"}} {{end}} {{if .IsRepresentableAsText}} From f6dbf0e7b36e6c460836b03ff0757839180852c5 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 15 Jan 2025 17:34:55 +0800 Subject: [PATCH 03/12] Fix incorrect TagName/BranchName usages (#33279) Add add a new test --- routers/web/repo/release.go | 1 + routers/web/repo/search.go | 2 +- routers/web/web.go | 2 +- services/context/repo.go | 4 ---- templates/repo/release_tag_header.tmpl | 2 +- tests/integration/release_test.go | 26 +++++++++++++++++--------- 6 files changed, 21 insertions(+), 16 deletions(-) diff --git a/routers/web/repo/release.go b/routers/web/repo/release.go index 19b83915af..284fd27abf 100644 --- a/routers/web/repo/release.go +++ b/routers/web/repo/release.go @@ -295,6 +295,7 @@ func SingleRelease(ctx *context.Context) { } ctx.Data["PageIsSingleTag"] = release.IsTag + ctx.Data["SingleReleaseTagName"] = release.TagName if release.IsTag { ctx.Data["Title"] = release.TagName } else { diff --git a/routers/web/repo/search.go b/routers/web/repo/search.go index c60301475f..d589586dad 100644 --- a/routers/web/repo/search.go +++ b/routers/web/repo/search.go @@ -70,7 +70,7 @@ func Search(ctx *context.Context) { res, err := git.GrepSearch(ctx, ctx.Repo.GitRepo, prepareSearch.Keyword, git.GrepOptions{ ContextLineNumber: 1, IsFuzzy: prepareSearch.IsFuzzy, - RefName: git.RefNameFromBranch(ctx.Repo.BranchName).String(), // BranchName should be default branch or the first existing branch + RefName: git.RefNameFromBranch(ctx.Repo.Repository.DefaultBranch).String(), // BranchName should be default branch or the first existing branch PathspecList: indexSettingToGitGrepPathspecList(), }) if err != nil { diff --git a/routers/web/web.go b/routers/web/web.go index 1fc5bc6545..1f72beadac 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -1592,7 +1592,7 @@ func registerRoutes(m *web.Router) { m.Get("/watchers", repo.Watchers) m.Get("/search", reqUnitCodeReader, repo.Search) m.Post("/action/{action}", reqSignIn, repo.Action) - }, optSignIn, context.RepoAssignment, context.RepoRef()) + }, optSignIn, context.RepoAssignment) common.AddOwnerRepoGitLFSRoutes(m, optSignInIgnoreCsrf, lfsServerEnabled) // "/{username}/{reponame}/{lfs-paths}": git-lfs support diff --git a/services/context/repo.go b/services/context/repo.go index 6c348b99cb..ef54b9cee8 100644 --- a/services/context/repo.go +++ b/services/context/repo.go @@ -56,7 +56,6 @@ type Repository struct { // RefFullName is the full ref name that the user is viewing RefFullName git.RefName BranchName string // it is the RefFullName's short name if its type is "branch" - TagName string // it is the RefFullName's short name if its type is "tag" TreePath string // Commit it is always set to the commit for the branch or tag, or just the commit that the user is viewing @@ -851,7 +850,6 @@ func RepoRefByType(detectRefType git.RefType) func(*Context) { ctx.Repo.CommitID = ctx.Repo.Commit.ID.String() } else if refType == git.RefTypeTag && ctx.Repo.GitRepo.IsTagExist(refShortName) { ctx.Repo.RefFullName = git.RefNameFromTag(refShortName) - ctx.Repo.TagName = refShortName ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refShortName) if err != nil { @@ -901,8 +899,6 @@ func RepoRefByType(detectRefType git.RefType) func(*Context) { ctx.Data["BranchName"] = ctx.Repo.BranchName - ctx.Data["TagName"] = ctx.Repo.TagName - ctx.Data["CommitID"] = ctx.Repo.CommitID ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch() // only used by the branch selector dropdown: AllowCreateNewRef diff --git a/templates/repo/release_tag_header.tmpl b/templates/repo/release_tag_header.tmpl index f96c76864f..fb17cf44c4 100644 --- a/templates/repo/release_tag_header.tmpl +++ b/templates/repo/release_tag_header.tmpl @@ -17,7 +17,7 @@ {{end}} {{if and (not .PageIsTagList) .CanCreateRelease}} - + {{ctx.Locale.Tr "repo.release.new_release"}} {{end}} diff --git a/tests/integration/release_test.go b/tests/integration/release_test.go index d3c4ed6a83..1a7f9e38b5 100644 --- a/tests/integration/release_test.go +++ b/tests/integration/release_test.go @@ -173,17 +173,25 @@ func TestViewReleaseListNoLogin(t *testing.T) { }, commitsToMain) } -func TestViewSingleReleaseNoLogin(t *testing.T) { +func TestViewSingleRelease(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequest(t, "GET", "/user2/repo-release/releases/tag/v1.0") - resp := MakeRequest(t, req, http.StatusOK) - - htmlDoc := NewHTMLParser(t, resp.Body) - // check the "number of commits to main since this release" - releaseList := htmlDoc.doc.Find("#release-list .ahead > a") - assert.EqualValues(t, 1, releaseList.Length()) - assert.EqualValues(t, "3 commits", releaseList.First().Text()) + t.Run("NoLogin", func(t *testing.T) { + req := NewRequest(t, "GET", "/user2/repo-release/releases/tag/v1.0") + resp := MakeRequest(t, req, http.StatusOK) + htmlDoc := NewHTMLParser(t, resp.Body) + // check the "number of commits to main since this release" + releaseList := htmlDoc.doc.Find("#release-list .ahead > a") + assert.EqualValues(t, 1, releaseList.Length()) + assert.EqualValues(t, "3 commits", releaseList.First().Text()) + }) + t.Run("Login", func(t *testing.T) { + session := loginUser(t, "user1") + req := NewRequest(t, "GET", "/user2/repo1/releases/tag/delete-tag") // "delete-tag" is the only one with is_tag=true (although strange name) + resp := session.MakeRequest(t, req, http.StatusOK) + // the New Release button should contain the tag name + assert.Contains(t, resp.Body.String(), ``) + }) } func TestViewReleaseListLogin(t *testing.T) { From d0962ce3da424f0a1df2acf595b20066d6e55128 Mon Sep 17 00:00:00 2001 From: Zettat123 Date: Wed, 15 Jan 2025 21:34:30 +0800 Subject: [PATCH 04/12] Move some Actions related functions from `routers` to `services` (#33280) Move the main logic of `generateTaskContext` and `findTaskNeeds` to the `services` layer. This is a part of #32751, since we need the git context and `needs` to parse the concurrency expressions. --------- Co-authored-by: Lunny Xiao Co-authored-by: wxiaoguang --- routers/api/actions/runner/main_test.go | 14 -- routers/api/actions/runner/utils.go | 144 ++-------------- services/actions/context.go | 161 ++++++++++++++++++ .../actions/context_test.go | 7 +- services/actions/init_test.go | 4 +- tests/integration/actions_job_test.go | 91 ++++++++++ 6 files changed, 268 insertions(+), 153 deletions(-) delete mode 100644 routers/api/actions/runner/main_test.go create mode 100644 services/actions/context.go rename routers/api/actions/runner/utils_test.go => services/actions/context_test.go (75%) diff --git a/routers/api/actions/runner/main_test.go b/routers/api/actions/runner/main_test.go deleted file mode 100644 index 1e80a4f5ca..0000000000 --- a/routers/api/actions/runner/main_test.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2024 The Gitea Authors. All rights reserved. -// SPDX-License-Identifier: MIT - -package runner - -import ( - "testing" - - "code.gitea.io/gitea/models/unittest" -) - -func TestMain(m *testing.M) { - unittest.MainTest(m) -} diff --git a/routers/api/actions/runner/utils.go b/routers/api/actions/runner/utils.go index 944bbbc7c5..0fd7ca5c44 100644 --- a/routers/api/actions/runner/utils.go +++ b/routers/api/actions/runner/utils.go @@ -8,14 +8,8 @@ import ( "fmt" actions_model "code.gitea.io/gitea/models/actions" - "code.gitea.io/gitea/models/db" secret_model "code.gitea.io/gitea/models/secret" - actions_module "code.gitea.io/gitea/modules/actions" - "code.gitea.io/gitea/modules/container" - "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/services/actions" runnerv1 "code.gitea.io/actions-proto-go/runner/v1" @@ -65,82 +59,16 @@ func pickTask(ctx context.Context, runner *actions_model.ActionRunner) (*runnerv } func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct { - event := map[string]any{} - _ = json.Unmarshal([]byte(t.Job.Run.EventPayload), &event) - - // TriggerEvent is added in https://github.com/go-gitea/gitea/pull/25229 - // This fallback is for the old ActionRun that doesn't have the TriggerEvent field - // and should be removed in 1.22 - eventName := t.Job.Run.TriggerEvent - if eventName == "" { - eventName = t.Job.Run.Event.Event() - } - - baseRef := "" - headRef := "" - ref := t.Job.Run.Ref - sha := t.Job.Run.CommitSHA - if pullPayload, err := t.Job.Run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil { - baseRef = pullPayload.PullRequest.Base.Ref - headRef = pullPayload.PullRequest.Head.Ref - - // if the TriggerEvent is pull_request_target, ref and sha need to be set according to the base of pull request - // In GitHub's documentation, ref should be the branch or tag that triggered workflow. But when the TriggerEvent is pull_request_target, - // the ref will be the base branch. - if t.Job.Run.TriggerEvent == actions_module.GithubEventPullRequestTarget { - ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name - sha = pullPayload.PullRequest.Base.Sha - } - } - - refName := git.RefName(ref) - giteaRuntimeToken, err := actions.CreateAuthorizationToken(t.ID, t.Job.RunID, t.JobID) if err != nil { log.Error("actions.CreateAuthorizationToken failed: %v", err) } - taskContext, err := structpb.NewStruct(map[string]any{ - // standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context - "action": "", // string, The name of the action currently running, or the id of a step. GitHub removes special characters, and uses the name __run when the current step runs a script without an id. If you use the same action more than once in the same job, the name will include a suffix with the sequence number with underscore before it. For example, the first script you run will have the name __run, and the second script will be named __run_2. Similarly, the second invocation of actions/checkout will be actionscheckout2. - "action_path": "", // string, The path where an action is located. This property is only supported in composite actions. You can use this path to access files located in the same repository as the action. - "action_ref": "", // string, For a step executing an action, this is the ref of the action being executed. For example, v2. - "action_repository": "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout. - "action_status": "", // string, For a composite action, the current result of the composite action. - "actor": t.Job.Run.TriggerUser.Name, // string, The username of the user that triggered the initial workflow run. If the workflow run is a re-run, this value may differ from github.triggering_actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges. - "api_url": setting.AppURL + "api/v1", // string, The URL of the GitHub REST API. - "base_ref": baseRef, // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. - "env": "", // string, Path on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions." - "event": event, // object, The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload. - "event_name": eventName, // string, The name of the event that triggered the workflow run. - "event_path": "", // string, The path to the file on the runner that contains the full event webhook payload. - "graphql_url": "", // string, The URL of the GitHub GraphQL API. - "head_ref": headRef, // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. - "job": fmt.Sprint(t.JobID), // string, The job_id of the current job. - "ref": ref, // string, The fully-formed ref of the branch or tag that triggered the workflow run. For workflows triggered by push, this is the branch or tag ref that was pushed. For workflows triggered by pull_request, this is the pull request merge branch. For workflows triggered by release, this is the release tag created. For other triggers, this is the branch or tag ref that triggered the workflow run. This is only set if a branch or tag is available for the event type. The ref given is fully-formed, meaning that for branches the format is refs/heads/, for pull requests it is refs/pull//merge, and for tags it is refs/tags/. For example, refs/heads/feature-branch-1. - "ref_name": refName.ShortName(), // string, The short ref name of the branch or tag that triggered the workflow run. This value matches the branch or tag name shown on GitHub. For example, feature-branch-1. - "ref_protected": false, // boolean, true if branch protections are configured for the ref that triggered the workflow run. - "ref_type": string(refName.RefType()), // string, The type of ref that triggered the workflow run. Valid values are branch or tag. - "path": "", // string, Path on the runner to the file that sets system PATH variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions." - "repository": t.Job.Run.Repo.OwnerName + "/" + t.Job.Run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World. - "repository_owner": t.Job.Run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat. - "repositoryUrl": t.Job.Run.Repo.HTMLURL(), // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git. - "retention_days": "", // string, The number of days that workflow run logs and artifacts are kept. - "run_id": fmt.Sprint(t.Job.RunID), // string, A unique number for each workflow run within a repository. This number does not change if you re-run the workflow run. - "run_number": fmt.Sprint(t.Job.Run.Index), // string, A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run. - "run_attempt": fmt.Sprint(t.Job.Attempt), // string, A unique number for each attempt of a particular workflow run in a repository. This number begins at 1 for the workflow run's first attempt, and increments with each re-run. - "secret_source": "Actions", // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces. - "server_url": setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com. - "sha": sha, // string, The commit SHA that triggered the workflow. The value of this commit SHA depends on the event that triggered the workflow. For more information, see "Events that trigger workflows." For example, ffac537e6cbbf934b08745a378932722df287a53. - "token": t.Token, // string, A token to authenticate on behalf of the GitHub App installed on your repository. This is functionally equivalent to the GITHUB_TOKEN secret. For more information, see "Automatic token authentication." - "triggering_actor": "", // string, The username of the user that initiated the workflow run. If the workflow run is a re-run, this value may differ from github.actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges. - "workflow": t.Job.Run.WorkflowID, // string, The name of the workflow. If the workflow file doesn't specify a name, the value of this property is the full path of the workflow file in the repository. - "workspace": "", // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action. + gitCtx := actions.GenerateGiteaContext(t.Job.Run, t.Job) + gitCtx["token"] = t.Token + gitCtx["gitea_runtime_token"] = giteaRuntimeToken - // additional contexts - "gitea_default_actions_url": setting.Actions.DefaultActionsURL.URL(), - "gitea_runtime_token": giteaRuntimeToken, - }) + taskContext, err := structpb.NewStruct(gitCtx) if err != nil { log.Error("structpb.NewStruct failed: %v", err) } @@ -150,68 +78,18 @@ func generateTaskContext(t *actions_model.ActionTask) *structpb.Struct { func findTaskNeeds(ctx context.Context, task *actions_model.ActionTask) (map[string]*runnerv1.TaskNeed, error) { if err := task.LoadAttributes(ctx); err != nil { - return nil, fmt.Errorf("LoadAttributes: %w", err) + return nil, fmt.Errorf("task LoadAttributes: %w", err) } - if len(task.Job.Needs) == 0 { - return nil, nil - } - needs := container.SetOf(task.Job.Needs...) - - jobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{RunID: task.Job.RunID}) + taskNeeds, err := actions.FindTaskNeeds(ctx, task.Job) if err != nil { - return nil, fmt.Errorf("FindRunJobs: %w", err) + return nil, err } - - jobIDJobs := make(map[string][]*actions_model.ActionRunJob) - for _, job := range jobs { - jobIDJobs[job.JobID] = append(jobIDJobs[job.JobID], job) - } - - ret := make(map[string]*runnerv1.TaskNeed, len(needs)) - for jobID, jobsWithSameID := range jobIDJobs { - if !needs.Contains(jobID) { - continue - } - var jobOutputs map[string]string - for _, job := range jobsWithSameID { - if job.TaskID == 0 || !job.Status.IsDone() { - // it shouldn't happen, or the job has been rerun - continue - } - got, err := actions_model.FindTaskOutputByTaskID(ctx, job.TaskID) - if err != nil { - return nil, fmt.Errorf("FindTaskOutputByTaskID: %w", err) - } - outputs := make(map[string]string, len(got)) - for _, v := range got { - outputs[v.OutputKey] = v.OutputValue - } - if len(jobOutputs) == 0 { - jobOutputs = outputs - } else { - jobOutputs = mergeTwoOutputs(outputs, jobOutputs) - } - } + ret := make(map[string]*runnerv1.TaskNeed, len(taskNeeds)) + for jobID, taskNeed := range taskNeeds { ret[jobID] = &runnerv1.TaskNeed{ - Outputs: jobOutputs, - Result: runnerv1.Result(actions_model.AggregateJobStatus(jobsWithSameID)), + Outputs: taskNeed.Outputs, + Result: runnerv1.Result(taskNeed.Result), } } - return ret, nil } - -// mergeTwoOutputs merges two outputs from two different ActionRunJobs -// Values with the same output name may be overridden. The user should ensure the output names are unique. -// See https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#using-job-outputs-in-a-matrix-job -func mergeTwoOutputs(o1, o2 map[string]string) map[string]string { - ret := make(map[string]string, len(o1)) - for k1, v1 := range o1 { - if len(v1) > 0 { - ret[k1] = v1 - } else { - ret[k1] = o2[k1] - } - } - return ret -} diff --git a/services/actions/context.go b/services/actions/context.go new file mode 100644 index 0000000000..d14728fae4 --- /dev/null +++ b/services/actions/context.go @@ -0,0 +1,161 @@ +// Copyright 2025 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package actions + +import ( + "context" + "fmt" + + actions_model "code.gitea.io/gitea/models/actions" + "code.gitea.io/gitea/models/db" + actions_module "code.gitea.io/gitea/modules/actions" + "code.gitea.io/gitea/modules/container" + "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/json" + "code.gitea.io/gitea/modules/setting" +) + +// GenerateGiteaContext generate the gitea context without token and gitea_runtime_token +// job can be nil when generating a context for parsing workflow-level expressions +func GenerateGiteaContext(run *actions_model.ActionRun, job *actions_model.ActionRunJob) map[string]any { + event := map[string]any{} + _ = json.Unmarshal([]byte(run.EventPayload), &event) + + baseRef := "" + headRef := "" + ref := run.Ref + sha := run.CommitSHA + if pullPayload, err := run.GetPullRequestEventPayload(); err == nil && pullPayload.PullRequest != nil && pullPayload.PullRequest.Base != nil && pullPayload.PullRequest.Head != nil { + baseRef = pullPayload.PullRequest.Base.Ref + headRef = pullPayload.PullRequest.Head.Ref + + // if the TriggerEvent is pull_request_target, ref and sha need to be set according to the base of pull request + // In GitHub's documentation, ref should be the branch or tag that triggered workflow. But when the TriggerEvent is pull_request_target, + // the ref will be the base branch. + if run.TriggerEvent == actions_module.GithubEventPullRequestTarget { + ref = git.BranchPrefix + pullPayload.PullRequest.Base.Name + sha = pullPayload.PullRequest.Base.Sha + } + } + + refName := git.RefName(ref) + + gitContext := map[string]any{ + // standard contexts, see https://docs.github.com/en/actions/learn-github-actions/contexts#github-context + "action": "", // string, The name of the action currently running, or the id of a step. GitHub removes special characters, and uses the name __run when the current step runs a script without an id. If you use the same action more than once in the same job, the name will include a suffix with the sequence number with underscore before it. For example, the first script you run will have the name __run, and the second script will be named __run_2. Similarly, the second invocation of actions/checkout will be actionscheckout2. + "action_path": "", // string, The path where an action is located. This property is only supported in composite actions. You can use this path to access files located in the same repository as the action. + "action_ref": "", // string, For a step executing an action, this is the ref of the action being executed. For example, v2. + "action_repository": "", // string, For a step executing an action, this is the owner and repository name of the action. For example, actions/checkout. + "action_status": "", // string, For a composite action, the current result of the composite action. + "actor": run.TriggerUser.Name, // string, The username of the user that triggered the initial workflow run. If the workflow run is a re-run, this value may differ from github.triggering_actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges. + "api_url": setting.AppURL + "api/v1", // string, The URL of the GitHub REST API. + "base_ref": baseRef, // string, The base_ref or target branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. + "env": "", // string, Path on the runner to the file that sets environment variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions." + "event": event, // object, The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload. + "event_name": run.TriggerEvent, // string, The name of the event that triggered the workflow run. + "event_path": "", // string, The path to the file on the runner that contains the full event webhook payload. + "graphql_url": "", // string, The URL of the GitHub GraphQL API. + "head_ref": headRef, // string, The head_ref or source branch of the pull request in a workflow run. This property is only available when the event that triggers a workflow run is either pull_request or pull_request_target. + "job": "", // string, The job_id of the current job. + "ref": ref, // string, The fully-formed ref of the branch or tag that triggered the workflow run. For workflows triggered by push, this is the branch or tag ref that was pushed. For workflows triggered by pull_request, this is the pull request merge branch. For workflows triggered by release, this is the release tag created. For other triggers, this is the branch or tag ref that triggered the workflow run. This is only set if a branch or tag is available for the event type. The ref given is fully-formed, meaning that for branches the format is refs/heads/, for pull requests it is refs/pull//merge, and for tags it is refs/tags/. For example, refs/heads/feature-branch-1. + "ref_name": refName.ShortName(), // string, The short ref name of the branch or tag that triggered the workflow run. This value matches the branch or tag name shown on GitHub. For example, feature-branch-1. + "ref_protected": false, // boolean, true if branch protections are configured for the ref that triggered the workflow run. + "ref_type": string(refName.RefType()), // string, The type of ref that triggered the workflow run. Valid values are branch or tag. + "path": "", // string, Path on the runner to the file that sets system PATH variables from workflow commands. This file is unique to the current step and is a different file for each step in a job. For more information, see "Workflow commands for GitHub Actions." + "repository": run.Repo.OwnerName + "/" + run.Repo.Name, // string, The owner and repository name. For example, Codertocat/Hello-World. + "repository_owner": run.Repo.OwnerName, // string, The repository owner's name. For example, Codertocat. + "repositoryUrl": run.Repo.HTMLURL(), // string, The Git URL to the repository. For example, git://github.com/codertocat/hello-world.git. + "retention_days": "", // string, The number of days that workflow run logs and artifacts are kept. + "run_id": "", // string, A unique number for each workflow run within a repository. This number does not change if you re-run the workflow run. + "run_number": fmt.Sprint(run.Index), // string, A unique number for each run of a particular workflow in a repository. This number begins at 1 for the workflow's first run, and increments with each new run. This number does not change if you re-run the workflow run. + "run_attempt": "", // string, A unique number for each attempt of a particular workflow run in a repository. This number begins at 1 for the workflow run's first attempt, and increments with each re-run. + "secret_source": "Actions", // string, The source of a secret used in a workflow. Possible values are None, Actions, Dependabot, or Codespaces. + "server_url": setting.AppURL, // string, The URL of the GitHub server. For example: https://github.com. + "sha": sha, // string, The commit SHA that triggered the workflow. The value of this commit SHA depends on the event that triggered the workflow. For more information, see "Events that trigger workflows." For example, ffac537e6cbbf934b08745a378932722df287a53. + "triggering_actor": "", // string, The username of the user that initiated the workflow run. If the workflow run is a re-run, this value may differ from github.actor. Any workflow re-runs will use the privileges of github.actor, even if the actor initiating the re-run (github.triggering_actor) has different privileges. + "workflow": run.WorkflowID, // string, The name of the workflow. If the workflow file doesn't specify a name, the value of this property is the full path of the workflow file in the repository. + "workspace": "", // string, The default working directory on the runner for steps, and the default location of your repository when using the checkout action. + + // additional contexts + "gitea_default_actions_url": setting.Actions.DefaultActionsURL.URL(), + } + + if job != nil { + gitContext["job"] = job.JobID + gitContext["run_id"] = fmt.Sprint(job.RunID) + gitContext["run_attempt"] = fmt.Sprint(job.Attempt) + } + + return gitContext +} + +type TaskNeed struct { + Result actions_model.Status + Outputs map[string]string +} + +// FindTaskNeeds finds the `needs` for the task by the task's job +func FindTaskNeeds(ctx context.Context, job *actions_model.ActionRunJob) (map[string]*TaskNeed, error) { + if len(job.Needs) == 0 { + return nil, nil + } + needs := container.SetOf(job.Needs...) + + jobs, err := db.Find[actions_model.ActionRunJob](ctx, actions_model.FindRunJobOptions{RunID: job.RunID}) + if err != nil { + return nil, fmt.Errorf("FindRunJobs: %w", err) + } + + jobIDJobs := make(map[string][]*actions_model.ActionRunJob) + for _, job := range jobs { + jobIDJobs[job.JobID] = append(jobIDJobs[job.JobID], job) + } + + ret := make(map[string]*TaskNeed, len(needs)) + for jobID, jobsWithSameID := range jobIDJobs { + if !needs.Contains(jobID) { + continue + } + var jobOutputs map[string]string + for _, job := range jobsWithSameID { + if job.TaskID == 0 || !job.Status.IsDone() { + // it shouldn't happen, or the job has been rerun + continue + } + got, err := actions_model.FindTaskOutputByTaskID(ctx, job.TaskID) + if err != nil { + return nil, fmt.Errorf("FindTaskOutputByTaskID: %w", err) + } + outputs := make(map[string]string, len(got)) + for _, v := range got { + outputs[v.OutputKey] = v.OutputValue + } + if len(jobOutputs) == 0 { + jobOutputs = outputs + } else { + jobOutputs = mergeTwoOutputs(outputs, jobOutputs) + } + } + ret[jobID] = &TaskNeed{ + Outputs: jobOutputs, + Result: actions_model.AggregateJobStatus(jobsWithSameID), + } + } + return ret, nil +} + +// mergeTwoOutputs merges two outputs from two different ActionRunJobs +// Values with the same output name may be overridden. The user should ensure the output names are unique. +// See https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#using-job-outputs-in-a-matrix-job +func mergeTwoOutputs(o1, o2 map[string]string) map[string]string { + ret := make(map[string]string, len(o1)) + for k1, v1 := range o1 { + if len(v1) > 0 { + ret[k1] = v1 + } else { + ret[k1] = o2[k1] + } + } + return ret +} diff --git a/routers/api/actions/runner/utils_test.go b/services/actions/context_test.go similarity index 75% rename from routers/api/actions/runner/utils_test.go rename to services/actions/context_test.go index d7a6f84550..6ed094b289 100644 --- a/routers/api/actions/runner/utils_test.go +++ b/services/actions/context_test.go @@ -1,7 +1,7 @@ // Copyright 2024 The Gitea Authors. All rights reserved. // SPDX-License-Identifier: MIT -package runner +package actions import ( "context" @@ -13,12 +13,13 @@ import ( "github.com/stretchr/testify/assert" ) -func Test_findTaskNeeds(t *testing.T) { +func TestFindTaskNeeds(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) task := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionTask{ID: 51}) + job := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: task.JobID}) - ret, err := findTaskNeeds(context.Background(), task) + ret, err := FindTaskNeeds(context.Background(), job) assert.NoError(t, err) assert.Len(t, ret, 1) assert.Contains(t, ret, "job1") diff --git a/services/actions/init_test.go b/services/actions/init_test.go index 59c321ccd7..7ef0702204 100644 --- a/services/actions/init_test.go +++ b/services/actions/init_test.go @@ -17,9 +17,7 @@ import ( ) func TestMain(m *testing.M) { - unittest.MainTest(m, &unittest.TestOptions{ - FixtureFiles: []string{"action_runner_token.yml"}, - }) + unittest.MainTest(m) os.Exit(m.Run()) } diff --git a/tests/integration/actions_job_test.go b/tests/integration/actions_job_test.go index e13277678d..a0c06b06fd 100644 --- a/tests/integration/actions_job_test.go +++ b/tests/integration/actions_job_test.go @@ -4,17 +4,23 @@ package integration import ( + "context" "encoding/base64" "fmt" "net/http" "net/url" + "reflect" "testing" "time" actions_model "code.gitea.io/gitea/models/actions" auth_model "code.gitea.io/gitea/models/auth" + repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/json" + "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" runnerv1 "code.gitea.io/actions-proto-go/runner/v1" @@ -347,6 +353,91 @@ jobs: }) } +func TestActionsGiteaContext(t *testing.T) { + onGiteaRun(t, func(t *testing.T, u *url.URL) { + user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) + user2Session := loginUser(t, user2.Name) + user2Token := getTokenForLoggedInUser(t, user2Session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) + + apiBaseRepo := createActionsTestRepo(t, user2Token, "actions-gitea-context", false) + baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiBaseRepo.ID}) + user2APICtx := NewAPITestContext(t, baseRepo.OwnerName, baseRepo.Name, auth_model.AccessTokenScopeWriteRepository) + + runner := newMockRunner() + runner.registerAsRepoRunner(t, baseRepo.OwnerName, baseRepo.Name, "mock-runner", []string{"ubuntu-latest"}) + + // init the workflow + wfTreePath := ".gitea/workflows/pull.yml" + wfFileContent := `name: Pull Request +on: pull_request +jobs: + wf1-job: + runs-on: ubuntu-latest + steps: + - run: echo 'test the pull' +` + opts := getWorkflowCreateFileOptions(user2, baseRepo.DefaultBranch, fmt.Sprintf("create %s", wfTreePath), wfFileContent) + createWorkflowFile(t, user2Token, baseRepo.OwnerName, baseRepo.Name, wfTreePath, opts) + // user2 creates a pull request + doAPICreateFile(user2APICtx, "user2-patch.txt", &api.CreateFileOptions{ + FileOptions: api.FileOptions{ + NewBranchName: "user2/patch-1", + Message: "create user2-patch.txt", + Author: api.Identity{ + Name: user2.Name, + Email: user2.Email, + }, + Committer: api.Identity{ + Name: user2.Name, + Email: user2.Email, + }, + Dates: api.CommitDateOptions{ + Author: time.Now(), + Committer: time.Now(), + }, + }, + ContentBase64: base64.StdEncoding.EncodeToString([]byte("user2-fix")), + })(t) + apiPull, err := doAPICreatePullRequest(user2APICtx, baseRepo.OwnerName, baseRepo.Name, baseRepo.DefaultBranch, "user2/patch-1")(t) + assert.NoError(t, err) + task := runner.fetchTask(t) + gtCtx := task.Context.GetFields() + actionTask := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionTask{ID: task.Id}) + actionRunJob := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: actionTask.JobID}) + actionRun := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: actionRunJob.RunID}) + assert.NoError(t, actionRun.LoadAttributes(context.Background())) + + assert.Equal(t, user2.Name, gtCtx["actor"].GetStringValue()) + assert.Equal(t, setting.AppURL+"api/v1", gtCtx["api_url"].GetStringValue()) + assert.Equal(t, apiPull.Base.Ref, gtCtx["base_ref"].GetStringValue()) + runEvent := map[string]any{} + assert.NoError(t, json.Unmarshal([]byte(actionRun.EventPayload), &runEvent)) + assert.True(t, reflect.DeepEqual(gtCtx["event"].GetStructValue().AsMap(), runEvent)) + assert.Equal(t, actionRun.TriggerEvent, gtCtx["event_name"].GetStringValue()) + assert.Equal(t, apiPull.Head.Ref, gtCtx["head_ref"].GetStringValue()) + assert.Equal(t, actionRunJob.JobID, gtCtx["job"].GetStringValue()) + assert.Equal(t, actionRun.Ref, gtCtx["ref"].GetStringValue()) + assert.Equal(t, (git.RefName(actionRun.Ref)).ShortName(), gtCtx["ref_name"].GetStringValue()) + assert.False(t, gtCtx["ref_protected"].GetBoolValue()) + assert.Equal(t, string((git.RefName(actionRun.Ref)).RefType()), gtCtx["ref_type"].GetStringValue()) + assert.Equal(t, actionRun.Repo.OwnerName+"/"+actionRun.Repo.Name, gtCtx["repository"].GetStringValue()) + assert.Equal(t, actionRun.Repo.OwnerName, gtCtx["repository_owner"].GetStringValue()) + assert.Equal(t, actionRun.Repo.HTMLURL(), gtCtx["repositoryUrl"].GetStringValue()) + assert.Equal(t, fmt.Sprint(actionRunJob.RunID), gtCtx["run_id"].GetStringValue()) + assert.Equal(t, fmt.Sprint(actionRun.Index), gtCtx["run_number"].GetStringValue()) + assert.Equal(t, fmt.Sprint(actionRunJob.Attempt), gtCtx["run_attempt"].GetStringValue()) + assert.Equal(t, "Actions", gtCtx["secret_source"].GetStringValue()) + assert.Equal(t, setting.AppURL, gtCtx["server_url"].GetStringValue()) + assert.Equal(t, actionRun.CommitSHA, gtCtx["sha"].GetStringValue()) + assert.Equal(t, actionRun.WorkflowID, gtCtx["workflow"].GetStringValue()) + assert.Equal(t, setting.Actions.DefaultActionsURL.URL(), gtCtx["gitea_default_actions_url"].GetStringValue()) + token := gtCtx["token"].GetStringValue() + assert.Equal(t, actionTask.TokenLastEight, token[len(token)-8:]) + + doAPIDeleteRepository(user2APICtx)(t) + }) +} + func createActionsTestRepo(t *testing.T, authToken, repoName string, isPrivate bool) *api.Repository { req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{ Name: repoName, From 6659a381ea19acfc18eb5660bd6223a1e19147e4 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 15 Jan 2025 23:38:03 +0800 Subject: [PATCH 05/12] Fix closed dependency title (#33285) Fix #33283 --- templates/repo/issue/sidebar/issue_dependencies.tmpl | 6 +++--- web_src/css/repo.css | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/templates/repo/issue/sidebar/issue_dependencies.tmpl b/templates/repo/issue/sidebar/issue_dependencies.tmpl index 837bcd5670..17e9738c6f 100644 --- a/templates/repo/issue/sidebar/issue_dependencies.tmpl +++ b/templates/repo/issue/sidebar/issue_dependencies.tmpl @@ -22,7 +22,7 @@ {{range .BlockingDependencies}}
- + #{{.Issue.Index}} {{.Issue.Title | ctx.RenderUtils.RenderEmoji}}
@@ -54,7 +54,7 @@ {{range .BlockedByDependencies}}
- + #{{.Issue.Index}} {{.Issue.Title | ctx.RenderUtils.RenderEmoji}}
@@ -76,7 +76,7 @@
{{svg "octicon-lock" 16}} - + #{{.Issue.Index}} {{.Issue.Title | ctx.RenderUtils.RenderEmoji}}
diff --git a/web_src/css/repo.css b/web_src/css/repo.css index 22bbe3cc23..e86f81f13c 100644 --- a/web_src/css/repo.css +++ b/web_src/css/repo.css @@ -784,7 +784,7 @@ td .commit-summary { box-shadow: none; } -.repository.view.issue .ui.depending .item.is-closed .title { +.repository.view.issue .ui.depending .item.is-closed .issue-dependency-title { text-decoration: line-through; } From b15d01b0cec32f34fafc41eaa97887305b1376f7 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 16 Jan 2025 04:05:18 +0800 Subject: [PATCH 06/12] Prepare for support performance trace (#33286) For #32973 --- modules/web/handler.go | 4 ++-- modules/web/routing/context.go | 20 +++++++++++--------- routers/init.go | 2 +- routers/web/base.go | 4 ++-- routers/web/web.go | 2 +- services/context/base.go | 24 +++++++++++------------- 6 files changed, 28 insertions(+), 28 deletions(-) diff --git a/modules/web/handler.go b/modules/web/handler.go index 9a3e4a7f17..42a649714d 100644 --- a/modules/web/handler.go +++ b/modules/web/handler.go @@ -121,7 +121,7 @@ func wrapHandlerProvider[T http.Handler](hp func(next http.Handler) T, funcInfo return func(next http.Handler) http.Handler { h := hp(next) // this handle could be dynamically generated, so we can't use it for debug info return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - routing.UpdateFuncInfo(req.Context(), funcInfo) + defer routing.RecordFuncInfo(req.Context(), funcInfo)() h.ServeHTTP(resp, req) }) } @@ -157,7 +157,7 @@ func toHandlerProvider(handler any) func(next http.Handler) http.Handler { return // it's doing pre-check, just return } - routing.UpdateFuncInfo(req.Context(), funcInfo) + defer routing.RecordFuncInfo(req.Context(), funcInfo)() ret := fn.Call(argsIn) // handle the return value (no-op at the moment) diff --git a/modules/web/routing/context.go b/modules/web/routing/context.go index c5e85a415b..fbf371b839 100644 --- a/modules/web/routing/context.go +++ b/modules/web/routing/context.go @@ -12,16 +12,18 @@ type contextKeyType struct{} var contextKey contextKeyType -// UpdateFuncInfo updates a context's func info -func UpdateFuncInfo(ctx context.Context, funcInfo *FuncInfo) { - record, ok := ctx.Value(contextKey).(*requestRecord) - if !ok { - return - } +// RecordFuncInfo records a func info into context +func RecordFuncInfo(ctx context.Context, funcInfo *FuncInfo) (end func()) { + // TODO: reqCtx := reqctx.FromContext(ctx), add trace support + end = func() {} - record.lock.Lock() - record.funcInfo = funcInfo - record.lock.Unlock() + // save the func info into the context record + if record, ok := ctx.Value(contextKey).(*requestRecord); ok { + record.lock.Lock() + record.funcInfo = funcInfo + record.lock.Unlock() + } + return end } // MarkLongPolling marks the request is a long-polling request, and the logger may output different message for it diff --git a/routers/init.go b/routers/init.go index e7aa765bf0..744feee2f0 100644 --- a/routers/init.go +++ b/routers/init.go @@ -213,7 +213,7 @@ func NormalRoutes() *web.Router { } r.NotFound(func(w http.ResponseWriter, req *http.Request) { - routing.UpdateFuncInfo(req.Context(), routing.GetFuncInfo(http.NotFound, "GlobalNotFound")) + defer routing.RecordFuncInfo(req.Context(), routing.GetFuncInfo(http.NotFound, "GlobalNotFound"))() http.NotFound(w, req) }) return r diff --git a/routers/web/base.go b/routers/web/base.go index aa0b43c16a..abe11593f7 100644 --- a/routers/web/base.go +++ b/routers/web/base.go @@ -34,7 +34,7 @@ func storageHandler(storageSetting *setting.Storage, prefix string, objStore sto http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } - routing.UpdateFuncInfo(req.Context(), funcInfo) + defer routing.RecordFuncInfo(req.Context(), funcInfo)() rPath := strings.TrimPrefix(req.URL.Path, "/"+prefix+"/") rPath = util.PathJoinRelX(rPath) @@ -65,7 +65,7 @@ func storageHandler(storageSetting *setting.Storage, prefix string, objStore sto http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } - routing.UpdateFuncInfo(req.Context(), funcInfo) + defer routing.RecordFuncInfo(req.Context(), funcInfo)() rPath := strings.TrimPrefix(req.URL.Path, "/"+prefix+"/") rPath = util.PathJoinRelX(rPath) diff --git a/routers/web/web.go b/routers/web/web.go index 1f72beadac..7343fbd008 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -1622,7 +1622,7 @@ func registerRoutes(m *web.Router) { m.NotFound(func(w http.ResponseWriter, req *http.Request) { ctx := context.GetWebContext(req) - routing.UpdateFuncInfo(ctx, routing.GetFuncInfo(ctx.NotFound, "WebNotFound")) + defer routing.RecordFuncInfo(ctx, routing.GetFuncInfo(ctx.NotFound, "WebNotFound"))() ctx.NotFound("", nil) }) } diff --git a/services/context/base.go b/services/context/base.go index 7a39353e09..5db84f42a5 100644 --- a/services/context/base.go +++ b/services/context/base.go @@ -4,7 +4,6 @@ package context import ( - "context" "fmt" "html/template" "io" @@ -25,8 +24,7 @@ type BaseContextKeyType struct{} var BaseContextKey BaseContextKeyType type Base struct { - context.Context - reqctx.RequestDataStore + reqctx.RequestContext Resp ResponseWriter Req *http.Request @@ -172,19 +170,19 @@ func (b *Base) TrN(cnt any, key1, keyN string, args ...any) template.HTML { } func NewBaseContext(resp http.ResponseWriter, req *http.Request) *Base { - ds := reqctx.GetRequestDataStore(req.Context()) + reqCtx := reqctx.FromContext(req.Context()) b := &Base{ - Context: req.Context(), - RequestDataStore: ds, - Req: req, - Resp: WrapResponseWriter(resp), - Locale: middleware.Locale(resp, req), - Data: ds.GetData(), + RequestContext: reqCtx, + + Req: req, + Resp: WrapResponseWriter(resp), + Locale: middleware.Locale(resp, req), + Data: reqCtx.GetData(), } b.Req = b.Req.WithContext(b) - ds.SetContextValue(BaseContextKey, b) - ds.SetContextValue(translation.ContextKey, b.Locale) - ds.SetContextValue(httplib.RequestContextKey, b.Req) + reqCtx.SetContextValue(BaseContextKey, b) + reqCtx.SetContextValue(translation.ContextKey, b.Locale) + reqCtx.SetContextValue(httplib.RequestContextKey, b.Req) return b } From 4b21a6c792e1bc42ce0f824c7dd7d1426aad2d3b Mon Sep 17 00:00:00 2001 From: silverwind Date: Wed, 15 Jan 2025 21:26:17 +0100 Subject: [PATCH 07/12] Enable Typescript `noImplicitThis` (#33250) - Enable https://www.typescriptlang.org/tsconfig/#noImplicitThis - Wrap Vue Template-Syntax SFCs in [`defineComponent`](https://vuejs.org/api/general#definecomponent) which makes type inference and linter work better - Move `createApp` calls outside the SFCs into separate files - Use [`PropType`](https://vuejs.org/api/utility-types#proptype-t) where appropriate - Some top-level component properties changed order as dictated by the linter - Fix all tsc and lint issues that popped up during these refactors --- tsconfig.json | 1 + web_src/js/components/DashboardRepoList.vue | 14 +-- web_src/js/components/DiffCommitSelector.vue | 13 ++- web_src/js/components/DiffFileList.vue | 4 +- web_src/js/components/DiffFileTree.vue | 6 +- web_src/js/components/DiffFileTreeItem.vue | 4 +- .../js/components/PullRequestMergeForm.vue | 2 +- web_src/js/components/RepoActionView.vue | 104 ++++++------------ .../js/components/RepoActivityTopAuthors.vue | 18 +-- .../js/components/RepoBranchTagSelector.vue | 95 ++++++++-------- web_src/js/components/RepoContributors.vue | 9 +- web_src/js/features/common-organization.ts | 2 +- web_src/js/features/comp/WebHookEditor.ts | 6 +- web_src/js/features/dashboard.ts | 9 ++ web_src/js/features/install.ts | 14 +-- web_src/js/features/pull-view-file.ts | 2 +- web_src/js/features/repo-actions.ts | 47 ++++++++ web_src/js/features/repo-commit.ts | 2 +- web_src/js/features/repo-home.ts | 2 +- web_src/js/features/repo-issue.ts | 2 +- web_src/js/features/repo-settings.ts | 6 +- web_src/js/features/sshkey-helper.ts | 2 +- web_src/js/features/user-settings.ts | 2 +- web_src/js/index.ts | 5 +- web_src/js/modules/fomantic/dimmer.ts | 2 +- web_src/js/modules/fomantic/dropdown.ts | 12 +- web_src/js/modules/fomantic/modal.ts | 2 +- web_src/js/modules/tippy.ts | 2 +- web_src/js/svg.ts | 10 +- 29 files changed, 209 insertions(+), 190 deletions(-) create mode 100644 web_src/js/features/dashboard.ts create mode 100644 web_src/js/features/repo-actions.ts diff --git a/tsconfig.json b/tsconfig.json index d32cca0aaa..c41f9646d6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -23,6 +23,7 @@ "stripInternal": true, "strict": false, "strictFunctionTypes": true, + "noImplicitThis": true, "noUnusedLocals": true, "noUnusedParameters": true, "noPropertyAccessFromIndexSignature": false, diff --git a/web_src/js/components/DashboardRepoList.vue b/web_src/js/components/DashboardRepoList.vue index 41793d60ed..40ecbba5e3 100644 --- a/web_src/js/components/DashboardRepoList.vue +++ b/web_src/js/components/DashboardRepoList.vue @@ -1,5 +1,5 @@