-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
106 lines (95 loc) · 2.26 KB
/
config.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
package main
import (
"errors"
giturls "github.com/whilp/git-urls"
"net/url"
"os"
"os/user"
"regexp"
"strings"
)
type ConfigInput struct {
src string
dst string
target string
branch string
cdir string
key string
proto string
git bool
quiet bool
verbose bool
}
type Config struct {
src []string
dst []string
url url.URL
branch string
cdir string
key string
proto string
git bool
quiet bool
verbose bool
}
func NewConfig(ci ConfigInput) (Config, error) {
// validate src & dst must not be empty
if ci.src == "" {
ci.src = "."
}
// parse src & dst strings into slices
src := strings.Split(ci.src, ",")
dst := strings.Split(ci.dst, ",")
// validate clone directory
if ci.cdir == "" {
return Config{}, errors.New("config: cdir value must not be empty")
}
if _, err := os.Stat(ci.cdir); os.IsNotExist(err) {
return Config{}, errors.New("config: cdir must be a valid path")
}
// validate proto is auto, https, or ssh
if ci.proto == "" {
return Config{}, errors.New("config: proto must not be empty")
} else if ci.proto != "auto" && ci.proto != "https" && ci.proto != "ssh" {
return Config{}, errors.New("config: invalid proto")
}
// validate url directory
if ci.target == "" {
return Config{}, errors.New("config: url must not be empty")
}
// convert short target into url
gitUrl, err := giturls.Parse(ci.target)
if err != nil {
return Config{}, err
}
// convert short format to actual url
filePath := regexp.MustCompile(`^file://@[a-z0-9-]{0,38}/`)
if filePath.MatchString(gitUrl.String()) {
configURL := ""
if ci.proto == "ssh" || ci.proto == "auto" {
// TODO: Only set auto to ssh if the repo is private
ci.proto = "ssh"
configURL = "[email protected]:" + ci.target
} else {
configURL = "https://github.com/" + ci.target + ".git"
}
gitUrl, _ = giturls.Parse(configURL)
}
// validate ssh key exists if proto is ssh and repo is private
if ci.proto == "ssh" && ci.key == "" {
usr, _ := user.Current()
ci.key = usr.HomeDir + "/.ssh/id_rsa"
}
return Config{
url: *gitUrl,
src: src,
dst: dst,
branch: ci.branch,
cdir: ci.cdir,
key: ci.key,
proto: ci.proto,
git: ci.git,
quiet: ci.quiet,
verbose: ci.verbose,
}, nil
}