mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-18 18:04:17 +00:00
feat: add hub persistence to config for CLI and Web UI
Hub sources are now saved in config.yaml (both global and project), replacing the Web UI's localStorage-based approach. This allows CLI and UI to share the same hub list. - Add HubConfig/HubEntry types and helper methods (resolve, add, remove) - Add CLI subcommands: hub add/list/remove/default - Search --hub now resolves saved labels (e.g. --hub team) - Add REST API endpoints for hub CRUD (GET/PUT/POST/DELETE /api/hub/saved) - Migrate SearchPage from localStorage to server API calls
This commit is contained in:
@@ -1,5 +1,30 @@
|
||||
# Changelog
|
||||
|
||||
## [0.12.1] - 2026-02-13
|
||||
|
||||
### Added
|
||||
- **Hub persistence** — saved hubs stored in `config.yaml` (both global and project), shared between CLI and Web UI
|
||||
- `hub add <url>` — save a hub source (`--label` to name it; first add auto-sets as default)
|
||||
- `hub list` — list saved hubs (`*` marks default)
|
||||
- `hub remove <label>` — remove a saved hub
|
||||
- `hub default [label]` — show or set the default hub (`--reset` to clear)
|
||||
- All subcommands support `--project` / `--global` mode
|
||||
- **Hub label resolution in search** — `search --hub <label>` resolves saved hub labels instead of requiring full URLs
|
||||
- `search --hub team` looks up the "team" hub from config
|
||||
- `search --hub` (bare) uses the config default, falling back to community hub
|
||||
- **Hub saved API** — REST endpoints for hub CRUD (`GET/PUT/POST/DELETE /api/hub/saved`)
|
||||
- **Web UI hub persistence** — hub list and default hub now persisted on server instead of browser localStorage
|
||||
- **Search fuzzy filter** — hub search results filtered by fuzzy match on name + substring match on description and tags
|
||||
- **Tag badges in search** — `#tag` badges displayed in both CLI interactive selector and Web UI hub search results
|
||||
- **Web UI tag filter** — inline filter input on hub search cards matching name, description, and tags
|
||||
|
||||
### Changed
|
||||
- `search --hub` (bare flag) now defaults to community skillshare-hub instead of requiring a URL
|
||||
- Web UI SearchPage migrated from localStorage to server API for hub state
|
||||
|
||||
### Fixed
|
||||
- `audit <path>` no longer fails with "config not found" in CI environments without a skillshare config
|
||||
|
||||
## [0.12.0] - 2026-02-13
|
||||
|
||||
### Added
|
||||
|
||||
+78
-6
@@ -17,14 +17,82 @@ func cmdHub(args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch args[0] {
|
||||
subcmd := args[0]
|
||||
subargs := args[1:]
|
||||
|
||||
// For subcommands that support --project/--global, parse mode
|
||||
switch subcmd {
|
||||
case "index":
|
||||
return cmdHubIndex(args[1:])
|
||||
return cmdHubIndex(subargs)
|
||||
case "add":
|
||||
mode, rest, err := parseModeArgs(subargs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine working directory: %w", err)
|
||||
}
|
||||
if mode == modeAuto && projectConfigExists(cwd) {
|
||||
mode = modeProject
|
||||
} else if mode == modeAuto {
|
||||
mode = modeGlobal
|
||||
}
|
||||
applyModeLabel(mode)
|
||||
return cmdHubAdd(rest, mode, cwd)
|
||||
case "list", "ls":
|
||||
mode, _, err := parseModeArgs(subargs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine working directory: %w", err)
|
||||
}
|
||||
if mode == modeAuto && projectConfigExists(cwd) {
|
||||
mode = modeProject
|
||||
} else if mode == modeAuto {
|
||||
mode = modeGlobal
|
||||
}
|
||||
applyModeLabel(mode)
|
||||
return cmdHubList(mode, cwd)
|
||||
case "remove", "rm":
|
||||
mode, rest, err := parseModeArgs(subargs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine working directory: %w", err)
|
||||
}
|
||||
if mode == modeAuto && projectConfigExists(cwd) {
|
||||
mode = modeProject
|
||||
} else if mode == modeAuto {
|
||||
mode = modeGlobal
|
||||
}
|
||||
applyModeLabel(mode)
|
||||
return cmdHubRemove(rest, mode, cwd)
|
||||
case "default":
|
||||
mode, rest, err := parseModeArgs(subargs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine working directory: %w", err)
|
||||
}
|
||||
if mode == modeAuto && projectConfigExists(cwd) {
|
||||
mode = modeProject
|
||||
} else if mode == modeAuto {
|
||||
mode = modeGlobal
|
||||
}
|
||||
applyModeLabel(mode)
|
||||
return cmdHubDefault(rest, mode, cwd)
|
||||
case "help", "-h", "--help":
|
||||
printHubHelp()
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unknown hub subcommand: %s\nRun 'skillshare hub help' for usage", args[0])
|
||||
return fmt.Errorf("unknown hub subcommand: %s\nRun 'skillshare hub help' for usage", subcmd)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,11 +229,15 @@ func resolveSourcePath(mode runMode, cwd string) (string, error) {
|
||||
func printHubHelp() {
|
||||
fmt.Println(`Usage: skillshare hub <subcommand> [options]
|
||||
|
||||
Manage private skill hubs.
|
||||
Manage skill hubs — saved hub sources for search.
|
||||
|
||||
Subcommands:
|
||||
index Build an index.json from source skills
|
||||
help Show this help
|
||||
add <url> Save a hub source (--label to set name)
|
||||
list List saved hubs (* marks default)
|
||||
remove <label> Remove a saved hub
|
||||
default [label] Show or set the default hub (--reset to clear)
|
||||
index Build an index.json from source skills
|
||||
help Show this help
|
||||
|
||||
Run 'skillshare hub <subcommand> --help' for details.`)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/ui"
|
||||
)
|
||||
|
||||
func cmdHubAdd(args []string, mode runMode, cwd string) error {
|
||||
var hubURL string
|
||||
var label string
|
||||
|
||||
i := 0
|
||||
for i < len(args) {
|
||||
arg := args[i]
|
||||
key, val, hasEq := strings.Cut(arg, "=")
|
||||
switch {
|
||||
case key == "--label" || key == "-l":
|
||||
if hasEq {
|
||||
label = strings.TrimSpace(val)
|
||||
} else if i+1 >= len(args) {
|
||||
return fmt.Errorf("--label requires a value")
|
||||
} else {
|
||||
i++
|
||||
label = strings.TrimSpace(args[i])
|
||||
}
|
||||
case key == "--help" || key == "-h":
|
||||
printHubAddHelp()
|
||||
return nil
|
||||
case strings.HasPrefix(arg, "-"):
|
||||
return fmt.Errorf("unknown option: %s", arg)
|
||||
default:
|
||||
if hubURL != "" {
|
||||
return fmt.Errorf("unexpected argument: %s", arg)
|
||||
}
|
||||
hubURL = strings.TrimSpace(arg)
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
if hubURL == "" {
|
||||
return fmt.Errorf("usage: skillshare hub add <url> [--label name]")
|
||||
}
|
||||
|
||||
// Derive label from URL if not provided
|
||||
if label == "" {
|
||||
label = deriveLabelFromURL(hubURL)
|
||||
}
|
||||
|
||||
hubCfg, saveFn, err := loadHubConfigForWrite(mode, cwd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := hubCfg.AddHub(config.HubEntry{Label: label, URL: hubURL}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// First add auto-sets default
|
||||
if len(hubCfg.Hubs) == 1 {
|
||||
hubCfg.Default = label
|
||||
}
|
||||
|
||||
if err := saveFn(*hubCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ui.Success("Added hub %q → %s", label, hubURL)
|
||||
if hubCfg.Default == label {
|
||||
ui.Info("Set as default hub")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cmdHubList(mode runMode, cwd string) error {
|
||||
hubCfg, err := loadHubConfigForRead(mode, cwd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(hubCfg.Hubs) == 0 {
|
||||
ui.Info("No saved hubs. Use 'skillshare hub add <url>' to add one.")
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, h := range hubCfg.Hubs {
|
||||
marker := " "
|
||||
if strings.EqualFold(h.Label, hubCfg.Default) {
|
||||
marker = "* "
|
||||
}
|
||||
annotation := ""
|
||||
if h.BuiltIn {
|
||||
annotation = " (built-in)"
|
||||
}
|
||||
fmt.Printf("%s%-20s %s%s\n", marker, h.Label, h.URL, annotation)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cmdHubRemove(args []string, mode runMode, cwd string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: skillshare hub remove <label>")
|
||||
}
|
||||
label := strings.TrimSpace(args[0])
|
||||
|
||||
hubCfg, saveFn, err := loadHubConfigForWrite(mode, cwd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := hubCfg.RemoveHub(label); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := saveFn(*hubCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ui.Success("Removed hub %q", label)
|
||||
return nil
|
||||
}
|
||||
|
||||
func cmdHubDefault(args []string, mode runMode, cwd string) error {
|
||||
var reset bool
|
||||
var label string
|
||||
|
||||
for _, arg := range args {
|
||||
switch arg {
|
||||
case "--reset":
|
||||
reset = true
|
||||
case "--help", "-h":
|
||||
printHubDefaultHelp()
|
||||
return nil
|
||||
default:
|
||||
if strings.HasPrefix(arg, "-") {
|
||||
return fmt.Errorf("unknown option: %s", arg)
|
||||
}
|
||||
label = strings.TrimSpace(arg)
|
||||
}
|
||||
}
|
||||
|
||||
hubCfg, saveFn, err := loadHubConfigForWrite(mode, cwd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Show current default
|
||||
if label == "" && !reset {
|
||||
if hubCfg.Default == "" {
|
||||
ui.Info("No default hub set (using community hub)")
|
||||
} else {
|
||||
url, ok := hubCfg.ResolveHub(hubCfg.Default)
|
||||
if ok {
|
||||
fmt.Printf("%s → %s\n", hubCfg.Default, url)
|
||||
} else {
|
||||
fmt.Printf("%s (label not found in hubs)\n", hubCfg.Default)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reset default
|
||||
if reset {
|
||||
hubCfg.Default = ""
|
||||
if err := saveFn(*hubCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
ui.Success("Default hub cleared (using community hub)")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Set default
|
||||
if !hubCfg.HasHub(label) {
|
||||
return fmt.Errorf("hub %q not found; run 'skillshare hub list' to see available hubs", label)
|
||||
}
|
||||
hubCfg.Default = label
|
||||
if err := saveFn(*hubCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
ui.Success("Default hub set to %q", label)
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadHubConfigForRead loads the HubConfig from the appropriate config.
|
||||
func loadHubConfigForRead(mode runMode, cwd string) (*config.HubConfig, error) {
|
||||
if mode == modeProject {
|
||||
pcfg, err := config.LoadProject(cwd)
|
||||
if err != nil {
|
||||
return &config.HubConfig{}, nil // graceful fallback
|
||||
}
|
||||
return &pcfg.Hub, nil
|
||||
}
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return &config.HubConfig{}, nil // graceful fallback
|
||||
}
|
||||
return &cfg.Hub, nil
|
||||
}
|
||||
|
||||
// loadHubConfigForWrite loads the HubConfig and returns a save function.
|
||||
func loadHubConfigForWrite(mode runMode, cwd string) (*config.HubConfig, func(config.HubConfig) error, error) {
|
||||
if mode == modeProject {
|
||||
pcfg, err := config.LoadProject(cwd)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to load project config: %w", err)
|
||||
}
|
||||
saveFn := func(h config.HubConfig) error {
|
||||
pcfg.Hub = h
|
||||
return pcfg.Save(cwd)
|
||||
}
|
||||
return &pcfg.Hub, saveFn, nil
|
||||
}
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to load config: %w", err)
|
||||
}
|
||||
saveFn := func(h config.HubConfig) error {
|
||||
cfg.Hub = h
|
||||
return cfg.Save()
|
||||
}
|
||||
return &cfg.Hub, saveFn, nil
|
||||
}
|
||||
|
||||
// deriveLabelFromURL extracts a short label from a URL or path.
|
||||
func deriveLabelFromURL(rawURL string) string {
|
||||
// Try parsing as URL
|
||||
if u, err := url.Parse(rawURL); err == nil && u.Host != "" {
|
||||
// Use last meaningful path segment
|
||||
p := strings.TrimSuffix(u.Path, "/")
|
||||
base := filepath.Base(p)
|
||||
base = strings.TrimSuffix(base, filepath.Ext(base))
|
||||
if base != "" && base != "." {
|
||||
return base
|
||||
}
|
||||
return u.Host
|
||||
}
|
||||
// File path: use filename without extension
|
||||
base := filepath.Base(rawURL)
|
||||
base = strings.TrimSuffix(base, filepath.Ext(base))
|
||||
if base != "" && base != "." {
|
||||
return base
|
||||
}
|
||||
return rawURL
|
||||
}
|
||||
|
||||
func printHubAddHelp() {
|
||||
fmt.Println(`Usage: skillshare hub add <url> [options]
|
||||
|
||||
Add a hub source to your saved hubs list.
|
||||
|
||||
Options:
|
||||
--label, -l <name> Label for the hub (default: derived from URL)
|
||||
--project, -p Use project mode
|
||||
--global, -g Use global mode
|
||||
--help, -h Show this help
|
||||
|
||||
Examples:
|
||||
skillshare hub add https://internal.corp/skills/hub.json
|
||||
skillshare hub add https://internal.corp/hub.json --label team
|
||||
skillshare hub add ./skillshare-hub.json --label local`)
|
||||
}
|
||||
|
||||
func printHubDefaultHelp() {
|
||||
fmt.Println(`Usage: skillshare hub default [label] [options]
|
||||
|
||||
Show or set the default hub. When set, 'search --hub' uses this hub
|
||||
instead of the community hub.
|
||||
|
||||
Options:
|
||||
--reset Clear default (revert to community hub)
|
||||
--project, -p Use project mode
|
||||
--global, -g Use global mode
|
||||
--help, -h Show this help
|
||||
|
||||
Examples:
|
||||
skillshare hub default Show current default
|
||||
skillshare hub default team Set default to "team"
|
||||
skillshare hub default --reset Clear default`)
|
||||
}
|
||||
@@ -180,7 +180,7 @@ func printUsage() {
|
||||
// Utilities
|
||||
fmt.Println("UTILITIES")
|
||||
cmd("audit", "[name]", "Scan skills for security threats")
|
||||
cmd("hub", "index", "Build index.json for private skill search")
|
||||
cmd("hub", "<subcommand>", "Manage hubs (add, list, remove, default, index)")
|
||||
cmd("log", "", "View operation log")
|
||||
cmd("ui", "", "Launch web dashboard")
|
||||
cmd("doctor", "", "Check environment and diagnose issues")
|
||||
|
||||
@@ -45,7 +45,8 @@ func cmdSearch(args []string) error {
|
||||
var query string
|
||||
var jsonOutput bool
|
||||
var listOnly bool
|
||||
var indexURL string
|
||||
var hubInput string // raw --hub value
|
||||
var hubBare bool // --hub with no value
|
||||
var limit int = 20
|
||||
|
||||
// Parse remaining arguments
|
||||
@@ -60,12 +61,12 @@ func cmdSearch(args []string) error {
|
||||
listOnly = true
|
||||
case key == "--hub":
|
||||
if hasEq {
|
||||
indexURL = strings.TrimSpace(val)
|
||||
hubInput = strings.TrimSpace(val)
|
||||
} else if i+1 < len(rest) && !strings.HasPrefix(rest[i+1], "-") {
|
||||
i++
|
||||
indexURL = strings.TrimSpace(rest[i])
|
||||
hubInput = strings.TrimSpace(rest[i])
|
||||
} else {
|
||||
indexURL = defaultHubURL
|
||||
hubBare = true
|
||||
}
|
||||
case key == "--limit" || key == "-n":
|
||||
if hasEq {
|
||||
@@ -100,6 +101,16 @@ func cmdSearch(args []string) error {
|
||||
i++
|
||||
}
|
||||
|
||||
// Resolve --hub value to a URL
|
||||
var indexURL string
|
||||
if hubInput != "" || hubBare {
|
||||
resolved, err := resolveHubURL(hubInput, hubBare, mode, cwd, defaultHubURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
indexURL = resolved
|
||||
}
|
||||
|
||||
// JSON mode: silent search, output JSON
|
||||
if jsonOutput {
|
||||
return searchJSON(query, limit, indexURL)
|
||||
@@ -654,5 +665,72 @@ Examples:
|
||||
skillshare search --hub Browse skillshare-hub
|
||||
skillshare search react --hub Search "react" in skillshare-hub
|
||||
skillshare search --hub ./skillshare-hub.json Custom local index
|
||||
skillshare search react --hub https://internal.corp/skills/index.json`)
|
||||
skillshare search react --hub https://internal.corp/skills/index.json
|
||||
|
||||
# Hub search with saved hubs
|
||||
skillshare hub add https://internal.corp/hub.json --label team
|
||||
skillshare search --hub team Search using saved hub label
|
||||
skillshare hub default team
|
||||
skillshare search --hub Uses default hub`)
|
||||
}
|
||||
|
||||
// resolveHubURL resolves the --hub flag value to a URL.
|
||||
// - bare=true, input="" → config default → fallback to defaultHubURL
|
||||
// - input looks like URL/path → passthrough
|
||||
// - otherwise → label lookup in config
|
||||
func resolveHubURL(input string, bare bool, mode runMode, cwd, defaultHubURL string) (string, error) {
|
||||
if bare && input == "" {
|
||||
// --hub with no value: try config default, then community hub
|
||||
hubCfg := loadHubConfig(mode, cwd)
|
||||
url, err := hubCfg.DefaultHub()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if url != "" {
|
||||
return url, nil
|
||||
}
|
||||
return defaultHubURL, nil
|
||||
}
|
||||
|
||||
// Check if input looks like a URL or path
|
||||
if looksLikeURLOrPath(input) {
|
||||
return input, nil
|
||||
}
|
||||
|
||||
// Try label lookup
|
||||
hubCfg := loadHubConfig(mode, cwd)
|
||||
url, ok := hubCfg.ResolveHub(input)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("hub %q not found; run 'skillshare hub list' to see saved hubs", input)
|
||||
}
|
||||
return url, nil
|
||||
}
|
||||
|
||||
// looksLikeURLOrPath returns true if the value appears to be a URL or file path
|
||||
// rather than a hub label.
|
||||
func looksLikeURLOrPath(v string) bool {
|
||||
return strings.HasPrefix(v, "http://") ||
|
||||
strings.HasPrefix(v, "https://") ||
|
||||
strings.HasPrefix(v, "file://") ||
|
||||
strings.HasPrefix(v, "/") ||
|
||||
strings.HasPrefix(v, "./") ||
|
||||
strings.HasPrefix(v, "../") ||
|
||||
strings.HasPrefix(v, "~")
|
||||
}
|
||||
|
||||
// loadHubConfig loads the HubConfig from the appropriate config, returning
|
||||
// an empty HubConfig on error (graceful fallback).
|
||||
func loadHubConfig(mode runMode, cwd string) config.HubConfig {
|
||||
if mode == modeProject {
|
||||
pcfg, err := config.LoadProject(cwd)
|
||||
if err != nil {
|
||||
return config.HubConfig{}
|
||||
}
|
||||
return pcfg.Hub
|
||||
}
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return config.HubConfig{}
|
||||
}
|
||||
return cfg.Hub
|
||||
}
|
||||
|
||||
@@ -21,6 +21,19 @@ type AuditConfig struct {
|
||||
BlockThreshold string `yaml:"block_threshold,omitempty"` // CRITICAL/HIGH/MEDIUM/LOW/INFO
|
||||
}
|
||||
|
||||
// HubEntry represents a single saved hub source.
|
||||
type HubEntry struct {
|
||||
Label string `yaml:"label"`
|
||||
URL string `yaml:"url"`
|
||||
BuiltIn bool `yaml:"builtin,omitempty"`
|
||||
}
|
||||
|
||||
// HubConfig holds hub persistence settings.
|
||||
type HubConfig struct {
|
||||
Default string `yaml:"default,omitempty"`
|
||||
Hubs []HubEntry `yaml:"hubs,omitempty"`
|
||||
}
|
||||
|
||||
// Config holds the application configuration
|
||||
type Config struct {
|
||||
Source string `yaml:"source"`
|
||||
@@ -28,6 +41,7 @@ type Config struct {
|
||||
Targets map[string]TargetConfig `yaml:"targets"`
|
||||
Ignore []string `yaml:"ignore,omitempty"`
|
||||
Audit AuditConfig `yaml:"audit,omitempty"`
|
||||
Hub HubConfig `yaml:"hub,omitempty"`
|
||||
}
|
||||
|
||||
const defaultAuditBlockThreshold = "CRITICAL"
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ResolveHub looks up a hub URL by label. Returns the URL and true if found.
|
||||
func (h *HubConfig) ResolveHub(label string) (string, bool) {
|
||||
label = strings.TrimSpace(label)
|
||||
for _, entry := range h.Hubs {
|
||||
if strings.EqualFold(entry.Label, label) {
|
||||
return entry.URL, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// DefaultHub returns the URL of the default hub.
|
||||
// Returns "" if no default is set (caller should fall back to community hub).
|
||||
// Returns an error if default is set but the label is not found in hubs.
|
||||
func (h *HubConfig) DefaultHub() (string, error) {
|
||||
if h.Default == "" {
|
||||
return "", nil
|
||||
}
|
||||
url, ok := h.ResolveHub(h.Default)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("default hub %q not found in saved hubs", h.Default)
|
||||
}
|
||||
return url, nil
|
||||
}
|
||||
|
||||
// HasHub checks if a hub with the given label exists.
|
||||
func (h *HubConfig) HasHub(label string) bool {
|
||||
label = strings.TrimSpace(label)
|
||||
for _, entry := range h.Hubs {
|
||||
if strings.EqualFold(entry.Label, label) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AddHub adds a new hub entry. Returns an error if the label already exists.
|
||||
func (h *HubConfig) AddHub(entry HubEntry) error {
|
||||
entry.Label = strings.TrimSpace(entry.Label)
|
||||
entry.URL = strings.TrimSpace(entry.URL)
|
||||
if entry.Label == "" {
|
||||
return fmt.Errorf("hub label cannot be empty")
|
||||
}
|
||||
if entry.URL == "" {
|
||||
return fmt.Errorf("hub URL cannot be empty")
|
||||
}
|
||||
if h.HasHub(entry.Label) {
|
||||
return fmt.Errorf("hub %q already exists", entry.Label)
|
||||
}
|
||||
h.Hubs = append(h.Hubs, entry)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveHub removes a hub by label. Clears default if it was the removed one.
|
||||
func (h *HubConfig) RemoveHub(label string) error {
|
||||
label = strings.TrimSpace(label)
|
||||
found := false
|
||||
filtered := make([]HubEntry, 0, len(h.Hubs))
|
||||
for _, entry := range h.Hubs {
|
||||
if strings.EqualFold(entry.Label, label) {
|
||||
found = true
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, entry)
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("hub %q not found", label)
|
||||
}
|
||||
h.Hubs = filtered
|
||||
if strings.EqualFold(h.Default, label) {
|
||||
h.Default = ""
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func TestHubConfig_ResolveHub(t *testing.T) {
|
||||
h := HubConfig{
|
||||
Hubs: []HubEntry{
|
||||
{Label: "team", URL: "https://internal.corp/hub.json"},
|
||||
{Label: "local", URL: "./hub.json"},
|
||||
},
|
||||
}
|
||||
|
||||
url, ok := h.ResolveHub("team")
|
||||
if !ok || url != "https://internal.corp/hub.json" {
|
||||
t.Errorf("ResolveHub(team) = %q, %v", url, ok)
|
||||
}
|
||||
|
||||
// Case-insensitive lookup
|
||||
url, ok = h.ResolveHub("Team")
|
||||
if !ok || url != "https://internal.corp/hub.json" {
|
||||
t.Errorf("ResolveHub(Team) = %q, %v", url, ok)
|
||||
}
|
||||
|
||||
_, ok = h.ResolveHub("nonexistent")
|
||||
if ok {
|
||||
t.Error("ResolveHub(nonexistent) should return false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubConfig_DefaultHub(t *testing.T) {
|
||||
h := HubConfig{
|
||||
Default: "team",
|
||||
Hubs: []HubEntry{
|
||||
{Label: "team", URL: "https://internal.corp/hub.json"},
|
||||
},
|
||||
}
|
||||
|
||||
url, err := h.DefaultHub()
|
||||
if err != nil {
|
||||
t.Fatalf("DefaultHub() error: %v", err)
|
||||
}
|
||||
if url != "https://internal.corp/hub.json" {
|
||||
t.Errorf("DefaultHub() = %q, want https://internal.corp/hub.json", url)
|
||||
}
|
||||
|
||||
// Empty default returns empty
|
||||
h2 := HubConfig{}
|
||||
url, err = h2.DefaultHub()
|
||||
if err != nil {
|
||||
t.Fatalf("empty DefaultHub() error: %v", err)
|
||||
}
|
||||
if url != "" {
|
||||
t.Errorf("empty DefaultHub() = %q, want empty", url)
|
||||
}
|
||||
|
||||
// Default set but label missing → error
|
||||
h3 := HubConfig{Default: "missing"}
|
||||
_, err = h3.DefaultHub()
|
||||
if err == nil {
|
||||
t.Error("DefaultHub() with missing label should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubConfig_AddHub(t *testing.T) {
|
||||
h := HubConfig{}
|
||||
|
||||
if err := h.AddHub(HubEntry{Label: "test", URL: "https://example.com/hub.json"}); err != nil {
|
||||
t.Fatalf("AddHub() error: %v", err)
|
||||
}
|
||||
if len(h.Hubs) != 1 {
|
||||
t.Fatalf("len(Hubs) = %d, want 1", len(h.Hubs))
|
||||
}
|
||||
|
||||
// Duplicate label
|
||||
if err := h.AddHub(HubEntry{Label: "test", URL: "https://other.com/hub.json"}); err == nil {
|
||||
t.Error("AddHub() duplicate should error")
|
||||
}
|
||||
|
||||
// Empty label
|
||||
if err := h.AddHub(HubEntry{Label: "", URL: "https://x.com"}); err == nil {
|
||||
t.Error("AddHub() empty label should error")
|
||||
}
|
||||
|
||||
// Empty URL
|
||||
if err := h.AddHub(HubEntry{Label: "x", URL: ""}); err == nil {
|
||||
t.Error("AddHub() empty URL should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubConfig_RemoveHub(t *testing.T) {
|
||||
h := HubConfig{
|
||||
Default: "team",
|
||||
Hubs: []HubEntry{
|
||||
{Label: "team", URL: "https://internal.corp/hub.json"},
|
||||
{Label: "local", URL: "./hub.json"},
|
||||
},
|
||||
}
|
||||
|
||||
if err := h.RemoveHub("team"); err != nil {
|
||||
t.Fatalf("RemoveHub() error: %v", err)
|
||||
}
|
||||
if len(h.Hubs) != 1 {
|
||||
t.Fatalf("len(Hubs) = %d, want 1", len(h.Hubs))
|
||||
}
|
||||
if h.Default != "" {
|
||||
t.Errorf("default should be cleared, got %q", h.Default)
|
||||
}
|
||||
|
||||
// Remove non-default
|
||||
h2 := HubConfig{
|
||||
Default: "team",
|
||||
Hubs: []HubEntry{
|
||||
{Label: "team", URL: "a"},
|
||||
{Label: "local", URL: "b"},
|
||||
},
|
||||
}
|
||||
if err := h2.RemoveHub("local"); err != nil {
|
||||
t.Fatalf("RemoveHub(local) error: %v", err)
|
||||
}
|
||||
if h2.Default != "team" {
|
||||
t.Errorf("default should still be team, got %q", h2.Default)
|
||||
}
|
||||
|
||||
// Remove nonexistent
|
||||
if err := h2.RemoveHub("nope"); err == nil {
|
||||
t.Error("RemoveHub(nope) should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubConfig_HasHub(t *testing.T) {
|
||||
h := HubConfig{
|
||||
Hubs: []HubEntry{{Label: "team", URL: "x"}},
|
||||
}
|
||||
if !h.HasHub("team") {
|
||||
t.Error("HasHub(team) should be true")
|
||||
}
|
||||
if h.HasHub("other") {
|
||||
t.Error("HasHub(other) should be false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubConfig_YAMLRoundTrip(t *testing.T) {
|
||||
original := Config{
|
||||
Source: "/tmp/skills",
|
||||
Targets: map[string]TargetConfig{"claude": {Path: "/tmp/claude"}},
|
||||
Hub: HubConfig{
|
||||
Default: "team",
|
||||
Hubs: []HubEntry{
|
||||
{Label: "team", URL: "https://internal.corp/hub.json"},
|
||||
{Label: "local", URL: "./hub.json"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(&original)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
|
||||
var loaded Config
|
||||
if err := yaml.Unmarshal(data, &loaded); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
|
||||
if loaded.Hub.Default != "team" {
|
||||
t.Errorf("hub.default = %q, want team", loaded.Hub.Default)
|
||||
}
|
||||
if len(loaded.Hub.Hubs) != 2 {
|
||||
t.Fatalf("hub.hubs len = %d, want 2", len(loaded.Hub.Hubs))
|
||||
}
|
||||
if loaded.Hub.Hubs[0].Label != "team" {
|
||||
t.Errorf("hubs[0].label = %q, want team", loaded.Hub.Hubs[0].Label)
|
||||
}
|
||||
if loaded.Hub.Hubs[1].URL != "./hub.json" {
|
||||
t.Errorf("hubs[1].url = %q, want ./hub.json", loaded.Hub.Hubs[1].URL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubConfig_EmptyOmitted(t *testing.T) {
|
||||
cfg := Config{
|
||||
Source: "/tmp/skills",
|
||||
Targets: map[string]TargetConfig{},
|
||||
}
|
||||
|
||||
data, err := yaml.Marshal(&cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
|
||||
s := string(data)
|
||||
if contains(s, "hub:") {
|
||||
t.Errorf("empty HubConfig should be omitted from YAML, got:\n%s", s)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
return len(s) >= len(substr) && searchString(s, substr)
|
||||
}
|
||||
|
||||
func searchString(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -69,6 +69,7 @@ type ProjectConfig struct {
|
||||
Targets []ProjectTargetEntry `yaml:"targets"`
|
||||
Skills []ProjectSkill `yaml:"skills,omitempty"`
|
||||
Audit AuditConfig `yaml:"audit,omitempty"`
|
||||
Hub HubConfig `yaml:"hub,omitempty"`
|
||||
}
|
||||
|
||||
// ProjectConfigPath returns the project config path for the given root.
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/config"
|
||||
)
|
||||
|
||||
type hubConfigResponse struct {
|
||||
Hubs []hubEntryJSON `json:"hubs"`
|
||||
Default string `json:"default"`
|
||||
}
|
||||
|
||||
type hubEntryJSON struct {
|
||||
Label string `json:"label"`
|
||||
URL string `json:"url"`
|
||||
BuiltIn bool `json:"builtIn,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleGetHubSaved(w http.ResponseWriter, r *http.Request) {
|
||||
hub := s.hubConfig()
|
||||
resp := hubConfigResponse{
|
||||
Default: hub.Default,
|
||||
Hubs: make([]hubEntryJSON, 0, len(hub.Hubs)),
|
||||
}
|
||||
for _, h := range hub.Hubs {
|
||||
resp.Hubs = append(resp.Hubs, hubEntryJSON{
|
||||
Label: h.Label,
|
||||
URL: h.URL,
|
||||
BuiltIn: h.BuiltIn,
|
||||
})
|
||||
}
|
||||
writeJSON(w, resp)
|
||||
}
|
||||
|
||||
func (s *Server) handlePutHubSaved(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
start := time.Now()
|
||||
|
||||
var req hubConfigResponse
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
hubCfg := config.HubConfig{
|
||||
Default: req.Default,
|
||||
Hubs: make([]config.HubEntry, 0, len(req.Hubs)),
|
||||
}
|
||||
for _, h := range req.Hubs {
|
||||
hubCfg.Hubs = append(hubCfg.Hubs, config.HubEntry{
|
||||
Label: h.Label,
|
||||
URL: h.URL,
|
||||
BuiltIn: h.BuiltIn,
|
||||
})
|
||||
}
|
||||
|
||||
s.setHubConfig(hubCfg)
|
||||
if err := s.saveConfig(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.reloadConfig(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
s.writeOpsLog("hub-save", "ok", start, map[string]any{"count": len(hubCfg.Hubs)}, "")
|
||||
writeJSON(w, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) handlePostHubSaved(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
start := time.Now()
|
||||
|
||||
var req struct {
|
||||
Label string `json:"label"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
hubCfg := s.hubConfig()
|
||||
if err := hubCfg.AddHub(config.HubEntry{Label: req.Label, URL: req.URL}); err != nil {
|
||||
writeError(w, http.StatusConflict, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
s.setHubConfig(*hubCfg)
|
||||
if err := s.saveConfig(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.reloadConfig(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
s.writeOpsLog("hub-add", "ok", start, map[string]any{"label": req.Label}, "")
|
||||
writeJSON(w, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleDeleteHubSaved(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
start := time.Now()
|
||||
|
||||
label := strings.TrimSpace(r.PathValue("label"))
|
||||
if label == "" {
|
||||
writeError(w, http.StatusBadRequest, "label is required")
|
||||
return
|
||||
}
|
||||
|
||||
hubCfg := s.hubConfig()
|
||||
if err := hubCfg.RemoveHub(label); err != nil {
|
||||
writeError(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
s.setHubConfig(*hubCfg)
|
||||
if err := s.saveConfig(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.reloadConfig(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
s.writeOpsLog("hub-remove", "ok", start, map[string]any{"label": label}, "")
|
||||
writeJSON(w, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
// hubConfig returns a copy of the current hub config.
|
||||
func (s *Server) hubConfig() *config.HubConfig {
|
||||
if s.IsProjectMode() {
|
||||
h := s.projectCfg.Hub
|
||||
return &h
|
||||
}
|
||||
h := s.cfg.Hub
|
||||
return &h
|
||||
}
|
||||
|
||||
// setHubConfig sets the hub config on the appropriate config object.
|
||||
func (s *Server) setHubConfig(h config.HubConfig) {
|
||||
if s.IsProjectMode() {
|
||||
s.projectCfg.Hub = h
|
||||
} else {
|
||||
s.cfg.Hub = h
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,10 @@ func (s *Server) registerRoutes() {
|
||||
|
||||
// Hub
|
||||
s.mux.HandleFunc("GET /api/hub/index", s.handleHubIndex)
|
||||
s.mux.HandleFunc("GET /api/hub/saved", s.handleGetHubSaved)
|
||||
s.mux.HandleFunc("PUT /api/hub/saved", s.handlePutHubSaved)
|
||||
s.mux.HandleFunc("POST /api/hub/saved", s.handlePostHubSaved)
|
||||
s.mux.HandleFunc("DELETE /api/hub/saved/{label}", s.handleDeleteHubSaved)
|
||||
|
||||
// Search & Install
|
||||
s.mux.HandleFunc("GET /api/search", s.handleSearch)
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
//go:build !online
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/testutil"
|
||||
)
|
||||
|
||||
func TestHubAdd_Basic(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
result := sb.RunCLI("hub", "add", "https://example.com/hub.json", "--label", "test")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "Added hub")
|
||||
result.AssertAnyOutputContains(t, "test")
|
||||
// First add should auto-set default
|
||||
result.AssertAnyOutputContains(t, "default")
|
||||
}
|
||||
|
||||
func TestHubAdd_DeriveLabel(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
result := sb.RunCLI("hub", "add", "https://internal.corp/skills/team-hub.json")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "team-hub")
|
||||
}
|
||||
|
||||
func TestHubAdd_Duplicate(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
result := sb.RunCLI("hub", "add", "https://example.com/hub.json", "--label", "test")
|
||||
result.AssertSuccess(t)
|
||||
|
||||
result = sb.RunCLI("hub", "add", "https://other.com/hub.json", "--label", "test")
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "already exists")
|
||||
}
|
||||
|
||||
func TestHubList_Empty(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
result := sb.RunCLI("hub", "list")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "No saved hubs")
|
||||
}
|
||||
|
||||
func TestHubList_ShowsHubs(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\nhub:\n default: alpha\n hubs:\n - label: alpha\n url: https://a.com/hub.json\n - label: beta\n url: https://b.com/hub.json\n")
|
||||
|
||||
result := sb.RunCLI("hub", "list")
|
||||
result.AssertSuccess(t)
|
||||
combined := result.Stdout + result.Stderr
|
||||
if !strings.Contains(combined, "* ") {
|
||||
t.Errorf("expected default marker '*' in output, got:\n%s", combined)
|
||||
}
|
||||
result.AssertAnyOutputContains(t, "alpha")
|
||||
result.AssertAnyOutputContains(t, "beta")
|
||||
}
|
||||
|
||||
func TestHubRemove_Basic(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\nhub:\n default: test\n hubs:\n - label: test\n url: https://example.com/hub.json\n")
|
||||
|
||||
result := sb.RunCLI("hub", "remove", "test")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "Removed")
|
||||
|
||||
// List should be empty now
|
||||
result = sb.RunCLI("hub", "list")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "No saved hubs")
|
||||
}
|
||||
|
||||
func TestHubRemove_NotFound(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
result := sb.RunCLI("hub", "remove", "nonexistent")
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "not found")
|
||||
}
|
||||
|
||||
func TestHubDefault_Show(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\nhub:\n default: team\n hubs:\n - label: team\n url: https://example.com/hub.json\n")
|
||||
|
||||
result := sb.RunCLI("hub", "default")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "team")
|
||||
result.AssertAnyOutputContains(t, "https://example.com/hub.json")
|
||||
}
|
||||
|
||||
func TestHubDefault_Set(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\nhub:\n hubs:\n - label: alpha\n url: https://a.com/hub.json\n - label: beta\n url: https://b.com/hub.json\n")
|
||||
|
||||
result := sb.RunCLI("hub", "default", "beta")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "beta")
|
||||
|
||||
// Verify it's set
|
||||
result = sb.RunCLI("hub", "default")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "beta")
|
||||
}
|
||||
|
||||
func TestHubDefault_Reset(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\nhub:\n default: team\n hubs:\n - label: team\n url: https://example.com/hub.json\n")
|
||||
|
||||
result := sb.RunCLI("hub", "default", "--reset")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "cleared")
|
||||
|
||||
// Verify cleared
|
||||
result = sb.RunCLI("hub", "default")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "No default")
|
||||
}
|
||||
|
||||
func TestHubDefault_NotFound(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
result := sb.RunCLI("hub", "default", "nonexistent")
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "not found")
|
||||
}
|
||||
|
||||
func TestHub_HelpShowsSubcommands(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
result := sb.RunCLI("hub", "help")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "add")
|
||||
result.AssertAnyOutputContains(t, "list")
|
||||
result.AssertAnyOutputContains(t, "remove")
|
||||
result.AssertAnyOutputContains(t, "default")
|
||||
result.AssertAnyOutputContains(t, "index")
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/testutil"
|
||||
@@ -110,3 +111,64 @@ func TestSearch_IndexURL_SpinnerText(t *testing.T) {
|
||||
// JSON mode shows progress on stderr
|
||||
result.AssertAnyOutputContains(t, "Browsing popular skills")
|
||||
}
|
||||
|
||||
func TestSearch_HubLabel_ResolvesFromConfig(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
indexPath := writeIndexFile(t, sb.Home, []map[string]string{
|
||||
{"name": "my-skill", "description": "A skill", "source": "owner/repo/my-skill"},
|
||||
})
|
||||
|
||||
// Write config with a saved hub
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\nhub:\n hubs:\n - label: test\n url: " + indexPath + "\n")
|
||||
|
||||
result := sb.RunCLI("search", "my-skill", "--hub", "test", "--list")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "my-skill")
|
||||
}
|
||||
|
||||
func TestSearch_HubLabel_NotFound(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
result := sb.RunCLI("search", "x", "--hub", "nonexistent", "--list")
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "not found")
|
||||
}
|
||||
|
||||
func TestSearch_HubBare_UsesDefault(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
indexPath := writeIndexFile(t, sb.Home, []map[string]string{
|
||||
{"name": "default-skill", "source": "a/b"},
|
||||
})
|
||||
|
||||
// Config with default hub set
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\nhub:\n default: myhub\n hubs:\n - label: myhub\n url: " + indexPath + "\n")
|
||||
|
||||
result := sb.RunCLI("search", "--hub", "--json")
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, "default-skill")
|
||||
}
|
||||
|
||||
func TestSearch_HubBare_FallbackToCommunity(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
|
||||
// No default set — bare --hub should use community hub (which will fail in offline test,
|
||||
// but we can verify the URL is attempted, not that it returned a label error)
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + "\ntargets: {}\n")
|
||||
|
||||
// This will try to fetch the community hub URL which will fail in offline mode,
|
||||
// but it should NOT produce "not found" label error — it should try the URL
|
||||
result := sb.RunCLI("search", "--hub", "--json")
|
||||
// The search itself may fail (network) but shouldn't error with "not found"
|
||||
combined := result.Stdout + result.Stderr
|
||||
if strings.Contains(combined, "not found; run") {
|
||||
t.Errorf("bare --hub with no default should fallback to community hub, not label error")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,21 @@ export const api = {
|
||||
|
||||
// Hub
|
||||
hubIndex: () => apiFetch<HubIndex>('/hub/index'),
|
||||
getHubConfig: () => apiFetch<HubConfigResponse>('/hub/saved'),
|
||||
putHubConfig: (data: { hubs: HubSavedEntry[]; default: string }) =>
|
||||
apiFetch<{ success: boolean }>('/hub/saved', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
addHub: (hub: { label: string; url: string }) =>
|
||||
apiFetch<{ success: boolean }>('/hub/saved', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(hub),
|
||||
}),
|
||||
removeHub: (label: string) =>
|
||||
apiFetch<{ success: boolean }>(`/hub/saved/${encodeURIComponent(label)}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
|
||||
// Search & Install
|
||||
search: (q: string, limit = 20) =>
|
||||
@@ -478,3 +493,15 @@ export interface AuditRulesResponse {
|
||||
raw: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
// Hub saved config types
|
||||
export interface HubSavedEntry {
|
||||
label: string;
|
||||
url: string;
|
||||
builtIn?: boolean;
|
||||
}
|
||||
|
||||
export interface HubConfigResponse {
|
||||
hubs: HubSavedEntry[];
|
||||
default: string;
|
||||
}
|
||||
|
||||
+87
-41
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { Search, Star, Download, Globe, Database, Settings } from 'lucide-react';
|
||||
import Card from '../components/Card';
|
||||
import Badge from '../components/Badge';
|
||||
@@ -12,35 +12,12 @@ import { api, type SearchResult, type DiscoveredSkill } from '../api/client';
|
||||
|
||||
type SearchMode = 'github' | 'hub';
|
||||
|
||||
const LS_MODE = 'search:mode';
|
||||
const LS_SELECTED = 'search:selectedHub';
|
||||
const LS_SAVED = 'search:savedHubs';
|
||||
|
||||
const COMMUNITY_HUB: SavedHub = {
|
||||
label: 'Skillshare Hub',
|
||||
url: 'https://raw.githubusercontent.com/runkids/skillshare-hub/main/skillshare-hub.json',
|
||||
builtIn: true,
|
||||
};
|
||||
|
||||
function loadMode(): SearchMode {
|
||||
const v = localStorage.getItem(LS_MODE);
|
||||
return v === 'hub' ? 'hub' : 'github';
|
||||
}
|
||||
|
||||
function loadSelectedHub(): string {
|
||||
return localStorage.getItem(LS_SELECTED) || COMMUNITY_HUB.url;
|
||||
}
|
||||
|
||||
function loadUserHubs(): SavedHub[] {
|
||||
try {
|
||||
const raw = localStorage.getItem(LS_SAVED);
|
||||
if (!raw) return [];
|
||||
return JSON.parse(raw) as SavedHub[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function mergeHubs(userHubs: SavedHub[]): SavedHub[] {
|
||||
return [COMMUNITY_HUB, ...userHubs.filter((h) => normalizeURL(h.url) !== normalizeURL(COMMUNITY_HUB.url))];
|
||||
}
|
||||
@@ -50,7 +27,7 @@ function normalizeURL(url: string): string {
|
||||
}
|
||||
|
||||
export default function SearchPage() {
|
||||
const [mode, setMode] = useState<SearchMode>(loadMode);
|
||||
const [mode, setMode] = useState<SearchMode>('github');
|
||||
const [query, setQuery] = useState('');
|
||||
const [results, setResults] = useState<SearchResult[] | null>(null);
|
||||
const [searching, setSearching] = useState(false);
|
||||
@@ -58,9 +35,10 @@ export default function SearchPage() {
|
||||
const { toast } = useToast();
|
||||
|
||||
// Hub state
|
||||
const [selectedHub, setSelectedHub] = useState(loadSelectedHub);
|
||||
const [savedHubs, setSavedHubs] = useState<SavedHub[]>(() => mergeHubs(loadUserHubs()));
|
||||
const [selectedHub, setSelectedHub] = useState(COMMUNITY_HUB.url);
|
||||
const [savedHubs, setSavedHubs] = useState<SavedHub[]>([COMMUNITY_HUB]);
|
||||
const [showHubManager, setShowHubManager] = useState(false);
|
||||
const [hubLoaded, setHubLoaded] = useState(false);
|
||||
|
||||
// Install state
|
||||
const [installing, setInstalling] = useState<string | null>(null);
|
||||
@@ -71,10 +49,38 @@ export default function SearchPage() {
|
||||
const [pendingSource, setPendingSource] = useState('');
|
||||
const [batchInstalling, setBatchInstalling] = useState(false);
|
||||
|
||||
// Fetch hub config from server on mount
|
||||
useEffect(() => {
|
||||
fetchHubConfig();
|
||||
}, []);
|
||||
|
||||
const fetchHubConfig = async () => {
|
||||
try {
|
||||
const res = await api.getHubConfig();
|
||||
const merged = mergeHubs(
|
||||
res.hubs.map((h) => ({ label: h.label, url: h.url, builtIn: h.builtIn })),
|
||||
);
|
||||
setSavedHubs(merged);
|
||||
|
||||
// Resolve default hub to a URL for the select
|
||||
if (res.default) {
|
||||
const match = merged.find(
|
||||
(h) => h.label.toLowerCase() === res.default.toLowerCase(),
|
||||
);
|
||||
if (match) {
|
||||
setSelectedHub(match.url);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Graceful fallback: use community hub only
|
||||
} finally {
|
||||
setHubLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
const switchMode = useCallback((newMode: SearchMode) => {
|
||||
setMode(newMode);
|
||||
setResults(null);
|
||||
localStorage.setItem(LS_MODE, newMode);
|
||||
}, []);
|
||||
|
||||
const handleSearch = async (searchQuery?: string) => {
|
||||
@@ -199,23 +205,63 @@ export default function SearchPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleHubsSave = (updated: SavedHub[]) => {
|
||||
const merged = mergeHubs(updated);
|
||||
setSavedHubs(merged);
|
||||
// Only persist user-added hubs
|
||||
const handleHubsSave = async (updated: SavedHub[]) => {
|
||||
const userOnly = updated.filter((h) => !h.builtIn);
|
||||
localStorage.setItem(LS_SAVED, JSON.stringify(userOnly));
|
||||
// If selected hub was removed, fall back to community hub
|
||||
if (!merged.some((h) => normalizeURL(h.url) === normalizeURL(selectedHub))) {
|
||||
setSelectedHub(COMMUNITY_HUB.url);
|
||||
localStorage.setItem(LS_SELECTED, COMMUNITY_HUB.url);
|
||||
try {
|
||||
// Find the label that matches the currently selected hub URL
|
||||
const merged = mergeHubs(userOnly);
|
||||
const currentMatch = merged.find((h) => normalizeURL(h.url) === normalizeURL(selectedHub));
|
||||
const defaultLabel = currentMatch && !currentMatch.builtIn ? currentMatch.label : '';
|
||||
|
||||
await api.putHubConfig({
|
||||
hubs: userOnly.map((h) => ({ label: h.label, url: h.url })),
|
||||
default: defaultLabel,
|
||||
});
|
||||
setSavedHubs(merged);
|
||||
|
||||
// If selected hub was removed, fall back to community hub
|
||||
if (!merged.some((h) => normalizeURL(h.url) === normalizeURL(selectedHub))) {
|
||||
setSelectedHub(COMMUNITY_HUB.url);
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
toast((e as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectHub = (url: string) => {
|
||||
const handleSelectHub = async (url: string) => {
|
||||
setSelectedHub(url);
|
||||
localStorage.setItem(LS_SELECTED, url);
|
||||
setResults(null);
|
||||
|
||||
// Persist selected hub as default on server
|
||||
const match = savedHubs.find((h) => normalizeURL(h.url) === normalizeURL(url));
|
||||
if (match && !match.builtIn) {
|
||||
try {
|
||||
const userOnly = savedHubs.filter((h) => !h.builtIn);
|
||||
await api.putHubConfig({
|
||||
hubs: userOnly.map((h) => ({ label: h.label, url: h.url })),
|
||||
default: match.label,
|
||||
});
|
||||
} catch {
|
||||
// Non-critical — selection still works locally
|
||||
}
|
||||
} else {
|
||||
// Selected community hub — clear default
|
||||
try {
|
||||
const userOnly = savedHubs.filter((h) => !h.builtIn);
|
||||
await api.putHubConfig({
|
||||
hubs: userOnly.map((h) => ({ label: h.label, url: h.url })),
|
||||
default: '',
|
||||
});
|
||||
} catch {
|
||||
// Non-critical
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleHubManagerClose = () => {
|
||||
setShowHubManager(false);
|
||||
// Re-fetch to ensure we're in sync with server
|
||||
fetchHubConfig();
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -254,7 +300,7 @@ export default function SearchPage() {
|
||||
</div>
|
||||
|
||||
{/* Hub selector (only in hub mode) */}
|
||||
{mode === 'hub' && (
|
||||
{mode === 'hub' && hubLoaded && (
|
||||
<Card className="mb-4 !overflow-visible">
|
||||
{savedHubs.length > 0 ? (
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -464,7 +510,7 @@ export default function SearchPage() {
|
||||
open={showHubManager}
|
||||
hubs={savedHubs}
|
||||
onSave={handleHubsSave}
|
||||
onClose={() => setShowHubManager(false)}
|
||||
onClose={handleHubManagerClose}
|
||||
/>
|
||||
|
||||
{/* Skill Picker Modal for multi-skill repos */}
|
||||
|
||||
@@ -4,7 +4,86 @@ sidebar_position: 8
|
||||
|
||||
# hub
|
||||
|
||||
Manage private skill hubs. Currently provides the `index` subcommand for building searchable skill catalogs.
|
||||
Manage skill hubs — saved hub sources for search.
|
||||
|
||||
## hub add
|
||||
|
||||
Save a hub source to config for reuse in [`search --hub`](./search.md).
|
||||
|
||||
```bash
|
||||
skillshare hub add <url> [options]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--label`, `-l` | Custom label (default: derived from URL hostname) |
|
||||
| `--project`, `-p` | Save to project config |
|
||||
| `--global`, `-g` | Save to global config |
|
||||
|
||||
The first hub added is automatically set as the default. Labels are case-insensitive.
|
||||
|
||||
```bash
|
||||
skillshare hub add https://internal.corp/hub.json --label team
|
||||
skillshare hub add ./local-hub.json # label derived: "local-hub"
|
||||
```
|
||||
|
||||
## hub list
|
||||
|
||||
List saved hubs. `*` marks the default hub.
|
||||
|
||||
```bash
|
||||
skillshare hub list [options]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--project`, `-p` | Show project hubs |
|
||||
| `--global`, `-g` | Show global hubs |
|
||||
|
||||
```
|
||||
$ skillshare hub list
|
||||
* team https://internal.corp/hub.json
|
||||
local ./local-hub.json
|
||||
```
|
||||
|
||||
Alias: `hub ls`
|
||||
|
||||
## hub remove
|
||||
|
||||
Remove a saved hub by label.
|
||||
|
||||
```bash
|
||||
skillshare hub remove <label> [options]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--project`, `-p` | Remove from project config |
|
||||
| `--global`, `-g` | Remove from global config |
|
||||
|
||||
If the removed hub was the default, the default is cleared.
|
||||
|
||||
Alias: `hub rm`
|
||||
|
||||
## hub default
|
||||
|
||||
Show or set the default hub used by `search --hub` (bare flag).
|
||||
|
||||
```bash
|
||||
skillshare hub default [label] [options]
|
||||
```
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--reset` | Clear the default (revert to community hub) |
|
||||
| `--project`, `-p` | Use project config |
|
||||
| `--global`, `-g` | Use global config |
|
||||
|
||||
```bash
|
||||
skillshare hub default # Show current default
|
||||
skillshare hub default team # Set default to "team"
|
||||
skillshare hub default --reset # Clear default → community hub
|
||||
```
|
||||
|
||||
## hub index
|
||||
|
||||
@@ -100,3 +179,19 @@ A typical private hub workflow:
|
||||
```
|
||||
|
||||
For more details, see the [Hub Index Guide](../guides/hub-index.md).
|
||||
|
||||
## Config Format
|
||||
|
||||
Saved hubs are stored under the `hub:` key in `config.yaml`:
|
||||
|
||||
```yaml
|
||||
hub:
|
||||
default: team
|
||||
hubs:
|
||||
- label: team
|
||||
url: https://internal.corp/hub.json
|
||||
- label: local
|
||||
url: ./local-hub.json
|
||||
```
|
||||
|
||||
The community hub ([skillshare-hub](https://github.com/runkids/skillshare-hub)) is implicit and doesn't need to be saved. When no default is set, `search --hub` falls back to the community hub automatically.
|
||||
|
||||
@@ -189,6 +189,29 @@ When `--hub` is used without a URL, it defaults to the community [skillshare-hub
|
||||
|
||||
Want to share your skill with the community? [Open a PR](https://github.com/runkids/skillshare-hub) to add your skill — CI runs `skillshare audit` on every submission.
|
||||
|
||||
## Saved Hub Labels
|
||||
|
||||
Save hubs with [`hub add`](./hub.md#hub-add) and search by label instead of typing full URLs:
|
||||
|
||||
```bash
|
||||
# Save a hub once
|
||||
skillshare hub add https://internal.corp/hub.json --label team
|
||||
|
||||
# Search by label
|
||||
skillshare search react --hub team
|
||||
|
||||
# Set as default for bare --hub
|
||||
skillshare hub default team
|
||||
skillshare search --hub # Uses "team" hub
|
||||
```
|
||||
|
||||
Resolution order for `--hub <value>`:
|
||||
1. URL or path (starts with `http`, `/`, `.`, `~`, `file://`) → used directly
|
||||
2. Otherwise → label lookup from saved hubs
|
||||
3. Bare `--hub` (no value) → config default → community hub fallback
|
||||
|
||||
See [`hub`](./hub.md) for managing saved hubs.
|
||||
|
||||
## Private Index Search
|
||||
|
||||
Search from a private hub index instead of GitHub:
|
||||
@@ -215,7 +238,7 @@ skillshare search --hub ./skillshare-hub.json # Search it
|
||||
```
|
||||
|
||||
:::tip Default hub
|
||||
`skillshare search --hub` (without a URL) defaults to the community [skillshare-hub](https://github.com/runkids/skillshare-hub) index, so you don't need to type the full URL every time.
|
||||
`skillshare search --hub` (without a URL) defaults to the community [skillshare-hub](https://github.com/runkids/skillshare-hub) index, so you don't need to type the full URL every time. Or set your own default with `skillshare hub default <label>`.
|
||||
:::
|
||||
|
||||
For more details, see the [Hub Index Guide](../guides/hub-index.md).
|
||||
|
||||
Reference in New Issue
Block a user