gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package repo
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. git_model "code.gitea.io/gitea/models/git"
  12. repo_model "code.gitea.io/gitea/models/repo"
  13. "code.gitea.io/gitea/models/unit"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/optional"
  17. repo_module "code.gitea.io/gitea/modules/repository"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/templates"
  20. "code.gitea.io/gitea/modules/util"
  21. "code.gitea.io/gitea/modules/web"
  22. "code.gitea.io/gitea/routers/utils"
  23. "code.gitea.io/gitea/services/context"
  24. "code.gitea.io/gitea/services/forms"
  25. pull_service "code.gitea.io/gitea/services/pull"
  26. release_service "code.gitea.io/gitea/services/release"
  27. repo_service "code.gitea.io/gitea/services/repository"
  28. )
  29. const (
  30. tplBranch templates.TplName = "repo/branch/list"
  31. )
  32. // Branches render repository branch page
  33. func Branches(ctx *context.Context) {
  34. ctx.Data["Title"] = "Branches"
  35. ctx.Data["AllowsPulls"] = ctx.Repo.Repository.AllowsPulls(ctx)
  36. ctx.Data["IsWriter"] = ctx.Repo.CanWrite(unit.TypeCode)
  37. ctx.Data["IsMirror"] = ctx.Repo.Repository.IsMirror
  38. ctx.Data["CanPull"] = ctx.Repo.CanWrite(unit.TypeCode) ||
  39. (ctx.IsSigned && repo_model.HasForkedRepo(ctx, ctx.Doer.ID, ctx.Repo.Repository.ID))
  40. ctx.Data["PageIsViewCode"] = true
  41. ctx.Data["PageIsBranches"] = true
  42. page := max(ctx.FormInt("page"), 1)
  43. pageSize := setting.Git.BranchesRangeSize
  44. kw := ctx.FormString("q")
  45. defaultBranch, branches, branchesCount, err := repo_service.LoadBranches(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, optional.None[bool](), kw, page, pageSize)
  46. if err != nil {
  47. ctx.ServerError("LoadBranches", err)
  48. return
  49. }
  50. commitIDs := []string{defaultBranch.DBBranch.CommitID}
  51. for _, branch := range branches {
  52. commitIDs = append(commitIDs, branch.DBBranch.CommitID)
  53. }
  54. commitStatuses, err := git_model.GetLatestCommitStatusForRepoCommitIDs(ctx, ctx.Repo.Repository.ID, commitIDs)
  55. if err != nil {
  56. ctx.ServerError("LoadBranches", err)
  57. return
  58. }
  59. if !ctx.Repo.CanRead(unit.TypeActions) {
  60. for key := range commitStatuses {
  61. git_model.CommitStatusesHideActionsURL(ctx, commitStatuses[key])
  62. }
  63. }
  64. commitStatus := make(map[string]*git_model.CommitStatus)
  65. for commitID, cs := range commitStatuses {
  66. commitStatus[commitID] = git_model.CalcCommitStatus(cs)
  67. }
  68. ctx.Data["Keyword"] = kw
  69. ctx.Data["Branches"] = branches
  70. ctx.Data["CommitStatus"] = commitStatus
  71. ctx.Data["CommitStatuses"] = commitStatuses
  72. ctx.Data["DefaultBranchBranch"] = defaultBranch
  73. pager := context.NewPagination(int(branchesCount), pageSize, page, 5)
  74. pager.AddParamFromRequest(ctx.Req)
  75. ctx.Data["Page"] = pager
  76. ctx.HTML(http.StatusOK, tplBranch)
  77. }
  78. // DeleteBranchPost responses for delete merged branch
  79. func DeleteBranchPost(ctx *context.Context) {
  80. defer jsonRedirectBranches(ctx)
  81. branchName := ctx.FormString("name")
  82. if err := repo_service.DeleteBranch(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, branchName, nil); err != nil {
  83. switch {
  84. case git.IsErrBranchNotExist(err):
  85. log.Debug("DeleteBranch: Can't delete non existing branch '%s'", branchName)
  86. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  87. case errors.Is(err, repo_service.ErrBranchIsDefault):
  88. log.Debug("DeleteBranch: Can't delete default branch '%s'", branchName)
  89. ctx.Flash.Error(ctx.Tr("repo.branch.default_deletion_failed", branchName))
  90. case errors.Is(err, git_model.ErrBranchIsProtected):
  91. log.Debug("DeleteBranch: Can't delete protected branch '%s'", branchName)
  92. ctx.Flash.Error(ctx.Tr("repo.branch.protected_deletion_failed", branchName))
  93. default:
  94. log.Error("DeleteBranch: %v", err)
  95. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  96. }
  97. return
  98. }
  99. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", branchName))
  100. }
  101. // RestoreBranchPost responses for delete merged branch
  102. func RestoreBranchPost(ctx *context.Context) {
  103. defer jsonRedirectBranches(ctx)
  104. branchID := ctx.FormInt64("branch_id")
  105. branchName := ctx.FormString("name")
  106. deletedBranch, err := git_model.GetDeletedBranchByID(ctx, ctx.Repo.Repository.ID, branchID)
  107. if err != nil {
  108. log.Error("GetDeletedBranchByID: %v", err)
  109. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", branchName))
  110. return
  111. } else if deletedBranch == nil {
  112. log.Debug("RestoreBranch: Can't restore branch[%d] '%s', as it does not exist", branchID, branchName)
  113. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", branchName))
  114. return
  115. }
  116. if err := git.Push(ctx, ctx.Repo.Repository.RepoPath(), git.PushOptions{
  117. Remote: ctx.Repo.Repository.RepoPath(),
  118. Branch: fmt.Sprintf("%s:%s%s", deletedBranch.CommitID, git.BranchPrefix, deletedBranch.Name),
  119. Env: repo_module.PushingEnvironment(ctx.Doer, ctx.Repo.Repository),
  120. }); err != nil {
  121. if strings.Contains(err.Error(), "already exists") {
  122. log.Debug("RestoreBranch: Can't restore branch '%s', since one with same name already exist", deletedBranch.Name)
  123. ctx.Flash.Error(ctx.Tr("repo.branch.already_exists", deletedBranch.Name))
  124. return
  125. }
  126. log.Error("RestoreBranch: CreateBranch: %v", err)
  127. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", deletedBranch.Name))
  128. return
  129. }
  130. objectFormat := git.ObjectFormatFromName(ctx.Repo.Repository.ObjectFormatName)
  131. // Don't return error below this
  132. if err := repo_service.PushUpdate(
  133. &repo_module.PushUpdateOptions{
  134. RefFullName: git.RefNameFromBranch(deletedBranch.Name),
  135. OldCommitID: objectFormat.EmptyObjectID().String(),
  136. NewCommitID: deletedBranch.CommitID,
  137. PusherID: ctx.Doer.ID,
  138. PusherName: ctx.Doer.Name,
  139. RepoUserName: ctx.Repo.Owner.Name,
  140. RepoName: ctx.Repo.Repository.Name,
  141. }); err != nil {
  142. log.Error("RestoreBranch: Update: %v", err)
  143. }
  144. ctx.Flash.Success(ctx.Tr("repo.branch.restore_success", deletedBranch.Name))
  145. }
  146. func jsonRedirectBranches(ctx *context.Context) {
  147. ctx.JSONRedirect(ctx.Repo.RepoLink + "/branches?page=" + url.QueryEscape(ctx.FormString("page")))
  148. }
  149. // CreateBranch creates new branch in repository
  150. func CreateBranch(ctx *context.Context) {
  151. form := web.GetForm(ctx).(*forms.NewBranchForm)
  152. if !ctx.Repo.CanCreateBranch() {
  153. ctx.NotFound(nil)
  154. return
  155. }
  156. if ctx.HasError() {
  157. ctx.Flash.Error(ctx.GetErrMsg())
  158. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL())
  159. return
  160. }
  161. var err error
  162. if form.CreateTag {
  163. target := ctx.Repo.CommitID
  164. if ctx.Repo.RefFullName.IsBranch() {
  165. target = ctx.Repo.BranchName
  166. }
  167. err = release_service.CreateNewTag(ctx, ctx.Doer, ctx.Repo.Repository, target, form.NewBranchName, "")
  168. } else if ctx.Repo.RefFullName.IsBranch() {
  169. err = repo_service.CreateNewBranch(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, ctx.Repo.BranchName, form.NewBranchName)
  170. } else {
  171. err = repo_service.CreateNewBranchFromCommit(ctx, ctx.Doer, ctx.Repo.Repository, ctx.Repo.GitRepo, ctx.Repo.CommitID, form.NewBranchName)
  172. }
  173. if err != nil {
  174. if release_service.IsErrProtectedTagName(err) {
  175. ctx.Flash.Error(ctx.Tr("repo.release.tag_name_protected"))
  176. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL())
  177. return
  178. }
  179. if release_service.IsErrTagAlreadyExists(err) {
  180. e := err.(release_service.ErrTagAlreadyExists)
  181. ctx.Flash.Error(ctx.Tr("repo.branch.tag_collision", e.TagName))
  182. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL())
  183. return
  184. }
  185. if git_model.IsErrBranchAlreadyExists(err) || git.IsErrPushOutOfDate(err) {
  186. ctx.Flash.Error(ctx.Tr("repo.branch.branch_already_exists", form.NewBranchName))
  187. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL())
  188. return
  189. }
  190. if git_model.IsErrBranchNameConflict(err) {
  191. e := err.(git_model.ErrBranchNameConflict)
  192. ctx.Flash.Error(ctx.Tr("repo.branch.branch_name_conflict", form.NewBranchName, e.BranchName))
  193. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL())
  194. return
  195. }
  196. if git.IsErrPushRejected(err) {
  197. e := err.(*git.ErrPushRejected)
  198. if len(e.Message) == 0 {
  199. ctx.Flash.Error(ctx.Tr("repo.editor.push_rejected_no_message"))
  200. } else {
  201. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  202. "Message": ctx.Tr("repo.editor.push_rejected"),
  203. "Summary": ctx.Tr("repo.editor.push_rejected_summary"),
  204. "Details": utils.SanitizeFlashErrorString(e.Message),
  205. })
  206. if err != nil {
  207. ctx.ServerError("UpdatePullRequest.HTMLString", err)
  208. return
  209. }
  210. ctx.Flash.Error(flashError)
  211. }
  212. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.RefTypeNameSubURL())
  213. return
  214. }
  215. ctx.ServerError("CreateNewBranch", err)
  216. return
  217. }
  218. if form.CreateTag {
  219. ctx.Flash.Success(ctx.Tr("repo.tag.create_success", form.NewBranchName))
  220. ctx.Redirect(ctx.Repo.RepoLink + "/src/tag/" + util.PathEscapeSegments(form.NewBranchName))
  221. return
  222. }
  223. ctx.Flash.Success(ctx.Tr("repo.branch.create_success", form.NewBranchName))
  224. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(form.NewBranchName) + "/" + util.PathEscapeSegments(form.CurrentPath))
  225. }
  226. func MergeUpstream(ctx *context.Context) {
  227. branchName := ctx.FormString("branch")
  228. _, err := repo_service.MergeUpstream(ctx, ctx.Doer, ctx.Repo.Repository, branchName, false)
  229. if err != nil {
  230. if errors.Is(err, util.ErrNotExist) {
  231. ctx.JSONErrorNotFound()
  232. return
  233. } else if pull_service.IsErrMergeConflicts(err) {
  234. ctx.JSONError(ctx.Tr("repo.pulls.merge_conflict"))
  235. return
  236. }
  237. ctx.ServerError("MergeUpstream", err)
  238. return
  239. }
  240. ctx.JSONRedirect("")
  241. }