1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2024-11-26 09:00:57 +02:00
lazygit/pkg/commands/git.go

498 lines
14 KiB
Go
Raw Normal View History

package commands
import (
2018-08-12 12:22:20 +02:00
"errors"
"fmt"
"os"
2018-08-12 12:22:20 +02:00
"os/exec"
2018-08-12 11:50:55 +02:00
"strings"
"github.com/Sirupsen/logrus"
2018-08-12 11:50:55 +02:00
"github.com/jesseduffield/gocui"
2018-08-12 13:04:47 +02:00
"github.com/jesseduffield/lazygit/pkg/utils"
2018-08-12 11:50:55 +02:00
gitconfig "github.com/tcnksm/go-gitconfig"
gogit "gopkg.in/src-d/go-git.v4"
)
// GitCommand is our main git interface
type GitCommand struct {
Log *logrus.Logger
OSCommand *OSCommand
2018-08-12 11:50:55 +02:00
Worktree *gogit.Worktree
Repo *gogit.Repository
}
// NewGitCommand it runs git commands
func NewGitCommand(log *logrus.Logger, osCommand *OSCommand) (*GitCommand, error) {
gitCommand := &GitCommand{
Log: log,
OSCommand: osCommand,
}
return gitCommand, nil
}
// SetupGit sets git repo up
func (c *GitCommand) SetupGit() {
c.verifyInGitRepo()
c.navigateToRepoRootDirectory()
c.setupWorktree()
}
2018-08-12 12:22:20 +02:00
// GetStashEntries stash entryies
func (c *GitCommand) GetStashEntries() []StashEntry {
stashEntries := make([]StashEntry, 0)
rawString, _ := c.OSCommand.RunDirectCommand("git stash list --pretty='%gs'")
2018-08-12 13:04:47 +02:00
for i, line := range utils.SplitLines(rawString) {
2018-08-12 12:22:20 +02:00
stashEntries = append(stashEntries, stashEntryFromLine(line, i))
}
return stashEntries
}
func stashEntryFromLine(line string, index int) StashEntry {
return StashEntry{
Name: line,
Index: index,
DisplayString: line,
}
}
// GetStashEntryDiff stash diff
func (c *GitCommand) GetStashEntryDiff(index int) (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunCommand("git stash show -p --color stash@{" + fmt.Sprint(index) + "}")
2018-08-12 12:22:20 +02:00
}
func includes(array []string, str string) bool {
for _, arrayStr := range array {
if arrayStr == str {
return true
}
}
return false
}
// GetStatusFiles git status files
2018-08-13 12:26:02 +02:00
func (c *GitCommand) GetStatusFiles() []File {
2018-08-12 13:04:47 +02:00
statusOutput, _ := c.GitStatus()
statusStrings := utils.SplitLines(statusOutput)
2018-08-13 12:26:02 +02:00
files := make([]File, 0)
2018-08-12 12:22:20 +02:00
for _, statusString := range statusStrings {
change := statusString[0:2]
stagedChange := change[0:1]
unstagedChange := statusString[1:2]
filename := statusString[3:]
2018-08-12 13:04:47 +02:00
tracked := !includes([]string{"??", "A "}, change)
2018-08-13 12:26:02 +02:00
file := File{
2018-08-12 12:22:20 +02:00
Name: filename,
DisplayString: statusString,
HasStagedChanges: !includes([]string{" ", "U", "?"}, stagedChange),
HasUnstagedChanges: unstagedChange != " ",
Tracked: tracked,
Deleted: unstagedChange == "D" || stagedChange == "D",
HasMergeConflicts: change == "UU",
}
2018-08-13 12:26:02 +02:00
files = append(files, file)
2018-08-12 12:22:20 +02:00
}
2018-08-13 12:26:02 +02:00
c.Log.Info(files) // TODO: use a dumper-esque log here
return files
2018-08-12 12:22:20 +02:00
}
// StashDo modify stash
func (c *GitCommand) StashDo(index int, method string) (string, error) {
return c.OSCommand.RunCommand("git stash " + method + " stash@{" + fmt.Sprint(index) + "}")
}
// StashSave save stash
func (c *GitCommand) StashSave(message string) (string, error) {
2018-08-14 03:15:29 +02:00
output, err := c.OSCommand.RunCommand("git stash save " + c.OSCommand.Quote(message))
2018-08-12 12:22:20 +02:00
if err != nil {
return output, err
}
// if there are no local changes to save, the exit code is 0, but we want
// to raise an error
if output == "No local changes to save\n" {
return output, errors.New(output)
}
return output, nil
}
// MergeStatusFiles merge status files
2018-08-13 12:26:02 +02:00
func (c *GitCommand) MergeStatusFiles(oldFiles, newFiles []File) []File {
if len(oldFiles) == 0 {
return newFiles
2018-08-12 12:22:20 +02:00
}
appendedIndexes := make([]int, 0)
// retain position of files we already could see
2018-08-13 12:26:02 +02:00
result := make([]File, 0)
for _, oldFile := range oldFiles {
for newIndex, newFile := range newFiles {
if oldFile.Name == newFile.Name {
result = append(result, newFile)
2018-08-12 12:22:20 +02:00
appendedIndexes = append(appendedIndexes, newIndex)
break
}
}
}
// append any new files to the end
2018-08-13 12:26:02 +02:00
for index, newFile := range newFiles {
2018-08-12 12:22:20 +02:00
if !includesInt(appendedIndexes, index) {
2018-08-13 12:26:02 +02:00
result = append(result, newFile)
2018-08-12 12:22:20 +02:00
}
}
return result
}
func (c *GitCommand) verifyInGitRepo() {
if output, err := c.OSCommand.RunCommand("git status"); err != nil {
fmt.Println(output)
os.Exit(1)
}
}
2018-08-12 13:04:47 +02:00
// GetBranchName branch name
func (c *GitCommand) GetBranchName() (string, error) {
return c.OSCommand.RunDirectCommand("git symbolic-ref --short HEAD")
}
func (c *GitCommand) navigateToRepoRootDirectory() {
_, err := os.Stat(".git")
for os.IsNotExist(err) {
c.Log.Debug("going up a directory to find the root")
os.Chdir("..")
_, err = os.Stat(".git")
}
}
func (c *GitCommand) setupWorktree() {
2018-08-12 13:04:47 +02:00
r, err := gogit.PlainOpen(".")
if err != nil {
panic(err)
}
c.Repo = r
w, err := r.Worktree()
if err != nil {
panic(err)
}
c.Worktree = w
}
2018-08-12 11:50:55 +02:00
// ResetHard does the equivalent of `git reset --hard HEAD`
func (c *GitCommand) ResetHard() error {
2018-08-12 13:04:47 +02:00
return c.Worktree.Reset(&gogit.ResetOptions{Mode: gogit.HardReset})
2018-08-12 11:50:55 +02:00
}
// UpstreamDifferenceCount checks how many pushables/pullables there are for the
// current branch
func (c *GitCommand) UpstreamDifferenceCount() (string, string) {
2018-08-12 13:04:47 +02:00
pushableCount, err := c.OSCommand.RunDirectCommand("git rev-list @{u}..head --count")
2018-08-12 11:50:55 +02:00
if err != nil {
return "?", "?"
}
2018-08-12 13:04:47 +02:00
pullableCount, err := c.OSCommand.RunDirectCommand("git rev-list head..@{u} --count")
2018-08-12 11:50:55 +02:00
if err != nil {
return "?", "?"
}
return strings.TrimSpace(pushableCount), strings.TrimSpace(pullableCount)
}
// GetCommitsToPush Returns the sha's of the commits that have not yet been pushed
// to the remote branch of the current branch
func (c *GitCommand) GetCommitsToPush() []string {
2018-08-12 13:04:47 +02:00
pushables, err := c.OSCommand.RunDirectCommand("git rev-list @{u}..head --abbrev-commit")
2018-08-12 11:50:55 +02:00
if err != nil {
return make([]string, 0)
}
2018-08-12 13:04:47 +02:00
return utils.SplitLines(pushables)
2018-08-12 11:50:55 +02:00
}
// RenameCommit renames the topmost commit with the given name
func (c *GitCommand) RenameCommit(name string) (string, error) {
2018-08-14 03:15:29 +02:00
return c.OSCommand.RunDirectCommand("git commit --allow-empty --amend -m " + c.OSCommand.Quote(name))
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// Fetch fetch git repo
2018-08-12 11:50:55 +02:00
func (c *GitCommand) Fetch() (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunDirectCommand("git fetch")
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// ResetToCommit reset to commit
2018-08-12 11:50:55 +02:00
func (c *GitCommand) ResetToCommit(sha string) (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunDirectCommand("git reset " + sha)
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// NewBranch create new branch
2018-08-12 11:50:55 +02:00
func (c *GitCommand) NewBranch(name string) (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunDirectCommand("git checkout -b " + name)
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// DeleteBranch delete branch
2018-08-12 11:50:55 +02:00
func (c *GitCommand) DeleteBranch(branch string) (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunCommand("git branch -d " + branch)
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// ListStash list stash
2018-08-12 11:50:55 +02:00
func (c *GitCommand) ListStash() (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunDirectCommand("git stash list")
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// Merge merge
2018-08-12 11:50:55 +02:00
func (c *GitCommand) Merge(branchName string) (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunDirectCommand("git merge --no-edit " + branchName)
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// AbortMerge abort merge
2018-08-12 11:50:55 +02:00
func (c *GitCommand) AbortMerge() (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunDirectCommand("git merge --abort")
2018-08-12 12:22:20 +02:00
}
// UsingGpg tells us whether the user has gpg enabled so that we can know
// whether we need to run a subprocess to allow them to enter their password
func (c *GitCommand) UsingGpg() bool {
gpgsign, _ := gitconfig.Global("commit.gpgsign")
if gpgsign == "" {
gpgsign, _ = gitconfig.Local("commit.gpgsign")
}
if gpgsign == "" {
return false
}
return true
}
2018-08-13 12:26:02 +02:00
// Commit commit to git
func (c *GitCommand) Commit(g *gocui.Gui, message string) (*exec.Cmd, error) {
2018-08-14 03:15:29 +02:00
command := "git commit -m " + c.OSCommand.Quote(message)
if c.UsingGpg() {
return c.OSCommand.PrepareSubProcess(c.OSCommand.Platform.shell, c.OSCommand.Platform.shellArg, command)
2018-08-12 11:50:55 +02:00
}
2018-08-13 12:26:02 +02:00
// TODO: make these runDirectCommand functions just return an error
_, err := c.OSCommand.RunDirectCommand(command)
2018-08-13 12:26:02 +02:00
return nil, err
2018-08-12 11:50:55 +02:00
}
2018-08-13 12:26:02 +02:00
// Pull pull from repo
func (c *GitCommand) Pull() (string, error) {
2018-08-12 12:22:20 +02:00
return c.OSCommand.RunCommand("git pull --no-edit")
2018-08-12 11:50:55 +02:00
}
2018-08-13 12:26:02 +02:00
// Push push to a branch
func (c *GitCommand) Push(branchName string) (string, error) {
return c.OSCommand.RunDirectCommand("git push -u origin " + branchName)
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// SquashPreviousTwoCommits squashes a commit down to the one below it
// retaining the message of the higher commit
func (c *GitCommand) SquashPreviousTwoCommits(message string) (string, error) {
2018-08-14 03:15:29 +02:00
return c.OSCommand.RunDirectCommand("git reset --soft HEAD^ && git commit --amend -m " + c.OSCommand.Quote(message))
2018-08-12 11:50:55 +02:00
}
2018-08-12 12:22:20 +02:00
// SquashFixupCommit squashes a 'FIXUP' commit into the commit beneath it,
// retaining the commit message of the lower commit
func (c *GitCommand) SquashFixupCommit(branchName string, shaValue string) (string, error) {
2018-08-12 11:50:55 +02:00
var err error
commands := []string{
"git checkout -q " + shaValue,
"git reset --soft " + shaValue + "^",
"git commit --amend -C " + shaValue + "^",
"git rebase --onto HEAD " + shaValue + " " + branchName,
}
ret := ""
for _, command := range commands {
2018-08-12 13:04:47 +02:00
c.Log.Info(command)
output, err := c.OSCommand.RunDirectCommand(command)
2018-08-12 11:50:55 +02:00
ret += output
if err != nil {
2018-08-12 13:04:47 +02:00
c.Log.Info(ret)
2018-08-12 11:50:55 +02:00
break
}
}
if err != nil {
// We are already in an error state here so we're just going to append
// the output of these commands
2018-08-12 13:04:47 +02:00
output, _ := c.OSCommand.RunDirectCommand("git branch -d " + shaValue)
2018-08-12 12:22:20 +02:00
ret += output
output, _ = c.OSCommand.RunDirectCommand("git checkout " + branchName)
ret += output
2018-08-12 11:50:55 +02:00
}
return ret, err
}
2018-08-12 12:22:20 +02:00
// CatFile obtain the contents of a file
func (c *GitCommand) CatFile(file string) (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunDirectCommand("cat " + file)
2018-08-12 12:22:20 +02:00
}
// StageFile stages a file
func (c *GitCommand) StageFile(file string) error {
2018-08-12 13:04:47 +02:00
_, err := c.OSCommand.RunCommand("git add " + file)
2018-08-12 12:22:20 +02:00
return err
}
// UnStageFile unstages a file
func (c *GitCommand) UnStageFile(file string, tracked bool) error {
var command string
if tracked {
command = "git reset HEAD "
} else {
command = "git rm --cached "
}
2018-08-12 13:04:47 +02:00
_, err := c.OSCommand.RunCommand(command + file)
2018-08-12 12:22:20 +02:00
return err
}
// GitStatus returns the plaintext short status of the repo
func (c *GitCommand) GitStatus() (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunCommand("git status --untracked-files=all --short")
2018-08-12 12:22:20 +02:00
}
// IsInMergeState states whether we are still mid-merge
func (c *GitCommand) IsInMergeState() (bool, error) {
2018-08-12 13:04:47 +02:00
output, err := c.OSCommand.RunCommand("git status --untracked-files=all")
2018-08-12 12:22:20 +02:00
if err != nil {
return false, err
}
return strings.Contains(output, "conclude merge") || strings.Contains(output, "unmerged paths"), nil
}
// RemoveFile directly
2018-08-13 12:26:02 +02:00
func (c *GitCommand) RemoveFile(file File) error {
2018-08-12 12:22:20 +02:00
// if the file isn't tracked, we assume you want to delete it
if !file.Tracked {
2018-08-12 13:04:47 +02:00
_, err := c.OSCommand.RunCommand("rm -rf ./" + file.Name)
2018-08-12 12:22:20 +02:00
return err
}
// if the file is tracked, we assume you want to just check it out
2018-08-12 13:04:47 +02:00
_, err := c.OSCommand.RunCommand("git checkout " + file.Name)
2018-08-12 12:22:20 +02:00
return err
}
// Checkout checks out a branch, with --force if you set the force arg to true
func (c *GitCommand) Checkout(branch string, force bool) (string, error) {
forceArg := ""
if force {
forceArg = "--force "
}
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunCommand("git checkout " + forceArg + branch)
2018-08-12 12:22:20 +02:00
}
2018-08-13 12:26:02 +02:00
// AddPatch prepares a subprocess for adding a patch by patch
2018-08-12 12:22:20 +02:00
// this will eventually be swapped out for a better solution inside the Gui
2018-08-13 12:26:02 +02:00
func (c *GitCommand) AddPatch(filename string) (*exec.Cmd, error) {
return c.OSCommand.PrepareSubProcess("git", "add", "--patch", filename)
}
// PrepareCommitSubProcess prepares a subprocess for `git commit`
func (c *GitCommand) PrepareCommitSubProcess() (*exec.Cmd, error) {
return c.OSCommand.PrepareSubProcess("git", "commit")
2018-08-12 12:22:20 +02:00
}
// GetBranchGraph gets the color-formatted graph of the log for the given branch
// Currently it limits the result to 100 commits, but when we get async stuff
// working we can do lazy loading
func (c *GitCommand) GetBranchGraph(branchName string) (string, error) {
2018-08-12 13:04:47 +02:00
return c.OSCommand.RunCommand("git log --graph --color --abbrev-commit --decorate --date=relative --pretty=medium -100 " + branchName)
2018-08-12 12:22:20 +02:00
}
2018-08-12 13:04:47 +02:00
// Map (from https://gobyexample.com/collection-functions)
func Map(vs []string, f func(string) string) []string {
2018-08-12 12:22:20 +02:00
vsm := make([]string, len(vs))
for i, v := range vs {
vsm[i] = f(v)
}
return vsm
}
func includesString(list []string, a string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
// not sure how to genericise this because []interface{} doesn't accept e.g.
// []int arguments
func includesInt(list []int, a int) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
2018-08-12 13:04:47 +02:00
// GetCommits obtains the commits of the current branch
func (c *GitCommand) GetCommits() []Commit {
2018-08-13 12:26:02 +02:00
pushables := c.GetCommitsToPush()
log := c.GetLog()
2018-08-12 13:04:47 +02:00
commits := make([]Commit, 0)
// now we can split it up and turn it into commits
2018-08-13 12:26:02 +02:00
lines := utils.SplitLines(log)
2018-08-12 13:04:47 +02:00
for _, line := range lines {
splitLine := strings.Split(line, " ")
sha := splitLine[0]
pushed := includesString(pushables, sha)
commits = append(commits, Commit{
Sha: sha,
Name: strings.Join(splitLine[1:], " "),
Pushed: pushed,
DisplayString: strings.Join(splitLine, " "),
})
}
return commits
}
// GetLog gets the git log (currently limited to 30 commits for performance
// until we work out lazy loading
func (c *GitCommand) GetLog() string {
// currently limiting to 30 for performance reasons
// TODO: add lazyloading when you scroll down
result, err := c.OSCommand.RunDirectCommand("git log --oneline -30")
if err != nil {
// assume if there is an error there are no commits yet for this branch
return ""
}
return result
}
// Ignore adds a file to the gitignore for the repo
func (c *GitCommand) Ignore(filename string) {
if _, err := c.OSCommand.RunDirectCommand("echo '" + filename + "' >> .gitignore"); err != nil {
panic(err)
}
}
// Show shows the diff of a commit
func (c *GitCommand) Show(sha string) string {
result, err := c.OSCommand.RunDirectCommand("git show --color " + sha)
if err != nil {
panic(err)
}
return result
}
// Diff returns the diff of a file
2018-08-13 12:26:02 +02:00
func (c *GitCommand) Diff(file File) string {
2018-08-12 13:04:47 +02:00
cachedArg := ""
if file.HasStagedChanges && !file.HasUnstagedChanges {
cachedArg = "--cached "
}
deletedArg := ""
if file.Deleted {
deletedArg = "-- "
}
trackedArg := ""
if !file.Tracked && !file.HasStagedChanges {
trackedArg = "--no-index /dev/null "
}
command := "git diff --color " + cachedArg + deletedArg + trackedArg + file.Name
// for now we assume an error means the file was deleted
s, _ := c.OSCommand.RunCommand(command)
return s
}