Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue #409 - WIP #451

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added cmd/av/av
Binary file not shown.
23 changes: 15 additions & 8 deletions cmd/av/stack_restack.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ import (
)

var stackRestackFlags struct {
All bool
Current bool
Abort bool
Continue bool
Skip bool
DryRun bool
All bool
Current bool
Abort bool
Continue bool
Skip bool
DryRun bool
Interactive bool
}

var stackRestackCmd = &cobra.Command{
Expand Down Expand Up @@ -77,12 +78,13 @@ func (vm *stackRestackViewModel) Init() tea.Cmd {
vm.restackModel.Continue = stackRestackFlags.Continue
vm.restackModel.Skip = stackRestackFlags.Skip
vm.restackModel.DryRun = stackRestackFlags.DryRun
vm.restackModel.Interactive = stackRestackFlags.Interactive
return vm.restackModel.Init()
}

func (vm *stackRestackViewModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case *sequencerui.RestackProgress, spinner.TickMsg:
case *git.RebaseResultMsg, *sequencerui.RestackProgress, spinner.TickMsg:
var cmd tea.Cmd
vm.restackModel, cmd = vm.restackModel.Update(msg)
return vm, cmd
Expand Down Expand Up @@ -191,6 +193,7 @@ func (vm *stackRestackViewModel) createState() (*sequencerui.RestackState, error
currentBranchRef,
stackRestackFlags.All,
stackRestackFlags.Current,
stackRestackFlags.Interactive,
)
if err != nil {
return nil, err
Expand Down Expand Up @@ -224,6 +227,10 @@ func init() {
&stackRestackFlags.DryRun, "dry-run", false,
"show the list of branches that will be rebased without actually rebasing them",
)
stackRestackCmd.Flags().BoolVar(
&stackRestackFlags.Interactive, "interactive", false,
"run the rebase command with interactive option",
)

stackRestackCmd.MarkFlagsMutuallyExclusive("continue", "abort", "skip")
stackRestackCmd.MarkFlagsMutuallyExclusive("continue", "abort", "skip", "interactive")
}
4 changes: 3 additions & 1 deletion internal/git/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ func (r *Repo) Run(opts *RunOpts) (*Output, error) {
cmd.Dir = r.repoDir
r.log.Debugf("git %s", opts.Args)
var stdout, stderr bytes.Buffer
var err error
if opts.Interactive {
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
Expand All @@ -192,7 +193,8 @@ func (r *Repo) Run(opts *RunOpts) (*Output, error) {
cmd.Stdin = opts.Stdin
}
cmd.Env = append(os.Environ(), opts.Env...)
err := cmd.Run()
err = cmd.Run()

var exitError *exec.ExitError
if err != nil && !errors.As(err, &exitError) {
return nil, errors.Wrapf(err, "git %s", opts.Args)
Expand Down
115 changes: 109 additions & 6 deletions internal/git/rebase.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package git

import (
"bytes"
"os"
"os/exec"
"regexp"
"strings"

"emperror.dev/errors"
tea "github.com/charmbracelet/bubbletea"
"github.com/sirupsen/logrus"
)

Expand All @@ -19,6 +24,9 @@ type RebaseOpts struct {
// Optional (mutually exclusive with all other options)
Skip bool
// Optional
// If set, this is the rebase will be run with interactive option
Interactive bool
// Optional
// If set, use `git rebase --onto <upstream> ...`
Onto string
// Optional
Expand All @@ -29,7 +37,6 @@ type RebaseOpts struct {

func (r *Repo) Rebase(opts RebaseOpts) (*Output, error) {
// TODO: probably move the parseRebaseOutput logic in sync to here

args := []string{"rebase"}
if opts.Continue {
return r.Run(&RunOpts{
Expand All @@ -49,6 +56,10 @@ func (r *Repo) Rebase(opts RebaseOpts) (*Output, error) {
Args: []string{"rebase", "--skip"},
})
}

if opts.Interactive {
args = append(args, "-i")
}
if opts.Onto != "" {
args = append(args, "--onto", opts.Onto)
}
Expand All @@ -57,7 +68,100 @@ func (r *Repo) Rebase(opts RebaseOpts) (*Output, error) {
args = append(args, opts.Branch)
}

return r.Run(&RunOpts{Args: args})
return r.Run(&RunOpts{
Args: args,
Interactive: opts.Interactive,
})
}

type RebaseResultMsg struct {
Upstream string
OnTo string
Branch string
ExitCode int
Stderr string
}

func (r *Repo) RebaseInteractive(upstream, onto, branch string) tea.Cmd {
args := []string{"rebase", "-i"}
if onto != "" {
args = append(args, "--onto", onto)
}
args = append(args, upstream)
if branch != "" {
args = append(args, branch)
}
cmd := exec.Command("git", args...)
cmd.Dir = r.repoDir
r.log.Debugf("git %s", args)
var stderr bytes.Buffer
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = &stderr
return tea.ExecProcess(cmd, func(err error) tea.Msg {
if err != nil {
var exitError *exec.ExitError
if !errors.As(err, &exitError) {
return errors.Wrapf(err, "git %s", args)
}
return &RebaseResultMsg{
Upstream: upstream,
OnTo: onto,
Branch: branch,
ExitCode: exitError.ExitCode(),
Stderr: stderr.String(),
}
}
return &RebaseResultMsg{
Upstream: upstream,
OnTo: onto,
Branch: branch,
Stderr: stderr.String(),
}
})
}

func (r *Repo) InteractiveRebaseParse(msg *RebaseResultMsg) *RebaseResult {
stderr := msg.Stderr

if msg.ExitCode == 0 {
if strings.Contains(stderr, "Successfully rebased") {
return &RebaseResult{Status: RebaseUpdated}
}

logrus.WithFields(logrus.Fields{
"stderr": stderr,
}).Warnf("unexpected output from git rebase with exit code 0 (assuming rebase was successful)")
return &RebaseResult{Status: RebaseUpdated}
}

var status RebaseStatus
lowerStderr := strings.ToLower(stderr)
switch {
case strings.Contains(lowerStderr, "no rebase in progress"):
status = RebaseNotInProgress
case strings.Contains(lowerStderr, "could not apply"):
status = RebaseConflict
default:
logrus.WithField("exit_code", msg.ExitCode).
Warn("unexpected output from git rebase with non-zero exit code (assuming rebase had conflicts): ", stderr)
return &RebaseResult{
Status: RebaseConflict,
Hint: stderr,
}
}

hint := normalizeRebaseHint(msg.Stderr)
headline := ""
errorMatches := errorMatchRegex.FindStringSubmatch(hint)
if len(errorMatches) > 1 {
headline = errorMatches[1]
}
return &RebaseResult{
Status: status,
Hint: normalizeRebaseHint(msg.Stderr),
ErrorHeadline: headline,
}
}

// RebaseParse runs a `git rebase` and parses the output into a RebaseResult.
Expand Down Expand Up @@ -102,8 +206,7 @@ var errorMatchRegex = regexp.MustCompile(`(?m)^error: (.+)$`)
// 3. Remove the "hint:" lines since they usually include instructions to run
// the `git rebase --continue` command which is usually not what we want to
// tell users to do with av.
func normalizeRebaseHint(stderr []byte) string {
res := string(stderr)
func normalizeRebaseHint(res string) string {
res = carriageReturnRegex.ReplaceAllString(res, "")
res = hintRegex.ReplaceAllString(res, "")
res = strings.ReplaceAll(res, "git rebase", "av stack sync")
Expand Down Expand Up @@ -151,15 +254,15 @@ func parseRebaseResult(opts RebaseOpts, out *Output) (*RebaseResult, error) {
}, nil
}

hint := normalizeRebaseHint(out.Stderr)
hint := normalizeRebaseHint(stderr)
headline := ""
errorMatches := errorMatchRegex.FindStringSubmatch(hint)
if len(errorMatches) > 1 {
headline = errorMatches[1]
}
return &RebaseResult{
Status: status,
Hint: normalizeRebaseHint(out.Stderr),
Hint: normalizeRebaseHint(stderr),
ErrorHeadline: headline,
}, nil
}
2 changes: 1 addition & 1 deletion internal/sequencer/planner/planner.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func PlanForRestack(
tx meta.ReadTx,
repo *git.Repo,
currentBranch plumbing.ReferenceName,
restackAll, restackCurrent bool,
restackAll, restackCurrent, restackInteractive bool,
) ([]sequencer.RestackOp, error) {
var targetBranches []plumbing.ReferenceName
var err error
Expand Down
Loading