You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

branch.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "fmt"
  8. "net/http"
  9. "strings"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/context"
  13. auth "code.gitea.io/gitea/modules/forms"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/repofiles"
  17. repo_module "code.gitea.io/gitea/modules/repository"
  18. "code.gitea.io/gitea/modules/util"
  19. "code.gitea.io/gitea/modules/web"
  20. "code.gitea.io/gitea/routers/utils"
  21. release_service "code.gitea.io/gitea/services/release"
  22. repo_service "code.gitea.io/gitea/services/repository"
  23. )
  24. const (
  25. tplBranch base.TplName = "repo/branch/list"
  26. )
  27. // Branch contains the branch information
  28. type Branch struct {
  29. Name string
  30. Commit *git.Commit
  31. IsProtected bool
  32. IsDeleted bool
  33. IsIncluded bool
  34. DeletedBranch *models.DeletedBranch
  35. CommitsAhead int
  36. CommitsBehind int
  37. LatestPullRequest *models.PullRequest
  38. MergeMovedOn bool
  39. }
  40. // Branches render repository branch page
  41. func Branches(ctx *context.Context) {
  42. ctx.Data["Title"] = "Branches"
  43. ctx.Data["IsRepoToolbarBranches"] = true
  44. ctx.Data["DefaultBranch"] = ctx.Repo.Repository.DefaultBranch
  45. ctx.Data["AllowsPulls"] = ctx.Repo.Repository.AllowsPulls()
  46. ctx.Data["IsWriter"] = ctx.Repo.CanWrite(models.UnitTypeCode)
  47. ctx.Data["IsMirror"] = ctx.Repo.Repository.IsMirror
  48. ctx.Data["CanPull"] = ctx.Repo.CanWrite(models.UnitTypeCode) || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID))
  49. ctx.Data["PageIsViewCode"] = true
  50. ctx.Data["PageIsBranches"] = true
  51. page := ctx.QueryInt("page")
  52. if page <= 1 {
  53. page = 1
  54. }
  55. limit := ctx.QueryInt("limit")
  56. if limit <= 0 || limit > git.BranchesRangeSize {
  57. limit = git.BranchesRangeSize
  58. }
  59. skip := (page - 1) * limit
  60. log.Debug("Branches: skip: %d limit: %d", skip, limit)
  61. branches, branchesCount := loadBranches(ctx, skip, limit)
  62. if ctx.Written() {
  63. return
  64. }
  65. ctx.Data["Branches"] = branches
  66. pager := context.NewPagination(int(branchesCount), git.BranchesRangeSize, page, 5)
  67. pager.SetDefaultParams(ctx)
  68. ctx.Data["Page"] = pager
  69. ctx.HTML(http.StatusOK, tplBranch)
  70. }
  71. // DeleteBranchPost responses for delete merged branch
  72. func DeleteBranchPost(ctx *context.Context) {
  73. defer redirect(ctx)
  74. branchName := ctx.Query("name")
  75. if branchName == ctx.Repo.Repository.DefaultBranch {
  76. log.Debug("DeleteBranch: Can't delete default branch '%s'", branchName)
  77. ctx.Flash.Error(ctx.Tr("repo.branch.default_deletion_failed", branchName))
  78. return
  79. }
  80. isProtected, err := ctx.Repo.Repository.IsProtectedBranch(branchName, ctx.User)
  81. if err != nil {
  82. log.Error("DeleteBranch: %v", err)
  83. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  84. return
  85. }
  86. if isProtected {
  87. log.Debug("DeleteBranch: Can't delete protected branch '%s'", branchName)
  88. ctx.Flash.Error(ctx.Tr("repo.branch.protected_deletion_failed", branchName))
  89. return
  90. }
  91. if !ctx.Repo.GitRepo.IsBranchExist(branchName) {
  92. log.Debug("DeleteBranch: Can't delete non existing branch '%s'", branchName)
  93. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  94. return
  95. }
  96. if err := deleteBranch(ctx, branchName); err != nil {
  97. log.Error("DeleteBranch: %v", err)
  98. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  99. return
  100. }
  101. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", branchName))
  102. }
  103. // RestoreBranchPost responses for delete merged branch
  104. func RestoreBranchPost(ctx *context.Context) {
  105. defer redirect(ctx)
  106. branchID := ctx.QueryInt64("branch_id")
  107. branchName := ctx.Query("name")
  108. deletedBranch, err := ctx.Repo.Repository.GetDeletedBranchByID(branchID)
  109. if err != nil {
  110. log.Error("GetDeletedBranchByID: %v", err)
  111. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", branchName))
  112. return
  113. }
  114. if err := git.Push(ctx.Repo.Repository.RepoPath(), git.PushOptions{
  115. Remote: ctx.Repo.Repository.RepoPath(),
  116. Branch: fmt.Sprintf("%s:%s%s", deletedBranch.Commit, git.BranchPrefix, deletedBranch.Name),
  117. Env: models.PushingEnvironment(ctx.User, ctx.Repo.Repository),
  118. }); err != nil {
  119. if strings.Contains(err.Error(), "already exists") {
  120. log.Debug("RestoreBranch: Can't restore branch '%s', since one with same name already exist", deletedBranch.Name)
  121. ctx.Flash.Error(ctx.Tr("repo.branch.already_exists", deletedBranch.Name))
  122. return
  123. }
  124. log.Error("RestoreBranch: CreateBranch: %v", err)
  125. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", deletedBranch.Name))
  126. return
  127. }
  128. // Don't return error below this
  129. if err := repo_service.PushUpdate(
  130. &repo_module.PushUpdateOptions{
  131. RefFullName: git.BranchPrefix + deletedBranch.Name,
  132. OldCommitID: git.EmptySHA,
  133. NewCommitID: deletedBranch.Commit,
  134. PusherID: ctx.User.ID,
  135. PusherName: ctx.User.Name,
  136. RepoUserName: ctx.Repo.Owner.Name,
  137. RepoName: ctx.Repo.Repository.Name,
  138. }); err != nil {
  139. log.Error("RestoreBranch: Update: %v", err)
  140. }
  141. ctx.Flash.Success(ctx.Tr("repo.branch.restore_success", deletedBranch.Name))
  142. }
  143. func redirect(ctx *context.Context) {
  144. ctx.JSON(http.StatusOK, map[string]interface{}{
  145. "redirect": ctx.Repo.RepoLink + "/branches",
  146. })
  147. }
  148. func deleteBranch(ctx *context.Context, branchName string) error {
  149. commit, err := ctx.Repo.GitRepo.GetBranchCommit(branchName)
  150. if err != nil {
  151. log.Error("GetBranchCommit: %v", err)
  152. return err
  153. }
  154. if err := ctx.Repo.GitRepo.DeleteBranch(branchName, git.DeleteBranchOptions{
  155. Force: true,
  156. }); err != nil {
  157. log.Error("DeleteBranch: %v", err)
  158. return err
  159. }
  160. // Don't return error below this
  161. if err := repo_service.PushUpdate(
  162. &repo_module.PushUpdateOptions{
  163. RefFullName: git.BranchPrefix + branchName,
  164. OldCommitID: commit.ID.String(),
  165. NewCommitID: git.EmptySHA,
  166. PusherID: ctx.User.ID,
  167. PusherName: ctx.User.Name,
  168. RepoUserName: ctx.Repo.Owner.Name,
  169. RepoName: ctx.Repo.Repository.Name,
  170. }); err != nil {
  171. log.Error("Update: %v", err)
  172. }
  173. if err := ctx.Repo.Repository.AddDeletedBranch(branchName, commit.ID.String(), ctx.User.ID); err != nil {
  174. log.Warn("AddDeletedBranch: %v", err)
  175. }
  176. return nil
  177. }
  178. // loadBranches loads branches from the repository limited by page & pageSize.
  179. // NOTE: May write to context on error.
  180. func loadBranches(ctx *context.Context, skip, limit int) ([]*Branch, int) {
  181. defaultBranch, err := repo_module.GetBranch(ctx.Repo.Repository, ctx.Repo.Repository.DefaultBranch)
  182. if err != nil {
  183. log.Error("loadBranches: get default branch: %v", err)
  184. ctx.ServerError("GetDefaultBranch", err)
  185. return nil, 0
  186. }
  187. rawBranches, totalNumOfBranches, err := repo_module.GetBranches(ctx.Repo.Repository, skip, limit)
  188. if err != nil {
  189. log.Error("GetBranches: %v", err)
  190. ctx.ServerError("GetBranches", err)
  191. return nil, 0
  192. }
  193. protectedBranches, err := ctx.Repo.Repository.GetProtectedBranches()
  194. if err != nil {
  195. ctx.ServerError("GetProtectedBranches", err)
  196. return nil, 0
  197. }
  198. repoIDToRepo := map[int64]*models.Repository{}
  199. repoIDToRepo[ctx.Repo.Repository.ID] = ctx.Repo.Repository
  200. repoIDToGitRepo := map[int64]*git.Repository{}
  201. repoIDToGitRepo[ctx.Repo.Repository.ID] = ctx.Repo.GitRepo
  202. var branches []*Branch
  203. for i := range rawBranches {
  204. if rawBranches[i].Name == defaultBranch.Name {
  205. // Skip default branch
  206. continue
  207. }
  208. var branch = loadOneBranch(ctx, rawBranches[i], protectedBranches, repoIDToRepo, repoIDToGitRepo)
  209. if branch == nil {
  210. return nil, 0
  211. }
  212. branches = append(branches, branch)
  213. }
  214. // Always add the default branch
  215. log.Debug("loadOneBranch: load default: '%s'", defaultBranch.Name)
  216. branches = append(branches, loadOneBranch(ctx, defaultBranch, protectedBranches, repoIDToRepo, repoIDToGitRepo))
  217. if ctx.Repo.CanWrite(models.UnitTypeCode) {
  218. deletedBranches, err := getDeletedBranches(ctx)
  219. if err != nil {
  220. ctx.ServerError("getDeletedBranches", err)
  221. return nil, 0
  222. }
  223. branches = append(branches, deletedBranches...)
  224. }
  225. return branches, totalNumOfBranches - 1
  226. }
  227. func loadOneBranch(ctx *context.Context, rawBranch *git.Branch, protectedBranches []*models.ProtectedBranch,
  228. repoIDToRepo map[int64]*models.Repository,
  229. repoIDToGitRepo map[int64]*git.Repository) *Branch {
  230. log.Trace("loadOneBranch: '%s'", rawBranch.Name)
  231. commit, err := rawBranch.GetCommit()
  232. if err != nil {
  233. ctx.ServerError("GetCommit", err)
  234. return nil
  235. }
  236. branchName := rawBranch.Name
  237. var isProtected bool
  238. for _, b := range protectedBranches {
  239. if b.BranchName == branchName {
  240. isProtected = true
  241. break
  242. }
  243. }
  244. divergence, divergenceError := repofiles.CountDivergingCommits(ctx.Repo.Repository, git.BranchPrefix+branchName)
  245. if divergenceError != nil {
  246. ctx.ServerError("CountDivergingCommits", divergenceError)
  247. return nil
  248. }
  249. pr, err := models.GetLatestPullRequestByHeadInfo(ctx.Repo.Repository.ID, branchName)
  250. if err != nil {
  251. ctx.ServerError("GetLatestPullRequestByHeadInfo", err)
  252. return nil
  253. }
  254. headCommit := commit.ID.String()
  255. mergeMovedOn := false
  256. if pr != nil {
  257. pr.HeadRepo = ctx.Repo.Repository
  258. if err := pr.LoadIssue(); err != nil {
  259. ctx.ServerError("pr.LoadIssue", err)
  260. return nil
  261. }
  262. if repo, ok := repoIDToRepo[pr.BaseRepoID]; ok {
  263. pr.BaseRepo = repo
  264. } else if err := pr.LoadBaseRepo(); err != nil {
  265. ctx.ServerError("pr.LoadBaseRepo", err)
  266. return nil
  267. } else {
  268. repoIDToRepo[pr.BaseRepoID] = pr.BaseRepo
  269. }
  270. pr.Issue.Repo = pr.BaseRepo
  271. if pr.HasMerged {
  272. baseGitRepo, ok := repoIDToGitRepo[pr.BaseRepoID]
  273. if !ok {
  274. baseGitRepo, err = git.OpenRepository(pr.BaseRepo.RepoPath())
  275. if err != nil {
  276. ctx.ServerError("OpenRepository", err)
  277. return nil
  278. }
  279. defer baseGitRepo.Close()
  280. repoIDToGitRepo[pr.BaseRepoID] = baseGitRepo
  281. }
  282. pullCommit, err := baseGitRepo.GetRefCommitID(pr.GetGitRefName())
  283. if err != nil && !git.IsErrNotExist(err) {
  284. ctx.ServerError("GetBranchCommitID", err)
  285. return nil
  286. }
  287. if err == nil && headCommit != pullCommit {
  288. // the head has moved on from the merge - we shouldn't delete
  289. mergeMovedOn = true
  290. }
  291. }
  292. }
  293. isIncluded := divergence.Ahead == 0 && ctx.Repo.Repository.DefaultBranch != branchName
  294. return &Branch{
  295. Name: branchName,
  296. Commit: commit,
  297. IsProtected: isProtected,
  298. IsIncluded: isIncluded,
  299. CommitsAhead: divergence.Ahead,
  300. CommitsBehind: divergence.Behind,
  301. LatestPullRequest: pr,
  302. MergeMovedOn: mergeMovedOn,
  303. }
  304. }
  305. func getDeletedBranches(ctx *context.Context) ([]*Branch, error) {
  306. branches := []*Branch{}
  307. deletedBranches, err := ctx.Repo.Repository.GetDeletedBranches()
  308. if err != nil {
  309. return branches, err
  310. }
  311. for i := range deletedBranches {
  312. deletedBranches[i].LoadUser()
  313. branches = append(branches, &Branch{
  314. Name: deletedBranches[i].Name,
  315. IsDeleted: true,
  316. DeletedBranch: deletedBranches[i],
  317. })
  318. }
  319. return branches, nil
  320. }
  321. // CreateBranch creates new branch in repository
  322. func CreateBranch(ctx *context.Context) {
  323. form := web.GetForm(ctx).(*auth.NewBranchForm)
  324. if !ctx.Repo.CanCreateBranch() {
  325. ctx.NotFound("CreateBranch", nil)
  326. return
  327. }
  328. if ctx.HasError() {
  329. ctx.Flash.Error(ctx.GetErrMsg())
  330. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  331. return
  332. }
  333. var err error
  334. if form.CreateTag {
  335. if ctx.Repo.IsViewTag {
  336. err = release_service.CreateNewTag(ctx.User, ctx.Repo.Repository, ctx.Repo.CommitID, form.NewBranchName, "")
  337. } else {
  338. err = release_service.CreateNewTag(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName, "")
  339. }
  340. } else if ctx.Repo.IsViewBranch {
  341. err = repo_module.CreateNewBranch(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName)
  342. } else if ctx.Repo.IsViewTag {
  343. err = repo_module.CreateNewBranchFromCommit(ctx.User, ctx.Repo.Repository, ctx.Repo.CommitID, form.NewBranchName)
  344. } else {
  345. err = repo_module.CreateNewBranchFromCommit(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName)
  346. }
  347. if err != nil {
  348. if models.IsErrTagAlreadyExists(err) {
  349. e := err.(models.ErrTagAlreadyExists)
  350. ctx.Flash.Error(ctx.Tr("repo.branch.tag_collision", e.TagName))
  351. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  352. return
  353. }
  354. if models.IsErrBranchAlreadyExists(err) || git.IsErrPushOutOfDate(err) {
  355. ctx.Flash.Error(ctx.Tr("repo.branch.branch_already_exists", form.NewBranchName))
  356. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  357. return
  358. }
  359. if models.IsErrBranchNameConflict(err) {
  360. e := err.(models.ErrBranchNameConflict)
  361. ctx.Flash.Error(ctx.Tr("repo.branch.branch_name_conflict", form.NewBranchName, e.BranchName))
  362. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  363. return
  364. }
  365. if git.IsErrPushRejected(err) {
  366. e := err.(*git.ErrPushRejected)
  367. if len(e.Message) == 0 {
  368. ctx.Flash.Error(ctx.Tr("repo.editor.push_rejected_no_message"))
  369. } else {
  370. flashError, err := ctx.HTMLString(string(tplAlertDetails), map[string]interface{}{
  371. "Message": ctx.Tr("repo.editor.push_rejected"),
  372. "Summary": ctx.Tr("repo.editor.push_rejected_summary"),
  373. "Details": utils.SanitizeFlashErrorString(e.Message),
  374. })
  375. if err != nil {
  376. ctx.ServerError("UpdatePullRequest.HTMLString", err)
  377. return
  378. }
  379. ctx.Flash.Error(flashError)
  380. }
  381. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  382. return
  383. }
  384. ctx.ServerError("CreateNewBranch", err)
  385. return
  386. }
  387. if form.CreateTag {
  388. ctx.Flash.Success(ctx.Tr("repo.tag.create_success", form.NewBranchName))
  389. ctx.Redirect(ctx.Repo.RepoLink + "/src/tag/" + util.PathEscapeSegments(form.NewBranchName))
  390. return
  391. }
  392. ctx.Flash.Success(ctx.Tr("repo.branch.create_success", form.NewBranchName))
  393. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(form.NewBranchName))
  394. }