From 7bf4b82ad7ec6cd979d74cc5f1394d4293cb2f19 Mon Sep 17 00:00:00 2001 From: Katrina Owen Date: Tue, 1 Aug 2017 19:57:58 -0600 Subject: [PATCH] Move open logic into separate package --- browser/open.go | 32 ++++++++++++++++++++++++++++++++ cmd/open.go | 34 ++++------------------------------ 2 files changed, 36 insertions(+), 30 deletions(-) create mode 100644 browser/open.go diff --git a/browser/open.go b/browser/open.go new file mode 100644 index 000000000..48221326c --- /dev/null +++ b/browser/open.go @@ -0,0 +1,32 @@ +package browser + +import ( + "os/exec" + "runtime" + "strings" +) + +// Open opens a browser to the given URL. +// The terminal's open command is operating system dependent. +func Open(url string) error { + // Escape characters are not allowed by cmd/bash. + switch runtime.GOOS { + case "windows": + url = strings.Replace(url, "&", `^&`, -1) + default: + url = strings.Replace(url, "&", `\&`, -1) + } + + // The command to open the browser is OS-dependent. + var cmd *exec.Cmd + switch runtime.GOOS { + case "darwin": + cmd = exec.Command("open", url) + case "freebsd", "linux", "netbsd", "openbsd": + cmd = exec.Command("xdg-open", url) + case "windows": + cmd = exec.Command("cmd", "/c", "start", url) + } + + return cmd.Run() +} diff --git a/cmd/open.go b/cmd/open.go index 5197b60ba..8967befe7 100644 --- a/cmd/open.go +++ b/cmd/open.go @@ -4,16 +4,14 @@ import ( "fmt" "log" "os" - "os/exec" - "runtime" - "strings" "github.com/exercism/cli/api" + "github.com/exercism/cli/browser" "github.com/exercism/cli/config" app "github.com/urfave/cli" ) -// Open uses the given track and problem and opens it in the browser. +// Open opens the user's latest iteration of the exercise on the given track. func Open(ctx *app.Context) error { c, err := config.New(ctx.GlobalString("config")) if err != nil { @@ -31,32 +29,8 @@ func Open(ctx *app.Context) error { slug := args[1] submission, err := client.SubmissionURL(trackID, slug) if err != nil { - log.Fatal(err) - } - - url := submission.URL - // Escape characters are not allowed by cmd/bash. - switch runtime.GOOS { - case "windows": - url = strings.Replace(url, "&", `^&`, -1) - default: - url = strings.Replace(url, "&", `\&`, -1) - } - - // The command to open the browser is OS-dependent. - var cmd *exec.Cmd - switch runtime.GOOS { - case "darwin": - cmd = exec.Command("open", url) - case "freebsd", "linux", "netbsd", "openbsd": - cmd = exec.Command("xdg-open", url) - case "windows": - cmd = exec.Command("cmd", "/c", "start", url) - } - - if err := cmd.Run(); err != nil { - log.Fatal(err) + return err } - return nil + return browser.Open(submission.URL) }