Skip to content

Commit

Permalink
Move open logic into separate package
Browse files Browse the repository at this point in the history
  • Loading branch information
Katrina Owen committed Aug 2, 2017
1 parent 54de9de commit 7bf4b82
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 30 deletions.
32 changes: 32 additions & 0 deletions browser/open.go
Original file line number Diff line number Diff line change
@@ -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()
}
34 changes: 4 additions & 30 deletions cmd/open.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
}

0 comments on commit 7bf4b82

Please sign in to comment.