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();
670 const show
= new Deno
.Command("git", {
674 "--format=%H%x00%cI%x00%cD",
675 recency
? `HEAD~${5 - recency}` : commit
,
681 [hash
, dateTime
, humanReadable
],
682 ] = await Promise
.allSettled([
683 new Response(show
.stdout
).text().then((rev
) =>
684 rev
.trim().split("\0")
686 new Response(show
.stderr
).text(),
687 ]).then(logErrorsAndCollectResults
);
691 const ref
of (await
diffReferences(current
, !recency
))
700 results
[recency
] = { dateTime
, hash
, humanReadable
, refs
};
701 } while (recency
-- > 0 && current
&& current
!= commit
);
706 (name
) => ensureDir(`${DESTINATION}/${name}`),
708 ["style.css"].map((dependency
) =>
709 getRemoteContent(dependency
).then((source
) =>
711 `${DESTINATION}/${dependency}`,
717 ]).then(logErrorsAndCollectResults
);
719 const redLinks
= (() => {
720 const result
= new Set();
721 for (const page
of pages
.values()) {
722 for (const link
of page
.internalLinks()) {
723 if (pages
.has(link
)) {
733 const [pageRef
, { ast
, namespace, sections
, source
}] of pages
735 const title
= sections
.main
?.title
?? pageRef
;
736 djot
.applyFilter(ast
, () => {
737 let isNavigationPage
= true;
741 const { content
, navigation
} = (() => {
742 const navigation
= [];
743 if (pageRef
== "Special:RecentlyChanged") {
746 attributes
: { class: "recent-changes" },
749 children
: Array
.from(function* () {
751 const [index
, result
] of recentlyChanged
754 if (result
!= null) {
760 yield* listOfInternalLinks(refs
, (link
) => ({
761 tag
: index
== 0 ? "span" : "strong",
762 attributes
: { "data-recency": `${index}` },
765 ...(index
== 0 ? [] : [
767 rawInline
`<small>(<time dateTime="${dateTime}">`,
768 str
`${humanReadable}`,
769 rawInline
`</time>)</small>`,
780 isNavigationPage
= false;
781 return { content
: e
.children
, navigation
};
789 generated
: "", // will be removed later
792 children
: [str
`${title}`],
794 rawBlock
`<details id="navigation-about" open="">`,
795 rawBlock
`<summary>about this listing</summary>`,
798 rawBlock
`</article>`,
799 rawBlock
`</details>`,
802 rawBlock
`<nav id="navigation">`,
812 rawBlock
`</article>`,
819 const attributes
= e
.attributes
?? NIL
;
821 isNavigationPage
&& e
.level
== 1 &&
822 attributes
?.class == "main"
824 if ("generated" in attributes
) {
825 delete attributes
.generated
;
834 if (e
.level
== 1 && e
.attributes
?.class == "main") {
836 rawBlock
`<header class="main">`,
838 { tag
: "verbatim", text
: pageRef
},
850 const { attributes
, children
, reference
} = e
;
851 if (attributes
["data-realm"] == "internal") {
853 if (redLinks
.has(reference
)) {
855 `/Special:NotFound?path=/${reference}`;
856 attributes
["data-notfound"] = "";
858 e
.destination
= `/${reference}`;
860 if (children
.length
== 0) {
862 pages
.get(reference
)?.sections
?.main
?? NIL
;
863 const { v
} = attributes
;
866 str
`${section.title ?? reference}`,
872 section.variantTitles?.[v] ?? section.title ??
879 if (children
.length
== 0 && "title" in attributes
) {
882 str
`${attributes.title}`,
888 (attributes
.class ?? "").split(/\s/gu).includes("sig")
892 attributes
: { class: "sig" },
893 children
: [str
`—${"\xA0"}`, e
],
903 if (e
.children
.length
< 1) {
904 // The heading for this section was removed and it had
905 // no other children.
914 const doc
= getDOM(template
);
915 const result
= getDOM(`${djot.renderHTML(ast)}`);
916 const headElement
= domutils
.findOne(
917 (node
) => node
.name
== "head",
920 const titleElement
= domutils
.findOne(
921 (node
) => node
.name
== "title",
924 const contentElement
= domutils
.findOne(
925 (node
) => node
.name
== "gitwikiweb-content",
928 if (headElement
== null) {
930 "GitWikiWeb: Template must explicitly include a <head> element.",
933 domutils
.appendChild(
935 new Element("link", {
938 href
: `/${pageRef}/source.djot`,
941 if (titleElement
== null) {
942 domutils
.prependChild(
944 new Element("title", {}, [new Text(title
)]),
947 domutils
.prependChild(titleElement
, new Text(`${title} | `));
950 if (contentElement
== null) {
952 "GitWikiWeb: Template did not include a <gitwikiweb-content> element.",
955 for (const node
of result
) {
956 domutils
.prepend(contentElement
, node
);
958 domutils
.removeElement(contentElement
);
962 `${DESTINATION}/${pageRef}/index.html`,
965 encodeEntities
: "utf8",
966 selfClosingTags
: true,
974 `${DESTINATION}/${pageRef}/source.djot`,
980 await Promise
.allSettled(promises
).then(
981 logErrorsAndCollectResults
,
983 console
.log(`GitWikiWeb: Wrote ${pages.size} page(s).`);