mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-27 22:14:40 +01:00
fix: report unreadable files and non-property frontmatter as content problems; document quartzContent for plugins
This commit is contained in:
12 files changed
+205
-4
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
More build errors caused by content are reported as content problems ("fix the file and build again") instead of "This is likely a Quartz bug": frontmatter that holds a single value instead of properties, Markdown files and assets Quartz can't read (permission denied, a directory named like a note). Plugins can do the same by throwing an `Error` with `quartzContent = true` (see "Reporting problems in content" in Making plugins).
|
||||
@@ -583,6 +583,18 @@ Each view registration includes:
|
||||
|
||||
The `ViewRegistry` is a global singleton (via `Symbol.for`) ensuring all copies of the module share the same registry.
|
||||
|
||||
### Reporting problems in content
|
||||
|
||||
When your plugin fails because of a file's content rather than a bug in your code — a `.canvas` file that isn't valid JSON, a property with a value your plugin can't use, a file it can't read — throw an `Error` with `quartzContent` set to `true` and a message that names the problem:
|
||||
|
||||
```ts
|
||||
const err = new Error(`Invalid canvas: ${parseError.message}`)
|
||||
;(err as Error & { quartzContent?: boolean }).quartzContent = true
|
||||
throw err
|
||||
```
|
||||
|
||||
Quartz then reports it as a problem in the file's content ("fix it and build again") instead of asking the user to report a bug in your plugin, and leaves out the stack trace. Errors from transformers name the file being processed; from an emitter or a page type's `generate`, put the file's path in your message. Quartz checks the property, not the class, so plugins don't need to import anything from Quartz; it also finds the property on an error's `cause`. Only use it when the content is at fault — a wrong guess sends users looking for a problem in their notes that isn't there.
|
||||
|
||||
## Building and Distribution
|
||||
|
||||
Quartz v5 plugins ship pre-built `dist/` in their repositories. When a user installs your plugin, Quartz detects the pre-built output and skips the install/build cycle entirely — making installation near-instant.
|
||||
|
||||
@@ -7,6 +7,7 @@ Common issues and solutions when working with Quartz.
|
||||
## Reading build output
|
||||
|
||||
- **Errors from plugins** say which plugin failed (name, version, source), what it was doing ("while transforming the Markdown of `notes/x.md`", "component Backlinks while rendering `features/x`"), any problems Quartz already knew about that plugin, and where to report it. To confirm a plugin is the cause, disable it (`npx quartz plugin disable <name>`) and build again.
|
||||
- **Problems in a file's content** (frontmatter that isn't valid YAML/TOML, a file Quartz can't read) name the file and say "This is a problem in the file's content": fix the file and build again — it's not a bug in Quartz or a plugin.
|
||||
- **Plugins that fail to load** (can't be installed, their code throws on import, no plugin found in the package) are marked `✗` with the file and line where it failed. Locally the build continues without them so you can check the rest of the site; they are listed again at the top of the end-of-build summary. In CI (`CI` set, e.g. GitHub Actions, Netlify, Vercel, Cloudflare Pages) the build fails instead, so a site with a missing feature isn't deployed — set `QUARTZ_ALLOW_BROKEN_PLUGINS=1` to deploy anyway.
|
||||
- **Warnings** printed while loading the config (plugins that need a newer Quartz, plugins missing data they need, layout typos, plugin entries that are now built in) are repeated in a summary at the end of the build.
|
||||
- **Notes** in that summary point out links to pages that are not on your site — including links to [[RemoveDrafts|drafts]], which are the usual cause of "this link 404s". `npx quartz build --verbose` lists every such link, the order plugins run in, the built-ins and the layout of each page type.
|
||||
|
||||
+6
-1
@@ -46,7 +46,12 @@ function updateSlugs(ctx: BuildCtx, allFiles: string[]): void {
|
||||
? collectPermalinks({
|
||||
files: allFiles.filter((fp) => fp.endsWith(".md")),
|
||||
permalinkOf: (fp) => {
|
||||
const source = fs.readFileSync(path.join(ctx.argv.directory, fp))
|
||||
let source: Buffer
|
||||
try {
|
||||
source = fs.readFileSync(path.join(ctx.argv.directory, fp))
|
||||
} catch {
|
||||
return undefined // an unreadable file is reported when the file is parsed
|
||||
}
|
||||
if (!source.includes("permalink")) return undefined
|
||||
try {
|
||||
return readFrontmatterData(source, options).permalink
|
||||
|
||||
@@ -242,6 +242,18 @@ describe("frontmatter built-in", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("frontmatter holding a single value instead of properties is a content error", () => {
|
||||
for (const source of ["---\nhello\n---\nbody\n", "---\n42\n---\n"]) {
|
||||
assert.throws(
|
||||
() => readFrontmatterData(source),
|
||||
(err: Error) => isContentError(err) && /expected properties/.test(err.message),
|
||||
)
|
||||
}
|
||||
// empty frontmatter and lists keep working as before
|
||||
assert.deepStrictEqual(readFrontmatterData("---\n---\nbody\n"), {})
|
||||
assert.deepStrictEqual(readFrontmatterData("---\nnull\n---\n"), {})
|
||||
})
|
||||
|
||||
test("a permalink is the page's address, not an alias (Obsidian Publish)", () => {
|
||||
const data: Record<string, unknown> = { permalink: "short", aliases: ["old-name"] }
|
||||
assert.deepStrictEqual(normalizeFrontmatter(data, "x").aliases, ["old-name"])
|
||||
|
||||
@@ -157,6 +157,12 @@ export function readFrontmatterData(
|
||||
js: refuseJavaScript,
|
||||
},
|
||||
})
|
||||
// YAML/TOML can hold a single value (`--- hello ---`); properties are key/value pairs
|
||||
if (typeof data !== "object" || data === null) {
|
||||
throw new ContentError(
|
||||
`Invalid frontmatter: expected properties (\`key: value\` lines), got a ${typeof data} (${JSON.stringify(data)})`,
|
||||
)
|
||||
}
|
||||
return data
|
||||
} catch (err) {
|
||||
if (err instanceof ContentError) throw err
|
||||
|
||||
@@ -4,6 +4,7 @@ import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { Assets } from "./assets"
|
||||
import { isContentError } from "../../util/pluginErrors"
|
||||
import type { StaticResources } from "../../util/resources"
|
||||
import type { BuildCtx } from "../../util/ctx"
|
||||
import type { ChangeEvent } from "../types"
|
||||
@@ -52,3 +53,52 @@ describe("Assets.partialEmit", () => {
|
||||
await assert.doesNotReject(consumeDelete(output, changeEvent))
|
||||
})
|
||||
})
|
||||
|
||||
describe("Assets.emit", () => {
|
||||
const emitAll = async (directory: string, output: string) => {
|
||||
const ctx = {
|
||||
argv: { directory, output },
|
||||
cfg: { configuration: { ignorePatterns: [] }, plugins: { pageTypes: [] } },
|
||||
} as unknown as BuildCtx
|
||||
const emitted = Assets().emit(ctx, [], {} as StaticResources)
|
||||
const files: unknown[] = []
|
||||
for await (const file of emitted as AsyncIterable<unknown>) files.push(file)
|
||||
return files
|
||||
}
|
||||
const tempDir = async () => {
|
||||
const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-assets-"))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
const isRoot = process.getuid?.() === 0
|
||||
|
||||
test("an unreadable asset is a content error", { skip: isRoot }, async () => {
|
||||
const content = await tempDir()
|
||||
const output = await tempDir()
|
||||
const asset = path.join(content, "secret.png")
|
||||
await fs.promises.writeFile(asset, "x")
|
||||
await fs.promises.chmod(asset, 0o000)
|
||||
try {
|
||||
await assert.rejects(
|
||||
emitAll(content, output),
|
||||
(err: Error) =>
|
||||
isContentError(err) &&
|
||||
err.message === "Cannot read `secret.png`: permission denied (EACCES)",
|
||||
)
|
||||
} finally {
|
||||
await fs.promises.chmod(asset, 0o644)
|
||||
}
|
||||
})
|
||||
|
||||
test("an unwritable output is not a content error", { skip: isRoot }, async () => {
|
||||
const content = await tempDir()
|
||||
const output = await tempDir()
|
||||
await fs.promises.writeFile(path.join(content, "image.png"), "x")
|
||||
await fs.promises.chmod(output, 0o555)
|
||||
try {
|
||||
await assert.rejects(emitAll(content, output), (err: Error) => !isContentError(err))
|
||||
} finally {
|
||||
await fs.promises.chmod(output, 0o755)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,7 @@ import path from "path"
|
||||
import fs from "fs"
|
||||
import { glob } from "../../util/glob"
|
||||
import { Argv, BuildCtx } from "../../util/ctx"
|
||||
import { unreadableFileError } from "../../util/pluginErrors"
|
||||
import { QuartzConfig } from "../../cfg"
|
||||
import { visit } from "unist-util-visit"
|
||||
import { Element } from "hast"
|
||||
@@ -99,10 +100,25 @@ const copyFile = async (argv: Argv, fp: FilePath) => {
|
||||
const dir = path.dirname(dest) as FilePath
|
||||
await fs.promises.mkdir(dir, { recursive: true })
|
||||
|
||||
await fs.promises.copyFile(src, dest)
|
||||
try {
|
||||
await fs.promises.copyFile(src, dest)
|
||||
} catch (err) {
|
||||
throw await unreadableSource(err, src, fp)
|
||||
}
|
||||
return dest
|
||||
}
|
||||
|
||||
/** A content file Quartz can't read (no permission, …) is a content problem, not a Quartz bug. */
|
||||
async function unreadableSource(err: unknown, src: FilePath, fp: FilePath): Promise<unknown> {
|
||||
if ((err as NodeJS.ErrnoException | null)?.code === "ENOENT") return err
|
||||
try {
|
||||
await fs.promises.access(src, fs.constants.R_OK)
|
||||
return err // the source is readable: the output side failed
|
||||
} catch {
|
||||
return unreadableFileError(err, fp) ?? err
|
||||
}
|
||||
}
|
||||
|
||||
export const Assets: QuartzEmitterPlugin = () => {
|
||||
return {
|
||||
name: "Assets",
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import fs from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { readContentFile } from "./parse"
|
||||
import { isContentError } from "../util/pluginErrors"
|
||||
import type { FilePath } from "../util/path"
|
||||
|
||||
describe("readContentFile", () => {
|
||||
test("reads a file", async () => {
|
||||
const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-parse-"))
|
||||
try {
|
||||
const fp = path.join(dir, "note.md")
|
||||
await fs.promises.writeFile(fp, "# hi")
|
||||
assert.strictEqual((await readContentFile(fp as FilePath)).toString(), "# hi")
|
||||
} finally {
|
||||
await fs.promises.rm(dir, { recursive: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a file that can't be read is a content error", async () => {
|
||||
const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "quartz-parse-"))
|
||||
try {
|
||||
// a directory named like a note, and a file that is gone
|
||||
await fs.promises.mkdir(path.join(dir, "folder.md"))
|
||||
for (const [name, reason] of [
|
||||
["folder.md", "it is a directory (EISDIR)"],
|
||||
["missing.md", "it no longer exists (ENOENT)"],
|
||||
]) {
|
||||
await assert.rejects(
|
||||
readContentFile(path.join(dir, name) as FilePath),
|
||||
(err: Error) =>
|
||||
isContentError(err) && err.message === `Cannot read \`${name}\`: ${reason}`,
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
await fs.promises.rm(dir, { recursive: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -15,7 +15,12 @@ import { QuartzLogger } from "../util/log"
|
||||
import { trace } from "../util/trace"
|
||||
import { BuildCtx, WorkerSerializableBuildCtx } from "../util/ctx"
|
||||
import { styleText } from "util"
|
||||
import { attributeError, attributePluggables, originOf } from "../util/pluginErrors"
|
||||
import {
|
||||
attributeError,
|
||||
attributePluggables,
|
||||
originOf,
|
||||
unreadableFileError,
|
||||
} from "../util/pluginErrors"
|
||||
|
||||
export type QuartzMdProcessor = Processor<MDRoot, MDRoot, MDRoot>
|
||||
export type QuartzHtmlProcessor = Processor<undefined, MDRoot, HTMLRoot>
|
||||
@@ -90,6 +95,19 @@ async function transpileWorkerScript() {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a content file. A file that can't be read (no permission, removed during the build, …) is a
|
||||
* problem with the content, not a Quartz bug.
|
||||
* @internal Exported for testing.
|
||||
*/
|
||||
export async function readContentFile(fp: FilePath) {
|
||||
try {
|
||||
return await read(fp)
|
||||
} catch (err) {
|
||||
throw unreadableFileError(err, path.basename(fp)) ?? err
|
||||
}
|
||||
}
|
||||
|
||||
export function createFileParser(ctx: BuildCtx, fps: FilePath[]) {
|
||||
const { argv, cfg } = ctx
|
||||
return async (processor: QuartzMdProcessor) => {
|
||||
@@ -97,7 +115,7 @@ export function createFileParser(ctx: BuildCtx, fps: FilePath[]) {
|
||||
for (const fp of fps) {
|
||||
try {
|
||||
const perf = new PerfTimer()
|
||||
const file = await read(fp)
|
||||
const file = await readContentFile(fp)
|
||||
|
||||
// strip leading and trailing whitespace
|
||||
file.value = file.value.toString().trim()
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
PluginError,
|
||||
ContentError,
|
||||
isContentError,
|
||||
unreadableFileError,
|
||||
} from "./pluginErrors"
|
||||
import {
|
||||
recordDiagnostic,
|
||||
@@ -238,3 +239,19 @@ describe("plugin load failures", () => {
|
||||
assert.ok(text.indexOf("failed to load") < text.indexOf("some warning"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("unreadableFileError", () => {
|
||||
test("turns a file-system error into a content error naming the file", () => {
|
||||
const fsError = Object.assign(new Error("EACCES: permission denied, open 'x'"), {
|
||||
code: "EACCES",
|
||||
})
|
||||
const err = unreadableFileError(fsError, "notes/x.md")
|
||||
assert.ok(err && isContentError(err))
|
||||
assert.strictEqual(err.message, "Cannot read `notes/x.md`: permission denied (EACCES)")
|
||||
assert.strictEqual(err.cause, fsError)
|
||||
})
|
||||
|
||||
test("leaves other errors alone", () => {
|
||||
assert.strictEqual(unreadableFileError(new TypeError("boom"), "x.md"), undefined)
|
||||
})
|
||||
})
|
||||
@@ -50,6 +50,24 @@ export class ContentError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
const fileErrorReasons: Record<string, string> = {
|
||||
EACCES: "permission denied",
|
||||
EPERM: "permission denied",
|
||||
EISDIR: "it is a directory",
|
||||
ENOENT: "it no longer exists",
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@link ContentError} for a content file that can't be read (`err` from `fs`), or `undefined`
|
||||
* when `err` is not a file-system error.
|
||||
*/
|
||||
export function unreadableFileError(err: unknown, file: string): ContentError | undefined {
|
||||
const code = (err as NodeJS.ErrnoException | null)?.code
|
||||
if (typeof code !== "string") return undefined
|
||||
const reason = fileErrorReasons[code] ?? (err as Error).message
|
||||
return new ContentError(`Cannot read \`${file}\`: ${reason} (${code})`, { cause: err })
|
||||
}
|
||||
|
||||
/** Whether `err` or one of its causes (e.g. inside a {@link PluginError}) is a {@link ContentError}. */
|
||||
export function isContentError(err: unknown): boolean {
|
||||
let e = err
|
||||
|
||||
Reference in new issue
Block a user