-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcleanup.go
96 lines (79 loc) · 2.45 KB
/
cleanup.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
package main
import (
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
"github.com/utilitywarehouse/git-mirror/pkg/mirror"
)
var gitExecutablePath = exec.Command("git").String()
// cleanupOrphanedRepos deletes directory of the repos from the default root
// which are no longer referenced in config and it was removed while app was down.
// Any removal while app is running is already handled by ensureConfig() hence
// this function should be called once
// this is best effort clean up as orphaned published link will not be clean up
// as its not known where it was published.
func cleanupOrphanedRepos(config *mirror.RepoPoolConfig, repoPool *mirror.RepoPool) {
// if default root is not set repos might not be located in same dir
if config.Defaults.Root == "" {
return
}
repoDirs := repoPool.RepositoriesDirPath()
defaultRepoDirRoot := mirror.DefaultRepoDir(config.Defaults.Root)
entries, err := os.ReadDir(defaultRepoDirRoot)
if err != nil {
logger.Error("unable to read root dir for clean up", "err", err)
return
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
fullPath := filepath.Join(defaultRepoDirRoot, entry.Name())
if slices.Contains(repoDirs, fullPath) {
continue
}
// since git-mirror creates bare repository for mirror
// non-repo dir or non-bare repo dir must be skipped
ok, err := isBareRepo(fullPath)
if err != nil {
logger.Error("unable to check if bare repo", "path", fullPath, "err", err)
continue
}
if !ok {
continue
}
logger.Info("removing orphaned repo dir...", "path", fullPath)
if err := os.RemoveAll(fullPath); err != nil {
logger.Error("unable orphaned repo dir", "path", fullPath, "err", err)
continue
}
}
}
func isInsideGitDir(cwd string) bool {
// err is expected here
output, _ := runGitCommand(cwd, "rev-parse", "--is-inside-git-dir")
return output == "true"
}
func isBareRepo(cwd string) (bool, error) {
// bare repository doesn't have worktrees
if !isInsideGitDir(cwd) {
return false, nil
}
output, err := runGitCommand(cwd, "rev-parse", "--is-bare-repository")
if err != nil {
return false, err
}
return strconv.ParseBool(output)
}
// runGitCommand runs git command with given arguments on given CWD
func runGitCommand(cwd string, args ...string) (string, error) {
cmd := exec.Command(gitExecutablePath, args...)
if cwd != "" {
cmd.Dir = cwd
}
output, err := cmd.CombinedOutput()
return strings.TrimSpace(string(output)), err
}