diff options
author | zeripath <art27@cantab.net> | 2022-01-19 23:26:57 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-19 23:26:57 +0000 |
commit | 5cb0c9aa0d7eed087055b1efca79628957207d36 (patch) | |
tree | d117a514e1f17e5f6bfcda1be273f6a971112663 /routers | |
parent | 4563148a61ba892e8f2bb66342f00a950bcd5315 (diff) | |
download | gitea-5cb0c9aa0d7eed087055b1efca79628957207d36.tar.gz gitea-5cb0c9aa0d7eed087055b1efca79628957207d36.zip |
Propagate context and ensure git commands run in request context (#17868)
This PR continues the work in #17125 by progressively ensuring that git
commands run within the request context.
This now means that the if there is a git repo already open in the context it will be used instead of reopening it.
Signed-off-by: Andrew Thornton <art27@cantab.net>
Diffstat (limited to 'routers')
41 files changed, 188 insertions, 205 deletions
diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 7a2347650a..7a723a138a 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -778,10 +778,10 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route { m.Combo("/forks").Get(repo.ListForks). Post(reqToken(), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork) m.Group("/branches", func() { - m.Get("", repo.ListBranches) - m.Get("/*", repo.GetBranch) - m.Delete("/*", context.ReferencesGitRepo(false), reqRepoWriter(unit.TypeCode), repo.DeleteBranch) - m.Post("", reqRepoWriter(unit.TypeCode), bind(api.CreateBranchRepoOption{}), repo.CreateBranch) + m.Get("", context.ReferencesGitRepo(false), repo.ListBranches) + m.Get("/*", context.ReferencesGitRepo(false), repo.GetBranch) + m.Delete("/*", reqRepoWriter(unit.TypeCode), context.ReferencesGitRepo(false), repo.DeleteBranch) + m.Post("", reqRepoWriter(unit.TypeCode), context.ReferencesGitRepo(false), bind(api.CreateBranchRepoOption{}), repo.CreateBranch) }, reqRepoReader(unit.TypeCode)) m.Group("/branch_protections", func() { m.Get("", repo.ListBranchProtections) @@ -957,7 +957,7 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route { Post(reqToken(), bind(api.CreateStatusOption{}), repo.NewCommitStatus) }, reqRepoReader(unit.TypeCode)) m.Group("/commits", func() { - m.Get("", repo.GetAllCommits) + m.Get("", context.ReferencesGitRepo(false), repo.GetAllCommits) m.Group("/{ref}", func() { m.Get("/status", repo.GetCombinedCommitStatusByRef) m.Get("/statuses", repo.GetCommitStatusesByRef) @@ -965,7 +965,7 @@ func Routes(sessioner func(http.Handler) http.Handler) *web.Route { }, reqRepoReader(unit.TypeCode)) m.Group("/git", func() { m.Group("/commits", func() { - m.Get("/{sha}", repo.GetSingleCommit) + m.Get("/{sha}", context.ReferencesGitRepo(false), repo.GetSingleCommit) m.Get("/{sha}.{diffType:diff|patch}", repo.DownloadCommitDiffOrPatch) }) m.Get("/refs", repo.GetGitAllRefs) diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index f1007b7ee2..eb0b78a5ba 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -78,6 +78,7 @@ func Markdown(ctx *context.APIContext) { } if err := markdown.Render(&markup.RenderContext{ + Ctx: ctx, URLPrefix: urlPrefix, Metas: meta, IsWiki: form.Wiki, @@ -87,6 +88,7 @@ func Markdown(ctx *context.APIContext) { } default: if err := markdown.RenderRaw(&markup.RenderContext{ + Ctx: ctx, URLPrefix: form.Context, }, strings.NewReader(form.Text), ctx.Resp); err != nil { ctx.InternalServerError(err) @@ -117,7 +119,9 @@ func MarkdownRaw(ctx *context.APIContext) { // "422": // "$ref": "#/responses/validationError" defer ctx.Req.Body.Close() - if err := markdown.RenderRaw(&markup.RenderContext{}, ctx.Req.Body, ctx.Resp); err != nil { + if err := markdown.RenderRaw(&markup.RenderContext{ + Ctx: ctx, + }, ctx.Req.Body, ctx.Resp); err != nil { ctx.InternalServerError(err) return } diff --git a/routers/api/v1/misc/signing.go b/routers/api/v1/misc/signing.go index e2833173a3..b99e560ccf 100644 --- a/routers/api/v1/misc/signing.go +++ b/routers/api/v1/misc/signing.go @@ -52,7 +52,7 @@ func SigningKey(ctx *context.APIContext) { path = ctx.Repo.Repository.RepoPath() } - content, err := asymkey_service.PublicSigningKey(path) + content, err := asymkey_service.PublicSigningKey(ctx, path) if err != nil { ctx.Error(http.StatusInternalServerError, "gpg export", err) return diff --git a/routers/api/v1/repo/blob.go b/routers/api/v1/repo/blob.go index e3ce0e1916..19d893a68b 100644 --- a/routers/api/v1/repo/blob.go +++ b/routers/api/v1/repo/blob.go @@ -45,7 +45,7 @@ func GetBlob(ctx *context.APIContext) { ctx.Error(http.StatusBadRequest, "", "sha not provided") return } - if blob, err := files_service.GetBlobBySHA(ctx.Repo.Repository, sha); err != nil { + if blob, err := files_service.GetBlobBySHA(ctx, ctx.Repo.Repository, sha); err != nil { ctx.Error(http.StatusBadRequest, "", err) } else { ctx.JSON(http.StatusOK, blob) diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 56266b406a..c5480bf2c5 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -53,7 +53,7 @@ func GetBranch(ctx *context.APIContext) { branchName := ctx.Params("*") - branch, err := repo_service.GetBranch(ctx.Repo.Repository, branchName) + branch, err := ctx.Repo.GitRepo.GetBranch(branchName) if err != nil { if git.IsErrBranchNotExist(err) { ctx.NotFound(err) @@ -176,7 +176,7 @@ func CreateBranch(ctx *context.APIContext) { opt.OldBranchName = ctx.Repo.Repository.DefaultBranch } - err := repo_service.CreateNewBranch(ctx.User, ctx.Repo.Repository, opt.OldBranchName, opt.BranchName) + err := repo_service.CreateNewBranch(ctx, ctx.User, ctx.Repo.Repository, opt.OldBranchName, opt.BranchName) if err != nil { if models.IsErrBranchDoesNotExist(err) { @@ -198,7 +198,7 @@ func CreateBranch(ctx *context.APIContext) { return } - branch, err := repo_service.GetBranch(ctx.Repo.Repository, opt.BranchName) + branch, err := ctx.Repo.GitRepo.GetBranch(opt.BranchName) if err != nil { ctx.Error(http.StatusInternalServerError, "GetBranch", err) return @@ -257,7 +257,7 @@ func ListBranches(ctx *context.APIContext) { listOptions := utils.GetListOptions(ctx) skip, _ := listOptions.GetStartEnd() - branches, totalNumOfBranches, err := repo_service.GetBranches(ctx.Repo.Repository, skip, listOptions.PageSize) + branches, totalNumOfBranches, err := ctx.Repo.GitRepo.GetBranches(skip, listOptions.PageSize) if err != nil { ctx.Error(http.StatusInternalServerError, "GetBranches", err) return diff --git a/routers/api/v1/repo/commits.go b/routers/api/v1/repo/commits.go index a2b4298602..b6c47e0685 100644 --- a/routers/api/v1/repo/commits.go +++ b/routers/api/v1/repo/commits.go @@ -62,13 +62,7 @@ func GetSingleCommit(ctx *context.APIContext) { } func getCommit(ctx *context.APIContext, identifier string) { - gitRepo, err := git.OpenRepository(ctx.Repo.Repository.RepoPath()) - if err != nil { - ctx.Error(http.StatusInternalServerError, "OpenRepository", err) - return - } - defer gitRepo.Close() - commit, err := gitRepo.GetCommit(identifier) + commit, err := ctx.Repo.GitRepo.GetCommit(identifier) if err != nil { if git.IsErrNotExist(err) { ctx.NotFound(identifier) @@ -78,7 +72,7 @@ func getCommit(ctx *context.APIContext, identifier string) { return } - json, err := convert.ToCommit(ctx.Repo.Repository, commit, nil) + json, err := convert.ToCommit(ctx.Repo.Repository, ctx.Repo.GitRepo, commit, nil) if err != nil { ctx.Error(http.StatusInternalServerError, "toCommit", err) return @@ -136,13 +130,6 @@ func GetAllCommits(ctx *context.APIContext) { return } - gitRepo, err := git.OpenRepository(ctx.Repo.Repository.RepoPath()) - if err != nil { - ctx.Error(http.StatusInternalServerError, "OpenRepository", err) - return - } - defer gitRepo.Close() - listOptions := utils.GetListOptions(ctx) if listOptions.Page <= 0 { listOptions.Page = 1 @@ -158,26 +145,27 @@ func GetAllCommits(ctx *context.APIContext) { var ( commitsCountTotal int64 commits []*git.Commit + err error ) if len(path) == 0 { var baseCommit *git.Commit if len(sha) == 0 { // no sha supplied - use default branch - head, err := gitRepo.GetHEADBranch() + head, err := ctx.Repo.GitRepo.GetHEADBranch() if err != nil { ctx.Error(http.StatusInternalServerError, "GetHEADBranch", err) return } - baseCommit, err = gitRepo.GetBranchCommit(head.Name) + baseCommit, err = ctx.Repo.GitRepo.GetBranchCommit(head.Name) if err != nil { ctx.Error(http.StatusInternalServerError, "GetCommit", err) return } } else { // get commit specified by sha - baseCommit, err = gitRepo.GetCommit(sha) + baseCommit, err = ctx.Repo.GitRepo.GetCommit(sha) if err != nil { ctx.Error(http.StatusInternalServerError, "GetCommit", err) return @@ -202,7 +190,7 @@ func GetAllCommits(ctx *context.APIContext) { sha = ctx.Repo.Repository.DefaultBranch } - commitsCountTotal, err = gitRepo.FileCommitsCount(sha, path) + commitsCountTotal, err = ctx.Repo.GitRepo.FileCommitsCount(sha, path) if err != nil { ctx.Error(http.StatusInternalServerError, "FileCommitsCount", err) return @@ -211,7 +199,7 @@ func GetAllCommits(ctx *context.APIContext) { return } - commits, err = gitRepo.CommitsByFileAndRange(sha, path, listOptions.Page) + commits, err = ctx.Repo.GitRepo.CommitsByFileAndRange(sha, path, listOptions.Page) if err != nil { ctx.Error(http.StatusInternalServerError, "CommitsByFileAndRange", err) return @@ -225,7 +213,7 @@ func GetAllCommits(ctx *context.APIContext) { apiCommits := make([]*api.Commit, len(commits)) for i, commit := range commits { // Create json struct - apiCommits[i], err = convert.ToCommit(ctx.Repo.Repository, commit, userCache) + apiCommits[i], err = convert.ToCommit(ctx.Repo.Repository, ctx.Repo.GitRepo, commit, userCache) if err != nil { ctx.Error(http.StatusInternalServerError, "toCommit", err) return @@ -282,6 +270,7 @@ func DownloadCommitDiffOrPatch(ctx *context.APIContext) { // "$ref": "#/responses/notFound" repoPath := repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) if err := git.GetRawDiff( + ctx, repoPath, ctx.Params(":sha"), git.RawDiffType(ctx.Params(":diffType")), diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index f02c7ea345..a27e383bc3 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -122,7 +122,7 @@ func GetArchive(ctx *context.APIContext) { repoPath := repo_model.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) if ctx.Repo.GitRepo == nil { - gitRepo, err := git.OpenRepository(repoPath) + gitRepo, err := git.OpenRepositoryCtx(ctx, repoPath) if err != nil { ctx.Error(http.StatusInternalServerError, "OpenRepository", err) return @@ -402,7 +402,7 @@ func createOrUpdateFile(ctx *context.APIContext, opts *files_service.UpdateRepoF } opts.Content = string(content) - return files_service.CreateOrUpdateRepoFile(ctx.Repo.Repository, ctx.User, opts) + return files_service.CreateOrUpdateRepoFile(ctx, ctx.Repo.Repository, ctx.User, opts) } // DeleteFile Delete a file in a repository @@ -489,7 +489,7 @@ func DeleteFile(ctx *context.APIContext) { opts.Message = ctx.Tr("repo.editor.delete", opts.TreePath) } - if fileResponse, err := files_service.DeleteRepoFile(ctx.Repo.Repository, ctx.User, opts); err != nil { + if fileResponse, err := files_service.DeleteRepoFile(ctx, ctx.Repo.Repository, ctx.User, opts); err != nil { if git.IsErrBranchNotExist(err) || models.IsErrRepoFileDoesNotExist(err) || git.IsErrNotExist(err) { ctx.Error(http.StatusNotFound, "DeleteFile", err) return @@ -555,7 +555,7 @@ func GetContents(ctx *context.APIContext) { treePath := ctx.Params("*") ref := ctx.FormTrim("ref") - if fileList, err := files_service.GetContentsOrList(ctx.Repo.Repository, treePath, ref); err != nil { + if fileList, err := files_service.GetContentsOrList(ctx, ctx.Repo.Repository, treePath, ref); err != nil { if git.IsErrNotExist(err) { ctx.NotFound("GetContentsOrList", err) return diff --git a/routers/api/v1/repo/notes.go b/routers/api/v1/repo/notes.go index a5f9512983..edcb27b1ec 100644 --- a/routers/api/v1/repo/notes.go +++ b/routers/api/v1/repo/notes.go @@ -55,7 +55,7 @@ func GetNote(ctx *context.APIContext) { } func getNote(ctx *context.APIContext, identifier string) { - gitRepo, err := git.OpenRepository(ctx.Repo.Repository.RepoPath()) + gitRepo, err := git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.RepoPath()) if err != nil { ctx.Error(http.StatusInternalServerError, "OpenRepository", err) return @@ -72,7 +72,7 @@ func getNote(ctx *context.APIContext, identifier string) { return } - cmt, err := convert.ToCommit(ctx.Repo.Repository, note.Commit, nil) + cmt, err := convert.ToCommit(ctx.Repo.Repository, gitRepo, note.Commit, nil) if err != nil { ctx.Error(http.StatusInternalServerError, "ToCommit", err) return diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index 158abd4651..52ff8425de 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -119,7 +119,7 @@ func ListPullRequests(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) return } - apiPrs[i] = convert.ToAPIPullRequest(prs[i], ctx.User) + apiPrs[i] = convert.ToAPIPullRequest(ctx, prs[i], ctx.User) } ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) @@ -175,7 +175,7 @@ func GetPullRequest(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) return } - ctx.JSON(http.StatusOK, convert.ToAPIPullRequest(pr, ctx.User)) + ctx.JSON(http.StatusOK, convert.ToAPIPullRequest(ctx, pr, ctx.User)) } // DownloadPullDiffOrPatch render a pull's raw diff or patch @@ -235,7 +235,7 @@ func DownloadPullDiffOrPatch(ctx *context.APIContext) { binary := ctx.FormBool("binary") - if err := pull_service.DownloadDiffOrPatch(pr, ctx, patch, binary); err != nil { + if err := pull_service.DownloadDiffOrPatch(ctx, pr, ctx, patch, binary); err != nil { ctx.InternalServerError(err) return } @@ -411,7 +411,7 @@ func CreatePullRequest(ctx *context.APIContext) { } } - if err := pull_service.NewPullRequest(repo, prIssue, labelIDs, []string{}, pr, assigneeIDs); err != nil { + if err := pull_service.NewPullRequest(ctx, repo, prIssue, labelIDs, []string{}, pr, assigneeIDs); err != nil { if models.IsErrUserDoesNotHaveAccessToRepo(err) { ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err) return @@ -421,7 +421,7 @@ func CreatePullRequest(ctx *context.APIContext) { } log.Trace("Pull request created: %d/%d", repo.ID, prIssue.ID) - ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(pr, ctx.User)) + ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(ctx, pr, ctx.User)) } // EditPullRequest does what it says @@ -598,7 +598,7 @@ func EditPullRequest(ctx *context.APIContext) { ctx.Error(http.StatusNotFound, "NewBaseBranchNotExist", fmt.Errorf("new base '%s' not exist", form.Base)) return } - if err := pull_service.ChangeTargetBranch(pr, ctx.User, form.Base); err != nil { + if err := pull_service.ChangeTargetBranch(ctx, pr, ctx.User, form.Base); err != nil { if models.IsErrPullRequestAlreadyExists(err) { ctx.Error(http.StatusConflict, "IsErrPullRequestAlreadyExists", err) return @@ -628,7 +628,7 @@ func EditPullRequest(ctx *context.APIContext) { } // TODO this should be 200, not 201 - ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(pr, ctx.User)) + ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(ctx, pr, ctx.User)) } // IsPullRequestMerged checks if a PR exists given an index @@ -792,7 +792,7 @@ func MergePullRequest(ctx *context.APIContext) { return } - if err := pull_service.CheckPRReadyToMerge(pr, false); err != nil { + if err := pull_service.CheckPRReadyToMerge(ctx, pr, false); err != nil { if !models.IsErrNotAllowedToMerge(err) { ctx.Error(http.StatusInternalServerError, "CheckPRReadyToMerge", err) return @@ -810,7 +810,7 @@ func MergePullRequest(ctx *context.APIContext) { } } - if _, err := pull_service.IsSignedIfRequired(pr, ctx.User); err != nil { + if _, err := pull_service.IsSignedIfRequired(ctx, pr, ctx.User); err != nil { if !asymkey_service.IsErrWontSign(err) { ctx.Error(http.StatusInternalServerError, "IsSignedIfRequired", err) return @@ -838,7 +838,7 @@ func MergePullRequest(ctx *context.APIContext) { message += "\n\n" + form.MergeMessageField } - if err := pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), form.HeadCommitID, message); err != nil { + if err := pull_service.Merge(ctx, pr, ctx.User, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), form.HeadCommitID, message); err != nil { if models.IsErrInvalidMergeStyle(err) { ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", repo_model.MergeStyle(form.Do))) return @@ -888,7 +888,7 @@ func MergePullRequest(ctx *context.APIContext) { if ctx.Repo != nil && ctx.Repo.Repository != nil && ctx.Repo.Repository.ID == pr.HeadRepoID && ctx.Repo.GitRepo != nil { headRepo = ctx.Repo.GitRepo } else { - headRepo, err = git.OpenRepository(pr.HeadRepo.RepoPath()) + headRepo, err = git.OpenRepositoryCtx(ctx, pr.HeadRepo.RepoPath()) if err != nil { ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err) return @@ -982,7 +982,7 @@ func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) headRepo = ctx.Repo.Repository headGitRepo = ctx.Repo.GitRepo } else { - headGitRepo, err = git.OpenRepository(repo_model.RepoPath(headUser.Name, headRepo.Name)) + headGitRepo, err = git.OpenRepositoryCtx(ctx, repo_model.RepoPath(headUser.Name, headRepo.Name)) if err != nil { ctx.Error(http.StatusInternalServerError, "OpenRepository", err) return nil, nil, nil, nil, "", "" @@ -1135,7 +1135,7 @@ func UpdatePullRequest(ctx *context.APIContext) { // default merge commit message message := fmt.Sprintf("Merge branch '%s' into %s", pr.BaseBranch, pr.HeadBranch) - if err = pull_service.Update(pr, ctx.User, message, rebase); err != nil { + if err = pull_service.Update(ctx, pr, ctx.User, message, rebase); err != nil { if models.IsErrMergeConflicts(err) { ctx.Error(http.StatusConflict, "Update", "merge failed because of conflict") return @@ -1204,12 +1204,13 @@ func GetPullRequestCommits(ctx *context.APIContext) { } var prInfo *git.CompareInfo - baseGitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath()) + baseGitRepo, closer, err := git.RepositoryFromContextOrOpen(ctx, pr.BaseRepo.RepoPath()) if err != nil { ctx.ServerError("OpenRepository", err) return } - defer baseGitRepo.Close() + defer closer.Close() + if pr.HasMerged { prInfo, err = baseGitRepo.GetCompareInfo(pr.BaseRepo.RepoPath(), pr.MergeBase, pr.GetGitRefName(), false, false) } else { @@ -1236,7 +1237,7 @@ func GetPullRequestCommits(ctx *context.APIContext) { apiCommits := make([]*api.Commit, 0, end-start) for i := start; i < end; i++ { - apiCommit, err := convert.ToCommit(ctx.Repo.Repository, commits[i], userCache) + apiCommit, err := convert.ToCommit(ctx.Repo.Repository, baseGitRepo, commits[i], userCache) if err != nil { ctx.ServerError("toCommit", err) return diff --git a/routers/api/v1/repo/pull_review.go b/routers/api/v1/repo/pull_review.go index ec5f045647..9eb63bafad 100644 --- a/routers/api/v1/repo/pull_review.go +++ b/routers/api/v1/repo/pull_review.go @@ -97,7 +97,7 @@ func ListPullReviews(ctx *context.APIContext) { return } - apiReviews, err := convert.ToPullReviewList(allReviews, ctx.User) + apiReviews, err := convert.ToPullReviewList(ctx, allReviews, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "convertToPullReviewList", err) return @@ -148,7 +148,7 @@ func GetPullReview(ctx *context.APIContext) { return } - apiReview, err := convert.ToPullReview(review, ctx.User) + apiReview, err := convert.ToPullReview(ctx, review, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "convertToPullReview", err) return @@ -198,7 +198,7 @@ func GetPullReviewComments(ctx *context.APIContext) { return } - apiComments, err := convert.ToPullReviewCommentList(review, ctx.User) + apiComments, err := convert.ToPullReviewCommentList(ctx, review, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "convertToPullReviewCommentList", err) return @@ -328,12 +328,13 @@ func CreatePullReview(ctx *context.APIContext) { // if CommitID is empty, set it as lastCommitID if opts.CommitID == "" { - gitRepo, err := git.OpenRepository(pr.Issue.Repo.RepoPath()) + + gitRepo, closer, err := git.RepositoryFromContextOrOpen(ctx, pr.Issue.Repo.RepoPath()) if err != nil { ctx.Error(http.StatusInternalServerError, "git.OpenRepository", err) return } - defer gitRepo.Close() + defer closer.Close() headCommitID, err := gitRepo.GetRefCommitID(pr.GetGitRefName()) if err != nil { @@ -351,7 +352,7 @@ func CreatePullReview(ctx *context.APIContext) { line = c.OldLineNum * -1 } - if _, err := pull_service.CreateCodeComment( + if _, err := pull_service.CreateCodeComment(ctx, ctx.User, ctx.Repo.GitRepo, pr.Issue, @@ -368,14 +369,14 @@ func CreatePullReview(ctx *context.APIContext) { } // create review and associate all pending review comments - review, _, err := pull_service.SubmitReview(ctx.User, ctx.Repo.GitRepo, pr.Issue, reviewType, opts.Body, opts.CommitID, nil) + review, _, err := pull_service.SubmitReview(ctx, ctx.User, ctx.Repo.GitRepo, pr.Issue, reviewType, opts.Body, opts.CommitID, nil) if err != nil { ctx.Error(http.StatusInternalServerError, "SubmitReview", err) return } // convert response - apiReview, err := convert.ToPullReview(review, ctx.User) + apiReview, err := convert.ToPullReview(ctx, review, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "convertToPullReview", err) return @@ -456,14 +457,14 @@ func SubmitPullReview(ctx *context.APIContext) { } // create review and associate all pending review comments - review, _, err = pull_service.SubmitReview(ctx.User, ctx.Repo.GitRepo, pr.Issue, reviewType, opts.Body, headCommitID, nil) + review, _, err = pull_service.SubmitReview(ctx, ctx.User, ctx.Repo.GitRepo, pr.Issue, reviewType, opts.Body, headCommitID, nil) if err != nil { ctx.Error(http.StatusInternalServerError, "SubmitReview", err) return } // convert response - apiReview, err := convert.ToPullReview(review, ctx.User) + apiReview, err := convert.ToPullReview(ctx, review, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "convertToPullReview", err) return @@ -555,7 +556,7 @@ func prepareSingleReview(ctx *context.APIContext) (*models.Review, *models.PullR return nil, nil, true } - if err := review.LoadAttributes(); err != nil && !user_model.IsErrUserNotExist(err) { + if err := review.LoadAttributes(ctx); err != nil && !user_model.IsErrUserNotExist(err) { ctx.Error(http.StatusInternalServerError, "ReviewLoadAttributes", err) return nil, nil, true } @@ -765,7 +766,7 @@ func apiReviewRequest(ctx *context.APIContext, opts api.PullReviewRequestOptions } if isAdd { - apiReviews, err := convert.ToPullReviewList(reviews, ctx.User) + apiReviews, err := convert.ToPullReviewList(ctx, reviews, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "convertToPullReviewList", err) return @@ -883,7 +884,7 @@ func dismissReview(ctx *context.APIContext, msg string, isDismiss bool) { return } - _, err := pull_service.DismissReview(review.ID, msg, ctx.User, isDismiss) + _, err := pull_service.DismissReview(ctx, review.ID, msg, ctx.User, isDismiss) if err != nil { ctx.Error(http.StatusInternalServerError, "pull_service.DismissReview", err) return @@ -895,7 +896,7 @@ func dismissReview(ctx *context.APIContext, msg string, isDismiss bool) { } // convert response - apiReview, err := convert.ToPullReview(review, ctx.User) + apiReview, err := convert.ToPullReview(ctx, review, ctx.User) if err != nil { ctx.Error(http.StatusInternalServerError, "convertToPullReview", err) return diff --git a/routers/api/v1/repo/release.go b/routers/api/v1/repo/release.go index 299eaddbc8..3cdd798151 100644 --- a/routers/api/v1/repo/release.go +++ b/routers/api/v1/repo/release.go @@ -356,7 +356,7 @@ func DeleteRelease(ctx *context.APIContext) { ctx.NotFound() return } - if err := releaseservice.DeleteReleaseByID(id, ctx.User, false); err != nil { + if err := releaseservice.DeleteReleaseByID(ctx, id, ctx.User, false); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteReleaseByID", err) return } diff --git a/routers/api/v1/repo/release_tags.go b/routers/api/v1/repo/release_tags.go index 4b853d44bb..d77bdf0331 100644 --- a/routers/api/v1/repo/release_tags.go +++ b/routers/api/v1/repo/release_tags.go @@ -110,7 +110,7 @@ func DeleteReleaseByTag(ctx *context.APIContext) { return } - if err = releaseservice.DeleteReleaseByID(release.ID, ctx.User, false); err != nil { + if err = releaseservice.DeleteReleaseByID(ctx, release.ID, ctx.User, false); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteReleaseByID", err) } diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index 340ba0f6d5..5f17dc9268 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -704,7 +704,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err if ctx.Repo.GitRepo == nil && !repo.IsEmpty { var err error - ctx.Repo.GitRepo, err = git.OpenRepository(ctx.Repo.Repository.RepoPath()) + ctx.Repo.GitRepo, err = git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.RepoPath()) if err != nil { ctx.Error(http.StatusInternalServerError, "Unable to OpenRepository", err) return err @@ -1023,7 +1023,7 @@ func Delete(ctx *context.APIContext) { ctx.Repo.GitRepo.Close() } - if err := repo_service.DeleteRepository(ctx.User, repo, true); err != nil { + if err := repo_service.DeleteRepository(ctx, ctx.User, repo, true); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteRepository", err) return } diff --git a/routers/api/v1/repo/status.go b/routers/api/v1/repo/status.go index 9d0fbbddad..72d790794e 100644 --- a/routers/api/v1/repo/status.go +++ b/routers/api/v1/repo/status.go @@ -62,7 +62,7 @@ func NewCommitStatus(ctx *context.APIContext) { Description: form.Description, Context: form.Context, } - if err := files_service.CreateCommitStatus(ctx.Repo.Repository, ctx.User, sha, status); err != nil { + if err := files_service.CreateCommitStatus(ctx, ctx.Repo.Repository, ctx.User, sha, status); err != nil { ctx.Error(http.StatusInternalServerError, "CreateCommitStatus", err) return } diff --git a/routers/api/v1/repo/tag.go b/routers/api/v1/repo/tag.go index 13a625bafb..a60f4f320f 100644 --- a/routers/api/v1/repo/tag.go +++ b/routers/api/v1/repo/tag.go @@ -191,7 +191,7 @@ func CreateTag(ctx *context.APIContext) { return } - if err := releaseservice.CreateNewTag(ctx.User, ctx.Repo.Repository, commit.ID.String(), form.TagName, form.Message); err != nil { + if err := releaseservice.CreateNewTag(ctx, ctx.User, ctx.Repo.Repository, commit.ID.String(), form.TagName, form.Message); err != nil { if models.IsErrTagAlreadyExists(err) { ctx.Error(http.StatusConflict, "tag exist", err) return @@ -255,7 +255,7 @@ func DeleteTag(ctx *context.APIContext) { return } - if err = releaseservice.DeleteReleaseByID(tag.ID, ctx.User, true); err != nil { + if err = releaseservice.DeleteReleaseByID(ctx, tag.ID, ctx.User, true); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteReleaseByID", err) } diff --git a/routers/api/v1/repo/tree.go b/routers/api/v1/repo/tree.go index 411d87d6c5..b8294ebe31 100644 --- a/routers/api/v1/repo/tree.go +++ b/routers/api/v1/repo/tree.go @@ -60,7 +60,7 @@ func GetTree(ctx *context.APIContext) { ctx.Error(http.StatusBadRequest, "", "sha not provided") return } - if tree, err := files_service.GetTreeBySHA(ctx.Repo.Repository, sha, ctx.FormInt("page"), ctx.FormInt("per_page"), ctx.FormBool("recursive")); err != nil { + if tree, err := files_service.GetTreeBySHA(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, sha, ctx.FormInt("page"), ctx.FormInt("per_page"), ctx.FormBool("recursive")); err != nil { ctx.Error(http.StatusBadRequest, "", err.Error()) } else { ctx.SetTotalCountHeader(int64(tree.TotalCount)) diff --git a/routers/api/v1/repo/wiki.go b/routers/api/v1/repo/wiki.go index bef32f367b..94f1dbe0ea 100644 --- a/routers/api/v1/repo/wiki.go +++ b/routers/api/v1/repo/wiki.go @@ -71,7 +71,7 @@ func NewWikiPage(ctx *context.APIContext) { } form.ContentBase64 = string(content) - if err := wiki_service.AddWikiPage(ctx.User, ctx.Repo.Repository, wikiName, form.ContentBase64, form.Message); err != nil { + if err := wiki_service.AddWikiPage(ctx, ctx.User, ctx.Repo.Repository, wikiName, form.ContentBase64, form.Message); err != nil { if models.IsErrWikiReservedName(err) { ctx.Error(http.StatusBadRequest, "IsErrWikiReservedName", err) } else if models.IsErrWikiAlreadyExist(err) { @@ -144,7 +144,7 @@ func EditWikiPage(ctx *context.APIContext) { } form.ContentBase64 = string(content) - if err := wiki_service.EditWikiPage(ctx.User, ctx.Repo.Repository, oldWikiName, newWikiName, form.ContentBase64, form.Message); err != nil { + if err := wiki_service.EditWikiPage(ctx, ctx.User, ctx.Repo.Repository, oldWikiName, newWikiName, form.ContentBase64, form.Message); err != nil { ctx.Error(http.StatusInternalServerError, "EditWikiPage", err) return } @@ -233,7 +233,7 @@ func DeleteWikiPage(ctx *context.APIContext) { wikiName := wiki_service.NormalizeWikiName(ctx.Params(":pageName")) - if err := wiki_service.DeleteWikiPage(ctx.User, ctx.Repo.Repository, wikiName); err != nil { + if err := wiki_service.DeleteWikiPage(ctx, ctx.User, ctx.Repo.Repository, wikiName); err != nil { if err.Error() == "file does not exist" { ctx.NotFound(err) return @@ -458,7 +458,7 @@ func findEntryForFile(commit *git.Commit, target string) (*git.TreeEntry, error) // findWikiRepoCommit opens the wiki repo and returns the latest commit, writing to context on error. // The caller is responsible for closing the returned repo again func findWikiRepoCommit(ctx *context.APIContext) (*git.Repository, *git.Commit) { - wikiRepo, err := git.OpenRepository(ctx.Repo.Repository.WikiPath()) + wikiRepo, err := git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.WikiPath()) if err != nil { if git.IsErrNotExist(err) || err.Error() == "no such file or directory" { diff --git a/routers/api/v1/utils/git.go b/routers/api/v1/utils/git.go index ac68c3625d..a941c1fc2c 100644 --- a/routers/api/v1/utils/git.go +++ b/routers/api/v1/utils/git.go @@ -36,7 +36,7 @@ func ResolveRefOrSha(ctx *context.APIContext, ref string) string { func GetGitRefs(ctx *context.APIContext, filter string) ([]*git.Reference, string, error) { if ctx.Repo.GitRepo == nil { var err error - ctx.Repo.GitRepo, err = git.OpenRepository(ctx.Repo.Repository.RepoPath()) + ctx.Repo.GitRepo, err = git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.RepoPath()) if err != nil { return nil, "OpenRepository", err } diff --git a/routers/private/default_branch.go b/routers/private/default_branch.go index 5fdd0df735..55ffef43f3 100644 --- a/routers/private/default_branch.go +++ b/routers/private/default_branch.go @@ -12,7 +12,6 @@ import ( repo_model "code.gitea.io/gitea/models/repo" gitea_context "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/private" ) @@ -34,38 +33,18 @@ func SetDefaultBranch(ctx *gitea_context.PrivateContext) { ownerName := ctx.Params(":owner") repoName := ctx.Params(":repo") branch := ctx.Params(":branch") - repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) - if err != nil { - log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err) - ctx.JSON(http.StatusInternalServerError, private.Response{ - Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err), - }) - return - } - if repo.OwnerName == "" { - repo.OwnerName = ownerName - } - repo.DefaultBranch = branch - gitRepo, err := git.OpenRepository(repo.RepoPath()) - if err != nil { - ctx.JSON(http.StatusInternalServerError, private.Response{ - Err: fmt.Sprintf("Failed to get git repository: %s/%s Error: %v", ownerName, repoName, err), - }) - return - } - if err := gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil { + ctx.Repo.Repository.DefaultBranch = branch + if err := ctx.Repo.GitRepo.SetDefaultBranch(ctx.Repo.Repository.DefaultBranch); err != nil { if !git.IsErrUnsupportedVersion(err) { - gitRepo.Close() ctx.JSON(http.StatusInternalServerError, private.Response{ Err: fmt.Sprintf("Unable to set default branch on repository: %s/%s Error: %v", ownerName, repoName, err), }) return } } - gitRepo.Close() - if err := repo_model.UpdateDefaultBranch(repo); err != nil { + if err := repo_model.UpdateDefaultBranch(ctx.Repo.Repository); err != nil { ctx.JSON(http.StatusInternalServerError, private.Response{ Err: fmt.Sprintf("Unable to set default branch on repository: %s/%s Error: %v", ownerName, repoName, err), }) diff --git a/routers/private/hook_pre_receive.go b/routers/private/hook_pre_receive.go index b8f61cbb11..649bfa5cf3 100644 --- a/routers/private/hook_pre_receive.go +++ b/routers/private/hook_pre_receive.go @@ -183,7 +183,7 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID, refFullN // 2. Disallow force pushes to protected branches if git.EmptySHA != oldCommitID { - output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), ctx.env) + output, err := git.NewCommandContext(ctx, "rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), ctx.env) if err != nil { log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err) ctx.JSON(http.StatusInternalServerError, private.Response{ @@ -228,7 +228,7 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID, refFullN globs := protectBranch.GetProtectedFilePatterns() if len(globs) > 0 { - _, err := pull_service.CheckFileProtection(oldCommitID, newCommitID, globs, 1, ctx.env, gitRepo) + _, err := pull_service.CheckFileProtection(gitRepo, oldCommitID, newCommitID, globs, 1, ctx.env) if err != nil { if !models.IsErrFilePathProtected(err) { log.Error("Unable to check file protection for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err) @@ -270,7 +270,7 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID, refFullN // Allow commits that only touch unprotected files globs := protectBranch.GetUnprotectedFilePatterns() if len(globs) > 0 { - unprotectedFilesOnly, err := pull_service.CheckUnprotectedFiles(oldCommitID, newCommitID, globs, ctx.env, gitRepo) + unprotectedFilesOnly, err := pull_service.CheckUnprotectedFiles(gitRepo, oldCommitID, newCommitID, globs, ctx.env) if err != nil { log.Error("Unable to check file protection for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err) ctx.JSON(http.StatusInternalServerError, private.Response{ @@ -337,7 +337,7 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID, refFullN } // Check all status checks and reviews are ok - if err := pull_service.CheckPRReadyToMerge(pr, true); err != nil { + if err := pull_service.CheckPRReadyToMerge(ctx, pr, true); err != nil { if models.IsErrNotAllowedToMerge(err) { log.Warn("Forbidden: User %d is not allowed push to protected branch %s in %-v and pr #%d is not ready to be merged: %s", ctx.opts.UserID, branchName, repo, pr.Index, err.Error()) ctx.JSON(http.StatusForbidden, private.Response{ diff --git a/routers/private/hook_verification.go b/routers/private/hook_verification.go index 1b44550cff..5940045dc6 100644 --- a/routers/private/hook_verification.go +++ b/routers/private/hook_verification.go @@ -44,7 +44,7 @@ func verifyCommits(oldCommitID, newCommitID string, repo *git.Repository, env [] }() // This is safe as force pushes are already forbidden - err = git.NewCommand("rev-list", oldCommitID+"..."+newCommitID). + err = git.NewCommandContext(repo.Ctx, "rev-list", oldCommitID+"..."+newCommitID). RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path, stdoutWriter, nil, nil, func(ctx context.Context, cancel context.CancelFunc) error { @@ -88,7 +88,7 @@ func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error { }() hash := git.MustIDFromString(sha) - return git.NewCommand("cat-file", "commit", sha). + return git.NewCommandContext(repo.Ctx, "cat-file", "commit", sha). RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path, stdoutWriter, nil, nil, func(ctx context.Context, cancel context.CancelFunc) error { diff --git a/routers/private/internal.go b/routers/private/internal.go index 183ab5e98a..4960f561c1 100644 --- a/routers/private/internal.go +++ b/routers/private/internal.go @@ -57,8 +57,8 @@ func Routes() *web.Route { r.Post("/ssh/{id}/update/{repoid}", UpdatePublicKeyInRepo) r.Post("/ssh/log", bind(private.SSHLogOption{}), SSHLog) r.Post("/hook/pre-receive/{owner}/{repo}", RepoAssignment, bind(private.HookOptions{}), HookPreReceive) - r.Post("/hook/post-receive/{owner}/{repo}", bind(private.HookOptions{}), HookPostReceive) - r.Post("/hook/proc-receive/{owner}/{repo}", RepoAssignment, bind(private.HookOptions{}), HookProcReceive) + r.Post("/hook/post-receive/{owner}/{repo}", context.OverrideContext, bind(private.HookOptions{}), HookPostReceive) + r.Post("/hook/proc-receive/{owner}/{repo}", context.OverrideContext, RepoAssignment, bind(private.HookOptions{}), HookProcReceive) r.Post("/hook/set-default-branch/{owner}/{repo}/{branch}", RepoAssignment, SetDefaultBranch) r.Get("/serv/none/{keyid}", ServNoCommand) r.Get("/serv/command/{keyid}/{owner}/{repo}", ServCommand) diff --git a/routers/private/internal_repo.go b/routers/private/internal_repo.go index 8d0fd72235..ade862c613 100644 --- a/routers/private/internal_repo.go +++ b/routers/private/internal_repo.go @@ -43,7 +43,7 @@ func RepoAssignment(ctx *gitea_context.PrivateContext) context.CancelFunc { return nil } - gitRepo, err := git.OpenRepository(repo.RepoPath()) + gitRepo, err := git.OpenRepositoryCtx(ctx, repo.RepoPath()) if err != nil { log.Error("Failed to open repository: %s/%s Error: %v", ownerName, repoName, err) ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ diff --git a/routers/private/serv.go b/routers/private/serv.go index 6bf0ceeca2..65989d868b 100644 --- a/routers/private/serv.go +++ b/routers/private/serv.go @@ -401,7 +401,7 @@ func ServCommand(ctx *context.PrivateContext) { } // Finally if we're trying to touch the wiki we should init it - if err = wiki_service.InitWiki(repo); err != nil { + if err = wiki_service.InitWiki(ctx, repo); err != nil { log.Error("Failed to initialize the wiki in %-v Error: %v", repo, err) ctx.JSON(http.StatusInternalServerError, private.ErrServCommand{ Results: results, diff --git a/routers/web/admin/repos.go b/routers/web/admin/repos.go index 7e3ec96fce..c4290fc22b 100644 --- a/routers/web/admin/repos.go +++ b/routers/web/admin/repos.go @@ -52,7 +52,7 @@ func DeleteRepo(ctx *context.Context) { ctx.Repo.GitRepo.Close() } - if err := repo_service.DeleteRepository(ctx.User, repo, true); err != nil { + if err := repo_service.DeleteRepository(ctx, ctx.User, repo, true); err != nil { ctx.ServerError("DeleteRepository", err) return } diff --git a/routers/web/feed/convert.go b/routers/web/feed/convert.go index 4743668621..4dbd9c9d0e 100644 --- a/routers/web/feed/convert.go +++ b/routers/web/feed/convert.go @@ -180,7 +180,7 @@ func feedActionsToFeedItems(ctx *context.Context, actions []*models.Action) (ite desc += fmt.Sprintf("<a href=\"%s\">%s</a>\n%s", html.EscapeString(fmt.Sprintf("%s/commit/%s", act.GetRepoLink(), commit.Sha1)), commit.Sha1, - templates.RenderCommitMessage(commit.Message, repoLink, nil), + templates.RenderCommitMessage(ctx, commit.Message, repoLink, nil), ) } diff --git a/routers/web/org/home.go b/routers/web/org/home.go index 3a42044281..43f6211af3 100644 --- a/routers/web/org/home.go +++ b/routers/web/org/home.go @@ -40,6 +40,7 @@ func Home(ctx *context.Context) { ctx.Data["Title"] = org.DisplayName() if len(org.Description) != 0 { desc, err := markdown.RenderString(&markup.RenderContext{ + Ctx: ctx, URLPrefix: ctx.Repo.RepoLink, Metas: map[string]string{"mode": "document"}, GitRepo: ctx.Repo.GitRepo, diff --git a/routers/web/repo/activity.go b/routers/web/repo/activity.go index ae37b51403..b2f25ebe72 100644 --- a/routers/web/repo/activity.go +++ b/routers/web/repo/activity.go @@ -52,7 +52,7 @@ func Activity(ctx *context.Context) { ctx.Data["PeriodText"] = ctx.Tr("repo.activity.period." + ctx.Data["Period"].(string)) var err error - if ctx.Data["Activity"], err = models.GetActivityStats(ctx.Repo.Repository, timeFrom, + if ctx.Data["Activity"], err = models.GetActivityStats(ctx, ctx.Repo.Repository, timeFrom, ctx.Repo.CanRead(unit.TypeReleases), ctx.Repo.CanRead(unit.TypeIssues), ctx.Repo.CanRead(unit.TypePullRequests), @@ -61,7 +61,7 @@ func Activity(ctx *context.Context) { return } - if ctx.PageData["repoActivityTopAuthors"], err = models.GetActivityStatsTopAuthors(ctx.Repo.Repository, timeFrom, 10); err != nil { + if ctx.PageData["repoActivityTopAuthors"], err = models.GetActivityStatsTopAuthors(ctx, ctx.Repo.Repository, timeFrom, 10); err != nil { ctx.ServerError("GetActivityStatsTopAuthors", err) return } @@ -94,7 +94,7 @@ func ActivityAuthors(ctx *context.Context) { } var err error - authors, err := models.GetActivityStatsTopAuthors(ctx.Repo.Repository, timeFrom, 10) + authors, err := models.GetActivityStatsTopAuthors(ctx, ctx.Repo.Repository, timeFrom, 10) if err != nil { ctx.ServerError("GetActivityStatsTopAuthors", err) return diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go index 29b8acd61c..ed1b2a9b1a 100644 --- a/routers/web/repo/branch.go +++ b/routers/web/repo/branch.go @@ -256,7 +256,7 @@ func loadOneBranch(ctx *context.Context, rawBranch, defaultBranch *git.Branch, p Behind: -1, } if defaultBranch != nil { - divergence, err = files_service.CountDivergingCommits(ctx.Repo.Repository, git.BranchPrefix+branchName) + divergence, err = files_service.CountDivergingCommits(ctx, ctx.Repo.Repository, git.BranchPrefix+branchName) if err != nil { log.Error("CountDivergingCommits", err) } @@ -289,7 +289,7 @@ func loadOneBranch(ctx *context.Context, rawBranch, defaultBranch *git.Branch, p if pr.HasMerged { baseGitRepo, ok := repoIDToGitRepo[pr.BaseRepoID] if !ok { - baseGitRepo, err = git.OpenRepository(pr.BaseRepo.RepoPath()) + baseGitRepo, err = git.OpenRepositoryCtx(ctx, pr.BaseRepo.RepoPath()) if err != nil { ctx.ServerError("OpenRepository", err) return nil @@ -363,11 +363,11 @@ func CreateBranch(ctx *context.Context) { if ctx.Repo.IsViewBranch { target = ctx.Repo.BranchName } - err = release_service.CreateNewTag(ctx.User, ctx.Repo.Repository, target, form.NewBranchName, "") + err = release_service.CreateNewTag(ctx, ctx.User, ctx.Repo.Repository, target, form.NewBranchName, "") } else if ctx.Repo.IsViewBranch { - err = repo_service.CreateNewBranch(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName) + err = repo_service.CreateNewBranch(ctx, ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName) } else { - err = repo_service.CreateNewBranchFromCommit(ctx.User, ctx.Repo.Repository, ctx.Repo.CommitID, form.NewBranchName) + err = repo_service.CreateNewBranchFromCommit(ctx, ctx.User, ctx.Repo.Repository, ctx.Repo.CommitID, form.NewBranchName) } if err != nil { if models.IsErrTagAlreadyExists(err) { diff --git a/routers/web/repo/commit.go b/routers/web/repo/commit.go index 304f76158c..12457e45ee 100644 --- a/routers/web/repo/commit.go +++ b/routers/web/repo/commit.go @@ -118,12 +118,12 @@ func Graph(ctx *context.Context) { return } - graphCommitsCount, err := ctx.Repo.GetCommitGraphsCount(hidePRRefs, realBranches, files) + graphCommitsCount, err := ctx.Repo.GetCommitGraphsCount(ctx, hidePRRefs, realBranches, files) if err != nil { log.Warn("GetCommitGraphsCount error for generate graph exclude prs: %t branches: %s in %-v, Will Ignore branches and try again. Underlying Error: %v", hidePRRefs, branches, ctx.Repo.Repository, err) realBranches = []string{} branches = []string{} - graphCommitsCount, err = ctx.Repo.GetCommitGraphsCount(hidePRRefs, realBranches, files) + graphCommitsCount, err = ctx.Repo.GetCommitGraphsCount(ctx, hidePRRefs, realBranches, files) if err != nil { ctx.ServerError("GetCommitGraphsCount", err) return @@ -265,7 +265,7 @@ func Diff(ctx *context.Context) { ) if ctx.Data["PageIsWiki"] != nil { - gitRepo, err = git.OpenRepository(ctx.Repo.Repository.WikiPath()) + gitRepo, err = git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.WikiPath()) if err != nil { ctx.ServerError("Repo.GitRepo.GetCommit", err) return @@ -388,6 +388,7 @@ func RawDiff(ctx *context.Context) { repoPath = repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) } if err := git.GetRawDiff( + ctx, repoPath, ctx.Params(":sha"), git.RawDiffType(ctx.Params(":ext")), diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index 3b07c35cb0..22e6be2021 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -6,6 +6,7 @@ package repo import ( "bufio" + gocontext "context" "encoding/csv" "errors" "fmt" @@ -136,14 +137,14 @@ func setCsvCompareContext(ctx *context.Context) { return csvReader, reader, err } - baseReader, baseBlobCloser, err := csvReaderFromCommit(&markup.RenderContext{Filename: diffFile.OldName}, baseCommit) + baseReader, baseBlobCloser, err := csvReaderFromCommit(&markup.RenderContext{Ctx: ctx, Filename: diffFile.OldName}, baseCommit) if baseBlobCloser != nil { defer baseBlobCloser.Close() } if err == errTooLarge { return CsvDiffResult{nil, err.Error()} } - headReader, headBlobCloser, err := csvReaderFromCommit(&markup.RenderContext{Filename: diffFile.Name}, headCommit) + headReader, headBlobCloser, err := csvReaderFromCommit(&markup.RenderContext{Ctx: ctx, Filename: diffFile.Name}, headCommit) if headBlobCloser != nil { defer headBlobCloser.Close() } @@ -382,7 +383,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { ci.HeadRepo = ctx.Repo.Repository ci.HeadGitRepo = ctx.Repo.GitRepo } else if has { - ci.HeadGitRepo, err = git.OpenRepository(ci.HeadRepo.RepoPath()) + ci.HeadGitRepo, err = git.OpenRepositoryCtx(ctx, ci.HeadRepo.RepoPath()) if err != nil { ctx.ServerError("OpenRepository", err) return nil @@ -442,7 +443,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { if canRead { ctx.Data["RootRepo"] = rootRepo if !fileOnly { - branches, tags, err := getBranchesAndTagsForRepo(rootRepo) + branches, tags, err := getBranchesAndTagsForRepo(ctx, rootRepo) if err != nil { ctx.ServerError("GetBranchesForRepo", err) return nil @@ -467,7 +468,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { if canRead { ctx.Data["OwnForkRepo"] = ownForkRepo if !fileOnly { - branches, tags, err := getBranchesAndTagsForRepo(ownForkRepo) + branches, tags, err := getBranchesAndTagsForRepo(ctx, ownForkRepo) if err != nil { ctx.ServerError("GetBranchesForRepo", err) return nil @@ -653,8 +654,8 @@ func PrepareCompareDiff( return false } -func getBranchesAndTagsForRepo(repo *repo_model.Repository) (branches, tags []string, err error) { - gitRepo, err := git.OpenRepository(repo.RepoPath()) +func getBranchesAndTagsForRepo(ctx gocontext.Context, repo *repo_model.Repository) (branches, tags []string, err error) { + gitRepo, err := git.OpenRepositoryCtx(ctx, repo.RepoPath()) if err != nil { return nil, nil, err } diff --git a/routers/web/repo/editor.go b/routers/web/repo/editor.go index 5904ba2f0b..c4fff1e421 100644 --- a/routers/web/repo/editor.go +++ b/routers/web/repo/editor.go @@ -26,7 +26,6 @@ import ( "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/routers/utils" "code.gitea.io/gitea/services/forms" - repo_service "code.gitea.io/gitea/services/repository" files_service "code.gitea.io/gitea/services/repository/files" ) @@ -41,7 +40,7 @@ const ( ) func renderCommitRights(ctx *context.Context) bool { - canCommitToBranch, err := ctx.Repo.CanCommitToBranch(ctx.User) + canCommitToBranch, err := ctx.Repo.CanCommitToBranch(ctx, ctx.User) if err != nil { log.Error("CanCommitToBranch: %v", err) } @@ -242,7 +241,7 @@ func editFilePost(ctx *context.Context, form forms.EditRepoFileForm, isNewFile b message += "\n\n" + form.CommitMessage } - if _, err := files_service.CreateOrUpdateRepoFile(ctx.Repo.Repository, ctx.User, &files_service.UpdateRepoFileOptions{ + if _, err := files_service.CreateOrUpdateRepoFile(ctx, ctx.Repo.Repository, ctx.User, &files_service.UpdateRepoFileOptions{ LastCommitID: form.LastCommit, OldBranch: ctx.Repo.BranchName, NewBranch: branchName, @@ -367,7 +366,7 @@ func DiffPreviewPost(ctx *context.Context) { return } - diff, err := files_service.GetDiffPreview(ctx.Repo.Repository, ctx.Repo.BranchName, treePath, form.Content) + diff, err := files_service.GetDiffPreview(ctx, ctx.Repo.Repository, ctx.Repo.BranchName, treePath, form.Content) if err != nil { ctx.Error(http.StatusInternalServerError, "GetDiffPreview: "+err.Error()) return @@ -448,7 +447,7 @@ func DeleteFilePost(ctx *context.Context) { message += "\n\n" + form.CommitMessage } - if _, err := files_service.DeleteRepoFile(ctx.Repo.Repository, ctx.User, &files_service.DeleteRepoFileOptions{ + if _, err := files_service.DeleteRepoFile(ctx, ctx.Repo.Repository, ctx.User, &files_service.DeleteRepoFileOptions{ LastCommitID: form.LastCommit, OldBranch: ctx.Repo.BranchName, NewBranch: branchName, @@ -610,7 +609,7 @@ func UploadFilePost(ctx *context.Context) { } if oldBranchName != branchName { - if _, err := repo_service.GetBranch(ctx.Repo.Repository, branchName); err == nil { + if _, err := ctx.Repo.GitRepo.GetBranch(branchName); err == nil { ctx.Data["Err_NewBranchName"] = true ctx.RenderWithErr(ctx.Tr("repo.editor.branch_already_exists", branchName), tplUploadFile, &form) return @@ -654,7 +653,7 @@ func UploadFilePost(ctx *context.Context) { message += "\n\n" + form.CommitMessage } - if err := files_service.UploadRepoFiles(ctx.Repo.Repository, ctx.User, &files_service.UploadRepoFileOptions{ + if err := files_service.UploadRepoFiles(ctx, ctx.Repo.Repository, ctx.User, &files_service.UploadRepoFileOptions{ LastCommitID: ctx.Repo.CommitID, OldBranch: oldBranchName, NewBranch: branchName, @@ -802,7 +801,7 @@ func GetUniquePatchBranchName(ctx *context.Context) string { prefix := ctx.User.LowerName + "-patch-" for i := 1; i <= 1000; i++ { branchName := fmt.Sprintf("%s%d", prefix, i) - if _, err := repo_service.GetBranch(ctx.Repo.Repository, branchName); err != nil { + if _, err := ctx.Repo.GitRepo.GetBranch(branchName); err != nil { if git.IsErrBranchNotExist(err) { return branchName } diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go index 6ebf6a789a..5e73843920 100644 --- a/routers/web/repo/http.go +++ b/routers/web/repo/http.go @@ -8,6 +8,7 @@ package repo import ( "bytes" "compress/gzip" + gocontext "context" "fmt" "net/http" "os" @@ -324,12 +325,12 @@ func dummyInfoRefs(ctx *context.Context) { } }() - if err := git.InitRepository(tmpDir, true); err != nil { + if err := git.InitRepository(ctx, tmpDir, true); err != nil { log.Error("Failed to init bare repo for git-receive-pack cache: %v", err) return } - refs, err := git.NewCommand("receive-pack", "--stateless-rpc", "--advertise-refs", ".").RunInDirBytes(tmpDir) + refs, err := git.NewCommandContext(ctx, "receive-pack", "--stateless-rpc", "--advertise-refs", ".").RunInDirBytes(tmpDir) if err != nil { log.Error(fmt.Sprintf("%v - %s", err, string(refs))) } @@ -412,17 +413,17 @@ func (h *serviceHandler) sendFile(contentType, file string) { // one or more key=value pairs separated by colons var safeGitProtocolHeader = regexp.MustCompile(`^[0-9a-zA-Z]+=[0-9a-zA-Z]+(:[0-9a-zA-Z]+=[0-9a-zA-Z]+)*$`) -func getGitConfig(option, dir string) string { - out, err := git.NewCommand("config", option).RunInDir(dir) +func getGitConfig(ctx gocontext.Context, option, dir string) string { + out, err := git.NewCommandContext(ctx, "config", option).RunInDir(dir) if err != nil { log.Error("%v - %s", err, out) } return out[0 : len(out)-1] } -func getConfigSetting(service, dir string) bool { +func getConfigSetting(ctx gocontext.Context, service, dir string) bool { service = strings.ReplaceAll(service, "-", "") - setting := getGitConfig("http."+service, dir) + setting := getGitConfig(ctx, "http."+service, dir) if service == "uploadpack" { return setting != "false" @@ -431,7 +432,7 @@ func getConfigSetting(service, dir string) bool { return setting == "true" } -func hasAccess(service string, h serviceHandler, checkContentType bool) bool { +func hasAccess(ctx gocontext.Context, service string, h serviceHandler, checkContentType bool) bool { if checkContentType { if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) { return false @@ -448,10 +449,10 @@ func hasAccess(service string, h serviceHandler, checkContentType bool) bool { return h.cfg.UploadPack } - return getConfigSetting(service, h.dir) + return getConfigSetting(ctx, service, h.dir) } -func serviceRPC(h serviceHandler, service string) { +func serviceRPC(ctx gocontext.Context, h serviceHandler, service string) { defer func() { if err := h.r.Body.Close(); err != nil { log.Error("serviceRPC: Close: %v", err) @@ -459,7 +460,7 @@ func serviceRPC(h serviceHandler, service string) { }() - if !hasAccess(service, h, true) { + if !hasAccess(ctx, service, h, true) { h.w.WriteHeader(http.StatusUnauthorized) return } @@ -486,7 +487,6 @@ func serviceRPC(h serviceHandler, service string) { h.environ = append(h.environ, "GIT_PROTOCOL="+protocol) } - // ctx, cancel := gocontext.WithCancel(git.DefaultContext) ctx, _, finished := process.GetManager().AddContext(h.r.Context(), fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", h.dir)) defer finished() @@ -508,7 +508,7 @@ func serviceRPC(h serviceHandler, service string) { func ServiceUploadPack(ctx *context.Context) { h := httpBase(ctx) if h != nil { - serviceRPC(*h, "upload-pack") + serviceRPC(ctx, *h, "upload-pack") } } @@ -516,7 +516,7 @@ func ServiceUploadPack(ctx *context.Context) { func ServiceReceivePack(ctx *context.Context) { h := httpBase(ctx) if h != nil { - serviceRPC(*h, "receive-pack") + serviceRPC(ctx, *h, "receive-pack") } } @@ -528,8 +528,8 @@ func getServiceType(r *http.Request) string { return strings.Replace(serviceType, "git-", "", 1) } -func updateServerInfo(dir string) []byte { - out, err := git.NewCommand("update-server-info").RunInDirBytes(dir) +func updateServerInfo(ctx gocontext.Context, dir string) []byte { + out, err := git.NewCommandContext(ctx, "update-server-info").RunInDirBytes(dir) if err != nil { log.Error(fmt.Sprintf("%v - %s", err, string(out))) } @@ -551,7 +551,7 @@ func GetInfoRefs(ctx *context.Context) { return } h.setHeaderNoCache() - if hasAccess(getServiceType(h.r), *h, false) { + if hasAccess(ctx, getServiceType(h.r), *h, false) { service := getServiceType(h.r) if protocol := h.r.Header.Get("Git-Protocol"); protocol != "" && safeGitProtocolHeader.MatchString(protocol) { @@ -559,7 +559,7 @@ func GetInfoRefs(ctx *context.Context) { } h.environ = append(os.Environ(), h.environ...) - refs, err := git.NewCommand(service, "--stateless-rpc", "--advertise-refs", ".").RunInDirTimeoutEnv(h.environ, -1, h.dir) + refs, err := git.NewCommandContext(ctx, service, "--stateless-rpc", "--advertise-refs", ".").RunInDirTimeoutEnv(h.environ, -1, h.dir) if err != nil { log.Error(fmt.Sprintf("%v - %s", err, string(refs))) } @@ -570,7 +570,7 @@ func GetInfoRefs(ctx *context.Context) { _, _ = h.w.Write([]byte("0000")) _, _ = h.w.Write(refs) } else { - updateServerInfo(h.dir) + updateServerInfo(ctx, h.dir) h.sendFile("text/plain; charset=utf-8", "info/refs") } } diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 9dee477537..ba871127f7 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -263,7 +263,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti } } - commitStatus, err := pull_service.GetIssuesLastCommitStatus(issues) + commitStatus, err := pull_service.GetIssuesLastCommitStatus(ctx, issues) if err != nil { ctx.ServerError("GetIssuesLastCommitStatus", err) return @@ -1434,14 +1434,14 @@ func ViewIssue(ctx *context.Context) { if comment.Review == nil { continue } - if err = comment.Review.LoadAttributes(); err != nil { + if err = comment.Review.LoadAttributes(ctx); err != nil { if !user_model.IsErrUserNotExist(err) { ctx.ServerError("Review.LoadAttributes", err) return } comment.Review.Reviewer = user_model.NewGhostUser() } - if err = comment.Review.LoadCodeComments(); err != nil { + if err = comment.Review.LoadCodeComments(ctx); err != nil { ctx.ServerError("Review.LoadCodeComments", err) return } @@ -1471,7 +1471,7 @@ func ViewIssue(ctx *context.Context) { } } else if comment.Type == models.CommentTypePullPush { participants = addParticipant(comment.Poster, participants) - if err = comment.LoadPushCommits(); err != nil { + if err = comment.LoadPushCommits(ctx); err != nil { ctx.ServerError("LoadPushCommits", err) return } @@ -1583,7 +1583,7 @@ func ViewIssue(ctx *context.Context) { } ctx.Data["WillSign"] = false if ctx.User != nil { - sign, key, _, err := asymkey_service.SignMerge(pull, ctx.User, pull.BaseRepo.RepoPath(), pull.BaseBranch, pull.GetGitRefName()) + sign, key, _, err := asymkey_service.SignMerge(ctx, pull, ctx.User, pull.BaseRepo.RepoPath(), pull.BaseBranch, pull.GetGitRefName()) ctx.Data["WillSign"] = sign ctx.Data["SigningKey"] = key if err != nil { diff --git a/routers/web/repo/lfs.go b/routers/web/repo/lfs.go index 8943641381..6b5e1dd624 100644 --- a/routers/web/repo/lfs.go +++ b/routers/web/repo/lfs.go @@ -115,7 +115,7 @@ func LFSLocks(ctx *context.Context) { } }() - if err := git.Clone(ctx.Repo.Repository.RepoPath(), tmpBasePath, git.CloneRepoOptions{ + if err := git.Clone(ctx, ctx.Repo.Repository.RepoPath(), tmpBasePath, git.CloneRepoOptions{ Bare: true, Shared: true, }); err != nil { @@ -124,7 +124,7 @@ func LFSLocks(ctx *context.Context) { return } - gitRepo, err := git.OpenRepository(tmpBasePath) + gitRepo, err := git.OpenRepositoryCtx(ctx, tmpBasePath) if err != nil { log.Error("Unable to open temporary repository: %s (%v)", tmpBasePath, err) ctx.ServerError("LFSLocks", fmt.Errorf("Failed to open new temporary repository in: %s %v", tmpBasePath, err)) diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index 6e68fd0c69..517156863e 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -413,12 +413,17 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare } ctx.Data["EnableStatusCheck"] = pull.ProtectedBranch != nil && pull.ProtectedBranch.EnableStatusCheck - baseGitRepo, err := git.OpenRepository(pull.BaseRepo.RepoPath()) - if err != nil { - ctx.ServerError("OpenRepository", err) - return nil + var baseGitRepo *git.Repository + if pull.BaseRepoID == ctx.Repo.Repository.ID && ctx.Repo.GitRepo != nil { + baseGitRepo = ctx.Repo.GitRepo + } else { + baseGitRepo, err := git.OpenRepositoryCtx(ctx, pull.BaseRepo.RepoPath()) + if err != nil { + ctx.ServerError("OpenRepository", err) + return nil + } + defer baseGitRepo.Close() } - defer baseGitRepo.Close() if !baseGitRepo.IsBranchExist(pull.BaseBranch) { ctx.Data["IsPullRequestBroken"] = true @@ -464,7 +469,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare var headBranchSha string // HeadRepo may be missing if pull.HeadRepo != nil { - headGitRepo, err := git.OpenRepository(pull.HeadRepo.RepoPath()) + headGitRepo, err := git.OpenRepositoryCtx(ctx, pull.HeadRepo.RepoPath()) if err != nil { ctx.ServerError("OpenRepository", err) return nil @@ -491,12 +496,13 @@ func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.Compare } if headBranchExist { + var err error ctx.Data["UpdateAllowed"], ctx.Data["UpdateByRebaseAllowed"], err = pull_service.IsUserAllowedToUpdate(pull, ctx.User) if err != nil { ctx.ServerError("IsUserAllowedToUpdate", err) return nil } - ctx.Data["GetCommitMessages"] = pull_service.GetSquashMergeCommitMessages(pull) + ctx.Data["GetCommitMessages"] = pull_service.GetSquashMergeCommitMessages(ctx, pull) } sha, err := baseGitRepo.GetRefCommitID(pull.GetGitRefName()) @@ -695,7 +701,7 @@ func ViewPullFiles(ctx *context.Context) { return } - if err = diff.LoadComments(issue, ctx.User); err != nil { + if err = diff.LoadComments(ctx, issue, ctx.User); err != nil { ctx.ServerError("LoadComments", err) return } @@ -804,7 +810,7 @@ func UpdatePullRequest(ctx *context.Context) { // default merge commit message message := fmt.Sprintf("Merge branch '%s' into %s", issue.PullRequest.BaseBranch, issue.PullRequest.HeadBranch) - if err = pull_service.Update(issue.PullRequest, ctx.User, message, rebase); err != nil { + if err = pull_service.Update(ctx, issue.PullRequest, ctx.User, message, rebase); err != nil { if models.IsErrMergeConflicts(err) { conflictError := err.(models.ErrMergeConflicts) flashError, err := ctx.RenderToString(tplAlertDetails, map[string]interface{}{ @@ -916,7 +922,7 @@ func MergePullRequest(ctx *context.Context) { return } - if err := pull_service.CheckPRReadyToMerge(pr, false); err != nil { + if err := pull_service.CheckPRReadyToMerge(ctx, pr, false); err != nil { if !models.IsErrNotAllowedToMerge(err) { ctx.ServerError("Merge PR status", err) return @@ -969,7 +975,7 @@ func MergePullRequest(ctx *context.Context) { return } - if err = pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), form.HeadCommitID, message); err != nil { + if err = pull_service.Merge(ctx, pr, ctx.User, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), form.HeadCommitID, message); err != nil { if models.IsErrInvalidMergeStyle(err) { ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option")) ctx.Redirect(issue.Link()) @@ -1065,7 +1071,7 @@ func MergePullRequest(ctx *context.Context) { if ctx.Repo != nil && ctx.Repo.Repository != nil && pr.HeadRepoID == ctx.Repo.Repository.ID && ctx.Repo.GitRepo != nil { headRepo = ctx.Repo.GitRepo } else { - headRepo, err = git.OpenRepository(pr.HeadRepo.RepoPath()) + headRepo, err = git.OpenRepositoryCtx(ctx, pr.HeadRepo.RepoPath()) if err != nil { ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err) return @@ -1184,7 +1190,7 @@ func CompareAndPullRequestPost(ctx *context.Context) { // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt // instead of 500. - if err := pull_service.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, assigneeIDs); err != nil { + if err := pull_service.NewPullRequest(ctx, repo, pullIssue, labelIDs, attachments, pullRequest, assigneeIDs); err != nil { if models.IsErrUserDoesNotHaveAccessToRepo(err) { ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err.Error()) return @@ -1276,7 +1282,7 @@ func CleanUpPullRequest(ctx *context.Context) { gitBaseRepo = ctx.Repo.GitRepo } else { // If not just open it - gitBaseRepo, err = git.OpenRepository(pr.BaseRepo.RepoPath()) + gitBaseRepo, err = git.OpenRepositoryCtx(ctx, pr.BaseRepo.RepoPath()) if err != nil { ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err) return @@ -1291,7 +1297,7 @@ func CleanUpPullRequest(ctx *context.Context) { gitRepo = ctx.Repo.GitRepo } else if pr.BaseRepoID != pr.HeadRepoID { // Otherwise just load it up - gitRepo, err = git.OpenRepository(pr.HeadRepo.RepoPath()) + gitRepo, err = git.OpenRepositoryCtx(ctx, pr.HeadRepo.RepoPath()) if err != nil { ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err) return @@ -1375,7 +1381,7 @@ func DownloadPullDiffOrPatch(ctx *context.Context, patch bool) { binary := ctx.FormBool("binary") - if err := pull_service.DownloadDiffOrPatch(pr, ctx, patch, binary); err != nil { + if err := pull_service.DownloadDiffOrPatch(ctx, pr, ctx, patch, binary); err != nil { ctx.ServerError("DownloadDiffOrPatch", err) return } @@ -1404,7 +1410,7 @@ func UpdatePullRequestTarget(ctx *context.Context) { return } - if err := pull_service.ChangeTargetBranch(pr, ctx.User, targetBranch); err != nil { + if err := pull_service.ChangeTargetBranch(ctx, pr, ctx.User, targetBranch); err != nil { if models.IsErrPullRequestAlreadyExists(err) { err := err.(models.ErrPullRequestAlreadyExists) diff --git a/routers/web/repo/pull_review.go b/routers/web/repo/pull_review.go index 257aa737f6..c92f08a88a 100644 --- a/routers/web/repo/pull_review.go +++ b/routers/web/repo/pull_review.go @@ -68,7 +68,7 @@ func CreateCodeComment(ctx *context.Context) { signedLine *= -1 } - comment, err := pull_service.CreateCodeComment( + comment, err := pull_service.CreateCodeComment(ctx, ctx.User, ctx.Repo.GitRepo, issue, @@ -152,7 +152,7 @@ func UpdateResolveConversation(ctx *context.Context) { } func renderConversation(ctx *context.Context, comment *models.Comment) { - comments, err := models.FetchCodeCommentsByLine(comment.Issue, ctx.User, comment.TreePath, comment.Line) + comments, err := models.FetchCodeCommentsByLine(ctx, comment.Issue, ctx.User, comment.TreePath, comment.Line) if err != nil { ctx.ServerError("FetchCodeCommentsByLine", err) return @@ -217,7 +217,7 @@ func SubmitReview(ctx *context.Context) { attachments = form.Files } - _, comm, err := pull_service.SubmitReview(ctx.User, ctx.Repo.GitRepo, issue, reviewType, form.Content, form.CommitID, attachments) + _, comm, err := pull_service.SubmitReview(ctx, ctx.User, ctx.Repo.GitRepo, issue, reviewType, form.Content, form.CommitID, attachments) if err != nil { if models.IsContentEmptyErr(err) { ctx.Flash.Error(ctx.Tr("repo.issues.review.content.empty")) @@ -234,7 +234,7 @@ func SubmitReview(ctx *context.Context) { // DismissReview dismissing stale review by repo admin func DismissReview(ctx *context.Context) { form := web.GetForm(ctx).(*forms.DismissReviewForm) - comm, err := pull_service.DismissReview(form.ReviewID, form.Message, ctx.User, true) + comm, err := pull_service.DismissReview(ctx, form.ReviewID, form.Message, ctx.User, true) if err != nil { ctx.ServerError("pull_service.DismissReview", err) return diff --git a/routers/web/repo/release.go b/routers/web/repo/release.go index f2ab8b85f2..13623e15ef 100644 --- a/routers/web/repo/release.go +++ b/routers/web/repo/release.go @@ -325,7 +325,7 @@ func NewReleasePost(ctx *context.Context) { } if len(form.TagOnly) > 0 { - if err = releaseservice.CreateNewTag(ctx.User, ctx.Repo.Repository, form.Target, form.TagName, msg); err != nil { + if err = releaseservice.CreateNewTag(ctx, ctx.User, ctx.Repo.Repository, form.Target, form.TagName, msg); err != nil { if models.IsErrTagAlreadyExists(err) { e := err.(models.ErrTagAlreadyExists) ctx.Flash.Error(ctx.Tr("repo.branch.tag_collision", e.TagName)) @@ -516,7 +516,7 @@ func DeleteTag(ctx *context.Context) { } func deleteReleaseOrTag(ctx *context.Context, isDelTag bool) { - if err := releaseservice.DeleteReleaseByID(ctx.FormInt64("id"), ctx.User, isDelTag); err != nil { + if err := releaseservice.DeleteReleaseByID(ctx, ctx.FormInt64("id"), ctx.User, isDelTag); err != nil { ctx.Flash.Error("DeleteReleaseByID: " + err.Error()) } else { if isDelTag { diff --git a/routers/web/repo/setting.go b/routers/web/repo/setting.go index b7269b6718..d1c03b59a6 100644 --- a/routers/web/repo/setting.go +++ b/routers/web/repo/setting.go @@ -66,7 +66,7 @@ func Settings(ctx *context.Context) { ctx.Data["DisableNewPushMirrors"] = setting.Mirror.DisableNewPush ctx.Data["DefaultMirrorInterval"] = setting.Mirror.DefaultInterval - signing, _ := asymkey_service.SigningKey(ctx.Repo.Repository.RepoPath()) + signing, _ := asymkey_service.SigningKey(ctx, ctx.Repo.Repository.RepoPath()) ctx.Data["SigningKeyAvailable"] = len(signing) > 0 ctx.Data["SigningSettings"] = setting.Repository.Signing ctx.Data["CodeIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled @@ -221,7 +221,7 @@ func SettingsPost(ctx *context.Context) { return } - if err := mirror_service.UpdateAddress(ctx.Repo.Mirror, address); err != nil { + if err := mirror_service.UpdateAddress(ctx, ctx.Repo.Mirror, address); err != nil { ctx.ServerError("UpdateAddress", err) return } @@ -297,7 +297,7 @@ func SettingsPost(ctx *context.Context) { return } - if err = mirror_service.RemovePushMirrorRemote(m); err != nil { + if err = mirror_service.RemovePushMirrorRemote(ctx, m); err != nil { ctx.ServerError("RemovePushMirrorRemote", err) return } @@ -354,7 +354,7 @@ func SettingsPost(ctx *context.Context) { return } - if err := mirror_service.AddPushMirrorRemote(m, address); err != nil { + if err := mirror_service.AddPushMirrorRemote(ctx, m, address); err != nil { if err := repo_model.DeletePushMirrorByID(m.ID); err != nil { log.Error("DeletePushMirrorByID %v", err) } @@ -578,7 +578,7 @@ func SettingsPost(ctx *context.Context) { } repo.IsMirror = false - if _, err := repository.CleanUpMigrateInfo(repo); err != nil { + if _, err := repository.CleanUpMigrateInfo(ctx, repo); err != nil { ctx.ServerError("CleanUpMigrateInfo", err) return } else if err = repo_model.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil { @@ -723,7 +723,7 @@ func SettingsPost(ctx *context.Context) { ctx.Repo.GitRepo.Close() } - if err := repo_service.DeleteRepository(ctx.User, ctx.Repo.Repository, true); err != nil { + if err := repo_service.DeleteRepository(ctx, ctx.User, ctx.Repo.Repository, true); err != nil { ctx.ServerError("DeleteRepository", err) return } @@ -742,7 +742,7 @@ func SettingsPost(ctx *context.Context) { return } - err := wiki_service.DeleteWiki(repo) + err := wiki_service.DeleteWiki(ctx, repo) if err != nil { log.Error("Delete Wiki: %v", err.Error()) } diff --git a/routers/web/repo/wiki.go b/routers/web/repo/wiki.go index d8666c7a29..e57aa5ec29 100644 --- a/routers/web/repo/wiki.go +++ b/routers/web/repo/wiki.go @@ -90,7 +90,7 @@ func findEntryForFile(commit *git.Commit, target string) (*git.TreeEntry, error) } func findWikiRepoCommit(ctx *context.Context) (*git.Repository, *git.Commit, error) { - wikiRepo, err := git.OpenRepository(ctx.Repo.Repository.WikiPath()) + wikiRepo, err := git.OpenRepositoryCtx(ctx, ctx.Repo.Repository.WikiPath()) if err != nil { ctx.ServerError("OpenRepository", err) return nil, nil, err @@ -220,6 +220,7 @@ func renderViewPage(ctx *context.Context) (*git.Repository, *git.TreeEntry) { } var rctx = &markup.RenderContext{ + Ctx: ctx, URLPrefix: ctx.Repo.RepoLink, Metas: ctx.Repo.Repository.ComposeDocumentMetas(), IsWiki: true, @@ -657,7 +658,7 @@ func NewWikiPost(ctx *context.Context) { form.Message = ctx.Tr("repo.editor.add", form.Title) } - if err := wiki_service.AddWikiPage(ctx.User, ctx.Repo.Repository, wikiName, form.Content, form.Message); err != nil { + if err := wiki_service.AddWikiPage(ctx, ctx.User, ctx.Repo.Repository, wikiName, form.Content, form.Message); err != nil { if models.IsErrWikiReservedName(err) { ctx.Data["Err_Title"] = true ctx.RenderWithErr(ctx.Tr("repo.wiki.reserved_page", wikiName), tplWikiNew, &form) @@ -709,7 +710,7 @@ func EditWikiPost(ctx *context.Context) { form.Message = ctx.Tr("repo.editor.update", form.Title) } - if err := wiki_service.EditWikiPage(ctx.User, ctx.Repo.Repository, oldWikiName, newWikiName, form.Content, form.Message); err != nil { + if err := wiki_service.EditWikiPage(ctx, ctx.User, ctx.Repo.Repository, oldWikiName, newWikiName, form.Content, form.Message); err != nil { ctx.ServerError("EditWikiPage", err) return } @@ -724,7 +725,7 @@ func DeleteWikiPagePost(ctx *context.Context) { wikiName = "Home" } - if err := wiki_service.DeleteWikiPage(ctx.User, ctx.Repo.Repository, wikiName); err != nil { + if err := wiki_service.DeleteWikiPage(ctx, ctx.User, ctx.Repo.Repository, wikiName); err != nil { ctx.ServerError("DeleteWikiPage", err) return } diff --git a/routers/web/user/home.go b/routers/web/user/home.go index 367cf5ca08..04459573af 100644 --- a/routers/web/user/home.go +++ b/routers/web/user/home.go @@ -540,7 +540,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) { } } - commitStatus, err := pull_service.GetIssuesLastCommitStatus(issues) + commitStatus, err := pull_service.GetIssuesLastCommitStatus(ctx, issues) if err != nil { ctx.ServerError("GetIssuesLastCommitStatus", err) return |