/
open.go
62 lines (53 loc) · 1.2 KB
/
open.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package cmd
import (
"fmt"
"log"
"os"
"os/exec"
"runtime"
"strings"
"github.com/exercism/cli/api"
"github.com/exercism/cli/config"
"github.com/urfave/cli"
)
// Open uses the given track and problem and opens it in the browser.
func Open(ctx *cli.Context) error {
c, err := config.New(ctx.GlobalString("config"))
if err != nil {
log.Fatal(err)
}
client := api.NewClient(c)
args := ctx.Args()
if len(args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: exercism open TRACK_ID PROBLEM\n")
os.Exit(1)
}
trackID := args[0]
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 nil
}