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

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