-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
96 lines (75 loc) · 1.89 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
95
96
package main
import (
"errors"
"log"
"os"
"os/exec"
"regexp"
"strings"
flag "github.com/ogier/pflag"
)
type Command struct {
GitURL string
GitArgs []string
Follow bool
}
func (c *Command) MakeGitDir() error {
return os.MkdirAll(ParseGitPath(c.GitURL), 0755)
}
func (c *Command) Clone() error {
_, err := exec.LookPath("git")
if err != nil {
return errors.New("git must be installed")
}
args := []string{"clone"}
args = append(args, c.GitArgs...)
args = append(args, c.GitURL, ParseGitPath(c.GitURL))
cmd := exec.Command("git", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
return err
}
func (c *Command) Chdir() error {
// Currently doesn't work. Somehow I need to jump to the parent process
return os.Chdir(ParseGitPath(c.GitURL))
}
func ParseGitPath(path string) string {
// remove protocol
re := regexp.MustCompile(`^(ssh|https|http|git|ftps|ftp)://`)
path = re.ReplaceAllString(path, "")
//remove username
re = regexp.MustCompile(`^\w+@`)
path = re.ReplaceAllString(path, "")
// remove colon and port
re = regexp.MustCompile(`:\d*/?`)
path = re.ReplaceAllString(path, "/")
// Clean up the end
path = strings.TrimSuffix(path, "/")
path = strings.TrimSuffix(path, ".git")
gopath := os.Getenv("GOPATH")
combine := []string{gopath, "src", path}
path = strings.Join(combine, "/")
return path
}
func main() {
cmd := Command{}
followDesc := "(WIP) After the clone, change to the new directory"
flag.BoolVarP(&cmd.Follow, "follow", "f", false, followDesc)
flag.Parse()
args := flag.Args()
cmd.GitArgs = args[:len(args)-1]
cmd.GitURL = args[len(args)-1]
if err := cmd.MakeGitDir(); err != nil {
log.Fatal("Problem creating the directory", err)
}
if err := cmd.Clone(); err != nil {
log.Fatal("Problem cloning the repo: ", err)
}
if cmd.Follow {
err := cmd.Chdir()
if err != nil {
log.Fatal("Unable to follow: ", err)
}
}
}