Compare commits

...

2 Commits

Author SHA1 Message Date
mscherer 34b5436ae1
Refactor various strings (#17784)
Fixes #16478

Co-authored-by: Gusted <williamzijl7@hotmail.com>

Co-authored-by: Gusted <williamzijl7@hotmail.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2021-12-02 15:28:08 +08:00
a1012112796 ba57e30f13
fix 500 error while use a reserved name in org rename (#17878)
fix #17876

Signed-off-by: a1012112796 <1012112796@qq.com>
2021-12-02 10:43:43 +08:00
19 changed files with 47 additions and 40 deletions

View File

@ -215,7 +215,7 @@ func main() {
//Use git cli command for windows //Use git cli command for windows
runCmd("git", "fetch", remoteUpstream, fmt.Sprintf("pull/%s/head:%s", pr, branch)) runCmd("git", "fetch", remoteUpstream, fmt.Sprintf("pull/%s/head:%s", pr, branch))
} else { } else {
ref := fmt.Sprintf("refs/pull/%s/head:%s", pr, branchRef) ref := fmt.Sprintf(gitea_git.PullPrefix+"%s/head:%s", pr, branchRef)
err = repo.Fetch(&git.FetchOptions{ err = repo.Fetch(&git.FetchOptions{
RemoteName: remoteUpstream, RemoteName: remoteUpstream,
RefSpecs: []config.RefSpec{ RefSpecs: []config.RefSpec{

View File

@ -20,6 +20,7 @@ import (
"code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/references" "code.gitea.io/gitea/modules/references"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
@ -761,8 +762,8 @@ func (issue *Issue) ChangeRef(doer *user_model.User, oldRef string) (err error)
if err = issue.loadRepo(db.GetEngine(ctx)); err != nil { if err = issue.loadRepo(db.GetEngine(ctx)); err != nil {
return fmt.Errorf("loadRepo: %v", err) return fmt.Errorf("loadRepo: %v", err)
} }
oldRefFriendly := strings.TrimPrefix(oldRef, "refs/heads/") oldRefFriendly := strings.TrimPrefix(oldRef, git.BranchPrefix)
newRefFriendly := strings.TrimPrefix(issue.Ref, "refs/heads/") newRefFriendly := strings.TrimPrefix(issue.Ref, git.BranchPrefix)
opts := &CreateCommentOptions{ opts := &CreateCommentOptions{
Type: CommentTypeChangeIssueRef, Type: CommentTypeChangeIssueRef,

View File

@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/models/unit"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
@ -349,7 +350,7 @@ func (pr *PullRequest) GetDefaultSquashMessage() string {
// GetGitRefName returns git ref for hidden pull request branch // GetGitRefName returns git ref for hidden pull request branch
func (pr *PullRequest) GetGitRefName() string { func (pr *PullRequest) GetGitRefName() string {
return fmt.Sprintf("refs/pull/%d/head", pr.Index) return fmt.Sprintf(git.PullPrefix+"%d/head", pr.Index)
} }
// IsChecking returns true if this pull request is still checking conflict. // IsChecking returns true if this pull request is still checking conflict.

View File

@ -10,7 +10,6 @@ import (
"crypto/sha256" "crypto/sha256"
"crypto/subtle" "crypto/subtle"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"net/url" "net/url"
"os" "os"
@ -73,11 +72,6 @@ const (
EmailNotificationsDisabled = "disabled" EmailNotificationsDisabled = "disabled"
) )
var (
// ErrUserNameIllegal user name contains illegal characters error
ErrUserNameIllegal = errors.New("User name contains illegal characters")
)
// User represents the object of individual and member of organization. // User represents the object of individual and member of organization.
type User struct { type User struct {
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`

View File

@ -79,7 +79,7 @@ func ToAPIPullRequest(pr *models.PullRequest, doer *user_model.User) *api.PullRe
}, },
Head: &api.PRBranchInfo{ Head: &api.PRBranchInfo{
Name: pr.HeadBranch, Name: pr.HeadBranch,
Ref: fmt.Sprintf("refs/pull/%d/head", pr.Index), Ref: fmt.Sprintf(git.PullPrefix+"%d/head", pr.Index),
RepoID: -1, RepoID: -1,
}, },
} }

View File

@ -141,7 +141,7 @@ func CommitChangesWithArgs(repoPath string, args []string, opts CommitChangesOpt
func AllCommitsCount(repoPath string, hidePRRefs bool, files ...string) (int64, error) { func AllCommitsCount(repoPath string, hidePRRefs bool, files ...string) (int64, error) {
args := []string{"--all", "--count"} args := []string{"--all", "--count"}
if hidePRRefs { if hidePRRefs {
args = append([]string{"--exclude=refs/pull/*"}, args...) args = append([]string{"--exclude=" + PullPrefix + "*"}, args...)
} }
cmd := NewCommand("rev-list") cmd := NewCommand("rev-list")
cmd.AddArguments(args...) cmd.AddArguments(args...)

View File

@ -6,6 +6,15 @@ package git
import "strings" import "strings"
const (
// RemotePrefix is the base directory of the remotes information of git.
RemotePrefix = "refs/remotes/"
// PullPrefix is the base directory of the pull information of git.
PullPrefix = "refs/pull/"
pullLen = len(PullPrefix)
)
// Reference represents a Git ref. // Reference represents a Git ref.
type Reference struct { type Reference struct {
Name string Name string
@ -24,17 +33,17 @@ func (ref *Reference) ShortName() string {
if ref == nil { if ref == nil {
return "" return ""
} }
if strings.HasPrefix(ref.Name, "refs/heads/") { if strings.HasPrefix(ref.Name, BranchPrefix) {
return ref.Name[11:] return strings.TrimPrefix(ref.Name, BranchPrefix)
} }
if strings.HasPrefix(ref.Name, "refs/tags/") { if strings.HasPrefix(ref.Name, TagPrefix) {
return ref.Name[10:] return strings.TrimPrefix(ref.Name, TagPrefix)
} }
if strings.HasPrefix(ref.Name, "refs/remotes/") { if strings.HasPrefix(ref.Name, RemotePrefix) {
return ref.Name[13:] return strings.TrimPrefix(ref.Name, RemotePrefix)
} }
if strings.HasPrefix(ref.Name, "refs/pull/") && strings.IndexByte(ref.Name[10:], '/') > -1 { if strings.HasPrefix(ref.Name, PullPrefix) && strings.IndexByte(ref.Name[pullLen:], '/') > -1 {
return ref.Name[10 : strings.IndexByte(ref.Name[10:], '/')+10] return ref.Name[pullLen : strings.IndexByte(ref.Name[pullLen:], '/')+pullLen]
} }
return ref.Name return ref.Name
@ -45,16 +54,16 @@ func (ref *Reference) RefGroup() string {
if ref == nil { if ref == nil {
return "" return ""
} }
if strings.HasPrefix(ref.Name, "refs/heads/") { if strings.HasPrefix(ref.Name, BranchPrefix) {
return "heads" return "heads"
} }
if strings.HasPrefix(ref.Name, "refs/tags/") { if strings.HasPrefix(ref.Name, TagPrefix) {
return "tags" return "tags"
} }
if strings.HasPrefix(ref.Name, "refs/remotes/") { if strings.HasPrefix(ref.Name, RemotePrefix) {
return "remotes" return "remotes"
} }
if strings.HasPrefix(ref.Name, "refs/pull/") && strings.IndexByte(ref.Name[10:], '/') > -1 { if strings.HasPrefix(ref.Name, PullPrefix) && strings.IndexByte(ref.Name[pullLen:], '/') > -1 {
return "pull" return "pull"
} }
return "" return ""

View File

@ -371,7 +371,7 @@ func parseSize(objects string) *CountObject {
// GetLatestCommitTime returns time for latest commit in repository (across all branches) // GetLatestCommitTime returns time for latest commit in repository (across all branches)
func GetLatestCommitTime(repoPath string) (time.Time, error) { func GetLatestCommitTime(repoPath string) (time.Time, error) {
cmd := NewCommand("for-each-ref", "--sort=-committerdate", "refs/heads/", "--count", "1", "--format=%(committerdate)") cmd := NewCommand("for-each-ref", "--sort=-committerdate", BranchPrefix, "--count", "1", "--format=%(committerdate)")
stdout, err := cmd.RunInDir(repoPath) stdout, err := cmd.RunInDir(repoPath)
if err != nil { if err != nil {
return time.Time{}, err return time.Time{}, err

View File

@ -33,7 +33,7 @@ func (repo *Repository) GetMergeBase(tmpRemote string, base, head string) (strin
} }
if tmpRemote != "origin" { if tmpRemote != "origin" {
tmpBaseName := "refs/remotes/" + tmpRemote + "/tmp_" + base tmpBaseName := RemotePrefix + tmpRemote + "/tmp_" + base
// Fetch commit into a temporary branch in order to be able to handle commits and tags // Fetch commit into a temporary branch in order to be able to handle commits and tags
_, err := NewCommandContext(repo.Ctx, "fetch", tmpRemote, base+":"+tmpBaseName).RunInDir(repo.Path) _, err := NewCommandContext(repo.Ctx, "fetch", tmpRemote, base+":"+tmpBaseName).RunInDir(repo.Path)
if err == nil { if err == nil {

View File

@ -66,7 +66,7 @@ func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) {
refName = refName[:len(refName)-1] refName = refName[:len(refName)-1]
// refName cannot be HEAD but can be remotes or stash // refName cannot be HEAD but can be remotes or stash
if strings.HasPrefix(refName, "/refs/remotes/") || refName == "/refs/stash" { if strings.HasPrefix(refName, RemotePrefix) || refName == "/refs/stash" {
continue continue
} }

View File

@ -29,7 +29,7 @@ func GetCommitGraph(r *git.Repository, page int, maxAllowedColors int, hidePRRef
args = append(args, "--graph", "--date-order", "--decorate=full") args = append(args, "--graph", "--date-order", "--decorate=full")
if hidePRRefs { if hidePRRefs {
args = append(args, "--exclude=refs/pull/*") args = append(args, "--exclude="+git.PullPrefix+"*")
} }
if len(branches) == 0 { if len(branches) == 0 {

View File

@ -8,6 +8,8 @@ package migration
import ( import (
"fmt" "fmt"
"time" "time"
"code.gitea.io/gitea/modules/git"
) )
// PullRequest defines a standard pull request information // PullRequest defines a standard pull request information
@ -43,7 +45,7 @@ func (p *PullRequest) IsForkPullRequest() bool {
// GetGitRefName returns pull request relative path to head // GetGitRefName returns pull request relative path to head
func (p PullRequest) GetGitRefName() string { func (p PullRequest) GetGitRefName() string {
return fmt.Sprintf("refs/pull/%d/head", p.Number) return fmt.Sprintf(git.PullPrefix+"%d/head", p.Number)
} }
// PullRequestBranch represents a pull request branch // PullRequestBranch represents a pull request branch

View File

@ -73,7 +73,7 @@ func SettingsPost(ctx *context.Context) {
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSettingsOptions, &form) ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSettingsOptions, &form)
return return
} else if err = user_model.ChangeUserName(org.AsUser(), form.Name); err != nil { } else if err = user_model.ChangeUserName(org.AsUser(), form.Name); err != nil {
if err == user_model.ErrUserNameIllegal { if db.IsErrNameReserved(err) || db.IsErrNamePatternNotAllowed(err) {
ctx.Data["OrgName"] = true ctx.Data["OrgName"] = true
ctx.RenderWithErr(ctx.Tr("form.illegal_username"), tplSettingsOptions, &form) ctx.RenderWithErr(ctx.Tr("form.illegal_username"), tplSettingsOptions, &form)
} else { } else {

View File

@ -104,7 +104,7 @@ func Graph(ctx *context.Context) {
copy(realBranches, branches) copy(realBranches, branches)
for i, branch := range realBranches { for i, branch := range realBranches {
if strings.HasPrefix(branch, "--") { if strings.HasPrefix(branch, "--") {
realBranches[i] = "refs/heads/" + branch realBranches[i] = git.BranchPrefix + branch
} }
} }
ctx.Data["SelectedBranches"] = realBranches ctx.Data["SelectedBranches"] = realBranches

View File

@ -403,7 +403,7 @@ func SyncPullMirror(ctx context.Context, repoID int64) bool {
for _, result := range results { for _, result := range results {
// Discard GitHub pull requests, i.e. refs/pull/* // Discard GitHub pull requests, i.e. refs/pull/*
if strings.HasPrefix(result.refName, "refs/pull/") { if strings.HasPrefix(result.refName, git.PullPrefix) {
continue continue
} }
@ -499,7 +499,7 @@ func checkAndUpdateEmptyRepository(m *models.Mirror, gitRepo *git.Repository, re
} }
firstName := "" firstName := ""
for _, result := range results { for _, result := range results {
if strings.HasPrefix(result.refName, "refs/pull/") { if strings.HasPrefix(result.refName, git.PullPrefix) {
continue continue
} }
tp, name := git.SplitRefName(result.refName) tp, name := git.SplitRefName(result.refName)

View File

@ -421,9 +421,9 @@ func rawMerge(pr *models.PullRequest, doer *user_model.User, mergeStyle models.M
var pushCmd *git.Command var pushCmd *git.Command
if mergeStyle == models.MergeStyleRebaseUpdate { if mergeStyle == models.MergeStyleRebaseUpdate {
// force push the rebase result to head brach // force push the rebase result to head brach
pushCmd = git.NewCommand("push", "-f", "head_repo", stagingBranch+":refs/heads/"+pr.HeadBranch) pushCmd = git.NewCommand("push", "-f", "head_repo", stagingBranch+":"+git.BranchPrefix+pr.HeadBranch)
} else { } else {
pushCmd = git.NewCommand("push", "origin", baseBranch+":refs/heads/"+pr.BaseBranch) pushCmd = git.NewCommand("push", "origin", baseBranch+":"+git.BranchPrefix+pr.BaseBranch)
} }
// Push back to upstream. // Push back to upstream.

View File

@ -451,8 +451,8 @@ func pushToBaseRepoHelper(pr *models.PullRequest, prefixHeadBranch string) (err
log.Info("Can't push with %s%s", prefixHeadBranch, pr.HeadBranch) log.Info("Can't push with %s%s", prefixHeadBranch, pr.HeadBranch)
return err return err
} }
log.Info("Retrying to push with refs/heads/%s", pr.HeadBranch) log.Info("Retrying to push with "+git.BranchPrefix+"%s", pr.HeadBranch)
err = pushToBaseRepoHelper(pr, "refs/heads/") err = pushToBaseRepoHelper(pr, git.BranchPrefix)
return err return err
} }
log.Error("Unable to push PR head for %s#%d (%-v:%s) due to Error: %v", pr.BaseRepo.FullName(), pr.Index, pr.BaseRepo, gitRefName, err) log.Error("Unable to push PR head for %s#%d (%-v:%s) due to Error: %v", pr.BaseRepo.FullName(), pr.Index, pr.BaseRepo, gitRefName, err)

View File

@ -152,8 +152,8 @@ func RenameBranch(repo *models.Repository, doer *user_model.User, gitRepo *git.R
return "", err return "", err
} }
notification.NotifyDeleteRef(doer, repo, "branch", "refs/heads/"+from) notification.NotifyDeleteRef(doer, repo, "branch", git.BranchPrefix+from)
notification.NotifyCreateRef(doer, repo, "branch", "refs/heads/"+to) notification.NotifyCreateRef(doer, repo, "branch", git.BranchPrefix+to)
return "", nil return "", nil
} }

View File

@ -266,7 +266,7 @@ func (t *TemporaryUploadRepository) Push(doer *user_model.User, commitHash strin
env := models.PushingEnvironment(doer, t.repo) env := models.PushingEnvironment(doer, t.repo)
if err := git.Push(t.gitRepo.Ctx, t.basePath, git.PushOptions{ if err := git.Push(t.gitRepo.Ctx, t.basePath, git.PushOptions{
Remote: t.repo.RepoPath(), Remote: t.repo.RepoPath(),
Branch: strings.TrimSpace(commitHash) + ":refs/heads/" + strings.TrimSpace(branch), Branch: strings.TrimSpace(commitHash) + ":" + git.BranchPrefix + strings.TrimSpace(branch),
Env: env, Env: env,
}); err != nil { }); err != nil {
if git.IsErrPushOutOfDate(err) { if git.IsErrPushOutOfDate(err) {