-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
152 lines (131 loc) · 3.96 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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/spf13/pflag"
)
var (
version = "0.3.4"
commit = "none"
date = "unknown"
)
var r = regexp.MustCompile(`^(?:.*://)?(?:[^@]+@)?([^:/]+)(?::\d+)?[/:]?(.*)$`)
func main() {
var showCommandHelp, showVersionInfo, quiet bool
pflag.BoolVarP(&showCommandHelp, "help", "h", false, "Show this help message and exit")
pflag.BoolVarP(&showVersionInfo, "version", "v", false, "Show the version number and exit")
pflag.BoolVarP(&quiet, "quiet", "q", false, "Suppress output")
pflag.Parse()
if showCommandHelp {
usage()
return
}
if showVersionInfo {
if commit != "none" {
fmt.Printf("gclone version %s, commit %s, built at %s\n", version, commit, date)
} else {
fmt.Printf("gclone version %s\n", version)
}
return
}
if _, err := exec.LookPath("git"); err != nil {
prnt("git not found")
os.Exit(1)
}
var projectDir string
for _, arg := range pflag.Args() {
repository := arg
projectDir = getProjectDir(repository)
if ok := isDirectoryNotEmpty(projectDir); ok {
continue
}
if err := os.MkdirAll(filepath.Dir(projectDir), 0750); err != nil {
prnt("failed create directory: %s", err)
continue
}
cmd := exec.Command("git", "clone", repository)
if !quiet {
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
}
cmd.Dir = filepath.Dir(projectDir)
if err := cmd.Run(); err != nil {
prnt("failed clone repository: %s", err)
continue
}
if !quiet {
fmt.Fprintln(os.Stderr)
}
}
// Print latest project directory
abs, _ := filepath.Abs(projectDir)
fmt.Println(abs)
}
// normalize normalizes the given repository string and returns the parsed repository URL.
func normalize(repo string) string {
match := r.FindStringSubmatch(repo)
if len(match) != 3 {
return ""
}
path := match[2]
path = strings.TrimPrefix(path, "/")
path = strings.TrimPrefix(path, "~")
path = strings.TrimPrefix(path, "/")
path = strings.TrimSuffix(path, "/")
path = strings.TrimSuffix(path, ".git")
return filepath.Join(match[1], path)
}
// getProjectDir returns the project directory based on the given repository URL.
// It retrieves the GIT_PROJECT_DIR environment variable and normalizes it.
// If the GIT_PROJECT_DIR starts with "~", it replaces it with the user's home directory.
// The normalized repository URL is then joined with the GIT_PROJECT_DIR to form the project directory path.
// The project directory path is returned as a string.
func getProjectDir(repository string) string {
gitProjectDir := os.Getenv("GIT_PROJECT_DIR")
if strings.HasPrefix(gitProjectDir, "~") {
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
gitProjectDir = filepath.Join(homeDir, gitProjectDir[1:])
}
return filepath.Join(gitProjectDir, normalize(repository))
}
// isDirectoryNotEmpty checks if the specified directory is not empty.
// It uses the Readdirnames function to get the directory contents without loading full FileInfo
// structures for each entry. If there are any entries, it returns true. Otherwise, it returns false.
func isDirectoryNotEmpty(name string) bool {
f, err := os.Open(name)
if err != nil {
return false
}
defer f.Close()
_, err = f.Readdirnames(1)
return err == nil
}
// Usage prints the usage of the program.
func usage() {
fmt.Println("usage: gclone [-h] [-v] [REPOSITORY]")
fmt.Println()
fmt.Println("positional arguments:")
fmt.Println(" REPOSITORY Repository URL")
fmt.Println()
fmt.Println("optional arguments:")
fmt.Println(" -h, --help Show this help message and exit")
fmt.Println(" -v, --version Show the version number and exit")
fmt.Println()
fmt.Println("environment variables:")
fmt.Println(" GIT_PROJECT_DIR Directory to clone repositories")
fmt.Println()
fmt.Println("example:")
fmt.Println(" GIT_PROJECT_DIR=\"$HOME/src\" gclone https://github.com/user/repo")
}
func prnt(format string, args ...any) {
fmt.Fprintf(os.Stderr, format, args...)
fmt.Fprintln(os.Stderr)
}