From ae2e3b463a91d94caa8bdf62e5c3a3d726b8b4e4 Mon Sep 17 00:00:00 2001
From: Jacky Zhao <j.zhao2k19@gmail.com>
Date: Sun, 23 Jul 2023 18:49:26 +0000
Subject: [PATCH] improve error handling while serving

---
 quartz/build.ts                       |   47 +++++++++++++++--------
 quartz/trace.ts                       |    4 +
 content/features/upcoming features.md |    1 
 content/index.md                      |    4 +
 quartz/processors/emit.ts             |    4 +-
 quartz/log.ts                         |    6 ++-
 content/build.md                      |    3 +
 quartz/processors/parse.ts            |   15 +++++--
 8 files changed, 56 insertions(+), 28 deletions(-)

diff --git a/content/build.md b/content/build.md
new file mode 100644
index 0000000..2857057
--- /dev/null
+++ b/content/build.md
@@ -0,0 +1,3 @@
+---
+title: "Building your Quartz"
+---
diff --git a/content/features/upcoming features.md b/content/features/upcoming features.md
index 6d39bb7..5cb7b97 100644
--- a/content/features/upcoming features.md
+++ b/content/features/upcoming features.md
@@ -2,7 +2,6 @@
 draft: true
 ---
 
-- typography fixes
 - parse tags in content
 - breadcrumbs component
 - filetree component
diff --git a/content/index.md b/content/index.md
index 8e012fa..5c32c23 100644
--- a/content/index.md
+++ b/content/index.md
@@ -16,10 +16,12 @@
 npx quartz create
 ```
 
-This will guide you through initializing your Quartz with content and previewing it locally.
+This will guide you through initializing your Quartz with content.
 
 When you're ready, you can edit `quartz.config.ts` to customize and configure Quartz more. Read the [[configuration]] page for more information on what each field in the configuration does.
 
+Then, when you're ready, see how to [[build]] and [[hosting|host]] Quartz.
+
 ## 🔧 Features
 
 - [[full-text search|Full-text search]], [[graph view]], [[backlinks]], [[Latex]], [[syntax highlighting]], [[popover previews]], and many more right out of the box
diff --git a/quartz/build.ts b/quartz/build.ts
index df83f6e..e5bfcaa 100644
--- a/quartz/build.ts
+++ b/quartz/build.ts
@@ -23,7 +23,7 @@
   port: number
 }
 
-export default async function buildQuartz(argv: Argv, version: string) {
+async function buildQuartz(argv: Argv, version: string) {
   console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`))
   const perf = new PerfTimer()
   const output = argv.output
@@ -82,23 +82,29 @@
       if (!ignored(fp)) {
         console.log(chalk.yellow(`Detected change in ${fp}, rebuilding...`))
         const fullPath = `${argv.directory}${path.sep}${fp}` as FilePath
-        if (action === "add" || action === "change") {
-          const [parsedContent] = await parseMarkdown(
-            cfg.plugins.transformers,
-            argv.directory,
-            [fullPath],
-            argv.verbose,
-          )
-          contentMap.set(fullPath, parsedContent)
-        } else if (action === "unlink") {
-          contentMap.delete(fullPath)
+
+        try {
+          if (action === "add" || action === "change") {
+            const [parsedContent] = await parseMarkdown(
+              cfg.plugins.transformers,
+              argv.directory,
+              [fullPath],
+              argv.verbose,
+            )
+            contentMap.set(fullPath, parsedContent)
+          } else if (action === "unlink") {
+            contentMap.delete(fullPath)
+          }
+
+          await rimraf(output)
+          const parsedFiles = [...contentMap.values()]
+          const filteredContent = filterContent(cfg.plugins.filters, parsedFiles, argv.verbose)
+          await emitContent(argv.directory, output, cfg, filteredContent, argv.serve, argv.verbose)
+          console.log(chalk.green(`Done rebuilding in ${perf.timeSince("rebuild")}`))
+        } catch {
+          console.log(chalk.yellow(`Rebuild failed. Waiting on a change to fix the error...`))
         }
 
-        await rimraf(output)
-        const parsedFiles = [...contentMap.values()]
-        const filteredContent = filterContent(cfg.plugins.filters, parsedFiles, argv.verbose)
-        await emitContent(argv.directory, output, cfg, filteredContent, argv.serve, argv.verbose)
-        console.log(chalk.green(`Done rebuilding in ${perf.timeSince("rebuild")}`))
         connections.forEach((conn) => conn.send("rebuild"))
       }
     }
@@ -133,3 +139,12 @@
     console.log("hint: exit with ctrl+c")
   }
 }
+
+export default async (argv: Argv, version: string) => {
+  try {
+    await buildQuartz(argv, version)
+  } catch {
+    console.log(chalk.red("\nExiting Quartz due to a fatal error"))
+    process.exit(1)
+  }
+}
diff --git a/quartz/log.ts b/quartz/log.ts
index 73e5d7e..773945c 100644
--- a/quartz/log.ts
+++ b/quartz/log.ts
@@ -17,10 +17,12 @@
     }
   }
 
-  success(text: string) {
+  end(text?: string) {
     if (!this.verbose) {
       this.spinner!.stop(true)
     }
-    console.log(text)
+    if (text) {
+      console.log(text)
+    }
   }
 }
diff --git a/quartz/processors/emit.ts b/quartz/processors/emit.ts
index d056732..6ff9a21 100644
--- a/quartz/processors/emit.ts
+++ b/quartz/processors/emit.ts
@@ -143,7 +143,7 @@
       }
     } catch (err) {
       trace(`Failed to emit from plugin \`${emitter.name}\``, err as Error)
-      process.exit(1)
+      throw err
     }
   }
 
@@ -173,5 +173,5 @@
     }
   }
 
-  log.success(`Emitted ${emittedFiles} files to \`${output}\` in ${perf.timeSince()}`)
+  log.end(`Emitted ${emittedFiles} files to \`${output}\` in ${perf.timeSince()}`)
 }
diff --git a/quartz/processors/parse.ts b/quartz/processors/parse.ts
index a068899..55783dc 100644
--- a/quartz/processors/parse.ts
+++ b/quartz/processors/parse.ts
@@ -107,7 +107,7 @@
         }
       } catch (err) {
         trace(`\nFailed to process \`${fp}\``, err as Error)
-        process.exit(1)
+        throw err
       }
     }
 
@@ -135,9 +135,14 @@
   let res: ProcessedContent[] = []
   log.start(`Parsing input files using ${concurrency} threads`)
   if (concurrency === 1) {
-    const processor = createProcessor(transformers)
-    const parse = createFileParser(transformers, baseDir, fps, allSlugs, verbose)
-    res = await parse(processor)
+    try {
+      const processor = createProcessor(transformers)
+      const parse = createFileParser(transformers, baseDir, fps, allSlugs, verbose)
+      res = await parse(processor)
+    } catch (error) {
+      log.end()
+      throw error
+    }
   } else {
     await transpileWorkerScript()
     const pool = workerpool.pool("./quartz/bootstrap-worker.mjs", {
@@ -156,6 +161,6 @@
     await pool.terminate()
   }
 
-  log.success(`Parsed ${res.length} Markdown files in ${perf.timeSince()}`)
+  log.end(`Parsed ${res.length} Markdown files in ${perf.timeSince()}`)
   return res
 }
diff --git a/quartz/trace.ts b/quartz/trace.ts
index d9d45d2..803fd2f 100644
--- a/quartz/trace.ts
+++ b/quartz/trace.ts
@@ -5,7 +5,9 @@
   const stack = err.stack
   console.log()
   console.log(
-    chalk.bgRed.white.bold(" ERROR ") +
+    "\n" +
+      chalk.bgRed.black.bold(" ERROR ") +
+      "\n" +
       chalk.red(` ${msg}`) +
       (err.message.length > 0 ? `: ${err.message}` : ""),
   )

--
Gitblit v1.10.0