hook.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright 2014 The Gogs 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. "crypto/tls"
  9. "fmt"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "strings"
  14. "github.com/Unknwon/com"
  15. "github.com/urfave/cli"
  16. log "gopkg.in/clog.v1"
  17. "github.com/gogits/git-module"
  18. "github.com/gogits/gogs/models"
  19. "github.com/gogits/gogs/modules/httplib"
  20. "github.com/gogits/gogs/modules/setting"
  21. http "github.com/gogits/gogs/routers/repo"
  22. )
  23. var (
  24. CmdHook = cli.Command{
  25. Name: "hook",
  26. Usage: "Delegate commands to corresponding Git hooks",
  27. Description: "All sub-commands should only be called by Git",
  28. Flags: []cli.Flag{
  29. stringFlag("config, c", "custom/conf/app.ini", "Custom configuration file path"),
  30. },
  31. Subcommands: []cli.Command{
  32. subcmdHookPreReceive,
  33. subcmdHookUpadte,
  34. subcmdHookPostReceive,
  35. },
  36. }
  37. subcmdHookPreReceive = cli.Command{
  38. Name: "pre-receive",
  39. Usage: "Delegate pre-receive Git hook",
  40. Description: "This command should only be called by Git",
  41. Action: runHookPreReceive,
  42. }
  43. subcmdHookUpadte = cli.Command{
  44. Name: "update",
  45. Usage: "Delegate update Git hook",
  46. Description: "This command should only be called by Git",
  47. Action: runHookUpdate,
  48. }
  49. subcmdHookPostReceive = cli.Command{
  50. Name: "post-receive",
  51. Usage: "Delegate post-receive Git hook",
  52. Description: "This command should only be called by Git",
  53. Action: runHookPostReceive,
  54. }
  55. )
  56. func runHookPreReceive(c *cli.Context) error {
  57. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  58. return nil
  59. }
  60. setup(c, "hooks/pre-receive.log", true)
  61. isWiki := strings.Contains(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
  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. if isWiki {
  68. continue
  69. }
  70. fields := bytes.Fields(scanner.Bytes())
  71. if len(fields) != 3 {
  72. continue
  73. }
  74. oldCommitID := string(fields[0])
  75. newCommitID := string(fields[1])
  76. branchName := strings.TrimPrefix(string(fields[2]), git.BRANCH_PREFIX)
  77. // Branch protection
  78. repoID := com.StrTo(os.Getenv(http.ENV_REPO_ID)).MustInt64()
  79. protectBranch, err := models.GetProtectBranchOfRepoByName(repoID, branchName)
  80. if err != nil {
  81. if models.IsErrBranchNotExist(err) {
  82. continue
  83. }
  84. fail("Internal error", "GetProtectBranchOfRepoByName [repo_id: %d, branch: %s]: %v", repoID, branchName, err)
  85. }
  86. if !protectBranch.Protected {
  87. continue
  88. }
  89. // Check if branch allows direct push
  90. if protectBranch.RequirePullRequest {
  91. fail(fmt.Sprintf("Branch '%s' is protected and commits must be merged through pull request", branchName), "")
  92. }
  93. // check and deletion
  94. if newCommitID == git.EMPTY_SHA {
  95. fail(fmt.Sprintf("Branch '%s' is protected from deletion", branchName), "")
  96. }
  97. // Check force push
  98. output, err := git.NewCommand("rev-list", oldCommitID, "^"+newCommitID).Run()
  99. if err != nil {
  100. fail("Internal error", "Fail to detect force push: %v", err)
  101. } else if len(output) > 0 {
  102. fail(fmt.Sprintf("Branch '%s' is protected from force push", branchName), "")
  103. }
  104. }
  105. customHooksPath := filepath.Join(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), "pre-receive")
  106. if !com.IsFile(customHooksPath) {
  107. return nil
  108. }
  109. hookCmd := exec.Command(customHooksPath)
  110. hookCmd.Stdout = os.Stdout
  111. hookCmd.Stdin = buf
  112. hookCmd.Stderr = os.Stderr
  113. if err := hookCmd.Run(); err != nil {
  114. fail("Internal error", "Fail to execute custom pre-receive hook: %v", err)
  115. }
  116. return nil
  117. }
  118. func runHookUpdate(c *cli.Context) error {
  119. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  120. return nil
  121. }
  122. setup(c, "hooks/update.log", false)
  123. args := c.Args()
  124. if len(args) != 3 {
  125. fail("Arguments received are not equal to three", "Arguments received are not equal to three")
  126. } else if len(args[0]) == 0 {
  127. fail("First argument 'refName' is empty", "First argument 'refName' is empty")
  128. }
  129. customHooksPath := filepath.Join(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), "update")
  130. if !com.IsFile(customHooksPath) {
  131. return nil
  132. }
  133. hookCmd := exec.Command(customHooksPath, args...)
  134. hookCmd.Stdout = os.Stdout
  135. hookCmd.Stdin = os.Stdin
  136. hookCmd.Stderr = os.Stderr
  137. if err := hookCmd.Run(); err != nil {
  138. fail("Internal error", "Fail to execute custom pre-receive hook: %v", err)
  139. }
  140. return nil
  141. }
  142. func runHookPostReceive(c *cli.Context) error {
  143. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  144. return nil
  145. }
  146. setup(c, "hooks/post-receive.log", true)
  147. isWiki := strings.Contains(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
  148. buf := bytes.NewBuffer(nil)
  149. scanner := bufio.NewScanner(os.Stdin)
  150. for scanner.Scan() {
  151. buf.Write(scanner.Bytes())
  152. buf.WriteByte('\n')
  153. // TODO: support news feeds for wiki
  154. if isWiki {
  155. continue
  156. }
  157. fields := bytes.Fields(scanner.Bytes())
  158. if len(fields) != 3 {
  159. continue
  160. }
  161. options := models.PushUpdateOptions{
  162. OldCommitID: string(fields[0]),
  163. NewCommitID: string(fields[1]),
  164. RefFullName: string(fields[2]),
  165. PusherID: com.StrTo(os.Getenv(http.ENV_AUTH_USER_ID)).MustInt64(),
  166. PusherName: os.Getenv(http.ENV_AUTH_USER_NAME),
  167. RepoUserName: os.Getenv(http.ENV_REPO_OWNER_NAME),
  168. RepoName: os.Getenv(http.ENV_REPO_NAME),
  169. }
  170. if err := models.PushUpdate(options); err != nil {
  171. log.Error(2, "PushUpdate: %v", err)
  172. }
  173. // Ask for running deliver hook and test pull request tasks.
  174. reqURL := setting.LocalURL + options.RepoUserName + "/" + options.RepoName + "/tasks/trigger?branch=" +
  175. strings.TrimPrefix(options.RefFullName, git.BRANCH_PREFIX) +
  176. "&secret=" + os.Getenv(http.ENV_REPO_OWNER_SALT_MD5) +
  177. "&pusher=" + os.Getenv(http.ENV_AUTH_USER_ID)
  178. log.Trace("Trigger task: %s", reqURL)
  179. resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
  180. InsecureSkipVerify: true,
  181. }).Response()
  182. if err == nil {
  183. resp.Body.Close()
  184. if resp.StatusCode/100 != 2 {
  185. log.Error(2, "Fail to trigger task: not 2xx response code")
  186. }
  187. } else {
  188. log.Error(2, "Fail to trigger task: %v", err)
  189. }
  190. }
  191. customHooksPath := filepath.Join(os.Getenv(http.ENV_REPO_CUSTOM_HOOKS_PATH), "post-receive")
  192. if !com.IsFile(customHooksPath) {
  193. return nil
  194. }
  195. hookCmd := exec.Command(customHooksPath)
  196. hookCmd.Stdout = os.Stdout
  197. hookCmd.Stdin = buf
  198. hookCmd.Stderr = os.Stderr
  199. if err := hookCmd.Run(); err != nil {
  200. fail("Internal error", "Fail to execute custom post-receive hook: %v", err)
  201. }
  202. return nil
  203. }