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.

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