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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "bufio"
  6. "bytes"
  7. "context"
  8. "fmt"
  9. "io"
  10. "os"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/private"
  17. repo_module "code.gitea.io/gitea/modules/repository"
  18. "code.gitea.io/gitea/modules/setting"
  19. "github.com/urfave/cli/v2"
  20. )
  21. const (
  22. hookBatchSize = 30
  23. )
  24. var (
  25. // CmdHook represents the available hooks sub-command.
  26. CmdHook = &cli.Command{
  27. Name: "hook",
  28. Usage: "(internal) Should only be called by Git",
  29. Description: "Delegate commands to corresponding Git hooks",
  30. Before: PrepareConsoleLoggerLevel(log.FATAL),
  31. Subcommands: []*cli.Command{
  32. subcmdHookPreReceive,
  33. subcmdHookUpdate,
  34. subcmdHookPostReceive,
  35. subcmdHookProcReceive,
  36. },
  37. }
  38. subcmdHookPreReceive = &cli.Command{
  39. Name: "pre-receive",
  40. Usage: "Delegate pre-receive Git hook",
  41. Description: "This command should only be called by Git",
  42. Action: runHookPreReceive,
  43. Flags: []cli.Flag{
  44. &cli.BoolFlag{
  45. Name: "debug",
  46. },
  47. },
  48. }
  49. subcmdHookUpdate = &cli.Command{
  50. Name: "update",
  51. Usage: "Delegate update Git hook",
  52. Description: "This command should only be called by Git",
  53. Action: runHookUpdate,
  54. Flags: []cli.Flag{
  55. &cli.BoolFlag{
  56. Name: "debug",
  57. },
  58. },
  59. }
  60. subcmdHookPostReceive = &cli.Command{
  61. Name: "post-receive",
  62. Usage: "Delegate post-receive Git hook",
  63. Description: "This command should only be called by Git",
  64. Action: runHookPostReceive,
  65. Flags: []cli.Flag{
  66. &cli.BoolFlag{
  67. Name: "debug",
  68. },
  69. },
  70. }
  71. // Note: new hook since git 2.29
  72. subcmdHookProcReceive = &cli.Command{
  73. Name: "proc-receive",
  74. Usage: "Delegate proc-receive Git hook",
  75. Description: "This command should only be called by Git",
  76. Action: runHookProcReceive,
  77. Flags: []cli.Flag{
  78. &cli.BoolFlag{
  79. Name: "debug",
  80. },
  81. },
  82. }
  83. )
  84. type delayWriter struct {
  85. internal io.Writer
  86. buf *bytes.Buffer
  87. timer *time.Timer
  88. }
  89. func newDelayWriter(internal io.Writer, delay time.Duration) *delayWriter {
  90. timer := time.NewTimer(delay)
  91. return &delayWriter{
  92. internal: internal,
  93. buf: &bytes.Buffer{},
  94. timer: timer,
  95. }
  96. }
  97. func (d *delayWriter) Write(p []byte) (n int, err error) {
  98. if d.buf != nil {
  99. select {
  100. case <-d.timer.C:
  101. _, err := d.internal.Write(d.buf.Bytes())
  102. if err != nil {
  103. return 0, err
  104. }
  105. d.buf = nil
  106. return d.internal.Write(p)
  107. default:
  108. return d.buf.Write(p)
  109. }
  110. }
  111. return d.internal.Write(p)
  112. }
  113. func (d *delayWriter) WriteString(s string) (n int, err error) {
  114. if d.buf != nil {
  115. select {
  116. case <-d.timer.C:
  117. _, err := d.internal.Write(d.buf.Bytes())
  118. if err != nil {
  119. return 0, err
  120. }
  121. d.buf = nil
  122. return d.internal.Write([]byte(s))
  123. default:
  124. return d.buf.WriteString(s)
  125. }
  126. }
  127. return d.internal.Write([]byte(s))
  128. }
  129. func (d *delayWriter) Close() error {
  130. if d == nil {
  131. return nil
  132. }
  133. stopped := d.timer.Stop()
  134. if stopped || d.buf == nil {
  135. return nil
  136. }
  137. _, err := d.internal.Write(d.buf.Bytes())
  138. d.buf = nil
  139. return err
  140. }
  141. type nilWriter struct{}
  142. func (n *nilWriter) Write(p []byte) (int, error) {
  143. return len(p), nil
  144. }
  145. func (n *nilWriter) WriteString(s string) (int, error) {
  146. return len(s), nil
  147. }
  148. func runHookPreReceive(c *cli.Context) error {
  149. if isInternal, _ := strconv.ParseBool(os.Getenv(repo_module.EnvIsInternal)); isInternal {
  150. return nil
  151. }
  152. ctx, cancel := installSignals()
  153. defer cancel()
  154. setup(ctx, c.Bool("debug"))
  155. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  156. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  157. return fail(ctx, `Rejecting changes as Gitea environment not set.
  158. If you are pushing over SSH you must push with a key managed by
  159. Gitea or set your environment appropriately.`, "")
  160. }
  161. return nil
  162. }
  163. // the environment is set by serv command
  164. isWiki, _ := strconv.ParseBool(os.Getenv(repo_module.EnvRepoIsWiki))
  165. username := os.Getenv(repo_module.EnvRepoUsername)
  166. reponame := os.Getenv(repo_module.EnvRepoName)
  167. userID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPusherID), 10, 64)
  168. prID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPRID), 10, 64)
  169. deployKeyID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvDeployKeyID), 10, 64)
  170. actionPerm, _ := strconv.ParseInt(os.Getenv(repo_module.EnvActionPerm), 10, 64)
  171. hookOptions := private.HookOptions{
  172. UserID: userID,
  173. GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories),
  174. GitObjectDirectory: os.Getenv(private.GitObjectDirectory),
  175. GitQuarantinePath: os.Getenv(private.GitQuarantinePath),
  176. GitPushOptions: pushOptions(),
  177. PullRequestID: prID,
  178. DeployKeyID: deployKeyID,
  179. ActionPerm: int(actionPerm),
  180. }
  181. scanner := bufio.NewScanner(os.Stdin)
  182. oldCommitIDs := make([]string, hookBatchSize)
  183. newCommitIDs := make([]string, hookBatchSize)
  184. refFullNames := make([]git.RefName, hookBatchSize)
  185. count := 0
  186. total := 0
  187. lastline := 0
  188. var out io.Writer
  189. out = &nilWriter{}
  190. if setting.Git.VerbosePush {
  191. if setting.Git.VerbosePushDelay > 0 {
  192. dWriter := newDelayWriter(os.Stdout, setting.Git.VerbosePushDelay)
  193. defer dWriter.Close()
  194. out = dWriter
  195. } else {
  196. out = os.Stdout
  197. }
  198. }
  199. supportProcReceive := git.DefaultFeatures().SupportProcReceive
  200. for scanner.Scan() {
  201. // TODO: support news feeds for wiki
  202. if isWiki {
  203. continue
  204. }
  205. fields := bytes.Fields(scanner.Bytes())
  206. if len(fields) != 3 {
  207. continue
  208. }
  209. oldCommitID := string(fields[0])
  210. newCommitID := string(fields[1])
  211. refFullName := git.RefName(fields[2])
  212. total++
  213. lastline++
  214. // If the ref is a branch or tag, check if it's protected
  215. // if supportProcReceive all ref should be checked because
  216. // permission check was delayed
  217. if supportProcReceive || refFullName.IsBranch() || refFullName.IsTag() {
  218. oldCommitIDs[count] = oldCommitID
  219. newCommitIDs[count] = newCommitID
  220. refFullNames[count] = refFullName
  221. count++
  222. fmt.Fprintf(out, "*")
  223. if count >= hookBatchSize {
  224. fmt.Fprintf(out, " Checking %d references\n", count)
  225. hookOptions.OldCommitIDs = oldCommitIDs
  226. hookOptions.NewCommitIDs = newCommitIDs
  227. hookOptions.RefFullNames = refFullNames
  228. extra := private.HookPreReceive(ctx, username, reponame, hookOptions)
  229. if extra.HasError() {
  230. return fail(ctx, extra.UserMsg, "HookPreReceive(batch) failed: %v", extra.Error)
  231. }
  232. count = 0
  233. lastline = 0
  234. }
  235. } else {
  236. fmt.Fprintf(out, ".")
  237. }
  238. if lastline >= hookBatchSize {
  239. fmt.Fprintf(out, "\n")
  240. lastline = 0
  241. }
  242. }
  243. if count > 0 {
  244. hookOptions.OldCommitIDs = oldCommitIDs[:count]
  245. hookOptions.NewCommitIDs = newCommitIDs[:count]
  246. hookOptions.RefFullNames = refFullNames[:count]
  247. fmt.Fprintf(out, " Checking %d references\n", count)
  248. extra := private.HookPreReceive(ctx, username, reponame, hookOptions)
  249. if extra.HasError() {
  250. return fail(ctx, extra.UserMsg, "HookPreReceive(last) failed: %v", extra.Error)
  251. }
  252. } else if lastline > 0 {
  253. fmt.Fprintf(out, "\n")
  254. }
  255. fmt.Fprintf(out, "Checked %d references in total\n", total)
  256. return nil
  257. }
  258. func runHookUpdate(c *cli.Context) error {
  259. // Update is empty and is kept only for backwards compatibility
  260. return nil
  261. }
  262. func runHookPostReceive(c *cli.Context) error {
  263. ctx, cancel := installSignals()
  264. defer cancel()
  265. setup(ctx, c.Bool("debug"))
  266. // First of all run update-server-info no matter what
  267. if _, _, err := git.NewCommand(ctx, "update-server-info").RunStdString(nil); err != nil {
  268. return fmt.Errorf("Failed to call 'git update-server-info': %w", err)
  269. }
  270. // Now if we're an internal don't do anything else
  271. if isInternal, _ := strconv.ParseBool(os.Getenv(repo_module.EnvIsInternal)); isInternal {
  272. return nil
  273. }
  274. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  275. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  276. return fail(ctx, `Rejecting changes as Gitea environment not set.
  277. If you are pushing over SSH you must push with a key managed by
  278. Gitea or set your environment appropriately.`, "")
  279. }
  280. return nil
  281. }
  282. var out io.Writer
  283. var dWriter *delayWriter
  284. out = &nilWriter{}
  285. if setting.Git.VerbosePush {
  286. if setting.Git.VerbosePushDelay > 0 {
  287. dWriter = newDelayWriter(os.Stdout, setting.Git.VerbosePushDelay)
  288. defer dWriter.Close()
  289. out = dWriter
  290. } else {
  291. out = os.Stdout
  292. }
  293. }
  294. // the environment is set by serv command
  295. repoUser := os.Getenv(repo_module.EnvRepoUsername)
  296. isWiki, _ := strconv.ParseBool(os.Getenv(repo_module.EnvRepoIsWiki))
  297. repoName := os.Getenv(repo_module.EnvRepoName)
  298. pusherID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPusherID), 10, 64)
  299. pusherName := os.Getenv(repo_module.EnvPusherName)
  300. hookOptions := private.HookOptions{
  301. UserName: pusherName,
  302. UserID: pusherID,
  303. GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories),
  304. GitObjectDirectory: os.Getenv(private.GitObjectDirectory),
  305. GitQuarantinePath: os.Getenv(private.GitQuarantinePath),
  306. GitPushOptions: pushOptions(),
  307. }
  308. oldCommitIDs := make([]string, hookBatchSize)
  309. newCommitIDs := make([]string, hookBatchSize)
  310. refFullNames := make([]git.RefName, hookBatchSize)
  311. count := 0
  312. total := 0
  313. wasEmpty := false
  314. masterPushed := false
  315. results := make([]private.HookPostReceiveBranchResult, 0)
  316. scanner := bufio.NewScanner(os.Stdin)
  317. for scanner.Scan() {
  318. // TODO: support news feeds for wiki
  319. if isWiki {
  320. continue
  321. }
  322. fields := bytes.Fields(scanner.Bytes())
  323. if len(fields) != 3 {
  324. continue
  325. }
  326. fmt.Fprintf(out, ".")
  327. oldCommitIDs[count] = string(fields[0])
  328. newCommitIDs[count] = string(fields[1])
  329. refFullNames[count] = git.RefName(fields[2])
  330. commitID, _ := git.NewIDFromString(newCommitIDs[count])
  331. if refFullNames[count] == git.BranchPrefix+"master" && !commitID.IsZero() && count == total {
  332. masterPushed = true
  333. }
  334. count++
  335. total++
  336. if count >= hookBatchSize {
  337. fmt.Fprintf(out, " Processing %d references\n", count)
  338. hookOptions.OldCommitIDs = oldCommitIDs
  339. hookOptions.NewCommitIDs = newCommitIDs
  340. hookOptions.RefFullNames = refFullNames
  341. resp, extra := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
  342. if extra.HasError() {
  343. _ = dWriter.Close()
  344. hookPrintResults(results)
  345. return fail(ctx, extra.UserMsg, "HookPostReceive failed: %v", extra.Error)
  346. }
  347. wasEmpty = wasEmpty || resp.RepoWasEmpty
  348. results = append(results, resp.Results...)
  349. count = 0
  350. }
  351. }
  352. if count == 0 {
  353. if wasEmpty && masterPushed {
  354. // We need to tell the repo to reset the default branch to master
  355. extra := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
  356. if extra.HasError() {
  357. return fail(ctx, extra.UserMsg, "SetDefaultBranch failed: %v", extra.Error)
  358. }
  359. }
  360. fmt.Fprintf(out, "Processed %d references in total\n", total)
  361. _ = dWriter.Close()
  362. hookPrintResults(results)
  363. return nil
  364. }
  365. hookOptions.OldCommitIDs = oldCommitIDs[:count]
  366. hookOptions.NewCommitIDs = newCommitIDs[:count]
  367. hookOptions.RefFullNames = refFullNames[:count]
  368. fmt.Fprintf(out, " Processing %d references\n", count)
  369. resp, extra := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
  370. if resp == nil {
  371. _ = dWriter.Close()
  372. hookPrintResults(results)
  373. return fail(ctx, extra.UserMsg, "HookPostReceive failed: %v", extra.Error)
  374. }
  375. wasEmpty = wasEmpty || resp.RepoWasEmpty
  376. results = append(results, resp.Results...)
  377. fmt.Fprintf(out, "Processed %d references in total\n", total)
  378. if wasEmpty && masterPushed {
  379. // We need to tell the repo to reset the default branch to master
  380. extra := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
  381. if extra.HasError() {
  382. return fail(ctx, extra.UserMsg, "SetDefaultBranch failed: %v", extra.Error)
  383. }
  384. }
  385. _ = dWriter.Close()
  386. hookPrintResults(results)
  387. return nil
  388. }
  389. func hookPrintResults(results []private.HookPostReceiveBranchResult) {
  390. for _, res := range results {
  391. hookPrintResult(res.Message, res.Create, res.Branch, res.URL)
  392. }
  393. }
  394. func hookPrintResult(output, isCreate bool, branch, url string) {
  395. if !output {
  396. return
  397. }
  398. fmt.Fprintln(os.Stderr, "")
  399. if isCreate {
  400. fmt.Fprintf(os.Stderr, "Create a new pull request for '%s':\n", branch)
  401. fmt.Fprintf(os.Stderr, " %s\n", url)
  402. } else {
  403. fmt.Fprint(os.Stderr, "Visit the existing pull request:\n")
  404. fmt.Fprintf(os.Stderr, " %s\n", url)
  405. }
  406. fmt.Fprintln(os.Stderr, "")
  407. _ = os.Stderr.Sync()
  408. }
  409. func pushOptions() map[string]string {
  410. opts := make(map[string]string)
  411. if pushCount, err := strconv.Atoi(os.Getenv(private.GitPushOptionCount)); err == nil {
  412. for idx := 0; idx < pushCount; idx++ {
  413. opt := os.Getenv(fmt.Sprintf("GIT_PUSH_OPTION_%d", idx))
  414. kv := strings.SplitN(opt, "=", 2)
  415. if len(kv) == 2 {
  416. opts[kv[0]] = kv[1]
  417. }
  418. }
  419. }
  420. return opts
  421. }
  422. func runHookProcReceive(c *cli.Context) error {
  423. ctx, cancel := installSignals()
  424. defer cancel()
  425. setup(ctx, c.Bool("debug"))
  426. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  427. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  428. return fail(ctx, `Rejecting changes as Gitea environment not set.
  429. If you are pushing over SSH you must push with a key managed by
  430. Gitea or set your environment appropriately.`, "")
  431. }
  432. return nil
  433. }
  434. if !git.DefaultFeatures().SupportProcReceive {
  435. return fail(ctx, "No proc-receive support", "current git version doesn't support proc-receive.")
  436. }
  437. reader := bufio.NewReader(os.Stdin)
  438. repoUser := os.Getenv(repo_module.EnvRepoUsername)
  439. repoName := os.Getenv(repo_module.EnvRepoName)
  440. pusherID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPusherID), 10, 64)
  441. pusherName := os.Getenv(repo_module.EnvPusherName)
  442. // 1. Version and features negotiation.
  443. // S: PKT-LINE(version=1\0push-options atomic...) / PKT-LINE(version=1\n)
  444. // S: flush-pkt
  445. // H: PKT-LINE(version=1\0push-options...)
  446. // H: flush-pkt
  447. rs, err := readPktLine(ctx, reader, pktLineTypeData)
  448. if err != nil {
  449. return err
  450. }
  451. const VersionHead string = "version=1"
  452. var (
  453. hasPushOptions bool
  454. response = []byte(VersionHead)
  455. requestOptions []string
  456. )
  457. index := bytes.IndexByte(rs.Data, byte(0))
  458. if index >= len(rs.Data) {
  459. return fail(ctx, "Protocol: format error", "pkt-line: format error "+fmt.Sprint(rs.Data))
  460. }
  461. if index < 0 {
  462. if len(rs.Data) == 10 && rs.Data[9] == '\n' {
  463. index = 9
  464. } else {
  465. return fail(ctx, "Protocol: format error", "pkt-line: format error "+fmt.Sprint(rs.Data))
  466. }
  467. }
  468. if string(rs.Data[0:index]) != VersionHead {
  469. return fail(ctx, "Protocol: version error", "Received unsupported version: %s", string(rs.Data[0:index]))
  470. }
  471. requestOptions = strings.Split(string(rs.Data[index+1:]), " ")
  472. for _, option := range requestOptions {
  473. if strings.HasPrefix(option, "push-options") {
  474. response = append(response, byte(0))
  475. response = append(response, []byte("push-options")...)
  476. hasPushOptions = true
  477. }
  478. }
  479. response = append(response, '\n')
  480. _, err = readPktLine(ctx, reader, pktLineTypeFlush)
  481. if err != nil {
  482. return err
  483. }
  484. err = writeDataPktLine(ctx, os.Stdout, response)
  485. if err != nil {
  486. return err
  487. }
  488. err = writeFlushPktLine(ctx, os.Stdout)
  489. if err != nil {
  490. return err
  491. }
  492. // 2. receive commands from server.
  493. // S: PKT-LINE(<old-oid> <new-oid> <ref>)
  494. // S: ... ...
  495. // S: flush-pkt
  496. // # [receive push-options]
  497. // S: PKT-LINE(push-option)
  498. // S: ... ...
  499. // S: flush-pkt
  500. hookOptions := private.HookOptions{
  501. UserName: pusherName,
  502. UserID: pusherID,
  503. }
  504. hookOptions.OldCommitIDs = make([]string, 0, hookBatchSize)
  505. hookOptions.NewCommitIDs = make([]string, 0, hookBatchSize)
  506. hookOptions.RefFullNames = make([]git.RefName, 0, hookBatchSize)
  507. for {
  508. // note: pktLineTypeUnknow means pktLineTypeFlush and pktLineTypeData all allowed
  509. rs, err = readPktLine(ctx, reader, pktLineTypeUnknow)
  510. if err != nil {
  511. return err
  512. }
  513. if rs.Type == pktLineTypeFlush {
  514. break
  515. }
  516. t := strings.SplitN(string(rs.Data), " ", 3)
  517. if len(t) != 3 {
  518. continue
  519. }
  520. hookOptions.OldCommitIDs = append(hookOptions.OldCommitIDs, t[0])
  521. hookOptions.NewCommitIDs = append(hookOptions.NewCommitIDs, t[1])
  522. hookOptions.RefFullNames = append(hookOptions.RefFullNames, git.RefName(t[2]))
  523. }
  524. hookOptions.GitPushOptions = make(map[string]string)
  525. if hasPushOptions {
  526. for {
  527. rs, err = readPktLine(ctx, reader, pktLineTypeUnknow)
  528. if err != nil {
  529. return err
  530. }
  531. if rs.Type == pktLineTypeFlush {
  532. break
  533. }
  534. kv := strings.SplitN(string(rs.Data), "=", 2)
  535. if len(kv) == 2 {
  536. hookOptions.GitPushOptions[kv[0]] = kv[1]
  537. }
  538. }
  539. }
  540. // 3. run hook
  541. resp, extra := private.HookProcReceive(ctx, repoUser, repoName, hookOptions)
  542. if extra.HasError() {
  543. return fail(ctx, extra.UserMsg, "HookProcReceive failed: %v", extra.Error)
  544. }
  545. // 4. response result to service
  546. // # a. OK, but has an alternate reference. The alternate reference name
  547. // # and other status can be given in option directives.
  548. // H: PKT-LINE(ok <ref>)
  549. // H: PKT-LINE(option refname <refname>)
  550. // H: PKT-LINE(option old-oid <old-oid>)
  551. // H: PKT-LINE(option new-oid <new-oid>)
  552. // H: PKT-LINE(option forced-update)
  553. // H: ... ...
  554. // H: flush-pkt
  555. // # b. NO, I reject it.
  556. // H: PKT-LINE(ng <ref> <reason>)
  557. // # c. Fall through, let 'receive-pack' to execute it.
  558. // H: PKT-LINE(ok <ref>)
  559. // H: PKT-LINE(option fall-through)
  560. for _, rs := range resp.Results {
  561. if len(rs.Err) > 0 {
  562. err = writeDataPktLine(ctx, os.Stdout, []byte("ng "+rs.OriginalRef.String()+" "+rs.Err))
  563. if err != nil {
  564. return err
  565. }
  566. continue
  567. }
  568. if rs.IsNotMatched {
  569. err = writeDataPktLine(ctx, os.Stdout, []byte("ok "+rs.OriginalRef.String()))
  570. if err != nil {
  571. return err
  572. }
  573. err = writeDataPktLine(ctx, os.Stdout, []byte("option fall-through"))
  574. if err != nil {
  575. return err
  576. }
  577. continue
  578. }
  579. err = writeDataPktLine(ctx, os.Stdout, []byte("ok "+rs.OriginalRef))
  580. if err != nil {
  581. return err
  582. }
  583. err = writeDataPktLine(ctx, os.Stdout, []byte("option refname "+rs.Ref))
  584. if err != nil {
  585. return err
  586. }
  587. commitID, _ := git.NewIDFromString(rs.OldOID)
  588. if !commitID.IsZero() {
  589. err = writeDataPktLine(ctx, os.Stdout, []byte("option old-oid "+rs.OldOID))
  590. if err != nil {
  591. return err
  592. }
  593. }
  594. err = writeDataPktLine(ctx, os.Stdout, []byte("option new-oid "+rs.NewOID))
  595. if err != nil {
  596. return err
  597. }
  598. if rs.IsForcePush {
  599. err = writeDataPktLine(ctx, os.Stdout, []byte("option forced-update"))
  600. if err != nil {
  601. return err
  602. }
  603. }
  604. }
  605. err = writeFlushPktLine(ctx, os.Stdout)
  606. if err == nil {
  607. for _, res := range resp.Results {
  608. hookPrintResult(res.ShouldShowMessage, res.IsCreatePR, res.HeadBranch, res.URL)
  609. }
  610. }
  611. return err
  612. }
  613. // git PKT-Line api
  614. // pktLineType message type of pkt-line
  615. type pktLineType int64
  616. const (
  617. // UnKnow type
  618. pktLineTypeUnknow pktLineType = 0
  619. // flush-pkt "0000"
  620. pktLineTypeFlush pktLineType = iota
  621. // data line
  622. pktLineTypeData
  623. )
  624. // gitPktLine pkt-line api
  625. type gitPktLine struct {
  626. Type pktLineType
  627. Length uint64
  628. Data []byte
  629. }
  630. func readPktLine(ctx context.Context, in *bufio.Reader, requestType pktLineType) (*gitPktLine, error) {
  631. var (
  632. err error
  633. r *gitPktLine
  634. )
  635. // read prefix
  636. lengthBytes := make([]byte, 4)
  637. for i := 0; i < 4; i++ {
  638. lengthBytes[i], err = in.ReadByte()
  639. if err != nil {
  640. return nil, fail(ctx, "Protocol: stdin error", "Pkt-Line: read stdin failed : %v", err)
  641. }
  642. }
  643. r = new(gitPktLine)
  644. r.Length, err = strconv.ParseUint(string(lengthBytes), 16, 32)
  645. if err != nil {
  646. return nil, fail(ctx, "Protocol: format parse error", "Pkt-Line format is wrong :%v", err)
  647. }
  648. if r.Length == 0 {
  649. if requestType == pktLineTypeData {
  650. return nil, fail(ctx, "Protocol: format data error", "Pkt-Line format is wrong")
  651. }
  652. r.Type = pktLineTypeFlush
  653. return r, nil
  654. }
  655. if r.Length <= 4 || r.Length > 65520 || requestType == pktLineTypeFlush {
  656. return nil, fail(ctx, "Protocol: format length error", "Pkt-Line format is wrong")
  657. }
  658. r.Data = make([]byte, r.Length-4)
  659. for i := range r.Data {
  660. r.Data[i], err = in.ReadByte()
  661. if err != nil {
  662. return nil, fail(ctx, "Protocol: data error", "Pkt-Line: read stdin failed : %v", err)
  663. }
  664. }
  665. r.Type = pktLineTypeData
  666. return r, nil
  667. }
  668. func writeFlushPktLine(ctx context.Context, out io.Writer) error {
  669. l, err := out.Write([]byte("0000"))
  670. if err != nil || l != 4 {
  671. return fail(ctx, "Protocol: write error", "Pkt-Line response failed: %v", err)
  672. }
  673. return nil
  674. }
  675. func writeDataPktLine(ctx context.Context, out io.Writer, data []byte) error {
  676. hexchar := []byte("0123456789abcdef")
  677. hex := func(n uint64) byte {
  678. return hexchar[(n)&15]
  679. }
  680. length := uint64(len(data) + 4)
  681. tmp := make([]byte, 4)
  682. tmp[0] = hex(length >> 12)
  683. tmp[1] = hex(length >> 8)
  684. tmp[2] = hex(length >> 4)
  685. tmp[3] = hex(length)
  686. lr, err := out.Write(tmp)
  687. if err != nil || lr != 4 {
  688. return fail(ctx, "Protocol: write error", "Pkt-Line response failed: %v", err)
  689. }
  690. lr, err = out.Write(data)
  691. if err != nil || int(length-4) != lr {
  692. return fail(ctx, "Protocol: write error", "Pkt-Line response failed: %v", err)
  693. }
  694. return nil
  695. }