package cli import ( "context" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" "sync" "github.com/spf13/cobra" "tangled.org/rockorager.dev/knit/internal/git" "tangled.org/rockorager.dev/knit/internal/tangled" ) func newPRCmd(app *App) *cobra.Command { cmd := &cobra.Command{ Use: "pr ", Aliases: []string{"pull"}, Short: "Manage pull requests", Long: `Manage pull requests. A pull request on Tangled is a series of immutable rounds. Each round records a base and a head commit. To update a pull request, push to its branch and run ` + "`knit pr resubmit`" + ` to add a round.`, } addRepoFlag(app, cmd) cmd.AddCommand( newPRCreateCmd(app), newTicketListCmd(app, pullKind), newPRViewCmd(app), newPRCheckoutCmd(app), newPRDiffCmd(app), newPRChecksCmd(app), newPRResubmitCmd(app), newPRMergeCmd(app), newTicketCommentCmd(app, pullKind), newTicketStateCmd(app, pullKind, "close", "Close a pull request", tangled.StateClosed), newTicketStateCmd(app, pullKind, "reopen", "Reopen a pull request", tangled.StateOpen), newTicketEditCmd(app, pullKind), ) return cmd } // pushTarget is where a local branch's commits are pushed: a git remote and // the Tangled repository behind it. type pushTarget struct { remote *git.Remote repo *tangled.Repo } // headSource finds where branch is pushed to: its configured push remote, // else origin, which in a fork's clone is the fork, else the remote of the // base repository. func (a *App) headSource(ctx context.Context, branch string, base *tangled.Repo, baseRemote *git.Remote) (*pushTarget, error) { remotes, err := git.Remotes() if err != nil { return nil, err } find := func(name string) *git.Remote { for _, r := range remotes { if r.Name == name { return r } } return nil } if name := git.PushRemote(branch); name != "" { if r := find(name); r != nil { repo, err := a.repoForRemote(ctx, r) if err != nil { return nil, fmt.Errorf("branch %s pushes to %s: %w", branch, name, err) } return &pushTarget{r, repo}, nil } } if r := find("origin"); r != nil { if repo, err := a.repoForRemote(ctx, r); err == nil { return &pushTarget{r, repo}, nil } } if baseRemote != nil { return &pushTarget{baseRemote, base}, nil } return nil, fmt.Errorf("can't tell where to push %s; add a remote for %s or set the branch's upstream", branch, base.FullName()) } // pushBranch pushes branch to the remote unless the remote already has it at // the same commit. func (a *App) pushBranch(target *pushTarget, branch, head string) error { remoteHead, _ := git.Output("ls-remote", target.remote.Name, "refs/heads/"+branch) if f := strings.Fields(remoteHead); len(f) > 0 && f[0] == head { return nil } a.Infof("Pushing %s to %s (%s)\n", branch, target.remote.Name, target.repo.FullName()) return git.Run("push", "--quiet", "--set-upstream", target.remote.Name, branch) } // mergeBase fetches the target branch of the base repository and returns the // merge base of it and head. func (a *App) mergeBase(base *tangled.Repo, baseRemote *git.Remote, target, head string) (string, error) { from := base.CloneURL("https") if baseRemote != nil { from = baseRemote.Name } if _, err := git.Output("fetch", "--quiet", from, "refs/heads/"+target); err != nil { return "", fmt.Errorf("fetching %s: %w", target, err) } targetHead, err := git.RevParse("FETCH_HEAD") if err != nil { return "", err } mb, err := git.Output("merge-base", targetHead, head) if err != nil { return "", fmt.Errorf("%s has no history in common with %s", target, head) } if mb == head { return "", fmt.Errorf("no commits between %s and %s", target, head) } return mb, nil } func newPRCreateCmd(app *App) *cobra.Command { var ( title, body, bodyFile, baseBranch, headBranch string fill, web bool ) cmd := &cobra.Command{ Use: "create", Short: "Create a pull request", Long: `Create a pull request from a branch. The head branch (the current branch by default) is pushed to the remote it tracks, or to the base repository's remote, if the remote doesn't have it yet. The pull request's first round covers the commits between the merge base with the base branch and the head of the branch. Without --title or --fill, knit prompts for the title and body when run interactively. --fill uses the commit message when there is one commit, and the branch name otherwise.`, Example: ` knit pr create --fill knit pr create --base develop --title "Add retries" --body "..." knit pr create --web`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() base, baseRemote, err := app.baseRepoAndRemote(ctx) if err != nil { return err } if baseBranch == "" { baseBranch = base.DefaultBranch } if headBranch == "" { if headBranch, err = git.CurrentBranch(); err != nil { return err } } c := app.Client() if web { q := url.Values{"sourceBranch": {headBranch}, "targetBranch": {baseBranch}} return app.browse(c.WebURL(base, "pulls", "new") + "?" + q.Encode()) } if err := app.requireAuth(ctx); err != nil { return err } source, err := app.headSource(ctx, headBranch, base, baseRemote) if err != nil { return err } if source.repo.DID == base.DID && headBranch == baseBranch { return fmt.Errorf("head branch %s is the base branch; check out the branch with your changes", headBranch) } head, err := git.RevParse(headBranch) if err != nil { return fmt.Errorf("unknown branch %s", headBranch) } mb, err := app.mergeBase(base, baseRemote, baseBranch, head) if err != nil { return err } text, given, err := app.readBody(cmd, body, bodyFile) if err != nil { return err } if fill || (title == "" && app.interactive()) { t, b := fillFromCommits(mb, head, headBranch) if title == "" { title = t } if !given { text = b } } if !fill && app.interactive() && !cmd.Flags().Changed("title") { app.Infof("Creating pull request for %s into %s in %s\n\n", app.Cyan(headBranch), app.Cyan(baseBranch), app.Bold(base.FullName())) if err := app.promptInput("Title", "", &title); err != nil { return err } if !given { ok, err := app.promptConfirm("Edit the body in your editor?") if err != nil { return err } if ok { if text, err = app.editText(text, "PULL.md"); err != nil { return err } } } } if strings.TrimSpace(title) == "" { return errors.New("--title or --fill is required when not running interactively") } if err := app.pushBranch(source, headBranch, head); err != nil { return err } w, err := c.OpenPull(ctx, base, tangled.TicketInput{Title: strings.TrimSpace(title), Body: strings.TrimSpace(text), TargetBranch: baseBranch}, tangled.PatchInput{Base: mb, Head: head, SourceRepo: source.repo.DID, SourceBranch: headBranch}) if err != nil { return err } app.settle(ctx, w) app.Printf("%s\n", app.ticketURL(base, pullKind, tangled.RkeyFromURI(w.URI))) return nil }, } cmd.Flags().StringVarP(&title, "title", "t", "", "Title of the pull request") cmd.Flags().StringVarP(&body, "body", "b", "", "Body of the pull request") cmd.Flags().StringVarP(&bodyFile, "body-file", "F", "", "Read the body from `file` (use \"-\" for standard input)") cmd.Flags().StringVarP(&baseBranch, "base", "B", "", "The branch to merge into (default: the repository's default branch)") cmd.Flags().StringVarP(&headBranch, "head", "H", "", "The branch with your changes (default: the current branch)") cmd.Flags().BoolVarP(&fill, "fill", "f", false, "Use commit info for the title and body") cmd.Flags().BoolVarP(&web, "web", "w", false, "Open the browser to create a pull request") return cmd } // fillFromCommits suggests a title and body from the commits in base..head. func fillFromCommits(base, head, branch string) (string, string) { out, err := git.Output("rev-list", base+".."+head) if err == nil && len(strings.Fields(out)) == 1 { subject, _ := git.Output("log", "-1", "--format=%s", head) msgBody, _ := git.Output("log", "-1", "--format=%b", head) return subject, msgBody } title := strings.NewReplacer("-", " ", "_", " ").Replace(branch[strings.LastIndex(branch, "/")+1:]) log, _ := git.Output("log", "--reverse", "--format=- %s", base+".."+head) return capitalize(title), log } // pullArg resolves a pull request argument, or with no argument, the open // pull request whose source branch is the current branch. func (a *App) pullArg(ctx context.Context, args []string) (string, *tangled.Repo, error) { if len(args) == 1 { return a.ticketRepo(ctx, args[0]) } repo, err := a.baseRepo(ctx) if err != nil { return "", nil, err } branch, err := git.CurrentBranch() if err != nil { return "", nil, err } number, err := a.findPullForBranch(ctx, repo, branch) return number, repo, err } // findPullForBranch finds an open pull request whose latest round came from // branch, preferring ones you opened. func (a *App) findPullForBranch(ctx context.Context, repo *tangled.Repo, branch string) (string, error) { c := a.Client() opts := tangled.ListTicketsOptions{Pulls: true, State: "open", Limit: 100} if me, err := c.Me(ctx); err == nil { opts.Author = me } pulls, err := c.ListTickets(ctx, repo.DID, opts) if err != nil { return "", err } var ( mu sync.Mutex found []string wg sync.WaitGroup ) for _, p := range pulls { wg.Add(1) go func() { defer wg.Done() patches, err := c.ListPatches(ctx, p.URI) if err != nil || len(patches) == 0 || patches[len(patches)-1].SourceBranch != branch { return } mu.Lock() found = append(found, p.Number) mu.Unlock() }() } wg.Wait() switch len(found) { case 0: return "", fmt.Errorf("no open pull request found for branch %s; pass a number", branch) case 1: return found[0], nil } return "", fmt.Errorf("several open pull requests come from branch %s (#%s); pass a number", branch, strings.Join(found, ", #")) } // pull fetches a pull request and its rounds. func (a *App) pull(ctx context.Context, repo *tangled.Repo, number string) (*tangled.Ticket, []*tangled.Patch, error) { c := a.Client() t, err := c.GetTicket(ctx, repo.DID, number) if err != nil { return nil, nil, err } if !t.IsPull() { return nil, nil, fmt.Errorf("#%s is an issue, not a pull request", number) } patches, err := c.ListPatches(ctx, t.URI) if err != nil { return nil, nil, err } return t, patches, nil } // latestRound returns the newest round of a pull request. func latestRound(number string, patches []*tangled.Patch) (*tangled.Patch, error) { if len(patches) == 0 { // pull requests from before branch-based rounds have none return nil, fmt.Errorf("pull request #%s has no rounds; it predates branch-based pull requests", number) } return patches[len(patches)-1], nil } func newPRViewCmd(app *App) *cobra.Command { var comments, web, asJSON bool cmd := &cobra.Command{ Use: "view []", Short: "View a pull request", Long: "View a pull request. With no argument, shows the open pull request for the current branch.", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() number, repo, err := app.pullArg(ctx, args) if err != nil { return err } url := app.ticketURL(repo, pullKind, number) if web { return app.browse(url) } c := app.Client() t, patches, err := app.pull(ctx, repo, number) if err != nil { return err } app.labelNames(ctx, repo, t) var cms []*tangled.Comment if comments || asJSON { if cms, err = c.ListComments(ctx, t.URI); err != nil { return err } } if asJSON { return app.PrintJSON(struct { *tangled.Ticket Rounds []*tangled.Patch `json:"rounds"` CommentList []*tangled.Comment `json:"commentList"` }{t, patches, cms}) } extra := []string{fmt.Sprintf("%s %s", app.Gray("Into"), app.Cyan(t.TargetBranch))} if len(patches) > 0 { latest, err := latestRound(number, patches) if err != nil { return err } from := latest.SourceBranch if latest.SourceRepo != "" && latest.SourceRepo != repo.DID { if src, err := c.GetRepoByDID(ctx, latest.SourceRepo); err == nil { from = src.FullName() + ":" + from } else { from = latest.SourceRepo + ":" + from } } extra[0] += fmt.Sprintf(" %s %s", app.Gray("from"), app.Cyan(from)) extra = append(extra, fmt.Sprintf("%s %d (latest %s..%s)", app.Gray("Rounds:"), len(patches), short(latest.Base), short(latest.Head))) } app.printTicket(t, pullKind, extra) if comments { app.printComments(cms) } else if t.Comments > 0 { app.Printf("%s\n\n", app.Gray(fmt.Sprintf("Use --comments to view %s.", countNoun(t.Comments, "comment")))) } app.Printf("%s\n", app.Gray("View this pull request on Tangled: "+url)) return nil }, } cmd.Flags().BoolVarP(&comments, "comments", "c", false, "Show comments") cmd.Flags().BoolVarP(&web, "web", "w", false, "Open the pull request in the browser") cmd.Flags().BoolVar(&asJSON, "json", false, "Output JSON") return cmd } func short(oid string) string { if len(oid) > 8 { return oid[:8] } return oid } func newPRCheckoutCmd(app *App) *cobra.Command { var branch string var force bool cmd := &cobra.Command{ Use: "checkout ", Aliases: []string{"co"}, Short: "Check out a pull request in git", Long: `Check out the head commit of a pull request's latest round. The local branch is named after the pull request's source branch unless --branch is given. An existing branch is fast-forwarded, or reset with --force.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() number, repo, err := app.ticketRepo(ctx, args[0]) if err != nil { return err } _, patches, err := app.pull(ctx, repo, number) if err != nil { return err } latest, err := latestRound(number, patches) if err != nil { return err } src := repo if latest.SourceRepo != "" && latest.SourceRepo != repo.DID { if src, err = app.Client().GetRepoByDID(ctx, latest.SourceRepo); err != nil { return fmt.Errorf("looking up the source repository: %w", err) } } if !git.HasCommit(latest.Head) { fetchURL := src.CloneURL("https") if r := app.remoteFor(src); r != nil { fetchURL = r.Name } // the branch may have moved on since the round was submitted; // fetching it still brings the round's commit unless it was // force-pushed away, so fall back to asking for the commit if latest.SourceBranch != "" { _, _ = git.Output("fetch", "--quiet", fetchURL, "refs/heads/"+latest.SourceBranch) } if !git.HasCommit(latest.Head) { if _, err := git.Output("fetch", "--quiet", fetchURL, latest.Head); err != nil { return fmt.Errorf("fetching %s from %s: %w", short(latest.Head), src.FullName(), err) } } } if branch == "" { branch = latest.SourceBranch } if branch == "" { branch = "pr-" + number } if _, err := git.RevParse("refs/heads/" + branch); err != nil { return git.Run("checkout", "--quiet", "-b", branch, latest.Head) } if err := git.Run("checkout", "--quiet", branch); err != nil { return err } if force { return git.Run("reset", "--quiet", "--hard", latest.Head) } return git.Run("merge", "--quiet", "--ff-only", latest.Head) }, } cmd.Flags().StringVarP(&branch, "branch", "b", "", "Local branch name to use") cmd.Flags().BoolVarP(&force, "force", "f", false, "Reset an existing local branch to the pull request's head") return cmd } func newPRDiffCmd(app *App) *cobra.Command { var round int var color string cmd := &cobra.Command{ Use: "diff []", Short: "View the changes in a pull request", Long: `Print a round of a pull request as a patch series in git format-patch form, which git am can apply. Rounds count from 0; the latest round is the default.`, Example: ` knit pr diff 12 knit pr diff 12 --round 0 knit pr diff 12 | git am`, Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() number, repo, err := app.pullArg(ctx, args) if err != nil { return err } version := "latest" if cmd.Flags().Changed("round") { version = strconv.Itoa(round) } u := fmt.Sprintf("%s/%s/%s/pulls/%s/%s.patch", strings.TrimRight(app.Config.Get("appview"), "/"), repo.Owner, repo.Name, number, version) req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { return err } resp, err := app.Client().HTTP.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("fetching the patch for #%s: HTTP %d", number, resp.StatusCode) } useColor := color == "always" || (color == "auto" && app.colorEnabled()) if !useColor { _, err = io.Copy(app.Out, resp.Body) return err } data, err := io.ReadAll(resp.Body) if err != nil { return err } for _, line := range strings.SplitAfter(string(data), "\n") { switch { case strings.HasPrefix(line, "+++"), strings.HasPrefix(line, "---"), strings.HasPrefix(line, "diff --git"): app.Printf("\x1b[1m%s\x1b[0m", line) case strings.HasPrefix(line, "+"): app.Printf("\x1b[32m%s\x1b[0m", line) case strings.HasPrefix(line, "-"): app.Printf("\x1b[31m%s\x1b[0m", line) case strings.HasPrefix(line, "@@"): app.Printf("\x1b[36m%s\x1b[0m", line) default: app.Printf("%s", line) } } return nil }, } cmd.Flags().IntVarP(&round, "round", "r", 0, "Round to show (default: the latest)") cmd.Flags().StringVar(&color, "color", "auto", "Use color in diff output: always, never, auto") return cmd } func newPRResubmitCmd(app *App) *cobra.Command { cmd := &cobra.Command{ Use: "resubmit []", Short: "Add a round to a pull request from its branch", Long: `Push the pull request's source branch and submit it as a new round. Rounds are immutable, so pushing to the branch alone doesn't change what reviewers see; resubmitting does. The new round's base is the merge base with the current target branch, so rebasing onto the target is picked up too. With no argument, resubmits the open pull request for the current branch.`, Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() number, base, err := app.pullArg(ctx, args) if err != nil { return err } t, patches, err := app.pull(ctx, base, number) if err != nil { return err } if t.State != tangled.StateOpen { return fmt.Errorf("pull request #%s is %s", number, t.State) } latest, err := latestRound(number, patches) if err != nil { return err } branch := latest.SourceBranch if branch == "" { if branch, err = git.CurrentBranch(); err != nil { return err } } head, err := git.RevParse("refs/heads/" + branch) if err != nil { return fmt.Errorf("no local branch %s; check it out with `knit pr checkout %s`", branch, number) } if head == latest.Head { return fmt.Errorf("%s is still at %s, the head of the latest round; commit or rebase first", branch, short(head)) } baseRemote := app.remoteFor(base) source, err := app.headSource(ctx, branch, base, baseRemote) if err != nil { return err } if latest.SourceRepo != "" && source.repo.DID != latest.SourceRepo { return fmt.Errorf("branch %s pushes to %s, but the pull request comes from another repository", branch, source.repo.FullName()) } mb, err := app.mergeBase(base, baseRemote, t.TargetBranch, head) if err != nil { return err } if err := app.pushBranch(source, branch, head); err != nil { return err } w, err := app.Client().SubmitPatch(ctx, base, number, tangled.PatchInput{ Base: mb, Head: head, SourceRepo: source.repo.DID, SourceBranch: branch, }) if err != nil { return err } app.settle(ctx, w) app.Success("Submitted round %d of #%s", len(patches)+1, number) app.Printf("%s\n", app.ticketURL(base, pullKind, number)) return nil }, } return cmd } func newPRMergeCmd(app *App) *cobra.Command { var deleteBranch bool cmd := &cobra.Command{ Use: "merge []", Short: "Merge a pull request", Long: `Merge the latest round of a pull request into its target branch. Tangled merges by rebasing the round's commits onto the target branch.`, Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() number, repo, err := app.pullArg(ctx, args) if err != nil { return err } t, patches, err := app.pull(ctx, repo, number) if err != nil { return err } if t.State != tangled.StateOpen { return fmt.Errorf("pull request #%s is %s", number, app.stateLabel(t.State, true)) } latest, err := latestRound(number, patches) if err != nil { return err } c := app.Client() if err := c.MergePull(ctx, repo, t, latest.Head); err != nil { return err } app.Success("Merged pull request #%s (%s) into %s", number, t.Title, t.TargetBranch) if deleteBranch && latest.SourceBranch != "" { src := repo if latest.SourceRepo != "" && latest.SourceRepo != repo.DID { if src, err = c.GetRepoByDID(ctx, latest.SourceRepo); err != nil { return err } } if err := c.DeleteBranch(ctx, src, latest.SourceBranch); err != nil { return fmt.Errorf("deleting branch %s: %w", latest.SourceBranch, err) } app.Success("Deleted branch %s", latest.SourceBranch) } return nil }, } cmd.Flags().BoolVarP(&deleteBranch, "delete-branch", "d", false, "Delete the source branch after merging") return cmd }