-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgopen.go
126 lines (98 loc) · 2.5 KB
/
gopen.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/kevinburke/ssh_config"
"github.com/manifoldco/promptui"
)
var (
openbrowser = func(url string) {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
if err != nil {
log.Fatal(err)
}
}
getGitRemoteOrigin = func() []byte {
items := listRemotes()
getRemoteUrl := func(remote string) []byte {
out, err := exec.Command("git", "remote", "get-url", remote).CombinedOutput()
if err != nil {
fmt.Printf("%s\n", errors.New("Not a git repository"))
os.Exit(1)
}
return out
}
if len(items) == 1 {
return getRemoteUrl(items[0])
}
prompt := promptui.Select{
Label: "Select git remote",
Items: items,
}
_, result, _ := prompt.Run()
return getRemoteUrl(result)
}
mountRepoUrl = func(remote string) (string, error) {
repo := strings.Split(remote, ":")
gitRemoteEndpoint := strings.Split(string(repo[0]), "@")
gitRemoteUrl := strings.Split(gitRemoteEndpoint[1], " ")
ssh_host := strings.Split(gitRemoteEndpoint[1], " ")
f, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config"))
if err != nil {
log.Fatal(err)
return "", errors.New("Could not open config file")
}
cfg, err := ssh_config.Decode(f)
if err != nil {
log.Fatal(err)
return "", errors.New("Could not decode the ssh_config file")
}
hostname, err := cfg.Get(ssh_host[0], "Hostname")
if err != nil {
log.Fatal(err)
return "", errors.New("Could not get hostname")
}
if hostname == "" {
hostname = gitRemoteUrl[0]
}
url := strings.TrimSuffix("https://"+hostname+"/"+repo[1], "\n")
return url, nil
}
listRemotes = func() []string {
out, err := exec.Command("git", "remote").Output()
if err != nil {
fmt.Printf("%s\n", errors.New("Not a git repository"))
os.Exit(1)
}
return strings.Split(strings.TrimSpace(string(out)), "\n")
}
)
func main() {
cmdOutput := getGitRemoteOrigin()
if strings.Contains(string(cmdOutput), "https") {
openbrowser(string(cmdOutput))
os.Exit(0)
}
repositoryUrl, err := mountRepoUrl(string(cmdOutput))
if err != nil {
log.Fatalf("%s", "Could not retrieve the repositoryUrl correctly")
os.Exit(1)
}
openbrowser(repositoryUrl)
}