Skip to content

A full-featured download manager.

feat(docs): add obsidian create command

Dr_rOot9d640d95fd83
diff --git a/package.json b/package.json
index 4be06e2e..8f9b89dd 100644
--- a/package.json
+++ b/package.json
@@ -50,6 +50,7 @@
"docs": "node scripts/obsidian-docs.mjs",
"docs:clear": "node scripts/obsidian-docs.mjs clear",
"docs:context": "node scripts/obsidian-docs.mjs context",
+ "docs:create": "node scripts/obsidian-docs.mjs create",
"docs:doctor": "node scripts/obsidian-docs.mjs doctor",
"docs:list": "node scripts/obsidian-docs.mjs list",
"docs:status": "node scripts/obsidian-docs.mjs status",
diff --git a/scripts/obsidian-docs-lib.mjs b/scripts/obsidian-docs-lib.mjs
index 5ac3a061..ac4ef6d8 100644
--- a/scripts/obsidian-docs-lib.mjs
+++ b/scripts/obsidian-docs-lib.mjs
@@ -12,6 +12,17 @@ import path from 'node:path'
export const TASK_ID_PATTERN = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+$/
export const LOCAL_CONTEXT_FILE = '.obsidian-doc-context.json'
+export const MAX_CREATE_CONTENT_BYTES = 512 * 1024
+
+const DOCUMENT_DIRECTORY_KEYS = Object.freeze({
+ 'archive-plans': 'archivePlans',
+ decisions: 'decisions',
+ evidence: 'evidence',
+ 'legacy-import': 'legacyImport',
+ plans: 'activePlans',
+ publication: 'publication',
+ specs: 'activeSpecs',
+})
const TASK_LINE_PATTERN =
/^(\s*-\s+\[)([ xX])(\]\s+\[([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)\]\s+)(.+)$/
@@ -152,6 +163,71 @@ export function assertActivePlanMarkdownPath(config, vaultPath) {
return vaultPath
}
+export function resolveCreateDocumentPath(config, kind, filename) {
+ const directoryKey = DOCUMENT_DIRECTORY_KEYS[kind]
+ if (!directoryKey) {
+ throw new Error(
+ `Document directory must be one of: ${Object.keys(
+ DOCUMENT_DIRECTORY_KEYS
+ ).join(', ')}`
+ )
+ }
+ if (typeof filename !== 'string' || !filename.endsWith('.md')) {
+ throw new Error('Document path must end with .md')
+ }
+ return assertProjectMarkdownPath(
+ config,
+ projectPath(config, directoryKey, filename)
+ )
+}
+
+export function inspectDocument(config, vaultPath) {
+ assertProjectMarkdownPath(config, vaultPath)
+ const code = `(async()=>{const path=${JSON.stringify(
+ vaultPath
+ )};const entry=app.vault.getAbstractFileByPath(path);return JSON.stringify({exists:Boolean(entry),markdown:Boolean(entry&&entry.extension==="md")})})()`
+ return evaluateObsidian(config, code)
+}
+
+export function createDocument(config, options, dependencies = {}) {
+ const vaultPath = resolveCreateDocumentPath(
+ config,
+ options.kind,
+ options.filename
+ )
+ const content = options.content ?? ''
+ if (typeof content !== 'string') {
+ throw new Error('Document content must be a string')
+ }
+ if (content.includes('\0')) {
+ throw new Error('Document content must not contain NUL characters')
+ }
+ if (Buffer.byteLength(content, 'utf8') > MAX_CREATE_CONTENT_BYTES) {
+ throw new Error(
+ `Document content must not exceed ${MAX_CREATE_CONTENT_BYTES} bytes`
+ )
+ }
+ const inspect = dependencies.inspect ?? inspectDocument
+ const runner = dependencies.run ?? runObsidian
+ const existing = inspect(config, vaultPath)
+ if (existing.exists && !existing.markdown) {
+ throw new Error(`Vault path is not a Markdown file: ${vaultPath}`)
+ }
+ if (existing.exists && options.overwrite !== true) {
+ throw new Error(
+ `Document already exists; pass --overwrite to replace it: ${vaultPath}`
+ )
+ }
+ const args = ['create', `path=${vaultPath}`, `content=${content}`]
+ if (options.overwrite === true) args.push('overwrite')
+ runner(config, args)
+ return {
+ created: !existing.exists,
+ overwritten: existing.exists,
+ path: vaultPath,
+ }
+}
+
export function parseTaskLines(content) {
const tasks = []
const seen = new Set()
diff --git a/scripts/obsidian-docs.mjs b/scripts/obsidian-docs.mjs
index baa90dca..01353a2f 100644
--- a/scripts/obsidian-docs.mjs
+++ b/scripts/obsidian-docs.mjs
@@ -1,10 +1,12 @@
#!/usr/bin/env node
+import { lstatSync, readFileSync } from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import {
checkActivePlans,
clearLocalContext,
+ createDocument,
getGitState,
listDocuments,
loadDocsConfig,
@@ -48,6 +50,7 @@ ignored obsidian-docs.config.json and customize it before using vault commands.
Usage:
pnpm run docs:doctor
+ pnpm run docs:create -- <directory> <path.md> [--from <file> | --stdin] [--overwrite]
pnpm run docs:list -- plans|specs [--all] [--include-indexes]
pnpm run docs:use -- <plan-id>
pnpm run docs:clear
@@ -56,6 +59,9 @@ Usage:
pnpm run docs:task -- done <task-id> [plan-id] --commit <git-ref>
pnpm run docs:task -- todo <task-id> [plan-id]
pnpm run docs:check -- [--format json]
+
+Create directories:
+ specs, plans, decisions, evidence, publication, archive-plans, legacy-import
`)
}
@@ -64,6 +70,32 @@ function requireValue(value, label) {
return value
}
+function readCreateContent(options) {
+ const hasFile = options.from !== undefined
+ const hasStdin = options.stdin !== undefined
+ if (hasFile && hasStdin) {
+ throw new Error('Use only one of --from or --stdin')
+ }
+ if (hasFile) {
+ if (typeof options.from !== 'string') {
+ throw new Error('--from requires a file path')
+ }
+ const sourcePath = path.resolve(REPO_ROOT, options.from)
+ const stats = lstatSync(sourcePath)
+ if (stats.isSymbolicLink() || !stats.isFile()) {
+ throw new Error('--from must reference a regular file, not a symlink')
+ }
+ return readFileSync(sourcePath, 'utf8')
+ }
+ if (hasStdin) {
+ if (options.stdin !== true) {
+ throw new Error('--stdin does not accept a value')
+ }
+ return readFileSync(0, 'utf8')
+ }
+ return ''
+}
+
function formatDocumentTable(documents) {
const rows = documents.map((document) => [
document.id,
@@ -115,6 +147,26 @@ export function main(argv = process.argv.slice(2)) {
return
}
const config = loadDocsConfig(REPO_ROOT, options.config)
+ if (command === 'create') {
+ const kind = requireValue(args[0], 'document directory')
+ const filename = requireValue(args[1], 'document path')
+ if (args.length !== 2) {
+ throw new Error('create requires a document directory and path')
+ }
+ if (options.overwrite !== undefined && options.overwrite !== true) {
+ throw new Error('--overwrite does not accept a value')
+ }
+ const result = createDocument(config, {
+ content: readCreateContent(options),
+ filename,
+ kind,
+ overwrite: options.overwrite === true,
+ })
+ console.log(
+ `${result.overwritten ? 'Overwrote' : 'Created'} ${result.path}`
+ )
+ return
+ }
if (command === 'doctor') {
const version = runObsidian(config, ['version'])
const vault = runObsidian(config, ['vault', 'info=name'])
diff --git a/tests/scripts/obsidian-docs.test.ts b/tests/scripts/obsidian-docs.test.ts
index 589cb9b6..da656a07 100644
--- a/tests/scripts/obsidian-docs.test.ts
+++ b/tests/scripts/obsidian-docs.test.ts
@@ -14,12 +14,14 @@ import { parseArguments } from '../../scripts/obsidian-docs.mjs'
import {
assertProjectMarkdownPath,
clearLocalContext,
+ createDocument,
deriveProgress,
loadDocsConfig,
parseEvalJson,
parseTaskLines,
projectPath,
readLocalContext,
+ resolveCreateDocumentPath,
selectPlanDocuments,
validateActivePlanDocuments,
validateDocsConfig,
@@ -232,6 +234,22 @@ describe('CLI parsing', () => {
})
})
+ it('parses create input and overwrite options', () => {
+ expect(
+ parseArguments([
+ 'create',
+ 'decisions',
+ 'sample.md',
+ '--from',
+ '/tmp/sample.md',
+ '--overwrite',
+ ])
+ ).toEqual({
+ positional: ['create', 'decisions', 'sample.md'],
+ options: { from: '/tmp/sample.md', overwrite: true },
+ })
+ })
+
it('parses Obsidian eval output without exposing its prefix', () => {
expect(parseEvalJson('=> {"ok":true}\n')).toEqual({ ok: true })
expect(parseEvalJson('debug\n=> [1,2,3]\n')).toEqual([1, 2, 3])
@@ -280,6 +298,123 @@ describe('CLI parsing', () => {
})
})
+describe('document creation', () => {
+ it('resolves configured directories and invokes Obsidian without a shell', () => {
+ const calls: Array<{ args: string[]; config: unknown }> = []
+ const result = createDocument(
+ config,
+ {
+ content: '# Decision\n',
+ filename: 'media/sample.md',
+ kind: 'decisions',
+ overwrite: true,
+ },
+ {
+ inspect: () => ({ exists: true, markdown: true }),
+ run: (receivedConfig: unknown, args: string[]) => {
+ calls.push({ args, config: receivedConfig })
+ return ''
+ },
+ }
+ )
+
+ expect(result).toEqual({
+ created: false,
+ overwritten: true,
+ path: 'projects/example/40-decisions/media/sample.md',
+ })
+ expect(calls).toEqual([
+ {
+ args: [
+ 'create',
+ 'path=projects/example/40-decisions/media/sample.md',
+ 'content=# Decision\n',
+ 'overwrite',
+ ],
+ config,
+ },
+ ])
+ })
+
+ it('leaves overwrite disabled unless it is explicitly requested', () => {
+ const calls: string[][] = []
+ createDocument(
+ config,
+ {
+ filename: 'sample.md',
+ kind: 'decisions',
+ },
+ {
+ inspect: () => ({ exists: false, markdown: false }),
+ run: (_receivedConfig: unknown, args: string[]) => {
+ calls.push(args)
+ return ''
+ },
+ }
+ )
+
+ expect(calls).toEqual([
+ ['create', 'path=projects/example/40-decisions/sample.md', 'content='],
+ ])
+ })
+
+ it('rejects an existing document before invoking the create command', () => {
+ const run = () => {
+ throw new Error('create should not run')
+ }
+ expect(() =>
+ createDocument(
+ config,
+ {
+ filename: 'sample.md',
+ kind: 'decisions',
+ },
+ {
+ inspect: () => ({ exists: true, markdown: true }),
+ run,
+ }
+ )
+ ).toThrow(/already exists/)
+ })
+
+ it('rejects unknown directories, traversal, and non-Markdown paths', () => {
+ expect(() =>
+ resolveCreateDocumentPath(config, 'unknown', 'sample.md')
+ ).toThrow(/must be one of/)
+ expect(() =>
+ resolveCreateDocumentPath(config, 'decisions', '../sample.md')
+ ).toThrow(/safe relative path/)
+ expect(() =>
+ resolveCreateDocumentPath(config, 'decisions', 'sample.txt')
+ ).toThrow(/must end with .md/)
+ })
+
+ it('rejects content that cannot be passed safely to the CLI', () => {
+ expect(() =>
+ createDocument(
+ config,
+ {
+ content: 'unsafe\0content',
+ filename: 'sample.md',
+ kind: 'decisions',
+ },
+ { inspect: () => ({ exists: false, markdown: false }) }
+ )
+ ).toThrow(/NUL/)
+ expect(() =>
+ createDocument(
+ config,
+ {
+ content: 'x'.repeat(512 * 1024 + 1),
+ filename: 'sample.md',
+ kind: 'decisions',
+ },
+ { inspect: () => ({ exists: false, markdown: false }) }
+ )
+ ).toThrow(/must not exceed/)
+ })
+})
+
describe('plan selection security', () => {
it('selects one validated bilingual plan pair', () => {
const index = activePlanPair()