Skip to content

Commit a27db87

Browse files
authored
Add custom patch command "Move patch into new commit before the original commit" (#4552)
- **PR Description** This is often useful to extract preparatory refactoring commits from a bigger one. It works best when selecting only entire hunks or even entire files; if partial hunks are in the patch, you are likely to get conflicts. Along the way, fix rewording merge commits. (Not because I find this super important, but just because I came across the code while working on this.) - **Please check if the PR fulfills these requirements** * [x] Cheatsheets are up-to-date (run `go generate ./...`) * [x] Code has been formatted (see [here](https://github.com/jesseduffield/lazygit/blob/master/CONTRIBUTING.md#code-formatting)) * [x] Tests have been added/updated (see [here](https://github.com/jesseduffield/lazygit/blob/master/pkg/integration/README.md) for the integration test guide) * [x] Text is internationalised (see [here](https://github.com/jesseduffield/lazygit/blob/master/CONTRIBUTING.md#internationalisation)) * [ ] If a new UserConfig entry was added, make sure it can be hot-reloaded (see [here](https://github.com/jesseduffield/lazygit/blob/master/docs/dev/Codebase_Guide.md#using-userconfig)) * [ ] Docs have been updated if necessary * [x] You've read through your own file changes for silly mistakes etc
2 parents ef1da6f + f6d1333 commit a27db87

15 files changed

+438
-9
lines changed

pkg/commands/git_commands/patch.go

+23
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,29 @@ func (self *PatchCommands) PullPatchIntoNewCommit(
314314
return self.rebase.ContinueRebase()
315315
}
316316

317+
func (self *PatchCommands) PullPatchIntoNewCommitBefore(
318+
commits []*models.Commit,
319+
commitIdx int,
320+
commitSummary string,
321+
commitDescription string,
322+
) error {
323+
if err := self.rebase.BeginInteractiveRebaseForCommit(commits, commitIdx+1, true); err != nil {
324+
return err
325+
}
326+
327+
if err := self.ApplyCustomPatch(false, false); err != nil {
328+
_ = self.rebase.AbortRebase()
329+
return err
330+
}
331+
332+
if err := self.commit.CommitCmdObj(commitSummary, commitDescription, false).Run(); err != nil {
333+
return err
334+
}
335+
336+
self.PatchBuilder.Reset()
337+
return self.rebase.ContinueRebase()
338+
}
339+
317340
// We have just applied a patch in reverse to discard it from a commit; if we
318341
// now try to apply the patch again to move it to a later commit, or to the
319342
// index, then this would conflict "with itself" in case the patch contained

pkg/commands/git_commands/rebase.go

+13-1
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,19 @@ func (self *RebaseCommands) SquashAllAboveFixupCommits(commit *models.Commit) er
400400
func (self *RebaseCommands) BeginInteractiveRebaseForCommit(
401401
commits []*models.Commit, commitIndex int, keepCommitsThatBecomeEmpty bool,
402402
) error {
403-
return self.BeginInteractiveRebaseForCommitRange(commits, commitIndex, commitIndex, keepCommitsThatBecomeEmpty)
403+
if commitIndex < len(commits) && commits[commitIndex].IsMerge() {
404+
if self.config.NeedsGpgSubprocessForCommit() {
405+
return errors.New(self.Tr.DisabledForGPG)
406+
}
407+
408+
return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
409+
baseHashOrRoot: getBaseHashOrRoot(commits, commitIndex),
410+
instruction: daemon.NewInsertBreakInstruction(),
411+
keepCommitsThatBecomeEmpty: keepCommitsThatBecomeEmpty,
412+
}).Run()
413+
} else {
414+
return self.BeginInteractiveRebaseForCommitRange(commits, commitIndex, commitIndex, keepCommitsThatBecomeEmpty)
415+
}
404416
}
405417

406418
func (self *RebaseCommands) BeginInteractiveRebaseForCommitRange(

pkg/gui/controllers/custom_patch_options_menu_action.go

+43-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"github.com/jesseduffield/gocui"
88
"github.com/jesseduffield/lazygit/pkg/gui/controllers/helpers"
99
"github.com/jesseduffield/lazygit/pkg/gui/types"
10+
"github.com/jesseduffield/lazygit/pkg/utils"
1011
)
1112

1213
type CustomPatchOptionsMenuAction struct {
@@ -46,7 +47,7 @@ func (self *CustomPatchOptionsMenuAction) Call() error {
4647
if self.c.Git().Patch.PatchBuilder.CanRebase && self.c.Git().Status.WorkingTreeState().None() {
4748
menuItems = append(menuItems, []*types.MenuItem{
4849
{
49-
Label: fmt.Sprintf(self.c.Tr.RemovePatchFromOriginalCommit, self.c.Git().Patch.PatchBuilder.To),
50+
Label: fmt.Sprintf(self.c.Tr.RemovePatchFromOriginalCommit, utils.ShortHash(self.c.Git().Patch.PatchBuilder.To)),
5051
Tooltip: self.c.Tr.RemovePatchFromOriginalCommitTooltip,
5152
OnPress: self.handleDeletePatchFromCommit,
5253
Key: 'd',
@@ -63,6 +64,12 @@ func (self *CustomPatchOptionsMenuAction) Call() error {
6364
OnPress: self.handlePullPatchIntoNewCommit,
6465
Key: 'n',
6566
},
67+
{
68+
Label: self.c.Tr.MovePatchIntoNewCommitBefore,
69+
Tooltip: self.c.Tr.MovePatchIntoNewCommitBeforeTooltip,
70+
OnPress: self.handlePullPatchIntoNewCommitBefore,
71+
Key: 'N',
72+
},
6673
}...)
6774

6875
if self.c.Context().Current().GetKey() == self.c.Contexts().LocalCommits.GetKey() {
@@ -222,6 +229,41 @@ func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommit() error {
222229
return nil
223230
}
224231

232+
func (self *CustomPatchOptionsMenuAction) handlePullPatchIntoNewCommitBefore() error {
233+
if ok, err := self.validateNormalWorkingTreeState(); !ok {
234+
return err
235+
}
236+
237+
self.returnFocusFromPatchExplorerIfNecessary()
238+
239+
commitIndex := self.getPatchCommitIndex()
240+
self.c.Helpers().Commits.OpenCommitMessagePanel(
241+
&helpers.OpenCommitMessagePanelOpts{
242+
// Pass a commit index of one less than the moved-from commit, so that
243+
// you can press up arrow once to recall the original commit message:
244+
CommitIndex: commitIndex - 1,
245+
InitialMessage: "",
246+
SummaryTitle: self.c.Tr.CommitSummaryTitle,
247+
DescriptionTitle: self.c.Tr.CommitDescriptionTitle,
248+
PreserveMessage: false,
249+
OnConfirm: func(summary string, description string) error {
250+
return self.c.WithWaitingStatus(self.c.Tr.RebasingStatus, func(gocui.Task) error {
251+
self.c.Helpers().Commits.CloseCommitMessagePanel()
252+
self.c.LogAction(self.c.Tr.Actions.MovePatchIntoNewCommit)
253+
err := self.c.Git().Patch.PullPatchIntoNewCommitBefore(self.c.Model().Commits, commitIndex, summary, description)
254+
if err := self.c.Helpers().MergeAndRebase.CheckMergeOrRebase(err); err != nil {
255+
return err
256+
}
257+
self.c.Context().Push(self.c.Contexts().LocalCommits, types.OnFocusOpts{})
258+
return nil
259+
})
260+
},
261+
},
262+
)
263+
264+
return nil
265+
}
266+
225267
func (self *CustomPatchOptionsMenuAction) handleApplyPatch(reverse bool) error {
226268
self.returnFocusFromPatchExplorerIfNecessary()
227269

pkg/i18n/english.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -813,6 +813,8 @@ type TranslationSet struct {
813813
MovePatchOutIntoIndexTooltip string
814814
MovePatchIntoNewCommit string
815815
MovePatchIntoNewCommitTooltip string
816+
MovePatchIntoNewCommitBefore string
817+
MovePatchIntoNewCommitBeforeTooltip string
816818
MovePatchToSelectedCommit string
817819
MovePatchToSelectedCommitTooltip string
818820
CopyPatchToClipboard string
@@ -1896,8 +1898,10 @@ func EnglishTranslationSet() *TranslationSet {
18961898
RemovePatchFromOriginalCommitTooltip: "Remove the current patch from its commit. This is achieved by starting an interactive rebase at the commit, applying the patch in reverse, and then continuing the rebase. If later commits depend on the patch, you may need to resolve conflicts.",
18971899
MovePatchOutIntoIndex: "Move patch out into index",
18981900
MovePatchOutIntoIndexTooltip: "Move the patch out of its commit and into the index. This is achieved by starting an interactive rebase at the commit, applying the patch in reverse, continuing the rebase to completion, and then applying the patch to the index. If later commits depend on the patch, you may need to resolve conflicts.",
1899-
MovePatchIntoNewCommit: "Move patch into new commit",
1901+
MovePatchIntoNewCommit: "Move patch into new commit after the original commit",
19001902
MovePatchIntoNewCommitTooltip: "Move the patch out of its commit and into a new commit sitting on top of the original commit. This is achieved by starting an interactive rebase at the original commit, applying the patch in reverse, then applying the patch to the index and committing it as a new commit, before continuing the rebase to completion. If later commits depend on the patch, you may need to resolve conflicts.",
1903+
MovePatchIntoNewCommitBefore: "Move patch into new commit before the original commit",
1904+
MovePatchIntoNewCommitBeforeTooltip: "Move the patch out of its commit and into a new commit before the original commit. This works best when the custom patch contains only entire hunks or even entire files; if it contains partial hunks, you are likely to get conflicts.",
19011905
MovePatchToSelectedCommit: "Move patch to selected commit (%s)",
19021906
MovePatchToSelectedCommitTooltip: "Move the patch out of its original commit and into the selected commit. This is achieved by starting an interactive rebase at the original commit, applying the patch in reverse, then continuing the rebase up to the selected commit, before applying the patch forward and amending the selected commit. The rebase is then continued to completion. If commits between the source and destination commit depend on the patch, you may need to resolve conflicts.",
19031907
CopyPatchToClipboard: "Copy patch to clipboard",

pkg/integration/tests/cherry_pick/cherry_pick_merge.go

-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ var CherryPickMerge = NewIntegrationTest(NewIntegrationTestArgs{
1515
EmptyCommit("base").
1616
NewBranch("first-branch").
1717
NewBranch("second-branch").
18-
Checkout("first-branch").
19-
Checkout("second-branch").
2018
CreateFileAndAdd("file1.txt", "content").
2119
Commit("one").
2220
CreateFileAndAdd("file2.txt", "content").
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package interactive_rebase
2+
3+
import (
4+
"github.com/jesseduffield/lazygit/pkg/config"
5+
. "github.com/jesseduffield/lazygit/pkg/integration/components"
6+
)
7+
8+
var RewordLastCommitOfStackedBranch = NewIntegrationTest(NewIntegrationTestArgs{
9+
Description: "Rewords the last commit of a branch in the middle of a stack",
10+
ExtraCmdArgs: []string{},
11+
Skip: false,
12+
GitVersion: AtLeast("2.38.0"),
13+
SetupConfig: func(config *config.AppConfig) {
14+
config.GetUserConfig().Git.MainBranches = []string{"master"}
15+
config.GetAppState().GitLogShowGraph = "never"
16+
},
17+
SetupRepo: func(shell *Shell) {
18+
shell.
19+
CreateNCommits(1).
20+
NewBranch("branch1").
21+
CreateNCommitsStartingAt(2, 2).
22+
NewBranch("branch2").
23+
CreateNCommitsStartingAt(2, 4)
24+
25+
shell.SetConfig("rebase.updateRefs", "true")
26+
},
27+
Run: func(t *TestDriver, keys config.KeybindingConfig) {
28+
t.Views().Commits().
29+
Focus().
30+
Lines(
31+
Contains("CI commit 05").IsSelected(),
32+
Contains("CI commit 04"),
33+
Contains("CI * commit 03"),
34+
Contains("CI commit 02"),
35+
Contains("CI commit 01"),
36+
).
37+
NavigateToLine(Contains("commit 03")).
38+
Press(keys.Commits.RenameCommit).
39+
Tap(func() {
40+
t.ExpectPopup().CommitMessagePanel().
41+
Title(Equals("Reword commit")).
42+
InitialText(Equals("commit 03")).
43+
Clear().
44+
Type("renamed 03").
45+
Confirm()
46+
}).
47+
Lines(
48+
Contains("CI commit 05"),
49+
Contains("CI commit 04"),
50+
Contains("CI * renamed 03"),
51+
Contains("CI commit 02"),
52+
Contains("CI commit 01"),
53+
)
54+
},
55+
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package interactive_rebase
2+
3+
import (
4+
"github.com/jesseduffield/lazygit/pkg/config"
5+
. "github.com/jesseduffield/lazygit/pkg/integration/components"
6+
)
7+
8+
var RewordMergeCommit = NewIntegrationTest(NewIntegrationTestArgs{
9+
Description: "Rewords a merge commit which is not the current head 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+
CreateFileAndAdd("file1.txt", "content").
18+
Commit("one").
19+
Checkout("master").
20+
Merge("first-branch").
21+
NewBranch("second-branch").
22+
EmptyCommit("two")
23+
},
24+
Run: func(t *TestDriver, keys config.KeybindingConfig) {
25+
t.Views().Commits().
26+
Focus().
27+
Lines(
28+
Contains("CI ◯ two").IsSelected(),
29+
Contains("CI ⏣─╮ Merge branch 'first-branch'"),
30+
Contains("CI │ ◯ one"),
31+
Contains("CI ◯─╯ base"),
32+
).
33+
SelectNextItem().
34+
Press(keys.Commits.RenameCommit).
35+
Tap(func() {
36+
t.ExpectPopup().CommitMessagePanel().
37+
Title(Equals("Reword commit")).
38+
InitialText(Equals("Merge branch 'first-branch'")).
39+
Clear().
40+
Type("renamed merge").
41+
Confirm()
42+
}).
43+
Lines(
44+
Contains("CI ◯ two"),
45+
Contains("CI ⏣─╮ renamed merge").IsSelected(),
46+
Contains("CI │ ◯ one"),
47+
Contains("CI ◯ ╯ base"),
48+
)
49+
},
50+
})

pkg/integration/tests/patch_building/move_to_new_commit.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ var MoveToNewCommit = NewIntegrationTest(NewIntegrationTestArgs{
4848

4949
t.Views().Information().Content(Contains("Building patch"))
5050

51-
t.Common().SelectPatchOption(Contains("Move patch into new commit"))
51+
t.Common().SelectPatchOption(Contains("Move patch into new commit after the original commit"))
5252

5353
t.ExpectPopup().CommitMessagePanel().
5454
InitialText(Equals("")).
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package patch_building
2+
3+
import (
4+
"github.com/jesseduffield/lazygit/pkg/config"
5+
. "github.com/jesseduffield/lazygit/pkg/integration/components"
6+
)
7+
8+
var MoveToNewCommitBefore = NewIntegrationTest(NewIntegrationTestArgs{
9+
Description: "Move a patch from a commit to a new commit before the original one",
10+
ExtraCmdArgs: []string{},
11+
Skip: false,
12+
GitVersion: AtLeast("2.26.0"),
13+
SetupConfig: func(config *config.AppConfig) {},
14+
SetupRepo: func(shell *Shell) {
15+
shell.CreateDir("dir")
16+
shell.CreateFileAndAdd("dir/file1", "file1 content")
17+
shell.CreateFileAndAdd("dir/file2", "file2 content")
18+
shell.Commit("first commit")
19+
20+
shell.UpdateFileAndAdd("dir/file1", "file1 content with old changes")
21+
shell.DeleteFileAndAdd("dir/file2")
22+
shell.CreateFileAndAdd("dir/file3", "file3 content")
23+
shell.Commit("commit to move from")
24+
25+
shell.UpdateFileAndAdd("dir/file1", "file1 content with new changes")
26+
shell.Commit("third commit")
27+
},
28+
Run: func(t *TestDriver, keys config.KeybindingConfig) {
29+
t.Views().Commits().
30+
Focus().
31+
Lines(
32+
Contains("third commit").IsSelected(),
33+
Contains("commit to move from"),
34+
Contains("first commit"),
35+
).
36+
SelectNextItem().
37+
PressEnter()
38+
39+
t.Views().CommitFiles().
40+
IsFocused().
41+
Lines(
42+
Contains("dir").IsSelected(),
43+
Contains(" M file1"),
44+
Contains(" D file2"),
45+
Contains(" A file3"),
46+
).
47+
PressPrimaryAction().
48+
PressEscape()
49+
50+
t.Views().Information().Content(Contains("Building patch"))
51+
52+
t.Common().SelectPatchOption(Contains("Move patch into new commit before the original commit"))
53+
54+
t.ExpectPopup().CommitMessagePanel().
55+
InitialText(Equals("")).
56+
Type("new commit").Confirm()
57+
58+
t.Views().Commits().
59+
IsFocused().
60+
Lines(
61+
Contains("third commit"),
62+
Contains("commit to move from").IsSelected(),
63+
Contains("new commit"),
64+
Contains("first commit"),
65+
).
66+
SelectNextItem().
67+
PressEnter()
68+
69+
t.Views().CommitFiles().
70+
IsFocused().
71+
Lines(
72+
Contains("dir").IsSelected(),
73+
Contains(" M file1"),
74+
Contains(" D file2"),
75+
Contains(" A file3"),
76+
).
77+
PressEscape()
78+
79+
t.Views().Commits().
80+
IsFocused().
81+
SelectPreviousItem().
82+
PressEnter()
83+
84+
// the original commit has no more files in it
85+
t.Views().CommitFiles().
86+
IsFocused().
87+
Lines(
88+
Contains("(none)"),
89+
)
90+
},
91+
})

0 commit comments

Comments
 (0)