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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. "io"
  10. "net/http"
  11. "os"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/private"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/util"
  20. "github.com/urfave/cli"
  21. )
  22. const (
  23. hookBatchSize = 30
  24. )
  25. var (
  26. // CmdHook represents the available hooks sub-command.
  27. CmdHook = cli.Command{
  28. Name: "hook",
  29. Usage: "Delegate commands to corresponding Git hooks",
  30. Description: "This should only be called by Git",
  31. Subcommands: []cli.Command{
  32. subcmdHookPreReceive,
  33. subcmdHookUpdate,
  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. Flags: []cli.Flag{
  43. cli.BoolFlag{
  44. Name: "debug",
  45. },
  46. },
  47. }
  48. subcmdHookUpdate = cli.Command{
  49. Name: "update",
  50. Usage: "Delegate update Git hook",
  51. Description: "This command should only be called by Git",
  52. Action: runHookUpdate,
  53. Flags: []cli.Flag{
  54. cli.BoolFlag{
  55. Name: "debug",
  56. },
  57. },
  58. }
  59. subcmdHookPostReceive = cli.Command{
  60. Name: "post-receive",
  61. Usage: "Delegate post-receive Git hook",
  62. Description: "This command should only be called by Git",
  63. Action: runHookPostReceive,
  64. Flags: []cli.Flag{
  65. cli.BoolFlag{
  66. Name: "debug",
  67. },
  68. },
  69. }
  70. )
  71. type delayWriter struct {
  72. internal io.Writer
  73. buf *bytes.Buffer
  74. timer *time.Timer
  75. }
  76. func newDelayWriter(internal io.Writer, delay time.Duration) *delayWriter {
  77. timer := time.NewTimer(delay)
  78. return &delayWriter{
  79. internal: internal,
  80. buf: &bytes.Buffer{},
  81. timer: timer,
  82. }
  83. }
  84. func (d *delayWriter) Write(p []byte) (n int, err error) {
  85. if d.buf != nil {
  86. select {
  87. case <-d.timer.C:
  88. _, err := d.internal.Write(d.buf.Bytes())
  89. if err != nil {
  90. return 0, err
  91. }
  92. d.buf = nil
  93. return d.internal.Write(p)
  94. default:
  95. return d.buf.Write(p)
  96. }
  97. }
  98. return d.internal.Write(p)
  99. }
  100. func (d *delayWriter) WriteString(s string) (n int, err error) {
  101. if d.buf != nil {
  102. select {
  103. case <-d.timer.C:
  104. _, err := d.internal.Write(d.buf.Bytes())
  105. if err != nil {
  106. return 0, err
  107. }
  108. d.buf = nil
  109. return d.internal.Write([]byte(s))
  110. default:
  111. return d.buf.WriteString(s)
  112. }
  113. }
  114. return d.internal.Write([]byte(s))
  115. }
  116. func (d *delayWriter) Close() error {
  117. if d == nil {
  118. return nil
  119. }
  120. stopped := util.StopTimer(d.timer)
  121. if stopped || d.buf == nil {
  122. return nil
  123. }
  124. _, err := d.internal.Write(d.buf.Bytes())
  125. d.buf = nil
  126. return err
  127. }
  128. type nilWriter struct{}
  129. func (n *nilWriter) Write(p []byte) (int, error) {
  130. return len(p), nil
  131. }
  132. func (n *nilWriter) WriteString(s string) (int, error) {
  133. return len(s), nil
  134. }
  135. func runHookPreReceive(c *cli.Context) error {
  136. if os.Getenv(models.EnvIsInternal) == "true" {
  137. return nil
  138. }
  139. setup("hooks/pre-receive.log", c.Bool("debug"))
  140. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  141. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  142. fail(`Rejecting changes as Gitea environment not set.
  143. If you are pushing over SSH you must push with a key managed by
  144. Gitea or set your environment appropriately.`, "")
  145. } else {
  146. return nil
  147. }
  148. }
  149. // the environment setted on serv command
  150. isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
  151. username := os.Getenv(models.EnvRepoUsername)
  152. reponame := os.Getenv(models.EnvRepoName)
  153. userID, _ := strconv.ParseInt(os.Getenv(models.EnvPusherID), 10, 64)
  154. prID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchPRID), 10, 64)
  155. isDeployKey, _ := strconv.ParseBool(os.Getenv(models.EnvIsDeployKey))
  156. hookOptions := private.HookOptions{
  157. UserID: userID,
  158. GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories),
  159. GitObjectDirectory: os.Getenv(private.GitObjectDirectory),
  160. GitQuarantinePath: os.Getenv(private.GitQuarantinePath),
  161. ProtectedBranchID: prID,
  162. IsDeployKey: isDeployKey,
  163. }
  164. scanner := bufio.NewScanner(os.Stdin)
  165. oldCommitIDs := make([]string, hookBatchSize)
  166. newCommitIDs := make([]string, hookBatchSize)
  167. refFullNames := make([]string, hookBatchSize)
  168. count := 0
  169. total := 0
  170. lastline := 0
  171. var out io.Writer
  172. out = &nilWriter{}
  173. if setting.Git.VerbosePush {
  174. if setting.Git.VerbosePushDelay > 0 {
  175. dWriter := newDelayWriter(os.Stdout, setting.Git.VerbosePushDelay)
  176. defer dWriter.Close()
  177. out = dWriter
  178. } else {
  179. out = os.Stdout
  180. }
  181. }
  182. for scanner.Scan() {
  183. // TODO: support news feeds for wiki
  184. if isWiki {
  185. continue
  186. }
  187. fields := bytes.Fields(scanner.Bytes())
  188. if len(fields) != 3 {
  189. continue
  190. }
  191. oldCommitID := string(fields[0])
  192. newCommitID := string(fields[1])
  193. refFullName := string(fields[2])
  194. total++
  195. lastline++
  196. // If the ref is a branch, check if it's protected
  197. if strings.HasPrefix(refFullName, git.BranchPrefix) {
  198. oldCommitIDs[count] = oldCommitID
  199. newCommitIDs[count] = newCommitID
  200. refFullNames[count] = refFullName
  201. count++
  202. fmt.Fprintf(out, "*")
  203. if count >= hookBatchSize {
  204. fmt.Fprintf(out, " Checking %d branches\n", count)
  205. hookOptions.OldCommitIDs = oldCommitIDs
  206. hookOptions.NewCommitIDs = newCommitIDs
  207. hookOptions.RefFullNames = refFullNames
  208. statusCode, msg := private.HookPreReceive(username, reponame, hookOptions)
  209. switch statusCode {
  210. case http.StatusOK:
  211. // no-op
  212. case http.StatusInternalServerError:
  213. fail("Internal Server Error", msg)
  214. default:
  215. fail(msg, "")
  216. }
  217. count = 0
  218. lastline = 0
  219. }
  220. } else {
  221. fmt.Fprintf(out, ".")
  222. }
  223. if lastline >= hookBatchSize {
  224. fmt.Fprintf(out, "\n")
  225. lastline = 0
  226. }
  227. }
  228. if count > 0 {
  229. hookOptions.OldCommitIDs = oldCommitIDs[:count]
  230. hookOptions.NewCommitIDs = newCommitIDs[:count]
  231. hookOptions.RefFullNames = refFullNames[:count]
  232. fmt.Fprintf(out, " Checking %d branches\n", count)
  233. statusCode, msg := private.HookPreReceive(username, reponame, hookOptions)
  234. switch statusCode {
  235. case http.StatusInternalServerError:
  236. fail("Internal Server Error", msg)
  237. case http.StatusForbidden:
  238. fail(msg, "")
  239. }
  240. } else if lastline > 0 {
  241. fmt.Fprintf(out, "\n")
  242. lastline = 0
  243. }
  244. fmt.Fprintf(out, "Checked %d references in total\n", total)
  245. return nil
  246. }
  247. func runHookUpdate(c *cli.Context) error {
  248. // Update is empty and is kept only for backwards compatibility
  249. return nil
  250. }
  251. func runHookPostReceive(c *cli.Context) error {
  252. if os.Getenv(models.EnvIsInternal) == "true" {
  253. return nil
  254. }
  255. setup("hooks/post-receive.log", c.Bool("debug"))
  256. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  257. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  258. fail(`Rejecting changes as Gitea environment not set.
  259. If you are pushing over SSH you must push with a key managed by
  260. Gitea or set your environment appropriately.`, "")
  261. } else {
  262. return nil
  263. }
  264. }
  265. var out io.Writer
  266. var dWriter *delayWriter
  267. out = &nilWriter{}
  268. if setting.Git.VerbosePush {
  269. if setting.Git.VerbosePushDelay > 0 {
  270. dWriter = newDelayWriter(os.Stdout, setting.Git.VerbosePushDelay)
  271. defer dWriter.Close()
  272. out = dWriter
  273. } else {
  274. out = os.Stdout
  275. }
  276. }
  277. // the environment setted on serv command
  278. repoUser := os.Getenv(models.EnvRepoUsername)
  279. isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
  280. repoName := os.Getenv(models.EnvRepoName)
  281. pusherID, _ := strconv.ParseInt(os.Getenv(models.EnvPusherID), 10, 64)
  282. pusherName := os.Getenv(models.EnvPusherName)
  283. hookOptions := private.HookOptions{
  284. UserName: pusherName,
  285. UserID: pusherID,
  286. GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories),
  287. GitObjectDirectory: os.Getenv(private.GitObjectDirectory),
  288. GitQuarantinePath: os.Getenv(private.GitQuarantinePath),
  289. }
  290. oldCommitIDs := make([]string, hookBatchSize)
  291. newCommitIDs := make([]string, hookBatchSize)
  292. refFullNames := make([]string, hookBatchSize)
  293. count := 0
  294. total := 0
  295. wasEmpty := false
  296. masterPushed := false
  297. results := make([]private.HookPostReceiveBranchResult, 0)
  298. scanner := bufio.NewScanner(os.Stdin)
  299. for scanner.Scan() {
  300. // TODO: support news feeds for wiki
  301. if isWiki {
  302. continue
  303. }
  304. fields := bytes.Fields(scanner.Bytes())
  305. if len(fields) != 3 {
  306. continue
  307. }
  308. fmt.Fprintf(out, ".")
  309. oldCommitIDs[count] = string(fields[0])
  310. newCommitIDs[count] = string(fields[1])
  311. refFullNames[count] = string(fields[2])
  312. if refFullNames[count] == git.BranchPrefix+"master" && newCommitIDs[count] != git.EmptySHA && count == total {
  313. masterPushed = true
  314. }
  315. count++
  316. total++
  317. if count >= hookBatchSize {
  318. fmt.Fprintf(out, " Processing %d references\n", count)
  319. hookOptions.OldCommitIDs = oldCommitIDs
  320. hookOptions.NewCommitIDs = newCommitIDs
  321. hookOptions.RefFullNames = refFullNames
  322. resp, err := private.HookPostReceive(repoUser, repoName, hookOptions)
  323. if resp == nil {
  324. _ = dWriter.Close()
  325. hookPrintResults(results)
  326. fail("Internal Server Error", err)
  327. }
  328. wasEmpty = wasEmpty || resp.RepoWasEmpty
  329. results = append(results, resp.Results...)
  330. count = 0
  331. }
  332. }
  333. if count == 0 {
  334. if wasEmpty && masterPushed {
  335. // We need to tell the repo to reset the default branch to master
  336. err := private.SetDefaultBranch(repoUser, repoName, "master")
  337. if err != nil {
  338. fail("Internal Server Error", "SetDefaultBranch failed with Error: %v", err)
  339. }
  340. }
  341. fmt.Fprintf(out, "Processed %d references in total\n", total)
  342. _ = dWriter.Close()
  343. hookPrintResults(results)
  344. return nil
  345. }
  346. hookOptions.OldCommitIDs = oldCommitIDs[:count]
  347. hookOptions.NewCommitIDs = newCommitIDs[:count]
  348. hookOptions.RefFullNames = refFullNames[:count]
  349. fmt.Fprintf(out, " Processing %d references\n", count)
  350. resp, err := private.HookPostReceive(repoUser, repoName, hookOptions)
  351. if resp == nil {
  352. _ = dWriter.Close()
  353. hookPrintResults(results)
  354. fail("Internal Server Error", err)
  355. }
  356. wasEmpty = wasEmpty || resp.RepoWasEmpty
  357. results = append(results, resp.Results...)
  358. fmt.Fprintf(out, "Processed %d references in total\n", total)
  359. if wasEmpty && masterPushed {
  360. // We need to tell the repo to reset the default branch to master
  361. err := private.SetDefaultBranch(repoUser, repoName, "master")
  362. if err != nil {
  363. fail("Internal Server Error", "SetDefaultBranch failed with Error: %v", err)
  364. }
  365. }
  366. _ = dWriter.Close()
  367. hookPrintResults(results)
  368. return nil
  369. }
  370. func hookPrintResults(results []private.HookPostReceiveBranchResult) {
  371. for _, res := range results {
  372. if !res.Message {
  373. continue
  374. }
  375. fmt.Fprintln(os.Stderr, "")
  376. if res.Create {
  377. fmt.Fprintf(os.Stderr, "Create a new pull request for '%s':\n", res.Branch)
  378. fmt.Fprintf(os.Stderr, " %s\n", res.URL)
  379. } else {
  380. fmt.Fprint(os.Stderr, "Visit the existing pull request:\n")
  381. fmt.Fprintf(os.Stderr, " %s\n", res.URL)
  382. }
  383. fmt.Fprintln(os.Stderr, "")
  384. os.Stderr.Sync()
  385. }
  386. }