Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

hook.go 20KB

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