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.

hook.go 6.6 kB

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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cmd
  5. import (
  6. "bufio"
  7. "bytes"
  8. "fmt"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/private"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/urfave/cli"
  18. )
  19. var (
  20. // CmdHook represents the available hooks sub-command.
  21. CmdHook = cli.Command{
  22. Name: "hook",
  23. Usage: "Delegate commands to corresponding Git hooks",
  24. Description: "This should only be called by Git",
  25. Subcommands: []cli.Command{
  26. subcmdHookPreReceive,
  27. subcmdHookUpdate,
  28. subcmdHookPostReceive,
  29. },
  30. }
  31. subcmdHookPreReceive = cli.Command{
  32. Name: "pre-receive",
  33. Usage: "Delegate pre-receive Git hook",
  34. Description: "This command should only be called by Git",
  35. Action: runHookPreReceive,
  36. }
  37. subcmdHookUpdate = cli.Command{
  38. Name: "update",
  39. Usage: "Delegate update Git hook",
  40. Description: "This command should only be called by Git",
  41. Action: runHookUpdate,
  42. }
  43. subcmdHookPostReceive = cli.Command{
  44. Name: "post-receive",
  45. Usage: "Delegate post-receive Git hook",
  46. Description: "This command should only be called by Git",
  47. Action: runHookPostReceive,
  48. }
  49. )
  50. func runHookPreReceive(c *cli.Context) error {
  51. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  52. return nil
  53. }
  54. setup("hooks/pre-receive.log")
  55. // the environment setted on serv command
  56. repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
  57. isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
  58. username := os.Getenv(models.EnvRepoUsername)
  59. reponame := os.Getenv(models.EnvRepoName)
  60. userIDStr := os.Getenv(models.EnvPusherID)
  61. repoPath := models.RepoPath(username, reponame)
  62. buf := bytes.NewBuffer(nil)
  63. scanner := bufio.NewScanner(os.Stdin)
  64. for scanner.Scan() {
  65. buf.Write(scanner.Bytes())
  66. buf.WriteByte('\n')
  67. // TODO: support news feeds for wiki
  68. if isWiki {
  69. continue
  70. }
  71. fields := bytes.Fields(scanner.Bytes())
  72. if len(fields) != 3 {
  73. continue
  74. }
  75. oldCommitID := string(fields[0])
  76. newCommitID := string(fields[1])
  77. refFullName := string(fields[2])
  78. // If the ref is a branch, check if it's protected
  79. if strings.HasPrefix(refFullName, git.BranchPrefix) {
  80. branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
  81. protectBranch, err := private.GetProtectedBranchBy(repoID, branchName)
  82. if err != nil {
  83. fail("Internal error", fmt.Sprintf("retrieve protected branches information failed: %v", err))
  84. }
  85. if protectBranch != nil && protectBranch.IsProtected() {
  86. // check and deletion
  87. if newCommitID == git.EmptySHA {
  88. fail(fmt.Sprintf("branch %s is protected from deletion", branchName), "")
  89. }
  90. // detect force push
  91. if git.EmptySHA != oldCommitID {
  92. output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDir(repoPath)
  93. if err != nil {
  94. fail("Internal error", "Fail to detect force push: %v", err)
  95. } else if len(output) > 0 {
  96. fail(fmt.Sprintf("branch %s is protected from force push", branchName), "")
  97. }
  98. }
  99. userID, _ := strconv.ParseInt(userIDStr, 10, 64)
  100. canPush, err := private.CanUserPush(protectBranch.ID, userID)
  101. if err != nil {
  102. fail("Internal error", "Fail to detect user can push: %v", err)
  103. } else if !canPush {
  104. fail(fmt.Sprintf("protected branch %s can not be pushed to", branchName), "")
  105. }
  106. }
  107. }
  108. }
  109. return nil
  110. }
  111. func runHookUpdate(c *cli.Context) error {
  112. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  113. return nil
  114. }
  115. setup("hooks/update.log")
  116. return nil
  117. }
  118. func runHookPostReceive(c *cli.Context) error {
  119. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  120. return nil
  121. }
  122. setup("hooks/post-receive.log")
  123. // the environment setted on serv command
  124. repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
  125. repoUser := os.Getenv(models.EnvRepoUsername)
  126. isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
  127. repoName := os.Getenv(models.EnvRepoName)
  128. pusherID, _ := strconv.ParseInt(os.Getenv(models.EnvPusherID), 10, 64)
  129. pusherName := os.Getenv(models.EnvPusherName)
  130. buf := bytes.NewBuffer(nil)
  131. scanner := bufio.NewScanner(os.Stdin)
  132. for scanner.Scan() {
  133. buf.Write(scanner.Bytes())
  134. buf.WriteByte('\n')
  135. // TODO: support news feeds for wiki
  136. if isWiki {
  137. continue
  138. }
  139. fields := bytes.Fields(scanner.Bytes())
  140. if len(fields) != 3 {
  141. continue
  142. }
  143. oldCommitID := string(fields[0])
  144. newCommitID := string(fields[1])
  145. refFullName := string(fields[2])
  146. // Only trigger activity updates for changes to branches or
  147. // tags. Updates to other refs (eg, refs/notes, refs/changes,
  148. // or other less-standard refs spaces are ignored since there
  149. // may be a very large number of them).
  150. if strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) {
  151. if err := private.PushUpdate(models.PushUpdateOptions{
  152. RefFullName: refFullName,
  153. OldCommitID: oldCommitID,
  154. NewCommitID: newCommitID,
  155. PusherID: pusherID,
  156. PusherName: pusherName,
  157. RepoUserName: repoUser,
  158. RepoName: repoName,
  159. }); err != nil {
  160. log.GitLogger.Error("Update: %v", err)
  161. }
  162. }
  163. if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
  164. branch := strings.TrimPrefix(refFullName, git.BranchPrefix)
  165. repo, pullRequestAllowed, err := private.GetRepository(repoID)
  166. if err != nil {
  167. log.GitLogger.Error("get repo: %v", err)
  168. break
  169. }
  170. if !pullRequestAllowed {
  171. break
  172. }
  173. baseRepo := repo
  174. if repo.IsFork {
  175. baseRepo = repo.BaseRepo
  176. }
  177. if !repo.IsFork && branch == baseRepo.DefaultBranch {
  178. break
  179. }
  180. pr, err := private.ActivePullRequest(baseRepo.ID, repo.ID, baseRepo.DefaultBranch, branch)
  181. if err != nil {
  182. log.GitLogger.Error("get active pr: %v", err)
  183. break
  184. }
  185. fmt.Fprintln(os.Stderr, "")
  186. if pr == nil {
  187. if repo.IsFork {
  188. branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
  189. }
  190. fmt.Fprintf(os.Stderr, "Create a new pull request for '%s':\n", branch)
  191. fmt.Fprintf(os.Stderr, " %s/compare/%s...%s\n", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch))
  192. } else {
  193. fmt.Fprint(os.Stderr, "Visit the existing pull request:\n")
  194. fmt.Fprintf(os.Stderr, " %s/pulls/%d\n", baseRepo.HTMLURL(), pr.Index)
  195. }
  196. fmt.Fprintln(os.Stderr, "")
  197. }
  198. }
  199. return nil
  200. }