-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
290 lines (264 loc) · 7.6 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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Package main provides main command. It is used to sync all the git repositories in a directory with their remote repositories.
// It uses the 'find' command to get all the directories in the path specified by the user.
// It then runs the 'git -C pull --all' command in each directory.
// It also provides the option to save the list of git repositories to a file.
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"syscall"
)
var flags struct {
path string
fileName string
pull bool
list bool
help bool
export bool
toImport bool
}
func main() {
flag.StringVar(&flags.path, "path", ".", "Path to the directory containing git repositories")
flag.StringVar(&flags.fileName, "file", "", "File name to save the list of git repositories")
flag.BoolVar(&flags.pull, "pull", false, "Pull all the git repositories")
flag.BoolVar(&flags.list, "list", false, "List all the git repositories")
flag.BoolVar(&flags.help, "help", false, "Show help")
flag.BoolVar(&flags.export, "export", false, "Export all the git repositories to a JSON file")
flag.BoolVar(&flags.toImport, "import", false, "Import all the git repositories from a JSON file")
flag.Parse()
// check if no arguments are specified
if flags.help || len(os.Args) == 1 {
flag.Usage()
os.Exit(0)
}
path := parsePath(flags.path)
list := getDirectories(path)
if flags.list {
urls := getGitRepos(list)
if flags.fileName != "" {
saveToFile(flags.fileName, urls)
} else {
printList(urls)
}
}
if flags.pull {
pullGitRepos(list)
os.Exit(0)
}
if flags.export {
repoData := getExportData(list)
exportJSON(repoData)
os.Exit(0)
}
if flags.toImport {
jsonData := importJSON(flags.fileName)
createRepos(jsonData)
os.Exit(0)
}
}
// getDirectories function uses the 'path' argument to get all the directories in the path.
// It returns a list of directories as a string slice
func getDirectories(path string) []string {
output, err := exec.Command("find", path, "-type", "d", "-name", ".git", "-not", "-path", "*/.git/modules/*").
Output()
if err != nil {
log.Printf("Error in getting directories: %s", err)
}
return strings.Split(string(output), "\n")
}
// getGitRepos function gets the git repositories from the list of directories
func getGitRepos(list []string) (urls []string) {
urls = make([]string, 0, len(list))
wg := sync.WaitGroup{}
wg.Add(len(list))
for _, dir := range list {
go func(dir string) {
defer wg.Done()
dir = strings.TrimSuffix(dir, "/.git")
cmd, err := exec.Command("git", "-C", dir, "config", "--get", "remote.origin.url").Output()
if err != nil {
log.Printf("Error in getting git repo url %s, %s", dir, err)
return
}
urls = append(urls, string(cmd))
}(dir)
}
wg.Wait()
return urls
}
// pullGitRepos function uses goroutines to run the 'git -C pull --all' command in parallel
func pullGitRepos(list []string) {
wg := sync.WaitGroup{}
wg.Add(len(list))
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
for _, dir := range list {
go func(dir string) {
defer wg.Done()
if err := runCommand(dir, c); err != nil {
log.Print(err)
}
}(dir)
}
wg.Wait()
}
// runCommand function runs the 'git -C pull --all' command in the directory specified by the 'dir' argument
func runCommand(dir string, c chan os.Signal) (err error) {
dir = strings.TrimSuffix(dir, "/.git")
cmd := exec.Command("git", "-C", dir, "pull", "--all")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
log.Fatalf("Error starting pulling process %s, %s", dir, err)
}
select {
case <-c:
log.Fatal(cmd.Process.Kill())
default:
err = cmd.Wait()
}
return err
}
// parsePath function parses the path argument and returns the path as a string
// It also checks if the path is valid
func parsePath(path string) string {
if path == "." {
path, _ = os.Getwd()
return path
}
if strings.HasPrefix(path, "~/") {
home, _ := os.UserHomeDir()
path = strings.Replace(path, "~/", home, 1)
}
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
log.Fatal("Path does not exists. Please specify a valid path")
}
log.Fatalf("Error in getting path: %s", err)
}
return path
}
// printList function prints the list of git repositories. It is used when the user does not specify a file name.
func printList(list []string) {
for _, url := range list {
fmt.Println(url)
}
}
// saveToFile function saves the list of git repositories to a file. The file name is specified by the 'file' argument
func saveToFile(fileName string, list []string) {
file, err := os.Create(fileName)
if err != nil {
log.Fatalf("Error in creating file: %s", err)
}
defer file.Close()
for _, url := range list {
file.WriteString(url)
}
}
// getExportData function gets the data to export to JSON
func getExportData(dirs []string) (jsonData map[string]string) {
jsonData = make(map[string]string, len(dirs))
wg := sync.WaitGroup{}
wg.Add(len(dirs))
mtx := sync.Mutex{}
prefix := parsePath(flags.path) + "/"
for _, dir := range dirs {
go func(dir string) {
defer wg.Done()
if dir == "" {
return
}
data := getGitRepo(dir)
dir = strings.TrimPrefix(strings.TrimSuffix(dir, "/.git"), prefix)
mtx.Lock()
jsonData[dir] = data
mtx.Unlock()
}(dir)
}
wg.Wait()
return jsonData
}
// // getGitRepo function gets the git repository from the directory
func getGitRepo(dir string) string {
output, err := exec.Command("git", "-C", dir, "config", "--get", "remote.origin.url").Output()
if err != nil {
log.Fatalf("Error getting git repo from %s: %s", dir, err)
}
return strings.TrimSpace(string(output))
}
// saveFile function saves the data to a file
func saveFile(filename string, data []byte) {
if err := os.WriteFile(filename, data, 0644); err != nil {
log.Fatalf("Error saving file: %s, %s", filename, err)
}
}
// exportJSON function exports the data to a JSON file
func exportJSON(data map[string]string) {
result, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Fatalf("Error marshalling JSON: %s", err)
}
fileName := flags.fileName
if fileName == "" {
fileName = "export.json"
} else if !strings.HasSuffix(fileName, ".json") {
fileName += ".json"
}
saveFile(fileName, result)
}
// importJSON function imports the data from a JSON file
func importJSON(filename string) (jsonData map[string]string) {
if filename == "" {
log.Println("No filename specified, using 'export.json'")
filename = "export.json"
}
data, err := os.ReadFile(filename)
if err != nil {
log.Fatalf("Error reading file: %s, %s", filename, err)
}
if err = json.Unmarshal(data, &jsonData); err != nil {
log.Fatalf("Error unmarshalling JSON: %s", err)
}
return jsonData
}
// createRepos function creates the git repositories
func createRepos(data map[string]string) {
wg := sync.WaitGroup{}
wg.Add(len(data))
importPath := parsePath(flags.path) + "/"
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
for dir, url := range data {
go func(dir, url string) {
defer wg.Done()
dir = importPath + dir
if err := os.MkdirAll(dir, 0755); err != nil {
log.Fatalf("Error creating directory: %s, %s", dir, err)
}
clone(dir, url, c)
}(dir, url)
}
wg.Wait()
}
// clone function clones the git repository
func clone(dir, url string, c chan os.Signal) {
cmd := exec.Command("git", "clone", url, dir)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
log.Fatalf("Error starting clone process %s, %s", url, err)
}
select {
case <-c:
log.Fatal(cmd.Process.Kill())
default:
cmd.Wait()
}
}