Mid refactor change some more stuff

This commit is contained in:
Andrei Miulescu 2018-08-12 21:04:47 +10:00
parent e65ddd7b6f
commit e8eb78617c
No known key found for this signature in database
GPG key ID: 7C452D659F3A0FCB
16 changed files with 220 additions and 118 deletions

21
main.go
View file

@ -1,29 +1,22 @@
package main package main
import ( import (
"errors"
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log" "log"
"os" "os"
"os/exec"
"os/user" "os/user"
"path/filepath" "path/filepath"
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/app" "github.com/jesseduffield/lazygit/pkg/app"
"github.com/jesseduffield/lazygit/pkg/config" "github.com/jesseduffield/lazygit/pkg/config"
git "gopkg.in/src-d/go-git.v4" git "gopkg.in/src-d/go-git.v4"
) )
// ErrSubProcess is raised when we are running a subprocess
var ( var (
ErrSubprocess = errors.New("running subprocess")
subprocess *exec.Cmd
commit string commit string
version = "unversioned" version = "unversioned"
date string date string
@ -127,17 +120,5 @@ func main() {
// TODO remove this once r, w not used // TODO remove this once r, w not used
setupWorktree() setupWorktree()
app.Gui.Run() app.Gui.RunWithSubprocesses()
for {
if err := run(); err != nil {
if err == gocui.ErrQuit {
break
} else if err == ErrSubprocess {
subprocess.Run()
} else {
log.Panicln(err)
}
}
}
} }

View file

@ -10,7 +10,7 @@ import (
"github.com/Sirupsen/logrus" "github.com/Sirupsen/logrus"
"github.com/jesseduffield/gocui" "github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/git" "github.com/jesseduffield/lazygit/pkg/utils"
gitconfig "github.com/tcnksm/go-gitconfig" gitconfig "github.com/tcnksm/go-gitconfig"
gogit "gopkg.in/src-d/go-git.v4" gogit "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing/object" "gopkg.in/src-d/go-git.v4/plumbing/object"
@ -51,7 +51,7 @@ func (c *GitCommand) GitIgnore(filename string) {
func (c *GitCommand) GetStashEntries() []StashEntry { func (c *GitCommand) GetStashEntries() []StashEntry {
stashEntries := make([]StashEntry, 0) stashEntries := make([]StashEntry, 0)
rawString, _ := c.OSCommand.RunDirectCommand("git stash list --pretty='%gs'") rawString, _ := c.OSCommand.RunDirectCommand("git stash list --pretty='%gs'")
for i, line := range splitLines(rawString) { for i, line := range utils.SplitLines(rawString) {
stashEntries = append(stashEntries, stashEntryFromLine(line, i)) stashEntries = append(stashEntries, stashEntryFromLine(line, i))
} }
return stashEntries return stashEntries
@ -67,7 +67,7 @@ func stashEntryFromLine(line string, index int) StashEntry {
// GetStashEntryDiff stash diff // GetStashEntryDiff stash diff
func (c *GitCommand) GetStashEntryDiff(index int) (string, error) { func (c *GitCommand) GetStashEntryDiff(index int) (string, error) {
return runCommand("git stash show -p --color stash@{" + fmt.Sprint(index) + "}") return c.OSCommand.RunCommand("git stash show -p --color stash@{" + fmt.Sprint(index) + "}")
} }
func includes(array []string, str string) bool { func includes(array []string, str string) bool {
@ -81,8 +81,8 @@ func includes(array []string, str string) bool {
// GetStatusFiles git status files // GetStatusFiles git status files
func (c *GitCommand) GetStatusFiles() []GitFile { func (c *GitCommand) GetStatusFiles() []GitFile {
statusOutput, _ := getGitStatus() statusOutput, _ := c.GitStatus()
statusStrings := splitLines(statusOutput) statusStrings := utils.SplitLines(statusOutput)
gitFiles := make([]GitFile, 0) gitFiles := make([]GitFile, 0)
for _, statusString := range statusStrings { for _, statusString := range statusStrings {
@ -90,7 +90,7 @@ func (c *GitCommand) GetStatusFiles() []GitFile {
stagedChange := change[0:1] stagedChange := change[0:1]
unstagedChange := statusString[1:2] unstagedChange := statusString[1:2]
filename := statusString[3:] filename := statusString[3:]
tracked := !f([]string{"??", "A "}, change) tracked := !includes([]string{"??", "A "}, change)
gitFile := GitFile{ gitFile := GitFile{
Name: filename, Name: filename,
DisplayString: statusString, DisplayString: statusString,
@ -102,7 +102,7 @@ func (c *GitCommand) GetStatusFiles() []GitFile {
} }
gitFiles = append(gitFiles, gitFile) gitFiles = append(gitFiles, gitFile)
} }
objectLog(gitFiles) c.Log.Info(gitFiles) // TODO: use a dumper-esque log here
return gitFiles return gitFiles
} }
@ -162,6 +162,11 @@ func (c *GitCommand) verifyInGitRepo() {
} }
} }
// GetBranchName branch name
func (c *GitCommand) GetBranchName() (string, error) {
return c.OSCommand.RunDirectCommand("git symbolic-ref --short HEAD")
}
func (c *GitCommand) navigateToRepoRootDirectory() { func (c *GitCommand) navigateToRepoRootDirectory() {
_, err := os.Stat(".git") _, err := os.Stat(".git")
for os.IsNotExist(err) { for os.IsNotExist(err) {
@ -172,7 +177,7 @@ func (c *GitCommand) navigateToRepoRootDirectory() {
} }
func (c *GitCommand) setupWorktree() { func (c *GitCommand) setupWorktree() {
r, err := git.PlainOpen(".") r, err := gogit.PlainOpen(".")
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -187,17 +192,17 @@ func (c *GitCommand) setupWorktree() {
// ResetHard does the equivalent of `git reset --hard HEAD` // ResetHard does the equivalent of `git reset --hard HEAD`
func (c *GitCommand) ResetHard() error { func (c *GitCommand) ResetHard() error {
return c.Worktree.Reset(&gogit.ResetOptions{Mode: git.HardReset}) return c.Worktree.Reset(&gogit.ResetOptions{Mode: gogit.HardReset})
} }
// UpstreamDifferenceCount checks how many pushables/pullables there are for the // UpstreamDifferenceCount checks how many pushables/pullables there are for the
// current branch // current branch
func (c *GitCommand) UpstreamDifferenceCount() (string, string) { func (c *GitCommand) UpstreamDifferenceCount() (string, string) {
pushableCount, err := c.OSCommand.runDirectCommand("git rev-list @{u}..head --count") pushableCount, err := c.OSCommand.RunDirectCommand("git rev-list @{u}..head --count")
if err != nil { if err != nil {
return "?", "?" return "?", "?"
} }
pullableCount, err := c.OSCommand.runDirectCommand("git rev-list head..@{u} --count") pullableCount, err := c.OSCommand.RunDirectCommand("git rev-list head..@{u} --count")
if err != nil { if err != nil {
return "?", "?" return "?", "?"
} }
@ -207,18 +212,11 @@ func (c *GitCommand) UpstreamDifferenceCount() (string, string) {
// GetCommitsToPush Returns the sha's of the commits that have not yet been pushed // GetCommitsToPush Returns the sha's of the commits that have not yet been pushed
// to the remote branch of the current branch // to the remote branch of the current branch
func (c *GitCommand) GetCommitsToPush() []string { func (c *GitCommand) GetCommitsToPush() []string {
pushables, err := c.OSCommand.runDirectCommand("git rev-list @{u}..head --abbrev-commit") pushables, err := c.OSCommand.RunDirectCommand("git rev-list @{u}..head --abbrev-commit")
if err != nil { if err != nil {
return make([]string, 0) return make([]string, 0)
} }
return splitLines(pushables) return utils.SplitLines(pushables)
}
// GetGitBranches returns a list of branches for the current repo, with recency
// values stored against those that are in the reflog
func (c *GitCommand) GetGitBranches() []Branch {
builder := git.newBranchListBuilder()
return builder.build()
} }
// BranchIncluded states whether a branch is included in a list of branches, // BranchIncluded states whether a branch is included in a list of branches,
@ -234,60 +232,49 @@ func (c *GitCommand) BranchIncluded(branchName string, branches []Branch) bool {
// RenameCommit renames the topmost commit with the given name // RenameCommit renames the topmost commit with the given name
func (c *GitCommand) RenameCommit(name string) (string, error) { func (c *GitCommand) RenameCommit(name string) (string, error) {
return c.OSCommand.runDirectCommand("git commit --allow-empty --amend -m \"" + name + "\"") return c.OSCommand.RunDirectCommand("git commit --allow-empty --amend -m \"" + name + "\"")
} }
// Fetch fetch git repo // Fetch fetch git repo
func (c *GitCommand) Fetch() (string, error) { func (c *GitCommand) Fetch() (string, error) {
return c.OSCommand.runDirectCommand("git fetch") return c.OSCommand.RunDirectCommand("git fetch")
} }
// ResetToCommit reset to commit // ResetToCommit reset to commit
func (c *GitCommand) ResetToCommit(sha string) (string, error) { func (c *GitCommand) ResetToCommit(sha string) (string, error) {
return c.OSCommand.runDirectCommand("git reset " + sha) return c.OSCommand.RunDirectCommand("git reset " + sha)
} }
// NewBranch create new branch // NewBranch create new branch
func (c *GitCommand) NewBranch(name string) (string, error) { func (c *GitCommand) NewBranch(name string) (string, error) {
return c.OSCommand.runDirectCommand("git checkout -b " + name) return c.OSCommand.RunDirectCommand("git checkout -b " + name)
} }
// DeleteBranch delete branch // DeleteBranch delete branch
func (c *GitCommand) DeleteBranch(branch string) (string, error) { func (c *GitCommand) DeleteBranch(branch string) (string, error) {
return runCommand("git branch -d " + branch) return c.OSCommand.RunCommand("git branch -d " + branch)
} }
// ListStash list stash // ListStash list stash
func (c *GitCommand) ListStash() (string, error) { func (c *GitCommand) ListStash() (string, error) {
return c.OSCommand.runDirectCommand("git stash list") return c.OSCommand.RunDirectCommand("git stash list")
} }
// Merge merge // Merge merge
func (c *GitCommand) Merge(branchName string) (string, error) { func (c *GitCommand) Merge(branchName string) (string, error) {
return c.OSCommand.runDirectCommand("git merge --no-edit " + branchName) return c.OSCommand.RunDirectCommand("git merge --no-edit " + branchName)
} }
// AbortMerge abort merge // AbortMerge abort merge
func (c *GitCommand) AbortMerge() (string, error) { func (c *GitCommand) AbortMerge() (string, error) {
return c.OSCommand.runDirectCommand("git merge --abort") return c.OSCommand.RunDirectCommand("git merge --abort")
}
func runSubProcess(g *gocui.Gui, cmdName string, commandArgs ...string) {
subprocess = exec.Command(cmdName, commandArgs...)
subprocess.Stdin = os.Stdin
subprocess.Stdout = os.Stdout
subprocess.Stderr = os.Stderr
g.Update(func(g *gocui.Gui) error {
return ErrSubprocess
})
} }
// GitCommit commit to git // GitCommit commit to git
func (c *GitCommand) GitCommit(g *gocui.Gui, message string) (string, error) { func (c *GitCommand) GitCommit(g *gocui.Gui, message string) (string, error) {
gpgsign, _ := gitconfig.Global("commit.gpgsign") gpgsign, _ := gitconfig.Global("commit.gpgsign")
if gpgsign != "" { if gpgsign != "" {
runSubProcess(g, "git", "commit") sub, err := c.OSCommand.RunSubProcess("git", "commit")
return "", nil return "", nil
} }
userName, err := gitconfig.Username() userName, err := gitconfig.Username()
@ -295,7 +282,7 @@ func (c *GitCommand) GitCommit(g *gocui.Gui, message string) (string, error) {
return "", errNoUsername return "", errNoUsername
} }
userEmail, err := gitconfig.Email() userEmail, err := gitconfig.Email()
_, err = w.Commit(message, &git.CommitOptions{ _, err = c.Worktree.Commit(message, &gogit.CommitOptions{
Author: &object.Signature{ Author: &object.Signature{
Name: userName, Name: userName,
Email: userEmail, Email: userEmail,
@ -321,7 +308,7 @@ func (c *GitCommand) GitPush() (string, error) {
// SquashPreviousTwoCommits squashes a commit down to the one below it // SquashPreviousTwoCommits squashes a commit down to the one below it
// retaining the message of the higher commit // retaining the message of the higher commit
func (c *GitCommand) SquashPreviousTwoCommits(message string) (string, error) { func (c *GitCommand) SquashPreviousTwoCommits(message string) (string, error) {
return runDirectCommand("git reset --soft HEAD^ && git commit --amend -m \"" + message + "\"") return c.OSCommand.RunDirectCommand("git reset --soft HEAD^ && git commit --amend -m \"" + message + "\"")
} }
// SquashFixupCommit squashes a 'FIXUP' commit into the commit beneath it, // SquashFixupCommit squashes a 'FIXUP' commit into the commit beneath it,
@ -336,18 +323,18 @@ func (c *GitCommand) SquashFixupCommit(branchName string, shaValue string) (stri
} }
ret := "" ret := ""
for _, command := range commands { for _, command := range commands {
devLog(command) c.Log.Info(command)
output, err := c.OSCommand.runDirectCommand(command) output, err := c.OSCommand.RunDirectCommand(command)
ret += output ret += output
if err != nil { if err != nil {
devLog(ret) c.Log.Info(ret)
break break
} }
} }
if err != nil { if err != nil {
// We are already in an error state here so we're just going to append // We are already in an error state here so we're just going to append
// the output of these commands // the output of these commands
output, _ = c.OSCommand.RunDirectCommand("git branch -d " + shaValue) output, _ := c.OSCommand.RunDirectCommand("git branch -d " + shaValue)
ret += output ret += output
output, _ = c.OSCommand.RunDirectCommand("git checkout " + branchName) output, _ = c.OSCommand.RunDirectCommand("git checkout " + branchName)
ret += output ret += output
@ -357,12 +344,12 @@ func (c *GitCommand) SquashFixupCommit(branchName string, shaValue string) (stri
// CatFile obtain the contents of a file // CatFile obtain the contents of a file
func (c *GitCommand) CatFile(file string) (string, error) { func (c *GitCommand) CatFile(file string) (string, error) {
return c.OSCommand.runDirectCommand("cat " + file) return c.OSCommand.RunDirectCommand("cat " + file)
} }
// StageFile stages a file // StageFile stages a file
func (c *GitCommand) StageFile(file string) error { func (c *GitCommand) StageFile(file string) error {
_, err := c.OSCommand.runCommand("git add " + file) _, err := c.OSCommand.RunCommand("git add " + file)
return err return err
} }
@ -374,18 +361,18 @@ func (c *GitCommand) UnStageFile(file string, tracked bool) error {
} else { } else {
command = "git rm --cached " command = "git rm --cached "
} }
_, err := c.OSCommand.runCommand(command + file) _, err := c.OSCommand.RunCommand(command + file)
return err return err
} }
// GitStatus returns the plaintext short status of the repo // GitStatus returns the plaintext short status of the repo
func (c *GitCommand) GitStatus() (string, error) { func (c *GitCommand) GitStatus() (string, error) {
return c.OSCommand.runCommand("git status --untracked-files=all --short") return c.OSCommand.RunCommand("git status --untracked-files=all --short")
} }
// IsInMergeState states whether we are still mid-merge // IsInMergeState states whether we are still mid-merge
func (c *GitCommand) IsInMergeState() (bool, error) { func (c *GitCommand) IsInMergeState() (bool, error) {
output, err := c.OSCommand.runCommand("git status --untracked-files=all") output, err := c.OSCommand.RunCommand("git status --untracked-files=all")
if err != nil { if err != nil {
return false, err return false, err
} }
@ -396,11 +383,11 @@ func (c *GitCommand) IsInMergeState() (bool, error) {
func (c *GitCommand) RemoveFile(file GitFile) error { func (c *GitCommand) RemoveFile(file GitFile) error {
// if the file isn't tracked, we assume you want to delete it // if the file isn't tracked, we assume you want to delete it
if !file.Tracked { if !file.Tracked {
_, err := c.OSCommand.runCommand("rm -rf ./" + file.Name) _, err := c.OSCommand.RunCommand("rm -rf ./" + file.Name)
return err return err
} }
// if the file is tracked, we assume you want to just check it out // if the file is tracked, we assume you want to just check it out
_, err := c.OSCommand.runCommand("git checkout " + file.Name) _, err := c.OSCommand.RunCommand("git checkout " + file.Name)
return err return err
} }
@ -410,24 +397,24 @@ func (c *GitCommand) Checkout(branch string, force bool) (string, error) {
if force { if force {
forceArg = "--force " forceArg = "--force "
} }
return c.OSCommand.runCommand("git checkout " + forceArg + branch) return c.OSCommand.RunCommand("git checkout " + forceArg + branch)
} }
// AddPatch runs a subprocess for adding a patch by patch // AddPatch runs a subprocess for adding a patch by patch
// this will eventually be swapped out for a better solution inside the Gui // this will eventually be swapped out for a better solution inside the Gui
func (c *GitCommand) AddPatch(g *gocui.Gui, filename string) { func (c *GitCommand) AddPatch(g *gocui.Gui, filename string) (*exec.Cmd, error) {
runSubProcess(g, "git", "add", "--patch", filename) return c.OSCommand.RunSubProcess("git", "add", "--patch", filename)
} }
// GetBranchGraph gets the color-formatted graph of the log for the given branch // 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 // Currently it limits the result to 100 commits, but when we get async stuff
// working we can do lazy loading // working we can do lazy loading
func (c *GitCommand) GetBranchGraph(branchName string) (string, error) { func (c *GitCommand) GetBranchGraph(branchName string) (string, error) {
return c.OSCommand.runCommand("git log --graph --color --abbrev-commit --decorate --date=relative --pretty=medium -100 " + branchName) return c.OSCommand.RunCommand("git log --graph --color --abbrev-commit --decorate --date=relative --pretty=medium -100 " + branchName)
} }
// map (from https://gobyexample.com/collection-functions) // Map (from https://gobyexample.com/collection-functions)
func map(vs []string, f func(string) string) []string { func Map(vs []string, f func(string) string) []string {
vsm := make([]string, len(vs)) vsm := make([]string, len(vs))
for i, v := range vs { for i, v := range vs {
vsm[i] = f(v) vsm[i] = f(v)
@ -454,3 +441,73 @@ func includesInt(list []int, a int) bool {
} }
return false return false
} }
// GetCommits obtains the commits of the current branch
func (c *GitCommand) GetCommits() []Commit {
pushables := gogit.GetCommitsToPush()
log := getLog()
commits := make([]Commit, 0)
// now we can split it up and turn it into commits
lines := utils.RplitLines(log)
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
func (c *GitCommand) Diff(file GitFile) string {
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
}

View file

@ -1,8 +1,8 @@
package git package commands
// File : A staged/unstaged file // File : A staged/unstaged file
// TODO: decide whether to give all of these the Git prefix // TODO: decide whether to give all of these the Git prefix
type File struct { type GitFile struct {
Name string Name string
HasStagedChanges bool HasStagedChanges bool
HasUnstagedChanges bool HasUnstagedChanges bool
@ -26,3 +26,9 @@ type StashEntry struct {
Name string Name string
DisplayString string DisplayString string
} }
// Branch : A git branch
type Branch struct {
Name string
Recency string
}

View file

@ -85,7 +85,8 @@ func getPlatform() platform {
} }
} }
func (c *OSCommand) getOpenCommand() (string, string, error) { // GetOpenCommand get open command
func (c *OSCommand) GetOpenCommand() (string, string, error) {
//NextStep open equivalents: xdg-open (linux), cygstart (cygwin), open (OSX) //NextStep open equivalents: xdg-open (linux), cygstart (cygwin), open (OSX)
trailMap := map[string]string{ trailMap := map[string]string{
"xdg-open": " &>/dev/null &", "xdg-open": " &>/dev/null &",
@ -93,7 +94,7 @@ func (c *OSCommand) getOpenCommand() (string, string, error) {
"open": "", "open": "",
} }
for name, trail := range trailMap { for name, trail := range trailMap {
if out, _ := c.runCommand("which " + name); out != "exit status 1" { if out, _ := c.RunCommand("which " + name); out != "exit status 1" {
return name, trail, nil return name, trail, nil
} }
} }
@ -103,22 +104,22 @@ func (c *OSCommand) getOpenCommand() (string, string, error) {
// VsCodeOpenFile opens the file in code, with the -r flag to open in the // VsCodeOpenFile opens the file in code, with the -r flag to open in the
// current window // current window
func (c *OSCommand) VsCodeOpenFile(g *gocui.Gui, filename string) (string, error) { func (c *OSCommand) VsCodeOpenFile(g *gocui.Gui, filename string) (string, error) {
return c.runCommand("code -r " + filename) return c.RunCommand("code -r " + filename)
} }
// SublimeOpenFile opens the filein sublime // SublimeOpenFile opens the filein sublime
// may be deprecated in the future // may be deprecated in the future
func (c *OSCommand) SublimeOpenFile(g *gocui.Gui, filename string) (string, error) { func (c *OSCommand) SublimeOpenFile(g *gocui.Gui, filename string) (string, error) {
return c.runCommand("subl " + filename) return c.RunCommand("subl " + filename)
} }
// OpenFile opens a file with the given // OpenFile opens a file with the given
func (c *OSCommand) OpenFile(g *gocui.Gui, filename string) (string, error) { func (c *OSCommand) OpenFile(g *gocui.Gui, filename string) (string, error) {
cmdName, cmdTrail, err := getOpenCommand() cmdName, cmdTrail, err := c.GetOpenCommand()
if err != nil { if err != nil {
return "", err return "", err
} }
return c.runCommand(cmdName + " " + filename + cmdTrail) return c.RunCommand(cmdName + " " + filename + cmdTrail)
} }
// EditFile opens a file in a subprocess using whatever editor is available, // EditFile opens a file in a subprocess using whatever editor is available,
@ -132,13 +133,23 @@ func (c *OSCommand) editFile(g *gocui.Gui, filename string) (string, error) {
editor = os.Getenv("EDITOR") editor = os.Getenv("EDITOR")
} }
if editor == "" { if editor == "" {
if _, err := c.OSCommand.runCommand("which vi"); err == nil { if _, err := c.RunCommand("which vi"); err == nil {
editor = "vi" editor = "vi"
} }
} }
if editor == "" { if editor == "" {
return "", createErrorPanel(g, "No editor defined in $VISUAL, $EDITOR, or git config.") return "", createErrorPanel(g, "No editor defined in $VISUAL, $EDITOR, or git config.")
} }
runSubProcess(g, editor, filename) c.RunSubProcess(editor, filename)
return "", nil return "", nil
} }
// RunSubProcess iniRunSubProcessrocess then tells the Gui to switch to it
func (c *OSCommand) RunSubProcess(cmdName string, commandArgs ...string) (*exec.Cmd, error) {
subprocess := exec.Command(cmdName, commandArgs...)
subprocess.Stdin = os.Stdin
subprocess.Stdout = os.Stdout
subprocess.Stderr = os.Stderr
return subprocess, nil
}

View file

@ -6,12 +6,6 @@ import (
"github.com/fatih/color" "github.com/fatih/color"
) )
// Branch : A git branch
type Branch struct {
Name string
Recency string
}
// GetDisplayString returns the dispaly string of branch // GetDisplayString returns the dispaly string of branch
// func (b *Branch) GetDisplayString() string { // func (b *Branch) GetDisplayString() string {
// return gui.withPadding(b.Recency, 4) + gui.coloredString(b.Name, b.getColor()) // return gui.withPadding(b.Recency, 4) + gui.coloredString(b.Name, b.getColor())

View file

@ -4,6 +4,10 @@ import (
"regexp" "regexp"
"strings" "strings"
"github.com/jesseduffield/lazygit/pkg/commands"
"github.com/Sirupsen/logrus"
"gopkg.in/src-d/go-git.v4/plumbing" "gopkg.in/src-d/go-git.v4/plumbing"
) )
@ -15,20 +19,26 @@ import (
// our safe branches, then add the remaining safe branches, ensuring uniqueness // our safe branches, then add the remaining safe branches, ensuring uniqueness
// along the way // along the way
type branchListBuilder struct{} type BranchListBuilder struct {
Log *logrus.Log
func newBranchListBuilder() *branchListBuilder { GitCommand *commands.GitCommand
return &branchListBuilder{}
} }
func (b *branchListBuilder) obtainCurrentBranch() Branch { func NewBranchListBuilder(log *logrus.Logger, gitCommand *GitCommand) (*BranchListBuilder, error) {
return nil, &BranchListBuilder{
Log: log,
GitCommand: gitCommand
}
}
func (b *branchListBuilder) ObtainCurrentBranch() Branch {
// I used go-git for this, but that breaks if you've just done a git init, // I used go-git for this, but that breaks if you've just done a git init,
// even though you're on 'master' // even though you're on 'master'
branchName, _ := runDirectCommand("git symbolic-ref --short HEAD") branchName, _ := runDirectCommand("git symbolic-ref --short HEAD")
return Branch{Name: strings.TrimSpace(branchName), Recency: " *"} return Branch{Name: strings.TrimSpace(branchName), Recency: " *"}
} }
func (*branchListBuilder) obtainReflogBranches() []Branch { func (*branchListBuilder) ObtainReflogBranches() []Branch {
branches := make([]Branch, 0) branches := make([]Branch, 0)
rawString, err := runDirectCommand("git reflog -n100 --pretty='%cr|%gs' --grep-reflog='checkout: moving' HEAD") rawString, err := runDirectCommand("git reflog -n100 --pretty='%cr|%gs' --grep-reflog='checkout: moving' HEAD")
if err != nil { if err != nil {

View file

@ -5,6 +5,9 @@ import (
// "io" // "io"
// "io/ioutil" // "io/ioutil"
"errors"
"log"
"os/exec"
"runtime" "runtime"
"strings" "strings"
"time" "time"
@ -19,6 +22,13 @@ import (
// OverlappingEdges determines if panel edges overlap // OverlappingEdges determines if panel edges overlap
var OverlappingEdges = false var OverlappingEdges = false
// ErrSubprocess tells us we're switching to a subprocess so we need to
// close the Gui until it is finished
var (
ErrSubprocess = errors.New("running subprocess")
subprocess *exec.Cmd
)
type stateType struct { type stateType struct {
GitFiles []git.File GitFiles []git.File
Branches []git.Branch Branches []git.Branch
@ -273,6 +283,20 @@ func resizePopupPanels(g *gocui.Gui) error {
return nil return nil
} }
func RunWithSubprocesses() {
for {
if err := run(); err != nil {
if err == gocui.ErrQuit {
break
} else if err == ErrSubprocess {
subprocess.Run()
} else {
log.Panicln(err)
}
}
}
}
func run() (err error) { func run() (err error) {
g, err := gocui.NewGui(gocui.OutputNormal, OverlappingEdges) g, err := gocui.NewGui(gocui.OutputNormal, OverlappingEdges)
if err != nil { if err != nil {

View file

@ -1,4 +1,4 @@
package main package panels
import ( import (
"fmt" "fmt"
@ -123,7 +123,8 @@ func refreshBranches(g *gocui.Gui) error {
if err != nil { if err != nil {
panic(err) panic(err)
} }
state.Branches = git.GetGitBranches() builder := git.newBranchListBuilder() // TODO: add constructor params
state.Branches = builder.build()
v.Clear() v.Clear()
for _, branch := range state.Branches { for _, branch := range state.Branches {
fmt.Fprintln(v, branch.getDisplayString()) fmt.Fprintln(v, branch.getDisplayString())

View file

@ -1,4 +1,4 @@
package main package panels
import "github.com/jesseduffield/gocui" import "github.com/jesseduffield/gocui"

View file

@ -1,4 +1,4 @@
package main package panels
import ( import (
"errors" "errors"

View file

@ -4,7 +4,7 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package main package panels
import ( import (
"strings" "strings"

View file

@ -1,4 +1,4 @@
package main package panels
import ( import (
@ -194,6 +194,17 @@ func handleCommitEditorPress(g *gocui.Gui, filesView *gocui.View) error {
return nil return nil
} }
func runSubprocess(g *gocui.Gui, commands string...) error {
var err error
// need this OsCommand to be available
if subprocess, err = osCommand.RunSubProcess(commands...); err != nil {
return err
}
g.Update(func(g *gocui.Gui) error {
return gui.ErrSubprocess
})
}
func genericFileOpen(g *gocui.Gui, v *gocui.View, open func(*gocui.Gui, string) (string, error)) error { func genericFileOpen(g *gocui.Gui, v *gocui.View, open func(*gocui.Gui, string) (string, error)) error {
file, err := getSelectedFile(g) file, err := getSelectedFile(g)
if err != nil { if err != nil {

View file

@ -1,6 +1,6 @@
// though this panel is called the merge panel, it's really going to use the main panel. This may change in the future // though this panel is called the merge panel, it's really going to use the main panel. This may change in the future
package main package panels
import ( import (
"bufio" "bufio"

View file

@ -1,4 +1,4 @@
package main package panels
import ( import (
"fmt" "fmt"

View file

@ -1,4 +1,4 @@
package main package panels
import ( import (
"fmt" "fmt"

View file

@ -10,7 +10,10 @@ import (
"github.com/fatih/color" "github.com/fatih/color"
) )
func splitLines(multilineString string) []string { // SplitLines takes a multiline string and splits it on newlines
// currently we are also stripping \r's which may have adverse effects for
// windows users (but no issues have been raised yet)
func SplitLines(multilineString string) []string {
multilineString = strings.Replace(multilineString, "\r", "", -1) multilineString = strings.Replace(multilineString, "\r", "", -1)
if multilineString == "" || multilineString == "\n" { if multilineString == "" || multilineString == "\n" {
return make([]string, 0) return make([]string, 0)
@ -22,25 +25,29 @@ func splitLines(multilineString string) []string {
return lines return lines
} }
func withPadding(str string, padding int) string { // WithPadding pads a string as much as you want
func WithPadding(str string, padding int) string {
if padding-len(str) < 0 { if padding-len(str) < 0 {
return str return str
} }
return str + strings.Repeat(" ", padding-len(str)) return str + strings.Repeat(" ", padding-len(str))
} }
func coloredString(str string, colorAttribute color.Attribute) string { // ColoredString takes a string and a colour attribute and returns a colored
// string with that attribute
func ColoredString(str string, colorAttribute color.Attribute) string {
colour := color.New(colorAttribute) colour := color.New(colorAttribute)
return coloredStringDirect(str, colour) return ColoredStringDirect(str, colour)
} }
// used for aggregating a few color attributes rather than just sending a single one // ColoredStringDirect used for aggregating a few color attributes rather than
func coloredStringDirect(str string, colour *color.Color) string { // just sending a single one
func ColoredStringDirect(str string, colour *color.Color) string {
return colour.SprintFunc()(fmt.Sprint(str)) return colour.SprintFunc()(fmt.Sprint(str))
} }
// used to get the project name // GetCurrentProject gets the repo's base name
func getCurrentProject() string { func GetCurrentProject() string {
pwd, err := os.Getwd() pwd, err := os.Getwd()
if err != nil { if err != nil {
log.Fatalln(err.Error()) log.Fatalln(err.Error())