mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-20 20:34:19 +00:00
@@ -1 +0,0 @@
|
||||
github: [runkids]
|
||||
@@ -39,12 +39,10 @@ jobs:
|
||||
cache-dependency-path: ui/pnpm-lock.yaml
|
||||
|
||||
- name: Build UI assets
|
||||
run: make ui-build
|
||||
run: cd ui && pnpm install --frozen-lockfile && pnpm run build
|
||||
|
||||
- name: Verify embedded UI assets exist
|
||||
run: |
|
||||
test -f internal/server/dist/index.html
|
||||
test -n "$(find internal/server/dist/assets -maxdepth 1 -type f | head -n 1)"
|
||||
- name: Create UI dist archive
|
||||
run: tar czf skillshare-ui-dist.tar.gz -C ui/dist .
|
||||
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
|
||||
@@ -8,45 +8,8 @@ on:
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
ui-embed-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: ui/pnpm-lock.yaml
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.23"
|
||||
|
||||
- name: Build UI assets
|
||||
run: make ui-build
|
||||
|
||||
- name: Verify embedded dist assets exist
|
||||
run: |
|
||||
test -f internal/server/dist/index.html
|
||||
test -n "$(find internal/server/dist/assets -maxdepth 1 -type f | head -n 1)"
|
||||
|
||||
- name: Build binary with embedded UI
|
||||
run: |
|
||||
mkdir -p bin
|
||||
go build -o bin/skillshare ./cmd/skillshare
|
||||
|
||||
unit-test:
|
||||
runs-on: ubuntu-latest
|
||||
needs: ui-embed-check
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -64,7 +27,6 @@ jobs:
|
||||
|
||||
integration-test:
|
||||
runs-on: ${{ matrix.os }}
|
||||
needs: ui-embed-check
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
|
||||
+6
-2
@@ -5,8 +5,6 @@ project_name: skillshare
|
||||
before:
|
||||
hooks:
|
||||
- go mod tidy
|
||||
- test -f internal/server/dist/index.html
|
||||
- 'test -n "$(find internal/server/dist/assets -maxdepth 1 -type f | head -n 1)"'
|
||||
|
||||
builds:
|
||||
- main: ./cmd/skillshare
|
||||
@@ -32,6 +30,8 @@ archives:
|
||||
|
||||
checksum:
|
||||
name_template: "checksums.txt"
|
||||
extra_files:
|
||||
- glob: skillshare-ui-dist.tar.gz
|
||||
|
||||
changelog:
|
||||
sort: asc
|
||||
@@ -41,6 +41,10 @@ changelog:
|
||||
- "^test:"
|
||||
- "^ci:"
|
||||
|
||||
release:
|
||||
extra_files:
|
||||
- glob: skillshare-ui-dist.tar.gz
|
||||
|
||||
brews:
|
||||
- repository:
|
||||
owner: runkids
|
||||
|
||||
@@ -1,5 +1,30 @@
|
||||
# Changelog
|
||||
|
||||
## [0.13.0] - 2026-02-16
|
||||
|
||||
### Added
|
||||
- **Skill-level `targets` field** — SKILL.md frontmatter now accepts a `targets` list to restrict which targets a skill syncs to; `check` validates unknown target names
|
||||
- **Target filter CLI** — `target <name> --add-include/--add-exclude/--remove-include/--remove-exclude` for inline filter editing; Web UI inline filter editor on Targets page
|
||||
- **XDG Base Directory support** — respect `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_STATE_HOME`; backups/trash stored in data dir, logs in state dir; automatic migration from legacy layout on first run
|
||||
- **Windows legacy path migration** — existing Windows installs at `~\.config\skillshare\` are auto-migrated to `%AppData%\skillshare\` with config source path rewrite
|
||||
- **Fuzzy subdirectory resolution** — `install owner/repo/skill-name` now fuzzy-matches nested skill directories by basename when exact path doesn't exist, with ambiguity error for multiple matches
|
||||
- **`list` grouped display** — skills are grouped by directory with tree-style formatting; `--verbose`/`-v` flag for detailed output
|
||||
- **Runtime UI download** — `skillshare ui` downloads frontend assets from GitHub Releases on first launch and caches at `~/.cache/skillshare/ui/<version>/`; `--clear-cache` to reset; `upgrade` pre-downloads UI assets
|
||||
|
||||
### Changed
|
||||
- **Unified project target names** — project targets now use the same short names as global (e.g. `claude` instead of `claude-code`); old names preserved as aliases for backward compatibility
|
||||
- **Binary no longer embeds UI** — removed `go:embed` and build tags; UI served exclusively from disk cache, reducing binary size
|
||||
- **Docker images simplified** — production and CI Dockerfiles no longer include Node build stages
|
||||
|
||||
### Fixed
|
||||
- **Windows `DataDir()`/`StateDir()` paths** — now correctly fall back to `%AppData%` instead of Unix-style `~/.local/` paths
|
||||
- **Migration result reporting** — structured `MigrationResult` with status tracking; migration outcomes printed at startup
|
||||
|
||||
### Breaking Changes
|
||||
- **Windows paths relocated** — config/data moves from `%USERPROFILE%\.config\skillshare\` to `%AppData%\skillshare\` (auto-migrated)
|
||||
- **XDG data/state split (macOS/Linux)** — backups and trash move from `~/.config/skillshare/` to `~/.local/share/skillshare/`; logs move to `~/.local/state/skillshare/` (auto-migrated)
|
||||
- **Project target names changed** — `claude-code` → `claude`, `gemini-cli` → `gemini`, etc. (old names still work via aliases)
|
||||
|
||||
## [0.12.6] - 2026-02-13
|
||||
|
||||
### Added
|
||||
|
||||
@@ -26,16 +26,12 @@ help:
|
||||
@echo " make fmt-check # verify formatting only"
|
||||
@echo " make check # fmt-check + lint + test"
|
||||
@echo " make ui-install # install frontend dependencies"
|
||||
@echo " make ui-build # build frontend + copy to embed"
|
||||
@echo " make ui-build # build frontend"
|
||||
@echo " make ui-dev # Go API server + Vite dev server (requires local Go)"
|
||||
@echo " make build-all # ui-build + build (full binary)"
|
||||
@echo " make build-all # ui-build + build"
|
||||
@echo " make clean # remove build artifacts"
|
||||
|
||||
build:
|
||||
@if [ ! -f internal/server/dist/index.html ]; then \
|
||||
mkdir -p internal/server/dist && \
|
||||
printf '<!DOCTYPE html><html><body><h1>UI not built</h1><p>Run: make build-all</p></body></html>' > internal/server/dist/index.html; \
|
||||
fi
|
||||
mkdir -p bin && go build -o bin/skillshare ./cmd/skillshare
|
||||
|
||||
build-meta:
|
||||
@@ -114,12 +110,10 @@ ui-install:
|
||||
|
||||
ui-build: ui-install
|
||||
cd ui && pnpm run build
|
||||
rm -rf internal/server/dist
|
||||
cp -r ui/dist internal/server/dist
|
||||
|
||||
ui-dev:
|
||||
@trap 'kill 0' EXIT; \
|
||||
go run -tags dev ./cmd/skillshare ui --no-open & \
|
||||
go run ./cmd/skillshare ui --no-open & \
|
||||
cd ui && pnpm run dev
|
||||
|
||||
build-all: ui-build build
|
||||
|
||||
@@ -44,9 +44,9 @@
|
||||
> **Recent Updates**
|
||||
> | Version | Highlights |
|
||||
> |---------|------------|
|
||||
> | [0.13.0](https://github.com/runkids/skillshare/releases/tag/v0.13.0) | Skill-level targets, XDG compliance, unified target names, runtime UI download |
|
||||
> | [0.12.0](https://github.com/runkids/skillshare/releases/tag/v0.12.0) | Skill Hub — generate indexes, search private catalogs with `--hub` |
|
||||
> | [0.11.0](https://github.com/runkids/skillshare/releases/tag/v0.11.0) | Security Audit, Operation Log, Trash, Update Preview — full audit trail + safety net |
|
||||
> | [0.10.0](https://github.com/runkids/skillshare/releases/tag/v0.10.0) | Web Dashboard — visual skill management via `skillshare ui` |
|
||||
|
||||
## Why skillshare
|
||||
|
||||
@@ -87,7 +87,7 @@ skillshare uses a **declarative** approach: define your targets once in `config.
|
||||
|
||||
## How It Works
|
||||
- macOS / Linux: `~/.config/skillshare/skills/`
|
||||
- Windows: `%USERPROFILE%\.config\skillshare\skills\`
|
||||
- Windows: `%AppData%\skillshare\skills\`
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
@@ -105,7 +105,7 @@ skillshare uses a **declarative** approach: define your targets once in `config.
|
||||
| Platform | Source Path | Link Type |
|
||||
|----------|-------------|-----------|
|
||||
| macOS/Linux | `~/.config/skillshare/skills/` | Symlinks |
|
||||
| Windows | `%USERPROFILE%\.config\skillshare\skills\` | NTFS Junctions (no admin required) |
|
||||
| Windows | `%AppData%\skillshare\skills\` | NTFS Junctions (no admin required) |
|
||||
|
||||
> [!TIP]
|
||||
> Skills can be organized in folders (e.g. `frontend/react/react-best-practices/`) — they're auto-flattened on sync. See the [Organizing Guide](https://skillshare.runkids.cc/docs/guides/organizing-skills) and [runkids/my-skills](https://github.com/runkids/my-skills) for a real-world example.
|
||||
@@ -145,7 +145,7 @@ irm https://raw.githubusercontent.com/runkids/skillshare/main/install.ps1 | iex
|
||||
brew install skillshare
|
||||
```
|
||||
|
||||
> **Note:** Recommended for CLI-only users. The Homebrew build does not include the [web dashboard](#web-dashboard) — all other commands work identically. For the full experience including `skillshare ui`, use the curl/PowerShell installer above.
|
||||
> **Note:** All install methods include the web dashboard. `skillshare ui` automatically downloads UI assets on first launch — no extra setup needed.
|
||||
|
||||
### Shorthand (Optional)
|
||||
|
||||
@@ -161,11 +161,14 @@ alias ss='skillshare'
|
||||
# macOS/Linux
|
||||
brew uninstall skillshare # Homebrew
|
||||
sudo rm /usr/local/bin/skillshare # Manual install
|
||||
rm -rf ~/.config/skillshare # Config & data (optional)
|
||||
rm -rf ~/.config/skillshare # Config & skills (optional)
|
||||
rm -rf ~/.local/share/skillshare # Backups & trash (optional)
|
||||
rm -rf ~/.local/state/skillshare # Logs (optional)
|
||||
rm -rf ~/.cache/skillshare # UI & version cache (optional)
|
||||
|
||||
# Windows (PowerShell)
|
||||
Remove-Item "$env:LOCALAPPDATA\Programs\skillshare" -Recurse -Force
|
||||
Remove-Item "$env:USERPROFILE\.config\skillshare" -Recurse -Force # optional
|
||||
Remove-Item "$env:APPDATA\skillshare" -Recurse -Force # optional
|
||||
```
|
||||
|
||||
---
|
||||
@@ -281,7 +284,7 @@ skillshare ui -p # Project mode (manages .skillshare/)
|
||||
- Opens `http://127.0.0.1:19420`
|
||||
- Requires `skillshare init` (or `init -p` for project mode) first
|
||||
- Auto-detects project mode when `.skillshare/config.yaml` exists
|
||||
- Runs from the same CLI binary (no extra frontend setup)
|
||||
- UI assets are downloaded on first launch (~1 MB), then cached offline at `~/.cache/skillshare/ui/`
|
||||
|
||||
For containers/remote hosts:
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/git"
|
||||
"skillshare/internal/install"
|
||||
ssync "skillshare/internal/sync"
|
||||
"skillshare/internal/ui"
|
||||
)
|
||||
|
||||
@@ -244,9 +245,27 @@ func runCheck(sourceDir string, jsonOutput bool) error {
|
||||
ui.Info("Run 'skillshare update <name>' or 'skillshare update --all'")
|
||||
}
|
||||
|
||||
// Warn about unknown target names in skill-level targets field
|
||||
warnUnknownSkillTargets(sourceDir)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func warnUnknownSkillTargets(sourceDir string) {
|
||||
discovered, err := ssync.DiscoverSourceSkills(sourceDir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
warnings := findUnknownSkillTargets(discovered)
|
||||
if len(warnings) > 0 {
|
||||
fmt.Println()
|
||||
for _, w := range warnings {
|
||||
ui.Warning("Skill targets: %s", w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func checkTrackedRepo(name, repoPath string) checkRepoResult {
|
||||
result := checkRepoResult{Name: name}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/backup"
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/sync"
|
||||
"skillshare/internal/trash"
|
||||
@@ -76,6 +77,9 @@ func cmdDoctorGlobal() error {
|
||||
return nil
|
||||
}
|
||||
ui.Success("Config: %s", config.ConfigPath())
|
||||
ui.Info("Config directory: %s", config.BaseDir())
|
||||
ui.Info("Data directory: %s", config.DataDir())
|
||||
ui.Info("State directory: %s", config.StateDir())
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
@@ -84,7 +88,7 @@ func cmdDoctorGlobal() error {
|
||||
}
|
||||
|
||||
runDoctorChecks(cfg, result, false)
|
||||
checkBackupStatus(false, config.ConfigPath())
|
||||
checkBackupStatus(false, backup.BackupDir())
|
||||
checkTrashStatus(trash.TrashDir())
|
||||
checkVersionDoctor(cfg)
|
||||
checkForUpdates()
|
||||
@@ -118,7 +122,7 @@ func cmdDoctorProject(root string) error {
|
||||
}
|
||||
|
||||
runDoctorChecks(cfg, result, true)
|
||||
checkBackupStatus(true, cfgPath)
|
||||
checkBackupStatus(true, "")
|
||||
checkTrashStatus(trash.ProjectTrashDir(root))
|
||||
checkVersionDoctor(cfg)
|
||||
checkForUpdates()
|
||||
@@ -142,6 +146,9 @@ func runDoctorChecks(cfg *config.Config, result *doctorResult, isProject bool) {
|
||||
// Check skills validity
|
||||
checkSkillsValidity(cfg.Source, result)
|
||||
|
||||
// Check skill-level targets field
|
||||
checkSkillTargetsField(cfg.Source, result)
|
||||
|
||||
// Check each target
|
||||
checkTargets(cfg, result)
|
||||
|
||||
@@ -338,6 +345,7 @@ func checkSyncDrift(cfg *config.Config, result *doctorResult) {
|
||||
result.addError()
|
||||
continue
|
||||
}
|
||||
filtered = sync.FilterSkillsByTarget(filtered, name)
|
||||
expectedCount := len(filtered)
|
||||
if expectedCount == 0 {
|
||||
continue
|
||||
@@ -423,6 +431,22 @@ func checkSkillsValidity(source string, result *doctorResult) {
|
||||
}
|
||||
}
|
||||
|
||||
// checkSkillTargetsField validates that skill-level targets values are known target names
|
||||
func checkSkillTargetsField(source string, result *doctorResult) {
|
||||
discovered, err := sync.DiscoverSourceSkills(source)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
warnings := findUnknownSkillTargets(discovered)
|
||||
if len(warnings) > 0 {
|
||||
for _, w := range warnings {
|
||||
ui.Warning("Skill targets: %s", w)
|
||||
}
|
||||
result.addWarning()
|
||||
}
|
||||
}
|
||||
|
||||
// checkBrokenSymlinks finds broken symlinks in targets
|
||||
func checkBrokenSymlinks(cfg *config.Config, result *doctorResult) {
|
||||
for name, target := range cfg.Targets {
|
||||
@@ -531,13 +555,11 @@ func checkDuplicateSkills(cfg *config.Config, result *doctorResult) {
|
||||
}
|
||||
|
||||
// checkBackupStatus shows last backup time
|
||||
func checkBackupStatus(isProject bool, cfgPath string) {
|
||||
func checkBackupStatus(isProject bool, backupDir string) {
|
||||
if isProject {
|
||||
ui.Info("Backups: not used in project mode")
|
||||
return
|
||||
}
|
||||
|
||||
backupDir := filepath.Join(filepath.Dir(cfgPath), "backups")
|
||||
entries, err := os.ReadDir(backupDir)
|
||||
if err != nil || len(entries) == 0 {
|
||||
ui.Info("Backups: none found")
|
||||
|
||||
@@ -183,7 +183,7 @@ func performFreshInit(opts *initOptions, home string) error {
|
||||
// Default source path (same location as config)
|
||||
sourcePath := opts.sourcePath
|
||||
if sourcePath == "" {
|
||||
sourcePath = filepath.Join(home, ".config", "skillshare", "skills")
|
||||
sourcePath = filepath.Join(config.BaseDir(), "skills")
|
||||
}
|
||||
|
||||
// Find directories with skills to potentially copy from
|
||||
|
||||
@@ -266,14 +266,13 @@ func createProjectTargetDirs(root string, targets []config.ProjectTargetEntry) e
|
||||
return nil
|
||||
}
|
||||
|
||||
knownTargets := config.ProjectTargets()
|
||||
created := map[string]bool{}
|
||||
|
||||
for _, target := range targets {
|
||||
name := target.Name
|
||||
path := target.Path
|
||||
if path == "" {
|
||||
if known, ok := knownTargets[name]; ok {
|
||||
if known, ok := config.LookupProjectTarget(name); ok {
|
||||
path = known.Path
|
||||
} else {
|
||||
continue
|
||||
@@ -311,13 +310,12 @@ func reinitProjectWithDiscover(root string, opts projectInitOptions) error {
|
||||
}
|
||||
|
||||
// Build set of existing paths for accurate dedup.
|
||||
knownTargets := config.ProjectTargets()
|
||||
existingPaths := make(map[string]bool)
|
||||
for _, t := range cfg.Targets {
|
||||
name := strings.TrimSpace(t.Name)
|
||||
if t.Path != "" {
|
||||
existingPaths[filepath.FromSlash(t.Path)] = true
|
||||
} else if known, ok := knownTargets[name]; ok {
|
||||
} else if known, ok := config.LookupProjectTarget(name); ok {
|
||||
existingPaths[filepath.FromSlash(known.Path)] = true
|
||||
}
|
||||
}
|
||||
@@ -356,7 +354,7 @@ func reinitProjectWithDiscover(root string, opts projectInitOptions) error {
|
||||
}
|
||||
target := findGroupedTarget(newTargets, name)
|
||||
if target == nil {
|
||||
if known, ok := knownTargets[name]; ok && existingPaths[filepath.FromSlash(known.Path)] {
|
||||
if known, ok := config.LookupProjectTarget(name); ok && existingPaths[filepath.FromSlash(known.Path)] {
|
||||
ui.Info("Target already covered: %s (skipped)", name)
|
||||
} else {
|
||||
ui.Warning("Target not detected: %s (skipped)", name)
|
||||
|
||||
@@ -694,11 +694,25 @@ func promptOrchestratorSelection(rootSkill install.SkillInfo, childSkills []inst
|
||||
}
|
||||
|
||||
func promptMultiSelect(skills []install.SkillInfo) ([]install.SkillInfo, error) {
|
||||
// Sort by path so skills in the same directory cluster together
|
||||
sorted := make([]install.SkillInfo, len(skills))
|
||||
copy(sorted, skills)
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
return sorted[i].Path < sorted[j].Path
|
||||
})
|
||||
skills = sorted
|
||||
|
||||
options := make([]string, len(skills))
|
||||
for i, skill := range skills {
|
||||
loc := skill.Path
|
||||
if skill.Path == "." {
|
||||
dir := filepath.Dir(skill.Path)
|
||||
var loc string
|
||||
switch {
|
||||
case skill.Path == ".":
|
||||
loc = "root"
|
||||
case dir == ".":
|
||||
loc = "root"
|
||||
default:
|
||||
loc = dir
|
||||
}
|
||||
options[i] = fmt.Sprintf("%s \033[90m%s\033[0m", skill.Name, loc)
|
||||
}
|
||||
|
||||
+152
-21
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/config"
|
||||
@@ -37,6 +38,7 @@ func buildSkillEntries(discovered []sync.DiscoveredSkill) []skillEntry {
|
||||
entry := skillEntry{
|
||||
Name: d.FlatName,
|
||||
IsNested: d.IsInRepo || utils.HasNestedSeparator(d.FlatName),
|
||||
RelPath: d.RelPath,
|
||||
}
|
||||
|
||||
if d.IsInRepo {
|
||||
@@ -57,37 +59,165 @@ func buildSkillEntries(discovered []sync.DiscoveredSkill) []skillEntry {
|
||||
return skills
|
||||
}
|
||||
|
||||
// displaySkillsVerbose displays skills in verbose mode
|
||||
func displaySkillsVerbose(skills []skillEntry) {
|
||||
// extractGroupDir returns the parent directory from a RelPath.
|
||||
// "frontend/react-helper" → "frontend", "my-skill" → "", "_team/frontend/ui" → "_team/frontend"
|
||||
func extractGroupDir(relPath string) string {
|
||||
i := strings.LastIndex(relPath, "/")
|
||||
if i < 0 {
|
||||
return ""
|
||||
}
|
||||
return relPath[:i]
|
||||
}
|
||||
|
||||
// groupSkillEntries groups skill entries by their parent directory.
|
||||
// Returns ordered group keys and a map of group→entries.
|
||||
// Top-level skills (no parent dir) are grouped under "".
|
||||
func groupSkillEntries(skills []skillEntry) ([]string, map[string][]skillEntry) {
|
||||
groups := make(map[string][]skillEntry)
|
||||
for _, s := range skills {
|
||||
fmt.Printf(" %s%s%s\n", ui.Cyan, s.Name, ui.Reset)
|
||||
if s.RepoName != "" {
|
||||
fmt.Printf(" %sTracked repo:%s %s\n", ui.Gray, ui.Reset, s.RepoName)
|
||||
dir := extractGroupDir(s.RelPath)
|
||||
groups[dir] = append(groups[dir], s)
|
||||
}
|
||||
|
||||
// Collect sorted directory keys (non-empty first, then top-level "")
|
||||
var dirs []string
|
||||
for k := range groups {
|
||||
if k != "" {
|
||||
dirs = append(dirs, k)
|
||||
}
|
||||
if s.Source != "" {
|
||||
fmt.Printf(" %sSource:%s %s\n", ui.Gray, ui.Reset, s.Source)
|
||||
fmt.Printf(" %sType:%s %s\n", ui.Gray, ui.Reset, s.Type)
|
||||
fmt.Printf(" %sInstalled:%s %s\n", ui.Gray, ui.Reset, s.InstalledAt)
|
||||
} else {
|
||||
fmt.Printf(" %sSource:%s (local - no metadata)\n", ui.Gray, ui.Reset)
|
||||
}
|
||||
sort.Strings(dirs)
|
||||
// Append top-level group last
|
||||
if _, ok := groups[""]; ok {
|
||||
dirs = append(dirs, "")
|
||||
}
|
||||
|
||||
return dirs, groups
|
||||
}
|
||||
|
||||
// displayName returns the base skill name for display within a group.
|
||||
// When grouped under a directory, show just the base name; otherwise show full name.
|
||||
func displayName(s skillEntry, groupDir string) string {
|
||||
if groupDir == "" {
|
||||
return s.Name
|
||||
}
|
||||
// Use the last segment of RelPath as the display name
|
||||
base := s.RelPath
|
||||
if i := strings.LastIndex(base, "/"); i >= 0 {
|
||||
base = base[i+1:]
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// hasGroups returns true if any skill has a parent directory (i.e., non-flat).
|
||||
func hasGroups(skills []skillEntry) bool {
|
||||
for _, s := range skills {
|
||||
if extractGroupDir(s.RelPath) != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// displaySkillsVerbose displays skills in verbose mode, grouped by directory
|
||||
func displaySkillsVerbose(skills []skillEntry) {
|
||||
if !hasGroups(skills) {
|
||||
// Flat display — no grouping needed
|
||||
for _, s := range skills {
|
||||
fmt.Printf(" %s%s%s\n", ui.Cyan, s.Name, ui.Reset)
|
||||
printVerboseDetails(s, " ")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
dirs, groups := groupSkillEntries(skills)
|
||||
for i, dir := range dirs {
|
||||
if dir != "" {
|
||||
if i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
fmt.Printf(" %s%s/%s\n", ui.Gray, dir, ui.Reset)
|
||||
} else if i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
for _, s := range groups[dir] {
|
||||
name := displayName(s, dir)
|
||||
indent := " "
|
||||
detailIndent := " "
|
||||
if dir == "" {
|
||||
indent = " "
|
||||
detailIndent = " "
|
||||
}
|
||||
fmt.Printf("%s%s%s%s\n", indent, ui.Cyan, name, ui.Reset)
|
||||
printVerboseDetails(s, detailIndent)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
// displaySkillsCompact displays skills in compact mode
|
||||
func printVerboseDetails(s skillEntry, indent string) {
|
||||
if s.RepoName != "" {
|
||||
fmt.Printf("%s%sTracked repo:%s %s\n", indent, ui.Gray, ui.Reset, s.RepoName)
|
||||
}
|
||||
if s.Source != "" {
|
||||
fmt.Printf("%s%sSource:%s %s\n", indent, ui.Gray, ui.Reset, s.Source)
|
||||
fmt.Printf("%s%sType:%s %s\n", indent, ui.Gray, ui.Reset, s.Type)
|
||||
fmt.Printf("%s%sInstalled:%s %s\n", indent, ui.Gray, ui.Reset, s.InstalledAt)
|
||||
} else {
|
||||
fmt.Printf("%s%sSource:%s (local - no metadata)\n", indent, ui.Gray, ui.Reset)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
// displaySkillsCompact displays skills in compact mode, grouped by directory
|
||||
func displaySkillsCompact(skills []skillEntry) {
|
||||
maxNameLen := 0
|
||||
for _, s := range skills {
|
||||
if len(s.Name) > maxNameLen {
|
||||
maxNameLen = len(s.Name)
|
||||
if !hasGroups(skills) {
|
||||
// Flat display — identical to previous behavior
|
||||
maxNameLen := 0
|
||||
for _, s := range skills {
|
||||
if len(s.Name) > maxNameLen {
|
||||
maxNameLen = len(s.Name)
|
||||
}
|
||||
}
|
||||
for _, s := range skills {
|
||||
suffix := getSkillSuffix(s)
|
||||
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", ui.Cyan, ui.Reset, maxNameLen, ui.Gray, ui.Reset)
|
||||
fmt.Printf(format, s.Name, suffix)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
for _, s := range skills {
|
||||
suffix := getSkillSuffix(s)
|
||||
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", ui.Cyan, ui.Reset, maxNameLen, ui.Gray, ui.Reset)
|
||||
fmt.Printf(format, s.Name, suffix)
|
||||
dirs, groups := groupSkillEntries(skills)
|
||||
for i, dir := range dirs {
|
||||
if dir != "" {
|
||||
if i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
fmt.Printf(" %s%s/%s\n", ui.Gray, dir, ui.Reset)
|
||||
} else if i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
// Calculate max name length within this group
|
||||
maxNameLen := 0
|
||||
for _, s := range groups[dir] {
|
||||
name := displayName(s, dir)
|
||||
if len(name) > maxNameLen {
|
||||
maxNameLen = len(name)
|
||||
}
|
||||
}
|
||||
|
||||
for _, s := range groups[dir] {
|
||||
name := displayName(s, dir)
|
||||
suffix := getSkillSuffix(s)
|
||||
if dir != "" {
|
||||
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", ui.Cyan, ui.Reset, maxNameLen, ui.Gray, ui.Reset)
|
||||
fmt.Printf(format, name, suffix)
|
||||
} else {
|
||||
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", ui.Cyan, ui.Reset, maxNameLen, ui.Gray, ui.Reset)
|
||||
fmt.Printf(format, name, suffix)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,6 +342,7 @@ type skillEntry struct {
|
||||
InstalledAt string
|
||||
IsNested bool
|
||||
RepoName string
|
||||
RelPath string
|
||||
}
|
||||
|
||||
// abbreviateSource shortens long sources for display
|
||||
|
||||
@@ -4,20 +4,12 @@ import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/install"
|
||||
"skillshare/internal/sync"
|
||||
"skillshare/internal/ui"
|
||||
)
|
||||
|
||||
type projectSkillEntry struct {
|
||||
Name string
|
||||
Source string
|
||||
Remote bool
|
||||
RepoName string
|
||||
}
|
||||
|
||||
func cmdListProject(root string) error {
|
||||
if !projectConfigExists(root) {
|
||||
if err := performProjectInit(root, projectInitOptions{}); err != nil {
|
||||
@@ -34,28 +26,7 @@ func cmdListProject(root string) error {
|
||||
}
|
||||
|
||||
trackedRepos, _ := install.GetTrackedRepos(sourcePath)
|
||||
|
||||
var skills []projectSkillEntry
|
||||
for _, d := range discovered {
|
||||
entry := projectSkillEntry{
|
||||
Name: d.FlatName,
|
||||
}
|
||||
|
||||
if d.IsInRepo {
|
||||
parts := strings.SplitN(d.RelPath, "/", 2)
|
||||
if len(parts) > 0 {
|
||||
entry.RepoName = parts[0]
|
||||
}
|
||||
}
|
||||
|
||||
meta, _ := install.ReadMeta(d.SourcePath)
|
||||
if meta != nil && meta.Source != "" {
|
||||
entry.Source = meta.Source
|
||||
entry.Remote = true
|
||||
}
|
||||
|
||||
skills = append(skills, entry)
|
||||
}
|
||||
skills := buildSkillEntries(discovered)
|
||||
|
||||
sort.Slice(skills, func(i, j int) bool {
|
||||
return skills[i].Name < skills[j].Name
|
||||
@@ -69,19 +40,7 @@ func cmdListProject(root string) error {
|
||||
|
||||
if len(skills) > 0 {
|
||||
ui.Header("Installed skills (project)")
|
||||
|
||||
maxNameLen := 0
|
||||
for _, skill := range skills {
|
||||
if len(skill.Name) > maxNameLen {
|
||||
maxNameLen = len(skill.Name)
|
||||
}
|
||||
}
|
||||
|
||||
for _, skill := range skills {
|
||||
suffix := getProjectSkillSuffix(skill)
|
||||
format := fmt.Sprintf(" %s→%s %%-%ds %s%%s%s\n", ui.Cyan, ui.Reset, maxNameLen, ui.Gray, ui.Reset)
|
||||
fmt.Printf(format, skill.Name, suffix)
|
||||
}
|
||||
displaySkillsCompact(skills)
|
||||
}
|
||||
|
||||
if len(trackedRepos) > 0 {
|
||||
@@ -94,7 +53,7 @@ func cmdListProject(root string) error {
|
||||
for _, skill := range skills {
|
||||
if skill.RepoName != "" {
|
||||
trackedCount++
|
||||
} else if skill.Remote {
|
||||
} else if skill.Source != "" {
|
||||
remoteCount++
|
||||
}
|
||||
}
|
||||
@@ -102,13 +61,3 @@ func cmdListProject(root string) error {
|
||||
ui.Info("%d skill(s): %d tracked, %d remote, %d local", len(skills), trackedCount, remoteCount, localCount)
|
||||
return nil
|
||||
}
|
||||
|
||||
func getProjectSkillSuffix(s projectSkillEntry) string {
|
||||
if s.RepoName != "" {
|
||||
return fmt.Sprintf("tracked: %s", s.RepoName)
|
||||
}
|
||||
if s.Remote {
|
||||
return abbreviateSource(s.Source)
|
||||
}
|
||||
return "local"
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/ui"
|
||||
versioncheck "skillshare/internal/version"
|
||||
)
|
||||
@@ -44,6 +45,13 @@ func main() {
|
||||
// Clean up any leftover .old files from Windows self-upgrade
|
||||
cleanupOldBinary()
|
||||
|
||||
// Migrate Windows legacy ~/.config/skillshare → %AppData%\skillshare
|
||||
results := config.MigrateWindowsLegacyDir()
|
||||
|
||||
// Migrate legacy dirs (backups/trash/logs) to XDG data/state dirs
|
||||
results = append(results, config.MigrateXDGDirs()...)
|
||||
reportMigrationResults(results)
|
||||
|
||||
// Set version for other packages to use
|
||||
versioncheck.Version = version
|
||||
|
||||
@@ -90,6 +98,23 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
func reportMigrationResults(results []config.MigrationResult) {
|
||||
for _, r := range results {
|
||||
switch r.Status {
|
||||
case config.MigrationMoved:
|
||||
ui.Info("Migrated legacy data: %s -> %s", r.From, r.To)
|
||||
case config.MigrationFailed:
|
||||
if r.From != "" && r.To != "" {
|
||||
ui.Warning("Legacy migration failed: %s -> %s (%v)", r.From, r.To, r.Err)
|
||||
continue
|
||||
}
|
||||
ui.Warning("Legacy migration failed: %v", r.Err)
|
||||
}
|
||||
// MigrationSkippedDestinationExists is silent — it means the new
|
||||
// location already has data (normal after first migration).
|
||||
}
|
||||
}
|
||||
|
||||
func printUsage() {
|
||||
// Colors
|
||||
y := "\033[33m" // yellow - commands
|
||||
|
||||
@@ -150,6 +150,7 @@ description: >-
|
||||
"trigger phrase 1", "trigger phrase 2", or needs help
|
||||
with a specific task.
|
||||
# ── Optional fields ──────────────────────────────────
|
||||
# targets: [] # e.g. [claude, cursor] — omit for all targets
|
||||
# license: MIT
|
||||
# allowed-tools: "Bash(python:*) WebFetch"
|
||||
# metadata:
|
||||
|
||||
@@ -138,6 +138,7 @@ func printTargetsStatus(cfg *config.Config, discovered []sync.DiscoveredSkill) e
|
||||
if err != nil {
|
||||
return fmt.Errorf("target %s has invalid include/exclude config: %w", name, err)
|
||||
}
|
||||
filtered = sync.FilterSkillsByTarget(filtered, name)
|
||||
expectedCount := len(filtered)
|
||||
_, linkedCount, _ := sync.CheckStatusMerge(target.Path, cfg.Source)
|
||||
if linkedCount < expectedCount {
|
||||
|
||||
@@ -108,6 +108,7 @@ func printProjectTargetsStatus(runtime *projectRuntime, discovered []sync.Discov
|
||||
if err != nil {
|
||||
return fmt.Errorf("target %s has invalid include/exclude config: %w", entry.Name, err)
|
||||
}
|
||||
filtered = sync.FilterSkillsByTarget(filtered, entry.Name)
|
||||
expectedCount := len(filtered)
|
||||
_, linkedCount, _ := sync.CheckStatusMerge(target.Path, runtime.sourcePath)
|
||||
if linkedCount < expectedCount {
|
||||
|
||||
@@ -180,7 +180,7 @@ func syncMergeMode(name string, target config.TargetConfig, source string, dryRu
|
||||
}
|
||||
|
||||
// Prune orphan links (skills that no longer exist in source)
|
||||
pruneResult, pruneErr := sync.PruneOrphanLinks(target.Path, source, target.Include, target.Exclude, dryRun)
|
||||
pruneResult, pruneErr := sync.PruneOrphanLinks(target.Path, source, target.Include, target.Exclude, name, dryRun)
|
||||
if pruneErr != nil {
|
||||
ui.Warning("%s: prune failed: %v", name, pruneErr)
|
||||
}
|
||||
|
||||
+63
-10
@@ -5,9 +5,11 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/backup"
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/oplog"
|
||||
"skillshare/internal/sync"
|
||||
"skillshare/internal/ui"
|
||||
"skillshare/internal/utils"
|
||||
@@ -80,18 +82,33 @@ Subcommands:
|
||||
remove <name> Remove a target
|
||||
remove --all Remove all targets
|
||||
list List configured targets
|
||||
<name> Show target info
|
||||
<name> Show target info or modify settings
|
||||
|
||||
Options:
|
||||
--project, -p Use project-level config in current directory
|
||||
--global, -g Use global config (~/.config/skillshare)
|
||||
|
||||
Target Settings:
|
||||
<name> --mode <mode> Set sync mode (merge or symlink)
|
||||
<name> --add-include <pattern> Add an include filter pattern
|
||||
<name> --add-exclude <pattern> Add an exclude filter pattern
|
||||
<name> --remove-include <pattern> Remove an include filter pattern
|
||||
<name> --remove-exclude <pattern> Remove an exclude filter pattern
|
||||
|
||||
Examples:
|
||||
skillshare target add cursor
|
||||
skillshare target add my-ide .my-ide/skills
|
||||
skillshare target remove cursor
|
||||
skillshare target list
|
||||
skillshare target cursor`)
|
||||
skillshare target cursor
|
||||
skillshare target claude --add-include "team-*"
|
||||
skillshare target claude --remove-include "team-*"
|
||||
skillshare target claude --add-exclude "_legacy*"
|
||||
|
||||
Project mode:
|
||||
skillshare target add claude -p
|
||||
skillshare target claude --add-include "team-*" -p
|
||||
skillshare target list -p`)
|
||||
}
|
||||
|
||||
func targetAdd(args []string) error {
|
||||
@@ -385,6 +402,12 @@ func targetList() error {
|
||||
}
|
||||
|
||||
func targetInfo(name string, args []string) error {
|
||||
// Parse filter flags first, pass remaining to mode parsing
|
||||
filterOpts, remaining, err := parseFilterFlags(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -395,19 +418,47 @@ func targetInfo(name string, args []string) error {
|
||||
return fmt.Errorf("target '%s' not found. Use 'skillshare target list' to see available targets", name)
|
||||
}
|
||||
|
||||
// Parse flags
|
||||
// Parse --mode from remaining args
|
||||
var newMode string
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch args[i] {
|
||||
for i := 0; i < len(remaining); i++ {
|
||||
switch remaining[i] {
|
||||
case "--mode", "-m":
|
||||
if i+1 >= len(args) {
|
||||
if i+1 >= len(remaining) {
|
||||
return fmt.Errorf("--mode requires a value (merge or symlink)")
|
||||
}
|
||||
newMode = args[i+1]
|
||||
newMode = remaining[i+1]
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
// Apply filter updates if any
|
||||
if filterOpts.hasUpdates() {
|
||||
start := time.Now()
|
||||
changes, fErr := applyFilterUpdates(&target.Include, &target.Exclude, filterOpts)
|
||||
if fErr != nil {
|
||||
return fErr
|
||||
}
|
||||
cfg.Targets[name] = target
|
||||
if err := cfg.Save(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, change := range changes {
|
||||
ui.Success("%s: %s", name, change)
|
||||
}
|
||||
if len(changes) > 0 {
|
||||
ui.Info("Run 'skillshare sync' to apply filter changes")
|
||||
}
|
||||
|
||||
e := oplog.NewEntry("target", statusFromErr(nil), time.Since(start))
|
||||
e.Args = map[string]any{
|
||||
"action": "filter",
|
||||
"name": name,
|
||||
"changes": changes,
|
||||
}
|
||||
oplog.Write(config.ConfigPath(), oplog.OpsFile, e) //nolint:errcheck
|
||||
return nil
|
||||
}
|
||||
|
||||
// If --mode is provided, update the mode
|
||||
if newMode != "" {
|
||||
return updateTargetMode(cfg, name, target, newMode)
|
||||
@@ -454,9 +505,11 @@ func showTargetInfo(cfg *config.Config, name string, target config.TargetConfig)
|
||||
status := sync.CheckStatus(target.Path, cfg.Source)
|
||||
|
||||
ui.Header(fmt.Sprintf("Target: %s", name))
|
||||
fmt.Printf(" Path: %s\n", target.Path)
|
||||
fmt.Printf(" Mode: %s\n", mode)
|
||||
fmt.Printf(" Status: %s\n", status)
|
||||
fmt.Printf(" Path: %s\n", target.Path)
|
||||
fmt.Printf(" Mode: %s\n", mode)
|
||||
fmt.Printf(" Status: %s\n", status)
|
||||
fmt.Printf(" Include: %s\n", formatFilterList(target.Include))
|
||||
fmt.Printf(" Exclude: %s\n", formatFilterList(target.Exclude))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/config"
|
||||
ssync "skillshare/internal/sync"
|
||||
)
|
||||
|
||||
// filterUpdateOpts holds parsed filter modification flags.
|
||||
type filterUpdateOpts struct {
|
||||
AddInclude []string
|
||||
AddExclude []string
|
||||
RemoveInclude []string
|
||||
RemoveExclude []string
|
||||
}
|
||||
|
||||
func (o filterUpdateOpts) hasUpdates() bool {
|
||||
return len(o.AddInclude) > 0 || len(o.AddExclude) > 0 ||
|
||||
len(o.RemoveInclude) > 0 || len(o.RemoveExclude) > 0
|
||||
}
|
||||
|
||||
// parseFilterFlags extracts --add-include, --add-exclude, --remove-include,
|
||||
// --remove-exclude flags from args. Returns the parsed opts and any
|
||||
// remaining (non-filter) arguments.
|
||||
func parseFilterFlags(args []string) (filterUpdateOpts, []string, error) {
|
||||
var opts filterUpdateOpts
|
||||
var rest []string
|
||||
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch args[i] {
|
||||
case "--add-include":
|
||||
if i+1 >= len(args) {
|
||||
return opts, nil, fmt.Errorf("--add-include requires a value")
|
||||
}
|
||||
i++
|
||||
opts.AddInclude = append(opts.AddInclude, args[i])
|
||||
case "--add-exclude":
|
||||
if i+1 >= len(args) {
|
||||
return opts, nil, fmt.Errorf("--add-exclude requires a value")
|
||||
}
|
||||
i++
|
||||
opts.AddExclude = append(opts.AddExclude, args[i])
|
||||
case "--remove-include":
|
||||
if i+1 >= len(args) {
|
||||
return opts, nil, fmt.Errorf("--remove-include requires a value")
|
||||
}
|
||||
i++
|
||||
opts.RemoveInclude = append(opts.RemoveInclude, args[i])
|
||||
case "--remove-exclude":
|
||||
if i+1 >= len(args) {
|
||||
return opts, nil, fmt.Errorf("--remove-exclude requires a value")
|
||||
}
|
||||
i++
|
||||
opts.RemoveExclude = append(opts.RemoveExclude, args[i])
|
||||
default:
|
||||
rest = append(rest, args[i])
|
||||
}
|
||||
}
|
||||
|
||||
return opts, rest, nil
|
||||
}
|
||||
|
||||
// applyFilterUpdates modifies include/exclude slices according to opts.
|
||||
// It validates patterns with filepath.Match, deduplicates, and returns
|
||||
// a human-readable list of changes applied.
|
||||
func applyFilterUpdates(include, exclude *[]string, opts filterUpdateOpts) ([]string, error) {
|
||||
var changes []string
|
||||
|
||||
// Validate all patterns first
|
||||
for _, p := range opts.AddInclude {
|
||||
if _, err := filepath.Match(p, ""); err != nil {
|
||||
return nil, fmt.Errorf("invalid include pattern %q: %w", p, err)
|
||||
}
|
||||
}
|
||||
for _, p := range opts.AddExclude {
|
||||
if _, err := filepath.Match(p, ""); err != nil {
|
||||
return nil, fmt.Errorf("invalid exclude pattern %q: %w", p, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Apply additions (deduplicated)
|
||||
for _, p := range opts.AddInclude {
|
||||
if !containsPattern(*include, p) {
|
||||
*include = append(*include, p)
|
||||
changes = append(changes, fmt.Sprintf("added include: %s", p))
|
||||
}
|
||||
}
|
||||
for _, p := range opts.AddExclude {
|
||||
if !containsPattern(*exclude, p) {
|
||||
*exclude = append(*exclude, p)
|
||||
changes = append(changes, fmt.Sprintf("added exclude: %s", p))
|
||||
}
|
||||
}
|
||||
|
||||
// Apply removals
|
||||
for _, p := range opts.RemoveInclude {
|
||||
if removePattern(include, p) {
|
||||
changes = append(changes, fmt.Sprintf("removed include: %s", p))
|
||||
}
|
||||
}
|
||||
for _, p := range opts.RemoveExclude {
|
||||
if removePattern(exclude, p) {
|
||||
changes = append(changes, fmt.Sprintf("removed exclude: %s", p))
|
||||
}
|
||||
}
|
||||
|
||||
return changes, nil
|
||||
}
|
||||
|
||||
func containsPattern(patterns []string, p string) bool {
|
||||
for _, existing := range patterns {
|
||||
if existing == p {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func removePattern(patterns *[]string, p string) bool {
|
||||
for i, existing := range *patterns {
|
||||
if existing == p {
|
||||
*patterns = append((*patterns)[:i], (*patterns)[i+1:]...)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// formatFilterList formats a filter list for display, or "(none)" if empty.
|
||||
func formatFilterList(patterns []string) string {
|
||||
if len(patterns) == 0 {
|
||||
return "(none)"
|
||||
}
|
||||
return strings.Join(patterns, ", ")
|
||||
}
|
||||
|
||||
// findUnknownSkillTargets returns warnings for skills whose targets field
|
||||
// references unknown target names. Shared by check and doctor commands.
|
||||
func findUnknownSkillTargets(discovered []ssync.DiscoveredSkill) []string {
|
||||
knownNames := config.KnownTargetNames()
|
||||
knownSet := make(map[string]bool, len(knownNames))
|
||||
for _, n := range knownNames {
|
||||
knownSet[n] = true
|
||||
}
|
||||
|
||||
var warnings []string
|
||||
for _, skill := range discovered {
|
||||
if skill.Targets == nil {
|
||||
continue
|
||||
}
|
||||
for _, t := range skill.Targets {
|
||||
if !knownSet[t] {
|
||||
warnings = append(warnings, fmt.Sprintf("%s: unknown target %q", skill.RelPath, t))
|
||||
}
|
||||
}
|
||||
}
|
||||
return warnings
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseFilterFlags(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
wantOpts filterUpdateOpts
|
||||
wantRest []string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "no flags",
|
||||
args: []string{"--mode", "merge"},
|
||||
wantOpts: filterUpdateOpts{},
|
||||
wantRest: []string{"--mode", "merge"},
|
||||
},
|
||||
{
|
||||
name: "all four flags",
|
||||
args: []string{
|
||||
"--add-include", "team-*",
|
||||
"--add-exclude", "_legacy*",
|
||||
"--remove-include", "old-*",
|
||||
"--remove-exclude", "test-*",
|
||||
},
|
||||
wantOpts: filterUpdateOpts{
|
||||
AddInclude: []string{"team-*"},
|
||||
AddExclude: []string{"_legacy*"},
|
||||
RemoveInclude: []string{"old-*"},
|
||||
RemoveExclude: []string{"test-*"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "multiple values for same flag",
|
||||
args: []string{
|
||||
"--add-include", "a-*",
|
||||
"--add-include", "b-*",
|
||||
},
|
||||
wantOpts: filterUpdateOpts{
|
||||
AddInclude: []string{"a-*", "b-*"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mixed with other flags",
|
||||
args: []string{
|
||||
"--mode", "merge",
|
||||
"--add-include", "team-*",
|
||||
},
|
||||
wantOpts: filterUpdateOpts{
|
||||
AddInclude: []string{"team-*"},
|
||||
},
|
||||
wantRest: []string{"--mode", "merge"},
|
||||
},
|
||||
{
|
||||
name: "missing value for --add-include",
|
||||
args: []string{"--add-include"},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "missing value for --add-exclude",
|
||||
args: []string{"--add-exclude"},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "missing value for --remove-include",
|
||||
args: []string{"--remove-include"},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "missing value for --remove-exclude",
|
||||
args: []string{"--remove-exclude"},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
opts, rest, err := parseFilterFlags(tt.args)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
assertStringSlice(t, "AddInclude", opts.AddInclude, tt.wantOpts.AddInclude)
|
||||
assertStringSlice(t, "AddExclude", opts.AddExclude, tt.wantOpts.AddExclude)
|
||||
assertStringSlice(t, "RemoveInclude", opts.RemoveInclude, tt.wantOpts.RemoveInclude)
|
||||
assertStringSlice(t, "RemoveExclude", opts.RemoveExclude, tt.wantOpts.RemoveExclude)
|
||||
assertStringSlice(t, "rest", rest, tt.wantRest)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyFilterUpdates(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
include []string
|
||||
exclude []string
|
||||
opts filterUpdateOpts
|
||||
wantInclude []string
|
||||
wantExclude []string
|
||||
wantChanges int
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "add include",
|
||||
opts: filterUpdateOpts{
|
||||
AddInclude: []string{"team-*"},
|
||||
},
|
||||
wantInclude: []string{"team-*"},
|
||||
wantChanges: 1,
|
||||
},
|
||||
{
|
||||
name: "add exclude",
|
||||
opts: filterUpdateOpts{
|
||||
AddExclude: []string{"_legacy*"},
|
||||
},
|
||||
wantExclude: []string{"_legacy*"},
|
||||
wantChanges: 1,
|
||||
},
|
||||
{
|
||||
name: "remove include",
|
||||
include: []string{"team-*", "org-*"},
|
||||
opts: filterUpdateOpts{
|
||||
RemoveInclude: []string{"team-*"},
|
||||
},
|
||||
wantInclude: []string{"org-*"},
|
||||
wantChanges: 1,
|
||||
},
|
||||
{
|
||||
name: "remove exclude",
|
||||
exclude: []string{"_legacy*", "test-*"},
|
||||
opts: filterUpdateOpts{
|
||||
RemoveExclude: []string{"_legacy*"},
|
||||
},
|
||||
wantExclude: []string{"test-*"},
|
||||
wantChanges: 1,
|
||||
},
|
||||
{
|
||||
name: "deduplicate add",
|
||||
include: []string{"team-*"},
|
||||
opts: filterUpdateOpts{
|
||||
AddInclude: []string{"team-*"},
|
||||
},
|
||||
wantInclude: []string{"team-*"},
|
||||
wantChanges: 0,
|
||||
},
|
||||
{
|
||||
name: "remove nonexistent is no-op",
|
||||
opts: filterUpdateOpts{
|
||||
RemoveInclude: []string{"nope"},
|
||||
},
|
||||
wantChanges: 0,
|
||||
},
|
||||
{
|
||||
name: "invalid include pattern",
|
||||
opts: filterUpdateOpts{
|
||||
AddInclude: []string{"[invalid"},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "invalid exclude pattern",
|
||||
opts: filterUpdateOpts{
|
||||
AddExclude: []string{"[invalid"},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "multiple operations",
|
||||
include: []string{"old-*"},
|
||||
exclude: []string{"old-exc-*"},
|
||||
opts: filterUpdateOpts{
|
||||
AddInclude: []string{"new-*"},
|
||||
RemoveInclude: []string{"old-*"},
|
||||
AddExclude: []string{"new-exc-*"},
|
||||
RemoveExclude: []string{"old-exc-*"},
|
||||
},
|
||||
wantInclude: []string{"new-*"},
|
||||
wantExclude: []string{"new-exc-*"},
|
||||
wantChanges: 4,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
include := append([]string(nil), tt.include...)
|
||||
exclude := append([]string(nil), tt.exclude...)
|
||||
|
||||
changes, err := applyFilterUpdates(&include, &exclude, tt.opts)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if len(changes) != tt.wantChanges {
|
||||
t.Errorf("changes count = %d, want %d (changes: %v)", len(changes), tt.wantChanges, changes)
|
||||
}
|
||||
assertStringSlice(t, "include", include, tt.wantInclude)
|
||||
assertStringSlice(t, "exclude", exclude, tt.wantExclude)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterUpdateOpts_HasUpdates(t *testing.T) {
|
||||
if (filterUpdateOpts{}).hasUpdates() {
|
||||
t.Error("empty opts should not have updates")
|
||||
}
|
||||
if !(filterUpdateOpts{AddInclude: []string{"x"}}).hasUpdates() {
|
||||
t.Error("opts with AddInclude should have updates")
|
||||
}
|
||||
}
|
||||
|
||||
func assertStringSlice(t *testing.T, label string, got, want []string) {
|
||||
t.Helper()
|
||||
if len(got) == 0 && len(want) == 0 {
|
||||
return
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Errorf("%s: got %v, want %v", label, got, want)
|
||||
return
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != want[i] {
|
||||
t.Errorf("%s[%d]: got %q, want %q", label, i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,10 @@ import (
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/oplog"
|
||||
"skillshare/internal/sync"
|
||||
"skillshare/internal/ui"
|
||||
"skillshare/internal/utils"
|
||||
@@ -35,9 +37,8 @@ func targetAddProject(args []string, root string) error {
|
||||
}
|
||||
}
|
||||
|
||||
projectTargets := config.ProjectTargets()
|
||||
knownPath := ""
|
||||
if known, ok := projectTargets[name]; ok {
|
||||
if known, ok := config.LookupProjectTarget(name); ok {
|
||||
knownPath = filepath.ToSlash(known.Path)
|
||||
}
|
||||
|
||||
@@ -287,14 +288,20 @@ func targetInfoProject(name string, args []string, root string) error {
|
||||
}
|
||||
}
|
||||
|
||||
// Parse filter flags first, pass remaining to mode parsing
|
||||
filterOpts, remaining, err := parseFilterFlags(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var newMode string
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch args[i] {
|
||||
for i := 0; i < len(remaining); i++ {
|
||||
switch remaining[i] {
|
||||
case "--mode", "-m":
|
||||
if i+1 >= len(args) {
|
||||
if i+1 >= len(remaining) {
|
||||
return fmt.Errorf("--mode requires a value (merge or symlink)")
|
||||
}
|
||||
newMode = args[i+1]
|
||||
newMode = remaining[i+1]
|
||||
i++
|
||||
}
|
||||
}
|
||||
@@ -316,6 +323,34 @@ func targetInfoProject(name string, args []string, root string) error {
|
||||
return fmt.Errorf("target '%s' not found. Use 'skillshare target list' to see available targets", name)
|
||||
}
|
||||
|
||||
// Apply filter updates if any
|
||||
if filterOpts.hasUpdates() {
|
||||
start := time.Now()
|
||||
entry := &cfg.Targets[targetIdx]
|
||||
changes, fErr := applyFilterUpdates(&entry.Include, &entry.Exclude, filterOpts)
|
||||
if fErr != nil {
|
||||
return fErr
|
||||
}
|
||||
if err := cfg.Save(root); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, change := range changes {
|
||||
ui.Success("%s: %s", name, change)
|
||||
}
|
||||
if len(changes) > 0 {
|
||||
ui.Info("Run 'skillshare sync' to apply filter changes")
|
||||
}
|
||||
|
||||
e := oplog.NewEntry("target", statusFromErr(nil), time.Since(start))
|
||||
e.Args = map[string]any{
|
||||
"action": "filter",
|
||||
"name": name,
|
||||
"changes": changes,
|
||||
}
|
||||
oplog.Write(config.ProjectConfigPath(root), oplog.OpsFile, e) //nolint:errcheck
|
||||
return nil
|
||||
}
|
||||
|
||||
if newMode != "" {
|
||||
return updateTargetModeProject(cfg, targetIdx, newMode, root)
|
||||
}
|
||||
@@ -341,17 +376,20 @@ func targetInfoProject(name string, args []string, root string) error {
|
||||
}
|
||||
|
||||
ui.Header(fmt.Sprintf("Target: %s", name))
|
||||
fmt.Printf(" Path: %s\n", projectTargetDisplayPath(targetEntry))
|
||||
fmt.Printf(" Mode: %s\n", displayMode)
|
||||
fmt.Printf(" Path: %s\n", projectTargetDisplayPath(targetEntry))
|
||||
fmt.Printf(" Mode: %s\n", displayMode)
|
||||
|
||||
if mode == "symlink" {
|
||||
status := sync.CheckStatus(target.Path, sourcePath)
|
||||
fmt.Printf(" Status: %s\n", status)
|
||||
fmt.Printf(" Status: %s\n", status)
|
||||
} else {
|
||||
status, linked, local := sync.CheckStatusMerge(target.Path, sourcePath)
|
||||
fmt.Printf(" Status: %s (%d shared, %d local)\n", status, linked, local)
|
||||
fmt.Printf(" Status: %s (%d shared, %d local)\n", status, linked, local)
|
||||
}
|
||||
|
||||
fmt.Printf(" Include: %s\n", formatFilterList(targetEntry.Include))
|
||||
fmt.Printf(" Exclude: %s\n", formatFilterList(targetEntry.Exclude))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+58
-18
@@ -10,6 +10,8 @@ import (
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/server"
|
||||
"skillshare/internal/ui"
|
||||
"skillshare/internal/uidist"
|
||||
versionpkg "skillshare/internal/version"
|
||||
)
|
||||
|
||||
func cmdUI(args []string) error {
|
||||
@@ -40,6 +42,12 @@ func cmdUI(args []string) error {
|
||||
}
|
||||
case "--no-open":
|
||||
noOpen = true
|
||||
case "--clear-cache":
|
||||
if err := uidist.ClearCache(); err != nil {
|
||||
return fmt.Errorf("failed to clear UI cache: %w", err)
|
||||
}
|
||||
ui.Success("UI cache cleared.")
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unknown flag: %s", rest[i])
|
||||
}
|
||||
@@ -66,6 +74,40 @@ func cmdUI(args []string) error {
|
||||
return startGlobalUI(addr, url, noOpen)
|
||||
}
|
||||
|
||||
// ensureUIAvailable checks whether the UI is cached and downloads it if needed.
|
||||
// Returns the disk directory to serve from, or "" for dev mode (placeholder).
|
||||
func ensureUIAvailable() (string, error) {
|
||||
ver := versionpkg.Version
|
||||
|
||||
// Check cache first — works for all versions including "dev"
|
||||
// (e.g., Docker playground pre-populates cache for "dev")
|
||||
if dir, ok := uidist.IsCached(ver); ok {
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
if ver == "dev" || ver == "" {
|
||||
// Dev mode without cached UI: use placeholder, Vite serves the frontend
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// Download with spinner
|
||||
sp := ui.StartSpinner("Downloading UI assets...")
|
||||
if err := uidist.Download(ver); err != nil {
|
||||
sp.Fail("Download failed")
|
||||
fmt.Println()
|
||||
ui.Warning("Install with the full installer to get the web UI:")
|
||||
fmt.Println(" curl -fsSL https://raw.githubusercontent.com/runkids/skillshare/main/install.sh | sh")
|
||||
return "", fmt.Errorf("could not download UI assets: %w", err)
|
||||
}
|
||||
sp.Success("UI assets downloaded and cached")
|
||||
|
||||
dir, ok := uidist.IsCached(ver)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("UI assets were downloaded but cache verification failed")
|
||||
}
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
func startProjectUI(addr, url string, noOpen bool) error {
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
@@ -88,19 +130,18 @@ func startProjectUI(addr, url string, noOpen bool) error {
|
||||
Mode: "merge",
|
||||
}
|
||||
|
||||
if !server.IsUIBuilt() {
|
||||
ui.Warning("Web UI is not included in this build.")
|
||||
ui.Warning("Install with the full installer to get the web UI:")
|
||||
fmt.Println(" curl -fsSL https://raw.githubusercontent.com/runkids/skillshare/main/install.sh | sh")
|
||||
return nil
|
||||
uiDir, err := ensureUIAvailable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
srv := server.NewProject(cfg, rt.config, cwd, addr, uiDir)
|
||||
if !noOpen {
|
||||
ui.Success("Opening %s in your browser... (project mode)", url)
|
||||
openBrowser(url)
|
||||
srv.SetOnReady(func() {
|
||||
ui.Success("Opening %s in your browser... (project mode)", url)
|
||||
openBrowser(url)
|
||||
})
|
||||
}
|
||||
|
||||
srv := server.NewProject(cfg, rt.config, cwd, addr)
|
||||
return srv.Start()
|
||||
}
|
||||
|
||||
@@ -110,19 +151,18 @@ func startGlobalUI(addr, url string, noOpen bool) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if !server.IsUIBuilt() {
|
||||
ui.Warning("Web UI is not included in this build.")
|
||||
ui.Warning("Install with the full installer to get the web UI:")
|
||||
fmt.Println(" curl -fsSL https://raw.githubusercontent.com/runkids/skillshare/main/install.sh | sh")
|
||||
return nil
|
||||
uiDir, err := ensureUIAvailable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
srv := server.New(cfg, addr, uiDir)
|
||||
if !noOpen {
|
||||
ui.Success("Opening %s in your browser...", url)
|
||||
openBrowser(url)
|
||||
srv.SetOnReady(func() {
|
||||
ui.Success("Opening %s in your browser...", url)
|
||||
openBrowser(url)
|
||||
})
|
||||
}
|
||||
|
||||
srv := server.New(cfg, addr)
|
||||
return srv.Start()
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/install"
|
||||
"skillshare/internal/ui"
|
||||
"skillshare/internal/uidist"
|
||||
versionpkg "skillshare/internal/version"
|
||||
)
|
||||
|
||||
@@ -174,6 +175,16 @@ func upgradeCLIBinary(dryRun, force bool) error {
|
||||
// Clear version cache so next check fetches fresh data
|
||||
versionpkg.ClearCache()
|
||||
|
||||
// Pre-download UI assets for the new version (best-effort)
|
||||
if latestVersion != "" {
|
||||
uiSpinner := ui.StartSpinner("Downloading UI assets...")
|
||||
if err := uidist.Download(latestVersion); err != nil {
|
||||
uiSpinner.Warn("UI download skipped (run 'skillshare ui' to retry)")
|
||||
} else {
|
||||
uiSpinner.Success("UI assets cached")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,6 @@ services:
|
||||
GITHUB_TOKEN: ${SKILLSHARE_PLAYGROUND_GITHUB_TOKEN:-}
|
||||
volumes:
|
||||
- .:/workspace:ro
|
||||
- /workspace/internal/server/dist # writable overlay for go:embed (entrypoint copies UI assets here)
|
||||
- go-mod-cache:/go/pkg/mod
|
||||
- go-build-cache:/go/build-cache
|
||||
- playground-home:/sandbox-home
|
||||
@@ -81,8 +80,8 @@ services:
|
||||
- -c
|
||||
- >-
|
||||
cd /workspace &&
|
||||
go run -tags dev ./cmd/skillshare init -g --no-copy --no-git --skill 2>/dev/null;
|
||||
go run -tags dev ./cmd/skillshare ui -g --no-open --host 0.0.0.0
|
||||
go run ./cmd/skillshare init -g --no-copy --no-git --skill 2>/dev/null;
|
||||
go run ./cmd/skillshare ui -g --no-open --host 0.0.0.0
|
||||
ports:
|
||||
- "19420:19420"
|
||||
environment:
|
||||
|
||||
+2
-12
@@ -2,27 +2,17 @@
|
||||
# Usage: docker run ghcr.io/<org>/skillshare-ci audit /path/to/skills
|
||||
# Build: docker build -f docker/ci/Dockerfile -t skillshare-ci .
|
||||
|
||||
# Stage 1: Build frontend assets
|
||||
FROM node:22-bookworm-slim AS ui-builder
|
||||
RUN npm install -g pnpm@latest
|
||||
WORKDIR /ui
|
||||
COPY ui/package.json ui/pnpm-lock.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
COPY ui/ ./
|
||||
RUN pnpm run build
|
||||
|
||||
# Stage 2: Build Go binary
|
||||
# Stage 1: Build Go binary
|
||||
FROM golang:1.25.5-bookworm AS go-builder
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
COPY --from=ui-builder /ui/dist internal/server/dist/
|
||||
ARG TARGETARCH=amd64
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} \
|
||||
go build -trimpath -ldflags="-s -w" -o /skillshare ./cmd/skillshare
|
||||
|
||||
# Stage 3: Minimal CI runtime
|
||||
# Stage 2: Minimal CI runtime
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
git ca-certificates && \
|
||||
|
||||
@@ -1,27 +1,17 @@
|
||||
# Production Dockerfile — lightweight single-binary image
|
||||
# Build: docker build -f docker/production/Dockerfile -t skillshare .
|
||||
|
||||
# Stage 1: Build frontend assets
|
||||
FROM node:22-bookworm-slim AS ui-builder
|
||||
RUN npm install -g pnpm@latest
|
||||
WORKDIR /ui
|
||||
COPY ui/package.json ui/pnpm-lock.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
COPY ui/ ./
|
||||
RUN pnpm run build
|
||||
|
||||
# Stage 2: Build Go binary
|
||||
# Stage 1: Build Go binary
|
||||
FROM golang:1.25.5-bookworm AS go-builder
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
COPY --from=ui-builder /ui/dist internal/server/dist/
|
||||
ARG TARGETARCH=amd64
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} \
|
||||
go build -trimpath -ldflags="-s -w" -o /skillshare ./cmd/skillshare
|
||||
|
||||
# Stage 3: Minimal runtime
|
||||
# Stage 2: Minimal runtime
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
bash git ca-certificates curl tini && \
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Stage 1: Build frontend assets
|
||||
# Stage 1: Build frontend assets (for playground UI)
|
||||
FROM node:22-bookworm-slim AS ui-builder
|
||||
RUN npm install -g pnpm@latest
|
||||
WORKDIR /ui
|
||||
@@ -14,10 +14,9 @@ RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends bash git ca-certificates curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy pre-built frontend for go:embed at build time
|
||||
# Copy pre-built frontend for playground UI cache
|
||||
COPY --from=ui-builder /ui/dist /ui-dist
|
||||
|
||||
# Entrypoint copies /ui-dist → internal/server/dist/ when missing (fixes gitignore)
|
||||
COPY docker/sandbox/entrypoint.sh /entrypoint.sh
|
||||
RUN chmod +x /entrypoint.sh
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
#!/bin/bash
|
||||
# Docker entrypoint: ensure pre-built frontend assets are available for go:embed.
|
||||
# The host volume mount (.:/workspace) may not include internal/server/dist/
|
||||
# (gitignored), so we copy from the Docker-built /ui-dist if needed.
|
||||
if [ -d /ui-dist ] && [ ! -f internal/server/dist/index.html ]; then
|
||||
mkdir -p internal/server/dist
|
||||
cp -r /ui-dist/* internal/server/dist/
|
||||
# Docker entrypoint: populate UI cache from pre-built /ui-dist if available.
|
||||
# This allows "skillshare ui" to serve the full React SPA in the playground
|
||||
# even though the binary version is "dev" (no runtime download needed).
|
||||
if [ -d /ui-dist ] && [ -n "$HOME" ]; then
|
||||
cache_dir="$HOME/.cache/skillshare/ui/dev"
|
||||
if [ ! -f "$cache_dir/index.html" ]; then
|
||||
mkdir -p "$cache_dir"
|
||||
cp -r /ui-dist/* "$cache_dir/"
|
||||
fi
|
||||
fi
|
||||
exec "$@"
|
||||
|
||||
@@ -7,16 +7,13 @@ import (
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/config"
|
||||
)
|
||||
|
||||
// BackupDir returns the backup directory path.
|
||||
// Returns empty string if home directory cannot be determined.
|
||||
func BackupDir() string {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(home, ".config", "skillshare", "backups")
|
||||
return filepath.Join(config.DataDir(), "backups")
|
||||
}
|
||||
|
||||
// Create creates a backup of the target directory
|
||||
|
||||
@@ -127,6 +127,16 @@ func TestCopyDir_EmptyDir(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackupDir_RespectsXDGDataHome(t *testing.T) {
|
||||
t.Setenv("XDG_DATA_HOME", "/custom/data")
|
||||
|
||||
got := BackupDir()
|
||||
want := filepath.Join("/custom/data", "skillshare", "backups")
|
||||
if got != want {
|
||||
t.Errorf("BackupDir() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
func writeTestFile(t *testing.T, path, content string) {
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestLoadProject_DefaultAuditThreshold(t *testing.T) {
|
||||
t.Fatalf("mkdir project config dir: %v", err)
|
||||
}
|
||||
|
||||
raw := "targets:\n - claude-code\n"
|
||||
raw := "targets:\n - claude\n"
|
||||
if err := os.WriteFile(cfgPath, []byte(raw), 0644); err != nil {
|
||||
t.Fatalf("write project config: %v", err)
|
||||
}
|
||||
@@ -73,7 +73,7 @@ func TestLoadProject_InvalidAuditThreshold(t *testing.T) {
|
||||
t.Fatalf("mkdir project config dir: %v", err)
|
||||
}
|
||||
|
||||
raw := "targets:\n - claude-code\naudit:\n block_threshold: urgent\n"
|
||||
raw := "targets:\n - claude\naudit:\n block_threshold: urgent\n"
|
||||
if err := os.WriteFile(cfgPath, []byte(raw), 0644); err != nil {
|
||||
t.Fatalf("write project config: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBaseDir_DefaultFallback(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", "")
|
||||
home, _ := os.UserHomeDir()
|
||||
|
||||
got := BaseDir()
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
winDir, _ := os.UserConfigDir()
|
||||
want := filepath.Join(winDir, "skillshare")
|
||||
if got != want {
|
||||
t.Errorf("BaseDir() = %q, want %q", got, want)
|
||||
}
|
||||
} else {
|
||||
want := filepath.Join(home, ".config", "skillshare")
|
||||
if got != want {
|
||||
t.Errorf("BaseDir() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseDir_RespectsXDGConfigHome(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", "/custom/config")
|
||||
|
||||
got := BaseDir()
|
||||
want := filepath.Join("/custom/config", "skillshare")
|
||||
if got != want {
|
||||
t.Errorf("BaseDir() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigPath_RespectsXDGConfigHome(t *testing.T) {
|
||||
t.Setenv("SKILLSHARE_CONFIG", "")
|
||||
t.Setenv("XDG_CONFIG_HOME", "/custom/config")
|
||||
|
||||
got := ConfigPath()
|
||||
want := filepath.Join("/custom/config", "skillshare", "config.yaml")
|
||||
if got != want {
|
||||
t.Errorf("ConfigPath() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigPath_SKILLSHARECONFIGTakesPriority(t *testing.T) {
|
||||
t.Setenv("SKILLSHARE_CONFIG", "/override/config.yaml")
|
||||
t.Setenv("XDG_CONFIG_HOME", "/custom/config")
|
||||
|
||||
got := ConfigPath()
|
||||
want := "/override/config.yaml"
|
||||
if got != want {
|
||||
t.Errorf("ConfigPath() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -48,14 +49,85 @@ type Config struct {
|
||||
|
||||
const defaultAuditBlockThreshold = "CRITICAL"
|
||||
|
||||
// BaseDir returns the skillshare data root directory.
|
||||
// Priority:
|
||||
// 1. $XDG_CONFIG_HOME/skillshare (any platform, if set)
|
||||
// 2. %AppData%/skillshare (Windows only, via os.UserConfigDir())
|
||||
// 3. ~/.config/skillshare (Linux, macOS, Windows fallback)
|
||||
func BaseDir() string {
|
||||
if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" {
|
||||
return filepath.Join(xdg, "skillshare")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
if dir, err := os.UserConfigDir(); err == nil {
|
||||
return filepath.Join(dir, "skillshare")
|
||||
}
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, ".config", "skillshare")
|
||||
}
|
||||
|
||||
// DataDir returns the data directory (XDG_DATA_HOME).
|
||||
// Priority:
|
||||
// 1. $XDG_DATA_HOME/skillshare (any platform, if set)
|
||||
// 2. %AppData%/skillshare (Windows only, via os.UserConfigDir())
|
||||
// 3. ~/.local/share/skillshare (Linux, macOS)
|
||||
func DataDir() string {
|
||||
if xdg := os.Getenv("XDG_DATA_HOME"); xdg != "" {
|
||||
return filepath.Join(xdg, "skillshare")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
if dir, err := os.UserConfigDir(); err == nil {
|
||||
return filepath.Join(dir, "skillshare")
|
||||
}
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, ".local", "share", "skillshare")
|
||||
}
|
||||
|
||||
// StateDir returns the state directory (XDG_STATE_HOME).
|
||||
// Priority:
|
||||
// 1. $XDG_STATE_HOME/skillshare (any platform, if set)
|
||||
// 2. %AppData%/skillshare (Windows only, via os.UserConfigDir())
|
||||
// 3. ~/.local/state/skillshare (Linux, macOS)
|
||||
func StateDir() string {
|
||||
if xdg := os.Getenv("XDG_STATE_HOME"); xdg != "" {
|
||||
return filepath.Join(xdg, "skillshare")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
if dir, err := os.UserConfigDir(); err == nil {
|
||||
return filepath.Join(dir, "skillshare")
|
||||
}
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, ".local", "state", "skillshare")
|
||||
}
|
||||
|
||||
// CacheDir returns the cache directory (XDG_CACHE_HOME).
|
||||
// Priority:
|
||||
// 1. $XDG_CACHE_HOME/skillshare (any platform, if set)
|
||||
// 2. %AppData%/skillshare (Windows only, via os.UserConfigDir())
|
||||
// 3. ~/.cache/skillshare (Linux, macOS)
|
||||
func CacheDir() string {
|
||||
if xdg := os.Getenv("XDG_CACHE_HOME"); xdg != "" {
|
||||
return filepath.Join(xdg, "skillshare")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
if dir, err := os.UserConfigDir(); err == nil {
|
||||
return filepath.Join(dir, "skillshare")
|
||||
}
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, ".cache", "skillshare")
|
||||
}
|
||||
|
||||
// ConfigPath returns the config file path, respecting SKILLSHARE_CONFIG env var
|
||||
func ConfigPath() string {
|
||||
// Allow override for testing
|
||||
if envPath := os.Getenv("SKILLSHARE_CONFIG"); envPath != "" {
|
||||
return envPath
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, ".config", "skillshare", "config.yaml")
|
||||
return filepath.Join(BaseDir(), "config.yaml")
|
||||
}
|
||||
|
||||
// Load reads the config from the default location
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDataDir_DefaultFallback(t *testing.T) {
|
||||
t.Setenv("XDG_DATA_HOME", "")
|
||||
home, _ := os.UserHomeDir()
|
||||
|
||||
got := DataDir()
|
||||
want := filepath.Join(home, ".local", "share", "skillshare")
|
||||
if got != want {
|
||||
t.Errorf("DataDir() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDataDir_RespectsXDGDataHome(t *testing.T) {
|
||||
t.Setenv("XDG_DATA_HOME", "/custom/data")
|
||||
|
||||
got := DataDir()
|
||||
want := filepath.Join("/custom/data", "skillshare")
|
||||
if got != want {
|
||||
t.Errorf("DataDir() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateDir_DefaultFallback(t *testing.T) {
|
||||
t.Setenv("XDG_STATE_HOME", "")
|
||||
home, _ := os.UserHomeDir()
|
||||
|
||||
got := StateDir()
|
||||
want := filepath.Join(home, ".local", "state", "skillshare")
|
||||
if got != want {
|
||||
t.Errorf("StateDir() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateDir_RespectsXDGStateHome(t *testing.T) {
|
||||
t.Setenv("XDG_STATE_HOME", "/custom/state")
|
||||
|
||||
got := StateDir()
|
||||
want := filepath.Join("/custom/state", "skillshare")
|
||||
if got != want {
|
||||
t.Errorf("StateDir() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/utils"
|
||||
)
|
||||
|
||||
type MigrationStatus string
|
||||
|
||||
const (
|
||||
MigrationMoved MigrationStatus = "moved"
|
||||
MigrationSkippedNoSource MigrationStatus = "skipped_no_source"
|
||||
MigrationSkippedNoChange MigrationStatus = "skipped_no_change"
|
||||
MigrationSkippedDestinationExists MigrationStatus = "skipped_destination_exists"
|
||||
MigrationSkippedSamePath MigrationStatus = "skipped_same_path"
|
||||
MigrationFailed MigrationStatus = "failed"
|
||||
)
|
||||
|
||||
type MigrationResult struct {
|
||||
From string
|
||||
To string
|
||||
Status MigrationStatus
|
||||
Err error
|
||||
}
|
||||
|
||||
// MigrateWindowsLegacyDir moves the entire ~/.config/skillshare directory to
|
||||
// %AppData%\skillshare on Windows. This handles upgrades from pre-v0.13.0 where
|
||||
// Windows incorrectly used the Unix-style ~/.config/ path.
|
||||
// No-op on non-Windows platforms or if legacy dir doesn't exist.
|
||||
func MigrateWindowsLegacyDir() []MigrationResult {
|
||||
if runtime.GOOS != "windows" {
|
||||
return nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return []MigrationResult{{
|
||||
Status: MigrationFailed,
|
||||
Err: fmt.Errorf("resolve user home: %w", err),
|
||||
}}
|
||||
}
|
||||
oldDir := filepath.Join(home, ".config", "skillshare")
|
||||
newDir := BaseDir() // %AppData%\skillshare on Windows
|
||||
if oldDir == newDir {
|
||||
return []MigrationResult{{
|
||||
From: oldDir,
|
||||
To: newDir,
|
||||
Status: MigrationSkippedSamePath,
|
||||
}} // XDG_CONFIG_HOME points to ~/.config, no migration needed
|
||||
}
|
||||
dirResult := migrateDir(oldDir, newDir)
|
||||
results := []MigrationResult{dirResult}
|
||||
|
||||
// Keep config.yaml source in sync after legacy dir move.
|
||||
if dirResult.Status == MigrationMoved {
|
||||
results = append(results, migrateConfigSourcePath(oldDir, newDir))
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// MigrateXDGDirs moves backups/trash/logs from legacy config dir to proper XDG dirs.
|
||||
// Called once at startup. No-op if already migrated or no legacy data exists.
|
||||
func MigrateXDGDirs() []MigrationResult {
|
||||
base := BaseDir()
|
||||
moves := []struct{ old, new string }{
|
||||
{filepath.Join(base, "backups"), filepath.Join(DataDir(), "backups")},
|
||||
{filepath.Join(base, "trash"), filepath.Join(DataDir(), "trash")},
|
||||
{filepath.Join(base, "logs"), filepath.Join(StateDir(), "logs")},
|
||||
}
|
||||
results := make([]MigrationResult, 0, len(moves))
|
||||
for _, m := range moves {
|
||||
if m.old == m.new {
|
||||
results = append(results, MigrationResult{
|
||||
From: m.old,
|
||||
To: m.new,
|
||||
Status: MigrationSkippedSamePath,
|
||||
})
|
||||
continue
|
||||
}
|
||||
results = append(results, migrateDir(m.old, m.new))
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
func migrateDir(oldPath, newPath string) MigrationResult {
|
||||
result := MigrationResult{From: oldPath, To: newPath}
|
||||
if _, err := os.Stat(oldPath); os.IsNotExist(err) {
|
||||
result.Status = MigrationSkippedNoSource
|
||||
return result // nothing to migrate
|
||||
}
|
||||
if _, err := os.Stat(newPath); err == nil {
|
||||
result.Status = MigrationSkippedDestinationExists
|
||||
return result // destination already exists
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(newPath), 0755); err != nil {
|
||||
result.Status = MigrationFailed
|
||||
result.Err = fmt.Errorf("create destination parent dir: %w", err)
|
||||
return result
|
||||
}
|
||||
if err := os.Rename(oldPath, newPath); err != nil {
|
||||
result.Status = MigrationFailed
|
||||
result.Err = fmt.Errorf("move %s -> %s: %w", oldPath, newPath, err)
|
||||
return result
|
||||
}
|
||||
result.Status = MigrationMoved
|
||||
return result
|
||||
}
|
||||
|
||||
func migrateConfigSourcePath(oldRoot, newRoot string) MigrationResult {
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
return MigrationResult{
|
||||
From: ConfigPath(),
|
||||
To: ConfigPath(),
|
||||
Status: MigrationFailed,
|
||||
Err: fmt.Errorf("load config for source migration: %w", err),
|
||||
}
|
||||
}
|
||||
|
||||
oldSource := cfg.Source
|
||||
newSource, changed := remapPathPrefix(oldSource, oldRoot, newRoot)
|
||||
if !changed {
|
||||
return MigrationResult{
|
||||
From: oldSource,
|
||||
To: oldSource,
|
||||
Status: MigrationSkippedNoChange,
|
||||
}
|
||||
}
|
||||
|
||||
cfg.Source = newSource
|
||||
if err := cfg.Save(); err != nil {
|
||||
return MigrationResult{
|
||||
From: oldSource,
|
||||
To: newSource,
|
||||
Status: MigrationFailed,
|
||||
Err: fmt.Errorf("save updated config source: %w", err),
|
||||
}
|
||||
}
|
||||
|
||||
return MigrationResult{
|
||||
From: oldSource,
|
||||
To: newSource,
|
||||
Status: MigrationMoved,
|
||||
}
|
||||
}
|
||||
|
||||
func remapPathPrefix(path, oldRoot, newRoot string) (string, bool) {
|
||||
cleanPath := filepath.Clean(path)
|
||||
cleanOld := filepath.Clean(oldRoot)
|
||||
cleanNew := filepath.Clean(newRoot)
|
||||
|
||||
if utils.PathsEqual(cleanPath, cleanOld) {
|
||||
return cleanNew, true
|
||||
}
|
||||
|
||||
oldPrefix := cleanOld + string(os.PathSeparator)
|
||||
if !utils.PathHasPrefix(cleanPath, oldPrefix) {
|
||||
return cleanPath, false
|
||||
}
|
||||
|
||||
rel, err := filepath.Rel(cleanOld, cleanPath)
|
||||
if err != nil {
|
||||
return cleanPath, false
|
||||
}
|
||||
if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
|
||||
return cleanPath, false
|
||||
}
|
||||
|
||||
return filepath.Join(cleanNew, rel), true
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMigrateXDGDirs_MovesLegacyDirs(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
configHome := filepath.Join(tmp, "config")
|
||||
dataHome := filepath.Join(tmp, "data")
|
||||
stateHome := filepath.Join(tmp, "state")
|
||||
|
||||
t.Setenv("XDG_CONFIG_HOME", configHome)
|
||||
t.Setenv("XDG_DATA_HOME", dataHome)
|
||||
t.Setenv("XDG_STATE_HOME", stateHome)
|
||||
|
||||
// Create legacy directories with content
|
||||
legacyBackups := filepath.Join(configHome, "skillshare", "backups")
|
||||
legacyTrash := filepath.Join(configHome, "skillshare", "trash")
|
||||
legacyLogs := filepath.Join(configHome, "skillshare", "logs")
|
||||
|
||||
os.MkdirAll(legacyBackups, 0755)
|
||||
os.WriteFile(filepath.Join(legacyBackups, "backup1.tar"), []byte("data"), 0644)
|
||||
|
||||
os.MkdirAll(legacyTrash, 0755)
|
||||
os.WriteFile(filepath.Join(legacyTrash, "trashed"), []byte("data"), 0644)
|
||||
|
||||
os.MkdirAll(legacyLogs, 0755)
|
||||
os.WriteFile(filepath.Join(legacyLogs, "ops.log"), []byte("data"), 0644)
|
||||
|
||||
results := MigrateXDGDirs()
|
||||
|
||||
// Verify moved to new locations
|
||||
newBackups := filepath.Join(dataHome, "skillshare", "backups")
|
||||
newTrash := filepath.Join(dataHome, "skillshare", "trash")
|
||||
newLogs := filepath.Join(stateHome, "skillshare", "logs")
|
||||
|
||||
if _, err := os.Stat(filepath.Join(newBackups, "backup1.tar")); err != nil {
|
||||
t.Errorf("backups not migrated: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(newTrash, "trashed")); err != nil {
|
||||
t.Errorf("trash not migrated: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(newLogs, "ops.log")); err != nil {
|
||||
t.Errorf("logs not migrated: %v", err)
|
||||
}
|
||||
|
||||
// Verify legacy dirs removed
|
||||
if _, err := os.Stat(legacyBackups); !os.IsNotExist(err) {
|
||||
t.Error("legacy backups dir should be removed after migration")
|
||||
}
|
||||
if _, err := os.Stat(legacyTrash); !os.IsNotExist(err) {
|
||||
t.Error("legacy trash dir should be removed after migration")
|
||||
}
|
||||
if _, err := os.Stat(legacyLogs); !os.IsNotExist(err) {
|
||||
t.Error("legacy logs dir should be removed after migration")
|
||||
}
|
||||
|
||||
assertNoMigrationFailures(t, results)
|
||||
}
|
||||
|
||||
func TestMigrateXDGDirs_NoopWhenNoLegacyDirs(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(tmp, "config"))
|
||||
t.Setenv("XDG_DATA_HOME", filepath.Join(tmp, "data"))
|
||||
t.Setenv("XDG_STATE_HOME", filepath.Join(tmp, "state"))
|
||||
|
||||
// No legacy dirs exist — should not panic or error
|
||||
results := MigrateXDGDirs()
|
||||
assertNoMigrationFailures(t, results)
|
||||
}
|
||||
|
||||
func TestMigrateXDGDirs_SkipsWhenDestExists(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
configHome := filepath.Join(tmp, "config")
|
||||
dataHome := filepath.Join(tmp, "data")
|
||||
stateHome := filepath.Join(tmp, "state")
|
||||
|
||||
t.Setenv("XDG_CONFIG_HOME", configHome)
|
||||
t.Setenv("XDG_DATA_HOME", dataHome)
|
||||
t.Setenv("XDG_STATE_HOME", stateHome)
|
||||
|
||||
// Create both legacy and new backups dir
|
||||
legacyBackups := filepath.Join(configHome, "skillshare", "backups")
|
||||
newBackups := filepath.Join(dataHome, "skillshare", "backups")
|
||||
|
||||
os.MkdirAll(legacyBackups, 0755)
|
||||
os.WriteFile(filepath.Join(legacyBackups, "old.tar"), []byte("old"), 0644)
|
||||
|
||||
os.MkdirAll(newBackups, 0755)
|
||||
os.WriteFile(filepath.Join(newBackups, "new.tar"), []byte("new"), 0644)
|
||||
|
||||
results := MigrateXDGDirs()
|
||||
|
||||
// New dir should be untouched
|
||||
data, err := os.ReadFile(filepath.Join(newBackups, "new.tar"))
|
||||
if err != nil || string(data) != "new" {
|
||||
t.Error("existing new dir should not be overwritten")
|
||||
}
|
||||
|
||||
// Legacy dir should still exist (not removed since dest already existed)
|
||||
if _, err := os.Stat(legacyBackups); os.IsNotExist(err) {
|
||||
t.Error("legacy dir should remain when dest already exists")
|
||||
}
|
||||
|
||||
result := findMigrationResultByFrom(results, legacyBackups)
|
||||
if result == nil {
|
||||
t.Fatalf("expected migration result for %s", legacyBackups)
|
||||
}
|
||||
if result.Status != MigrationSkippedDestinationExists {
|
||||
t.Fatalf("unexpected migration status for backup dir: got %q, want %q", result.Status, MigrationSkippedDestinationExists)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMigrateWindowsLegacyDir_UsesMigrateDir tests the underlying migrateDir
|
||||
// logic that MigrateWindowsLegacyDir delegates to. We can't test the actual
|
||||
// function on non-Windows (it early-returns), so we test the migration path directly.
|
||||
func TestMigrateWindowsLegacyDir_MigrationPath(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
oldDir := filepath.Join(tmp, ".config", "skillshare")
|
||||
newDir := filepath.Join(tmp, "AppData", "skillshare")
|
||||
|
||||
// Create legacy dir with config and skills
|
||||
os.MkdirAll(filepath.Join(oldDir, "skills"), 0755)
|
||||
os.WriteFile(filepath.Join(oldDir, "config.yaml"), []byte("source: skills"), 0644)
|
||||
os.WriteFile(filepath.Join(oldDir, "skills", "SKILL.md"), []byte("# skill"), 0644)
|
||||
|
||||
// Simulate what MigrateWindowsLegacyDir does: migrateDir(old, new)
|
||||
result := migrateDir(oldDir, newDir)
|
||||
|
||||
// Verify moved
|
||||
data, err := os.ReadFile(filepath.Join(newDir, "config.yaml"))
|
||||
if err != nil || string(data) != "source: skills" {
|
||||
t.Errorf("config.yaml not migrated: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(newDir, "skills", "SKILL.md")); err != nil {
|
||||
t.Errorf("skills dir not migrated: %v", err)
|
||||
}
|
||||
|
||||
// Verify old dir removed
|
||||
if _, err := os.Stat(oldDir); !os.IsNotExist(err) {
|
||||
t.Error("legacy dir should be removed after migration")
|
||||
}
|
||||
if result.Status != MigrationMoved {
|
||||
t.Fatalf("unexpected migration status: got %q, want %q", result.Status, MigrationMoved)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateWindowsLegacyDir_SkipsOnNonWindows(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("this test verifies non-Windows no-op behavior")
|
||||
}
|
||||
// Should not panic or do anything on non-Windows
|
||||
results := MigrateWindowsLegacyDir()
|
||||
assertNoMigrationFailures(t, results)
|
||||
}
|
||||
|
||||
func TestMigrateWindowsLegacyDir_SkipsWhenDestExists(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
oldDir := filepath.Join(tmp, ".config", "skillshare")
|
||||
newDir := filepath.Join(tmp, "AppData", "skillshare")
|
||||
|
||||
os.MkdirAll(oldDir, 0755)
|
||||
os.WriteFile(filepath.Join(oldDir, "config.yaml"), []byte("old"), 0644)
|
||||
|
||||
os.MkdirAll(newDir, 0755)
|
||||
os.WriteFile(filepath.Join(newDir, "config.yaml"), []byte("new"), 0644)
|
||||
|
||||
result := migrateDir(oldDir, newDir)
|
||||
|
||||
// New dir untouched
|
||||
data, _ := os.ReadFile(filepath.Join(newDir, "config.yaml"))
|
||||
if string(data) != "new" {
|
||||
t.Error("existing dest should not be overwritten")
|
||||
}
|
||||
|
||||
// Old dir still exists
|
||||
if _, err := os.Stat(oldDir); os.IsNotExist(err) {
|
||||
t.Error("legacy dir should remain when dest already exists")
|
||||
}
|
||||
if result.Status != MigrationSkippedDestinationExists {
|
||||
t.Fatalf("unexpected migration status: got %q, want %q", result.Status, MigrationSkippedDestinationExists)
|
||||
}
|
||||
}
|
||||
|
||||
func findMigrationResultByFrom(results []MigrationResult, from string) *MigrationResult {
|
||||
for i := range results {
|
||||
if results[i].From == from {
|
||||
return &results[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func assertNoMigrationFailures(t *testing.T, results []MigrationResult) {
|
||||
t.Helper()
|
||||
for _, r := range results {
|
||||
if r.Status == MigrationFailed {
|
||||
t.Fatalf("unexpected migration failure for %s -> %s: %v", r.From, r.To, r.Err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateConfigSourcePath_RewritesLegacySource(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
cfgPath := filepath.Join(tmp, "config.yaml")
|
||||
oldRoot := filepath.Join(tmp, "old", "skillshare")
|
||||
newRoot := filepath.Join(tmp, "new", "skillshare")
|
||||
oldSource := filepath.Join(oldRoot, "skills")
|
||||
newSource := filepath.Join(newRoot, "skills")
|
||||
|
||||
t.Setenv("SKILLSHARE_CONFIG", cfgPath)
|
||||
|
||||
cfg := &Config{
|
||||
Source: oldSource,
|
||||
Targets: map[string]TargetConfig{},
|
||||
}
|
||||
if err := cfg.Save(); err != nil {
|
||||
t.Fatalf("save config: %v", err)
|
||||
}
|
||||
|
||||
result := migrateConfigSourcePath(oldRoot, newRoot)
|
||||
if result.Status != MigrationMoved {
|
||||
t.Fatalf("unexpected migration status: got %q, want %q", result.Status, MigrationMoved)
|
||||
}
|
||||
if result.From != oldSource || result.To != newSource {
|
||||
t.Fatalf("unexpected migration result: from=%q to=%q", result.From, result.To)
|
||||
}
|
||||
|
||||
updated, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("reload config: %v", err)
|
||||
}
|
||||
if updated.Source != newSource {
|
||||
t.Fatalf("source not rewritten: got %q, want %q", updated.Source, newSource)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateConfigSourcePath_SkipsWhenUnrelatedSource(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
cfgPath := filepath.Join(tmp, "config.yaml")
|
||||
oldRoot := filepath.Join(tmp, "old", "skillshare")
|
||||
newRoot := filepath.Join(tmp, "new", "skillshare")
|
||||
customSource := filepath.Join(tmp, "custom", "skills")
|
||||
|
||||
t.Setenv("SKILLSHARE_CONFIG", cfgPath)
|
||||
|
||||
cfg := &Config{
|
||||
Source: customSource,
|
||||
Targets: map[string]TargetConfig{},
|
||||
}
|
||||
if err := cfg.Save(); err != nil {
|
||||
t.Fatalf("save config: %v", err)
|
||||
}
|
||||
|
||||
result := migrateConfigSourcePath(oldRoot, newRoot)
|
||||
if result.Status != MigrationSkippedNoChange {
|
||||
t.Fatalf("unexpected migration status: got %q, want %q", result.Status, MigrationSkippedNoChange)
|
||||
}
|
||||
|
||||
updated, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("reload config: %v", err)
|
||||
}
|
||||
if updated.Source != customSource {
|
||||
t.Fatalf("source should remain unchanged: got %q, want %q", updated.Source, customSource)
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
// ProjectTargetEntry supports both string and object forms in YAML.
|
||||
// String: "claude-code"
|
||||
// String: "claude"
|
||||
// Object: { name: "my-custom-ide", path: ".my-ide/skills/" }
|
||||
type ProjectTargetEntry struct {
|
||||
Name string
|
||||
|
||||
@@ -23,7 +23,7 @@ func TestReconcileProjectSkills_AddsNewSkill(t *testing.T) {
|
||||
}
|
||||
|
||||
cfg := &ProjectConfig{
|
||||
Targets: []ProjectTargetEntry{{Name: "claude-code"}},
|
||||
Targets: []ProjectTargetEntry{{Name: "claude"}},
|
||||
}
|
||||
|
||||
if err := ReconcileProjectSkills(root, cfg, skillsDir); err != nil {
|
||||
@@ -56,7 +56,7 @@ func TestReconcileProjectSkills_UpdatesExistingSource(t *testing.T) {
|
||||
}
|
||||
|
||||
cfg := &ProjectConfig{
|
||||
Targets: []ProjectTargetEntry{{Name: "claude-code"}},
|
||||
Targets: []ProjectTargetEntry{{Name: "claude"}},
|
||||
Skills: []ProjectSkill{{Name: "my-skill", Source: "github.com/user/repo-v1"}},
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ func TestReconcileProjectSkills_SkipsNoMeta(t *testing.T) {
|
||||
}
|
||||
|
||||
cfg := &ProjectConfig{
|
||||
Targets: []ProjectTargetEntry{{Name: "claude-code"}},
|
||||
Targets: []ProjectTargetEntry{{Name: "claude"}},
|
||||
}
|
||||
|
||||
if err := ReconcileProjectSkills(root, cfg, skillsDir); err != nil {
|
||||
|
||||
@@ -11,10 +11,11 @@ import (
|
||||
)
|
||||
|
||||
type targetSpec struct {
|
||||
GlobalName string `yaml:"global_name"`
|
||||
ProjectName string `yaml:"project_name"`
|
||||
GlobalPath string `yaml:"global_path"`
|
||||
ProjectPath string `yaml:"project_path"`
|
||||
GlobalName string `yaml:"global_name"`
|
||||
ProjectName string `yaml:"project_name"`
|
||||
GlobalPath string `yaml:"global_path"`
|
||||
ProjectPath string `yaml:"project_path"`
|
||||
Aliases []string `yaml:"aliases,omitempty"` // Deprecated: backward compat for old project_name values. Remove once safe.
|
||||
}
|
||||
|
||||
type targetsFile struct {
|
||||
@@ -82,10 +83,26 @@ func ProjectTargets() map[string]TargetConfig {
|
||||
}
|
||||
|
||||
// LookupProjectTarget returns the known project target config for a name.
|
||||
// It first checks canonical project names, then falls back to aliases.
|
||||
func LookupProjectTarget(name string) (TargetConfig, bool) {
|
||||
targets := ProjectTargets()
|
||||
target, ok := targets[name]
|
||||
return target, ok
|
||||
if target, ok := targets[name]; ok {
|
||||
return target, true
|
||||
}
|
||||
|
||||
// Fallback: check aliases (backward compat — remove once safe)
|
||||
specs, err := loadTargetSpecs()
|
||||
if err != nil {
|
||||
return TargetConfig{}, false
|
||||
}
|
||||
for _, spec := range specs {
|
||||
for _, alias := range spec.Aliases {
|
||||
if alias == name && spec.ProjectName != "" && spec.ProjectPath != "" {
|
||||
return targets[spec.ProjectName], true
|
||||
}
|
||||
}
|
||||
}
|
||||
return TargetConfig{}, false
|
||||
}
|
||||
|
||||
// LookupGlobalTarget returns the known global target config for a name.
|
||||
@@ -164,6 +181,64 @@ func GroupedProjectTargets() []GroupedProjectTarget {
|
||||
return result
|
||||
}
|
||||
|
||||
// MatchesTargetName checks whether a skill-declared target name matches a
|
||||
// config target name. It handles alias matching (e.g. "claude" matches
|
||||
// the alias "claude-code") by looking up the target spec registry.
|
||||
func MatchesTargetName(skillTarget, configTarget string) bool {
|
||||
if skillTarget == configTarget {
|
||||
return true
|
||||
}
|
||||
|
||||
specs, err := loadTargetSpecs()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, spec := range specs {
|
||||
allNames := make([]string, 0, 2+len(spec.Aliases))
|
||||
allNames = append(allNames, spec.GlobalName, spec.ProjectName)
|
||||
allNames = append(allNames, spec.Aliases...) // backward compat — remove once safe
|
||||
hasSkill := false
|
||||
hasConfig := false
|
||||
for _, n := range allNames {
|
||||
if n == skillTarget {
|
||||
hasSkill = true
|
||||
}
|
||||
if n == configTarget {
|
||||
hasConfig = true
|
||||
}
|
||||
}
|
||||
if hasSkill && hasConfig {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// KnownTargetNames returns all known target names (both global and project).
|
||||
func KnownTargetNames() []string {
|
||||
specs, err := loadTargetSpecs()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
seen := make(map[string]bool)
|
||||
var names []string
|
||||
for _, spec := range specs {
|
||||
candidates := make([]string, 0, 2+len(spec.Aliases))
|
||||
candidates = append(candidates, spec.GlobalName, spec.ProjectName)
|
||||
candidates = append(candidates, spec.Aliases...) // backward compat — remove once safe
|
||||
for _, n := range candidates {
|
||||
if n != "" && !seen[n] {
|
||||
seen[n] = true
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func normalizeTargetPath(path string) string {
|
||||
if path == "" {
|
||||
return path
|
||||
|
||||
@@ -24,9 +24,10 @@ targets:
|
||||
global_path: "~/.bob/skills"
|
||||
project_path: ".bob/skills"
|
||||
- global_name: claude
|
||||
project_name: claude-code
|
||||
project_name: claude
|
||||
global_path: "~/.claude/skills"
|
||||
project_path: ".claude/skills"
|
||||
aliases: [claude-code]
|
||||
- global_name: cline
|
||||
project_name: cline
|
||||
global_path: "~/.cline/skills"
|
||||
@@ -44,9 +45,10 @@ targets:
|
||||
global_path: "~/.codex/skills"
|
||||
project_path: ".agents/skills"
|
||||
- global_name: commandcode
|
||||
project_name: command-code
|
||||
project_name: commandcode
|
||||
global_path: "~/.commandcode/skills"
|
||||
project_path: ".commandcode/skills"
|
||||
aliases: [command-code]
|
||||
- global_name: continue
|
||||
project_name: continue
|
||||
global_path: "~/.continue/skills"
|
||||
@@ -56,9 +58,10 @@ targets:
|
||||
global_path: "~/.snowflake/cortex/skills"
|
||||
project_path: ".cortex/skills"
|
||||
- global_name: copilot
|
||||
project_name: github-copilot
|
||||
project_name: copilot
|
||||
global_path: "~/.copilot/skills"
|
||||
project_path: ".github/skills"
|
||||
aliases: [github-copilot]
|
||||
- global_name: crush
|
||||
project_name: crush
|
||||
global_path: "~/.config/crush/skills"
|
||||
@@ -68,41 +71,47 @@ targets:
|
||||
global_path: "~/.cursor/skills"
|
||||
project_path: ".cursor/skills"
|
||||
- global_name: deepagents
|
||||
project_name: deep-agents
|
||||
project_name: deepagents
|
||||
global_path: "~/.deepagents/agent/skills"
|
||||
project_path: ".deepagents/skills"
|
||||
aliases: [deep-agents]
|
||||
- global_name: droid
|
||||
project_name: droid
|
||||
global_path: "~/.factory/skills"
|
||||
project_path: ".factory/skills"
|
||||
- global_name: gemini
|
||||
project_name: gemini-cli
|
||||
project_name: gemini
|
||||
global_path: "~/.gemini/skills"
|
||||
project_path: ".gemini/skills"
|
||||
aliases: [gemini-cli]
|
||||
- global_name: goose
|
||||
project_name: goose
|
||||
global_path: "~/.config/goose/skills"
|
||||
project_path: ".agents/skills"
|
||||
- global_name: iflow
|
||||
project_name: iflow-cli
|
||||
project_name: iflow
|
||||
global_path: "~/.iflow/skills"
|
||||
project_path: ".iflow/skills"
|
||||
aliases: [iflow-cli]
|
||||
- global_name: junie
|
||||
project_name: junie
|
||||
global_path: "~/.junie/skills"
|
||||
project_path: ".junie/skills"
|
||||
- global_name: kilocode
|
||||
project_name: kilo
|
||||
project_name: kilocode
|
||||
global_path: "~/.kilocode/skills"
|
||||
project_path: ".kilocode/skills"
|
||||
aliases: [kilo]
|
||||
- global_name: kimi
|
||||
project_name: kimi-cli
|
||||
project_name: kimi
|
||||
global_path: "~/.kimi/skills"
|
||||
project_path: ".agents/skills"
|
||||
aliases: [kimi-cli]
|
||||
- global_name: kiro
|
||||
project_name: kiro-cli
|
||||
project_name: kiro
|
||||
global_path: "~/.kiro/skills"
|
||||
project_path: ".kiro/skills"
|
||||
aliases: [kiro-cli]
|
||||
- global_name: kode
|
||||
project_name: kode
|
||||
global_path: "~/.kode/skills"
|
||||
@@ -150,9 +159,10 @@ targets:
|
||||
global_path: "~/.qoder/skills"
|
||||
project_path: ".qoder/skills"
|
||||
- global_name: qwen
|
||||
project_name: qwen-code
|
||||
project_name: qwen
|
||||
global_path: "~/.qwen/skills"
|
||||
project_path: ".qwen/skills"
|
||||
aliases: [qwen-code]
|
||||
- global_name: roo
|
||||
project_name: roo
|
||||
global_path: "~/.roo/skills"
|
||||
@@ -166,9 +176,10 @@ targets:
|
||||
global_path: "~/.trae-cn/skills"
|
||||
project_path: ".trae/skills"
|
||||
- global_name: vibe
|
||||
project_name: mistral-vibe
|
||||
project_name: vibe
|
||||
global_path: "~/.vibe/skills"
|
||||
project_path: ".vibe/skills"
|
||||
aliases: [mistral-vibe]
|
||||
- global_name: windsurf
|
||||
project_name: windsurf
|
||||
global_path: "~/.codeium/windsurf/skills"
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMatchesTargetName_SameName(t *testing.T) {
|
||||
if !MatchesTargetName("claude", "claude") {
|
||||
t.Error("identical names should match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesTargetName_CrossMode(t *testing.T) {
|
||||
// "claude" is global_name/project_name, "claude-code" is an alias for the same spec
|
||||
if !MatchesTargetName("claude", "claude-code") {
|
||||
t.Error("claude should match claude-code (cross-mode)")
|
||||
}
|
||||
if !MatchesTargetName("claude-code", "claude") {
|
||||
t.Error("claude-code should match claude (cross-mode)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesTargetName_DifferentTargets(t *testing.T) {
|
||||
if MatchesTargetName("claude", "cursor") {
|
||||
t.Error("claude should not match cursor")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesTargetName_UnknownName(t *testing.T) {
|
||||
if MatchesTargetName("unknown-tool", "claude") {
|
||||
t.Error("unknown target should not match claude")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnownTargetNames(t *testing.T) {
|
||||
names := KnownTargetNames()
|
||||
if len(names) == 0 {
|
||||
t.Fatal("expected known target names to be non-empty")
|
||||
}
|
||||
|
||||
// Verify some well-known names are present
|
||||
found := map[string]bool{}
|
||||
for _, n := range names {
|
||||
found[n] = true
|
||||
}
|
||||
for _, want := range []string{"claude", "claude-code", "cursor"} {
|
||||
if !found[want] {
|
||||
t.Errorf("expected %q in known target names", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,3 +90,29 @@ func TestGroupedProjectTargets_MembersAreSorted(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupProjectTarget_Alias(t *testing.T) {
|
||||
// Canonical name should resolve
|
||||
tc, ok := LookupProjectTarget("claude")
|
||||
if !ok {
|
||||
t.Fatal("LookupProjectTarget should find canonical name 'claude'")
|
||||
}
|
||||
if tc.Path == "" {
|
||||
t.Error("expected non-empty path for claude")
|
||||
}
|
||||
|
||||
// Alias should also resolve to the same target
|
||||
tcAlias, ok := LookupProjectTarget("claude-code")
|
||||
if !ok {
|
||||
t.Fatal("LookupProjectTarget should find alias 'claude-code'")
|
||||
}
|
||||
if tcAlias.Path != tc.Path {
|
||||
t.Errorf("alias path %q != canonical path %q", tcAlias.Path, tc.Path)
|
||||
}
|
||||
|
||||
// Unknown name should not resolve
|
||||
_, ok = LookupProjectTarget("nonexistent-tool")
|
||||
if ok {
|
||||
t.Error("LookupProjectTarget should not find unknown name")
|
||||
}
|
||||
}
|
||||
|
||||
+54
-19
@@ -220,6 +220,45 @@ func DiscoverFromGit(source *Source) (*DiscoveryResult, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// resolveSubdir resolves a subdirectory path within a cloned repo.
|
||||
// It first checks for an exact match. If not found, it scans the repo for
|
||||
// SKILL.md files and looks for a skill whose name matches filepath.Base(subdir).
|
||||
// Returns the resolved subdir path (may differ from input) or an error.
|
||||
func resolveSubdir(repoPath, subdir string) (string, error) {
|
||||
// 1. Exact match — fast path
|
||||
exact := filepath.Join(repoPath, subdir)
|
||||
info, err := os.Stat(exact)
|
||||
if err == nil {
|
||||
if !info.IsDir() {
|
||||
return "", fmt.Errorf("'%s' is not a directory", subdir)
|
||||
}
|
||||
return subdir, nil
|
||||
}
|
||||
if !os.IsNotExist(err) {
|
||||
return "", fmt.Errorf("cannot access subdirectory: %w", err)
|
||||
}
|
||||
|
||||
// 2. Fuzzy match — scan for SKILL.md files whose directory basename matches
|
||||
baseName := filepath.Base(subdir)
|
||||
skills := discoverSkills(repoPath, false) // exclude root
|
||||
var candidates []string
|
||||
for _, sk := range skills {
|
||||
if sk.Name == baseName {
|
||||
candidates = append(candidates, sk.Path)
|
||||
}
|
||||
}
|
||||
|
||||
switch len(candidates) {
|
||||
case 0:
|
||||
return "", fmt.Errorf("subdirectory '%s' does not exist in repository", subdir)
|
||||
case 1:
|
||||
return candidates[0], nil
|
||||
default:
|
||||
return "", fmt.Errorf("subdirectory '%s' is ambiguous — multiple matches found:\n %s",
|
||||
subdir, strings.Join(candidates, "\n "))
|
||||
}
|
||||
}
|
||||
|
||||
// discoverSkills finds directories containing SKILL.md
|
||||
// If includeRoot is true, root-level SKILL.md is also included (with Path=".")
|
||||
func discoverSkills(repoPath string, includeRoot bool) []SkillInfo {
|
||||
@@ -285,20 +324,17 @@ func DiscoverFromGitSubdir(source *Source) (*DiscoveryResult, error) {
|
||||
return nil, fmt.Errorf("failed to clone repository: %w", err)
|
||||
}
|
||||
|
||||
// Verify subdirectory exists
|
||||
subdirPath := filepath.Join(repoPath, source.Subdir)
|
||||
info, err := os.Stat(subdirPath)
|
||||
// Resolve subdirectory (exact match or fuzzy by skill name)
|
||||
resolved, err := resolveSubdir(repoPath, source.Subdir)
|
||||
if err != nil {
|
||||
os.RemoveAll(tempDir)
|
||||
if os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("subdirectory '%s' does not exist in repository", source.Subdir)
|
||||
}
|
||||
return nil, fmt.Errorf("cannot access subdirectory: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
os.RemoveAll(tempDir)
|
||||
return nil, fmt.Errorf("'%s' is not a directory", source.Subdir)
|
||||
if resolved != source.Subdir {
|
||||
source.Subdir = resolved
|
||||
source.Name = filepath.Base(resolved)
|
||||
}
|
||||
subdirPath := filepath.Join(repoPath, resolved)
|
||||
|
||||
// Discover skills within the subdirectory (include root)
|
||||
skills := discoverSkills(subdirPath, true)
|
||||
@@ -424,18 +460,17 @@ func installFromGitSubdir(source *Source, destPath string, result *InstallResult
|
||||
return nil, fmt.Errorf("failed to clone repository: %w", err)
|
||||
}
|
||||
|
||||
// Verify subdirectory exists
|
||||
subdirPath := filepath.Join(tempRepoPath, source.Subdir)
|
||||
info, err := os.Stat(subdirPath)
|
||||
// Resolve subdirectory (exact match or fuzzy by skill name)
|
||||
resolved, err := resolveSubdir(tempRepoPath, source.Subdir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("subdirectory '%s' does not exist in repository", source.Subdir)
|
||||
}
|
||||
return nil, fmt.Errorf("cannot access subdirectory: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return nil, fmt.Errorf("'%s' is not a directory", source.Subdir)
|
||||
if resolved != source.Subdir {
|
||||
source.Subdir = resolved
|
||||
source.Name = filepath.Base(resolved)
|
||||
result.SkillName = source.Name
|
||||
}
|
||||
subdirPath := filepath.Join(tempRepoPath, resolved)
|
||||
|
||||
// Copy subdirectory to destination
|
||||
if err := copyDir(subdirPath, destPath); err != nil {
|
||||
|
||||
@@ -148,6 +148,87 @@ func TestDiscoverSkills_FindsHiddenDirs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSubdir(t *testing.T) {
|
||||
t.Run("exact match", func(t *testing.T) {
|
||||
repoPath := t.TempDir()
|
||||
// Create exact subdir with SKILL.md
|
||||
os.MkdirAll(filepath.Join(repoPath, "vue"), 0755)
|
||||
os.WriteFile(filepath.Join(repoPath, "vue", "SKILL.md"), []byte("# Vue"), 0644)
|
||||
|
||||
resolved, err := resolveSubdir(repoPath, "vue")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if resolved != "vue" {
|
||||
t.Errorf("resolved = %q, want %q", resolved, "vue")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fuzzy match via nested skill", func(t *testing.T) {
|
||||
repoPath := t.TempDir()
|
||||
// Skill lives under skills/ prefix, not at root
|
||||
os.MkdirAll(filepath.Join(repoPath, "skills", "vue"), 0755)
|
||||
os.WriteFile(filepath.Join(repoPath, "skills", "vue", "SKILL.md"), []byte("# Vue"), 0644)
|
||||
|
||||
resolved, err := resolveSubdir(repoPath, "vue")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if resolved != "skills/vue" {
|
||||
t.Errorf("resolved = %q, want %q", resolved, "skills/vue")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no match", func(t *testing.T) {
|
||||
repoPath := t.TempDir()
|
||||
// Empty repo — no skills at all
|
||||
_, err := resolveSubdir(repoPath, "nonexistent")
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "does not exist") {
|
||||
t.Errorf("error = %q, want substring %q", err.Error(), "does not exist")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ambiguous match", func(t *testing.T) {
|
||||
repoPath := t.TempDir()
|
||||
// Two different paths with same skill name
|
||||
os.MkdirAll(filepath.Join(repoPath, "frontend", "pdf"), 0755)
|
||||
os.WriteFile(filepath.Join(repoPath, "frontend", "pdf", "SKILL.md"), []byte("# PDF FE"), 0644)
|
||||
os.MkdirAll(filepath.Join(repoPath, "backend", "pdf"), 0755)
|
||||
os.WriteFile(filepath.Join(repoPath, "backend", "pdf", "SKILL.md"), []byte("# PDF BE"), 0644)
|
||||
|
||||
_, err := resolveSubdir(repoPath, "pdf")
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "ambiguous") {
|
||||
t.Errorf("error = %q, want substring %q", err.Error(), "ambiguous")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "frontend/pdf") {
|
||||
t.Errorf("error should list candidate 'frontend/pdf': %q", err.Error())
|
||||
}
|
||||
if !strings.Contains(err.Error(), "backend/pdf") {
|
||||
t.Errorf("error should list candidate 'backend/pdf': %q", err.Error())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("not a directory", func(t *testing.T) {
|
||||
repoPath := t.TempDir()
|
||||
// Create a file (not dir) at the subdir path
|
||||
os.WriteFile(filepath.Join(repoPath, "vue"), []byte("not a dir"), 0644)
|
||||
|
||||
_, err := resolveSubdir(repoPath, "vue")
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "not a directory") {
|
||||
t.Errorf("error = %q, want substring %q", err.Error(), "not a directory")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestWrapGitError(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/install"
|
||||
)
|
||||
|
||||
@@ -28,10 +29,14 @@ type Entry struct {
|
||||
}
|
||||
|
||||
// LogDir returns the logs directory derived from a config file path.
|
||||
// For global mode: ~/.config/skillshare/logs/
|
||||
// For project mode: .skillshare/logs/
|
||||
// For project mode: .skillshare/logs/ (alongside project config)
|
||||
// For global mode: $XDG_STATE_HOME/skillshare/logs/
|
||||
func LogDir(configPath string) string {
|
||||
return filepath.Join(filepath.Dir(configPath), "logs")
|
||||
configDir := filepath.Dir(configPath)
|
||||
if filepath.Base(configDir) == ".skillshare" {
|
||||
return filepath.Join(configDir, "logs")
|
||||
}
|
||||
return filepath.Join(config.StateDir(), "logs")
|
||||
}
|
||||
|
||||
// Write appends a single JSONL entry to the named log file.
|
||||
|
||||
@@ -11,14 +11,26 @@ import (
|
||||
func tempConfigPath(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
// Isolate XDG_STATE_HOME so global-mode LogDir() doesn't collide across tests
|
||||
t.Setenv("XDG_STATE_HOME", filepath.Join(dir, "state"))
|
||||
return filepath.Join(dir, "config.yaml")
|
||||
}
|
||||
|
||||
func TestLogDir(t *testing.T) {
|
||||
func TestLogDir_Global(t *testing.T) {
|
||||
t.Setenv("XDG_STATE_HOME", "/custom/state")
|
||||
|
||||
got := LogDir("/home/user/.config/skillshare/config.yaml")
|
||||
want := "/home/user/.config/skillshare/logs"
|
||||
want := "/custom/state/skillshare/logs"
|
||||
if got != want {
|
||||
t.Errorf("LogDir() = %q, want %q", got, want)
|
||||
t.Errorf("LogDir(global) = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogDir_Project(t *testing.T) {
|
||||
got := LogDir("/project/.skillshare/config.yaml")
|
||||
want := "/project/.skillshare/logs"
|
||||
if got != want {
|
||||
t.Errorf("LogDir(project) = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
//go:build !dev
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsUIBuilt reports whether the embedded dist contains a real frontend build.
|
||||
// Returns false when the dist only contains a placeholder (e.g. Homebrew or make build without UI).
|
||||
func IsUIBuilt() bool {
|
||||
data, err := distFS.ReadFile("dist/index.html")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return !strings.Contains(string(data), "UI not built")
|
||||
}
|
||||
|
||||
//go:embed all:dist
|
||||
var distFS embed.FS
|
||||
|
||||
// spaHandler returns a handler that serves the embedded SPA.
|
||||
// Unknown paths fall back to index.html for client-side routing.
|
||||
func spaHandler() http.Handler {
|
||||
sub, err := fs.Sub(distFS, "dist")
|
||||
if err != nil {
|
||||
panic("embed: " + err.Error())
|
||||
}
|
||||
fileServer := http.FileServer(http.FS(sub))
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Try to serve the file directly
|
||||
path := strings.TrimPrefix(r.URL.Path, "/")
|
||||
if path == "" {
|
||||
path = "index.html"
|
||||
}
|
||||
|
||||
if _, err := fs.Stat(sub, path); err == nil {
|
||||
fileServer.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// SPA fallback: serve index.html for unknown paths
|
||||
index, err := fs.ReadFile(sub, "index.html")
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
http.Error(w, "UI not built. Run: make ui-build", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write(index)
|
||||
})
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
//go:build dev
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// IsUIBuilt reports whether the embedded dist contains a real frontend build.
|
||||
// In dev mode, the frontend is served by Vite, not embedded.
|
||||
func IsUIBuilt() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// spaHandler returns a placeholder handler when building with -tags dev.
|
||||
// In dev mode, use the Vite dev server on :5173 instead.
|
||||
func spaHandler() http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html>
|
||||
<html>
|
||||
<head><title>Skillshare UI (dev)</title></head>
|
||||
<body>
|
||||
<h1>Skillshare UI — Dev Mode</h1>
|
||||
<p>The frontend is served by Vite at <a href="http://localhost:5173">localhost:5173</a>.</p>
|
||||
<p>Or run <code>make ui-build</code> to embed the built frontend.</p>
|
||||
</body>
|
||||
</html>`))
|
||||
})
|
||||
}
|
||||
@@ -239,7 +239,7 @@ func (s *Server) handlePull(w http.ResponseWriter, r *http.Request) {
|
||||
res.Updated = mergeResult.Updated
|
||||
res.Skipped = mergeResult.Skipped
|
||||
}
|
||||
pruneResult, err := ssync.PruneOrphanLinks(target.Path, src, target.Include, target.Exclude, false)
|
||||
pruneResult, err := ssync.PruneOrphanLinks(target.Path, src, target.Include, target.Exclude, name, false)
|
||||
if err == nil {
|
||||
res.Pruned = pruneResult.Removed
|
||||
}
|
||||
|
||||
@@ -14,16 +14,17 @@ import (
|
||||
)
|
||||
|
||||
type skillItem struct {
|
||||
Name string `json:"name"`
|
||||
FlatName string `json:"flatName"`
|
||||
RelPath string `json:"relPath"`
|
||||
SourcePath string `json:"sourcePath"`
|
||||
IsInRepo bool `json:"isInRepo"`
|
||||
InstalledAt string `json:"installedAt,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
RepoURL string `json:"repoUrl,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Name string `json:"name"`
|
||||
FlatName string `json:"flatName"`
|
||||
RelPath string `json:"relPath"`
|
||||
SourcePath string `json:"sourcePath"`
|
||||
IsInRepo bool `json:"isInRepo"`
|
||||
Targets []string `json:"targets,omitempty"`
|
||||
InstalledAt string `json:"installedAt,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
RepoURL string `json:"repoUrl,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleListSkills(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -41,6 +42,7 @@ func (s *Server) handleListSkills(w http.ResponseWriter, r *http.Request) {
|
||||
RelPath: d.RelPath,
|
||||
SourcePath: d.SourcePath,
|
||||
IsInRepo: d.IsInRepo,
|
||||
Targets: d.Targets,
|
||||
}
|
||||
|
||||
// Enrich with metadata if available
|
||||
@@ -80,6 +82,7 @@ func (s *Server) handleGetSkill(w http.ResponseWriter, r *http.Request) {
|
||||
RelPath: d.RelPath,
|
||||
SourcePath: d.SourcePath,
|
||||
IsInRepo: d.IsInRepo,
|
||||
Targets: d.Targets,
|
||||
}
|
||||
|
||||
if meta, _ := install.ReadMeta(d.SourcePath); meta != nil {
|
||||
|
||||
@@ -72,7 +72,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
res.Skipped = mergeResult.Skipped
|
||||
|
||||
// Prune orphans
|
||||
pruneResult, err := ssync.PruneOrphanLinks(target.Path, s.cfg.Source, target.Include, target.Exclude, body.DryRun)
|
||||
pruneResult, err := ssync.PruneOrphanLinks(target.Path, s.cfg.Source, target.Include, target.Exclude, name, body.DryRun)
|
||||
if err == nil {
|
||||
res.Pruned = pruneResult.Removed
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ func (s *Server) handleListTargets(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, "invalid include/exclude for target "+name+": "+err.Error())
|
||||
return
|
||||
}
|
||||
filtered = ssync.FilterSkillsByTarget(filtered, name)
|
||||
item.ExpectedSkillCount = len(filtered)
|
||||
}
|
||||
status, linked, local := ssync.CheckStatusMerge(target.Path, s.cfg.Source)
|
||||
@@ -202,6 +203,75 @@ func (s *Server) handleRemoveTarget(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"success": true, "name": name})
|
||||
}
|
||||
|
||||
func (s *Server) handleUpdateTarget(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
name := r.PathValue("name")
|
||||
|
||||
target, exists := s.cfg.Targets[name]
|
||||
if !exists {
|
||||
writeError(w, http.StatusNotFound, "target not found: "+name)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Include *[]string `json:"include"` // null = no change, [] = clear
|
||||
Exclude *[]string `json:"exclude"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
// Validate patterns
|
||||
if body.Include != nil {
|
||||
if _, err := ssync.FilterSkills(nil, *body.Include, nil); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid include pattern: "+err.Error())
|
||||
return
|
||||
}
|
||||
target.Include = *body.Include
|
||||
}
|
||||
if body.Exclude != nil {
|
||||
if _, err := ssync.FilterSkills(nil, nil, *body.Exclude); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid exclude pattern: "+err.Error())
|
||||
return
|
||||
}
|
||||
target.Exclude = *body.Exclude
|
||||
}
|
||||
|
||||
s.cfg.Targets[name] = target
|
||||
|
||||
// In project mode, also update the project config
|
||||
if s.IsProjectMode() {
|
||||
for i := range s.projectCfg.Targets {
|
||||
if s.projectCfg.Targets[i].Name == name {
|
||||
if body.Include != nil {
|
||||
s.projectCfg.Targets[i].Include = *body.Include
|
||||
}
|
||||
if body.Exclude != nil {
|
||||
s.projectCfg.Targets[i].Exclude = *body.Exclude
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.saveConfig(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to save config: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
s.writeOpsLog("target", "ok", start, map[string]any{
|
||||
"action": "filter",
|
||||
"name": name,
|
||||
"scope": "ui",
|
||||
}, "")
|
||||
|
||||
writeJSON(w, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
// unlinkMergeSymlinks removes symlinks in targetPath that point under the
|
||||
// source directory and copies the skill contents back as real files.
|
||||
func (s *Server) unlinkMergeSymlinks(targetPath string) {
|
||||
|
||||
@@ -35,7 +35,7 @@ func TestHandlePutConfig_WritesOpsLog(t *testing.T) {
|
||||
s := New(&config.Config{
|
||||
Source: sourceDir,
|
||||
Targets: map[string]config.TargetConfig{},
|
||||
}, "127.0.0.1:0")
|
||||
}, "127.0.0.1:0", "")
|
||||
|
||||
payload, _ := json.Marshal(map[string]string{"raw": initialRaw})
|
||||
req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(payload))
|
||||
@@ -85,7 +85,7 @@ func TestHandleAuditAll_WritesAuditLog(t *testing.T) {
|
||||
s := New(&config.Config{
|
||||
Source: sourceDir,
|
||||
Targets: map[string]config.TargetConfig{},
|
||||
}, "127.0.0.1:0")
|
||||
}, "127.0.0.1:0", "")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/audit", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
@@ -134,7 +134,7 @@ func TestHandleAuditAll_HighOnlyClassifiedAsWarning(t *testing.T) {
|
||||
s := New(&config.Config{
|
||||
Source: sourceDir,
|
||||
Targets: map[string]config.TargetConfig{},
|
||||
}, "127.0.0.1:0")
|
||||
}, "127.0.0.1:0", "")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/audit", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
@@ -211,7 +211,7 @@ func TestHandleInstall_WritesDetailedInstallLog(t *testing.T) {
|
||||
s := New(&config.Config{
|
||||
Source: sourceDir,
|
||||
Targets: map[string]config.TargetConfig{},
|
||||
}, "127.0.0.1:0")
|
||||
}, "127.0.0.1:0", "")
|
||||
|
||||
payload, _ := json.Marshal(map[string]any{
|
||||
"source": localSource,
|
||||
@@ -301,7 +301,7 @@ func TestHandleInstall_ErrorAlsoWritesInstallLog(t *testing.T) {
|
||||
s := New(&config.Config{
|
||||
Source: sourceDir,
|
||||
Targets: map[string]config.TargetConfig{},
|
||||
}, "127.0.0.1:0")
|
||||
}, "127.0.0.1:0", "")
|
||||
|
||||
payload, _ := json.Marshal(map[string]any{
|
||||
"source": localSource,
|
||||
|
||||
+46
-11
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -28,28 +29,40 @@ type Server struct {
|
||||
// Project mode fields (empty/nil for global mode)
|
||||
projectRoot string
|
||||
projectCfg *config.ProjectConfig
|
||||
|
||||
// uiDistDir, when non-empty, serves UI from this disk directory
|
||||
// instead of the embedded SPA. Used for runtime-downloaded UI assets.
|
||||
uiDistDir string
|
||||
|
||||
// onReady is called after the listener is bound but before serving.
|
||||
// Used to open the browser only after the port is confirmed available.
|
||||
onReady func()
|
||||
}
|
||||
|
||||
// New creates a new Server for global mode
|
||||
func New(cfg *config.Config, addr string) *Server {
|
||||
// New creates a new Server for global mode.
|
||||
// uiDistDir, when non-empty, serves UI from disk instead of the embedded SPA.
|
||||
func New(cfg *config.Config, addr, uiDistDir string) *Server {
|
||||
s := &Server{
|
||||
cfg: cfg,
|
||||
addr: addr,
|
||||
mux: http.NewServeMux(),
|
||||
cfg: cfg,
|
||||
addr: addr,
|
||||
mux: http.NewServeMux(),
|
||||
uiDistDir: uiDistDir,
|
||||
}
|
||||
s.registerRoutes()
|
||||
s.handler = s.withConfigAutoReload(s.mux)
|
||||
return s
|
||||
}
|
||||
|
||||
// NewProject creates a new Server for project mode
|
||||
func NewProject(cfg *config.Config, projectCfg *config.ProjectConfig, projectRoot, addr string) *Server {
|
||||
// NewProject creates a new Server for project mode.
|
||||
// uiDistDir, when non-empty, serves UI from disk instead of the embedded SPA.
|
||||
func NewProject(cfg *config.Config, projectCfg *config.ProjectConfig, projectRoot, addr, uiDistDir string) *Server {
|
||||
s := &Server{
|
||||
cfg: cfg,
|
||||
addr: addr,
|
||||
mux: http.NewServeMux(),
|
||||
projectRoot: projectRoot,
|
||||
projectCfg: projectCfg,
|
||||
uiDistDir: uiDistDir,
|
||||
}
|
||||
s.registerRoutes()
|
||||
s.handler = s.withConfigAutoReload(s.mux)
|
||||
@@ -139,12 +152,30 @@ func (s *Server) Start() error {
|
||||
return s.StartWithContext(ctx)
|
||||
}
|
||||
|
||||
// SetOnReady sets a callback invoked after the listener is bound but before
|
||||
// serving begins. Used to open the browser only after the port is confirmed
|
||||
// available.
|
||||
func (s *Server) SetOnReady(fn func()) {
|
||||
s.onReady = fn
|
||||
}
|
||||
|
||||
// StartWithContext starts the HTTP server and shuts down gracefully when ctx is cancelled.
|
||||
func (s *Server) StartWithContext(ctx context.Context) error {
|
||||
s.startTime = time.Now()
|
||||
|
||||
// Bind the port first so callers know immediately if it's in use.
|
||||
ln, err := net.Listen("tcp", s.addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("Skillshare UI running at http://%s\n", s.addr)
|
||||
|
||||
if s.onReady != nil {
|
||||
s.onReady()
|
||||
}
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: s.addr,
|
||||
Handler: s.handler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
@@ -154,8 +185,7 @@ func (s *Server) StartWithContext(ctx context.Context) error {
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
fmt.Printf("Skillshare UI running at http://%s\n", s.addr)
|
||||
errCh <- srv.ListenAndServe()
|
||||
errCh <- srv.Serve(ln)
|
||||
}()
|
||||
|
||||
select {
|
||||
@@ -192,6 +222,7 @@ func (s *Server) registerRoutes() {
|
||||
// Targets
|
||||
s.mux.HandleFunc("GET /api/targets", s.handleListTargets)
|
||||
s.mux.HandleFunc("POST /api/targets", s.handleAddTarget)
|
||||
s.mux.HandleFunc("PATCH /api/targets/{name}", s.handleUpdateTarget)
|
||||
s.mux.HandleFunc("DELETE /api/targets/{name}", s.handleRemoveTarget)
|
||||
|
||||
// Sync
|
||||
@@ -259,7 +290,11 @@ func (s *Server) registerRoutes() {
|
||||
s.mux.HandleFunc("GET /api/config/available-targets", s.handleAvailableTargets)
|
||||
|
||||
// SPA fallback — must be last
|
||||
s.mux.Handle("/", spaHandler())
|
||||
if s.uiDistDir != "" {
|
||||
s.mux.Handle("/", spaHandlerFromDisk(s.uiDistDir))
|
||||
} else {
|
||||
s.mux.Handle("/", uiPlaceholderHandler())
|
||||
}
|
||||
}
|
||||
|
||||
// handleHealth responds with status, version, and uptime
|
||||
|
||||
@@ -37,7 +37,7 @@ func TestServer_AutoReloadsConfigForAPIRequests(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("failed to load initial config: %v", err)
|
||||
}
|
||||
s := New(cfg, "127.0.0.1:0")
|
||||
s := New(cfg, "127.0.0.1:0", "")
|
||||
|
||||
req1 := httptest.NewRequest(http.MethodGet, "/api/overview", nil)
|
||||
rr1 := httptest.NewRecorder()
|
||||
@@ -104,7 +104,7 @@ func TestServer_ConfigEndpointStillWorksWhenConfigTemporarilyInvalid(t *testing.
|
||||
if err != nil {
|
||||
t.Fatalf("failed to load initial config: %v", err)
|
||||
}
|
||||
s := New(cfg, "127.0.0.1:0")
|
||||
s := New(cfg, "127.0.0.1:0", "")
|
||||
|
||||
invalidRaw := "source: [\n"
|
||||
if err := os.WriteFile(cfgPath, []byte(invalidRaw), 0644); err != nil {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// uiPlaceholderHandler returns a handler for when no UI dist is available.
|
||||
// Used in dev mode (Vite on :5173) or API-only scenarios.
|
||||
func uiPlaceholderHandler() http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(`<!DOCTYPE html>
|
||||
<html>
|
||||
<head><title>Skillshare UI (dev mode)</title>
|
||||
<style>body{font-family:system-ui,sans-serif;max-width:600px;margin:60px auto;padding:0 20px;color:#333}
|
||||
code{background:#f0f0f0;padding:2px 6px;border-radius:3px;font-size:0.9em}
|
||||
pre{background:#f0f0f0;padding:12px 16px;border-radius:6px;overflow-x:auto}</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Skillshare UI — Dev Mode</h1>
|
||||
<p>This is the API server. The frontend needs to be started separately:</p>
|
||||
<pre>cd ui && pnpm run dev</pre>
|
||||
<p>Then open <a href="http://localhost:5173">http://localhost:5173</a> (Vite proxies <code>/api</code> to this server).</p>
|
||||
<p>Or use <code>make ui-dev</code> to start both together.</p>
|
||||
<hr>
|
||||
<p style="color:#888;font-size:0.85em">In production builds, <code>skillshare ui</code> downloads and serves the frontend automatically.</p>
|
||||
</body>
|
||||
</html>`))
|
||||
})
|
||||
}
|
||||
|
||||
// spaHandlerFromDisk serves a SPA from a directory on disk.
|
||||
// Unknown paths fall back to index.html for client-side routing.
|
||||
func spaHandlerFromDisk(dir string) http.Handler {
|
||||
fileServer := http.FileServer(http.Dir(dir))
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Try to serve the file directly
|
||||
path := strings.TrimPrefix(r.URL.Path, "/")
|
||||
if path == "" {
|
||||
path = "index.html"
|
||||
}
|
||||
|
||||
fullPath := filepath.Join(dir, path)
|
||||
if _, err := os.Stat(fullPath); err == nil {
|
||||
fileServer.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// SPA fallback: serve index.html
|
||||
indexPath := filepath.Join(dir, "index.html")
|
||||
index, err := os.ReadFile(indexPath)
|
||||
if err != nil {
|
||||
http.Error(w, "UI assets not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write(index)
|
||||
})
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/config"
|
||||
)
|
||||
|
||||
// FilterSkills filters discovered skills by include/exclude patterns.
|
||||
@@ -88,3 +90,23 @@ func shouldSyncFlatName(name string, includePatterns, excludePatterns []string)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// FilterSkillsByTarget removes skills whose Targets field does not include
|
||||
// the given target name. Skills with nil Targets (no field declared) pass
|
||||
// through unconditionally.
|
||||
func FilterSkillsByTarget(skills []DiscoveredSkill, targetName string) []DiscoveredSkill {
|
||||
filtered := make([]DiscoveredSkill, 0, len(skills))
|
||||
for _, skill := range skills {
|
||||
if skill.Targets == nil {
|
||||
filtered = append(filtered, skill)
|
||||
continue
|
||||
}
|
||||
for _, t := range skill.Targets {
|
||||
if config.MatchesTargetName(t, targetName) {
|
||||
filtered = append(filtered, skill)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package sync
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFilterSkillsByTarget_NilPassesThrough(t *testing.T) {
|
||||
skills := []DiscoveredSkill{
|
||||
{FlatName: "no-targets", Targets: nil},
|
||||
}
|
||||
result := FilterSkillsByTarget(skills, "claude")
|
||||
if len(result) != 1 {
|
||||
t.Errorf("nil Targets should pass through, got %d", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterSkillsByTarget_ExactMatch(t *testing.T) {
|
||||
skills := []DiscoveredSkill{
|
||||
{FlatName: "claude-only", Targets: []string{"claude"}},
|
||||
{FlatName: "cursor-only", Targets: []string{"cursor"}},
|
||||
}
|
||||
result := FilterSkillsByTarget(skills, "claude")
|
||||
if len(result) != 1 || result[0].FlatName != "claude-only" {
|
||||
t.Errorf("expected only claude-only, got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterSkillsByTarget_CrossModeMatch(t *testing.T) {
|
||||
skills := []DiscoveredSkill{
|
||||
{FlatName: "cross-mode", Targets: []string{"claude"}},
|
||||
}
|
||||
// "claude-code" is an alias for claude
|
||||
result := FilterSkillsByTarget(skills, "claude-code")
|
||||
if len(result) != 1 {
|
||||
t.Errorf("cross-mode match should work, got %d results", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterSkillsByTarget_NoMatch(t *testing.T) {
|
||||
skills := []DiscoveredSkill{
|
||||
{FlatName: "claude-only", Targets: []string{"claude"}},
|
||||
}
|
||||
result := FilterSkillsByTarget(skills, "cursor")
|
||||
if len(result) != 0 {
|
||||
t.Errorf("expected 0 results, got %d", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterSkillsByTarget_MultipleTargets(t *testing.T) {
|
||||
skills := []DiscoveredSkill{
|
||||
{FlatName: "multi", Targets: []string{"claude", "cursor"}},
|
||||
}
|
||||
result := FilterSkillsByTarget(skills, "cursor")
|
||||
if len(result) != 1 {
|
||||
t.Errorf("skill with multiple targets should match, got %d", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterSkillsByTarget_MixedNilAndSpecific(t *testing.T) {
|
||||
skills := []DiscoveredSkill{
|
||||
{FlatName: "all-targets", Targets: nil},
|
||||
{FlatName: "claude-only", Targets: []string{"claude"}},
|
||||
{FlatName: "cursor-only", Targets: []string{"cursor"}},
|
||||
}
|
||||
result := FilterSkillsByTarget(skills, "claude")
|
||||
if len(result) != 2 {
|
||||
t.Errorf("expected 2 results (nil + claude-only), got %d", len(result))
|
||||
}
|
||||
}
|
||||
+11
-5
@@ -13,10 +13,11 @@ import (
|
||||
|
||||
// DiscoveredSkill represents a skill found during recursive source directory scan.
|
||||
type DiscoveredSkill struct {
|
||||
SourcePath string // Full path: ~/.config/skillshare/skills/_team/frontend/ui
|
||||
RelPath string // Relative path from source: _team/frontend/ui
|
||||
FlatName string // Flat name for target: _team__frontend__ui
|
||||
IsInRepo bool // Whether this skill is inside a tracked repo (_-prefixed directory)
|
||||
SourcePath string // Full path: ~/.config/skillshare/skills/_team/frontend/ui
|
||||
RelPath string // Relative path from source: _team/frontend/ui
|
||||
FlatName string // Flat name for target: _team__frontend__ui
|
||||
IsInRepo bool // Whether this skill is inside a tracked repo (_-prefixed directory)
|
||||
Targets []string // From SKILL.md frontmatter; nil = all targets
|
||||
}
|
||||
|
||||
// DiscoverSourceSkills recursively scans the source directory for skills.
|
||||
@@ -59,11 +60,14 @@ func DiscoverSourceSkills(sourcePath string) ([]DiscoveredSkill, error) {
|
||||
isInRepo = true
|
||||
}
|
||||
|
||||
targets := utils.ParseFrontmatterList(filepath.Join(skillDir, "SKILL.md"), "targets")
|
||||
|
||||
skills = append(skills, DiscoveredSkill{
|
||||
SourcePath: skillDir,
|
||||
RelPath: relPath,
|
||||
FlatName: utils.PathToFlatName(relPath),
|
||||
IsInRepo: isInRepo,
|
||||
Targets: targets,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -349,6 +353,7 @@ func SyncTargetMerge(name string, target config.TargetConfig, sourcePath string,
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to apply filters for target %s: %w", name, err)
|
||||
}
|
||||
discoveredSkills = FilterSkillsByTarget(discoveredSkills, name)
|
||||
|
||||
for _, skill := range discoveredSkills {
|
||||
// Use flat name in target (e.g., "personal__writing__email")
|
||||
@@ -431,7 +436,7 @@ type PruneResult struct {
|
||||
// 1. Source-linked entries excluded by include/exclude filters (remove from target)
|
||||
// 2. Orphan links/directories that no longer exist in source
|
||||
// 3. Unknown local directories (kept with warning)
|
||||
func PruneOrphanLinks(targetPath, sourcePath string, include, exclude []string, dryRun bool) (*PruneResult, error) {
|
||||
func PruneOrphanLinks(targetPath, sourcePath string, include, exclude []string, targetName string, dryRun bool) (*PruneResult, error) {
|
||||
result := &PruneResult{}
|
||||
|
||||
// Discover all skills from source, then filter to target-managed skills.
|
||||
@@ -443,6 +448,7 @@ func PruneOrphanLinks(targetPath, sourcePath string, include, exclude []string,
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to apply filters for pruning: %w", err)
|
||||
}
|
||||
managedSkills = FilterSkillsByTarget(managedSkills, targetName)
|
||||
includePatterns, err := normalizePatterns(include)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid include pattern for pruning: %w", err)
|
||||
|
||||
@@ -58,7 +58,9 @@ func NewSandbox(t *testing.T) *Sandbox {
|
||||
dirs := []string{
|
||||
filepath.Join(home, ".config", "skillshare"),
|
||||
filepath.Join(home, ".config", "skillshare", "skills"),
|
||||
filepath.Join(home, ".config", "skillshare", "backups"),
|
||||
filepath.Join(home, ".local", "share", "skillshare", "backups"),
|
||||
filepath.Join(home, ".local", "share", "skillshare", "trash"),
|
||||
filepath.Join(home, ".local", "state", "skillshare", "logs"),
|
||||
filepath.Join(home, ".claude"),
|
||||
filepath.Join(home, ".codex"),
|
||||
filepath.Join(home, ".cursor"),
|
||||
@@ -74,6 +76,14 @@ func NewSandbox(t *testing.T) *Sandbox {
|
||||
sb.SetEnv("HOME", home)
|
||||
sb.SetEnv("SKILLSHARE_CONFIG", sb.ConfigPath)
|
||||
|
||||
// Point XDG variables into the sandbox so config.BaseDir()/DataDir()/
|
||||
// StateDir() resolve to sandbox paths. Without this, CI runners that
|
||||
// set XDG_CONFIG_HOME (e.g. ubuntu-latest) cause the subprocess to
|
||||
// write files outside the sandbox.
|
||||
sb.SetEnv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
sb.SetEnv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
|
||||
sb.SetEnv("XDG_STATE_HOME", filepath.Join(home, ".local", "state"))
|
||||
|
||||
return sb
|
||||
}
|
||||
|
||||
@@ -264,7 +274,8 @@ func (sb *Sandbox) SetupProjectDir(targets ...string) string {
|
||||
|
||||
// Create target directories
|
||||
knownPaths := map[string]string{
|
||||
"claude-code": ".claude/skills",
|
||||
"claude": ".claude/skills",
|
||||
"claude-code": ".claude/skills", // legacy alias
|
||||
"cursor": ".cursor/skills",
|
||||
"codex": ".agents/skills",
|
||||
}
|
||||
|
||||
@@ -7,17 +7,15 @@ import (
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/config"
|
||||
)
|
||||
|
||||
const defaultMaxAge = 7 * 24 * time.Hour // 7 days
|
||||
|
||||
// TrashDir returns the global trash directory path.
|
||||
func TrashDir() string {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(home, ".config", "skillshare", "trash")
|
||||
return filepath.Join(config.DataDir(), "trash")
|
||||
}
|
||||
|
||||
// ProjectTrashDir returns the project-level trash directory path.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package trash
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTrashDir_RespectsXDGDataHome(t *testing.T) {
|
||||
t.Setenv("XDG_DATA_HOME", "/custom/data")
|
||||
|
||||
got := TrashDir()
|
||||
want := filepath.Join("/custom/data", "skillshare", "trash")
|
||||
if got != want {
|
||||
t.Errorf("TrashDir() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package uidist
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bufio"
|
||||
"compress/gzip"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/version"
|
||||
)
|
||||
|
||||
// AssetName is the filename of the UI dist tarball in GitHub releases
|
||||
const AssetName = "skillshare-ui-dist.tar.gz"
|
||||
|
||||
// CacheDir returns the cache directory for a specific version's UI dist.
|
||||
// Path: ~/.cache/skillshare/ui/{ver}/
|
||||
func CacheDir(ver string) string {
|
||||
return filepath.Join(config.CacheDir(), "ui", ver)
|
||||
}
|
||||
|
||||
// IsCached checks whether a cached UI dist exists for the given version.
|
||||
// Returns the directory path and true if index.html exists there.
|
||||
func IsCached(ver string) (string, bool) {
|
||||
dir := CacheDir(ver)
|
||||
if _, err := os.Stat(filepath.Join(dir, "index.html")); err == nil {
|
||||
return dir, true
|
||||
}
|
||||
return dir, false
|
||||
}
|
||||
|
||||
// Download fetches the UI dist tarball for the given version, verifies its
|
||||
// checksum, extracts it to the cache directory, and cleans up old versions.
|
||||
func Download(ver string) error {
|
||||
dir := CacheDir(ver)
|
||||
|
||||
// Fetch expected checksum
|
||||
expectedHash, err := fetchChecksum(ver)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch checksum: %w", err)
|
||||
}
|
||||
|
||||
// Download tarball to temp file
|
||||
tarballURL := version.BuildUIDistURL(ver)
|
||||
tmpFile, err := downloadToTemp(tarballURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to download UI assets: %w", err)
|
||||
}
|
||||
defer os.Remove(tmpFile)
|
||||
|
||||
// Verify checksum
|
||||
actualHash, err := fileSHA256(tmpFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to compute checksum: %w", err)
|
||||
}
|
||||
if actualHash != expectedHash {
|
||||
return fmt.Errorf("checksum mismatch: expected %s, got %s", expectedHash, actualHash)
|
||||
}
|
||||
|
||||
// Extract to cache dir
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create cache dir: %w", err)
|
||||
}
|
||||
if err := extractTarGz(tmpFile, dir); err != nil {
|
||||
// Clean up partial extraction
|
||||
os.RemoveAll(dir)
|
||||
return fmt.Errorf("failed to extract UI assets: %w", err)
|
||||
}
|
||||
|
||||
// Clean old versions (best-effort)
|
||||
_ = cleanOldVersions(ver)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearCache removes the entire UI cache directory (~/.cache/skillshare/ui/).
|
||||
func ClearCache() error {
|
||||
dir := filepath.Join(config.CacheDir(), "ui")
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return os.RemoveAll(dir)
|
||||
}
|
||||
|
||||
// ClearVersion removes a specific version's cached UI dist.
|
||||
func ClearVersion(ver string) error {
|
||||
dir := CacheDir(ver)
|
||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return os.RemoveAll(dir)
|
||||
}
|
||||
|
||||
// cleanOldVersions removes cached UI dist versions other than currentVer.
|
||||
func cleanOldVersions(currentVer string) error {
|
||||
uiDir := filepath.Join(config.CacheDir(), "ui")
|
||||
entries, err := os.ReadDir(uiDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.IsDir() && e.Name() != currentVer {
|
||||
os.RemoveAll(filepath.Join(uiDir, e.Name()))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchChecksum downloads checksums.txt and parses the SHA256 for AssetName.
|
||||
func fetchChecksum(ver string) (string, error) {
|
||||
url := version.BuildChecksumsURL(ver)
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("checksums.txt returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return parseChecksum(resp.Body, AssetName)
|
||||
}
|
||||
|
||||
// parseChecksum reads a checksums.txt (format: "hash filename\n") and returns
|
||||
// the hash for the given target filename.
|
||||
func parseChecksum(r io.Reader, target string) (string, error) {
|
||||
scanner := bufio.NewScanner(r)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
// GoReleaser format: "<sha256> <filename>"
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) == 2 && parts[1] == target {
|
||||
return parts[0], nil
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "", fmt.Errorf("checksum for %s not found in checksums.txt", target)
|
||||
}
|
||||
|
||||
// maxDownloadSize limits the UI dist download to prevent unexpected disk usage.
|
||||
const maxDownloadSize = 100 * 1024 * 1024 // 100 MB
|
||||
|
||||
// downloadToTemp downloads a URL to a temporary file and returns its path.
|
||||
func downloadToTemp(url string) (string, error) {
|
||||
client := &http.Client{Timeout: 120 * time.Second}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("download returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp("", "skillshare-ui-dist-*.tar.gz")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tmp.Close()
|
||||
|
||||
limited := io.LimitReader(resp.Body, maxDownloadSize+1)
|
||||
n, err := io.Copy(tmp, limited)
|
||||
if err != nil {
|
||||
os.Remove(tmp.Name())
|
||||
return "", err
|
||||
}
|
||||
if n > maxDownloadSize {
|
||||
os.Remove(tmp.Name())
|
||||
return "", fmt.Errorf("download exceeds maximum size (%d MB)", maxDownloadSize/(1024*1024))
|
||||
}
|
||||
|
||||
return tmp.Name(), nil
|
||||
}
|
||||
|
||||
// fileSHA256 computes the SHA-256 hex digest of a file.
|
||||
func fileSHA256(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// maxFileSize limits individual file extraction to prevent decompression bombs.
|
||||
const maxFileSize = 50 * 1024 * 1024 // 50 MB per file
|
||||
|
||||
// extractTarGz extracts a .tar.gz file into destDir.
|
||||
// The tarball is expected to contain a flat structure (no top-level directory).
|
||||
func extractTarGz(tarballPath, destDir string) error {
|
||||
f, err := os.Open(tarballPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
gz, err := gzip.NewReader(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer gz.Close()
|
||||
|
||||
cleanDest := filepath.Clean(destDir) + string(os.PathSeparator)
|
||||
|
||||
tr := tar.NewReader(gz)
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Sanitize path to prevent zip-slip
|
||||
clean := filepath.Clean(hdr.Name)
|
||||
if strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) {
|
||||
return fmt.Errorf("invalid path in archive: %s", hdr.Name)
|
||||
}
|
||||
target := filepath.Join(destDir, clean)
|
||||
// Canonical check: joined path must stay within destDir
|
||||
if !strings.HasPrefix(target, cleanDest) && target != filepath.Clean(destDir) {
|
||||
return fmt.Errorf("invalid path in archive: %s", hdr.Name)
|
||||
}
|
||||
|
||||
switch hdr.Typeflag {
|
||||
case tar.TypeDir:
|
||||
if err := os.MkdirAll(target, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
case tar.TypeReg:
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(hdr.Mode)&0755|0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
limited := io.LimitReader(tr, maxFileSize+1)
|
||||
n, copyErr := io.Copy(out, limited)
|
||||
out.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
if n > maxFileSize {
|
||||
return fmt.Errorf("file %s exceeds maximum size", hdr.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package uidist
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCacheDir_Default(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", tmp)
|
||||
|
||||
dir := CacheDir("1.2.3")
|
||||
expected := filepath.Join(tmp, "skillshare", "ui", "1.2.3")
|
||||
if dir != expected {
|
||||
t.Errorf("got %s, want %s", dir, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsCached_Missing(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", tmp)
|
||||
|
||||
_, ok := IsCached("1.0.0")
|
||||
if ok {
|
||||
t.Error("expected IsCached to return false for missing version")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsCached_Present(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", tmp)
|
||||
|
||||
dir := filepath.Join(tmp, "skillshare", "ui", "1.0.0")
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "index.html"), []byte("<html>"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
gotDir, ok := IsCached("1.0.0")
|
||||
if !ok {
|
||||
t.Error("expected IsCached to return true")
|
||||
}
|
||||
if gotDir != dir {
|
||||
t.Errorf("got dir %s, want %s", gotDir, dir)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseChecksum(t *testing.T) {
|
||||
input := "abc123 skillshare_1.0.0_linux_amd64.tar.gz\ndef456 skillshare-ui-dist.tar.gz\n"
|
||||
hash, err := parseChecksum(strings.NewReader(input), "skillshare-ui-dist.tar.gz")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hash != "def456" {
|
||||
t.Errorf("got %s, want def456", hash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseChecksum_NotFound(t *testing.T) {
|
||||
input := "abc123 other-file.tar.gz\n"
|
||||
_, err := parseChecksum(strings.NewReader(input), "skillshare-ui-dist.tar.gz")
|
||||
if err == nil {
|
||||
t.Error("expected error for missing checksum")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarGz(t *testing.T) {
|
||||
// Create an in-memory tar.gz with test files
|
||||
tarball := createTestTarGz(t, map[string]string{
|
||||
"index.html": "<html>hello</html>",
|
||||
"assets/main.js": "console.log('hi')",
|
||||
"assets/style.css": "body {}",
|
||||
})
|
||||
|
||||
// Write to temp file
|
||||
tmpFile := filepath.Join(t.TempDir(), "test.tar.gz")
|
||||
if err := os.WriteFile(tmpFile, tarball, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Extract
|
||||
destDir := filepath.Join(t.TempDir(), "extracted")
|
||||
if err := os.MkdirAll(destDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := extractTarGz(tmpFile, destDir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Verify files exist
|
||||
for _, name := range []string{"index.html", "assets/main.js", "assets/style.css"} {
|
||||
p := filepath.Join(destDir, name)
|
||||
if _, err := os.Stat(p); err != nil {
|
||||
t.Errorf("expected file %s to exist: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify content
|
||||
data, err := os.ReadFile(filepath.Join(destDir, "index.html"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(data) != "<html>hello</html>" {
|
||||
t.Errorf("unexpected content: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarGz_RejectsPathTraversal(t *testing.T) {
|
||||
tarball := createTestTarGz(t, map[string]string{
|
||||
"../escape.txt": "nope",
|
||||
})
|
||||
|
||||
tmpFile := filepath.Join(t.TempDir(), "evil.tar.gz")
|
||||
if err := os.WriteFile(tmpFile, tarball, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
destDir := filepath.Join(t.TempDir(), "dest")
|
||||
if err := os.MkdirAll(destDir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := extractTarGz(tmpFile, destDir)
|
||||
if err == nil {
|
||||
t.Error("expected error for path traversal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearCache(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", tmp)
|
||||
|
||||
// Create fake cached version
|
||||
dir := filepath.Join(tmp, "skillshare", "ui", "1.0.0")
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "index.html"), []byte("hi"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := ClearCache(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// ui/ directory should be gone
|
||||
if _, err := os.Stat(filepath.Join(tmp, "skillshare", "ui")); !os.IsNotExist(err) {
|
||||
t.Error("expected ui cache dir to be removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearCache_NoDir(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", tmp)
|
||||
|
||||
// Should not error when nothing exists
|
||||
if err := ClearCache(); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearVersion(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", tmp)
|
||||
|
||||
// Create two versions
|
||||
for _, v := range []string{"1.0.0", "1.1.0"} {
|
||||
dir := filepath.Join(tmp, "skillshare", "ui", v)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(dir, "index.html"), []byte("hi"), 0644)
|
||||
}
|
||||
|
||||
if err := ClearVersion("1.0.0"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 1.0.0 gone, 1.1.0 still there
|
||||
if _, err := os.Stat(filepath.Join(tmp, "skillshare", "ui", "1.0.0")); !os.IsNotExist(err) {
|
||||
t.Error("expected 1.0.0 to be removed")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(tmp, "skillshare", "ui", "1.1.0")); err != nil {
|
||||
t.Error("expected 1.1.0 to still exist")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanOldVersions(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", tmp)
|
||||
|
||||
// Create three versions
|
||||
for _, v := range []string{"0.9.0", "1.0.0", "1.1.0"} {
|
||||
dir := filepath.Join(tmp, "skillshare", "ui", v)
|
||||
os.MkdirAll(dir, 0755)
|
||||
os.WriteFile(filepath.Join(dir, "index.html"), []byte("hi"), 0644)
|
||||
}
|
||||
|
||||
if err := cleanOldVersions("1.0.0"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Only 1.0.0 should remain
|
||||
entries, _ := os.ReadDir(filepath.Join(tmp, "skillshare", "ui"))
|
||||
if len(entries) != 1 || entries[0].Name() != "1.0.0" {
|
||||
names := make([]string, len(entries))
|
||||
for i, e := range entries {
|
||||
names[i] = e.Name()
|
||||
}
|
||||
t.Errorf("expected only [1.0.0], got %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
// createTestTarGz builds an in-memory tar.gz from a map of path→content.
|
||||
func createTestTarGz(t *testing.T, files map[string]string) []byte {
|
||||
t.Helper()
|
||||
|
||||
var buf bytes.Buffer
|
||||
gw := gzip.NewWriter(&buf)
|
||||
tw := tar.NewWriter(gw)
|
||||
|
||||
for name, content := range files {
|
||||
hdr := &tar.Header{
|
||||
Name: name,
|
||||
Mode: 0644,
|
||||
Size: int64(len(content)),
|
||||
}
|
||||
if err := tw.WriteHeader(hdr); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tw.Write([]byte(content)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// ParseSkillName reads the SKILL.md and extracts the "name" from frontmatter.
|
||||
@@ -57,6 +59,77 @@ func isYAMLBlockIndicator(s string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// ParseFrontmatterList reads a SKILL.md file and extracts a YAML list field from frontmatter.
|
||||
// Supports both inline [a, b] and block (- a\n- b) formats.
|
||||
// Returns nil when the field is absent or the file cannot be read.
|
||||
func ParseFrontmatterList(filePath, field string) []string {
|
||||
raw := extractFrontmatterRaw(filePath)
|
||||
if raw == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var fm map[string]any
|
||||
if err := yaml.Unmarshal([]byte(raw), &fm); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
val, ok := fm[field]
|
||||
if !ok || val == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch v := val.(type) {
|
||||
case []any:
|
||||
result := make([]string, 0, len(v))
|
||||
for _, item := range v {
|
||||
if s, ok := item.(string); ok {
|
||||
result = append(result, s)
|
||||
}
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// extractFrontmatterRaw reads the raw frontmatter text between --- delimiters.
|
||||
func extractFrontmatterRaw(filePath string) string {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
inFrontmatter := false
|
||||
var lines []string
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
trimmed := strings.TrimSpace(line)
|
||||
|
||||
if trimmed == "---" {
|
||||
if inFrontmatter {
|
||||
break
|
||||
}
|
||||
inFrontmatter = true
|
||||
continue
|
||||
}
|
||||
|
||||
if inFrontmatter {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
}
|
||||
|
||||
if len(lines) == 0 {
|
||||
return ""
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// ParseFrontmatterField reads a SKILL.md file and extracts the value of a given frontmatter field.
|
||||
// It supports both inline values and YAML block scalars (>, >-, |, |-).
|
||||
func ParseFrontmatterField(filePath, field string) string {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseFrontmatterList_InlineFormat(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "SKILL.md")
|
||||
os.WriteFile(path, []byte("---\nname: my-skill\ntargets: [claude, cursor]\n---\n# Content"), 0644)
|
||||
|
||||
result := ParseFrontmatterList(path, "targets")
|
||||
if len(result) != 2 || result[0] != "claude" || result[1] != "cursor" {
|
||||
t.Errorf("got %v, want [claude cursor]", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFrontmatterList_BlockFormat(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "SKILL.md")
|
||||
os.WriteFile(path, []byte("---\nname: my-skill\ntargets:\n - claude\n - cursor\n---\n# Content"), 0644)
|
||||
|
||||
result := ParseFrontmatterList(path, "targets")
|
||||
if len(result) != 2 || result[0] != "claude" || result[1] != "cursor" {
|
||||
t.Errorf("got %v, want [claude cursor]", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFrontmatterList_FieldAbsent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "SKILL.md")
|
||||
os.WriteFile(path, []byte("---\nname: my-skill\n---\n# Content"), 0644)
|
||||
|
||||
result := ParseFrontmatterList(path, "targets")
|
||||
if result != nil {
|
||||
t.Errorf("got %v, want nil", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFrontmatterList_EmptyList(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "SKILL.md")
|
||||
os.WriteFile(path, []byte("---\nname: my-skill\ntargets: []\n---\n# Content"), 0644)
|
||||
|
||||
result := ParseFrontmatterList(path, "targets")
|
||||
if result != nil {
|
||||
t.Errorf("got %v, want nil", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFrontmatterList_FileNotFound(t *testing.T) {
|
||||
result := ParseFrontmatterList("/nonexistent/SKILL.md", "targets")
|
||||
if result != nil {
|
||||
t.Errorf("got %v, want nil", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFrontmatterList_NoFrontmatter(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "SKILL.md")
|
||||
os.WriteFile(path, []byte("# Just content, no frontmatter"), 0644)
|
||||
|
||||
result := ParseFrontmatterList(path, "targets")
|
||||
if result != nil {
|
||||
t.Errorf("got %v, want nil", result)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/config"
|
||||
)
|
||||
|
||||
// Version is set by main.go at startup
|
||||
@@ -31,27 +33,9 @@ type CheckResult struct {
|
||||
UpdateAvailable bool
|
||||
}
|
||||
|
||||
// getCacheDir returns the cache directory, respecting XDG_CACHE_HOME
|
||||
func getCacheDir() (string, error) {
|
||||
// XDG Base Directory Specification: use XDG_CACHE_HOME if set
|
||||
if cacheHome := os.Getenv("XDG_CACHE_HOME"); cacheHome != "" {
|
||||
return filepath.Join(cacheHome, "skillshare"), nil
|
||||
}
|
||||
// Default: ~/.cache/skillshare
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(homeDir, ".cache", "skillshare"), nil
|
||||
}
|
||||
|
||||
// getCachePath returns the path to the cache file
|
||||
func getCachePath() (string, error) {
|
||||
cacheDir, err := getCacheDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(cacheDir, cacheFileName), nil
|
||||
func getCachePath() string {
|
||||
return filepath.Join(config.CacheDir(), cacheFileName)
|
||||
}
|
||||
|
||||
// legacyCachePath returns the old cache path for migration cleanup
|
||||
@@ -73,11 +57,7 @@ func cleanupLegacyCache() {
|
||||
|
||||
// ClearCache removes the version check cache file
|
||||
func ClearCache() {
|
||||
cachePath, err := getCachePath()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
os.Remove(cachePath)
|
||||
os.Remove(getCachePath())
|
||||
}
|
||||
|
||||
// GetCachedVersion returns the cached latest version if available
|
||||
@@ -91,12 +71,7 @@ func GetCachedVersion() string {
|
||||
|
||||
// loadCache loads the version check cache from disk
|
||||
func loadCache() (*Cache, error) {
|
||||
cachePath, err := getCachePath()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(cachePath)
|
||||
data, err := os.ReadFile(getCachePath())
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil // No cache yet
|
||||
@@ -114,10 +89,7 @@ func loadCache() (*Cache, error) {
|
||||
|
||||
// saveCache saves the version check cache to disk
|
||||
func saveCache(cache *Cache) error {
|
||||
cachePath, err := getCachePath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cachePath := getCachePath()
|
||||
|
||||
// Ensure directory exists
|
||||
if err := os.MkdirAll(filepath.Dir(cachePath), 0755); err != nil {
|
||||
|
||||
@@ -64,6 +64,16 @@ func BuildDownloadURL(version string) (string, error) {
|
||||
return url, nil
|
||||
}
|
||||
|
||||
// BuildUIDistURL constructs the direct download URL for the UI dist tarball
|
||||
func BuildUIDistURL(ver string) string {
|
||||
return fmt.Sprintf("https://github.com/%s/releases/download/v%s/skillshare-ui-dist.tar.gz", githubRepo, ver)
|
||||
}
|
||||
|
||||
// BuildChecksumsURL constructs the direct download URL for the checksums file
|
||||
func BuildChecksumsURL(ver string) string {
|
||||
return fmt.Sprintf("https://github.com/%s/releases/download/v%s/checksums.txt", githubRepo, ver)
|
||||
}
|
||||
|
||||
// newGitHubClient creates an HTTP client with optional auth
|
||||
func newGitHubClient() *http.Client {
|
||||
return &http.Client{Timeout: 10 * time.Second}
|
||||
|
||||
@@ -30,21 +30,15 @@ echo " mise run fmt # format Go files"
|
||||
echo " mise run fmt:check # verify formatting only"
|
||||
echo " mise run check # fmt:check + lint + test"
|
||||
echo " mise run ui:install # install frontend dependencies"
|
||||
echo " mise run ui:build # build frontend + copy to embed"
|
||||
echo " mise run ui:build # build frontend"
|
||||
echo " mise run ui:dev # Go API server + Vite dev server (requires local Go)"
|
||||
echo " mise run build:all # ui:build + build (full binary)"
|
||||
echo " mise run build:all # ui:build + build"
|
||||
echo " mise run clean # remove build artifacts"
|
||||
"""
|
||||
|
||||
[tasks.build]
|
||||
description = "Build the skillshare binary"
|
||||
run = """
|
||||
if [ ! -f internal/server/dist/index.html ]; then
|
||||
mkdir -p internal/server/dist
|
||||
printf '<!DOCTYPE html><html><body><h1>UI not built</h1><p>Run: mise run build:all</p></body></html>' > internal/server/dist/index.html
|
||||
fi
|
||||
mkdir -p bin && go build -o bin/skillshare ./cmd/skillshare
|
||||
"""
|
||||
run = "mkdir -p bin && go build -o bin/skillshare ./cmd/skillshare"
|
||||
|
||||
[tasks."build:meta"]
|
||||
description = "Build with version metadata"
|
||||
@@ -148,19 +142,15 @@ description = "Install frontend dependencies"
|
||||
run = "cd ui && pnpm install"
|
||||
|
||||
[tasks."ui:build"]
|
||||
description = "Build frontend and copy to embed directory"
|
||||
description = "Build frontend"
|
||||
depends = ["ui:install"]
|
||||
run = """
|
||||
(cd ui && pnpm run build)
|
||||
rm -rf internal/server/dist
|
||||
cp -r ui/dist internal/server/dist
|
||||
"""
|
||||
run = "cd ui && pnpm run build"
|
||||
|
||||
[tasks."ui:dev"]
|
||||
description = "Go API server + Vite dev server"
|
||||
run = """
|
||||
trap 'kill 0' EXIT
|
||||
go run -tags dev ./cmd/skillshare ui --no-open &
|
||||
go run ./cmd/skillshare ui --no-open &
|
||||
cd ui && pnpm run dev
|
||||
"""
|
||||
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
---
|
||||
name: skillshare
|
||||
version: 0.11.7
|
||||
version: 0.13.0
|
||||
description: |
|
||||
Syncs skills across AI CLI tools (Claude, Cursor, Windsurf, etc.) from a single source of truth.
|
||||
Global mode (~/.config/skillshare/) and project mode (.skillshare/ per-repo).
|
||||
Commands: status, sync, install, uninstall, update, check, search, new, collect,
|
||||
push, pull, diff, list, doctor, audit, init-rules, trash, log, backup, restore, target, ui, upgrade.
|
||||
Features: target-level skill filtering (include/exclude), skill-level targets field,
|
||||
XDG Base Directory support, fuzzy subdirectory resolution for monorepo installs.
|
||||
Use when: managing skills across AI tools, "skillshare" CLI, skill sync/install/search,
|
||||
project skills setup, security audit, web dashboard, or troubleshooting.
|
||||
project skills setup, target filtering, security audit, web dashboard, or troubleshooting.
|
||||
argument-hint: "[command] [target] [--dry-run] [-p|-g]"
|
||||
---
|
||||
|
||||
@@ -50,7 +52,7 @@ AI cannot respond to CLI prompts. Always pass flags to skip interactive prompts.
|
||||
```bash
|
||||
# Key non-interactive patterns
|
||||
skillshare init --no-copy --all-targets --git --skill # Global fresh start
|
||||
skillshare init -p --targets "claude-code,cursor" # Project init
|
||||
skillshare init -p --targets "claude,cursor" # Project init
|
||||
skillshare install user/repo --all # Install all skills
|
||||
skillshare install user/repo -s pdf,commit # Select specific
|
||||
```
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
| Wrong mode detected | Use `-p` (project) or `-g` (global) to force |
|
||||
| Custom audit rules not applying | Verify `audit-rules.yaml` path: global (`~/.config/skillshare/`) or project (`.skillshare/`). Run `skillshare audit --init-rules` to create template |
|
||||
| Nested skill not found | `update`/`uninstall` resolve short names — e.g., `skillshare update vue` finds `frontend/vue/vue-best-practices`. Use full path if ambiguous |
|
||||
| Config in wrong location | Skillshare respects `$XDG_CONFIG_HOME`. If set, config is at `$XDG_CONFIG_HOME/skillshare/`. Otherwise `~/.config/skillshare/` |
|
||||
| Skill not syncing to target | Check target filters (`target <name>`) and skill-level `targets` field in SKILL.md. Both can restrict which skills sync where |
|
||||
| Old project target names | Old names like `claude-code` still work as aliases. New canonical name is `claude` |
|
||||
|
||||
## Diagnostic Commands
|
||||
|
||||
@@ -77,7 +80,7 @@ AI cannot respond to CLI prompts. Always use flags:
|
||||
```bash
|
||||
# Good (non-interactive)
|
||||
skillshare init --copy-from claude --all-targets --git
|
||||
skillshare init -p --targets "claude-code,cursor"
|
||||
skillshare init -p --targets "claude,cursor"
|
||||
skillshare uninstall my-skill --force
|
||||
skillshare uninstall my-skill --force -p
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ Initialize skillshare configuration (global or project).
|
||||
|
||||
## Global Init
|
||||
|
||||
**Source:** Always `~/.config/skillshare/skills` (use `--source` only if user explicitly requests).
|
||||
**Source:** `~/.config/skillshare/skills` by default. Respects `$XDG_CONFIG_HOME` — if set, uses `$XDG_CONFIG_HOME/skillshare/skills`. Use `--source` only if user explicitly requests a custom path.
|
||||
|
||||
### Flags
|
||||
|
||||
@@ -58,7 +58,7 @@ Creates `.skillshare/` in current directory with `config.yaml`, `.gitignore`, an
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `-p, --project` | Enable project mode |
|
||||
| `--targets "claude-code,cursor"` | Specific targets (non-interactive) |
|
||||
| `--targets "claude,cursor"` | Specific targets (non-interactive) |
|
||||
| `--discover` | Discover new AI tools |
|
||||
| `--discover --select "a,b"` | Non-interactive discovery |
|
||||
| `--dry-run, -n` | Preview changes |
|
||||
@@ -69,7 +69,7 @@ Creates `.skillshare/` in current directory with `config.yaml`, `.gitignore`, an
|
||||
|
||||
```bash
|
||||
# Initialize with specific targets
|
||||
skillshare init -p --targets "claude-code,cursor"
|
||||
skillshare init -p --targets "claude,cursor"
|
||||
|
||||
# Verify
|
||||
skillshare status
|
||||
|
||||
@@ -12,6 +12,7 @@ Install skills from local path or git repository.
|
||||
# GitHub shorthand
|
||||
user/repo # Browse repo for skills
|
||||
user/repo/path/to/skill # Direct path
|
||||
user/repo/skill-name # Fuzzy resolve (finds nested skill by name)
|
||||
|
||||
# GitLab / Bitbucket / other hosts
|
||||
gitlab.com/user/repo # GitLab shorthand
|
||||
@@ -71,6 +72,8 @@ skillshare install user/repo --skip-audit # Skip security scan
|
||||
| `--skip-audit` | Skip security audit for this install |
|
||||
| `--dry-run, -n` | Preview |
|
||||
|
||||
**Fuzzy subdirectory resolution:** When a monorepo has nested skill directories, you can specify just the skill name — e.g., `user/repo/vue-best-practices` finds `skills/vue-best-practices/` automatically. Fails with an error if multiple matches exist.
|
||||
|
||||
**Tracked repos:** Prefixed with `_`, nested with `__` (e.g., `_team__frontend__ui`).
|
||||
|
||||
**Project `install -p` (no source):** Installs all remote skills listed in `.skillshare/config.yaml`. Useful for new team members.
|
||||
@@ -81,7 +84,7 @@ skillshare install user/repo --skip-audit # Skip security scan
|
||||
|
||||
## check
|
||||
|
||||
Check for available updates without applying changes.
|
||||
Check for available updates and validate skill metadata.
|
||||
|
||||
```bash
|
||||
skillshare check # Show update status for all repos/skills
|
||||
@@ -92,6 +95,7 @@ skillshare check -p # Check project skills
|
||||
- **Tracked repos:** Fetches from origin, shows commits behind
|
||||
- **Remote skills:** Compares installed version with remote HEAD
|
||||
- **Local skills:** Shown as "local source"
|
||||
- **Targets validation:** Warns about unknown target names in skill-level `targets` field
|
||||
|
||||
## update
|
||||
|
||||
|
||||
@@ -20,21 +20,26 @@ Project mode output includes: source path, targets with sync mode, remote skills
|
||||
Show differences between source and targets.
|
||||
|
||||
```bash
|
||||
skillshare diff # All targets
|
||||
skillshare diff # All targets (auto-detects mode)
|
||||
skillshare diff claude # Specific target
|
||||
skillshare diff -p # Project mode
|
||||
skillshare diff -g # Force global
|
||||
```
|
||||
|
||||
Project mode shows filter info and skill-level target restrictions.
|
||||
|
||||
## list
|
||||
|
||||
List installed skills.
|
||||
List installed skills, grouped by directory.
|
||||
|
||||
```bash
|
||||
skillshare list # Auto-detects mode
|
||||
skillshare list --verbose # With source info
|
||||
skillshare list # Auto-detects mode (grouped display)
|
||||
skillshare list --verbose # With source URL, install date, tracked info
|
||||
skillshare list -v # Short form of --verbose
|
||||
skillshare list -g # Force global
|
||||
```
|
||||
|
||||
Project mode shows local vs remote skills.
|
||||
Skills organized in subdirectories are displayed in groups. Tracked repos shown in a dedicated section with skill counts. Project mode shows local vs remote skills.
|
||||
|
||||
## search
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ skillshare collect --all # From all targets
|
||||
skillshare collect --dry-run # Preview
|
||||
|
||||
# Project (auto-detected or -p)
|
||||
skillshare collect claude-code # From project target
|
||||
skillshare collect claude # From project target
|
||||
skillshare collect --all # All project targets
|
||||
skillshare collect --all --force # Skip confirmation
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Target Management
|
||||
|
||||
Manage AI CLI tool targets (Claude, Cursor, Windsurf, etc.). Skillshare supports 46+ built-in targets.
|
||||
Manage AI CLI tool targets (Claude, Cursor, Windsurf, etc.). Skillshare supports 48+ built-in targets.
|
||||
|
||||
## Global Targets
|
||||
|
||||
@@ -15,7 +15,7 @@ skillshare target remove myapp # Remove target (safe)
|
||||
|
||||
```bash
|
||||
skillshare target list -p # List project targets
|
||||
skillshare target claude-code -p # Show project target info
|
||||
skillshare target claude -p # Show project target info
|
||||
skillshare target add windsurf -p # Add known target
|
||||
skillshare target add custom-tool ./tools/skills -p # Add custom path (relative)
|
||||
skillshare target remove windsurf -p # Remove project target
|
||||
@@ -25,7 +25,7 @@ skillshare target remove windsurf -p # Remove project target
|
||||
|
||||
```yaml
|
||||
targets:
|
||||
- claude-code # Short: known target, merge mode
|
||||
- claude # Short: known target, merge mode
|
||||
- name: cursor # Long: with explicit mode
|
||||
mode: symlink
|
||||
- name: custom-ide # Long: with custom path
|
||||
@@ -33,6 +33,50 @@ targets:
|
||||
mode: merge
|
||||
```
|
||||
|
||||
## Target Filters
|
||||
|
||||
Control which skills sync to each target using include/exclude glob patterns.
|
||||
|
||||
```bash
|
||||
# Add filters
|
||||
skillshare target claude --add-include "team-*" # Only sync matching skills
|
||||
skillshare target claude --add-exclude "_legacy*" # Skip matching skills
|
||||
skillshare target claude --add-include "team-*" -p # Project target filter
|
||||
|
||||
# Remove filters
|
||||
skillshare target claude --remove-include "team-*"
|
||||
skillshare target claude --remove-exclude "_legacy*"
|
||||
```
|
||||
|
||||
**Config format** with filters:
|
||||
|
||||
```yaml
|
||||
targets:
|
||||
- name: claude
|
||||
include: ["team-*", "core-*"]
|
||||
exclude: ["_legacy*"]
|
||||
- cursor # No filters = sync all skills
|
||||
```
|
||||
|
||||
**Pattern syntax:** `filepath.Match` globs — `*` matches any non-separator chars, `?` matches single char.
|
||||
|
||||
**Precedence:** Include filters apply first (whitelist), then exclude filters remove from that set. No filters = all skills.
|
||||
|
||||
## Skill-Level Targets
|
||||
|
||||
Skills can declare which targets they should sync to via a `targets` frontmatter field in SKILL.md:
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: enterprise-skill
|
||||
targets: [claude, cursor]
|
||||
---
|
||||
```
|
||||
|
||||
- Skills **without** `targets` sync to all targets (backward compatible)
|
||||
- `check` warns about unknown target names in the `targets` field
|
||||
- Works with both global and project mode target names
|
||||
|
||||
## Sync Modes
|
||||
|
||||
Per-target mode (both global and project):
|
||||
@@ -40,7 +84,7 @@ Per-target mode (both global and project):
|
||||
```bash
|
||||
skillshare target claude --mode merge # Per-skill symlinks (default)
|
||||
skillshare target claude --mode symlink # Entire dir symlinked
|
||||
skillshare target claude-code --mode symlink -p # Project target mode
|
||||
skillshare target claude --mode symlink -p # Project target mode
|
||||
```
|
||||
|
||||
| Mode | Description | Local Skills |
|
||||
@@ -48,6 +92,10 @@ skillshare target claude-code --mode symlink -p # Project target mode
|
||||
| `merge` | Individual symlinks per skill | Preserved |
|
||||
| `symlink` | Single symlink for entire dir | Not possible |
|
||||
|
||||
## Unified Target Names
|
||||
|
||||
Global and project modes use the **same short names** (e.g., `claude`, `cursor`, `windsurf`). Old project-only names (e.g., `claude-code`) are supported as aliases for backward compatibility.
|
||||
|
||||
## Safety
|
||||
|
||||
**Always use** `target remove` to unlink targets.
|
||||
|
||||
@@ -204,10 +204,10 @@ audit:
|
||||
func TestInstall_ProjectBlockThresholdHigh_BlocksHighFinding(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- claude-code
|
||||
- claude
|
||||
audit:
|
||||
block_threshold: HIGH
|
||||
`)
|
||||
@@ -361,7 +361,7 @@ func copyDirRecursive(t *testing.T, src, dst string) {
|
||||
func TestAudit_Project(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Create a skill in project
|
||||
projectSkills := filepath.Join(projectRoot, ".skillshare", "skills")
|
||||
@@ -439,7 +439,7 @@ func TestAudit_CustomRules_DisableBuiltin(t *testing.T) {
|
||||
func TestAudit_ProjectCustomRules(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Create a skill with "FIXME"
|
||||
projectSkills := filepath.Join(projectRoot, ".skillshare", "skills")
|
||||
@@ -488,7 +488,7 @@ func TestAudit_InitRules_Global(t *testing.T) {
|
||||
func TestAudit_InitRules_Project(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "audit", "-p", "--init-rules")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
@@ -48,7 +48,7 @@ targets:
|
||||
backupResult.AssertSuccess(t)
|
||||
|
||||
// Verify backup contains local skill but not the symlinked one
|
||||
backupDir := filepath.Join(sb.Home, ".config", "skillshare", "backups")
|
||||
backupDir := filepath.Join(sb.Home, ".local", "share", "skillshare", "backups")
|
||||
entries, err := os.ReadDir(backupDir)
|
||||
if err != nil || len(entries) == 0 {
|
||||
t.Fatal("backup directory should contain a timestamp directory")
|
||||
@@ -233,7 +233,7 @@ targets:
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "Dry run")
|
||||
|
||||
backupDir := filepath.Join(sb.Home, ".config", "skillshare", "backups")
|
||||
backupDir := filepath.Join(sb.Home, ".local", "share", "skillshare", "backups")
|
||||
entries, err := os.ReadDir(backupDir)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read backup dir: %v", err)
|
||||
@@ -251,7 +251,7 @@ func TestBackup_CleanupDryRun_DoesNotRemoveBackups(t *testing.T) {
|
||||
targets: {}
|
||||
`)
|
||||
|
||||
backupRoot := filepath.Join(sb.Home, ".config", "skillshare", "backups")
|
||||
backupRoot := filepath.Join(sb.Home, ".local", "share", "skillshare", "backups")
|
||||
timestampDir := filepath.Join(backupRoot, "2024-01-01_00-00-00")
|
||||
backupPath := filepath.Join(timestampDir, "claude", "old-skill")
|
||||
os.MkdirAll(backupPath, 0755)
|
||||
|
||||
@@ -14,7 +14,7 @@ func TestCollectProject_FindsLocalSkills(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Place a local (non-symlinked) skill in the target
|
||||
targetSkillDir := filepath.Join(projectRoot, ".claude", "skills", "local-skill")
|
||||
@@ -31,7 +31,7 @@ func TestCollectProject_DryRun(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sourcePath := filepath.Join(projectRoot, ".skillshare", "skills")
|
||||
|
||||
// Place a local skill in the target
|
||||
@@ -54,7 +54,7 @@ func TestCollectProject_Force(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sourcePath := filepath.Join(projectRoot, ".skillshare", "skills")
|
||||
|
||||
// Create existing skill in source
|
||||
@@ -86,7 +86,7 @@ func TestCollectProject_NoLocalSkills(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Create a skill in source and symlink it (no local skills)
|
||||
sb.CreateProjectSkill(projectRoot, "synced-skill", map[string]string{"SKILL.md": "# Synced"})
|
||||
|
||||
@@ -339,7 +339,7 @@ func TestDoctor_ProjectMode_AutoDetectsProjectConfig(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "project-skill", map[string]string{"SKILL.md": "# Project Skill"})
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "doctor")
|
||||
@@ -355,7 +355,7 @@ func TestDoctor_ProjectMode_WithFlagUsesProjectConfig(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "project-skill", map[string]string{"SKILL.md": "# Project Skill"})
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "doctor", "-p")
|
||||
|
||||
@@ -158,11 +158,11 @@ func TestExclude_ProjectMerge_SkipsExcludedOnFirstSync(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "keep-me", map[string]string{"SKILL.md": "# Keep"})
|
||||
sb.CreateProjectSkill(projectRoot, "exclude-me", map[string]string{"SKILL.md": "# Exclude"})
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- name: claude-code
|
||||
- name: claude
|
||||
exclude: [exclude-*]
|
||||
`)
|
||||
|
||||
@@ -182,19 +182,19 @@ func TestExclude_ProjectMerge_RemovesExistingSourceLink(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "keep-me", map[string]string{"SKILL.md": "# Keep"})
|
||||
sb.CreateProjectSkill(projectRoot, "exclude-me", map[string]string{"SKILL.md": "# Exclude"})
|
||||
|
||||
// First sync without filters.
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- claude-code
|
||||
- claude
|
||||
`)
|
||||
sb.RunCLIInDir(projectRoot, "sync", "-p").AssertSuccess(t)
|
||||
|
||||
// Add exclude and sync again.
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- name: claude-code
|
||||
- name: claude
|
||||
exclude: [exclude-*]
|
||||
`)
|
||||
result := sb.RunCLIInDir(projectRoot, "sync", "-p")
|
||||
@@ -213,10 +213,10 @@ func TestExclude_ProjectMerge_PreservesLocalDirectory(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "exclude-me", map[string]string{"SKILL.md": "# Source"})
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- name: claude-code
|
||||
- name: claude
|
||||
exclude: [exclude-*]
|
||||
`)
|
||||
|
||||
@@ -244,10 +244,10 @@ func TestExclude_ProjectMerge_InvalidExcludePatternFails(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "skill-a", map[string]string{"SKILL.md": "# Skill"})
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- name: claude-code
|
||||
- name: claude
|
||||
exclude: ["["]
|
||||
`)
|
||||
|
||||
@@ -400,17 +400,17 @@ func TestInclude_ProjectMerge_RemovesExistingSourceLinkOutsideInclude(t *testing
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "include-me", map[string]string{"SKILL.md": "# Include"})
|
||||
sb.CreateProjectSkill(projectRoot, "other-skill", map[string]string{"SKILL.md": "# Other"})
|
||||
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- claude-code
|
||||
- claude
|
||||
`)
|
||||
sb.RunCLIInDir(projectRoot, "sync", "-p").AssertSuccess(t)
|
||||
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- name: claude-code
|
||||
- name: claude
|
||||
include: [include-*]
|
||||
`)
|
||||
result := sb.RunCLIInDir(projectRoot, "sync", "-p")
|
||||
@@ -429,11 +429,11 @@ func TestInclude_ProjectMerge_PreservesLocalDirectoryOutsideInclude(t *testing.T
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "include-me", map[string]string{"SKILL.md": "# Include"})
|
||||
sb.CreateProjectSkill(projectRoot, "other-skill", map[string]string{"SKILL.md": "# Source"})
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- name: claude-code
|
||||
- name: claude
|
||||
include: [include-*]
|
||||
`)
|
||||
|
||||
@@ -515,18 +515,18 @@ func TestIncludeExclude_ProjectMerge_PrecedenceAndRemoval(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "app-main", map[string]string{"SKILL.md": "# Main"})
|
||||
sb.CreateProjectSkill(projectRoot, "app-beta", map[string]string{"SKILL.md": "# Beta"})
|
||||
sb.CreateProjectSkill(projectRoot, "tool-main", map[string]string{"SKILL.md": "# Tool"})
|
||||
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- claude-code
|
||||
- claude
|
||||
`)
|
||||
sb.RunCLIInDir(projectRoot, "sync", "-p").AssertSuccess(t)
|
||||
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- name: claude-code
|
||||
- name: claude
|
||||
include: [app-*]
|
||||
exclude: ["*-beta"]
|
||||
`)
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
func TestGitignoreProject_InstallAddsEntry(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
sourceSkill := filepath.Join(sb.Root, "ext")
|
||||
os.MkdirAll(sourceSkill, 0755)
|
||||
@@ -35,7 +35,7 @@ func TestGitignoreProject_InstallAddsEntry(t *testing.T) {
|
||||
func TestGitignoreProject_UninstallRemovesEntry(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Create remote skill with meta
|
||||
skillDir := sb.CreateProjectSkill(projectRoot, "removable", map[string]string{
|
||||
@@ -50,7 +50,7 @@ func TestGitignoreProject_UninstallRemovesEntry(t *testing.T) {
|
||||
"# BEGIN SKILLSHARE MANAGED - DO NOT EDIT\nskills/removable/\n# END SKILLSHARE MANAGED\n")
|
||||
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- claude-code
|
||||
- claude
|
||||
skills:
|
||||
- name: removable
|
||||
source: org/removable
|
||||
@@ -67,7 +67,7 @@ skills:
|
||||
func TestGitignoreProject_PreservesUserEntries(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Write gitignore with user entries
|
||||
sb.WriteFile(filepath.Join(projectRoot, ".skillshare", ".gitignore"),
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestInitProject_Fresh_CreatesStructure(t *testing.T) {
|
||||
projectRoot := filepath.Join(sb.Root, "project")
|
||||
os.MkdirAll(projectRoot, 0755)
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude-code,cursor")
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude,cursor")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "Initialized successfully")
|
||||
|
||||
@@ -45,8 +45,8 @@ func TestInitProject_AlreadyInitialized_Error(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude")
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "already initialized")
|
||||
}
|
||||
@@ -58,7 +58,7 @@ func TestInitProject_DryRun_NoFiles(t *testing.T) {
|
||||
projectRoot := filepath.Join(sb.Root, "project")
|
||||
os.MkdirAll(projectRoot, 0755)
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude-code", "--dry-run")
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude", "--dry-run")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "Dry run")
|
||||
|
||||
@@ -74,12 +74,12 @@ func TestInitProject_ConfigContainsTargets(t *testing.T) {
|
||||
projectRoot := filepath.Join(sb.Root, "project")
|
||||
os.MkdirAll(projectRoot, 0755)
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude-code,cursor")
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude,cursor")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
cfg := sb.ReadFile(filepath.Join(projectRoot, ".skillshare", "config.yaml"))
|
||||
if !strings.Contains(cfg, "claude-code") {
|
||||
t.Error("config should contain claude-code target")
|
||||
if !strings.Contains(cfg, "claude") {
|
||||
t.Error("config should contain claude target")
|
||||
}
|
||||
if !strings.Contains(cfg, "cursor") {
|
||||
t.Error("config should contain cursor target")
|
||||
@@ -93,7 +93,7 @@ func TestInitProject_GitignoreIncludesLogsDirectory(t *testing.T) {
|
||||
projectRoot := filepath.Join(sb.Root, "project")
|
||||
os.MkdirAll(projectRoot, 0755)
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude-code")
|
||||
result := sb.RunCLIInDir(projectRoot, "init", "-p", "--targets", "claude")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
gitignore := sb.ReadFile(filepath.Join(projectRoot, ".skillshare", ".gitignore"))
|
||||
|
||||
@@ -107,7 +107,7 @@ targets: {}
|
||||
func TestInstallProject_Into(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Create a source skill to install
|
||||
sourceSkill := filepath.Join(sb.Root, "my-skill")
|
||||
@@ -138,7 +138,7 @@ func TestInstallProject_Into(t *testing.T) {
|
||||
func TestInstallProject_Into_NoSource_Rejected(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// --into without source should fail
|
||||
result := sb.RunCLIInDir(projectRoot, "install", "--into", "tools", "-p")
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
func TestInstallProject_LocalPath(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Create a source skill to install from
|
||||
sourceSkill := filepath.Join(sb.Root, "external-skill")
|
||||
@@ -32,7 +32,7 @@ func TestInstallProject_LocalPath(t *testing.T) {
|
||||
func TestInstallProject_CustomName(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
sourceSkill := filepath.Join(sb.Root, "my-source")
|
||||
os.MkdirAll(sourceSkill, 0755)
|
||||
@@ -49,7 +49,7 @@ func TestInstallProject_CustomName(t *testing.T) {
|
||||
func TestInstallProject_DryRun(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
sourceSkill := filepath.Join(sb.Root, "dry-skill")
|
||||
os.MkdirAll(sourceSkill, 0755)
|
||||
@@ -66,7 +66,7 @@ func TestInstallProject_DryRun(t *testing.T) {
|
||||
func TestInstallProject_TrackRequiresGitSource(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// --track with a non-git source should fail with git-related error
|
||||
result := sb.RunCLIInDir(projectRoot, "install", "/some/path", "--track", "-p")
|
||||
@@ -77,7 +77,7 @@ func TestInstallProject_TrackRequiresGitSource(t *testing.T) {
|
||||
func TestInstallProject_FromConfig_SkipsExisting(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Create an already-installed skill
|
||||
sb.CreateProjectSkill(projectRoot, "already-here", map[string]string{
|
||||
@@ -86,7 +86,7 @@ func TestInstallProject_FromConfig_SkipsExisting(t *testing.T) {
|
||||
|
||||
// Write config referencing it
|
||||
sb.WriteProjectConfig(projectRoot, `targets:
|
||||
- claude-code
|
||||
- claude
|
||||
skills:
|
||||
- name: already-here
|
||||
source: someone/skills/already-here
|
||||
@@ -101,7 +101,7 @@ skills:
|
||||
func TestInstallProject_FromConfig_EmptySkills(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "install", "-p")
|
||||
result.AssertSuccess(t)
|
||||
@@ -111,7 +111,7 @@ func TestInstallProject_FromConfig_EmptySkills(t *testing.T) {
|
||||
func TestInstallProject_NoSource_WithName_Errors(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "install", "-p", "--name", "custom")
|
||||
result.AssertFailure(t)
|
||||
|
||||
@@ -1218,3 +1218,132 @@ func TestInstall_SkillAndTrackConflict(t *testing.T) {
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "--skill cannot be used with --track")
|
||||
}
|
||||
|
||||
// TestInstall_SubdirFuzzyResolve tests that when a subdir doesn't exist at the
|
||||
// exact path, the installer scans the repo for a matching skill by basename.
|
||||
// e.g. "owner/repo/pdf" where "pdf" lives at "skills/pdf/SKILL.md".
|
||||
func TestInstall_SubdirFuzzyResolve(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
// Create a git repo where skills live under a skills/ prefix
|
||||
gitRepoPath := filepath.Join(sb.Root, "fuzzy-repo")
|
||||
skillPath := filepath.Join(gitRepoPath, "skills", "pdf")
|
||||
os.MkdirAll(skillPath, 0755)
|
||||
os.WriteFile(filepath.Join(skillPath, "SKILL.md"), []byte("# PDF Skill"), 0644)
|
||||
|
||||
// Initialize git repo
|
||||
cmd := exec.Command("git", "init")
|
||||
cmd.Dir = gitRepoPath
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Skip("git not available, skipping git test")
|
||||
}
|
||||
|
||||
for _, c := range [][]string{
|
||||
{"config", "user.email", "test@test.com"},
|
||||
{"config", "user.name", "Test"},
|
||||
{"add", "."},
|
||||
{"commit", "-m", "Initial commit"},
|
||||
} {
|
||||
cmd = exec.Command("git", c...)
|
||||
cmd.Dir = gitRepoPath
|
||||
cmd.Run()
|
||||
}
|
||||
|
||||
// Construct source with subdir "pdf" (simulates GitHub URL like owner/repo/pdf)
|
||||
source := &install.Source{
|
||||
Type: install.SourceTypeGitHTTPS,
|
||||
Raw: "file://" + gitRepoPath + "/pdf",
|
||||
CloneURL: "file://" + gitRepoPath,
|
||||
Subdir: "pdf",
|
||||
Name: "pdf",
|
||||
}
|
||||
|
||||
destPath := filepath.Join(sb.SourcePath, "pdf")
|
||||
result, err := install.Install(source, destPath, install.InstallOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("Install() error = %v", err)
|
||||
}
|
||||
|
||||
if result.Action != "cloned and extracted" {
|
||||
t.Errorf("Action = %q, want %q", result.Action, "cloned and extracted")
|
||||
}
|
||||
|
||||
// Verify skill was installed
|
||||
if !sb.FileExists(filepath.Join(sb.SourcePath, "pdf", "SKILL.md")) {
|
||||
t.Error("pdf skill should be installed via fuzzy subdir resolution")
|
||||
}
|
||||
|
||||
// Verify content is correct
|
||||
content := sb.ReadFile(filepath.Join(sb.SourcePath, "pdf", "SKILL.md"))
|
||||
if !strings.Contains(content, "PDF Skill") {
|
||||
t.Error("installed skill should have correct content")
|
||||
}
|
||||
}
|
||||
|
||||
// TestInstall_SubdirFuzzyResolve_Discovery tests fuzzy resolution through the
|
||||
// DiscoverFromGitSubdir path (multi-skill subdir with discovery).
|
||||
func TestInstall_SubdirFuzzyResolve_Discovery(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
// Create a git repo: skills/frontend/SKILL.md + skills/frontend/child-a/SKILL.md
|
||||
gitRepoPath := filepath.Join(sb.Root, "fuzzy-discover-repo")
|
||||
parentPath := filepath.Join(gitRepoPath, "skills", "frontend")
|
||||
childPath := filepath.Join(parentPath, "child-a")
|
||||
os.MkdirAll(parentPath, 0755)
|
||||
os.MkdirAll(childPath, 0755)
|
||||
os.WriteFile(filepath.Join(parentPath, "SKILL.md"), []byte("# Frontend"), 0644)
|
||||
os.WriteFile(filepath.Join(childPath, "SKILL.md"), []byte("# Child A"), 0644)
|
||||
|
||||
cmd := exec.Command("git", "init")
|
||||
cmd.Dir = gitRepoPath
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Skip("git not available, skipping git test")
|
||||
}
|
||||
|
||||
for _, c := range [][]string{
|
||||
{"config", "user.email", "test@test.com"},
|
||||
{"config", "user.name", "Test"},
|
||||
{"add", "."},
|
||||
{"commit", "-m", "Initial commit"},
|
||||
} {
|
||||
cmd = exec.Command("git", c...)
|
||||
cmd.Dir = gitRepoPath
|
||||
cmd.Run()
|
||||
}
|
||||
|
||||
// Construct source with subdir "frontend" (simulates GitHub URL like owner/repo/frontend)
|
||||
source := &install.Source{
|
||||
Type: install.SourceTypeGitHTTPS,
|
||||
Raw: "file://" + gitRepoPath + "/frontend",
|
||||
CloneURL: "file://" + gitRepoPath,
|
||||
Subdir: "frontend",
|
||||
Name: "frontend",
|
||||
}
|
||||
|
||||
discovery, err := install.DiscoverFromGitSubdir(source)
|
||||
if err != nil {
|
||||
t.Fatalf("DiscoverFromGitSubdir() error = %v", err)
|
||||
}
|
||||
defer install.CleanupDiscovery(discovery)
|
||||
|
||||
if len(discovery.Skills) == 0 {
|
||||
t.Fatal("expected at least 1 skill discovered")
|
||||
}
|
||||
|
||||
// Should find the root skill of the subdir + child
|
||||
var foundRoot bool
|
||||
for _, sk := range discovery.Skills {
|
||||
if sk.Path == "." {
|
||||
foundRoot = true
|
||||
}
|
||||
}
|
||||
if !foundRoot {
|
||||
t.Error("expected root skill of resolved subdir to be discovered")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
func TestListProject_ShowsLocalAndRemote(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Local skill (no meta)
|
||||
sb.CreateProjectSkill(projectRoot, "local-skill", map[string]string{
|
||||
@@ -43,7 +43,7 @@ func TestListProject_ShowsLocalAndRemote(t *testing.T) {
|
||||
func TestListProject_Empty(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "list", "-p")
|
||||
result.AssertSuccess(t)
|
||||
@@ -53,7 +53,7 @@ func TestListProject_Empty(t *testing.T) {
|
||||
func TestListProject_TrackedRepo_ShowsSkills(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Simulate a tracked repo with skills inside hidden directories (like openai/skills)
|
||||
skillsDir := filepath.Join(projectRoot, ".skillshare", "skills")
|
||||
@@ -75,7 +75,7 @@ func TestListProject_TrackedRepo_ShowsSkills(t *testing.T) {
|
||||
func TestListProject_AutoDetectsMode(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "skill", map[string]string{"SKILL.md": "# S"})
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "list")
|
||||
|
||||
@@ -103,6 +103,74 @@ func TestList_Help_ShowsUsage(t *testing.T) {
|
||||
result.AssertOutputContains(t, "--verbose")
|
||||
}
|
||||
|
||||
func TestList_GroupedDisplay(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
// Create nested skills in two directories + one top-level skill
|
||||
sb.CreateNestedSkill("frontend/react-helper", map[string]string{"SKILL.md": "# React"})
|
||||
sb.CreateNestedSkill("frontend/vue-helper", map[string]string{"SKILL.md": "# Vue"})
|
||||
sb.CreateNestedSkill("utils/helper", map[string]string{"SKILL.md": "# Helper"})
|
||||
sb.CreateSkill("top-level", map[string]string{"SKILL.md": "# Top"})
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets: {}
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("list")
|
||||
|
||||
result.AssertSuccess(t)
|
||||
// Should show directory headers
|
||||
result.AssertOutputContains(t, "frontend/")
|
||||
result.AssertOutputContains(t, "utils/")
|
||||
// Should show base names within groups (not flat names)
|
||||
result.AssertOutputContains(t, "react-helper")
|
||||
result.AssertOutputContains(t, "vue-helper")
|
||||
result.AssertOutputContains(t, "helper")
|
||||
// Should show top-level skill
|
||||
result.AssertOutputContains(t, "top-level")
|
||||
}
|
||||
|
||||
func TestList_GroupedDisplay_Verbose(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.CreateNestedSkill("frontend/react", map[string]string{"SKILL.md": "# React"})
|
||||
sb.CreateSkill("my-skill", map[string]string{"SKILL.md": "# Mine"})
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets: {}
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("list", "--verbose")
|
||||
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "frontend/")
|
||||
result.AssertOutputContains(t, "react")
|
||||
result.AssertOutputContains(t, "my-skill")
|
||||
}
|
||||
|
||||
func TestList_FlatDisplay_NoNesting(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
// All top-level skills — should not show directory headers
|
||||
sb.CreateSkill("alpha", map[string]string{"SKILL.md": "# Alpha"})
|
||||
sb.CreateSkill("beta", map[string]string{"SKILL.md": "# Beta"})
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets: {}
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("list")
|
||||
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "alpha")
|
||||
result.AssertOutputContains(t, "beta")
|
||||
// Should NOT have directory separator in output for pure flat lists
|
||||
result.AssertOutputNotContains(t, "/")
|
||||
}
|
||||
|
||||
func TestList_ShowsSourceInfo(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
@@ -191,7 +191,7 @@ targets:
|
||||
sb.RunCLI("sync")
|
||||
|
||||
// Check the log file exists and is valid JSONL
|
||||
logDir := filepath.Join(filepath.Dir(sb.ConfigPath), "logs")
|
||||
logDir := filepath.Join(sb.Home, ".local", "state", "skillshare", "logs")
|
||||
logFile := filepath.Join(logDir, "operations.log")
|
||||
|
||||
data, err := os.ReadFile(logFile)
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestMode_GlobalFlag_ForcesGlobal(t *testing.T) {
|
||||
defer sb.Cleanup()
|
||||
|
||||
// Create project dir with config
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Write global config
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
@@ -43,7 +43,7 @@ targets:
|
||||
func TestMode_AutoDetect_ProjectWhenConfigExists(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "auto-detect", map[string]string{"SKILL.md": "# A"})
|
||||
|
||||
// No flag → auto-detect project mode
|
||||
@@ -74,7 +74,7 @@ targets:
|
||||
func TestMode_InstallTrackRequiresGitInProject(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// --track now allowed in project mode, but requires a git source
|
||||
result := sb.RunCLIInDir(projectRoot, "install", "/some/path", "--track", "-p")
|
||||
|
||||
@@ -64,7 +64,7 @@ func TestRestore_FromLatest_RestoresBackup(t *testing.T) {
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
|
||||
// Create backup directory manually
|
||||
backupDir := filepath.Join(sb.Home, ".config", "skillshare", "backups")
|
||||
backupDir := filepath.Join(sb.Home, ".local", "share", "skillshare", "backups")
|
||||
timestamp := time.Now().Format("20060102-150405")
|
||||
backupPath := filepath.Join(backupDir, timestamp, "claude")
|
||||
os.MkdirAll(backupPath, 0755)
|
||||
@@ -99,7 +99,7 @@ func TestRestore_FromTimestamp_RestoresSpecific(t *testing.T) {
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
|
||||
// Create backup directory manually with specific timestamp
|
||||
backupDir := filepath.Join(sb.Home, ".config", "skillshare", "backups")
|
||||
backupDir := filepath.Join(sb.Home, ".local", "share", "skillshare", "backups")
|
||||
timestamp := "20240101-120000"
|
||||
backupPath := filepath.Join(backupDir, timestamp, "claude")
|
||||
os.MkdirAll(backupPath, 0755)
|
||||
@@ -132,7 +132,7 @@ func TestRestore_OverwritesSymlink(t *testing.T) {
|
||||
os.Symlink(sb.SourcePath, targetPath)
|
||||
|
||||
// Create backup
|
||||
backupDir := filepath.Join(sb.Home, ".config", "skillshare", "backups")
|
||||
backupDir := filepath.Join(sb.Home, ".local", "share", "skillshare", "backups")
|
||||
timestamp := time.Now().Format("20060102-150405")
|
||||
backupPath := filepath.Join(backupDir, timestamp, "claude")
|
||||
os.MkdirAll(backupPath, 0755)
|
||||
@@ -163,7 +163,7 @@ func TestRestore_DryRun_DoesNotRestore(t *testing.T) {
|
||||
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
|
||||
backupDir := filepath.Join(sb.Home, ".config", "skillshare", "backups")
|
||||
backupDir := filepath.Join(sb.Home, ".local", "share", "skillshare", "backups")
|
||||
timestamp := time.Now().Format("20060102-150405")
|
||||
backupPath := filepath.Join(backupDir, timestamp, "claude")
|
||||
os.MkdirAll(backupPath, 0755)
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
//go:build !online
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/testutil"
|
||||
)
|
||||
|
||||
func TestSkillTargets_OnlySyncsToMatchingTarget(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.CreateSkill("claude-skill", map[string]string{
|
||||
"SKILL.md": "---\nname: claude-skill\ntargets: [claude]\n---\n# Claude only",
|
||||
})
|
||||
sb.CreateSkill("universal-skill", map[string]string{
|
||||
"SKILL.md": "---\nname: universal-skill\n---\n# Universal",
|
||||
})
|
||||
|
||||
claudePath := sb.CreateTarget("claude")
|
||||
cursorPath := sb.CreateTarget("cursor")
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + claudePath + `
|
||||
cursor:
|
||||
path: ` + cursorPath + `
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("sync")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
// claude-skill should only be in claude target
|
||||
if !sb.IsSymlink(filepath.Join(claudePath, "claude-skill")) {
|
||||
t.Error("claude-skill should be synced to claude target")
|
||||
}
|
||||
if sb.FileExists(filepath.Join(cursorPath, "claude-skill")) {
|
||||
t.Error("claude-skill should NOT be synced to cursor target")
|
||||
}
|
||||
|
||||
// universal-skill (no targets field) should be in both
|
||||
if !sb.IsSymlink(filepath.Join(claudePath, "universal-skill")) {
|
||||
t.Error("universal-skill should be synced to claude target")
|
||||
}
|
||||
if !sb.IsSymlink(filepath.Join(cursorPath, "universal-skill")) {
|
||||
t.Error("universal-skill should be synced to cursor target")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillTargets_CrossModeMatching(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
// Skill declares "claude" (global name), target is configured as "claude"
|
||||
// but skill should also match if target were "claude" (project name)
|
||||
sb.CreateSkill("cross-skill", map[string]string{
|
||||
"SKILL.md": "---\nname: cross-skill\ntargets: [claude]\n---\n# Cross",
|
||||
})
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "cross-skill", map[string]string{
|
||||
"SKILL.md": "---\nname: cross-skill\ntargets: [claude]\n---\n# Cross",
|
||||
})
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "sync", "-p")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
// claude target path
|
||||
targetPath := filepath.Join(projectRoot, ".claude", "skills")
|
||||
if !sb.IsSymlink(filepath.Join(targetPath, "cross-skill")) {
|
||||
t.Error("skill with targets: [claude] should match claude target")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillTargets_MultipleTargetsListed(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.CreateSkill("multi-skill", map[string]string{
|
||||
"SKILL.md": "---\nname: multi-skill\ntargets: [claude, cursor]\n---\n# Multi",
|
||||
})
|
||||
sb.CreateSkill("single-skill", map[string]string{
|
||||
"SKILL.md": "---\nname: single-skill\ntargets: [cursor]\n---\n# Single",
|
||||
})
|
||||
|
||||
claudePath := sb.CreateTarget("claude")
|
||||
cursorPath := sb.CreateTarget("cursor")
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + claudePath + `
|
||||
cursor:
|
||||
path: ` + cursorPath + `
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("sync")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
// multi-skill should be in both
|
||||
if !sb.IsSymlink(filepath.Join(claudePath, "multi-skill")) {
|
||||
t.Error("multi-skill should be in claude")
|
||||
}
|
||||
if !sb.IsSymlink(filepath.Join(cursorPath, "multi-skill")) {
|
||||
t.Error("multi-skill should be in cursor")
|
||||
}
|
||||
|
||||
// single-skill should only be in cursor
|
||||
if sb.FileExists(filepath.Join(claudePath, "single-skill")) {
|
||||
t.Error("single-skill should NOT be in claude")
|
||||
}
|
||||
if !sb.IsSymlink(filepath.Join(cursorPath, "single-skill")) {
|
||||
t.Error("single-skill should be in cursor")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillTargets_DoctorNoDriftWarning(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.CreateSkill("claude-only", map[string]string{
|
||||
"SKILL.md": "---\nname: claude-only\ntargets: [claude]\n---\n# Claude only",
|
||||
})
|
||||
sb.CreateSkill("universal", map[string]string{
|
||||
"SKILL.md": "---\nname: universal\n---\n# Universal",
|
||||
})
|
||||
|
||||
claudePath := sb.CreateTarget("claude")
|
||||
cursorPath := sb.CreateTarget("cursor")
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + claudePath + `
|
||||
cursor:
|
||||
path: ` + cursorPath + `
|
||||
`)
|
||||
|
||||
sb.RunCLI("sync").AssertSuccess(t)
|
||||
|
||||
// Doctor should NOT warn about drift — cursor correctly has 1 skill (not 2)
|
||||
result := sb.RunCLI("doctor")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputNotContains(t, "not synced")
|
||||
}
|
||||
|
||||
func TestSkillTargets_StatusNoDriftWarning(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.CreateSkill("claude-only", map[string]string{
|
||||
"SKILL.md": "---\nname: claude-only\ntargets: [claude]\n---\n# Claude only",
|
||||
})
|
||||
sb.CreateSkill("universal", map[string]string{
|
||||
"SKILL.md": "---\nname: universal\n---\n# Universal",
|
||||
})
|
||||
|
||||
claudePath := sb.CreateTarget("claude")
|
||||
cursorPath := sb.CreateTarget("cursor")
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + claudePath + `
|
||||
cursor:
|
||||
path: ` + cursorPath + `
|
||||
`)
|
||||
|
||||
sb.RunCLI("sync").AssertSuccess(t)
|
||||
|
||||
// Status should NOT warn about drift
|
||||
result := sb.RunCLI("status")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputNotContains(t, "not synced")
|
||||
}
|
||||
|
||||
func TestSkillTargets_PrunesWhenTargetRestricted(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
// First sync with universal skill
|
||||
sb.CreateSkill("my-skill", map[string]string{
|
||||
"SKILL.md": "---\nname: my-skill\n---\n# Universal",
|
||||
})
|
||||
claudePath := sb.CreateTarget("claude")
|
||||
cursorPath := sb.CreateTarget("cursor")
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + claudePath + `
|
||||
cursor:
|
||||
path: ` + cursorPath + `
|
||||
`)
|
||||
|
||||
sb.RunCLI("sync").AssertSuccess(t)
|
||||
if !sb.IsSymlink(filepath.Join(cursorPath, "my-skill")) {
|
||||
t.Fatal("my-skill should be in cursor after first sync")
|
||||
}
|
||||
|
||||
// Update SKILL.md to restrict to claude only
|
||||
sb.CreateSkill("my-skill", map[string]string{
|
||||
"SKILL.md": "---\nname: my-skill\ntargets: [claude]\n---\n# Claude only now",
|
||||
})
|
||||
|
||||
sb.RunCLI("sync").AssertSuccess(t)
|
||||
if !sb.IsSymlink(filepath.Join(claudePath, "my-skill")) {
|
||||
t.Error("my-skill should still be in claude")
|
||||
}
|
||||
if sb.FileExists(filepath.Join(cursorPath, "my-skill")) {
|
||||
t.Error("my-skill should be pruned from cursor after adding targets restriction")
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
func TestStatusProject_ShowsSyncedTargets(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code", "cursor")
|
||||
projectRoot := sb.SetupProjectDir("claude", "cursor")
|
||||
sb.CreateProjectSkill(projectRoot, "skill-a", map[string]string{"SKILL.md": "# A"})
|
||||
|
||||
// Sync first
|
||||
@@ -26,7 +26,7 @@ func TestStatusProject_ShowsSyncedTargets(t *testing.T) {
|
||||
func TestStatusProject_ShowsUnsynced(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "unsynced", map[string]string{"SKILL.md": "# U"})
|
||||
|
||||
// Don't sync — should show "has files" (target dir exists but no symlinks)
|
||||
@@ -38,7 +38,7 @@ func TestStatusProject_ShowsUnsynced(t *testing.T) {
|
||||
func TestStatusProject_ShowsSourceAndTargets(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "status", "-p")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
func TestSyncProject_CreatesSymlinks(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "my-skill", map[string]string{
|
||||
"SKILL.md": "# My Skill",
|
||||
})
|
||||
@@ -30,7 +30,7 @@ func TestSyncProject_CreatesSymlinks(t *testing.T) {
|
||||
func TestSyncProject_MultipleTargets(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code", "cursor")
|
||||
projectRoot := sb.SetupProjectDir("claude", "cursor")
|
||||
sb.CreateProjectSkill(projectRoot, "shared", map[string]string{
|
||||
"SKILL.md": "# Shared",
|
||||
})
|
||||
@@ -49,7 +49,7 @@ func TestSyncProject_MultipleTargets(t *testing.T) {
|
||||
func TestSyncProject_PreservesLocalSkills(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "remote-skill", map[string]string{
|
||||
"SKILL.md": "# Remote",
|
||||
})
|
||||
@@ -73,7 +73,7 @@ func TestSyncProject_PreservesLocalSkills(t *testing.T) {
|
||||
func TestSyncProject_PrunesOrphanLinks(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "skill-a", map[string]string{"SKILL.md": "# A"})
|
||||
sb.CreateProjectSkill(projectRoot, "skill-b", map[string]string{"SKILL.md": "# B"})
|
||||
|
||||
@@ -98,7 +98,7 @@ func TestSyncProject_PrunesOrphanLinks(t *testing.T) {
|
||||
func TestSyncProject_DryRun_NoChanges(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "test", map[string]string{"SKILL.md": "# Test"})
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "sync", "-p", "--dry-run")
|
||||
@@ -113,7 +113,7 @@ func TestSyncProject_DryRun_NoChanges(t *testing.T) {
|
||||
func TestSyncProject_AutoDetectsMode(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
sb.CreateProjectSkill(projectRoot, "auto", map[string]string{"SKILL.md": "# Auto"})
|
||||
|
||||
// No -p flag; auto-detects from .skillshare/config.yaml
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
//go:build !online
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/testutil"
|
||||
)
|
||||
|
||||
func TestTargetFilter_AddInclude(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + targetPath + `
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("target", "claude", "--add-include", "team-*")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "added include: team-*")
|
||||
result.AssertOutputContains(t, "Run 'skillshare sync'")
|
||||
|
||||
// Verify config was updated
|
||||
configContent := sb.ReadFile(sb.ConfigPath)
|
||||
if !strings.Contains(configContent, "team-*") {
|
||||
t.Error("include pattern should be in config")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTargetFilter_AddExclude(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + targetPath + `
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("target", "claude", "--add-exclude", "_legacy*")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "added exclude: _legacy*")
|
||||
|
||||
configContent := sb.ReadFile(sb.ConfigPath)
|
||||
if !strings.Contains(configContent, "_legacy*") {
|
||||
t.Error("exclude pattern should be in config")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTargetFilter_RemoveInclude(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + targetPath + `
|
||||
include: [team-*, org-*]
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("target", "claude", "--remove-include", "team-*")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "removed include: team-*")
|
||||
|
||||
configContent := sb.ReadFile(sb.ConfigPath)
|
||||
if strings.Contains(configContent, "team-*") {
|
||||
t.Error("team-* should be removed from config")
|
||||
}
|
||||
if !strings.Contains(configContent, "org-*") {
|
||||
t.Error("org-* should still be in config")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTargetFilter_RemoveExclude(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + targetPath + `
|
||||
exclude: [_legacy*, test-*]
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("target", "claude", "--remove-exclude", "_legacy*")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "removed exclude: _legacy*")
|
||||
|
||||
configContent := sb.ReadFile(sb.ConfigPath)
|
||||
if strings.Contains(configContent, "_legacy*") {
|
||||
t.Error("_legacy* should be removed from config")
|
||||
}
|
||||
if !strings.Contains(configContent, "test-*") {
|
||||
t.Error("test-* should still be in config")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTargetFilter_InvalidPattern(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + targetPath + `
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("target", "claude", "--add-include", "[invalid")
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "invalid")
|
||||
}
|
||||
|
||||
func TestTargetFilter_ShowsInInfo(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + targetPath + `
|
||||
include: [team-*]
|
||||
exclude: [_legacy*]
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("target", "claude")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "Include: team-*")
|
||||
result.AssertOutputContains(t, "Exclude: _legacy*")
|
||||
}
|
||||
|
||||
func TestTargetFilter_SyncAfterFilter(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.CreateSkill("team-skill", map[string]string{"SKILL.md": "# Team"})
|
||||
sb.CreateSkill("other-skill", map[string]string{"SKILL.md": "# Other"})
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + targetPath + `
|
||||
`)
|
||||
|
||||
// Sync without filter -> both skills
|
||||
sb.RunCLI("sync").AssertSuccess(t)
|
||||
if !sb.IsSymlink(filepath.Join(targetPath, "team-skill")) {
|
||||
t.Error("team-skill should be linked")
|
||||
}
|
||||
if !sb.IsSymlink(filepath.Join(targetPath, "other-skill")) {
|
||||
t.Error("other-skill should be linked")
|
||||
}
|
||||
|
||||
// Add include filter via CLI
|
||||
sb.RunCLI("target", "claude", "--add-include", "team-*").AssertSuccess(t)
|
||||
|
||||
// Sync again -> only team-skill
|
||||
sb.RunCLI("sync").AssertSuccess(t)
|
||||
if !sb.IsSymlink(filepath.Join(targetPath, "team-skill")) {
|
||||
t.Error("team-skill should still be linked")
|
||||
}
|
||||
if sb.FileExists(filepath.Join(targetPath, "other-skill")) {
|
||||
t.Error("other-skill should be pruned after include filter")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTargetFilter_Deduplicate(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
targetPath := sb.CreateTarget("claude")
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + targetPath + `
|
||||
include: [team-*]
|
||||
`)
|
||||
|
||||
// Adding same pattern again should be a no-op
|
||||
result := sb.RunCLI("target", "claude", "--add-include", "team-*")
|
||||
result.AssertSuccess(t)
|
||||
// No "added" message since it's a duplicate
|
||||
if strings.Contains(result.Stdout, "added") {
|
||||
t.Error("should not report adding a duplicate pattern")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTargetFilter_HelpShowsFilterFlags(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
result := sb.RunCLI("target", "help")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "--add-include")
|
||||
result.AssertOutputContains(t, "--add-exclude")
|
||||
result.AssertOutputContains(t, "--remove-include")
|
||||
result.AssertOutputContains(t, "--remove-exclude")
|
||||
result.AssertOutputContains(t, "Project mode")
|
||||
}
|
||||
|
||||
func TestTargetFilter_Project_AddAndShow(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "claude", "--add-include", "team-*", "-p")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "added include: team-*")
|
||||
|
||||
// Verify the include shows in info
|
||||
info := sb.RunCLIInDir(projectRoot, "target", "claude", "-p")
|
||||
info.AssertSuccess(t)
|
||||
info.AssertOutputContains(t, "Include: team-*")
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
func TestTargetProject_AddKnownTarget(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "add", "cursor", "-p")
|
||||
result.AssertSuccess(t)
|
||||
@@ -29,7 +29,7 @@ func TestTargetProject_AddKnownTarget(t *testing.T) {
|
||||
func TestTargetProject_AddCustomTarget(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "add", "my-ide", ".my-ide/skills/", "-p")
|
||||
result.AssertSuccess(t)
|
||||
@@ -39,9 +39,9 @@ func TestTargetProject_AddCustomTarget(t *testing.T) {
|
||||
func TestTargetProject_AddDuplicate_Error(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "add", "claude-code", "-p")
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "add", "claude", "-p")
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "already exists")
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func TestTargetProject_AddDuplicate_Error(t *testing.T) {
|
||||
func TestTargetProject_RemoveTarget(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code", "cursor")
|
||||
projectRoot := sb.SetupProjectDir("claude", "cursor")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "remove", "cursor", "-p")
|
||||
result.AssertSuccess(t)
|
||||
@@ -64,7 +64,7 @@ func TestTargetProject_RemoveTarget(t *testing.T) {
|
||||
func TestTargetProject_RemoveAll(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code", "cursor")
|
||||
projectRoot := sb.SetupProjectDir("claude", "cursor")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "remove", "--all", "-p")
|
||||
result.AssertSuccess(t)
|
||||
@@ -73,11 +73,11 @@ func TestTargetProject_RemoveAll(t *testing.T) {
|
||||
func TestTargetProject_List(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code", "cursor")
|
||||
projectRoot := sb.SetupProjectDir("claude", "cursor")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "list", "-p")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "claude-code")
|
||||
result.AssertOutputContains(t, "claude")
|
||||
result.AssertOutputContains(t, "cursor")
|
||||
result.AssertOutputContains(t, "merge")
|
||||
}
|
||||
@@ -85,22 +85,22 @@ func TestTargetProject_List(t *testing.T) {
|
||||
func TestTargetProject_Info(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "claude-code", "-p")
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "claude", "-p")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "claude-code")
|
||||
result.AssertOutputContains(t, "claude")
|
||||
result.AssertOutputContains(t, "merge")
|
||||
}
|
||||
|
||||
func TestTargetProject_SetMode(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "claude-code", "--mode", "symlink", "-p")
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "claude", "--mode", "symlink", "-p")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "Changed claude-code mode")
|
||||
result.AssertAnyOutputContains(t, "Changed claude mode")
|
||||
|
||||
cfg := sb.ReadFile(filepath.Join(projectRoot, ".skillshare", "config.yaml"))
|
||||
if !strings.Contains(cfg, "symlink") {
|
||||
@@ -108,7 +108,7 @@ func TestTargetProject_SetMode(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify info shows symlink mode
|
||||
info := sb.RunCLIInDir(projectRoot, "target", "claude-code", "-p")
|
||||
info := sb.RunCLIInDir(projectRoot, "target", "claude", "-p")
|
||||
info.AssertSuccess(t)
|
||||
info.AssertOutputContains(t, "symlink")
|
||||
}
|
||||
@@ -116,9 +116,9 @@ func TestTargetProject_SetMode(t *testing.T) {
|
||||
func TestTargetProject_SetMode_InvalidMode(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "claude-code", "--mode", "invalid", "-p")
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "claude", "--mode", "invalid", "-p")
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "invalid mode")
|
||||
}
|
||||
@@ -126,10 +126,10 @@ func TestTargetProject_SetMode_InvalidMode(t *testing.T) {
|
||||
func TestTargetProject_ListShowsMode(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Set mode to symlink
|
||||
sb.RunCLIInDir(projectRoot, "target", "claude-code", "--mode", "symlink", "-p")
|
||||
sb.RunCLIInDir(projectRoot, "target", "claude", "--mode", "symlink", "-p")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "list", "-p")
|
||||
result.AssertSuccess(t)
|
||||
@@ -139,7 +139,7 @@ func TestTargetProject_ListShowsMode(t *testing.T) {
|
||||
func TestTargetProject_SyncSymlinkMode(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// Create a skill
|
||||
sb.CreateProjectSkill(projectRoot, "test-skill", map[string]string{
|
||||
@@ -147,7 +147,7 @@ func TestTargetProject_SyncSymlinkMode(t *testing.T) {
|
||||
})
|
||||
|
||||
// Set mode to symlink
|
||||
sb.RunCLIInDir(projectRoot, "target", "claude-code", "--mode", "symlink", "-p")
|
||||
sb.RunCLIInDir(projectRoot, "target", "claude", "--mode", "symlink", "-p")
|
||||
|
||||
// Sync
|
||||
result := sb.RunCLIInDir(projectRoot, "sync", "-p")
|
||||
@@ -167,7 +167,7 @@ func TestTargetProject_SyncSymlinkMode(t *testing.T) {
|
||||
func TestTargetProject_RemoveNotFound_Error(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "remove", "nonexistent", "-p")
|
||||
result.AssertFailure(t)
|
||||
@@ -177,7 +177,7 @@ func TestTargetProject_RemoveNotFound_Error(t *testing.T) {
|
||||
func TestTargetProject_RemoveDryRun(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
projectRoot := sb.SetupProjectDir("claude-code", "cursor")
|
||||
projectRoot := sb.SetupProjectDir("claude", "cursor")
|
||||
|
||||
result := sb.RunCLIInDir(projectRoot, "target", "remove", "cursor", "--dry-run", "-p")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
@@ -69,7 +69,7 @@ targets: {}
|
||||
}
|
||||
|
||||
// Trash should be empty now
|
||||
trashDir := filepath.Join(sb.Home, ".config", "skillshare", "trash")
|
||||
trashDir := filepath.Join(sb.Home, ".local", "share", "skillshare", "trash")
|
||||
entries, _ := os.ReadDir(trashDir)
|
||||
if len(entries) != 0 {
|
||||
t.Errorf("trash should be empty after restore, has %d entries", len(entries))
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestUIProject_ExplicitFlag(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
projectRoot := sb.SetupProjectDir("claude-code")
|
||||
projectRoot := sb.SetupProjectDir("claude")
|
||||
|
||||
// With -p flag and no .skillshare in a different dir, should fail
|
||||
emptyDir := filepath.Join(sb.Root, "empty")
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user