feat(library): projects & archive substrate — S1 (#107)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Pieces re-root from posts/<id>/ to projects/<name>/<id>/ with an archive/ twin root (ADR-0012): scan walks both levels, New Piece and Import land in the selected project else the default posts, the slug namespace is global across projects and archive (an archived slug is never reused), and every piece carries type: post frontmatter — stamped by New/Import, read leniently (absent or unknown reads as post), the file stays post.md for every content type. Write paths resolve the folder from the id alone (folder(of:)); sessions and sidecars never thread (project, id). Finish-audit hardening: duplicate ids on disk (Finder copy) dedupe in scan to the same first-match folder(of:) writes to; folder(of:) skips hidden/symlinked projects like scan does. Dev posts moved by hand to projects/posts/ — no migration machinery, the app never reads the old posts/ root (#103). Full suite green (128 unit + UI), swiftlint clean on changed files. Closes #107
This commit is contained in:
1 parent
50eecc6dcb
commit
3ca9d4e601
17 files changed
+608
-197
No files matched your search
+156
-76
@@ -5,6 +5,8 @@
|
||||
// #18 (S1.1): the write side of the Post lifecycle — slug naming, lazy folder
|
||||
// materialization on first write, frontmatter stamping (#59), Explicit Rename
|
||||
// = retitle + move (#60), Trash delete. Pure disk operations, no UI state.
|
||||
// #107 (ADR-0012): pieces live under projects/<project>/<slug>/ (archive/
|
||||
// mirrors the shape); the slug namespace is global across both roots.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@@ -13,6 +15,8 @@ import UniformTypeIdentifiers
|
||||
/// Write-side Post lifecycle (#18 map decisions #59/#60). One canonical write
|
||||
/// path: every file that leaves here carries the flat frontmatter block the
|
||||
/// #17 reader already parses. #22: import copies external markdown in (#94/#95).
|
||||
/// #107: the Piece ID is the durable identity — write paths resolve the folder
|
||||
/// from the id by searching both roots; nothing threads (project, id) around.
|
||||
nonisolated enum PostStore {
|
||||
/// #96: .md/.markdown only — every entry point (Open panel, Import panel,
|
||||
/// drag-drop filter) shares this list.
|
||||
@@ -28,6 +32,38 @@ nonisolated enum PostStore {
|
||||
|
||||
private static let markdownExtensions = ["md", "markdown"]
|
||||
|
||||
/// ADR-0012 id→folder resolution: the id is globally unique, so the
|
||||
/// folder is found by searching the container roots in order (projects/
|
||||
/// before archive/, project names sorted for determinism). nil when the
|
||||
/// id lives under neither root.
|
||||
// ponytail: linear walk of projects/ then archive/ per call — one
|
||||
// debounced flush = 2–3 walks (overwrite + sidecar). Fine at human
|
||||
// project counts; cache id→folder if it ever measures hot.
|
||||
// Audit: project-level guards mirror scan's skips (hidden dirs,
|
||||
// symlinks) so write paths and the library agree on what exists —
|
||||
// a piece in a dot-project must never shadow a visible one.
|
||||
static func folder(of id: String, home: URL) -> URL? {
|
||||
for root in Post.containerRoots {
|
||||
let rootURL = home.appendingPathComponent(root, isDirectory: true)
|
||||
guard let projects = try? FileManager.default.contentsOfDirectory(
|
||||
at: rootURL,
|
||||
includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
|
||||
) else { continue }
|
||||
for project in projects.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
|
||||
let values = try? project.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
|
||||
guard values?.isDirectory ?? false, !(values?.isSymbolicLink ?? false),
|
||||
!project.lastPathComponent.hasPrefix(".") else { continue }
|
||||
let dir = rootURL.appendingPathComponent(project.lastPathComponent, isDirectory: true)
|
||||
.appendingPathComponent(id, isDirectory: true)
|
||||
var isDir: ObjCBool = true
|
||||
if FileManager.default.fileExists(atPath: dir.path, isDirectory: &isDir), isDir.boolValue {
|
||||
return dir
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// The shared slug function (#60): lowercase, diacritic-fold, strip
|
||||
/// punctuation, whitespace runs → single hyphens, keep CJK, cap 80.
|
||||
/// A slugless title (blank, punctuation-only) is `untitled` (CONTEXT.md).
|
||||
@@ -56,14 +92,34 @@ nonisolated enum PostStore {
|
||||
}
|
||||
|
||||
/// First free slug for a title: base slug, then `-2`, `-3`… (#60).
|
||||
/// Case-insensitive existence check (#60): enumerates `posts/` and
|
||||
/// compares lowercased — independent of the volume's case sensitivity.
|
||||
/// `excluding` skips a folder (the renamer's own, still present).
|
||||
static func availableSlug(for title: String, in postsRoot: URL, excluding ownID: String? = nil) -> String {
|
||||
let taken = Set(
|
||||
((try? FileManager.default.contentsOfDirectory(atPath: postsRoot.path)) ?? [])
|
||||
.map { $0.lowercased() },
|
||||
)
|
||||
/// Case-insensitive existence check (#60): the slug namespace is GLOBAL
|
||||
/// (#107) — every entry (dir or file) under `projects/*/` and `archive/*/`
|
||||
/// is taken, lowercased — independent of the volume's case sensitivity,
|
||||
/// and an archived slug is never reused. `excluding` skips an id (the
|
||||
/// renamer's own, still present).
|
||||
/// First free slug for a title: base slug, then `-2`, `-3`… (#60), over
|
||||
/// the GLOBAL namespace (#107) — every entry under `projects/*/` and
|
||||
/// `archive/*/` (an archived slug must never be reused; restore would
|
||||
/// collide). Case-insensitive existence check (#60), independent of the
|
||||
/// volume's case sensitivity. `excluding` skips a folder (the renamer's
|
||||
/// own, still present).
|
||||
// ponytail: O(all pieces) per call — enumerates every project's entries
|
||||
// to build the taken set. Fine at human scale (new-piece / rename only);
|
||||
// index the namespace if it ever measures hot.
|
||||
static func availableSlug(for title: String, home: URL, excluding ownID: String? = nil) -> String {
|
||||
var taken = Set<String>()
|
||||
for root in Post.containerRoots {
|
||||
let rootURL = home.appendingPathComponent(root, isDirectory: true)
|
||||
guard let projects = try? FileManager.default.contentsOfDirectory(atPath: rootURL.path) else { continue }
|
||||
for project in projects {
|
||||
let entries = (try? FileManager.default.contentsOfDirectory(
|
||||
atPath: rootURL.appendingPathComponent(project, isDirectory: true).path,
|
||||
)) ?? []
|
||||
for entry in entries {
|
||||
taken.insert(entry.lowercased())
|
||||
}
|
||||
}
|
||||
}
|
||||
let base = slug(from: title) // slug() is already lowercase
|
||||
if !taken.contains(base) || base == ownID?.lowercased() {
|
||||
return base
|
||||
@@ -75,24 +131,27 @@ nonisolated enum PostStore {
|
||||
return "\(base)-\(suffix)"
|
||||
}
|
||||
|
||||
/// First write (#62): lazily materialize `posts/<slug>/post.md` with the
|
||||
/// #59 block stamped. Pass State First Draft, origin writer — the only
|
||||
/// values #18 writes; the folder appears here, never on New Post.
|
||||
static func writeNew(body: String, home: URL) throws -> Post {
|
||||
/// First write (#62): lazily materialize `projects/<project>/<slug>/post.md`
|
||||
/// with the #59 block stamped (plus `type: post`, #107). Pass State First
|
||||
/// Draft, origin writer — the only values #18 writes; the folder appears
|
||||
/// here, never on New Post.
|
||||
static func writeNew(body: String, project: String = Post.defaultProject, home: URL) throws -> Post {
|
||||
try materialize(
|
||||
text: stamped(body: body, passState: .firstDraft, origin: .writer),
|
||||
title: Post.title(of: body),
|
||||
origin: .writer,
|
||||
project: project,
|
||||
home: home,
|
||||
)
|
||||
}
|
||||
|
||||
/// #22/#94/#95: import one external markdown file as a Post — copy, never
|
||||
/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
|
||||
/// verbatim with `pass_state: First Draft` and `origin: <chosen>` set /
|
||||
/// overwritten (our two keys win); id = Title slug at import; collisions
|
||||
/// `-2`/`-3`… (#60 machinery); a fresh copy, no mtime preservation (#96).
|
||||
static func importFile(at url: URL, origin: Post.Origin, home: URL) throws -> Post {
|
||||
/// verbatim with `type: post`, `pass_state: First Draft` and
|
||||
/// `origin: <chosen>` set / overwritten (our three keys win); id = Title
|
||||
/// slug at import; collisions `-2`/`-3`… (#60 machinery); a fresh copy,
|
||||
/// no mtime preservation (#96).
|
||||
static func importFile(at url: URL, origin: Post.Origin, project: String = Post.defaultProject, home: URL) throws -> Post {
|
||||
var raw = try String(contentsOf: url, encoding: .utf8)
|
||||
// ponytail: normalize line endings + strip BOM at the import boundary —
|
||||
// in Swift a CRLF pair is ONE grapheme, so every "\n" split in the
|
||||
@@ -100,7 +159,9 @@ nonisolated enum PostStore {
|
||||
// title); true CRLF preservation would need grapheme-aware joins
|
||||
// everywhere. Lone-CR (pre-OSX) files still degrade to `untitled` —
|
||||
// ceiling named, add a "\r" pass if one ever shows up.
|
||||
if raw.hasPrefix("\u{FEFF}") { raw.removeFirst() }
|
||||
if raw.hasPrefix("\u{FEFF}") {
|
||||
raw.removeFirst()
|
||||
}
|
||||
raw = raw.replacingOccurrences(of: "\r\n", with: "\n")
|
||||
let (block, body) = splitFrontmatter(raw)
|
||||
let text = mergedFrontmatter(keeping: block, origin: origin) + body
|
||||
@@ -108,60 +169,66 @@ nonisolated enum PostStore {
|
||||
text: text,
|
||||
title: Post.title(of: body),
|
||||
origin: origin,
|
||||
project: project,
|
||||
home: home,
|
||||
)
|
||||
}
|
||||
|
||||
/// #95: external frontmatter keys ride along verbatim; `pass_state` and
|
||||
/// `origin` are set/overwritten in place — our two keys win, everything
|
||||
/// else untouched. Absent keys are inserted before the closing `---`.
|
||||
/// Returns the block INCLUDING its trailing newline; "" for a bare file
|
||||
/// (the caller then writes the #59 stamp shape via a fresh block).
|
||||
/// #95/#107: external frontmatter keys ride along verbatim; `type`,
|
||||
/// `pass_state` and `origin` are set/overwritten in place — our three
|
||||
/// keys win, everything else untouched. Absent keys are inserted before
|
||||
/// the closing `---` (in that order). Returns the block INCLUDING its
|
||||
/// trailing newline; "" for a bare file (the caller then writes the #59
|
||||
/// stamp shape via a fresh block).
|
||||
private static func mergedFrontmatter(keeping block: String, origin: Post.Origin) -> String {
|
||||
guard !block.isEmpty else {
|
||||
return "---\npass_state: \(Post.PassState.firstDraft.rawValue)\norigin: \(origin.rawValue)\n---\n"
|
||||
return "---\ntype: post\npass_state: \(Post.PassState.firstDraft.rawValue)\norigin: \(origin.rawValue)\n---\n"
|
||||
}
|
||||
var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
|
||||
// Drop the empty tail the block's final newline produced — re-added below.
|
||||
if let last = lines.last, last.isEmpty {
|
||||
lines.removeLast()
|
||||
}
|
||||
var ours: Set<String> = []
|
||||
// #107: three our-keys win — type/pass_state/origin set-overwrite in
|
||||
// place, absent ones insert before the closing --- in stamp order.
|
||||
// Ordered pairs (a Dictionary's iteration order is unspecified).
|
||||
let ours: [(key: String, value: String)] = [
|
||||
("type", "post"),
|
||||
("pass_state", Post.PassState.firstDraft.rawValue),
|
||||
("origin", origin.rawValue),
|
||||
]
|
||||
let oursByKey = Dictionary(ours.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
|
||||
var seen = Set<String>()
|
||||
for (index, line) in lines.enumerated() {
|
||||
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
|
||||
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty, trimmed != "---" else { continue }
|
||||
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
|
||||
if key == "pass_state" {
|
||||
lines[index] = "pass_state: \(Post.PassState.firstDraft.rawValue)"
|
||||
ours.insert("pass_state")
|
||||
} else if key == "origin" {
|
||||
lines[index] = "origin: \(origin.rawValue)"
|
||||
ours.insert("origin")
|
||||
if let value = oursByKey[key] {
|
||||
lines[index] = "\(key): \(value)"
|
||||
seen.insert(key)
|
||||
}
|
||||
}
|
||||
var insertions: [String] = []
|
||||
if !ours.contains("pass_state") {
|
||||
insertions.append("pass_state: \(Post.PassState.firstDraft.rawValue)")
|
||||
}
|
||||
if !ours.contains("origin") {
|
||||
insertions.append("origin: \(origin.rawValue)")
|
||||
}
|
||||
let insertions = ours.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
|
||||
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
|
||||
lines.insert(contentsOf: insertions, at: close)
|
||||
}
|
||||
return lines.joined(separator: "\n") + "\n"
|
||||
}
|
||||
|
||||
/// #62/#95: lazily materialize `posts/<slug>/post.md` with the given
|
||||
/// (already stamped/merged) text. Shared by `writeNew` and `importFile` —
|
||||
/// one lazy-folder path, TOCTOU-guarded, never clobbering.
|
||||
/// #62/#95: lazily materialize `projects/<project>/<slug>/post.md` with
|
||||
/// the given (already stamped/merged) text. Shared by `writeNew` and
|
||||
/// `importFile` — one lazy-folder path, TOCTOU-guarded, never clobbering.
|
||||
/// Returns the created Post (id, title, First Draft, origin).
|
||||
private static func materialize(text: String, title: String, origin: Post.Origin, home: URL) throws -> Post {
|
||||
let postsRoot = home.appendingPathComponent("posts", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: postsRoot, withIntermediateDirectories: true)
|
||||
let id = availableSlug(for: title, in: postsRoot)
|
||||
let dir = postsRoot.appendingPathComponent(id, isDirectory: true)
|
||||
private static func materialize(text: String, title: String, origin: Post.Origin, project: String, home: URL) throws -> Post {
|
||||
let projectsRoot = home.appendingPathComponent("projects", isDirectory: true)
|
||||
try FileManager.default.createDirectory(
|
||||
at: projectsRoot.appendingPathComponent(project, isDirectory: true),
|
||||
withIntermediateDirectories: true,
|
||||
)
|
||||
let id = availableSlug(for: title, home: home)
|
||||
let dir = projectsRoot.appendingPathComponent(project, isDirectory: true)
|
||||
.appendingPathComponent(id, isDirectory: true)
|
||||
let fileURL = dir.appendingPathComponent("post.md")
|
||||
// TOCTOU guard (audit): a folder appearing between slug pick and write
|
||||
// must fail loudly, never clobber another post's content.
|
||||
@@ -179,31 +246,34 @@ nonisolated enum PostStore {
|
||||
}
|
||||
throw error
|
||||
}
|
||||
return Post(id: id, title: title, passState: .firstDraft, origin: origin)
|
||||
return Post(id: id, title: title, passState: .firstDraft, origin: origin, type: .post, project: project, isArchived: false)
|
||||
}
|
||||
|
||||
/// Save an existing Post: body-only text in, file normalized out. The
|
||||
/// file's present `pass_state`/`origin` are preserved (origin immutable,
|
||||
/// CONTEXT.md; bare corpus posts normalize on save, #59). A vanished
|
||||
/// post throws — `writeNew` is the only creator; saving must never
|
||||
/// resurrect a deleted post with reset metadata.
|
||||
/// file's present `pass_state`/`origin`/`type` are preserved (origin
|
||||
/// immutable, CONTEXT.md; bare corpus posts normalize on save, #59). A
|
||||
/// vanished post throws — `writeNew` is the only creator; saving must
|
||||
/// never resurrect a deleted post with reset metadata.
|
||||
static func overwrite(id: String, body: String, home: URL) throws {
|
||||
let fileURL = home.appendingPathComponent("posts/\(id)/post.md")
|
||||
guard let existing = try? String(contentsOf: fileURL, encoding: .utf8) else {
|
||||
guard let dir = folder(of: id, home: home),
|
||||
let existing = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
|
||||
else {
|
||||
throw CocoaError(.fileReadNoSuchFile)
|
||||
}
|
||||
let matter = Post.frontmatter(of: existing)
|
||||
let passState = Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft
|
||||
let origin = Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer
|
||||
try stamped(body: body, passState: passState, origin: origin)
|
||||
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||
let type = Post.ContentType(rawValue: matter["type"] ?? "") ?? .post
|
||||
try stamped(body: body, passState: passState, origin: origin, type: type)
|
||||
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
/// Body text (frontmatter stripped) for editing; nil when unreadable.
|
||||
/// Bare corpus posts return whole — they normalize on save (#59).
|
||||
static func readBody(id: String, home: URL) -> String? {
|
||||
let fileURL = home.appendingPathComponent("posts/\(id)/post.md")
|
||||
guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else { return nil }
|
||||
guard let dir = folder(of: id, home: home),
|
||||
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
|
||||
else { return nil }
|
||||
return splitFrontmatter(text).body
|
||||
}
|
||||
|
||||
@@ -218,29 +288,36 @@ nonisolated enum PostStore {
|
||||
var scrollOffset: Double = 0
|
||||
}
|
||||
|
||||
private static func stateURL(id: String, home: URL) -> URL {
|
||||
home.appendingPathComponent("posts/\(id)/.museion-state.json")
|
||||
private static func stateURL(id: String, home: URL) -> URL? {
|
||||
folder(of: id, home: home)?.appendingPathComponent(".museion-state.json")
|
||||
}
|
||||
|
||||
/// Read the sidecar; nil when absent or corrupt (a fresh cursor is fine).
|
||||
static func readCursor(id: String, home: URL) -> CursorState? {
|
||||
guard let data = try? Data(contentsOf: stateURL(id: id, home: home)) else { return nil }
|
||||
guard let url = stateURL(id: id, home: home),
|
||||
let data = try? Data(contentsOf: url)
|
||||
else { return nil }
|
||||
return try? JSONDecoder().decode(CursorState.self, from: data)
|
||||
}
|
||||
|
||||
/// Write the sidecar. Best-effort by design — a failed cursor write must
|
||||
/// never read as a failed content save, so failures are swallowed here.
|
||||
static func writeCursor(_ state: CursorState, id: String, home: URL) {
|
||||
guard let data = try? JSONEncoder().encode(state) else { return }
|
||||
try? data.write(to: stateURL(id: id, home: home), options: .atomic)
|
||||
guard let url = stateURL(id: id, home: home),
|
||||
let data = try? JSONEncoder().encode(state)
|
||||
else { return }
|
||||
try? data.write(to: url, options: .atomic)
|
||||
}
|
||||
|
||||
/// Explicit Rename (#60): rewrite the `# Title` line as the first
|
||||
/// non-empty body line, then move the folder to the new slug. The file
|
||||
/// stays `post.md`; a title that slugs to the current id only retitles.
|
||||
/// non-empty body line, then move the folder to the new slug — within
|
||||
/// the SAME parent (ADR-0012: the piece stays in its project, archived
|
||||
/// stays archived). The file stays `post.md`; a title that slugs to the
|
||||
/// current id only retitles.
|
||||
static func rename(_ post: Post, to title: String, home: URL) throws -> Post {
|
||||
let postsRoot = home.appendingPathComponent("posts", isDirectory: true)
|
||||
let dir = postsRoot.appendingPathComponent(post.id, isDirectory: true)
|
||||
guard let dir = folder(of: post.id, home: home) else {
|
||||
throw CocoaError(.fileReadNoSuchFile)
|
||||
}
|
||||
let fileURL = dir.appendingPathComponent("post.md")
|
||||
let text = try String(contentsOf: fileURL, encoding: .utf8)
|
||||
let (block, body) = splitFrontmatter(text)
|
||||
@@ -250,27 +327,30 @@ nonisolated enum PostStore {
|
||||
// availableSlug excludes our own (still-present) folder: a retitle
|
||||
// whose slug matches the current id (any case) keeps the clean name
|
||||
// (no -2 against ourselves); a genuine collision lands on -2 (#60).
|
||||
let newID = availableSlug(for: title, in: postsRoot, excluding: post.id)
|
||||
let newID = availableSlug(for: title, home: home, excluding: post.id)
|
||||
guard newID != post.id else {
|
||||
return Post(id: post.id, title: title, passState: post.passState, origin: post.origin)
|
||||
return Post(id: post.id, title: title, passState: post.passState, origin: post.origin,
|
||||
type: post.type, project: post.project, isArchived: post.isArchived)
|
||||
}
|
||||
try FileManager.default.moveItem(at: dir, to: postsRoot.appendingPathComponent(newID, isDirectory: true))
|
||||
return Post(id: newID, title: title, passState: post.passState, origin: post.origin)
|
||||
try FileManager.default.moveItem(at: dir, to: dir.deletingLastPathComponent().appendingPathComponent(newID, isDirectory: true))
|
||||
return Post(id: newID, title: title, passState: post.passState, origin: post.origin,
|
||||
type: post.type, project: post.project, isArchived: post.isArchived)
|
||||
}
|
||||
|
||||
/// Delete = move the Post folder to the Trash (recoverable in Finder) —
|
||||
/// never permanent removal (#18 AC).
|
||||
static func trash(_ post: Post, home: URL) throws {
|
||||
guard let dir = folder(of: post.id, home: home) else {
|
||||
throw CocoaError(.fileReadNoSuchFile)
|
||||
}
|
||||
var trashed: NSURL?
|
||||
try FileManager.default.trashItem(
|
||||
at: home.appendingPathComponent("posts/\(post.id)", isDirectory: true),
|
||||
resultingItemURL: &trashed,
|
||||
)
|
||||
try FileManager.default.trashItem(at: dir, resultingItemURL: &trashed)
|
||||
}
|
||||
|
||||
/// The #59 v1 block — flat keys, the exact shape the #17 reader parses.
|
||||
static func stamped(body: String, passState: Post.PassState, origin: Post.Origin) -> String {
|
||||
"---\npass_state: \(passState.rawValue)\norigin: \(origin.rawValue)\n---\n" + body
|
||||
/// The #59 v1 block (+ `type`, #107) — flat keys, the exact shape the
|
||||
/// #17 reader parses.
|
||||
static func stamped(body: String, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType = .post) -> String {
|
||||
"---\ntype: \(type.rawValue)\npass_state: \(passState.rawValue)\norigin: \(origin.rawValue)\n---\n" + body
|
||||
}
|
||||
|
||||
/// Splits a file into its verbatim frontmatter block (with both `---`
|
||||
|
||||
Reference in new issue
Block a user