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.

hook.go 6.8KB

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. log.GitLogger.Fatal(2, "retrieve protected branches information failed")
  100. }
  101. if protectBranch != nil && protectBranch.IsProtected() {
  102. // detect force push
  103. if git.EmptySHA != oldCommitID {
  104. output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDir(repoPath)
  105. if err != nil {
  106. fail("Internal error", "Fail to detect force push: %v", err)
  107. } else if len(output) > 0 {
  108. fail(fmt.Sprintf("branch %s is protected from force push", branchName), "")
  109. }
  110. }
  111. // check and deletion
  112. if newCommitID == git.EmptySHA {
  113. fail(fmt.Sprintf("branch %s is protected from deletion", branchName), "")
  114. } else {
  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. }
  125. return nil
  126. }
  127. func runHookUpdate(c *cli.Context) error {
  128. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  129. return nil
  130. }
  131. if c.IsSet("config") {
  132. setting.CustomConf = c.String("config")
  133. } else if c.GlobalIsSet("config") {
  134. setting.CustomConf = c.GlobalString("config")
  135. }
  136. hookSetup("hooks/update.log")
  137. return nil
  138. }
  139. func runHookPostReceive(c *cli.Context) error {
  140. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  141. return nil
  142. }
  143. if c.IsSet("config") {
  144. setting.CustomConf = c.String("config")
  145. } else if c.GlobalIsSet("config") {
  146. setting.CustomConf = c.GlobalString("config")
  147. }
  148. hookSetup("hooks/post-receive.log")
  149. // the environment setted on serv command
  150. repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
  151. repoUser := os.Getenv(models.EnvRepoUsername)
  152. isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
  153. repoName := os.Getenv(models.EnvRepoName)
  154. pusherID, _ := strconv.ParseInt(os.Getenv(models.EnvPusherID), 10, 64)
  155. pusherName := os.Getenv(models.EnvPusherName)
  156. buf := bytes.NewBuffer(nil)
  157. scanner := bufio.NewScanner(os.Stdin)
  158. for scanner.Scan() {
  159. buf.Write(scanner.Bytes())
  160. buf.WriteByte('\n')
  161. // TODO: support news feeds for wiki
  162. if isWiki {
  163. continue
  164. }
  165. fields := bytes.Fields(scanner.Bytes())
  166. if len(fields) != 3 {
  167. continue
  168. }
  169. oldCommitID := string(fields[0])
  170. newCommitID := string(fields[1])
  171. refFullName := string(fields[2])
  172. if err := private.PushUpdate(models.PushUpdateOptions{
  173. RefFullName: refFullName,
  174. OldCommitID: oldCommitID,
  175. NewCommitID: newCommitID,
  176. PusherID: pusherID,
  177. PusherName: pusherName,
  178. RepoUserName: repoUser,
  179. RepoName: repoName,
  180. }); err != nil {
  181. log.GitLogger.Error(2, "Update: %v", err)
  182. }
  183. if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
  184. branch := strings.TrimPrefix(refFullName, git.BranchPrefix)
  185. repo, pullRequestAllowed, err := private.GetRepository(repoID)
  186. if err != nil {
  187. log.GitLogger.Error(2, "get repo: %v", err)
  188. break
  189. }
  190. if !pullRequestAllowed {
  191. break
  192. }
  193. baseRepo := repo
  194. if repo.IsFork {
  195. baseRepo = repo.BaseRepo
  196. }
  197. if !repo.IsFork && branch == baseRepo.DefaultBranch {
  198. break
  199. }
  200. pr, err := private.ActivePullRequest(baseRepo.ID, repo.ID, baseRepo.DefaultBranch, branch)
  201. if err != nil {
  202. log.GitLogger.Error(2, "get active pr: %v", err)
  203. break
  204. }
  205. fmt.Fprintln(os.Stderr, "")
  206. if pr == nil {
  207. if repo.IsFork {
  208. branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
  209. }
  210. fmt.Fprintf(os.Stderr, "Create a new pull request for '%s':\n", branch)
  211. fmt.Fprintf(os.Stderr, " %s/compare/%s...%s\n", baseRepo.HTMLURL(), url.QueryEscape(baseRepo.DefaultBranch), url.QueryEscape(branch))
  212. } else {
  213. fmt.Fprint(os.Stderr, "Visit the existing pull request:\n")
  214. fmt.Fprintf(os.Stderr, " %s/pulls/%d\n", baseRepo.HTMLURL(), pr.Index)
  215. }
  216. fmt.Fprintln(os.Stderr, "")
  217. }
  218. }
  219. return nil
  220. }