Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

separate logger package from utils #123

Merged
merged 5 commits into from
Apr 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 61 additions & 54 deletions commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"strings"
"syscall"

"github.com/motemen/ghq/utils"
"github.com/motemen/ghq/logger"
"github.com/urfave/cli"
)

Expand Down Expand Up @@ -156,31 +156,37 @@ func doGet(c *cli.Context) error {

if repoPath != "" {
// Guess it
utils.Log("resolved", fmt.Sprintf("relative %q to %q", argURL, "https://"+repoPath))
logger.Log("resolved", fmt.Sprintf("relative %q to %q", argURL, "https://"+repoPath))
argURL = "https://" + repoPath
}
}
}

url, err := NewURL(argURL)
utils.DieIf(err)
if err != nil {
return err
}

isSSH := c.Bool("p")
if isSSH {
// Assume Git repository if `-p` is given.
url, err = ConvertGitURLHTTPToSSH(url)
utils.DieIf(err)
if url, err = ConvertGitURLHTTPToSSH(url); err != nil {
return err
}
}

remote, err := NewRemoteRepository(url)
utils.DieIf(err)
if err != nil {
return err
}

if remote.IsValid() == false {
utils.Log("error", fmt.Sprintf("Not a valid repository: %s", url))
os.Exit(1)
return fmt.Errorf("Not a valid repository: %s", url)
}

getRemoteRepository(remote, doUpdate, isShallow, vcsBackend)
if err := getRemoteRepository(remote, doUpdate, isShallow, vcsBackend); err != nil {
return err
}
if andLook {
doLook(c)
}
Expand All @@ -190,7 +196,7 @@ func doGet(c *cli.Context) error {
// getRemoteRepository clones or updates a remote repository remote.
// If doUpdate is true, updates the locally cloned repository. Otherwise does nothing.
// If isShallow is true, does shallow cloning. (no effect if already cloned or the VCS is Mercurial and git-svn)
func getRemoteRepository(remote RemoteRepository, doUpdate bool, isShallow bool, vcsBackend string) {
func getRemoteRepository(remote RemoteRepository, doUpdate bool, isShallow bool, vcsBackend string) error {
remoteURL := remote.URL()
local := LocalRepositoryFromURL(remoteURL)

Expand All @@ -203,35 +209,36 @@ func getRemoteRepository(remote RemoteRepository, doUpdate bool, isShallow bool,
newPath = true
err = nil
}
utils.PanicIf(err)
if err != nil {
return err
}
}

if newPath {
utils.Log("clone", fmt.Sprintf("%s -> %s", remoteURL, path))
logger.Log("clone", fmt.Sprintf("%s -> %s", remoteURL, path))

vcs := vcsRegistry[vcsBackend]
repoURL := remoteURL
if vcs == nil {
vcs, repoURL = remote.VCS()
if vcs == nil {
utils.Log("error", fmt.Sprintf("Could not find version control system: %s", remoteURL))
os.Exit(1)
return fmt.Errorf("Could not find version control system: %s", remoteURL)
}
}

err := vcs.Clone(repoURL, path, isShallow)
if err != nil {
utils.Log("error", err.Error())
os.Exit(1)
return err
}
} else {
if doUpdate {
utils.Log("update", path)
logger.Log("update", path)
local.VCS().Update(path)
} else {
utils.Log("exists", path)
logger.Log("exists", path)
}
}
return nil
}

func doList(c *cli.Context) error {
Expand Down Expand Up @@ -335,39 +342,33 @@ func doLook(c *cli.Context) error {

switch len(reposFound) {
case 0:
utils.Log("error", "No repository found")
os.Exit(1)

return fmt.Errorf("No repository found")
case 1:
if runtime.GOOS == "windows" {
cmd := exec.Command(os.Getenv("COMSPEC"))
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = reposFound[0].FullPath
err := cmd.Start()
if err == nil {
cmd.Wait()
os.Exit(0)
}
} else {
shell := os.Getenv("SHELL")
if shell == "" {
shell = "/bin/sh"
if err := cmd.Start(); err != nil {
return err
}

utils.Log("cd", reposFound[0].FullPath)
err := os.Chdir(reposFound[0].FullPath)
utils.PanicIf(err)

env := append(syscall.Environ(), "GHQ_LOOK="+reposFound[0].RelPath)
syscall.Exec(shell, []string{shell}, env)
return cmd.Wait()
}

shell := os.Getenv("SHELL")
if shell == "" {
shell = "/bin/sh"
}
logger.Log("cd", reposFound[0].FullPath)
if err := os.Chdir(reposFound[0].FullPath); err != nil {
return err
}
env := append(syscall.Environ(), "GHQ_LOOK="+reposFound[0].RelPath)
syscall.Exec(shell, []string{shell}, env)
default:
utils.Log("error", "More than one repositories are found; Try more precise name")
logger.Log("error", "More than one repositories are found; Try more precise name")
for _, repo := range reposFound {
utils.Log("error", "- "+strings.Join(repo.PathParts, "/"))
logger.Log("error", "- "+strings.Join(repo.PathParts, "/"))
}
}
return nil
Expand Down Expand Up @@ -398,23 +399,28 @@ func doImport(c *cli.Context) error {
if err == nil && command == "" {
err = fmt.Errorf("ghq.import.%s configuration not found", subCommand)
}
utils.DieIf(err)
if err != nil {
return err
}

// execute `sh -c 'COMMAND "$@"' -- ARG...`
// TODO: Windows
command = strings.TrimLeft(command, "!")
shellCommand := append([]string{"sh", "-c", command + ` "$@"`, "--"}, c.Args().Tail()...)

utils.Log("run", strings.Join(append([]string{command}, c.Args().Tail()...), " "))
logger.Log("run", strings.Join(append([]string{command}, c.Args().Tail()...), " "))

cmd := exec.Command(shellCommand[0], shellCommand[1:]...)
cmd.Stderr = os.Stderr

in, err = cmd.StdoutPipe()
utils.DieIf(err)
if err != nil {
return err
}

err = cmd.Start()
utils.DieIf(err)
if err := cmd.Start(); err != nil {
return err
}

finalize = cmd.Wait
}
Expand All @@ -424,35 +430,36 @@ func doImport(c *cli.Context) error {
line := scanner.Text()
url, err := NewURL(line)
if err != nil {
utils.Log("error", fmt.Sprintf("Could not parse URL <%s>: %s", line, err))
logger.Log("error", fmt.Sprintf("Could not parse URL <%s>: %s", line, err))
continue
}
if isSSH {
url, err = ConvertGitURLHTTPToSSH(url)
if err != nil {
utils.Log("error", fmt.Sprintf("Could not convert URL <%s>: %s", url, err))
logger.Log("error", fmt.Sprintf("Could not convert URL <%s>: %s", url, err))
continue
}
}

remote, err := NewRemoteRepository(url)
if utils.ErrorIf(err) {
if err != nil {
logger.Log("error", err.Error())
continue
}
if remote.IsValid() == false {
utils.Log("error", fmt.Sprintf("Not a valid repository: %s", url))
logger.Log("error", fmt.Sprintf("Not a valid repository: %s", url))
continue
}

getRemoteRepository(remote, doUpdate, isShallow, vcsBackend)
if err := getRemoteRepository(remote, doUpdate, isShallow, vcsBackend); err != nil {
return err
}
}
if err := scanner.Err(); err != nil {
utils.Log("error", fmt.Sprintf("While reading input: %s", err))
os.Exit(1)
return fmt.Errorf("While reading input: %s", err)
}

utils.DieIf(finalize())
return nil
return finalize()
}

func doRoot(c *cli.Context) error {
Expand Down
4 changes: 2 additions & 2 deletions git.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"strings"
"syscall"

"github.com/motemen/ghq/utils"
"github.com/motemen/ghq/logger"
)

// GitConfigSingle fetches single git-config variable.
Expand Down Expand Up @@ -77,7 +77,7 @@ func gitVersionOutputSatisfies(gitVersionOutput string, baseVersionParts []uint)

for i, v := range baseVersionParts {
thisV64, err := strconv.ParseUint(versionStrings[i+1], 10, 0)
utils.PanicIf(err)
logger.PanicIf(err)

thisV := uint(thisV64)

Expand Down
8 changes: 4 additions & 4 deletions local_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"path/filepath"
"strings"

"github.com/motemen/ghq/utils"
"github.com/motemen/ghq/logger"
)

type LocalRepository struct {
Expand Down Expand Up @@ -205,12 +205,12 @@ func localRepositoryRoots() []string {
} else {
var err error
_localRepositoryRoots, err = GitConfigAll("ghq.root")
utils.PanicIf(err)
logger.PanicIf(err)
}

if len(_localRepositoryRoots) == 0 {
homeDir, err := os.UserHomeDir()
utils.PanicIf(err)
logger.PanicIf(err)

_localRepositoryRoots = []string{filepath.Join(homeDir, ".ghq")}
}
Expand All @@ -219,7 +219,7 @@ func localRepositoryRoots() []string {
path := filepath.Clean(v)
if _, err := os.Stat(path); err == nil {
_localRepositoryRoots[i], err = filepath.EvalSymlinks(path)
utils.PanicIf(err)
logger.PanicIf(err)
} else {
_localRepositoryRoots[i] = path
}
Expand Down
20 changes: 1 addition & 19 deletions utils/log.go → logger/log.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package utils
package logger

import (
"os"

"github.com/motemen/go-colorine"
)

Expand All @@ -29,22 +27,6 @@ func Log(prefix, message string) {
logger.Log(prefix, message)
}

func ErrorIf(err error) bool {
if err != nil {
Log("error", err.Error())
return true
}

return false
}

func DieIf(err error) {
if err != nil {
Log("error", err.Error())
os.Exit(1)
}
}

func PanicIf(err error) {
if err != nil {
panic(err)
Expand Down
2 changes: 1 addition & 1 deletion utils/log_test.go → logger/log_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package utils
package logger

import "testing"

Expand Down
10 changes: 9 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"os"

"github.com/motemen/ghq/logger"
"github.com/urfave/cli"
)

Expand All @@ -12,7 +13,14 @@ const Version = "0.10.0"
var revision = "HEAD"

func main() {
newApp().Run(os.Args)
if err := newApp().Run(os.Args); err != nil {
exitCode := 1
if excoder, ok := err.(cli.ExitCoder); ok {
exitCode = excoder.ExitCode()
}
logger.Log("error", err.Error())
os.Exit(exitCode)
}
}

func newApp() *cli.App {
Expand Down
5 changes: 3 additions & 2 deletions remote_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"regexp"
"strings"

"github.com/motemen/ghq/logger"
"github.com/motemen/ghq/utils"
)

Expand Down Expand Up @@ -141,7 +142,7 @@ func (repo *OtherRepository) VCS() (*VCSBackend, *url.URL) {
// vcs = github
vcs, err := GitConfig("--get-urlmatch", "ghq.vcs", repo.URL().String())
if err != nil {
utils.Log("error", err.Error())
logger.Log("error", err.Error())
}

if vcs == "git" || vcs == "github" {
Expand All @@ -168,7 +169,7 @@ func (repo *OtherRepository) VCS() (*VCSBackend, *url.URL) {
return FossilBackend, repo.URL()
}
} else {
utils.Log("warning", "This version of Git does not support `config --get-urlmatch`; per-URL settings are not available")
logger.Log("warning", "This version of Git does not support `config --get-urlmatch`; per-URL settings are not available")
}

// Detect VCS backend automatically
Expand Down
Loading