| 378 | } |
| 379 | |
| 380 | func writeDirMeta(ctx context.Context, dir string) error { |
| 381 | if err := ensureContext(ctx, fmt.Sprintf("write meta for %s", dir)); err != nil { |
| 382 | return err |
| 383 | } |
| 384 | entries, err := os.ReadDir(dir) |
| 385 | if err != nil { |
| 386 | return fmt.Errorf("docpost: read dir %s: %w", dir, err) |
| 387 | } |
| 388 | var files, subdirs []string |
| 389 | hasIndex := false |
| 390 | for _, e := range entries { |
| 391 | name := e.Name() |
| 392 | if e.IsDir() { |
| 393 | subdirs = append(subdirs, name) |
| 394 | continue |
| 395 | } |
| 396 | if !strings.HasSuffix(name, ".mdx") { |
| 397 | continue |
| 398 | } |
| 399 | base := strings.TrimSuffix(name, ".mdx") |
| 400 | if base == docpostIndexKey { |
| 401 | hasIndex = true |
| 402 | continue |
| 403 | } |
| 404 | files = append(files, base) |
| 405 | } |
| 406 | sort.Strings(files) |
| 407 | sort.Strings(subdirs) |
| 408 | |
| 409 | pages := make([]string, 0, 1+len(files)+len(subdirs)) |
| 410 | if hasIndex { |
| 411 | pages = append(pages, docpostIndexKey) |
| 412 | } |
| 413 | pages = append(pages, files...) |
| 414 | pages = append(pages, subdirs...) |
| 415 | |
| 416 | meta := struct { |
| 417 | Title string `json:"title"` |
| 418 | Pages []string `json:"pages"` |
| 419 | }{ |
| 420 | Title: titleCase(filepath.Base(dir)), |
| 421 | Pages: pages, |
| 422 | } |
| 423 | data, err := json.MarshalIndent(meta, "", " ") |
| 424 | if err != nil { |
| 425 | return fmt.Errorf("docpost: marshal meta for %s: %w", dir, err) |
| 426 | } |
| 427 | metaPath := filepath.Join(dir, docpostMetaJSONPath) |
| 428 | if err := os.WriteFile(metaPath, append(data, '\n'), 0o600); err != nil { |
| 429 | return fmt.Errorf("docpost: write %s: %w", metaPath, err) |
| 430 | } |
| 431 | return nil |
| 432 | } |
| 433 | |
| 434 | // titleCase renders a lowercase command segment as a display title. |
| 435 | // Replaces dashes with spaces and capitalises each word. |