mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-20 20:34:19 +00:00
Merge pull request #492 from runkids/runkids/extras-filter-435
feat(extras): choose which files each target syncs, and edit targets in place
This commit is contained in:
@@ -70,8 +70,8 @@ _skillshare() {
|
||||
local enable_flags="--dry-run -n --kind --help -h"
|
||||
local disable_flags="--dry-run -n --kind --help -h"
|
||||
local analyze_flags="--verbose -v --filter --no-tui --json --help -h"
|
||||
local extras_flags="--mode --target --flatten --no-flatten --add-target --as --remove-target --prune --help -h"
|
||||
local extras_init_flags="--target --mode --source --file --as --flatten --force --no-tui --help -h"
|
||||
local extras_flags="--mode --target --flatten --no-flatten --add-include --add-exclude --remove-include --remove-exclude --add-target --as --remove-target --prune --help -h"
|
||||
local extras_init_flags="--target --mode --source --file --as --flatten --include --exclude --force --no-tui --help -h"
|
||||
local extras_list_flags="--json --no-tui --help -h"
|
||||
local extras_remove_flags="--force -f --help -h"
|
||||
local extras_collect_flags="--from --dry-run --force -f --help -h"
|
||||
|
||||
@@ -424,6 +424,8 @@ complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l mo
|
||||
complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l source -r -F -d 'Custom source directory'
|
||||
complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l file -r -F -d 'Single-file extra'
|
||||
complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l as -r -d 'Target filename'
|
||||
complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l include -r -d 'Sync only matching files'
|
||||
complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l exclude -r -d 'Skip matching files'
|
||||
complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l flatten -d 'Flatten subdirectory files'
|
||||
complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l force -d 'Overwrite existing extra'
|
||||
complete -c skillshare -n '__fish_skillshare_using_subcommand extras init' -l no-tui -d 'Skip interactive TUI'
|
||||
@@ -437,6 +439,10 @@ complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fis
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l target -r -F -d 'Target for --mode'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l flatten -d 'Enable flatten'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l no-flatten -d 'Disable flatten'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l add-include -r -d 'Add an include pattern'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l add-exclude -r -d 'Add an exclude pattern'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l remove-include -r -d 'Remove an include pattern'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l remove-exclude -r -d 'Remove an exclude pattern'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l add-target -r -F -d 'Add a target'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l as -r -d 'Target filename'
|
||||
complete -c skillshare -n '__fish_skillshare_using_command extras; and not __fish_seen_subcommand_from init list remove collect source memory' -l remove-target -r -F -d 'Detach a target'
|
||||
|
||||
@@ -689,6 +689,12 @@ export extern "skillshare extras" [
|
||||
--as: string # Target filename
|
||||
--flatten # Flatten subdirectory files
|
||||
--no-flatten # Disable flatten
|
||||
--include: string # init: sync only matching files
|
||||
--exclude: string # init: skip matching files
|
||||
--add-include: string # Add an include pattern
|
||||
--add-exclude: string # Add an exclude pattern
|
||||
--remove-include: string # Remove an include pattern
|
||||
--remove-exclude: string # Remove an exclude pattern
|
||||
--add-target: string # Add a target
|
||||
--remove-target: string # Detach a target
|
||||
--prune # With --remove-target: delete managed files
|
||||
|
||||
@@ -211,7 +211,7 @@ $_skillshareCompleter = {
|
||||
'mcp' = '--tools-allow', '--tools-deny', '--pi-options', '--target', '--from', '--url', '--file', '--sync', '--replace', '--disabled', '--keep-files', '--revision', '--dry-run', '-n', '--json', '--no-dns', '--live', '--timeout', '--http', '--tls-cert', '--tls-key', '--check', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g'
|
||||
'plugin' = '--target', '--from', '--plugin', '--name', '--source-ref', '--entry', '--revision', '--dry-run', '-n', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g'
|
||||
'extras memory' = '--from', '--version', '--search', '--update-mode', '--json', '--help', '-h', '--project', '-p', '--global', '-g'
|
||||
'extras' = '--mode', '--target', '--source', '--file', '--as', '--flatten', '--no-flatten', '--add-target', '--remove-target', '--prune', '--from', '--dry-run', '--force', '-f', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g'
|
||||
'extras' = '--mode', '--target', '--source', '--file', '--as', '--flatten', '--no-flatten', '--include', '--exclude', '--add-include', '--add-exclude', '--remove-include', '--remove-exclude', '--add-target', '--remove-target', '--prune', '--from', '--dry-run', '--force', '-f', '--json', '--no-tui', '--help', '-h', '--project', '-p', '--global', '-g'
|
||||
'status' = '--json', '--help', '-h', '--project', '-p', '--global', '-g'
|
||||
'new' = '--pattern', '-P', '--dry-run', '-n', '--help', '-h', '--project', '-p', '--global', '-g'
|
||||
'search' = '--json', '--list', '-l', '--hub', '--limit', '-n', '--help', '-h', '--project', '-p', '--global', '-g'
|
||||
|
||||
@@ -667,6 +667,8 @@ _skillshare() {
|
||||
'--file[Single-file extra]:file:_files'
|
||||
'--as[Target filename]:filename:'
|
||||
'--flatten[Flatten subdirectory files]'
|
||||
'*--include[Sync only matching files]:pattern:'
|
||||
'*--exclude[Skip matching files]:pattern:'
|
||||
'--force[Overwrite existing extra]'
|
||||
'--no-tui[Skip interactive TUI]'
|
||||
)
|
||||
@@ -699,6 +701,10 @@ _skillshare() {
|
||||
'--target[Target for --mode]:path:_files -/'
|
||||
'--flatten[Enable flatten]'
|
||||
'--no-flatten[Disable flatten]'
|
||||
'*--add-include[Add an include pattern]:pattern:'
|
||||
'*--add-exclude[Add an exclude pattern]:pattern:'
|
||||
'*--remove-include[Remove an include pattern]:pattern:'
|
||||
'*--remove-exclude[Remove an exclude pattern]:pattern:'
|
||||
'--add-target[Add a target]:path:_files -/'
|
||||
'--as[Target filename]:filename:'
|
||||
'--remove-target[Detach a target]:path:_files -/'
|
||||
|
||||
@@ -70,6 +70,7 @@ func collectExtrasDiff(extras []config.ExtraConfig, sourceResolver func(config.E
|
||||
}
|
||||
|
||||
for _, t := range extra.Targets {
|
||||
files := sync.ExtraTargetFiles(files, t)
|
||||
mode := sync.ExtraTargetMode(t.Mode, extra.File != "")
|
||||
r := extraDiffResult{
|
||||
extraName: extra.Name,
|
||||
|
||||
@@ -19,7 +19,8 @@ func cmdExtras(args []string) error {
|
||||
if hasFlag(args, "--remove-target") {
|
||||
return cmdExtrasRemoveTarget(args)
|
||||
}
|
||||
if sub != "init" && (hasFlag(args, "--mode") || hasFlag(args, "--flatten") || hasFlag(args, "--no-flatten")) {
|
||||
if sub != "init" && (hasFlag(args, "--mode") || hasFlag(args, "--flatten") || hasFlag(args, "--no-flatten") ||
|
||||
hasFlag(args, "--add-include") || hasFlag(args, "--add-exclude") || hasFlag(args, "--remove-include") || hasFlag(args, "--remove-exclude")) {
|
||||
return cmdExtrasMode(args)
|
||||
}
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ func extrasCollectGlobal(name, fromPath string, dryRun, force bool, start time.T
|
||||
}
|
||||
|
||||
sourceDir := config.ResolveExtrasSourceDir(*extra, cfg.EffectiveExtrasSource(), cfg.EffectiveSkillsSource())
|
||||
return runCollect(sourceDir, targetPath, extra.Name, target.Mode, dryRun, force, target.Flatten, "global", config.ConfigPath(), start, "")
|
||||
return runCollect(sourceDir, targetPath, extra.Name, target, dryRun, force, "global", config.ConfigPath(), start, "")
|
||||
}
|
||||
|
||||
func extrasCollectProject(cwd, name, fromPath string, dryRun, force bool, start time.Time) error {
|
||||
@@ -109,7 +109,7 @@ func extrasCollectProject(cwd, name, fromPath string, dryRun, force bool, start
|
||||
}
|
||||
|
||||
sourceDir := config.ResolveExtrasSourceDirProject(*extra, projCfg.EffectiveExtrasSource(cwd), cwd)
|
||||
return runCollect(sourceDir, expandedPath, extra.Name, target.Mode, dryRun, force, target.Flatten, "project", config.ProjectConfigPath(cwd), start, cwd)
|
||||
return runCollect(sourceDir, expandedPath, extra.Name, target, dryRun, force, "project", config.ProjectConfigPath(cwd), start, cwd)
|
||||
}
|
||||
|
||||
// errSingleFileCollect: collect walks a whole target directory, which for a
|
||||
@@ -148,8 +148,8 @@ func resolveCollectExtra(extras []config.ExtraConfig, name, fromPath string, mod
|
||||
return found, config.ExtraTargetConfig{Path: fromPath}, nil
|
||||
}
|
||||
|
||||
func runCollect(sourceDir, targetPath, name, mode string, dryRun, force, flatten bool, scope, cfgPath string, start time.Time, projectRoot string) error {
|
||||
result, err := sync.CollectExtraFiles(sourceDir, targetPath, mode, dryRun, force, flatten, projectRoot)
|
||||
func runCollect(sourceDir, targetPath, name string, target config.ExtraTargetConfig, dryRun, force bool, scope, cfgPath string, start time.Time, projectRoot string) error {
|
||||
result, err := sync.CollectExtraFiles(sourceDir, targetPath, target.Mode, dryRun, force, target.Flatten, projectRoot, target.Include, target.Exclude)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
func cmdExtrasInit(args []string) error {
|
||||
start := time.Now()
|
||||
|
||||
mode, rest, err := parseModeArgs(args, "--target", "--mode", "--source", "--file", "--as")
|
||||
mode, rest, err := parseModeArgs(args, "--target", "--mode", "--source", "--file", "--as", "--include", "--exclude")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -35,6 +35,7 @@ func cmdExtrasInit(args []string) error {
|
||||
var syncMode string
|
||||
var sourceOverride string
|
||||
var file, as string
|
||||
var include, exclude []string
|
||||
var force bool
|
||||
var noTUI bool
|
||||
var flatten bool
|
||||
@@ -70,6 +71,16 @@ func cmdExtrasInit(args []string) error {
|
||||
}
|
||||
i++
|
||||
as = rest[i]
|
||||
case "--include", "--exclude":
|
||||
if i+1 >= len(rest) {
|
||||
return fmt.Errorf("%s requires a pattern", rest[i])
|
||||
}
|
||||
if rest[i] == "--include" {
|
||||
include = append(include, rest[i+1])
|
||||
} else {
|
||||
exclude = append(exclude, rest[i+1])
|
||||
}
|
||||
i++
|
||||
case "--flatten":
|
||||
flatten = true
|
||||
case "--force":
|
||||
@@ -101,7 +112,7 @@ func cmdExtrasInit(args []string) error {
|
||||
|
||||
initTargets := make([]extrasInitTarget, 0, len(targets))
|
||||
for _, t := range targets {
|
||||
initTargets = append(initTargets, extrasInitTarget{path: t, mode: syncMode, flatten: flatten, as: as})
|
||||
initTargets = append(initTargets, extrasInitTarget{path: t, mode: syncMode, flatten: flatten, as: as, include: include, exclude: exclude})
|
||||
}
|
||||
opts := extrasInitOptions{name: name, source: sourceOverride, file: file, targets: initTargets, force: force}
|
||||
if err := validateExtrasInit(opts); err != nil {
|
||||
@@ -130,7 +141,7 @@ type extrasInitOptions struct {
|
||||
func (o extrasInitOptions) extra() config.ExtraConfig {
|
||||
extra := config.ExtraConfig{Name: o.name, Source: o.source, File: o.file}
|
||||
for _, t := range o.targets {
|
||||
et := config.ExtraTargetConfig{Path: t.path, Flatten: t.flatten, As: t.as}
|
||||
et := config.ExtraTargetConfig{Path: t.path, Flatten: t.flatten, As: t.as, Include: t.include, Exclude: t.exclude}
|
||||
if t.mode != "" {
|
||||
et.Mode = t.mode
|
||||
}
|
||||
@@ -336,6 +347,8 @@ func printExtrasInitHelp() {
|
||||
{"--as <filename>", "Target filename for every --target (requires --file; default: the --file name)"},
|
||||
{"--mode <mode>", "Sync mode: merge (default), copy, symlink; import, prepend or append for single-file extras"},
|
||||
{"--flatten", "Flatten files from subdirectories into target root (folder extras only)"},
|
||||
{"--include <pattern>", "Sync only files matching this .gitignore pattern (repeatable; folder extras only)"},
|
||||
{"--exclude <pattern>", "Skip files matching this .gitignore pattern (repeatable; folder extras only)"},
|
||||
{"--force", "Overwrite if extra already exists"},
|
||||
{"-p, --project", "Create in project mode (.skillshare/)"},
|
||||
{"-g, --global", "Create in global mode (~/.config/skillshare/)"},
|
||||
@@ -347,6 +360,7 @@ func printExtrasInitHelp() {
|
||||
helpRow{"skillshare extras init rules --source ~/company-shared/rules --target ~/.claude/rules", ""},
|
||||
helpRow{"skillshare extras init rules --target ~/.claude/rules --force", ""},
|
||||
helpRow{"skillshare extras init agents --target ~/.claude/agents --flatten", ""},
|
||||
helpRow{"skillshare extras init docs --target ~/.claude/docs --include index.md --include learning.md", ""},
|
||||
helpRow{"skillshare extras init prompts --target .claude/prompts -p", ""},
|
||||
helpRow{"skillshare extras init review -p --source .skillshare/extras/prompts \\", ""},
|
||||
helpRow{" --file review.md --target .claude/commands", ""},
|
||||
|
||||
@@ -22,6 +22,8 @@ type extrasInitTarget struct {
|
||||
mode string
|
||||
flatten bool
|
||||
as string // single file: target filename ("" = the source file name)
|
||||
include []string
|
||||
exclude []string
|
||||
}
|
||||
|
||||
// extrasInitAnswers is what the extras init questions collect.
|
||||
|
||||
@@ -90,7 +90,7 @@ func buildExtrasListEntries(extras []config.ExtraConfig, extrasSource, extension
|
||||
} else if _, err := os.Stat(resolvedPath); os.IsNotExist(err) {
|
||||
ti.Status = "not synced"
|
||||
} else {
|
||||
ti.Status = sync.CheckSyncStatus(files, sourceDir, resolvedPath, m, t.Flatten, outputExt)
|
||||
ti.Status = sync.CheckSyncStatus(sync.ExtraTargetFiles(files, t), sourceDir, resolvedPath, m, t.Flatten, outputExt)
|
||||
}
|
||||
|
||||
entry.Targets = append(entry.Targets, ti)
|
||||
|
||||
@@ -912,12 +912,21 @@ func (m extrasListTUIModel) renderModePicker() string {
|
||||
}
|
||||
|
||||
func (m extrasListTUIModel) doSetMode(name, targetPath, newMode string) (string, error) {
|
||||
// Validate before saving so a mode the target's filters rule out (symlink)
|
||||
// is refused instead of breaking every later sync.
|
||||
setMode := func(extras []config.ExtraConfig) error {
|
||||
if err := applyExtraTarget(extras, name, targetPath, func(t *config.ExtraTargetConfig) { t.Mode = newMode }); err != nil {
|
||||
return err
|
||||
}
|
||||
_, extra := findExtraByName(extras, name)
|
||||
return config.ValidateExtraConfig(extra)
|
||||
}
|
||||
if m.projCfg != nil {
|
||||
projCfg, err := config.LoadProject(m.cwd)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := applyExtraTarget(projCfg.Extras, name, targetPath, func(t *config.ExtraTargetConfig) { t.Mode = newMode }); err != nil {
|
||||
if err := setMode(projCfg.Extras); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := projCfg.Save(m.cwd); err != nil {
|
||||
@@ -928,7 +937,7 @@ func (m extrasListTUIModel) doSetMode(name, targetPath, newMode string) (string,
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := applyExtraTarget(cfg.Extras, name, targetPath, func(t *config.ExtraTargetConfig) { t.Mode = newMode }); err != nil {
|
||||
if err := setMode(cfg.Extras); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := cfg.Save(); err != nil {
|
||||
@@ -1078,7 +1087,7 @@ func (m extrasListTUIModel) doCollect(name, targetPath string) (string, error) {
|
||||
collected := 0
|
||||
for _, t := range targets {
|
||||
resolved := config.ExpandPath(t.Path)
|
||||
result, err := sync.CollectExtraFiles(sourceDir, resolved, t.Mode, false, false, t.Flatten, m.projectRoot())
|
||||
result, err := sync.CollectExtraFiles(sourceDir, resolved, t.Mode, false, false, t.Flatten, m.projectRoot(), t.Include, t.Exclude)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("collect from %s: %w", t.Path, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/config"
|
||||
)
|
||||
|
||||
func TestExtrasListTUI_SetModeRejectsSymlinkForFilteredTarget(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(dir, ".skillshare"), 0755)
|
||||
os.WriteFile(filepath.Join(dir, ".skillshare", "config.yaml"), []byte(`extras:
|
||||
- name: docs
|
||||
targets:
|
||||
- path: .claude/docs
|
||||
include: [index.md]
|
||||
`), 0644)
|
||||
m := extrasListTUIModel{projCfg: &config.ProjectConfig{}, cwd: dir}
|
||||
|
||||
if _, err := m.doSetMode("docs", ".claude/docs", "symlink"); err == nil {
|
||||
t.Fatal("expected symlink to be refused for a target with filters")
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,18 @@ import (
|
||||
func cmdExtrasMode(args []string) error {
|
||||
start := time.Now()
|
||||
|
||||
mode, rest, err := parseModeArgs(args, "--target", "--mode")
|
||||
mode, rest, err := parseModeArgs(args, "--target", "--mode", "--add-include", "--add-exclude", "--remove-include", "--remove-exclude")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parsedFilters, rest, err := parseFilterFlags(rest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if parsedFilters.Agents.hasUpdates() {
|
||||
return fmt.Errorf("agent filter flags are not supported for extras; use --add-include/--add-exclude/--remove-include/--remove-exclude")
|
||||
}
|
||||
filters := parsedFilters.Skills
|
||||
|
||||
cwd, _ := os.Getwd()
|
||||
mode = resolveAutoMode(mode, cwd)
|
||||
@@ -62,8 +70,8 @@ func cmdExtrasMode(args []string) error {
|
||||
if name == "" {
|
||||
return fmt.Errorf("extras name is required: skillshare extras <name> --mode <mode> [--target <path>]")
|
||||
}
|
||||
if syncMode == "" && !flattenSet {
|
||||
return fmt.Errorf("--mode or --flatten/--no-flatten is required")
|
||||
if syncMode == "" && !flattenSet && !filters.hasUpdates() {
|
||||
return fmt.Errorf("--mode, --flatten/--no-flatten, or an include/exclude flag is required")
|
||||
}
|
||||
|
||||
if syncMode != "" {
|
||||
@@ -109,7 +117,7 @@ func cmdExtrasMode(args []string) error {
|
||||
targetPath = extra.Targets[0].Path
|
||||
default:
|
||||
// flatten-only changes apply to all targets when --target is omitted
|
||||
if flattenSet && syncMode == "" {
|
||||
if flattenSet && syncMode == "" && !filters.hasUpdates() {
|
||||
return applyFlattenAll(extras, name, flattenVal, saveFn, configPath, start)
|
||||
}
|
||||
return fmt.Errorf("extra %q has %d targets — use --target to specify which one", name, len(extra.Targets))
|
||||
@@ -161,7 +169,21 @@ func cmdExtrasMode(args []string) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, updated := findExtraByName(extras, name); updated.File != "" || config.ManagedExtraMode(syncMode) {
|
||||
var filterChanges []string
|
||||
if filters.hasUpdates() {
|
||||
var filterErr error
|
||||
if err := applyExtraTarget(extras, name, targetPath, func(t *config.ExtraTargetConfig) {
|
||||
filterChanges, filterErr = applyFilterUpdates(&t.Include, &t.Exclude, filters)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if filterErr != nil {
|
||||
return filterErr
|
||||
}
|
||||
}
|
||||
// Filters rule out single files and symlink mode, so check them whenever
|
||||
// either side changes.
|
||||
if _, updated := findExtraByName(extras, name); updated.File != "" || config.ManagedExtraMode(syncMode) || syncMode == "symlink" || filters.hasUpdates() {
|
||||
if err := config.ValidateExtraConfig(updated); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -182,10 +204,17 @@ func cmdExtrasMode(args []string) error {
|
||||
if flattenSet {
|
||||
parts = append(parts, fmt.Sprintf("flatten=%v", flattenVal))
|
||||
}
|
||||
parts = append(parts, filterChanges...)
|
||||
if len(parts) == 0 {
|
||||
parts = append(parts, "no changes")
|
||||
}
|
||||
ui.Done(ui.MarkOK, fmt.Sprintf("Updated %s target %s: %s", name, shortenPath(targetPath), strings.Join(parts, ", ")), 0)
|
||||
|
||||
e := oplog.NewEntry("extras-mode", "ok", time.Since(start))
|
||||
e.Args = map[string]any{"name": name, "target": targetPath, "mode": syncMode, "flatten": flattenVal}
|
||||
if len(filterChanges) > 0 {
|
||||
e.Args["filters"] = filterChanges
|
||||
}
|
||||
oplog.WriteWithLimit(configPath, oplog.OpsFile, e, logMaxEntries()) //nolint:errcheck
|
||||
|
||||
return nil
|
||||
@@ -248,7 +277,7 @@ func applyExtraTarget(extras []config.ExtraConfig, name, targetPath string, appl
|
||||
}
|
||||
|
||||
func printExtrasModeHelp() {
|
||||
printHelp("skillshare extras <name> --mode <mode> [--target <path>]", "Change the sync mode or flatten setting of an extra's target.",
|
||||
printHelp("skillshare extras <name> --mode <mode> [--target <path>]", "Change the sync mode, flatten setting, or file filters of an extra's target.\nFilters use .gitignore patterns on paths inside the source: draft* matches\nat any depth, images/ covers a folder. Files that stop matching are pruned\non the next sync in merge mode; copy mode leaves them in place.",
|
||||
helpGroup{title: "Arguments", rows: []helpRow{
|
||||
{"name", "Extra name (e.g., rules, commands)"},
|
||||
}},
|
||||
@@ -256,6 +285,10 @@ func printExtrasModeHelp() {
|
||||
{"--mode <mode>", "New sync mode: merge, copy, or symlink"},
|
||||
{"--flatten", "Enable flatten (sync subdirectory files into target root)"},
|
||||
{"--no-flatten", "Disable flatten"},
|
||||
{"--add-include <pattern>", "Sync only files matching this pattern (repeatable)"},
|
||||
{"--add-exclude <pattern>", "Skip files matching this pattern (repeatable)"},
|
||||
{"--remove-include <pattern>", "Remove an include pattern"},
|
||||
{"--remove-exclude <pattern>", "Remove an exclude pattern"},
|
||||
{"--target <path>", "Target directory path (optional if extra has only one target)"},
|
||||
{"-p, --project", "Use project mode (.skillshare/)"},
|
||||
{"-g, --global", "Use global mode (~/.config/skillshare/)"},
|
||||
@@ -263,6 +296,8 @@ func printExtrasModeHelp() {
|
||||
helpExamples(
|
||||
helpRow{"skillshare extras rules --mode copy", ""},
|
||||
helpRow{"skillshare extras agents --flatten", ""},
|
||||
helpRow{"skillshare extras docs --target ~/.claude/docs --add-include index.md --add-include learning.md", ""},
|
||||
helpRow{"skillshare extras docs --add-exclude \"draft*\" --add-exclude images/", ""},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -195,6 +195,7 @@ func managedExtraTargetFiles(target config.ExtraTargetConfig, sourceDir, extensi
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files = sync.ExtraTargetFiles(files, target)
|
||||
|
||||
outputExt := ""
|
||||
if target.Extension != "" {
|
||||
|
||||
@@ -271,7 +271,7 @@ func printExtrasStatus(extras []config.ExtraConfig, sourceDirFn func(config.Extr
|
||||
continue
|
||||
}
|
||||
mode := sync.ExtraTargetMode(t.Mode, extra.File != "")
|
||||
ui.Row(ui.MarkNone, extra.Name, pad(shortenPath(t.Path), pathW)+" "+theme.Dim().Render(plural(len(files), "file")+" · "+mode), width)
|
||||
ui.Row(ui.MarkNone, extra.Name, pad(shortenPath(t.Path), pathW)+" "+theme.Dim().Render(plural(len(sync.ExtraTargetFiles(files, t)), "file")+" · "+mode), width)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,6 +296,11 @@ type ExtraTargetConfig struct {
|
||||
Flatten bool `yaml:"flatten,omitempty"` // flatten subdirectories into target root
|
||||
Extension string `yaml:"extension,omitempty"` // transform script applied during sync (implies copy)
|
||||
As string `yaml:"as,omitempty"` // target filename for a single-file extra (default: the extra's file)
|
||||
// Include and Exclude select which source files sync to this target, as
|
||||
// .gitignore-style patterns on the path inside the source (directory
|
||||
// extras with merge or copy mode only).
|
||||
Include []string `yaml:"include,omitempty"`
|
||||
Exclude []string `yaml:"exclude,omitempty"`
|
||||
}
|
||||
|
||||
// ExtraConfig holds configuration for a non-skill resource type (rules, commands, etc.).
|
||||
|
||||
@@ -29,7 +29,7 @@ func ValidateExtraConnections(extras []ExtraConfig, sourceDir func(ExtraConfig)
|
||||
type owner struct{ name, mode string }
|
||||
owners := map[string]owner{}
|
||||
for _, extra := range extras {
|
||||
if !usesSingleFileSettings(extra) {
|
||||
if !needsExtraValidation(extra) {
|
||||
continue
|
||||
}
|
||||
if err := ValidateExtraConfig(extra); err != nil {
|
||||
@@ -159,12 +159,15 @@ func validateExtrasImportSupport(extras []ExtraConfig, targets map[string]Target
|
||||
return nil
|
||||
}
|
||||
|
||||
func usesSingleFileSettings(extra ExtraConfig) bool {
|
||||
// needsExtraValidation reports whether an extra sets anything beyond a plain
|
||||
// folder sync (single-file settings or file filters), which ValidateExtraConfig
|
||||
// must then check before sync.
|
||||
func needsExtraValidation(extra ExtraConfig) bool {
|
||||
if extra.File != "" {
|
||||
return true
|
||||
}
|
||||
for _, target := range extra.Targets {
|
||||
if target.As != "" || ManagedExtraMode(target.Mode) {
|
||||
if target.As != "" || ManagedExtraMode(target.Mode) || len(target.Include) > 0 || len(target.Exclude) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -102,6 +103,20 @@ func validateExtraTarget(file string, t ExtraTargetConfig) error {
|
||||
if err := ValidateExtraFlatten(t.Flatten, t.Mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(t.Include) > 0 || len(t.Exclude) > 0 {
|
||||
if file != "" {
|
||||
return fmt.Errorf("include and exclude cannot be used with a single-file extra")
|
||||
}
|
||||
if t.Mode == "symlink" {
|
||||
return fmt.Errorf("include and exclude cannot be used with symlink mode (symlink links the entire directory)")
|
||||
}
|
||||
if err := validateExtraPatterns("include", t.Include); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateExtraPatterns("exclude", t.Exclude); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if file == "" {
|
||||
if t.As != "" {
|
||||
return fmt.Errorf("as requires file")
|
||||
@@ -131,3 +146,17 @@ func validateExtraFilename(field, name string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateExtraPatterns rejects .gitignore-style patterns whose path segments
|
||||
// are not valid globs, so a typo fails at config time instead of matching
|
||||
// nothing during sync.
|
||||
func validateExtraPatterns(field string, patterns []string) error {
|
||||
for _, p := range patterns {
|
||||
for _, seg := range strings.Split(strings.TrimPrefix(strings.TrimSpace(p), "!"), "/") {
|
||||
if _, err := path.Match(seg, ""); err != nil {
|
||||
return fmt.Errorf("invalid %s pattern %q: %w", field, p, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -29,6 +29,10 @@ func TestValidateExtraConfig_SingleFile(t *testing.T) {
|
||||
{"extension with single-file copy", ExtraConfig{Name: "i", File: "AGENTS.md", Targets: []ExtraTargetConfig{{Path: "/t", Mode: "copy", Extension: "x"}}}, "extension cannot be used with a single-file extra"},
|
||||
{"extension on directory extra", ExtraConfig{Name: "rules", Targets: []ExtraTargetConfig{{Path: "/t", Mode: "copy", Extension: "x"}}}, ""},
|
||||
{"unknown mode", ExtraConfig{Name: "i", Targets: []ExtraTargetConfig{{Path: "/t", Mode: "bogus"}}}, "invalid mode"},
|
||||
{"filters on directory extra", ExtraConfig{Name: "docs", Targets: []ExtraTargetConfig{{Path: "/t", Include: []string{"*.md"}, Exclude: []string{"draft*"}}}}, ""},
|
||||
{"filters with symlink", ExtraConfig{Name: "docs", Targets: []ExtraTargetConfig{{Path: "/t", Mode: "symlink", Include: []string{"*.md"}}}}, "symlink"},
|
||||
{"filters with file", ExtraConfig{Name: "i", File: "AGENTS.md", Targets: []ExtraTargetConfig{{Path: "/t", Exclude: []string{"x"}}}}, "single-file"},
|
||||
{"invalid filter pattern", ExtraConfig{Name: "docs", Targets: []ExtraTargetConfig{{Path: "/t", Include: []string{"guides/[a"}}}}, "invalid include pattern"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -100,3 +104,15 @@ func TestValidSyncModes_SkillsRejectImport(t *testing.T) {
|
||||
t.Errorf("extras mode import rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A malformed pattern written by hand in the config must stop sync before it
|
||||
// matches nothing and merge prunes every link.
|
||||
func TestValidateExtraConnections_RejectsBadFilterOnFolderExtra(t *testing.T) {
|
||||
err := ValidateExtraConnections([]ExtraConfig{
|
||||
{Name: "docs", Targets: []ExtraTargetConfig{{Path: "/tgt", Include: []string{"["}}}},
|
||||
}, func(e ExtraConfig) string { return "/src/" + e.Name }, func(p string) string { return p })
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for the malformed include pattern")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,12 +46,15 @@ type extrasListEntry struct {
|
||||
|
||||
// extrasTargetInfo is the per-target sync status inside an extra entry.
|
||||
type extrasTargetInfo struct {
|
||||
Path string `json:"path"`
|
||||
Mode string `json:"mode"`
|
||||
Flatten bool `json:"flatten"`
|
||||
Extension string `json:"extension,omitempty"`
|
||||
As string `json:"as,omitempty"` // single-file extra: target filename
|
||||
Status string `json:"status"` // "synced", "drift", "modified", "not synced", "no source"
|
||||
Path string `json:"path"`
|
||||
Mode string `json:"mode"`
|
||||
Flatten bool `json:"flatten"`
|
||||
Extension string `json:"extension,omitempty"`
|
||||
As string `json:"as,omitempty"` // single-file extra: target filename
|
||||
Include []string `json:"include,omitempty"`
|
||||
Exclude []string `json:"exclude,omitempty"`
|
||||
FileCount int `json:"file_count"` // source files this target syncs after include/exclude
|
||||
Status string `json:"status"` // "synced", "drift", "modified", "not synced", "no source"
|
||||
}
|
||||
|
||||
// extrasSourceDir returns the source directory for the named extra in the
|
||||
@@ -143,7 +146,11 @@ func (s *Server) handleExtras(w http.ResponseWriter, r *http.Request) {
|
||||
Flatten: t.Flatten,
|
||||
Extension: t.Extension,
|
||||
As: t.As,
|
||||
Include: t.Include,
|
||||
Exclude: t.Exclude,
|
||||
}
|
||||
targetFiles := syncpkg.ExtraTargetFiles(files, t)
|
||||
ti.FileCount = len(targetFiles)
|
||||
|
||||
if extra.File != "" {
|
||||
ti.Status = syncpkg.ExtraFileStatus(syncpkg.NewExtraFile(sourceDir, extra.File, targetPath, t.As, m))
|
||||
@@ -184,7 +191,7 @@ func (s *Server) handleExtras(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("warning: extension %q for extra %q could not be resolved (%v); sync status may be inaccurate", t.Extension, extra.Name, serr)
|
||||
}
|
||||
}
|
||||
ti.Status = syncpkg.CheckSyncStatus(files, sourceDir, targetPath, m, t.Flatten, outputExt)
|
||||
ti.Status = syncpkg.CheckSyncStatus(targetFiles, sourceDir, targetPath, m, t.Flatten, outputExt)
|
||||
}
|
||||
|
||||
entry.Targets = append(entry.Targets, ti)
|
||||
@@ -302,7 +309,7 @@ func (s *Server) handleExtrasDiff(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
targetPath := resolveExtrasTargetPath(projectRoot, t.Path)
|
||||
items := buildExtrasDiffItems(files, sourceDir, targetPath, m, t.Flatten, outputExt)
|
||||
items := buildExtrasDiffItems(syncpkg.ExtraTargetFiles(files, t), sourceDir, targetPath, m, t.Flatten, outputExt)
|
||||
synced := len(items) == 0
|
||||
|
||||
out = append(out, extrasDiffEntry{
|
||||
@@ -846,8 +853,8 @@ func (s *Server) handleExtrasMode(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if extra.File != "" || config.ManagedExtraMode(newMode) {
|
||||
changed := config.ExtraTargetConfig{Path: t.Path, Mode: newMode, Flatten: newFlatten, Extension: newExtension, As: t.As}
|
||||
if extra.File != "" || config.ManagedExtraMode(newMode) || len(t.Include) > 0 || len(t.Exclude) > 0 {
|
||||
changed := config.ExtraTargetConfig{Path: t.Path, Mode: newMode, Flatten: newFlatten, Extension: newExtension, As: t.As, Include: t.Include, Exclude: t.Exclude}
|
||||
if err := config.ValidateExtraConfig(config.ExtraConfig{Name: extra.Name, File: extra.File, Targets: []config.ExtraTargetConfig{changed}}); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"skillshare/internal/config"
|
||||
syncpkg "skillshare/internal/sync"
|
||||
)
|
||||
|
||||
// handleExtrasPreview — POST /api/extras/{name}/preview
|
||||
// Shows what draft include and exclude patterns do to the extra's source files.
|
||||
func (s *Server) handleExtrasPreview(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Include []string `json:"include"`
|
||||
Exclude []string `json:"exclude"`
|
||||
}
|
||||
if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil {
|
||||
if !errors.Is(err, errBodyTooLarge) {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
extras := s.extrasConfig()
|
||||
idx := slices.IndexFunc(extras, func(e config.ExtraConfig) bool { return e.Name == r.PathValue("name") })
|
||||
if idx < 0 {
|
||||
s.mu.RUnlock()
|
||||
writeError(w, http.StatusNotFound, "extra not found: "+r.PathValue("name"))
|
||||
return
|
||||
}
|
||||
sourceDir := s.extrasSourceDir(extras[idx])
|
||||
s.mu.RUnlock()
|
||||
|
||||
files, err := syncpkg.DiscoverExtraFiles(sourceDir)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "source not readable: "+err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{
|
||||
"files": syncpkg.PreviewExtraFilter(files, body.Include, body.Exclude),
|
||||
"unmatched": syncpkg.UnmatchedIncludes(files, body.Include),
|
||||
})
|
||||
}
|
||||
|
||||
// handleExtrasEditTarget — PUT /api/extras/{name}/targets
|
||||
// Replaces one target's settings. A new folder or file name removes what
|
||||
// skillshare put at the old place (copies stay) and syncs the extra; other
|
||||
// changes only write config and take effect on the next sync.
|
||||
func (s *Server) handleExtrasEditTarget(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
name := r.PathValue("name")
|
||||
|
||||
var body struct {
|
||||
Path string `json:"path"` // the target as stored in config
|
||||
Target struct {
|
||||
Path string `json:"path"`
|
||||
Mode string `json:"mode"`
|
||||
Flatten bool `json:"flatten"`
|
||||
Extension string `json:"extension"`
|
||||
As string `json:"as"`
|
||||
Include []string `json:"include"`
|
||||
Exclude []string `json:"exclude"`
|
||||
} `json:"target"`
|
||||
}
|
||||
if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil {
|
||||
if !errors.Is(err, errBodyTooLarge) {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
}
|
||||
return
|
||||
}
|
||||
if body.Path == "" || body.Target.Path == "" {
|
||||
writeError(w, http.StatusBadRequest, "path is required")
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
extras := s.extrasConfig()
|
||||
idx := slices.IndexFunc(extras, func(e config.ExtraConfig) bool { return e.Name == name })
|
||||
if idx == -1 {
|
||||
writeError(w, http.StatusNotFound, "extra not found: "+name)
|
||||
return
|
||||
}
|
||||
extra := extras[idx]
|
||||
tIdx := slices.IndexFunc(extra.Targets, func(t config.ExtraTargetConfig) bool { return t.Path == body.Path })
|
||||
if tIdx == -1 {
|
||||
writeError(w, http.StatusNotFound, "target not found: "+body.Path)
|
||||
return
|
||||
}
|
||||
old := extra.Targets[tIdx]
|
||||
|
||||
in := body.Target
|
||||
next := config.ExtraTargetConfig{Path: in.Path, Mode: in.Mode, Flatten: in.Flatten, Extension: in.Extension, As: in.As, Include: in.Include, Exclude: in.Exclude}
|
||||
if next.Extension != "" {
|
||||
// A transform extension only makes sense with copy mode.
|
||||
next.Mode = "copy"
|
||||
}
|
||||
if next.Mode == "symlink" {
|
||||
// One link to the whole folder cannot leave files out.
|
||||
next.Include, next.Exclude = nil, nil
|
||||
}
|
||||
newPath := filepath.Clean(resolveExtrasTargetPath(s.projectRoot, next.Path))
|
||||
if !s.IsProjectMode() {
|
||||
next.Path = newPath
|
||||
}
|
||||
oldPath := filepath.Clean(resolveExtrasTargetPath(s.projectRoot, old.Path))
|
||||
for j, t := range extra.Targets {
|
||||
if j != tIdx && filepath.Clean(resolveExtrasTargetPath(s.projectRoot, t.Path)) == newPath {
|
||||
writeError(w, http.StatusConflict, "target already exists: "+in.Path)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := config.ValidateExtraConfig(config.ExtraConfig{Name: name, File: extra.File, Targets: []config.ExtraTargetConfig{next}}); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
prev := extra.Targets
|
||||
extras[idx].Targets = slices.Clone(prev)
|
||||
extras[idx].Targets[tIdx] = next
|
||||
if err := s.validateExtra(name); err != nil {
|
||||
extras[idx].Targets = prev
|
||||
if !writeExtraTargetConflict(w, err, in.Path) {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := s.saveAndReloadConfig(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
moved := newPath != oldPath || next.As != old.As
|
||||
resp := map[string]any{"success": true, "name": name, "target": next.Path}
|
||||
status, msg := "ok", ""
|
||||
if moved {
|
||||
sourceDir := s.extrasSourceDir(extra)
|
||||
oldMode := syncpkg.ExtraTargetMode(old.Mode, extra.File != "")
|
||||
var errs []string
|
||||
resp["pruned"], errs = clearExtraTarget(extra.File, sourceDir, oldPath, old.As, oldMode)
|
||||
results := s.syncExtras(name, false, false)
|
||||
resp["extras"] = results
|
||||
if len(errs) > 0 {
|
||||
resp["prune_errors"] = errs
|
||||
}
|
||||
if status, _ = extrasSyncStatus(results); len(errs) > 0 {
|
||||
status, msg = "partial", errs[0]
|
||||
}
|
||||
}
|
||||
|
||||
s.writeOpsLog("extras-target", status, start, map[string]any{
|
||||
"name": name, "target": next.Path, "from": old.Path, "action": "edit", "scope": "ui",
|
||||
}, msg)
|
||||
writeJSON(w, resp)
|
||||
}
|
||||
|
||||
// handleExtrasEdit — PATCH /api/extras/{name}
|
||||
// Renames an extra or points it at another source folder. A rename keeps the
|
||||
// folder: an extra in its default folder gets that folder as its source. A new
|
||||
// source must already exist; the old folder is left as it is, and every target
|
||||
// is relinked to the new one.
|
||||
func (s *Server) handleExtrasEdit(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
name := r.PathValue("name")
|
||||
|
||||
var body struct {
|
||||
Name string `json:"name"`
|
||||
// Source is left alone when omitted; "" means the default folder. Global:
|
||||
// a path; project: relative to the project root or a path inside it.
|
||||
Source *string `json:"source"`
|
||||
}
|
||||
if err := decodeJSON(w, r, &body, defaultJSONBodyLimit); err != nil {
|
||||
if !errors.Is(err, errBodyTooLarge) {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
extras := s.extrasConfig()
|
||||
idx := slices.IndexFunc(extras, func(e config.ExtraConfig) bool { return e.Name == name })
|
||||
if idx == -1 {
|
||||
writeError(w, http.StatusNotFound, "extra not found: "+name)
|
||||
return
|
||||
}
|
||||
extra := extras[idx]
|
||||
oldSource := s.extrasSourceDir(extra)
|
||||
next := extra
|
||||
|
||||
if body.Name != "" && body.Name != name {
|
||||
// Sync skips agent target folders for the extra named agents, and the
|
||||
// memory notes live in the extra named memory.
|
||||
for _, special := range []string{"agents", "memory"} {
|
||||
if strings.EqualFold(name, special) || strings.EqualFold(body.Name, special) {
|
||||
writeError(w, http.StatusBadRequest, "an extra cannot be renamed to or from "+special)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := config.ValidateExtraName(body.Name); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
others := slices.DeleteFunc(slices.Clone(extras), func(e config.ExtraConfig) bool { return e.Name == name })
|
||||
if err := config.ValidateExtraNameUnique(body.Name, others); err != nil {
|
||||
writeError(w, http.StatusConflict, err.Error())
|
||||
return
|
||||
}
|
||||
next.Name = body.Name
|
||||
if next.Source == "" {
|
||||
source, err := s.storedExtraSource(oldSource)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
next.Source = source
|
||||
}
|
||||
}
|
||||
|
||||
if body.Source != nil {
|
||||
source := *body.Source
|
||||
if source != "" && s.IsProjectMode() {
|
||||
if abs := config.ExpandPath(source); filepath.IsAbs(abs) {
|
||||
if rel, err := filepath.Rel(s.projectRoot, abs); err == nil {
|
||||
source = rel
|
||||
}
|
||||
}
|
||||
if err := config.ValidateProjectExtraSource(source); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
source = filepath.ToSlash(filepath.Clean(source))
|
||||
} else if source != "" {
|
||||
source = filepath.Clean(config.ExpandPath(source))
|
||||
}
|
||||
next.Source = source
|
||||
}
|
||||
newSource := s.extrasSourceDir(next)
|
||||
relink := filepath.Clean(newSource) != filepath.Clean(oldSource)
|
||||
if relink {
|
||||
if extra.File != "" {
|
||||
if info, err := os.Stat(filepath.Join(newSource, extra.File)); err != nil || info.IsDir() {
|
||||
writeError(w, http.StatusBadRequest, fmt.Sprintf("%s not found in %s", extra.File, newSource))
|
||||
return
|
||||
}
|
||||
} else if info, err := os.Stat(newSource); err != nil || !info.IsDir() {
|
||||
writeError(w, http.StatusBadRequest, "folder not found: "+newSource)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
extras[idx] = next
|
||||
if err := s.validateExtra(next.Name); err != nil {
|
||||
extras[idx] = extra
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.saveAndReloadConfig(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// Links into the old folder go only once the config points elsewhere, so a
|
||||
// failed save leaves working targets alone.
|
||||
var pruneErrs []string
|
||||
if relink {
|
||||
for _, t := range extra.Targets {
|
||||
mode := syncpkg.ExtraTargetMode(t.Mode, extra.File != "")
|
||||
_, errs := clearExtraTarget(extra.File, oldSource, resolveExtrasTargetPath(s.projectRoot, t.Path), t.As, mode)
|
||||
pruneErrs = append(pruneErrs, errs...)
|
||||
}
|
||||
}
|
||||
|
||||
resp := map[string]any{"success": true, "name": next.Name}
|
||||
status, msg := "ok", ""
|
||||
if relink {
|
||||
results := s.syncExtras(next.Name, false, false)
|
||||
resp["extras"] = results
|
||||
status, _ = extrasSyncStatus(results)
|
||||
}
|
||||
if len(pruneErrs) > 0 {
|
||||
resp["prune_errors"] = pruneErrs
|
||||
status, msg = "partial", pruneErrs[0]
|
||||
}
|
||||
|
||||
s.writeOpsLog("extras-edit", status, start, map[string]any{
|
||||
"name": next.Name, "from": name, "source": next.Source, "scope": "ui",
|
||||
}, msg)
|
||||
writeJSON(w, resp)
|
||||
}
|
||||
|
||||
// clearExtraTarget removes what skillshare put at one target: links into
|
||||
// sourceDir in merge mode, the folder link in symlink mode, and a single-file
|
||||
// target goes back to how it was. Copies stay, since nothing records which
|
||||
// copied files are skillshare's.
|
||||
func clearExtraTarget(file, sourceDir, targetPath, as, mode string) (int, []string) {
|
||||
if file != "" {
|
||||
changed, err := syncpkg.RestoreExtraTarget(syncpkg.NewExtraFile(sourceDir, file, targetPath, as, mode))
|
||||
if err != nil {
|
||||
return 0, []string{err.Error()}
|
||||
}
|
||||
if changed {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
if mode == "symlink" && !linksTo(targetPath, sourceDir) {
|
||||
return 0, nil
|
||||
}
|
||||
return syncpkg.PruneExtraTargetFiles(targetPath, sourceDir, mode, nil)
|
||||
}
|
||||
|
||||
// storedExtraSource is dir as an extra's source field: absolute in global
|
||||
// mode, relative to the project root in project mode.
|
||||
func (s *Server) storedExtraSource(dir string) (string, error) {
|
||||
if !s.IsProjectMode() {
|
||||
return dir, nil
|
||||
}
|
||||
rel, err := filepath.Rel(s.projectRoot, dir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.ToSlash(rel), nil
|
||||
}
|
||||
|
||||
// validateExtra runs the ownership and import checks for one extra against the
|
||||
// whole config. Callers must hold s.mu.
|
||||
func (s *Server) validateExtra(name string) error {
|
||||
if s.IsProjectMode() {
|
||||
return s.projectCfg.ValidateExtras(s.projectRoot, name)
|
||||
}
|
||||
return s.cfg.ValidateExtras(name)
|
||||
}
|
||||
|
||||
// linksTo reports whether link is a symlink to dir, comparing the link text
|
||||
// too, so a link whose folder has since moved or been deleted still counts.
|
||||
func linksTo(link, dir string) bool {
|
||||
dest, err := os.Readlink(link)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if !filepath.IsAbs(dest) {
|
||||
dest = filepath.Join(filepath.Dir(link), dest)
|
||||
}
|
||||
if filepath.Clean(dest) == filepath.Clean(dir) {
|
||||
return true
|
||||
}
|
||||
real, err := filepath.EvalSymlinks(link)
|
||||
src, srcErr := filepath.EvalSymlinks(dir)
|
||||
return err == nil && srcErr == nil && real == src
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/config"
|
||||
)
|
||||
|
||||
// newDocsExtraServer serves a docs extra holding index.md and draft.md with
|
||||
// one merge target, and returns the server, the extra's folder and the target.
|
||||
func newDocsExtraServer(t *testing.T, target config.ExtraTargetConfig) (*Server, string, string) {
|
||||
t.Helper()
|
||||
if target.Path == "" {
|
||||
target.Path = t.TempDir()
|
||||
}
|
||||
s, skillsDir := newTestServerWithExtras(t, []config.ExtraConfig{{Name: "docs", Targets: []config.ExtraTargetConfig{target}}}, "")
|
||||
docs := filepath.Join(filepath.Dir(skillsDir), "extras", "docs")
|
||||
os.WriteFile(filepath.Join(docs, "index.md"), []byte("i"), 0644)
|
||||
os.WriteFile(filepath.Join(docs, "draft.md"), []byte("d"), 0644)
|
||||
return s, docs, target.Path
|
||||
}
|
||||
|
||||
func serveExtras(s *Server, method, path, body string) *httptest.ResponseRecorder {
|
||||
rr := httptest.NewRecorder()
|
||||
s.handler.ServeHTTP(rr, httptest.NewRequest(method, path, strings.NewReader(body)))
|
||||
return rr
|
||||
}
|
||||
|
||||
func TestHandleExtras_ListsTargetFilterAndFileCount(t *testing.T) {
|
||||
s, _, _ := newDocsExtraServer(t, config.ExtraTargetConfig{Exclude: []string{"draft*"}})
|
||||
|
||||
rr := serveExtras(s, http.MethodGet, "/api/extras", "")
|
||||
|
||||
var resp struct {
|
||||
Extras []extrasListEntry `json:"extras"`
|
||||
}
|
||||
json.Unmarshal(rr.Body.Bytes(), &resp)
|
||||
if ti := resp.Extras[0].Targets[0]; ti.FileCount != 1 || len(ti.Exclude) != 1 {
|
||||
t.Errorf("target = %+v, want file_count 1 and the exclude pattern", ti)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleExtrasPreview_NamesTheExcludePattern(t *testing.T) {
|
||||
s, _, _ := newDocsExtraServer(t, config.ExtraTargetConfig{})
|
||||
|
||||
rr := serveExtras(s, http.MethodPost, "/api/extras/docs/preview", `{"exclude":["draft*"],"include":["*.md","nope.md"]}`)
|
||||
|
||||
body := rr.Body.String()
|
||||
if !strings.Contains(body, `{"file":"draft.md","status":"excluded","reason":"draft*"}`) || !strings.Contains(body, `"unmatched":["nope.md"]`) {
|
||||
t.Errorf("unexpected preview: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleExtrasEditTarget_NewPathRemovesOldLinksAndSyncs(t *testing.T) {
|
||||
s, _, oldTgt := newDocsExtraServer(t, config.ExtraTargetConfig{})
|
||||
serveExtras(s, http.MethodPost, "/api/extras/sync", `{"name":"docs"}`)
|
||||
newTgt := t.TempDir()
|
||||
|
||||
rr := serveExtras(s, http.MethodPut, "/api/extras/docs/targets", `{"path":"`+oldTgt+`","target":{"path":"`+newTgt+`"}}`)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(oldTgt, "index.md")); !os.IsNotExist(err) {
|
||||
t.Errorf("old link should be gone, lstat err = %v", err)
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(newTgt, "index.md")); err != nil {
|
||||
t.Errorf("new target should be synced: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleExtrasEditTarget_SymlinkDropsFilters(t *testing.T) {
|
||||
s, _, tgt := newDocsExtraServer(t, config.ExtraTargetConfig{Include: []string{"index.md"}})
|
||||
|
||||
rr := serveExtras(s, http.MethodPut, "/api/extras/docs/targets", `{"path":"`+tgt+`","target":{"path":"`+tgt+`","mode":"symlink","include":["index.md"]}}`)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
if got := s.cfg.Extras[0].Targets[0]; got.Mode != "symlink" || got.Include != nil {
|
||||
t.Errorf("target = %+v, want symlink with no include", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleExtrasEdit_RenameKeepsTheFolder(t *testing.T) {
|
||||
s, docs, _ := newDocsExtraServer(t, config.ExtraTargetConfig{})
|
||||
|
||||
rr := serveExtras(s, http.MethodPatch, "/api/extras/docs", `{"name":"notes"}`)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
if got := s.cfg.Extras[0]; got.Name != "notes" || got.Source != docs {
|
||||
t.Errorf("extra = %+v, want notes with source %s", got, docs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleExtrasEdit_RenameFromAgentsRejected(t *testing.T) {
|
||||
s, _ := newTestServerWithExtras(t, []config.ExtraConfig{{Name: "agents", Targets: []config.ExtraTargetConfig{{Path: t.TempDir()}}}}, "")
|
||||
|
||||
rr := serveExtras(s, http.MethodPatch, "/api/extras/agents", `{"name":"helpers"}`)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleExtrasEdit_MissingSourceRejected(t *testing.T) {
|
||||
s, _, _ := newDocsExtraServer(t, config.ExtraTargetConfig{})
|
||||
|
||||
rr := serveExtras(s, http.MethodPatch, "/api/extras/docs", `{"source":"`+filepath.Join(t.TempDir(), "nope")+`"}`)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleExtrasEdit_NewSourceRelinksTargets(t *testing.T) {
|
||||
s, _, tgt := newDocsExtraServer(t, config.ExtraTargetConfig{})
|
||||
serveExtras(s, http.MethodPost, "/api/extras/sync", `{"name":"docs"}`)
|
||||
newSrc := t.TempDir()
|
||||
os.WriteFile(filepath.Join(newSrc, "guide.md"), []byte("g"), 0644)
|
||||
|
||||
rr := serveExtras(s, http.MethodPatch, "/api/extras/docs", `{"source":"`+newSrc+`"}`)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(tgt, "index.md")); !os.IsNotExist(err) {
|
||||
t.Errorf("link into the old folder should be gone, lstat err = %v", err)
|
||||
}
|
||||
if dest, err := os.Readlink(filepath.Join(tgt, "guide.md")); err != nil || !strings.HasPrefix(dest, newSrc) {
|
||||
t.Errorf("guide.md should link into the new folder, got %q, %v", dest, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleExtrasMode_SymlinkRejectedWhenTargetHasFilters(t *testing.T) {
|
||||
s, _, tgt := newDocsExtraServer(t, config.ExtraTargetConfig{Include: []string{"index.md"}})
|
||||
|
||||
rr := serveExtras(s, http.MethodPatch, "/api/extras/docs/mode", `{"target":"`+tgt+`","mode":"symlink"}`)
|
||||
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleExtrasEdit_NewSourceRelinksSymlinkWhoseOldFolderIsGone(t *testing.T) {
|
||||
link := filepath.Join(t.TempDir(), "docs")
|
||||
s, docs, _ := newDocsExtraServer(t, config.ExtraTargetConfig{Path: link, Mode: "symlink"})
|
||||
if err := os.Symlink(docs, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.RemoveAll(docs)
|
||||
newSrc := t.TempDir()
|
||||
|
||||
rr := serveExtras(s, http.MethodPatch, "/api/extras/docs", `{"source":"`+newSrc+`"}`)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
if dest, err := os.Readlink(link); err != nil || dest != newSrc {
|
||||
t.Errorf("target should link to the new folder, got %q, %v", dest, err)
|
||||
}
|
||||
}
|
||||
@@ -648,6 +648,9 @@ func (s *Server) registerRoutes() {
|
||||
s.mux.HandleFunc("DELETE /api/extras/{name}", s.handleExtrasDelete)
|
||||
s.mux.HandleFunc("POST /api/extras/{name}/targets", s.handleExtrasAddTarget)
|
||||
s.mux.HandleFunc("DELETE /api/extras/{name}/targets", s.handleExtrasRemoveTarget)
|
||||
s.mux.HandleFunc("PUT /api/extras/{name}/targets", s.handleExtrasEditTarget)
|
||||
s.mux.HandleFunc("POST /api/extras/{name}/preview", s.handleExtrasPreview)
|
||||
s.mux.HandleFunc("PATCH /api/extras/{name}", s.handleExtrasEdit)
|
||||
|
||||
// Extensions (transform extensions management)
|
||||
s.mux.HandleFunc("GET /api/extensions", s.handleExtensionsList)
|
||||
|
||||
+27
-7
@@ -86,6 +86,13 @@ func DiscoverExtraFiles(sourcePath string) ([]string, error) {
|
||||
// When dryRun is true the function counts what would happen but makes no
|
||||
// filesystem changes.
|
||||
func SyncExtra(sourcePath, targetPath, mode string, dryRun, force, flatten bool, projectRoot string, spec *ExtensionSpec) (*ExtraResult, error) {
|
||||
return syncExtraDir(sourcePath, targetPath, mode, dryRun, force, flatten, projectRoot, spec, nil, nil)
|
||||
}
|
||||
|
||||
// syncExtraDir is SyncExtra limited to the source files that pass include and
|
||||
// exclude (see FilterExtraFiles). Files filtered out count as absent, so merge
|
||||
// prunes their links like links to deleted source files.
|
||||
func syncExtraDir(sourcePath, targetPath, mode string, dryRun, force, flatten bool, projectRoot string, spec *ExtensionSpec, include, exclude []string) (*ExtraResult, error) {
|
||||
if spec != nil {
|
||||
// Transform extensions emit generated files into the target, so only
|
||||
// copy semantics apply. Reject merge/symlink here so the API and the
|
||||
@@ -93,7 +100,7 @@ func SyncExtra(sourcePath, targetPath, mode string, dryRun, force, flatten bool,
|
||||
if mode != "" && mode != "copy" {
|
||||
return nil, fmt.Errorf("extension %q requires copy mode, got %q", spec.Name, mode)
|
||||
}
|
||||
return syncExtraTransform(sourcePath, targetPath, spec, dryRun, force, flatten)
|
||||
return syncExtraTransform(sourcePath, targetPath, spec, dryRun, force, flatten, include, exclude)
|
||||
}
|
||||
if mode == "" {
|
||||
mode = "merge"
|
||||
@@ -101,12 +108,15 @@ func SyncExtra(sourcePath, targetPath, mode string, dryRun, force, flatten bool,
|
||||
if flatten && mode == "symlink" {
|
||||
return nil, fmt.Errorf("flatten cannot be used with symlink mode")
|
||||
}
|
||||
if mode == "symlink" && (len(include) > 0 || len(exclude) > 0) {
|
||||
return nil, fmt.Errorf("include and exclude cannot be used with symlink mode")
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case "symlink":
|
||||
return syncExtraSymlinkMode(sourcePath, targetPath, dryRun, force, projectRoot)
|
||||
case "merge", "copy":
|
||||
return syncExtraPerFile(sourcePath, targetPath, mode, dryRun, force, flatten, projectRoot)
|
||||
return syncExtraPerFile(sourcePath, targetPath, mode, dryRun, force, flatten, projectRoot, include, exclude)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported extras sync mode: %q", mode)
|
||||
}
|
||||
@@ -116,13 +126,14 @@ func SyncExtra(sourcePath, targetPath, mode string, dryRun, force, flatten bool,
|
||||
// transformed output into targetPath using copy semantics. Output files are
|
||||
// renamed per spec.OutputExt. It does not prune output-looking orphans because
|
||||
// copy targets do not carry ownership metadata.
|
||||
func syncExtraTransform(sourcePath, targetPath string, spec *ExtensionSpec, dryRun, force, flatten bool) (*ExtraResult, error) {
|
||||
func syncExtraTransform(sourcePath, targetPath string, spec *ExtensionSpec, dryRun, force, flatten bool, include, exclude []string) (*ExtraResult, error) {
|
||||
result := &ExtraResult{}
|
||||
|
||||
files, err := DiscoverExtraFiles(sourcePath)
|
||||
files, warnings, err := discoverExtraTargetFiles(sourcePath, include, exclude)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.Warnings = warnings
|
||||
absSrc, err := filepath.Abs(sourcePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to resolve source path: %w", err)
|
||||
@@ -304,7 +315,7 @@ func syncExtraSymlinkMode(sourcePath, targetPath string, dryRun, force bool, pro
|
||||
// syncExtraPerFile handles merge (symlink) and copy modes on a per-file basis.
|
||||
// Merge copies instead when file links are unavailable; those copies are
|
||||
// tracked so later syncs keep them updated and pruned like links.
|
||||
func syncExtraPerFile(sourcePath, targetPath, mode string, dryRun, force, flatten bool, projectRoot string) (*ExtraResult, error) {
|
||||
func syncExtraPerFile(sourcePath, targetPath, mode string, dryRun, force, flatten bool, projectRoot string, include, exclude []string) (*ExtraResult, error) {
|
||||
result := &ExtraResult{}
|
||||
|
||||
var copies *copyTracker
|
||||
@@ -316,10 +327,11 @@ func syncExtraPerFile(sourcePath, targetPath, mode string, dryRun, force, flatte
|
||||
}
|
||||
}
|
||||
|
||||
files, err := DiscoverExtraFiles(sourcePath)
|
||||
files, warnings, err := discoverExtraTargetFiles(sourcePath, include, exclude)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.Warnings = append(result.Warnings, warnings...)
|
||||
|
||||
absSrc, err := filepath.Abs(sourcePath)
|
||||
if err != nil {
|
||||
@@ -778,7 +790,8 @@ type ExtraCollectResult struct {
|
||||
// (identical content is still skipped).
|
||||
// When flatten is true, collected files are placed in the source root
|
||||
// (basename only) rather than preserving the target subdirectory structure.
|
||||
func CollectExtraFiles(sourceDir, targetDir, mode string, dryRun, force, flatten bool, projectRoot string) (*ExtraCollectResult, error) {
|
||||
// Files that include and exclude leave out of the target are skipped.
|
||||
func CollectExtraFiles(sourceDir, targetDir, mode string, dryRun, force, flatten bool, projectRoot string, include, exclude []string) (*ExtraCollectResult, error) {
|
||||
result := &ExtraCollectResult{}
|
||||
// Without file links the collected files stay in place, as copies.
|
||||
if !canCreateFileLink() {
|
||||
@@ -799,6 +812,7 @@ func CollectExtraFiles(sourceDir, targetDir, mode string, dryRun, force, flatten
|
||||
// Source paths claimed this run: with flatten, two target files can share
|
||||
// a basename, and the second must not overwrite the first.
|
||||
claimed := make(map[string]bool)
|
||||
filter := newExtraFilter(include, exclude)
|
||||
|
||||
err := filepath.Walk(targetDir, func(path string, info os.FileInfo, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
@@ -836,6 +850,12 @@ func CollectExtraFiles(sourceDir, targetDir, mode string, dryRun, force, flatten
|
||||
if flatten {
|
||||
destRel = filepath.Base(rel)
|
||||
}
|
||||
// A file the target's filters leave out would be pruned again by the
|
||||
// next sync, so it stays where it is.
|
||||
if !filter.keeps(destRel) {
|
||||
result.Skipped++
|
||||
return nil
|
||||
}
|
||||
destPath := filepath.Join(sourceDir, destRel)
|
||||
if claimed[destPath] {
|
||||
result.Errors = append(result.Errors, fmt.Sprintf("skipped %s: %s already collected from another file", rel, destRel))
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package sync
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"skillshare/internal/config"
|
||||
"skillshare/internal/skillignore"
|
||||
)
|
||||
|
||||
// extraFilter decides which source files (paths relative to the extra's
|
||||
// source) a target syncs. include and exclude use .gitignore syntax: a pattern
|
||||
// without "/" matches at any depth and "dir/" covers a folder.
|
||||
type extraFilter struct{ inc, exc *skillignore.Matcher }
|
||||
|
||||
func newExtraFilter(include, exclude []string) extraFilter {
|
||||
return extraFilter{skillignore.Compile(include), skillignore.Compile(exclude)}
|
||||
}
|
||||
|
||||
func (f extraFilter) included(rel string) bool {
|
||||
return !f.inc.HasRules() || f.inc.Match(rel, false)
|
||||
}
|
||||
|
||||
func (f extraFilter) keeps(rel string) bool {
|
||||
return f.included(rel) && !f.exc.Match(rel, false)
|
||||
}
|
||||
|
||||
// FilterExtraFiles keeps the source files that pass include and exclude.
|
||||
func FilterExtraFiles(files, include, exclude []string) []string {
|
||||
if len(include) == 0 && len(exclude) == 0 {
|
||||
return files
|
||||
}
|
||||
f := newExtraFilter(include, exclude)
|
||||
var kept []string
|
||||
for _, rel := range files {
|
||||
if f.keeps(rel) {
|
||||
kept = append(kept, rel)
|
||||
}
|
||||
}
|
||||
return kept
|
||||
}
|
||||
|
||||
// UnmatchedIncludes returns the include patterns that select no file at all.
|
||||
func UnmatchedIncludes(files, include []string) []string {
|
||||
var unmatched []string
|
||||
for _, p := range include {
|
||||
m := skillignore.Compile([]string{p})
|
||||
if !m.HasRules() || strings.HasPrefix(strings.TrimSpace(p), "!") {
|
||||
continue // blank, comment, or a negation that only narrows earlier rules
|
||||
}
|
||||
if !matchesAnyFile(m, files) {
|
||||
unmatched = append(unmatched, p)
|
||||
}
|
||||
}
|
||||
return unmatched
|
||||
}
|
||||
|
||||
// ExtraTargetFiles narrows an extra's source files to the ones target syncs.
|
||||
func ExtraTargetFiles(files []string, target config.ExtraTargetConfig) []string {
|
||||
return FilterExtraFiles(files, target.Include, target.Exclude)
|
||||
}
|
||||
|
||||
// ExtraFilterEntry is one source file in a filter preview. Status is
|
||||
// "synced", "not_included", or "excluded"; Reason names the exclude pattern
|
||||
// that dropped an excluded file.
|
||||
type ExtraFilterEntry struct {
|
||||
File string `json:"file"`
|
||||
Status string `json:"status"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
// PreviewExtraFilter reports what include and exclude do to each source file.
|
||||
func PreviewExtraFilter(files, include, exclude []string) []ExtraFilterEntry {
|
||||
f := newExtraFilter(include, exclude)
|
||||
excludes := make([]*skillignore.Matcher, len(exclude))
|
||||
for i, p := range exclude {
|
||||
excludes[i] = skillignore.Compile([]string{p})
|
||||
}
|
||||
entries := make([]ExtraFilterEntry, 0, len(files))
|
||||
for _, rel := range files {
|
||||
e := ExtraFilterEntry{File: rel, Status: "synced"}
|
||||
switch {
|
||||
case !f.included(rel):
|
||||
e.Status = "not_included"
|
||||
case !f.keeps(rel):
|
||||
e.Status = "excluded"
|
||||
for i, m := range excludes {
|
||||
if m.Match(rel, false) {
|
||||
e.Reason = exclude[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
entries = append(entries, e)
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
// UnmatchedIncludeWarning is the sync warning for an include pattern that
|
||||
// selects no file.
|
||||
func UnmatchedIncludeWarning(pattern string) string {
|
||||
return fmt.Sprintf("include %q matches no file", pattern)
|
||||
}
|
||||
|
||||
func matchesAnyFile(m *skillignore.Matcher, files []string) bool {
|
||||
for _, rel := range files {
|
||||
if m.Match(rel, false) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// discoverExtraTargetFiles lists the source files one target syncs, with a
|
||||
// warning for each include pattern that selects nothing.
|
||||
func discoverExtraTargetFiles(sourcePath string, include, exclude []string) ([]string, []string, error) {
|
||||
files, err := DiscoverExtraFiles(sourcePath)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
kept := FilterExtraFiles(files, include, exclude)
|
||||
unmatched := UnmatchedIncludes(files, include)
|
||||
warnings := make([]string, 0, len(unmatched))
|
||||
for _, p := range unmatched {
|
||||
warnings = append(warnings, UnmatchedIncludeWarning(p))
|
||||
}
|
||||
return kept, warnings, nil
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package sync
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/config"
|
||||
)
|
||||
|
||||
var filterTestFiles = []string{"draft.md", "guides/draft-2.md", "guides/setup.md", "images/logo.png", "index.md"}
|
||||
|
||||
func TestFilterExtraFiles_GitignoreSemantics(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
include, exclude []string
|
||||
want []string
|
||||
}{
|
||||
{"no filters keeps all", nil, nil, filterTestFiles},
|
||||
{"bare name matches at any depth", []string{"setup.md"}, nil, []string{"guides/setup.md"}},
|
||||
{"glob without slash matches at any depth", nil, []string{"draft*"}, []string{"guides/setup.md", "images/logo.png", "index.md"}},
|
||||
{"trailing slash covers a folder", nil, []string{"images/"}, []string{"draft.md", "guides/draft-2.md", "guides/setup.md", "index.md"}},
|
||||
{"double star matches nested files", []string{"**/*.png"}, nil, []string{"images/logo.png"}},
|
||||
{"exclude applies after include", []string{"guides/"}, []string{"draft*"}, []string{"guides/setup.md"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := FilterExtraFiles(filterTestFiles, tt.include, tt.exclude)
|
||||
if !slices.Equal(got, tt.want) {
|
||||
t.Errorf("got %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmatchedIncludes_ReportsPatternWithNoFile(t *testing.T) {
|
||||
unmatched := UnmatchedIncludes(filterTestFiles, []string{"index.md", "index.mdd", "!index.md"})
|
||||
|
||||
if !slices.Equal(unmatched, []string{"index.mdd"}) {
|
||||
t.Errorf("unmatched = %v, want [index.mdd]", unmatched)
|
||||
}
|
||||
}
|
||||
|
||||
func filterTestExtra(tgt string, target config.ExtraTargetConfig) config.ExtraConfig {
|
||||
target.Path = tgt
|
||||
return config.ExtraConfig{Name: "docs", Targets: []config.ExtraTargetConfig{target}}
|
||||
}
|
||||
|
||||
func TestRunExtraTargets_IncludeSyncsOnlyMatches(t *testing.T) {
|
||||
src, tgt := setupExtrasTest(t, map[string]string{"index.md": "i", "draft.md": "d"})
|
||||
|
||||
run := RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Include: []string{"index.md"}}), src, runTestOptions())
|
||||
|
||||
if r := run.Targets[0]; r.Err != nil || r.Result.Synced != 1 {
|
||||
t.Fatalf("expected one synced file, got %+v", r)
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(tgt, "draft.md")); !os.IsNotExist(err) {
|
||||
t.Errorf("draft.md must not be synced, lstat err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunExtraTargets_NarrowedFilterPrunesMergeLinks(t *testing.T) {
|
||||
src, tgt := setupExtrasTest(t, map[string]string{"index.md": "i", "draft.md": "d"})
|
||||
RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{}), src, runTestOptions())
|
||||
|
||||
run := RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Exclude: []string{"draft*"}}), src, runTestOptions())
|
||||
|
||||
if r := run.Targets[0]; r.Err != nil || r.Result.Pruned != 1 {
|
||||
t.Fatalf("expected the draft.md link pruned, got %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunExtraTargets_CopyKeepsFilteredOutFiles(t *testing.T) {
|
||||
src, tgt := setupExtrasTest(t, map[string]string{"index.md": "i", "draft.md": "d"})
|
||||
RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Mode: "copy"}), src, runTestOptions())
|
||||
|
||||
RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Mode: "copy", Exclude: []string{"draft*"}}), src, runTestOptions())
|
||||
|
||||
if _, err := os.Stat(filepath.Join(tgt, "draft.md")); err != nil {
|
||||
t.Errorf("copy mode must keep draft.md, stat err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunExtraTargets_WarnsUnmatchedInclude(t *testing.T) {
|
||||
src, tgt := setupExtrasTest(t, map[string]string{"index.md": "i"})
|
||||
|
||||
run := RunExtraTargets(filterTestExtra(tgt, config.ExtraTargetConfig{Include: []string{"index.mdd"}}), src, runTestOptions())
|
||||
|
||||
if r := run.Targets[0]; !slices.Contains(r.Result.Warnings, UnmatchedIncludeWarning("index.mdd")) {
|
||||
t.Errorf("expected unmatched include warning, got %v", r.Result.Warnings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectExtraFiles_SkipsFilteredOutFiles(t *testing.T) {
|
||||
src, tgt := setupExtrasTest(t, nil)
|
||||
os.WriteFile(filepath.Join(tgt, "draft.md"), []byte("d"), 0644)
|
||||
|
||||
result, err := CollectExtraFiles(src, tgt, "", false, false, false, "", nil, []string{"draft*"})
|
||||
|
||||
if err != nil || result.Collected != 0 {
|
||||
t.Fatalf("expected nothing collected, got %+v, err %v", result, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(src, "draft.md")); !os.IsNotExist(err) {
|
||||
t.Errorf("draft.md must stay out of the source, stat err = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,7 @@ func runExtraTarget(extra config.ExtraConfig, t config.ExtraTargetConfig, source
|
||||
// sync just that file to <target>/<as or file>; others sync the directory.
|
||||
func SyncExtraTarget(extra config.ExtraConfig, target config.ExtraTargetConfig, sourceDir, targetPath, mode string, dryRun, force bool, projectRoot string, spec *ExtensionSpec) (*ExtraResult, error) {
|
||||
if extra.File == "" {
|
||||
return SyncExtra(sourceDir, targetPath, mode, dryRun, force, target.Flatten, projectRoot, spec)
|
||||
return syncExtraDir(sourceDir, targetPath, mode, dryRun, force, target.Flatten, projectRoot, spec, target.Include, target.Exclude)
|
||||
}
|
||||
if spec != nil {
|
||||
return nil, fmt.Errorf("extensions are not supported for single-file extras")
|
||||
|
||||
@@ -431,7 +431,7 @@ func TestCollectExtraFiles(t *testing.T) {
|
||||
os.MkdirAll(targetDir, 0755)
|
||||
os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("# Rule 1"), 0644)
|
||||
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, false, "")
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, false, "", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CollectExtraFiles: %v", err)
|
||||
}
|
||||
@@ -466,7 +466,7 @@ func TestCollectExtraFiles_DryRun(t *testing.T) {
|
||||
os.MkdirAll(targetDir, 0755)
|
||||
os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("# Rule 1"), 0644)
|
||||
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", true, false, false, "")
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", true, false, false, "", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CollectExtraFiles dry run: %v", err)
|
||||
}
|
||||
@@ -500,7 +500,7 @@ func TestCollectExtraFiles_SkipsExisting(t *testing.T) {
|
||||
os.WriteFile(filepath.Join(sourceDir, "rule1.md"), []byte("source version"), 0644)
|
||||
os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("target version"), 0644)
|
||||
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, false, "")
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, false, "", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CollectExtraFiles: %v", err)
|
||||
}
|
||||
@@ -521,7 +521,7 @@ func TestCollectExtraFiles_ForceOverwritesExisting(t *testing.T) {
|
||||
os.WriteFile(filepath.Join(sourceDir, "rule1.md"), []byte("source version"), 0644)
|
||||
os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("target version"), 0644)
|
||||
|
||||
if _, err := CollectExtraFiles(sourceDir, targetDir, "", false, true, false, ""); err != nil {
|
||||
if _, err := CollectExtraFiles(sourceDir, targetDir, "", false, true, false, "", nil, nil); err != nil {
|
||||
t.Fatalf("CollectExtraFiles: %v", err)
|
||||
}
|
||||
|
||||
@@ -539,7 +539,7 @@ func TestCollectExtraFiles_ForceSkipsIdentical(t *testing.T) {
|
||||
os.WriteFile(filepath.Join(sourceDir, "rule1.md"), []byte("same"), 0644)
|
||||
os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("same"), 0644)
|
||||
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "copy", false, true, false, "")
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "copy", false, true, false, "", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CollectExtraFiles: %v", err)
|
||||
}
|
||||
@@ -555,7 +555,7 @@ func TestCollectExtraFiles_CopyModeKeepsTargetFile(t *testing.T) {
|
||||
os.MkdirAll(targetDir, 0755)
|
||||
os.WriteFile(filepath.Join(targetDir, "rule1.md"), []byte("# Rule 1"), 0644)
|
||||
|
||||
if _, err := CollectExtraFiles(sourceDir, targetDir, "copy", false, false, false, ""); err != nil {
|
||||
if _, err := CollectExtraFiles(sourceDir, targetDir, "copy", false, false, false, "", nil, nil); err != nil {
|
||||
t.Fatalf("CollectExtraFiles: %v", err)
|
||||
}
|
||||
|
||||
@@ -799,7 +799,7 @@ func TestCollectExtraFiles_Flatten(t *testing.T) {
|
||||
// New local file in target (not from source)
|
||||
os.WriteFile(filepath.Join(targetDir, "new-agent.md"), []byte("# New Agent"), 0644)
|
||||
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, true, "")
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, true, "", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CollectExtraFiles: %v", err)
|
||||
}
|
||||
@@ -830,7 +830,7 @@ func TestCollectExtraFiles_FlattenSkipsExisting(t *testing.T) {
|
||||
os.WriteFile(filepath.Join(sourceDir, "conflict.md"), []byte("source version"), 0644)
|
||||
os.WriteFile(filepath.Join(targetDir, "conflict.md"), []byte("target version"), 0644)
|
||||
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, true, "")
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, false, true, "", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CollectExtraFiles: %v", err)
|
||||
}
|
||||
@@ -851,7 +851,7 @@ func TestCollectExtraFiles_ForceFlattenCollisionKeepsFirst(t *testing.T) {
|
||||
os.WriteFile(filepath.Join(targetDir, "a", "x.md"), []byte("A"), 0644)
|
||||
os.WriteFile(filepath.Join(targetDir, "b", "x.md"), []byte("B"), 0644)
|
||||
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, true, true, "")
|
||||
result, err := CollectExtraFiles(sourceDir, targetDir, "", false, true, true, "", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CollectExtraFiles: %v", err)
|
||||
}
|
||||
|
||||
@@ -520,6 +520,18 @@
|
||||
"description": "When true, files from subdirectories are synced directly into the target root instead of preserving directory structure.",
|
||||
"default": false
|
||||
},
|
||||
"include": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "Sync only source files that match one of these .gitignore-style patterns (path inside the source). A pattern without '/' matches at any depth; 'dir/' covers a folder. Not allowed with symlink mode or a single-file extra.",
|
||||
"examples": [["index.md", "learning.md"], ["guides/", "**/*.md"]]
|
||||
},
|
||||
"exclude": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "Skip source files that match one of these .gitignore-style patterns. Applied after include. Not allowed with symlink mode or a single-file extra.",
|
||||
"examples": [["draft*", "images/"]]
|
||||
},
|
||||
"extension": {
|
||||
"type": "string",
|
||||
"description": "Transform each file through an extension before writing it to this target (copy mode only). A bare name resolves under the extensions directory; a path (containing a separator or starting with '.') is used directly.",
|
||||
|
||||
@@ -455,6 +455,18 @@
|
||||
"description": "When true, files from subdirectories are synced directly into the target root instead of preserving directory structure.",
|
||||
"default": false
|
||||
},
|
||||
"include": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "Sync only source files that match one of these .gitignore-style patterns (path inside the source). A pattern without '/' matches at any depth; 'dir/' covers a folder. Not allowed with symlink mode or a single-file extra.",
|
||||
"examples": [["index.md", "learning.md"], ["guides/", "**/*.md"]]
|
||||
},
|
||||
"exclude": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "Skip source files that match one of these .gitignore-style patterns. Applied after include. Not allowed with symlink mode or a single-file extra.",
|
||||
"examples": [["draft*", "images/"]]
|
||||
},
|
||||
"extension": {
|
||||
"type": "string",
|
||||
"description": "Transform each file through an extension before writing it to this target (copy mode only). A bare name resolves under the extensions directory; a path (containing a separator or starting with '.') is used directly.",
|
||||
|
||||
@@ -37,6 +37,7 @@ skillshare extras init rules --no-tui ... # Skip prompts
|
||||
| `--as <filename>` | File name at every target (default: `--file` name); requires `--file` |
|
||||
| `--mode <mode>` | Sync mode: `merge` (default), `copy`, `symlink`; `import`, `prepend` or `append` only with `--file` |
|
||||
| `--flatten` | Sync subdirectory files into the target root; not with `symlink` or `--file` |
|
||||
| `--include` / `--exclude <pattern>` | Sync only / skip matching files (`.gitignore` syntax on the path inside the source; repeatable); not with `symlink` or `--file` |
|
||||
| `--no-tui` | Skip interactive prompts |
|
||||
| `-p` / `-g` | Force project / global mode |
|
||||
|
||||
@@ -52,6 +53,16 @@ skillshare extras personal --add-target ~/.claude --as CLAUDE.md --mode import
|
||||
`--as` sets the target filename for a single-file extra; it defaults to `file`.
|
||||
Run `skillshare sync extras` after adding the target.
|
||||
|
||||
```bash
|
||||
skillshare extras docs --target ~/.claude/docs --add-include index.md
|
||||
skillshare extras docs --target ~/.cursor/docs --add-exclude "draft*" --add-exclude images/
|
||||
```
|
||||
|
||||
`--add-include`, `--add-exclude`, `--remove-include` and `--remove-exclude` change one
|
||||
target's file filters. A pattern without `/` matches at any depth; `dir/` covers a folder.
|
||||
The next sync removes links to files that stop matching in `merge` mode; `copy` mode leaves
|
||||
copied files in place. `sync` warns when an include matches no file.
|
||||
|
||||
## extras list
|
||||
|
||||
Show all configured extras with sync status per target.
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//go:build !online
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"skillshare/internal/testutil"
|
||||
)
|
||||
|
||||
// setupDocsExtra writes a docs extra with index.md and draft.md synced to one
|
||||
// target, with extraTarget appended to the target entry, and returns the
|
||||
// target directory.
|
||||
func setupDocsExtra(t *testing.T, sb *testutil.Sandbox, extraTarget string) string {
|
||||
t.Helper()
|
||||
sb.CreateSkill("placeholder", map[string]string{"SKILL.md": "# Placeholder"})
|
||||
claude := sb.CreateTarget("claude")
|
||||
|
||||
docsSource := filepath.Join(filepath.Dir(sb.SourcePath), "extras", "docs")
|
||||
os.MkdirAll(docsSource, 0755)
|
||||
os.WriteFile(filepath.Join(docsSource, "index.md"), []byte("# Index"), 0644)
|
||||
os.WriteFile(filepath.Join(docsSource, "draft.md"), []byte("# Draft"), 0644)
|
||||
|
||||
docsTarget := filepath.Join(sb.Home, ".claude", "docs")
|
||||
os.MkdirAll(docsTarget, 0755)
|
||||
|
||||
sb.WriteConfig(`source: ` + sb.SourcePath + `
|
||||
targets:
|
||||
claude:
|
||||
path: ` + claude + `
|
||||
extras:
|
||||
- name: docs
|
||||
targets:
|
||||
- path: ` + docsTarget + extraTarget + `
|
||||
`)
|
||||
return docsTarget
|
||||
}
|
||||
|
||||
func TestExtras_AddExclude_NextSyncPrunesExcludedLink(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
docsTarget := setupDocsExtra(t, sb, "")
|
||||
sb.RunCLI("sync", "extras").AssertSuccess(t)
|
||||
|
||||
sb.RunCLI("extras", "docs", "--add-exclude", "draft*", "-g").AssertSuccess(t)
|
||||
sb.RunCLI("sync", "extras").AssertSuccess(t)
|
||||
|
||||
if _, err := os.Lstat(filepath.Join(docsTarget, "draft.md")); !os.IsNotExist(err) {
|
||||
t.Errorf("draft.md link should be pruned, lstat err = %v", err)
|
||||
}
|
||||
if !sb.IsSymlink(filepath.Join(docsTarget, "index.md")) {
|
||||
t.Error("index.md should stay linked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtras_Init_IncludeWritesTargetFilter(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
setupDocsExtra(t, sb, "")
|
||||
notesTarget := filepath.Join(sb.Home, ".claude", "notes")
|
||||
|
||||
sb.RunCLI("extras", "init", "notes", "--target", notesTarget, "--include", "index.md", "-g").AssertSuccess(t)
|
||||
|
||||
if cfg := sb.ReadFile(sb.ConfigPath); !strings.Contains(cfg, "include:\n - index.md") {
|
||||
t.Errorf("expected include in config, got:\n%s", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtras_Mode_SymlinkRejectedWithFilters(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
setupDocsExtra(t, sb, "\n include: [index.md]")
|
||||
|
||||
result := sb.RunCLI("extras", "docs", "--mode", "symlink", "-g")
|
||||
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "symlink")
|
||||
}
|
||||
|
||||
func TestSyncExtras_WarnsUnmatchedInclude(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
setupDocsExtra(t, sb, "\n include: [index.mdd]")
|
||||
|
||||
result := sb.RunCLI("sync", "extras")
|
||||
|
||||
result.AssertSuccess(t)
|
||||
result.AssertAnyOutputContains(t, `include "index.mdd" matches no file`)
|
||||
}
|
||||
|
||||
func TestExtras_FlattenWithFilterNeedsTargetOnMultiTargetExtra(t *testing.T) {
|
||||
sb := testutil.NewSandbox(t)
|
||||
defer sb.Cleanup()
|
||||
setupDocsExtra(t, sb, "\n - path: "+filepath.Join(sb.Home, ".cursor", "docs"))
|
||||
|
||||
result := sb.RunCLI("extras", "docs", "--flatten", "--add-exclude", "draft*", "-g")
|
||||
|
||||
result.AssertFailure(t)
|
||||
result.AssertAnyOutputContains(t, "--target")
|
||||
}
|
||||
+18
-1
@@ -1,5 +1,5 @@
|
||||
import { apiFetch } from './http';
|
||||
import type { ExtensionInfo, Extra, ExtraDiffResult, ExtrasSyncResult } from './types/extras';
|
||||
import type { ExtensionInfo, Extra, ExtraDiffResult, ExtraEditResult, ExtraFilterEntry, ExtrasSyncResult } from './types/extras';
|
||||
|
||||
export const extrasApi = {
|
||||
listExtras: () => apiFetch<{ extras: Extra[] }>('/extras'),
|
||||
@@ -53,6 +53,23 @@ export const extrasApi = {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(target),
|
||||
}),
|
||||
previewExtraFilter: (name: string, include: string[], exclude: string[]) =>
|
||||
apiFetch<{ files: ExtraFilterEntry[]; unmatched: string[] | null }>(`/extras/${encodeURIComponent(name)}/preview`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ include, exclude }),
|
||||
}),
|
||||
// A new path or file name also clears the old place and syncs.
|
||||
editExtraTarget: (name: string, path: string, target: { path: string; mode: string; flatten: boolean; extension: string; as: string; include: string[]; exclude: string[] }) =>
|
||||
apiFetch<ExtraEditResult>(`/extras/${encodeURIComponent(name)}/targets`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ path, target }),
|
||||
}),
|
||||
// source: omitted = unchanged, '' = the default folder; a new source relinks every target.
|
||||
editExtra: (name: string, data: { name?: string; source?: string }) =>
|
||||
apiFetch<ExtraEditResult>(`/extras/${encodeURIComponent(name)}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
removeExtraTarget: (name: string, path: string) =>
|
||||
apiFetch<{ success: boolean }>(`/extras/${encodeURIComponent(name)}/targets`, {
|
||||
method: 'DELETE',
|
||||
|
||||
@@ -5,6 +5,9 @@ export interface ExtraTarget {
|
||||
flatten: boolean;
|
||||
extension?: string; // transform extension name; presence implies copy mode
|
||||
as?: string; // single-file extra: target filename
|
||||
include?: string[];
|
||||
exclude?: string[];
|
||||
file_count: number; // source files this target syncs after include/exclude
|
||||
status: string; // "synced" | "drift" | "modified" | "not synced" | "no source"
|
||||
}
|
||||
|
||||
@@ -18,6 +21,19 @@ export interface Extra {
|
||||
targets: ExtraTarget[];
|
||||
}
|
||||
|
||||
export interface ExtraFilterEntry {
|
||||
file: string;
|
||||
status: 'synced' | 'not_included' | 'excluded';
|
||||
reason?: string; // the exclude pattern that dropped the file
|
||||
}
|
||||
|
||||
/** What an edit that moves files returns: the sync it ran and any old-location cleanup errors. */
|
||||
export interface ExtraEditResult {
|
||||
success: boolean;
|
||||
extras?: ExtrasSyncResult[];
|
||||
prune_errors?: string[];
|
||||
}
|
||||
|
||||
export interface ExtensionInfo {
|
||||
name: string;
|
||||
description?: string;
|
||||
|
||||
@@ -126,7 +126,8 @@ export function SkillContextMenu({
|
||||
item={item}
|
||||
expanded={expandedKey === item.key}
|
||||
onExpand={() => setExpandedKey(item.key)}
|
||||
onCollapse={() => setExpandedKey(null)}
|
||||
// A late timer from a submenu left earlier must not close the one open now
|
||||
onCollapse={() => setExpandedKey((k) => (k === item.key ? null : k))}
|
||||
onClose={onClose}
|
||||
parentMenuRef={menuRef}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
import { X } from 'lucide-react';
|
||||
import { api } from '../../api/client';
|
||||
import type { Extra, ExtraEditResult, ExtraTarget } from '../../api/client';
|
||||
import { queryKeys } from '../../lib/queryKeys';
|
||||
import { buildSyncToast, sumEntry, syncToastType } from '../../lib/extrasSyncToast';
|
||||
import { shortenHome } from '../../lib/paths';
|
||||
import { useToast } from '../Toast';
|
||||
import { useT, plural } from '../../i18n';
|
||||
import Button from '../Button';
|
||||
import DialogShell from '../DialogShell';
|
||||
import { Select } from '../Input';
|
||||
import FilterSection from '../targets/FilterSection';
|
||||
|
||||
/** <folder>/<file>, for a single-file extra's source or target file, with the separator the folder already uses (a backslash on Windows). */
|
||||
export const joinFile = (dir: string, file: string) => {
|
||||
const sep = dir.lastIndexOf('\\') > dir.lastIndexOf('/') ? '\\' : '/';
|
||||
return `${dir.replace(/[\\/]+$/, '')}${sep}${file}`;
|
||||
};
|
||||
|
||||
export const MODES = ['merge', 'copy', 'symlink'] as const;
|
||||
// A single file can't be a directory symlink; import writes an @ line instead.
|
||||
export const FILE_MODES = ['merge', 'copy', 'import', 'prepend', 'append'] as const;
|
||||
|
||||
const Mono = ({ children }: { children: ReactNode }) => <span className="font-mono">{children}</span>;
|
||||
|
||||
/** Reports a save: the sync it ran when files moved, else a plain saved toast. */
|
||||
function useSaveToast() {
|
||||
const { toast } = useToast();
|
||||
const t = useT();
|
||||
return (name: string, res: ExtraEditResult) => {
|
||||
if (res.prune_errors?.length) toast(t('extras.edit.pruneFailed', { error: res.prune_errors.join('; ') }), 'error');
|
||||
if (!res.extras) {
|
||||
toast(t('extras.edit.saved', { name }), 'success');
|
||||
return;
|
||||
}
|
||||
const totals = sumEntry(res.extras.find((e) => e.name === name));
|
||||
toast(buildSyncToast(t('extras.toast.syncOne', { name }), t('extras.toast.syncOneFailed', { name }), totals, false, t), syncToastType(totals));
|
||||
};
|
||||
}
|
||||
|
||||
function DialogFrame({ title, subtitle, saving, canSave, saveLabel, onClose, onSave, children }: {
|
||||
title: string;
|
||||
subtitle: ReactNode;
|
||||
saving: boolean;
|
||||
canSave: boolean;
|
||||
saveLabel: string;
|
||||
onClose: () => void;
|
||||
onSave: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const t = useT();
|
||||
return (
|
||||
<DialogShell open onClose={onClose} padding="none" preventClose={saving} ariaLabel={title} className="!max-w-[720px]">
|
||||
<div className="dh">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<h2 className="ss-h2">{title}</h2>
|
||||
<p className="truncate text-[13px] text-ink-2">{subtitle}</p>
|
||||
</div>
|
||||
<button type="button" className="ss-ib" aria-label={t('common.close')} onClick={onClose} disabled={saving}><X size={16} /></button>
|
||||
</div>
|
||||
<div className="db">{children}</div>
|
||||
<div className="df">
|
||||
<span className="flex-1" />
|
||||
<Button variant="ghost" onClick={onClose} disabled={saving}>{t('extras.cancel')}</Button>
|
||||
<Button variant="primary" loading={saving} disabled={!canSave} onClick={onSave}>{saveLabel}</Button>
|
||||
</div>
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
|
||||
/** Where a target syncs, how, and which files: everything Add target sets, plus the file filters. */
|
||||
export function EditTargetDialog({ extra, target, extensions, markFor, onClose, onSaved }: {
|
||||
extra: Extra;
|
||||
target: ExtraTarget;
|
||||
extensions: string[];
|
||||
markFor: (path: string) => ReactNode;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const t = useT();
|
||||
const { toast } = useToast();
|
||||
const report = useSaveToast();
|
||||
const single = Boolean(extra.file);
|
||||
const [path, setPath] = useState(target.path);
|
||||
const [mode, setMode] = useState(target.mode);
|
||||
const [flatten, setFlatten] = useState(target.flatten);
|
||||
const [extension, setExtension] = useState(target.extension ?? '');
|
||||
const [as, setAs] = useState(target.as ?? '');
|
||||
const [filters, setFilters] = useState({ include: target.include ?? [], exclude: target.exclude ?? [] });
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const filtered = !single && mode !== 'symlink';
|
||||
const preview = useQuery({
|
||||
queryKey: queryKeys.extrasPreview(extra.name, filters.include, filters.exclude),
|
||||
queryFn: () => api.previewExtraFilter(extra.name, filters.include, filters.exclude),
|
||||
placeholderData: keepPreviousData,
|
||||
enabled: filtered && extra.source_exists,
|
||||
});
|
||||
const files = preview.data?.files ?? [];
|
||||
const entries = files.map((f) => ({ skill: f.file, target: path, status: f.status, reason: f.reason ?? '' }));
|
||||
const dropped = files.filter((f) => f.status !== 'synced').length;
|
||||
const unmatched = preview.data?.unmatched ?? [];
|
||||
|
||||
const trimmed = path.trim();
|
||||
const moved = trimmed !== target.path || as.trim() !== (target.as ?? '');
|
||||
const patterns = (target.include?.length ?? 0) + (target.exclude?.length ?? 0);
|
||||
const flat = flatten && mode !== 'symlink';
|
||||
const filtersChanged = filters.include.join('\n') !== (target.include ?? []).join('\n') || filters.exclude.join('\n') !== (target.exclude ?? []).join('\n');
|
||||
const canSave = trimmed !== '' && !saving;
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await api.editExtraTarget(extra.name, target.path, {
|
||||
path: trimmed, mode: extension ? 'copy' : mode, flatten: flat, extension, as: as.trim(),
|
||||
include: filtered ? filters.include : [], exclude: filtered ? filters.exclude : [],
|
||||
});
|
||||
report(extra.name, res);
|
||||
onSaved();
|
||||
} catch (err) {
|
||||
toast((err as Error).message, 'error');
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const was = (value: string) => <span className="hp font-mono">{t('extras.edit.was', { value: shortenHome(value) })}</span>;
|
||||
|
||||
return (
|
||||
<DialogFrame
|
||||
title={t('extras.edit.targetTitle')}
|
||||
subtitle={<><Mono>{extra.name}</Mono> → <Mono>{shortenHome(target.path)}</Mono></>}
|
||||
saving={saving}
|
||||
canSave={canSave}
|
||||
saveLabel={t(moved ? 'extras.edit.saveAndSync' : 'common.save')}
|
||||
onClose={onClose}
|
||||
onSave={() => void save()}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="mt-[27px]">{markFor(trimmed)}</span>
|
||||
<div className="ss-fld min-w-0 flex-1">
|
||||
<label htmlFor="edit-target-path">{t('extras.modal.colPath')}</label>
|
||||
<span className="ss-inp"><input id="edit-target-path" className="font-mono" value={path} onChange={(e) => setPath(e.target.value)} disabled={saving} /></span>
|
||||
{trimmed !== target.path && was(target.path)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-start gap-3">
|
||||
{single ? (
|
||||
<div className="ss-fld min-w-0 flex-1">
|
||||
<label htmlFor="edit-target-as">{t('extras.modal.fileName')}</label>
|
||||
<span className="ss-inp"><input id="edit-target-as" className="font-mono" value={as} placeholder={extra.file} onChange={(e) => setAs(e.target.value)} disabled={saving} /></span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="ss-fld min-w-0 flex-1">
|
||||
<span className="text-[13px] font-semibold">{t('extras.modal.colExtension')}</span>
|
||||
<Select
|
||||
value={extension}
|
||||
onChange={(v) => { setExtension(v); if (v) setMode('copy'); }}
|
||||
options={[{ value: '', label: t('extras.noExtension') }, ...extensions.map((e) => ({ value: e, label: e }))]}
|
||||
disabled={saving || mode === 'symlink' || (extensions.length === 0 && !extension)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="ss-fld w-[180px]">
|
||||
<span className="text-[13px] font-semibold">{t('extras.modal.colMode')}</span>
|
||||
<Select
|
||||
value={extension ? 'copy' : mode}
|
||||
onChange={setMode}
|
||||
options={(single ? FILE_MODES : MODES).map((m) => ({ value: m, label: m, description: t(single ? `extras.fileModeDescription.${m}` : `extras.modeDescription.${m}`) }))}
|
||||
disabled={saving || Boolean(extension)}
|
||||
/>
|
||||
</div>
|
||||
{!single && (
|
||||
<div className="ss-fld w-[110px]">
|
||||
<span className="text-[13px] font-semibold">{t('extras.flatten')}</span>
|
||||
<span className="flex h-9 items-center gap-2">
|
||||
<button type="button" role="switch" aria-checked={flat} aria-label={t('extras.flatten')} className={`ss-sw ${flat ? 'on' : ''} disabled:opacity-50`} onClick={() => setFlatten(!flatten)} disabled={saving || mode === 'symlink'}><i /></button>
|
||||
<span className="text-xs text-ink-2">{t(flat ? 'extras.flattenOn' : 'extras.flattenOff')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{moved && (
|
||||
<div className="ss-note inf">
|
||||
<span className="flex-1">{t(target.mode === 'copy' ? 'extras.edit.moveCopyNote' : 'extras.edit.moveNote', { from: shortenHome(target.path), to: shortenHome(trimmed) })}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!single && (
|
||||
<div className="mt-2 flex flex-col gap-4 border-t border-line pt-5">
|
||||
<h3 className="text-[14px] font-semibold">{t('extras.edit.files')}</h3>
|
||||
{mode === 'symlink' ? (
|
||||
<div className="ss-note inf">
|
||||
<span className="flex-1">{patterns > 0 ? t(plural('extras.edit.symlinkClears', patterns), { count: patterns }) : t('targetDetail.symlinkNoFilters')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<FilterSection
|
||||
kind="file"
|
||||
mode={mode}
|
||||
name={shortenHome(trimmed)}
|
||||
include={filters.include}
|
||||
exclude={filters.exclude}
|
||||
onChange={setFilters}
|
||||
entries={entries}
|
||||
loaded={preview.isSuccess}
|
||||
loading={preview.isPending && preview.fetchStatus !== 'idle'}
|
||||
error={preview.error}
|
||||
disabled={saving}
|
||||
includeWarning={unmatched.length > 0 ? (
|
||||
<div className="ss-note warn">
|
||||
<span className="flex-1">{unmatched.map((p) => t('extras.edit.unmatched', { pattern: p, name: extra.name })).join(' ')}</span>
|
||||
</div>
|
||||
) : undefined}
|
||||
/>
|
||||
{dropped > 0 && filtersChanged && !moved && (
|
||||
<div className="ss-note">
|
||||
<span className="flex-1">{mode === 'copy'
|
||||
? t('extras.edit.copyNote', { path: shortenHome(target.path) })
|
||||
: t(plural('extras.edit.pruneNote', dropped), { count: dropped, name: extra.name })}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogFrame>
|
||||
);
|
||||
}
|
||||
|
||||
/** Name and source folder of an extra. A new folder relinks every target; a new name changes only the config. */
|
||||
export function EditExtraDialog({ extra, sharedDir, onClose, onSaved }: {
|
||||
extra: Extra;
|
||||
sharedDir: string;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const t = useT();
|
||||
const { toast } = useToast();
|
||||
const report = useSaveToast();
|
||||
const [name, setName] = useState(extra.name);
|
||||
const wasCustom = extra.source_type === 'per-extra';
|
||||
const [custom, setCustom] = useState(wasCustom);
|
||||
const [source, setSource] = useState(wasCustom ? shortenHome(extra.source_dir) : '');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const trimmedName = name.trim();
|
||||
const trimmedSource = source.trim();
|
||||
const renamed = trimmedName !== extra.name;
|
||||
// Back to the shared folder means the folder named after the extra there.
|
||||
const sourceChanged = custom ? trimmedSource !== '' && trimmedSource !== shortenHome(extra.source_dir) : wasCustom;
|
||||
const canSave = trimmedName !== '' && (renamed || sourceChanged) && !(custom && trimmedSource === '') && !saving;
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await api.editExtra(extra.name, {
|
||||
...(renamed && { name: trimmedName }),
|
||||
...(sourceChanged && { source: custom ? trimmedSource : '' }),
|
||||
});
|
||||
report(trimmedName, res);
|
||||
onSaved();
|
||||
} catch (err) {
|
||||
toast((err as Error).message, 'error');
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const sharedPath = joinFile(shortenHome(sharedDir), wasCustom ? trimmedName || '…' : extra.name);
|
||||
const newPath = custom ? trimmedSource : sharedPath;
|
||||
|
||||
return (
|
||||
<DialogFrame
|
||||
title={t('extras.edit.extraTitle')}
|
||||
subtitle={<Mono>{shortenHome(extra.file ? joinFile(extra.source_dir, extra.file) : extra.source_dir)}</Mono>}
|
||||
saving={saving}
|
||||
canSave={canSave}
|
||||
saveLabel={t(sourceChanged ? 'extras.edit.saveAndSync' : 'common.save')}
|
||||
onClose={onClose}
|
||||
onSave={() => void save()}
|
||||
>
|
||||
<div className="ss-fld">
|
||||
<label htmlFor="edit-extra-name">{t('extras.modal.name')}</label>
|
||||
<span className="ss-inp"><input id="edit-extra-name" className="font-mono" value={name} onChange={(e) => setName(e.target.value)} disabled={saving} /></span>
|
||||
{renamed && <span className="hp font-mono">{t('extras.edit.was', { value: extra.name })}</span>}
|
||||
</div>
|
||||
<div className="ss-fld">
|
||||
<span className="text-[13px] font-semibold">{t('extras.modal.source')}</span>
|
||||
<Select
|
||||
value={custom ? 'custom' : 'shared'}
|
||||
onChange={(v) => setCustom(v === 'custom')}
|
||||
options={[
|
||||
{ value: 'shared', label: t('extras.sourceType.shared') },
|
||||
{ value: 'custom', label: t('extras.sourceType.custom') },
|
||||
]}
|
||||
disabled={saving}
|
||||
/>
|
||||
{custom ? (
|
||||
<span className="ss-inp">
|
||||
<input className="font-mono" value={source} onChange={(e) => setSource(e.target.value)} placeholder={t('extras.modal.sourcePathPlaceholder')} aria-label={t('extras.sourceType.custom')} disabled={saving} />
|
||||
</span>
|
||||
) : (
|
||||
<span className="hp truncate font-mono">{sharedPath}</span>
|
||||
)}
|
||||
{sourceChanged && <span className="hp font-mono">{t('extras.edit.was', { value: shortenHome(extra.source_dir) })}</span>}
|
||||
</div>
|
||||
{sourceChanged ? (
|
||||
<div className="ss-note inf"><span className="flex-1">{t('extras.edit.relinkNote', { path: newPath })}</span></div>
|
||||
) : renamed && (
|
||||
<div className="ss-note"><span className="flex-1">{t('extras.edit.renameNote', { path: shortenHome(extra.source_dir) })}</span></div>
|
||||
)}
|
||||
</DialogFrame>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Fragment, useState } from 'react';
|
||||
import { Fragment, useState, type ReactNode } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react';
|
||||
import type { SyncMatrixEntry } from '../../api/client';
|
||||
@@ -8,7 +8,7 @@ import { useI18n, useT, plural } from '../../i18n';
|
||||
import PatternInput from './PatternInput';
|
||||
import { joinList, patternName, togglePatterns } from './targetView';
|
||||
|
||||
type Kind = 'skill' | 'agent';
|
||||
type Kind = 'skill' | 'agent' | 'file';
|
||||
const MODES = ['merge', 'copy', 'symlink'] as const;
|
||||
// Sentences that end in a full-width stop run on without a space.
|
||||
const CJK_STOP = /[。!?]$/;
|
||||
@@ -31,13 +31,15 @@ interface Props {
|
||||
alsoReadBy?: string[];
|
||||
/** Targets with skills on whose folder this tool also reads, so it sees their skills twice */
|
||||
readsFrom?: string[];
|
||||
/** Shown in place of the include hint, such as an include that matches nothing */
|
||||
includeWarning?: ReactNode;
|
||||
}
|
||||
|
||||
/** Include and exclude patterns with a live preview; a click on a preview row edits them. */
|
||||
export default function FilterSection({ kind, mode, name, include, exclude, onChange, entries, loaded, loading, error, disabled, alsoReadBy = [], readsFrom = [] }: Props) {
|
||||
export default function FilterSection({ kind, mode, name, include, exclude, onChange, entries, loaded, loading, error, disabled, alsoReadBy = [], readsFrom = [], includeWarning }: Props) {
|
||||
const { t, locale } = useI18n();
|
||||
const [help, setHelp] = useState(false);
|
||||
const agent = kind === 'agent';
|
||||
const files = kind === 'file';
|
||||
const synced = entries.filter((e) => e.status === 'synced').length;
|
||||
|
||||
const reason = (e: SyncMatrixEntry) => {
|
||||
@@ -50,7 +52,7 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh
|
||||
}
|
||||
};
|
||||
|
||||
const baseHint = t(agent ? 'targetDetail.includeHint.agents' : 'targetDetail.includeHint.skills');
|
||||
const baseHint = t(`targetDetail.includeHint.${kind}s`);
|
||||
const includeHint = alsoReadBy.length > 0
|
||||
? baseHint + (CJK_STOP.test(baseHint) ? '' : ' ') + t('targetDetail.alsoReadBy.filterHint', { names: joinList(alsoReadBy, locale) })
|
||||
: baseHint;
|
||||
@@ -71,7 +73,7 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh
|
||||
<>
|
||||
{loaded && (
|
||||
<p className="text-[13.5px]">
|
||||
{t(plural(`targetDetail.summary.${agent ? 'agents' : 'skills'}`, entries.length), { synced, total: entries.length, name })}
|
||||
{t(plural(`targetDetail.summary.${kind}s`, entries.length), { synced, total: entries.length, name })}
|
||||
</p>
|
||||
)}
|
||||
{readers}
|
||||
@@ -79,12 +81,12 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh
|
||||
<div className="ss-fld">
|
||||
<label htmlFor="filter-include">{t('targetDetail.include')}</label>
|
||||
<PatternInput id="filter-include" patterns={include} onChange={(next) => onChange({ include: next, exclude })} disabled={disabled} />
|
||||
<span className="hp">{includeHint}</span>
|
||||
{includeWarning ?? <span className="hp">{includeHint}</span>}
|
||||
</div>
|
||||
<div className="ss-fld">
|
||||
<label htmlFor="filter-exclude">{t('targetDetail.exclude')}</label>
|
||||
<PatternInput id="filter-exclude" patterns={exclude} onChange={(next) => onChange({ include, exclude: next })} disabled={disabled} />
|
||||
<span className="hp">{t(agent ? 'targetDetail.excludeHint.agents' : 'targetDetail.excludeHint.skills')}</span>
|
||||
<span className="hp">{t(`targetDetail.excludeHint.${kind}s`)}</span>
|
||||
</div>
|
||||
<button type="button" className="ss-disc self-start" aria-expanded={help} onClick={() => setHelp(!help)}>
|
||||
{help ? <ChevronDown size={15} /> : <ChevronRight size={15} />}
|
||||
@@ -93,9 +95,19 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh
|
||||
{help && (
|
||||
<ul className="ml-[22px] -mt-2 flex list-disc flex-col gap-1 pl-4 text-[13px] text-ink-2">
|
||||
<li>{t('targetDetail.help.wildcards')}</li>
|
||||
<li>{t('targetDetail.help.nested')}</li>
|
||||
<li>{t('targetDetail.help.order')}</li>
|
||||
<li>{t('targetDetail.help.declared')}</li>
|
||||
{files ? (
|
||||
<>
|
||||
<li>{t('targetDetail.help.anyDepth')}</li>
|
||||
<li>{t('targetDetail.help.folders')}</li>
|
||||
<li>{t('targetDetail.help.orderFiles')}</li>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<li>{t('targetDetail.help.nested')}</li>
|
||||
<li>{t('targetDetail.help.order')}</li>
|
||||
<li>{t('targetDetail.help.declared')}</li>
|
||||
</>
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
@@ -108,11 +120,11 @@ export default function FilterSection({ kind, mode, name, include, exclude, onCh
|
||||
<div className="mt-2 flex flex-col gap-3 border-t border-line pt-5">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<h3 className="text-[14px] font-semibold">{t('targetDetail.previewCount', { count: entries.length })}</h3>
|
||||
<p className="text-[13px] text-ink-3">{t('targetDetail.clickHint')}</p>
|
||||
<p className="text-[13px] text-ink-3">{t(files ? 'targetDetail.clickHintFiles' : 'targetDetail.clickHint')}</p>
|
||||
</div>
|
||||
<div className="ss-list !shadow-none">
|
||||
<div className="ss-lh">
|
||||
<span className="flex-1">{t('resources.col.name')}</span>
|
||||
<span className="flex-1">{t(files ? 'targetDetail.colFile' : 'resources.col.name')}</span>
|
||||
<span className="w-[170px]">{t('targetDetail.becauseOf')}</span>
|
||||
<span className="w-[96px]">{t('targetDetail.result')}</span>
|
||||
</div>
|
||||
|
||||
@@ -427,6 +427,26 @@
|
||||
"extras.toast.skipped": "{skipped} übersprungen",
|
||||
"extras.toast.skippedForce": "{skipped} übersprungen (Force aktivieren, um zu überschreiben)",
|
||||
"extras.toast.syncOne": "\"{name}\" synchronisiert",
|
||||
"extras.editTarget": "Ziel bearbeiten…",
|
||||
"extras.editExtra": "Extra bearbeiten…",
|
||||
"extras.filteredFiles": "{count} / {total} Dateien",
|
||||
"extras.edit.targetTitle": "Ziel bearbeiten",
|
||||
"extras.edit.extraTitle": "Extra bearbeiten",
|
||||
"extras.edit.was": "vorher {value}",
|
||||
"extras.edit.files": "Dateien",
|
||||
"extras.edit.saveAndSync": "Speichern und synchronisieren",
|
||||
"extras.edit.saved": "„{name}“ gespeichert",
|
||||
"extras.edit.pruneFailed": "Der alte Ort konnte nicht aufgeräumt werden: {error}",
|
||||
"extras.edit.moveNote": "Beim Speichern wird dieses Ziel verschoben: skillshare entfernt, was es in {from} abgelegt hat, und synchronisiert dann nach {to}. Andere Dateien in beiden Ordnern bleiben unberührt.",
|
||||
"extras.edit.moveCopyNote": "Beim Speichern wird nach {to} synchronisiert. Dateien, die zuvor nach {from} kopiert wurden, bleiben dort, bis du sie löschst.",
|
||||
"extras.edit.pruneNote.one": "Der nächste Sync entfernt den Link zu {count} übersprungenen Datei aus diesem Ziel. Die Dateien in {name} bleiben.",
|
||||
"extras.edit.pruneNote.other": "Der nächste Sync entfernt die Links zu {count} übersprungenen Dateien aus diesem Ziel. Die Dateien in {name} bleiben.",
|
||||
"extras.edit.copyNote": "Der copy-Modus löscht zuvor kopierte Dateien nicht. Dateien, die die Filter jetzt überspringen, bleiben in {path}, bis du sie löschst.",
|
||||
"extras.edit.unmatched": "{pattern} passt auf keine Datei in {name}.",
|
||||
"extras.edit.symlinkClears.one": "Im symlink-Modus wird der ganze Ordner verlinkt, daher gelten keine Dateifilter. Beim Speichern wird {count} Muster entfernt. Wähle merge oder copy, um festzulegen, was synchronisiert wird.",
|
||||
"extras.edit.symlinkClears.other": "Im symlink-Modus wird der ganze Ordner verlinkt, daher gelten keine Dateifilter. Beim Speichern werden {count} Muster entfernt. Wähle merge oder copy, um festzulegen, was synchronisiert wird.",
|
||||
"extras.edit.renameNote": "Der Ordner bleibt unter {path}, auf der Festplatte ändert sich nichts. Nur der Name in deiner Konfiguration ändert sich.",
|
||||
"extras.edit.relinkNote": "Beim Speichern werden alle Ziele neu verlinkt: skillshare entfernt die Links in den alten Ordner und synchronisiert dann aus {path}. Bereits kopierte Dateien in Zielen bleiben. Der alte Ordner wird nicht gelöscht.",
|
||||
"extras.toast.syncOneFailed": "\"{name}\" Sync fehlgeschlagen",
|
||||
"extras.toast.syncedNFiles": "{synced} Datei(en) zu {targets} Ziel(en)",
|
||||
"extras.toast.extensionChanged": "Extension auf „{extension}“ gesetzt (Copy-Modus)",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "Verschachtelte Skills verwenden ihren flachen Namen, z. B. team__frontend__ui.",
|
||||
"targetDetail.help.order": "Einschließen wird zuerst geprüft. Ein Name, der auf Ausschließen passt, wird nie synchronisiert.",
|
||||
"targetDetail.help.declared": "Ein Skill, der in seiner SKILL.md Ziele angibt, geht nur an diese Ziele.",
|
||||
"targetDetail.addPattern": "Name oder Muster hinzufügen",
|
||||
"targetDetail.addPattern": "Name oder Muster eingeben, dann Enter",
|
||||
"targetDetail.removePattern": "{pattern} entfernen",
|
||||
"targetDetail.loadingPreview": "Vorschau wird geladen…",
|
||||
"targetDetail.previewCount": "Vorschau · {count}",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "Klicken, um diesen Namen auszuschließen",
|
||||
"targetDetail.clickInclude": "Klicken, um diesen Namen einzuschließen",
|
||||
"targetDetail.clickHint": "Klicke auf eine Zeile, um sie per Name ein- oder auszuschließen.",
|
||||
"targetDetail.summary.files.one": "{synced} von {total} Datei geht an {name}.",
|
||||
"targetDetail.summary.files.other": "{synced} von {total} Dateien gehen an {name}.",
|
||||
"targetDetail.includeHint.files": "Nur passende Dateien werden synchronisiert. Leer lassen, um alle Dateien zu synchronisieren.",
|
||||
"targetDetail.excludeHint.files": "Passende Dateien werden übersprungen. Wird nach include angewendet.",
|
||||
"targetDetail.help.anyDepth": "Ein Muster ohne / passt in jeder Tiefe: draft* überspringt auch notes/draft.md.",
|
||||
"targetDetail.help.folders": "Ein Muster mit / am Ende deckt einen Ordner ab, etwa images/. ** passt auf beliebig viele Ordner.",
|
||||
"targetDetail.help.orderFiles": "Include wird zuerst geprüft. Eine Datei, die auf exclude passt, wird nie synchronisiert.",
|
||||
"targetDetail.clickHintFiles": "Klicke auf eine Zeile, um sie per Pfad ein- oder auszuschließen.",
|
||||
"targetDetail.colFile": "Datei",
|
||||
"targetDetail.agentsFolder": "Agents-Ordner",
|
||||
"targetDetail.agentsFolderHint": "Agents sind einzelne Markdown-Dateien. Dieses Tool liest sie von hier.",
|
||||
"targetDetail.syncMode": "Sync-Modus",
|
||||
|
||||
@@ -543,6 +543,26 @@
|
||||
"extras.toast.targetRemoved": "Target \"{path}\" removed",
|
||||
"extras.toast.removed": "\"{name}\" removed",
|
||||
"extras.toast.syncOne": "\"{name}\" synced",
|
||||
"extras.editTarget": "Edit target…",
|
||||
"extras.editExtra": "Edit extra…",
|
||||
"extras.filteredFiles": "{count} / {total} files",
|
||||
"extras.edit.targetTitle": "Edit target",
|
||||
"extras.edit.extraTitle": "Edit extra",
|
||||
"extras.edit.was": "was {value}",
|
||||
"extras.edit.files": "Files",
|
||||
"extras.edit.saveAndSync": "Save and sync",
|
||||
"extras.edit.saved": "\"{name}\" saved",
|
||||
"extras.edit.pruneFailed": "Could not clean up the old location: {error}",
|
||||
"extras.edit.moveNote": "Saving moves this target: skillshare removes what it put in {from}, then syncs to {to}. Other files in either folder are not touched.",
|
||||
"extras.edit.moveCopyNote": "Saving syncs this target to {to}. Files copied to {from} before stay there until you delete them.",
|
||||
"extras.edit.pruneNote.one": "Next Sync removes the link to {count} skipped file from this target. The files in {name} stay.",
|
||||
"extras.edit.pruneNote.other": "Next Sync removes the links to {count} skipped files from this target. The files in {name} stay.",
|
||||
"extras.edit.copyNote": "copy mode does not delete files it copied before. Files the filters now skip stay in {path} until you delete them.",
|
||||
"extras.edit.unmatched": "{pattern} matches no file in {name}.",
|
||||
"extras.edit.symlinkClears.one": "In symlink mode the whole folder is linked, so file filters do not apply. Saving clears the {count} pattern. Pick merge or copy to choose what syncs.",
|
||||
"extras.edit.symlinkClears.other": "In symlink mode the whole folder is linked, so file filters do not apply. Saving clears the {count} patterns. Pick merge or copy to choose what syncs.",
|
||||
"extras.edit.renameNote": "The folder stays at {path}, so nothing on disk changes. Only the name in your config changes.",
|
||||
"extras.edit.relinkNote": "Saving relinks every target: skillshare removes the links into the old folder, then syncs from {path}. Copies already in targets stay. The old folder is not deleted.",
|
||||
"extras.toast.syncOneFailed": "\"{name}\" sync failed",
|
||||
"extras.toast.noFilesInSource": "no files in source",
|
||||
"extras.toast.syncedNFiles": "{synced} file(s) to {targets} target(s)",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "Nested skills use their flat name, like team__frontend__ui.",
|
||||
"targetDetail.help.order": "Include is checked first. A name that matches exclude is never synced.",
|
||||
"targetDetail.help.declared": "A skill that lists targets in its SKILL.md only goes to those targets.",
|
||||
"targetDetail.addPattern": "Add a name or pattern",
|
||||
"targetDetail.addPattern": "Type a name or pattern, then press Enter",
|
||||
"targetDetail.removePattern": "Remove {pattern}",
|
||||
"targetDetail.loadingPreview": "Loading preview…",
|
||||
"targetDetail.previewCount": "Preview · {count}",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "Click to exclude this name",
|
||||
"targetDetail.clickInclude": "Click to include this name",
|
||||
"targetDetail.clickHint": "Click a row to include or exclude it by name.",
|
||||
"targetDetail.summary.files.one": "{synced} of {total} file goes to {name}.",
|
||||
"targetDetail.summary.files.other": "{synced} of {total} files go to {name}.",
|
||||
"targetDetail.includeHint.files": "Only files that match are synced. Leave empty to sync every file.",
|
||||
"targetDetail.excludeHint.files": "Files that match are skipped. Applied after include.",
|
||||
"targetDetail.help.anyDepth": "A pattern without / matches at any depth: draft* also skips notes/draft.md.",
|
||||
"targetDetail.help.folders": "A pattern ending in / covers a folder, like images/. ** matches any number of folders.",
|
||||
"targetDetail.help.orderFiles": "Include is checked first. A file that matches exclude is never synced.",
|
||||
"targetDetail.clickHintFiles": "Click a row to include or exclude it by path.",
|
||||
"targetDetail.colFile": "File",
|
||||
"targetDetail.agentsFolder": "Agents folder",
|
||||
"targetDetail.agentsFolderHint": "Agents are single Markdown files. This tool reads them from here.",
|
||||
"targetDetail.syncMode": "Sync mode",
|
||||
|
||||
@@ -426,6 +426,26 @@
|
||||
"extras.toast.skipped": "{skipped} omitidos",
|
||||
"extras.toast.skippedForce": "{skipped} omitidos (activa Force para sobrescribir)",
|
||||
"extras.toast.syncOne": "\"{name}\" sincronizado",
|
||||
"extras.editTarget": "Editar destino…",
|
||||
"extras.editExtra": "Editar extra…",
|
||||
"extras.filteredFiles": "{count} / {total} archivos",
|
||||
"extras.edit.targetTitle": "Editar destino",
|
||||
"extras.edit.extraTitle": "Editar extra",
|
||||
"extras.edit.was": "antes {value}",
|
||||
"extras.edit.files": "Archivos",
|
||||
"extras.edit.saveAndSync": "Guardar y sincronizar",
|
||||
"extras.edit.saved": "\"{name}\" guardado",
|
||||
"extras.edit.pruneFailed": "No se pudo limpiar la ubicación anterior: {error}",
|
||||
"extras.edit.moveNote": "Al guardar se mueve este destino: skillshare quita lo que puso en {from} y luego sincroniza en {to}. Los demás archivos de ambas carpetas no se tocan.",
|
||||
"extras.edit.moveCopyNote": "Al guardar se sincroniza en {to}. Los archivos copiados antes en {from} se quedan ahí hasta que los borres.",
|
||||
"extras.edit.pruneNote.one": "La próxima sincronización quita de este destino el enlace a {count} archivo omitido. Los archivos de {name} se quedan.",
|
||||
"extras.edit.pruneNote.other": "La próxima sincronización quita de este destino los enlaces a {count} archivos omitidos. Los archivos de {name} se quedan.",
|
||||
"extras.edit.copyNote": "El modo copy no borra los archivos que copió antes. Los archivos que ahora omiten los filtros se quedan en {path} hasta que los borres.",
|
||||
"extras.edit.unmatched": "{pattern} no coincide con ningún archivo de {name}.",
|
||||
"extras.edit.symlinkClears.one": "En modo symlink se enlaza la carpeta completa, así que los filtros de archivos no se aplican. Al guardar se borra {count} patrón. Elige merge o copy para decidir qué se sincroniza.",
|
||||
"extras.edit.symlinkClears.other": "En modo symlink se enlaza la carpeta completa, así que los filtros de archivos no se aplican. Al guardar se borran {count} patrones. Elige merge o copy para decidir qué se sincroniza.",
|
||||
"extras.edit.renameNote": "La carpeta sigue en {path}, así que nada cambia en el disco. Solo cambia el nombre en tu configuración.",
|
||||
"extras.edit.relinkNote": "Al guardar se vuelven a enlazar todos los destinos: skillshare quita los enlaces a la carpeta anterior y luego sincroniza desde {path}. Las copias que ya están en los destinos se quedan. La carpeta anterior no se borra.",
|
||||
"extras.toast.syncOneFailed": "Error al sincronizar \"{name}\"",
|
||||
"extras.toast.syncedNFiles": "{synced} archivo(s) a {targets} destino(s)",
|
||||
"extras.toast.created": "Extra \"{name}\" creado",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "Los skills anidados usan su nombre plano, como team__frontend__ui.",
|
||||
"targetDetail.help.order": "Primero se comprueba incluir. Un nombre que coincide con excluir nunca se sincroniza.",
|
||||
"targetDetail.help.declared": "Un skill que declara destinos en su SKILL.md solo va a esos destinos.",
|
||||
"targetDetail.addPattern": "Añade un nombre o patrón",
|
||||
"targetDetail.addPattern": "Escribe un nombre o patrón y pulsa Enter",
|
||||
"targetDetail.removePattern": "Quitar {pattern}",
|
||||
"targetDetail.loadingPreview": "Cargando vista previa…",
|
||||
"targetDetail.previewCount": "Vista previa · {count}",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "Haz clic para excluir este nombre",
|
||||
"targetDetail.clickInclude": "Haz clic para incluir este nombre",
|
||||
"targetDetail.clickHint": "Haz clic en una fila para incluirla o excluirla por nombre.",
|
||||
"targetDetail.summary.files.one": "{synced} de {total} archivo va a {name}.",
|
||||
"targetDetail.summary.files.other": "{synced} de {total} archivos van a {name}.",
|
||||
"targetDetail.includeHint.files": "Solo se sincronizan los archivos que coinciden. Déjalo vacío para sincronizar todos.",
|
||||
"targetDetail.excludeHint.files": "Los archivos que coinciden se omiten. Se aplica después de include.",
|
||||
"targetDetail.help.anyDepth": "Un patrón sin / coincide a cualquier profundidad: draft* también omite notes/draft.md.",
|
||||
"targetDetail.help.folders": "Un patrón que termina en / cubre una carpeta, como images/. ** coincide con cualquier número de carpetas.",
|
||||
"targetDetail.help.orderFiles": "Include se comprueba primero. Un archivo que coincide con exclude nunca se sincroniza.",
|
||||
"targetDetail.clickHintFiles": "Haz clic en una fila para incluirla o excluirla por ruta.",
|
||||
"targetDetail.colFile": "Archivo",
|
||||
"targetDetail.agentsFolder": "Carpeta de agents",
|
||||
"targetDetail.agentsFolderHint": "Los agents son archivos Markdown sueltos. Esta herramienta los lee desde aquí.",
|
||||
"targetDetail.syncMode": "Modo de sincronización",
|
||||
|
||||
@@ -434,6 +434,26 @@
|
||||
"extras.toast.skipped": "{skipped} رد شد",
|
||||
"extras.toast.skippedForce": "{skipped} رد شد (برای بازنویسی Force را فعال کنید)",
|
||||
"extras.toast.syncOne": "\"{name}\" همگام شد",
|
||||
"extras.editTarget": "ویرایش مقصد…",
|
||||
"extras.editExtra": "ویرایش extra…",
|
||||
"extras.filteredFiles": "{count} / {total} فایل",
|
||||
"extras.edit.targetTitle": "ویرایش مقصد",
|
||||
"extras.edit.extraTitle": "ویرایش extra",
|
||||
"extras.edit.was": "قبلاً {value}",
|
||||
"extras.edit.files": "فایلها",
|
||||
"extras.edit.saveAndSync": "ذخیره و همگامسازی",
|
||||
"extras.edit.saved": "«{name}» ذخیره شد",
|
||||
"extras.edit.pruneFailed": "پاکسازی مکان قبلی ممکن نشد: {error}",
|
||||
"extras.edit.moveNote": "ذخیره این مقصد را جابهجا میکند: skillshare آنچه در {from} گذاشته بود را حذف میکند و سپس با {to} همگام میکند. فایلهای دیگر در هر دو پوشه دست نمیخورند.",
|
||||
"extras.edit.moveCopyNote": "ذخیره با {to} همگام میکند. فایلهایی که قبلاً در {from} کپی شدهاند تا وقتی حذفشان نکنید همانجا میمانند.",
|
||||
"extras.edit.pruneNote.one": "همگامسازی بعدی پیوند {count} فایل ردشده را از این مقصد حذف میکند. فایلهای {name} میمانند.",
|
||||
"extras.edit.pruneNote.other": "همگامسازی بعدی پیوند {count} فایل ردشده را از این مقصد حذف میکند. فایلهای {name} میمانند.",
|
||||
"extras.edit.copyNote": "حالت copy فایلهایی را که قبلاً کپی کرده حذف نمیکند. فایلهایی که اکنون فیلترها رد میکنند تا وقتی حذفشان نکنید در {path} میمانند.",
|
||||
"extras.edit.unmatched": "{pattern} با هیچ فایلی در {name} مطابقت ندارد.",
|
||||
"extras.edit.symlinkClears.one": "در حالت symlink کل پوشه پیوند میشود، پس فیلتر فایل اعمال نمیشود. ذخیره {count} الگو را پاک میکند. برای انتخاب آنچه همگام شود merge یا copy را برگزینید.",
|
||||
"extras.edit.symlinkClears.other": "در حالت symlink کل پوشه پیوند میشود، پس فیلتر فایل اعمال نمیشود. ذخیره {count} الگو را پاک میکند. برای انتخاب آنچه همگام شود merge یا copy را برگزینید.",
|
||||
"extras.edit.renameNote": "پوشه در {path} میماند، پس چیزی روی دیسک تغییر نمیکند. فقط نام در پیکربندی شما عوض میشود.",
|
||||
"extras.edit.relinkNote": "ذخیره همهٔ مقصدها را دوباره پیوند میدهد: skillshare پیوندهای پوشهٔ قبلی را حذف میکند و سپس از {path} همگام میکند. کپیهایی که در مقصدها هستند میمانند. پوشهٔ قبلی حذف نمیشود.",
|
||||
"extras.toast.syncOneFailed": "همگامسازی \"{name}\" ناموفق بود",
|
||||
"extras.toast.syncedNFiles": "{synced} فایل به {targets} هدف",
|
||||
"filterStudio.noPreview.description": "ابتدا {kindLabel} به منبع خود اضافه کنید.",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "اسکیلهای تودرتو از نام تخت خود استفاده میکنند، مانند team__frontend__ui.",
|
||||
"targetDetail.help.order": "ابتدا شامل بررسی میشود. نامی که با استثنا مطابقت دارد هرگز همگام نمیشود.",
|
||||
"targetDetail.help.declared": "اسکیلی که در SKILL.md خود هدفها را مشخص کند فقط به همان هدفها میرود.",
|
||||
"targetDetail.addPattern": "افزودن نام یا الگو",
|
||||
"targetDetail.addPattern": "نام یا الگو را بنویسید و Enter را بزنید",
|
||||
"targetDetail.removePattern": "حذف {pattern}",
|
||||
"targetDetail.loadingPreview": "در حال بارگذاری پیشنمایش…",
|
||||
"targetDetail.previewCount": "پیشنمایش · {count}",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "برای استثنا کردن این نام کلیک کنید",
|
||||
"targetDetail.clickInclude": "برای شامل کردن این نام کلیک کنید",
|
||||
"targetDetail.clickHint": "روی یک ردیف کلیک کنید تا با نامش شامل یا استثنا شود.",
|
||||
"targetDetail.summary.files.one": "{synced} از {total} فایل به {name} میرود.",
|
||||
"targetDetail.summary.files.other": "{synced} از {total} فایل به {name} میروند.",
|
||||
"targetDetail.includeHint.files": "فقط فایلهای مطابق همگام میشوند. برای همگامسازی همهٔ فایلها خالی بگذارید.",
|
||||
"targetDetail.excludeHint.files": "فایلهای مطابق رد میشوند. پس از include اعمال میشود.",
|
||||
"targetDetail.help.anyDepth": "الگوی بدون / در هر عمقی مطابقت دارد: draft* فایل notes/draft.md را هم رد میکند.",
|
||||
"targetDetail.help.folders": "الگویی که با / تمام شود یک پوشه را در بر میگیرد، مثل images/. ** با هر تعداد پوشه مطابقت دارد.",
|
||||
"targetDetail.help.orderFiles": "ابتدا include بررسی میشود. فایلی که با exclude مطابقت داشته باشد هرگز همگام نمیشود.",
|
||||
"targetDetail.clickHintFiles": "روی یک ردیف کلیک کنید تا بر اساس مسیر include یا exclude شود.",
|
||||
"targetDetail.colFile": "فایل",
|
||||
"targetDetail.agentsFolder": "پوشه Agentها",
|
||||
"targetDetail.agentsFolderHint": "Agentها فایلهای Markdown تکی هستند. این ابزار آنها را از اینجا میخواند.",
|
||||
"targetDetail.syncMode": "حالت همگامسازی",
|
||||
|
||||
@@ -427,6 +427,26 @@
|
||||
"extras.toast.skipped": "{skipped} ignoré(s)",
|
||||
"extras.toast.skippedForce": "{skipped} ignoré(s) (activez Force pour remplacer)",
|
||||
"extras.toast.syncOne": "« {name} » synchronisé",
|
||||
"extras.editTarget": "Modifier la cible…",
|
||||
"extras.editExtra": "Modifier l’extra…",
|
||||
"extras.filteredFiles": "{count} / {total} fichiers",
|
||||
"extras.edit.targetTitle": "Modifier la cible",
|
||||
"extras.edit.extraTitle": "Modifier l’extra",
|
||||
"extras.edit.was": "avant : {value}",
|
||||
"extras.edit.files": "Fichiers",
|
||||
"extras.edit.saveAndSync": "Enregistrer et synchroniser",
|
||||
"extras.edit.saved": "« {name} » enregistré",
|
||||
"extras.edit.pruneFailed": "Impossible de nettoyer l’ancien emplacement : {error}",
|
||||
"extras.edit.moveNote": "L’enregistrement déplace cette cible : skillshare retire ce qu’il a placé dans {from}, puis synchronise vers {to}. Les autres fichiers des deux dossiers ne sont pas touchés.",
|
||||
"extras.edit.moveCopyNote": "L’enregistrement synchronise vers {to}. Les fichiers copiés auparavant dans {from} y restent jusqu’à ce que vous les supprimiez.",
|
||||
"extras.edit.pruneNote.one": "La prochaine synchronisation retire de cette cible le lien vers {count} fichier ignoré. Les fichiers de {name} restent.",
|
||||
"extras.edit.pruneNote.other": "La prochaine synchronisation retire de cette cible les liens vers {count} fichiers ignorés. Les fichiers de {name} restent.",
|
||||
"extras.edit.copyNote": "Le mode copy ne supprime pas les fichiers copiés auparavant. Les fichiers que les filtres ignorent désormais restent dans {path} jusqu’à ce que vous les supprimiez.",
|
||||
"extras.edit.unmatched": "{pattern} ne correspond à aucun fichier de {name}.",
|
||||
"extras.edit.symlinkClears.one": "En mode symlink, tout le dossier est lié : les filtres de fichiers ne s’appliquent pas. L’enregistrement efface {count} motif. Choisissez merge ou copy pour décider de ce qui est synchronisé.",
|
||||
"extras.edit.symlinkClears.other": "En mode symlink, tout le dossier est lié : les filtres de fichiers ne s’appliquent pas. L’enregistrement efface {count} motifs. Choisissez merge ou copy pour décider de ce qui est synchronisé.",
|
||||
"extras.edit.renameNote": "Le dossier reste à {path}, rien ne change sur le disque. Seul le nom dans votre configuration change.",
|
||||
"extras.edit.relinkNote": "L’enregistrement relie à nouveau toutes les cibles : skillshare retire les liens vers l’ancien dossier, puis synchronise depuis {path}. Les copies déjà présentes dans les cibles restent. L’ancien dossier n’est pas supprimé.",
|
||||
"extras.toast.syncOneFailed": "Échec de la synchronisation de « {name} »",
|
||||
"extras.toast.syncedNFiles": "{synced} fichier(s) vers {targets} cible(s)",
|
||||
"extras.toast.extensionChanged": "Extension définie sur «{extension}» (mode copy)",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "Les skills imbriqués utilisent leur nom à plat, par exemple team__frontend__ui.",
|
||||
"targetDetail.help.order": "L’inclusion est vérifiée en premier. Un nom qui correspond à une exclusion n’est jamais synchronisé.",
|
||||
"targetDetail.help.declared": "Un skill qui liste des cibles dans son SKILL.md ne va que vers ces cibles.",
|
||||
"targetDetail.addPattern": "Ajouter un nom ou un schéma",
|
||||
"targetDetail.addPattern": "Saisissez un nom ou un schéma, puis Entrée",
|
||||
"targetDetail.removePattern": "Retirer {pattern}",
|
||||
"targetDetail.loadingPreview": "Chargement de l’aperçu…",
|
||||
"targetDetail.previewCount": "Aperçu · {count}",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "Cliquer pour exclure ce nom",
|
||||
"targetDetail.clickInclude": "Cliquer pour inclure ce nom",
|
||||
"targetDetail.clickHint": "Cliquez sur une ligne pour l’inclure ou l’exclure par son nom.",
|
||||
"targetDetail.summary.files.one": "{synced} fichier sur {total} va vers {name}.",
|
||||
"targetDetail.summary.files.other": "{synced} fichiers sur {total} vont vers {name}.",
|
||||
"targetDetail.includeHint.files": "Seuls les fichiers correspondants sont synchronisés. Laissez vide pour tout synchroniser.",
|
||||
"targetDetail.excludeHint.files": "Les fichiers correspondants sont ignorés. Appliqué après include.",
|
||||
"targetDetail.help.anyDepth": "Un motif sans / correspond à toute profondeur : draft* ignore aussi notes/draft.md.",
|
||||
"targetDetail.help.folders": "Un motif terminé par / couvre un dossier, comme images/. ** correspond à n’importe quel nombre de dossiers.",
|
||||
"targetDetail.help.orderFiles": "Include est vérifié en premier. Un fichier qui correspond à exclude n’est jamais synchronisé.",
|
||||
"targetDetail.clickHintFiles": "Cliquez sur une ligne pour l’inclure ou l’exclure par son chemin.",
|
||||
"targetDetail.colFile": "Fichier",
|
||||
"targetDetail.agentsFolder": "Dossier des agents",
|
||||
"targetDetail.agentsFolderHint": "Les agents sont des fichiers Markdown individuels. Cet outil les lit ici.",
|
||||
"targetDetail.syncMode": "Mode de synchronisation",
|
||||
|
||||
@@ -426,6 +426,26 @@
|
||||
"extras.toast.skipped": "{skipped} dilewati",
|
||||
"extras.toast.skippedForce": "{skipped} dilewati (aktifkan Force untuk menimpa)",
|
||||
"extras.toast.syncOne": "\"{name}\" disinkronkan",
|
||||
"extras.editTarget": "Edit target…",
|
||||
"extras.editExtra": "Edit extra…",
|
||||
"extras.filteredFiles": "{count} / {total} file",
|
||||
"extras.edit.targetTitle": "Edit target",
|
||||
"extras.edit.extraTitle": "Edit extra",
|
||||
"extras.edit.was": "sebelumnya {value}",
|
||||
"extras.edit.files": "File",
|
||||
"extras.edit.saveAndSync": "Simpan dan sinkronkan",
|
||||
"extras.edit.saved": "\"{name}\" disimpan",
|
||||
"extras.edit.pruneFailed": "Tidak dapat membersihkan lokasi lama: {error}",
|
||||
"extras.edit.moveNote": "Menyimpan akan memindahkan target ini: skillshare menghapus yang ditaruhnya di {from}, lalu menyinkronkan ke {to}. File lain di kedua folder tidak disentuh.",
|
||||
"extras.edit.moveCopyNote": "Menyimpan akan menyinkronkan ke {to}. File yang sebelumnya disalin ke {from} tetap di sana sampai Anda menghapusnya.",
|
||||
"extras.edit.pruneNote.one": "Sync berikutnya menghapus tautan ke {count} file yang dilewati dari target ini. File di {name} tetap ada.",
|
||||
"extras.edit.pruneNote.other": "Sync berikutnya menghapus tautan ke {count} file yang dilewati dari target ini. File di {name} tetap ada.",
|
||||
"extras.edit.copyNote": "Mode copy tidak menghapus file yang sudah disalin sebelumnya. File yang kini dilewati filter tetap di {path} sampai Anda menghapusnya.",
|
||||
"extras.edit.unmatched": "{pattern} tidak cocok dengan file mana pun di {name}.",
|
||||
"extras.edit.symlinkClears.one": "Dalam mode symlink seluruh folder ditautkan, jadi filter file tidak berlaku. Menyimpan akan menghapus {count} pola. Pilih merge atau copy untuk memilih apa yang disinkronkan.",
|
||||
"extras.edit.symlinkClears.other": "Dalam mode symlink seluruh folder ditautkan, jadi filter file tidak berlaku. Menyimpan akan menghapus {count} pola. Pilih merge atau copy untuk memilih apa yang disinkronkan.",
|
||||
"extras.edit.renameNote": "Folder tetap di {path}, jadi tidak ada yang berubah di disk. Hanya nama di konfigurasi Anda yang berubah.",
|
||||
"extras.edit.relinkNote": "Menyimpan akan menautkan ulang setiap target: skillshare menghapus tautan ke folder lama, lalu menyinkronkan dari {path}. Salinan yang sudah ada di target tetap ada. Folder lama tidak dihapus.",
|
||||
"extras.toast.syncOneFailed": "\"{name}\" gagal disinkronkan",
|
||||
"extras.toast.syncedNFiles": "{synced} file ke {targets} target",
|
||||
"extras.toast.created": "Extra \"{name}\" dibuat",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "Skill bertingkat memakai nama datarnya, misalnya team__frontend__ui.",
|
||||
"targetDetail.help.order": "Sertakan diperiksa lebih dulu. Nama yang cocok dengan pengecualian tidak pernah disinkronkan.",
|
||||
"targetDetail.help.declared": "Skill yang mencantumkan target di SKILL.md hanya dikirim ke target tersebut.",
|
||||
"targetDetail.addPattern": "Tambah nama atau pola",
|
||||
"targetDetail.addPattern": "Ketik nama atau pola, lalu tekan Enter",
|
||||
"targetDetail.removePattern": "Hapus {pattern}",
|
||||
"targetDetail.loadingPreview": "Memuat pratinjau…",
|
||||
"targetDetail.previewCount": "Pratinjau · {count}",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "Klik untuk mengecualikan nama ini",
|
||||
"targetDetail.clickInclude": "Klik untuk menyertakan nama ini",
|
||||
"targetDetail.clickHint": "Klik baris untuk menyertakan atau mengecualikannya berdasarkan nama.",
|
||||
"targetDetail.summary.files.one": "{synced} dari {total} file masuk ke {name}.",
|
||||
"targetDetail.summary.files.other": "{synced} dari {total} file masuk ke {name}.",
|
||||
"targetDetail.includeHint.files": "Hanya file yang cocok yang disinkronkan. Biarkan kosong untuk menyinkronkan semua file.",
|
||||
"targetDetail.excludeHint.files": "File yang cocok dilewati. Diterapkan setelah include.",
|
||||
"targetDetail.help.anyDepth": "Pola tanpa / cocok di kedalaman mana pun: draft* juga melewati notes/draft.md.",
|
||||
"targetDetail.help.folders": "Pola yang diakhiri / mencakup satu folder, seperti images/. ** cocok dengan sejumlah folder.",
|
||||
"targetDetail.help.orderFiles": "Include diperiksa lebih dulu. File yang cocok dengan exclude tidak pernah disinkronkan.",
|
||||
"targetDetail.clickHintFiles": "Klik baris untuk meng-include atau meng-exclude berdasarkan path.",
|
||||
"targetDetail.colFile": "File",
|
||||
"targetDetail.agentsFolder": "Folder agent",
|
||||
"targetDetail.agentsFolderHint": "Agent adalah file Markdown tunggal. Alat ini membacanya dari sini.",
|
||||
"targetDetail.syncMode": "Mode sinkronisasi",
|
||||
|
||||
@@ -427,6 +427,26 @@
|
||||
"extras.toast.skipped": "{skipped} 件スキップ",
|
||||
"extras.toast.skippedForce": "{skipped} 件スキップ(上書きするには Force を有効にしてください)",
|
||||
"extras.toast.syncOne": "「{name}」を同期しました",
|
||||
"extras.editTarget": "ターゲットを編集…",
|
||||
"extras.editExtra": "extra を編集…",
|
||||
"extras.filteredFiles": "{count} / {total} ファイル",
|
||||
"extras.edit.targetTitle": "ターゲットを編集",
|
||||
"extras.edit.extraTitle": "extra を編集",
|
||||
"extras.edit.was": "変更前: {value}",
|
||||
"extras.edit.files": "ファイル",
|
||||
"extras.edit.saveAndSync": "保存して同期",
|
||||
"extras.edit.saved": "「{name}」を保存しました",
|
||||
"extras.edit.pruneFailed": "古い場所を片付けられませんでした: {error}",
|
||||
"extras.edit.moveNote": "保存するとこのターゲットを移動します。skillshare が {from} に置いたものを削除してから {to} に同期します。どちらのフォルダの他のファイルにも触れません。",
|
||||
"extras.edit.moveCopyNote": "保存すると {to} に同期します。以前 {from} にコピーしたファイルは、削除するまでそのまま残ります。",
|
||||
"extras.edit.pruneNote.one": "次の同期で、スキップされた {count} ファイルへのリンクをこのターゲットから削除します。{name} 内のファイルは残ります。",
|
||||
"extras.edit.pruneNote.other": "次の同期で、スキップされた {count} ファイルへのリンクをこのターゲットから削除します。{name} 内のファイルは残ります。",
|
||||
"extras.edit.copyNote": "copy モードは以前コピーしたファイルを削除しません。フィルターで外れたファイルは、削除するまで {path} に残ります。",
|
||||
"extras.edit.unmatched": "{pattern} は {name} のどのファイルにも一致しません。",
|
||||
"extras.edit.symlinkClears.one": "symlink モードはフォルダ全体をリンクするため、ファイルフィルターは適用されません。保存すると {count} 個のパターンを消去します。同期するファイルを選ぶには merge か copy を選んでください。",
|
||||
"extras.edit.symlinkClears.other": "symlink モードはフォルダ全体をリンクするため、ファイルフィルターは適用されません。保存すると {count} 個のパターンを消去します。同期するファイルを選ぶには merge か copy を選んでください。",
|
||||
"extras.edit.renameNote": "フォルダは {path} のままなので、ディスク上は何も変わりません。設定内の名前だけが変わります。",
|
||||
"extras.edit.relinkNote": "保存するとすべてのターゲットを再リンクします。skillshare が古いフォルダへのリンクを削除してから {path} から同期します。ターゲット内のコピー済みファイルは残り、古いフォルダも削除されません。",
|
||||
"extras.toast.syncOneFailed": "「{name}」の同期に失敗しました",
|
||||
"extras.toast.syncedNFiles": "{targets} 個のターゲットに {synced} 件のファイルを同期しました",
|
||||
"extras.toast.extensionChanged": "extension を「{extension}」に設定しました(copy モード)",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "ネストしたスキルは team__frontend__ui のようなフラット名で指定します。",
|
||||
"targetDetail.help.order": "含める条件を先に確認します。除外に一致する名前は同期されません。",
|
||||
"targetDetail.help.declared": "SKILL.md でターゲットを指定したスキルは、そのターゲットにだけ同期されます。",
|
||||
"targetDetail.addPattern": "名前またはパターンを追加",
|
||||
"targetDetail.addPattern": "名前またはパターンを入力して Enter",
|
||||
"targetDetail.removePattern": "{pattern} を削除",
|
||||
"targetDetail.loadingPreview": "プレビューを読み込み中…",
|
||||
"targetDetail.previewCount": "プレビュー · {count} 件",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "クリックしてこの名前を除外",
|
||||
"targetDetail.clickInclude": "クリックしてこの名前を含める",
|
||||
"targetDetail.clickHint": "行をクリックすると、その名前で含めるか除外できます。",
|
||||
"targetDetail.summary.files.one": "{total} 件中 {synced} 件のファイルが {name} に同期されます。",
|
||||
"targetDetail.summary.files.other": "{total} 件中 {synced} 件のファイルが {name} に同期されます。",
|
||||
"targetDetail.includeHint.files": "一致するファイルだけを同期します。空にするとすべてのファイルを同期します。",
|
||||
"targetDetail.excludeHint.files": "一致するファイルはスキップされます。include の後に適用されます。",
|
||||
"targetDetail.help.anyDepth": "/ を含まないパターンはどの階層にも一致します。draft* は notes/draft.md もスキップします。",
|
||||
"targetDetail.help.folders": "/ で終わるパターンはフォルダ全体を対象にします(例: images/)。** は任意の数のフォルダに一致します。",
|
||||
"targetDetail.help.orderFiles": "include が先に判定されます。exclude に一致するファイルは同期されません。",
|
||||
"targetDetail.clickHintFiles": "行をクリックすると、そのパスで include または exclude します。",
|
||||
"targetDetail.colFile": "ファイル",
|
||||
"targetDetail.agentsFolder": "Agent フォルダー",
|
||||
"targetDetail.agentsFolderHint": "Agent は単一の Markdown ファイルです。このツールはここから読み込みます。",
|
||||
"targetDetail.syncMode": "同期モード",
|
||||
|
||||
@@ -434,6 +434,26 @@
|
||||
"extras.toast.skipped": "{skipped}개 건너뜀",
|
||||
"extras.toast.skippedForce": "{skipped}개 건너뜀 (재정의하려면 Force 활성화)",
|
||||
"extras.toast.syncOne": "\"{name}\" 동기화 완료",
|
||||
"extras.editTarget": "대상 편집…",
|
||||
"extras.editExtra": "extra 편집…",
|
||||
"extras.filteredFiles": "{count} / {total}개 파일",
|
||||
"extras.edit.targetTitle": "대상 편집",
|
||||
"extras.edit.extraTitle": "extra 편집",
|
||||
"extras.edit.was": "이전: {value}",
|
||||
"extras.edit.files": "파일",
|
||||
"extras.edit.saveAndSync": "저장 후 동기화",
|
||||
"extras.edit.saved": "\"{name}\" 저장됨",
|
||||
"extras.edit.pruneFailed": "이전 위치를 정리하지 못했습니다: {error}",
|
||||
"extras.edit.moveNote": "저장하면 이 대상을 옮깁니다. skillshare가 {from}에 둔 항목을 제거한 뒤 {to}로 동기화합니다. 두 폴더의 다른 파일은 건드리지 않습니다.",
|
||||
"extras.edit.moveCopyNote": "저장하면 {to}로 동기화합니다. 이전에 {from}에 복사한 파일은 직접 삭제할 때까지 남아 있습니다.",
|
||||
"extras.edit.pruneNote.one": "다음 동기화에서 건너뛴 파일 {count}개의 링크를 이 대상에서 제거합니다. {name}의 파일은 그대로 남습니다.",
|
||||
"extras.edit.pruneNote.other": "다음 동기화에서 건너뛴 파일 {count}개의 링크를 이 대상에서 제거합니다. {name}의 파일은 그대로 남습니다.",
|
||||
"extras.edit.copyNote": "copy 모드는 이전에 복사한 파일을 삭제하지 않습니다. 필터에서 빠진 파일은 직접 삭제할 때까지 {path}에 남습니다.",
|
||||
"extras.edit.unmatched": "{pattern}은(는) {name}의 어떤 파일과도 일치하지 않습니다.",
|
||||
"extras.edit.symlinkClears.one": "symlink 모드는 폴더 전체를 링크하므로 파일 필터가 적용되지 않습니다. 저장하면 패턴 {count}개가 지워집니다. 동기화할 파일을 고르려면 merge 또는 copy를 선택하세요.",
|
||||
"extras.edit.symlinkClears.other": "symlink 모드는 폴더 전체를 링크하므로 파일 필터가 적용되지 않습니다. 저장하면 패턴 {count}개가 지워집니다. 동기화할 파일을 고르려면 merge 또는 copy를 선택하세요.",
|
||||
"extras.edit.renameNote": "폴더는 {path}에 그대로 있으므로 디스크에는 아무 변화가 없습니다. 설정의 이름만 바뀝니다.",
|
||||
"extras.edit.relinkNote": "저장하면 모든 대상을 다시 링크합니다. skillshare가 이전 폴더로 향하는 링크를 제거한 뒤 {path}에서 동기화합니다. 대상에 이미 복사된 파일은 남고, 이전 폴더도 삭제되지 않습니다.",
|
||||
"extras.toast.syncOneFailed": "\"{name}\" 동기화 실패",
|
||||
"extras.toast.syncedNFiles": "{targets}개 대상에 {synced}개 파일 동기화됨",
|
||||
"filterStudio.noPreview.description": "먼저 소스에 {kindLabel}을(를) 추가하세요.",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "중첩된 skill은 team__frontend__ui 같은 평면 이름을 씁니다.",
|
||||
"targetDetail.help.order": "포함을 먼저 확인합니다. 제외와 일치하는 이름은 동기화되지 않습니다.",
|
||||
"targetDetail.help.declared": "SKILL.md에 대상을 적은 skill은 그 대상으로만 동기화됩니다.",
|
||||
"targetDetail.addPattern": "이름 또는 패턴 추가",
|
||||
"targetDetail.addPattern": "이름 또는 패턴 입력 후 Enter",
|
||||
"targetDetail.removePattern": "{pattern} 제거",
|
||||
"targetDetail.loadingPreview": "미리보기 불러오는 중…",
|
||||
"targetDetail.previewCount": "미리보기 · {count}개",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "클릭하여 이 이름 제외",
|
||||
"targetDetail.clickInclude": "클릭하여 이 이름 포함",
|
||||
"targetDetail.clickHint": "행을 클릭하면 이름으로 포함하거나 제외합니다.",
|
||||
"targetDetail.summary.files.one": "파일 {total}개 중 {synced}개가 {name}(으)로 동기화됩니다.",
|
||||
"targetDetail.summary.files.other": "파일 {total}개 중 {synced}개가 {name}(으)로 동기화됩니다.",
|
||||
"targetDetail.includeHint.files": "일치하는 파일만 동기화합니다. 비워 두면 모든 파일을 동기화합니다.",
|
||||
"targetDetail.excludeHint.files": "일치하는 파일은 건너뜁니다. include 다음에 적용됩니다.",
|
||||
"targetDetail.help.anyDepth": "/가 없는 패턴은 모든 깊이에서 일치합니다. draft*는 notes/draft.md도 건너뜁니다.",
|
||||
"targetDetail.help.folders": "/로 끝나는 패턴은 폴더 전체를 가리킵니다(예: images/). **는 여러 단계의 폴더와 일치합니다.",
|
||||
"targetDetail.help.orderFiles": "include를 먼저 확인합니다. exclude와 일치하는 파일은 동기화되지 않습니다.",
|
||||
"targetDetail.clickHintFiles": "행을 클릭하면 해당 경로를 include 또는 exclude합니다.",
|
||||
"targetDetail.colFile": "파일",
|
||||
"targetDetail.agentsFolder": "Agents 폴더",
|
||||
"targetDetail.agentsFolderHint": "agent는 개별 Markdown 파일입니다. 이 도구는 여기에서 읽습니다.",
|
||||
"targetDetail.syncMode": "동기화 모드",
|
||||
|
||||
@@ -427,6 +427,26 @@
|
||||
"extras.toast.skipped": "{skipped} ignorado(s)",
|
||||
"extras.toast.skippedForce": "{skipped} ignorado(s) (ative Force para substituir)",
|
||||
"extras.toast.syncOne": "\"{name}\" sincronizado",
|
||||
"extras.editTarget": "Editar destino…",
|
||||
"extras.editExtra": "Editar extra…",
|
||||
"extras.filteredFiles": "{count} / {total} arquivos",
|
||||
"extras.edit.targetTitle": "Editar destino",
|
||||
"extras.edit.extraTitle": "Editar extra",
|
||||
"extras.edit.was": "antes {value}",
|
||||
"extras.edit.files": "Arquivos",
|
||||
"extras.edit.saveAndSync": "Salvar e sincronizar",
|
||||
"extras.edit.saved": "\"{name}\" salvo",
|
||||
"extras.edit.pruneFailed": "Não foi possível limpar o local antigo: {error}",
|
||||
"extras.edit.moveNote": "Salvar move este destino: o skillshare remove o que colocou em {from} e depois sincroniza para {to}. Os outros arquivos das duas pastas não são alterados.",
|
||||
"extras.edit.moveCopyNote": "Salvar sincroniza para {to}. Os arquivos copiados antes para {from} ficam lá até você apagá-los.",
|
||||
"extras.edit.pruneNote.one": "A próxima sincronização remove deste destino o link para {count} arquivo ignorado. Os arquivos em {name} continuam.",
|
||||
"extras.edit.pruneNote.other": "A próxima sincronização remove deste destino os links para {count} arquivos ignorados. Os arquivos em {name} continuam.",
|
||||
"extras.edit.copyNote": "O modo copy não apaga arquivos que copiou antes. Os arquivos que os filtros agora ignoram ficam em {path} até você apagá-los.",
|
||||
"extras.edit.unmatched": "{pattern} não corresponde a nenhum arquivo em {name}.",
|
||||
"extras.edit.symlinkClears.one": "No modo symlink a pasta inteira é vinculada, então os filtros de arquivos não se aplicam. Salvar apaga {count} padrão. Escolha merge ou copy para decidir o que sincronizar.",
|
||||
"extras.edit.symlinkClears.other": "No modo symlink a pasta inteira é vinculada, então os filtros de arquivos não se aplicam. Salvar apaga {count} padrões. Escolha merge ou copy para decidir o que sincronizar.",
|
||||
"extras.edit.renameNote": "A pasta continua em {path}, então nada muda no disco. Só o nome na sua configuração muda.",
|
||||
"extras.edit.relinkNote": "Salvar vincula de novo todos os destinos: o skillshare remove os links para a pasta antiga e depois sincroniza a partir de {path}. Cópias já presentes nos destinos continuam. A pasta antiga não é apagada.",
|
||||
"extras.toast.syncOneFailed": "\"{name}\" falhou ao sincronizar",
|
||||
"extras.toast.syncedNFiles": "{synced} arquivo(s) para {targets} destino(s)",
|
||||
"extras.toast.extensionChanged": "Extensão definida como \"{extension}\" (modo copy)",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "Skills aninhadas usam o nome plano, como team__frontend__ui.",
|
||||
"targetDetail.help.order": "Incluir é verificado primeiro. Um nome que corresponde a excluir nunca é sincronizado.",
|
||||
"targetDetail.help.declared": "Uma skill que lista destinos no SKILL.md só vai para esses destinos.",
|
||||
"targetDetail.addPattern": "Adicione um nome ou padrão",
|
||||
"targetDetail.addPattern": "Digite um nome ou padrão e pressione Enter",
|
||||
"targetDetail.removePattern": "Remover {pattern}",
|
||||
"targetDetail.loadingPreview": "Carregando prévia…",
|
||||
"targetDetail.previewCount": "Prévia · {count}",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "Clique para excluir este nome",
|
||||
"targetDetail.clickInclude": "Clique para incluir este nome",
|
||||
"targetDetail.clickHint": "Clique em uma linha para incluí-la ou excluí-la pelo nome.",
|
||||
"targetDetail.summary.files.one": "{synced} de {total} arquivo vai para {name}.",
|
||||
"targetDetail.summary.files.other": "{synced} de {total} arquivos vão para {name}.",
|
||||
"targetDetail.includeHint.files": "Só os arquivos que correspondem são sincronizados. Deixe vazio para sincronizar todos.",
|
||||
"targetDetail.excludeHint.files": "Arquivos que correspondem são ignorados. Aplicado depois de include.",
|
||||
"targetDetail.help.anyDepth": "Um padrão sem / corresponde em qualquer profundidade: draft* também ignora notes/draft.md.",
|
||||
"targetDetail.help.folders": "Um padrão terminado em / cobre uma pasta, como images/. ** corresponde a qualquer número de pastas.",
|
||||
"targetDetail.help.orderFiles": "Include é verificado primeiro. Um arquivo que corresponde a exclude nunca é sincronizado.",
|
||||
"targetDetail.clickHintFiles": "Clique em uma linha para incluí-la ou excluí-la pelo caminho.",
|
||||
"targetDetail.colFile": "Arquivo",
|
||||
"targetDetail.agentsFolder": "Pasta de agents",
|
||||
"targetDetail.agentsFolderHint": "Agents são arquivos Markdown avulsos. Esta ferramenta os lê daqui.",
|
||||
"targetDetail.syncMode": "Modo de sincronização",
|
||||
|
||||
@@ -427,6 +427,26 @@
|
||||
"extras.toast.skipped": "{skipped} 个已跳过",
|
||||
"extras.toast.skippedForce": "{skipped} 个已跳过(启用 Force 可覆盖)",
|
||||
"extras.toast.syncOne": "「{name}」已同步",
|
||||
"extras.editTarget": "编辑目标…",
|
||||
"extras.editExtra": "编辑 extra…",
|
||||
"extras.filteredFiles": "{count} / {total} 个文件",
|
||||
"extras.edit.targetTitle": "编辑目标",
|
||||
"extras.edit.extraTitle": "编辑 extra",
|
||||
"extras.edit.was": "原为 {value}",
|
||||
"extras.edit.files": "文件",
|
||||
"extras.edit.saveAndSync": "保存并同步",
|
||||
"extras.edit.saved": "已保存“{name}”",
|
||||
"extras.edit.pruneFailed": "无法清理旧位置:{error}",
|
||||
"extras.edit.moveNote": "保存时会移动这个目标:skillshare 先移除它放在 {from} 的文件,再同步到 {to}。两个文件夹中的其他文件都不会被改动。",
|
||||
"extras.edit.moveCopyNote": "保存后会同步到 {to}。之前复制到 {from} 的文件会保留在原处,直到你自行删除。",
|
||||
"extras.edit.pruneNote.one": "下次同步会从这个目标移除 {count} 个被跳过文件的链接。{name} 中的文件不受影响。",
|
||||
"extras.edit.pruneNote.other": "下次同步会从这个目标移除 {count} 个被跳过文件的链接。{name} 中的文件不受影响。",
|
||||
"extras.edit.copyNote": "copy 模式不会删除之前复制过去的文件。现在被筛掉的文件会保留在 {path},直到你自行删除。",
|
||||
"extras.edit.unmatched": "{pattern} 在 {name} 中没有匹配到任何文件。",
|
||||
"extras.edit.symlinkClears.one": "symlink 模式会链接整个文件夹,文件筛选不会生效。保存时会清除这 {count} 个 pattern。要选择同步哪些文件,请改用 merge 或 copy。",
|
||||
"extras.edit.symlinkClears.other": "symlink 模式会链接整个文件夹,文件筛选不会生效。保存时会清除这 {count} 个 pattern。要选择同步哪些文件,请改用 merge 或 copy。",
|
||||
"extras.edit.renameNote": "文件夹仍在 {path},磁盘上不会有任何变化,只有配置中的名称会改。",
|
||||
"extras.edit.relinkNote": "保存时会重新链接每个目标:skillshare 先移除指向旧文件夹的链接,再从 {path} 同步。目标中已复制的文件会保留,旧文件夹也不会被删除。",
|
||||
"extras.toast.syncOneFailed": "「{name}」同步失败",
|
||||
"extras.toast.syncedNFiles": "{synced} 个文件 → {targets} 个目标",
|
||||
"extras.toast.extensionChanged": "扩展已设为「{extension}」(复制模式)",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "嵌套 Skill 使用扁平名称,例如 team__frontend__ui。",
|
||||
"targetDetail.help.order": "先检查包含。匹配排除的名称永远不会同步。",
|
||||
"targetDetail.help.declared": "在 SKILL.md 中列出目标的 Skill 只会同步到这些目标。",
|
||||
"targetDetail.addPattern": "添加名称或模式",
|
||||
"targetDetail.addPattern": "输入名称或模式后按 Enter",
|
||||
"targetDetail.removePattern": "移除 {pattern}",
|
||||
"targetDetail.loadingPreview": "正在加载预览…",
|
||||
"targetDetail.previewCount": "预览 · {count} 个",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "点击排除这个名称",
|
||||
"targetDetail.clickInclude": "点击包含这个名称",
|
||||
"targetDetail.clickHint": "点击某一行即可按名称包含或排除。",
|
||||
"targetDetail.summary.files.one": "{total} 个文件中有 {synced} 个同步到 {name}。",
|
||||
"targetDetail.summary.files.other": "{total} 个文件中有 {synced} 个同步到 {name}。",
|
||||
"targetDetail.includeHint.files": "只同步匹配的文件。留空则同步所有文件。",
|
||||
"targetDetail.excludeHint.files": "匹配的文件会被跳过。在包含之后应用。",
|
||||
"targetDetail.help.anyDepth": "不含 / 的 pattern 会匹配任意层级:draft* 也会跳过 notes/draft.md。",
|
||||
"targetDetail.help.folders": "以 / 结尾的 pattern 覆盖整个文件夹,例如 images/。** 可匹配任意层文件夹。",
|
||||
"targetDetail.help.orderFiles": "先检查包含。匹配排除的文件一律不会同步。",
|
||||
"targetDetail.clickHintFiles": "点击某一行即可按路径包含或排除。",
|
||||
"targetDetail.colFile": "文件",
|
||||
"targetDetail.agentsFolder": "Agent 文件夹",
|
||||
"targetDetail.agentsFolderHint": "Agent 是单个 Markdown 文件,这个工具从这里读取。",
|
||||
"targetDetail.syncMode": "同步模式",
|
||||
|
||||
@@ -429,6 +429,26 @@
|
||||
"extras.toast.modeChanged": "模式已變更為「{mode}」",
|
||||
"extras.toast.removed": "「{name}」已移除",
|
||||
"extras.toast.syncOne": "「{name}」已同步",
|
||||
"extras.editTarget": "編輯目標…",
|
||||
"extras.editExtra": "編輯 extra…",
|
||||
"extras.filteredFiles": "{count} / {total} 個檔案",
|
||||
"extras.edit.targetTitle": "編輯目標",
|
||||
"extras.edit.extraTitle": "編輯 extra",
|
||||
"extras.edit.was": "原本是 {value}",
|
||||
"extras.edit.files": "檔案",
|
||||
"extras.edit.saveAndSync": "儲存並同步",
|
||||
"extras.edit.saved": "已儲存「{name}」",
|
||||
"extras.edit.pruneFailed": "無法清理舊位置:{error}",
|
||||
"extras.edit.moveNote": "儲存時會搬移這個目標:skillshare 先移除它放在 {from} 的檔案,再同步到 {to}。兩個資料夾裡的其他檔案都不會動到。",
|
||||
"extras.edit.moveCopyNote": "儲存後會同步到 {to}。之前複製到 {from} 的檔案會留在原處,直到你自行刪除。",
|
||||
"extras.edit.pruneNote.one": "下次同步會從這個目標移除 {count} 個被略過檔案的連結。{name} 裡的檔案不受影響。",
|
||||
"extras.edit.pruneNote.other": "下次同步會從這個目標移除 {count} 個被略過檔案的連結。{name} 裡的檔案不受影響。",
|
||||
"extras.edit.copyNote": "copy 模式不會刪除之前複製過去的檔案。現在被篩掉的檔案會留在 {path},直到你自行刪除。",
|
||||
"extras.edit.unmatched": "{pattern} 在 {name} 裡沒有對到任何檔案。",
|
||||
"extras.edit.symlinkClears.one": "symlink 模式會連結整個資料夾,檔案篩選不會生效。儲存時會清除這 {count} 個 pattern。要選擇同步哪些檔案,請改用 merge 或 copy。",
|
||||
"extras.edit.symlinkClears.other": "symlink 模式會連結整個資料夾,檔案篩選不會生效。儲存時會清除這 {count} 個 pattern。要選擇同步哪些檔案,請改用 merge 或 copy。",
|
||||
"extras.edit.renameNote": "資料夾仍在 {path},磁碟上什麼都不會變,只有設定裡的名稱會改。",
|
||||
"extras.edit.relinkNote": "儲存時會重新連結每個目標:skillshare 先移除指向舊資料夾的連結,再從 {path} 同步。目標裡已複製的檔案會留著,舊資料夾也不會被刪除。",
|
||||
"extras.toast.syncOneFailed": "「{name}」同步失敗",
|
||||
"extras.toast.noFilesInSource": "來源目錄沒有檔案",
|
||||
"extras.toast.syncedNFiles": "{synced} 個檔案 → {targets} 個目標",
|
||||
@@ -1732,7 +1752,7 @@
|
||||
"targetDetail.help.nested": "巢狀 Skill 使用扁平名稱,例如 team__frontend__ui。",
|
||||
"targetDetail.help.order": "先檢查包含。符合排除的名稱一律不會同步。",
|
||||
"targetDetail.help.declared": "在 SKILL.md 列出目標的 Skill 只會同步到那些目標。",
|
||||
"targetDetail.addPattern": "新增名稱或模式",
|
||||
"targetDetail.addPattern": "輸入名稱或模式後按 Enter",
|
||||
"targetDetail.removePattern": "移除 {pattern}",
|
||||
"targetDetail.loadingPreview": "正在載入預覽…",
|
||||
"targetDetail.previewCount": "預覽 · {count} 個",
|
||||
@@ -1748,6 +1768,15 @@
|
||||
"targetDetail.clickExclude": "點擊排除這個名稱",
|
||||
"targetDetail.clickInclude": "點擊包含這個名稱",
|
||||
"targetDetail.clickHint": "點擊某一列即可依名稱包含或排除。",
|
||||
"targetDetail.summary.files.one": "{total} 個檔案中有 {synced} 個同步到 {name}。",
|
||||
"targetDetail.summary.files.other": "{total} 個檔案中有 {synced} 個同步到 {name}。",
|
||||
"targetDetail.includeHint.files": "只同步符合的檔案。留空就同步所有檔案。",
|
||||
"targetDetail.excludeHint.files": "符合的檔案會被略過。在包含之後套用。",
|
||||
"targetDetail.help.anyDepth": "不含 / 的 pattern 會比對任何層級:draft* 也會略過 notes/draft.md。",
|
||||
"targetDetail.help.folders": "以 / 結尾的 pattern 涵蓋整個資料夾,例如 images/。** 可比對任意層資料夾。",
|
||||
"targetDetail.help.orderFiles": "先檢查包含。符合排除的檔案一律不會同步。",
|
||||
"targetDetail.clickHintFiles": "點擊某一列即可依路徑包含或排除。",
|
||||
"targetDetail.colFile": "檔案",
|
||||
"targetDetail.agentsFolder": "Agents 資料夾",
|
||||
"targetDetail.agentsFolderHint": "Agent 是單一 Markdown 檔案,這個工具從這裡讀取。",
|
||||
"targetDetail.syncMode": "同步模式",
|
||||
|
||||
@@ -65,6 +65,7 @@ export const queryKeys = {
|
||||
templates: ['templates'] as const,
|
||||
skillPreview: (req: object) => ['skill-preview', req] as const,
|
||||
extras: ['extras'] as const,
|
||||
extrasPreview: (...parts: unknown[]) => ['extras-preview', ...parts] as const,
|
||||
// Under `extras`, so invalidating that key refreshes both.
|
||||
extrasExtensions: ['extras', 'extensions'] as const,
|
||||
extensions: ['extensions'] as const,
|
||||
|
||||
@@ -28,6 +28,9 @@ vi.mock('../api/client', async (load) => {
|
||||
],
|
||||
}),
|
||||
createExtra: vi.fn().mockResolvedValue({ success: true }),
|
||||
previewExtraFilter: vi.fn().mockResolvedValue({ files: [{ file: 'index.md', status: 'synced' }, { file: 'draft.md', status: 'synced' }], unmatched: null }),
|
||||
editExtraTarget: vi.fn().mockResolvedValue({ success: true }),
|
||||
editExtra: vi.fn().mockResolvedValue({ success: true }),
|
||||
listExtraExtensions: vi.fn().mockResolvedValue({ extensions: [] }),
|
||||
availableTargets: vi.fn().mockResolvedValue({ targets: [] }),
|
||||
getOverview: vi.fn().mockResolvedValue({}),
|
||||
@@ -134,6 +137,34 @@ describe('Extras page in a project', () => {
|
||||
vi.mocked(api.getOverview).mockResolvedValue({} as never);
|
||||
});
|
||||
|
||||
// Issue #435: a click on a preview row excludes that file from the target.
|
||||
it('saves a file excluded from a target in Edit target', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPage();
|
||||
await user.click(await screen.findByRole('button', { name: 'More actions for .claude/rules' }));
|
||||
await user.click(screen.getByRole('menuitem', { name: 'Edit target…' }));
|
||||
const dialog = screen.getByRole('dialog');
|
||||
await user.click(await within(dialog).findByRole('button', { name: /draft\.md/ }));
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Save' }));
|
||||
|
||||
expect(api.editExtraTarget).toHaveBeenCalledWith('rules', '.claude/rules', {
|
||||
path: '.claude/rules', mode: 'merge', flatten: false, extension: '', as: '', include: [], exclude: ['draft.md'],
|
||||
});
|
||||
});
|
||||
|
||||
it('renames an extra in Edit extra', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderPage();
|
||||
await user.click(await screen.findByRole('button', { name: 'More actions for rules' }));
|
||||
await user.click(screen.getByRole('menuitem', { name: 'Edit extra…' }));
|
||||
const name = within(screen.getByRole('dialog')).getByLabelText('Name');
|
||||
await user.clear(name);
|
||||
await user.type(name, 'docs');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
expect(api.editExtra).toHaveBeenCalledWith('rules', { name: 'docs' });
|
||||
});
|
||||
|
||||
// A target page's "Share with Extras" link.
|
||||
it('opens Add extra ready to share a target file', async () => {
|
||||
renderPage('/extras?add=file&target=%2Fhome%2Fme%2F.pi%2Fagent&file=APPEND_SYSTEM.md');
|
||||
|
||||
+29
-13
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router-dom';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Ellipsis, FileText, FoldVertical, Folder, FolderPlus, Link2, Plus, Puzzle, RefreshCw, Trash2, X, Zap } from 'lucide-react';
|
||||
import { Ellipsis, FileText, FoldVertical, Folder, FolderPlus, Link2, ListFilter, Pencil, Plus, Puzzle, RefreshCw, Trash2, X, Zap } from 'lucide-react';
|
||||
import { api } from '../api/client';
|
||||
import type { AvailableTarget, Extra, ExtraTarget } from '../api/client';
|
||||
import { queryKeys, staleTimes } from '../lib/queryKeys';
|
||||
@@ -24,21 +24,12 @@ import ProjectInstructions from '../components/instructions/ProjectInstructions'
|
||||
import SharedInstructions from '../components/instructions/SharedInstructions';
|
||||
import { isAgentsExtra } from '../components/instructions/instructionsView';
|
||||
import { useAvailableTargetsQuery, useOverviewQuery } from '../hooks/useSharedQueries';
|
||||
import { EditExtraDialog, EditTargetDialog, FILE_MODES, MODES, joinFile } from '../components/extras/ExtraEditDialogs';
|
||||
import { invalidate } from '../lib/queryEvents';
|
||||
|
||||
const MODES = ['merge', 'copy', 'symlink'] as const;
|
||||
// A single file can't be a directory symlink; import writes an @ line instead.
|
||||
const FILE_MODES = ['merge', 'copy', 'import', 'prepend', 'append'] as const;
|
||||
|
||||
/** A file name typed where a path would be wrong. */
|
||||
const isPathLike = (name: string) => /[\\/]/.test(name);
|
||||
|
||||
/** <folder>/<file>, for a single-file extra's source or target file, with the separator the folder already uses (a backslash on Windows). */
|
||||
const joinFile = (dir: string, file: string) => {
|
||||
const sep = dir.lastIndexOf('\\') > dir.lastIndexOf('/') ? '\\' : '/';
|
||||
return `${dir.replace(/[\\/]+$/, '')}${sep}${file}`;
|
||||
};
|
||||
|
||||
const STATUS: Record<string, { tone: string; labelKey: string }> = {
|
||||
synced: { tone: 'ok', labelKey: 'extras.status.synced' },
|
||||
drift: { tone: 'warn', labelKey: 'extras.status.drift' },
|
||||
@@ -432,12 +423,15 @@ function AddTargetRow({ onAdd, onCancel, extensions, known, file }: {
|
||||
);
|
||||
}
|
||||
|
||||
function TargetTags({ target }: { target: ExtraTarget }) {
|
||||
function TargetTags({ target, total }: { target: ExtraTarget; total: number }) {
|
||||
const t = useT();
|
||||
const filtered = (target.include?.length ?? 0) + (target.exclude?.length ?? 0) > 0;
|
||||
return (
|
||||
<span className="flex w-[210px] shrink-0 items-center gap-1.5">
|
||||
{target.extension && <span className="ss-tag"><Puzzle size={11} />{target.extension}</span>}
|
||||
<span className="ss-tag">{target.mode}</span>
|
||||
{target.flatten && <span className="ss-tag">flatten</span>}
|
||||
{filtered && <span className="ss-tag"><ListFilter size={11} />{t('extras.filteredFiles', { count: target.file_count, total })}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -487,6 +481,8 @@ export default function ExtrasPage() {
|
||||
const [menu, setMenu] = useState<{ x: number; y: number; items: ContextMenuItem[] } | null>(null);
|
||||
const [removeExtra, setRemoveExtra] = useState<string | null>(null);
|
||||
const [removeTarget, setRemoveTarget] = useState<{ name: string; path: string } | null>(null);
|
||||
const [editing, setEditing] = useState<{ extra: Extra; target?: ExtraTarget } | null>(null);
|
||||
const closeEdit = () => { setEditing(null); void invalidate(queryClient, 'extrasChanged'); };
|
||||
|
||||
const openMenu = (e: React.MouseEvent<HTMLButtonElement>, items: ContextMenuItem[]) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
@@ -543,6 +539,7 @@ export default function ExtrasPage() {
|
||||
const extraMenu = (extra: Extra): ContextMenuItem[] => [
|
||||
{ key: 'sync', label: t('extras.sync'), icon: <RefreshCw size={14} />, onSelect: () => void sync(extra.name, false) },
|
||||
{ key: 'force', label: t('extras.forceSync'), icon: <Zap size={14} />, onSelect: () => void sync(extra.name, true) },
|
||||
{ key: 'edit', label: t('extras.editExtra'), icon: <Pencil size={14} />, onSelect: () => setEditing({ extra }) },
|
||||
{ key: 'remove', label: t('extras.removeConfirm.title'), icon: <Trash2 size={14} />, danger: true, onSelect: () => setRemoveExtra(extra.name) },
|
||||
];
|
||||
|
||||
@@ -559,6 +556,7 @@ export default function ExtrasPage() {
|
||||
onSelect: () => void changeTarget(extra.name, tg, { mode: m }, t('extras.toast.modeChanged', { mode: m })),
|
||||
})),
|
||||
},
|
||||
{ key: 'edit', label: t('extras.editTarget'), icon: <Pencil size={14} />, onSelect: () => setEditing({ extra, target: tg }) },
|
||||
...(extra.targets.length > 1
|
||||
? [{ key: 'remove', label: t('extras.removeTarget'), icon: <Trash2 size={14} />, danger: true, onSelect: () => setRemoveTarget({ name: extra.name, path: tg.path }) }]
|
||||
: []),
|
||||
@@ -608,6 +606,7 @@ export default function ExtrasPage() {
|
||||
})),
|
||||
}]),
|
||||
// The last target can't go: an extra needs somewhere to sync to
|
||||
{ key: 'edit', label: t('extras.editTarget'), icon: <Pencil size={14} />, onSelect: () => setEditing({ extra, target: tg }) },
|
||||
...(extra.targets.length > 1
|
||||
? [{ key: 'remove', label: t('extras.removeTarget'), icon: <Trash2 size={14} />, danger: true, onSelect: () => setRemoveTarget({ name: extra.name, path: tg.path }) }]
|
||||
: []),
|
||||
@@ -683,7 +682,7 @@ export default function ExtrasPage() {
|
||||
<div key={tg.path} className="ss-r !min-h-[46px]">
|
||||
<TargetMark path={tg.path} known={known} />
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[13px]" title={dest}>{shortenHome(dest)}</span>
|
||||
<TargetTags target={tg} />
|
||||
<TargetTags target={tg} total={extra.file_count} />
|
||||
<span className="w-[120px] shrink-0">
|
||||
<span className={`ss-st ${status?.tone ?? ''}`}>{status ? t(status.labelKey) : tg.status}</span>
|
||||
</span>
|
||||
@@ -729,6 +728,23 @@ export default function ExtrasPage() {
|
||||
initial={prefill ?? undefined}
|
||||
/>
|
||||
)}
|
||||
{editing && (editing.target ? (
|
||||
<EditTargetDialog
|
||||
extra={editing.extra}
|
||||
target={editing.target}
|
||||
extensions={extensions}
|
||||
markFor={(path) => <TargetMark path={path} known={known} />}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={closeEdit}
|
||||
/>
|
||||
) : (
|
||||
<EditExtraDialog
|
||||
extra={editing.extra}
|
||||
sharedDir={sharedDir}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={closeEdit}
|
||||
/>
|
||||
))}
|
||||
<SkillContextMenu open={!!menu} anchorPoint={menu ?? undefined} items={menu?.items ?? []} onClose={() => setMenu(null)} />
|
||||
<ConfirmDialog
|
||||
open={removeExtra !== null}
|
||||
|
||||
@@ -143,6 +143,8 @@ The wizard asks **What do you want to sync?** after the name: **Folder** or **Si
|
||||
| `--as <filename>` | File name to write at every target (default: the `--file` name). Requires `--file` |
|
||||
| `--mode <mode>` | Sync mode: `merge` (default), `copy`, or `symlink`; `import`, `prepend` and `append` only with `--file` |
|
||||
| `--flatten` | Sync files from subdirectories directly into the target root (cannot be used with `symlink` mode or `--file`) |
|
||||
| `--include <pattern>` | Sync only files that match ([file filters](#choosing-files)); repeatable. Not with `symlink` mode or `--file` |
|
||||
| `--exclude <pattern>` | Skip files that match ([file filters](#choosing-files)); repeatable. Not with `symlink` mode or `--file` |
|
||||
| `--source <path>` | Custom source directory for this extra (overrides `extras_source` and default; relative to the project root in project mode) |
|
||||
| `--force` | Overwrite if extra already exists |
|
||||
| `--no-tui` | Skip interactive wizard, use CLI flags only |
|
||||
@@ -260,13 +262,16 @@ skillshare extras source ~/company-shared/extras
|
||||
|
||||
### Operating on an existing extra
|
||||
|
||||
Change a target's sync mode or flatten setting, or add/remove a target via `extras <name>`. Run
|
||||
`skillshare sync extras` afterward to apply mode, flatten, or added-target changes. `--remove-target
|
||||
Change a target's sync mode, flatten setting, or [file filters](#choosing-files), or add/remove a
|
||||
target via `extras <name>`. Run `skillshare sync extras` afterward to apply mode, flatten, filter, or
|
||||
added-target changes. `--remove-target
|
||||
--prune` also restores or removes managed files immediately.
|
||||
|
||||
```bash
|
||||
skillshare extras <name> --mode <mode> [--target <path>] [-p|-g]
|
||||
skillshare extras <name> --flatten | --no-flatten [--target <path>]
|
||||
skillshare extras <name> --add-include <pattern> | --add-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --remove-include <pattern> | --remove-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --add-target <path> [--as <filename>] [--mode <mode>] [--flatten] [-p|-g]
|
||||
skillshare extras <name> --remove-target <path> [--prune] [-p|-g]
|
||||
skillshare extras <name> --help
|
||||
@@ -279,11 +284,15 @@ skillshare extras <name> --help
|
||||
| `--mode <mode>` | New sync mode: `merge`, `copy`, or `symlink`; `import`, `prepend` and `append` only for [single-file extras](#single-file-extras) |
|
||||
| `--flatten` | Enable flatten (sync subdirectory files into target root) |
|
||||
| `--no-flatten` | Disable flatten |
|
||||
| `--add-include <pattern>` | Add an include pattern to the target (repeatable) |
|
||||
| `--add-exclude <pattern>` | Add an exclude pattern to the target (repeatable) |
|
||||
| `--remove-include <pattern>` | Remove an include pattern |
|
||||
| `--remove-exclude <pattern>` | Remove an exclude pattern |
|
||||
| `--add-target <path>` | Add a new target to the extra |
|
||||
| `--as <filename>` | Target filename for `--add-target` (single-file extras only; defaults to `file`) |
|
||||
| `--remove-target <path>` | Remove a target from the extra (config-only by default) |
|
||||
| `--prune` | With `--remove-target`: also delete skillshare-managed files under that target. For a single-file extra it restores the target file instead |
|
||||
| `--target <path>` | Target directory path (required for `--mode` with multi-target extras; `--flatten`/`--no-flatten` applies to all targets when omitted) |
|
||||
| `--target <path>` | Target directory path (required for `--mode` and filter flags with multi-target extras; `--flatten`/`--no-flatten` applies to all targets when omitted) |
|
||||
| `--project, -p` | Use project-mode extras (`.skillshare/`) |
|
||||
| `--global, -g` | Use global extras (`~/.config/skillshare/`) |
|
||||
|
||||
@@ -300,6 +309,10 @@ skillshare extras rules --mode copy --target ~/.claude/rules
|
||||
skillshare extras agents --flatten
|
||||
skillshare extras agents --no-flatten
|
||||
|
||||
# Sync only two files to Claude, and skip drafts everywhere else
|
||||
skillshare extras docs --target ~/.claude/docs --add-include index.md --add-include learning.md
|
||||
skillshare extras docs --target ~/.cursor/docs --add-exclude "draft*"
|
||||
|
||||
# Add a new target to an existing extra (then sync)
|
||||
skillshare extras rules --add-target ~/.cursor/rules
|
||||
skillshare extras commands --add-target ~/.config/opencode/commands --mode copy
|
||||
@@ -312,7 +325,11 @@ skillshare extras rules --remove-target ~/.cursor/rules
|
||||
skillshare extras rules --remove-target ~/.cursor/rules --prune
|
||||
```
|
||||
|
||||
Also available via the TUI (`e` key) and Web UI (mode dropdown and flatten checkbox on each target).
|
||||
Also available via the TUI (`e` key) and the Web UI target menu. In the Web UI, **Edit target…** also
|
||||
changes a target's folder, file name, and file filters, and **Edit extra…** renames an extra or points
|
||||
it at another source folder. A new target folder or source folder takes effect right away: skillshare
|
||||
removes the links it made at the old place (copies stay) and syncs. A rename keeps the source folder
|
||||
and records it as the extra's `source`. The extras named `agents` and `memory` cannot be renamed.
|
||||
|
||||
### `extras remove`
|
||||
|
||||
@@ -401,6 +418,37 @@ extras:
|
||||
|
||||
---
|
||||
|
||||
## Choosing files {#choosing-files}
|
||||
|
||||
Each target of a folder extra can sync only some of the source files with `include` and `exclude`:
|
||||
|
||||
```yaml
|
||||
extras:
|
||||
- name: docs
|
||||
targets:
|
||||
- path: ~/.claude/docs
|
||||
include: [index.md, learning.md]
|
||||
- path: ~/.cursor/docs
|
||||
mode: copy
|
||||
exclude: ["draft*", images/]
|
||||
```
|
||||
|
||||
Patterns use `.gitignore` syntax on the file's path inside the source, before `flatten` or an
|
||||
extension renames it:
|
||||
|
||||
- A pattern without `/` matches at any depth: `draft*` also skips `notes/draft.md`.
|
||||
- A pattern ending in `/` covers a folder, like `images/`. `**` matches any number of folders.
|
||||
- With `include`, only matching files sync. `exclude` is applied after it.
|
||||
|
||||
`sync` warns when an `include` pattern matches no file, which usually means a typo.
|
||||
|
||||
When a filter stops matching a file, the next sync removes its link in `merge` mode. `copy` mode
|
||||
does not delete files it copied before; remove them yourself. Filters cannot be used with `symlink`
|
||||
mode, which links the whole folder, or with a [single-file extra](#single-file-extras). `extras
|
||||
collect` skips files the target's filters leave out.
|
||||
|
||||
---
|
||||
|
||||
## Extension transforms
|
||||
|
||||
Some tools do not read markdown. Gemini CLI expects TOML commands; Codex CLI expects TOML agents. The `extension` field on a target runs an external script that converts each source file into the target's native format during sync.
|
||||
|
||||
@@ -713,6 +713,8 @@ extras:
|
||||
| `targets[].mode` | No | `merge` (default), `copy`, or `symlink`; `import`, `prepend` and `append` for single-file extras only |
|
||||
| `targets[].as` | No | File name in the target for a single-file extra (default: the `file` name) |
|
||||
| `targets[].flatten` | No | When `true`, sync subdirectory files directly into target root (cannot use with `symlink` or `file`) |
|
||||
| `targets[].include` | No | Sync only source files matching these `.gitignore`-style patterns (cannot use with `symlink` or `file`). See [choosing files](../commands/extras.md#choosing-files) |
|
||||
| `targets[].exclude` | No | Skip source files matching these patterns; applied after `include` (cannot use with `symlink` or `file`) |
|
||||
|
||||
`extras_source` is auto-populated to the default path (`~/.config/skillshare/extras/`) on `skillshare init` or first `extras init`. Override it to use a custom location for all extras.
|
||||
|
||||
|
||||
+42
-3
@@ -77,6 +77,8 @@ skillshare extras init <name> --file <filename> [--as <filename>] --target <path
|
||||
| `--as <filename>` | すべての Target で書き出すファイル名(デフォルト: `--file` の名前)。`--file` が必要 |
|
||||
| `--mode <mode>` | sync モード: `merge`(デフォルト)、`copy`、または `symlink`。`import` は `--file` 指定時のみ |
|
||||
| `--flatten` | サブディレクトリ内のファイルを Target のルート直下に sync する(`symlink` モードや `--file` とは併用不可) |
|
||||
| `--include <pattern>` | 一致するファイルだけを sync する([ファイルフィルター](#choosing-files))。複数指定可。`symlink` モードや `--file` とは併用不可 |
|
||||
| `--exclude <pattern>` | 一致するファイルをスキップする([ファイルフィルター](#choosing-files))。複数指定可。`symlink` モードや `--file` とは併用不可 |
|
||||
| `--source <path>` | この Extras 用のカスタム Source ディレクトリ(`extras_source` とデフォルトを上書き。Project モードではプロジェクトルートからの相対パス) |
|
||||
| `--force` | すでに存在する Extras を上書き |
|
||||
| `--no-tui` | インタラクティブウィザードをスキップし、CLI フラグのみを使用 |
|
||||
@@ -194,11 +196,13 @@ skillshare extras source ~/company-shared/extras
|
||||
|
||||
### 既存の Extras を操作する
|
||||
|
||||
`extras <name>` で Target の sync モードや flatten 設定を変更し、Target を追加・削除できます。モード、flatten、追加した Target の変更は `skillshare sync extras` で適用します。`--remove-target --prune` は管理対象ファイルの復元や削除もすぐに行います。
|
||||
`extras <name>` で Target の sync モード、flatten 設定、[ファイルフィルター](#choosing-files)を変更し、Target を追加・削除できます。モード、flatten、フィルター、追加した Target の変更は `skillshare sync extras` で適用します。`--remove-target --prune` は管理対象ファイルの復元や削除もすぐに行います。
|
||||
|
||||
```bash
|
||||
skillshare extras <name> --mode <mode> [--target <path>] [-p|-g]
|
||||
skillshare extras <name> --flatten | --no-flatten [--target <path>]
|
||||
skillshare extras <name> --add-include <pattern> | --add-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --remove-include <pattern> | --remove-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --add-target <path> [--as <filename>] [--mode <mode>] [--flatten] [-p|-g]
|
||||
skillshare extras <name> --remove-target <path> [--prune] [-p|-g]
|
||||
skillshare extras <name> --help
|
||||
@@ -211,11 +215,15 @@ skillshare extras <name> --help
|
||||
| `--mode <mode>` | 新しい sync モード: `merge`、`copy`、または `symlink`。`import` は[単一ファイルの Extras](#single-file-extras) でのみ使用可 |
|
||||
| `--flatten` | flatten を有効化(サブディレクトリのファイルを Target ルートに sync) |
|
||||
| `--no-flatten` | flatten を無効化 |
|
||||
| `--add-include <pattern>` | Target に include パターンを追加(複数指定可) |
|
||||
| `--add-exclude <pattern>` | Target に exclude パターンを追加(複数指定可) |
|
||||
| `--remove-include <pattern>` | include パターンを削除 |
|
||||
| `--remove-exclude <pattern>` | exclude パターンを削除 |
|
||||
| `--add-target <path>` | Extras に新しい Target を追加 |
|
||||
| `--as <filename>` | `--add-target` の Target ファイル名(単一ファイルの Extras のみ。既定値は `file`) |
|
||||
| `--remove-target <path>` | Extras から Target を削除(デフォルトでは設定のみ) |
|
||||
| `--prune` | `--remove-target` と併用: その Target 配下の skillshare 管理ファイルも削除。単一ファイルの Extras では、代わりに Target のファイルを元に戻す |
|
||||
| `--target <path>` | Target ディレクトリのパス(複数 Target を持つ Extras で `--mode` を使う場合は必須。省略時、`--flatten`/`--no-flatten` はすべての Target に適用される) |
|
||||
| `--target <path>` | Target ディレクトリのパス(複数 Target を持つ Extras で `--mode` やフィルターのフラグを使う場合は必須。省略時、`--flatten`/`--no-flatten` はすべての Target に適用される) |
|
||||
| `--project, -p` | Project モードの Extras(`.skillshare/`)を使用 |
|
||||
| `--global, -g` | グローバルの Extras(`~/.config/skillshare/`)を使用 |
|
||||
|
||||
@@ -232,6 +240,10 @@ skillshare extras rules --mode copy --target ~/.claude/rules
|
||||
skillshare extras agents --flatten
|
||||
skillshare extras agents --no-flatten
|
||||
|
||||
# Claude には 2 ファイルだけ、それ以外では下書きをスキップ
|
||||
skillshare extras docs --target ~/.claude/docs --add-include index.md --add-include learning.md
|
||||
skillshare extras docs --target ~/.cursor/docs --add-exclude "draft*"
|
||||
|
||||
# 既存の Extras に新しい Target を追加する(その後 sync)
|
||||
skillshare extras rules --add-target ~/.cursor/rules
|
||||
skillshare extras commands --add-target ~/.config/opencode/commands --mode copy
|
||||
@@ -244,7 +256,7 @@ skillshare extras rules --remove-target ~/.cursor/rules
|
||||
skillshare extras rules --remove-target ~/.cursor/rules --prune
|
||||
```
|
||||
|
||||
TUI(`e` キー)と Web UI(各 Target のモードのドロップダウンと flatten チェックボックス)からも操作できます。
|
||||
TUI(`e` キー)と Web UI の Target メニューからも操作できます。Web UI の **Edit target…** では Target のフォルダ、ファイル名、ファイルフィルターも変更でき、**Edit extra…** では Extras の名前変更や別の Source フォルダへの切り替えができます。Target フォルダや Source フォルダの変更はすぐに反映されます。skillshare は古い場所に作ったリンクを削除し(コピーしたファイルは残ります)、sync します。名前を変更しても Source フォルダは移動せず、その Extras の `source` として記録されます。`agents` と `memory` という名前の Extras は名前を変更できません。
|
||||
|
||||
### `extras remove`
|
||||
|
||||
@@ -332,6 +344,33 @@ extras:
|
||||
|
||||
---
|
||||
|
||||
## ファイルを選ぶ {#choosing-files}
|
||||
|
||||
フォルダの Extras では、Target ごとに `include` と `exclude` で Source の一部のファイルだけを sync できます。
|
||||
|
||||
```yaml
|
||||
extras:
|
||||
- name: docs
|
||||
targets:
|
||||
- path: ~/.claude/docs
|
||||
include: [index.md, learning.md]
|
||||
- path: ~/.cursor/docs
|
||||
mode: copy
|
||||
exclude: ["draft*", images/]
|
||||
```
|
||||
|
||||
パターンは `.gitignore` の構文で、`flatten` や拡張子変換で名前が変わる前の、Source 内でのファイルのパスに対して照合されます。
|
||||
|
||||
- `/` を含まないパターンはどの階層にも一致します。`draft*` は `notes/draft.md` もスキップします。
|
||||
- `/` で終わるパターンはフォルダ全体を対象にします(例: `images/`)。`**` は任意の数のフォルダに一致します。
|
||||
- `include` があると、一致するファイルだけが sync されます。`exclude` はその後に適用されます。
|
||||
|
||||
`include` のパターンがどのファイルにも一致しないとき、`sync` は警告を出します。多くはタイプミスです。
|
||||
|
||||
フィルターに一致しなくなったファイルは、次の sync で `merge` モードならリンクが削除されます。`copy` モードは以前コピーしたファイルを削除しないので、自分で削除してください。フィルターはフォルダ全体をリンクする `symlink` モードや[単一ファイルの Extras](#single-file-extras) では使えません。`extras collect` は Target のフィルターで除外されるファイルをスキップします。
|
||||
|
||||
---
|
||||
|
||||
## 拡張子変換(Extension transforms) {#extension-transforms}
|
||||
|
||||
一部のツールは markdown を読み込みません。Gemini CLI は TOML の commands を、Codex CLI は TOML の agents を期待します。Target の `extension` フィールドは、sync 時に各 Source ファイルを Target のネイティブ形式に変換する外部スクリプトを実行します。
|
||||
|
||||
+2
@@ -732,6 +732,8 @@ extras:
|
||||
| `targets[].mode` | いいえ | `merge`(デフォルト)、`copy`、または `symlink`。`import` は単一ファイルの Extras でのみ使用可 |
|
||||
| `targets[].as` | いいえ | 単一ファイルの Extra における Target 内のファイル名(デフォルト: `file` の名前) |
|
||||
| `targets[].flatten` | いいえ | `true` の場合、サブディレクトリのファイルを Target のルートに直接 Sync する(`symlink` または `file` とは併用不可) |
|
||||
| `targets[].include` | いいえ | これらの `.gitignore` 形式のパターンに一致する Source ファイルだけを Sync する(`symlink` または `file` とは併用不可)。[ファイルを選ぶ](../commands/extras.md#choosing-files)を参照 |
|
||||
| `targets[].exclude` | いいえ | これらのパターンに一致する Source ファイルをスキップする。`include` の後に適用(`symlink` または `file` とは併用不可) |
|
||||
|
||||
`extras_source` は `skillshare init` または最初の `extras init` 実行時に、デフォルトのパス
|
||||
(`~/.config/skillshare/extras/`)に自動的に設定されます。すべての Extra に対してカスタムの場所を
|
||||
|
||||
+42
-3
@@ -77,6 +77,8 @@ wizard는 이름 다음에 **What do you want to sync?**를 묻습니다: **Fold
|
||||
| `--as <filename>` | 모든 target에 쓸 파일 이름 (기본값: `--file` 이름). `--file` 필요 |
|
||||
| `--mode <mode>` | 동기화 mode: `merge` (기본값), `copy`, 또는 `symlink`. `import`는 `--file`과 함께만 사용 가능 |
|
||||
| `--flatten` | 하위 디렉터리의 파일을 target 루트에 바로 동기화 (`symlink` mode 또는 `--file`과 함께 사용 불가) |
|
||||
| `--include <pattern>` | 일치하는 파일만 동기화 ([파일 필터](#choosing-files)), 반복 가능. `symlink` mode 또는 `--file`과 함께 사용 불가 |
|
||||
| `--exclude <pattern>` | 일치하는 파일 건너뛰기 ([파일 필터](#choosing-files)), 반복 가능. `symlink` mode 또는 `--file`과 함께 사용 불가 |
|
||||
| `--source <path>` | 이 extra에 대한 사용자 지정 source 디렉터리 (`extras_source` 및 기본값을 재정의; 프로젝트 모드에서는 프로젝트 루트 기준 상대 경로) |
|
||||
| `--force` | extra가 이미 존재하면 덮어쓰기 |
|
||||
| `--no-tui` | interactive wizard 생략, CLI 플래그만 사용 |
|
||||
@@ -194,11 +196,13 @@ skillshare extras source ~/company-shared/extras
|
||||
|
||||
### Operating on an existing extra
|
||||
|
||||
`extras <name>`으로 target의 sync mode와 flatten 설정을 변경하거나 target을 추가·제거합니다. mode, flatten, target 추가 후 `skillshare sync extras`로 적용하세요. `--remove-target --prune`은 관리 파일을 즉시 복원하거나 제거합니다.
|
||||
`extras <name>`으로 target의 sync mode, flatten 설정, [파일 필터](#choosing-files)를 변경하거나 target을 추가·제거합니다. mode, flatten, 필터, target 추가 후 `skillshare sync extras`로 적용하세요. `--remove-target --prune`은 관리 파일을 즉시 복원하거나 제거합니다.
|
||||
|
||||
```bash
|
||||
skillshare extras <name> --mode <mode> [--target <path>] [-p|-g]
|
||||
skillshare extras <name> --flatten | --no-flatten [--target <path>]
|
||||
skillshare extras <name> --add-include <pattern> | --add-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --remove-include <pattern> | --remove-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --add-target <path> [--as <filename>] [--mode <mode>] [--flatten] [-p|-g]
|
||||
skillshare extras <name> --remove-target <path> [--prune] [-p|-g]
|
||||
skillshare extras <name> --help
|
||||
@@ -211,11 +215,15 @@ skillshare extras <name> --help
|
||||
| `--mode <mode>` | 새 동기화 mode: `merge`, `copy`, 또는 `symlink`. `import`는 [single-file extra](#single-file-extras) 전용 |
|
||||
| `--flatten` | flatten 활성화 (하위 디렉터리 파일을 target 루트에 동기화) |
|
||||
| `--no-flatten` | flatten 비활성화 |
|
||||
| `--add-include <pattern>` | target에 include pattern 추가 (반복 가능) |
|
||||
| `--add-exclude <pattern>` | target에 exclude pattern 추가 (반복 가능) |
|
||||
| `--remove-include <pattern>` | include pattern 제거 |
|
||||
| `--remove-exclude <pattern>` | exclude pattern 제거 |
|
||||
| `--add-target <path>` | extra에 새 target 추가 |
|
||||
| `--as <filename>` | `--add-target`의 target 파일 이름 (single-file extra 전용, 기본값은 `file`) |
|
||||
| `--remove-target <path>` | extra에서 target 제거 (기본적으로 config 전용) |
|
||||
| `--prune` | `--remove-target`과 함께: 해당 target 아래의 skillshare 관리 파일도 삭제. single-file extra에서는 대신 target 파일을 복원 |
|
||||
| `--target <path>` | target 디렉터리 경로 (multi-target extra에서 `--mode`에 필요; 생략 시 `--flatten`/`--no-flatten`은 모든 target에 적용) |
|
||||
| `--target <path>` | target 디렉터리 경로 (multi-target extra에서 `--mode`나 필터 플래그에 필요; 생략 시 `--flatten`/`--no-flatten`은 모든 target에 적용) |
|
||||
| `--project, -p` | 프로젝트 모드 extras 사용 (`.skillshare/`) |
|
||||
| `--global, -g` | 전역 extras 사용 (`~/.config/skillshare/`) |
|
||||
|
||||
@@ -232,6 +240,10 @@ skillshare extras rules --mode copy --target ~/.claude/rules
|
||||
skillshare extras agents --flatten
|
||||
skillshare extras agents --no-flatten
|
||||
|
||||
# Claude에는 파일 두 개만, 다른 곳에서는 초안 건너뛰기
|
||||
skillshare extras docs --target ~/.claude/docs --add-include index.md --add-include learning.md
|
||||
skillshare extras docs --target ~/.cursor/docs --add-exclude "draft*"
|
||||
|
||||
# Add a new target to an existing extra (then sync)
|
||||
skillshare extras rules --add-target ~/.cursor/rules
|
||||
skillshare extras commands --add-target ~/.config/opencode/commands --mode copy
|
||||
@@ -244,7 +256,7 @@ skillshare extras rules --remove-target ~/.cursor/rules
|
||||
skillshare extras rules --remove-target ~/.cursor/rules --prune
|
||||
```
|
||||
|
||||
Web UI(각 target의 mode 드롭다운과 flatten 체크박스)와 TUI(`e` 키)에서도 사용할 수 있습니다.
|
||||
TUI(`e` 키)와 Web UI의 target 메뉴에서도 사용할 수 있습니다. Web UI의 **Edit target…**에서는 target의 폴더, 파일 이름, 파일 필터도 바꿀 수 있고, **Edit extra…**에서는 extra 이름을 바꾸거나 다른 source 폴더를 지정할 수 있습니다. target 폴더나 source 폴더 변경은 바로 적용됩니다. skillshare가 이전 위치에 만든 링크를 제거하고(복사된 파일은 남음) 동기화합니다. 이름을 바꿔도 source 폴더는 그대로이며, extra의 `source`로 기록됩니다. 이름이 `agents`와 `memory`인 extra는 이름을 바꿀 수 없습니다.
|
||||
|
||||
### `extras remove`
|
||||
|
||||
@@ -332,6 +344,33 @@ extras:
|
||||
|
||||
---
|
||||
|
||||
## 파일 고르기 {#choosing-files}
|
||||
|
||||
폴더 extra의 각 target은 `include`와 `exclude`로 source 파일 일부만 동기화할 수 있습니다:
|
||||
|
||||
```yaml
|
||||
extras:
|
||||
- name: docs
|
||||
targets:
|
||||
- path: ~/.claude/docs
|
||||
include: [index.md, learning.md]
|
||||
- path: ~/.cursor/docs
|
||||
mode: copy
|
||||
exclude: ["draft*", images/]
|
||||
```
|
||||
|
||||
pattern은 `.gitignore` 문법을 따르며, `flatten`이나 extension으로 이름이 바뀌기 전의 source 안 파일 경로와 비교합니다:
|
||||
|
||||
- `/`가 없는 pattern은 모든 깊이에서 일치합니다. `draft*`는 `notes/draft.md`도 건너뜁니다.
|
||||
- `/`로 끝나는 pattern은 폴더 전체를 가리킵니다(예: `images/`). `**`는 여러 단계의 폴더와 일치합니다.
|
||||
- `include`가 있으면 일치하는 파일만 동기화됩니다. `exclude`는 그다음에 적용됩니다.
|
||||
|
||||
`include` pattern이 어떤 파일과도 일치하지 않으면 `sync`가 경고합니다. 대개 오타입니다.
|
||||
|
||||
필터가 더 이상 어떤 파일과 일치하지 않으면 `merge` mode에서는 다음 sync 때 그 링크를 제거합니다. `copy` mode는 이전에 복사한 파일을 삭제하지 않으므로 직접 지워야 합니다. 필터는 폴더 전체를 링크하는 `symlink` mode나 [단일 파일 extra](#single-file-extras)에는 사용할 수 없습니다. `extras collect`는 target 필터에서 빠진 파일을 건너뜁니다.
|
||||
|
||||
---
|
||||
|
||||
## Extension transforms
|
||||
|
||||
일부 도구는 markdown을 읽지 않습니다. Gemini CLI는 TOML commands를, Codex CLI는 TOML agents를 요구합니다. target의 `extension` 필드는 동기화 중 각 source 파일을 target의 네이티브 형식으로 변환하는 외부 스크립트를 실행합니다.
|
||||
|
||||
+2
@@ -708,6 +708,8 @@ extras:
|
||||
| `targets[].mode` | No | `merge` (기본값), `copy`, 또는 `symlink`. `import`는 single-file extra 전용 |
|
||||
| `targets[].as` | No | single-file extra에서 target 쪽 파일 이름 (기본값: `file` 이름) |
|
||||
| `targets[].flatten` | No | `true`이면 하위 디렉터리 파일을 Target 루트로 직접 동기화 (`symlink` 또는 `file`과 함께 사용 불가) |
|
||||
| `targets[].include` | 아니요 | 이 `.gitignore` 스타일 pattern과 일치하는 source 파일만 동기화 (`symlink` 또는 `file`과 함께 사용 불가). [파일 고르기](../commands/extras.md#choosing-files) 참고 |
|
||||
| `targets[].exclude` | 아니요 | 이 pattern과 일치하는 source 파일을 건너뜀. `include` 다음에 적용 (`symlink` 또는 `file`과 함께 사용 불가) |
|
||||
|
||||
`extras_source`는 `skillshare init` 또는 첫 `extras init` 시 기본 경로(`~/.config/skillshare/extras/`)로 자동 채워집니다. 모든 extra에 custom 위치를 사용하려면 이 값을 재정의하세요.
|
||||
|
||||
|
||||
+42
-3
@@ -77,6 +77,8 @@ skillshare extras init <name> --file <filename> [--as <filename>] --target <path
|
||||
| `--as <filename>` | 写入每个 target 的文件名(默认为 `--file` 的名称)。需要搭配 `--file` |
|
||||
| `--mode <mode>` | Sync mode:`merge`(默认)、`copy` 或 `symlink`;`import` 仅可搭配 `--file` |
|
||||
| `--flatten` | 将子目录中的文件直接同步到 target 根目录(不能与 `symlink` mode 或 `--file` 一起使用) |
|
||||
| `--include <pattern>` | 只同步匹配的文件([文件筛选](#choosing-files)),可重复。不能与 `symlink` mode 或 `--file` 一起使用 |
|
||||
| `--exclude <pattern>` | 跳过匹配的文件([文件筛选](#choosing-files)),可重复。不能与 `symlink` mode 或 `--file` 一起使用 |
|
||||
| `--source <path>` | 该 extra 的自定义 source 目录(覆盖 `extras_source` 和默认值;project mode 下为相对于项目根目录的路径) |
|
||||
| `--force` | 如果 extra 已存在则覆盖 |
|
||||
| `--no-tui` | 跳过交互式向导,仅使用 CLI flags |
|
||||
@@ -194,11 +196,13 @@ skillshare extras source ~/company-shared/extras
|
||||
|
||||
### 操作一个已存在的 extra
|
||||
|
||||
通过 `extras <name>` 更改 target 的 sync mode、flatten 设置,或添加/移除 target。更改 mode、flatten 或添加 target 后,请运行 `skillshare sync extras` 应用。`--remove-target --prune` 也会立即还原或移除受管理的文件。
|
||||
通过 `extras <name>` 更改 target 的 sync mode、flatten 设置或[文件筛选](#choosing-files),或添加/移除 target。更改 mode、flatten、筛选或添加 target 后,请运行 `skillshare sync extras` 应用。`--remove-target --prune` 也会立即还原或移除受管理的文件。
|
||||
|
||||
```bash
|
||||
skillshare extras <name> --mode <mode> [--target <path>] [-p|-g]
|
||||
skillshare extras <name> --flatten | --no-flatten [--target <path>]
|
||||
skillshare extras <name> --add-include <pattern> | --add-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --remove-include <pattern> | --remove-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --add-target <path> [--as <filename>] [--mode <mode>] [--flatten] [-p|-g]
|
||||
skillshare extras <name> --remove-target <path> [--prune] [-p|-g]
|
||||
skillshare extras <name> --help
|
||||
@@ -211,11 +215,15 @@ skillshare extras <name> --help
|
||||
| `--mode <mode>` | 新的 sync mode:`merge`、`copy` 或 `symlink`;`import` 仅用于[单文件 extras](#single-file-extras) |
|
||||
| `--flatten` | 启用 flatten(将子目录文件同步到 target 根目录) |
|
||||
| `--no-flatten` | 禁用 flatten |
|
||||
| `--add-include <pattern>` | 为 target 添加 include pattern(可重复) |
|
||||
| `--add-exclude <pattern>` | 为 target 添加 exclude pattern(可重复) |
|
||||
| `--remove-include <pattern>` | 移除一个 include pattern |
|
||||
| `--remove-exclude <pattern>` | 移除一个 exclude pattern |
|
||||
| `--add-target <path>` | 为该 extra 添加一个新 target |
|
||||
| `--as <filename>` | `--add-target` 的 target 文件名(仅限单文件 extra;默认为 `file`) |
|
||||
| `--remove-target <path>` | 从该 extra 中移除一个 target(默认仅修改配置) |
|
||||
| `--prune` | 与 `--remove-target` 一起使用:同时删除该 target 下由 skillshare 管理的文件。对单文件 extra 则改为还原 target 文件 |
|
||||
| `--target <path>` | Target 目录路径(对多 target 的 extra 使用 `--mode` 时必填;省略时 `--flatten`/`--no-flatten` 会应用于所有 target) |
|
||||
| `--target <path>` | Target 目录路径(对多 target 的 extra 使用 `--mode` 或筛选标志时必填;省略时 `--flatten`/`--no-flatten` 会应用于所有 target) |
|
||||
| `--project, -p` | 使用 project-mode extras(`.skillshare/`) |
|
||||
| `--global, -g` | 使用 global extras(`~/.config/skillshare/`) |
|
||||
|
||||
@@ -232,6 +240,10 @@ skillshare extras rules --mode copy --target ~/.claude/rules
|
||||
skillshare extras agents --flatten
|
||||
skillshare extras agents --no-flatten
|
||||
|
||||
# 只同步两个文件到 Claude,其他地方跳过草稿
|
||||
skillshare extras docs --target ~/.claude/docs --add-include index.md --add-include learning.md
|
||||
skillshare extras docs --target ~/.cursor/docs --add-exclude "draft*"
|
||||
|
||||
# 为已存在的 extra 添加一个新 target(然后 sync)
|
||||
skillshare extras rules --add-target ~/.cursor/rules
|
||||
skillshare extras commands --add-target ~/.config/opencode/commands --mode copy
|
||||
@@ -244,7 +256,7 @@ skillshare extras rules --remove-target ~/.cursor/rules
|
||||
skillshare extras rules --remove-target ~/.cursor/rules --prune
|
||||
```
|
||||
|
||||
也可以通过 TUI(`e` 键)和 Web UI(每个 target 上的 mode 下拉菜单和 flatten 复选框)进行操作。
|
||||
也可以通过 TUI(`e` 键)和 Web UI 的 target 菜单进行操作。在 Web UI 中,**Edit target…** 还能修改 target 的文件夹、文件名和文件筛选,**Edit extra…** 可以重命名 extra 或改用另一个 source 文件夹。修改 target 文件夹或 source 文件夹会立即生效:skillshare 会移除它在旧位置创建的链接(复制的文件会保留),然后同步。重命名不会移动 source 文件夹,而是把它记为该 extra 的 `source`。名为 `agents` 和 `memory` 的 extra 不能重命名。
|
||||
|
||||
### `extras remove`
|
||||
|
||||
@@ -332,6 +344,33 @@ extras:
|
||||
|
||||
---
|
||||
|
||||
## 选择文件 {#choosing-files}
|
||||
|
||||
文件夹 extra 的每个 target 都可以用 `include` 和 `exclude` 只同步部分 source 文件:
|
||||
|
||||
```yaml
|
||||
extras:
|
||||
- name: docs
|
||||
targets:
|
||||
- path: ~/.claude/docs
|
||||
include: [index.md, learning.md]
|
||||
- path: ~/.cursor/docs
|
||||
mode: copy
|
||||
exclude: ["draft*", images/]
|
||||
```
|
||||
|
||||
Pattern 使用 `.gitignore` 语法,匹配的是文件在 source 中的路径,在 `flatten` 或 extension 改名之前:
|
||||
|
||||
- 不含 `/` 的 pattern 会匹配任意层级:`draft*` 也会跳过 `notes/draft.md`。
|
||||
- 以 `/` 结尾的 pattern 覆盖整个文件夹,例如 `images/`。`**` 可匹配任意层文件夹。
|
||||
- 有 `include` 时只同步匹配的文件。`exclude` 在其之后应用。
|
||||
|
||||
某个 `include` pattern 没有匹配到任何文件时,`sync` 会发出警告,通常意味着拼写错误。
|
||||
|
||||
筛选不再匹配某个文件时,下次 sync 会在 `merge` mode 下移除它的链接。`copy` mode 不会删除之前复制过去的文件,需要自行删除。筛选不能与链接整个文件夹的 `symlink` mode 一起使用,也不能用于[单文件 extra](#single-file-extras)。`extras collect` 会跳过被 target 筛选排除的文件。
|
||||
|
||||
---
|
||||
|
||||
## Extension 转换 {#extension-transforms}
|
||||
|
||||
有些工具不读取 markdown。Gemini CLI 需要 TOML commands;Codex CLI 需要 TOML agents。target 上的 `extension` 字段会在 sync 期间运行一个外部脚本,将每个 source 文件转换为该 target 的原生格式。
|
||||
|
||||
+2
@@ -703,6 +703,8 @@ extras:
|
||||
| `targets[].mode` | 否 | `merge`(默认)、`copy` 或 `symlink`;`import` 仅用于单文件 extras |
|
||||
| `targets[].as` | 否 | 单文件 extra 在 target 中的文件名(默认:`file` 的名称) |
|
||||
| `targets[].flatten` | 否 | 为 `true` 时,将子目录文件直接 sync 到 Target 根目录(不能与 `symlink` 或 `file` 同时使用) |
|
||||
| `targets[].include` | 否 | 只同步匹配这些 `.gitignore` 风格 pattern 的 source 文件(不能与 `symlink` 或 `file` 同时使用)。参见[选择文件](../commands/extras.md#choosing-files) |
|
||||
| `targets[].exclude` | 否 | 跳过匹配这些 pattern 的 source 文件,在 `include` 之后应用(不能与 `symlink` 或 `file` 同时使用) |
|
||||
|
||||
`extras_source` 会在 `skillshare init` 或首次 `extras init` 时自动填充为默认路径(`~/.config/skillshare/extras/`)。可覆盖它以对所有 extras 使用自定义位置。
|
||||
|
||||
|
||||
+42
-3
@@ -77,6 +77,8 @@ skillshare extras init <name> --file <filename> [--as <filename>] --target <path
|
||||
| `--as <filename>` | 寫入每個 target 時使用的檔名(預設為 `--file` 的名稱)。需要搭配 `--file` |
|
||||
| `--mode <mode>` | Sync 模式:`merge`(預設)、`copy`,或 `symlink`;`import` 僅限搭配 `--file` |
|
||||
| `--flatten` | 將子目錄中的檔案直接同步到 target 根目錄(無法與 `symlink` 模式或 `--file` 一起使用) |
|
||||
| `--include <pattern>` | 只同步符合的檔案([檔案篩選](#choosing-files)),可重複指定。不能與 `symlink` 模式或 `--file` 一起使用 |
|
||||
| `--exclude <pattern>` | 略過符合的檔案([檔案篩選](#choosing-files)),可重複指定。不能與 `symlink` 模式或 `--file` 一起使用 |
|
||||
| `--source <path>` | 此 extra 的自訂 source 目錄(會覆寫 `extras_source` 與預設值;project mode 中為相對於專案根目錄的路徑) |
|
||||
| `--force` | 若 extra 已存在則覆寫 |
|
||||
| `--no-tui` | 略過互動式精靈,只使用 CLI 旗標 |
|
||||
@@ -194,11 +196,13 @@ skillshare extras source ~/company-shared/extras
|
||||
|
||||
### Operating on an existing extra
|
||||
|
||||
透過 `extras <name>` 變更 target 的 sync 模式、flatten 設定,或新增/移除 target。變更模式、flatten 或新增 target 後,請執行 `skillshare sync extras` 套用。`--remove-target --prune` 也會立即還原或移除受管理的檔案。
|
||||
透過 `extras <name>` 變更 target 的 sync 模式、flatten 設定或[檔案篩選](#choosing-files),或新增/移除 target。變更模式、flatten、篩選或新增 target 後,請執行 `skillshare sync extras` 套用。`--remove-target --prune` 也會立即還原或移除受管理的檔案。
|
||||
|
||||
```bash
|
||||
skillshare extras <name> --mode <mode> [--target <path>] [-p|-g]
|
||||
skillshare extras <name> --flatten | --no-flatten [--target <path>]
|
||||
skillshare extras <name> --add-include <pattern> | --add-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --remove-include <pattern> | --remove-exclude <pattern> [--target <path>]
|
||||
skillshare extras <name> --add-target <path> [--as <filename>] [--mode <mode>] [--flatten] [-p|-g]
|
||||
skillshare extras <name> --remove-target <path> [--prune] [-p|-g]
|
||||
skillshare extras <name> --help
|
||||
@@ -211,11 +215,15 @@ skillshare extras <name> --help
|
||||
| `--mode <mode>` | 新的 sync 模式:`merge`、`copy`,或 `symlink`;`import` 僅限[單一檔案 extra](#single-file-extras) |
|
||||
| `--flatten` | 啟用 flatten(將子目錄檔案同步到 target 根目錄) |
|
||||
| `--no-flatten` | 停用 flatten |
|
||||
| `--add-include <pattern>` | 為 target 加上 include pattern(可重複指定) |
|
||||
| `--add-exclude <pattern>` | 為 target 加上 exclude pattern(可重複指定) |
|
||||
| `--remove-include <pattern>` | 移除一個 include pattern |
|
||||
| `--remove-exclude <pattern>` | 移除一個 exclude pattern |
|
||||
| `--add-target <path>` | 為此 extra 新增一個 target |
|
||||
| `--as <filename>` | `--add-target` 的 target 檔名(僅限單一檔案 extra;預設為 `file`) |
|
||||
| `--remove-target <path>` | 從此 extra 移除一個 target(預設僅變更設定) |
|
||||
| `--prune` | 搭配 `--remove-target` 使用:同時刪除該 target 底下由 skillshare 管理的檔案。若是單一檔案 extra,則會改為還原 target 檔案 |
|
||||
| `--target <path>` | Target 目錄路徑(多 target 的 extra 使用 `--mode` 時為必填;省略時 `--flatten`/`--no-flatten` 會套用到所有 target) |
|
||||
| `--target <path>` | Target 目錄路徑(多 target 的 extra 使用 `--mode` 或篩選旗標時為必填;省略時 `--flatten`/`--no-flatten` 會套用到所有 target) |
|
||||
| `--project, -p` | 使用 project mode 的 extras(`.skillshare/`) |
|
||||
| `--global, -g` | 使用 global 的 extras(`~/.config/skillshare/`) |
|
||||
|
||||
@@ -232,6 +240,10 @@ skillshare extras rules --mode copy --target ~/.claude/rules
|
||||
skillshare extras agents --flatten
|
||||
skillshare extras agents --no-flatten
|
||||
|
||||
# 只同步兩個檔案到 Claude,其他地方略過草稿
|
||||
skillshare extras docs --target ~/.claude/docs --add-include index.md --add-include learning.md
|
||||
skillshare extras docs --target ~/.cursor/docs --add-exclude "draft*"
|
||||
|
||||
# 為既有的 extra 新增一個 target(之後再 sync)
|
||||
skillshare extras rules --add-target ~/.cursor/rules
|
||||
skillshare extras commands --add-target ~/.config/opencode/commands --mode copy
|
||||
@@ -244,7 +256,7 @@ skillshare extras rules --remove-target ~/.cursor/rules
|
||||
skillshare extras rules --remove-target ~/.cursor/rules --prune
|
||||
```
|
||||
|
||||
也可以透過 TUI(`e` 鍵)以及 Web UI(每個 target 上的模式下拉選單與 flatten 核取方塊)操作。
|
||||
也可以透過 TUI(`e` 鍵)以及 Web UI 的 target 選單操作。在 Web UI 中,**Edit target…** 還能改 target 的資料夾、檔名與檔案篩選,**Edit extra…** 可以重新命名 extra 或改用另一個 source 資料夾。改 target 資料夾或 source 資料夾會立即生效:skillshare 會移除它在舊位置建立的連結(複製的檔案會留著),然後同步。重新命名不會搬動 source 資料夾,而是把它記成這個 extra 的 `source`。名為 `agents` 與 `memory` 的 extra 不能重新命名。
|
||||
|
||||
### `extras remove`
|
||||
|
||||
@@ -332,6 +344,33 @@ extras:
|
||||
|
||||
---
|
||||
|
||||
## 挑選檔案 {#choosing-files}
|
||||
|
||||
資料夾 extra 的每個 target 都能用 `include` 與 `exclude` 只同步部分 source 檔案:
|
||||
|
||||
```yaml
|
||||
extras:
|
||||
- name: docs
|
||||
targets:
|
||||
- path: ~/.claude/docs
|
||||
include: [index.md, learning.md]
|
||||
- path: ~/.cursor/docs
|
||||
mode: copy
|
||||
exclude: ["draft*", images/]
|
||||
```
|
||||
|
||||
Pattern 使用 `.gitignore` 語法,比對的是檔案在 source 裡的路徑,在 `flatten` 或 extension 改名之前:
|
||||
|
||||
- 不含 `/` 的 pattern 會比對任何層級:`draft*` 也會略過 `notes/draft.md`。
|
||||
- 以 `/` 結尾的 pattern 涵蓋整個資料夾,例如 `images/`。`**` 可比對任意層資料夾。
|
||||
- 有 `include` 時只同步符合的檔案。`exclude` 在它之後套用。
|
||||
|
||||
某個 `include` pattern 沒有對到任何檔案時,`sync` 會發出警告,通常代表打錯字。
|
||||
|
||||
篩選不再符合某個檔案時,下次 sync 會在 `merge` 模式移除它的連結。`copy` 模式不會刪除之前複製過去的檔案,需要自行刪除。篩選不能與連結整個資料夾的 `symlink` 模式一起使用,也不能用在[單一檔案 extra](#single-file-extras)。`extras collect` 會略過被 target 篩選排除的檔案。
|
||||
|
||||
---
|
||||
|
||||
## Extension transforms
|
||||
|
||||
有些工具不讀取 markdown。Gemini CLI 需要 TOML 格式的 commands;Codex CLI 需要 TOML 格式的 agents。target 上的 `extension` 欄位會在同步時執行外部腳本,把每個 source 檔案轉換成該 target 的原生格式。
|
||||
|
||||
+2
@@ -703,6 +703,8 @@ extras:
|
||||
| `targets[].mode` | 否 | `merge`(預設)、`copy` 或 `symlink`;`import` 僅限單一檔案 Extra |
|
||||
| `targets[].as` | 否 | 單一檔案 Extra 在 Target 中的檔名(預設:`file` 的名稱) |
|
||||
| `targets[].flatten` | 否 | 為 `true` 時,把子目錄檔案直接同步到 Target 根目錄(不能與 `symlink` 或 `file` 併用) |
|
||||
| `targets[].include` | 否 | 只同步符合這些 `.gitignore` 風格 pattern 的 source 檔案(不能與 `symlink` 或 `file` 併用)。請見[挑選檔案](../commands/extras.md#choosing-files) |
|
||||
| `targets[].exclude` | 否 | 略過符合這些 pattern 的 source 檔案,在 `include` 之後套用(不能與 `symlink` 或 `file` 併用) |
|
||||
|
||||
`extras_source` 會在執行 `skillshare init` 或第一次 `extras init` 時,自動填入預設路徑(`~/.config/skillshare/extras/`)。可覆寫它,讓所有 Extras 使用自訂位置。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user