-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcmd_init.go
More file actions
513 lines (443 loc) · 13.5 KB
/
cmd_init.go
File metadata and controls
513 lines (443 loc) · 13.5 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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
const repoURL = "https://github.com/lorehq/lore-template.git"
var validPlatforms = []string{"claude", "copilot", "cursor", "gemini", "windsurf", "opencode", "cline"}
// alwaysKeep are entries kept from the template. Platform files are generated by projection.
var alwaysKeep = []string{".lore", ".gitignore", ".gitattributes"}
var namePattern = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
func cmdInit(args []string) {
var name string
var platforms string
for i := 0; i < len(args); i++ {
switch args[i] {
case "--help", "-h":
fmt.Print(initHelpText)
return
case "--platforms", "-p":
if i+1 >= len(args) {
fatal("--platforms requires a value")
}
i++
platforms = args[i]
default:
if name == "" {
name = args[i]
}
}
}
// Determine mode: current dir (no name) or new dir (name given)
cwd, _ := os.Getwd()
var targetDir string
var projectName string
inPlace := name == ""
if inPlace {
// Init in current directory
targetDir = cwd
projectName = filepath.Base(cwd)
if !isProjectSafeDir(targetDir) {
fatal("Cannot initialize here — your home directory is not a project.\nUse: lore init <project-name>")
}
} else {
// Validate project name
projectName = filepath.Base(name)
if !namePattern.MatchString(projectName) {
fatal("Invalid project name '%s'. Names may contain letters, numbers, dots, hyphens, and underscores.", projectName)
}
// Resolve target directory
isPath := strings.Contains(name, "/") || strings.Contains(name, string(filepath.Separator))
if isPath {
targetDir, _ = filepath.Abs(name)
} else {
targetDir = filepath.Join(cwd, name)
}
// Guard: already exists
if _, err := os.Stat(targetDir); err == nil {
fatal("%s already exists", targetDir)
}
}
// Guard: already a Lore project
if _, err := os.Stat(filepath.Join(targetDir, ".lore")); err == nil {
fatal("Already a Lore project (.lore/ exists in %s)", targetDir)
}
// Parse or pick platforms
var platformList []string
if platforms != "" {
platformList = parsePlatforms(platforms)
} else {
platformList = pickPlatforms()
}
if len(platformList) == 0 {
fatal("No platforms selected.")
}
// Clone template
fmt.Println("Cloning Lore template...")
tmpDir, err := os.MkdirTemp("", "lore-init-*")
if err != nil {
fatal("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)
templateDir := os.Getenv("LORE_TEMPLATE")
if templateDir != "" {
if err := copyDir(templateDir, tmpDir); err != nil {
fatal("Failed to copy template: %v", err)
}
} else {
tag := "v" + version
if version == "dev" {
tag = "main"
}
cmd := exec.Command("git", "clone", "--depth", "1", "--branch", tag, repoURL, tmpDir)
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fatal("Failed to clone template (tag %s): %v", tag, err)
}
}
// Strip .git from template
os.RemoveAll(filepath.Join(tmpDir, ".git"))
// Filter: only keep alwaysKeep entries (platform files are generated by projection)
keep := make(map[string]bool)
for _, e := range alwaysKeep {
keep[e] = true
}
entries, _ := os.ReadDir(tmpDir)
for _, e := range entries {
if !keep[e.Name()] {
os.RemoveAll(filepath.Join(tmpDir, e.Name()))
}
}
// For in-place init: don't overwrite .gitignore from template.
// ensureGitignore will merge Lore entries into whatever exists.
if inPlace {
os.Remove(filepath.Join(tmpDir, ".gitignore"))
}
// Copy filtered template to target
if err := copyDir(tmpDir, targetDir); err != nil {
fatal("Failed to create project: %v", err)
}
// Ensure Lore entries in .gitignore (appends to existing, creates if missing)
ensureGitignore(targetDir)
// Write config.json
writeConfig(targetDir, projectName, platformList)
// Create inherit.json with empty defaults
writeInheritConfig(targetDir, map[string]map[string]string{
"rules": {},
"skills": {},
"agents": {},
})
// Create .lore/MCP/ and .lore/HOOKS/ directories
os.MkdirAll(filepath.Join(targetDir, ".lore", "MCP"), 0755)
os.MkdirAll(filepath.Join(targetDir, ".lore", "HOOKS"), 0755)
// Create MEMORY.md and LORE.md
createLocalFiles(targetDir)
// Git init (only for new directories — existing dirs may already have git)
if !inPlace {
gitInit := exec.Command("git", "init", "-b", "main")
gitInit.Dir = targetDir
gitInit.Stdout = os.Stdout
gitInit.Stderr = os.Stderr
_ = gitInit.Run()
}
if inPlace {
// In-place: back up existing platform files, don't generate yet
backedUp := backupPlatformFiles(targetDir, platformList)
fmt.Printf("\nInitialized Lore in %s\n", targetDir)
if len(backedUp) > 0 {
fmt.Println("\nBacked up existing files (migrate content to .lore/LORE.md):")
for _, f := range backedUp {
clean := strings.TrimSuffix(f, "/")
fmt.Printf(" %s → %s.pre-lore\n", f, clean)
}
}
fmt.Println("\nNext steps:")
fmt.Println(" Edit .lore/LORE.md with your project instructions")
if len(backedUp) > 0 {
fmt.Println(" Review .pre-lore backups and migrate content into .lore/LORE.md")
}
fmt.Println(" lore generate --platforms " + strings.Join(platformList, ","))
fmt.Println(" git add -A && git commit -m \"Init Lore\"")
} else {
// New project: auto-generate platform files
fmt.Println("Generating platform files...")
runProjection(targetDir, platformList)
fmt.Printf("\nInitialized Lore in %s\n", targetDir)
fmt.Println("\nNext steps:")
fmt.Printf(" cd %s\n", name)
fmt.Println(" git add -A && git commit -m \"Init Lore\"")
}
}
func parsePlatforms(input string) []string {
if strings.TrimSpace(strings.ToLower(input)) == "all" {
return append([]string{}, validPlatforms...)
}
parts := strings.Split(input, ",")
var result []string
for _, p := range parts {
p = strings.TrimSpace(p)
if p == "" {
continue
}
if !isValidPlatform(p) {
fatal("Unknown platform: %s\nValid: %s, all", p, strings.Join(validPlatforms, ", "))
}
result = append(result, p)
}
return result
}
func isValidPlatform(p string) bool {
for _, v := range validPlatforms {
if v == p {
return true
}
}
return false
}
// pickPlatforms runs an interactive platform picker using bubbletea.
func pickPlatforms() []string {
m := &pickerModel{
platforms: validPlatforms,
selected: make(map[int]bool),
}
p := tea.NewProgram(m)
final, err := p.Run()
if err != nil {
fatal("Platform picker error: %v", err)
}
fm := final.(*pickerModel)
if fm.cancelled {
fmt.Println("Cancelled.")
os.Exit(0)
}
var result []string
for i, p := range fm.platforms {
if fm.selected[i] {
result = append(result, p)
}
}
return result
}
// --- Interactive platform picker ---
type pickerModel struct {
platforms []string
cursor int
selected map[int]bool
done bool
cancelled bool
}
func (m *pickerModel) Init() tea.Cmd { return nil }
func (m *pickerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "q", "ctrl+c":
m.cancelled = true
return m, tea.Quit
case "up", "k":
if m.cursor > 0 {
m.cursor--
}
case "down", "j":
if m.cursor < len(m.platforms)-1 {
m.cursor++
}
case " ", "x":
m.selected[m.cursor] = !m.selected[m.cursor]
case "enter":
m.done = true
return m, tea.Quit
}
}
return m, nil
}
func (m *pickerModel) View() string {
s := lipgloss.NewStyle().Bold(true).Render("Select platforms") + " (space to toggle, enter to confirm)\n\n"
for i, p := range m.platforms {
cursor := " "
if m.cursor == i {
cursor = "> "
}
check := "[ ]"
if m.selected[i] {
check = "[x]"
}
s += fmt.Sprintf("%s%s %s\n", cursor, check, p)
}
s += "\n" + lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Render("q: cancel • space: toggle • enter: confirm")
return s
}
// --- Backup ---
// backupPlatformFiles backs up existing platform files that would be overwritten
// by projection. Returns the list of files that were backed up.
func backupPlatformFiles(targetDir string, platforms []string) []string {
// Files that projection overwrites per platform
targets := map[string][]string{
"claude": {"CLAUDE.md", ".claude/settings.json"},
"cursor": {"AGENTS.md", ".cursor/hooks.json"},
"copilot": {"AGENTS.md", ".github/copilot-instructions.md", ".github/hooks/lore.json"},
"gemini": {"GEMINI.md", ".gemini/settings.json"},
"windsurf": {"AGENTS.md", ".windsurfrules", ".windsurf/hooks.json"},
"opencode": {"AGENTS.md", ".opencode/plugins/lore-hooks.mjs"},
"cline": {"AGENTS.md", ".clinerules/_lore-mandate.md"},
}
// Directories where projection writes rules/skills/agents.
// Back up existing content so users don't lose hand-written agentics.
dirTargets := map[string][]string{
"claude": {".claude/rules", ".claude/skills", ".claude/agents"},
"cursor": {".cursor/rules", ".cursor/skills", ".cursor/agents"},
"copilot": {".github/instructions", ".github/skills", ".github/agents"},
"gemini": {".gemini/skills", ".gemini/agents"},
"windsurf": {".windsurf/rules", ".windsurf/skills"},
"opencode": {".opencode/skills", ".opencode/agents"},
"cline": {".clinerules", ".cline/skills"},
}
seen := map[string]bool{}
var backedUp []string
for _, platform := range platforms {
// Back up files
for _, f := range targets[platform] {
if seen[f] {
continue
}
seen[f] = true
src := filepath.Join(targetDir, f)
if _, err := os.Stat(src); err != nil {
continue
}
dst := src + ".pre-lore"
if _, err := os.Stat(dst); err == nil {
continue // don't overwrite existing backup
}
if data, err := os.ReadFile(src); err == nil {
os.WriteFile(dst, data, 0644)
backedUp = append(backedUp, f)
}
}
// Back up directories (rename to .pre-lore)
for _, d := range dirTargets[platform] {
if seen[d] {
continue
}
seen[d] = true
src := filepath.Join(targetDir, d)
if info, err := os.Stat(src); err != nil || !info.IsDir() {
continue
}
// Only back up if it has content
entries, err := os.ReadDir(src)
if err != nil || len(entries) == 0 {
continue
}
dst := src + ".pre-lore"
if _, err := os.Stat(dst); err == nil {
continue
}
if err := copyDir(src, dst); err == nil {
backedUp = append(backedUp, d+"/")
}
}
}
return backedUp
}
// ensureGitignore creates or appends Lore entries to .gitignore.
func ensureGitignore(targetDir string) {
entries := []string{".lore/MEMORY.md", ".lore/.session-nonce", ".lore/.last-generated", ".lore/.sessions/", "*.pre-lore"}
gitignorePath := filepath.Join(targetDir, ".gitignore")
existing := ""
if data, err := os.ReadFile(gitignorePath); err == nil {
existing = string(data)
}
var toAdd []string
for _, entry := range entries {
if !strings.Contains(existing, entry) {
toAdd = append(toAdd, entry)
}
}
if len(toAdd) == 0 {
return
}
f, err := os.OpenFile(gitignorePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return
}
defer f.Close()
// Add newline before Lore entries if file has content and doesn't end with newline
if len(existing) > 0 && !strings.HasSuffix(existing, "\n") {
f.WriteString("\n")
}
for _, entry := range toAdd {
f.WriteString(entry + "\n")
}
}
// --- File operations ---
func writeConfig(targetDir, projectName string, platforms []string) {
platMap := platformsFromList(platforms)
cfg := map[string]interface{}{
"platforms": orderedPlatformJSON(platMap),
}
data, _ := json.MarshalIndent(cfg, "", " ")
_ = os.MkdirAll(filepath.Join(targetDir, ".lore"), 0755)
_ = os.WriteFile(filepath.Join(targetDir, ".lore", "config.json"), append(data, '\n'), 0644)
}
func createLocalFiles(targetDir string) {
memPath := filepath.Join(targetDir, ".lore", "MEMORY.md")
if _, err := os.Stat(memPath); err != nil {
_ = os.WriteFile(memPath, []byte("# Local Memory\n"), 0644)
}
// LORE.md — operator instructions, projected into each platform's mandate file
lorePath := filepath.Join(targetDir, ".lore", "LORE.md")
if _, err := os.Stat(lorePath); err != nil {
stub, _ := templateFS.ReadFile("templates/project-lore.md")
_ = os.WriteFile(lorePath, stub, 0644)
}
}
func copyFile(src, dst string) {
data, err := os.ReadFile(src)
if err != nil {
return
}
_ = os.WriteFile(dst, data, 0644)
}
// copyDir recursively copies src to dst.
func copyDir(src, dst string) error {
return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(src, path)
target := filepath.Join(dst, rel)
if info.IsDir() {
return os.MkdirAll(target, info.Mode())
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
return os.WriteFile(target, data, info.Mode())
})
}
func fatal(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "Error: "+format+"\n", args...)
os.Exit(1)
}
const initHelpText = `Initialize Lore in a project.
Usage: lore init [name] [--platforms <list>]
lore init Initialize in current directory
lore init <name> Create new directory and initialize
Options:
-p, --platforms <list> Comma-separated platforms (interactive picker if omitted)
Valid: claude, copilot, cursor, gemini, windsurf, opencode, cline
--help, -h Print this help
Examples:
lore init # current dir, interactive picker
lore init --platforms claude # current dir, specific platform
lore init myproject --platforms claude,cursor # new dir
`