This repository was archived by the owner on Aug 22, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanifest.go
More file actions
375 lines (341 loc) · 9.95 KB
/
Copy pathmanifest.go
File metadata and controls
375 lines (341 loc) · 9.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
)
// ── types ────────────────────────────────────────────────────────────
type MirrorEntry struct {
From string `json:"from"`
To string `json:"to"`
Exclude []string `json:"exclude,omitempty"`
}
type Manifest struct {
Version int `json:"version"`
Comment string `json:"comment,omitempty"`
Directories []DirEntry `json:"directories"`
Symlinks []SymlinkEntry `json:"symlinks,omitempty"`
Mirrors []MirrorEntry `json:"mirrors,omitempty"`
Skills []SkillEntry `json:"skills"`
}
type DirEntry struct {
Name string `json:"name"`
Path string `json:"path"`
Comment string `json:"comment,omitempty"`
}
type SymlinkEntry struct {
From string `json:"from"`
To string `json:"to"`
}
type SkillEntry struct {
Name string `json:"name"`
Target string `json:"target"`
Source SourceEntry `json:"source"`
Note string `json:"note,omitempty"`
extra map[string]json.RawMessage
}
func (s *SkillEntry) UnmarshalJSON(data []byte) error {
type alias SkillEntry
if err := json.Unmarshal(data, (*alias)(s)); err != nil {
return err
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
for k, v := range raw {
switch k {
case "name", "target", "source", "note":
continue
default:
if s.extra == nil {
s.extra = make(map[string]json.RawMessage)
}
s.extra[k] = v
}
}
return nil
}
func (s SkillEntry) MarshalJSON() ([]byte, error) {
type alias SkillEntry
base, err := json.Marshal(alias(s))
if err != nil {
return nil, err
}
if len(s.extra) == 0 {
return base, nil
}
var merged map[string]json.RawMessage
if err := json.Unmarshal(base, &merged); err != nil {
return nil, err
}
for k, v := range s.extra {
merged[k] = v
}
return json.Marshal(merged)
}
type SourceEntry struct {
Type string `json:"type,omitempty"`
Files map[string]string `json:"files,omitempty"`
Repo string `json:"repo"`
Ref string `json:"ref"`
Path string `json:"path,omitempty"`
extra map[string]json.RawMessage
}
func (s *SourceEntry) UnmarshalJSON(data []byte) error {
type alias SourceEntry
if err := json.Unmarshal(data, (*alias)(s)); err != nil {
return err
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
for k, v := range raw {
switch k {
case "type", "files", "repo", "ref", "path":
continue
default:
if s.extra == nil {
s.extra = make(map[string]json.RawMessage)
}
s.extra[k] = v
}
}
return nil
}
func (s SourceEntry) MarshalJSON() ([]byte, error) {
type alias SourceEntry
base, err := json.Marshal(alias(s))
if err != nil {
return nil, err
}
if len(s.extra) == 0 {
return base, nil
}
var merged map[string]json.RawMessage
if err := json.Unmarshal(base, &merged); err != nil {
return nil, err
}
for k, v := range s.extra {
merged[k] = v
}
return json.Marshal(merged)
}
// ── lock ─────────────────────────────────────────────────────────────
type LockFile struct {
Version int `json:"version"`
Skills map[string]LockSkill `json:"skills"`
}
type LockSkill struct {
Commit string `json:"commit"`
Path string `json:"path"`
SourceHash string `json:"sourceHash,omitempty"`
ContentHash string `json:"contentHash,omitempty"`
}
// ── path helpers ─────────────────────────────────────────────────────
const specialTargetOMP = "omp"
func expandPath(p string) string {
if len(p) > 1 && p[:2] == "~/" {
home, _ := os.UserHomeDir()
return filepath.Join(home, p[2:])
}
return p
}
func resolveOMPUserSkillsDir() string {
if out, err := exec.Command("omp", "config", "path").Output(); err == nil {
agentDir := strings.TrimSpace(string(out))
if agentDir != "" {
return filepath.Join(expandPath(agentDir), "skills")
}
}
configDir := ".omp"
if v := strings.TrimSpace(os.Getenv("PI_CONFIG_DIR")); v != "" {
configDir = v
}
home, _ := os.UserHomeDir()
return filepath.Join(home, configDir, "agent", "skills")
}
func targetExists(dirName string, dirs []DirEntry) bool {
if dirName == specialTargetOMP {
return true
}
for _, d := range dirs {
if d.Name == dirName {
return true
}
}
return false
}
func resolveTargetPath(dirName string, dirs []DirEntry) string {
if dirName == specialTargetOMP {
return resolveOMPUserSkillsDir()
}
for _, d := range dirs {
if d.Name == dirName {
return expandPath(d.Path)
}
}
return ""
}
// ── I/O ──────────────────────────────────────────────────────────────
// atomicWriteFile writes data to path atomically by writing to a temp file
// in the same directory (same filesystem) and renaming.
func atomicWriteFile(path string, data []byte, perm os.FileMode) error {
// Resolve symlinks so writes land on the real file, not the symlink
realPath := path
if resolved, err := filepath.EvalSymlinks(path); err == nil {
realPath = resolved
} else if !os.IsNotExist(err) {
// Symlink exists but can't resolve — try resolving parent dir
if dir, err2 := filepath.EvalSymlinks(filepath.Dir(path)); err2 == nil {
realPath = filepath.Join(dir, filepath.Base(path))
}
}
if err := os.MkdirAll(filepath.Dir(realPath), 0o755); err != nil {
return fmt.Errorf("mkdir %s: %w", filepath.Dir(realPath), err)
}
f, err := os.CreateTemp(filepath.Dir(realPath), ".tmp-"+filepath.Base(realPath))
if err != nil {
return fmt.Errorf("create temp: %w", err)
}
tmpName := f.Name()
if _, err := f.Write(data); err != nil {
f.Close()
os.Remove(tmpName)
return fmt.Errorf("write temp: %w", err)
}
if err := f.Chmod(perm); err != nil {
f.Close()
os.Remove(tmpName)
return fmt.Errorf("chmod temp: %w", err)
}
f.Close()
return os.Rename(tmpName, realPath)
}
func readManifest(path string) (*Manifest, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read manifest: %w", err)
}
var m Manifest
if err := json.Unmarshal(data, &m); err != nil {
return nil, fmt.Errorf("parse manifest: %w", err)
}
if m.Version == 0 {
m.Version = 1
}
return &m, nil
}
// defaultIndent is used for new files and when existing formatting can't be detected.
const defaultIndent = " "
// detectIndent returns the indentation unit of an existing JSON document. Callers
// hardcoding two spaces made every mutation rewrite files that are indented
// differently (dotfiles runs biome, which indents JSON with tabs), burying a
// one-line change in a whole-file diff.
func detectIndent(data []byte) string {
nl := bytes.IndexByte(data, '\n')
if nl < 0 {
return defaultIndent
}
rest := data[nl+1:]
n := 0
for n < len(rest) && (rest[n] == ' ' || rest[n] == '\t') {
n++
}
if n == 0 {
return defaultIndent
}
return string(rest[:n])
}
// fileIndent detects the indentation of the file at path, falling back to
// defaultIndent when it is absent or unreadable.
func fileIndent(path string) string {
data, err := os.ReadFile(path)
if err != nil {
return defaultIndent
}
return detectIndent(data)
}
// writeManifest serializes the manifest with deterministic formatting, preserving
// the file's existing indentation. Output is idempotent: writing the same data
// twice produces identical bytes.
func writeManifest(path string, m *Manifest) error {
data, err := json.MarshalIndent(m, "", fileIndent(path))
if err != nil {
return fmt.Errorf("encode manifest: %w", err)
}
data = append(data, '\n')
return atomicWriteFile(path, data, 0o644)
}
func readLock(path string) (*LockFile, error) {
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return &LockFile{Version: 1, Skills: make(map[string]LockSkill)}, nil
}
return nil, fmt.Errorf("read lock: %w", err)
}
var l LockFile
if err := json.Unmarshal(data, &l); err != nil {
return nil, fmt.Errorf("parse lock: %w", err)
}
if l.Skills == nil {
l.Skills = make(map[string]LockSkill)
}
return &l, nil
}
// writeLock mirrors writeManifest: preserve the file's existing indentation and
// emit a trailing newline, so a single entry change does not reformat the whole
// lock or trip POSIX text-file conventions.
func writeLock(path string, l *LockFile) error {
data, err := json.MarshalIndent(l, "", fileIndent(path))
if err != nil {
return fmt.Errorf("encode lock: %w", err)
}
data = append(data, '\n')
return atomicWriteFile(path, data, 0o644)
}
// validateSkillName checks that a skill name is safe to use as a directory name.
func validateSkillName(name string) error {
if name == "" {
return fmt.Errorf("skill name is required")
}
if name == "." || name == ".." {
return fmt.Errorf("invalid skill name %q", name)
}
if strings.Contains(name, "/") || strings.Contains(name, "\\") || strings.Contains(name, "\x00") {
return fmt.Errorf("skill name %q contains invalid characters", name)
}
return nil
}
// computeSourceHash computes a deterministic hash of a source entry configuration.
// Used to detect changes in source configuration (type, path, files map).
func computeSourceHash(src SourceEntry) string {
h := sha256.New()
h.Write([]byte(src.Type))
h.Write([]byte{0})
h.Write([]byte(src.Path))
h.Write([]byte{0})
if len(src.Files) > 0 {
keys := make([]string, 0, len(src.Files))
for k := range src.Files {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
h.Write([]byte(k))
h.Write([]byte{0})
h.Write([]byte(src.Files[k]))
h.Write([]byte{0})
}
}
return hex.EncodeToString(h.Sum(nil)[:6])
}