diff options
author | ᴜɴᴋɴᴡᴏɴ <u@gogs.io> | 2020-03-08 19:09:31 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-03-08 19:09:31 +0800 |
commit | 6437d0180b97a26319b50c2e22927dac7c94fcdd (patch) | |
tree | 3d0d097e7f498e4b970065096e7500876d365a8b /internal/route | |
parent | c65b5b9f84dee21dc362311b299694e8e00f6ac6 (diff) |
git: migrate to github.com/gogs/git-module@v1.0.0 (#5958)
* WIP
* Finish `internal/db/git_diff.go`
* FInish internal/db/mirror.go
* Finish internal/db/pull.go
* Finish internal/db/release.go
* Finish internal/db/repo.go
* Finish internal/db/repo_branch.go
* Finish internal/db/repo_editor.go
* Finish internal/db/update.go
* Save my work
* Add license header
* Compile!
* Merge master
* Finish internal/cmd/hook.go
* Finish internal/conf/static.go
* Finish internal/context/repo.go
* Finish internal/db/action.go
* Finish internal/db/git_diff.go
* Fix submodule URL inferring
* Finish internal/db/mirror.go
* Updat to beta.4
* css: update fonts
* Finish internal/db/pull.go
* Finish internal/db/release.go
* Finish internal/db/repo_branch.go
* Finish internal/db/wiki.go
* gitutil: enhance infer submodule UR
* Finish internal/route/api/v1/repo/commits.go
* mirror: only collect branch commits after sync
* mirror: fix tag support
* Finish internal/db/repo.go
* Finish internal/db/repo_editor.go
* Finish internal/db/update.go
* Finish internal/gitutil/pull_request.go
* Make it compile
* Finish internal/route/repo/setting.go
* Finish internal/route/repo/branch.go
* Finish internal/route/api/v1/repo/file.go
* Finish internal/route/repo/download.go
* Finish internal/route/repo/editor.go
* Use helper
* Finish internal/route/repo/issue.go
* Finish internal/route/repo/pull.go
* Finish internal/route/repo/release.go
* Finish internal/route/repo/repo.go
* Finish internal/route/repo/wiki.go
* Finish internal/route/repo/commit.go
* Finish internal/route/repo/view.go
* Finish internal/gitutil/tag.go
* go.sum
Diffstat (limited to 'internal/route')
-rw-r--r-- | internal/route/api/v1/convert/convert.go | 2 | ||||
-rw-r--r-- | internal/route/api/v1/repo/commits.go | 37 | ||||
-rw-r--r-- | internal/route/api/v1/repo/contents.go | 75 | ||||
-rw-r--r-- | internal/route/api/v1/repo/file.go | 15 | ||||
-rw-r--r-- | internal/route/api/v1/repo/tree.go | 21 | ||||
-rw-r--r-- | internal/route/install.go | 4 | ||||
-rw-r--r-- | internal/route/repo/branch.go | 4 | ||||
-rw-r--r-- | internal/route/repo/commit.go | 83 | ||||
-rw-r--r-- | internal/route/repo/download.go | 41 | ||||
-rw-r--r-- | internal/route/repo/editor.go | 53 | ||||
-rw-r--r-- | internal/route/repo/issue.go | 19 | ||||
-rw-r--r-- | internal/route/repo/pull.go | 140 | ||||
-rw-r--r-- | internal/route/repo/release.go | 46 | ||||
-rw-r--r-- | internal/route/repo/repo.go | 37 | ||||
-rw-r--r-- | internal/route/repo/setting.go | 31 | ||||
-rw-r--r-- | internal/route/repo/view.go | 89 | ||||
-rw-r--r-- | internal/route/repo/webhook.go | 76 | ||||
-rw-r--r-- | internal/route/repo/wiki.go | 67 |
18 files changed, 400 insertions, 440 deletions
diff --git a/internal/route/api/v1/convert/convert.go b/internal/route/api/v1/convert/convert.go index 0bc2a5ca..027bebbc 100644 --- a/internal/route/api/v1/convert/convert.go +++ b/internal/route/api/v1/convert/convert.go @@ -43,7 +43,7 @@ func ToCommit(c *git.Commit) *api.PayloadCommit { } return &api.PayloadCommit{ ID: c.ID.String(), - Message: c.Message(), + Message: c.Message, URL: "Not implemented", Author: &api.PayloadUser{ Name: c.Author.Name, diff --git a/internal/route/api/v1/repo/commits.go b/internal/route/api/v1/repo/commits.go index ddcd09b7..b3903053 100644 --- a/internal/route/api/v1/repo/commits.go +++ b/internal/route/api/v1/repo/commits.go @@ -16,6 +16,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/db" "gogs.io/gogs/internal/db/errors" + "gogs.io/gogs/internal/gitutil" ) func GetSingleCommit(c *context.APIContext) { @@ -25,14 +26,14 @@ func GetSingleCommit(c *context.APIContext) { return } - gitRepo, err := git.OpenRepository(c.Repo.Repository.RepoPath()) + gitRepo, err := git.Open(c.Repo.Repository.RepoPath()) if err != nil { - c.ServerError("OpenRepository", err) + c.ServerError("open repository", err) return } - commit, err := gitRepo.GetCommit(c.Params(":sha")) + commit, err := gitRepo.CatFileCommit(c.Params(":sha")) if err != nil { - c.NotFoundOrServerError("GetCommit", git.IsErrNotExist, err) + c.NotFoundOrServerError("get commit", gitutil.IsErrRevisionNotExist, err) return } @@ -59,8 +60,8 @@ func GetSingleCommit(c *context.APIContext) { } // Retrieve parent(s) of the commit - apiParents := make([]*api.CommitMeta, commit.ParentCount()) - for i := 0; i < commit.ParentCount(); i++ { + apiParents := make([]*api.CommitMeta, commit.ParentsCount()) + for i := 0; i < commit.ParentsCount(); i++ { sha, _ := commit.ParentID(i) apiParents[i] = &api.CommitMeta{ URL: c.BaseURL + "/repos/" + c.Repo.Repository.FullName() + "/commits/" + sha.String(), @@ -99,24 +100,24 @@ func GetSingleCommit(c *context.APIContext) { } func GetReferenceSHA(c *context.APIContext) { - gitRepo, err := git.OpenRepository(c.Repo.Repository.RepoPath()) + gitRepo, err := git.Open(c.Repo.Repository.RepoPath()) if err != nil { - c.ServerError("OpenRepository", err) + c.ServerError("open repository", err) return } ref := c.Params("*") - refType := 0 // 0-undetermined, 1-branch, 2-tag - if strings.HasPrefix(ref, git.BRANCH_PREFIX) { - ref = strings.TrimPrefix(ref, git.BRANCH_PREFIX) + refType := 0 // 0-unknown, 1-branch, 2-tag + if strings.HasPrefix(ref, git.RefsHeads) { + ref = strings.TrimPrefix(ref, git.RefsHeads) refType = 1 - } else if strings.HasPrefix(ref, git.TAG_PREFIX) { - ref = strings.TrimPrefix(ref, git.TAG_PREFIX) + } else if strings.HasPrefix(ref, git.RefsTags) { + ref = strings.TrimPrefix(ref, git.RefsTags) refType = 2 } else { - if gitRepo.IsBranchExist(ref) { + if gitRepo.HasBranch(ref) { refType = 1 - } else if gitRepo.IsTagExist(ref) { + } else if gitRepo.HasTag(ref) { refType = 2 } else { c.NotFound() @@ -126,12 +127,12 @@ func GetReferenceSHA(c *context.APIContext) { var sha string if refType == 1 { - sha, err = gitRepo.GetBranchCommitID(ref) + sha, err = gitRepo.BranchCommitID(ref) } else if refType == 2 { - sha, err = gitRepo.GetTagCommitID(ref) + sha, err = gitRepo.TagCommitID(ref) } if err != nil { - c.NotFoundOrServerError("get reference commit ID", git.IsErrNotExist, err) + c.NotFoundOrServerError("get reference commit ID", gitutil.IsErrRevisionNotExist, err) return } c.PlainText(http.StatusOK, []byte(sha)) diff --git a/internal/route/api/v1/repo/contents.go b/internal/route/api/v1/repo/contents.go index 7f7ec18e..40303921 100644 --- a/internal/route/api/v1/repo/contents.go +++ b/internal/route/api/v1/repo/contents.go @@ -7,11 +7,9 @@ package repo import ( "encoding/base64" "fmt" - "io/ioutil" - - "github.com/gogs/git-module" "gogs.io/gogs/internal/context" + "gogs.io/gogs/internal/gitutil" ) type repoContent struct { @@ -38,9 +36,9 @@ type Links struct { } func GetContents(c *context.APIContext) { - treeEntry, err := c.Repo.Commit.GetTreeEntryByPath(c.Repo.TreePath) + treeEntry, err := c.Repo.Commit.TreeEntry(c.Repo.TreePath) if err != nil { - c.NotFoundOrServerError("GetTreeEntryByPath", git.IsErrNotExist, err) + c.NotFoundOrServerError("get tree entry", gitutil.IsErrRevisionNotExist, err) return } username := c.Params(":username") @@ -56,8 +54,8 @@ func GetContents(c *context.APIContext) { // :baseurl/repos/:username/:project/tree/:sha templateHTMLLLink := "%s/repos/%s/%s/tree/%s" - gitURL := fmt.Sprintf(templateGitURLLink, c.BaseURL, username, reponame, treeEntry.ID.String()) - htmlURL := fmt.Sprintf(templateHTMLLLink, c.BaseURL, username, reponame, treeEntry.ID.String()) + gitURL := fmt.Sprintf(templateGitURLLink, c.BaseURL, username, reponame, treeEntry.ID().String()) + htmlURL := fmt.Sprintf(templateHTMLLLink, c.BaseURL, username, reponame, treeEntry.ID().String()) selfURL := fmt.Sprintf(templateSelfLink, c.BaseURL, username, reponame, c.Repo.TreePath) // TODO(unknwon): Make a treeEntryToRepoContent helper. @@ -65,7 +63,7 @@ func GetContents(c *context.APIContext) { Size: treeEntry.Size(), Name: treeEntry.Name(), Path: c.Repo.TreePath, - Sha: treeEntry.ID.String(), + Sha: treeEntry.ID().String(), URL: selfURL, GitURL: gitURL, HTMLURL: htmlURL, @@ -82,65 +80,57 @@ func GetContents(c *context.APIContext) { // 2. SubModule // 3. SymLink // 4. Blob (file) - if treeEntry.IsSubModule() { + if treeEntry.IsCommit() { // TODO(unknwon): submoduleURL is not set as current git-module doesn't handle it properly contents.Type = "submodule" c.JSONSuccess(contents) return - } else if treeEntry.IsLink() { + } else if treeEntry.IsSymlink() { contents.Type = "symlink" - blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath) + blob, err := c.Repo.Commit.Blob(c.Repo.TreePath) if err != nil { c.ServerError("GetBlobByPath", err) return } - b, err := blob.Data() + p, err := blob.Bytes() if err != nil { c.ServerError("Data", err) return } - buf, err := ioutil.ReadAll(b) - if err != nil { - c.ServerError("ReadAll", err) - return - } - contents.Target = string(buf) + contents.Target = string(p) c.JSONSuccess(contents) return - } else if treeEntry.Type == "blob" { - blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath) + } else if treeEntry.IsBlob() { + blob, err := c.Repo.Commit.Blob(c.Repo.TreePath) if err != nil { c.ServerError("GetBlobByPath", err) return } - b, err := blob.Data() + p, err := blob.Bytes() if err != nil { c.ServerError("Data", err) return } - buf, err := ioutil.ReadAll(b) - if err != nil { - c.ServerError("ReadAll", err) - return - } - contents.Content = base64.StdEncoding.EncodeToString(buf) + contents.Content = base64.StdEncoding.EncodeToString(p) contents.Type = "file" c.JSONSuccess(contents) return } + // TODO: treeEntry.IsExec() + // treeEntry is a directory - dirTree, err := c.Repo.GitRepo.GetTree(treeEntry.ID.String()) + dirTree, err := c.Repo.GitRepo.LsTree(treeEntry.ID().String()) if err != nil { - c.NotFoundOrServerError("GetTree", git.IsErrNotExist, err) + c.NotFoundOrServerError("get tree", gitutil.IsErrRevisionNotExist, err) return } - entries, err := dirTree.ListEntries() + entries, err := dirTree.Entries() if err != nil { - c.NotFoundOrServerError("ListEntries", git.IsErrNotExist, err) + c.NotFoundOrServerError("list entries", gitutil.IsErrRevisionNotExist, err) return } @@ -151,33 +141,28 @@ func GetContents(c *context.APIContext) { var results = make([]*repoContent, 0, len(entries)) for _, entry := range entries { - gitURL := fmt.Sprintf(templateGitURLLink, c.BaseURL, username, reponame, entry.ID.String()) - htmlURL := fmt.Sprintf(templateHTMLLLink, c.BaseURL, username, reponame, entry.ID.String()) + gitURL := fmt.Sprintf(templateGitURLLink, c.BaseURL, username, reponame, entry.ID().String()) + htmlURL := fmt.Sprintf(templateHTMLLLink, c.BaseURL, username, reponame, entry.ID().String()) selfURL := fmt.Sprintf(templateSelfLink, c.BaseURL, username, reponame, c.Repo.TreePath) var contentType string - if entry.IsDir() { + if entry.IsTree() { contentType = "dir" - } else if entry.IsSubModule() { + } else if entry.IsCommit() { // TODO(unknwon): submoduleURL is not set as current git-module doesn't handle it properly contentType = "submodule" - } else if entry.IsLink() { + } else if entry.IsSymlink() { contentType = "symlink" - blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath) + blob, err := c.Repo.Commit.Blob(c.Repo.TreePath) if err != nil { c.ServerError("GetBlobByPath", err) return } - b, err := blob.Data() + p, err := blob.Bytes() if err != nil { c.ServerError("Data", err) return } - buf, err := ioutil.ReadAll(b) - if err != nil { - c.ServerError("ReadAll", err) - return - } - contents.Target = string(buf) + contents.Target = string(p) } else { contentType = "file" } @@ -187,7 +172,7 @@ func GetContents(c *context.APIContext) { Size: entry.Size(), Name: entry.Name(), Path: c.Repo.TreePath, - Sha: entry.ID.String(), + Sha: entry.ID().String(), URL: selfURL, GitURL: gitURL, HTMLURL: htmlURL, diff --git a/internal/route/api/v1/repo/file.go b/internal/route/api/v1/repo/file.go index 6b1cf470..414d0285 100644 --- a/internal/route/api/v1/repo/file.go +++ b/internal/route/api/v1/repo/file.go @@ -9,6 +9,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/db" + "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/route/repo" ) @@ -23,9 +24,9 @@ func GetRawFile(c *context.APIContext) { return } - blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath) + blob, err := c.Repo.Commit.Blob(c.Repo.TreePath) if err != nil { - c.NotFoundOrServerError("GetBlobByPath", git.IsErrNotExist, err) + c.NotFoundOrServerError("get blob", gitutil.IsErrRevisionNotExist, err) return } if err = repo.ServeBlob(c.Context, blob); err != nil { @@ -35,9 +36,9 @@ func GetRawFile(c *context.APIContext) { func GetArchive(c *context.APIContext) { repoPath := db.RepoPath(c.Params(":username"), c.Params(":reponame")) - gitRepo, err := git.OpenRepository(repoPath) + gitRepo, err := git.Open(repoPath) if err != nil { - c.ServerError("OpenRepository", err) + c.ServerError("open repository", err) return } c.Repo.GitRepo = gitRepo @@ -46,16 +47,16 @@ func GetArchive(c *context.APIContext) { } func GetEditorconfig(c *context.APIContext) { - ec, err := c.Repo.GetEditorconfig() + ec, err := c.Repo.Editorconfig() if err != nil { - c.NotFoundOrServerError("GetEditorconfig", git.IsErrNotExist, err) + c.NotFoundOrServerError("get .editorconfig", gitutil.IsErrRevisionNotExist, err) return } fileName := c.Params("filename") def, err := ec.GetDefinitionForFilename(fileName) if err != nil { - c.ServerError("GetDefinitionForFilename", err) + c.ServerError("get definition for filename", err) return } if def == nil { diff --git a/internal/route/api/v1/repo/tree.go b/internal/route/api/v1/repo/tree.go index c39f3acd..b3485e7a 100644 --- a/internal/route/api/v1/repo/tree.go +++ b/internal/route/api/v1/repo/tree.go @@ -1,3 +1,7 @@ +// Copyright 2020 The Gogs 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 repo import ( @@ -6,6 +10,7 @@ import ( "github.com/gogs/git-module" "gogs.io/gogs/internal/context" + "gogs.io/gogs/internal/gitutil" ) type repoGitTree struct { @@ -24,14 +29,14 @@ type repoGitTreeEntry struct { } func GetRepoGitTree(c *context.APIContext) { - gitTree, err := c.Repo.GitRepo.GetTree(c.Params(":sha")) + gitTree, err := c.Repo.GitRepo.LsTree(c.Params(":sha")) if err != nil { - c.NotFoundOrServerError("GetRepoGitTree", git.IsErrNotExist, err) + c.NotFoundOrServerError("get tree", gitutil.IsErrRevisionNotExist, err) return } - entries, err := gitTree.ListEntries() + entries, err := gitTree.Entries() if err != nil { - c.ServerError("GetRepoGitTree", err) + c.ServerError("list entries", err) return } @@ -48,7 +53,7 @@ func GetRepoGitTree(c *context.APIContext) { children := make([]*repoGitTreeEntry, 0, len(entries)) for _, entry := range entries { var mode string - switch entry.Type { + switch entry.Type() { case git.ObjectCommit: mode = "160000" case git.ObjectTree: @@ -63,10 +68,10 @@ func GetRepoGitTree(c *context.APIContext) { children = append(children, &repoGitTreeEntry{ Path: entry.Name(), Mode: mode, - Type: string(entry.Type), + Type: string(entry.Type()), Size: entry.Size(), - Sha: entry.ID.String(), - URL: fmt.Sprintf(templateURL+"/%s", entry.ID.String()), + Sha: entry.ID().String(), + URL: fmt.Sprintf(templateURL+"/%s", entry.ID().String()), }) } c.JSONSuccess(&repoGitTree{ diff --git a/internal/route/install.go b/internal/route/install.go index fa969f37..187a65a6 100644 --- a/internal/route/install.go +++ b/internal/route/install.go @@ -41,9 +41,9 @@ func checkRunMode() { if conf.IsProdMode() { macaron.Env = macaron.PROD macaron.ColorLog = false - git.Debug = false + git.SetOutput(nil) } else { - git.Debug = true + git.SetOutput(os.Stdout) } log.Info("Run mode: %s", strings.Title(macaron.Env)) } diff --git a/internal/route/repo/branch.go b/internal/route/repo/branch.go index c8d49bbb..2ee353b3 100644 --- a/internal/route/repo/branch.go +++ b/internal/route/repo/branch.go @@ -119,11 +119,11 @@ func DeleteBranchPost(c *context.Context) { c.Redirect(redirectTo) }() - if !c.Repo.GitRepo.IsBranchExist(branchName) { + if !c.Repo.GitRepo.HasBranch(branchName) { return } if len(commitID) > 0 { - branchCommitID, err := c.Repo.GitRepo.GetBranchCommitID(branchName) + branchCommitID, err := c.Repo.GitRepo.BranchCommitID(branchName) if err != nil { log.Error("Failed to get commit ID of branch %q: %v", branchName, err) return diff --git a/internal/route/repo/commit.go b/internal/route/repo/commit.go index 95075fb6..e7fa5778 100644 --- a/internal/route/repo/commit.go +++ b/internal/route/repo/commit.go @@ -5,7 +5,6 @@ package repo import ( - "container/list" "path" "github.com/gogs/git-module" @@ -13,6 +12,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/db" + "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/tool" ) @@ -33,13 +33,9 @@ func RefCommits(c *context.Context) { } } -func RenderIssueLinks(oldCommits *list.List, repoLink string) *list.List { - newCommits := list.New() - for e := oldCommits.Front(); e != nil; e = e.Next() { - c := e.Value.(*git.Commit) - newCommits.PushBack(c) - } - return newCommits +// TODO(unknwon) +func RenderIssueLinks(oldCommits []*git.Commit, repoLink string) []*git.Commit { + return oldCommits } func renderCommits(c *context.Context, filename string) { @@ -53,30 +49,23 @@ func renderCommits(c *context.Context, filename string) { } pageSize := c.QueryInt("pageSize") if pageSize < 1 { - pageSize = git.DefaultCommitsPageSize + pageSize = conf.UI.User.CommitsPagingNum } - // Both 'git log branchName' and 'git log commitID' work. - var err error - var commits *list.List - if len(filename) == 0 { - commits, err = c.Repo.Commit.CommitsByRangeSize(page, pageSize) - } else { - commits, err = c.Repo.GitRepo.CommitsByFileAndRangeSize(c.Repo.BranchName, filename, page, pageSize) - } + commits, err := c.Repo.Commit.CommitsByPage(page, pageSize, git.CommitsByPageOptions{Path: filename}) if err != nil { - c.Handle(500, "CommitsByRangeSize/CommitsByFileAndRangeSize", err) + c.ServerError("paging commits", err) return } + commits = RenderIssueLinks(commits, c.Repo.RepoLink) - commits = db.ValidateCommitsWithEmails(commits) - c.Data["Commits"] = commits + c.Data["Commits"] = db.ValidateCommitsWithEmails(commits) if page > 1 { c.Data["HasPrevious"] = true c.Data["PreviousPage"] = page - 1 } - if commits.Len() == pageSize { + if len(commits) == pageSize { c.Data["HasNext"] = true c.Data["NextPage"] = page + 1 } @@ -102,12 +91,12 @@ func SearchCommits(c *context.Context) { commits, err := c.Repo.Commit.SearchCommits(keyword) if err != nil { - c.Handle(500, "SearchCommits", err) + c.ServerError("SearchCommits", err) return } + commits = RenderIssueLinks(commits, c.Repo.RepoLink) - commits = db.ValidateCommitsWithEmails(commits) - c.Data["Commits"] = commits + c.Data["Commits"] = db.ValidateCommitsWithEmails(commits) c.Data["Keyword"] = keyword c.Data["Username"] = c.Repo.Owner.Name @@ -128,22 +117,23 @@ func Diff(c *context.Context) { repoName := c.Repo.Repository.Name commitID := c.Params(":sha") - commit, err := c.Repo.GitRepo.GetCommit(commitID) + commit, err := c.Repo.GitRepo.CatFileCommit(commitID) if err != nil { - c.NotFoundOrServerError("get commit by ID", git.IsErrNotExist, err) + // TODO: Move checker to gitutil package + c.NotFoundOrServerError("get commit by ID", gitutil.IsErrRevisionNotExist, err) return } - diff, err := db.GetDiffCommit(db.RepoPath(userName, repoName), - commitID, conf.Git.MaxGitDiffLines, - conf.Git.MaxGitDiffLineCharacters, conf.Git.MaxGitDiffFiles) + diff, err := gitutil.RepoDiff(c.Repo.GitRepo, + commitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, + ) if err != nil { - c.NotFoundOrServerError("get diff commit", git.IsErrNotExist, err) + c.NotFoundOrServerError("get diff", gitutil.IsErrRevisionNotExist, err) return } - parents := make([]string, commit.ParentCount()) - for i := 0; i < commit.ParentCount(); i++ { + parents := make([]string, commit.ParentsCount()) + for i := 0; i < commit.ParentsCount(); i++ { sha, err := commit.ParentID(i) parents[i] = sha.String() if err != nil { @@ -169,7 +159,7 @@ func Diff(c *context.Context) { c.Data["Parents"] = parents c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 c.Data["SourcePath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "src", commitID) - if commit.ParentCount() > 0 { + if commit.ParentsCount() > 0 { c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "src", parents[0]) } c.Data["RawPath"] = conf.Server.Subpath + "/" + path.Join(userName, repoName, "raw", commitID) @@ -177,13 +167,12 @@ func Diff(c *context.Context) { } func RawDiff(c *context.Context) { - if err := git.GetRawDiff( - db.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name), + if err := c.Repo.GitRepo.RawDiff( c.Params(":sha"), - git.RawDiffType(c.Params(":ext")), + git.RawDiffFormat(c.Params(":ext")), c.Resp, ); err != nil { - c.NotFoundOrServerError("GetRawDiff", git.IsErrNotExist, err) + c.NotFoundOrServerError("get raw diff", gitutil.IsErrRevisionNotExist, err) return } } @@ -195,31 +184,31 @@ func CompareDiff(c *context.Context) { beforeCommitID := c.Params(":before") afterCommitID := c.Params(":after") - commit, err := c.Repo.GitRepo.GetCommit(afterCommitID) + commit, err := c.Repo.GitRepo.CatFileCommit(afterCommitID) if err != nil { c.Handle(404, "GetCommit", err) return } - diff, err := db.GetDiffRange(db.RepoPath(userName, repoName), beforeCommitID, - afterCommitID, conf.Git.MaxGitDiffLines, - conf.Git.MaxGitDiffLineCharacters, conf.Git.MaxGitDiffFiles) + diff, err := gitutil.RepoDiff(c.Repo.GitRepo, + afterCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, + git.DiffOptions{Base: beforeCommitID}, + ) if err != nil { - c.Handle(404, "GetDiffRange", err) + c.ServerError("get diff", err) return } - commits, err := commit.CommitsBeforeUntil(beforeCommitID) + commits, err := commit.CommitsAfter(beforeCommitID) if err != nil { - c.Handle(500, "CommitsBeforeUntil", err) + c.ServerError("get commits after", err) return } - commits = db.ValidateCommitsWithEmails(commits) c.Data["IsSplitStyle"] = c.Query("style") == "split" c.Data["CommitRepoLink"] = c.Repo.RepoLink - c.Data["Commits"] = commits - c.Data["CommitsCount"] = commits.Len() + c.Data["Commits"] = db.ValidateCommitsWithEmails(commits) + c.Data["CommitsCount"] = len(commits) c.Data["BeforeCommitID"] = beforeCommitID c.Data["AfterCommitID"] = afterCommitID c.Data["Username"] = userName diff --git a/internal/route/repo/download.go b/internal/route/repo/download.go index b75bcb9f..4bf27e20 100644 --- a/internal/route/repo/download.go +++ b/internal/route/repo/download.go @@ -6,32 +6,26 @@ package repo import ( "fmt" - "io" "net/http" "path" "github.com/gogs/git-module" - "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/conf" + "gogs.io/gogs/internal/context" + "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/tool" ) -func serveData(c *context.Context, name string, r io.Reader) error { - buf := make([]byte, 1024) - n, _ := r.Read(buf) - if n >= 0 { - buf = buf[:n] - } - - commit, err := c.Repo.Commit.GetCommitByPath(c.Repo.TreePath) +func serveData(c *context.Context, name string, data []byte) error { + commit, err := c.Repo.Commit.CommitByPath(git.CommitByRevisionOptions{Path: c.Repo.TreePath}) if err != nil { - return fmt.Errorf("GetCommitByPath: %v", err) + return fmt.Errorf("get commit by path %q: %v", c.Repo.TreePath, err) } c.Resp.Header().Set("Last-Modified", commit.Committer.When.Format(http.TimeFormat)) - if !tool.IsTextFile(buf) { - if !tool.IsImageFile(buf) { + if !tool.IsTextFile(data) { + if !tool.IsImageFile(data) { c.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+name+"\"") c.Resp.Header().Set("Content-Transfer-Encoding", "binary") } @@ -39,33 +33,30 @@ func serveData(c *context.Context, name string, r io.Reader) error { c.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8") } - if _, err := c.Resp.Write(buf); err != nil { + if _, err := c.Resp.Write(data); err != nil { return fmt.Errorf("write buffer to response: %v", err) } - _, err = io.Copy(c.Resp, r) - return err + return nil } func ServeBlob(c *context.Context, blob *git.Blob) error { - dataRc, err := blob.Data() + p, err := blob.Bytes() if err != nil { return err } - return serveData(c, path.Base(c.Repo.TreePath), dataRc) + return serveData(c, path.Base(c.Repo.TreePath), p) } func SingleDownload(c *context.Context) { - blob, err := c.Repo.Commit.GetBlobByPath(c.Repo.TreePath) + blob, err := c.Repo.Commit.Blob(c.Repo.TreePath) if err != nil { - if git.IsErrNotExist(err) { - c.Handle(404, "GetBlobByPath", nil) - } else { - c.Handle(500, "GetBlobByPath", err) - } + c.NotFoundOrServerError("get blob", gitutil.IsErrRevisionNotExist, err) return } + if err = ServeBlob(c, blob); err != nil { - c.Handle(500, "ServeBlob", err) + c.ServerError("serve blob", err) + return } } diff --git a/internal/route/repo/editor.go b/internal/route/repo/editor.go index 7b7a0935..17434dff 100644 --- a/internal/route/repo/editor.go +++ b/internal/route/repo/editor.go @@ -6,19 +6,18 @@ package repo import ( "fmt" - "io/ioutil" "net/http" "path" "strings" log "unknwon.dev/clog/v2" - "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/db" "gogs.io/gogs/internal/db/errors" "gogs.io/gogs/internal/form" + "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/pathutil" "gogs.io/gogs/internal/template" "gogs.io/gogs/internal/tool" @@ -55,20 +54,20 @@ func editFile(c *context.Context, isNewFile bool) { treeNames, treePaths := getParentTreeFields(c.Repo.TreePath) if !isNewFile { - entry, err := c.Repo.Commit.GetTreeEntryByPath(c.Repo.TreePath) + entry, err := c.Repo.Commit.TreeEntry(c.Repo.TreePath) if err != nil { - c.NotFoundOrServerError("GetTreeEntryByPath", git.IsErrNotExist, err) + c.NotFoundOrServerError("get tree entry", gitutil.IsErrRevisionNotExist, err) return } // No way to edit a directory online. - if entry.IsDir() { + if entry.IsTree() { c.NotFound() return } blob := entry.Blob() - dataRc, err := blob.Data() + p, err := blob.Bytes() if err != nil { c.ServerError("blob.Data", err) return @@ -77,23 +76,17 @@ func editFile(c *context.Context, isNewFile bool) { c.Data["FileSize"] = blob.Size() c.Data["FileName"] = blob.Name() - buf := make([]byte, 1024) - n, _ := dataRc.Read(buf) - buf = buf[:n] - // Only text file are editable online. - if !tool.IsTextFile(buf) { + if !tool.IsTextFile(p) { c.NotFound() return } - d, _ := ioutil.ReadAll(dataRc) - buf = append(buf, d...) - if err, content := template.ToUTF8WithErr(buf); err != nil { + if err, content := template.ToUTF8WithErr(p); err != nil { if err != nil { log.Error("Failed to convert encoding to UTF-8: %v", err) } - c.Data["FileContent"] = string(buf) + c.Data["FileContent"] = string(p) } else { c.Data["FileContent"] = content } @@ -182,9 +175,9 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { var newTreePath string for index, part := range treeNames { newTreePath = path.Join(newTreePath, part) - entry, err := c.Repo.Commit.GetTreeEntryByPath(newTreePath) + entry, err := c.Repo.Commit.TreeEntry(newTreePath) if err != nil { - if git.IsErrNotExist(err) { + if gitutil.IsErrRevisionNotExist(err) { // Means there is no item with that name, so we're good break } @@ -193,17 +186,17 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { return } if index != len(treeNames)-1 { - if !entry.IsDir() { + if !entry.IsTree() { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), EDIT_FILE, &f) return } } else { - if entry.IsLink() { + if entry.IsSymlink() { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.file_is_a_symlink", part), EDIT_FILE, &f) return - } else if entry.IsDir() { + } else if entry.IsTree() { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.filename_is_a_directory", part), EDIT_FILE, &f) return @@ -212,9 +205,9 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { } if !isNewFile { - _, err := c.Repo.Commit.GetTreeEntryByPath(oldTreePath) + _, err := c.Repo.Commit.TreeEntry(oldTreePath) if err != nil { - if git.IsErrNotExist(err) { + if gitutil.IsErrRevisionNotExist(err) { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), EDIT_FILE, &f) } else { @@ -223,7 +216,7 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { return } if lastCommit != c.Repo.CommitID { - files, err := c.Repo.Commit.GetFilesChangedSinceCommit(lastCommit) + files, err := c.Repo.Commit.FilesChangedAfter(lastCommit) if err != nil { c.ServerError("GetFilesChangedSinceCommit", err) return @@ -240,9 +233,9 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { if oldTreePath != f.TreePath { // We have a new filename (rename or completely new file) so we need to make sure it doesn't already exist, can't clobber. - entry, err := c.Repo.Commit.GetTreeEntryByPath(f.TreePath) + entry, err := c.Repo.Commit.TreeEntry(f.TreePath) if err != nil { - if !git.IsErrNotExist(err) { + if !gitutil.IsErrRevisionNotExist(err) { c.ServerError("GetTreeEntryByPath", err) return } @@ -302,11 +295,11 @@ func NewFilePost(c *context.Context, f form.EditRepoFile) { func DiffPreviewPost(c *context.Context, f form.EditPreviewDiff) { treePath := c.Repo.TreePath - entry, err := c.Repo.Commit.GetTreeEntryByPath(treePath) + entry, err := c.Repo.Commit.TreeEntry(treePath) if err != nil { c.Error(500, "GetTreeEntryByPath: "+err.Error()) return - } else if entry.IsDir() { + } else if entry.IsTree() { c.Error(422) return } @@ -468,9 +461,9 @@ func UploadFilePost(c *context.Context, f form.UploadRepoFile) { var newTreePath string for _, part := range treeNames { newTreePath = path.Join(newTreePath, part) - entry, err := c.Repo.Commit.GetTreeEntryByPath(newTreePath) + entry, err := c.Repo.Commit.TreeEntry(newTreePath) if err != nil { - if git.IsErrNotExist(err) { + if gitutil.IsErrRevisionNotExist(err) { // Means there is no item with that name, so we're good break } @@ -480,7 +473,7 @@ func UploadFilePost(c *context.Context, f form.UploadRepoFile) { } // User can only upload files to a directory. - if !entry.IsDir() { + if !entry.IsTree() { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), UPLOAD_FILE, &f) return diff --git a/internal/route/repo/issue.go b/internal/route/repo/issue.go index 5495402a..fea9af98 100644 --- a/internal/route/repo/issue.go +++ b/internal/route/repo/issue.go @@ -6,8 +6,6 @@ package repo import ( "fmt" - "io" - "io/ioutil" "net/http" "net/url" "strings" @@ -303,30 +301,23 @@ func RetrieveRepoMetas(c *context.Context, repo *db.Repository) []*db.Label { } func getFileContentFromDefaultBranch(c *context.Context, filename string) (string, bool) { - var r io.Reader - var bytes []byte - if c.Repo.Commit == nil { var err error - c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(c.Repo.Repository.DefaultBranch) + c.Repo.Commit, err = c.Repo.GitRepo.BranchCommit(c.Repo.Repository.DefaultBranch) if err != nil { return "", false } } - entry, err := c.Repo.Commit.GetTreeEntryByPath(filename) - if err != nil { - return "", false - } - r, err = entry.Blob().Data() + entry, err := c.Repo.Commit.TreeEntry(filename) if err != nil { return "", false } - bytes, err = ioutil.ReadAll(r) + p, err := entry.Blob().Bytes() if err != nil { return "", false } - return string(bytes), true + return string(p), true } func setTemplateIfExists(c *context.Context, ctxDataKey string, possibleFiles []string) { @@ -656,7 +647,7 @@ func viewIssue(c *context.Context, isPullList bool) { } c.Data["IsPullBranchDeletable"] = pull.BaseRepoID == pull.HeadRepoID && - c.Repo.IsWriter() && c.Repo.GitRepo.IsBranchExist(pull.HeadBranch) && + c.Repo.IsWriter() && c.Repo.GitRepo.HasBranch(pull.HeadBranch) && !branchProtected c.Data["DeleteBranchLink"] = c.Repo.MakeURL(url.URL{ diff --git a/internal/route/repo/pull.go b/internal/route/repo/pull.go index b819857b..a1b47480 100644 --- a/internal/route/repo/pull.go +++ b/internal/route/repo/pull.go @@ -5,7 +5,6 @@ package repo import ( - "container/list" "path" "strings" @@ -19,6 +18,7 @@ import ( "gogs.io/gogs/internal/db" "gogs.io/gogs/internal/db/errors" "gogs.io/gogs/internal/form" + "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/tool" ) @@ -183,19 +183,21 @@ func PrepareMergedViewPullInfo(c *context.Context, issue *db.Issue) { c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch var err error - c.Data["NumCommits"], err = c.Repo.GitRepo.CommitsCountBetween(pull.MergeBase, pull.MergedCommitID) + c.Data["NumCommits"], err = c.Repo.GitRepo.RevListCount([]string{pull.MergeBase + "..." + pull.MergedCommitID}) if err != nil { c.ServerError("Repo.GitRepo.CommitsCountBetween", err) return } - c.Data["NumFiles"], err = c.Repo.GitRepo.FilesCountBetween(pull.MergeBase, pull.MergedCommitID) + + names, err := c.Repo.GitRepo.DiffNameOnly(pull.MergeBase, pull.MergedCommitID, git.DiffNameOnlyOptions{NeedsMergeBase: true}) + c.Data["NumFiles"] = len(names) if err != nil { c.ServerError("Repo.GitRepo.FilesCountBetween", err) return } } -func PrepareViewPullInfo(c *context.Context, issue *db.Issue) *git.PullRequestInfo { +func PrepareViewPullInfo(c *context.Context, issue *db.Issue) *gitutil.PullRequestMeta { repo := c.Repo.Repository pull := issue.PullRequest @@ -208,14 +210,14 @@ func PrepareViewPullInfo(c *context.Context, issue *db.Issue) *git.PullRequestIn ) if pull.HeadRepo != nil { - headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath()) + headGitRepo, err = git.Open(pull.HeadRepo.RepoPath()) if err != nil { - c.ServerError("OpenRepository", err) + c.ServerError("open repository", err) return nil } } - if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) { + if pull.HeadRepo == nil || !headGitRepo.HasBranch(pull.HeadBranch) { c.Data["IsPullReuqestBroken"] = true c.Data["HeadTarget"] = "deleted" c.Data["NumCommits"] = 0 @@ -223,8 +225,8 @@ func PrepareViewPullInfo(c *context.Context, issue *db.Issue) *git.PullRequestIn return nil } - prInfo, err := headGitRepo.GetPullRequestInfo(db.RepoPath(repo.Owner.Name, repo.Name), - pull.BaseBranch, pull.HeadBranch) + baseRepoPath := db.RepoPath(repo.Owner.Name, repo.Name) + prMeta, err := gitutil.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, pull.HeadBranch, pull.BaseBranch) if err != nil { if strings.Contains(err.Error(), "fatal: Not a valid object name") { c.Data["IsPullReuqestBroken"] = true @@ -237,9 +239,9 @@ func PrepareViewPullInfo(c *context.Context, issue *db.Issue) *git.PullRequestIn c.ServerError("GetPullRequestInfo", err) return nil } - c.Data["NumCommits"] = prInfo.Commits.Len() - c.Data["NumFiles"] = prInfo.NumFiles - return prInfo + c.Data["NumCommits"] = len(prMeta.Commits) + c.Data["NumFiles"] = prMeta.NumFiles + return prMeta } func ViewPullCommits(c *context.Context) { @@ -257,25 +259,25 @@ func ViewPullCommits(c *context.Context) { c.Data["Reponame"] = pull.HeadRepo.Name } - var commits *list.List + var commits []*git.Commit if pull.HasMerged { PrepareMergedViewPullInfo(c, issue) if c.Written() { return } - startCommit, err := c.Repo.GitRepo.GetCommit(pull.MergeBase) + startCommit, err := c.Repo.GitRepo.CatFileCommit(pull.MergeBase) if err != nil { - c.ServerError("Repo.GitRepo.GetCommit", err) + c.ServerError("get commit of merge base", err) return } - endCommit, err := c.Repo.GitRepo.GetCommit(pull.MergedCommitID) + endCommit, err := c.Repo.GitRepo.CatFileCommit(pull.MergedCommitID) if err != nil { - c.ServerError("Repo.GitRepo.GetCommit", err) + c.ServerError("get merged commit", err) return } - commits, err = c.Repo.GitRepo.CommitsBetween(endCommit, startCommit) + commits, err = c.Repo.GitRepo.RevList([]string{startCommit.ID.String() + "..." + endCommit.ID.String()}) if err != nil { - c.ServerError("Repo.GitRepo.CommitsBetween", err) + c.ServerError("list commits", err) return } @@ -290,9 +292,8 @@ func ViewPullCommits(c *context.Context) { commits = prInfo.Commits } - commits = db.ValidateCommitsWithEmails(commits) - c.Data["Commits"] = commits - c.Data["CommitsCount"] = commits.Len() + c.Data["Commits"] = db.ValidateCommitsWithEmails(commits) + c.Data["CommitsCount"] = len(commits) c.Success(PULL_COMMITS) } @@ -308,7 +309,7 @@ func ViewPullFiles(c *context.Context) { pull := issue.PullRequest var ( - diffRepoPath string + diffGitRepo *git.Repository startCommitID string endCommitID string gitRepo *git.Repository @@ -320,7 +321,7 @@ func ViewPullFiles(c *context.Context) { return } - diffRepoPath = c.Repo.GitRepo.Path + diffGitRepo = c.Repo.GitRepo startCommitID = pull.MergeBase endCommitID = pull.MergedCommitID gitRepo = c.Repo.GitRepo @@ -335,37 +336,38 @@ func ViewPullFiles(c *context.Context) { headRepoPath := db.RepoPath(pull.HeadUserName, pull.HeadRepo.Name) - headGitRepo, err := git.OpenRepository(headRepoPath) + headGitRepo, err := git.Open(headRepoPath) if err != nil { - c.ServerError("OpenRepository", err) + c.ServerError("open repository", err) return } - headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch) + headCommitID, err := headGitRepo.BranchCommitID(pull.HeadBranch) if err != nil { - c.ServerError("GetBranchCommitID", err) + c.ServerError("get head branch commit ID", err) return } - diffRepoPath = headRepoPath + diffGitRepo = headGitRepo startCommitID = prInfo.MergeBase endCommitID = headCommitID gitRepo = headGitRepo } - diff, err := db.GetDiffRange(diffRepoPath, - startCommitID, endCommitID, conf.Git.MaxGitDiffLines, - conf.Git.MaxGitDiffLineCharacters, conf.Git.MaxGitDiffFiles) + diff, err := gitutil.RepoDiff(diffGitRepo, + endCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, + git.DiffOptions{Base: startCommitID}, + ) if err != nil { - c.ServerError("GetDiffRange", err) + c.ServerError("get diff", err) return } c.Data["Diff"] = diff c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 - commit, err := gitRepo.GetCommit(endCommitID) + commit, err := gitRepo.CatFileCommit(endCommitID) if err != nil { - c.ServerError("GetCommit", err) + c.ServerError("get commit", err) return } @@ -424,7 +426,7 @@ func MergePullRequest(c *context.Context) { c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) } -func ParseCompareInfo(c *context.Context) (*db.User, *db.Repository, *git.Repository, *git.PullRequestInfo, string, string) { +func ParseCompareInfo(c *context.Context) (*db.User, *db.Repository, *git.Repository, *gitutil.PullRequestMeta, string, string) { baseRepo := c.Repo.Repository // Get compared branches information @@ -473,7 +475,7 @@ func ParseCompareInfo(c *context.Context) (*db.User, *db.Repository, *git.Reposi c.Repo.PullRequest.SameRepo = isSameRepo // Check if base branch is valid. - if !c.Repo.GitRepo.IsBranchExist(baseBranch) { + if !c.Repo.GitRepo.HasBranch(baseBranch) { c.NotFound() return nil, nil, nil, nil, "", "" } @@ -497,9 +499,9 @@ func ParseCompareInfo(c *context.Context) (*db.User, *db.Repository, *git.Reposi return nil, nil, nil, nil, "", "" } - headGitRepo, err = git.OpenRepository(db.RepoPath(headUser.Name, headRepo.Name)) + headGitRepo, err = git.Open(db.RepoPath(headUser.Name, headRepo.Name)) if err != nil { - c.ServerError("OpenRepository", err) + c.ServerError("open repository", err) return nil, nil, nil, nil, "", "" } } else { @@ -514,31 +516,32 @@ func ParseCompareInfo(c *context.Context) (*db.User, *db.Repository, *git.Reposi } // Check if head branch is valid. - if !headGitRepo.IsBranchExist(headBranch) { + if !headGitRepo.HasBranch(headBranch) { c.NotFound() return nil, nil, nil, nil, "", "" } - headBranches, err := headGitRepo.GetBranches() + headBranches, err := headGitRepo.Branches() if err != nil { - c.ServerError("GetBranches", err) + c.ServerError("get branches", err) return nil, nil, nil, nil, "", "" } c.Data["HeadBranches"] = headBranches - prInfo, err := headGitRepo.GetPullRequestInfo(db.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch) + baseRepoPath := db.RepoPath(baseRepo.Owner.Name, baseRepo.Name) + meta, err := gitutil.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, headBranch, baseBranch) if err != nil { - if git.IsErrNoMergeBase(err) { + if gitutil.IsErrNoMergeBase(err) { c.Data["IsNoMergeBase"] = true c.Success(COMPARE_PULL) } else { - c.ServerError("GetPullRequestInfo", err) + c.ServerError("get pull request meta", err) } return nil, nil, nil, nil, "", "" } - c.Data["BeforeCommitID"] = prInfo.MergeBase + c.Data["BeforeCommitID"] = meta.MergeBase - return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch + return headUser, headRepo, headGitRepo, meta, baseBranch, headBranch } func PrepareCompareDiff( @@ -546,8 +549,9 @@ func PrepareCompareDiff( headUser *db.User, headRepo *db.Repository, headGitRepo *git.Repository, - prInfo *git.PullRequestInfo, - baseBranch, headBranch string) bool { + meta *gitutil.PullRequestMeta, + headBranch string, +) bool { var ( repo = c.Repo.Repository @@ -557,44 +561,44 @@ func PrepareCompareDiff( // Get diff information. c.Data["CommitRepoLink"] = headRepo.Link() - headCommitID, err := headGitRepo.GetBranchCommitID(headBranch) + headCommitID, err := headGitRepo.BranchCommitID(headBranch) if err != nil { - c.ServerError("GetBranchCommitID", err) + c.ServerError("get head branch commit ID", err) return false } c.Data["AfterCommitID"] = headCommitID - if headCommitID == prInfo.MergeBase { + if headCommitID == meta.MergeBase { c.Data["IsNothingToCompare"] = true return true } - diff, err := db.GetDiffRange(db.RepoPath(headUser.Name, headRepo.Name), - prInfo.MergeBase, headCommitID, conf.Git.MaxGitDiffLines, - conf.Git.MaxGitDiffLineCharacters, conf.Git.MaxGitDiffFiles) + diff, err := gitutil.RepoDiff(headGitRepo, + headCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, + git.DiffOptions{Base: meta.MergeBase}, + ) if err != nil { - c.ServerError("GetDiffRange", err) + c.ServerError("get repository diff", err) return false } c.Data["Diff"] = diff c.Data["DiffNotAvailable"] = diff.NumFiles() == 0 - headCommit, err := headGitRepo.GetCommit(headCommitID) + headCommit, err := headGitRepo.CatFileCommit(headCommitID) if err != nil { - c.ServerError("GetCommit", err) + c.ServerError("get head commit", err) return false } - prInfo.Commits = db.ValidateCommitsWithEmails(prInfo.Commits) - c.Data["Commits"] = prInfo.Commits - c.Data["CommitCount"] = prInfo.Commits.Len() + c.Data["Commits"] = db.ValidateCommitsWithEmails(meta.Commits) + c.Data["CommitCount"] = len(meta.Commits) c.Data["Username"] = headUser.Name c.Data["Reponame"] = headRepo.Name c.Data["IsImageFile"] = headCommit.IsImageFile headTarget := path.Join(headUser.Name, repo.Name) c.Data["SourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", headCommitID) - c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", prInfo.MergeBase) + c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", meta.MergeBase) c.Data["RawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", headCommitID) return false } @@ -625,7 +629,7 @@ func CompareAndPullRequest(c *context.Context) { return } - nothingToCompare := PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch) + nothingToCompare := PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, headBranch) if c.Written() { return } @@ -667,7 +671,7 @@ func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) { attachments []string ) - headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c) + headUser, headRepo, headGitRepo, meta, baseBranch, headBranch := ParseCompareInfo(c) if c.Written() { return } @@ -686,7 +690,7 @@ func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) { // This stage is already stop creating new pull request, so it does not matter if it has // something to compare or not. - PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch) + PrepareCompareDiff(c, headUser, headRepo, headGitRepo, meta, headBranch) if c.Written() { return } @@ -695,9 +699,9 @@ func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) { return } - patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch) + patch, err := headGitRepo.DiffBinary(meta.MergeBase, headBranch) if err != nil { - c.ServerError("GetPatch", err) + c.ServerError("get patch", err) return } @@ -720,7 +724,7 @@ func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) { BaseBranch: baseBranch, HeadRepo: headRepo, BaseRepo: repo, - MergeBase: prInfo.MergeBase, + MergeBase: meta.MergeBase, Type: db.PULL_REQUEST_GOGS, } // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt diff --git a/internal/route/repo/release.go b/internal/route/repo/release.go index 282aa053..f945e4fc 100644 --- a/internal/route/repo/release.go +++ b/internal/route/repo/release.go @@ -8,13 +8,15 @@ import ( "fmt" "strings" + "github.com/gogs/git-module" log "unknwon.dev/clog/v2" + "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/db" "gogs.io/gogs/internal/form" + "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/markup" - "gogs.io/gogs/internal/conf" ) const ( @@ -26,14 +28,14 @@ const ( func calReleaseNumCommitsBehind(repoCtx *context.Repository, release *db.Release, countCache map[string]int64) error { // Get count if not exists if _, ok := countCache[release.Target]; !ok { - if repoCtx.GitRepo.IsBranchExist(release.Target) { - commit, err := repoCtx.GitRepo.GetBranchCommit(release.Target) + if repoCtx.GitRepo.HasBranch(release.Target) { + commit, err := repoCtx.GitRepo.BranchCommit(release.Target) if err != nil { - return fmt.Errorf("GetBranchCommit: %v", err) + return fmt.Errorf("get branch commit: %v", err) } countCache[release.Target], err = commit.CommitsCount() if err != nil { - return fmt.Errorf("CommitsCount: %v", err) + return fmt.Errorf("count commits: %v", err) } } else { // Use NumCommits of the newest release on that target @@ -49,13 +51,13 @@ func Releases(c *context.Context) { c.Data["PageIsViewFiles"] = true c.Data["PageIsReleaseList"] = true - tagsResult, err := c.Repo.GitRepo.GetTagsAfter(c.Query("after"), 10) + tagsPage, err := gitutil.Module.ListTagsAfter(c.Repo.GitRepo.Path(), c.Query("after"), 10) if err != nil { - c.Handle(500, fmt.Sprintf("GetTags '%s'", c.Repo.Repository.RepoPath()), err) + c.ServerError("get tags", err) return } - releases, err := db.GetPublishedReleasesByRepoID(c.Repo.Repository.ID, tagsResult.Tags...) + releases, err := db.GetPublishedReleasesByRepoID(c.Repo.Repository.ID, tagsPage.Tags...) if err != nil { c.Handle(500, "GetPublishedReleasesByRepoID", err) return @@ -64,8 +66,8 @@ func Releases(c *context.Context) { // Temproray cache commits count of used branches to speed up. countCache := make(map[string]int64) - results := make([]*db.Release, len(tagsResult.Tags)) - for i, rawTag := range tagsResult.Tags { + results := make([]*db.Release, len(tagsPage.Tags)) + for i, rawTag := range tagsPage.Tags { for j, r := range releases { if r == nil || r.TagName != rawTag { continue @@ -89,9 +91,9 @@ func Releases(c *context.Context) { // No published release matches this tag if results[i] == nil { - commit, err := c.Repo.GitRepo.GetTagCommit(rawTag) + commit, err := c.Repo.GitRepo.TagCommit(rawTag) if err != nil { - c.Handle(500, "GetTagCommit", err) + c.Handle(500, "get tag commit", err) return } @@ -103,7 +105,7 @@ func Releases(c *context.Context) { results[i].NumCommits, err = commit.CommitsCount() if err != nil { - c.Handle(500, "CommitsCount", err) + c.ServerError("count commits", err) return } results[i].NumCommitsBehind = c.Repo.CommitsCount - results[i].NumCommits @@ -113,7 +115,7 @@ func Releases(c *context.Context) { // Only show drafts if user is viewing the latest page var drafts []*db.Release - if tagsResult.HasLatest { + if tagsPage.HasLatest { drafts, err = db.GetDraftReleasesByRepoID(c.Repo.Repository.ID) if err != nil { c.Handle(500, "GetDraftReleasesByRepoID", err) @@ -140,9 +142,9 @@ func Releases(c *context.Context) { } c.Data["Releases"] = results - c.Data["HasPrevious"] = !tagsResult.HasLatest - c.Data["ReachEnd"] = tagsResult.ReachEnd - c.Data["PreviousAfter"] = tagsResult.PreviousAfter + c.Data["HasPrevious"] = !tagsPage.HasLatest + c.Data["ReachEnd"] = !tagsPage.HasNext + c.Data["PreviousAfter"] = tagsPage.PreviousAfter if len(results) > 0 { c.Data["NextAfter"] = results[len(results)-1].TagName } @@ -175,14 +177,14 @@ func NewReleasePost(c *context.Context, f form.NewRelease) { return } - if !c.Repo.GitRepo.IsBranchExist(f.Target) { + if !c.Repo.GitRepo.HasBranch(f.Target) { c.RenderWithErr(c.Tr("form.target_branch_not_exist"), RELEASE_NEW, &f) return } // Use current time if tag not yet exist, otherwise get time from Git var tagCreatedUnix int64 - tag, err := c.Repo.GitRepo.GetTag(f.TagName) + tag, err := c.Repo.GitRepo.Tag(git.RefsTags + f.TagName) if err == nil { commit, err := tag.Commit() if err == nil { @@ -190,15 +192,15 @@ func NewReleasePost(c *context.Context, f form.NewRelease) { } } - commit, err := c.Repo.GitRepo.GetBranchCommit(f.Target) + commit, err := c.Repo.GitRepo.BranchCommit(f.Target) if err != nil { - c.Handle(500, "GetBranchCommit", err) + c.ServerError("get branch commit", err) return } commitsCount, err := commit.CommitsCount() if err != nil { - c.Handle(500, "CommitsCount", err) + c.ServerError("count commits", err) return } diff --git a/internal/route/repo/repo.go b/internal/route/repo/repo.go index 7f7c2bce..a0bd25fe 100644 --- a/internal/route/repo/repo.go +++ b/internal/route/repo/repo.go @@ -8,6 +8,7 @@ import ( "fmt" "os" "path" + "path/filepath" "strings" "github.com/unknwon/com" @@ -271,22 +272,22 @@ func Action(c *context.Context) { func Download(c *context.Context) { var ( - uri = c.Params("*") - refName string - ext string - archivePath string - archiveType git.ArchiveType + uri = c.Params("*") + refName string + ext string + archivePath string + archiveFormat git.ArchiveFormat ) switch { case strings.HasSuffix(uri, ".zip"): ext = ".zip" - archivePath = path.Join(c.Repo.GitRepo.Path, "archives/zip") - archiveType = git.ZIP + archivePath = filepath.Join(c.Repo.GitRepo.Path(), "archives", "zip") + archiveFormat = git.ArchiveZip case strings.HasSuffix(uri, ".tar.gz"): ext = ".tar.gz" - archivePath = path.Join(c.Repo.GitRepo.Path, "archives/targz") - archiveType = git.TARGZ + archivePath = filepath.Join(c.Repo.GitRepo.Path(), "archives", "targz") + archiveFormat = git.ArchiveTarGz default: log.Trace("Unknown format: %s", uri) c.Error(404) @@ -307,20 +308,20 @@ func Download(c *context.Context) { err error ) gitRepo := c.Repo.GitRepo - if gitRepo.IsBranchExist(refName) { - commit, err = gitRepo.GetBranchCommit(refName) + if gitRepo.HasBranch(refName) { + commit, err = gitRepo.BranchCommit(refName) if err != nil { - c.Handle(500, "GetBranchCommit", err) + c.ServerError("get branch commit", err) return } - } else if gitRepo.IsTagExist(refName) { - commit, err = gitRepo.GetTagCommit(refName) + } else if gitRepo.HasTag(refName) { + commit, err = gitRepo.TagCommit(refName) if err != nil { - c.Handle(500, "GetTagCommit", err) + c.ServerError("get tag commit", err) return } } else if len(refName) >= 7 && len(refName) <= 40 { - commit, err = gitRepo.GetCommit(refName) + commit, err = gitRepo.CatFileCommit(refName) if err != nil { c.NotFound() return @@ -332,8 +333,8 @@ func Download(c *context.Context) { archivePath = path.Join(archivePath, tool.ShortSHA1(commit.ID.String())+ext) if !com.IsFile(archivePath) { - if err := commit.CreateArchive(archivePath, archiveType); err != nil { - c.Handle(500, "Download -> CreateArchive "+archivePath, err) + if err := commit.CreateArchive(archiveFormat, archivePath); err != nil { + c.ServerError("creates archive", err) return } } diff --git a/internal/route/repo/setting.go b/internal/route/repo/setting.go index 405ead4f..bf463f4a 100644 --- a/internal/route/repo/setting.go +++ b/internal/route/repo/setting.go @@ -7,6 +7,7 @@ package repo import ( "fmt" "io/ioutil" + "os" "strings" "time" @@ -448,7 +449,7 @@ func SettingsBranches(c *context.Context) { // Filter out deleted branches branches := make([]string, 0, len(protectBranches)) for i := range protectBranches { - if c.Repo.GitRepo.IsBranchExist(protectBranches[i].Name) { + if c.Repo.GitRepo.HasBranch(protectBranches[i].Name) { branches = append(branches, protectBranches[i].Name) } } @@ -459,15 +460,12 @@ func SettingsBranches(c *context.Context) { func UpdateDefaultBranch(c *context.Context) { branch := c.Query("branch") - if c.Repo.GitRepo.IsBranchExist(branch) && + if c.Repo.GitRepo.HasBranch(branch) && c.Repo.Repository.DefaultBranch != branch { c.Repo.Repository.DefaultBranch = branch - if err := c.Repo.GitRepo.SetDefaultBranch(branch); err != nil { - if !git.IsErrUnsupportedVersion(err) { - c.Handle(500, "SetDefaultBranch", err) - return - } - + if _, err := c.Repo.GitRepo.SymbolicRef(git.SymbolicRefOptions{ + Ref: git.RefsHeads + branch, + }); err != nil { c.Flash.Warning(c.Tr("repo.settings.update_default_branch_unsupported")) c.Redirect(c.Repo.RepoLink + "/settings/branches") return @@ -485,7 +483,7 @@ func UpdateDefaultBranch(c *context.Context) { func SettingsProtectedBranch(c *context.Context) { branch := c.Params("*") - if !c.Repo.GitRepo.IsBranchExist(branch) { + if !c.Repo.GitRepo.HasBranch(branch) { c.NotFound() return } @@ -530,7 +528,7 @@ func SettingsProtectedBranch(c *context.Context) { func SettingsProtectedBranchPost(c *context.Context, f form.ProtectBranch) { branch := c.Params("*") - if !c.Repo.GitRepo.IsBranchExist(branch) { + if !c.Repo.GitRepo.HasBranch(branch) { c.NotFound() return } @@ -570,7 +568,7 @@ func SettingsGitHooks(c *context.Context) { c.Data["Title"] = c.Tr("repo.settings.githooks") c.Data["PageIsSettingsGitHooks"] = true - hooks, err := c.Repo.GitRepo.Hooks() + hooks, err := c.Repo.GitRepo.Hooks("custom_hooks") if err != nil { c.Handle(500, "Hooks", err) return @@ -586,9 +584,9 @@ func SettingsGitHooksEdit(c *context.Context) { c.Data["RequireSimpleMDE"] = true name := c.Params(":name") - hook, err := c.Repo.GitRepo.GetHook(name) + hook, err := c.Repo.GitRepo.Hook("custom_hooks", git.HookName(name)) if err != nil { - if err == git.ErrNotValidHook { + if err == os.ErrNotExist { c.Handle(404, "GetHook", err) } else { c.Handle(500, "GetHook", err) @@ -601,17 +599,16 @@ func SettingsGitHooksEdit(c *context.Context) { func SettingsGitHooksEditPost(c *context.Context) { name := c.Params(":name") - hook, err := c.Repo.GitRepo.GetHook(name) + hook, err := c.Repo.GitRepo.Hook("custom_hooks", git.HookName(name)) if err != nil { - if err == git.ErrNotValidHook { + if err == os.ErrNotExist { c.Handle(404, "GetHook", err) } else { c.Handle(500, "GetHook", err) } return } - hook.Content = c.Query("content") - if err = hook.Update(); err != nil { + if err = hook.Update(c.Query("content")); err != nil { c.Handle(500, "hook.Update", err) return } diff --git a/internal/route/repo/view.go b/internal/route/repo/view.go index f493f190..b07dafe2 100644 --- a/internal/route/repo/view.go +++ b/internal/route/repo/view.go @@ -8,19 +8,20 @@ import ( "bytes" "fmt" gotemplate "html/template" - "io/ioutil" "path" "strings" + "time" + "github.com/gogs/git-module" + "github.com/pkg/errors" "github.com/unknwon/paginater" log "unknwon.dev/clog/v2" - "github.com/gogs/git-module" - + "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/db" + "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/markup" - "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/template" "gogs.io/gogs/internal/template/highlight" "gogs.io/gogs/internal/tool" @@ -34,32 +35,36 @@ const ( ) func renderDirectory(c *context.Context, treeLink string) { - tree, err := c.Repo.Commit.SubTree(c.Repo.TreePath) + tree, err := c.Repo.Commit.Subtree(c.Repo.TreePath) if err != nil { - c.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err) + c.NotFoundOrServerError("get subtree", gitutil.IsErrRevisionNotExist, err) return } - entries, err := tree.ListEntries() + entries, err := tree.Entries() if err != nil { - c.ServerError("ListEntries", err) + c.ServerError("list entries", err) return } entries.Sort() - c.Data["Files"], err = entries.GetCommitsInfoWithCustomConcurrency(c.Repo.Commit, c.Repo.TreePath, conf.Repository.CommitsFetchConcurrency) + c.Data["Files"], err = entries.CommitsInfo(c.Repo.Commit, git.CommitsInfoOptions{ + Path: c.Repo.TreePath, + MaxConcurrency: conf.Repository.CommitsFetchConcurrency, + Timeout: 5 * time.Minute, + }) if err != nil { - c.ServerError("GetCommitsInfoWithCustomConcurrency", err) + c.ServerError("get commits info", err) return } var readmeFile *git.Blob for _, entry := range entries { - if entry.IsDir() || !markup.IsReadmeFile(entry.Name()) { + if entry.IsTree() || !markup.IsReadmeFile(entry.Name()) { continue } - // TODO: collect all possible README files and show with priority. + // TODO(unknwon): collect all possible README files and show with priority. readmeFile = entry.Blob() break } @@ -69,37 +74,30 @@ func renderDirectory(c *context.Context, treeLink string) { c.Data["ReadmeInList"] = true c.Data["ReadmeExist"] = true - dataRc, err := readmeFile.Data() + p, err := readmeFile.Bytes() if err != nil { c.ServerError("readmeFile.Data", err) return } - buf := make([]byte, 1024) - n, _ := dataRc.Read(buf) - buf = buf[:n] - - isTextFile := tool.IsTextFile(buf) + isTextFile := tool.IsTextFile(p) c.Data["IsTextFile"] = isTextFile c.Data["FileName"] = readmeFile.Name() if isTextFile { - d, _ := ioutil.ReadAll(dataRc) - buf = append(buf, d...) - switch markup.Detect(readmeFile.Name()) { case markup.MARKDOWN: c.Data["IsMarkdown"] = true - buf = markup.Markdown(buf, treeLink, c.Repo.Repository.ComposeMetas()) + p = markup.Markdown(p, treeLink, c.Repo.Repository.ComposeMetas()) case markup.ORG_MODE: c.Data["IsMarkdown"] = true - buf = markup.OrgMode(buf, treeLink, c.Repo.Repository.ComposeMetas()) + p = markup.OrgMode(p, treeLink, c.Repo.Repository.ComposeMetas()) case markup.IPYTHON_NOTEBOOK: c.Data["IsIPythonNotebook"] = true c.Data["RawFileLink"] = c.Repo.RepoLink + "/raw/" + path.Join(c.Repo.BranchName, c.Repo.TreePath, readmeFile.Name()) default: - buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1) + p = bytes.Replace(p, []byte("\n"), []byte(`<br>`), -1) } - c.Data["FileContent"] = string(buf) + c.Data["FileContent"] = string(p) } } @@ -107,9 +105,9 @@ func renderDirectory(c *context.Context, treeLink string) { // or of directory if not in root directory. latestCommit := c.Repo.Commit if len(c.Repo.TreePath) > 0 { - latestCommit, err = c.Repo.Commit.GetCommitByPath(c.Repo.TreePath) + latestCommit, err = c.Repo.Commit.CommitByPath(git.CommitByRevisionOptions{Path: c.Repo.TreePath}) if err != nil { - c.ServerError("GetCommitByPath", err) + c.ServerError("get commit by path", err) return } } @@ -126,7 +124,7 @@ func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink stri c.Data["IsViewFile"] = true blob := entry.Blob() - dataRc, err := blob.Data() + p, err := blob.Bytes() if err != nil { c.Handle(500, "Data", err) return @@ -137,11 +135,7 @@ func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink stri c.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name()) c.Data["RawFileLink"] = rawLink + "/" + c.Repo.TreePath - buf := make([]byte, 1024) - n, _ := dataRc.Read(buf) - buf = buf[:n] - - isTextFile := tool.IsTextFile(buf) + isTextFile := tool.IsTextFile(p) c.Data["IsTextFile"] = isTextFile // Assume file is not editable first. @@ -159,26 +153,23 @@ func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink stri c.Data["ReadmeExist"] = markup.IsReadmeFile(blob.Name()) - d, _ := ioutil.ReadAll(dataRc) - buf = append(buf, d...) - switch markup.Detect(blob.Name()) { case markup.MARKDOWN: c.Data["IsMarkdown"] = true - c.Data["FileContent"] = string(markup.Markdown(buf, path.Dir(treeLink), c.Repo.Repository.ComposeMetas())) + c.Data["FileContent"] = string(markup.Markdown(p, path.Dir(treeLink), c.Repo.Repository.ComposeMetas())) case markup.ORG_MODE: c.Data["IsMarkdown"] = true - c.Data["FileContent"] = string(markup.OrgMode(buf, path.Dir(treeLink), c.Repo.Repository.ComposeMetas())) + c.Data["FileContent"] = string(markup.OrgMode(p, path.Dir(treeLink), c.Repo.Repository.ComposeMetas())) case markup.IPYTHON_NOTEBOOK: c.Data["IsIPythonNotebook"] = true default: // Building code view blocks with line number on server side. var fileContent string - if err, content := template.ToUTF8WithErr(buf); err != nil { + if err, content := template.ToUTF8WithErr(p); err != nil { if err != nil { log.Error("ToUTF8WithErr: %s", err) } - fileContent = string(buf) + fileContent = string(p) } else { fileContent = content } @@ -210,11 +201,11 @@ func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink stri c.Data["EditFileTooltip"] = c.Tr("repo.editor.fork_before_edit") } - case tool.IsPDFFile(buf): + case tool.IsPDFFile(p): c.Data["IsPDFFile"] = true - case tool.IsVideoFile(buf): + case tool.IsVideoFile(p): c.Data["IsVideoFile"] = true - case tool.IsImageFile(buf): + case tool.IsImageFile(p): c.Data["IsImageFile"] = true } @@ -229,9 +220,9 @@ func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink stri } func setEditorconfigIfExists(c *context.Context) { - ec, err := c.Repo.GetEditorconfig() - if err != nil && !git.IsErrNotExist(err) { - log.Trace("setEditorconfigIfExists.GetEditorconfig [%d]: %v", c.Repo.Repository.ID, err) + ec, err := c.Repo.Editorconfig() + if err != nil && !gitutil.IsErrRevisionNotExist(errors.Cause(err)) { + log.Warn("setEditorconfigIfExists.Editorconfig [repo_id: %d]: %v", c.Repo.Repository.ID, err) return } c.Data["Editorconfig"] = ec @@ -277,13 +268,13 @@ func Home(c *context.Context) { c.Data["PageIsRepoHome"] = isRootDir // Get current entry user currently looking at. - entry, err := c.Repo.Commit.GetTreeEntryByPath(c.Repo.TreePath) + entry, err := c.Repo.Commit.TreeEntry(c.Repo.TreePath) if err != nil { - c.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err) + c.NotFoundOrServerError("get tree entry", gitutil.IsErrRevisionNotExist, err) return } - if entry.IsDir() { + if entry.IsTree() { renderDirectory(c, treeLink) } else { renderFile(c, entry, treeLink, rawLink) diff --git a/internal/route/repo/webhook.go b/internal/route/repo/webhook.go index 8931a056..705fd2ad 100644 --- a/internal/route/repo/webhook.go +++ b/internal/route/repo/webhook.go @@ -14,11 +14,11 @@ import ( git "github.com/gogs/git-module" api "github.com/gogs/go-gogs-client" + "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/db" "gogs.io/gogs/internal/db/errors" "gogs.io/gogs/internal/form" - "gogs.io/gogs/internal/conf" ) const ( @@ -517,23 +517,37 @@ func DingtalkHooksEditPost(c *context.Context, f form.NewDingtalkHook) { } func TestWebhook(c *context.Context) { - var authorUsername, committerUsername string + + var ( + commitID string + commitMessage string + author *git.Signature + committer *git.Signature + authorUsername string + committerUsername string + nameStatus *git.NameStatus + ) // Grab latest commit or fake one if it's empty repository. - commit := c.Repo.Commit - if commit == nil { + + if c.Repo.Commit == nil { + commitID = git.EmptyID + commitMessage = "This is a fake commit" ghost := db.NewGhostUser() - commit = &git.Commit{ - ID: git.MustIDFromString(git.EMPTY_SHA), - Author: ghost.NewGitSig(), - Committer: ghost.NewGitSig(), - CommitMessage: "This is a fake commit", - } + author = ghost.NewGitSig() + committer = ghost.NewGitSig() authorUsername = ghost.Name committerUsername = ghost.Name + nameStatus = &git.NameStatus{} + } else { + commitID = c.Repo.Commit.ID.String() + commitMessage = c.Repo.Commit.Message + author = c.Repo.Commit.Author + committer = c.Repo.Commit.Committer + // Try to match email with a real user. - author, err := db.GetUserByEmail(commit.Author.Email) + author, err := db.GetUserByEmail(c.Repo.Commit.Author.Email) if err == nil { authorUsername = author.Name } else if !errors.IsUserNotExist(err) { @@ -541,44 +555,44 @@ func TestWebhook(c *context.Context) { return } - committer, err := db.GetUserByEmail(commit.Committer.Email) + user, err := db.GetUserByEmail(c.Repo.Commit.Committer.Email) if err == nil { - committerUsername = committer.Name + committerUsername = user.Name } else if !errors.IsUserNotExist(err) { c.Handle(500, "GetUserByEmail.(committer)", err) return } - } - fileStatus, err := commit.FileStatus() - if err != nil { - c.Handle(500, "FileStatus", err) - return + nameStatus, err = c.Repo.Commit.ShowNameStatus() + if err != nil { + c.Handle(500, "FileStatus", err) + return + } } apiUser := c.User.APIFormat() p := &api.PushPayload{ - Ref: git.BRANCH_PREFIX + c.Repo.Repository.DefaultBranch, - Before: commit.ID.String(), - After: commit.ID.String(), + Ref: git.RefsHeads + c.Repo.Repository.DefaultBranch, + Before: commitID, + After: commitID, Commits: []*api.PayloadCommit{ { - ID: commit.ID.String(), - Message: commit.Message(), - URL: c.Repo.Repository.HTMLURL() + "/commit/" + commit.ID.String(), + ID: commitID, + Message: commitMessage, + URL: c.Repo.Repository.HTMLURL() + "/commit/" + commitID, Author: &api.PayloadUser{ - Name: commit.Author.Name, - Email: commit.Author.Email, + Name: author.Name, + Email: author.Email, UserName: authorUsername, }, Committer: &api.PayloadUser{ - Name: commit.Committer.Name, - Email: commit.Committer.Email, + Name: committer.Name, + Email: committer.Email, UserName: committerUsername, }, - Added: fileStatus.Added, - Removed: fileStatus.Removed, - Modified: fileStatus.Modified, + Added: nameStatus.Added, + Removed: nameStatus.Removed, + Modified: nameStatus.Modified, }, }, Repo: c.Repo.Repository.APIFormat(nil), diff --git a/internal/route/repo/wiki.go b/internal/route/repo/wiki.go index 8a48c319..91bc3c91 100644 --- a/internal/route/repo/wiki.go +++ b/internal/route/repo/wiki.go @@ -5,7 +5,6 @@ package repo import ( - "io/ioutil" "strings" "time" @@ -14,6 +13,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/db" "gogs.io/gogs/internal/form" + "gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/markup" ) @@ -43,27 +43,27 @@ type PageMeta struct { } func renderWikiPage(c *context.Context, isViewPage bool) (*git.Repository, string) { - wikiRepo, err := git.OpenRepository(c.Repo.Repository.WikiPath()) + wikiRepo, err := git.Open(c.Repo.Repository.WikiPath()) if err != nil { - c.Handle(500, "OpenRepository", err) + c.ServerError("open repository", err) return nil, "" } - commit, err := wikiRepo.GetBranchCommit("master") + commit, err := wikiRepo.BranchCommit("master") if err != nil { - c.Handle(500, "GetBranchCommit", err) + c.ServerError("get branch commit", err) return nil, "" } // Get page list. if isViewPage { - entries, err := commit.ListEntries() + entries, err := commit.Entries() if err != nil { - c.Handle(500, "ListEntries", err) + c.ServerError("list entries", err) return nil, "" } pages := make([]PageMeta, 0, len(entries)) for i := range entries { - if entries[i].Type == git.OBJECT_BLOB && strings.HasSuffix(entries[i].Name(), ".md") { + if entries[i].Type() == git.ObjectBlob && strings.HasSuffix(entries[i].Name(), ".md") { name := strings.TrimSuffix(entries[i].Name(), ".md") pages = append(pages, PageMeta{ Name: name, @@ -86,29 +86,24 @@ func renderWikiPage(c *context.Context, isViewPage bool) (*git.Repository, strin c.Data["title"] = pageName c.Data["RequireHighlightJS"] = true - blob, err := commit.GetBlobByPath(pageName + ".md") + blob, err := commit.Blob(pageName + ".md") if err != nil { - if git.IsErrNotExist(err) { + if gitutil.IsErrRevisionNotExist(err) { c.Redirect(c.Repo.RepoLink + "/wiki/_pages") } else { - c.Handle(500, "GetBlobByPath", err) + c.ServerError("GetBlobByPath", err) } return nil, "" } - r, err := blob.Data() + p, err := blob.Bytes() if err != nil { - c.Handle(500, "Data", err) - return nil, "" - } - data, err := ioutil.ReadAll(r) - if err != nil { - c.Handle(500, "ReadAll", err) + c.ServerError("Data", err) return nil, "" } if isViewPage { - c.Data["content"] = string(markup.Markdown(data, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) + c.Data["content"] = string(markup.Markdown(p, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas())) } else { - c.Data["content"] = string(data) + c.Data["content"] = string(p) } return wikiRepo, pageName @@ -129,12 +124,12 @@ func Wiki(c *context.Context) { } // Get last change information. - lastCommit, err := wikiRepo.GetCommitByPath(pageName + ".md") + commits, err := wikiRepo.Log(git.RefsHeads+"master", git.LogOptions{Path: pageName + ".md"}) if err != nil { - c.Handle(500, "GetCommitByPath", err) + c.ServerError("get commits by path", err) return } - c.Data["Author"] = lastCommit.Author + c.Data["Author"] = commits[0].Author c.HTML(200, WIKI_VIEW) } @@ -148,35 +143,35 @@ func WikiPages(c *context.Context) { return } - wikiRepo, err := git.OpenRepository(c.Repo.Repository.WikiPath()) + wikiRepo, err := git.Open(c.Repo.Repository.WikiPath()) if err != nil { - c.Handle(500, "OpenRepository", err) + c.ServerError("open repository", err) return } - commit, err := wikiRepo.GetBranchCommit("master") + commit, err := wikiRepo.BranchCommit("master") if err != nil { - c.Handle(500, "GetBranchCommit", err) + c.ServerError("get branch commit", err) return } - entries, err := commit.ListEntries() + entries, err := commit.Entries() if err != nil { - c.Handle(500, "ListEntries", err) + c.ServerError("list entries", err) return } pages := make([]PageMeta, 0, len(entries)) for i := range entries { - if entries[i].Type == git.OBJECT_BLOB && strings.HasSuffix(entries[i].Name(), ".md") { - commit, err := wikiRepo.GetCommitByPath(entries[i].Name()) + if entries[i].Type() == git.ObjectBlob && strings.HasSuffix(entries[i].Name(), ".md") { + commits, err := wikiRepo.Log(git.RefsHeads+"master", git.LogOptions{Path: entries[i].Name()}) if err != nil { - c.ServerError("GetCommitByPath", err) + c.ServerError("get commits by path", err) return } name := strings.TrimSuffix(entries[i].Name(), ".md") pages = append(pages, PageMeta{ Name: name, URL: db.ToWikiPageURL(name), - Updated: commit.Author.When, + Updated: commits[0].Author.When, }) } } @@ -212,7 +207,7 @@ func NewWikiPost(c *context.Context, f form.NewWiki) { c.Data["Err_Title"] = true c.RenderWithErr(c.Tr("repo.wiki.page_already_exists"), WIKI_NEW, &f) } else { - c.Handle(500, "AddWikiPage", err) + c.ServerError("AddWikiPage", err) } return } @@ -249,7 +244,7 @@ func EditWikiPost(c *context.Context, f form.NewWiki) { } if err := c.Repo.Repository.EditWikiPage(c.User, f.OldTitle, f.Title, f.Content, f.Message); err != nil { - c.Handle(500, "EditWikiPage", err) + c.ServerError("EditWikiPage", err) return } @@ -264,7 +259,7 @@ func DeleteWikiPagePost(c *context.Context) { pageName := db.ToWikiPageName(pageURL) if err := c.Repo.Repository.DeleteWikiPage(c.User, pageName); err != nil { - c.Handle(500, "DeleteWikiPage", err) + c.ServerError("DeleteWikiPage", err) return } |