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.

372 lines
11 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 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
5 years ago
10 years ago
10 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
5 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
5 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
5 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
5 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
5 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
5 years ago
10 years ago
  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. "strings"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/auth"
  10. "code.gitea.io/gitea/modules/base"
  11. "code.gitea.io/gitea/modules/context"
  12. "code.gitea.io/gitea/modules/git"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/repofiles"
  15. repo_module "code.gitea.io/gitea/modules/repository"
  16. "code.gitea.io/gitea/modules/util"
  17. "code.gitea.io/gitea/routers/utils"
  18. )
  19. const (
  20. tplBranch base.TplName = "repo/branch/list"
  21. )
  22. // Branch contains the branch information
  23. type Branch struct {
  24. Name string
  25. Commit *git.Commit
  26. IsProtected bool
  27. IsDeleted bool
  28. IsIncluded bool
  29. DeletedBranch *models.DeletedBranch
  30. CommitsAhead int
  31. CommitsBehind int
  32. LatestPullRequest *models.PullRequest
  33. MergeMovedOn bool
  34. }
  35. // Branches render repository branch page
  36. func Branches(ctx *context.Context) {
  37. ctx.Data["Title"] = "Branches"
  38. ctx.Data["IsRepoToolbarBranches"] = true
  39. ctx.Data["DefaultBranch"] = ctx.Repo.Repository.DefaultBranch
  40. ctx.Data["AllowsPulls"] = ctx.Repo.Repository.AllowsPulls()
  41. ctx.Data["IsWriter"] = ctx.Repo.CanWrite(models.UnitTypeCode)
  42. ctx.Data["IsMirror"] = ctx.Repo.Repository.IsMirror
  43. ctx.Data["CanPull"] = ctx.Repo.CanWrite(models.UnitTypeCode) || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID))
  44. ctx.Data["PageIsViewCode"] = true
  45. ctx.Data["PageIsBranches"] = true
  46. ctx.Data["Branches"] = loadBranches(ctx)
  47. ctx.HTML(200, tplBranch)
  48. }
  49. // DeleteBranchPost responses for delete merged branch
  50. func DeleteBranchPost(ctx *context.Context) {
  51. defer redirect(ctx)
  52. branchName := ctx.Query("name")
  53. if branchName == ctx.Repo.Repository.DefaultBranch {
  54. ctx.Flash.Error(ctx.Tr("repo.branch.default_deletion_failed", branchName))
  55. return
  56. }
  57. isProtected, err := ctx.Repo.Repository.IsProtectedBranch(branchName, ctx.User)
  58. if err != nil {
  59. log.Error("DeleteBranch: %v", err)
  60. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  61. return
  62. }
  63. if isProtected {
  64. ctx.Flash.Error(ctx.Tr("repo.branch.protected_deletion_failed", branchName))
  65. return
  66. }
  67. if !ctx.Repo.GitRepo.IsBranchExist(branchName) || branchName == ctx.Repo.Repository.DefaultBranch {
  68. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  69. return
  70. }
  71. if err := deleteBranch(ctx, branchName); err != nil {
  72. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", branchName))
  73. return
  74. }
  75. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", branchName))
  76. }
  77. // RestoreBranchPost responses for delete merged branch
  78. func RestoreBranchPost(ctx *context.Context) {
  79. defer redirect(ctx)
  80. branchID := ctx.QueryInt64("branch_id")
  81. branchName := ctx.Query("name")
  82. deletedBranch, err := ctx.Repo.Repository.GetDeletedBranchByID(branchID)
  83. if err != nil {
  84. log.Error("GetDeletedBranchByID: %v", err)
  85. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", branchName))
  86. return
  87. }
  88. if err := ctx.Repo.GitRepo.CreateBranch(deletedBranch.Name, deletedBranch.Commit); err != nil {
  89. if strings.Contains(err.Error(), "already exists") {
  90. ctx.Flash.Error(ctx.Tr("repo.branch.already_exists", deletedBranch.Name))
  91. return
  92. }
  93. log.Error("CreateBranch: %v", err)
  94. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", deletedBranch.Name))
  95. return
  96. }
  97. if err := ctx.Repo.Repository.RemoveDeletedBranch(deletedBranch.ID); err != nil {
  98. log.Error("RemoveDeletedBranch: %v", err)
  99. ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", deletedBranch.Name))
  100. return
  101. }
  102. // Don't return error below this
  103. if err := repofiles.PushUpdate(
  104. ctx.Repo.Repository,
  105. deletedBranch.Name,
  106. repofiles.PushUpdateOptions{
  107. RefFullName: git.BranchPrefix + deletedBranch.Name,
  108. OldCommitID: git.EmptySHA,
  109. NewCommitID: deletedBranch.Commit,
  110. PusherID: ctx.User.ID,
  111. PusherName: ctx.User.Name,
  112. RepoUserName: ctx.Repo.Owner.Name,
  113. RepoName: ctx.Repo.Repository.Name,
  114. }); err != nil {
  115. log.Error("Update: %v", err)
  116. }
  117. ctx.Flash.Success(ctx.Tr("repo.branch.restore_success", deletedBranch.Name))
  118. }
  119. func redirect(ctx *context.Context) {
  120. ctx.JSON(200, map[string]interface{}{
  121. "redirect": ctx.Repo.RepoLink + "/branches",
  122. })
  123. }
  124. func deleteBranch(ctx *context.Context, branchName string) error {
  125. commit, err := ctx.Repo.GitRepo.GetBranchCommit(branchName)
  126. if err != nil {
  127. log.Error("GetBranchCommit: %v", err)
  128. return err
  129. }
  130. if err := ctx.Repo.GitRepo.DeleteBranch(branchName, git.DeleteBranchOptions{
  131. Force: true,
  132. }); err != nil {
  133. log.Error("DeleteBranch: %v", err)
  134. return err
  135. }
  136. // Don't return error below this
  137. if err := repofiles.PushUpdate(
  138. ctx.Repo.Repository,
  139. branchName,
  140. repofiles.PushUpdateOptions{
  141. RefFullName: git.BranchPrefix + branchName,
  142. OldCommitID: commit.ID.String(),
  143. NewCommitID: git.EmptySHA,
  144. PusherID: ctx.User.ID,
  145. PusherName: ctx.User.Name,
  146. RepoUserName: ctx.Repo.Owner.Name,
  147. RepoName: ctx.Repo.Repository.Name,
  148. }); err != nil {
  149. log.Error("Update: %v", err)
  150. }
  151. if err := ctx.Repo.Repository.AddDeletedBranch(branchName, commit.ID.String(), ctx.User.ID); err != nil {
  152. log.Warn("AddDeletedBranch: %v", err)
  153. }
  154. return nil
  155. }
  156. func loadBranches(ctx *context.Context) []*Branch {
  157. rawBranches, err := repo_module.GetBranches(ctx.Repo.Repository)
  158. if err != nil {
  159. ctx.ServerError("GetBranches", err)
  160. return nil
  161. }
  162. protectedBranches, err := ctx.Repo.Repository.GetProtectedBranches()
  163. if err != nil {
  164. ctx.ServerError("GetProtectedBranches", err)
  165. return nil
  166. }
  167. repoIDToRepo := map[int64]*models.Repository{}
  168. repoIDToRepo[ctx.Repo.Repository.ID] = ctx.Repo.Repository
  169. repoIDToGitRepo := map[int64]*git.Repository{}
  170. repoIDToGitRepo[ctx.Repo.Repository.ID] = ctx.Repo.GitRepo
  171. branches := make([]*Branch, len(rawBranches))
  172. for i := range rawBranches {
  173. commit, err := rawBranches[i].GetCommit()
  174. if err != nil {
  175. ctx.ServerError("GetCommit", err)
  176. return nil
  177. }
  178. var isProtected bool
  179. branchName := rawBranches[i].Name
  180. for _, b := range protectedBranches {
  181. if b.BranchName == branchName {
  182. isProtected = true
  183. break
  184. }
  185. }
  186. divergence, divergenceError := repofiles.CountDivergingCommits(ctx.Repo.Repository, branchName)
  187. if divergenceError != nil {
  188. ctx.ServerError("CountDivergingCommits", divergenceError)
  189. return nil
  190. }
  191. pr, err := models.GetLatestPullRequestByHeadInfo(ctx.Repo.Repository.ID, branchName)
  192. if err != nil {
  193. ctx.ServerError("GetLatestPullRequestByHeadInfo", err)
  194. return nil
  195. }
  196. headCommit := commit.ID.String()
  197. mergeMovedOn := false
  198. if pr != nil {
  199. pr.HeadRepo = ctx.Repo.Repository
  200. if err := pr.LoadIssue(); err != nil {
  201. ctx.ServerError("pr.LoadIssue", err)
  202. return nil
  203. }
  204. if repo, ok := repoIDToRepo[pr.BaseRepoID]; ok {
  205. pr.BaseRepo = repo
  206. } else if err := pr.LoadBaseRepo(); err != nil {
  207. ctx.ServerError("pr.LoadBaseRepo", err)
  208. return nil
  209. } else {
  210. repoIDToRepo[pr.BaseRepoID] = pr.BaseRepo
  211. }
  212. pr.Issue.Repo = pr.BaseRepo
  213. if pr.HasMerged {
  214. baseGitRepo, ok := repoIDToGitRepo[pr.BaseRepoID]
  215. if !ok {
  216. baseGitRepo, err = git.OpenRepository(pr.BaseRepo.RepoPath())
  217. if err != nil {
  218. ctx.ServerError("OpenRepository", err)
  219. return nil
  220. }
  221. defer baseGitRepo.Close()
  222. repoIDToGitRepo[pr.BaseRepoID] = baseGitRepo
  223. }
  224. pullCommit, err := baseGitRepo.GetRefCommitID(pr.GetGitRefName())
  225. if err != nil && !git.IsErrNotExist(err) {
  226. ctx.ServerError("GetBranchCommitID", err)
  227. return nil
  228. }
  229. if err == nil && headCommit != pullCommit {
  230. // the head has moved on from the merge - we shouldn't delete
  231. mergeMovedOn = true
  232. }
  233. }
  234. }
  235. isIncluded := divergence.Ahead == 0 && ctx.Repo.Repository.DefaultBranch != branchName
  236. branches[i] = &Branch{
  237. Name: branchName,
  238. Commit: commit,
  239. IsProtected: isProtected,
  240. IsIncluded: isIncluded,
  241. CommitsAhead: divergence.Ahead,
  242. CommitsBehind: divergence.Behind,
  243. LatestPullRequest: pr,
  244. MergeMovedOn: mergeMovedOn,
  245. }
  246. }
  247. if ctx.Repo.CanWrite(models.UnitTypeCode) {
  248. deletedBranches, err := getDeletedBranches(ctx)
  249. if err != nil {
  250. ctx.ServerError("getDeletedBranches", err)
  251. return nil
  252. }
  253. branches = append(branches, deletedBranches...)
  254. }
  255. return branches
  256. }
  257. func getDeletedBranches(ctx *context.Context) ([]*Branch, error) {
  258. branches := []*Branch{}
  259. deletedBranches, err := ctx.Repo.Repository.GetDeletedBranches()
  260. if err != nil {
  261. return branches, err
  262. }
  263. for i := range deletedBranches {
  264. deletedBranches[i].LoadUser()
  265. branches = append(branches, &Branch{
  266. Name: deletedBranches[i].Name,
  267. IsDeleted: true,
  268. DeletedBranch: deletedBranches[i],
  269. })
  270. }
  271. return branches, nil
  272. }
  273. // CreateBranch creates new branch in repository
  274. func CreateBranch(ctx *context.Context, form auth.NewBranchForm) {
  275. if !ctx.Repo.CanCreateBranch() {
  276. ctx.NotFound("CreateBranch", nil)
  277. return
  278. }
  279. if ctx.HasError() {
  280. ctx.Flash.Error(ctx.GetErrMsg())
  281. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  282. return
  283. }
  284. var err error
  285. if ctx.Repo.IsViewBranch {
  286. err = repo_module.CreateNewBranch(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName)
  287. } else {
  288. err = repo_module.CreateNewBranchFromCommit(ctx.User, ctx.Repo.Repository, ctx.Repo.BranchName, form.NewBranchName)
  289. }
  290. if err != nil {
  291. if models.IsErrTagAlreadyExists(err) {
  292. e := err.(models.ErrTagAlreadyExists)
  293. ctx.Flash.Error(ctx.Tr("repo.branch.tag_collision", e.TagName))
  294. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  295. return
  296. }
  297. if models.IsErrBranchAlreadyExists(err) || git.IsErrPushOutOfDate(err) {
  298. ctx.Flash.Error(ctx.Tr("repo.branch.branch_already_exists", form.NewBranchName))
  299. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  300. return
  301. }
  302. if models.IsErrBranchNameConflict(err) {
  303. e := err.(models.ErrBranchNameConflict)
  304. ctx.Flash.Error(ctx.Tr("repo.branch.branch_name_conflict", form.NewBranchName, e.BranchName))
  305. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  306. return
  307. }
  308. if git.IsErrPushRejected(err) {
  309. e := err.(*git.ErrPushRejected)
  310. if len(e.Message) == 0 {
  311. ctx.Flash.Error(ctx.Tr("repo.editor.push_rejected_no_message"))
  312. } else {
  313. ctx.Flash.Error(ctx.Tr("repo.editor.push_rejected", utils.SanitizeFlashErrorString(e.Message)))
  314. }
  315. ctx.Redirect(ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL())
  316. return
  317. }
  318. ctx.ServerError("CreateNewBranch", err)
  319. return
  320. }
  321. ctx.Flash.Success(ctx.Tr("repo.branch.create_success", form.NewBranchName))
  322. ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(form.NewBranchName))
  323. }