Skip to content

Commit

Permalink
Keep a count of clones so we can cleanup clone when not needed
Browse files Browse the repository at this point in the history
  • Loading branch information
komapa committed Nov 20, 2024
1 parent 3c456b8 commit 10765c2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
16 changes: 16 additions & 0 deletions api/internal/git/cloner.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type Cloner func(repoSpec *RepoSpec) error

var (
clones = make(map[string]filesys.ConfirmedDir)
cloneCount = make(map[filesys.ConfirmedDir]int)
cloneMutex sync.Mutex
)

Expand All @@ -23,6 +24,7 @@ var (
func ClonerUsingGitExec(repoSpec *RepoSpec) error {
if dir, found := clones[repoSpec.Raw()]; found {
repoSpec.Dir = dir
cloneCount[dir] += 1
return nil
}

Expand All @@ -34,6 +36,7 @@ func ClonerUsingGitExec(repoSpec *RepoSpec) error {
return err
}
repoSpec.Dir = r.dir

if err = r.run("init"); err != nil {
return err
}
Expand Down Expand Up @@ -73,3 +76,16 @@ func DoNothingCloner(dir filesys.ConfirmedDir) Cloner {
return nil
}
}

// DecrementCloneCount decrements the count of repoSpecs using a directory clone.
func DecrementCloneCount(dir filesys.ConfirmedDir) int {
cloneMutex.Lock()
defer cloneMutex.Unlock()

if count, exists := cloneCount[dir]; exists && count > 0 {
cloneCount[dir] -= 1
return cloneCount[dir]
}

return 0
}
7 changes: 6 additions & 1 deletion api/internal/git/repospec.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,12 @@ func (x *RepoSpec) AbsPath() string {
}

func (x *RepoSpec) Cleaner(fSys filesys.FileSystem) func() error {
return func() error { return fSys.RemoveAll(x.Dir.String()) }
return func() error {
if DecrementCloneCount(x.Dir) == 0 {
return fSys.RemoveAll(x.Dir.String())
}
return nil
}
}

const (
Expand Down

0 comments on commit 10765c2

Please sign in to comment.