feat(posts): import & external markdown — S1.1 (#22)
CI / ci (push) Canceled after 0s

External .md/.markdown opens and edits as-is in a single guest slot
(File > Open... Cmd+O, drag-onto-window): SessionTarget extends
EditorSession to write in place verbatim, no cursor sidecar, the #67
conflict alert reused for foreign files. Import... (Shift+Cmd+O)
copies multi-select files in as Posts behind ONE Origin ask
(writer default, immutable); external frontmatter keys ride verbatim
with pass_state/origin set; slug/collision machinery shared with
writeNew.

Audit fixes folded in: BOM stripped + CRLF normalized at the trust
boundary (a CRLF pair is one Swift grapheme — \n splits saw one
line); unreadable files refuse to open (loadFailed — a failed read
never becomes a write); dropped web links and severed symlinks
guarded; ~24 lines of reviewer-flagged dead weight removed.

7 new tests; full unit + UI suite green; swiftlint clean.

Map #22 stays open pending the live calibration pass (#88 posture).
This commit is contained in:
AlexKucera committed 2026-10-12 17:00:03 +02:00
1 parent 683d697367
commit 0f1c4ef4fe
14 files changed
+691 -49

No files matched your search

+97 -5
View File
@@ -8,11 +8,26 @@
//
import Foundation
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.
/// #17 reader already parses. #22: import copies external markdown in (#94/#95).
nonisolated enum PostStore {
/// #96: .md/.markdown only — every entry point (Open panel, Import panel,
/// drag-drop filter) shares this list.
static let openableTypes: [UTType] = markdownExtensions.compactMap { UTType(filenameExtension: $0) }
/// #91: drag-drop filter — local file URLs only (a dragged web link is
/// not a document; `String(contentsOf:)` would fetch it), extension
/// checked case-insensitively (UTType conformance on the pasteboard is
/// unreliable).
static func isMarkdown(_ url: URL) -> Bool {
url.isFileURL && markdownExtensions.contains(url.pathExtension.lowercased())
}
private static let markdownExtensions = ["md", "markdown"]
/// 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).
@@ -64,9 +79,87 @@ nonisolated enum PostStore {
/// #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 {
try materialize(
text: stamped(body: body, passState: .firstDraft, origin: .writer),
title: Post.title(of: body),
origin: .writer,
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 {
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
// corpus machinery sees a CRLF file as a single line (mangled id and
// 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() }
raw = raw.replacingOccurrences(of: "\r\n", with: "\n")
let (block, body) = splitFrontmatter(raw)
let text = mergedFrontmatter(keeping: block, origin: origin) + body
return try materialize(
text: text,
title: Post.title(of: body),
origin: origin,
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).
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"
}
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> = []
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")
}
}
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)")
}
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.
/// 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 title = Post.title(of: body)
let id = availableSlug(for: title, in: postsRoot)
let dir = postsRoot.appendingPathComponent(id, isDirectory: true)
let fileURL = dir.appendingPathComponent("post.md")
@@ -77,8 +170,7 @@ nonisolated enum PostStore {
}
do {
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try stamped(body: body, passState: .firstDraft, origin: .writer)
.write(to: fileURL, atomically: true, encoding: .utf8)
try text.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
// Don't strand an empty slug folder on partial failure (it would
// occupy the slug and push the retry to -2).
@@ -87,7 +179,7 @@ nonisolated enum PostStore {
}
throw error
}
return Post(id: id, title: title, passState: .firstDraft, origin: .writer)
return Post(id: id, title: title, passState: .firstDraft, origin: origin)
}
/// Save an existing Post: body-only text in, file normalized out. The