diff options
author | Anthony HAMON <hamon.anth@gmail.com> | 2018-08-29 21:47:48 +0200 |
---|---|---|
committer | Anthony HAMON <hamon.anth@gmail.com> | 2018-09-04 06:21:58 +0200 |
commit | 624d63d2fa90ad62998a62d8d17189cf0406864b (patch) | |
tree | f525a8c2782dd284492a941bd5dc8f3808d669de | |
parent | 19a80297950153a694be0ee94f7c3fdff614fa7e (diff) |
pkg/git : remove panic in SetupGit method
-rw-r--r-- | main.go | 8 | ||||
-rw-r--r-- | pkg/commands/git.go | 49 |
2 files changed, 41 insertions, 16 deletions
@@ -48,6 +48,12 @@ func main() { app.Log.Error(err.Error()) panic(err) } - app.GitCommand.SetupGit() + + if err := app.GitCommand.SetupGit(); err != nil { + app.Log.Error(err.Error()) + fmt.Println(err) + os.Exit(1) + } + app.Gui.RunWithSubprocesses() } diff --git a/pkg/commands/git.go b/pkg/commands/git.go index 704a45c73..68571769e 100644 --- a/pkg/commands/git.go +++ b/pkg/commands/git.go @@ -15,6 +15,10 @@ import ( gogit "gopkg.in/src-d/go-git.v4" ) +// ErrGitRepositoryInvalid is emitted when we run a git command in a folder +// to check if we have a valid git repository and we get an error instead +var ErrGitRepositoryInvalid = fmt.Errorf("can't find a valid git repository in current directory") + // GitCommand is our main git interface type GitCommand struct { Log *logrus.Entry @@ -35,13 +39,20 @@ func NewGitCommand(log *logrus.Entry, osCommand *OSCommand, tr *i18n.Localizer) } // SetupGit sets git repo up -func (c *GitCommand) SetupGit() { - c.verifyInGitRepo() - c.navigateToRepoRootDirectory() - if err := c.setupWorktree(); err != nil { - c.Log.Error(err) - panic(err) +func (c *GitCommand) SetupGit() error { + fs := []func() error{ + c.verifyInGitRepo, + c.navigateToRepoRootDirectory, + c.setupWorktree, + } + + for _, f := range fs { + if err := f(); err != nil { + return err + } } + + return nil } // GetStashEntries stash entryies @@ -145,11 +156,12 @@ func (c *GitCommand) MergeStatusFiles(oldFiles, newFiles []File) []File { return append(headResults, tailResults...) } -func (c *GitCommand) verifyInGitRepo() { - if output, err := c.OSCommand.RunCommandWithOutput("git status"); err != nil { - fmt.Println(output) - os.Exit(1) +func (c *GitCommand) verifyInGitRepo() error { + if _, err := c.OSCommand.RunCommandWithOutput("git status"); err != nil { + return ErrGitRepositoryInvalid } + + return nil } // GetBranchName branch name @@ -157,12 +169,19 @@ func (c *GitCommand) GetBranchName() (string, error) { return c.OSCommand.RunCommandWithOutput("git symbolic-ref --short HEAD") } -func (c *GitCommand) navigateToRepoRootDirectory() { - _, err := os.Stat(".git") - for os.IsNotExist(err) { +func (c *GitCommand) navigateToRepoRootDirectory() error { + for { + f, err := os.Stat(".git") + + if err == nil && f.IsDir() { + return nil + } + c.Log.Debug("going up a directory to find the root") - os.Chdir("..") - _, err = os.Stat(".git") + + if err = os.Chdir(".."); err != nil { + return err + } } } |