Debian Codegraph @

gitconfig_test.go

raw
1 package gitconfig
2
3 import (
4 "os"
5 "os/exec"
6 "path/filepath"
7 "sort"
8 "strings"
9 "testing"
10
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 )
14
15 // https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-config.html#EXAMPLES
16 var configSampleDocs = `#
17 # This is the config file, and
18 # a '#' or ';' character indicates
19 # a comment
20 #
21
22 ; core variables
23 [core]
24 ; Don't trust file modes
25 filemode = false
26
27 ; Our diff algorithm
28 [diff]
29 external = /usr/local/bin/diff-wrapper
30 renames = true
31
32 ; Proxy settings
33 [core]
34 gitproxy = default-proxy ; default proxy
35
36 ; HTTP
37 [http]
38 sslVerify
39
40 [http "https://weak.example.com"]
41 sslVerify = false
42 cookieFile = /tmp/cookie.txt
43 `
44
45 var configSampleComplex = `
46 [alias]
47
48 # add
49 a = add # add
50 aa = add --all
51 all = add -A
52 chunkyadd = add --patch # stage commits chunk by chunk
53
54 # branch
55 b = branch -v # branch (verbose)
56 branches = branch -a
57 recent = branch --sort=-committerdate
58
59 # commit
60 c = commit -m
61 ca = commit -am
62 ci = commit
63 credit = "!f() { git commit --amend --author \"$1 <$2>\" -C HEAD; }; f" # Credit an author on the latest commit
64 credit = commit --amend --author "$1 <$2>" -C HEAD
65 amend = commit --amend
66 commend = commit --amend --no-edit
67
68 # checkout
69 co = checkout # checkout
70 nb = checkout -b # create and switch to a new branch (mnemonic: "git new branch branchname...")
71 go = checkout -B # Switch to a branch, creating it if necessary
72
73 # clone
74 cr = clone --recursive # Clone a repository including all submodules
75
76 # cherry-pick
77 cp = cherry-pick -x # grab a change from a branch
78
79 # diff
80 d = !"git diff-index --quiet HEAD -- || clear; git diff --patch-with-stat" # Show the diff between the latest commit and the current state
81 di = diff
82 dc = diff --cached
83 div = divergence # Divergence (commits we added and commits remote added)
84 ds = diff --stat=160,120
85 gn = goodness # Goodness (summary of diff lines added/removed/total)
86 gnc = goodness --cached
87 last = diff HEAD^
88
89 # log
90 l = log --pretty=oneline -n 20 --graph # View the SHA, description, and history graph of the latest 20 commits
91 changes = log --pretty=format:\"%h %cr %cn %Cgreen%s%Creset\" --name-status
92 short = log --pretty=format:\"%h %cr %cn %Cgreen%s%Creset\"
93 changelog = log --pretty=format:\" * %s\"
94 shortnocolor = log --pretty=format:\"%h %cr %cn %s\"
95 show-graph = log --graph --abbrev-commit --pretty=oneline
96
97 # pull
98 please = push --force-with-lease
99 pl = pull
100 fa = fetch --all
101 ff = merge --ff-only
102 noff = merge --no-ff
103 pullff = pull --ff-only
104 p = !"git pull; git submodule foreach git pull origin master" # Pull in remote changes for the current repository and all its submodules
105 pp = !"git pull ; git push origin master"
106 ppd = !"git pull origin develop ; git push origin develop"
107 mdm = !"git checkout master ; git pull origin master ; git push origin master ; git merge develop ; git push origin master ; git checkout develop"
108
109 # push
110 ps = push
111 pom = pull origin master
112 pum = push origin master
113
114 # rebase
115 rc = rebase --continue # continue rebase
116 rs = rebase --skip # skip rebase
117 reb = "!r() { git rebase -i HEAD~$1; }; r" # Interactive rebase with the given number of latest commits
118
119 # remote
120 r = remote -v
121 remotes = remote -v
122
123 # reset
124 unstage = reset HEAD # remove files from index (tracking)
125 uncommit = reset --soft HEAD^ # go back before last commit, with files in uncommitted state
126 undo = reset --soft HEAD^
127 filelog = log -u # show changes to a file
128 mt = mergetool # fire up the merge tool
129
130 # stash
131 ss = stash # stash changes
132 sl = stash list # list stashes
133 sa = stash apply # apply stash (restore changes)
134 sd = stash drop # drop stashes (destroy changes)
135 stsh = stash --keep-index
136 staash = stash --include-untracked
137 staaash = stahs --all
138
139 # status
140 s = status -s # View the current working tree status using the short format
141 st = status # status
142 stat = status # status
143 shorty = status --short --branch
144
145 # tag
146 t = tag -n # show tags with <n> lines of each tag message
147 tags = tag -l # Show verbose output about tags, branches or remotes
148
149 # init
150 it = !"git init && git commit -m "root" --allow-empty"
151
152 # merge
153 merc = merge --no-ff
154 grog = log --graph --abbrev-commit --decorate --all --format=format:\"%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(dim white) - %an%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n %C(white)%s%C(reset)\"
155
156 [apply]
157 # Detect whitespace errors when applying a patch
158 whitespace = fix
159
160 [branch]
161 autosetupmerge = true
162
163 [core]
164 editor = vim
165 excludesfile = ~/.gitignore
166 attributesfile = ~/.gitattributes
167 # Treat spaces before tabs, lines that are indented with 8 or more spaces, and all kinds of trailing whitespace as an error
168 whitespace = space-before-tab,indent-with-non-tab,trailing-space
169 autocrlf = input
170 protectHFS = true
171 protectNTFS = true
172 sshCommand = ssh -oControlMaster=auto -oControlPersist=600 -oControlPath=/tmp/.ssh-%C
173
174 [receive]
175 fsckObjects = true
176 quotepath = false
177
178 [color]
179 # Use colors in Git commands that are capable of colored output when outputting to the terminal
180 ui = auto
181
182 [diff]
183
184 [format]
185 pretty = format:%C(blue)%ad%Creset %C(yellow)%h%C(green)%d%Creset %C(blue)%s %C(magenta) [%an]%Creset
186
187 [mergetool]
188 prompt = false
189
190 #[mergetool "mvimdiff"]
191 # cmd="mvim -c 'Gdiff' $MERGED" # use fugitive.vim for 3-way merge
192 # keepbackup=false
193
194 [merge]
195 # Include summaries of merged commits in newly created merge commit messages
196 log = true
197 summary = true
198 verbosity = 1
199 # tool = mvimdiff
200
201 # Use origin as the default remote on the master branch in all cases
202 [branch "master \""]
203 remote = origin
204 merge = refs/heads/master
205
206 [github]
207 user = johndoe
208
209 # URL shorthands
210 [url "[email protected]:"]
211 insteadOf = "gh:"
212 pushInsteadOf = "github:"
213 pushInsteadOf = "git://github.com/"
214 insteadOf = https://github.com
215
216 [url "git://github.com/"]
217 insteadOf = "github:"
218
219 [url "[email protected]:"]
220 insteadOf = "gst:"
221 pushInsteadOf = "gist:"
222 pushInsteadOf = "git://gist.github.com/"
223
224 [url "git://gist.github.com/"]
225 insteadOf = "gist:"
226
227 [url "[email protected]:"]
228 insteadOf = https://gitlab.com/
229
230 [url "[email protected]:"]
231 insteadOf = http://gitlab.com/
232
233 [user]
234 email = [email protected]
235 name = John Doe
236 signingkey = DEADBEEF
237
238 [push]
239 default = simple
240
241 [gc]
242 auto = 64
243 autopacklimit = 64
244 [pull]
245 rebase = false
246 [init]
247 defaultBranch = master
248 [fetch]
249 prune = true
250
251 [credential]
252 helper = osxkeychain
253
254 `
255
256 var configSampleGopass = `
257 # This is a gopass config file
258
259 [core]
260 autoimport = true
261 cliptimeout = 45
262 editor = vim
263 exportkeys = true
264 pager = false
265 notifications = true
266
267 [generate]
268 autoclip = true
269
270 [show]
271 safecontent = false
272
273 [mounts]
274 path = /home/johndoe/.password-store
275
276 [mounts "foo/sub"]
277 path = /home/johndoe/.password-store-foo-sub
278
279 [mounts "work"]
280 path = /home/johndoe/.password-store-work
281
282 [domain-alias "foo.com"]
283 insteadOf = foo.de
284
285 [domain-alias "foo.com"]
286 insteadOf = foo.it
287 `
288
289 func TestGopassSingleRead(t *testing.T) {
290 t.Parallel()
291
292 c := &Configs{
293 global: ParseConfig(strings.NewReader(configSampleGopass)),
294 }
295 c.global.noWrites = true
296
297 assert.Equal(t, "true", c.Get("generate.autoclip"))
298 assert.Equal(t, "true", c.Get("core.autoimport"))
299 assert.Equal(t, "45", c.Get("core.cliptimeout"))
300 assert.Equal(t, "vim", c.Get("core.editor"))
301 assert.Equal(t, "true", c.Get("core.exportkeys"))
302 assert.Equal(t, "false", c.Get("core.pager"))
303 assert.Equal(t, "true", c.Get("core.notifications"))
304 assert.Equal(t, "false", c.Get("show.safecontent"))
305 assert.Equal(t, []string{"foo.de", "foo.it"}, c.GetAll("domain-alias.foo.com.insteadOf"))
306
307 assert.Equal(t, "/home/johndoe/.password-store", c.Get("mounts.path"))
308 assert.Equal(t, "/home/johndoe/.password-store-foo-sub", c.Get("mounts.foo/sub.path"))
309 assert.Equal(t, "/home/johndoe/.password-store-work", c.Get("mounts.work.path"))
310
311 t.Logf("Raw:\n%s\n", c.global.raw.String())
312 t.Logf("Vars:\n%+v\n", c.global.vars)
313 }
314
315 func TestGopassReadWrite(t *testing.T) {
316 td := t.TempDir()
317 sysCfg := filepath.Join(td, "system", "config")
318 require.NoError(t, os.MkdirAll(filepath.Dir(sysCfg), 0o700))
319 require.NoError(t, os.WriteFile(sysCfg, []byte(`[core]
320 autoimport = true
321 editor = vim
322 cliptimeout = 45
323 exportkeys = true
324 pager = false
325 notifications = true
326 `), 0o600))
327
328 globalCfg := filepath.Join(td, "global", "config")
329 require.NoError(t, os.MkdirAll(filepath.Dir(globalCfg), 0o700))
330 require.NoError(t, os.WriteFile(globalCfg, []byte(`[generate]
331 autoclip = true
332 pager = false
333 [show]
334 safecontent = false
335 [mounts]
336 path = /home/johndoe/.password-store
337 [mounts "foo/sub"]
338 path = /home/johndoe/.password-store-foo-sub
339 [mounts "work"]
340 path = /home/johndoe/.password-store-work
341 [domain-alias "foo.com"]
342 insteadOf = foo.de
343 [domain-alias "foo.com"]
344 insteadOf = foo.it
345 `), 0o600))
346
347 t.Setenv("GOPASS_HOMEDIR", td)
348
349 c := New()
350 c.SystemConfig = sysCfg
351 c.GlobalConfig = filepath.Join("global", "config")
352 c.global.path = globalCfg
353 c.LoadAll(td)
354
355 assert.Equal(t, "true", c.Get("generate.autoclip"))
356 assert.Equal(t, "true", c.Get("core.autoimport"))
357 assert.Equal(t, "45", c.Get("core.cliptimeout"))
358 assert.Equal(t, "vim", c.Get("core.editor"))
359 assert.Equal(t, "true", c.Get("core.exportkeys"))
360 assert.Equal(t, "false", c.Get("core.pager"))
361 assert.Equal(t, "true", c.Get("core.notifications"))
362 assert.Equal(t, "false", c.Get("show.safecontent"))
363 assert.Equal(t, []string{"foo.de", "foo.it"}, c.GetAll("domain-alias.foo.com.insteadOf"))
364
365 assert.Equal(t, "/home/johndoe/.password-store", c.Get("mounts.path"))
366 assert.Equal(t, "/home/johndoe/.password-store-foo-sub", c.Get("mounts.foo/sub.path"))
367 assert.Equal(t, "/home/johndoe/.password-store-work", c.Get("mounts.work.path"))
368
369 t.Logf("Raw:\n%s\n", c.global.raw.String())
370 t.Logf("Vars:\n%+v\n", c.global.vars)
371 }
372
373 func TestParseSimple(t *testing.T) {
374 t.Parallel()
375
376 c := ParseConfig(strings.NewReader(configSampleDocs))
377
378 for k, v := range c.vars {
379 t.Logf("%s => %s\n", k, v)
380 }
381
382 want := map[string]string{
383 "core.filemode": "false",
384 "diff.external": "/usr/local/bin/diff-wrapper",
385 "diff.renames": "true",
386 "core.gitproxy": "default-proxy",
387 // TODO(gitconfig): "http.sslVerify": "", // not supported, yet
388 "http.https://weak.example.com.sslVerify": "false",
389 "http.https://weak.example.com.cookieFile": "/tmp/cookie.txt",
390 }
391
392 for k, w := range want {
393 v, ok := c.Get(k)
394 assert.True(t, ok)
395 assert.Equal(t, w, v)
396 }
397 }
398
399 func TestParseComplex(t *testing.T) {
400 t.Parallel()
401
402 c := ParseConfig(strings.NewReader(configSampleComplex))
403
404 // variable names are case-insensitive
405 _, ok := c.vars["core.sshcommand"]
406 assert.True(t, ok)
407
408 v, ok := c.Get("core.sshCommand")
409 assert.True(t, ok)
410 assert.Equal(t, "ssh -oControlMaster=auto -oControlPersist=600 -oControlPath=/tmp/.ssh-%C", v)
411 }
412
413 func TestParseDocs(t *testing.T) {
414 t.Parallel()
415
416 c := ParseConfig(strings.NewReader(configSampleComplex)) //nolint:staticcheck
417
418 v, ok := c.Get("core.sshCommand")
419 assert.True(t, ok)
420 assert.Equal(t, "ssh -oControlMaster=auto -oControlPersist=600 -oControlPath=/tmp/.ssh-%C", v)
421 }
422
423 func TestSet(t *testing.T) {
424 t.Parallel()
425
426 c := ParseConfig(strings.NewReader(configSampleDocs))
427 c.noWrites = true
428 require.NoError(t, c.Set("core.gitproxy", "foobar"))
429 want := strings.ReplaceAll(configSampleDocs, "default-proxy", "foobar")
430 assert.Equal(t, want, c.raw.String())
431 }
432
433 func TestUnset(t *testing.T) {
434 t.Parallel()
435
436 c := ParseConfig(strings.NewReader(configSampleDocs))
437 c.noWrites = true
438 require.NoError(t, c.Unset("core.filemode"))
439 want := `#
440 # This is the config file, and
441 # a '#' or ';' character indicates
442 # a comment
443 #
444
445 ; core variables
446 [core]
447 ; Don't trust file modes
448
449 ; Our diff algorithm
450 [diff]
451 external = /usr/local/bin/diff-wrapper
452 renames = true
453
454 ; Proxy settings
455 [core]
456 gitproxy = default-proxy ; default proxy
457
458 ; HTTP
459 [http]
460 sslVerify
461
462 [http "https://weak.example.com"]
463 sslVerify = false
464 cookieFile = /tmp/cookie.txt
465 `
466 assert.Equal(t, want, c.raw.String())
467 }
468
469 func TestSetEmptyConfig(t *testing.T) {
470 t.Parallel()
471
472 td := t.TempDir()
473 c := &Config{
474 path: filepath.Join(td, "config"),
475 noWrites: false,
476 }
477 require.Error(t, c.Set("foobar", "baz"))
478 require.NoError(t, c.Set("foo.bar", "baz"))
479
480 v, ok := c.Get("foo.bar")
481 assert.True(t, ok)
482 assert.Equal(t, "baz", v)
483
484 buf, err := os.ReadFile(c.path)
485 require.NoError(t, err)
486 assert.Equal(t, "[foo]\n\tbar = baz\n", string(buf))
487 }
488
489 func TestList(t *testing.T) {
490 t.Parallel()
491
492 c := &Configs{
493 global: ParseConfig(strings.NewReader(configSampleGopass)),
494 }
495 c.global.noWrites = true
496 assert.Equal(t, []string{
497 "mounts.foo/sub.path",
498 "mounts.path",
499 "mounts.work.path",
500 }, c.List("mounts."))
501 }
502
503 func TestListSections(t *testing.T) {
504 t.Parallel()
505
506 c := &Configs{global: ParseConfig(strings.NewReader(configSampleGopass))}
507 c.global.noWrites = true
508 assert.Equal(t, []string{"core", "domain-alias", "generate", "mounts", "show"}, c.ListSections())
509 }
510
511 func TestListSubsections(t *testing.T) {
512 t.Parallel()
513
514 c := &Configs{global: ParseConfig(strings.NewReader(configSampleGopass))}
515 c.global.noWrites = true
516 assert.Equal(t, []string{"foo/sub", "work"}, c.ListSubsections("mounts"))
517 }
518
519 func TestGitBinary(t *testing.T) {
520 t.Skip("not ready, yet") // TODO(gitconfig) make tests pass
521
522 cfgs := New()
523 cfgs.LoadAll(".")
524
525 cmd := exec.Command("git", "config", "--list")
526 buf, err := cmd.Output()
527 require.NoError(t, err)
528 lines := strings.Split(string(buf), "\n")
529 for _, line := range lines {
530 p := strings.SplitN(line, "=", 2)
531 if len(p) < 2 {
532 continue
533 }
534 key := p[0]
535 want := p[1]
536
537 assert.Equal(t, want, cfgs.Get(key), key)
538 }
539 }
540
541 func TestGitCliList(t *testing.T) {
542 t.Parallel()
543
544 t.Skip("not ready, yet") // TODO(gitconfig) make tests pass
545
546 c := New()
547 c.NoWrites = true
548 c.LoadAll("./.git")
549
550 cmd := exec.CommandContext(t.Context(), "git", "config", "--list")
551 buf, err := cmd.Output()
552 require.NoError(t, err)
553 cliOut := strings.Split(string(buf), "\n")
554 sort.Strings(cliOut)
555 // filter invalid lines and duplicates
556 cliOut = func(s []string) []string {
557 prev := ""
558 out := make([]string, 0, len(s))
559 for _, l := range s {
560 if !strings.Contains(l, "=") {
561 continue
562 }
563 if l == prev {
564 continue
565 }
566 out = append(out, l)
567 prev = l
568 }
569
570 return out
571 }(cliOut)
572
573 libOut := c.KVList("", "=")
574 // filter duplicates
575 libOut = func(s []string) []string {
576 prev := ""
577 out := make([]string, 0, len(s))
578 for _, l := range s {
579 if l == prev {
580 continue
581 }
582 out = append(out, l)
583 prev = l
584 }
585
586 return out
587 }(libOut)
588
589 // TODO: Enable this asserting when we have burned down all diffs.
590 // assert.Equal(t, cliOut, libOut)
591
592 diffs := 0
593 t.Logf("% 38s | % 38s | % 5s", "CLI", "LIB", "DIFF")
594 for i := 0; i < len(cliOut) || i < len(libOut); i++ {
595 left := ""
596 right := ""
597
598 if i < len(cliOut) {
599 left = cliOut[i]
600 }
601 if i < len(libOut) {
602 right = libOut[i]
603 }
604 left = strings.TrimSpace(left)
605 right = strings.TrimSpace(right)
606
607 // t.Logf("% 38s | % 38s | %t", left, right, left != right)
608 if left != right {
609 t.Logf("% 38s | % 38s | %t", left, right, left != right)
610 diffs++
611 }
612 }
613 assert.Zero(t, diffs, "There are %d differences between the CLI and the library output", diffs)
614 }