mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
Merge remote-tracking branch 'origin/main' into runkids/fix-audit-markdown-context
This commit is contained in:
@@ -113,7 +113,8 @@ func handleTrackedRepoInstall(source *install.Source, cfg *config.Config, opts i
|
||||
if result.SkillCount > 0 {
|
||||
next = append(next, "skillshare sync", "link them into your targets")
|
||||
}
|
||||
next = append(next, "skillshare update "+result.RepoName, "update this repo later")
|
||||
// --into places the repo in a folder; update takes the path from the source root.
|
||||
next = append(next, "skillshare update "+filepath.ToSlash(filepath.Join(opts.Into, result.RepoName)), "update this repo later")
|
||||
}
|
||||
ui.Next(next...)
|
||||
}
|
||||
|
||||
@@ -295,14 +295,9 @@ func buildSkillEntries(discovered []sync.DiscoveredSkill) []skillEntry {
|
||||
Kind: "skill",
|
||||
IsNested: d.IsInRepo || utils.HasNestedSeparator(d.FlatName),
|
||||
RelPath: d.RelPath,
|
||||
RepoName: d.RepoRelPath,
|
||||
Disabled: d.Disabled,
|
||||
}
|
||||
if d.IsInRepo {
|
||||
parts := strings.SplitN(d.RelPath, "/", 2)
|
||||
if len(parts) > 0 {
|
||||
skills[i].RepoName = parts[0]
|
||||
}
|
||||
}
|
||||
|
||||
// Enrich from centralized metadata store
|
||||
if entry := store.GetByPath(d.RelPath); entry != nil {
|
||||
@@ -574,7 +569,7 @@ func displayTrackedRepos(trackedRepos []string, discovered []sync.DiscoveredSkil
|
||||
func countRepoSkills(repoName string, discovered []sync.DiscoveredSkill) int {
|
||||
count := 0
|
||||
for _, d := range discovered {
|
||||
if d.IsInRepo && strings.HasPrefix(d.RelPath, repoName+"/") {
|
||||
if d.RepoRelPath == repoName {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,11 +187,14 @@ func skillGroup(e skillEntry) string {
|
||||
}
|
||||
|
||||
if e.RepoName != "" {
|
||||
// Tracked: first segment is repo dir, second is group
|
||||
if len(parts) >= 3 {
|
||||
return parts[1]
|
||||
// Tracked: the group is the first segment below the repo root, which
|
||||
// --into can place deeper than the first segment (org/_team).
|
||||
rest, below := strings.CutPrefix(e.RelPath, e.RepoName+"/")
|
||||
group, _, nested := strings.Cut(rest, "/")
|
||||
if !below || !nested {
|
||||
return ""
|
||||
}
|
||||
return ""
|
||||
return group
|
||||
}
|
||||
|
||||
// Non-tracked: first segment is group
|
||||
|
||||
@@ -133,14 +133,28 @@ func TestParseFilterQuery_EmptyValueIgnored(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSkillGroup_TrackedNested(t *testing.T) {
|
||||
e := skillEntry{RelPath: "_team-repo/security/audit", RepoName: "team/repo"}
|
||||
e := skillEntry{RelPath: "_team-repo/security/audit", RepoName: "_team-repo"}
|
||||
if got := skillGroup(e); got != "security" {
|
||||
t.Fatalf("skillGroup() = %q, want %q", got, "security")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillGroup_TrackedInstalledInto(t *testing.T) {
|
||||
e := skillEntry{RelPath: "org/_team-repo/security/audit", RepoName: "org/_team-repo"}
|
||||
if got := skillGroup(e); got != "security" {
|
||||
t.Fatalf("skillGroup() = %q, want %q", got, "security")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillGroup_TrackedInstalledIntoRootSkill(t *testing.T) {
|
||||
e := skillEntry{RelPath: "org/_team-repo", RepoName: "org/_team-repo"}
|
||||
if got := skillGroup(e); got != "" {
|
||||
t.Fatalf("skillGroup() = %q, want empty for the repo's root skill", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillGroup_TrackedRoot(t *testing.T) {
|
||||
e := skillEntry{RelPath: "_team-repo/my-skill", RepoName: "team/repo"}
|
||||
e := skillEntry{RelPath: "_team-repo/my-skill", RepoName: "_team-repo"}
|
||||
if got := skillGroup(e); got != "" {
|
||||
t.Fatalf("skillGroup() = %q, want empty for tracked root-level", got)
|
||||
}
|
||||
@@ -254,7 +268,7 @@ func TestMatchSkillItem_ANDLogic(t *testing.T) {
|
||||
item := skillItem{entry: skillEntry{
|
||||
Name: "audit",
|
||||
RelPath: "_team-repo/security/audit",
|
||||
RepoName: "team/repo",
|
||||
RepoName: "_team-repo",
|
||||
}}
|
||||
|
||||
// All conditions match
|
||||
|
||||
@@ -104,8 +104,8 @@ func TestApplyFilter_WithTags(t *testing.T) {
|
||||
items := []skillItem{
|
||||
{entry: skillEntry{Name: "local-skill", RelPath: "local-skill"}},
|
||||
{entry: skillEntry{Name: "react-tips", RelPath: "frontend/react-tips"}},
|
||||
{entry: skillEntry{Name: "audit", RelPath: "_team-repo/security/audit", RepoName: "team/repo"}},
|
||||
{entry: skillEntry{Name: "lint", RelPath: "_team-repo/lint", RepoName: "team/repo"}},
|
||||
{entry: skillEntry{Name: "audit", RelPath: "_team-repo/security/audit", RepoName: "_team-repo"}},
|
||||
{entry: skillEntry{Name: "lint", RelPath: "_team-repo/lint", RepoName: "_team-repo"}},
|
||||
{entry: skillEntry{Name: "remote-a", RelPath: "remote-a", Source: "github.com/foo/bar"}},
|
||||
}
|
||||
|
||||
|
||||
@@ -260,18 +260,12 @@ func buildTrackedRepoJSON(sourcePath string, trackedRepos []string, discovered [
|
||||
|
||||
missingRepos, _ := install.GetMissingTrackedRepos(sourcePath, walks...)
|
||||
|
||||
// Count skills per repo (single pass). A tracked repo may surface skills
|
||||
// at the repo root (RelPath equals the repo name, no slash) or nested
|
||||
// (RelPath has the form "<repo>/..."), so both shapes must be counted.
|
||||
// Count skills per repo (single pass). RepoRelPath covers skills at the
|
||||
// repo root and nested ones, and repos placed with --into (org/_repo).
|
||||
repoSkillCount := make(map[string]int, len(trackedRepos))
|
||||
for _, d := range discovered {
|
||||
if !d.IsInRepo {
|
||||
continue
|
||||
}
|
||||
if idx := strings.Index(d.RelPath, "/"); idx > 0 {
|
||||
repoSkillCount[d.RelPath[:idx]]++
|
||||
} else {
|
||||
repoSkillCount[d.RelPath]++
|
||||
if d.IsInRepo {
|
||||
repoSkillCount[d.RepoRelPath]++
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -227,7 +227,7 @@ func printTrackedReposStatus(sourcePath string, discovered []sync.DiscoveredSkil
|
||||
for _, repoName := range trackedRepos {
|
||||
skillCount := 0
|
||||
for _, d := range discovered {
|
||||
if d.IsInRepo && strings.HasPrefix(d.RelPath, repoName+"/") {
|
||||
if d.RepoRelPath == repoName {
|
||||
skillCount++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,8 +340,9 @@ func GetUpdatableSkills(sourceDir string) ([]string, error) {
|
||||
return getUpdatableSkillsImpl(sourceDir)
|
||||
}
|
||||
|
||||
// GetTrackedRepos returns tracked repositories in the source directory. An
|
||||
// optional walk policy follows first-level source links; omitted, none are.
|
||||
// GetTrackedRepos returns tracked repositories in the source directory as
|
||||
// slash paths relative to it (org/_team), on every OS. An optional walk policy
|
||||
// follows first-level source links; omitted, none are.
|
||||
func GetTrackedRepos(sourceDir string, walk ...sourcewalk.Options) ([]string, error) {
|
||||
var opts sourcewalk.Options
|
||||
if len(walk) > 0 {
|
||||
|
||||
@@ -52,7 +52,7 @@ func getMissingTrackedReposImpl(sourceDir string, walks ...sourcewalk.Options) (
|
||||
}
|
||||
existing := make(map[string]bool, len(existingRepos))
|
||||
for _, repo := range existingRepos {
|
||||
existing[filepath.ToSlash(repo)] = true
|
||||
existing[repo] = true
|
||||
}
|
||||
|
||||
var missing []TrackedRepoMeta
|
||||
@@ -101,7 +101,7 @@ func rehydrateMissingTrackedReposImpl(sourceDir string, parseOpts ParseOptions,
|
||||
}
|
||||
existing := make(map[string]bool, len(existingRepos))
|
||||
for _, repo := range existingRepos {
|
||||
existing[filepath.ToSlash(repo)] = true
|
||||
existing[repo] = true
|
||||
}
|
||||
|
||||
opts.Quiet = true
|
||||
@@ -237,7 +237,7 @@ func getTrackedReposImpl(sourceDir string, walk sourcewalk.Options) ([]string, e
|
||||
if IsGitRepo(path) {
|
||||
relPath, relErr := filepath.Rel(walkRoot, path)
|
||||
if relErr == nil {
|
||||
repos = append(repos, relPath)
|
||||
repos = append(repos, filepath.ToSlash(relPath))
|
||||
}
|
||||
return filepath.SkipDir // Don't recurse into tracked repos
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ func TestGetTrackedRepos_FindsNested(t *testing.T) {
|
||||
if len(repos) != 1 {
|
||||
t.Fatalf("expected 1 nested tracked repo, got %d", len(repos))
|
||||
}
|
||||
if repos[0] != filepath.Join("frontend", "_ui-skills") {
|
||||
if repos[0] != "frontend/_ui-skills" {
|
||||
t.Errorf("expected 'frontend/_ui-skills', got %q", repos[0])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package server
|
||||
import (
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/git"
|
||||
"skillshare/internal/install"
|
||||
@@ -108,7 +107,7 @@ func buildTrackedRepos(sourceDir string, skills []sync.DiscoveredSkill, walk sou
|
||||
// Count skills belonging to this repo
|
||||
skillCount := 0
|
||||
for _, sk := range skills {
|
||||
if sk.IsInRepo && strings.HasPrefix(sk.RelPath, repoName+"/") {
|
||||
if sk.RepoRelPath == repoName {
|
||||
skillCount++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ type skillItem struct {
|
||||
LinkName string `json:"linkName,omitempty"`
|
||||
LinkTarget string `json:"linkTarget,omitempty"`
|
||||
IsInRepo bool `json:"isInRepo"`
|
||||
RepoPath string `json:"repoPath,omitempty"`
|
||||
Targets []string `json:"targets,omitempty"`
|
||||
InstalledAt string `json:"installedAt,omitempty"`
|
||||
Source string `json:"source,omitempty"`
|
||||
@@ -107,13 +108,14 @@ func (s *Server) handleListSkills(w http.ResponseWriter, r *http.Request) {
|
||||
RelPath: d.RelPath,
|
||||
SourcePath: d.SourcePath,
|
||||
IsInRepo: d.IsInRepo,
|
||||
RepoPath: d.RepoRelPath,
|
||||
Targets: d.Targets,
|
||||
Disabled: d.Disabled,
|
||||
ManualOnly: manualOnly(d.SourcePath),
|
||||
}
|
||||
enrichSkillLink(&item, source, walk, linkTargets)
|
||||
|
||||
if entry := s.skillEntry(d.RelPath); entry != nil {
|
||||
if entry := s.discoveredSkillEntry(d.RelPath, d.RepoRelPath); entry != nil {
|
||||
if !entry.InstalledAt.IsZero() {
|
||||
item.InstalledAt = entry.InstalledAt.Format(time.RFC3339)
|
||||
}
|
||||
@@ -140,6 +142,7 @@ func (s *Server) handleListSkills(w http.ResponseWriter, r *http.Request) {
|
||||
RelPath: d.RelPath,
|
||||
SourcePath: d.SourcePath,
|
||||
IsInRepo: d.IsInRepo,
|
||||
RepoPath: d.RepoRelPath,
|
||||
Disabled: d.Disabled,
|
||||
Targets: d.Targets,
|
||||
}
|
||||
@@ -223,13 +226,14 @@ func (s *Server) handleGetSkill(w http.ResponseWriter, r *http.Request) {
|
||||
RelPath: d.RelPath,
|
||||
SourcePath: d.SourcePath,
|
||||
IsInRepo: d.IsInRepo,
|
||||
RepoPath: d.RepoRelPath,
|
||||
Targets: d.Targets,
|
||||
Disabled: d.Disabled,
|
||||
ManualOnly: manualOnly(d.SourcePath),
|
||||
}
|
||||
enrichSkillLink(&item, source, walk, make(map[string]string))
|
||||
|
||||
if entry := s.skillEntry(d.RelPath); entry != nil {
|
||||
if entry := s.discoveredSkillEntry(d.RelPath, d.RepoRelPath); entry != nil {
|
||||
if !entry.InstalledAt.IsZero() {
|
||||
item.InstalledAt = entry.InstalledAt.Format(time.RFC3339)
|
||||
}
|
||||
@@ -299,6 +303,7 @@ func (s *Server) handleGetSkill(w http.ResponseWriter, r *http.Request) {
|
||||
RelPath: d.RelPath,
|
||||
SourcePath: d.SourcePath,
|
||||
IsInRepo: d.IsInRepo,
|
||||
RepoPath: d.RepoRelPath,
|
||||
Disabled: d.Disabled,
|
||||
Targets: d.Targets,
|
||||
}
|
||||
|
||||
@@ -55,6 +55,86 @@ func TestHandleListSkills_WithSkills(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// listedSources saves store, lists resources through the full handler (which
|
||||
// reloads metadata from disk), and returns each resource's source by relPath.
|
||||
func listedSources(t *testing.T, s *Server, src string, store *install.MetadataStore) map[string]string {
|
||||
t.Helper()
|
||||
if err := store.Save(src); err != nil {
|
||||
t.Fatalf("save metadata: %v", err)
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/resources", nil))
|
||||
var resp struct {
|
||||
Resources []struct {
|
||||
RelPath string `json:"relPath"`
|
||||
Source string `json:"source"`
|
||||
} `json:"resources"`
|
||||
}
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode resources: %v: %s", err, rr.Body.String())
|
||||
}
|
||||
sources := make(map[string]string)
|
||||
for _, r := range resp.Resources {
|
||||
sources[r.RelPath] = r.Source
|
||||
}
|
||||
return sources
|
||||
}
|
||||
|
||||
func TestHandleListSkills_NestedTrackedSkillUsesRepoSource(t *testing.T) {
|
||||
s, src := newTestServer(t)
|
||||
addTrackedRepo(t, src, "_team-skills")
|
||||
addSkill(t, src, "_team-skills/skills/vue")
|
||||
const remote = "https://github.com/team/skills.git"
|
||||
store := install.NewMetadataStore()
|
||||
store.Set("_team-skills", &install.MetadataEntry{Source: remote, Tracked: true})
|
||||
|
||||
if got := listedSources(t, s, src, store)["_team-skills/skills/vue"]; got != remote {
|
||||
t.Fatalf("expected nested tracked skill to report source %q, got %q", remote, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleListSkills_TrackedRepoInstalledIntoReportsRepo(t *testing.T) {
|
||||
s, src := newTestServer(t)
|
||||
addTrackedRepo(t, src, "org/_team-skills")
|
||||
addSkill(t, src, "org/_team-skills/skills/vue")
|
||||
const remote = "https://github.com/team/skills.git"
|
||||
store := install.NewMetadataStore()
|
||||
store.Set("org/_team-skills", &install.MetadataEntry{Source: remote, Tracked: true})
|
||||
if err := store.Save(src); err != nil {
|
||||
t.Fatalf("save metadata: %v", err)
|
||||
}
|
||||
|
||||
rr := httptest.NewRecorder()
|
||||
s.handler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/resources", nil))
|
||||
var resp struct {
|
||||
Resources []struct {
|
||||
Source string `json:"source"`
|
||||
RepoPath string `json:"repoPath"`
|
||||
} `json:"resources"`
|
||||
}
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode resources: %v: %s", err, rr.Body.String())
|
||||
}
|
||||
if len(resp.Resources) != 1 || resp.Resources[0].Source != remote || resp.Resources[0].RepoPath != "org/_team-skills" {
|
||||
t.Fatalf("expected skill in repo org/_team-skills with source %q, got %+v", remote, resp.Resources)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleListSkills_NestedTrackedSkillIgnoresSameNamedTopLevelSkill(t *testing.T) {
|
||||
s, src := newTestServer(t)
|
||||
addTrackedRepo(t, src, "_team-skills")
|
||||
addSkill(t, src, "_team-skills/skills/vue")
|
||||
addSkill(t, src, "vue")
|
||||
const remote = "https://github.com/team/skills.git"
|
||||
store := install.NewMetadataStore()
|
||||
store.Set("_team-skills", &install.MetadataEntry{Source: remote, Tracked: true})
|
||||
store.Set("vue", &install.MetadataEntry{Source: "github.com/other/vue"})
|
||||
|
||||
if got := listedSources(t, s, src, store)["_team-skills/skills/vue"]; got != remote {
|
||||
t.Fatalf("expected nested tracked skill to report source %q, got %q", remote, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleListSkills_ManualOnly(t *testing.T) {
|
||||
s, src := newTestServer(t)
|
||||
addSkill(t, src, "auto")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"skillshare/internal/sourcewalk"
|
||||
"skillshare/internal/sync"
|
||||
"skillshare/internal/uninstall"
|
||||
"skillshare/internal/utils"
|
||||
)
|
||||
|
||||
type batchUninstallRequest struct {
|
||||
@@ -186,7 +188,12 @@ func (s *Server) resolveBatchUninstallItem(discovered []sync.DiscoveredSkill, so
|
||||
|
||||
repoPath := filepath.Join(source, name)
|
||||
_, repoFollowed := walk.Follow.Resolve(repoPath)
|
||||
managedRepo := strings.HasPrefix(name, "_") && filepath.Base(name) == name && !repoFollowed && install.IsGitRepo(repoPath)
|
||||
// A repo installed with --into is named by its path, e.g. org/_team. --into
|
||||
// folders cannot start with "_" (validate.IntoPath), so a deeper _ git dir
|
||||
// such as _team/vendor/_lib is part of a tracked repo, not a repo of its own.
|
||||
parent, base := path.Split(name)
|
||||
repoName := utils.IsTrackedRepoDir(base) && !strings.Contains("/"+parent, "/_")
|
||||
managedRepo := repoName && !repoFollowed && install.IsGitRepo(repoPath)
|
||||
var skill *sync.DiscoveredSkill
|
||||
if !managedRepo {
|
||||
var err error
|
||||
@@ -199,7 +206,7 @@ func (s *Server) resolveBatchUninstallItem(discovered []sync.DiscoveredSkill, so
|
||||
_, followed = walk.Follow.Resolve(skill.SourcePath)
|
||||
}
|
||||
// An explicit managed repo takes precedence over a skill's basename.
|
||||
if managedRepo || (strings.HasPrefix(name, "_") && !followed) {
|
||||
if managedRepo || (repoName && !followed) {
|
||||
if !install.IsGitRepo(repoPath) {
|
||||
return uninstall.Item{}, errors.New("not a tracked repository: " + name)
|
||||
}
|
||||
|
||||
@@ -225,6 +225,45 @@ func TestHandleUninstallSkill_AmbiguousLinkedBasename(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBatchUninstall_RepoInstalledInto(t *testing.T) {
|
||||
s, src := newTestServer(t)
|
||||
addTrackedRepo(t, src, "org/_team")
|
||||
addSkill(t, filepath.Join(src, "org", "_team"), "foo")
|
||||
_, res := postBatchUninstall(t, s, true, "org/_team")
|
||||
if _, err := os.Stat(filepath.Join(src, "org", "_team")); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected org/_team to be uninstalled, stat err %v: %+v", err, res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBatchUninstall_GitDirInsideTrackedRepoIsKept(t *testing.T) {
|
||||
s, src := newTestServer(t)
|
||||
addTrackedRepo(t, src, "_team")
|
||||
addTrackedRepo(t, src, "_team/vendor/_lib") // e.g. a submodule checkout
|
||||
_, res := postBatchUninstall(t, s, true, "_team/vendor/_lib")
|
||||
if len(res) != 1 || res[0].Success {
|
||||
t.Fatalf("expected the request to be refused: %+v", res)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(src, "_team", "vendor", "_lib", ".git")); err != nil {
|
||||
t.Fatalf("folder inside a tracked repo was removed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBatchUninstall_NestedRepoBehindUnfollowedLinkIsKept(t *testing.T) {
|
||||
s, src := newTestServer(t)
|
||||
outside := t.TempDir()
|
||||
addTrackedRepo(t, outside, "_evil")
|
||||
if err := os.Symlink(outside, filepath.Join(src, "org")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, res := postBatchUninstall(t, s, true, "org/_evil")
|
||||
if len(res) != 1 || res[0].Success {
|
||||
t.Fatalf("expected the request to be refused: %+v", res)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(outside, "_evil", ".git")); err != nil {
|
||||
t.Fatalf("repo outside the source was removed through an unfollowed link: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBatchUninstall_RepoBeforeLinkedBasename(t *testing.T) {
|
||||
s, src := newTestServer(t)
|
||||
addTrackedRepo(t, src, "_team")
|
||||
|
||||
@@ -160,6 +160,28 @@ func (s *Server) skillEntry(relPath string) *install.MetadataEntry {
|
||||
return copyMetadataEntry(s.skillsStore.GetByPath(relPath))
|
||||
}
|
||||
|
||||
// discoveredSkillEntry returns a copy of the metadata entry for a discovered
|
||||
// skill. A skill nested inside a tracked repo has no entry of its own, so it
|
||||
// falls back to the repo's entry, which carries the repo source. repoRelPath is
|
||||
// the skill's tracked repo root from discovery, empty outside a repo.
|
||||
func (s *Server) discoveredSkillEntry(relPath, repoRelPath string) *install.MetadataEntry {
|
||||
if repoRelPath == "" {
|
||||
return s.skillEntry(relPath)
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
// GetByPath also matches a bare basename key, which for a nested repo skill
|
||||
// can be an unrelated top-level skill of the same name. Only an exact or
|
||||
// group-matched entry belongs to the skill itself.
|
||||
if e := s.skillsStore.GetByPath(relPath); e != nil && (e.Group != "" || s.skillsStore.Has(relPath)) {
|
||||
return copyMetadataEntry(e)
|
||||
}
|
||||
if e := s.skillsStore.Get(repoRelPath); e != nil && e.Tracked {
|
||||
return copyMetadataEntry(e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// agentEntry returns a copy of the agents metadata entry for key, or nil.
|
||||
// It takes s.mu.RLock, so the caller must not hold s.mu.
|
||||
func (s *Server) agentEntry(key string) *install.MetadataEntry {
|
||||
|
||||
@@ -137,6 +137,51 @@ func TestDiscoverSourceSkills_TrackedRepo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverSourceSkills_TrackedRepoInstalledInto(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
// install --track --into org places the clone at org/_repo
|
||||
os.MkdirAll(filepath.Join(src, "org", "_repo", ".git"), 0755)
|
||||
writeSkillMD(t, filepath.Join(src, "org", "_repo", "skills", "vue"), "---\nname: vue\n---\n# Vue")
|
||||
|
||||
skills, err := DiscoverSourceSkills(src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(skills) != 1 || !skills[0].IsInRepo || skills[0].RepoRelPath != "org/_repo" {
|
||||
t.Fatalf("expected one skill in repo org/_repo, got %+v", skills)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverSourceSkills_NestedUnderscoreDirWithoutGitIsNotRepo(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
writeSkillMD(t, filepath.Join(src, "org", "_drafts", "vue"), "---\nname: vue\n---\n# Vue")
|
||||
|
||||
skills, err := DiscoverSourceSkills(src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(skills) != 1 || skills[0].IsInRepo {
|
||||
t.Fatalf("expected one skill outside any repo, got %+v", skills)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverSourceSkills_TrackedRepoInstalledIntoRespectsSkillIgnore(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
repoDir := filepath.Join(src, "org", "_repo")
|
||||
os.MkdirAll(filepath.Join(repoDir, ".git"), 0755)
|
||||
os.WriteFile(filepath.Join(repoDir, ".skillignore"), []byte("drafts\n"), 0644)
|
||||
writeSkillMD(t, filepath.Join(repoDir, "drafts", "wip"), "---\nname: wip\n---\n# WIP")
|
||||
writeSkillMD(t, filepath.Join(repoDir, "vue"), "---\nname: vue\n---\n# Vue")
|
||||
|
||||
skills, err := DiscoverSourceSkills(src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(skills) != 1 || skills[0].RelPath != "org/_repo/vue" {
|
||||
t.Fatalf("expected only org/_repo/vue, got %+v", skills)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverSourceSkills_ParsesTargets(t *testing.T) {
|
||||
src := t.TempDir()
|
||||
content := "---\nname: targeted\ntargets:\n - claude\n - cursor\n---\n# Targeted"
|
||||
|
||||
@@ -138,7 +138,24 @@ func matchesHostSkillPath(relPath, targetName, targetPath string) bool {
|
||||
func discoverSourceSkillsInternal(sourcePath string, opts discoverOptions) ([]DiscoveredSkill, []string, *skillignore.IgnoreStats, error) {
|
||||
var skills []DiscoveredSkill
|
||||
var trackedRepos []string
|
||||
ignoreMatchers := make(map[string]*skillignore.Matcher) // tracked repo abs path → .skillignore matcher
|
||||
ignoreMatchers := make(map[string]*skillignore.Matcher) // tracked repo slash rel path → .skillignore matcher
|
||||
repoRoots := make(map[string]bool) // slash rel paths of _-prefixed git repos seen so far, e.g. org/_team from --into
|
||||
|
||||
// repoOf returns the tracked repo root containing slash relPath, or "". A
|
||||
// _-prefixed first segment always counts; a deeper one only when the walk
|
||||
// saw it as a git repo, so a plain org/_drafts folder is not mistaken for a repo.
|
||||
repoOf := func(relPath string) string {
|
||||
first, _, _ := strings.Cut(relPath, "/")
|
||||
if utils.IsTrackedRepoDir(first) {
|
||||
return first
|
||||
}
|
||||
for i := len(first) + 1; i <= len(relPath); i++ {
|
||||
if (i == len(relPath) || relPath[i] == '/') && repoRoots[relPath[:i]] {
|
||||
return relPath[:i]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
walkRoot := utils.ResolveSymlink(sourcePath)
|
||||
rootMatcher := skillignore.ReadMatcher(walkRoot)
|
||||
@@ -189,15 +206,18 @@ func discoverSourceSkillsInternal(sourcePath string, opts discoverOptions) ([]Di
|
||||
// Collect tracked repos: _-prefixed directories that are git repos
|
||||
if info.IsDir() && info.Name() != "." && utils.IsTrackedRepoDir(info.Name()) {
|
||||
if install.IsGitRepo(path) {
|
||||
if opts.collectTracked {
|
||||
relPath, relErr := filepath.Rel(walkRoot, path)
|
||||
if relErr == nil && relPath != "." {
|
||||
relPath, relErr := filepath.Rel(walkRoot, path)
|
||||
repoRel := ""
|
||||
if relErr == nil && relPath != "." {
|
||||
repoRel = filepath.ToSlash(relPath)
|
||||
repoRoots[repoRel] = true
|
||||
if opts.collectTracked {
|
||||
trackedRepos = append(trackedRepos, relPath)
|
||||
}
|
||||
}
|
||||
m := skillignore.ReadMatcher(path)
|
||||
if m.HasRules() {
|
||||
ignoreMatchers[path] = m
|
||||
ignoreMatchers[repoRel] = m
|
||||
// Record repo-level .skillignore in stats
|
||||
if opts.collectIgnored {
|
||||
repoIgnorePath := filepath.Join(path, ".skillignore")
|
||||
@@ -219,12 +239,9 @@ func discoverSourceSkillsInternal(sourcePath string, opts discoverOptions) ([]Di
|
||||
relPath, relErr := filepath.Rel(walkRoot, path)
|
||||
if relErr == nil && relPath != "." {
|
||||
relPath = strings.ReplaceAll(relPath, "\\", "/")
|
||||
parts := strings.Split(relPath, "/")
|
||||
if len(parts) > 1 && utils.IsTrackedRepoDir(parts[0]) {
|
||||
repoAbsPath := filepath.Join(walkRoot, parts[0])
|
||||
if m, ok := ignoreMatchers[repoAbsPath]; ok {
|
||||
repoRelPath := strings.Join(parts[1:], "/")
|
||||
if m.CanSkipDir(repoRelPath) {
|
||||
if repo := repoOf(relPath); repo != "" && repo != relPath {
|
||||
if m, ok := ignoreMatchers[repo]; ok {
|
||||
if m.CanSkipDir(strings.TrimPrefix(relPath, repo+"/")) {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
}
|
||||
@@ -246,17 +263,14 @@ func discoverSourceSkillsInternal(sourcePath string, opts discoverOptions) ([]Di
|
||||
|
||||
relPath = strings.ReplaceAll(relPath, "\\", "/")
|
||||
|
||||
isInRepo := false
|
||||
parts := strings.Split(relPath, "/")
|
||||
if len(parts) > 0 && utils.IsTrackedRepoDir(parts[0]) {
|
||||
isInRepo = true
|
||||
}
|
||||
repoRelPath := repoOf(relPath)
|
||||
isInRepo := repoRelPath != ""
|
||||
|
||||
// Root-level .skillignore fallback (for files in non-skipped dirs),
|
||||
// then the repo-level .skillignore inside tracked repos. With
|
||||
// includeIgnored the skill is kept, flagged Disabled, and measured
|
||||
// like any other so analyze can price it for symlink-mode targets.
|
||||
disabled := rootMatcher.Match(relPath, false) || (isInRepo && isSkillIgnored(parts, walkRoot, ignoreMatchers))
|
||||
disabled := rootMatcher.Match(relPath, false) || (isInRepo && isSkillIgnored(relPath, repoRelPath, ignoreMatchers))
|
||||
if disabled {
|
||||
if opts.collectIgnored {
|
||||
stats.IgnoredSkills = append(stats.IgnoredSkills, relPath)
|
||||
@@ -308,6 +322,7 @@ func discoverSourceSkillsInternal(sourcePath string, opts discoverOptions) ([]Di
|
||||
RelPath: relPath,
|
||||
FlatName: utils.PathToFlatName(relPath),
|
||||
IsInRepo: isInRepo,
|
||||
RepoRelPath: repoRelPath,
|
||||
Targets: targets,
|
||||
DescChars: ctx.DescChars,
|
||||
BodyChars: ctx.BodyChars,
|
||||
|
||||
@@ -23,6 +23,7 @@ type DiscoveredSkill struct {
|
||||
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)
|
||||
RepoRelPath string // Tracked repo root relative to source (_team, or org/_team via --into); set when IsInRepo
|
||||
Targets []string // From SKILL.md frontmatter; nil = all targets
|
||||
DescChars int // Rune count of name + description (populated when collectContext)
|
||||
BodyChars int // Rune count of body after frontmatter (populated when collectContext)
|
||||
@@ -36,17 +37,17 @@ type DiscoveredSkill struct {
|
||||
|
||||
// isSkillIgnored checks whether a skill inside a tracked repo should be
|
||||
// skipped based on the repo's .skillignore matcher.
|
||||
// parts is strings.Split(relPath, "/"), where relPath is relative to source root.
|
||||
func isSkillIgnored(parts []string, walkRoot string, ignoreMatchers map[string]*skillignore.Matcher) bool {
|
||||
if len(parts) < 2 {
|
||||
// relPath and repoRelPath are slash paths relative to the source root, and
|
||||
// ignoreMatchers is keyed by repo root in the same form.
|
||||
func isSkillIgnored(relPath, repoRelPath string, ignoreMatchers map[string]*skillignore.Matcher) bool {
|
||||
if relPath == repoRelPath {
|
||||
return false
|
||||
}
|
||||
repoAbsPath := filepath.Join(walkRoot, parts[0])
|
||||
m, ok := ignoreMatchers[repoAbsPath]
|
||||
m, ok := ignoreMatchers[repoRelPath]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return m.Match(strings.Join(parts[1:], "/"), false)
|
||||
return m.Match(strings.TrimPrefix(relPath, repoRelPath+"/"), false)
|
||||
}
|
||||
|
||||
// walkOptions returns the optional traversal policy passed to a Discover
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
gosync "sync"
|
||||
|
||||
"skillshare/internal/git"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"skillshare/internal/sourcefs"
|
||||
"skillshare/internal/sourcewalk"
|
||||
"skillshare/internal/trash"
|
||||
"skillshare/internal/utils"
|
||||
)
|
||||
|
||||
// Item is one resolved skill, group directory or tracked repo.
|
||||
@@ -38,6 +40,9 @@ type Options struct {
|
||||
// ErrDirty refuses a tracked repo with uncommitted changes.
|
||||
var ErrDirty = errors.New("uncommitted changes")
|
||||
|
||||
// ErrInsideRepo refuses a skill or folder inside a tracked repo's checkout.
|
||||
var ErrInsideRepo = errors.New("inside a tracked repo; uninstall the repo instead")
|
||||
|
||||
// StatusError refuses a tracked repo whose git status could not be read.
|
||||
type StatusError struct{ Err error }
|
||||
|
||||
@@ -66,15 +71,16 @@ type Outcome struct {
|
||||
|
||||
// Preflight reports why each item cannot be uninstalled, without changing
|
||||
// anything and regardless of Force, so a caller can warn or confirm first.
|
||||
// The error is a move-out refusal, ErrDirty or a *StatusError. Move-out comes
|
||||
// first: a linked folder is never told to retry with force.
|
||||
// The error is a move-out refusal (including ErrInsideRepo), ErrDirty or a
|
||||
// *StatusError. Move-out comes first: a linked folder is never told to retry
|
||||
// with force.
|
||||
func Preflight(items []Item, o Options) []error {
|
||||
errs := make([]error, len(items))
|
||||
const maxDirtyWorkers = 8
|
||||
sem := make(chan struct{}, maxDirtyWorkers)
|
||||
var wg gosync.WaitGroup
|
||||
for i, item := range items {
|
||||
if errs[i] = sourcefs.CheckSkillMoveOut(o.SourceDir, item.Path, o.Follow); errs[i] != nil || !item.Repo {
|
||||
if errs[i] = checkMoveOut(item, o); errs[i] != nil || !item.Repo {
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
@@ -129,10 +135,35 @@ func Run(items []Item, o Options) Outcome {
|
||||
return out
|
||||
}
|
||||
|
||||
func moveOut(item Item, o Options) error {
|
||||
// checkMoveOut refuses an item that may not leave the source: one behind a
|
||||
// link the policy does not allow, or one inside a tracked repo's checkout.
|
||||
// Force skips neither.
|
||||
func checkMoveOut(item Item, o Options) error {
|
||||
if err := sourcefs.CheckSkillMoveOut(o.SourceDir, item.Path, o.Follow); err != nil {
|
||||
return err
|
||||
}
|
||||
rel, err := filepath.Rel(o.SourceDir, item.Path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
// A tracked repo is a _-prefixed git checkout; removing part of it would
|
||||
// leave it dirty for update. A followed source link is the user's own
|
||||
// checkout, whose skills may go one at a time.
|
||||
dir := o.SourceDir
|
||||
parents := strings.Split(filepath.ToSlash(rel), "/")
|
||||
for _, seg := range parents[:len(parents)-1] {
|
||||
dir = filepath.Join(dir, seg)
|
||||
if _, followed := o.Follow.Resolve(dir); utils.IsTrackedRepoDir(seg) && !followed && install.IsGitRepo(dir) {
|
||||
return ErrInsideRepo
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func moveOut(item Item, o Options) error {
|
||||
if err := checkMoveOut(item, o); err != nil {
|
||||
return err
|
||||
}
|
||||
if item.Repo && !o.Force {
|
||||
if err := checkDirty(item.Path); err != nil {
|
||||
return err
|
||||
|
||||
@@ -196,6 +196,27 @@ func TestRun_RefusesLinkedSkillRoot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_RefusesItemsInsideTrackedRepoEvenWhenForced(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.repo(t, "_team")
|
||||
skill := f.skill(t, "_team/foo")
|
||||
sub := f.skill(t, "_team/vendor/_lib")
|
||||
runGit(t, sub.Path, "init", "-q") // e.g. a submodule checkout
|
||||
sub.Repo = true
|
||||
f.opts.Force = true
|
||||
items := []Item{skill, sub}
|
||||
|
||||
preflight, run := Preflight(items, f.opts), Run(items, f.opts).Results
|
||||
for i := range items {
|
||||
if !errors.Is(preflight[i], ErrInsideRepo) || !errors.Is(run[i].Err, ErrInsideRepo) {
|
||||
t.Fatalf("%s: expected ErrInsideRepo, got preflight %v, run %v", items[i].Name, preflight[i], run[i].Err)
|
||||
}
|
||||
if !exists(items[i].Path) {
|
||||
t.Errorf("%s must stay in the repo", items[i].Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflight_ReportsDirtyRepoEvenWhenForced(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
dirty := f.repo(t, "_dirty")
|
||||
|
||||
@@ -212,6 +212,42 @@ func TestInstall_Track_RootSkillMd_ShowsInStatus(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestInstall_Track_Into_NamesRepoByPath verifies that a tracked repo
|
||||
// installed with --into is named by its path in the install hint and status.
|
||||
func TestInstall_Track_Into_NamesRepoByPath(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
setupGlobalConfig(sb)
|
||||
|
||||
repoURL := setupBareRepoWithNestedAndRootSkill(t, sb, "into")
|
||||
|
||||
result := sb.RunCLI("install", repoURL, "--track", "--name", "team-skills", "--into", "org")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertOutputContains(t, "skillshare update org/_team-skills")
|
||||
|
||||
statusResult := sb.RunCLI("status", "--json")
|
||||
statusResult.AssertSuccess(t)
|
||||
var output struct {
|
||||
TrackedRepos []struct {
|
||||
Name string `json:"name"`
|
||||
SkillCount int `json:"skill_count"`
|
||||
} `json:"tracked_repos"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(statusResult.Stdout), &output); err != nil {
|
||||
t.Fatalf("failed to parse status --json: %v\nstdout: %s", err, statusResult.Stdout)
|
||||
}
|
||||
const want = "org/_team-skills"
|
||||
for _, r := range output.TrackedRepos {
|
||||
if r.Name == want {
|
||||
if r.SkillCount == 0 {
|
||||
t.Fatalf("expected %s to count its skills, got %+v", want, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("tracked_repos should contain %q, got %+v", want, output.TrackedRepos)
|
||||
}
|
||||
|
||||
// TestInstall_Track_RootSkillMd_ReportsOneSkill verifies that the install
|
||||
// output correctly reports 1 skill (not 0) for a tracked repo whose only
|
||||
// SKILL.md is at the repo root. Phase B / AC1.
|
||||
|
||||
@@ -681,6 +681,26 @@ targets: {}
|
||||
result.AssertAnyOutputContains(t, "remaining")
|
||||
}
|
||||
|
||||
func TestUninstall_SkillInsideTrackedRepoIsRefused(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
repoPath := filepath.Join(sb.SourcePath, "_team")
|
||||
skillPath := filepath.Join(repoPath, "foo")
|
||||
os.MkdirAll(skillPath, 0755)
|
||||
os.WriteFile(filepath.Join(skillPath, "SKILL.md"), []byte("# Foo"), 0644)
|
||||
initGitRepo(t, repoPath)
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets: {}
|
||||
`)
|
||||
|
||||
result := sb.RunCLI("uninstall", "_team/foo", "--force")
|
||||
result.AssertAnyOutputContains(t, "uninstall the repo instead")
|
||||
if !sb.FileExists(skillPath) {
|
||||
t.Error("a skill inside a tracked repo must stay in the repo's checkout")
|
||||
}
|
||||
}
|
||||
|
||||
// makeUnreadableTrackedRepo creates a tracked repo whose `git status` fails
|
||||
// because its .git directory is empty.
|
||||
func makeUnreadableTrackedRepo(t *testing.T, sb *testutil.Sandbox, name string) string {
|
||||
|
||||
@@ -36,6 +36,8 @@ export interface Skill {
|
||||
linkName?: string;
|
||||
linkTarget?: string;
|
||||
isInRepo: boolean;
|
||||
/** Tracked repo root relative to the source (`_team`, or `org/_team` when installed with --into). */
|
||||
repoPath?: string;
|
||||
targets?: string[];
|
||||
installedAt?: string;
|
||||
source?: string;
|
||||
|
||||
@@ -20,6 +20,20 @@ const labels = (rows: ReturnType<typeof flattenTree>) =>
|
||||
rows.map((r) => `${' '.repeat(r.depth)}${r.type === 'folder' ? r.names.join(' / ') : r.skill.name}`);
|
||||
|
||||
describe('flattenTree', () => {
|
||||
it('gives a repo whose skill is its root SKILL.md its own repo row', () => {
|
||||
const rows = flattenTree(buildTree([skill('org/_repo', { isInRepo: true, repoPath: 'org/_repo' })]), new Set(), false);
|
||||
|
||||
expect(rows.map((r) => (r.type === 'folder' ? [r.names.join(' / '), r.repo] : [r.skill.name]))).toEqual([['org', false], ['_repo', true], ['_repo']]);
|
||||
});
|
||||
|
||||
it('marks a repo installed with --into as a repo root, not its parent folder', () => {
|
||||
const repo = { isInRepo: true, repoPath: 'org/_repo' };
|
||||
const rows = flattenTree(buildTree([skill('org/_repo/skills/x', repo)]), new Set(), false);
|
||||
|
||||
expect(rows.filter((r) => r.type === 'folder').map((r) => [r.names.join(' / '), r.type === 'folder' && r.repo]))
|
||||
.toEqual([['org', false], ['_repo', true], ['skills', false]]);
|
||||
});
|
||||
|
||||
it('merges chains of single-folder folders into one row, but never a tracked repo root', () => {
|
||||
expect(labels(flattenTree(buildTree(SKILLS), new Set(), false))).toEqual([
|
||||
'_repo',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Skill, SourceLink } from '../../api/client';
|
||||
import { sourceLinkOf } from '../../lib/resourceGrouping';
|
||||
import { repoOf, sourceLinkOf } from '../../lib/resourceGrouping';
|
||||
|
||||
/* Pure helpers behind the Skills page tree view: folder tree, visible rows, selection. */
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface FolderNode {
|
||||
skills: Skill[];
|
||||
count: number; // skills in this folder and every subfolder
|
||||
link?: SourceLink;
|
||||
repo?: boolean; // tracked repo root: _team, or org/_team when installed with --into
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,18 +49,20 @@ export function summarize(skills: Skill[]): TargetSummary {
|
||||
return { display: shown.length > 3 ? `${shown.length} targets` : shown.join(', '), targets: shown, isUniform };
|
||||
}
|
||||
|
||||
/** A tracked repo is a top-level folder whose name starts with "_". */
|
||||
/** A tracked repo root, as marked by buildTree from its skills' repo paths. */
|
||||
export function isRepoRoot(node: FolderNode): boolean {
|
||||
return !node.path.includes('/') && node.name.startsWith('_');
|
||||
return !!node.repo;
|
||||
}
|
||||
|
||||
export function buildTree(skills: Skill[], links: SourceLink[] = []): FolderNode {
|
||||
const root: FolderNode = { name: '', path: '', children: new Map(), skills: [], count: 0 };
|
||||
for (const skill of skills) {
|
||||
const link = sourceLinkOf(skill);
|
||||
const repo = repoOf(skill);
|
||||
const slash = skill.relPath.lastIndexOf('/');
|
||||
let node = root;
|
||||
const parent = slash > 0 ? skill.relPath.slice(0, slash) : link?.name;
|
||||
// A repo's root SKILL.md sits in the repo's own folder, so the repo gets its row.
|
||||
const parent = skill.relPath === repo ? repo : slash > 0 ? skill.relPath.slice(0, slash) : link?.name;
|
||||
if (parent) {
|
||||
for (const seg of parent.split('/')) {
|
||||
if (!node.children.has(seg)) {
|
||||
@@ -68,6 +71,7 @@ export function buildTree(skills: Skill[], links: SourceLink[] = []): FolderNode
|
||||
}
|
||||
node = node.children.get(seg)!;
|
||||
if (node.path === link?.name) node.link = link;
|
||||
if (node.path === repo) node.repo = true;
|
||||
}
|
||||
}
|
||||
node.skills.push(skill);
|
||||
@@ -97,7 +101,9 @@ export function flattenTree(root: FolderNode, collapsed: ReadonlySet<string>, ex
|
||||
const names = [child.name];
|
||||
// Repo and link roots keep their own row so their tags and actions stay visible.
|
||||
while (!repo && !child.link && deepest.skills.length === 0 && deepest.children.size === 1) {
|
||||
deepest = deepest.children.values().next().value!;
|
||||
const next = deepest.children.values().next().value!;
|
||||
if (isRepoRoot(next)) break; // an --into repo (org/_team) keeps its own row too
|
||||
deepest = next;
|
||||
names.push(deepest.name);
|
||||
}
|
||||
const isCollapsed = !expandAll && collapsed.has(deepest.path);
|
||||
|
||||
@@ -5,7 +5,7 @@ import { api, ApiError, type Skill } from '../../api/client';
|
||||
import { composeSkillMarkdown, parseSkillMarkdown, type Frontmatter } from '../../lib/frontmatter';
|
||||
import { highlightLines } from '../../lib/highlight';
|
||||
import { parseRemoteURL } from '../../lib/parseRemoteURL';
|
||||
import { formatTrackedRepoName } from '../../lib/resourceNames';
|
||||
import { folderOf, formatTrackedRepoName } from '../../lib/resourceNames';
|
||||
import { useI18n, useT, plural } from '../../i18n';
|
||||
import Button from '../Button';
|
||||
import ConfirmDialog from '../ConfirmDialog';
|
||||
@@ -199,7 +199,7 @@ export default function SkillEditor({ resource, docName, initialContent, onBack,
|
||||
const bodyLines = useMemo(() => highlightLines(body, 'md'), [body]);
|
||||
const gutter = `calc(30px + ${String(bodyLines.length).length}ch)`;
|
||||
const repo = resource.isInRepo
|
||||
? parseRemoteURL(resource.repoUrl)?.ownerRepo ?? formatTrackedRepoName(resource.relPath.split('/')[0])
|
||||
? parseRemoteURL(resource.repoUrl)?.ownerRepo ?? formatTrackedRepoName(folderOf(resource))
|
||||
: '';
|
||||
|
||||
return (
|
||||
|
||||
@@ -30,6 +30,13 @@ describe('groupBySource', () => {
|
||||
|
||||
expect(groups.map((g) => [g.key, g.items.length])).toEqual([['_repo-a', 2], ['_repo-b', 1], ['local', 1]]);
|
||||
});
|
||||
|
||||
it('groups a repo installed with --into under its full repo path', () => {
|
||||
const repo = { isInRepo: true, type: 'tracked', repoPath: 'org/_repo' };
|
||||
const groups = groupBySource([skill('org/_repo/skills/x', repo), skill('org/_repo/skills/y', repo)]);
|
||||
|
||||
expect(groups.map((g) => [g.key, g.items.length])).toEqual([['org/_repo', 2]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('groupByFolder', () => {
|
||||
|
||||
@@ -74,7 +74,7 @@ export function sortSkills(skills: Skill[], sortType: SortType): Skill[] {
|
||||
}
|
||||
|
||||
export function repoOf(s: Skill): string | undefined {
|
||||
return s.isInRepo ? s.relPath.split('/')[0] : undefined;
|
||||
return s.isInRepo ? folderOf(s) : undefined;
|
||||
}
|
||||
|
||||
export function sourceLinkOf(s: Skill): SourceLink | undefined {
|
||||
|
||||
@@ -11,8 +11,8 @@ export function formatTrackedRepoName(name: string): string {
|
||||
}
|
||||
|
||||
/** Folder a skill or agent lives in: its tracked repo, else its full parent path; '' at the source root. */
|
||||
export function folderOf(resource: { relPath: string; isInRepo: boolean }): string {
|
||||
if (resource.isInRepo) return resource.relPath.split('/')[0];
|
||||
export function folderOf(resource: { relPath: string; isInRepo: boolean; repoPath?: string }): string {
|
||||
if (resource.isInRepo) return resource.repoPath ?? resource.relPath.split('/')[0];
|
||||
const i = resource.relPath.lastIndexOf('/');
|
||||
return i > 0 ? resource.relPath.slice(0, i) : '';
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import { parseSkillMarkdown } from '../lib/frontmatter';
|
||||
import { isMarkdown } from '../lib/highlight';
|
||||
import { parseRemoteURL } from '../lib/parseRemoteURL';
|
||||
import { resourceHref } from '../lib/resourceNames';
|
||||
import { sourceLinkOf } from '../lib/resourceGrouping';
|
||||
import { repoOf, sourceLinkOf } from '../lib/resourceGrouping';
|
||||
import { targetFilterPatch } from '../lib/targetFilter';
|
||||
import { useSyncMatrix } from '../hooks/useSyncMatrix';
|
||||
import { projectUrl } from '../components/projects/projectView';
|
||||
@@ -142,7 +142,7 @@ export default function ResourceDetailPage() {
|
||||
const runUpdate = async (skipAudit: boolean) => {
|
||||
setUpdating(true);
|
||||
try {
|
||||
const target = resource.isInRepo ? resource.relPath.split('/')[0] : isAgent ? resource.flatName : resource.relPath;
|
||||
const target = repoOf(resource) ?? (isAgent ? resource.flatName : resource.relPath);
|
||||
const res = await api.update({ name: target, kind: resource.kind, skipAudit });
|
||||
const item = res.results[0];
|
||||
if (item?.action === 'updated') {
|
||||
|
||||
@@ -7,7 +7,8 @@ import type { CheckResult, LinkedRepo, Skill, UpdateResultItem } from '../api/cl
|
||||
import { queryKeys, staleTimes } from '../lib/queryKeys';
|
||||
import { clearAuditCache } from '../lib/auditCache';
|
||||
import { parseRemoteURL } from '../lib/parseRemoteURL';
|
||||
import { formatTrackedRepoName } from '../lib/resourceNames';
|
||||
import { folderOf, formatTrackedRepoName } from '../lib/resourceNames';
|
||||
import { repoOf } from '../lib/resourceGrouping';
|
||||
import { formatRelativeTime, useI18n, useT } from '../i18n';
|
||||
import Button from '../components/Button';
|
||||
import { Checkbox } from '../components/Checkbox';
|
||||
@@ -90,7 +91,7 @@ export function updateUnits(resources: Skill[], kind: Kind, linkedRepos: LinkedR
|
||||
units.push({ name: s.relPath, label: s.name, isRepo: false, items: [s], source: s.source });
|
||||
continue;
|
||||
}
|
||||
const dir = s.relPath.split('/')[0];
|
||||
const dir = folderOf(s);
|
||||
let unit = repos.get(dir);
|
||||
if (!unit) {
|
||||
unit = { name: dir, label: formatTrackedRepoName(dir), isRepo: true, items: [], source: s.repoUrl ?? s.source };
|
||||
@@ -185,7 +186,7 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
|
||||
? { status: 'error', message: repo.message, checkedAt }
|
||||
: { status: 'up-to-date', message: repo.message, checkedAt };
|
||||
for (const item of updatable) {
|
||||
if (!item.isInRepo || item.relPath.split('/')[0] !== repo.name) continue;
|
||||
if (repoOf(item) !== repo.name) continue;
|
||||
next.set(item.name, repoStatus);
|
||||
pending.delete(item.name);
|
||||
}
|
||||
@@ -258,7 +259,7 @@ export default function UpdatePage({ kind }: { kind: Kind }) {
|
||||
if (!isSuccessfulUpdateAction(result.action)) continue;
|
||||
for (const item of updatable) {
|
||||
const hit = result.isRepo
|
||||
? item.isInRepo && item.relPath.split('/')[0] === result.name
|
||||
? repoOf(item) === result.name
|
||||
: !item.isInRepo && matchesCheckSkill(item, result.name);
|
||||
if (hit) next.set(item.name, { ...status, message: result.message });
|
||||
}
|
||||
|
||||
@@ -174,11 +174,14 @@ For tracked repositories (folders starting with `_`):
|
||||
- Fails with `failed to check git status` when skillshare cannot read the repo's git status; other items in the batch are still removed, and `--force` skips the check
|
||||
- Automatically removes the entry from `.gitignore`
|
||||
- The `_` prefix is optional when uninstalling
|
||||
- A repo installed with `--into` is named by its path, such as `devops/_team-skills`
|
||||
- A skill or folder inside a tracked repo cannot be removed on its own, even with `--force`; the command fails with `inside a tracked repo; uninstall the repo instead`. Skills below a followed source link can still be removed one at a time
|
||||
|
||||
```bash
|
||||
skillshare uninstall _team-skills # With prefix
|
||||
skillshare uninstall team-skills # Without prefix (auto-detected)
|
||||
skillshare uninstall _team-skills --force # Force remove with uncommitted changes
|
||||
skillshare uninstall devops/_team-skills # Repo installed with --into devops
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -67,6 +67,8 @@ Tracked repos are prefixed with `_` to distinguish them from regular skills:
|
||||
└── _team-skills/ # Tracked repo (underscore prefix)
|
||||
```
|
||||
|
||||
A tracked repo installed with `--into` sits inside a folder, such as `devops/_team-skills/`. It is still treated as one repo: its skills are grouped under it, `status` counts them, and you update or uninstall it as `devops/_team-skills`. Below the top level, an `_` folder counts as a tracked repo only when it is a git clone, so a plain folder like `devops/_drafts/` stays a regular folder.
|
||||
|
||||
---
|
||||
|
||||
## Nested Skills & Auto-Flattening {#nested-skills--auto-flattening}
|
||||
|
||||
@@ -174,11 +174,14 @@ tracked repositories(`_` で始まるフォルダ)の場合:
|
||||
- skillshare がリポジトリの git status を読み取れない場合は `failed to check git status` で失敗します。バッチ内の他の項目は引き続き削除され、`--force` を使うとこのチェックをスキップします
|
||||
- `.gitignore` からエントリを自動的に削除します
|
||||
- uninstall 時に `_` prefix は省略可能です
|
||||
- `--into` でインストールしたリポジトリは `devops/_team-skills` のようにパスで指定します
|
||||
- 追跡リポジトリ内の Skill やフォルダは、`--force` を付けても単独では削除できず、`inside a tracked repo; uninstall the repo instead` で失敗します。followed source link 配下の Skill は 1 つずつ削除できます
|
||||
|
||||
```bash
|
||||
skillshare uninstall _team-skills # prefix 付き
|
||||
skillshare uninstall team-skills # prefix なし(自動検出)
|
||||
skillshare uninstall _team-skills --force # 未コミットの変更があっても強制削除
|
||||
skillshare uninstall devops/_team-skills # --into devops でインストールしたリポジトリ
|
||||
```
|
||||
|
||||
## 例
|
||||
|
||||
+2
@@ -67,6 +67,8 @@ skillshare sync
|
||||
└── _team-skills/ # Tracked repo (underscore prefix)
|
||||
```
|
||||
|
||||
`--into` でインストールした追跡リポジトリは、`devops/_team-skills/` のようにフォルダの中に置かれます。それでも 1 つのリポジトリとして扱われます。中の Skill はその下にまとめられ、`status` でも数えられ、更新やアンインストールには `devops/_team-skills` という名前を使います。最上位より下では、git clone された `_` フォルダだけが追跡リポジトリとみなされるため、`devops/_drafts/` のような普通のフォルダは通常のフォルダのままです。
|
||||
|
||||
---
|
||||
|
||||
## ネストされた Skill と自動フラット化 {#nested-skills--auto-flattening}
|
||||
|
||||
@@ -174,11 +174,14 @@ tracked repository(`_`로 시작하는 폴더)의 경우:
|
||||
- skillshare가 repo의 git status를 읽을 수 없으면 `failed to check git status`로 실패합니다. 배치의 다른 항목은 계속 제거되며, `--force`를 사용하면 이 확인을 건너뜁니다
|
||||
- `.gitignore`에서 항목을 자동으로 제거합니다
|
||||
- uninstall 시 `_` 접두사는 선택 사항입니다
|
||||
- `--into`로 설치한 repo는 `devops/_team-skills`처럼 경로로 지정합니다
|
||||
- tracked repo 안의 skill이나 폴더는 `--force`를 붙여도 따로 제거할 수 없으며, `inside a tracked repo; uninstall the repo instead`로 실패합니다. followed source link 아래의 skill은 하나씩 제거할 수 있습니다
|
||||
|
||||
```bash
|
||||
skillshare uninstall _team-skills # With prefix
|
||||
skillshare uninstall team-skills # Without prefix (auto-detected)
|
||||
skillshare uninstall _team-skills --force # Force remove with uncommitted changes
|
||||
skillshare uninstall devops/_team-skills # Repo installed with --into devops
|
||||
```
|
||||
|
||||
## 예시
|
||||
|
||||
+2
@@ -67,6 +67,8 @@ Tracked repo는 일반 skill과 구분하기 위해 `_` 접두사가 붙습니
|
||||
└── _team-skills/ # Tracked repo (underscore prefix)
|
||||
```
|
||||
|
||||
`--into`로 설치한 tracked repo는 `devops/_team-skills/`처럼 폴더 안에 놓입니다. 그래도 하나의 repo로 취급됩니다. 안에 있는 skill은 그 아래로 묶이고, `status`에서도 집계되며, 업데이트나 제거할 때는 `devops/_team-skills`라는 이름을 사용합니다. 최상위 아래에서는 git clone된 `_` 폴더만 tracked repo로 간주되므로, `devops/_drafts/` 같은 일반 폴더는 그대로 일반 폴더입니다.
|
||||
|
||||
---
|
||||
|
||||
## 중첩 Skill과 자동 평탄화 {#nested-skills--auto-flattening}
|
||||
|
||||
+3
@@ -179,11 +179,14 @@ skillshare uninstall frontend/hooks -G frontend --force # hooks removed once
|
||||
- 当 skillshare 无法读取该仓库的 git status 时,以 `failed to check git status` 失败;批次中的其他项目仍会被移除,`--force` 会跳过此检查
|
||||
- 自动从 `.gitignore` 中移除该条目
|
||||
- Uninstall 时 `_` 前缀是可选的
|
||||
- 用 `--into` 安装的 repo 以路径命名,例如 `devops/_team-skills`
|
||||
- tracked repo 中的 Skill 或文件夹不能单独移除,加上 `--force` 也一样;命令会以 `inside a tracked repo; uninstall the repo instead` 失败。位于 followed source link 下的 Skill 仍可逐个移除
|
||||
|
||||
```bash
|
||||
skillshare uninstall _team-skills # With prefix
|
||||
skillshare uninstall team-skills # Without prefix (auto-detected)
|
||||
skillshare uninstall _team-skills --force # Force remove with uncommitted changes
|
||||
skillshare uninstall devops/_team-skills # Repo installed with --into devops
|
||||
```
|
||||
|
||||
## 示例
|
||||
|
||||
+2
@@ -67,6 +67,8 @@ Tracked repos 会以 `_` 为前缀,以便与普通 Skill 区分:
|
||||
└── _team-skills/ # Tracked Repo(下划线前缀)
|
||||
```
|
||||
|
||||
用 `--into` 安装的 tracked repo 会放在文件夹里,例如 `devops/_team-skills/`。它仍然被视为一个 repo:其中的 Skill 会归在它下面,`status` 会统计这些 Skill,更新或卸载时使用 `devops/_team-skills` 这个名称。在第一层以下,只有 git clone 得到的 `_` 文件夹才算 tracked repo,因此像 `devops/_drafts/` 这样的普通文件夹仍是普通文件夹。
|
||||
|
||||
---
|
||||
|
||||
## 嵌套 Skill 与自动扁平化 {#nested-skills--auto-flattening}
|
||||
|
||||
+3
@@ -174,11 +174,14 @@ skillshare uninstall frontend/hooks -G frontend --force # hooks 只會被移除
|
||||
- 當 skillshare 無法讀取該儲存庫的 git status 時,會以 `failed to check git status` 失敗;批次中的其他項目仍會被移除,`--force` 會略過此檢查
|
||||
- 自動從 `.gitignore` 移除該項目
|
||||
- 解除安裝時 `_` 前綴為選填
|
||||
- 用 `--into` 安裝的 repo 以路徑命名,例如 `devops/_team-skills`
|
||||
- tracked repo 裡的 skill 或資料夾不能單獨移除,加上 `--force` 也一樣;指令會以 `inside a tracked repo; uninstall the repo instead` 失敗。位於 followed source link 底下的 skill 仍可逐一移除
|
||||
|
||||
```bash
|
||||
skillshare uninstall _team-skills # 含前綴
|
||||
skillshare uninstall team-skills # 不含前綴(自動偵測)
|
||||
skillshare uninstall _team-skills --force # 強制移除,即使有未提交的變更
|
||||
skillshare uninstall devops/_team-skills # 用 --into devops 安裝的 repo
|
||||
```
|
||||
|
||||
## 範例
|
||||
|
||||
+2
@@ -67,6 +67,8 @@ Tracked repos 會以 `_` 為前綴,以便與一般 skills 區分:
|
||||
└── _team-skills/ # Tracked repo (underscore prefix)
|
||||
```
|
||||
|
||||
用 `--into` 安裝的 tracked repo 會放在資料夾裡,例如 `devops/_team-skills/`。它仍然視為一個 repo:裡面的 skills 會歸在它底下,`status` 會計入這些 skills,更新或解除安裝時使用 `devops/_team-skills` 這個名稱。在第一層以下,只有 git clone 出來的 `_` 資料夾才算 tracked repo,所以像 `devops/_drafts/` 這樣的一般資料夾仍是普通資料夾。
|
||||
|
||||
---
|
||||
|
||||
## 巢狀 Skills 與自動扁平化 {#nested-skills--auto-flattening}
|
||||
|
||||
Reference in New Issue
Block a user