From 551a1546df692ca7a2391c9dfa0bef2615eebfbc Mon Sep 17 00:00:00 2001 From: Willie Date: Sun, 11 Oct 2026 21:21:31 +0800 Subject: [PATCH] fix(config): keep the comments of config.yaml when a command writes it (#526) Every writer re-encoded the in-memory struct, so a command such as target --mode copy dropped every comment. marshalConfig now takes the file being replaced and copies its comments onto the keys that are still present; list items are matched by name, and a read error fails the save. registry.yaml goes the same way. Fixes #525 --- internal/config/config.go | 8 +- internal/config/format.go | 133 ++++++++++++++++++++++++++++++++- internal/config/format_test.go | 113 +++++++++++++++++++++++++++- internal/config/project.go | 4 +- internal/config/registry.go | 7 +- 5 files changed, 252 insertions(+), 13 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index e8fa8974c..35d1daf8f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -744,11 +744,11 @@ func Load() (*Config, error) { // Migrate legacy flat target fields to skills: sub-key (one-time, persisted immediately) if migrateTargetConfigs(cfg.Targets) { - if data, err := marshalConfig(&cfg, schemaComment); err == nil { + if migrated, err := marshalConfig(&cfg, schemaComment, data); err == nil { // Write a symlinked config's target so the link survives. dest := utils.ResolveSymlink(path) tmpPath := dest + ".tmp" - if writeErr := os.WriteFile(tmpPath, data, 0644); writeErr == nil { + if writeErr := os.WriteFile(tmpPath, migrated, 0644); writeErr == nil { os.Rename(tmpPath, dest) } } @@ -822,7 +822,7 @@ func (c *Config) Save() error { if c.PreserveTildeOnSave { payload = payload.cloneForSave() } - data, err := marshalConfig(payload, schemaComment) + data, err := marshalConfigFile(path, payload, schemaComment) if err != nil { return fmt.Errorf("failed to marshal config: %w", err) } @@ -954,7 +954,7 @@ func migrateSkillsToRegistry(configPath string) error { return nil } delete(raw, "skills") - cleaned, err := marshalConfig(raw, schemaComment) + cleaned, err := marshalConfig(raw, schemaComment, data) if err != nil { return nil } diff --git a/internal/config/format.go b/internal/config/format.go index a426f7634..b04f53ada 100644 --- a/internal/config/format.go +++ b/internal/config/format.go @@ -2,7 +2,10 @@ package config import ( "bytes" + "errors" + "os" "sort" + "strings" "gopkg.in/yaml.v3" @@ -20,13 +23,16 @@ var configSections = []string{ // marshalConfig encodes v the way the dashboard's Beautify lays out a config: // the schema header first, top-level sections in configSections order (unknown // keys last, in their encoded order), and a blank line between sections. -func marshalConfig(v any, header []byte) ([]byte, error) { +// existing is the file being replaced, or nil; its comments are kept on every +// key that is still present. +func marshalConfig(v any, header []byte, existing []byte) ([]byte, error) { var doc yaml.Node if err := doc.Encode(v); err != nil { return nil, err } if doc.Kind == yaml.MappingNode { sortSections(&doc) + keepComments(&doc, existing) } data, err := utils.MarshalYAML(&doc) if err != nil { @@ -64,6 +70,131 @@ func sortSections(m *yaml.Node) { } } +// marshalConfigFile encodes v to replace the file at path, keeping that file's +// comments. A file that cannot be read for any reason other than being absent +// is an error: writing over it would silently drop its comments. +func marshalConfigFile(path string, v any, header []byte) ([]byte, error) { + existing, err := os.ReadFile(path) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, err + } + return marshalConfig(v, header, existing) +} + +// keepComments copies the comments of existing onto the same keys of m. A key +// that was removed loses its comments; a key that was added has none. Comments +// m already carries (raw sections such as hooks) win, and the schema directive +// is dropped, since marshalConfig writes its own header. +func keepComments(m *yaml.Node, existing []byte) { + var old yaml.Node + if yaml.Unmarshal(existing, &old) != nil || len(old.Content) == 0 || old.Content[0].Kind != yaml.MappingNode { + return + } + top := old.Content[0] + top.HeadComment = withoutSchemaDirective(joinComments(old.HeadComment, top.HeadComment)) + for i := 0; i < len(top.Content); i += 2 { + top.Content[i].HeadComment = withoutSchemaDirective(top.Content[i].HeadComment) + } + top.FootComment = joinComments(top.FootComment, old.FootComment) + copyComments(top, m) +} + +func copyComments(old, cur *yaml.Node) { + // A target that changed between `- claude` and `- name: claude` keeps its + // line comment on the name, the only place a block mapping can show one. + if old.Kind != cur.Kind { + if o, c := nameScalar(old), nameScalar(cur); o != nil && c != nil && c.LineComment == "" { + c.LineComment = o.LineComment + } + } + if cur.HeadComment == "" { + cur.HeadComment = old.HeadComment + } + if cur.LineComment == "" { + cur.LineComment = old.LineComment + } + if cur.FootComment == "" { + cur.FootComment = old.FootComment + } + switch { + case old.Kind == yaml.MappingNode && cur.Kind == yaml.MappingNode: + for i := 0; i+1 < len(old.Content); i += 2 { + for j := 0; j+1 < len(cur.Content); j += 2 { + if cur.Content[j].Value == old.Content[i].Value { + copyComments(old.Content[i], cur.Content[j]) + copyComments(old.Content[i+1], cur.Content[j+1]) + break + } + } + } + case old.Kind == yaml.SequenceNode && cur.Kind == yaml.SequenceNode: + used := make([]bool, len(cur.Content)) + for _, item := range old.Content { + for j, c := range cur.Content { + if !used[j] && itemIdentity(item) != "" && itemIdentity(item) == itemIdentity(c) { + used[j] = true + copyComments(item, c) + break + } + } + } + } +} + +// itemIdentity names a sequence item: its value for a scalar, and for a +// mapping its `name` value (so `- claude` and `- name: claude` are the same +// target) or, failing that, its first scalar key and value. Items without one +// ("" for a nested list) never match. +func itemIdentity(n *yaml.Node) string { + switch n.Kind { + case yaml.ScalarNode: + return n.Value + case yaml.MappingNode: + for i := 0; i+1 < len(n.Content); i += 2 { + if n.Content[i].Value == "name" && n.Content[i+1].Kind == yaml.ScalarNode { + return n.Content[i+1].Value + } + } + for i := 0; i+1 < len(n.Content); i += 2 { + if n.Content[i+1].Kind == yaml.ScalarNode { + return n.Content[i].Value + "=" + n.Content[i+1].Value + } + } + } + return "" +} + +// nameScalar is the node a sequence item's identity comes from: the scalar +// itself, or a mapping's `name` value. +func nameScalar(n *yaml.Node) *yaml.Node { + if n.Kind == yaml.ScalarNode { + return n + } + for i := 0; n.Kind == yaml.MappingNode && i+1 < len(n.Content); i += 2 { + if n.Content[i].Value == "name" && n.Content[i+1].Kind == yaml.ScalarNode { + return n.Content[i+1] + } + } + return nil +} + +func joinComments(a, b string) string { + if a == "" || b == "" { + return a + b + } + return a + "\n" + b +} + +func withoutSchemaDirective(comment string) string { + var kept []string + for _, line := range strings.Split(comment, "\n") { + if !strings.HasPrefix(line, "# yaml-language-server:") { + kept = append(kept, line) + } + } + return strings.TrimSpace(strings.Join(kept, "\n")) +} + func aliasesFollowAnchors(n *yaml.Node, anchors map[string]bool) bool { if n.Kind == yaml.AliasNode && !anchors[n.Value] { return false diff --git a/internal/config/format_test.go b/internal/config/format_test.go index faa41fabe..cecb52a87 100644 --- a/internal/config/format_test.go +++ b/internal/config/format_test.go @@ -90,7 +90,7 @@ func TestMarshalConfig_KeepsOrderWhenSortingWouldBreakAnAlias(t *testing.T) { if err := yaml.Unmarshal([]byte(src), &cfg); err != nil { t.Fatal(err) } - data, err := marshalConfig(&cfg, schemaComment) + data, err := marshalConfig(&cfg, schemaComment, nil) if err != nil { t.Fatal(err) } @@ -99,3 +99,114 @@ func TestMarshalConfig_KeepsOrderWhenSortingWouldBreakAnAlias(t *testing.T) { t.Errorf("saved config does not load: %v\n%s", err, data) } } + +func TestSave_KeepsCommentsOfTheExistingFile(t *testing.T) { + cfgPath := filepath.Join(t.TempDir(), "config.yaml") + t.Setenv("SKILLSHARE_CONFIG", cfgPath) + src := string(schemaComment) + ` +# BEGIN HUMAN-ONLY (generated) +sources: + skills: /src/skills # where skills live +# END HUMAN-ONLY + +mode: merge + +targets: + claude: + skills: + path: /home/u/.claude/skills +` + if err := os.WriteFile(cfgPath, []byte(src), 0644); err != nil { + t.Fatal(err) + } + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + cfg.Mode = "copy" + if err := cfg.Save(); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(cfgPath) + if err != nil { + t.Fatal(err) + } + got := string(data) + if strings.Count(got, "yaml-language-server") != 1 { + t.Errorf("schema header should appear once:\n%s", got) + } + if !strings.Contains(got, "mode: copy") { + t.Errorf("changed value missing:\n%s", got) + } + for _, want := range []string{"# BEGIN HUMAN-ONLY (generated)\nsources:", "/src/skills # where skills live", "# END HUMAN-ONLY\n\nmode: copy"} { + if !strings.Contains(got, want) { + t.Errorf("comment %q lost:\n%s", want, got) + } + } +} + +func TestMarshalConfig_CommentOnReorderedKeyFollowsIt(t *testing.T) { + existing := []byte(string(schemaComment) + "\n# kept on mode\nmode: merge\nsources:\n skills: /src\n") + cfg := Config{Mode: "merge", Sources: GlobalSources{Skills: "/src"}} + data, err := marshalConfig(&cfg, schemaComment, existing) + if err != nil { + t.Fatal(err) + } + got := string(data) + if strings.Count(got, "yaml-language-server") != 1 || !strings.Contains(got, "# kept on mode\nmode: merge") { + t.Errorf("comment should move with the key, header once:\n%s", got) + } +} + +func TestMarshalConfig_CommentOnListItemSurvivesListEdit(t *testing.T) { + existing := []byte("ignore:\n - tmp # scratch\n - build\n") + cfg := Config{Ignore: []string{"build", "tmp"}} + data, err := marshalConfig(&cfg, schemaComment, existing) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), "- tmp # scratch") { + t.Errorf("item comment lost:\n%s", data) + } +} + +func TestMarshalConfig_CommentOnRemovedKeyIsDropped(t *testing.T) { + existing := []byte("# gone with the key\nmode: merge\nsources:\n skills: /src\n") + cfg := Config{Sources: GlobalSources{Skills: "/src"}} + data, err := marshalConfig(&cfg, schemaComment, existing) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), "gone with the key") { + t.Errorf("comment of a removed key should not survive:\n%s", data) + } +} + +func TestMarshalConfig_ListOfMappingsMatchesByName(t *testing.T) { + existing := []byte("targets:\n - files:\n - a\n name: first # one\n - files:\n - b\n name: second # two\n") + var cfg ProjectConfig + if err := yaml.Unmarshal(existing, &cfg); err != nil { + t.Fatal(err) + } + cfg.Targets = cfg.Targets[1:] + data, err := marshalConfig(&cfg, projectSchemaComment, existing) + if err != nil { + t.Fatal(err) + } + got := string(data) + if strings.Contains(got, "# one") || !strings.Contains(got, "second # two") { + t.Errorf("comments should follow the target named in the item:\n%s", got) + } +} + +func TestMarshalConfig_ScalarAndObjectTargetShareComments(t *testing.T) { + existing := []byte("targets:\n - claude # mine\n") + cfg := ProjectConfig{Targets: []ProjectTargetEntry{{Name: "claude", Files: []string{"a"}}}} + data, err := marshalConfig(&cfg, projectSchemaComment, existing) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), "# mine") { + t.Errorf("comment should survive the switch to object form:\n%s", data) + } +} diff --git a/internal/config/project.go b/internal/config/project.go index 91142b805..25eae8369 100644 --- a/internal/config/project.go +++ b/internal/config/project.go @@ -462,7 +462,7 @@ func LoadProject(projectRoot string) (*ProjectConfig, error) { } } if migrated { - if mdata, merr := marshalConfig(&cfg, projectSchemaComment); merr == nil { + if mdata, merr := marshalConfig(&cfg, projectSchemaComment, data); merr == nil { // Write a symlinked config's target so the link survives. A link out of // the project is left alone; the next save reports it. if dest, err := utils.ConfigWritePath(path, true); err == nil { @@ -503,7 +503,7 @@ func (c *ProjectConfig) SaveIn(projectDir string) error { return fmt.Errorf("failed to create project config directory: %w", err) } - data, err := marshalConfig(c, projectSchemaComment) + data, err := marshalConfigFile(path, c, projectSchemaComment) if err != nil { return fmt.Errorf("failed to marshal project config: %w", err) } diff --git a/internal/config/registry.go b/internal/config/registry.go index 279e71379..05df80847 100644 --- a/internal/config/registry.go +++ b/internal/config/registry.go @@ -7,7 +7,6 @@ import ( "strings" "gopkg.in/yaml.v3" - "skillshare/internal/utils" ) const registryFileName = "registry.yaml" @@ -114,14 +113,12 @@ func (r *Registry) Save(dir string) error { return fmt.Errorf("failed to create registry directory: %w", err) } - data, err := utils.MarshalYAML(r) + path := RegistryPath(dir) + data, err := marshalConfigFile(path, r, registrySchemaComment) if err != nil { return fmt.Errorf("failed to marshal registry: %w", err) } - data = append(registrySchemaComment, data...) - - path := RegistryPath(dir) if err := os.WriteFile(path, data, 0644); err != nil { return fmt.Errorf("failed to write registry: %w", err) }