diff --git a/pkg/commands/git_commands/working_tree.go b/pkg/commands/git_commands/working_tree.go index e1339ee56d9..43ee275674c 100644 --- a/pkg/commands/git_commands/working_tree.go +++ b/pkg/commands/git_commands/working_tree.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "github.com/go-errors/errors" "github.com/jesseduffield/lazygit/pkg/commands/models" @@ -230,15 +231,25 @@ func (self *WorkingTreeCommands) DiscardUnstagedFileChanges(file *models.File) e return self.cmd.New(cmdArgs).Run() } +func escapeFilename(filename string) string { + escapedFilename := filename + if strings.HasPrefix(filename, "#") || strings.HasPrefix(filename, "!") { + escapedFilename = "\\" + filename + } + escapedFilename = strings.ReplaceAll(escapedFilename, "[", "\\[") + escapedFilename = strings.ReplaceAll(escapedFilename, "]", "\\]") + return escapedFilename +} + // Ignore adds a file to the gitignore for the repo func (self *WorkingTreeCommands) Ignore(filename string) error { - return self.os.AppendLineToFile(".gitignore", filename) + return self.os.AppendLineToFile(".gitignore", escapeFilename(filename)) } // Exclude adds a file to the .git/info/exclude for the repo func (self *WorkingTreeCommands) Exclude(filename string) error { excludeFile := filepath.Join(self.repoPaths.repoGitDirPath, "info", "exclude") - return self.os.AppendLineToFile(excludeFile, filename) + return self.os.AppendLineToFile(excludeFile, escapeFilename(filename)) } // WorktreeFileDiff returns the diff of a file