Debian Codegraph @

t/cmd/util/testutils.go

raw symbols SCIP
1 package util
2
3 // Utility functions for more complex go tests
4 // Need to be in a separate test package so they can be imported anywhere
5 // Also can't add _test.go suffix to exclude from main build (import doesn't work)
6
7 // To avoid import cycles, append "_test" to the package statement of any test using
8 // this package and use "import . original/package/name" to get the same visibility
9 // as if the test was in the same package (as usual)
10
11 import (
12 "fmt"
13 "io"
14 "math/rand"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "runtime"
19 "strings"
20 "sync"
21 "time"
22
23 "github.com/git-lfs/git-lfs/v3/config"
24 "github.com/git-lfs/git-lfs/v3/errors"
25 "github.com/git-lfs/git-lfs/v3/fs"
26 "github.com/git-lfs/git-lfs/v3/git"
27 "github.com/git-lfs/git-lfs/v3/lfs"
28 )
29
30 func init() {
31 path := os.Getenv("PATH")
32 sep := ""
33 if path != "" {
34 if runtime.GOOS == "windows" {
35 sep = ";"
36 } else {
37 sep = ":"
38 }
39 }
40
41 // Strip the trailing "t/cmd/util/testutils.go" from the path to this
42 // source file to create a path to the working tree's "bin" directory,
43 // then prepend that to the PATH environment variable to ensure our
44 // "git-lfs" binary is used in preference to any installed versions when
45 // executing the Go tests.
46 _, srcdir, _, _ := runtime.Caller(0)
47 for i := 0; i < 4; i++ {
48 srcdir = filepath.Dir(srcdir)
49 }
50 var err error
51 srcdir, err = filepath.Abs(srcdir)
52 if err != nil {
53 panic(err)
54 }
55 os.Setenv("PATH", filepath.Join(srcdir, "bin")+sep+path)
56 }
57
58 type RepoType int
59
60 const (
61 // Normal repo with working copy
62 RepoTypeNormal = RepoType(iota)
63 // Bare repo (no working copy)
64 RepoTypeBare = RepoType(iota)
65 // Repo with working copy but git dir is separate
66 RepoTypeSeparateDir = RepoType(iota)
67 )
68
69 var (
70 // Deterministic sequence of seeds for file data
71 fileInputSeed = rand.NewSource(0)
72 storageOnce sync.Once
73 )
74
75 type RepoCreateSettings struct {
76 RepoType RepoType
77 }
78
79 // Callback interface (testing.T compatible)
80 type RepoCallback interface {
81 // Fatalf reports error and fails
82 Fatalf(format string, args ...interface{})
83 // Errorf reports error and continues
84 Errorf(format string, args ...interface{})
85 }
86
87 type Repo struct {
88 // Path to the repo, working copy if non-bare
89 Path string
90 // Path to the git dir
91 GitDir string
92 // Paths to remotes
93 Remotes map[string]*Repo
94 // Settings used to create this repo
95 Settings *RepoCreateSettings
96 // Previous dir for pushd
97 popDir string
98 // Test callback
99 callback RepoCallback
100 cfg *config.Configuration
101 gitfilter *lfs.GitFilter
102 fs *fs.Filesystem
103 }
104
105 // Change to repo dir but save current dir
106 func (r *Repo) Pushd() {
107 if r.popDir != "" {
108 r.callback.Fatalf("Cannot Pushd twice")
109 }
110 oldwd, err := os.Getwd()
111 if err != nil {
112 r.callback.Fatalf("Can't get cwd %v", err)
113 }
114 err = os.Chdir(r.Path)
115 if err != nil {
116 r.callback.Fatalf("Can't chdir %v", err)
117 }
118 r.popDir = oldwd
119 }
120
121 func (r *Repo) Popd() {
122 if r.popDir != "" {
123 err := os.Chdir(r.popDir)
124 if err != nil {
125 r.callback.Fatalf("Can't chdir %v", err)
126 }
127 r.popDir = ""
128 }
129 }
130
131 func (r *Repo) Filesystem() *fs.Filesystem {
132 return r.fs
133 }
134
135 func (r *Repo) Configuration() *config.Configuration {
136 return r.cfg
137 }
138
139 func (r *Repo) GitConfig() *git.Configuration {
140 return r.cfg.GitConfig()
141 }
142
143 func (r *Repo) GitEnv() config.Environment {
144 return r.cfg.Git
145 }
146
147 func (r *Repo) OSEnv() config.Environment {
148 return r.cfg.Os
149 }
150
151 func (r *Repo) Cleanup() {
152 // pop out if necessary
153 r.Popd()
154
155 // Make sure cwd isn't inside a path we're going to delete
156 oldwd, err := os.Getwd()
157 if err == nil {
158 if strings.HasPrefix(oldwd, r.Path) ||
159 strings.HasPrefix(oldwd, r.GitDir) {
160 os.Chdir(os.TempDir())
161 }
162 }
163
164 if r.GitDir != "" {
165 os.RemoveAll(r.GitDir)
166 r.GitDir = ""
167 }
168 if r.Path != "" {
169 os.RemoveAll(r.Path)
170 r.Path = ""
171 }
172 for _, remote := range r.Remotes {
173 remote.Cleanup()
174 }
175 r.Remotes = nil
176 }
177
178 // NewRepo creates a new git repo in a new temp dir
179 func NewRepo(callback RepoCallback) *Repo {
180 return newRepo(callback, &RepoCreateSettings{
181 RepoType: RepoTypeNormal,
182 })
183 }
184
185 // NewBareRepo creates a new bare git repo in a new temp dir
186 // Note that the repository's path does not end in ".git".
187 func NewBareRepo(callback RepoCallback) *Repo {
188 return newRepo(callback, &RepoCreateSettings{
189 RepoType: RepoTypeBare,
190 })
191 }
192
193 // newRepo creates a new git repo in a new temp dir with more control over settings
194 func newRepo(callback RepoCallback, settings *RepoCreateSettings) *Repo {
195 ret := &Repo{
196 Settings: settings,
197 Remotes: make(map[string]*Repo),
198 callback: callback,
199 }
200
201 path, err := os.MkdirTemp("", "lfsRepo")
202 if err != nil {
203 callback.Fatalf("Can't create temp dir for git repo: %v", err)
204 }
205 ret.Path = path
206 args := []string{"init"}
207 switch settings.RepoType {
208 case RepoTypeBare:
209 args = append(args, "--bare")
210 ret.GitDir = ret.Path
211 case RepoTypeSeparateDir:
212 gitdir, err := os.MkdirTemp("", "lfstestgitdir")
213 if err != nil {
214 ret.Cleanup()
215 callback.Fatalf("Can't create temp dir for git repo: %v", err)
216 }
217 args = append(args, "--separate-dir", gitdir)
218 ret.GitDir = gitdir
219 default:
220 ret.GitDir = filepath.Join(ret.Path, ".git")
221 }
222
223 args = append(args, path)
224 cmd := exec.Command("git", args...)
225 err = cmd.Run()
226 if err != nil {
227 ret.Cleanup()
228 callback.Fatalf("Unable to create git repo at %v: %v", path, err)
229 }
230
231 ret.cfg = config.NewIn(ret.Path, ret.GitDir)
232 ret.fs = ret.cfg.Filesystem()
233 ret.gitfilter = lfs.NewGitFilter(ret.cfg)
234
235 // Configure default user/email so not reliant on env
236 ret.Pushd()
237 RunGitCommand(callback, true, "config", "user.name", "Git LFS Tests")
238 RunGitCommand(callback, true, "config", "user.email", "[email protected]")
239 ret.Popd()
240
241 return ret
242 }
243
244 // WrapRepo creates a new Repo instance for an existing git repo
245 func WrapRepo(c RepoCallback, path string) *Repo {
246 cfg := config.NewIn(path, "")
247 return &Repo{
248 Path: path,
249 GitDir: cfg.LocalGitDir(),
250 Settings: &RepoCreateSettings{
251 RepoType: RepoTypeNormal,
252 },
253 callback: c,
254 cfg: cfg,
255 gitfilter: lfs.NewGitFilter(cfg),
256 fs: cfg.Filesystem(),
257 }
258 }
259
260 // Simplistic fire & forget running of git command - returns combined output
261 func RunGitCommand(callback RepoCallback, failureCheck bool, args ...string) string {
262 outp, err := exec.Command("git", args...).CombinedOutput()
263 if failureCheck && err != nil {
264 callback.Fatalf("Error running git command 'git %v': %v %v", strings.Join(args, " "), err, string(outp))
265 }
266 return string(outp)
267
268 }
269
270 // Input data for a single file in a commit
271 type FileInput struct {
272 // Name of file (required)
273 Filename string
274 // Size of file (required)
275 Size int64
276 // Input data (optional, if provided will be source of data)
277 DataReader io.Reader
278 // Input data (optional, if provided will be source of data)
279 Data string
280 }
281
282 func (infile *FileInput) AddToIndex(output *CommitOutput, repo *Repo) {
283 inputData := infile.getFileInputReader()
284 pointer, err := infile.writeLFSPointer(repo, inputData)
285 if err != nil {
286 repo.callback.Errorf("%+v", err)
287 return
288 }
289 output.Files = append(output.Files, pointer)
290 RunGitCommand(repo.callback, true, "add", infile.Filename)
291 }
292
293 func (infile *FileInput) writeLFSPointer(repo *Repo, inputData io.Reader) (*lfs.Pointer, error) {
294 cleaned, err := repo.gitfilter.Clean(inputData, infile.Filename, infile.Size, nil)
295 if err != nil {
296 return nil, errors.Wrap(err, "creating pointer file")
297 }
298
299 // this only created the temp file, move to final location
300 tmpfile := cleaned.Filename
301 mediafile, err := repo.fs.ObjectPath(cleaned.Oid)
302 if err != nil {
303 return nil, errors.Wrap(err, "local media path")
304 }
305
306 if _, err := os.Stat(mediafile); err != nil {
307 if err := os.Rename(tmpfile, mediafile); err != nil {
308 return nil, err
309 }
310 }
311
312 // Write pointer to local filename for adding (not using clean filter)
313 os.MkdirAll(filepath.Dir(infile.Filename), 0755)
314 f, err := os.Create(infile.Filename)
315 if err != nil {
316 return nil, errors.Wrap(err, "creating pointer file")
317 }
318 _, err = cleaned.Pointer.Encode(f)
319 f.Close()
320 if err != nil {
321 return nil, errors.Wrap(err, "encoding pointer file")
322 }
323
324 return cleaned.Pointer, nil
325 }
326
327 func (infile *FileInput) getFileInputReader() io.Reader {
328 if infile.DataReader != nil {
329 return infile.DataReader
330 }
331
332 if len(infile.Data) > 0 {
333 return strings.NewReader(infile.Data)
334 }
335
336 // Different data for each file but deterministic
337 return NewPlaceholderDataReader(fileInputSeed.Int63(), infile.Size)
338 }
339
340 // Input for defining commits for test repo
341 type CommitInput struct {
342 // Date that we should commit on (optional, leave blank for 'now')
343 CommitDate time.Time
344 // List of files to include in this commit
345 Files []*FileInput
346 // List of parent branches (all branches must have been created in a previous NewBranch or be main)
347 // Can be omitted to just use the parent of the previous commit
348 ParentBranches []string
349 // Name of a new branch we should create at this commit (optional - main not required)
350 NewBranch string
351 // Names of any tags we should create at this commit (optional)
352 Tags []string
353 // Name of committer
354 CommitterName string
355 // Email of committer
356 CommitterEmail string
357 }
358
359 // Output struct with details of commits created for test
360 type CommitOutput struct {
361 Sha string
362 Parents []string
363 Files []*lfs.Pointer
364 }
365
366 func commitAtDate(atDate time.Time, committerName, committerEmail, msg string) error {
367 var args []string
368 if committerName != "" && committerEmail != "" {
369 args = append(args, "-c", fmt.Sprintf("user.name=%v", committerName))
370 args = append(args, "-c", fmt.Sprintf("user.email=%v", committerEmail))
371 }
372 args = append(args, "commit", "--allow-empty", "-m", msg)
373 cmd := exec.Command("git", args...)
374 env := os.Environ()
375 // set GIT_COMMITTER_DATE environment var e.g. "Fri Jun 21 20:26:41 2013 +0900"
376 if atDate.IsZero() {
377 env = append(env, "GIT_COMMITTER_DATE=")
378 env = append(env, "GIT_AUTHOR_DATE=")
379 } else {
380 env = append(env, fmt.Sprintf("GIT_COMMITTER_DATE=%v", git.FormatGitDate(atDate)))
381 env = append(env, fmt.Sprintf("GIT_AUTHOR_DATE=%v", git.FormatGitDate(atDate)))
382 }
383 cmd.Env = env
384 out, err := cmd.CombinedOutput()
385 if err != nil {
386 return fmt.Errorf("%v %v", err, string(out))
387 }
388 return nil
389 }
390
391 func (repo *Repo) AddCommits(inputs []*CommitInput) []*CommitOutput {
392 if repo.Settings.RepoType == RepoTypeBare {
393 repo.callback.Fatalf("Cannot use AddCommits on a bare repo; clone it & push changes instead")
394 }
395
396 // Change to repo working dir
397 oldwd, err := os.Getwd()
398 if err != nil {
399 repo.callback.Fatalf("Can't get cwd %v", err)
400 }
401 err = os.Chdir(repo.Path)
402 if err != nil {
403 repo.callback.Fatalf("Can't chdir to repo %v", err)
404 }
405 // Used to check whether we need to checkout another commit before
406 lastBranch := "main"
407 outputs := make([]*CommitOutput, 0, len(inputs))
408
409 for i, input := range inputs {
410 output := &CommitOutput{}
411 // first, are we on the correct branch
412 if len(input.ParentBranches) > 0 {
413 if input.ParentBranches[0] != lastBranch {
414 RunGitCommand(repo.callback, true, "checkout", input.ParentBranches[0])
415 lastBranch = input.ParentBranches[0]
416 }
417 }
418 // Is this a merge?
419 if len(input.ParentBranches) > 1 {
420 // Always take the *other* side in a merge so we adopt changes
421 // also don't automatically commit, we'll do that below
422 args := []string{"merge", "--no-ff", "--no-commit", "--strategy-option=theirs"}
423 args = append(args, input.ParentBranches[1:]...)
424 RunGitCommand(repo.callback, false, args...)
425 } else if input.NewBranch != "" {
426 RunGitCommand(repo.callback, true, "checkout", "-b", input.NewBranch)
427 lastBranch = input.NewBranch
428 }
429 // Any files to write?
430 for _, infile := range input.Files {
431 infile.AddToIndex(output, repo)
432 }
433 // Now commit
434 err = commitAtDate(input.CommitDate, input.CommitterName, input.CommitterEmail,
435 fmt.Sprintf("Test commit %d", i))
436 if err != nil {
437 repo.callback.Fatalf("Error committing: %v", err)
438 }
439
440 commit, err := git.GetCommitSummary("HEAD")
441 if err != nil {
442 repo.callback.Fatalf("Error determining commit SHA: %v", err)
443 }
444
445 // tags
446 for _, tag := range input.Tags {
447 // Use annotated tags, assume full release tags (also tag objects have edge cases)
448 RunGitCommand(repo.callback, true, "tag", "-a", "-m", "Added tag", tag)
449 }
450
451 output.Sha = commit.Sha
452 output.Parents = commit.Parents
453 outputs = append(outputs, output)
454 }
455
456 // Restore cwd
457 err = os.Chdir(oldwd)
458 if err != nil {
459 repo.callback.Fatalf("Can't restore old cwd %v", err)
460 }
461
462 return outputs
463 }
464
465 // Add a new remote (generate a path for it to live in, will be cleaned up)
466 func (r *Repo) AddRemote(name string) *Repo {
467 if _, exists := r.Remotes[name]; exists {
468 r.callback.Fatalf("Remote %v already exists", name)
469 }
470 remote := newRepo(r.callback, &RepoCreateSettings{
471 RepoType: RepoTypeBare,
472 })
473 r.Remotes[name] = remote
474 RunGitCommand(r.callback, true, "remote", "add", name, remote.Path)
475 return remote
476 }
477
478 // Just a pseudo-random stream of bytes (not cryptographic)
479 // Calls RNG a bit less often than using rand.Source directly
480 type PlaceholderDataReader struct {
481 source rand.Source
482 bytesLeft int64
483 }
484
485 func NewPlaceholderDataReader(seed, size int64) *PlaceholderDataReader {
486 return &PlaceholderDataReader{rand.NewSource(seed), size}
487 }
488
489 func (r *PlaceholderDataReader) Read(p []byte) (int, error) {
490 c := len(p)
491 i := 0
492 for i < c && r.bytesLeft > 0 {
493 // Use all 8 bytes of the 64-bit random number
494 val64 := r.source.Int63()
495 for j := 0; j < 8 && i < c && r.bytesLeft > 0; j++ {
496 // Duplicate this byte 16 times (faster)
497 for k := 0; k < 16 && r.bytesLeft > 0; k++ {
498 p[i] = byte(val64)
499 i++
500 r.bytesLeft--
501 }
502 // Next byte from the 8-byte number
503 val64 = val64 >> 8
504 }
505 }
506 var err error
507 if r.bytesLeft == 0 {
508 err = io.EOF
509 }
510 return i, err
511 }
512
513 // RefsByName implements sort.Interface for []*git.Ref based on name
514 type RefsByName []*git.Ref
515
516 func (a RefsByName) Len() int { return len(a) }
517 func (a RefsByName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
518 func (a RefsByName) Less(i, j int) bool { return a[i].Name < a[j].Name }
519
520 // WorktreesByName implements sort.Interface for []*git.Worktree based on dir
521 type WorktreesByName []*git.Worktree
522
523 func (a WorktreesByName) Len() int { return len(a) }
524 func (a WorktreesByName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
525 func (a WorktreesByName) Less(i, j int) bool { return a[i].Dir < a[j].Dir }
526
527 // WrappedPointersByOid implements sort.Interface for []*lfs.WrappedPointer based on oid
528 type WrappedPointersByOid []*lfs.WrappedPointer
529
530 func (a WrappedPointersByOid) Len() int { return len(a) }
531 func (a WrappedPointersByOid) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
532 func (a WrappedPointersByOid) Less(i, j int) bool { return a[i].Pointer.Oid < a[j].Pointer.Oid }
533
534 // PointersByOid implements sort.Interface for []*lfs.Pointer based on oid
535 type PointersByOid []*lfs.Pointer
536
537 func (a PointersByOid) Len() int { return len(a) }
538 func (a PointersByOid) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
539 func (a PointersByOid) Less(i, j int) bool { return a[i].Oid < a[j].Oid }