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.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. "net/url"
  10. "os"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "code.gitea.io/git"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/private"
  18. "code.gitea.io/gitea/modules/setting"
  19. "github.com/urfave/cli"
  20. )
  21. var (
  22. // CmdHook represents the available hooks sub-command.
  23. CmdHook = cli.Command{
  24. Name: "hook",
  25. Usage: "Delegate commands to corresponding Git hooks",
  26. Description: "This should only be called by Git",
  27. Flags: []cli.Flag{
  28. cli.StringFlag{
  29. Name: "config, c",
  30. Value: "custom/conf/app.ini",
  31. Usage: "Custom configuration file path",
  32. },
  33. },
  34. Subcommands: []cli.Command{
  35. subcmdHookPreReceive,
  36. subcmdHookUpdate,
  37. subcmdHookPostReceive,
  38. },
  39. }
  40. subcmdHookPreReceive = cli.Command{
  41. Name: "pre-receive",
  42. Usage: "Delegate pre-receive Git hook",
  43. Description: "This command should only be called by Git",
  44. Action: runHookPreReceive,
  45. }
  46. subcmdHookUpdate = cli.Command{
  47. Name: "update",
  48. Usage: "Delegate update Git hook",
  49. Description: "This command should only be called by Git",
  50. Action: runHookUpdate,
  51. }
  52. subcmdHookPostReceive = cli.Command{
  53. Name: "post-receive",
  54. Usage: "Delegate post-receive Git hook",
  55. Description: "This command should only be called by Git",
  56. Action: runHookPostReceive,
  57. }
  58. )
  59. func hookSetup(logPath string) {
  60. setting.NewContext()
  61. log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
  62. }
  63. func runHookPreReceive(c *cli.Context) error {
  64. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  65. return nil
  66. }
  67. if c.IsSet("config") {
  68. setting.CustomConf = c.String("config")
  69. } else if c.GlobalIsSet("config") {
  70. setting.CustomConf = c.GlobalString("config")
  71. }
  72. hookSetup("hooks/pre-receive.log")
  73. // the environment setted on serv command
  74. repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
  75. isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
  76. username := os.Getenv(models.EnvRepoUsername)
  77. reponame := os.Getenv(models.EnvRepoName)
  78. userIDStr := os.Getenv(models.EnvPusherID)
  79. repoPath := models.RepoPath(username, reponame)
  80. buf := bytes.NewBuffer(nil)
  81. scanner := bufio.NewScanner(os.Stdin)
  82. for scanner.Scan() {
  83. buf.Write(scanner.Bytes())
  84. buf.WriteByte('\n')
  85. // TODO: support news feeds for wiki
  86. if isWiki {
  87. continue
  88. }
  89. fields := bytes.Fields(scanner.Bytes())
  90. if len(fields) != 3 {
  91. continue
  92. }
  93. oldCommitID := string(fields[0])
  94. newCommitID := string(fields[1])
  95. refFullName := string(fields[2])
  96. branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
  97. protectBranch, err := private.GetProtectedBranchBy(repoID, branchName)
  98. if err != nil {
  99. fail("Internal error", fmt.Sprintf("retrieve protected branches information failed: %v", err))
  100. }
  101. if protectBranch != nil && protectBranch.IsProtected() {
  102. // check and deletion
  103. if newCommitID == git.EmptySHA {
  104. fail(fmt.Sprintf("branch %s is protected from deletion", branchName), "")
  105. }
  106. // detect force push
  107. if git.EmptySHA != oldCommitID {
  108. output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDir(repoPath)
  109. if err != nil {
  110. fail("Internal error", "Fail to detect force push: %v", err)
  111. } else if len(output) > 0 {
  112. fail(fmt.Sprintf("branch %s is protected from force push", branchName), "")
  113. }
  114. }
  115. userID, _ := strconv.ParseInt(userIDStr, 10, 64)
  116. canPush, err := private.CanUserPush(protectBranch.ID, userID)
  117. if err != nil {
  118. fail("Internal error", "Fail to detect user can push: %v", err)
  119. } else if !canPush {
  120. fail(fmt.Sprintf("protected branch %s can not be pushed to", branchName), "")
  121. }
  122. }
  123. }
  124. return nil
  125. }
  126. func runHookUpdate(c *cli.Context) error {
  127. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  128. return nil
  129. }
  130. if c.IsSet("config") {
  131. setting.CustomConf = c.String("config")
  132. } else if c.GlobalIsSet("config") {
  133. setting.CustomConf = c.GlobalString("config")
  134. }
  135. hookSetup("hooks/update.log")
  136. return nil
  137. }
  138. func runHookPostReceive(c *cli.Context) error {
  139. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  140. return nil
  141. }
  142. if c.IsSet("config") {
  143. setting.CustomConf = c.String("config")
  144. } else if c.GlobalIsSet("config") {
  145. setting.CustomConf = c.GlobalString("config")
  146. }
  147. hookSetup("hooks/post-receive.log")
  148. // the environment setted on serv command
  149. repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
  150. repoUser := os.Getenv(models.EnvRepoUsername)
  151. isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
  152. repoName := os.Getenv(models.EnvRepoName)
  153. pusherID, _ := strconv.ParseInt(os.Getenv(models.EnvPusherID), 10, 64)
  154. pusherName := os.Getenv(models.EnvPusherName)
  155. buf := bytes.NewBuffer(nil)
  156. scanner := bufio.NewScanner(os.Stdin)
  157. for scanner.Scan() {
  158. buf.Write(scanner.Bytes())
  159. buf.WriteByte('\n')
  160. // TODO: support news feeds for wiki
  161. if isWiki {
  162. continue
  163. }
  164. fields := bytes.Fields(scanner.Bytes())
  165. if len(fields) != 3 {
  166. continue
  167. }
  168. oldCommitID := string(fields[0])
  169. newCommitID := string(fields[1])
  170. refFullName := string(fields[2])
  171. if err := private.PushUpdate(models.PushUpdateOptions{
  172. RefFullName: refFullName,
  173. OldCommitID: oldCommitID,
  174. NewCommitID: newCommitID,
  175. PusherID: pusherID,
  176. PusherName: pusherName,
  177. RepoUserName: repoUser,
  178. RepoName: repoName,
  179. }); err != nil {
  180. log.GitLogger.Error(2, "Update: %v", err)
  181. }
  182. if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
  183. branch := strings.TrimPrefix(refFullName, git.BranchPrefix)
  184. repo, pullRequestAllowed, err := private.GetRepository(repoID)
  185. if err != nil {
  186. log.GitLogger.Error(2, "get repo: %v", err)
  187. break
  188. }
  189. if !pullRequestAllowed {
  190. break
  191. }
  192. baseRepo := repo
  193. if repo.IsFork {
  194. baseRepo = repo.BaseRepo
  195. }
  196. if !repo.IsFork && branch == baseRepo.DefaultBranch {
  197. break
  198. }
  199. pr, err := private.ActivePullRequest(baseRepo.ID, repo.ID, baseRepo.DefaultBranch, branch)
  200. if err != nil {
  201. log.GitLogger.Error(2, "get active pr: %v", err)
  202. break
  203. }
  204. fmt.Fprintln(os.Stderr, "")
  205. if pr == nil {
  206. if repo.IsFork {
  207. branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
  208. }
  209. fmt.Fprintf(os.Stderr, "Create a new pull request for '%s':\n", branch)
  210. fmt.Fprintf(os.Stderr, " %s/compare/%s...%s\n", baseRepo.HTMLURL(), url.QueryEscape(baseRepo.DefaultBranch), url.QueryEscape(branch))
  211. } else {
  212. fmt.Fprint(os.Stderr, "Visit the existing pull request:\n")
  213. fmt.Fprintf(os.Stderr, " %s/pulls/%d\n", baseRepo.HTMLURL(), pr.Index)
  214. }
  215. fmt.Fprintln(os.Stderr, "")
  216. }
  217. }
  218. return nil
  219. }