1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2024-11-30 09:16:47 +02:00
lazygit/gitcommands.go

471 lines
12 KiB
Go
Raw Normal View History

2018-05-19 09:04:33 +02:00
package main
2018-05-19 03:16:34 +02:00
import (
2018-05-21 12:52:48 +02:00
2018-05-19 03:16:34 +02:00
// "log"
2018-06-05 10:48:46 +02:00
"errors"
2018-05-21 12:52:48 +02:00
"fmt"
2018-05-26 05:23:39 +02:00
"os"
2018-05-19 03:16:34 +02:00
"os/exec"
"strings"
2018-06-02 00:35:49 +02:00
"time"
2018-05-27 08:32:09 +02:00
"github.com/fatih/color"
2018-05-19 03:16:34 +02:00
)
2018-05-21 12:52:48 +02:00
// GitFile : A staged/unstaged file
2018-06-05 10:48:46 +02:00
// TODO: decide whether to give all of these the Git prefix
2018-05-21 12:52:48 +02:00
type GitFile struct {
Name string
HasStagedChanges bool
HasUnstagedChanges bool
Tracked bool
Deleted bool
2018-06-09 11:06:33 +02:00
HasMergeConflicts bool
2018-06-01 15:23:31 +02:00
DisplayString string
2018-05-19 03:16:34 +02:00
}
2018-05-21 12:52:48 +02:00
// Branch : A git branch
type Branch struct {
Name string
Type string
BaseBranch string
2018-06-01 15:23:31 +02:00
DisplayString string
2018-05-19 03:16:34 +02:00
}
2018-05-27 08:32:09 +02:00
// Commit : A git commit
type Commit struct {
Sha string
Name string
2018-06-01 15:23:31 +02:00
Pushed bool
2018-05-27 08:32:09 +02:00
DisplayString string
}
2018-06-05 10:48:46 +02:00
// StashEntry : A git stash entry
type StashEntry struct {
Index int
Name string
DisplayString string
}
2018-05-21 12:52:48 +02:00
// Map (from https://gobyexample.com/collection-functions)
func Map(vs []string, f func(string) string) []string {
vsm := make([]string, len(vs))
for i, v := range vs {
vsm[i] = f(v)
}
return vsm
}
2018-05-19 03:16:34 +02:00
2018-06-02 01:05:20 +02:00
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 {
2018-05-26 05:23:39 +02:00
for _, b := range list {
if b == a {
return true
}
}
return false
}
2018-05-21 12:52:48 +02:00
func mergeGitStatusFiles(oldGitFiles, newGitFiles []GitFile) []GitFile {
if len(oldGitFiles) == 0 {
return newGitFiles
}
2018-05-19 03:16:34 +02:00
2018-06-02 01:05:20 +02:00
appendedIndexes := make([]int, 0)
// retain position of files we already could see
2018-05-21 12:52:48 +02:00
result := make([]GitFile, 0)
for _, oldGitFile := range oldGitFiles {
2018-06-02 01:05:20 +02:00
for newIndex, newGitFile := range newGitFiles {
2018-05-21 12:52:48 +02:00
if oldGitFile.Name == newGitFile.Name {
result = append(result, newGitFile)
2018-06-02 01:05:20 +02:00
appendedIndexes = append(appendedIndexes, newIndex)
2018-05-21 12:52:48 +02:00
break
}
}
2018-05-19 03:16:34 +02:00
}
2018-06-02 01:05:20 +02:00
// append any new files to the end
for index, newGitFile := range newGitFiles {
if !includesInt(appendedIndexes, index) {
result = append(result, newGitFile)
}
}
2018-05-21 12:52:48 +02:00
return result
}
2018-05-19 03:16:34 +02:00
2018-05-21 14:34:02 +02:00
func runDirectCommand(command string) (string, error) {
2018-06-02 00:35:49 +02:00
timeStart := time.Now()
2018-05-26 05:23:39 +02:00
commandLog(command)
2018-05-27 08:32:09 +02:00
cmdOut, err := exec.Command("bash", "-c", command).CombinedOutput()
2018-06-02 00:35:49 +02:00
devLog("run direct command time for command: ", command, time.Now().Sub(timeStart))
2018-05-21 12:52:48 +02:00
return string(cmdOut), err
}
2018-05-19 03:16:34 +02:00
2018-06-01 15:23:31 +02:00
func branchStringParts(branchString string) (string, string) {
2018-05-21 12:52:48 +02:00
splitBranchName := strings.Split(branchString, "\t")
2018-06-01 15:23:31 +02:00
return splitBranchName[0], splitBranchName[1]
}
// branchPropertiesFromName : returns branch type, base, and color
func branchPropertiesFromName(name string) (string, string, color.Attribute) {
if strings.Contains(name, "feature/") {
return "feature", "develop", color.FgGreen
} else if strings.Contains(name, "bugfix/") {
return "bugfix", "develop", color.FgYellow
} else if strings.Contains(name, "hotfix/") {
return "hotfix", "master", color.FgRed
}
return "other", name, color.FgWhite
}
2018-06-09 11:06:33 +02:00
func coloredString(str string, colour *color.Color) string {
return colour.SprintFunc()(fmt.Sprint(str))
2018-06-01 15:23:31 +02:00
}
func withPadding(str string, padding int) string {
return str + strings.Repeat(" ", padding-len(str))
}
func branchFromLine(line string, index int) Branch {
recency, name := branchStringParts(line)
2018-06-09 11:06:33 +02:00
branchType, branchBase, colourAttr := branchPropertiesFromName(name)
2018-06-01 15:23:31 +02:00
if index == 0 {
recency = " *"
}
2018-06-09 11:06:33 +02:00
colour := color.New(colourAttr)
2018-06-01 15:23:31 +02:00
displayString := withPadding(recency, 4) + coloredString(name, colour)
return Branch{
Name: name,
Type: branchType,
BaseBranch: branchBase,
DisplayString: displayString,
}
2018-05-19 03:16:34 +02:00
}
2018-05-21 12:52:48 +02:00
func getGitBranches() []Branch {
branches := make([]Branch, 0)
2018-06-01 15:23:31 +02:00
// check if there are any branches
branchCheck, _ := runDirectCommand("git branch")
if branchCheck == "" {
return branches
}
2018-05-21 14:34:02 +02:00
rawString, _ := runDirectCommand(getBranchesCommand)
2018-06-09 11:30:59 +02:00
branchLines := splitLines(rawString)
if len(branchLines) == 0 {
// sometimes the getBranchesCommand command returns nothing, in which case
// we assume you've just init'd or cloned the repo and you've got master
// checked out
branches = append(branches, branchFromLine(" *\tmaster", 0))
}
for i, line := range branchLines {
2018-06-01 15:23:31 +02:00
branches = append(branches, branchFromLine(line, i))
2018-05-19 03:16:34 +02:00
}
2018-05-21 12:52:48 +02:00
return branches
2018-05-19 03:16:34 +02:00
}
2018-06-05 10:48:46 +02:00
// TODO: DRY up this function and getGitBranches
func getGitStashEntries() []StashEntry {
stashEntries := make([]StashEntry, 0)
rawString, _ := runDirectCommand("git stash list --pretty='%gs'")
for i, line := range splitLines(rawString) {
stashEntries = append(stashEntries, stashEntryFromLine(line, i))
}
return stashEntries
}
func stashEntryFromLine(line string, index int) StashEntry {
return StashEntry{
Name: line,
Index: index,
DisplayString: line,
}
}
func getStashEntryDiff(index int) (string, error) {
return runCommand("git stash show -p --color stash@{" + fmt.Sprint(index) + "}")
}
2018-05-21 12:52:48 +02:00
func getGitStatusFiles() []GitFile {
statusOutput, _ := getGitStatus()
statusStrings := splitLines(statusOutput)
gitFiles := make([]GitFile, 0)
for _, statusString := range statusStrings {
stagedChange := statusString[0:1]
unstagedChange := statusString[1:2]
filename := statusString[3:]
tracked := statusString[0:2] != "??"
gitFile := GitFile{
Name: filename,
DisplayString: statusString,
2018-06-09 11:06:33 +02:00
HasStagedChanges: tracked && stagedChange != " " && stagedChange != "U",
2018-05-21 12:52:48 +02:00
HasUnstagedChanges: !tracked || unstagedChange != " ",
Tracked: tracked,
Deleted: unstagedChange == "D" || stagedChange == "D",
2018-06-09 11:06:33 +02:00
HasMergeConflicts: statusString[0:2] == "UU",
2018-05-21 12:52:48 +02:00
}
gitFiles = append(gitFiles, gitFile)
}
return gitFiles
2018-05-19 03:16:34 +02:00
}
2018-06-05 10:48:46 +02:00
func gitStashDo(index int, method string) (string, error) {
return runCommand("git stash " + method + " stash@{" + fmt.Sprint(index) + "}")
}
func gitStashSave(message string) (string, error) {
output, err := runCommand("git stash save \"" + message + "\"")
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
}
2018-05-27 08:32:09 +02:00
func gitCheckout(branch string, force bool) (string, error) {
2018-05-21 12:52:48 +02:00
forceArg := ""
if force {
forceArg = "--force "
}
2018-05-27 08:32:09 +02:00
return runCommand("git checkout " + forceArg + branch)
2018-05-19 03:16:34 +02:00
}
2018-05-27 08:32:09 +02:00
func runCommand(command string) (string, error) {
2018-06-05 11:30:55 +02:00
commandStartTime := time.Now()
2018-05-27 08:32:09 +02:00
commandLog(command)
splitCmd := strings.Split(command, " ")
cmdOut, err := exec.Command(splitCmd[0], splitCmd[1:]...).CombinedOutput()
2018-06-05 11:30:55 +02:00
devLog("run command time: ", time.Now().Sub(commandStartTime))
2018-05-19 09:04:33 +02:00
return string(cmdOut), err
}
2018-05-19 03:16:34 +02:00
2018-05-26 05:23:39 +02:00
func openFile(filename string) (string, error) {
return runCommand("open " + filename)
}
func sublimeOpenFile(filename string) (string, error) {
return runCommand("subl " + filename)
}
2018-05-21 12:52:48 +02:00
func getBranchDiff(branch string, baseBranch string) (string, error) {
return runCommand("git diff --color " + baseBranch + "..." + branch)
}
2018-06-01 15:23:31 +02:00
func verifyInGitRepo() {
if output, err := runCommand("git status"); err != nil {
fmt.Println(output)
os.Exit(1)
}
}
2018-05-27 08:32:09 +02:00
func getCommits() []Commit {
2018-06-01 15:23:31 +02:00
pushables := gitCommitsToPush()
2018-05-27 08:32:09 +02:00
log := getLog()
commits := make([]Commit, 0)
// now we can split it up and turn it into commits
lines := splitLines(log)
for _, line := range lines {
splitLine := strings.Split(line, " ")
2018-06-01 15:23:31 +02:00
sha := splitLine[0]
2018-06-02 01:05:20 +02:00
pushed := includesString(pushables, sha)
2018-06-01 15:23:31 +02:00
commits = append(commits, Commit{
Sha: sha,
Name: strings.Join(splitLine[1:], " "),
Pushed: pushed,
DisplayString: strings.Join(splitLine, " "),
})
2018-05-27 08:32:09 +02:00
}
return commits
}
2018-05-26 05:23:39 +02:00
func getLog() string {
2018-06-02 00:35:49 +02:00
// currently limiting to 30 for performance reasons
// TODO: add lazyloading when you scroll down
result, err := runDirectCommand("git log --oneline -30")
2018-05-27 08:32:09 +02:00
if err != nil {
2018-06-01 15:23:31 +02:00
// assume if there is an error there are no commits yet for this branch
return ""
2018-05-27 08:32:09 +02:00
}
return result
}
2018-06-01 15:23:31 +02:00
func gitIgnore(filename string) {
if _, err := runDirectCommand("echo '" + filename + "' >> .gitignore"); err != nil {
panic(err)
}
}
2018-05-27 08:32:09 +02:00
func gitShow(sha string) string {
result, err := runDirectCommand("git show --color " + sha)
2018-05-26 05:23:39 +02:00
if err != nil {
panic(err)
}
return result
}
2018-05-21 12:52:48 +02:00
func getDiff(file GitFile) string {
2018-05-19 09:04:33 +02:00
cachedArg := ""
2018-05-21 12:52:48 +02:00
if file.HasStagedChanges {
2018-05-19 09:04:33 +02:00
cachedArg = "--cached "
}
2018-05-21 12:52:48 +02:00
deletedArg := ""
2018-05-21 14:34:02 +02:00
if file.Deleted {
deletedArg = "-- "
}
trackedArg := ""
if !file.Tracked {
trackedArg = "--no-index /dev/null "
2018-05-21 12:52:48 +02:00
}
2018-05-21 14:34:02 +02:00
command := "git diff --color " + cachedArg + deletedArg + trackedArg + file.Name
2018-06-09 11:06:33 +02:00
// for now we assume an error means the file was deleted
s, _ := runCommand(command)
2018-05-19 09:04:33 +02:00
return s
}
2018-05-19 03:16:34 +02:00
2018-06-09 11:06:33 +02:00
func catFile(file string) (string, error) {
return runDirectCommand("cat " + file)
}
2018-05-19 09:04:33 +02:00
func stageFile(file string) error {
_, err := runCommand("git add " + file)
return err
}
func unStageFile(file string) error {
_, err := runCommand("git reset HEAD " + file)
return err
2018-05-19 03:16:34 +02:00
}
2018-05-21 12:52:48 +02:00
func getGitStatus() (string, error) {
return runCommand("git status --untracked-files=all --short")
}
2018-05-19 03:16:34 +02:00
2018-06-09 11:06:33 +02:00
func isInMergeState() (bool, error) {
output, err := runCommand("git status --untracked-files=all")
if err != nil {
return false, err
}
return strings.Contains(output, "conclude merge") || strings.Contains(output, "unmerged paths"), nil
}
2018-05-21 14:34:02 +02:00
func removeFile(file GitFile) error {
// if the file isn't tracked, we assume you want to delete it
if !file.Tracked {
_, err := runCommand("rm -rf ./" + file.Name)
return err
}
// if the file is tracked, we assume you want to just check it out
_, err := runCommand("git checkout " + file.Name)
return err
}
func gitCommit(message string) error {
_, err := runDirectCommand("git commit -m \"" + message + "\"")
return err
}
2018-05-27 08:32:09 +02:00
func gitPull() (string, error) {
return runDirectCommand("git pull --no-edit")
}
func gitPush() (string, error) {
return runDirectCommand("git push -u")
}
func gitSquashPreviousTwoCommits(message string) (string, error) {
return runDirectCommand("git reset --soft head^ && git commit --amend -m \"" + message + "\"")
}
func gitRenameCommit(message string) (string, error) {
return runDirectCommand("git commit --allow-empty --amend -m \"" + message + "\"")
}
2018-06-02 05:51:03 +02:00
func gitFetch() (string, error) {
return runDirectCommand("git fetch")
}
func gitResetToCommit(sha string) (string, error) {
return runDirectCommand("git reset " + sha)
}
func gitNewBranch(name string) (string, error) {
return runDirectCommand("git checkout -b " + name)
}
2018-06-05 10:48:46 +02:00
func gitListStash() (string, error) {
return runDirectCommand("git stash list")
}
2018-06-09 11:06:33 +02:00
func gitMerge(branchName string) (string, error) {
return runDirectCommand("git merge --no-edit " + branchName)
}
func gitAbortMerge() (string, error) {
return runDirectCommand("git merge --abort")
}
2018-06-01 15:23:31 +02:00
func gitUpstreamDifferenceCount() (string, string) {
pushableCount, err := runDirectCommand("git rev-list @{u}..head --count")
2018-05-27 08:32:09 +02:00
if err != nil {
2018-06-01 15:23:31 +02:00
return "?", "?"
}
pullableCount, err := runDirectCommand("git rev-list head..@{u} --count")
if err != nil {
return "?", "?"
2018-05-27 08:32:09 +02:00
}
2018-06-05 10:48:46 +02:00
return strings.TrimSpace(pushableCount), strings.TrimSpace(pullableCount)
2018-05-27 08:32:09 +02:00
}
2018-06-01 15:23:31 +02:00
func gitCommitsToPush() []string {
pushables, err := runDirectCommand("git rev-list @{u}..head --abbrev-commit")
if err != nil {
return make([]string, 0)
}
return splitLines(pushables)
}
func gitCurrentBranchName() string {
branchName, err := runDirectCommand("git rev-parse --abbrev-ref HEAD")
// if there is an error, assume there are no branches yet
if err != nil {
return ""
}
return branchName
2018-05-26 07:44:44 +02:00
}
2018-05-21 12:52:48 +02:00
const getBranchesCommand = `set -e
git reflog -n100 --pretty='%cr|%gs' --grep-reflog='checkout: moving' HEAD | {
seen=":"
git_dir="$(git rev-parse --git-dir)"
while read line; do
date="${line%%|*}"
branch="${line##* }"
if ! [[ $seen == *:"${branch}":* ]]; then
seen="${seen}${branch}:"
if [ -f "${git_dir}/refs/heads/${branch}" ]; then
printf "%s\t%s\n" "$date" "$branch"
fi
fi
2018-05-27 08:32:09 +02:00
done | sed 's/ days /d /g' | sed 's/ weeks /w /g' | sed 's/ hours /h /g' | sed 's/ minutes /m /g' | sed 's/ seconds /m /g' | sed 's/ago//g' | tr -d ' '
2018-05-19 03:16:34 +02:00
}
2018-05-21 12:52:48 +02:00
`