Welcome to mirror list, hosted at ThFree Co, Russian Federation.

command_factory_test.go « git « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f1dfca0b489435a8bcf3a502631734e2e13f3bf9 (plain)
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
package git_test

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io/fs"
	"net/http"
	"net/http/httptest"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"syscall"
	"testing"

	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/gitaly/v16/internal/git"
	"gitlab.com/gitlab-org/gitaly/v16/internal/git/gittest"
	"gitlab.com/gitlab-org/gitaly/v16/internal/git/trace2"
	"gitlab.com/gitlab-org/gitaly/v16/internal/git/trace2hooks"
	"gitlab.com/gitlab-org/gitaly/v16/internal/gitaly/config"
	"gitlab.com/gitlab-org/gitaly/v16/internal/helper/text"
	"gitlab.com/gitlab-org/gitaly/v16/internal/log"
	"gitlab.com/gitlab-org/gitaly/v16/internal/testhelper"
	"gitlab.com/gitlab-org/gitaly/v16/internal/testhelper/testcfg"
	"gitlab.com/gitlab-org/gitaly/v16/internal/tracing"
)

func TestGitCommandProxy(t *testing.T) {
	cfg := testcfg.Build(t)

	requestReceived := false

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requestReceived = true
	}))
	defer ts.Close()

	t.Setenv("http_proxy", ts.URL)

	ctx := testhelper.Context(t)

	dir := testhelper.TempDir(t)

	gitCmdFactory, cleanup, err := git.NewExecCommandFactory(cfg, testhelper.SharedLogger(t))
	require.NoError(t, err)
	defer cleanup()

	cmd, err := gitCmdFactory.NewWithoutRepo(ctx, git.Command{
		Name: "clone",
		Args: []string{"http://gitlab.com/bogus-repo", dir},
	}, git.WithDisabledHooks())
	require.NoError(t, err)

	err = cmd.Wait()
	require.NoError(t, err)
	require.True(t, requestReceived)
}

// Global git configuration is only disabled in tests for now. Gitaly should stop using the global
// git configuration in 15.0. See https://gitlab.com/gitlab-org/gitaly/-/issues/3617.
func TestExecCommandFactory_globalGitConfigIgnored(t *testing.T) {
	cfg := testcfg.Build(t)

	gitCmdFactory, cleanup, err := git.NewExecCommandFactory(cfg, testhelper.SharedLogger(t))
	require.NoError(t, err)
	defer cleanup()

	tmpHome := testhelper.TempDir(t)
	require.NoError(t, os.WriteFile(filepath.Join(tmpHome, ".gitconfig"), []byte(`[ignored]
	value = true
`,
	), os.ModePerm))
	ctx := testhelper.Context(t)

	for _, tc := range []struct {
		desc   string
		filter string
	}{
		{desc: "global", filter: "--global"},
		// The test doesn't override the system config as that would be a global change or would
		// require chrooting. The assertion won't catch problems on systems that do not have system
		// level configuration set.
		{desc: "system", filter: "--system"},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			var stdout strings.Builder
			cmd, err := gitCmdFactory.NewWithoutRepo(ctx, git.Command{
				Name:  "config",
				Flags: []git.Option{git.Flag{Name: "--list"}, git.Flag{Name: tc.filter}},
			}, git.WithEnv("HOME="+tmpHome), git.WithStdout(&stdout))
			require.NoError(t, err)
			require.NoError(t, cmd.Wait())
			require.Empty(t, stdout.String())
		})
	}
}

func TestExecCommandFactory_gitConfiguration(t *testing.T) {
	t.Parallel()

	ctx := testhelper.Context(t)
	cfg := testcfg.Build(t)

	repo, repoPath := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{
		SkipCreationViaService: true,
	})
	require.NoError(t, os.Remove(filepath.Join(repoPath, "config")))

	defaultConfig := func() []string {
		commandFactory, cleanup, err := git.NewExecCommandFactory(cfg, testhelper.SharedLogger(t))
		require.NoError(t, err)
		defer cleanup()

		globalConfig, err := commandFactory.GlobalConfiguration(ctx)
		require.NoError(t, err)

		var configEntries []string
		for _, config := range globalConfig {
			configEntries = append(configEntries, fmt.Sprintf(
				"%s=%s", strings.ToLower(config.Key), config.Value,
			))
		}
		return configEntries
	}

	for _, tc := range []struct {
		desc           string
		config         []config.GitConfig
		options        []git.CmdOpt
		expectedConfig []string
	}{
		{
			desc:           "without config",
			expectedConfig: defaultConfig(),
		},
		{
			desc: "config with simple entry",
			config: []config.GitConfig{
				{Key: "core.foo", Value: "bar"},
			},
			expectedConfig: append(defaultConfig(), "core.foo=bar"),
		},
		{
			desc: "config with empty value",
			config: []config.GitConfig{
				{Key: "core.empty", Value: ""},
			},
			expectedConfig: append(defaultConfig(), "core.empty="),
		},
		{
			desc: "config with subsection",
			config: []config.GitConfig{
				{Key: "http.http://example.com.proxy", Value: "http://proxy.example.com"},
			},
			expectedConfig: append(defaultConfig(), "http.http://example.com.proxy=http://proxy.example.com"),
		},
		{
			desc: "config with multiple keys",
			config: []config.GitConfig{
				{Key: "core.foo", Value: "initial"},
				{Key: "core.foo", Value: "second"},
			},
			expectedConfig: append(defaultConfig(), "core.foo=initial", "core.foo=second"),
		},
		{
			desc: "option",
			options: []git.CmdOpt{
				git.WithConfig(git.ConfigPair{Key: "core.foo", Value: "bar"}),
			},
			expectedConfig: append(defaultConfig(), "core.foo=bar"),
		},
		{
			desc: "multiple options",
			options: []git.CmdOpt{
				git.WithConfig(
					git.ConfigPair{Key: "core.foo", Value: "initial"},
					git.ConfigPair{Key: "core.foo", Value: "second"},
				),
			},
			expectedConfig: append(defaultConfig(), "core.foo=initial", "core.foo=second"),
		},
		{
			desc: "config comes after options",
			config: []config.GitConfig{
				{Key: "from.config", Value: "value"},
			},
			options: []git.CmdOpt{
				git.WithConfig(
					git.ConfigPair{Key: "from.option", Value: "value"},
				),
			},
			expectedConfig: append(defaultConfig(), "from.option=value", "from.config=value"),
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			cfg.Git.Config = tc.config

			commandFactory, cleanup, err := git.NewExecCommandFactory(cfg, testhelper.SharedLogger(t))
			require.NoError(t, err)
			defer cleanup()

			var stdout bytes.Buffer
			cmd, err := commandFactory.New(ctx, repo, git.Command{
				Name: "config",
				Flags: []git.Option{
					git.Flag{Name: "--list"},
				},
			}, append(tc.options, git.WithStdout(&stdout))...)
			require.NoError(t, err)
			require.NoError(t, cmd.Wait())
			require.Equal(t, tc.expectedConfig, strings.Split(text.ChompBytes(stdout.Bytes()), "\n"))
		})
	}
}

func TestCommandFactory_ExecutionEnvironment(t *testing.T) {
	testhelper.Unsetenv(t, "GITALY_TESTING_GIT_BINARY")
	testhelper.Unsetenv(t, "GITALY_TESTING_BUNDLED_GIT_PATH")

	ctx := testhelper.Context(t)

	assertExecEnv := func(t *testing.T, cfg config.Cfg, expectedExecEnv git.ExecutionEnvironment) {
		t.Helper()
		gitCmdFactory, cleanup, err := git.NewExecCommandFactory(cfg, testhelper.SharedLogger(t), git.WithSkipHooks())
		require.NoError(t, err)
		defer cleanup()

		// We need to compare the execution environments manually because they also have
		// some private variables which we cannot easily check here.
		actualExecEnv := gitCmdFactory.GetExecutionEnvironment(ctx)
		require.Equal(t, expectedExecEnv.BinaryPath, actualExecEnv.BinaryPath)
		require.Equal(t, expectedExecEnv.EnvironmentVariables, actualExecEnv.EnvironmentVariables)
	}

	t.Run("set in config", func(t *testing.T) {
		assertExecEnv(t, config.Cfg{
			Git: config.Git{
				BinPath: "/path/to/myGit",
			},
		}, git.ExecutionEnvironment{
			BinaryPath: "/path/to/myGit",
			EnvironmentVariables: []string{
				"LANG=en_US.UTF-8",
				"GIT_TERMINAL_PROMPT=0",
				"GIT_CONFIG_GLOBAL=/dev/null",
				"GIT_CONFIG_SYSTEM=/dev/null",
				"XDG_CONFIG_HOME=/dev/null",
			},
		})
	})

	t.Run("set using GITALY_TESTING_GIT_BINARY", func(t *testing.T) {
		t.Setenv("GITALY_TESTING_GIT_BINARY", "/path/to/env_git")

		assertExecEnv(t, config.Cfg{}, git.ExecutionEnvironment{
			BinaryPath: "/path/to/env_git",
			EnvironmentVariables: []string{
				"NO_SET_GIT_TEMPLATE_DIR=YesPlease",
				"LANG=en_US.UTF-8",
				"GIT_TERMINAL_PROMPT=0",
				"GIT_CONFIG_GLOBAL=/dev/null",
				"GIT_CONFIG_SYSTEM=/dev/null",
				"XDG_CONFIG_HOME=/dev/null",
			},
		})
	})

	t.Run("set using GITALY_TESTING_BUNDLED_GIT_PATH", func(t *testing.T) {
		writeExecutables := func(t *testing.T, dir string, executables ...string) {
			for _, executable := range executables {
				testhelper.WriteExecutable(t, filepath.Join(dir, executable), nil)
			}
		}

		missingBinaryError := func(dir, binary string) error {
			return fmt.Errorf("setting up Git execution environment: %w",
				fmt.Errorf("constructing Git environment: %w",
					fmt.Errorf("statting %q: %w", binary,
						&fs.PathError{
							Op:   "stat",
							Path: filepath.Join(dir, binary),
							Err:  syscall.ENOENT,
						},
					),
				),
			)
		}

		type setupData struct {
			binaryDir     string
			bundledGitDir string
			expectedErr   error
		}

		for _, tc := range []struct {
			desc  string
			setup func(t *testing.T) setupData
		}{
			{
				desc: "unset binary directory",
				setup: func(t *testing.T) setupData {
					return setupData{
						binaryDir:     "",
						bundledGitDir: "/does/not/exist",
						expectedErr: fmt.Errorf("setting up Git execution environment: %w",
							fmt.Errorf("constructing Git environment: %w",
								errors.New("cannot use bundled binaries without bin path being set"),
							),
						),
					}
				},
			},
			{
				desc: "missing directory",
				setup: func(t *testing.T) setupData {
					return setupData{
						binaryDir:     testhelper.TempDir(t),
						bundledGitDir: "/does/not/exist",
						expectedErr:   missingBinaryError("/does/not/exist", "gitaly-git-v2.38"),
					}
				},
			},
			{
				desc: "missing gitaly-git",
				setup: func(t *testing.T) setupData {
					bundledGitDir := testhelper.TempDir(t)

					return setupData{
						binaryDir:     testhelper.TempDir(t),
						bundledGitDir: bundledGitDir,
						expectedErr:   missingBinaryError(bundledGitDir, "gitaly-git-v2.38"),
					}
				},
			},
			{
				desc: "missing gitaly-git-remote-http",
				setup: func(t *testing.T) setupData {
					bundledGitDir := testhelper.TempDir(t)

					writeExecutables(t, bundledGitDir, "gitaly-git-v2.38")

					return setupData{
						binaryDir:     testhelper.TempDir(t),
						bundledGitDir: bundledGitDir,
						expectedErr:   missingBinaryError(bundledGitDir, "gitaly-git-remote-http-v2.38"),
					}
				},
			},
			{
				desc: "missing gitaly-git-http-backend",
				setup: func(t *testing.T) setupData {
					bundledGitDir := testhelper.TempDir(t)

					writeExecutables(t, bundledGitDir,
						"gitaly-git-v2.38",
						"gitaly-git-remote-http-v2.38",
					)

					return setupData{
						binaryDir:     testhelper.TempDir(t),
						bundledGitDir: bundledGitDir,
						expectedErr:   missingBinaryError(bundledGitDir, "gitaly-git-http-backend-v2.38"),
					}
				},
			},
			{
				desc: "successful",
				setup: func(t *testing.T) setupData {
					bundledGitDir := testhelper.TempDir(t)
					writeExecutables(t, bundledGitDir, "gitaly-git-v2.38", "gitaly-git-remote-http-v2.38", "gitaly-git-http-backend-v2.38")

					return setupData{
						binaryDir:     testhelper.TempDir(t),
						bundledGitDir: bundledGitDir,
					}
				},
			},
		} {
			t.Run(tc.desc, func(t *testing.T) {
				setupData := tc.setup(t)
				t.Setenv("GITALY_TESTING_BUNDLED_GIT_PATH", setupData.bundledGitDir)

				gitCmdFactory, cleanup, err := git.NewExecCommandFactory(
					config.Cfg{
						BinDir: setupData.binaryDir,
					},
					testhelper.SharedLogger(t),
					git.WithSkipHooks(),
					// Override the constructors so that we don't have to change
					// tests every time we're upgrading our bundled Git version.
					git.WithExecutionEnvironmentConstructors(
						git.BundledGitEnvironmentConstructor{
							Suffix: "-v2.38",
						},
					),
				)
				require.Equal(t, setupData.expectedErr, err)
				if err != nil {
					return
				}
				defer cleanup()

				// When the command factory has been successfully created then we
				// verify that the symlink that it has created match what we expect.
				gitBinPath := gitCmdFactory.GetExecutionEnvironment(ctx).BinaryPath
				for _, executable := range []string{"git", "git-remote-http", "git-http-backend"} {
					symlinkPath := filepath.Join(filepath.Dir(gitBinPath), executable)

					// The symlink in Git's temporary BinPath points to the Git
					// executable in Gitaly's BinDir.
					target, err := os.Readlink(symlinkPath)
					require.NoError(t, err)
					require.Equal(t, filepath.Join(setupData.binaryDir, "gitaly-"+executable+"-v2.38"), target)

					// And in a test setup, the symlink in Gitaly's BinDir must point to
					// the Git binary pointed to by the GITALY_TESTING_BUNDLED_GIT_PATH
					// environment variable.
					target, err = os.Readlink(target)
					require.NoError(t, err)
					require.Equal(t, filepath.Join(setupData.bundledGitDir, "gitaly-"+executable+"-v2.38"), target)
				}
			})
		}
	})

	t.Run("not set, get from system", func(t *testing.T) {
		resolvedPath, err := exec.LookPath("git")
		require.NoError(t, err)

		assertExecEnv(t, config.Cfg{}, git.ExecutionEnvironment{
			BinaryPath: resolvedPath,
			EnvironmentVariables: []string{
				"LANG=en_US.UTF-8",
				"GIT_TERMINAL_PROMPT=0",
				"GIT_CONFIG_GLOBAL=/dev/null",
				"GIT_CONFIG_SYSTEM=/dev/null",
				"XDG_CONFIG_HOME=/dev/null",
			},
		})
	})

	t.Run("doesn't exist in the system", func(t *testing.T) {
		testhelper.Unsetenv(t, "PATH")

		_, _, err := git.NewExecCommandFactory(config.Cfg{}, testhelper.SharedLogger(t), git.WithSkipHooks())
		require.EqualError(t, err, "setting up Git execution environment: could not set up any Git execution environments")
	})
}

func TestExecCommandFactoryHooksPath(t *testing.T) {
	ctx := testhelper.Context(t)

	t.Run("temporary hooks", func(t *testing.T) {
		cfg := config.Cfg{
			BinDir: testhelper.TempDir(t),
		}

		t.Run("no overrides", func(t *testing.T) {
			gitCmdFactory := gittest.NewCommandFactory(t, cfg)

			hooksPath := gitCmdFactory.HooksPath(ctx)

			// We cannot assert that the hooks path is equal to any specific
			// string, but instead we can assert that it exists and contains the
			// symlinks we expect.
			for _, hook := range []string{"update", "pre-receive", "post-receive", "reference-transaction"} {
				target, err := os.Readlink(filepath.Join(hooksPath, hook))
				require.NoError(t, err)
				require.Equal(t, cfg.BinaryPath("gitaly-hooks"), target)
			}
		})

		t.Run("with skip", func(t *testing.T) {
			gitCmdFactory := gittest.NewCommandFactory(t, cfg, git.WithSkipHooks())
			require.Equal(t, "/var/empty", gitCmdFactory.HooksPath(ctx))
		})
	})

	t.Run("hooks path", func(t *testing.T) {
		gitCmdFactory := gittest.NewCommandFactory(t, config.Cfg{
			BinDir: testhelper.TempDir(t),
		}, git.WithHooksPath("/hooks/path"))

		// The environment variable shouldn't override an explicitly set hooks path.
		require.Equal(t, "/hooks/path", gitCmdFactory.HooksPath(ctx))
	})
}

func TestExecCommandFactory_GitVersion(t *testing.T) {
	ctx := testhelper.Context(t)

	generateVersionScript := func(version string) func(git.ExecutionEnvironment) string {
		return func(git.ExecutionEnvironment) string {
			//nolint:gitaly-linters
			return fmt.Sprintf(
				`#!/usr/bin/env bash
				echo '%s'
			`, version)
		}
	}

	for _, tc := range []struct {
		desc            string
		versionString   string
		expectedErr     string
		expectedVersion string
	}{
		{
			desc:            "valid version",
			versionString:   "git version 2.33.1.gl1",
			expectedVersion: "2.33.1.gl1",
		},
		{
			desc:            "valid version with trailing newline",
			versionString:   "git version 2.33.1.gl1\n",
			expectedVersion: "2.33.1.gl1",
		},
		{
			desc:          "multi-line version",
			versionString: "git version 2.33.1.gl1\nfoobar\n",
			expectedErr:   "cannot parse git version: strconv.ParseUint: parsing \"1\\nfoobar\": invalid syntax",
		},
		{
			desc:          "unexpected format",
			versionString: "2.33.1\n",
			expectedErr:   "invalid version format: \"2.33.1\\n\\n\"",
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			gitCmdFactory := gittest.NewInterceptingCommandFactory(
				t, ctx, testcfg.Build(t), generateVersionScript(tc.versionString),
				gittest.WithRealCommandFactoryOptions(git.WithSkipHooks()),
				gittest.WithInterceptedVersion(),
			)

			actualVersion, err := gitCmdFactory.GitVersion(ctx)
			if tc.expectedErr == "" {
				require.NoError(t, err)
			} else {
				require.EqualError(t, err, tc.expectedErr)
			}
			require.Equal(t, tc.expectedVersion, actualVersion.String())
		})
	}

	t.Run("caching", func(t *testing.T) {
		gitCmdFactory := gittest.NewInterceptingCommandFactory(
			t, ctx, testcfg.Build(t), generateVersionScript("git version 1.2.3"),
			gittest.WithRealCommandFactoryOptions(git.WithSkipHooks()),
			gittest.WithInterceptedVersion(),
		)

		gitPath := gitCmdFactory.GetExecutionEnvironment(ctx).BinaryPath
		stat, err := os.Stat(gitPath)
		require.NoError(t, err)

		version, err := gitCmdFactory.GitVersion(ctx)
		require.NoError(t, err)
		require.Equal(t, "1.2.3", version.String())

		// We rewrite the file with the same content length and modification time such that
		// its file information doesn't change. As a result, information returned by
		// stat(3P) shouldn't differ and we should continue to see the cached version. This
		// is a known insufficiency, but it is extremely unlikely to ever happen in
		// production when the real Git binary changes.
		require.NoError(t, os.Remove(gitPath))
		testhelper.WriteExecutable(t, gitPath, []byte(generateVersionScript("git version 9.8.7")(git.ExecutionEnvironment{})))
		require.NoError(t, os.Chtimes(gitPath, stat.ModTime(), stat.ModTime()))

		// Given that we continue to use the cached version we shouldn't see any
		// change here.
		version, err = gitCmdFactory.GitVersion(ctx)
		require.NoError(t, err)
		require.Equal(t, "1.2.3", version.String())

		// If we really replace the Git binary with something else, then we should
		// see a changed version.
		require.NoError(t, os.Remove(gitPath))
		testhelper.WriteExecutable(t, gitPath, []byte(
			`#!/usr/bin/env bash
			echo 'git version 2.34.1'
		`))

		version, err = gitCmdFactory.GitVersion(ctx)
		require.NoError(t, err)
		require.Equal(t, "2.34.1", version.String())
	})
}

func TestExecCommandFactory_config(t *testing.T) {
	t.Parallel()

	ctx := testhelper.Context(t)
	cfg := testcfg.Build(t)

	// Create a repository and remove its gitconfig to bring us into a known state where there
	// is no repo-level configuration that interferes with our test.
	repo, repoDir := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{
		SkipCreationViaService: true,
	})
	require.NoError(t, os.Remove(filepath.Join(repoDir, "config")))

	expectedEnv := []string{
		"gc.auto=0",
		"maintenance.auto=0",
		"core.autocrlf=input",
		"core.usereplacerefs=false",
		"core.fsync=objects,derived-metadata,reference",
		"core.fsyncmethod=fsync",
		"core.packedrefstimeout=10000",
		"core.filesreflocktimeout=1000",
		"core.bigfilethreshold=50m",
	}

	gitCmdFactory := gittest.NewCommandFactory(t, cfg)

	var stdout bytes.Buffer
	cmd, err := gitCmdFactory.New(ctx, repo, git.Command{
		Name: "config",
		Flags: []git.Option{
			git.Flag{Name: "--list"},
		},
	}, git.WithStdout(&stdout))
	require.NoError(t, err)

	require.NoError(t, cmd.Wait())
	require.Equal(t, expectedEnv, strings.Split(strings.TrimSpace(stdout.String()), "\n"))
}

// TestFsckConfiguration tests the hardcoded configuration of the
// git fsck subcommand generated through the command factory.
func TestFsckConfiguration(t *testing.T) {
	t.Parallel()

	for _, tc := range []struct {
		desc string
		data string
	}{
		{
			desc: "with valid commit",
			data: strings.Join([]string{
				"tree " + gittest.DefaultObjectHash.EmptyTreeOID.String(),
				"author " + gittest.DefaultCommitterSignature,
				"committer " + gittest.DefaultCommitterSignature,
				"",
				"message",
			}, "\n"),
		},
		{
			desc: "with missing space",
			data: strings.Join([]string{
				"tree " + gittest.DefaultObjectHash.EmptyTreeOID.String(),
				"author Scrooge McDuck <scrooge@mcduck.com>1659043074 -0500",
				"committer Scrooge McDuck <scrooge@mcduck.com>1659975573 -0500",
				"",
				"message",
			}, "\n"),
		},
		{
			desc: "with bad timezone",
			data: strings.Join([]string{
				"tree " + gittest.DefaultObjectHash.EmptyTreeOID.String(),
				"author Scrooge McDuck <scrooge@mcduck.com> 1659043074 -0500BAD",
				"committer Scrooge McDuck <scrooge@mcduck.com> 1659975573 -0500BAD",
				"",
				"message",
			}, "\n"),
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx := testhelper.Context(t)
			cfg := testcfg.Build(t)
			repoProto, repoPath := gittest.CreateRepository(t, ctx, cfg,
				gittest.CreateRepositoryConfig{SkipCreationViaService: true},
			)

			// Create commit object.
			commitOut := gittest.ExecOpts(t, cfg, gittest.ExecConfig{Stdin: bytes.NewBufferString(tc.data)},
				"-C", repoPath, "hash-object", "-w", "-t", "commit", "--stdin", "--literally",
			)
			_, err := gittest.DefaultObjectHash.FromHex(text.ChompBytes(commitOut))
			require.NoError(t, err)

			gitCmdFactory, cleanup, err := git.NewExecCommandFactory(cfg, testhelper.SharedLogger(t))
			require.NoError(t, err)
			defer cleanup()

			// Create fsck command with configured ignore rules options.
			cmd, err := gitCmdFactory.New(ctx, repoProto,
				git.Command{Name: "fsck"},
			)
			require.NoError(t, err)

			// Execute git fsck command.
			err = cmd.Wait()
			require.NoError(t, err)
		})
	}
}

type dummyHook struct {
	name    string
	handler func(context.Context, *trace2.Trace) error
}

func (h *dummyHook) Name() string {
	return h.name
}

func (h *dummyHook) Handle(ctx context.Context, trace *trace2.Trace) error {
	return h.handler(ctx, trace)
}

func TestWithTrace2Hooks(t *testing.T) {
	t.Parallel()

	extractEventNames := func(trace *trace2.Trace) []string {
		var names []string
		trace.Walk(testhelper.Context(t), func(ctx context.Context, trace *trace2.Trace) context.Context {
			names = append(names, trace.Name)
			return nil
		})
		return names
	}

	// Trace2 outputs differently between platforms. It may include irrelevant events. In some
	// rare cases, it can also re-order the events, leading to flaky tests. So, we assert the
	// presences of essential events of the tested Git command.
	essentialEvents := []string{
		"pack-objects:enumerate-objects",
		"pack-objects:prepare-pack",
		"pack-objects:write-pack-file",
		"data:pack-objects:write_pack_file/wrote",
	}

	for _, tc := range []struct {
		desc           string
		setup          func(t *testing.T) []trace2.Hook
		expectedFields map[string]any
		withFields     bool
	}{
		{
			desc: "trace2 hook runs successfully",
			setup: func(t *testing.T) []trace2.Hook {
				return []trace2.Hook{
					&dummyHook{
						name: "dummy",
						handler: func(ctx context.Context, trace *trace2.Trace) error {
							require.Subset(t, extractEventNames(trace), essentialEvents)
							return nil
						},
					},
				}
			},
			withFields: true,
			expectedFields: map[string]any{
				"trace2.activated": "true",
				"trace2.hooks":     "dummy",
			},
		},
		{
			desc: "multiple trace2 hooks run successfully",
			setup: func(t *testing.T) []trace2.Hook {
				return []trace2.Hook{
					&dummyHook{
						name: "dummy",
						handler: func(ctx context.Context, trace *trace2.Trace) error {
							require.Subset(t, extractEventNames(trace), essentialEvents)
							return nil
						},
					},
					&dummyHook{
						name: "dummy2",
						handler: func(ctx context.Context, trace *trace2.Trace) error {
							require.Subset(t, extractEventNames(trace), essentialEvents)
							return nil
						},
					},
				}
			},
			withFields: true,
			expectedFields: map[string]any{
				"trace2.activated": "true",
				"trace2.hooks":     "dummy,dummy2",
			},
		},
		{
			desc: "no hooks provided",
			setup: func(t *testing.T) []trace2.Hook {
				return []trace2.Hook{}
			},
			withFields: true,
			expectedFields: map[string]any{
				"trace2.activated": nil,
				"trace2.hooks":     nil,
			},
		},
		{
			desc: "trace2 hook returns error",
			setup: func(t *testing.T) []trace2.Hook {
				return []trace2.Hook{
					&dummyHook{
						name: "dummy",
						handler: func(ctx context.Context, trace *trace2.Trace) error {
							return fmt.Errorf("something goes wrong")
						},
					},
					&dummyHook{
						name: "dummy2",
						handler: func(ctx context.Context, trace *trace2.Trace) error {
							require.Fail(t, "should not trigger hook after prior one fails")
							return nil
						},
					},
				}
			},
			withFields: true,
			expectedFields: map[string]any{
				"trace2.activated": "true",
				"trace2.hooks":     "dummy,dummy2",
				"trace2.error":     `trace2: executing "dummy" handler: something goes wrong`,
			},
		},
		{
			desc: "context does not initialize custom fields",
			setup: func(t *testing.T) []trace2.Hook {
				return []trace2.Hook{
					&dummyHook{
						name: "dummy",
						handler: func(ctx context.Context, trace *trace2.Trace) error {
							require.Subset(t, extractEventNames(trace), essentialEvents)
							return nil
						},
					},
				}
			},
			withFields: false,
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			hooks := tc.setup(t)
			ctx := testhelper.Context(t)
			if tc.withFields {
				ctx = log.InitContextCustomFields(ctx)
			}

			performPackObjectGit(t, ctx, git.WithTrace2Hooks(hooks))

			if tc.withFields {
				customFields := log.CustomFieldsFromContext(ctx)
				require.NotNil(t, customFields)

				logrusFields := customFields.Fields()
				for key, value := range tc.expectedFields {
					require.Equal(t, value, logrusFields[key])
				}
			} else {
				require.Nil(t, log.CustomFieldsFromContext(ctx))
			}
		})
	}
}

func TestTrace2TracingExporter(t *testing.T) {
	for _, tc := range []struct {
		desc          string
		tracerOptions []testhelper.StubTracingReporterOption
		setup         func(*testing.T, context.Context) context.Context
		assert        func(*testing.T, []string, map[string]any)
	}{
		{
			desc: "there is no active span",
			setup: func(t *testing.T, ctx context.Context) context.Context {
				return ctx
			},
			assert: func(t *testing.T, spans []string, statFields map[string]any) {
				require.NotContains(t, statFields, "trace2.activated")
				require.NotContains(t, statFields, "trace2.hooks")
				for _, span := range spans {
					require.NotEqual(t, "trace2.parse", span)
				}
			},
		},
		{
			desc: "active span is sampled",
			setup: func(t *testing.T, ctx context.Context) context.Context {
				_, ctx = tracing.StartSpan(ctx, "root", nil)
				return ctx
			},
			assert: func(t *testing.T, spans []string, statFields map[string]any) {
				require.Equal(t, statFields["trace2.activated"], "true")
				require.Equal(t, statFields["trace2.hooks"], "tracing_exporter")
				require.Subset(t, spans, []string{
					"git-rev-list",
					"git",
					"git:version",
					"git:start",
					"trace2.parse",
				})
			},
		},
		{
			desc:          "active span is not sampled",
			tracerOptions: []testhelper.StubTracingReporterOption{testhelper.NeverSampled()},
			setup: func(t *testing.T, ctx context.Context) context.Context {
				_, ctx = tracing.StartSpan(ctx, "root", nil)
				return ctx
			},
			assert: func(t *testing.T, spans []string, statFields map[string]any) {
				require.NotContains(t, statFields, "trace2.activated")
				require.NotContains(t, statFields, "trace2.hooks")
				for _, span := range spans {
					require.NotEqual(t, "trace2.parse", span)
				}
			},
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			reporter, cleanup := testhelper.StubTracingReporter(t, tc.tracerOptions...)
			defer cleanup()

			ctx := tc.setup(t, log.InitContextCustomFields(testhelper.Context(t)))
			performRevList(t, ctx)

			customFields := log.CustomFieldsFromContext(ctx)
			require.NotNil(t, customFields)
			statFields := customFields.Fields()

			var spans []string
			for _, span := range testhelper.ReportedSpans(t, reporter) {
				spans = append(spans, span.Operation)
			}

			tc.assert(t, spans, statFields)
		})
	}
}

func TestTrace2PackObjectsMetrics(t *testing.T) {
	t.Parallel()

	for _, tc := range []struct {
		desc              string
		performGitCommand func(t *testing.T, ctx context.Context, opts ...git.ExecCommandFactoryOption)
		assert            func(*testing.T, context.Context, log.Fields)
	}{
		{
			desc:              "git-pack-objects",
			performGitCommand: performPackObjectGit,
			assert: func(t *testing.T, ctx context.Context, statFields log.Fields) {
				require.Equal(t, "true", statFields["trace2.activated"])
				require.Equal(t, "pack_objects_metrics", statFields["trace2.hooks"])
				require.Contains(t, statFields, "pack_objects.enumerate_objects_ms")
				require.Contains(t, statFields, "pack_objects.prepare_pack_ms")
				require.Contains(t, statFields, "pack_objects.write_pack_file_ms")
				require.Equal(t, 1, statFields["pack_objects.written_object_count"])
			},
		},
		{
			desc: "other git command",
			performGitCommand: func(t *testing.T, ctx context.Context, opts ...git.ExecCommandFactoryOption) {
				cfg := testcfg.Build(t)
				repoProto, _ := gittest.CreateRepository(t, ctx, cfg,
					gittest.CreateRepositoryConfig{SkipCreationViaService: true},
				)
				gitCmdFactory, cleanup, err := git.NewExecCommandFactory(cfg, testhelper.SharedLogger(t), opts...)
				require.NoError(t, err)
				defer cleanup()

				cmd, err := gitCmdFactory.New(ctx, repoProto, git.Command{
					Name: "rev-list",
					Flags: []git.Option{
						git.Flag{Name: "--all"},
						git.Flag{Name: "--max-count=1"},
					},
				})
				require.NoError(t, err)

				err = cmd.Wait()
				require.NoError(t, err)
			},
			assert: func(t *testing.T, ctx context.Context, statFields log.Fields) {
				require.NotContains(t, statFields, "trace2.activated")
				require.NotContains(t, statFields, "trace2.hooks")
			},
		},
	} {
		tc := tc
		t.Run(tc.desc, func(t *testing.T) {
			t.Parallel()

			ctx := log.InitContextCustomFields(testhelper.Context(t))
			tc.performGitCommand(t, ctx)

			customFields := log.CustomFieldsFromContext(ctx)
			require.NotNil(t, customFields)

			logrusFields := customFields.Fields()
			tc.assert(t, ctx, logrusFields)
		})
	}
}

// This test modifies global tracing tracer. Thus, it cannot run in parallel.
func TestDefaultTrace2HooksFor(t *testing.T) {
	for _, tc := range []struct {
		desc          string
		subCmd        string
		setup         func(t *testing.T) (context.Context, []trace2.Hook)
		tracerOptions []testhelper.StubTracingReporterOption
	}{
		{
			desc:   "there is no active span",
			subCmd: "status",
			setup: func(t *testing.T) (context.Context, []trace2.Hook) {
				ctx := testhelper.Context(t)
				return ctx, []trace2.Hook{}
			},
		},
		{
			desc:   "active span is sampled",
			subCmd: "status",
			setup: func(t *testing.T) (context.Context, []trace2.Hook) {
				_, ctx := tracing.StartSpan(testhelper.Context(t), "root", nil)
				return ctx, []trace2.Hook{
					trace2hooks.NewTracingExporter(),
				}
			},
		},
		{
			desc:   "active span is not sampled",
			subCmd: "status",
			setup: func(t *testing.T) (context.Context, []trace2.Hook) {
				_, ctx := tracing.StartSpan(testhelper.Context(t), "root", nil)
				return ctx, []trace2.Hook{}
			},
			tracerOptions: []testhelper.StubTracingReporterOption{testhelper.NeverSampled()},
		},
		{
			desc:   "subcmd is pack-objects but span is not sampled",
			subCmd: "pack-objects",
			setup: func(t *testing.T) (context.Context, []trace2.Hook) {
				return testhelper.Context(t), []trace2.Hook{
					trace2hooks.NewPackObjectsMetrics(),
				}
			},
		},
		{
			desc:   "subcmd is pack-objects and active span is sampled",
			subCmd: "pack-objects",
			setup: func(t *testing.T) (context.Context, []trace2.Hook) {
				_, ctx := tracing.StartSpan(testhelper.Context(t), "root", nil)
				hooks := []trace2.Hook{
					trace2hooks.NewTracingExporter(),
					trace2hooks.NewPackObjectsMetrics(),
				}

				return ctx, hooks
			},
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			_, cleanup := testhelper.StubTracingReporter(t, tc.tracerOptions...)
			defer cleanup()

			ctx, expectedHooks := tc.setup(t)
			hooks := git.DefaultTrace2HooksFor(ctx, tc.subCmd)

			require.Equal(t, hookNames(expectedHooks), hookNames(hooks))
		})
	}
}

func performPackObjectGit(t *testing.T, ctx context.Context, opts ...git.ExecCommandFactoryOption) {
	cfg := testcfg.Build(t)
	repoProto, repoPath := gittest.CreateRepository(t, ctx, cfg,
		gittest.CreateRepositoryConfig{SkipCreationViaService: true},
	)

	var input bytes.Buffer
	for i := 0; i <= 10; i++ {
		input.WriteString(gittest.WriteCommit(t, cfg, repoPath).String())
		input.WriteString("\n")
	}

	gitCmdFactory, cleanup, err := git.NewExecCommandFactory(cfg, testhelper.SharedLogger(t), opts...)
	require.NoError(t, err)
	defer cleanup()

	cmd, err := gitCmdFactory.New(ctx, repoProto, git.Command{
		Name: "pack-objects",
		Flags: []git.Option{
			git.Flag{Name: "--compression=0"},
			git.Flag{Name: "--stdout"},
			git.Flag{Name: "-q"},
		},
	}, git.WithStdin(&input))
	require.NoError(t, err)

	err = cmd.Wait()
	require.NoError(t, err)
}

func performRevList(t *testing.T, ctx context.Context, opts ...git.ExecCommandFactoryOption) {
	cfg := testcfg.Build(t)
	repoProto, _ := gittest.CreateRepository(t, ctx, cfg,
		gittest.CreateRepositoryConfig{SkipCreationViaService: true},
	)
	gitCmdFactory, cleanup, err := git.NewExecCommandFactory(cfg, testhelper.SharedLogger(t), opts...)
	require.NoError(t, err)
	defer cleanup()

	cmd, err := gitCmdFactory.New(ctx, repoProto, git.Command{
		Name: "rev-list",
		Flags: []git.Option{
			git.Flag{Name: "--max-count=10"},
			git.Flag{Name: "--all"},
		},
	})
	require.NoError(t, err)

	err = cmd.Wait()
	require.NoError(t, err)
}

func hookNames(hooks []trace2.Hook) []string {
	var names []string
	for _, hook := range hooks {
		names = append(names, hook.Name())
	}
	return names
}