Skip to content

Commit c13c635

Browse files
authored
Use "git cherry-pick" for implementing copy/paste of commits (#4443)
- **PR Description** This is part three of a four part series of PRs that improve the cherry-pick and revert experience. With this PR we reimplement copy/paste of commits to use `git cherry-pick` under the hood. We do this because - it's closer to what you would do on the command line - it simplifies the code a bit - it allows us to support cherry-picking merge commits. Fixes #1374 Fixes #3317
2 parents b7d01d6 + 108054e commit c13c635

File tree

9 files changed

+103
-104
lines changed

9 files changed

+103
-104
lines changed

pkg/app/daemon/daemon.go

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88
"os/exec"
99
"strconv"
1010

11-
"github.com/jesseduffield/lazygit/pkg/commands/models"
1211
"github.com/jesseduffield/lazygit/pkg/common"
1312
"github.com/jesseduffield/lazygit/pkg/utils"
1413
"github.com/samber/lo"
@@ -33,7 +32,6 @@ const (
3332

3433
DaemonKindExitImmediately
3534
DaemonKindRemoveUpdateRefsForCopiedBranch
36-
DaemonKindCherryPick
3735
DaemonKindMoveTodosUp
3836
DaemonKindMoveTodosDown
3937
DaemonKindInsertBreak
@@ -56,7 +54,6 @@ func getInstruction() Instruction {
5654
mapping := map[DaemonKind]func(string) Instruction{
5755
DaemonKindExitImmediately: deserializeInstruction[*ExitImmediatelyInstruction],
5856
DaemonKindRemoveUpdateRefsForCopiedBranch: deserializeInstruction[*RemoveUpdateRefsForCopiedBranchInstruction],
59-
DaemonKindCherryPick: deserializeInstruction[*CherryPickCommitsInstruction],
6057
DaemonKindChangeTodoActions: deserializeInstruction[*ChangeTodoActionsInstruction],
6158
DaemonKindDropMergeCommit: deserializeInstruction[*DropMergeCommitInstruction],
6259
DaemonKindMoveFixupCommitDown: deserializeInstruction[*MoveFixupCommitDownInstruction],
@@ -180,39 +177,6 @@ func NewRemoveUpdateRefsForCopiedBranchInstruction() Instruction {
180177
return &RemoveUpdateRefsForCopiedBranchInstruction{}
181178
}
182179

183-
type CherryPickCommitsInstruction struct {
184-
Todo string
185-
}
186-
187-
func NewCherryPickCommitsInstruction(commits []*models.Commit) Instruction {
188-
todoLines := lo.Map(commits, func(commit *models.Commit, _ int) TodoLine {
189-
return TodoLine{
190-
Action: "pick",
191-
Commit: commit,
192-
}
193-
})
194-
195-
todo := TodoLinesToString(todoLines)
196-
197-
return &CherryPickCommitsInstruction{
198-
Todo: todo,
199-
}
200-
}
201-
202-
func (self *CherryPickCommitsInstruction) Kind() DaemonKind {
203-
return DaemonKindCherryPick
204-
}
205-
206-
func (self *CherryPickCommitsInstruction) SerializedInstructions() string {
207-
return serializeInstruction(self)
208-
}
209-
210-
func (self *CherryPickCommitsInstruction) run(common *common.Common) error {
211-
return handleInteractiveRebase(common, func(path string) error {
212-
return utils.PrependStrToTodoFile(path, []byte(self.Todo))
213-
})
214-
}
215-
216180
type ChangeTodoActionsInstruction struct {
217181
Changes []ChangeTodoAction
218182
}

pkg/commands/git_commands/rebase.go

Lines changed: 8 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -533,35 +533,15 @@ func (self *RebaseCommands) DiscardOldFileChanges(commits []*models.Commit, comm
533533

534534
// CherryPickCommits begins an interactive rebase with the given hashes being cherry picked onto HEAD
535535
func (self *RebaseCommands) CherryPickCommits(commits []*models.Commit) error {
536-
commitLines := lo.Map(commits, func(commit *models.Commit, _ int) string {
537-
return fmt.Sprintf("%s %s", utils.ShortHash(commit.Hash), commit.Name)
538-
})
539-
msg := utils.ResolvePlaceholderString(
540-
self.Tr.Log.CherryPickCommits,
541-
map[string]string{
542-
"commitLines": strings.Join(commitLines, "\n"),
543-
},
544-
)
545-
self.os.LogCommand(msg, false)
546-
547-
return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
548-
baseHashOrRoot: "HEAD",
549-
instruction: daemon.NewCherryPickCommitsInstruction(commits),
550-
}).Run()
551-
}
552-
553-
// CherryPickCommitsDuringRebase simply prepends the given commits to the existing git-rebase-todo file
554-
func (self *RebaseCommands) CherryPickCommitsDuringRebase(commits []*models.Commit) error {
555-
todoLines := lo.Map(commits, func(commit *models.Commit, _ int) daemon.TodoLine {
556-
return daemon.TodoLine{
557-
Action: "pick",
558-
Commit: commit,
559-
}
560-
})
536+
hasMergeCommit := lo.SomeBy(commits, func(c *models.Commit) bool { return c.IsMerge() })
537+
cmdArgs := NewGitCmd("cherry-pick").
538+
Arg("--allow-empty").
539+
ArgIf(self.version.IsAtLeast(2, 45, 0), "--empty=keep", "--keep-redundant-commits").
540+
ArgIf(hasMergeCommit, "-m1").
541+
Arg(lo.Reverse(lo.Map(commits, func(c *models.Commit, _ int) string { return c.Hash }))...).
542+
ToArgv()
561543

562-
todo := daemon.TodoLinesToString(todoLines)
563-
filePath := filepath.Join(self.repoPaths.worktreeGitDirPath, "rebase-merge/git-rebase-todo")
564-
return utils.PrependStrToTodoFile(filePath, []byte(todo))
544+
return self.cmd.New(cmdArgs).Run()
565545
}
566546

567547
func (self *RebaseCommands) DropMergeCommit(commits []*models.Commit, commitIndex int) error {

pkg/gui/controllers/basic_commits_controller.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -366,10 +366,6 @@ func (self *BasicCommitsController) canCopyCommits(selectedCommits []*models.Com
366366
if commit.Hash == "" {
367367
return &types.DisabledReason{Text: self.c.Tr.CannotCherryPickNonCommit, ShowErrorInPanel: true}
368368
}
369-
370-
if commit.IsMerge() {
371-
return &types.DisabledReason{Text: self.c.Tr.CannotCherryPickMergeCommit, ShowErrorInPanel: true}
372-
}
373369
}
374370

375371
return nil

pkg/gui/controllers/helpers/cherry_pick_helper.go

Lines changed: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -77,41 +77,23 @@ func (self *CherryPickHelper) Paste() error {
7777
"numCommits": strconv.Itoa(len(self.getData().CherryPickedCommits)),
7878
}),
7979
HandleConfirm: func() error {
80-
isInRebase, err := self.c.Git().Status.IsInRebase()
81-
if err != nil {
82-
return err
83-
}
84-
if isInRebase {
85-
if err := self.c.Git().Rebase.CherryPickCommitsDuringRebase(self.getData().CherryPickedCommits); err != nil {
86-
return err
87-
}
88-
err = self.c.Refresh(types.RefreshOptions{
89-
Mode: types.SYNC, Scope: []types.RefreshableView{types.REBASE_COMMITS},
90-
})
91-
if err != nil {
92-
return err
93-
}
94-
95-
return self.Reset()
96-
}
97-
9880
return self.c.WithWaitingStatus(self.c.Tr.CherryPickingStatus, func(gocui.Task) error {
9981
self.c.LogAction(self.c.Tr.Actions.CherryPick)
100-
err := self.c.Git().Rebase.CherryPickCommits(self.getData().CherryPickedCommits)
101-
err = self.rebaseHelper.CheckMergeOrRebase(err)
82+
result := self.c.Git().Rebase.CherryPickCommits(self.getData().CherryPickedCommits)
83+
err := self.rebaseHelper.CheckMergeOrRebase(result)
10284
if err != nil {
103-
return err
85+
return result
10486
}
10587

106-
// If we're in an interactive rebase at this point, it must
88+
// If we're in the cherry-picking state at this point, it must
10789
// be because there were conflicts. Don't clear the copied
108-
// commits in this case, since we might want to abort and
109-
// try pasting them again.
110-
isInRebase, err = self.c.Git().Status.IsInRebase()
111-
if err != nil {
112-
return err
90+
// commits in this case, since we might want to abort and try
91+
// pasting them again.
92+
isInCherryPick, result := self.c.Git().Status.IsInCherryPick()
93+
if result != nil {
94+
return result
11395
}
114-
if !isInRebase {
96+
if !isInCherryPick {
11597
self.getData().DidPaste = true
11698
self.rerender()
11799
}

pkg/gui/modes/cherrypicking/cherry_picking.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,7 @@ func (self *CherryPicking) Remove(selectedCommit *models.Commit, commitsList []*
5959
}
6060

6161
func (self *CherryPicking) update(selectedHashSet *set.Set[string], commitsList []*models.Commit) {
62-
cherryPickedCommits := lo.Filter(commitsList, func(commit *models.Commit, _ int) bool {
62+
self.CherryPickedCommits = lo.Filter(commitsList, func(commit *models.Commit, _ int) bool {
6363
return selectedHashSet.Includes(commit.Hash)
6464
})
65-
66-
self.CherryPickedCommits = lo.Map(cherryPickedCommits, func(commit *models.Commit, _ int) *models.Commit {
67-
return &models.Commit{Name: commit.Name, Hash: commit.Hash}
68-
})
6965
}

pkg/integration/tests/cherry_pick/cherry_pick_conflicts.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ var CherryPickConflicts = NewIntegrationTest(NewIntegrationTestArgs{
6969
SelectNextItem().
7070
PressPrimaryAction()
7171

72-
t.Common().ContinueOnConflictsResolved("rebase")
72+
t.Common().ContinueOnConflictsResolved("cherry-pick")
7373

7474
t.Views().Files().IsEmpty()
7575

pkg/integration/tests/cherry_pick/cherry_pick_during_rebase.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,8 @@ var CherryPickDuringRebase = NewIntegrationTest(NewIntegrationTestArgs{
7575
}).
7676
Lines(
7777
Contains("pick CI two"),
78-
Contains("pick CI three"),
79-
Contains(" CI <-- YOU ARE HERE --- one"),
78+
Contains(" CI <-- YOU ARE HERE --- three"),
79+
Contains(" CI one"),
8080
Contains(" CI base"),
8181
).
8282
Tap(func() {
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package cherry_pick
2+
3+
import (
4+
"github.com/jesseduffield/lazygit/pkg/config"
5+
. "github.com/jesseduffield/lazygit/pkg/integration/components"
6+
)
7+
8+
var CherryPickMerge = NewIntegrationTest(NewIntegrationTestArgs{
9+
Description: "Cherry pick a merge commit",
10+
ExtraCmdArgs: []string{},
11+
Skip: false,
12+
SetupConfig: func(config *config.AppConfig) {},
13+
SetupRepo: func(shell *Shell) {
14+
shell.
15+
EmptyCommit("base").
16+
NewBranch("first-branch").
17+
NewBranch("second-branch").
18+
Checkout("first-branch").
19+
Checkout("second-branch").
20+
CreateFileAndAdd("file1.txt", "content").
21+
Commit("one").
22+
CreateFileAndAdd("file2.txt", "content").
23+
Commit("two").
24+
Checkout("master").
25+
Merge("second-branch").
26+
Checkout("first-branch")
27+
},
28+
Run: func(t *TestDriver, keys config.KeybindingConfig) {
29+
t.Views().Branches().
30+
Focus().
31+
Lines(
32+
Contains("first-branch"),
33+
Contains("master"),
34+
Contains("second-branch"),
35+
).
36+
SelectNextItem().
37+
PressEnter()
38+
39+
t.Views().SubCommits().
40+
IsFocused().
41+
Lines(
42+
Contains("⏣─╮ Merge branch 'second-branch'").IsSelected(),
43+
Contains("│ ◯ two"),
44+
Contains("│ ◯ one"),
45+
Contains("◯ ╯ base"),
46+
).
47+
// copy the merge commit
48+
Press(keys.Commits.CherryPickCopy)
49+
50+
t.Views().Information().Content(Contains("1 commit copied"))
51+
52+
t.Views().Commits().
53+
Focus().
54+
Lines(
55+
Contains("base").IsSelected(),
56+
).
57+
Press(keys.Commits.PasteCommits).
58+
Tap(func() {
59+
t.ExpectPopup().Alert().
60+
Title(Equals("Cherry-pick")).
61+
Content(Contains("Are you sure you want to cherry-pick the 1 copied commit(s) onto this branch?")).
62+
Confirm()
63+
}).
64+
Tap(func() {
65+
t.Views().Information().Content(DoesNotContain("commit copied"))
66+
}).
67+
Lines(
68+
Contains("Merge branch 'second-branch'").IsSelected(),
69+
Contains("base"),
70+
)
71+
72+
t.Views().Main().ContainsLines(
73+
Contains("Merge branch 'second-branch'"),
74+
Contains("---"),
75+
Contains("file1.txt | 1 +"),
76+
Contains("file2.txt | 1 +"),
77+
Contains("2 files changed, 2 insertions(+)"),
78+
)
79+
},
80+
})

pkg/integration/tests/test_list.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ var tests = []*components.IntegrationTest{
8282
cherry_pick.CherryPick,
8383
cherry_pick.CherryPickConflicts,
8484
cherry_pick.CherryPickDuringRebase,
85+
cherry_pick.CherryPickMerge,
8586
cherry_pick.CherryPickRange,
8687
commit.AddCoAuthor,
8788
commit.AddCoAuthorRange,

0 commit comments

Comments
 (0)