1 // 🐙🕸️ GitWikiWeb ∷ build.js
2 // ====================================================================
4 // Copyright © 2023 Lady [@ Lady’s Computer].
6 // This Source Code Form is subject to the terms of the Mozilla Public
7 // License, v. 2.0. If a copy of the MPL was not distributed with this
8 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
10 // --------------------------------------------------------------------
12 // A script for generating static wiki pages from a git repository.
14 // First, clone this repository to your machine in an accessible
15 // location (for example, `/srv/git/GitWikiWeb`). A bare repository is
16 // fine; customize the templates and stylesheets as you like. Then, use
17 // this file as the post‐receive hook for your wiki as follows :—
19 // #!/usr/bin/env -S sh
20 // export GITWIKIWEB=/srv/git/GitWikiWeb
21 // git archive --remote=$GITWIKIWEB HEAD build.js \
23 // | deno run -A - ~/public/wiki $GITWIKIWEB current
25 // The directory `~/public/wiki` (or whatever you specify as the first
26 // argument to `deno run -A -`) **will be deleted** and a new static
27 // wiki will be generated in its place. This script is not very smart
28 // (yet) and cannot selectively determine which pages will need
29 // updating. It just wipes and regenerates the whole thing.
31 // This script will make a number of requests to `$GITWIKIWEB` to
32 // download the latest templates, stylesheets, ⁊·c from this
33 // repository. Consequently, it is best that you set it to a repository
34 // you control and can ensure uptime for—ideally one local to the
35 // computer hosting the wiki.
40 } from "https://deno.land/std@0.196.0/fs/mod.ts";
44 } from "https://deno.land/std@0.196.0/yaml/mod.ts";
45 import djot
from "npm:@djot/djot@0.2.3";
46 import { Parser
} from "npm:htmlparser2@9.0.0";
47 import { DomHandler
, Element
, Text
} from "npm:domhandler@5.0.3";
48 import * as domutils
from "npm:domutils@3.1.0";
49 import domSerializer
from "npm:dom-serializer@2.0.0";
51 const DESTINATION
= Deno
.args
[0] ?? "~/public/wiki";
52 const REMOTE
= Deno
.args
[1] ?? "/srv/git/GitWikiWeb";
53 const REV
= Deno
.args
[2] ?? "HEAD";
61 const NIL
= Object
.preventExtensions(Object
.create(null));
63 const rawBlock
= (strings
, ...substitutions
) => ({
66 text
: String
.raw(strings
, substitutions
),
68 const rawInline
= (strings
, ...substitutions
) => ({
71 text
: String
.raw(strings
, substitutions
),
73 const str
= (strings
, ...substitutions
) => ({
75 text
: String
.raw(strings
, substitutions
),
78 const getDOM
= (source
) => {
80 const handler
= new DomHandler((error
, dom
) => {
82 throw new Error("GitWikiWeb: Failed to process DOM.", {
89 const parser
= new Parser(handler
);
95 const getRemoteContent
= async (pathName
) => {
96 const getArchive
= new Deno
.Command("git", {
97 args
: ["archive", `--remote=${REMOTE}`, REV
, pathName
],
101 const untar
= new Deno
.Command("tar", {
107 getArchive
.stdout
.pipeTo(untar
.stdin
);
114 ] = await Promise
.allSettled([
115 new Response(getArchive
.stderr
).text(),
117 new Response(untar
.stdout
).text(),
118 new Response(untar
.stderr
).text(),
120 ]).then(logErrorsAndCollectResults
);
122 console
.error(err1
+ err2
);
126 if (!getArchiveStatus
.success
) {
128 `GitWikiWeb: git archive returned nonzero exit code: ${getArchiveStatus.code}.`,
130 } else if (!untarStatus
.success
) {
132 `GitWikiWeb: tar returned nonzero exit code: ${untarStatus.code}.`,
139 const logErrorsAndCollectResults
= (results
) =>
140 results
.map(({ value
, reason
}) => {
142 console
.error(reason
);
149 const getReferenceFromPath
= (path
) =>
150 /Sources\/([A-Z][0-9A-Za-z]*\/[A-Z][0-9A-Za-z]*)\.djot$/u.exec(path
)
151 ?.[1]?.replace
?.("/", ":");
153 const listOfInternalLinks
= (references
, wrapper
= ($) => $) => ({
157 children
: Array
.from(
160 const [namespace, pageName
] = splitReference(reference
);
168 "data-realm": "internal",
169 "data-pagename": pageName
,
170 "data-namespace": namespace,
181 const diffReferences
= async (hash
, againstHead
= false) => {
182 const diff
= new Deno
.Command("git", {
190 ...(againstHead
? [hash
, "HEAD"] : [hash
]),
195 const [diffNames
] = await Promise
.allSettled([
196 new Response(diff
.stdout
).text(),
197 new Response(diff
.stderr
).text(),
198 ]).then(logErrorsAndCollectResults
);
199 return references(diffNames
.split("\0")); // returns an iterable
202 function* references(paths
) {
203 for (const path
of paths
) {
204 const reference
= getReferenceFromPath(path
);
213 const splitReference
= (reference
) => {
214 const colonIndex
= reference
.indexOf(":");
216 reference
.substring(0, colonIndex
),
217 reference
.substring(colonIndex
+ 1),
221 class GitWikiWebPage
{
222 #internalLinks
= new Set();
223 #externalLinks
= new Map();
225 constructor(namespace, name
, ast
, source
, config
) {
226 const internalLinks
= this.#internalLinks
;
227 const externalLinks
= this.#externalLinks
;
228 const sections
= Object
.create(null);
229 djot
.applyFilter(ast
, () => {
230 let titleSoFar
= null; // used to collect strs from headings
235 const links_section
= [];
236 if (internalLinks
.size
|| externalLinks
.size
) {
239 rawBlock
`<nav id="links">`,
243 children
: [str
`this page contains links`],
246 if (internalLinks
.size
) {
248 rawBlock
`<details open="">`,
249 rawBlock
`<summary>on this wiki</summary>`,
250 listOfInternalLinks(internalLinks
),
251 rawBlock
`</details>`,
256 if (externalLinks
.size
) {
258 rawBlock
`<details open="">`,
259 rawBlock
`<summary>elsewhere on the Web</summary>`,
264 children
: Array
.from(
266 ([destination
, text
]) => ({
272 attributes
: { "data-realm": "external" },
290 rawBlock
`</details>`,
302 e
.children
.push(...links_section
);
308 const attributes
= e
.attributes
?? NIL
;
309 const { as
} = attributes
;
311 delete attributes
.as
;
313 as
== "b" || as
== "cite" || as
== "i" || as
== "u"
330 if (titleSoFar
!= null) {
344 const { attributes
} = e
;
345 attributes
.title
??= titleSoFar
;
352 const { attributes
, reference
, destination
} = e
;
354 /^(?:[A-Z][0-9A-Za-z]*|[@#])?:(?:[A-Z][0-9A-Za-z]*)?$/u
355 .test(reference
?? "")
357 const [namespacePrefix
, pageName
] = splitReference(
360 const expandedNamespace
= {
364 }[namespacePrefix
] ?? namespacePrefix
;
365 const resolvedReference
= pageName
== ""
366 ? `Namespace:${expandedNamespace}`
367 : `${expandedNamespace}:${pageName}`;
368 this.#internalLinks
.add(resolvedReference
);
369 e
.reference
= resolvedReference
;
370 attributes
["data-realm"] = "internal";
371 attributes
["data-pagename"] = pageName
;
372 attributes
["data-namespace"] = expandedNamespace
;
374 attributes
["data-realm"] = "external";
375 const remote
= destination
??
376 ast
.references
[reference
]?.destination
;
378 externalLinks
.set(remote
, attributes
?.title
);
385 non_breaking_space
: {
387 if (titleSoFar
!= null) {
388 titleSoFar
+= "\xA0";
399 const { attributes
, children
} = e
;
400 const heading
= children
.find(({ tag
}) =>
403 const title
= (() => {
404 if (heading
?.attributes
?.title
) {
405 const result
= heading
.attributes
.title
;
406 delete heading
.attributes
.title
;
409 return heading
.level
== 1
410 ? `${namespace}:${name}`
411 : "untitled section";
414 const variantTitles
= Object
.create(null);
415 for (const attr
in attributes
) {
416 if (attr
.startsWith("v-")) {
417 Object
.defineProperty(
420 { ...READ_ONLY
, value
: attributes
[attr
] },
422 delete attributes
[attr
];
427 const definition
= Object
.create(null, {
428 title
: { ...READ_ONLY
, value
: title
},
431 value
: Object
.preventExtensions(variantTitles
),
434 if (heading
.level
== 1 && !("main" in sections
)) {
435 attributes
.id
= "main";
436 heading
.attributes
??= {};
437 heading
.attributes
.class = "main";
442 Object
.defineProperty(
448 value
: Object
.preventExtensions(definition
),
453 `GitWikiWeb: A section with the provided @id already exists: ${attributes.id}`,
461 if (titleSoFar
!= null) {
470 enter
: ({ text
}) => {
471 if (titleSoFar
!= null) {
482 const codepoint
= /^U\+([0-9A-Fa-f]+)$/u.exec(alias
)?.[1];
485 String.fromCodePoint(parseInt(codepoint, 16))
488 const resolved
= config
.symbols
?.[alias
];
489 return resolved
!= null ? str
`${resolved}` : e
;
495 Object
.defineProperties(this, {
496 ast
: { ...READ_ONLY
, value
: ast
},
497 namespace: { ...READ_ONLY
, value
: namespace },
498 name
: { ...READ_ONLY
, value
: name
},
501 value
: Object
.preventExtensions(sections
),
503 source
: { ...READ_ONLY
, value
: source
},
508 yield* this.#externalLinks
;
512 yield* this.#internalLinks
;
517 const config
= await
getRemoteContent("config.yaml").then((yaml
) =>
518 parseYaml(yaml
, { schema
: JSON_SCHEMA
})
520 const ls
= new Deno
.Command("git", {
521 args
: ["ls-tree", "-rz", "HEAD"],
529 ] = await Promise
.allSettled([
530 new Response(ls
.stdout
).text().then((lsout
) =>
533 .slice(0, -1) // drop the last entry; it is empty
534 .map(($) => $.split(/\s+/g))
536 new Response(ls
.stderr
).text(),
538 ]).then(logErrorsAndCollectResults
);
540 console
.error(lserr
);
544 if (!lsstatus
.success
) {
546 `GitWikiWeb: git ls-tree returned nonzero exit code: ${lsstatus.code}.`,
549 const requiredButMissingPages
= new Map([
550 ["Special:FrontPage", "front page"],
551 ["Special:NotFound", "not found"],
552 ["Special:RecentlyChanged", "recently changed"],
554 const pages
= new Map();
555 const promises
= [emptyDir(DESTINATION
)];
556 for (const object
of objects
) {
557 const hash
= object
[2];
558 const path
= object
[3];
559 const reference
= getReferenceFromPath(path
);
560 if (reference
== null) {
563 const [namespace, pageName
] = splitReference(reference
);
564 const cat
= new Deno
.Command("git", {
565 args
: ["cat-file", "blob", hash
],
569 const promise
= Promise
.allSettled([
570 new Response(cat
.stdout
).text(),
571 new Response(cat
.stderr
).text(),
573 ]).then(logErrorsAndCollectResults
).then(
574 ([source
, caterr
, catstatus
]) => {
576 console
.error(caterr
);
580 if (!catstatus
.success
) {
582 `GitWikiWeb: git cat-file returned nonzero exit code: ${catstatus.code}.`,
585 const page
= new GitWikiWebPage(
590 console
.warn(`Djot(${reference}): ${$.render()}`),
595 const reference
= `${namespace}:${pageName}`;
596 pages
.set(reference
, page
);
597 requiredButMissingPages
.delete(reference
);
601 promises
.push(promise
);
604 for (const [reference
, defaultTitle
] of requiredButMissingPages
) {
605 const [namespace, pageName
] = splitReference(reference
);
606 const source
= `# ${defaultTitle}\n`;
607 const page
= new GitWikiWebPage(
612 console
.warn(`Djot(${reference}): ${$.render()}`),
617 pages
.set(reference
, page
);
619 await Promise
.allSettled(promises
).then(
620 logErrorsAndCollectResults
,
622 const [template
, recentlyChanged
] = await Promise
.allSettled([
623 getRemoteContent("template.html"),
625 const dateParse
= new Deno
.Command("git", {
626 args
: ["rev-parse", "--after=1 week ago"],
630 const [maxAge
] = await Promise
.allSettled([
631 new Response(dateParse
.stdout
).text(),
632 new Response(dateParse
.stderr
).text(),
633 ]).then(logErrorsAndCollectResults
);
638 const revList
= new Deno
.Command("git", {
639 args
: ["rev-list", maxAge
, "--reverse", "HEAD"],
643 [commit
] = await Promise
.allSettled([
644 new Response(revList
.stdout
).text().then((list
) =>
647 new Response(revList
.stderr
).text(),
648 ]).then(logErrorsAndCollectResults
);
651 const revList2
= new Deno
.Command("git", {
652 args
: ["rev-list", "--max-count=1", "HEAD^"],
656 [commit
] = await Promise
.allSettled([
657 new Response(revList2
.stdout
).text().then((list
) =>
660 new Response(revList2
.stderr
).text(),
661 ]).then(logErrorsAndCollectResults
);
665 const results
= new Array(6);
666 const seen
= new Set();
667 const maxRecency
= Math
.max(config
.max_recency
| 0, 0);
668 let recency
= maxRecency
;
671 const show
= new Deno
.Command("git", {
675 "--format=%H%x00%cI%x00%cD",
676 recency
? `HEAD~${maxRecency - recency}` : commit
,
682 [hash
, dateTime
, humanReadable
],
683 ] = await Promise
.allSettled([
684 new Response(show
.stdout
).text().then((rev
) =>
685 rev
.trim().split("\0")
687 new Response(show
.stderr
).text(),
688 ]).then(logErrorsAndCollectResults
);
692 const ref
of (await
diffReferences(current
, !recency
))
701 results
[recency
] = { dateTime
, hash
, humanReadable
, refs
};
702 } while (recency
-- > 0 && current
&& current
!= commit
);
707 (name
) => ensureDir(`${DESTINATION}/${name}`),
709 ["style.css"].map((dependency
) =>
710 getRemoteContent(dependency
).then((source
) =>
712 `${DESTINATION}/${dependency}`,
718 ]).then(logErrorsAndCollectResults
);
720 const redLinks
= (() => {
721 const result
= new Set();
722 for (const page
of pages
.values()) {
723 for (const link
of page
.internalLinks()) {
724 if (pages
.has(link
)) {
734 const [pageRef
, { ast
, namespace, sections
, source
}] of pages
736 const title
= sections
.main
?.title
?? pageRef
;
737 djot
.applyFilter(ast
, () => {
738 let isNavigationPage
= true;
742 const { content
, navigation
} = (() => {
743 const navigation
= [];
744 if (pageRef
== "Special:RecentlyChanged") {
747 attributes
: { class: "recent-changes" },
750 children
: Array
.from(function* () {
752 const [index
, result
] of recentlyChanged
755 if (result
!= null) {
761 yield* listOfInternalLinks(refs
, (link
) => ({
762 tag
: index
== 0 ? "span" : "strong",
763 attributes
: { "data-recency": `${index}` },
766 ...(index
== 0 ? [] : [
768 rawInline
`<small>(<time dateTime="${dateTime}">`,
769 str
`${humanReadable}`,
770 rawInline
`</time>)</small>`,
781 isNavigationPage
= false;
782 return { content
: e
.children
, navigation
};
790 generated
: "", // will be removed later
793 children
: [str
`${title}`],
795 rawBlock
`<details id="navigation-about" open="">`,
796 rawBlock
`<summary>about this listing</summary>`,
799 rawBlock
`</article>`,
800 rawBlock
`</details>`,
803 rawBlock
`<nav id="navigation">`,
813 rawBlock
`</article>`,
820 const attributes
= e
.attributes
?? NIL
;
822 isNavigationPage
&& e
.level
== 1 &&
823 attributes
?.class == "main"
825 if ("generated" in attributes
) {
826 delete attributes
.generated
;
835 if (e
.level
== 1 && e
.attributes
?.class == "main") {
837 rawBlock
`<header class="main">`,
839 { tag
: "verbatim", text
: pageRef
},
851 const { attributes
, children
, reference
} = e
;
852 if (attributes
["data-realm"] == "internal") {
854 if (redLinks
.has(reference
)) {
856 `/Special:NotFound?path=/${reference}`;
857 attributes
["data-notfound"] = "";
859 e
.destination
= `/${reference}`;
861 if (children
.length
== 0) {
863 pages
.get(reference
)?.sections
?.main
?? NIL
;
864 const { v
} = attributes
;
867 str
`${section.title ?? reference}`,
873 section.variantTitles?.[v] ?? section.title ??
880 if (children
.length
== 0 && "title" in attributes
) {
883 str
`${attributes.title}`,
889 (attributes
.class ?? "").split(/\s/gu).includes("sig")
893 attributes
: { class: "sig" },
894 children
: [str
`—${"\xA0"}`, e
],
904 if (e
.children
.length
< 1) {
905 // The heading for this section was removed and it had
906 // no other children.
915 const doc
= getDOM(template
);
916 const result
= getDOM(`${djot.renderHTML(ast)}`);
917 const headElement
= domutils
.findOne(
918 (node
) => node
.name
== "head",
921 const titleElement
= domutils
.findOne(
922 (node
) => node
.name
== "title",
925 const contentElement
= domutils
.findOne(
926 (node
) => node
.name
== "gitwikiweb-content",
929 if (headElement
== null) {
931 "GitWikiWeb: Template must explicitly include a <head> element.",
934 domutils
.appendChild(
936 new Element("link", {
939 href
: `/${pageRef}/source.djot`,
942 if (titleElement
== null) {
943 domutils
.prependChild(
945 new Element("title", {}, [new Text(title
)]),
948 domutils
.prependChild(titleElement
, new Text(`${title} | `));
951 if (contentElement
== null) {
953 "GitWikiWeb: Template did not include a <gitwikiweb-content> element.",
956 for (const node
of result
) {
957 domutils
.prepend(contentElement
, node
);
959 domutils
.removeElement(contentElement
);
963 `${DESTINATION}/${pageRef}/index.html`,
966 encodeEntities
: "utf8",
967 selfClosingTags
: true,
975 `${DESTINATION}/${pageRef}/source.djot`,
981 await Promise
.allSettled(promises
).then(
982 logErrorsAndCollectResults
,
984 console
.log(`GitWikiWeb: Wrote ${pages.size} page(s).`);