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.

backport.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package main
  4. import (
  5. "context"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "os"
  10. "os/exec"
  11. "os/signal"
  12. "path"
  13. "strconv"
  14. "strings"
  15. "syscall"
  16. "github.com/google/go-github/v45/github"
  17. "github.com/urfave/cli"
  18. "gopkg.in/yaml.v3"
  19. )
  20. const defaultVersion = "v1.18" // to backport to
  21. func main() {
  22. app := cli.NewApp()
  23. app.Name = "backport"
  24. app.Usage = "Backport provided PR-number on to the current or previous released version"
  25. app.Description = `Backport will look-up the PR in Gitea's git log and attempt to cherry-pick it on the current version`
  26. app.ArgsUsage = "<PR-to-backport>"
  27. app.Flags = []cli.Flag{
  28. cli.StringFlag{
  29. Name: "version",
  30. Usage: "Version branch to backport on to",
  31. },
  32. cli.StringFlag{
  33. Name: "upstream",
  34. Value: "origin",
  35. Usage: "Upstream remote for the Gitea upstream",
  36. },
  37. cli.StringFlag{
  38. Name: "release-branch",
  39. Value: "",
  40. Usage: "Release branch to backport on. Will default to release/<version>",
  41. },
  42. cli.StringFlag{
  43. Name: "cherry-pick",
  44. Usage: "SHA to cherry-pick as backport",
  45. },
  46. cli.StringFlag{
  47. Name: "backport-branch",
  48. Usage: "Backport branch to backport on to (default: backport-<pr>-<version>",
  49. },
  50. cli.StringFlag{
  51. Name: "remote",
  52. Value: "",
  53. Usage: "Remote for your fork of the Gitea upstream",
  54. },
  55. cli.StringFlag{
  56. Name: "fork-user",
  57. Value: "",
  58. Usage: "Forked user name on Github",
  59. },
  60. cli.BoolFlag{
  61. Name: "no-fetch",
  62. Usage: "Set this flag to prevent fetch of remote branches",
  63. },
  64. cli.BoolFlag{
  65. Name: "no-amend-message",
  66. Usage: "Set this flag to prevent automatic amendment of the commit message",
  67. },
  68. cli.BoolFlag{
  69. Name: "no-push",
  70. Usage: "Set this flag to prevent pushing the backport up to your fork",
  71. },
  72. cli.BoolFlag{
  73. Name: "no-xdg-open",
  74. Usage: "Set this flag to not use xdg-open to open the PR URL",
  75. },
  76. }
  77. cli.AppHelpTemplate = `NAME:
  78. {{.Name}} - {{.Usage}}
  79. USAGE:
  80. {{.HelpName}} {{if .VisibleFlags}}[options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}
  81. {{if len .Authors}}
  82. AUTHOR:
  83. {{range .Authors}}{{ . }}{{end}}
  84. {{end}}{{if .Commands}}
  85. OPTIONS:
  86. {{range .VisibleFlags}}{{.}}
  87. {{end}}{{end}}
  88. `
  89. app.Action = runBackport
  90. if err := app.Run(os.Args); err != nil {
  91. fmt.Fprintf(os.Stderr, "Unable to backport: %v\n", err)
  92. }
  93. }
  94. func runBackport(c *cli.Context) error {
  95. ctx, cancel := installSignals()
  96. defer cancel()
  97. version := c.String("version")
  98. if version == "" {
  99. version = readVersion()
  100. }
  101. if version == "" {
  102. version = defaultVersion
  103. }
  104. upstream := c.String("upstream")
  105. if upstream == "" {
  106. upstream = "origin"
  107. }
  108. forkUser := c.String("fork-user")
  109. remote := c.String("remote")
  110. if remote == "" && !c.Bool("--no-push") {
  111. var err error
  112. remote, forkUser, err = determineRemote(ctx, forkUser)
  113. if err != nil {
  114. return err
  115. }
  116. }
  117. upstreamReleaseBranch := c.String("release-branch")
  118. if upstreamReleaseBranch == "" {
  119. upstreamReleaseBranch = path.Join("release", version)
  120. }
  121. localReleaseBranch := path.Join(upstream, upstreamReleaseBranch)
  122. args := c.Args()
  123. if len(args) == 0 {
  124. return fmt.Errorf("no PR number provided\nProvide a PR number to backport")
  125. } else if len(args) != 1 {
  126. return fmt.Errorf("multiple PRs provided %v\nOnly a single PR can be backported at a time", args)
  127. }
  128. pr := args[0]
  129. backportBranch := c.String("backport-branch")
  130. if backportBranch == "" {
  131. backportBranch = "backport-" + pr + "-" + version
  132. }
  133. fmt.Printf("* Backporting %s to %s as %s\n", pr, localReleaseBranch, backportBranch)
  134. sha := c.String("cherry-pick")
  135. if sha == "" {
  136. var err error
  137. sha, err = determineSHAforPR(ctx, pr)
  138. if err != nil {
  139. return err
  140. }
  141. }
  142. if sha == "" {
  143. return fmt.Errorf("unable to determine sha for cherry-pick of %s", pr)
  144. }
  145. if !c.Bool("no-fetch") {
  146. if err := fetchRemoteAndMain(ctx, upstream, upstreamReleaseBranch); err != nil {
  147. return err
  148. }
  149. }
  150. if err := checkoutBackportBranch(ctx, backportBranch, localReleaseBranch); err != nil {
  151. return err
  152. }
  153. if err := cherrypick(ctx, sha); err != nil {
  154. return err
  155. }
  156. if !c.Bool("no-amend-message") {
  157. if err := amendCommit(ctx, pr); err != nil {
  158. return err
  159. }
  160. }
  161. if !c.Bool("no-push") {
  162. url := "https://github.com/go-gitea/gitea/compare/" + upstreamReleaseBranch + "..." + forkUser + ":" + backportBranch
  163. if err := gitPushUp(ctx, remote, backportBranch); err != nil {
  164. return err
  165. }
  166. if !c.Bool("no-xdg-open") {
  167. if err := xdgOpen(ctx, url); err != nil {
  168. return err
  169. }
  170. } else {
  171. fmt.Printf("* Navigate to %s to open PR\n", url)
  172. }
  173. }
  174. return nil
  175. }
  176. func xdgOpen(ctx context.Context, url string) error {
  177. fmt.Printf("* `xdg-open %s`\n", url)
  178. out, err := exec.CommandContext(ctx, "xdg-open", url).Output()
  179. if err != nil {
  180. fmt.Fprintf(os.Stderr, "%s", string(out))
  181. return fmt.Errorf("unable to xdg-open to %s: %w", url, err)
  182. }
  183. return nil
  184. }
  185. func gitPushUp(ctx context.Context, remote, backportBranch string) error {
  186. fmt.Printf("* `git push -u %s %s`\n", remote, backportBranch)
  187. out, err := exec.CommandContext(ctx, "git", "push", "-u", remote, backportBranch).Output()
  188. if err != nil {
  189. fmt.Fprintf(os.Stderr, "%s", string(out))
  190. return fmt.Errorf("unable to push up to %s: %w", remote, err)
  191. }
  192. return nil
  193. }
  194. func amendCommit(ctx context.Context, pr string) error {
  195. fmt.Printf("* Amending commit to prepend `Backport #%s` to body\n", pr)
  196. out, err := exec.CommandContext(ctx, "git", "log", "-1", "--pretty=format:%B").Output()
  197. if err != nil {
  198. fmt.Fprintf(os.Stderr, "%s", string(out))
  199. return fmt.Errorf("unable to get last log message: %w", err)
  200. }
  201. parts := strings.SplitN(string(out), "\n", 2)
  202. if len(parts) != 2 {
  203. return fmt.Errorf("unable to interpret log message:\n%s", string(out))
  204. }
  205. subject, body := parts[0], parts[1]
  206. if !strings.HasSuffix(subject, " (#"+pr+")") {
  207. subject = subject + " (#" + pr + ")"
  208. }
  209. out, err = exec.CommandContext(ctx, "git", "commit", "--amend", "-m", subject+"\n\nBackport #"+pr+"\n"+body).Output()
  210. if err != nil {
  211. fmt.Fprintf(os.Stderr, "%s", string(out))
  212. return fmt.Errorf("unable to amend last log message: %w", err)
  213. }
  214. return nil
  215. }
  216. func cherrypick(ctx context.Context, sha string) error {
  217. // Check if a CHERRY_PICK_HEAD exists
  218. if _, err := os.Stat(".git/CHERRY_PICK_HEAD"); err == nil {
  219. // Assume that we are in the middle of cherry-pick - continue it
  220. fmt.Println("* Attempting git cherry-pick --continue")
  221. out, err := exec.CommandContext(ctx, "git", "cherry-pick", "--continue").Output()
  222. if err != nil {
  223. fmt.Fprintf(os.Stderr, "git cherry-pick --continue failed:\n%s\n", string(out))
  224. return fmt.Errorf("unable to continue cherry-pick: %w", err)
  225. }
  226. return nil
  227. }
  228. fmt.Printf("* Attempting git cherry-pick %s\n", sha)
  229. out, err := exec.CommandContext(ctx, "git", "cherry-pick", sha).Output()
  230. if err != nil {
  231. fmt.Fprintf(os.Stderr, "git cherry-pick %s failed:\n%s\n", sha, string(out))
  232. return fmt.Errorf("git cherry-pick %s failed: %w", sha, err)
  233. }
  234. return nil
  235. }
  236. func checkoutBackportBranch(ctx context.Context, backportBranch, releaseBranch string) error {
  237. out, err := exec.CommandContext(ctx, "git", "branch", "--show-current").Output()
  238. if err != nil {
  239. return fmt.Errorf("unable to check current branch %w", err)
  240. }
  241. currentBranch := strings.TrimSpace(string(out))
  242. fmt.Printf("* Current branch is %s\n", currentBranch)
  243. if currentBranch == backportBranch {
  244. fmt.Printf("* Current branch is %s - not checking out\n", currentBranch)
  245. return nil
  246. }
  247. if _, err := exec.CommandContext(ctx, "git", "rev-list", "-1", backportBranch).Output(); err == nil {
  248. fmt.Printf("* Branch %s already exists. Checking it out...\n", backportBranch)
  249. return exec.CommandContext(ctx, "git", "checkout", "-f", backportBranch).Run()
  250. }
  251. fmt.Printf("* `git checkout -b %s %s`\n", backportBranch, releaseBranch)
  252. return exec.CommandContext(ctx, "git", "checkout", "-b", backportBranch, releaseBranch).Run()
  253. }
  254. func fetchRemoteAndMain(ctx context.Context, remote, releaseBranch string) error {
  255. fmt.Printf("* `git fetch %s main`\n", remote)
  256. out, err := exec.CommandContext(ctx, "git", "fetch", remote, "main").Output()
  257. if err != nil {
  258. fmt.Println(string(out))
  259. return fmt.Errorf("unable to fetch %s from %s: %w", "main", remote, err)
  260. }
  261. fmt.Println(string(out))
  262. fmt.Printf("* `git fetch %s %s`\n", remote, releaseBranch)
  263. out, err = exec.CommandContext(ctx, "git", "fetch", remote, releaseBranch).Output()
  264. if err != nil {
  265. fmt.Println(string(out))
  266. return fmt.Errorf("unable to fetch %s from %s: %w", releaseBranch, remote, err)
  267. }
  268. fmt.Println(string(out))
  269. return nil
  270. }
  271. func determineRemote(ctx context.Context, forkUser string) (string, string, error) {
  272. out, err := exec.CommandContext(ctx, "git", "remote", "-v").Output()
  273. if err != nil {
  274. fmt.Fprintf(os.Stderr, "Unable to list git remotes:\n%s\n", string(out))
  275. return "", "", fmt.Errorf("unable to determine forked remote: %w", err)
  276. }
  277. lines := strings.Split(string(out), "\n")
  278. for _, line := range lines {
  279. fields := strings.Split(line, "\t")
  280. name, remote := fields[0], fields[1]
  281. // only look at pushers
  282. if !strings.HasSuffix(remote, " (push)") {
  283. continue
  284. }
  285. // only look at github.com pushes
  286. if !strings.Contains(remote, "github.com") {
  287. continue
  288. }
  289. // ignore go-gitea/gitea
  290. if strings.Contains(remote, "go-gitea/gitea") {
  291. continue
  292. }
  293. if !strings.Contains(remote, forkUser) {
  294. continue
  295. }
  296. if strings.HasPrefix(remote, "git@github.com:") {
  297. forkUser = strings.TrimPrefix(remote, "git@github.com:")
  298. } else if strings.HasPrefix(remote, "https://github.com/") {
  299. forkUser = strings.TrimPrefix(remote, "https://github.com/")
  300. } else if strings.HasPrefix(remote, "https://www.github.com/") {
  301. forkUser = strings.TrimPrefix(remote, "https://www.github.com/")
  302. } else if forkUser == "" {
  303. return "", "", fmt.Errorf("unable to extract forkUser from remote %s: %s", name, remote)
  304. }
  305. idx := strings.Index(forkUser, "/")
  306. if idx >= 0 {
  307. forkUser = forkUser[:idx]
  308. }
  309. return name, forkUser, nil
  310. }
  311. return "", "", fmt.Errorf("unable to find appropriate remote in:\n%s", string(out))
  312. }
  313. func readVersion() string {
  314. bs, err := os.ReadFile("docs/config.yaml")
  315. if err != nil {
  316. if err == os.ErrNotExist {
  317. log.Println("`docs/config.yaml` not present")
  318. return ""
  319. }
  320. fmt.Fprintf(os.Stderr, "Unable to read `docs/config.yaml`: %v\n", err)
  321. return ""
  322. }
  323. type params struct {
  324. Version string
  325. }
  326. type docConfig struct {
  327. Params params
  328. }
  329. dc := &docConfig{}
  330. if err := yaml.Unmarshal(bs, dc); err != nil {
  331. fmt.Fprintf(os.Stderr, "Unable to read `docs/config.yaml`: %v\n", err)
  332. return ""
  333. }
  334. if dc.Params.Version == "" {
  335. fmt.Fprintf(os.Stderr, "No version in `docs/config.yaml`")
  336. return ""
  337. }
  338. version := dc.Params.Version
  339. if version[0] != 'v' {
  340. version = "v" + version
  341. }
  342. split := strings.SplitN(version, ".", 3)
  343. return strings.Join(split[:2], ".")
  344. }
  345. func determineSHAforPR(ctx context.Context, prStr string) (string, error) {
  346. prNum, err := strconv.Atoi(prStr)
  347. if err != nil {
  348. return "", err
  349. }
  350. client := github.NewClient(http.DefaultClient)
  351. pr, _, err := client.PullRequests.Get(ctx, "go-gitea", "gitea", prNum)
  352. if err != nil {
  353. return "", err
  354. }
  355. if pr.Merged == nil || !*pr.Merged {
  356. return "", fmt.Errorf("PR #%d is not yet merged - cannot determine sha to backport", prNum)
  357. }
  358. if pr.MergeCommitSHA != nil {
  359. return *pr.MergeCommitSHA, nil
  360. }
  361. return "", nil
  362. }
  363. func installSignals() (context.Context, context.CancelFunc) {
  364. ctx, cancel := context.WithCancel(context.Background())
  365. go func() {
  366. // install notify
  367. signalChannel := make(chan os.Signal, 1)
  368. signal.Notify(
  369. signalChannel,
  370. syscall.SIGINT,
  371. syscall.SIGTERM,
  372. )
  373. select {
  374. case <-signalChannel:
  375. case <-ctx.Done():
  376. }
  377. cancel()
  378. signal.Reset()
  379. }()
  380. return ctx, cancel
  381. }