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

branch.go 12 kB

11 years ago
11 years ago
2 years ago
11 years ago
11 years ago
11 years ago
2 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
4 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. "net/http"
  8. "strings"
  9. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/auth"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/repofiles"
  16. repo_module "code.gitea.io/gitea/modules/repository"
  17. "code.gitea.io/gitea/modules/util"
  18. "code.gitea.io/gitea/routers/utils"
  19. )
  20. const (
  21. tplBranch base.TplName = "repo/branch/list"
  22. )
  23. // Branch contains the branch information
  24. type Branch struct {
  25. Name string
  26. Commit *git.Commit
  27. IsProtected bool
  28. IsDeleted bool
  29. IsIncluded bool
  30. DeletedBranch *models.DeletedBranch
  31. CommitsAhead int
  32. CommitsBehind int
  33. LatestPullRequest *models.PullRequest
  34. MergeMovedOn bool
  35. }
  36. // Branches render repository branch page
  37. func Branches(ctx *context.Context) {
  38. ctx.Data["Title"] = "Branches"
  39. ctx.Data["IsRepoToolbarBranches"] = true
  40. ctx.Data["DefaultBranch"] = ctx.Repo.Repository.DefaultBranch
  41. ctx.Data["AllowsPulls"] = ctx.Repo.Repository.AllowsPulls()
  42. ctx.Data["IsWriter"] = ctx.Repo.CanWrite(models.UnitTypeCode)
  43. ctx.Data["IsMirror"] = ctx.Repo.Repository.IsMirror
  44. ctx.Data["CanPull"] = ctx.Repo.CanWrite(models.UnitTypeCode) || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID))
  45. ctx.Data["PageIsViewCode"] = true
  46. ctx.Data["PageIsBranches"] = true
  47. ctx.Data["Branches"] = loadBranches(ctx)
  48. ctx.HTML(200, tplBranch)
  49. }
  50. func BranchNames(ctx *context.Context) {
  51. page := ctx.QueryInt("page")
  52. pageSize := ctx.QueryInt("pageSize")
  53. if page <= 0 {
  54. page = 1
  55. }
  56. maxPagingNum := 50
  57. defaultPagingNum := 15
  58. if pageSize == 0 || pageSize > maxPagingNum {
  59. pageSize = defaultPagingNum
  60. }
  61. skip := (page - 1) * pageSize
  62. branchNames, total, _ := ctx.Repo.GitRepo.GetBranchNames(skip, pageSize)
  63. ctx.JSON(http.StatusOK, map[string]interface{}{
  64. "branches": branchNames,
  65. "total": total,
  66. })
  67. }
  68. // DeleteBranchPost responses for delete merged branch
  69. func DeleteBranchPost(ctx *context.Context) {
  70. defer redirect(ctx)
  71. branchName := ctx.Query("name")
  72. if branchName == ctx.Repo.Repository.DefaultBranch {
  73. ctx.Flash.Error(ctx.Tr("repo.branch.default_deletion_failed", branchName))
  74. return
  75. }
  76. isProtected, err := ctx.Repo.Repository.IsProtectedBranch(branchName, ctx.User)
  77. if err != nil {
  78. log.Error("DeleteBranch: %v", err)
  79. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  80. return
  81. }
  82. if isProtected {
  83. ctx.Flash.Error(ctx.Tr("repo.branch.protected_deletion_failed", branchName))
  84. return
  85. }
  86. if !ctx.Repo.GitRepo.IsBranchExist(branchName) || branchName == ctx.Repo.Repository.DefaultBranch {
  87. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  88. return
  89. }
  90. if err := deleteBranch(ctx, branchName); err != nil {
  91. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  92. return
  93. }
  94. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", branchName))
  95. }
  96. // RestoreBranchPost responses for delete merged branch
  97. func RestoreBranchPost(ctx *context.Context) {
  98. defer redirect(ctx)
  99. branchID := ctx.QueryInt64("branch_id")
  100. branchName := ctx.Query("name")
  101. deletedBranch, err := ctx.Repo.Repository.GetDeletedBranchByID(branchID)
  102. if err != nil {
  103. log.Error("GetDeletedBranchByID: %v", err)
  104. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", branchName))
  105. return
  106. }
  107. if err := ctx.Repo.GitRepo.CreateBranch(deletedBranch.Name, deletedBranch.Commit); err != nil {
  108. if strings.Contains(err.Error(), "already exists") {
  109. ctx.Flash.Error(ctx.Tr("repo.branch.already_exists", deletedBranch.Name))
  110. return
  111. }
  112. log.Error("CreateBranch: %v", err)
  113. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", deletedBranch.Name))
  114. return
  115. }
  116. if err := ctx.Repo.Repository.RemoveDeletedBranch(deletedBranch.ID); err != nil {
  117. log.Error("RemoveDeletedBranch: %v", err)
  118. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", deletedBranch.Name))
  119. return
  120. }
  121. // Don't return error below this
  122. if err := repofiles.PushUpdate(
  123. ctx.Repo.Repository,
  124. deletedBranch.Name,
  125. repofiles.PushUpdateOptions{
  126. RefFullName: git.BranchPrefix + deletedBranch.Name,
  127. OldCommitID: git.EmptySHA,
  128. NewCommitID: deletedBranch.Commit,
  129. PusherID: ctx.User.ID,
  130. PusherName: ctx.User.Name,
  131. RepoUserName: ctx.Repo.Owner.Name,
  132. RepoName: ctx.Repo.Repository.Name,
  133. }); err != nil {
  134. log.Error("Update: %v", err)
  135. }
  136. ctx.Flash.Success(ctx.Tr("repo.branch.restore_success", deletedBranch.Name))
  137. }
  138. func redirect(ctx *context.Context) {
  139. ctx.JSON(200, map[string]interface{}{
  140. "redirect": ctx.Repo.RepoLink + "/branches",
  141. })
  142. }
  143. func deleteBranch(ctx *context.Context, branchName string) error {
  144. commit, err := ctx.Repo.GitRepo.GetBranchCommit(branchName)
  145. if err != nil {
  146. log.Error("GetBranchCommit: %v", err)
  147. return err
  148. }
  149. if err := ctx.Repo.GitRepo.DeleteBranch(branchName, git.DeleteBranchOptions{
  150. Force: true,
  151. }); err != nil {
  152. log.Error("DeleteBranch: %v", err)
  153. return err
  154. }
  155. // Don't return error below this
  156. if err := repofiles.PushUpdate(
  157. ctx.Repo.Repository,
  158. branchName,
  159. repofiles.PushUpdateOptions{
  160. RefFullName: git.BranchPrefix + branchName,
  161. OldCommitID: commit.ID.String(),
  162. NewCommitID: git.EmptySHA,
  163. PusherID: ctx.User.ID,
  164. PusherName: ctx.User.Name,
  165. RepoUserName: ctx.Repo.Owner.Name,
  166. RepoName: ctx.Repo.Repository.Name,
  167. }); err != nil {
  168. log.Error("Update: %v", err)
  169. }
  170. if err := ctx.Repo.Repository.AddDeletedBranch(branchName, commit.ID.String(), ctx.User.ID); err != nil {
  171. log.Warn("AddDeletedBranch: %v", err)
  172. }
  173. return nil
  174. }
  175. func loadBranches(ctx *context.Context) []*Branch {
  176. rawBranches, _, err := repo_module.GetBranches(ctx.Repo.Repository, 0, 0)
  177. if err != nil {
  178. ctx.ServerError("GetBranches", err)
  179. return nil
  180. }
  181. protectedBranches, err := ctx.Repo.Repository.GetProtectedBranches()
  182. if err != nil {
  183. ctx.ServerError("GetProtectedBranches", err)
  184. return nil
  185. }
  186. repoIDToRepo := map[int64]*models.Repository{}
  187. repoIDToRepo[ctx.Repo.Repository.ID] = ctx.Repo.Repository
  188. repoIDToGitRepo := map[int64]*git.Repository{}
  189. repoIDToGitRepo[ctx.Repo.Repository.ID] = ctx.Repo.GitRepo
  190. branches := make([]*Branch, len(rawBranches))
  191. for i := range rawBranches {
  192. commit, err := rawBranches[i].GetCommit()
  193. if err != nil {
  194. ctx.ServerError("GetCommit", err)
  195. return nil
  196. }
  197. var isProtected bool
  198. branchName := rawBranches[i].Name
  199. for _, b := range protectedBranches {
  200. if b.BranchName == branchName {
  201. isProtected = true
  202. break
  203. }
  204. }
  205. divergence, divergenceError := repofiles.CountDivergingCommits(ctx.Repo.Repository, branchName)
  206. if divergenceError != nil {
  207. ctx.ServerError("CountDivergingCommits", divergenceError)
  208. return nil
  209. }
  210. pr, err := models.GetLatestPullRequestByHeadInfo(ctx.Repo.Repository.ID, branchName)
  211. if err != nil {
  212. ctx.ServerError("GetLatestPullRequestByHeadInfo", err)
  213. return nil
  214. }
  215. headCommit := commit.ID.String()
  216. mergeMovedOn := false
  217. if pr != nil {
  218. pr.HeadRepo = ctx.Repo.Repository
  219. if err := pr.LoadIssue(); err != nil {
  220. ctx.ServerError("pr.LoadIssue", err)
  221. return nil
  222. }
  223. if repo, ok := repoIDToRepo[pr.BaseRepoID]; ok {
  224. pr.BaseRepo = repo
  225. } else if err := pr.LoadBaseRepo(); err != nil {
  226. ctx.ServerError("pr.LoadBaseRepo", err)
  227. return nil
  228. } else {
  229. repoIDToRepo[pr.BaseRepoID] = pr.BaseRepo
  230. }
  231. pr.Issue.Repo = pr.BaseRepo
  232. if pr.HasMerged {
  233. baseGitRepo, ok := repoIDToGitRepo[pr.BaseRepoID]
  234. if !ok {
  235. baseGitRepo, err = git.OpenRepository(pr.BaseRepo.RepoPath())
  236. if err != nil {
  237. ctx.ServerError("OpenRepository", err)
  238. return nil
  239. }
  240. defer baseGitRepo.Close()
  241. repoIDToGitRepo[pr.BaseRepoID] = baseGitRepo
  242. }
  243. pullCommit, err := baseGitRepo.GetRefCommitID(pr.GetGitRefName())
  244. if err != nil && !git.IsErrNotExist(err) {
  245. ctx.ServerError("GetBranchCommitID", err)
  246. return nil
  247. }
  248. if err == nil && headCommit != pullCommit {
  249. // the head has moved on from the merge - we shouldn't delete
  250. mergeMovedOn = true
  251. }
  252. }
  253. }
  254. isIncluded := divergence.Ahead == 0 && ctx.Repo.Repository.DefaultBranch != branchName
  255. branches[i] = &Branch{
  256. Name: branchName,
  257. Commit: commit,
  258. IsProtected: isProtected,
  259. IsIncluded: isIncluded,
  260. CommitsAhead: divergence.Ahead,
  261. CommitsBehind: divergence.Behind,
  262. LatestPullRequest: pr,
  263. MergeMovedOn: mergeMovedOn,
  264. }
  265. }
  266. if ctx.Repo.CanWrite(models.UnitTypeCode) {
  267. deletedBranches, err := getDeletedBranches(ctx)
  268. if err != nil {
  269. ctx.ServerError("getDeletedBranches", err)
  270. return nil
  271. }
  272. branches = append(branches, deletedBranches...)
  273. }
  274. return branches
  275. }
  276. func getDeletedBranches(ctx *context.Context) ([]*Branch, error) {
  277. branches := []*Branch{}
  278. deletedBranches, err := ctx.Repo.Repository.GetDeletedBranches()
  279. if err != nil {
  280. return branches, err
  281. }
  282. for i := range deletedBranches {
  283. deletedBranches[i].LoadUser()
  284. branches = append(branches, &Branch{
  285. Name: deletedBranches[i].Name,
  286. IsDeleted: true,
  287. DeletedBranch: deletedBranches[i],
  288. })
  289. }
  290. return branches, nil
  291. }
  292. // CreateBranch creates new branch in repository
  293. func CreateBranch(ctx *context.Context, form auth.NewBranchForm) {
  294. if !ctx.Repo.CanCreateBranch() {
  295. ctx.NotFound("CreateBranch", nil)
  296. return
  297. }
  298. if ctx.HasError() {
  299. ctx.Flash.Error(ctx.GetErrMsg())
  300. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  301. return
  302. }
  303. var err error
  304. if ctx.Repo.IsViewBranch {
  305. err = repo_module.CreateNewBranch(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName)
  306. } else {
  307. err = repo_module.CreateNewBranchFromCommit(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName)
  308. }
  309. if err != nil {
  310. if models.IsErrTagAlreadyExists(err) {
  311. e := err.(models.ErrTagAlreadyExists)
  312. ctx.Flash.Error(ctx.Tr("repo.branch.tag_collision", e.TagName))
  313. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  314. return
  315. }
  316. if models.IsErrBranchAlreadyExists(err) || git.IsErrPushOutOfDate(err) {
  317. ctx.Flash.Error(ctx.Tr("repo.branch.branch_already_exists", form.NewBranchName))
  318. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  319. return
  320. }
  321. if models.IsErrBranchNameConflict(err) {
  322. e := err.(models.ErrBranchNameConflict)
  323. ctx.Flash.Error(ctx.Tr("repo.branch.branch_name_conflict", form.NewBranchName, e.BranchName))
  324. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  325. return
  326. }
  327. if git.IsErrPushRejected(err) {
  328. e := err.(*git.ErrPushRejected)
  329. if len(e.Message) == 0 {
  330. ctx.Flash.Error(ctx.Tr("repo.editor.push_rejected_no_message"))
  331. } else {
  332. ctx.Flash.Error(ctx.Tr("repo.editor.push_rejected", utils.SanitizeFlashErrorString(e.Message)))
  333. }
  334. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  335. return
  336. }
  337. ctx.ServerError("CreateNewBranch", err)
  338. return
  339. }
  340. ctx.Flash.Success(ctx.Tr("repo.branch.create_success", form.NewBranchName))
  341. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(form.NewBranchName))
  342. }