From 5537ca41e0069725e98ef9ad59a2d4dbaa0bd8ae Mon Sep 17 00:00:00 2001
From: Jacky Zhao <j.zhao2k19@gmail.com>
Date: Thu, 03 Aug 2023 05:16:32 +0000
Subject: [PATCH] use autostash and pull

---
 quartz/build.ts |   88 +++++++++++++++++++++++++++----------------
 1 files changed, 55 insertions(+), 33 deletions(-)

diff --git a/quartz/build.ts b/quartz/build.ts
index 553bd8c..07b51fb 100644
--- a/quartz/build.ts
+++ b/quartz/build.ts
@@ -2,7 +2,7 @@
 import path from "path"
 import { PerfTimer } from "./perf"
 import { rimraf } from "rimraf"
-import { globby, isGitIgnored } from "globby"
+import { isGitIgnored } from "globby"
 import chalk from "chalk"
 import http from "http"
 import serveHandler from "serve-handler"
@@ -10,16 +10,18 @@
 import { filterContent } from "./processors/filter"
 import { emitContent } from "./processors/emit"
 import cfg from "../quartz.config"
-import { FilePath } from "./path"
+import { FilePath, joinSegments, slugifyFilePath } from "./path"
 import chokidar from "chokidar"
 import { ProcessedContent } from "./plugins/vfile"
 import WebSocket, { WebSocketServer } from "ws"
 import { Argv, BuildCtx } from "./ctx"
+import { glob, toPosixPath } from "./glob"
 
 async function buildQuartz(argv: Argv, version: string) {
   const ctx: BuildCtx = {
     argv,
     cfg,
+    allSlugs: [],
   }
 
   console.log(chalk.bgGreen.black(`\n Quartz v${version} \n`))
@@ -41,16 +43,14 @@
   console.log(`Cleaned output directory \`${output}\` in ${perf.timeSince("clean")}`)
 
   perf.addEvent("glob")
-  const fps = await globby("**/*.md", {
-    cwd: argv.directory,
-    ignore: cfg.configuration.ignorePatterns,
-    gitignore: true,
-  })
+  const fps = await glob("**/*.md", argv.directory, cfg.configuration.ignorePatterns)
   console.log(
     `Found ${fps.length} input files from \`${argv.directory}\` in ${perf.timeSince("glob")}`,
   )
 
-  const filePaths = fps.map((fp) => `${argv.directory}${path.sep}${fp}` as FilePath)
+  const filePaths = fps.map((fp) => joinSegments(argv.directory, fp) as FilePath)
+  ctx.allSlugs = fps.map((fp) => slugifyFilePath(fp as FilePath))
+
   const parsedFiles = await parseMarkdown(ctx, filePaths)
   const filteredContent = filterContent(ctx, parsedFiles)
   await emitContent(ctx, filteredContent)
@@ -74,33 +74,55 @@
     contentMap.set(vfile.data.filePath!, content)
   }
 
-  async function rebuild(fp: string, action: "add" | "change" | "unlink") {
-    const perf = new PerfTimer()
+  let timeoutId: ReturnType<typeof setTimeout> | null = null
+  let toRebuild: Set<FilePath> = new Set()
+  let toRemove: Set<FilePath> = new Set()
+  async function rebuild(fp: string, action: "add" | "change" | "delete") {
+    fp = toPosixPath(fp)
     if (!ignored(fp)) {
-      console.log(chalk.yellow(`Detected change in ${fp}, rebuilding...`))
-      const fullPath = `${argv.directory}${path.sep}${fp}` as FilePath
-
-      try {
-        if (action === "add" || action === "change") {
-          const [parsedContent] = await parseMarkdown(ctx, [fullPath])
-          contentMap.set(fullPath, parsedContent)
-        } else if (action === "unlink") {
-          contentMap.delete(fullPath)
-        }
-
-        await rimraf(argv.output)
-        const parsedFiles = [...contentMap.values()]
-        const filteredContent = filterContent(ctx, parsedFiles)
-        await emitContent(
-          ctx,
-          filteredContent,
-        )
-        console.log(chalk.green(`Done rebuilding in ${perf.timeSince()}`))
-      } catch {
-        console.log(chalk.yellow(`Rebuild failed. Waiting on a change to fix the error...`))
+      const filePath = joinSegments(argv.directory, fp) as FilePath
+      if (action === "add" || action === "change") {
+        toRebuild.add(filePath)
+      } else if (action === "delete") {
+        toRemove.add(filePath)
       }
 
-      connections.forEach((conn) => conn.send("rebuild"))
+      if (timeoutId) {
+        clearTimeout(timeoutId)
+      }
+
+      timeoutId = setTimeout(async () => {
+        const perf = new PerfTimer()
+        console.log(chalk.yellow("Detected change, rebuilding..."))
+        try {
+          const filesToRebuild = [...toRebuild].filter((fp) => !toRemove.has(fp))
+
+          ctx.allSlugs = [...new Set([...contentMap.keys(), ...toRebuild])]
+            .filter((fp) => !toRemove.has(fp))
+            .map((fp) => slugifyFilePath(path.relative(argv.directory, fp) as FilePath))
+
+          const parsedContent = await parseMarkdown(ctx, filesToRebuild)
+          for (const content of parsedContent) {
+            const [_tree, vfile] = content
+            contentMap.set(vfile.data.filePath!, content)
+          }
+
+          for (const fp of toRemove) {
+            contentMap.delete(fp)
+          }
+
+          await rimraf(argv.output)
+          const parsedFiles = [...contentMap.values()]
+          const filteredContent = filterContent(ctx, parsedFiles)
+          await emitContent(ctx, filteredContent)
+          console.log(chalk.green(`Done rebuilding in ${perf.timeSince()}`))
+        } catch {
+          console.log(chalk.yellow(`Rebuild failed. Waiting on a change to fix the error...`))
+        }
+        connections.forEach((conn) => conn.send("rebuild"))
+        toRebuild.clear()
+        toRemove.clear()
+      }, 250)
     }
   }
 
@@ -113,7 +135,7 @@
   watcher
     .on("add", (fp) => rebuild(fp, "add"))
     .on("change", (fp) => rebuild(fp, "change"))
-    .on("unlink", (fp) => rebuild(fp, "unlink"))
+    .on("unlink", (fp) => rebuild(fp, "delete"))
 
   const server = http.createServer(async (req, res) => {
     await serveHandler(req, res, {

--
Gitblit v1.10.0