-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
94 lines (83 loc) · 1.95 KB
/
main.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
package main
import (
"flag"
"fmt"
"log"
"os/exec"
"strings"
"github.com/skanehira/ght/config"
"github.com/skanehira/ght/github"
"github.com/skanehira/ght/ui"
)
type Repo struct {
Owner string
Name string
}
func main() {
config.Init()
getRepoInfo()
github.NewClient(config.GitHub.Token)
if err := ui.New().Start(); err != nil {
log.Fatal(err)
}
}
func getRepoInfo() {
flag.Parse()
if len(flag.Args()) > 0 {
args := strings.Split(flag.Arg(0), "/")
if len(args) < 2 {
log.Fatal("invalid args")
}
config.GitHub.Owner = args[0]
config.GitHub.Repo = args[1]
} else {
repo, err := getOwnerRepo()
if err != nil {
log.Fatalf("invalid repo: %s", err)
}
config.GitHub.Owner = repo.Owner
config.GitHub.Repo = repo.Name
}
}
func getOwnerRepo() (*Repo, error) {
if _, err := exec.LookPath("git"); err != nil {
return nil, err
}
cmd := exec.Command("git", "remote", "get-url", "origin")
out, err := cmd.CombinedOutput()
result := strings.TrimRight(string(out), "\r\n")
if err != nil {
return nil, err
}
return parseRemote(result)
}
func parseRemote(remote string) (*Repo, error) {
if strings.HasSuffix(remote, ".git") {
remote = strings.TrimRight(remote, ".git")
}
var ownerRepo []string
if strings.HasPrefix(remote, "ssh") {
p := strings.Split(remote, "/")
if len(p) < 1 {
return nil, fmt.Errorf("cannot get owner/repo from remote: %s", remote)
}
ownerRepo = p[len(p)-2:]
} else if strings.HasPrefix(remote, "git") {
p := strings.Split(remote, ":")
if len(p) < 1 {
return nil, fmt.Errorf("cannot get owner/repo from remote: %s", remote)
}
ownerRepo = strings.Split(p[1], "/")
} else if strings.HasPrefix(remote, "http") || strings.HasPrefix(remote, "https") {
p := strings.Split(remote, "/")
if len(p) < 1 {
return nil, fmt.Errorf("cannot get owner/repo from remote: %s", remote)
}
ownerRepo = p[len(p)-2:]
}
repo := Repo{
Owner: ownerRepo[0],
Name: ownerRepo[1],
}
return &repo, nil
}