diff --git a/pkg/commands/models/commit.go b/pkg/commands/models/commit.go index 137528ee6..69aca8d73 100644 --- a/pkg/commands/models/commit.go +++ b/pkg/commands/models/commit.go @@ -160,3 +160,13 @@ func (c *Commit) IsTODO() bool { func IsHeadCommit(commits []*Commit, index int) bool { return !commits[index].IsTODO() && (index == 0 || commits[index-1].IsTODO()) } + +func HeadCommitIdx(commits []*Commit) int { + for index, commit := range commits { + if !commit.IsTODO() { + return index + } + } + + return -1 +} diff --git a/pkg/commands/models/commit_test.go b/pkg/commands/models/commit_test.go index d24238023..ecddec9c5 100644 --- a/pkg/commands/models/commit_test.go +++ b/pkg/commands/models/commit_test.go @@ -8,6 +8,49 @@ import ( "github.com/stretchr/testify/assert" ) +func TestHeadCommitIdx(t *testing.T) { + testCases := []struct { + name string + commits []*Commit + expected int + }{ + { + name: "first commit without rebase todos", + commits: makeTestCommits("a", "b"), + expected: 0, + }, + { + name: "first non-todo commit during an interactive rebase", + commits: []*Commit{ + makeTestTodoCommit(todo.Pick), + makeTestTodoCommit(todo.Reword), + makeTestCommit("a"), + makeTestCommit("b"), + }, + expected: 2, + }, + { + name: "no commits", + commits: nil, + expected: -1, + }, + { + name: "only rebase todos", + commits: []*Commit{ + makeTestTodoCommit(todo.Pick), + makeTestTodoCommit(todo.Reword), + }, + expected: -1, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + assert.Equal(t, testCase.expected, HeadCommitIdx(testCase.commits)) + }) + } +} + func TestIsHeadCommit(t *testing.T) { commits := []*Commit{ makeTestTodoCommit(todo.Pick), @@ -20,6 +63,15 @@ func TestIsHeadCommit(t *testing.T) { assert.False(t, IsHeadCommit(commits, 2)) } +func makeTestCommits(hashes ...string) []*Commit { + commits := make([]*Commit, 0, len(hashes)) + for _, hash := range hashes { + commits = append(commits, makeTestCommit(hash)) + } + + return commits +} + func makeTestCommit(hash string) *Commit { return NewCommit(&utils.StringPool{}, NewCommitOpts{Hash: hash}) }