From e14f6088f800ecc9624fd307651e3ed4b6d9a091 Mon Sep 17 00:00:00 2001 From: Wim Date: Tue, 18 Aug 2020 18:08:51 +0200 Subject: [PATCH 01/40] Remove hardcoded ES indexername (#12521) --- modules/indexer/issues/indexer.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/indexer/issues/indexer.go b/modules/indexer/issues/indexer.go index 42f08545764b..9edaef6bdd01 100644 --- a/modules/indexer/issues/indexer.go +++ b/modules/indexer/issues/indexer.go @@ -171,7 +171,7 @@ func InitIssueIndexer(syncReindex bool) { log.Debug("Created Bleve Indexer") case "elasticsearch": graceful.GetManager().RunWithShutdownFns(func(_, atTerminate func(context.Context, func())) { - issueIndexer, err := NewElasticSearchIndexer(setting.Indexer.IssueConnStr, "gitea_issues") + issueIndexer, err := NewElasticSearchIndexer(setting.Indexer.IssueConnStr, setting.Indexer.IssueIndexerName) if err != nil { log.Fatal("Unable to initialize Elastic Search Issue Indexer at connection: %s Error: %v", setting.Indexer.IssueConnStr, err) } From 1ca652c826c1053b86d5e4d4509b27c5f2beaf8a Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Wed, 19 Aug 2020 12:15:55 -0400 Subject: [PATCH 02/40] Add security policy to repo (#12536) --- SECURITY.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000000..9846a94f7e83 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,10 @@ +# Reporting security issues + +The Gitea maintainers take security seriously. +If you discover a security issue, please bring it to their attention right away! + +### Reporting a Vulnerability + +Please **DO NOT** file a public issue, instead send your report privately to `security@gitea.io`. + +Security reports are greatly appreciated and we will publicly thank you for it, although we keep your name confidential if you request it. From 1701d57fb2763cf8ab7e1d6ebeecccea85c5f987 Mon Sep 17 00:00:00 2001 From: zeripath Date: Wed, 19 Aug 2020 19:37:57 +0100 Subject: [PATCH 03/40] Set z-index for sticky diff box lower (#12537) Fix #12525 Signed-off-by: Andrew Thornton --- web_src/less/_repository.less | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web_src/less/_repository.less b/web_src/less/_repository.less index aaf729a8e17b..becc2e216ad0 100644 --- a/web_src/less/_repository.less +++ b/web_src/less/_repository.less @@ -1579,7 +1579,7 @@ &.sticky { position: sticky; top: 0; - z-index: 800; + z-index: 8; margin-bottom: 10px; border-bottom: 1px solid #d4d4d5; padding-left: 5px; From a5440fcb1ef7af8b1b3a828e30dc6af60f0744b2 Mon Sep 17 00:00:00 2001 From: zeripath Date: Wed, 19 Aug 2020 22:35:06 +0100 Subject: [PATCH 04/40] Report error if API merge is not allowed (#12528) #12496 demonstrated that the API merge needs to return some information as to why a merge has been disallowed with a status code 422. This PR ensures that a reason is always returned. Signed-off-by: Andrew Thornton Co-authored-by: Lauris BH --- routers/api/v1/repo/pull.go | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 21cc048a6929..126815839de2 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -759,8 +759,18 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { return } - if !pr.CanAutoMerge() || pr.HasMerged || pr.IsWorkInProgress() { - ctx.Status(http.StatusMethodNotAllowed) + if !pr.CanAutoMerge() { + ctx.Error(http.StatusMethodNotAllowed, "PR not in mergeable state", "Please try again later") + return + } + + if pr.HasMerged { + ctx.Error(http.StatusMethodNotAllowed, "PR already merged", "") + return + } + + if pr.IsWorkInProgress() { + ctx.Error(http.StatusMethodNotAllowed, "PR is a work in progress", "Work in progress PRs cannot be merged") return } @@ -812,7 +822,7 @@ func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) { if err := pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil { if models.IsErrInvalidMergeStyle(err) { - ctx.Status(http.StatusMethodNotAllowed) + ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", models.MergeStyle(form.Do))) return } else if models.IsErrMergeConflicts(err) { conflictError := err.(models.ErrMergeConflicts) From dcb543ac2a9cccc16dd161c820a4a002e8a83e82 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Thu, 20 Aug 2020 03:53:49 +0200 Subject: [PATCH 05/40] Show 2FA info on Admin Pannel: Users List (#12515) --- options/locale/locale_en-US.ini | 1 + routers/home.go | 1 + templates/admin/user/list.tmpl | 2 ++ templates/org/member/members.tmpl | 2 +- 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 9727f7d0d1ed..1cd94a46878d 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -1982,6 +1982,7 @@ users.full_name = Full Name users.activated = Activated users.admin = Admin users.restricted = Restricted +users.2fa = 2FA users.repos = Repos users.created = Created users.last_login = Last Sign-In diff --git a/routers/home.go b/routers/home.go index ae94207ade5c..5425670878ed 100644 --- a/routers/home.go +++ b/routers/home.go @@ -233,6 +233,7 @@ func RenderUserSearch(ctx *context.Context, opts *models.SearchUserOptions, tplN ctx.Data["Keyword"] = opts.Keyword ctx.Data["Total"] = count ctx.Data["Users"] = users + ctx.Data["UsersTwoFaStatus"] = models.UserList(users).GetTwoFaStatus() ctx.Data["ShowUserEmail"] = setting.UI.ShowUserEmail ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled diff --git a/templates/admin/user/list.tmpl b/templates/admin/user/list.tmpl index 3442d04195c4..d6dd7d5c0396 100644 --- a/templates/admin/user/list.tmpl +++ b/templates/admin/user/list.tmpl @@ -25,6 +25,7 @@ {{.i18n.Tr "admin.users.activated"}} {{.i18n.Tr "admin.users.admin"}} {{.i18n.Tr "admin.users.restricted"}} + {{.i18n.Tr "admin.users.2fa"}} {{.i18n.Tr "admin.users.repos"}} {{.i18n.Tr "admin.users.created"}} @@ -43,6 +44,7 @@ + {{.NumRepos}} {{.CreatedUnix.FormatShort}} {{if .LastLoginUnix}} diff --git a/templates/org/member/members.tmpl b/templates/org/member/members.tmpl index 1a65a02278da..1c33c55c5a6e 100644 --- a/templates/org/member/members.tmpl +++ b/templates/org/member/members.tmpl @@ -39,7 +39,7 @@
- 2FA + {{$.i18n.Tr "admin.users.2fa"}}
From d15bb17b78f8aee3285b5fadf924ac2dc569f790 Mon Sep 17 00:00:00 2001 From: zeripath Date: Thu, 20 Aug 2020 08:48:40 +0100 Subject: [PATCH 06/40] Default empty merger list to those with write permissions (#12535) Signed-off-by: Andrew Thornton Co-authored-by: Lunny Xiao --- models/branches.go | 5 +++-- modules/convert/convert.go | 6 +++++- services/pull/merge.go | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/models/branches.go b/models/branches.go index fc3c783b3a99..38aa79d2dc75 100644 --- a/models/branches.go +++ b/models/branches.go @@ -98,9 +98,10 @@ func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool { } // IsUserMergeWhitelisted checks if some user is whitelisted to merge to this branch -func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64) bool { +func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64, permissionInRepo Permission) bool { if !protectBranch.EnableMergeWhitelist { - return true + // Then we need to fall back on whether the user has write permission + return permissionInRepo.CanWrite(UnitTypeCode) } if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) { diff --git a/modules/convert/convert.go b/modules/convert/convert.go index ec18b130567f..94ecdd11503b 100644 --- a/modules/convert/convert.go +++ b/modules/convert/convert.go @@ -67,8 +67,12 @@ func ToBranch(repo *models.Repository, b *git.Branch, c *git.Commit, bp *models. } if user != nil { + permission, err := models.GetUserRepoPermission(repo, user) + if err != nil { + return nil, err + } branch.UserCanPush = bp.CanUserPush(user.ID) - branch.UserCanMerge = bp.IsUserMergeWhitelisted(user.ID) + branch.UserCanMerge = bp.IsUserMergeWhitelisted(user.ID, permission) } return branch, nil diff --git a/services/pull/merge.go b/services/pull/merge.go index 47521ce14770..27689384a58a 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -544,7 +544,7 @@ func IsUserAllowedToMerge(pr *models.PullRequest, p models.Permission, user *mod return false, err } - if (p.CanWrite(models.UnitTypeCode) && pr.ProtectedBranch == nil) || (pr.ProtectedBranch != nil && pr.ProtectedBranch.IsUserMergeWhitelisted(user.ID)) { + if (p.CanWrite(models.UnitTypeCode) && pr.ProtectedBranch == nil) || (pr.ProtectedBranch != nil && pr.ProtectedBranch.IsUserMergeWhitelisted(user.ID, p)) { return true, nil } From 0c9eb468e9a55f933286a45f366f41a7a4e79637 Mon Sep 17 00:00:00 2001 From: Gjergji Ramku Date: Thu, 20 Aug 2020 16:53:06 +0200 Subject: [PATCH 07/40] Fix typos (#12542) Signed-off-by: Gjergji Ramku --- routers/private/hook.go | 4 ++-- routers/private/serv.go | 2 +- routers/repo/compare.go | 2 +- services/gitdiff/gitdiff.go | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/routers/private/hook.go b/routers/private/hook.go index 215793c97092..6cdc5393f429 100644 --- a/routers/private/hook.go +++ b/routers/private/hook.go @@ -557,7 +557,7 @@ func SetDefaultBranch(ctx *macaron.Context) { if !git.IsErrUnsupportedVersion(err) { gitRepo.Close() ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ - "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err), + "Err": fmt.Sprintf("Unable to set default branch on repository: %s/%s Error: %v", ownerName, repoName, err), }) return } @@ -566,7 +566,7 @@ func SetDefaultBranch(ctx *macaron.Context) { if err := repo.UpdateDefaultBranch(); err != nil { ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ - "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err), + "Err": fmt.Sprintf("Unable to set default branch on repository: %s/%s Error: %v", ownerName, repoName, err), }) return } diff --git a/routers/private/serv.go b/routers/private/serv.go index d5b5fcc8f7e7..2e79fd79acda 100644 --- a/routers/private/serv.go +++ b/routers/private/serv.go @@ -80,7 +80,7 @@ func ServCommand(ctx *macaron.Context) { KeyID: keyID, } - // Now because we're not translating things properly let's just default some Engish strings here + // Now because we're not translating things properly let's just default some English strings here modeString := "read" if mode > models.AccessModeRead { modeString = "write to" diff --git a/routers/repo/compare.go b/routers/repo/compare.go index fb78ebdeacd4..f8a18f069670 100644 --- a/routers/repo/compare.go +++ b/routers/repo/compare.go @@ -598,7 +598,7 @@ func ExcerptBlob(ctx *context.Context) { direction := ctx.Query("direction") filePath := ctx.Query("path") gitRepo := ctx.Repo.GitRepo - chunkSize := gitdiff.BlobExceprtChunkSize + chunkSize := gitdiff.BlobExcerptChunkSize commit, err := gitRepo.GetCommit(commitID) if err != nil { ctx.Error(500, "GetCommit") diff --git a/services/gitdiff/gitdiff.go b/services/gitdiff/gitdiff.go index d50ae6ae2777..fd07a2ad9664 100644 --- a/services/gitdiff/gitdiff.go +++ b/services/gitdiff/gitdiff.go @@ -89,8 +89,8 @@ type DiffLineSectionInfo struct { RightHunkSize int } -// BlobExceprtChunkSize represent max lines of excerpt -const BlobExceprtChunkSize = 20 +// BlobExcerptChunkSize represent max lines of excerpt +const BlobExcerptChunkSize = 20 // GetType returns the type of a DiffLine. func (d *DiffLine) GetType() int { @@ -139,7 +139,7 @@ func (d *DiffLine) GetExpandDirection() DiffLineExpandDirection { } if d.SectionInfo.LastLeftIdx <= 0 && d.SectionInfo.LastRightIdx <= 0 { return DiffLineExpandUp - } else if d.SectionInfo.RightIdx-d.SectionInfo.LastRightIdx > BlobExceprtChunkSize && d.SectionInfo.RightHunkSize > 0 { + } else if d.SectionInfo.RightIdx-d.SectionInfo.LastRightIdx > BlobExcerptChunkSize && d.SectionInfo.RightHunkSize > 0 { return DiffLineExpandUpDown } else if d.SectionInfo.LeftHunkSize <= 0 && d.SectionInfo.RightHunkSize <= 0 { return DiffLineExpandDown From fff0204cab4df3b36ed746536a1601d79a5a27a1 Mon Sep 17 00:00:00 2001 From: Bagas Sanjaya Date: Thu, 20 Aug 2020 22:51:34 +0700 Subject: [PATCH 08/40] Add placeholder text for "Add SSH/GPG Key" forms (#12533) * Add placeholder text for "Add SSH/GPG Key" forms This commit add placeholder text for both Add SSH key and Add GPG key forms. * Localize placeholders Changes requested by @zeripath Co-authored-by: techknowlogick --- options/locale/locale_en-US.ini | 2 ++ templates/user/settings/keys_gpg.tmpl | 2 +- templates/user/settings/keys_ssh.tmpl | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 1cd94a46878d..c31d77e1a58e 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -500,6 +500,8 @@ ssh_helper = Need help? Have a look at GitHub's guide to Need help? Have a look at GitHub's guide about GPG. add_new_key = Add SSH Key add_new_gpg_key = Add GPG Key +key_content_ssh_placeholder = Begins with 'ssh-ed25519', 'ssh-rsa', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', or 'ecdsa-sha2-nistp521' +key_content_gpg_placeholder = Begins with '-----BEGIN PGP PUBLIC KEY BLOCK-----' ssh_key_been_used = This SSH key has already been added to the server. ssh_key_name_used = An SSH key with same name is already added to your account. gpg_key_id_used = A public GPG key with same ID already exists. diff --git a/templates/user/settings/keys_gpg.tmpl b/templates/user/settings/keys_gpg.tmpl index f86b44bef04f..332f864dcfa9 100644 --- a/templates/user/settings/keys_gpg.tmpl +++ b/templates/user/settings/keys_gpg.tmpl @@ -47,7 +47,7 @@
- +
- +
+
+ + -
-
-
- - -
+
- - - - {{ end }} {{ end }}
From b78448e94e1415eb810ee1126135c64ec2942c0f Mon Sep 17 00:00:00 2001 From: zeripath Date: Sat, 22 Aug 2020 10:09:43 +0100 Subject: [PATCH 21/40] Skip SSPI authentication attempts for /api/internal (#12556) * Skip SSPI authentication attempts for /api/internal SSPI fails badly on authentication attempts to /api/internal which it can never succesfully authenticate. Fix #11260 Signed-off-by: Andrew Thornton * Update oauth2.go Co-authored-by: techknowlogick Co-authored-by: Lauris BH --- modules/auth/sso/oauth2.go | 2 +- modules/auth/sso/sso.go | 5 +++++ modules/auth/sso/sspi_windows.go | 2 ++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/modules/auth/sso/oauth2.go b/modules/auth/sso/oauth2.go index 6860c12e3908..3f530f036f25 100644 --- a/modules/auth/sso/oauth2.go +++ b/modules/auth/sso/oauth2.go @@ -121,7 +121,7 @@ func (o *OAuth2) VerifyAuthData(ctx *macaron.Context, sess session.Store) *model return nil } - if !isAPIPath(ctx) && !isAttachmentDownload(ctx) { + if isInternalPath(ctx) || !isAPIPath(ctx) && !isAttachmentDownload(ctx) { return nil } diff --git a/modules/auth/sso/sso.go b/modules/auth/sso/sso.go index cf8148d89bc0..c2e36f3f5ebf 100644 --- a/modules/auth/sso/sso.go +++ b/modules/auth/sso/sso.go @@ -100,6 +100,11 @@ func isAPIPath(ctx *macaron.Context) bool { return strings.HasPrefix(ctx.Req.URL.Path, "/api/") } +// isInternalPath returns true if the specified URL is an internal API path +func isInternalPath(ctx *macaron.Context) bool { + return strings.HasPrefix(ctx.Req.URL.Path, "/api/internal/") +} + // isAttachmentDownload check if request is a file download (GET) with URL to an attachment func isAttachmentDownload(ctx *macaron.Context) bool { return strings.HasPrefix(ctx.Req.URL.Path, "/attachments/") && ctx.Req.Method == "GET" diff --git a/modules/auth/sso/sspi_windows.go b/modules/auth/sso/sspi_windows.go index 2bced4be28d6..00f15d97be5f 100644 --- a/modules/auth/sso/sspi_windows.go +++ b/modules/auth/sso/sspi_windows.go @@ -148,6 +148,8 @@ func (s *SSPI) shouldAuthenticate(ctx *macaron.Context) (shouldAuth bool) { } else if ctx.Req.FormValue("auth_with_sspi") == "1" { shouldAuth = true } + } else if isInternalPath(ctx) { + shouldAuth = false } else if isAPIPath(ctx) || isAttachmentDownload(ctx) { shouldAuth = true } From fcabbae1686b82cb495d8d430279b745a707f377 Mon Sep 17 00:00:00 2001 From: zeripath Date: Sat, 22 Aug 2020 13:56:33 +0100 Subject: [PATCH 22/40] Set utf8mb4 as the default charset on MySQL if CHARSET is unset (#12563) MySQL in its infinite wisdom determines that UTF8 does not mean UTF8. Our install scripts know about this and will set CHARSET to utf8mb4 if we users choose this but... users who do not explicitly set this variable will default to utf8mb3 without knowing it. This PR changes the unset CHARSET value to utf8mb4 if users choose to use mysql. Signed-off-by: Andrew Thornton --- modules/setting/database.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/setting/database.go b/modules/setting/database.go index a0734bc67a0e..d5d03c2a306b 100644 --- a/modules/setting/database.go +++ b/modules/setting/database.go @@ -60,11 +60,13 @@ func GetDBTypeByName(name string) string { func InitDBConfig() { sec := Cfg.Section("database") Database.Type = sec.Key("DB_TYPE").String() + defaultCharset := "utf8" switch Database.Type { case "sqlite3": Database.UseSQLite3 = true case "mysql": Database.UseMySQL = true + defaultCharset = "utf8mb4" case "postgres": Database.UsePostgreSQL = true case "mssql": @@ -78,7 +80,7 @@ func InitDBConfig() { } Database.Schema = sec.Key("SCHEMA").String() Database.SSLMode = sec.Key("SSL_MODE").MustString("disable") - Database.Charset = sec.Key("CHARSET").In("utf8", []string{"utf8", "utf8mb4"}) + Database.Charset = sec.Key("CHARSET").In(defaultCharset, []string{"utf8", "utf8mb4"}) Database.Path = sec.Key("PATH").MustString(filepath.Join(AppDataPath, "gitea.db")) Database.Timeout = sec.Key("SQLITE_TIMEOUT").MustInt(500) Database.MaxIdleConns = sec.Key("MAX_IDLE_CONNS").MustInt(2) From 7a8a05cc44a7ddf39ddea679434acacc8f47dfc1 Mon Sep 17 00:00:00 2001 From: zeripath Date: Sat, 22 Aug 2020 16:07:37 +0100 Subject: [PATCH 23/40] Fix diff path unquoting (#12554) * Fix diff path unquoting services/gitdiff/gitdiff.go whereby there it assumed that the path would always be quoted on both sides This PR simplifies the code here and uses fmt.Fscanf to parse the strings as necessary. Fix #12546 Signed-off-by: Andrew Thornton * Add testcase as per @mrsdizzie Signed-off-by: Andrew Thornton --- services/gitdiff/gitdiff.go | 47 ++++++++++++-------------------- services/gitdiff/gitdiff_test.go | 17 ++++++++++++ 2 files changed, 34 insertions(+), 30 deletions(-) diff --git a/services/gitdiff/gitdiff.go b/services/gitdiff/gitdiff.go index fd07a2ad9664..538f613b0458 100644 --- a/services/gitdiff/gitdiff.go +++ b/services/gitdiff/gitdiff.go @@ -18,7 +18,6 @@ import ( "os/exec" "regexp" "sort" - "strconv" "strings" "code.gitea.io/gitea/models" @@ -570,40 +569,28 @@ func ParsePatch(maxLines, maxLineCharacters, maxFiles int, reader io.Reader) (*D break } - var middle int - // Note: In case file name is surrounded by double quotes (it happens only in git-shell). // e.g. diff --git "a/xxx" "b/xxx" - hasQuote := line[len(cmdDiffHead)] == '"' - if hasQuote { - middle = strings.Index(line, ` "b/`) + var a string + var b string + + rd := strings.NewReader(line[len(cmdDiffHead):]) + char, _ := rd.ReadByte() + _ = rd.UnreadByte() + if char == '"' { + fmt.Fscanf(rd, "%q ", &a) } else { - middle = strings.Index(line, " b/") + fmt.Fscanf(rd, "%s ", &a) } - - beg := len(cmdDiffHead) - a := line[beg+2 : middle] - b := line[middle+3:] - - if hasQuote { - // Keep the entire string in double quotes for now - a = line[beg:middle] - b = line[middle+1:] - - var err error - a, err = strconv.Unquote(a) - if err != nil { - return nil, fmt.Errorf("Unquote: %v", err) - } - b, err = strconv.Unquote(b) - if err != nil { - return nil, fmt.Errorf("Unquote: %v", err) - } - // Now remove the /a /b - a = a[2:] - b = b[2:] - + char, _ = rd.ReadByte() + _ = rd.UnreadByte() + if char == '"' { + fmt.Fscanf(rd, "%q", &b) + } else { + fmt.Fscanf(rd, "%s", &b) } + a = a[2:] + b = b[2:] curFile = &DiffFile{ Name: b, diff --git a/services/gitdiff/gitdiff_test.go b/services/gitdiff/gitdiff_test.go index 597c9d394eb1..9826ece2dc5c 100644 --- a/services/gitdiff/gitdiff_test.go +++ b/services/gitdiff/gitdiff_test.go @@ -112,6 +112,23 @@ func TestParsePatch(t *testing.T) { } println(result) + var diff2a = `diff --git "a/A \\ B" b/A/B +--- "a/A \\ B" ++++ b/A/B +@@ -1,3 +1,6 @@ + # gitea-github-migrator ++ ++ Build Status +- Latest Release + Docker Pulls ++ cut off ++ cut off` + result, err = ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(diff2a)) + if err != nil { + t.Errorf("ParsePatch failed: %s", err) + } + println(result) + var diff3 = `diff --git a/README.md b/README.md --- a/README.md +++ b/README.md From 2026d885d6c11793e6fd68d06f163de90440e52d Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sun, 23 Aug 2020 01:12:40 +0800 Subject: [PATCH 24/40] Fix bug on migration 147 (#12565) --- models/migrations/v147.go | 98 ++++++++++++++++++++++++--------------- 1 file changed, 60 insertions(+), 38 deletions(-) diff --git a/models/migrations/v147.go b/models/migrations/v147.go index 9716d6e83b89..a39b224039fa 100644 --- a/models/migrations/v147.go +++ b/models/migrations/v147.go @@ -82,51 +82,73 @@ func createReviewsForCodeComments(x *xorm.Engine) error { if err := x.Sync2(new(Review), new(Comment)); err != nil { return err } - sess := x.NewSession() - defer sess.Close() - if err := sess.Begin(); err != nil { - return err - } - if err := sess.Where("review_id = 0 and type = 21").Iterate(new(Comment), func(idx int, bean interface{}) error { - comment := bean.(*Comment) - - review := &Review{ - Type: ReviewTypeComment, - ReviewerID: comment.PosterID, - IssueID: comment.IssueID, - Official: false, - CommitID: comment.CommitSHA, - Stale: comment.Invalidated, - OriginalAuthor: comment.OriginalAuthor, - OriginalAuthorID: comment.OriginalAuthorID, - CreatedUnix: comment.CreatedUnix, - UpdatedUnix: comment.CreatedUnix, - } - if _, err := sess.NoAutoTime().Insert(review); err != nil { + + var updateComment = func(comments []*Comment) error { + sess := x.NewSession() + defer sess.Close() + if err := sess.Begin(); err != nil { return err } - reviewComment := &Comment{ - Type: 22, - PosterID: comment.PosterID, - Content: "", - IssueID: comment.IssueID, - ReviewID: review.ID, - OriginalAuthor: comment.OriginalAuthor, - OriginalAuthorID: comment.OriginalAuthorID, - CreatedUnix: comment.CreatedUnix, - UpdatedUnix: comment.CreatedUnix, + for _, comment := range comments { + review := &Review{ + Type: ReviewTypeComment, + ReviewerID: comment.PosterID, + IssueID: comment.IssueID, + Official: false, + CommitID: comment.CommitSHA, + Stale: comment.Invalidated, + OriginalAuthor: comment.OriginalAuthor, + OriginalAuthorID: comment.OriginalAuthorID, + CreatedUnix: comment.CreatedUnix, + UpdatedUnix: comment.CreatedUnix, + } + if _, err := sess.NoAutoTime().Insert(review); err != nil { + return err + } + + reviewComment := &Comment{ + Type: 22, + PosterID: comment.PosterID, + Content: "", + IssueID: comment.IssueID, + ReviewID: review.ID, + OriginalAuthor: comment.OriginalAuthor, + OriginalAuthorID: comment.OriginalAuthorID, + CreatedUnix: comment.CreatedUnix, + UpdatedUnix: comment.CreatedUnix, + } + if _, err := sess.NoAutoTime().Insert(reviewComment); err != nil { + return err + } + + comment.ReviewID = review.ID + if _, err := sess.ID(comment.ID).Cols("review_id").NoAutoTime().Update(comment); err != nil { + return err + } + } + + return sess.Commit() + } + + var start = 0 + var batchSize = 100 + for { + var comments = make([]*Comment, 0, batchSize) + if err := x.Where("review_id = 0 and type = 21").Limit(batchSize, start).Find(&comments); err != nil { + return err } - if _, err := sess.NoAutoTime().Insert(reviewComment); err != nil { + + if err := updateComment(comments); err != nil { return err } - comment.ReviewID = review.ID - _, err := sess.ID(comment.ID).Cols("review_id").NoAutoTime().Update(comment) - return err - }); err != nil { - return err + start += len(comments) + + if len(comments) < batchSize { + break + } } - return sess.Commit() + return nil } From e429c1164ec68b154b7f06db2c2e04dd25bad094 Mon Sep 17 00:00:00 2001 From: zeripath Date: Sun, 23 Aug 2020 14:15:29 +0100 Subject: [PATCH 25/40] Ensure that the detected charset order is set in chardet test (#12574) TestToUTF8WithFallback is the cause of recurrent spurious test failures even despite code to set the detected charset order. The reason why this happens is because the preferred detected charset order is not being initialised for these tests. This PR simply ensures that this is set at the start of each test and would allow different tests to be written to allow differing orders. Replaces #12571 Close #12571 Signed-off-by: Andrew Thornton --- modules/charset/charset_test.go | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/modules/charset/charset_test.go b/modules/charset/charset_test.go index 394a42c71f0b..33f0c10a7a20 100644 --- a/modules/charset/charset_test.go +++ b/modules/charset/charset_test.go @@ -5,6 +5,7 @@ package charset import ( + "strings" "testing" "code.gitea.io/gitea/modules/setting" @@ -12,6 +13,22 @@ import ( "github.com/stretchr/testify/assert" ) +func resetDefaultCharsetsOrder() { + defaultDetectedCharsetsOrder := make([]string, 0, len(setting.Repository.DetectedCharsetsOrder)) + for _, charset := range setting.Repository.DetectedCharsetsOrder { + defaultDetectedCharsetsOrder = append(defaultDetectedCharsetsOrder, strings.ToLower(strings.TrimSpace(charset))) + } + setting.Repository.DetectedCharsetScore = map[string]int{} + i := 0 + for _, charset := range defaultDetectedCharsetsOrder { + canonicalCharset := strings.ToLower(strings.TrimSpace(charset)) + if _, has := setting.Repository.DetectedCharsetScore[canonicalCharset]; !has { + setting.Repository.DetectedCharsetScore[canonicalCharset] = i + i++ + } + } +} + func TestRemoveBOMIfPresent(t *testing.T) { res := RemoveBOMIfPresent([]byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}) assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res) @@ -21,6 +38,7 @@ func TestRemoveBOMIfPresent(t *testing.T) { } func TestToUTF8WithErr(t *testing.T) { + resetDefaultCharsetsOrder() var res string var err error @@ -76,6 +94,7 @@ func TestToUTF8WithErr(t *testing.T) { } func TestToUTF8WithFallback(t *testing.T) { + resetDefaultCharsetsOrder() // "ABC" res := ToUTF8WithFallback([]byte{0x41, 0x42, 0x43}) assert.Equal(t, []byte{0x41, 0x42, 0x43}, res) @@ -116,7 +135,7 @@ func TestToUTF8WithFallback(t *testing.T) { } func TestToUTF8(t *testing.T) { - + resetDefaultCharsetsOrder() // Note: golang compiler seems so behave differently depending on the current // locale, so some conversions might behave differently. For that reason, we don't // depend on particular conversions but in expected behaviors. @@ -165,6 +184,7 @@ func TestToUTF8(t *testing.T) { } func TestToUTF8DropErrors(t *testing.T) { + resetDefaultCharsetsOrder() // "ABC" res := ToUTF8DropErrors([]byte{0x41, 0x42, 0x43}) assert.Equal(t, []byte{0x41, 0x42, 0x43}, res) @@ -204,6 +224,7 @@ func TestToUTF8DropErrors(t *testing.T) { } func TestDetectEncoding(t *testing.T) { + resetDefaultCharsetsOrder() testSuccess := func(b []byte, expected string) { encoding, err := DetectEncoding(b) assert.NoError(t, err) @@ -225,10 +246,7 @@ func TestDetectEncoding(t *testing.T) { b = []byte{0x44, 0xe9, 0x63, 0x6f, 0x72, 0x0a} encoding, err := DetectEncoding(b) assert.NoError(t, err) - // due to a race condition in `chardet` library, it could either detect - // "ISO-8859-1" or "IS0-8859-2" here. Technically either is correct, so - // we accept either. - assert.Contains(t, encoding, "ISO-8859") + assert.Contains(t, encoding, "ISO-8859-1") old := setting.Repository.AnsiCharset setting.Repository.AnsiCharset = "placeholder" From e7d65cbc6e50d70753f7228c46cbff0cffde7eba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E6=99=BA=E8=B6=85?= <1012112796@qq.com> Date: Sun, 23 Aug 2020 23:03:18 +0800 Subject: [PATCH 26/40] Add email notify for new release (#12463) * Add email notify for new release Signed-off-by: a1012112796 <1012112796@qq.com> --- models/release.go | 1 + modules/notification/mail/mail.go | 13 ++++++ services/mailer/mail_release.go | 69 +++++++++++++++++++++++++++++++ templates/mail/release.tmpl | 56 +++++++++++++++++++++++++ 4 files changed, 139 insertions(+) create mode 100644 services/mailer/mail_release.go create mode 100644 templates/mail/release.tmpl diff --git a/models/release.go b/models/release.go index 0c76d17f4b74..f55341b86bb1 100644 --- a/models/release.go +++ b/models/release.go @@ -35,6 +35,7 @@ type Release struct { NumCommits int64 NumCommitsBehind int64 `xorm:"-"` Note string `xorm:"TEXT"` + RenderedNote string `xorm:"-"` IsDraft bool `xorm:"NOT NULL DEFAULT false"` IsPrerelease bool `xorm:"NOT NULL DEFAULT false"` IsTag bool `xorm:"NOT NULL DEFAULT false"` diff --git a/modules/notification/mail/mail.go b/modules/notification/mail/mail.go index 795c8af2c803..9b2c27280f7a 100644 --- a/modules/notification/mail/mail.go +++ b/modules/notification/mail/mail.go @@ -145,3 +145,16 @@ func (m *mailNotifier) NotifyPullRequestPushCommits(doer *models.User, pr *model m.NotifyCreateIssueComment(doer, comment.Issue.Repo, comment.Issue, comment) } + +func (m *mailNotifier) NotifyNewRelease(rel *models.Release) { + if err := rel.LoadAttributes(); err != nil { + log.Error("NotifyNewRelease: %v", err) + return + } + + if rel.IsDraft || rel.IsPrerelease { + return + } + + mailer.MailNewRelease(rel) +} diff --git a/services/mailer/mail_release.go b/services/mailer/mail_release.go new file mode 100644 index 000000000000..55182f55cf5d --- /dev/null +++ b/services/mailer/mail_release.go @@ -0,0 +1,69 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package mailer + +import ( + "bytes" + "fmt" + + "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/markup/markdown" + "code.gitea.io/gitea/modules/setting" +) + +const ( + tplNewReleaseMail base.TplName = "release" +) + +// MailNewRelease send new release notify to all all repo watchers. +func MailNewRelease(rel *models.Release) { + watcherIDList, err := models.GetRepoWatchersIDs(rel.RepoID) + if err != nil { + log.Error("GetRepoWatchersIDs(%d): %v", rel.RepoID, err) + return + } + + recipients, err := models.GetMaileableUsersByIDs(watcherIDList) + if err != nil { + log.Error("models.GetMaileableUsersByIDs: %v", err) + return + } + + tos := make([]string, 0, len(recipients)) + for _, to := range recipients { + if to.ID != rel.PublisherID { + tos = append(tos, to.Email) + } + } + + rel.RenderedNote = markdown.RenderString(rel.Note, rel.Repo.Link(), rel.Repo.ComposeMetas()) + subject := fmt.Sprintf("%s in %s released", rel.TagName, rel.Repo.FullName()) + + mailMeta := map[string]interface{}{ + "Release": rel, + "Subject": subject, + } + + var mailBody bytes.Buffer + + if err = bodyTemplates.ExecuteTemplate(&mailBody, string(tplNewReleaseMail), mailMeta); err != nil { + log.Error("ExecuteTemplate [%s]: %v", string(tplNewReleaseMail)+"/body", err) + return + } + + msgs := make([]*Message, 0, len(recipients)) + publisherName := rel.Publisher.DisplayName() + relURL := "<" + rel.HTMLURL() + ">" + for _, to := range tos { + msg := NewMessageFrom([]string{to}, publisherName, setting.MailService.FromEmail, subject, mailBody.String()) + msg.Info = subject + msg.SetHeader("Message-ID", relURL) + msgs = append(msgs, msg) + } + + SendAsyncs(msgs) +} diff --git a/templates/mail/release.tmpl b/templates/mail/release.tmpl new file mode 100644 index 000000000000..bb0eb17a56ec --- /dev/null +++ b/templates/mail/release.tmpl @@ -0,0 +1,56 @@ + + + + + {{.Subject}} + + + + + + +

@{{.Release.Publisher.Name}} released {{.Release.TagName}} + in {{.Release.Repo.FullName}}

+

Title: {{.Release.Title}}

+

+ Note:
+ {{- if eq .Release.RenderedNote ""}} + {{else}} + {{.Release.RenderedNote | Str2html}} + {{end -}} +

+

+

+ --- +
+ Downloads: +

+

+ + + From 43a397ce9ae082e0c6e9367e31743e1cb4d71c20 Mon Sep 17 00:00:00 2001 From: John Olheiser Date: Sun, 23 Aug 2020 11:02:35 -0500 Subject: [PATCH 27/40] Initial support for push options (#12169) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Initial support for push options Signed-off-by: jolheiser * Fix misspelling 🤦 Signed-off-by: jolheiser * Fix formatting after conflict resolution * defer close git repo * According the GitLab documentation, git >= 2.10 Signed-off-by: jolheiser * Words are hard. Thanks @mrsdizzie :sweat_smile: Co-authored-by: mrsdizzie * Only update if there are push options Signed-off-by: jolheiser Co-authored-by: mrsdizzie --- cmd/doctor.go | 31 ++++++++++++++++++++ cmd/hook.go | 16 ++++++++++ docs/content/doc/usage/push-options.en-us.md | 31 ++++++++++++++++++++ modules/git/git.go | 6 ++++ modules/private/hook.go | 22 ++++++++++++++ routers/private/hook.go | 12 ++++++++ 6 files changed, 118 insertions(+) create mode 100644 docs/content/doc/usage/push-options.en-us.md diff --git a/cmd/doctor.go b/cmd/doctor.go index 20c1904afa0b..2a93db27da23 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -127,6 +127,12 @@ var checklist = []check{ isDefault: false, f: runDoctorUserStarNum, }, + { + title: "Enable push options", + name: "enable-push-options", + isDefault: false, + f: runDoctorEnablePushOptions, + }, // more checks please append here } @@ -605,3 +611,28 @@ func runDoctorCheckDBConsistency(ctx *cli.Context) ([]string, error) { return results, nil } + +func runDoctorEnablePushOptions(ctx *cli.Context) ([]string, error) { + numRepos := 0 + _, err := iterateRepositories(func(repo *models.Repository) ([]string, error) { + numRepos++ + r, err := git.OpenRepository(repo.RepoPath()) + if err != nil { + return nil, err + } + defer r.Close() + + if ctx.Bool("fix") { + _, err := git.NewCommand("config", "receive.advertisePushOptions", "true").RunInDir(r.Path) + return nil, err + } + + return nil, nil + }) + + var prefix string + if !ctx.Bool("fix") { + prefix = "DRY RUN: " + } + return []string{fmt.Sprintf("%sEnabled push options for %d repositories.", prefix, numRepos)}, err +} diff --git a/cmd/hook.go b/cmd/hook.go index f5658de7cd75..863ed832a9ba 100644 --- a/cmd/hook.go +++ b/cmd/hook.go @@ -178,6 +178,7 @@ Gitea or set your environment appropriately.`, "") GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories), GitObjectDirectory: os.Getenv(private.GitObjectDirectory), GitQuarantinePath: os.Getenv(private.GitQuarantinePath), + GitPushOptions: pushOptions(), ProtectedBranchID: prID, IsDeployKey: isDeployKey, } @@ -326,6 +327,7 @@ Gitea or set your environment appropriately.`, "") GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories), GitObjectDirectory: os.Getenv(private.GitObjectDirectory), GitQuarantinePath: os.Getenv(private.GitQuarantinePath), + GitPushOptions: pushOptions(), } oldCommitIDs := make([]string, hookBatchSize) newCommitIDs := make([]string, hookBatchSize) @@ -438,3 +440,17 @@ func hookPrintResults(results []private.HookPostReceiveBranchResult) { os.Stderr.Sync() } } + +func pushOptions() map[string]string { + opts := make(map[string]string) + if pushCount, err := strconv.Atoi(os.Getenv(private.GitPushOptionCount)); err == nil { + for idx := 0; idx < pushCount; idx++ { + opt := os.Getenv(fmt.Sprintf("GIT_PUSH_OPTION_%d", idx)) + kv := strings.SplitN(opt, "=", 2) + if len(kv) == 2 { + opts[kv[0]] = kv[1] + } + } + } + return opts +} diff --git a/docs/content/doc/usage/push-options.en-us.md b/docs/content/doc/usage/push-options.en-us.md new file mode 100644 index 000000000000..439d13b42f88 --- /dev/null +++ b/docs/content/doc/usage/push-options.en-us.md @@ -0,0 +1,31 @@ +--- +date: "2020-07-06T16:00:00+02:00" +title: "Usage: Push Options" +slug: "push-options" +weight: 15 +toc: true +draft: false +menu: + sidebar: + parent: "usage" + name: "Push Options" + weight: 15 + identifier: "push-options" +--- + +# Push Options + +In Gitea `1.13`, support for some [push options](https://git-scm.com/docs/git-push#Documentation/git-push.txt--oltoptiongt) +were added. + + +## Supported Options + +- `repo.private` (true|false) - Change the repository's visibility. +This is particularly useful when combined with push-to-create. +- `repo.template` (true|false) - Change whether the repository is a template. + +Example of changing a repository's visibility to public: +```shell +git push -o repo.private=false -u origin master +``` diff --git a/modules/git/git.go b/modules/git/git.go index 6f231cee7a40..1061bdb0d525 100644 --- a/modules/git/git.go +++ b/modules/git/git.go @@ -120,6 +120,12 @@ func Init(ctx context.Context) error { return err } + if version.Compare(gitVersion, "2.10", ">=") { + if err := checkAndSetConfig("receive.advertisePushOptions", "true", true); err != nil { + return err + } + } + if version.Compare(gitVersion, "2.18", ">=") { if err := checkAndSetConfig("core.commitGraph", "true", true); err != nil { return err diff --git a/modules/private/hook.go b/modules/private/hook.go index 010fc4d72453..84d66943ba25 100644 --- a/modules/private/hook.go +++ b/modules/private/hook.go @@ -9,6 +9,7 @@ import ( "fmt" "net/http" "net/url" + "strconv" "time" "code.gitea.io/gitea/modules/setting" @@ -19,8 +20,28 @@ const ( GitAlternativeObjectDirectories = "GIT_ALTERNATE_OBJECT_DIRECTORIES" GitObjectDirectory = "GIT_OBJECT_DIRECTORY" GitQuarantinePath = "GIT_QUARANTINE_PATH" + GitPushOptionCount = "GIT_PUSH_OPTION_COUNT" ) +// GitPushOptions is a wrapper around a map[string]string +type GitPushOptions map[string]string + +// GitPushOptions keys +const ( + GitPushOptionRepoPrivate = "repo.private" + GitPushOptionRepoTemplate = "repo.template" +) + +// Bool checks for a key in the map and parses as a boolean +func (g GitPushOptions) Bool(key string, def bool) bool { + if val, ok := g[key]; ok { + if b, err := strconv.ParseBool(val); err == nil { + return b + } + } + return def +} + // HookOptions represents the options for the Hook calls type HookOptions struct { OldCommitIDs []string @@ -31,6 +52,7 @@ type HookOptions struct { GitObjectDirectory string GitAlternativeObjectDirectories string GitQuarantinePath string + GitPushOptions GitPushOptions ProtectedBranchID int64 IsDeployKey bool } diff --git a/routers/private/hook.go b/routers/private/hook.go index 6cdc5393f429..2bccca3e3e30 100644 --- a/routers/private/hook.go +++ b/routers/private/hook.go @@ -436,6 +436,18 @@ func HookPostReceive(ctx *macaron.Context, opts private.HookOptions) { } } + // Push Options + if repo != nil && len(opts.GitPushOptions) > 0 { + repo.IsPrivate = opts.GitPushOptions.Bool(private.GitPushOptionRepoPrivate, repo.IsPrivate) + repo.IsTemplate = opts.GitPushOptions.Bool(private.GitPushOptionRepoTemplate, repo.IsTemplate) + if err := models.UpdateRepositoryCols(repo, "is_private", "is_template"); err != nil { + log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err) + ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{ + Err: fmt.Sprintf("Failed to Update: %s/%s Error: %v", ownerName, repoName, err), + }) + } + } + results := make([]private.HookPostReceiveBranchResult, 0, len(opts.OldCommitIDs)) // We have to reload the repo in case its state is changed above From d2cee3eea60cd0e459e665dad289b2c5adc1a2a5 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Sun, 23 Aug 2020 16:03:36 +0000 Subject: [PATCH 28/40] [skip ci] Updated translations via Crowdin --- options/locale/locale_zh-CN.ini | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/options/locale/locale_zh-CN.ini b/options/locale/locale_zh-CN.ini index 10d35b649bcc..7592043a09c3 100644 --- a/options/locale/locale_zh-CN.ini +++ b/options/locale/locale_zh-CN.ini @@ -499,6 +499,8 @@ ssh_helper=需要帮助? 请查看有关 如何 gpg_helper=需要帮助吗?看一看 GitHub 关于GPG 的指导。 add_new_key=增加 SSH 密钥 add_new_gpg_key=添加的 GPG 密钥 +key_content_ssh_placeholder=以 'ssh-ed25519', 'ssh-rsa', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384' 或 'ecdsa-sha2-nistp521' 开头 +key_content_gpg_placeholder=以 '-----BEGIN PGP PUBLIC KEY BLOCK-----' 开头 ssh_key_been_used=此 SSH 密钥已添加到服务器。 ssh_key_name_used=使用相同名称的SSH公钥已经存在! gpg_key_id_used=使用相同名称的GPG公钥已经存在! @@ -1092,7 +1094,7 @@ issues.error_modifying_due_date=未能修改到期时间。 issues.error_removing_due_date=未能删除到期时间。 issues.push_commit_1=已于 %[2]s 推送了 %[1]d 提交 issues.push_commits_n=已于 %[2]s 推送了 %[1]d 提交 -issues.force_push_codes="强制推送%[1]s %[2]%[4]s %[6]s" +issues.force_push_codes="强制推送%[1]s %[2]s%[4]s %[6]s" issues.due_date_form=yyyy年mm月dd日 issues.due_date_form_add=添加到期时间 issues.due_date_form_edit=编辑 @@ -1981,6 +1983,7 @@ users.full_name=全名 users.activated=已激活 users.admin=管理员 users.restricted=受限 +users.2fa=两步验证 users.repos=仓库数 users.created=创建时间 users.last_login=上次登录 From dd8ec121880fda03691cf9f4b17be88e1d4be030 Mon Sep 17 00:00:00 2001 From: silverwind Date: Sun, 23 Aug 2020 21:05:17 +0200 Subject: [PATCH 29/40] Increase clickable area on files table links (#12553) --- integrations/repo_test.go | 2 +- templates/repo/view_list.tmpl | 52 ++++++++++++++++------------------- web_src/less/_repository.less | 15 ++++++---- 3 files changed, 34 insertions(+), 35 deletions(-) diff --git a/integrations/repo_test.go b/integrations/repo_test.go index c2a0368b0a57..3121b5135f49 100644 --- a/integrations/repo_test.go +++ b/integrations/repo_test.go @@ -148,7 +148,7 @@ func TestViewRepoWithSymlinks(t *testing.T) { resp := session.MakeRequest(t, req, http.StatusOK) htmlDoc := NewHTMLParser(t, resp.Body) - files := htmlDoc.doc.Find("#repo-files-table > TBODY > TR > TD.name > SPAN") + files := htmlDoc.doc.Find("#repo-files-table > TBODY > TR > TD.name") items := files.Map(func(i int, s *goquery.Selection) string { cls, _ := s.Find("SVG").Attr("class") file := strings.Trim(s.Find("A").Text(), " \t\n") diff --git a/templates/repo/view_list.tmpl b/templates/repo/view_list.tmpl index de7d5b1ea9eb..db810890f565 100644 --- a/templates/repo/view_list.tmpl +++ b/templates/repo/view_list.tmpl @@ -45,41 +45,35 @@ {{if $entry.IsSubModule}} - - {{svg "octicon-file-submodule" 16}} - {{$refURL := $commit.RefURL AppUrl $.Repository.FullName}} - {{if $refURL}} - {{$entry.Name}} @ {{ShortSha $commit.RefID}} - {{else}} - {{$entry.Name}} @ {{ShortSha $commit.RefID}} - {{end}} - + {{svg "octicon-file-submodule" 16}} + {{$refURL := $commit.RefURL AppUrl $.Repository.FullName}} + {{if $refURL}} + {{$entry.Name}} @ {{ShortSha $commit.RefID}} + {{else}} + {{$entry.Name}} @ {{ShortSha $commit.RefID}} + {{end}} {{else}} - - {{if $entry.IsDir}} - {{$subJumpablePathName := $entry.GetSubJumpablePathName}} - {{$subJumpablePath := SubJumpablePath $subJumpablePathName}} - {{svg "octicon-file-directory" 16}} - - {{if eq (len $subJumpablePath) 2}} - {{index $subJumpablePath 0}}{{index $subJumpablePath 1}} - {{else}} - {{index $subJumpablePath 0}} - {{end}} - - {{else}} - {{svg (printf "octicon-%s" (EntryIcon $entry)) 16}} - {{$entry.Name}} - {{end}} - + {{if $entry.IsDir}} + {{$subJumpablePathName := $entry.GetSubJumpablePathName}} + {{$subJumpablePath := SubJumpablePath $subJumpablePathName}} + {{svg "octicon-file-directory" 16}} + + {{if eq (len $subJumpablePath) 2}} + {{index $subJumpablePath 0}}{{index $subJumpablePath 1}} + {{else}} + {{index $subJumpablePath 0}} + {{end}} + + {{else}} + {{svg (printf "octicon-%s" (EntryIcon $entry)) 16}} + {{$entry.Name}} + {{end}} {{end}} - - {{$commit.Summary | RenderEmoji}} - + {{$commit.Summary | RenderEmoji}} {{TimeSince $commit.Committer.When $.Lang}} diff --git a/web_src/less/_repository.less b/web_src/less/_repository.less index becc2e216ad0..eb316ee71ee5 100644 --- a/web_src/less/_repository.less +++ b/web_src/less/_repository.less @@ -345,8 +345,8 @@ } td { - padding-top: 8px; - padding-bottom: 8px; + padding-top: 0; + padding-bottom: 0; overflow: initial; &.name { @@ -361,14 +361,19 @@ width: 120px; } - .truncate { + > a { + width: calc(100% - 8px); /* prevent overflow into adjacant cell */ display: inline-block; - max-width: 100%; + padding-top: 8px; + padding-bottom: 8px; overflow: hidden; text-overflow: ellipsis; - vertical-align: top; white-space: nowrap; } + + > * { + vertical-align: middle; + } } td.message .isSigned { From 1bf7b8d7c18a4d9e09c3797fe80709ff00bd8f39 Mon Sep 17 00:00:00 2001 From: zeripath Date: Sun, 23 Aug 2020 22:59:41 +0100 Subject: [PATCH 30/40] Fix signing.wont_sign.%!s() if Require Signing commits but not signed in (#12581) signing.wont_sign.%!s() will be displayed if the repository needs signed commits but the user is not logged in. This is displayed because of complicated logic in the the template repo/issue/view_content/pull.tmpl and a shortcut in the code of routers/repo/issue.go This PR adds a default value of notsignedin if users are not signed in, which although our templates will not show will prevent custom templates from showing the above. It also fixes the template to avoid showing signing errors if the user is not authorized to sign. Replaces #12564 Close #12564 Signed-off-by: Andrew Thornton --- options/locale/locale_en-US.ini | 1 + routers/repo/issue.go | 2 ++ templates/repo/issue/view_content/pull.tmpl | 8 ++++---- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index c31d77e1a58e..00c5ed60764f 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -1276,6 +1276,7 @@ signing.wont_sign.basesigned = The merge will not be signed as the base commit i signing.wont_sign.headsigned = The merge will not be signed as the head commit is not signed signing.wont_sign.commitssigned = The merge will not be signed as all the associated commits are not signed signing.wont_sign.approved = The merge will not be signed as the PR is not approved +signing.wont_sign.not_signed_in = You are not signed in ext_wiki = Ext. Wiki ext_wiki.desc = Link to an external wiki. diff --git a/routers/repo/issue.go b/routers/repo/issue.go index d671f8de74ea..dabe0f6b0fe1 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -1212,6 +1212,8 @@ func ViewIssue(ctx *context.Context) { log.Error("Error whilst checking if could sign pr %d in repo %s. Error: %v", pull.ID, pull.BaseRepo.FullName(), err) } } + } else { + ctx.Data["WontSignReason"] = "not_signed_in" } ctx.Data["IsPullBranchDeletable"] = canDelete && pull.HeadRepo != nil && diff --git a/templates/repo/issue/view_content/pull.tmpl b/templates/repo/issue/view_content/pull.tmpl index c2b9cb36b9a8..53e2ddf912b9 100644 --- a/templates/repo/issue/view_content/pull.tmpl +++ b/templates/repo/issue/view_content/pull.tmpl @@ -73,7 +73,7 @@ {{- else if .IsBlockedByOutdatedBranch}}red {{- else if and .EnableStatusCheck (or .RequiredStatusCheckState.IsFailure .RequiredStatusCheckState.IsError)}}red {{- else if and .EnableStatusCheck (or (not $.LatestCommitStatus) .RequiredStatusCheckState.IsPending .RequiredStatusCheckState.IsWarning)}}yellow - {{- else if and .RequireSigned (not .WillSign)}}red + {{- else if and .AllowMerge .RequireSigned (not .WillSign)}}red {{- else if .Issue.PullRequest.IsChecking}}yellow {{- else if .Issue.PullRequest.CanAutoMerge}}green {{- else}}red{{end}}">{{svg "octicon-git-merge" 32}} @@ -159,7 +159,7 @@ {{svg "octicon-x" 16}} {{$.i18n.Tr "repo.pulls.required_status_check_missing"}} - {{else if and .RequireSigned (not .WillSign)}} + {{else if and .AllowMerge .RequireSigned (not .WillSign)}}
{{svg "octicon-x" 16}} {{$.i18n.Tr "repo.pulls.require_signed_wont_sign"}} @@ -170,7 +170,7 @@
{{end}} {{$notAllOverridableChecksOk := or .IsBlockedByApprovals .IsBlockedByRejection .IsBlockedByOutdatedBranch (and .EnableStatusCheck (not .RequiredStatusCheckState.IsSuccess))}} - {{if and (or $.IsRepoAdmin (not $notAllOverridableChecksOk)) (or (not .RequireSigned) .WillSign)}} + {{if and (or $.IsRepoAdmin (not $notAllOverridableChecksOk)) (or (not .AllowMerge) (not .RequireSigned) .WillSign)}} {{if $notAllOverridableChecksOk}}
{{svg "octicon-dot-fill" 16}} @@ -216,7 +216,7 @@
{{end}} - {{if and (or $.IsRepoAdmin (not $notAllOverridableChecksOk)) (or (not .RequireSigned) .WillSign)}} + {{if and (or $.IsRepoAdmin (not $notAllOverridableChecksOk)) (or (not .AllowMerge) (not .RequireSigned) .WillSign)}} {{if .AllowMerge}} {{$prUnit := .Repository.MustGetUnit $.UnitTypePullRequests}} {{$approvers := .Issue.PullRequest.GetApprovers}} From 0c0f049d09dfcdaaf43029ff853a838c02efc79e Mon Sep 17 00:00:00 2001 From: silverwind Date: Mon, 24 Aug 2020 00:45:21 +0200 Subject: [PATCH 31/40] Reaction picker display improvements (#12576) - Remove overly thin font-width on counter - Add hover effect on reaction picker - Change colors on arc-green to green to match the theme Co-authored-by: Lunny Xiao Co-authored-by: zeripath --- web_src/less/_repository.less | 25 +++++++++++++++++------- web_src/less/themes/theme-arc-green.less | 10 ++++++++++ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/web_src/less/_repository.less b/web_src/less/_repository.less index eb316ee71ee5..0d994c565c8e 100644 --- a/web_src/less/_repository.less +++ b/web_src/less/_repository.less @@ -2345,9 +2345,10 @@ > .item { float: left; - padding: .5rem !important; + padding: .25rem !important; + margin: .25rem; font-size: 1.5em; - width: 45px; + width: 39px; left: 13px; img.emoji { @@ -2361,10 +2362,9 @@ padding: 0; display: flex; - .ui.label, - .ui.label.visible { + .ui.label { max-height: 40px; - padding: .4rem .8rem; + padding: 7px 18px; display: flex !important; align-items: center; border: 0; @@ -2372,7 +2372,7 @@ border-radius: 0; margin: 0; font-size: 14px; - font-weight: 100; + font-weight: normal; border-color: inherit !important; &.disabled { @@ -2393,11 +2393,22 @@ .select-reaction { display: flex; align-items: center; - padding: 0 .5rem; + padding: 0 14px; &:not(.active) a { display: none; } + + .item { + border-radius: 6px; + display: flex; + justify-content: center; + align-items: center; + } + + .item:hover { + background: #4183c4; + } } &:hover .select-reaction a { diff --git a/web_src/less/themes/theme-arc-green.less b/web_src/less/themes/theme-arc-green.less index f9b643e9693f..bf7d2e116065 100644 --- a/web_src/less/themes/theme-arc-green.less +++ b/web_src/less/themes/theme-arc-green.less @@ -704,6 +704,16 @@ a.ui.basic.green.label:hover { border-color: #26577b !important; } +.repository .segment.reactions .ui.label.basic.blue { + color: #a0cc75 !important; + background: #305020 !important; + border-color: #404552 !important; +} + +.repository .segment.reactions .select-reaction .item:hover { + background: #305020; +} + .ui.menu .item > .label { background: #565454; } From 26bf4c51fb900b8a31cfb6d17095515c118a68a1 Mon Sep 17 00:00:00 2001 From: silverwind Date: Mon, 24 Aug 2020 00:48:40 +0200 Subject: [PATCH 32/40] Change tab width go,tmpl,html to 2 (#12572) Make it easier to edit deeply nested code. I plan to convert Less to 2-space so that we have standardized indentation width in the codebase. Co-authored-by: techknowlogick --- .editorconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.editorconfig b/.editorconfig index 6059fa100b75..82542ea86dcc 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,7 +11,7 @@ trim_trailing_whitespace = false [*.{go,tmpl,html}] indent_style = tab -indent_size = 4 +indent_size = 2 [*.{less,css}] indent_style = space From ee047312a1a3238a8504200f7ded8536ebc838e3 Mon Sep 17 00:00:00 2001 From: silverwind Date: Mon, 24 Aug 2020 03:44:53 +0200 Subject: [PATCH 33/40] Fix emoji replacements, make emoji images consistent (#12567) - Fix emoji not being replaced in issue title change text - Make the image attributes consistent, add alt, remove align Co-authored-by: zeripath Co-authored-by: techknowlogick --- modules/markup/html.go | 1 + modules/markup/html_test.go | 2 +- modules/templates/helper.go | 2 +- templates/repo/issue/view_content/comments.tmpl | 2 +- web_src/js/features/emoji.js | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) diff --git a/modules/markup/html.go b/modules/markup/html.go index 41248654d80d..bef6269a6915 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -481,6 +481,7 @@ func createCustomEmoji(alias, class string) *html.Node { Attr: []html.Attribute{}, } if class != "" { + img.Attr = append(img.Attr, html.Attribute{Key: "alt", Val: fmt.Sprintf(`:%s:`, alias)}) img.Attr = append(img.Attr, html.Attribute{Key: "src", Val: fmt.Sprintf(`%s/img/emoji/%s.png`, setting.StaticURLPrefix, alias)}) } diff --git a/modules/markup/html_test.go b/modules/markup/html_test.go index 69c4e675f593..7f820d399055 100644 --- a/modules/markup/html_test.go +++ b/modules/markup/html_test.go @@ -255,7 +255,7 @@ func TestRender_emoji(t *testing.T) { //Text that should be turned into or recognized as emoji test( ":gitea:", - `

`) + `

:gitea:

`) test( "Some text with 😄 in the middle", diff --git a/modules/templates/helper.go b/modules/templates/helper.go index 718fe8f2672e..f86287f10bef 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -607,7 +607,7 @@ func ReactionToEmoji(reaction string) template.HTML { if val != nil { return template.HTML(val.Emoji) } - return template.HTML(fmt.Sprintf(``, setting.StaticURLPrefix, reaction)) + return template.HTML(fmt.Sprintf(`:%s:`, reaction, setting.StaticURLPrefix, reaction)) } // RenderNote renders the contents of a git-notes file as a commit message. diff --git a/templates/repo/issue/view_content/comments.tmpl b/templates/repo/issue/view_content/comments.tmpl index 850c5b91577f..39468ee6b272 100644 --- a/templates/repo/issue/view_content/comments.tmpl +++ b/templates/repo/issue/view_content/comments.tmpl @@ -218,7 +218,7 @@ {{.Poster.GetDisplayName}} - {{$.i18n.Tr "repo.issues.change_title_at" (.OldTitle|Escape) (.NewTitle|Escape) $createdStr | Safe}} + {{$.i18n.Tr "repo.issues.change_title_at" (.OldTitle|RenderEmoji) (.NewTitle|RenderEmoji) $createdStr | Safe}} {{else if eq .Type 11}} diff --git a/web_src/js/features/emoji.js b/web_src/js/features/emoji.js index 3c24a165b962..51d8801dc8e8 100644 --- a/web_src/js/features/emoji.js +++ b/web_src/js/features/emoji.js @@ -24,7 +24,7 @@ for (const key of emojiKeys) { export function emojiHTML(name) { let inner; if (name === 'gitea') { - inner = `:${name}:`; + inner = `:${name}:`; } else { inner = emojiString(name); } From 2ae8c7ab1cc1311a493fa4efa205412664f54f96 Mon Sep 17 00:00:00 2001 From: zeripath Date: Mon, 24 Aug 2020 16:48:15 +0100 Subject: [PATCH 34/40] Add cron running API (#12421) * Add cron running API Signed-off-by: Andrew Thornton * Apply suggestions from code review * placate-swagger Signed-off-by: Andrew Thornton * return not found Signed-off-by: Andrew Thornton * Apply suggestions from code review Co-authored-by: techknowlogick --- models/list_options.go | 8 +++ modules/structs/cron.go | 16 ++++++ routers/api/v1/admin/cron.go | 86 +++++++++++++++++++++++++++ routers/api/v1/api.go | 4 ++ routers/api/v1/swagger/cron.go | 16 ++++++ templates/swagger/v1_json.tmpl | 102 +++++++++++++++++++++++++++++++++ 6 files changed, 232 insertions(+) create mode 100644 modules/structs/cron.go create mode 100644 routers/api/v1/admin/cron.go create mode 100644 routers/api/v1/swagger/cron.go diff --git a/models/list_options.go b/models/list_options.go index 62c0944cc80c..0912355352d6 100644 --- a/models/list_options.go +++ b/models/list_options.go @@ -37,6 +37,14 @@ func (opts ListOptions) setEnginePagination(e Engine) Engine { return e.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize) } +// GetStartEnd returns the start and end of the ListOptions +func (opts ListOptions) GetStartEnd() (start, end int) { + opts.setDefaultValues() + start = (opts.Page - 1) * opts.PageSize + end = start + opts.Page + return +} + func (opts ListOptions) setDefaultValues() { if opts.PageSize <= 0 { opts.PageSize = setting.API.DefaultPagingNum diff --git a/modules/structs/cron.go b/modules/structs/cron.go new file mode 100644 index 000000000000..f52a5ed3c90a --- /dev/null +++ b/modules/structs/cron.go @@ -0,0 +1,16 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package structs + +import "time" + +// Cron represents a Cron task +type Cron struct { + Name string `json:"name"` + Schedule string `json:"schedule"` + Next time.Time `json:"next"` + Prev time.Time `json:"prev"` + ExecTimes int64 `json:"exec_times"` +} diff --git a/routers/api/v1/admin/cron.go b/routers/api/v1/admin/cron.go new file mode 100644 index 000000000000..2531346fcb0c --- /dev/null +++ b/routers/api/v1/admin/cron.go @@ -0,0 +1,86 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package admin + +import ( + "net/http" + + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/cron" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/routers/api/v1/utils" +) + +// ListCronTasks api for getting cron tasks +func ListCronTasks(ctx *context.APIContext) { + // swagger:operation GET /admin/cron admin adminCronList + // --- + // summary: List cron tasks + // produces: + // - application/json + // parameters: + // - name: page + // in: query + // description: page number of results to return (1-based) + // type: integer + // - name: limit + // in: query + // description: page size of results + // type: integer + // responses: + // "200": + // "$ref": "#/responses/CronList" + // "403": + // "$ref": "#/responses/forbidden" + tasks := cron.ListTasks() + listOpts := utils.GetListOptions(ctx) + start, end := listOpts.GetStartEnd() + + if len(tasks) > listOpts.PageSize { + tasks = tasks[start:end] + } + + res := make([]structs.Cron, len(tasks)) + for i, task := range tasks { + res[i] = structs.Cron{ + Name: task.Name, + Schedule: task.Spec, + Next: task.Next, + Prev: task.Prev, + ExecTimes: task.ExecTimes, + } + } + ctx.JSON(http.StatusOK, res) +} + +// PostCronTask api for getting cron tasks +func PostCronTask(ctx *context.APIContext) { + // swagger:operation POST /admin/cron/{task} admin adminCronRun + // --- + // summary: Run cron task + // produces: + // - application/json + // parameters: + // - name: task + // in: path + // description: task to run + // type: string + // required: true + // responses: + // "204": + // "$ref": "#/responses/empty" + // "404": + // "$ref": "#/responses/notFound" + task := cron.GetTask(ctx.Params(":task")) + if task == nil { + ctx.NotFound() + return + } + task.Run() + log.Trace("Cron Task %s started by admin(%s)", task.Name, ctx.User.Name) + + ctx.Status(http.StatusNoContent) +} diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 506e6a3ec05a..ab7ef6d6f714 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -934,6 +934,10 @@ func RegisterRoutes(m *macaron.Macaron) { }) m.Group("/admin", func() { + m.Group("/cron", func() { + m.Get("", admin.ListCronTasks) + m.Post("/:task", admin.PostCronTask) + }) m.Get("/orgs", admin.GetAllOrgs) m.Group("/users", func() { m.Get("", admin.GetAllUsers) diff --git a/routers/api/v1/swagger/cron.go b/routers/api/v1/swagger/cron.go new file mode 100644 index 000000000000..85f2ed0e3520 --- /dev/null +++ b/routers/api/v1/swagger/cron.go @@ -0,0 +1,16 @@ +// Copyright 2020 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package swagger + +import ( + api "code.gitea.io/gitea/modules/structs" +) + +// CronList +// swagger:response CronList +type swaggerResponseCronList struct { + // in:body + Body []api.Cron `json:"body"` +} diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index ec4570b4881a..d9c8aeb87d6a 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -23,6 +23,69 @@ }, "basePath": "{{AppSubUrl}}/api/v1", "paths": { + "/admin/cron": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "List cron tasks", + "operationId": "adminCronList", + "parameters": [ + { + "type": "integer", + "description": "page number of results to return (1-based)", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "page size of results", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "$ref": "#/responses/CronList" + }, + "403": { + "$ref": "#/responses/forbidden" + } + } + } + }, + "/admin/cron/{task}": { + "post": { + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "Run cron task", + "operationId": "adminCronRun", + "parameters": [ + { + "type": "string", + "description": "task to run", + "name": "task", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "$ref": "#/responses/empty" + }, + "404": { + "$ref": "#/responses/notFound" + } + } + } + }, "/admin/orgs": { "get": { "produces": [ @@ -11931,6 +11994,36 @@ }, "x-go-package": "code.gitea.io/gitea/modules/structs" }, + "Cron": { + "description": "Cron represents a Cron task", + "type": "object", + "properties": { + "exec_times": { + "type": "integer", + "format": "int64", + "x-go-name": "ExecTimes" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "next": { + "type": "string", + "format": "date-time", + "x-go-name": "Next" + }, + "prev": { + "type": "string", + "format": "date-time", + "x-go-name": "Prev" + }, + "schedule": { + "type": "string", + "x-go-name": "Schedule" + } + }, + "x-go-package": "code.gitea.io/gitea/modules/structs" + }, "DeleteEmailOption": { "description": "DeleteEmailOption options when deleting email addresses", "type": "object", @@ -15027,6 +15120,15 @@ "$ref": "#/definitions/ContentsResponse" } }, + "CronList": { + "description": "CronList", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Cron" + } + } + }, "DeployKey": { "description": "DeployKey", "schema": { From 63f3c42be99cd72e765f7d8abfb8b2500b487855 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Mon, 24 Aug 2020 15:49:17 +0000 Subject: [PATCH 35/40] [skip ci] Updated translations via Crowdin --- options/locale/locale_ja-JP.ini | 1 + options/locale/locale_tr-TR.ini | 1 + 2 files changed, 2 insertions(+) diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index 79b238e92a07..1f3c949d014d 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -1275,6 +1275,7 @@ signing.wont_sign.basesigned=ベース側のコミットが署名されていな signing.wont_sign.headsigned=HEADコミットが署名されていないため、マージは署名されません signing.wont_sign.commitssigned=関連するコミットに署名されていないものがあるため、マージは署名されません signing.wont_sign.approved=PRが未承認のため、マージは署名されません +signing.wont_sign.not_signed_in=あなたはサインインしていません ext_wiki=外部Wiki ext_wiki.desc=外部Wikiへのリンク。 diff --git a/options/locale/locale_tr-TR.ini b/options/locale/locale_tr-TR.ini index e26ca2ff36ca..b23ce691f5d8 100644 --- a/options/locale/locale_tr-TR.ini +++ b/options/locale/locale_tr-TR.ini @@ -1275,6 +1275,7 @@ signing.wont_sign.basesigned=Temel işleme imzalanmadığı için birleştirme i signing.wont_sign.headsigned=Ana işleme imzalanmadığı için birleştirme imzalanmayacak signing.wont_sign.commitssigned=İlişkili tüm işlemeler imzalanmadığı için birleştirme imzalanmayacak signing.wont_sign.approved=Değişiklik İsteği onaylanmadığı için birleştirme imzalanmayacak +signing.wont_sign.not_signed_in=Oturum açmadınız ext_wiki=Harici Wiki ext_wiki.desc=Harici bir wiki'ye bağlantı. From 4b97f9018b51c1ef56c16154931123aac6080445 Mon Sep 17 00:00:00 2001 From: 6543 <6543@obermui.de> Date: Mon, 24 Aug 2020 21:46:56 +0200 Subject: [PATCH 36/40] OpenGraph: use repo avatar if exist (#12586) --- models/repo.go | 5 +++++ templates/base/head.tmpl | 6 +++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/models/repo.go b/models/repo.go index b9ebec8be932..d9b65769763f 100644 --- a/models/repo.go +++ b/models/repo.go @@ -2254,6 +2254,11 @@ func (repo *Repository) relAvatarLink(e Engine) string { return setting.AppSubURL + "/repo-avatars/" + repo.Avatar } +// AvatarLink returns a link to the repository's avatar. +func (repo *Repository) AvatarLink() string { + return repo.avatarLink(x) +} + // avatarLink returns user avatar absolute link. func (repo *Repository) avatarLink(e Engine) string { link := repo.relAvatarLink(e) diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index 8c14ccfb6df5..5f27779235be 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -97,7 +97,11 @@ {{end}} {{end}} - + {{if .Repository.AvatarLink}} + + {{else}} + + {{end}} {{else}} From 125ffb87f0d14b75f89acf2a47dc13c0f6577774 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Mon, 24 Aug 2020 17:46:41 -0400 Subject: [PATCH 37/40] go1.15 on windows (#12589) * go1.15 on windows * update xgo to use node14 --- .drone.yml | 19 ++++--------------- Makefile | 5 +++-- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/.drone.yml b/.drone.yml index 0bb731d18d01..9824214bcdbe 100644 --- a/.drone.yml +++ b/.drone.yml @@ -447,23 +447,13 @@ steps: commands: - git fetch --tags --force - - name: static-windows - pull: always - image: techknowlogick/xgo:go-1.14.x - commands: - - apt update && apt -y install curl - - curl -sL https://deb.nodesource.com/setup_12.x | bash - && apt -y install nodejs - - export PATH=$PATH:$GOPATH/bin - - make frontend generate release-windows - environment: - GOPROXY: https://goproxy.cn # proxy.golang.org is blocked in China, this proxy is not - TAGS: bindata sqlite sqlite_unlock_notify - - name: static pull: always image: techknowlogick/xgo:go-1.15.x commands: - - make release-linux release-darwin release-copy release-compress release-sources release-docs release-check + - curl -sL https://deb.nodesource.com/setup_14.x | bash - && apt -y install nodejs + - export PATH=$PATH:$GOPATH/bin + - make release environment: GOPROXY: https://goproxy.cn # proxy.golang.org is blocked in China, this proxy is not TAGS: bindata sqlite sqlite_unlock_notify @@ -558,8 +548,7 @@ steps: pull: always image: techknowlogick/xgo:go-1.15.x commands: - - apt update && apt -y install curl - - curl -sL https://deb.nodesource.com/setup_12.x | bash - && apt -y install nodejs + - curl -sL https://deb.nodesource.com/setup_14.x | bash - && apt -y install nodejs - export PATH=$PATH:$GOPATH/bin - make release environment: diff --git a/Makefile b/Makefile index d0c1fdabfae4..bfeccf82e056 100644 --- a/Makefile +++ b/Makefile @@ -42,8 +42,10 @@ ifeq ($(HAS_GO), GO) endif ifeq ($(OS), Windows_NT) + GOFLAGS := -v -buildmode=exe EXECUTABLE ?= gitea.exe else + GOFLAGS := -v EXECUTABLE ?= gitea endif @@ -55,7 +57,6 @@ endif GOFMT ?= gofmt -s -GOFLAGS := -v EXTRA_GOFLAGS ?= MAKE_VERSION := $(shell $(MAKE) -v | head -n 1) @@ -556,7 +557,7 @@ release-windows: | $(DIST_DIRS) GO111MODULE=off $(GO) get -u src.techknowlogick.com/xgo; \ fi @echo "Warning: windows version is built using golang 1.14" - CGO_CFLAGS="$(CGO_CFLAGS)" GO111MODULE=off xgo -go go-1.14.x -dest $(DIST)/binaries -tags 'netgo osusergo $(TAGS)' -ldflags '-linkmode external -extldflags "-static" $(LDFLAGS)' -targets 'windows/*' -out gitea-$(VERSION) . + CGO_CFLAGS="$(CGO_CFLAGS)" GO111MODULE=off xgo -go $(XGO_VERSION) -buildmode exe -dest $(DIST)/binaries -tags 'netgo osusergo $(TAGS)' -ldflags '-linkmode external -extldflags "-static" $(LDFLAGS)' -targets 'windows/*' -out gitea-$(VERSION) . ifeq ($(CI),drone) cp /build/* $(DIST)/binaries endif From 019e577d54bc16c13488eb44e08a74bb9c3c66e7 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Mon, 24 Aug 2020 17:49:26 -0400 Subject: [PATCH 38/40] Update JWT docs in example config (#12591) * Update JWT docs in example config align with way we have `LFS_JWT_SECRET` in config Fix #12590 * Update custom/conf/app.example.ini Co-authored-by: John Olheiser Co-authored-by: John Olheiser --- custom/conf/app.example.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index 8d4636bfe412..607041527c57 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -971,8 +971,8 @@ ACCESS_TOKEN_EXPIRATION_TIME=3600 REFRESH_TOKEN_EXPIRATION_TIME=730 ; Check if refresh token got already used INVALIDATE_REFRESH_TOKENS=false -; OAuth2 authentication secret for access and refresh tokens, change this to a unique string. -JWT_SECRET=Bk0yK7Y9g_p56v86KaHqjSbxvNvu3SbKoOdOt2ZcXvU +; OAuth2 authentication secret for access and refresh tokens, change this yourself to a unique string. CLI generate option is helpful in this case. https://docs.gitea.io/en-us/command-line/#generate +JWT_SECRET= ; Maximum length of oauth2 token/cookie stored on server MAX_TOKEN_LENGTH=32767 From f3fb3c6f5600714548c63cb0771e887d7a226744 Mon Sep 17 00:00:00 2001 From: zeripath Date: Mon, 24 Aug 2020 23:39:18 +0100 Subject: [PATCH 39/40] Open transaction when adding Avatar email-hash pairs to the DB (#12577) When adding Avatar email-hash pairs we simply want the DB table to represent a Set. We don't care if the hash-pair is already present, so we just simply Insert and ignore the error. Unfortunately this seems to cause some DBs to log the duplicate insert to their logs - looking like a bug a in Gitea. Now, there is no standard way in SQL to say Insert but if there's an error ignore it. MySQL has INSERT IGNORE, PostgreSQL >= 9.5 has INSERT ... ON CONFLICT DO NOTHING, but I do not believe that SQLite or MSSQL have variants. This PR places the insert in a transaction which we are happy to fail if there is an error - hopefully this will stop the unnecessary logging. Signed-off-by: Andrew Thornton Co-authored-by: techknowlogick --- models/avatar.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/models/avatar.go b/models/avatar.go index 311d71462993..c9ba2961ef7b 100644 --- a/models/avatar.go +++ b/models/avatar.go @@ -41,7 +41,18 @@ func AvatarLink(email string) string { Email: lowerEmail, Hash: sum, } - _, _ = x.Insert(emailHash) + // OK we're going to open a session just because I think that that might hide away any problems with postgres reporting errors + sess := x.NewSession() + defer sess.Close() + if err := sess.Begin(); err != nil { + // we don't care about any DB problem just return the lowerEmail + return lowerEmail, nil + } + _, _ = sess.Insert(emailHash) + if err := sess.Commit(); err != nil { + // Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time + return lowerEmail, nil + } return lowerEmail, nil }) return setting.AppSubURL + "/avatar/" + url.PathEscape(sum) From e90e122b395f2dc0aff9ee917a7377078c774d31 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Tue, 25 Aug 2020 02:24:37 -0400 Subject: [PATCH 40/40] update to latest golangci-lint (v1.30.0) (#12597) --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index bfeccf82e056..1fec4eb503ca 100644 --- a/Makefile +++ b/Makefile @@ -681,7 +681,7 @@ pr\#%: clean-all golangci-lint: @hash golangci-lint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \ export BINARY="golangci-lint"; \ - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.24.0; \ + curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.30.0; \ fi golangci-lint run --timeout 5m