1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2024-12-12 11:15:00 +02:00

Refactor: simplify PrepareInteractiveRebaseCommand API

Instead of passing a bunch of different options in
PrepareInteractiveRebaseCommandOpts, where it was unclear how they interact if
several are set, have only a single field "instruction" which can be set to one
of various different instructions.

The functionality of replacing the entire todo file with our own is no longer
available; it is only possible to prepend todos to the existing file.

Also, instead of using different env vars for the various rebase operations that
we want to tell the daemon to do, use a single one that contains a json-encoded
struct with all available instructions. This makes the protocol much clearer,
and makes it easier to extend in the future.
This commit is contained in:
Stefan Haller 2023-04-06 11:13:42 +02:00
parent dad7a70bf8
commit a8586ba57e
4 changed files with 142 additions and 134 deletions

View File

@ -1,8 +1,7 @@
package daemon package daemon
import ( import (
"fmt" "encoding/json"
"io"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
@ -32,39 +31,39 @@ const (
const ( const (
DaemonKindEnvKey string = "LAZYGIT_DAEMON_KIND" DaemonKindEnvKey string = "LAZYGIT_DAEMON_KIND"
RebaseTODOEnvKey string = "LAZYGIT_REBASE_TODO"
// The `PrependLinesEnvKey` env variable is set to `true` to tell our daemon // Contains a json-encoded instance of the InteractiveRebaseInstructions struct
// to prepend the content of `RebaseTODOEnvKey` to the default `git-rebase-todo` InteractiveRebaseInstructionsEnvKey string = "LAZYGIT_DAEMON_INSTRUCTIONS"
// file instead of using it as a replacement. )
PrependLinesEnvKey string = "LAZYGIT_PREPEND_LINES"
// If this is set, it tells lazygit to read the original todo file, and // Exactly one of the fields in this struct is expected to be non-empty
// change the action for one or more entries in it. The value of the variable type InteractiveRebaseInstructions struct {
// will have one or more lines of the form "Sha1:newAction", e.g. // If this is non-empty, this string is prepended to the git-rebase-todo
// a02b54e1b7e7e8dd8bc1958c11ef4ee4df459ea4:edit // file. The string is expected to have newlines at the end of each line.
LinesToPrependToRebaseTODO string
// If this is non-empty, it tells lazygit to read the original todo file, and
// change the action for one or more entries in it.
// The existing action of the todo to be changed is expected to be "pick". // The existing action of the todo to be changed is expected to be "pick".
// ChangeTodoActions []ChangeTodoAction
// If this is used, the value of RebaseTODOEnvKey must be empty.
ChangeTodoActionEnvKey string = "LAZYGIT_CHANGE_TODO_ACTION"
// Can be set to the sha of a "pick" todo that will be moved down by one. // Can be set to the sha of a "pick" todo that will be moved down by one.
MoveTodoDownEnvKey string = "LAZYGIT_MOVE_COMMIT_DOWN" ShaToMoveDown string
// Can be set to the sha of a "pick" todo that will be moved up by one. // Can be set to the sha of a "pick" todo that will be moved up by one.
MoveTodoUpEnvKey string = "LAZYGIT_MOVE_COMMIT_UP" ShaToMoveUp string
) }
type ChangeTodoAction struct {
Sha string
NewAction todo.TodoCommand
}
type Daemon interface { type Daemon interface {
Run() error Run() error
} }
var logFile io.StringWriter
func Handle(common *common.Common) { func Handle(common *common.Common) {
logFile, _ = os.Create("/tmp/daemon-log.txt")
_, _ = logFile.WriteString("Hello Daemon\n")
d := getDaemon(common) d := getDaemon(common)
if d == nil { if d == nil {
return return
@ -118,43 +117,30 @@ func (self *rebaseDaemon) Run() error {
} }
func (self *rebaseDaemon) writeTodoFile(path string) error { func (self *rebaseDaemon) writeTodoFile(path string) error {
if changeTodoActionEnvValue := os.Getenv(ChangeTodoActionEnvKey); changeTodoActionEnvValue != "" { jsonData := os.Getenv(InteractiveRebaseInstructionsEnvKey)
return self.changeTodoAction(path, changeTodoActionEnvValue) instructions := InteractiveRebaseInstructions{}
} else if shaToMoveDown := os.Getenv(MoveTodoDownEnvKey); shaToMoveDown != "" { err := json.Unmarshal([]byte(jsonData), &instructions)
_, _ = logFile.WriteString(fmt.Sprintf("Moving commit down: %s\n", shaToMoveDown))
return utils.MoveTodoDown(path, shaToMoveDown, todo.Pick)
} else if shaToMoveUp := os.Getenv(MoveTodoUpEnvKey); shaToMoveUp != "" {
_, _ = logFile.WriteString(fmt.Sprintf("Moving commit up: %s\n", shaToMoveUp))
return utils.MoveTodoUp(path, shaToMoveUp, todo.Pick)
} else {
todoContent := []byte(os.Getenv(RebaseTODOEnvKey))
prependLines := os.Getenv(PrependLinesEnvKey) != ""
if prependLines {
existingContent, err := os.ReadFile(path)
if err != nil { if err != nil {
return err return err
} }
todoContent = append(todoContent, existingContent...) if instructions.LinesToPrependToRebaseTODO != "" {
return utils.PrependStrToTodoFile(path, []byte(instructions.LinesToPrependToRebaseTODO))
} else if len(instructions.ChangeTodoActions) != 0 {
return self.changeTodoAction(path, instructions.ChangeTodoActions)
} else if instructions.ShaToMoveDown != "" {
return utils.MoveTodoDown(path, instructions.ShaToMoveDown, todo.Pick)
} else if instructions.ShaToMoveUp != "" {
return utils.MoveTodoUp(path, instructions.ShaToMoveUp, todo.Pick)
} }
return os.WriteFile(path, todoContent, 0o644) self.c.Log.Error("No instructions were given to daemon")
} return nil
} }
func (self *rebaseDaemon) changeTodoAction(path string, changeTodoActionEnvValue string) error { func (self *rebaseDaemon) changeTodoAction(path string, changeTodoActions []ChangeTodoAction) error {
lines := strings.Split(changeTodoActionEnvValue, "\n") for _, c := range changeTodoActions {
for _, line := range lines { if err := utils.EditRebaseTodo(path, c.Sha, todo.Pick, c.NewAction); err != nil {
fields := strings.Split(line, ":")
if len(fields) != 2 {
return fmt.Errorf("Unexpected value for %s: %s", ChangeTodoActionEnvKey, changeTodoActionEnvValue)
}
sha, newAction := fields[0], self.actionFromString(fields[1])
if int(newAction) == 0 {
return fmt.Errorf("Unknown action in %s", changeTodoActionEnvValue)
}
if err := utils.EditRebaseTodo(path, sha, todo.Pick, newAction); err != nil {
return err return err
} }
} }
@ -162,16 +148,6 @@ func (self *rebaseDaemon) changeTodoAction(path string, changeTodoActionEnvValue
return nil return nil
} }
func (self *rebaseDaemon) actionFromString(actionString string) todo.TodoCommand {
for t := todo.Pick; t < todo.Comment; t++ {
if t.String() == actionString {
return t
}
}
return 0
}
func gitDir() string { func gitDir() string {
dir := env.GetGitDirEnv() dir := env.GetGitDirEnv()
if dir == "" { if dir == "" {

View File

@ -5,6 +5,7 @@ import (
"github.com/fsmiamoto/git-todo-parser/todo" "github.com/fsmiamoto/git-todo-parser/todo"
"github.com/go-errors/errors" "github.com/go-errors/errors"
"github.com/jesseduffield/lazygit/pkg/app/daemon"
"github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/commands/patch" "github.com/jesseduffield/lazygit/pkg/commands/patch"
"github.com/jesseduffield/lazygit/pkg/commands/types/enums" "github.com/jesseduffield/lazygit/pkg/commands/types/enums"
@ -107,9 +108,11 @@ func (self *PatchCommands) MovePatchToSelectedCommit(commits []*models.Commit, s
err := self.rebase.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{ err := self.rebase.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
baseShaOrRoot: commits[baseIndex].Sha, baseShaOrRoot: commits[baseIndex].Sha,
overrideEditor: true, overrideEditor: true,
changeTodoActions: []ChangeTodoAction{ instruction: ChangeTodoActionsInstruction{
{sha: commits[sourceCommitIdx].Sha, newAction: todo.Edit}, actions: []daemon.ChangeTodoAction{
{sha: commits[destinationCommitIdx].Sha, newAction: todo.Edit}, {Sha: commits[sourceCommitIdx].Sha, NewAction: todo.Edit},
{Sha: commits[destinationCommitIdx].Sha, NewAction: todo.Edit},
},
}, },
}).Run() }).Run()
if err != nil { if err != nil {

View File

@ -1,6 +1,7 @@
package git_commands package git_commands
import ( import (
"encoding/json"
"fmt" "fmt"
"path/filepath" "path/filepath"
"strings" "strings"
@ -57,11 +58,11 @@ func (self *RebaseCommands) RewordCommit(commits []*models.Commit, index int, me
func (self *RebaseCommands) RewordCommitInEditor(commits []*models.Commit, index int) (oscommands.ICmdObj, error) { func (self *RebaseCommands) RewordCommitInEditor(commits []*models.Commit, index int) (oscommands.ICmdObj, error) {
return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{ return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
baseShaOrRoot: getBaseShaOrRoot(commits, index+1), baseShaOrRoot: getBaseShaOrRoot(commits, index+1),
changeTodoActions: []ChangeTodoAction{ instruction: ChangeTodoActionsInstruction{
{ actions: []daemon.ChangeTodoAction{{
sha: commits[index].Sha, Sha: commits[index].Sha,
newAction: todo.Reword, NewAction: todo.Reword,
}, }},
}, },
}), nil }), nil
} }
@ -103,8 +104,8 @@ func (self *RebaseCommands) MoveCommitDown(commits []*models.Commit, index int)
return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{ return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
baseShaOrRoot: baseShaOrRoot, baseShaOrRoot: baseShaOrRoot,
instruction: MoveDownInstruction{sha: commits[index].Sha},
overrideEditor: true, overrideEditor: true,
moveDown: commits[index].Sha,
}).Run() }).Run()
} }
@ -113,8 +114,8 @@ func (self *RebaseCommands) MoveCommitUp(commits []*models.Commit, index int) er
return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{ return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
baseShaOrRoot: baseShaOrRoot, baseShaOrRoot: baseShaOrRoot,
instruction: MoveUpInstruction{sha: commits[index].Sha},
overrideEditor: true, overrideEditor: true,
moveUp: commits[index].Sha,
}).Run() }).Run()
} }
@ -128,11 +129,13 @@ func (self *RebaseCommands) InteractiveRebase(commits []*models.Commit, index in
return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{ return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
baseShaOrRoot: baseShaOrRoot, baseShaOrRoot: baseShaOrRoot,
overrideEditor: true, instruction: ChangeTodoActionsInstruction{
changeTodoActions: []ChangeTodoAction{{ actions: []daemon.ChangeTodoAction{{
sha: commits[index].Sha, Sha: commits[index].Sha,
newAction: action, NewAction: action,
}}, }},
},
overrideEditor: true,
}).Run() }).Run()
} }
@ -140,59 +143,72 @@ func (self *RebaseCommands) EditRebase(branchRef string) error {
commands := []TodoLine{{Action: "break"}} commands := []TodoLine{{Action: "break"}}
return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{ return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
baseShaOrRoot: branchRef, baseShaOrRoot: branchRef,
todoLines: commands, instruction: PrependLinesInstruction{todoLines: commands},
prepend: true,
}).Run() }).Run()
} }
type ChangeTodoAction struct { type InteractiveRebaseInstruction interface {
// Add our data to the instructions struct, and return a log string
serialize(instructions *daemon.InteractiveRebaseInstructions) string
}
type PrependLinesInstruction struct {
todoLines []TodoLine
}
func (self PrependLinesInstruction) serialize(instructions *daemon.InteractiveRebaseInstructions) string {
todoStr := TodoLinesToString(self.todoLines)
instructions.LinesToPrependToRebaseTODO = todoStr
return fmt.Sprintf("Creating TODO file for interactive rebase: \n\n%s", todoStr)
}
type ChangeTodoActionsInstruction struct {
actions []daemon.ChangeTodoAction
}
func (self ChangeTodoActionsInstruction) serialize(instructions *daemon.InteractiveRebaseInstructions) string {
instructions.ChangeTodoActions = self.actions
changeTodoStr := strings.Join(slices.Map(self.actions, func(c daemon.ChangeTodoAction) string {
return fmt.Sprintf("%s:%s", c.Sha, c.NewAction)
}), "\n")
return fmt.Sprintf("Changing TODO actions: %s", changeTodoStr)
}
type MoveDownInstruction struct {
sha string sha string
newAction todo.TodoCommand }
func (self MoveDownInstruction) serialize(instructions *daemon.InteractiveRebaseInstructions) string {
instructions.ShaToMoveDown = self.sha
return fmt.Sprintf("Moving TODO down: %s", self.sha)
}
type MoveUpInstruction struct {
sha string
}
func (self MoveUpInstruction) serialize(instructions *daemon.InteractiveRebaseInstructions) string {
instructions.ShaToMoveUp = self.sha
return fmt.Sprintf("Moving TODO up: %s", self.sha)
} }
type PrepareInteractiveRebaseCommandOpts struct { type PrepareInteractiveRebaseCommandOpts struct {
baseShaOrRoot string baseShaOrRoot string
todoLines []TodoLine instruction InteractiveRebaseInstruction
overrideEditor bool overrideEditor bool
prepend bool
changeTodoActions []ChangeTodoAction
moveDown string
moveUp string
} }
// PrepareInteractiveRebaseCommand returns the cmd for an interactive rebase // PrepareInteractiveRebaseCommand returns the cmd for an interactive rebase
// we tell git to run lazygit to edit the todo list, and we pass the client // we tell git to run lazygit to edit the todo list, and we pass the client
// lazygit a todo string to write to the todo file // lazygit a todo string to write to the todo file
func (self *RebaseCommands) PrepareInteractiveRebaseCommand(opts PrepareInteractiveRebaseCommandOpts) oscommands.ICmdObj { func (self *RebaseCommands) PrepareInteractiveRebaseCommand(opts PrepareInteractiveRebaseCommandOpts) oscommands.ICmdObj {
todo := self.buildTodo(opts.todoLines)
ex := oscommands.GetLazygitPath() ex := oscommands.GetLazygitPath()
prependLines := ""
if opts.prepend {
prependLines = "TRUE"
}
debug := "FALSE" debug := "FALSE"
if self.Debug { if self.Debug {
debug = "TRUE" debug = "TRUE"
} }
changeTodoValue := strings.Join(slices.Map(opts.changeTodoActions, func(c ChangeTodoAction) string {
return fmt.Sprintf("%s:%s", c.sha, c.newAction)
}), "\n")
moveDownValue := ""
if opts.moveDown != "" {
moveDownValue = opts.moveDown
}
moveUpValue := ""
if opts.moveUp != "" {
moveUpValue = opts.moveUp
}
if todo != "" && changeTodoValue != "" {
panic("It's not allowed to pass both todoLines and changeActionOpts")
}
rebaseMergesArg := " --rebase-merges" rebaseMergesArg := " --rebase-merges"
if self.version.IsOlderThan(2, 22, 0) { if self.version.IsOlderThan(2, 22, 0) {
rebaseMergesArg = "" rebaseMergesArg = ""
@ -204,25 +220,24 @@ func (self *RebaseCommands) PrepareInteractiveRebaseCommand(opts PrepareInteract
cmdObj := self.cmd.New(cmdStr) cmdObj := self.cmd.New(cmdStr)
gitSequenceEditor := ex gitSequenceEditor := ex
if todo != "" {
self.os.LogCommand(fmt.Sprintf("Creating TODO file for interactive rebase: \n\n%s", todo), false) if opts.instruction != nil {
} else if changeTodoValue != "" { instructions := daemon.InteractiveRebaseInstructions{}
self.os.LogCommand(fmt.Sprintf("Changing TODO action: %s", changeTodoValue), false) logStr := opts.instruction.serialize(&instructions)
} else if moveDownValue != "" { jsonData, err := json.Marshal(instructions)
self.os.LogCommand(fmt.Sprintf("Moving TODO down: %s", moveDownValue), false) if err == nil {
} else if moveUpValue != "" { envVar := fmt.Sprintf("%s=%s", daemon.InteractiveRebaseInstructionsEnvKey, jsonData)
self.os.LogCommand(fmt.Sprintf("Moving TODO up: %s", moveUpValue), false) cmdObj.AddEnvVars(envVar)
self.os.LogCommand(logStr, false)
} else {
self.Log.Error(err)
}
} else { } else {
gitSequenceEditor = "true" gitSequenceEditor = "true"
} }
cmdObj.AddEnvVars( cmdObj.AddEnvVars(
daemon.DaemonKindEnvKey+"="+string(daemon.InteractiveRebase), daemon.DaemonKindEnvKey+"="+string(daemon.InteractiveRebase),
daemon.RebaseTODOEnvKey+"="+todo,
daemon.PrependLinesEnvKey+"="+prependLines,
daemon.ChangeTodoActionEnvKey+"="+changeTodoValue,
daemon.MoveTodoDownEnvKey+"="+moveDownValue,
daemon.MoveTodoUpEnvKey+"="+moveUpValue,
"DEBUG="+debug, "DEBUG="+debug,
"LANG=en_US.UTF-8", // Force using EN as language "LANG=en_US.UTF-8", // Force using EN as language
"LC_ALL=en_US.UTF-8", // Force using EN as language "LC_ALL=en_US.UTF-8", // Force using EN as language
@ -297,10 +312,12 @@ func (self *RebaseCommands) BeginInteractiveRebaseForCommit(commits []*models.Co
return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{ return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
baseShaOrRoot: getBaseShaOrRoot(commits, commitIndex+1), baseShaOrRoot: getBaseShaOrRoot(commits, commitIndex+1),
overrideEditor: true, overrideEditor: true,
changeTodoActions: []ChangeTodoAction{{ instruction: ChangeTodoActionsInstruction{
sha: commits[commitIndex].Sha, actions: []daemon.ChangeTodoAction{{
newAction: todo.Edit, Sha: commits[commitIndex].Sha,
NewAction: todo.Edit,
}}, }},
},
}).Run() }).Run()
} }
@ -393,11 +410,13 @@ func (self *RebaseCommands) CherryPickCommits(commits []*models.Commit) error {
return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{ return self.PrepareInteractiveRebaseCommand(PrepareInteractiveRebaseCommandOpts{
baseShaOrRoot: "HEAD", baseShaOrRoot: "HEAD",
instruction: PrependLinesInstruction{
todoLines: todoLines, todoLines: todoLines,
},
}).Run() }).Run()
} }
func (self *RebaseCommands) buildTodo(todoLines []TodoLine) string { func TodoLinesToString(todoLines []TodoLine) string {
lines := slices.Map(todoLines, func(todoLine TodoLine) string { lines := slices.Map(todoLines, func(todoLine TodoLine) string {
return todoLine.ToString() return todoLine.ToString()
}) })

View File

@ -63,6 +63,16 @@ func WriteRebaseTodoFile(fileName string, todos []todo.Todo) error {
return err return err
} }
func PrependStrToTodoFile(filePath string, linesToPrepend []byte) error {
existingContent, err := os.ReadFile(filePath)
if err != nil {
return err
}
linesToPrepend = append(linesToPrepend, existingContent...)
return os.WriteFile(filePath, linesToPrepend, 0o644)
}
func MoveTodoDown(fileName string, sha string, action todo.TodoCommand) error { func MoveTodoDown(fileName string, sha string, action todo.TodoCommand) error {
todos, err := ReadRebaseTodoFile(fileName) todos, err := ReadRebaseTodoFile(fileName)
if err != nil { if err != nil {