From 91d0a9e87b8aae06cb6cdc170d16cffb63ff3235 Mon Sep 17 00:00:00 2001 From: Simon Pasquier Date: Fri, 4 Oct 2019 15:45:48 +0200 Subject: [PATCH] Support remotes other than "origin" Signed-off-by: Simon Pasquier --- pkg/repository/info.go | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/pkg/repository/info.go b/pkg/repository/info.go index 28356bcd..6d4e464b 100644 --- a/pkg/repository/info.go +++ b/pkg/repository/info.go @@ -39,10 +39,16 @@ type Info struct { Version string } -// shellOutput executes a shell command and returns the trimmed output +// shellOutput executes a shell command and returns the trimmed output. func shellOutput(cmd string, arg ...string) string { - out, _ := exec.Command(cmd, arg...).Output() - return strings.Trim(string(out), " \n\r") + out, _ := shellOutputWithError(cmd, arg...) + return out +} + +// shellOutputWithError executes a shell command and returns the trimmed output and error. +func shellOutputWithError(cmd string, arg ...string) (string, error) { + out, err := exec.Command(cmd, arg...).Output() + return strings.Trim(string(out), " \n\r"), err } // NewInfo returns a new Info. @@ -59,6 +65,7 @@ func NewInfo(warnf func(error)) (Info, error) { cmd := exec.Command("git", "rev-parse", "--show-toplevel") cmd.Stdout, cmd.Stderr = nil, nil if err := cmd.Run(); err != nil { + // Not a git repository. repo, err := os.Getwd() if err != nil { return info, errors.Wrap(err, "couldn't get current working directory") @@ -79,17 +86,27 @@ func NewInfo(warnf func(error)) (Info, error) { Revision: "non-git", } } else { - cmd := exec.Command("git", "config", "--get", "remote.origin.url") - repoURL, err := cmd.Output() + branch, err := shellOutputWithError("git", "rev-parse", "--abbrev-ref", "HEAD") + if err != nil { + return info, errors.Wrap(err, "unable to get the current branch") + } + + remote, err := shellOutputWithError("git", "config", "--get", fmt.Sprintf("branch.%s.remote", branch)) + if err != nil { + // default to origin. + remote = "origin" + } + + repoURL, err := shellOutputWithError("git", "config", "--get", fmt.Sprintf("remote.%s.url", remote)) if err != nil { - warnf(errors.Wrap(err, "unable to get repo location info from 'origin' remote")) + warnf(errors.Wrapf(err, "unable to get repository location for remote %q", remote)) } - repo, err := repoLocation(strings.Trim(string(repoURL), " \n\r")) + repo, err := repoLocation(repoURL) if err != nil { - return info, errors.Wrap(err, "couldn't parse repo location") + return info, errors.Wrapf(err, "couldn't parse repository location: %q", repoURL) } info = Info{ - Branch: shellOutput("git", "rev-parse", "--abbrev-ref", "HEAD"), + Branch: branch, Name: filepath.Base(repo), Owner: filepath.Base(filepath.Dir(repo)), Repo: repo,