|  | 
|  | 1 | +const { readFileSync: read, writeFileSync: write } = require("fs") | 
|  | 2 | + | 
|  | 3 | +const action = process.argv[2] | 
|  | 4 | + | 
|  | 5 | +switch (action) { | 
|  | 6 | +  case "check": { | 
|  | 7 | +    const currentToc = splitReadme()[1] | 
|  | 8 | +    if (currentToc !== generateToc()) { | 
|  | 9 | +      console.log("Table of content is outdated. Use 'write' to update it.") | 
|  | 10 | +      process.exit(1) | 
|  | 11 | +    } else { | 
|  | 12 | +      console.log("Table of content is up to date.") | 
|  | 13 | +    } | 
|  | 14 | +    break | 
|  | 15 | +  } | 
|  | 16 | + | 
|  | 17 | +  case "write": { | 
|  | 18 | +    const [start, _, end] = splitReadme() | 
|  | 19 | +    writeReadme(start + generateToc() + end) | 
|  | 20 | +    break | 
|  | 21 | +  } | 
|  | 22 | + | 
|  | 23 | +  default: | 
|  | 24 | +    console.log( | 
|  | 25 | +      `${process.argv[1]} takes one argument, either "check" or "write"` | 
|  | 26 | +    ) | 
|  | 27 | +    process.exit(1) | 
|  | 28 | +} | 
|  | 29 | + | 
|  | 30 | +function readReadme() { | 
|  | 31 | +  return read("README.md", { encoding: "utf-8" }) | 
|  | 32 | +} | 
|  | 33 | + | 
|  | 34 | +function writeReadme(content) { | 
|  | 35 | +  write("README.md", content, { encoding: "utf-8" }) | 
|  | 36 | +} | 
|  | 37 | + | 
|  | 38 | +function splitReadme() { | 
|  | 39 | +  const content = readReadme() | 
|  | 40 | +  let startTocIndex = content.indexOf("\n\n") + 2 | 
|  | 41 | +  let endTocIndex = content.indexOf("\n\n", startTocIndex) | 
|  | 42 | + | 
|  | 43 | +  return [ | 
|  | 44 | +    content.slice(0, startTocIndex), | 
|  | 45 | +    content.slice(startTocIndex, endTocIndex), | 
|  | 46 | +    content.slice(endTocIndex), | 
|  | 47 | +  ] | 
|  | 48 | +} | 
|  | 49 | + | 
|  | 50 | +function generateToc() { | 
|  | 51 | +  return readReadme() | 
|  | 52 | +    .split("\n") | 
|  | 53 | +    .flatMap((line) => { | 
|  | 54 | +      const level = line.match(/^#*/)[0].length | 
|  | 55 | +      if (!level) return [] | 
|  | 56 | + | 
|  | 57 | +      const title = line.slice(level + 1) | 
|  | 58 | +      const urlHash = title | 
|  | 59 | +        .toLowerCase() | 
|  | 60 | +        .replace(/ /g, "-") | 
|  | 61 | +        .replace(/[^-a-z0-9]/g, "") | 
|  | 62 | +      return `${"  ".repeat(level - 2)}- [${title}](#${urlHash})` | 
|  | 63 | +    }) | 
|  | 64 | +    .join("\n") | 
|  | 65 | +} | 
0 commit comments