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
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.195.0/fs/mod.ts";
41 import djot
from "npm:@djot/djot@0.2.3";
42 import { Parser
} from "npm:htmlparser2@9.0.0";
43 import { DomHandler
, Element
, Text
} from "npm:domhandler@5.0.3";
44 import * as domutils
from "npm:domutils@3.1.0";
45 import domSerializer
from "npm:dom-serializer@2.0.0";
47 const DESTINATION
= Deno
.args
[0] ?? "~/public/wiki";
48 const REMOTE
= Deno
.args
[1] ?? "/srv/git/GitWikiWeb";
56 const rawBlock
= (strings
, ...substitutions
) => ({
59 text
: String
.raw(strings
, substitutions
),
61 const rawInline
= (strings
, ...substitutions
) => ({
64 text
: String
.raw(strings
, substitutions
),
66 const str
= (strings
, ...substitutions
) => ({
68 text
: String
.raw(strings
, substitutions
),
71 const getDOM
= (source
) => {
73 const handler
= new DomHandler((error
, dom
) => {
75 throw new Error("GitWikiWeb: Failed to process DOM.", {
82 const parser
= new Parser(handler
);
88 const getRemoteContent
= async (pathName
) => {
89 const getArchive
= new Deno
.Command("git", {
90 args
: ["archive", `--remote=${REMOTE}`, "HEAD", pathName
],
94 const untar
= new Deno
.Command("tar", {
100 getArchive
.stdout
.pipeTo(untar
.stdin
);
107 ] = await Promise
.allSettled([
108 new Response(getArchive
.stderr
).text(),
110 new Response(untar
.stdout
).text(),
111 new Response(untar
.stderr
).text(),
113 ]).then(logErrorsAndCollectResults
);
115 console
.error(err1
+ err2
);
119 if (!getArchiveStatus
.success
) {
121 `GitWikiWeb: git archive returned nonzero exit code: ${getArchiveStatus.code}.`,
123 } else if (!untarStatus
.success
) {
125 `GitWikiWeb: tar returned nonzero exit code: ${untarStatus.code}.`,
132 const logErrorsAndCollectResults
= (results
) =>
133 results
.map(({ value
, reason
}) => {
135 console
.error(reason
);
142 const getReferenceFromPath
= (path
) =>
143 /Sources\/([A-Z][0-9A-Za-z]*\/[A-Z][0-9A-Za-z]*)\.djot$/u.exec(path
)
144 ?.[1]?.replace
?.("/", ":");
146 const listOfInternalLinks
= (references
, wrapper
= ($) => $) => ({
150 children
: Array
.from(
153 const [namespace, pageName
] = splitReference(reference
);
161 "data-realm": "internal",
162 "data-pagename": pageName
,
163 "data-namespace": namespace,
174 const diffReferences
= async (hash
) => {
175 const diff
= new Deno
.Command("git", {
188 const [diffNames
] = await Promise
.allSettled([
189 new Response(diff
.stdout
).text(),
190 new Response(diff
.stderr
).text(),
191 ]).then(logErrorsAndCollectResults
);
192 return references(diffNames
.split("\0")); // returns an iterable
195 function* references(paths
) {
196 for (const path
of paths
) {
197 const reference
= getReferenceFromPath(path
);
206 const splitReference
= (reference
) => {
207 const colonIndex
= reference
.indexOf(":");
209 reference
.substring(0, colonIndex
),
210 reference
.substring(colonIndex
+ 1),
214 class GitWikiWebPage
{
215 #internalLinks
= new Set();
216 #externalLinks
= new Map();
218 constructor(namespace, name
, ast
, source
) {
219 const internalLinks
= this.#internalLinks
;
220 const externalLinks
= this.#externalLinks
;
221 const sections
= Object
.create(null);
222 djot
.applyFilter(ast
, () => {
223 let titleSoFar
= null; // used to collect strs from headings
228 const links_section
= [];
229 if (internalLinks
.size
|| externalLinks
.size
) {
232 rawBlock
`<nav id="links">`,
236 children
: [str
`this page contains links`],
239 if (internalLinks
.size
) {
241 rawBlock
`<details open="">`,
242 rawBlock
`<summary>on this wiki</summary>`,
243 listOfInternalLinks(internalLinks
),
244 rawBlock
`</details>`,
249 if (externalLinks
.size
) {
251 rawBlock
`<details open="">`,
252 rawBlock
`<summary>elsewhere on the Web</summary>`,
257 children
: Array
.from(
259 ([destination
, text
]) => ({
265 attributes
: { "data-realm": "external" },
283 rawBlock
`</details>`,
295 e
.children
.push(...links_section
);
300 if (titleSoFar
!= null) {
314 const { attributes
} = e
;
315 attributes
.title
??= titleSoFar
;
322 const { attributes
, reference
, destination
} = e
;
324 /^(?:[A-Z][0-9A-Za-z]*|[@#])?:(?:[A-Z][0-9A-Za-z]*)?$/u
325 .test(reference
?? "")
327 const [namespacePrefix
, pageName
] = splitReference(
330 const expandedNamespace
= {
334 }[namespacePrefix
] ?? namespacePrefix
;
335 const resolvedReference
= pageName
== ""
336 ? `Namespace:${expandedNamespace}`
337 : `${expandedNamespace}:${pageName}`;
338 this.#internalLinks
.add(resolvedReference
);
339 e
.reference
= resolvedReference
;
340 attributes
["data-realm"] = "internal";
341 attributes
["data-pagename"] = pageName
;
342 attributes
["data-namespace"] = expandedNamespace
;
344 attributes
["data-realm"] = "external";
345 const remote
= destination
??
346 ast
.references
[reference
]?.destination
;
348 externalLinks
.set(remote
, attributes
?.title
);
355 non_breaking_space
: {
357 if (titleSoFar
!= null) {
358 titleSoFar
+= "\xA0";
369 const { attributes
, children
} = e
;
370 const heading
= children
.find(({ tag
}) =>
373 const title
= (() => {
374 if (heading
?.attributes
?.title
) {
375 const result
= heading
.attributes
.title
;
376 delete heading
.attributes
.title
;
379 return heading
.level
== 1
380 ? `${namespace}:${name}`
381 : "untitled section";
384 const variantTitles
= Object
.create(null);
385 for (const attr
in attributes
) {
386 if (attr
.startsWith("v-")) {
387 Object
.defineProperty(
390 { ...READ_ONLY
, value
: attributes
[attr
] },
392 delete attributes
[attr
];
397 const definition
= Object
.create(null, {
398 title
: { ...READ_ONLY
, value
: title
},
401 value
: Object
.preventExtensions(variantTitles
),
404 if (heading
.level
== 1 && !("main" in sections
)) {
405 attributes
.id
= "main";
406 heading
.attributes
??= {};
407 heading
.attributes
.class = "main";
412 Object
.defineProperty(
418 value
: Object
.preventExtensions(definition
),
423 `GitWikiWeb: A section with the provided @id already exists: ${attributes.id}`,
431 if (titleSoFar
!= null) {
440 enter
: ({ text
}) => {
441 if (titleSoFar
!= null) {
451 Object
.defineProperties(this, {
452 ast
: { ...READ_ONLY
, value
: ast
},
453 namespace: { ...READ_ONLY
, value
: namespace },
454 name
: { ...READ_ONLY
, value
: name
},
457 value
: Object
.preventExtensions(sections
),
459 source
: { ...READ_ONLY
, value
: source
},
464 yield* this.#externalLinks
;
468 yield* this.#internalLinks
;
473 const ls
= new Deno
.Command("git", {
474 args
: ["ls-tree", "-rz", "live"],
482 ] = await Promise
.allSettled([
483 new Response(ls
.stdout
).text().then((lsout
) =>
486 .slice(0, -1) // drop the last entry; it is empty
487 .map(($) => $.split(/\s+/g))
489 new Response(ls
.stderr
).text(),
491 ]).then(logErrorsAndCollectResults
);
493 console
.error(lserr
);
497 if (!lsstatus
.success
) {
499 `GitWikiWeb: git ls-tree returned nonzero exit code: ${lsstatus.code}.`,
502 const requiredButMissingPages
= new Map([
503 ["Special:FrontPage", "front page"],
504 ["Special:NotFound", "not found"],
505 ["Special:RecentlyChanged", "recently changed"],
507 const pages
= new Map();
508 const promises
= [emptyDir(DESTINATION
)];
509 for (const object
of objects
) {
510 const hash
= object
[2];
511 const path
= object
[3];
512 const reference
= getReferenceFromPath(path
);
513 if (reference
== null) {
516 const [namespace, pageName
] = splitReference(reference
);
517 const cat
= new Deno
.Command("git", {
518 args
: ["cat-file", "blob", hash
],
522 const promise
= Promise
.allSettled([
523 new Response(cat
.stdout
).text(),
524 new Response(cat
.stderr
).text(),
526 ]).then(logErrorsAndCollectResults
).then(
527 ([source
, caterr
, catstatus
]) => {
529 console
.error(caterr
);
533 if (!catstatus
.success
) {
535 `GitWikiWeb: git cat-file returned nonzero exit code: ${catstatus.code}.`,
538 const page
= new GitWikiWebPage(
543 console
.warn(`Djot(${reference}): ${$.render()}`),
547 const reference
= `${namespace}:${pageName}`;
548 pages
.set(reference
, page
);
549 requiredButMissingPages
.delete(reference
);
553 promises
.push(promise
);
556 for (const [reference
, defaultTitle
] of requiredButMissingPages
) {
557 const [namespace, pageName
] = splitReference(reference
);
558 const source
= `# ${defaultTitle}\n`;
559 const page
= new GitWikiWebPage(
564 console
.warn(`Djot(${reference}): ${$.render()}`),
568 pages
.set(reference
, page
);
570 await Promise
.allSettled(promises
).then(
571 logErrorsAndCollectResults
,
573 const [template
, recentlyChanged
] = await Promise
.allSettled([
574 getRemoteContent("template.html"),
576 const dateParse
= new Deno
.Command("git", {
577 args
: ["rev-parse", "--after=1 week ago"],
581 const [maxAge
] = await Promise
.allSettled([
582 new Response(dateParse
.stdout
).text(),
583 new Response(dateParse
.stderr
).text(),
584 ]).then(logErrorsAndCollectResults
);
589 const revList
= new Deno
.Command("git", {
590 args
: ["rev-list", maxAge
, "--reverse", "HEAD"],
594 [commit
] = await Promise
.allSettled([
595 new Response(revList
.stdout
).text().then((list
) =>
598 new Response(revList
.stderr
).text(),
599 ]).then(logErrorsAndCollectResults
);
602 const revList2
= new Deno
.Command("git", {
603 args
: ["rev-list", "--max-count=1", "HEAD^"],
607 [commit
] = await Promise
.allSettled([
608 new Response(revList2
.stdout
).text().then((list
) =>
611 new Response(revList2
.stderr
).text(),
612 ]).then(logErrorsAndCollectResults
);
616 const results
= new Array(6);
617 const seen
= new Set();
621 const show
= new Deno
.Command("git", {
625 "--format=%H%x00%cI%x00%cD",
626 recency
? `HEAD~${5 - recency}` : commit
,
632 [hash
, dateTime
, humanReadable
],
633 ] = await Promise
.allSettled([
634 new Response(show
.stdout
).text().then((rev
) =>
635 rev
.trim().split("\0")
637 new Response(show
.stderr
).text(),
638 ]).then(logErrorsAndCollectResults
);
641 for (const ref
of (await
diffReferences(current
))) {
649 results
[recency
] = { dateTime
, humanReadable
, refs
};
650 } while (recency
-- > 0 && current
&& current
!= commit
);
655 (name
) => ensureDir(`${DESTINATION}/${name}`),
657 ["style.css"].map((dependency
) =>
658 getRemoteContent(dependency
).then((source
) =>
660 `${DESTINATION}/${dependency}`,
666 ]).then(logErrorsAndCollectResults
);
668 const redLinks
= (() => {
669 const result
= new Set();
670 for (const page
of pages
.values()) {
671 for (const link
of page
.internalLinks()) {
672 if (pages
.has(link
)) {
682 const [pageRef
, { ast
, namespace, sections
, source
}] of pages
684 const title
= sections
.main
?.title
?? pageRef
;
685 djot
.applyFilter(ast
, () => {
686 let isNavigationPage
= true;
690 const { content
, navigation
} = (() => {
691 const navigation
= [];
692 if (pageRef
== "Special:RecentlyChanged") {
695 attributes
: { class: "recent-changes" },
698 children
: Array
.from(function* () {
700 const [index
, result
] of recentlyChanged
703 if (result
!= null) {
709 yield* listOfInternalLinks(refs
, (link
) => ({
710 tag
: index
== 0 ? "span" : "strong",
711 attributes
: { "data-recency": `${index}` },
714 ...(index
== 0 ? [] : [
716 rawInline
`<small>(<time dateTime="${dateTime}">`,
717 str
`${humanReadable}`,
718 rawInline
`</time>)</small>`,
729 isNavigationPage
= false;
730 return { content
: e
.children
, navigation
};
738 generated
: "", // will be removed later
741 children
: [str
`${title}`],
743 rawBlock
`<details id="navigation-about" open="">`,
744 rawBlock
`<summary>about this listing</summary>`,
747 rawBlock
`</article>`,
748 rawBlock
`</details>`,
751 rawBlock
`<nav id="navigation">`,
761 rawBlock
`</article>`,
768 const attributes
= e
.attributes
?? Object
.create(null);
770 isNavigationPage
&& e
.level
== 1 &&
771 attributes
?.class == "main"
773 if ("generated" in attributes
) {
774 delete attributes
.generated
;
783 if (e
.level
== 1 && e
.attributes
?.class == "main") {
785 rawBlock
`<header class="main">`,
787 { tag
: "verbatim", text
: pageRef
},
799 const { attributes
, children
, reference
} = e
;
800 if (attributes
["data-realm"] == "internal") {
802 if (redLinks
.has(reference
)) {
804 `/Special:NotFound?path=/${reference}`;
805 attributes
["data-notfound"] = "";
807 e
.destination
= `/${reference}`;
809 if (children
.length
== 0) {
811 pages
.get(reference
)?.sections
?.main
??
813 const { v
} = attributes
;
816 str
`${section.title ?? reference}`,
822 section.variantTitles?.[v] ?? section.title ??
829 if (children
.length
== 0 && "title" in attributes
) {
832 str
`${attributes.title}`,
838 (attributes
.class ?? "").split(/\s/gu).includes("sig")
842 attributes
: { class: "sig" },
843 children
: [str
`—${"\xA0"}`, e
],
853 if (e
.children
.length
< 1) {
854 // The heading for this section was removed and it had
855 // no other children.
864 const doc
= getDOM(template
);
865 const result
= getDOM(`${djot.renderHTML(ast)}`);
866 const headElement
= domutils
.findOne(
867 (node
) => node
.name
== "head",
870 const titleElement
= domutils
.findOne(
871 (node
) => node
.name
== "title",
874 const contentElement
= domutils
.findOne(
875 (node
) => node
.name
== "gitwikiweb-content",
878 if (headElement
== null) {
880 "GitWikiWeb: Template must explicitly include a <head> element.",
883 domutils
.appendChild(
885 new Element("link", {
888 href
: `/${pageRef}/source.djot`,
891 if (titleElement
== null) {
892 domutils
.prependChild(
894 new Element("title", {}, [new Text(title
)]),
897 domutils
.prependChild(titleElement
, new Text(`${title} | `));
900 if (contentElement
== null) {
902 "GitWikiWeb: Template did not include a <gitwikiweb-content> element.",
905 for (const node
of result
) {
906 domutils
.prepend(contentElement
, node
);
908 domutils
.removeElement(contentElement
);
912 `${DESTINATION}/${pageRef}/index.html`,
915 encodeEntities
: "utf8",
916 selfClosingTags
: true,
924 `${DESTINATION}/${pageRef}/source.djot`,
930 await Promise
.allSettled(promises
).then(
931 logErrorsAndCollectResults
,
933 console
.log(`GitWikiWeb: Wrote ${pages.size} page(s).`);