-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
450 lines (383 loc) · 10 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package main
// @TODO support list all users with author syntax, e.g.: "Author Name <[email protected]>"
// @TODO change remote urls to user urls, according to some funky scheme e.g. github.com => github-author-name.com
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"strconv"
"strings"
)
const (
// SSHWrapper a wrapper around ssh that uses the env var SSH_IDENTITY_FILE for the -i param, needed for `clone`
SSHWrapper = "ssh-i-from-env"
// SSHWrapperInstruction a text that's printed in case the wrapper is missing
SSHWrapperInstruction = `the wrapper: 'ssh-i-from-env' is missing!
create it according to the following template and add it to your path:
#!/bin/bash
ssh -i "$SSH_IDENTITY_FILE" $*
`
)
type GitConfig struct {
User
// either LOCAL or GLOBAL
Source string
SshCommand string
}
type User struct {
Short string `json:"short"`
Name string `json:"name"`
Email string `json:"email"`
PrivKey string `json:"privkey"`
}
type Users []User
type UserStatusFlag int
const (
UserStatusEmpty UserStatusFlag = iota
UserStatusFound
UserStatusUnknown
UserStatusNoGitDir
)
type UserStatus struct {
status UserStatusFlag
name string
}
func getDefinedGitUsers(path string) (result *Users, err error) {
contents, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
err = json.Unmarshal(contents, &result)
if err != nil {
return nil, err
}
return result, nil
}
// try to load git user from given path
func getGitConfig(fpath string) (result *GitConfig, err error) {
result = &GitConfig{}
rawGitConfig, err := ioutil.ReadFile(fpath)
if err != nil {
return nil, err
}
splitEquals := func(line string) (lhs string, rhs string, err error) {
words := strings.Split(line, "=")
if len(words) != 2 {
return "", "", fmt.Errorf("failed to split '%s' into 2 words through '='", line)
}
lhs = strings.TrimSpace(words[0])
rhs = strings.TrimSpace(words[1])
return lhs, rhs, nil
}
var userLines = make([]string, 0)
var sshCommand = ""
{ // iterate over lines of local git config
foundUserBlock := false
scanner := bufio.NewScanner(strings.NewReader(string(rawGitConfig)))
for scanner.Scan() {
text := scanner.Text()
stext := strings.TrimSpace(text)
if strings.HasPrefix(stext, ";") { // skip commments
continue
}
if strings.Contains(text, `sshCommand =`) {
_, rhs, err := splitEquals(text)
if err != nil {
return nil, err
}
sshCommand = rhs
continue
}
if foundUserBlock {
if strings.HasPrefix(text, "[") {
break
} else {
userLines = append(userLines, text)
}
} else {
if text == "[user]" {
foundUserBlock = true
}
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
}
if len(userLines) == 0 {
return nil, nil
}
result.SshCommand = sshCommand
for _, line := range userLines {
lhs, rhs, err := splitEquals(line)
if err != nil {
return nil, err
}
switch lhs {
case "name":
result.Name = rhs
result.Short = rhs
case "email":
result.Email = rhs
default:
return nil, fmt.Errorf("unsupported user key %s in line: %s", lhs, line)
}
}
return result, nil
}
func exitError() {
fmt.Printf("%%{$fg[red]%%}%s%%{${reset_color}%%}", "!")
os.Exit(1)
}
func main() {
var definedUsers *Users
var homeDir string
{ // load definedUsers
user, err := user.Current()
if err != nil {
panic(err)
}
homeDir = user.HomeDir
definedUsers, err = getDefinedGitUsers(path.Join(homeDir, ".config", "gitusers.json"))
if err != nil {
panic(err)
}
}
var assertGitDir func() error
var gitDir string
{ // walk upwards finding .git dir
wd, err := os.Getwd()
if err != nil {
panic(err)
}
originalWd := wd
var prepath string
walkUpwards:
for ; prepath != wd; wd = filepath.Dir(wd) {
prepath = wd
files, err := ioutil.ReadDir(wd)
if err != nil {
panic(err)
}
for _, f := range files {
if f.Name() == ".git" {
gitDir = path.Join(wd, f.Name())
// check if file is dir
if fi, err := os.Stat(gitDir); err != nil {
panic(err)
} else if !fi.IsDir() { // isFile
// assume its a submodule and follow the contents written therein
gitDirLinkRaw, err := ioutil.ReadFile(gitDir)
if err != nil {
panic(err)
}
gitDirLink := strings.TrimLeft(strings.TrimSpace(string(gitDirLinkRaw)), "gitdir: ")
gitDirParent := filepath.Dir(gitDir)
gitDir = filepath.Clean(path.Join(gitDirParent, string(gitDirLink)))
}
break walkUpwards
}
}
}
assertGitDir = func() error {
if gitDir == "" {
return fmt.Errorf("could not find .gitdir in %s", originalWd)
}
return nil
}
}
var cfg *GitConfig
if gitDir != "" { // load current from either local or global git config
var err error
// try local first
cfg, err = getGitConfig(path.Join(gitDir, "config"))
if err != nil {
exitError()
}
if cfg != nil {
cfg.Source = "LOCAL"
} else { // couldn't find local
// @TODO support other possible gitconfig paths
cfg, err = getGitConfig(path.Join(homeDir, ".gitconfig"))
if err != nil {
panic(err)
}
if cfg != nil {
cfg.Source = "GLOBAL"
}
}
}
expectedSshCommand := func(user *User) string {
if user.PrivKey != "" {
return fmt.Sprintf(`ssh -i %s`, user.PrivKey)
} else {
return fmt.Sprintf(`ssh`)
}
}
queryUserStatus := func() UserStatus {
err := assertGitDir()
if err != nil {
return UserStatus{status: UserStatusNoGitDir}
}
if cfg == nil {
return UserStatus{status: UserStatusEmpty}
}
// check if we know the current user
for _, defUser := range *definedUsers {
if cfg.Name == defUser.Name &&
cfg.Email == defUser.Email &&
cfg.SshCommand == expectedSshCommand(&defUser) {
return UserStatus{status: UserStatusFound, name: defUser.Short}
}
}
// so we don't know the current user
return UserStatus{status: UserStatusUnknown, name: cfg.Short}
}
// @TODO CLI autocompl
{ // check or set user
args := os.Args[1:]
if len(args) == 0 { // check
userStatus := queryUserStatus()
switch userStatus.status {
case UserStatusEmpty:
fmt.Printf("%%{$fg[red]%%}%s", "NONE")
os.Exit(0)
case UserStatusFound:
fmt.Print(userStatus.name)
os.Exit(0)
case UserStatusUnknown:
fmt.Printf("%%{$fg[red]%%}%s", userStatus.name)
}
os.Exit(0)
} else if len(args) == 1 &&
!strings.HasPrefix(args[0], "-") {
err := assertGitDir()
if err != nil {
panic(err)
}
setUser := args[0]
for _, defUser := range *definedUsers { // set
if defUser.Short == setUser ||
defUser.Name == setUser ||
defUser.Email == setUser {
ret, _, serr := runEnv("git", []string{"config", "user.name", defUser.Name}, []string{})
if ret != 0 {
panic(serr)
}
ret, _, serr = runEnv("git", []string{"config", "user.email", defUser.Email}, []string{})
if ret != 0 {
panic(serr)
}
ret, _, serr = runEnv("git", []string{"config", "core.sshCommand", expectedSshCommand(&defUser)}, []string{})
if ret != 0 {
panic(serr)
}
os.Exit(0)
}
}
// we could not match setUser with anything
log.Fatalf("could not find a defined user matching %s, defined users: %v", setUser, definedUsers)
} else if len(args) == 1 && args[0] == "-l" { // list
err := assertGitDir()
if err != nil {
panic(err)
}
for _, user := range *definedUsers {
fmt.Printf("%v\n", user)
}
} else if len(args) == 1 && args[0] == "-g" { // get
userStatus := queryUserStatus()
switch userStatus.status {
case UserStatusFound:
fmt.Println(userStatus.name)
os.Exit(0)
default:
os.Exit(1)
}
os.Exit(0)
} else if len(args) == 1 && args[0] == "-p" { // prompt
outCloseParen := "%{$fg[yellow]%})%{${reset_color}%}"
userStatus := queryUserStatus()
if userStatus.status == UserStatusNoGitDir {
os.Exit(0)
}
fmt.Print("%{$fg[yellow]%}(%{${reset_color}%}")
switch userStatus.status {
case UserStatusEmpty:
fmt.Printf("%%{$fg[red]%%}%s", "NONE")
case UserStatusFound:
fmt.Print(userStatus.name)
case UserStatusUnknown:
fmt.Printf("%%{$fg[red]%%}%s", userStatus.name)
}
fmt.Print("%{$fg[yellow]%};%{${reset_color}%}")
gitStatus := fetchGitStatus(":")
if gitStatus == nil {
fmt.Print("%{$fg[red]%}detached HEAD" + outCloseParen)
os.Exit(0)
}
fmt.Print("%{$fg[magenta]%}" + gitStatus.branch + "%{${reset_color}%}")
if gitStatus.depth > 1 {
fmt.Print("%{$fg[yellow]%}" + DigitsToSuperscript(strconv.Itoa(gitStatus.depth)) + "%{${reset_color}%}")
}
{ // post
var post string
{ // collect post
if gitStatus.ahead > 0 {
post += "↑" + strconv.Itoa(gitStatus.ahead)
}
if gitStatus.behind > 0 {
post += "↓" + strconv.Itoa(gitStatus.behind)
}
if gitStatus.stashes > 0 {
post += "≡" + strconv.Itoa(gitStatus.stashes)
}
if gitStatus.changed > 0 {
post += "☇" + strconv.Itoa(gitStatus.changed)
}
if gitStatus.staged > 0 {
post += "★"
}
}
if len(post) > 0 {
fmt.Print(" " + post)
}
}
fmt.Print(outCloseParen)
os.Exit(0)
} else if len(args) >= 3 && args[1] == "clone" { // <user> clone ...
user := args[0]
src := args[2]
restargs := args[3:]
for _, defUser := range *definedUsers { // set
if defUser.Short == user ||
defUser.Name == user ||
defUser.Email == user {
_, err := exec.LookPath(SSHWrapper)
if err != nil {
log.Fatalf(SSHWrapperInstruction)
}
cloneArgs := []string{fmt.Sprintf("GIT_SSH=%s", "ssh-i-from-env")}
if defUser.PrivKey != "" {
cloneArgs = append(cloneArgs, fmt.Sprintf("SSH_IDENTITY_FILE=%s", defUser.PrivKey))
}
ret, _, serr := runEnv("git", append([]string{"clone", src}, restargs...), cloneArgs)
if ret != 0 {
panic(serr)
}
os.Exit(0)
}
}
log.Fatalf("could not find a defined user matching %s, defined users: %v", user, definedUsers)
} else {
panic("unsupported argument")
}
}
}