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.2 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
  79. protectBranch, err := private.GetProtectedBranchBy(repoID, branchName)
  80. if err != nil {
  81. fail("Internal error", fmt.Sprintf("retrieve protected branches information failed: %v", err))
  82. }
  83. if protectBranch != nil && protectBranch.IsProtected() {
  84. // check and deletion
  85. if newCommitID == git.EmptySHA {
  86. fail(fmt.Sprintf("branch %s is protected from deletion", branchName), "")
  87. }
  88. // detect force push
  89. if git.EmptySHA != oldCommitID {
  90. output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDir(repoPath)
  91. if err != nil {
  92. fail("Internal error", "Fail to detect force push: %v", err)
  93. } else if len(output) > 0 {
  94. fail(fmt.Sprintf("branch %s is protected from force push", branchName), "")
  95. }
  96. }
  97. userID, _ := strconv.ParseInt(userIDStr, 10, 64)
  98. canPush, err := private.CanUserPush(protectBranch.ID, userID)
  99. if err != nil {
  100. fail("Internal error", "Fail to detect user can push: %v", err)
  101. } else if !canPush {
  102. fail(fmt.Sprintf("protected branch %s can not be pushed to", branchName), "")
  103. }
  104. }
  105. }
  106. return nil
  107. }
  108. func runHookUpdate(c *cli.Context) error {
  109. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  110. return nil
  111. }
  112. setup("hooks/update.log")
  113. return nil
  114. }
  115. func runHookPostReceive(c *cli.Context) error {
  116. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  117. return nil
  118. }
  119. setup("hooks/post-receive.log")
  120. // the environment setted on serv command
  121. repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
  122. repoUser := os.Getenv(models.EnvRepoUsername)
  123. isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
  124. repoName := os.Getenv(models.EnvRepoName)
  125. pusherID, _ := strconv.ParseInt(os.Getenv(models.EnvPusherID), 10, 64)
  126. pusherName := os.Getenv(models.EnvPusherName)
  127. buf := bytes.NewBuffer(nil)
  128. scanner := bufio.NewScanner(os.Stdin)
  129. for scanner.Scan() {
  130. buf.Write(scanner.Bytes())
  131. buf.WriteByte('\n')
  132. // TODO: support news feeds for wiki
  133. if isWiki {
  134. continue
  135. }
  136. fields := bytes.Fields(scanner.Bytes())
  137. if len(fields) != 3 {
  138. continue
  139. }
  140. oldCommitID := string(fields[0])
  141. newCommitID := string(fields[1])
  142. refFullName := string(fields[2])
  143. if err := private.PushUpdate(models.PushUpdateOptions{
  144. RefFullName: refFullName,
  145. OldCommitID: oldCommitID,
  146. NewCommitID: newCommitID,
  147. PusherID: pusherID,
  148. PusherName: pusherName,
  149. RepoUserName: repoUser,
  150. RepoName: repoName,
  151. }); err != nil {
  152. log.GitLogger.Error("Update: %v", err)
  153. }
  154. if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
  155. branch := strings.TrimPrefix(refFullName, git.BranchPrefix)
  156. repo, pullRequestAllowed, err := private.GetRepository(repoID)
  157. if err != nil {
  158. log.GitLogger.Error("get repo: %v", err)
  159. break
  160. }
  161. if !pullRequestAllowed {
  162. break
  163. }
  164. baseRepo := repo
  165. if repo.IsFork {
  166. baseRepo = repo.BaseRepo
  167. }
  168. if !repo.IsFork && branch == baseRepo.DefaultBranch {
  169. break
  170. }
  171. pr, err := private.ActivePullRequest(baseRepo.ID, repo.ID, baseRepo.DefaultBranch, branch)
  172. if err != nil {
  173. log.GitLogger.Error("get active pr: %v", err)
  174. break
  175. }
  176. fmt.Fprintln(os.Stderr, "")
  177. if pr == nil {
  178. if repo.IsFork {
  179. branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
  180. }
  181. fmt.Fprintf(os.Stderr, "Create a new pull request for '%s':\n", branch)
  182. fmt.Fprintf(os.Stderr, " %s/compare/%s...%s\n", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch))
  183. } else {
  184. fmt.Fprint(os.Stderr, "Visit the existing pull request:\n")
  185. fmt.Fprintf(os.Stderr, " %s/pulls/%d\n", baseRepo.HTMLURL(), pr.Index)
  186. }
  187. fmt.Fprintln(os.Stderr, "")
  188. }
  189. }
  190. return nil
  191. }