Files
skillshare/internal/install/install_tracked_test.go
T
Willie dcffa2ec5e fix(install): keep a moved skill's record instead of reinstalling it (#513)
* fix(install): keep a moved skill's record instead of reinstalling it

Install records are keyed by path, so a skill moved with mv shows up as
missing. "Install missing" (and bare `skillshare install`) then cloned it
again at the old path, leaving two copies that both sync to targets, and
reconcile could hand the new copy's record to the moved one.

A gone record now follows an unrecorded directory of the same name whose
files match the recorded hashes, when exactly one such directory exists.
Install-from-config skips such entries and reconcile re-keys the record,
so the moved copy keeps its source. Same-name skills with other files are
left alone, so an update can never overwrite them from that source.

Refs: #510

* fix(install): keep audit acceptances and unreadable links out of moves

Re-keying a moved skill went through Remove, which also drops the audit
findings accepted for the old path, so an unchanged skill could block or
prompt again on its next update. MoveEntry now carries them to the new key.

A record below a first-level source link that cannot be read looks gone
to Lstat, so an identical copy elsewhere could take its record while the
link was down. Such records are no longer matched as moved.

* fix(install): drop legacy-path acceptances and respect lock pins on move

A legacy basename key such as `demo` with group `old` keeps its accepted
audit findings under `old/demo`. MoveEntry removed only the key's own
acceptances, so the old path kept them and a later skill placed there
would inherit them without a new --force. It now deletes the old path.

When the lockfile pins another commit than the moved copy holds, treating
the copy as the moved skill re-keyed its stale record and let the project
lock be rewritten with the older commit. Such copies no longer count as a
move, so the pinned commit is installed as before.

* fix(install): search for moved skills only where reconcile looks

The search for a moved copy walked into installed skills and tracked
checkouts, which reconcile skips. A copy found there made install skip the
skill, then reconcile never saw the copy and pruned the record, and in
project mode the config entry with it. The search now stops at the same
boundaries.

* fix(install): never take a recorded skill as another's moved copy

Two identical skills can be recorded at different paths. When one of them
went missing, the other matched its hashes and was taken as its moved
copy, so install skipped the missing skill and reconcile pruned its record.
A directory with a record of its own is now never a move destination.

* fix(install): derive moved-copy paths from the resolved source root

sourcewalk.WalkDir reports paths under the resolved source root, but the
moved-copy search took them relative to the unresolved one. With a linked
source (or Windows short temp paths) every path came out as ../..., so the
installed-skill boundary never matched and a copy inside an installed
parent could be taken as the move, after which reconcile pruned the record.
The search now resolves the root first, as reconcile does.

* fix(install): move a record only to one copy of what the config declares

Three cases still let a move drop or misplace a record:

- In project mode the manifest can point a skill at a new source while a
  copy of the old one exists elsewhere; that copy was taken as the skill,
  so the new source was never installed. The record's source and branch
  must now match the config entry.
- A git checkout reconcile treats as tracked could be accepted before the
  tracked boundary was checked; the boundaries now run first.
- With two identical copies, reconcile re-keyed the record to whichever
  it walked first. Both reconcile and the install-from-config search now
  require exactly one destination, and reconcile decides after the walk.

* fix(install): clear accepted findings left at a move destination

A removed legacy grouped entry can leave findings accepted for its path
behind. MoveEntry only wrote the destination when the moved skill had its
own acceptances, so a skill moved into that path inherited findings it
never accepted. The destination is now cleared before the transfer.

* fix(install): follow a moved skill only while its declaration still matches

The install-from-config search compared source and branch but not the
tracking mode, so a skill switched to tracked was satisfied by an old
plain copy and never cloned.

Project reconciliation, which other installs also run, inferred moves
without looking at the manifest at all. A record whose declaration now
names another source could follow a copy of the old source, after which
the manifest entry was rewritten to that old source. Moves in project
mode now require the declaration to still match the record, through the
same MatchesDeclaration check the install path uses.

* fix(install): infer no move while a source link is unreadable

An unreadable followed source link can hide a second identical copy, so
a copy that looked unique could take the record arbitrarily. Reconcile
and the install-from-config search now infer a move only from a complete
inventory; reconcile already keeps the gone record in that case.

* fix(install): infer no move when the source walk hit an error

Both walks dropped traversal errors, so an unreadable directory that hid
a second identical copy left the visible one looking unique and it could
take the record. Any walk error now counts as an incomplete inventory,
like an unreadable source link, and no move is inferred from it.

* fix(install): keep a record whose move waits on a failed walk

When a walk error deferred a move, the walk still counted as complete, so
pruning dropped the gone record along with its accepted audit findings
and it could never follow the copy. A failed walk that deferred a move
now marks the inventory incomplete, as an unreadable source link does;
a failed walk with no move candidate keeps the old behavior.

Also correct InstallFromConfig's comments, which still said reconcile
runs only after an install.

* fix(install): move a moved skill's gitignore rule in project mode

Project reconcile added the managed ignore rule for a moved skill's new
path but left the old one, and the gitignore update only ever adds. If
the old path later held source-controlled files, Git kept ignoring them
without a word. Reconcile now reports the paths records moved away from,
and project reconcile removes their managed rules before adding the new.

* test(config): skip the unreadable-directory reconcile test on Windows

Windows does not stop reading a directory created with mode 0, and
os.Geteuid reports -1 there, so the root-only skip let the test run and
fail on the Windows runner.

* fix(install): count a candidate that cannot be hashed as an incomplete search

MovedEntryKey dropped a same-name candidate whose files could not be
hashed, so a readable identical copy beside it looked unique and could
take the record. It now returns the hash error, and reconcile and the
install-from-config search treat it like a walk error: no move is
inferred from that scan, and reconcile keeps the record waiting.
2026-10-10 23:14:52 +08:00

688 lines
26 KiB
Go

package install
import (
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"skillshare/internal/sourcewalk"
)
// makeRemote creates a bare git remote with a SKILL.md on the default branch,
// plus an optional extra branch if extraBranch != "".
func makeRemote(t *testing.T, extraBranch string) (remoteURL string) {
t.Helper()
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
tmp := t.TempDir()
work := filepath.Join(tmp, "work")
remote := filepath.Join(tmp, "remote.git")
mustRunGit(t, "", "init", "-b", "main", work)
mustRunGit(t, work, "config", "user.email", "test@test.com")
mustRunGit(t, work, "config", "user.name", "Test")
skillFile := filepath.Join(work, "SKILL.md")
if err := os.WriteFile(skillFile, []byte("# test skill"), 0644); err != nil {
t.Fatal(err)
}
mustRunGit(t, work, "add", ".")
mustRunGit(t, work, "commit", "-m", "init")
if extraBranch != "" {
mustRunGit(t, work, "checkout", "-b", extraBranch)
if err := os.WriteFile(skillFile, []byte("# test skill on "+extraBranch), 0644); err != nil {
t.Fatal(err)
}
mustRunGit(t, work, "add", ".")
mustRunGit(t, work, "commit", "-m", "branch commit")
mustRunGit(t, work, "checkout", "main")
}
mustRunGit(t, "", "clone", "--bare", work, remote)
return fileURL(remote)
}
// fileURL turns a local path into a file URL git accepts; Windows paths need
// a leading slash and forward slashes (file:///C:/dir).
func fileURL(p string) string {
p = filepath.ToSlash(p)
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
return "file://" + p
}
// metadataInstallContext is a global-mode InstallContext over a metadata file.
type metadataInstallContext struct{ dir string }
func (c metadataInstallContext) SourcePath() string { return c.dir }
func (c metadataInstallContext) ConfigSkills() []SkillEntryDTO {
return MetadataSkillEntries(LoadMetadataOrNew(c.dir))
}
func (metadataInstallContext) Reconcile() error { return nil }
func (metadataInstallContext) PostInstallSkill(string) error { return nil }
func (metadataInstallContext) Mode() string { return "global" }
func (metadataInstallContext) GitLabHosts() []string { return nil }
func (metadataInstallContext) AzureHosts() []string { return nil }
func (metadataInstallContext) CNBHosts() []string { return nil }
func (metadataInstallContext) GiteaHosts() []string { return nil }
// TestInstallFromConfig_SkipsMovedSkill verifies that a recorded skill the
// user moved to another folder is not installed again at its old path, which
// would leave two copies (issue #510).
func TestInstallFromConfig_SkipsMovedSkill(t *testing.T) {
origin := filepath.Join(t.TempDir(), "demo")
sourceDir := t.TempDir()
moved := filepath.Join(sourceDir, "grp", "demo")
for _, dir := range []string{origin, moved} {
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: demo\n---\n"), 0644); err != nil {
t.Fatal(err)
}
}
hashes, err := ComputeFileHashes(moved)
if err != nil {
t.Fatal(err)
}
store := LoadMetadataOrNew(sourceDir)
store.Set("demo", &MetadataEntry{Source: origin, Type: "local", FileHashes: hashes})
if err := store.Save(sourceDir); err != nil {
t.Fatal(err)
}
if _, err := InstallFromConfig(metadataInstallContext{sourceDir}, InstallOptions{SkipAudit: true, Quiet: true}); err != nil {
t.Fatalf("InstallFromConfig() error = %v", err)
}
if _, err := os.Stat(filepath.Join(sourceDir, "demo")); !os.IsNotExist(err) {
t.Errorf("moved skill was installed again at its old path (stat err = %v)", err)
}
}
// TestMovedCopyOf_IgnoresCopyBehindLock verifies that a moved copy at another
// commit than the lockfile pins is not taken as the locked skill, so the pin
// is not overwritten with the copy's older commit.
func TestMovedCopyOf_IgnoresCopyBehindLock(t *testing.T) {
sourceDir := t.TempDir()
moved := filepath.Join(sourceDir, "grp", "demo")
if err := os.MkdirAll(moved, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(moved, "SKILL.md"), []byte("---\nname: demo\n---\n"), 0644); err != nil {
t.Fatal(err)
}
hashes, err := ComputeFileHashes(moved)
if err != nil {
t.Fatal(err)
}
store := NewMetadataStore()
store.Set("demo", &MetadataEntry{Source: "github.com/user/repo/demo", Commit: strings.Repeat("a", 40), FileHashes: hashes})
if to := movedCopyOf(store, sourceDir, SkillEntryDTO{Name: "demo", Source: "github.com/user/repo/demo"}, nil, strings.Repeat("b", 40)); to != "" {
t.Errorf("movedCopyOf() = %q, want no match for a copy behind the lock", to)
}
}
// TestMovedCopyOf_StopsAtInstalledSkill verifies that a copy inside another
// installed skill is not taken as the move: reconcile never looks there, so
// it would prune the record the install was skipped for.
func TestMovedCopyOf_StopsAtInstalledSkill(t *testing.T) {
sourceDir := t.TempDir()
moved := filepath.Join(sourceDir, "parent", "demo")
if err := os.MkdirAll(moved, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(moved, "SKILL.md"), []byte("---\nname: demo\n---\n"), 0644); err != nil {
t.Fatal(err)
}
hashes, err := ComputeFileHashes(moved)
if err != nil {
t.Fatal(err)
}
store := NewMetadataStore()
store.Set("demo", &MetadataEntry{Source: "github.com/user/repo/demo", FileHashes: hashes})
store.Set("parent", &MetadataEntry{Source: "github.com/user/repo/parent"})
if to := movedCopyOf(store, sourceDir, SkillEntryDTO{Name: "demo", Source: "github.com/user/repo/demo"}, nil, ""); to != "" {
t.Errorf("movedCopyOf() = %q, want no match inside an installed skill", to)
}
}
// TestMovedCopyOf_IgnoresRecordedSkill verifies that a skill with its own
// record is never taken as another, identical skill's moved copy.
func TestMovedCopyOf_IgnoresRecordedSkill(t *testing.T) {
sourceDir := t.TempDir()
other := filepath.Join(sourceDir, "new", "demo")
if err := os.MkdirAll(other, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(other, "SKILL.md"), []byte("---\nname: demo\n---\n"), 0644); err != nil {
t.Fatal(err)
}
hashes, err := ComputeFileHashes(other)
if err != nil {
t.Fatal(err)
}
store := NewMetadataStore()
store.Set("old/demo", &MetadataEntry{Source: "github.com/user/repo/demo", Group: "old", FileHashes: hashes})
store.Set("new/demo", &MetadataEntry{Source: "github.com/user/repo/demo", Group: "new", FileHashes: hashes})
if to := movedCopyOf(store, sourceDir, SkillEntryDTO{Name: "demo", Group: "old", Source: "github.com/user/repo/demo"}, nil, ""); to != "" {
t.Errorf("movedCopyOf() = %q, want no match for a recorded skill", to)
}
}
// TestMovedCopyOf_StopsAtInstalledSkillUnderLinkedSource verifies that the
// installed-skill boundary holds when the skills source is itself a link.
func TestMovedCopyOf_StopsAtInstalledSkillUnderLinkedSource(t *testing.T) {
realDir := t.TempDir()
sourceDir := filepath.Join(t.TempDir(), "skills")
if err := os.Symlink(realDir, sourceDir); err != nil {
t.Skipf("symlink: %v", err)
}
moved := filepath.Join(realDir, "grp", "parent", "demo")
if err := os.MkdirAll(moved, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(moved, "SKILL.md"), []byte("---\nname: demo\n---\n"), 0644); err != nil {
t.Fatal(err)
}
hashes, err := ComputeFileHashes(moved)
if err != nil {
t.Fatal(err)
}
store := NewMetadataStore()
store.Set("demo", &MetadataEntry{Source: "github.com/user/repo/demo", FileHashes: hashes})
store.Set("grp/parent", &MetadataEntry{Source: "github.com/user/repo/parent", Group: "grp"})
if to := movedCopyOf(store, sourceDir, SkillEntryDTO{Name: "demo", Source: "github.com/user/repo/demo"}, nil, ""); to != "" {
t.Errorf("movedCopyOf() = %q, want no match inside an installed skill", to)
}
}
// writeMovedCopies writes identical demo skills at rels under sourceDir and
// returns their file hashes.
func writeMovedCopies(t *testing.T, sourceDir string, rels ...string) map[string]string {
t.Helper()
var hashes map[string]string
for _, rel := range rels {
dir := filepath.Join(sourceDir, filepath.FromSlash(rel))
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("---\nname: demo\n---\n"), 0644); err != nil {
t.Fatal(err)
}
var err error
if hashes, err = ComputeFileHashes(dir); err != nil {
t.Fatal(err)
}
}
return hashes
}
// TestMovedCopyOf_IgnoresChangedSource verifies that a copy of what was
// recorded is not taken as the skill once the config declares another source.
func TestMovedCopyOf_IgnoresChangedSource(t *testing.T) {
sourceDir := t.TempDir()
store := NewMetadataStore()
store.Set("demo", &MetadataEntry{Source: "github.com/user/a/demo", FileHashes: writeMovedCopies(t, sourceDir, "grp/demo")})
if to := movedCopyOf(store, sourceDir, SkillEntryDTO{Name: "demo", Source: "github.com/user/b/demo"}, nil, ""); to != "" {
t.Errorf("movedCopyOf() = %q, want no match after the source changed", to)
}
}
// TestMovedCopyOf_IgnoresSkillNowTracked verifies that a plain copy is not
// taken as the skill once the config declares it tracked.
func TestMovedCopyOf_IgnoresSkillNowTracked(t *testing.T) {
sourceDir := t.TempDir()
store := NewMetadataStore()
store.Set("demo", &MetadataEntry{Source: "github.com/user/repo/demo", FileHashes: writeMovedCopies(t, sourceDir, "grp/demo")})
if to := movedCopyOf(store, sourceDir, SkillEntryDTO{Name: "demo", Source: "github.com/user/repo/demo", Tracked: true}, nil, ""); to != "" {
t.Errorf("movedCopyOf() = %q, want no match once the skill is tracked", to)
}
}
// TestMovedCopyOf_IgnoresTrackedCheckout verifies that a git checkout
// reconcile treats as tracked is never taken as a moved plain skill.
func TestMovedCopyOf_IgnoresTrackedCheckout(t *testing.T) {
sourceDir := t.TempDir()
hashes := writeMovedCopies(t, sourceDir, "grp/_demo")
mustRunGit(t, "", "init", "-q", filepath.Join(sourceDir, "grp", "_demo"))
store := NewMetadataStore()
store.Set("_demo", &MetadataEntry{Source: "github.com/user/repo/_demo", FileHashes: hashes})
if to := movedCopyOf(store, sourceDir, SkillEntryDTO{Name: "_demo", Source: "github.com/user/repo/_demo"}, nil, ""); to != "" {
t.Errorf("movedCopyOf() = %q, want no match for a tracked checkout", to)
}
}
// TestMovedCopyOf_RequiresSingleCopy verifies that two identical copies leave
// the move undecided instead of picking one.
func TestMovedCopyOf_RequiresSingleCopy(t *testing.T) {
sourceDir := t.TempDir()
store := NewMetadataStore()
store.Set("demo", &MetadataEntry{Source: "github.com/user/repo/demo", FileHashes: writeMovedCopies(t, sourceDir, "a/demo", "b/demo")})
if to := movedCopyOf(store, sourceDir, SkillEntryDTO{Name: "demo", Source: "github.com/user/repo/demo"}, nil, ""); to != "" {
t.Errorf("movedCopyOf() = %q, want no match with two copies", to)
}
}
// TestInstallFromConfig_ReclonesMissingTrackedRepo verifies that a tracked repo
// declared in metadata but absent on disk is listed as missing and re-cloned
// under its recorded name (issue #212).
func TestInstallFromConfig_ReclonesMissingTrackedRepo(t *testing.T) {
remoteURL := makeRemote(t, "")
sourceDir := t.TempDir()
// Declare the tracked repo in metadata WITHOUT cloning it (fresh machine).
store := LoadMetadataOrNew(sourceDir)
store.Set("_team-skills", &MetadataEntry{Source: remoteURL, Tracked: true})
if err := store.Save(sourceDir); err != nil {
t.Fatalf("save metadata: %v", err)
}
ctx := metadataInstallContext{sourceDir}
if missing := MissingFromConfig(ctx); len(missing) != 1 || !missing[0].Tracked {
t.Fatalf("expected the tracked repo to be missing, got %+v", missing)
}
result, err := InstallFromConfig(ctx, InstallOptions{SkipAudit: true, Quiet: true})
if err != nil {
t.Fatalf("InstallFromConfig() error = %v", err)
}
if result.InstalledRepos != 1 || len(result.FailedSkills) != 0 {
t.Fatalf("unexpected result: %+v", result)
}
if _, err := os.Stat(filepath.Join(sourceDir, "_team-skills", ".git")); err != nil {
t.Fatalf("expected cloned repo at _team-skills: %v", err)
}
if missing := MissingFromConfig(ctx); len(missing) != 0 {
t.Fatalf("expected nothing missing after install, got %+v", missing)
}
}
// TestInstallTrackedRepo_NameFromOptions verifies that a name passed in
// opts.Name (--name, or the name recorded in config) wins over the
// URL-derived TrackName().
func TestInstallTrackedRepo_NameFromOptions(t *testing.T) {
remoteURL := makeRemote(t, "")
sourceDir := t.TempDir()
source := &Source{
Type: SourceTypeGitHTTPS,
Raw: remoteURL,
CloneURL: remoteURL,
}
result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "my-custom-name"})
if err != nil {
t.Fatalf("InstallTrackedRepo() error = %v", err)
}
if result.Action != "cloned" {
t.Fatalf("Action = %q, want %q", result.Action, "cloned")
}
want := filepath.Join(sourceDir, "_my-custom-name")
if _, err := os.Stat(want); err != nil {
t.Fatalf("expected repo at %q but stat failed: %v", want, err)
}
// Confirm the URL-derived name was NOT used.
unwanted := filepath.Join(sourceDir, "_"+source.TrackName())
if _, err := os.Stat(unwanted); err == nil {
t.Fatalf("repo should NOT exist at URL-derived path %q", unwanted)
}
}
// TestInstallTrackedRepo_SameBasenameDoesNotCollide verifies that two repos
// whose URLs end in the same basename get distinct owner-repo directories,
// even though ParseSource fills source.Name with that shared basename.
func TestInstallTrackedRepo_SameBasenameDoesNotCollide(t *testing.T) {
remoteURL := makeRemote(t, "")
sourceDir := t.TempDir()
seen := map[string]bool{}
for _, owner := range []string{"alice", "bob"} {
// Raw names the owner (TrackName reads it); the clone uses the local remote.
source := &Source{
Type: SourceTypeGitSSH,
Raw: "git@example.com:" + owner + "/skills.git",
CloneURL: remoteURL,
Name: "skills", // what ParseSource fills in from the basename
}
result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{SkipAudit: true})
if err != nil {
t.Fatalf("install %s: %v", owner, err)
}
if result.RepoName == "_skills" || seen[result.RepoName] {
t.Fatalf("repo %s got colliding name %q", owner, result.RepoName)
}
seen[result.RepoName] = true
}
}
// TestInstallTrackedRepo_ReusesLegacyBasenameCheckout verifies that repeating
// an install whose repo was cloned under the older basename name (_skills)
// skips as the same repo instead of cloning a second _owner-skills copy.
func TestInstallTrackedRepo_ReusesLegacyBasenameCheckout(t *testing.T) {
remoteURL := makeRemote(t, "")
sourceDir := t.TempDir()
source := &Source{Type: SourceTypeGitSSH, Raw: "git@example.com:alice/skills.git", CloneURL: remoteURL, Name: "skills"}
if _, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "skills", SkipAudit: true}); err != nil {
t.Fatalf("legacy install: %v", err)
}
_, err := InstallTrackedRepo(source, sourceDir, InstallOptions{SkipAudit: true})
if !errors.Is(err, ErrSkipSameRepo) {
t.Fatalf("err = %v, want ErrSkipSameRepo", err)
}
if _, err := os.Stat(filepath.Join(sourceDir, "_"+source.TrackName())); err == nil {
t.Fatal("cloned a second copy under the owner-qualified name")
}
}
// TestInstallTrackedRepo_BranchFromSource verifies that when opts.Branch is
// empty, the repo is cloned onto source.Branch rather than the remote default.
func TestInstallTrackedRepo_BranchFromSource(t *testing.T) {
const featureBranch = "feature/my-work"
remoteURL := makeRemote(t, featureBranch)
sourceDir := t.TempDir()
source := &Source{
Type: SourceTypeGitHTTPS,
Raw: remoteURL,
CloneURL: remoteURL,
Branch: featureBranch, // should be used; opts.Branch is empty
}
result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "mybranch-skill"})
if err != nil {
t.Fatalf("InstallTrackedRepo() error = %v", err)
}
if result.Action != "cloned" {
t.Fatalf("Action = %q, want %q", result.Action, "cloned")
}
repoPath := filepath.Join(sourceDir, "_mybranch-skill")
if _, err := os.Stat(repoPath); err != nil {
t.Fatalf("expected repo at %q: %v", repoPath, err)
}
out, err2 := exec.Command("git", "-C", repoPath, "rev-parse", "--abbrev-ref", "HEAD").Output()
if err2 != nil {
t.Fatalf("git rev-parse failed: %v", err2)
}
got := strings.TrimSpace(string(out))
if got != featureBranch {
t.Errorf("cloned branch = %q, want %q", got, featureBranch)
}
}
func TestMissingTrackedReposFollowPolicy(t *testing.T) {
source, checkout := t.TempDir(), t.TempDir()
mustRunGit(t, checkout, "init")
if err := os.Symlink(checkout, filepath.Join(source, "_dev-skills")); err != nil {
t.Fatal(err)
}
store := LoadMetadataOrNew(source)
store.Set("_dev-skills", &MetadataEntry{Source: "https://example.com/repo.git", Tracked: true})
if err := store.Save(source); err != nil {
t.Fatal(err)
}
walk := sourcewalk.Options{Follow: sourcewalk.NewFollow(source, nil)}
missing, err := GetMissingTrackedRepos(source, walk)
if err != nil || len(missing) != 0 {
t.Fatalf("present followed checkout reported missing: %+v %v", missing, err)
}
if got := MissingFromConfig(metadataInstallContext{source}); len(got) != 0 {
t.Fatalf("present followed checkout listed for install: %+v", got)
}
}
func TestInferTrackedKind_LocalGitPathBecomesFileURL(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
repo := t.TempDir()
mustRunGit(t, "", "init", "-b", "main", repo)
if err := os.WriteFile(filepath.Join(repo, "SKILL.md"), []byte("# s"), 0644); err != nil {
t.Fatal(err)
}
source, err := ParseSource(repo)
if err != nil {
t.Fatal(err)
}
kind, err := InferTrackedKind(source, "skill")
if err != nil {
t.Fatalf("local git repo should be trackable: %v", err)
}
if kind != "skill" || source.CloneURL != fileURL(repo) {
t.Errorf("kind=%q cloneURL=%q, want skill / %q", kind, source.CloneURL, fileURL(repo))
}
}
func TestInferTrackedKind_PlainLocalDirHintsFileURL(t *testing.T) {
source, err := ParseSource(t.TempDir())
if err != nil {
t.Fatal(err)
}
_, err = InferTrackedKind(source, "skill")
if err == nil || !strings.Contains(err.Error(), "file://") {
t.Fatalf("want error naming file://, got %v", err)
}
}
func TestLocalFileURL_KeepsWindowsDriveInPath(t *testing.T) {
// "C:/repo" is what a Windows path looks like after filepath.ToSlash.
if got := localFileURL("C:/repo"); got != "file:///C:/repo" {
t.Errorf("localFileURL(C:/repo) = %q, want file:///C:/repo", got)
}
if got := localFileURL("/tmp/repo"); got != "file:///tmp/repo" {
t.Errorf("localFileURL(/tmp/repo) = %q, want file:///tmp/repo", got)
}
if got := localFileURL("/tmp/my repo%20x#1"); got != "file:///tmp/my%20repo%2520x%231" {
t.Errorf("localFileURL escaping = %q, want file:///tmp/my%%20repo%%2520x%%231", got)
}
}
func TestParseSource_ExplicitUNCFileURLKeepsAuthority(t *testing.T) {
source, err := ParseSource("file://server/share/repo")
if err != nil {
t.Fatal(err)
}
if source.CloneURL != "file://server/share/repo" {
t.Errorf("CloneURL = %q, want file://server/share/repo", source.CloneURL)
}
}
func TestInferTrackedKind_LocalBareRepoPath(t *testing.T) {
bare := strings.TrimPrefix(makeRemote(t, ""), "file://")
// A Windows file URL is file:///C:/dir; drop the slash before the drive.
if len(bare) > 2 && bare[0] == '/' && bare[2] == ':' {
bare = bare[1:]
}
source, err := ParseSource(bare)
if err != nil {
t.Fatal(err)
}
if _, err := InferTrackedKind(source, "skill"); err != nil {
t.Fatalf("local bare repo should be trackable: %v", err)
}
}
func TestInstallTrackedRepo_ForceNeverDestroysItsLocalSource(t *testing.T) {
cases := []struct {
name string
repo string // relative to the destination
source func(repo string) string
dryRun bool
}{
{"same path", "", func(p string) string { return p }, false},
{"nested path", "nested", func(p string) string { return p }, false},
{"dry run", "nested", func(p string) string { return p }, true},
{"explicit file URL", "nested", func(p string) string { return fileURL(p) }, false},
{"localhost file URL", "nested", func(p string) string { return "file://localhost/" + strings.TrimPrefix(filepath.ToSlash(p), "/") }, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
sourceDir := t.TempDir()
dest := filepath.Join(sourceDir, "_foo")
repo := filepath.Join(dest, tc.repo)
mustRunGit(t, "", "init", "-b", "main", repo)
if err := os.WriteFile(filepath.Join(repo, "SKILL.md"), []byte("# skill"), 0644); err != nil {
t.Fatal(err)
}
mustRunGit(t, repo, "add", ".")
mustRunGit(t, repo, "-c", "user.email=a@b", "-c", "user.name=n", "commit", "-m", "i")
// Uncommitted work: a clone cannot carry it, so only refusing keeps it.
wip := filepath.Join(repo, "wip.txt")
if err := os.WriteFile(wip, []byte("unpushed"), 0644); err != nil {
t.Fatal(err)
}
source, err := ParseSource(tc.source(repo))
if err != nil {
t.Fatal(err)
}
_, err = InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "foo", Force: true, DryRun: tc.dryRun})
if err == nil {
t.Fatal("expected an error when the source is inside the install destination")
}
if _, err := os.Stat(wip); err != nil {
t.Fatalf("source must be left intact: %v", err)
}
})
}
}
func TestLocalCloneSource_UNCFileURL(t *testing.T) {
got := localCloneSource(&Source{CloneURL: "file://server/share/repo"})
if want := filepath.FromSlash("//server/share/repo"); got != want {
t.Errorf("localCloneSource = %q, want %q", got, want)
}
}
func TestInstallTrackedRepo_ForceKeepsExistingRepoWhenCloneFails(t *testing.T) {
remoteURL := makeRemote(t, "")
sourceDir := t.TempDir()
source := &Source{Type: SourceTypeGitHTTPS, Raw: remoteURL, CloneURL: remoteURL}
if _, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "foo"}); err != nil {
t.Fatalf("first install: %v", err)
}
_, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "foo", Force: true, Branch: "no-such-branch"})
if err == nil {
t.Fatal("expected the clone of a missing branch to fail")
}
if _, statErr := os.Stat(filepath.Join(sourceDir, "_foo", "SKILL.md")); statErr != nil {
t.Fatalf("the existing repo must survive a failed forced reinstall: %v", statErr)
}
entries, _ := os.ReadDir(sourceDir)
for _, e := range entries {
if strings.HasPrefix(e.Name(), ".skillshare-clone-") {
t.Errorf("staging dir %s was left behind", e.Name())
}
}
}
func TestInstallTrackedRepo_ForceReplacesExistingRepoInto(t *testing.T) {
remoteURL := makeRemote(t, "")
sourceDir := t.TempDir()
source := &Source{Type: SourceTypeGitHTTPS, Raw: remoteURL, CloneURL: remoteURL}
opts := InstallOptions{Name: "foo", Into: "team"}
if _, err := InstallTrackedRepo(source, sourceDir, opts); err != nil {
t.Fatalf("first install: %v", err)
}
stale := filepath.Join(sourceDir, "team", "_foo", "stale.txt")
if err := os.WriteFile(stale, []byte("x"), 0644); err != nil {
t.Fatal(err)
}
opts.Force = true
if _, err := InstallTrackedRepo(source, sourceDir, opts); err != nil {
t.Fatalf("forced reinstall: %v", err)
}
if _, err := os.Stat(stale); !os.IsNotExist(err) {
t.Errorf("the previous checkout should be replaced, stat err = %v", err)
}
if _, err := os.Stat(filepath.Join(sourceDir, "team", "_foo", "SKILL.md")); err != nil {
t.Errorf("the new clone should be in place: %v", err)
}
entries, _ := os.ReadDir(filepath.Join(sourceDir, "team"))
for _, e := range entries {
if strings.HasPrefix(e.Name(), ".skillshare-") {
t.Errorf("leftover %s after a forced reinstall", e.Name())
}
}
}
func TestInstallTrackedRepo_UpdateAcceptsSourceThatIsTheDestination(t *testing.T) {
remoteURL := makeRemote(t, "")
sourceDir := t.TempDir()
remote := &Source{Type: SourceTypeGitHTTPS, Raw: remoteURL, CloneURL: remoteURL}
if _, err := InstallTrackedRepo(remote, sourceDir, InstallOptions{Name: "foo"}); err != nil {
t.Fatalf("first install: %v", err)
}
source, err := ParseSource(filepath.Join(sourceDir, "_foo"))
if err != nil {
t.Fatal(err)
}
result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "foo", Update: true})
if err != nil {
t.Fatalf("--update pulls in place and must not be refused: %v", err)
}
if result.Action != "updated" {
t.Errorf("Action = %q, want updated", result.Action)
}
}
func TestInstallTrackedRepo_ForceReportsRootSkillUnderFinalName(t *testing.T) {
remoteURL := makeRemote(t, "")
sourceDir := t.TempDir()
source := &Source{Type: SourceTypeGitHTTPS, Raw: remoteURL, CloneURL: remoteURL}
if _, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "foo"}); err != nil {
t.Fatalf("first install: %v", err)
}
result, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "foo", Force: true})
if err != nil {
t.Fatalf("forced reinstall: %v", err)
}
if len(result.Skills) != 1 || result.Skills[0] != "_foo" {
t.Errorf("Skills = %v, want [_foo]", result.Skills)
}
}
func TestInstallTrackedRepo_KeepsDestinationClaimedByAnotherInstaller(t *testing.T) {
remoteURL := makeRemote(t, "")
sourceDir := t.TempDir()
source := &Source{Type: SourceTypeGitHTTPS, Raw: remoteURL, CloneURL: remoteURL}
theirs := filepath.Join(sourceDir, "_foo", "theirs.txt")
claim := func(string) {
// Another process creates the destination while this clone runs.
if err := os.MkdirAll(filepath.Dir(theirs), 0755); err == nil {
_ = os.WriteFile(theirs, []byte("x"), 0644)
}
}
_, err := InstallTrackedRepo(source, sourceDir, InstallOptions{Name: "foo", OnProgress: claim})
if err == nil {
t.Fatal("expected the install to fail when the destination was claimed meanwhile")
}
if _, statErr := os.Stat(theirs); statErr != nil {
t.Fatalf("the other installer's checkout must survive: %v", statErr)
}
}