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
);
307 if (titleSoFar
!= null) {
321 const { attributes
} = e
;
322 attributes
.title
??= titleSoFar
;
329 const { attributes
, reference
, destination
} = e
;
331 /^(?:[A-Z][0-9A-Za-z]*|[@#])?:(?:[A-Z][0-9A-Za-z]*)?$/u
332 .test(reference
?? "")
334 const [namespacePrefix
, pageName
] = splitReference(
337 const expandedNamespace
= {
341 }[namespacePrefix
] ?? namespacePrefix
;
342 const resolvedReference
= pageName
== ""
343 ? `Namespace:${expandedNamespace}`
344 : `${expandedNamespace}:${pageName}`;
345 this.#internalLinks
.add(resolvedReference
);
346 e
.reference
= resolvedReference
;
347 attributes
["data-realm"] = "internal";
348 attributes
["data-pagename"] = pageName
;
349 attributes
["data-namespace"] = expandedNamespace
;
351 attributes
["data-realm"] = "external";
352 const remote
= destination
??
353 ast
.references
[reference
]?.destination
;
355 externalLinks
.set(remote
, attributes
?.title
);
362 non_breaking_space
: {
364 if (titleSoFar
!= null) {
365 titleSoFar
+= "\xA0";
376 const { attributes
, children
} = e
;
377 const heading
= children
.find(({ tag
}) =>
380 const title
= (() => {
381 if (heading
?.attributes
?.title
) {
382 const result
= heading
.attributes
.title
;
383 delete heading
.attributes
.title
;
386 return heading
.level
== 1
387 ? `${namespace}:${name}`
388 : "untitled section";
391 const variantTitles
= Object
.create(null);
392 for (const attr
in attributes
) {
393 if (attr
.startsWith("v-")) {
394 Object
.defineProperty(
397 { ...READ_ONLY
, value
: attributes
[attr
] },
399 delete attributes
[attr
];
404 const definition
= Object
.create(null, {
405 title
: { ...READ_ONLY
, value
: title
},
408 value
: Object
.preventExtensions(variantTitles
),
411 if (heading
.level
== 1 && !("main" in sections
)) {
412 attributes
.id
= "main";
413 heading
.attributes
??= {};
414 heading
.attributes
.class = "main";
419 Object
.defineProperty(
425 value
: Object
.preventExtensions(definition
),
430 `GitWikiWeb: A section with the provided @id already exists: ${attributes.id}`,
438 if (titleSoFar
!= null) {
447 enter
: ({ text
}) => {
448 if (titleSoFar
!= null) {
459 const codepoint
= /^U\+([0-9A-Fa-f]+)$/u.exec(alias
)?.[1];
462 String.fromCodePoint(parseInt(codepoint, 16))
465 const resolved
= config
.symbols
?.[alias
];
466 return resolved
!= null ? str
`${resolved}` : e
;
472 Object
.defineProperties(this, {
473 ast
: { ...READ_ONLY
, value
: ast
},
474 namespace: { ...READ_ONLY
, value
: namespace },
475 name
: { ...READ_ONLY
, value
: name
},
478 value
: Object
.preventExtensions(sections
),
480 source
: { ...READ_ONLY
, value
: source
},
485 yield* this.#externalLinks
;
489 yield* this.#internalLinks
;
494 // Patches for Djot HTML renderer.
495 const { HTMLRenderer
: { prototype: htmlRendererPrototype
} } = djot
;
496 const { inTags
: upstreamInTags
} = htmlRendererPrototype
;
497 htmlRendererPrototype
.inTags = function (
501 extraAttrs
= undefined,
503 const attributes
= node
.attributes
?? NIL
;
504 if ("as" in attributes
) {
505 const newTag
= attributes
.as
;
506 delete attributes
.as
;
507 return upstreamInTags
.call(
515 return upstreamInTags
.call(
526 const config
= await
getRemoteContent("config.yaml").then((yaml
) =>
527 parseYaml(yaml
, { schema
: JSON_SCHEMA
})
529 const ls
= new Deno
.Command("git", {
530 args
: ["ls-tree", "-rz", "HEAD"],
538 ] = await Promise
.allSettled([
539 new Response(ls
.stdout
).text().then((lsout
) =>
542 .slice(0, -1) // drop the last entry; it is empty
543 .map(($) => $.split(/\s+/g))
545 new Response(ls
.stderr
).text(),
547 ]).then(logErrorsAndCollectResults
);
549 console
.error(lserr
);
553 if (!lsstatus
.success
) {
555 `GitWikiWeb: git ls-tree returned nonzero exit code: ${lsstatus.code}.`,
558 const requiredButMissingPages
= new Map([
559 ["Special:FrontPage", "front page"],
560 ["Special:NotFound", "not found"],
561 ["Special:RecentlyChanged", "recently changed"],
563 const pages
= new Map();
564 const promises
= [emptyDir(DESTINATION
)];
565 for (const object
of objects
) {
566 const hash
= object
[2];
567 const path
= object
[3];
568 const reference
= getReferenceFromPath(path
);
569 if (reference
== null) {
572 const [namespace, pageName
] = splitReference(reference
);
573 const cat
= new Deno
.Command("git", {
574 args
: ["cat-file", "blob", hash
],
578 const promise
= Promise
.allSettled([
579 new Response(cat
.stdout
).text(),
580 new Response(cat
.stderr
).text(),
582 ]).then(logErrorsAndCollectResults
).then(
583 ([source
, caterr
, catstatus
]) => {
585 console
.error(caterr
);
589 if (!catstatus
.success
) {
591 `GitWikiWeb: git cat-file returned nonzero exit code: ${catstatus.code}.`,
594 const page
= new GitWikiWebPage(
599 console
.warn(`Djot(${reference}): ${$.render()}`),
604 const reference
= `${namespace}:${pageName}`;
605 pages
.set(reference
, page
);
606 requiredButMissingPages
.delete(reference
);
610 promises
.push(promise
);
613 for (const [reference
, defaultTitle
] of requiredButMissingPages
) {
614 const [namespace, pageName
] = splitReference(reference
);
615 const source
= `# ${defaultTitle}\n`;
616 const page
= new GitWikiWebPage(
621 console
.warn(`Djot(${reference}): ${$.render()}`),
626 pages
.set(reference
, page
);
628 await Promise
.allSettled(promises
).then(
629 logErrorsAndCollectResults
,
631 const [template
, recentlyChanged
] = await Promise
.allSettled([
632 getRemoteContent("template.html"),
634 const dateParse
= new Deno
.Command("git", {
635 args
: ["rev-parse", "--after=1 week ago"],
639 const [maxAge
] = await Promise
.allSettled([
640 new Response(dateParse
.stdout
).text(),
641 new Response(dateParse
.stderr
).text(),
642 ]).then(logErrorsAndCollectResults
);
647 const revList
= new Deno
.Command("git", {
648 args
: ["rev-list", maxAge
, "--reverse", "HEAD"],
652 [commit
] = await Promise
.allSettled([
653 new Response(revList
.stdout
).text().then((list
) =>
656 new Response(revList
.stderr
).text(),
657 ]).then(logErrorsAndCollectResults
);
660 const revList2
= new Deno
.Command("git", {
661 args
: ["rev-list", "--max-count=1", "HEAD^"],
665 [commit
] = await Promise
.allSettled([
666 new Response(revList2
.stdout
).text().then((list
) =>
669 new Response(revList2
.stderr
).text(),
670 ]).then(logErrorsAndCollectResults
);
674 const results
= new Array(6);
675 const seen
= new Set();
676 const maxRecency
= Math
.max(config
.max_recency
| 0, 0);
677 let recency
= maxRecency
;
680 const show
= new Deno
.Command("git", {
684 "--format=%H%x00%cI%x00%cD",
685 recency
? `HEAD~${maxRecency - recency}` : commit
,
691 [hash
, dateTime
, humanReadable
],
692 ] = await Promise
.allSettled([
693 new Response(show
.stdout
).text().then((rev
) =>
694 rev
.trim().split("\0")
696 new Response(show
.stderr
).text(),
697 ]).then(logErrorsAndCollectResults
);
701 const ref
of (await
diffReferences(current
, !recency
))
710 results
[recency
] = { dateTime
, hash
, humanReadable
, refs
};
711 } while (recency
-- > 0 && current
&& current
!= commit
);
716 (name
) => ensureDir(`${DESTINATION}/${name}`),
718 ["style.css"].map((dependency
) =>
719 getRemoteContent(dependency
).then((source
) =>
721 `${DESTINATION}/${dependency}`,
727 ]).then(logErrorsAndCollectResults
);
729 const redLinks
= (() => {
730 const result
= new Set();
731 for (const page
of pages
.values()) {
732 for (const link
of page
.internalLinks()) {
733 if (pages
.has(link
)) {
743 const [pageRef
, { ast
, namespace, sections
, source
}] of pages
745 const title
= sections
.main
?.title
?? pageRef
;
746 djot
.applyFilter(ast
, () => {
747 let isNavigationPage
= true;
751 const { content
, navigation
} = (() => {
752 const navigation
= [];
753 if (pageRef
== "Special:RecentlyChanged") {
756 attributes
: { class: "recent-changes" },
759 children
: Array
.from(function* () {
761 const [index
, result
] of recentlyChanged
764 if (result
!= null) {
770 yield* listOfInternalLinks(refs
, (link
) => ({
771 tag
: index
== 0 ? "span" : "strong",
772 attributes
: { "data-recency": `${index}` },
775 ...(index
== 0 ? [] : [
777 rawInline
`<small>(<time dateTime="${dateTime}">`,
778 str
`${humanReadable}`,
779 rawInline
`</time>)</small>`,
790 isNavigationPage
= false;
791 return { content
: e
.children
, navigation
};
799 generated
: "", // will be removed later
802 children
: [str
`${title}`],
804 rawBlock
`<details id="navigation-about" open="">`,
805 rawBlock
`<summary>about this listing</summary>`,
808 rawBlock
`</article>`,
809 rawBlock
`</details>`,
812 rawBlock
`<nav id="navigation">`,
822 rawBlock
`</article>`,
829 const attributes
= e
.attributes
?? NIL
;
831 isNavigationPage
&& e
.level
== 1 &&
832 attributes
?.class == "main"
834 if ("generated" in attributes
) {
835 delete attributes
.generated
;
844 if (e
.level
== 1 && e
.attributes
?.class == "main") {
846 rawBlock
`<header class="main">`,
848 { tag
: "verbatim", text
: pageRef
},
860 const { attributes
, children
, reference
} = e
;
861 if (attributes
["data-realm"] == "internal") {
863 if (redLinks
.has(reference
)) {
865 `/Special:NotFound?path=/${reference}`;
866 attributes
["data-notfound"] = "";
868 e
.destination
= `/${reference}`;
870 if (children
.length
== 0) {
872 pages
.get(reference
)?.sections
?.main
?? NIL
;
873 const { v
} = attributes
;
876 str
`${section.title ?? reference}`,
882 section.variantTitles?.[v] ?? section.title ??
889 if (children
.length
== 0 && "title" in attributes
) {
892 str
`${attributes.title}`,
898 (attributes
.class ?? "").split(/\s/gu).includes("sig")
902 attributes
: { class: "sig" },
903 children
: [str
`—${"\xA0"}`, e
],
913 if (e
.children
.length
< 1) {
914 // The heading for this section was removed and it had
915 // no other children.
924 const doc
= getDOM(template
);
925 const result
= getDOM(`${djot.renderHTML(ast)}`);
926 const headElement
= domutils
.findOne(
927 (node
) => node
.name
== "head",
930 const titleElement
= domutils
.findOne(
931 (node
) => node
.name
== "title",
934 const contentElement
= domutils
.findOne(
935 (node
) => node
.name
== "gitwikiweb-content",
938 if (headElement
== null) {
940 "GitWikiWeb: Template must explicitly include a <head> element.",
943 domutils
.appendChild(
945 new Element("link", {
948 href
: `/${pageRef}/source.djot`,
951 if (titleElement
== null) {
952 domutils
.prependChild(
954 new Element("title", {}, [new Text(title
)]),
957 domutils
.prependChild(titleElement
, new Text(`${title} | `));
960 if (contentElement
== null) {
962 "GitWikiWeb: Template did not include a <gitwikiweb-content> element.",
965 for (const node
of result
) {
966 domutils
.prepend(contentElement
, node
);
968 domutils
.removeElement(contentElement
);
972 `${DESTINATION}/${pageRef}/index.html`,
975 encodeEntities
: "utf8",
976 selfClosingTags
: true,
984 `${DESTINATION}/${pageRef}/source.djot`,
990 await Promise
.allSettled(promises
).then(
991 logErrorsAndCollectResults
,
993 console
.log(`GitWikiWeb: Wrote ${pages.size} page(s).`);