Files
skillshare/internal/sync/copy.go
T
Rusty ShacklefordandWillie 85bcf589a7 feat(sync): recognize and route agent-specific skill variants (#649)
* docs(proposals): propose agent-specific skill variants

Tracked repositories can ship different files for the same skill across
agents. Counting and syncing each copy independently sends incompatible
instructions to every target unless users maintain routing filters.

Propose repository-scoped logical identity and exact variant routing while
preserving source files, explicit controls, and existing naming behavior.
Leave activation and compatibility decisions for maintainer review.

Refs #648

* docs(proposals): clarify variant routing compatibility

Explain how recognition affects universal-only targets and how existing
per-variant overrides preserve the desired routing. Fix the precedence
between variant identity and generic host-style path inference.

Include analyze, move, and catalog consumers while preserving physical
identifiers and actual context-cost accounting.

Refs #648

* docs(proposals): clarify activation assumptions and scope

Make acceptance cases conditional on maintainer-approved recognition being
enabled for the tracked source. Separate the provisional implementation
estimate from this proposal-only PR so its size is clear.

Refs #648

* docs(proposals): qualify naming and opt-in assumptions

State that the reproduced routing behavior uses default flat target
naming. Leave any opt-in surface with the maintainer's activation decision
without ruling out future CLI or config fields.

Refs #648

* feat: recognize and route tracked agent skill variants

Count tracked variants as logical skills in source and repository summaries,
while preserving physical paths, sync operations, and context costs. Select
matching canonical agent variants, including account targets, through shared
discovery and selection with existing explicit routing precedence.

Refs #648

* fix: count logical skills in sync inventory summaries

Use shared logical and physical inventory counts in global and project sync
closing lines while preserving each target's operation totals.

Refs #648

* fix: preserve variant routing diagnostics across previews

Resolve target selections once so CLI and server previews keep ambiguity
reasons and physical skip counts. Explain managed variants removed by
automatic agent routing, and report logical inventory in doctor.

Keep warning rows read-only, document upgrade recovery in translated
filtering references, and remove the optional README-only addition.

Refs #648

* fix: align sync matrix previews with shared variant selection

Classify the full source selection once per target so matrix previews honor
canonical aliases, account identity, exact-agent routing, and ambiguous
variant skips. Preserve each rejected physical path's existing diagnostic
and draft filter disambiguation; skipped preview rows remain read-only.

Refs #648

* test: expect singular skill wording in doctor source checks

Keep the undiscovered-link count assertion aligned with logical source
inventory formatting for one skill in global and project mode.

Refs #648

* fix: retain selection diagnostics in catalog and diff verdicts

Report warning-only diff targets as requiring attention while preserving
local-only folder semantics. Reuse shared per-path selection diagnostics
in target-scoped catalogs without applying target naming to served paths.

Compute source counts once in summary callers and require variant counts
in the source status formatter.

Refs #648

* test: tighten tracked variant preview fixtures

Use a real committed tracked repository for status counts, verify sync
preview banners retain server warnings, and use emitted ambiguity reason
text in target preview fixtures.

Refs #648

* fix(sync): keep agent variants in shared target folders

Compatible targets sharing a skills folder need a combined selection so
Codex and universal do not prune one another in merge or copy mode.
Carry every shared reader through selection, pruning and previews,
including project targets, account identities and path aliases.

Require a matching skill suffix under two distinct agents before
inferring variants, keeping ordinary agent-named categories unrestricted.
Separate naming warnings from ambiguous selection in diff and explain
ambiguous removals. Add global/project regression coverage for repeated
sync, target-only sync, status JSON, diff and API consumers.

* fix(variants): align consumer counts, hints and diagnostics

Use logical source counts in list, tracked install and init summaries while matching audit caches against physical variants. Restore localized dashboard skip hints and explain symlink routing limits in status and doctor, including project and JSON output.

Document paired-agent detection and compatible shared-folder selection in the proposal, built-in skill and English plus translated command pages. Add focused regressions for the affected consumers.

* fix(sync): cover initial sync and ignored variant diagnostics

Init syncs a fresh in-memory config, so resolve shared target identities
before its first sync as well as when loading saved configuration.

A whole-directory symlink exposes ignored skills too. Diagnose agent
variants using physical inventory when active discovery has none, while
keeping logical counts and merge/copy selection restricted to enabled
skills. Cover global/project JSON status and doctor with regressions.

Reuse sourcewalk directory and canonical-path helpers so traversal guards
remain enforced and path resolution has a single existing owner.

* fix(variants): address conversion, counts and selection diagnostics

Ignore runtime agent identities when comparing convertible project targets and count logical skills during init. Keep selection warnings separate from naming warnings and preserve agent-named parent skills as ordinary skills.

Cover account sync/prune, project ambiguity and overrides in merge/copy modes, and init/status agreement. Focused verification ran in an isolated Linux Codex container, not the devcontainer, as authorized.

* refactor(variants): remove obsolete selection helpers

Remove the unused FilterSkillsByTarget wrapper and prune agent parameter, cache canonical target aliases once, and restore catalog skip ordering to avoid an unrelated behavior change. Completes the optional cleanup from PR 649 review.

* fix(ui): expose localized variant selection diagnostics

Show target warnings with source paths, localize ambiguity across preview and detail consumers, and let skipped preview rows add a physical exclude pattern. Show tracked repository variant counts alongside logical skills.

Drop display-only rendered cases while retaining mutation protection and plain TypeScript logic coverage. Inspect target states in Clean/Playful light/dark and Traditional Chinese.

* docs(variants): explain diagnostics and add sync runbook

Document doctor variant_routing and logical/physical counts, diff selection skips, and the nested parent-skill boundary. Keep all four command translations aligned and add isolated account/project E2E scenarios.

Both runbook steps passed in the authorized Linux Codex container with separate HOME/XDG/TMPDIR fixtures. Website typecheck and all five locale builds passed.

* test(config): use native paths in project conversion fixture

The shared-agent regression fixture appended slash-separated suffixes to Windows temporary paths, so project path matching returned no candidates. Build each path with filepath.Join and preserve all conversion assertions.

Focused project configuration tests passed in the authorized isolated Linux Codex container, not the devcontainer. Windows CI verifies the platform-specific fixture correction.

* fix(ui): recompute shared skill routing for filter previews

Evaluate edited include/exclude settings in the complete target map before
classifying the draft, so a formerly shared folder no longer keeps its old
union when the filters differ. Preserve the saved target configuration.

* fix(mcp): keep parent skills when peer variants route elsewhere

Do not treat an otherwise eligible variant for another agent as an unserved
nested skill. Continue blocking parent publication for explicitly filtered,
disabled, ambiguous, or invalid children so filters still hide their files.

* fix(ui): distinguish agent selection from naming skips

Expose separate naming and selection skip counts on target summaries.
Show each applicable remedy in target details and sync previews so ambiguity
keeps its filter/override guidance alongside naming and collision hints.

* fix(list): include disabled rows in tracked repository counts

Count the complete inventory that list displays, including ignored skills
and physical variants, without changing the enabled counts used by status,
install, or sync. Clone rows before counting to preserve disabled state.

* docs: align variant counts and routing recovery guidance

Show logical skill and physical variant counts in list/install documentation
and keep the four translations aligned with the filtering examples. Explain
that agent-named skill parents keep ordinary nested skills and retain the
devcontainer-only runbook environment. Removal warnings now recommend a
source-local override, since include filters cannot undo agent routing.

* fix(mcp): preserve explicit target restrictions on nested variants

Limit the differently routed child exemption to automatic layout inference.
Frontmatter targets and dashboard source-local overrides must still prevent
a parent from publishing files explicitly restricted to another target.

* fix(ui): fill target name in naming warning guidance

Pass the current target name when rendering localized warning hints so the
same naming guidance shown beside the controls does not expose a placeholder
in the warning banner. Verified in the populated target preview.

---------

Co-authored-by: Willie <egg358358@gmail.com>
2026-10-29 16:47:38 +08:00

578 lines
19 KiB
Go

package sync
import (
"crypto/sha256"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"skillshare/internal/config"
"skillshare/internal/skillignore"
"skillshare/internal/utils"
)
// CopyResult holds the result of a copy sync operation.
type CopyResult struct {
Copied []string // newly copied skills
Skipped []string // checksum unchanged, or a user's folder kept
KeptLocal []string // the Skipped that are a user's folder on a skill's name; --force replaces them
Updated []string // checksum changed, overwritten
DirCreated string // Non-empty if target directory was auto-created (or would be in dry-run)
// UnmatchedIncludes are the include patterns that select no skill.
UnmatchedIncludes []UnmatchedInclude
}
// CopyOptions controls copy-mode sync behavior.
type CopyOptions struct {
IgnorePatterns []string
}
// SyncTargetCopy performs copy mode sync — copies each skill individually
// while preserving target-specific (unmanaged) skills.
func SyncTargetCopy(name string, target config.TargetConfig, sourcePath string, dryRun, force bool) (*CopyResult, error) {
return SyncTargetCopyWithOptions(name, target, sourcePath, dryRun, force, CopyOptions{
IgnorePatterns: DefaultFileIgnorePatterns(),
})
}
// SyncTargetCopyWithOptions is SyncTargetCopy with explicit copy behavior options.
func SyncTargetCopyWithOptions(name string, target config.TargetConfig, sourcePath string, dryRun, force bool, opts CopyOptions) (*CopyResult, error) {
skills, err := DiscoverSourceSkills(sourcePath)
if err != nil {
return nil, fmt.Errorf("failed to discover skills: %w", err)
}
return SyncTargetCopyWithSkillsOptions(name, target, skills, sourcePath, dryRun, force, nil, opts)
}
// SyncTargetCopyWithSkills is like SyncTargetCopy but accepts pre-discovered skills
// and an optional progress callback for per-skill UI updates.
// sourcePath is the skills source directory, used to detect symlink-mode targets.
func SyncTargetCopyWithSkills(name string, target config.TargetConfig, allSkills []DiscoveredSkill, sourcePath string, dryRun, force bool, onProgress func(current, total int, skill string)) (*CopyResult, error) {
return SyncTargetCopyWithSkillsOptions(name, target, allSkills, sourcePath, dryRun, force, onProgress, CopyOptions{
IgnorePatterns: DefaultFileIgnorePatterns(),
})
}
// SyncTargetCopyWithSkillsOptions is SyncTargetCopyWithSkills with explicit copy behavior options.
func SyncTargetCopyWithSkillsOptions(name string, target config.TargetConfig, allSkills []DiscoveredSkill, sourcePath string, dryRun, force bool, onProgress func(current, total int, skill string), opts CopyOptions) (*CopyResult, error) {
sc := target.SkillsConfig()
result := &CopyResult{}
if !sc.IsEnabled() {
return result, nil
}
ignorePatterns := opts.IgnorePatterns
if ignorePatterns == nil {
ignorePatterns = DefaultFileIgnorePatterns()
}
// Convert from symlink mode if needed, auto-create if missing.
dirCreated, err := ensureRealTargetDir(sc.Path, sourcePath, "copy", dryRun)
if err != nil {
return nil, err
}
if dirCreated {
result.DirCreated = sc.Path
}
// When dry-run would create the directory, suppress per-skill diagnostic
// messages (they flood the terminal). Counts are still populated.
quietDryRun := dirCreated && dryRun
resolution, err := ResolveTargetSkillsForTarget(name, target.SkillsConfig(), allSkills)
if err != nil {
return nil, err
}
printResolutionSummary(resolution)
result.UnmatchedIncludes = resolution.UnmatchedIncludes
// Read existing manifest
manifest, err := ReadManifest(sc.Path)
if err != nil {
return nil, fmt.Errorf("failed to read manifest: %w", err)
}
naming := resolution.Naming
taken := resolution.ValidTargetNames()
for i, resolved := range resolution.Skills {
skill := resolved.Skill
activeName, err := selectActiveTargetNameForSync("copy", sc.Path, resolved, taken, manifest, dryRun)
if err != nil {
return nil, err
}
if onProgress != nil {
onProgress(i+1, len(resolution.Skills), activeName)
}
targetSkillPath := filepath.Join(sc.Path, activeName)
// Compute source mtime for fast-path skip
currentMtime, mtimeErr := DirMaxMtimeWithIgnore(skill.SourcePath, ignorePatterns)
// mtime fast-path: if source mtime is unchanged AND target is still a valid dir, skip checksum
oldChecksum, isManaged := manifest.Managed[activeName]
oldMtime := manifest.Mtimes[activeName] // 0 if missing
// A copy made under another naming carries another name:, so it is
// refreshed even when the source is unchanged. A legacy entry kept
// under its old name keeps its old naming.
onDesiredName := activeName == resolved.TargetName
recordedNaming := manifest.Naming[activeName]
namingChanged := onDesiredName && recordedNaming != "" && recordedNaming != naming
// Under prefixed naming the copy's name: becomes the entry name, so it
// matches its folder. A legacy entry kept under its old name is copied as is.
rewriteName := ""
if naming == "prefixed" && onDesiredName && resolved.TargetName != resolved.SkillName {
rewriteName = resolved.TargetName
}
recordNaming := func() {
if onDesiredName && !dryRun {
manifest.Naming[activeName] = naming
}
}
if mtimeErr == nil && isManaged && !force && !namingChanged && oldMtime > 0 && currentMtime == oldMtime {
// Verify target still exists as a directory (user may have replaced it)
if ti, err := os.Lstat(targetSkillPath); err == nil && ti.IsDir() {
recordNaming()
result.Skipped = append(result.Skipped, activeName)
continue
}
}
// mtime changed or no record — compute full checksum
srcChecksum, err := DirChecksumWithIgnore(skill.SourcePath, ignorePatterns)
if err != nil {
return nil, fmt.Errorf("failed to checksum source skill %s: %w", activeName, err)
}
// Check what exists at the target path
targetInfo, lstatErr := os.Lstat(targetSkillPath)
exists := lstatErr == nil
if exists {
// If it's a symlink (leftover from merge mode), remove it
if utils.IsSymlinkOrJunction(targetSkillPath) {
if dryRun {
if !quietDryRun {
fmt.Fprintf(DiagOutput, "[dry-run] Would replace symlink with copy: %s\n", activeName)
}
} else {
os.Remove(targetSkillPath)
}
// Fall through to copy below
} else {
// Non-directory entries are invalid for managed skills.
// Managed/forced entries should be replaced with a proper skill directory.
if !targetInfo.IsDir() {
if isManaged || force {
if dryRun {
if !quietDryRun {
fmt.Fprintf(DiagOutput, "[dry-run] Would replace non-directory entry with copy: %s\n", activeName)
}
} else {
if err := os.RemoveAll(targetSkillPath); err != nil {
return nil, fmt.Errorf("failed to remove invalid entry %s: %w", activeName, err)
}
if err := copySkillToTarget(skill.SourcePath, targetSkillPath, rewriteName, ignorePatterns); err != nil {
return nil, fmt.Errorf("failed to copy skill %s: %w", activeName, err)
}
manifest.Managed[activeName] = srcChecksum
recordNaming()
if mtimeErr == nil {
manifest.Mtimes[activeName] = currentMtime
}
}
result.Updated = append(result.Updated, activeName)
continue
}
// Local non-directory entry — preserve unless --force.
result.Skipped = append(result.Skipped, activeName)
result.KeptLocal = append(result.KeptLocal, activeName)
continue
}
if !force && isManaged && !namingChanged && oldChecksum == srcChecksum {
// Unchanged — skip (but update mtime record if it changed)
if mtimeErr == nil && currentMtime != oldMtime && !dryRun {
manifest.Mtimes[activeName] = currentMtime
}
recordNaming()
result.Skipped = append(result.Skipped, activeName)
continue
}
if isManaged || force {
// Managed or forced — overwrite
if dryRun {
if !quietDryRun {
fmt.Fprintf(DiagOutput, "[dry-run] Would update copy: %s\n", activeName)
}
} else {
if err := os.RemoveAll(targetSkillPath); err != nil {
return nil, fmt.Errorf("failed to remove old copy %s: %w", activeName, err)
}
}
if !dryRun {
if err := copySkillToTarget(skill.SourcePath, targetSkillPath, rewriteName, ignorePatterns); err != nil {
return nil, fmt.Errorf("failed to copy skill %s: %w", activeName, err)
}
manifest.Managed[activeName] = srcChecksum
recordNaming()
if mtimeErr == nil {
manifest.Mtimes[activeName] = currentMtime
}
}
result.Updated = append(result.Updated, activeName)
continue
}
// Not managed (local skill) — preserve
result.Skipped = append(result.Skipped, activeName)
result.KeptLocal = append(result.KeptLocal, activeName)
continue
}
}
// Copy skill to target
if dryRun {
if !quietDryRun {
dest := targetSkillPath
// A dry run leaves an entry it would rename at its old name.
if !onDesiredName {
newPath := filepath.Join(sc.Path, resolved.TargetName)
if _, err := os.Lstat(newPath); os.IsNotExist(err) {
dest = newPath
}
}
fmt.Fprintf(DiagOutput, "[dry-run] Would copy: %s -> %s\n", skill.SourcePath, dest)
}
} else {
if err := copySkillToTarget(skill.SourcePath, targetSkillPath, rewriteName, ignorePatterns); err != nil {
return nil, fmt.Errorf("failed to copy skill %s: %w", activeName, err)
}
manifest.Managed[activeName] = srcChecksum
recordNaming()
if mtimeErr == nil {
manifest.Mtimes[activeName] = currentMtime
}
}
result.Copied = append(result.Copied, activeName)
}
// Write updated manifest
if !dryRun {
if err := WriteManifest(sc.Path, manifest); err != nil {
return nil, fmt.Errorf("failed to write manifest: %w", err)
}
}
return result, nil
}
// copySkillToTarget copies a skill into dst and, when newName is set, rewrites
// name: in the copied SKILL.md to it. The source is never touched.
func copySkillToTarget(src, dst, newName string, ignorePatterns []string) error {
if err := copyDirectoryWithIgnore(src, dst, ignorePatterns); err != nil {
return err
}
if newName == "" {
return nil
}
skillFile := filepath.Join(dst, "SKILL.md")
// The copy keeps the source's mode; lift a read-only one for the rewrite only.
if info, err := os.Stat(skillFile); err == nil && info.Mode().Perm()&0o200 == 0 {
os.Chmod(skillFile, info.Mode().Perm()|0o200)
defer os.Chmod(skillFile, info.Mode().Perm())
}
if err := utils.SetFrontmatterValue(skillFile, "name", newName); err != nil {
// dst was just created by this copy; left behind without a manifest
// entry, it would pass for a user's folder and never be refreshed.
os.RemoveAll(dst)
return fmt.Errorf("failed to set prefixed name: %w", err)
}
return nil
}
// PruneOrphanCopies removes managed copies that no longer exist in source.
func PruneOrphanCopies(targetPath, sourcePath string, include, exclude []string, targetName, targetNaming string, dryRun bool) (*PruneResult, error) {
allSourceSkills, err := DiscoverSourceSkills(sourcePath)
if err != nil {
return nil, fmt.Errorf("failed to discover skills for pruning: %w", err)
}
return PruneOrphanCopiesWithSkills(targetPath, allSourceSkills, include, exclude, targetName, targetNaming, dryRun)
}
// PruneOrphanCopiesWithSkills is like PruneOrphanCopies but accepts pre-discovered skills.
func PruneOrphanCopiesWithSkills(targetPath string, allSourceSkills []DiscoveredSkill, include, exclude []string, targetName, targetNaming string, dryRun bool) (*PruneResult, error) {
sc := config.ResourceTargetConfig{Path: targetPath, TargetNaming: targetNaming, Include: include, Exclude: exclude}
return pruneOrphanCopiesWithConfig(targetName, sc, allSourceSkills, dryRun)
}
func pruneOrphanCopiesWithConfig(targetName string, sc config.ResourceTargetConfig, allSourceSkills []DiscoveredSkill, dryRun bool) (*PruneResult, error) {
targetPath := sc.Path
result := &PruneResult{}
manifest, err := ReadManifest(targetPath)
if err != nil {
return nil, fmt.Errorf("failed to read manifest: %w", err)
}
resolution, err := ResolveTargetSkillsForTarget(targetName, sc, allSourceSkills)
if err != nil {
return nil, err
}
validTargetNames := resolution.ValidTargetNames()
legacyNames := resolution.LegacyNames("copy", targetPath, manifest)
// Remove manifest entries that are no longer in source
for entryName := range manifest.Managed {
if validTargetNames[entryName] {
continue
}
if _, keepLegacy := legacyNames[entryName]; keepLegacy {
continue
}
entryPath := filepath.Join(targetPath, entryName)
if dryRun {
fmt.Fprintf(DiagOutput, "[dry-run] Would remove orphan copy: %s\n", entryPath)
} else {
if err := os.RemoveAll(entryPath); err != nil {
result.Warnings = append(result.Warnings,
fmt.Sprintf("%s: failed to remove: %v", entryName, err))
continue
}
manifest.Remove(entryName)
}
result.Removed = append(result.Removed, entryName)
}
// Write updated manifest (only if we actually removed something)
if !dryRun && len(result.Removed) > 0 {
if err := WriteManifest(targetPath, manifest); err != nil {
return result, fmt.Errorf("failed to write manifest: %w", err)
}
}
return result, nil
}
// CheckStatusCopy checks the status of a target in copy mode.
// Returns: status, managed count, local count.
func CheckStatusCopy(targetPath string) (TargetStatus, int, int) {
info, err := os.Lstat(targetPath)
if err != nil {
if os.IsNotExist(err) {
return StatusNotExist, 0, 0
}
return StatusUnknown, 0, 0
}
// If it's a symlink, it's using symlink mode, not copy
if utils.IsSymlinkOrJunction(targetPath) {
return StatusLinked, 0, 0
}
if !info.IsDir() {
return StatusUnknown, 0, 0
}
manifest, err := ReadManifest(targetPath)
if err != nil {
return StatusUnknown, 0, 0
}
// Count managed entries that actually exist on disk
managedCount := 0
for name := range manifest.Managed {
if info, err := os.Stat(filepath.Join(targetPath, name)); err == nil && info.IsDir() {
managedCount++
}
}
// Count local (non-managed) entries
localCount := 0
entries, _ := os.ReadDir(targetPath)
for _, entry := range entries {
if utils.IsHidden(entry.Name()) {
continue
}
if !entry.IsDir() {
continue
}
if _, isManaged := manifest.Managed[entry.Name()]; !isManaged {
localCount++
}
}
if managedCount > 0 || len(manifest.Managed) > 0 {
return StatusCopied, managedCount, localCount
}
return StatusHasFiles, 0, localCount
}
// DirMaxMtime returns the latest ModTime (UnixNano) among all files in dir.
// Skips .git directories. Only uses os.Stat (via filepath.Walk), never reads file content.
func DirMaxMtime(dir string) (int64, error) {
return DirMaxMtimeWithIgnore(dir, nil)
}
// DirMaxMtimeWithIgnore returns the latest ModTime among non-ignored files in dir.
func DirMaxMtimeWithIgnore(dir string, ignorePatterns []string) (int64, error) {
var maxMtime int64
hasSymlink := false
ignore := compileFileIgnore(ignorePatterns)
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath, relErr := filepath.Rel(dir, path)
if relErr != nil {
return relErr
}
relPath = strings.ReplaceAll(relPath, "\\", "/")
if info.IsDir() {
if info.Name() == ".git" {
return filepath.SkipDir
}
if relPath != "." && isFileIgnored(ignore, relPath, true) {
return filepath.SkipDir
}
return nil
}
if isFileIgnored(ignore, relPath, false) {
return nil
}
// Symlink targets can change without updating the link mtime.
// Disable mtime fast-path for symlink-containing skills.
if utils.IsLinkMode(path, info.Mode()) {
hasSymlink = true
return nil
}
if mt := info.ModTime().UnixNano(); mt > maxMtime {
maxMtime = mt
}
return nil
})
if err != nil {
return 0, err
}
if hasSymlink {
return 0, fmt.Errorf("mtime fast-path not supported for directories containing symlinks")
}
return maxMtime, nil
}
// DirChecksum computes a deterministic SHA256 checksum of a directory.
// It hashes sorted relative paths and file contents.
func DirChecksum(dir string) (string, error) {
return DirChecksumWithIgnore(dir, nil)
}
// DirChecksumWithIgnore computes a deterministic checksum of non-ignored files in dir.
func DirChecksumWithIgnore(dir string, ignorePatterns []string) (string, error) {
var entries []checksumEntry
err := collectChecksumEntries(dir, "", &entries, map[string]bool{}, compileFileIgnore(ignorePatterns))
if err != nil {
return "", err
}
// Sort for deterministic output
sort.Slice(entries, func(i, j int) bool {
return entries[i].relPath < entries[j].relPath
})
h := sha256.New()
for _, e := range entries {
io.WriteString(h, e.relPath)
h.Write([]byte{0}) // separator
h.Write(e.content)
h.Write([]byte{0}) // separator
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
type checksumEntry struct {
relPath string
content []byte
}
// collectChecksumEntries recursively collects file entries for checksumming.
// Directory symlinks are dereferenced to hash effective copied content.
func collectChecksumEntries(root, relPrefix string, entries *[]checksumEntry, active map[string]bool, ignore *skillignore.Matcher) error {
resolvedRoot, err := resolveLinkRoot(root)
if err != nil {
return fmt.Errorf("failed to resolve checksum root %s: %w", root, err)
}
if active[resolvedRoot] {
return fmt.Errorf("detected symlink directory cycle while checksumming: %s", root)
}
active[resolvedRoot] = true
defer delete(active, resolvedRoot)
// The root link has already been resolved and entered in the cycle set.
root = resolvedRoot
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath, err := filepath.Rel(root, path)
if err != nil {
return err
}
// Normalize path separators for cross-platform consistency
relPath = strings.ReplaceAll(relPath, "\\", "/")
if relPath == "." {
relPath = ""
}
fullRelPath := relPath
if relPrefix != "" {
if fullRelPath == "" {
fullRelPath = relPrefix
} else {
fullRelPath = relPrefix + "/" + fullRelPath
}
}
if info.IsDir() {
if info.Name() == ".git" {
return filepath.SkipDir
}
if fullRelPath != "" && isFileIgnored(ignore, fullRelPath, true) {
return filepath.SkipDir
}
return nil
}
if isFileIgnored(ignore, fullRelPath, false) {
return nil
}
// A symlink can point to a directory. In copy mode we dereference
// directory symlinks, so checksum should include effective contents.
if utils.IsLinkMode(path, info.Mode()) {
targetInfo, statErr := os.Stat(path)
if statErr != nil {
return fmt.Errorf("failed to stat symlink target %s: %w", path, statErr)
}
if targetInfo.IsDir() {
resolvedDir, resolveErr := filepath.EvalSymlinks(path)
if resolveErr != nil {
return fmt.Errorf("failed to resolve symlink directory %s: %w", path, resolveErr)
}
return collectChecksumEntries(resolvedDir, fullRelPath, entries, active, ignore)
}
}
content, err := os.ReadFile(path)
if err != nil {
return err
}
*entries = append(*entries, checksumEntry{relPath: fullRelPath, content: content})
return nil
})
}