Cycle's maintenance passes become a BuiltinJobs list for the scheduler to seed as locked schedules. Mirrors use a file lock shared by every Manager and held across refresh and clone, so pruning cannot race a clone.
94 lines
2.5 KiB
Go
94 lines
2.5 KiB
Go
package worktree
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestPruneMirrorsRemovesOnlyIdleUnusedMirrorsInsideRoot(t *testing.T) {
|
|
now := time.Now()
|
|
old := now.Add(-48 * time.Hour)
|
|
tests := []struct {
|
|
name string
|
|
setup func(t *testing.T, repo, outside string)
|
|
remove bool
|
|
}{
|
|
{name: "idle and alone", remove: true, setup: func(t *testing.T, repo, _ string) {
|
|
mirror(t, repo, old)
|
|
}},
|
|
{name: "a task clone borrows it", setup: func(t *testing.T, repo, _ string) {
|
|
mirror(t, repo, old)
|
|
mkdir(t, filepath.Join(repo, "issue-1"))
|
|
}},
|
|
{name: "used recently", setup: func(t *testing.T, repo, _ string) {
|
|
mirror(t, repo, now.Add(-time.Hour))
|
|
}},
|
|
{name: "a clone holds the lock", setup: func(t *testing.T, repo, _ string) {
|
|
mirror(t, repo, old)
|
|
unlock, err := lockMirror(filepath.Join(repo, mirrorName), false)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(unlock)
|
|
}},
|
|
{name: "symlink to a directory outside the root", setup: func(t *testing.T, repo, outside string) {
|
|
mkdir(t, repo)
|
|
if err := os.Symlink(outside, filepath.Join(repo, mirrorName)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
lock(t, repo, old)
|
|
}},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
root := t.TempDir()
|
|
outside := t.TempDir()
|
|
sentinel := filepath.Join(outside, "keep")
|
|
if err := os.WriteFile(sentinel, nil, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
repo := filepath.Join(root, "org-x", "owner", "repo")
|
|
tt.setup(t, repo, outside)
|
|
|
|
removed, err := PruneMirrors(context.Background(), root, 24*time.Hour, now)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, statErr := os.Lstat(filepath.Join(repo, mirrorName))
|
|
if gone := os.IsNotExist(statErr); gone != tt.remove || (len(removed) == 1) != tt.remove {
|
|
t.Fatalf("removed %v, mirror gone %v; want removal %v", removed, gone, tt.remove)
|
|
}
|
|
if _, err := os.Stat(sentinel); err != nil {
|
|
t.Fatalf("pruning touched a path outside the root: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func mirror(t *testing.T, repo string, used time.Time) {
|
|
t.Helper()
|
|
mkdir(t, filepath.Join(repo, mirrorName, "objects"))
|
|
lock(t, repo, used)
|
|
}
|
|
|
|
func lock(t *testing.T, repo string, used time.Time) {
|
|
t.Helper()
|
|
path := filepath.Join(repo, mirrorName+".lock")
|
|
if err := os.WriteFile(path, nil, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.Chtimes(path, used, used); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func mkdir(t *testing.T, dir string) {
|
|
t.Helper()
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|