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 NIL
= Object
.preventExtensions(Object
.create(null));
58 const rawBlock
= (strings
, ...substitutions
) => ({
61 text
: String
.raw(strings
, substitutions
),
63 const rawInline
= (strings
, ...substitutions
) => ({
66 text
: String
.raw(strings
, substitutions
),
68 const str
= (strings
, ...substitutions
) => ({
70 text
: String
.raw(strings
, substitutions
),
73 const getDOM
= (source
) => {
75 const handler
= new DomHandler((error
, dom
) => {
77 throw new Error("GitWikiWeb: Failed to process DOM.", {
84 const parser
= new Parser(handler
);
90 const getRemoteContent
= async (pathName
) => {
91 const getArchive
= new Deno
.Command("git", {
92 args
: ["archive", `--remote=${REMOTE}`, "HEAD", pathName
],
96 const untar
= new Deno
.Command("tar", {
102 getArchive
.stdout
.pipeTo(untar
.stdin
);
109 ] = await Promise
.allSettled([
110 new Response(getArchive
.stderr
).text(),
112 new Response(untar
.stdout
).text(),
113 new Response(untar
.stderr
).text(),
115 ]).then(logErrorsAndCollectResults
);
117 console
.error(err1
+ err2
);
121 if (!getArchiveStatus
.success
) {
123 `GitWikiWeb: git archive returned nonzero exit code: ${getArchiveStatus.code}.`,
125 } else if (!untarStatus
.success
) {
127 `GitWikiWeb: tar returned nonzero exit code: ${untarStatus.code}.`,
134 const logErrorsAndCollectResults
= (results
) =>
135 results
.map(({ value
, reason
}) => {
137 console
.error(reason
);
144 const getReferenceFromPath
= (path
) =>
145 /Sources\/([A-Z][0-9A-Za-z]*\/[A-Z][0-9A-Za-z]*)\.djot$/u.exec(path
)
146 ?.[1]?.replace
?.("/", ":");
148 const listOfInternalLinks
= (references
, wrapper
= ($) => $) => ({
152 children
: Array
.from(
155 const [namespace, pageName
] = splitReference(reference
);
163 "data-realm": "internal",
164 "data-pagename": pageName
,
165 "data-namespace": namespace,
176 const diffReferences
= async (hash
) => {
177 const diff
= new Deno
.Command("git", {
190 const [diffNames
] = await Promise
.allSettled([
191 new Response(diff
.stdout
).text(),
192 new Response(diff
.stderr
).text(),
193 ]).then(logErrorsAndCollectResults
);
194 return references(diffNames
.split("\0")); // returns an iterable
197 function* references(paths
) {
198 for (const path
of paths
) {
199 const reference
= getReferenceFromPath(path
);
208 const splitReference
= (reference
) => {
209 const colonIndex
= reference
.indexOf(":");
211 reference
.substring(0, colonIndex
),
212 reference
.substring(colonIndex
+ 1),
216 class GitWikiWebPage
{
217 #internalLinks
= new Set();
218 #externalLinks
= new Map();
220 constructor(namespace, name
, ast
, source
) {
221 const internalLinks
= this.#internalLinks
;
222 const externalLinks
= this.#externalLinks
;
223 const sections
= Object
.create(null);
224 djot
.applyFilter(ast
, () => {
225 let titleSoFar
= null; // used to collect strs from headings
230 const links_section
= [];
231 if (internalLinks
.size
|| externalLinks
.size
) {
234 rawBlock
`<nav id="links">`,
238 children
: [str
`this page contains links`],
241 if (internalLinks
.size
) {
243 rawBlock
`<details open="">`,
244 rawBlock
`<summary>on this wiki</summary>`,
245 listOfInternalLinks(internalLinks
),
246 rawBlock
`</details>`,
251 if (externalLinks
.size
) {
253 rawBlock
`<details open="">`,
254 rawBlock
`<summary>elsewhere on the Web</summary>`,
259 children
: Array
.from(
261 ([destination
, text
]) => ({
267 attributes
: { "data-realm": "external" },
285 rawBlock
`</details>`,
297 e
.children
.push(...links_section
);
303 const attributes
= e
.attributes
?? NIL
;
304 const { as
} = attributes
;
306 delete attributes
.as
;
308 as
== "b" || as
== "cite" || as
== "i" || as
== "u"
325 if (titleSoFar
!= null) {
339 const { attributes
} = e
;
340 attributes
.title
??= titleSoFar
;
347 const { attributes
, reference
, destination
} = e
;
349 /^(?:[A-Z][0-9A-Za-z]*|[@#])?:(?:[A-Z][0-9A-Za-z]*)?$/u
350 .test(reference
?? "")
352 const [namespacePrefix
, pageName
] = splitReference(
355 const expandedNamespace
= {
359 }[namespacePrefix
] ?? namespacePrefix
;
360 const resolvedReference
= pageName
== ""
361 ? `Namespace:${expandedNamespace}`
362 : `${expandedNamespace}:${pageName}`;
363 this.#internalLinks
.add(resolvedReference
);
364 e
.reference
= resolvedReference
;
365 attributes
["data-realm"] = "internal";
366 attributes
["data-pagename"] = pageName
;
367 attributes
["data-namespace"] = expandedNamespace
;
369 attributes
["data-realm"] = "external";
370 const remote
= destination
??
371 ast
.references
[reference
]?.destination
;
373 externalLinks
.set(remote
, attributes
?.title
);
380 non_breaking_space
: {
382 if (titleSoFar
!= null) {
383 titleSoFar
+= "\xA0";
394 const { attributes
, children
} = e
;
395 const heading
= children
.find(({ tag
}) =>
398 const title
= (() => {
399 if (heading
?.attributes
?.title
) {
400 const result
= heading
.attributes
.title
;
401 delete heading
.attributes
.title
;
404 return heading
.level
== 1
405 ? `${namespace}:${name}`
406 : "untitled section";
409 const variantTitles
= Object
.create(null);
410 for (const attr
in attributes
) {
411 if (attr
.startsWith("v-")) {
412 Object
.defineProperty(
415 { ...READ_ONLY
, value
: attributes
[attr
] },
417 delete attributes
[attr
];
422 const definition
= Object
.create(null, {
423 title
: { ...READ_ONLY
, value
: title
},
426 value
: Object
.preventExtensions(variantTitles
),
429 if (heading
.level
== 1 && !("main" in sections
)) {
430 attributes
.id
= "main";
431 heading
.attributes
??= {};
432 heading
.attributes
.class = "main";
437 Object
.defineProperty(
443 value
: Object
.preventExtensions(definition
),
448 `GitWikiWeb: A section with the provided @id already exists: ${attributes.id}`,
456 if (titleSoFar
!= null) {
465 enter
: ({ text
}) => {
466 if (titleSoFar
!= null) {
476 Object
.defineProperties(this, {
477 ast
: { ...READ_ONLY
, value
: ast
},
478 namespace: { ...READ_ONLY
, value
: namespace },
479 name
: { ...READ_ONLY
, value
: name
},
482 value
: Object
.preventExtensions(sections
),
484 source
: { ...READ_ONLY
, value
: source
},
489 yield* this.#externalLinks
;
493 yield* this.#internalLinks
;
498 const ls
= new Deno
.Command("git", {
499 args
: ["ls-tree", "-rz", "live"],
507 ] = await Promise
.allSettled([
508 new Response(ls
.stdout
).text().then((lsout
) =>
511 .slice(0, -1) // drop the last entry; it is empty
512 .map(($) => $.split(/\s+/g))
514 new Response(ls
.stderr
).text(),
516 ]).then(logErrorsAndCollectResults
);
518 console
.error(lserr
);
522 if (!lsstatus
.success
) {
524 `GitWikiWeb: git ls-tree returned nonzero exit code: ${lsstatus.code}.`,
527 const requiredButMissingPages
= new Map([
528 ["Special:FrontPage", "front page"],
529 ["Special:NotFound", "not found"],
530 ["Special:RecentlyChanged", "recently changed"],
532 const pages
= new Map();
533 const promises
= [emptyDir(DESTINATION
)];
534 for (const object
of objects
) {
535 const hash
= object
[2];
536 const path
= object
[3];
537 const reference
= getReferenceFromPath(path
);
538 if (reference
== null) {
541 const [namespace, pageName
] = splitReference(reference
);
542 const cat
= new Deno
.Command("git", {
543 args
: ["cat-file", "blob", hash
],
547 const promise
= Promise
.allSettled([
548 new Response(cat
.stdout
).text(),
549 new Response(cat
.stderr
).text(),
551 ]).then(logErrorsAndCollectResults
).then(
552 ([source
, caterr
, catstatus
]) => {
554 console
.error(caterr
);
558 if (!catstatus
.success
) {
560 `GitWikiWeb: git cat-file returned nonzero exit code: ${catstatus.code}.`,
563 const page
= new GitWikiWebPage(
568 console
.warn(`Djot(${reference}): ${$.render()}`),
572 const reference
= `${namespace}:${pageName}`;
573 pages
.set(reference
, page
);
574 requiredButMissingPages
.delete(reference
);
578 promises
.push(promise
);
581 for (const [reference
, defaultTitle
] of requiredButMissingPages
) {
582 const [namespace, pageName
] = splitReference(reference
);
583 const source
= `# ${defaultTitle}\n`;
584 const page
= new GitWikiWebPage(
589 console
.warn(`Djot(${reference}): ${$.render()}`),
593 pages
.set(reference
, page
);
595 await Promise
.allSettled(promises
).then(
596 logErrorsAndCollectResults
,
598 const [template
, recentlyChanged
] = await Promise
.allSettled([
599 getRemoteContent("template.html"),
601 const dateParse
= new Deno
.Command("git", {
602 args
: ["rev-parse", "--after=1 week ago"],
606 const [maxAge
] = await Promise
.allSettled([
607 new Response(dateParse
.stdout
).text(),
608 new Response(dateParse
.stderr
).text(),
609 ]).then(logErrorsAndCollectResults
);
614 const revList
= new Deno
.Command("git", {
615 args
: ["rev-list", maxAge
, "--reverse", "HEAD"],
619 [commit
] = await Promise
.allSettled([
620 new Response(revList
.stdout
).text().then((list
) =>
623 new Response(revList
.stderr
).text(),
624 ]).then(logErrorsAndCollectResults
);
627 const revList2
= new Deno
.Command("git", {
628 args
: ["rev-list", "--max-count=1", "HEAD^"],
632 [commit
] = await Promise
.allSettled([
633 new Response(revList2
.stdout
).text().then((list
) =>
636 new Response(revList2
.stderr
).text(),
637 ]).then(logErrorsAndCollectResults
);
641 const results
= new Array(6);
642 const seen
= new Set();
646 const show
= new Deno
.Command("git", {
650 "--format=%H%x00%cI%x00%cD",
651 recency
? `HEAD~${5 - recency}` : commit
,
657 [hash
, dateTime
, humanReadable
],
658 ] = await Promise
.allSettled([
659 new Response(show
.stdout
).text().then((rev
) =>
660 rev
.trim().split("\0")
662 new Response(show
.stderr
).text(),
663 ]).then(logErrorsAndCollectResults
);
666 for (const ref
of (await
diffReferences(current
))) {
674 results
[recency
] = { dateTime
, humanReadable
, refs
};
675 } while (recency
-- > 0 && current
&& current
!= commit
);
680 (name
) => ensureDir(`${DESTINATION}/${name}`),
682 ["style.css"].map((dependency
) =>
683 getRemoteContent(dependency
).then((source
) =>
685 `${DESTINATION}/${dependency}`,
691 ]).then(logErrorsAndCollectResults
);
693 const redLinks
= (() => {
694 const result
= new Set();
695 for (const page
of pages
.values()) {
696 for (const link
of page
.internalLinks()) {
697 if (pages
.has(link
)) {
707 const [pageRef
, { ast
, namespace, sections
, source
}] of pages
709 const title
= sections
.main
?.title
?? pageRef
;
710 djot
.applyFilter(ast
, () => {
711 let isNavigationPage
= true;
715 const { content
, navigation
} = (() => {
716 const navigation
= [];
717 if (pageRef
== "Special:RecentlyChanged") {
720 attributes
: { class: "recent-changes" },
723 children
: Array
.from(function* () {
725 const [index
, result
] of recentlyChanged
728 if (result
!= null) {
734 yield* listOfInternalLinks(refs
, (link
) => ({
735 tag
: index
== 0 ? "span" : "strong",
736 attributes
: { "data-recency": `${index}` },
739 ...(index
== 0 ? [] : [
741 rawInline
`<small>(<time dateTime="${dateTime}">`,
742 str
`${humanReadable}`,
743 rawInline
`</time>)</small>`,
754 isNavigationPage
= false;
755 return { content
: e
.children
, navigation
};
763 generated
: "", // will be removed later
766 children
: [str
`${title}`],
768 rawBlock
`<details id="navigation-about" open="">`,
769 rawBlock
`<summary>about this listing</summary>`,
772 rawBlock
`</article>`,
773 rawBlock
`</details>`,
776 rawBlock
`<nav id="navigation">`,
786 rawBlock
`</article>`,
793 const attributes
= e
.attributes
?? NIL
;
795 isNavigationPage
&& e
.level
== 1 &&
796 attributes
?.class == "main"
798 if ("generated" in attributes
) {
799 delete attributes
.generated
;
808 if (e
.level
== 1 && e
.attributes
?.class == "main") {
810 rawBlock
`<header class="main">`,
812 { tag
: "verbatim", text
: pageRef
},
824 const { attributes
, children
, reference
} = e
;
825 if (attributes
["data-realm"] == "internal") {
827 if (redLinks
.has(reference
)) {
829 `/Special:NotFound?path=/${reference}`;
830 attributes
["data-notfound"] = "";
832 e
.destination
= `/${reference}`;
834 if (children
.length
== 0) {
836 pages
.get(reference
)?.sections
?.main
?? NIL
;
837 const { v
} = attributes
;
840 str
`${section.title ?? reference}`,
846 section.variantTitles?.[v] ?? section.title ??
853 if (children
.length
== 0 && "title" in attributes
) {
856 str
`${attributes.title}`,
862 (attributes
.class ?? "").split(/\s/gu).includes("sig")
866 attributes
: { class: "sig" },
867 children
: [str
`—${"\xA0"}`, e
],
877 if (e
.children
.length
< 1) {
878 // The heading for this section was removed and it had
879 // no other children.
888 const doc
= getDOM(template
);
889 const result
= getDOM(`${djot.renderHTML(ast)}`);
890 const headElement
= domutils
.findOne(
891 (node
) => node
.name
== "head",
894 const titleElement
= domutils
.findOne(
895 (node
) => node
.name
== "title",
898 const contentElement
= domutils
.findOne(
899 (node
) => node
.name
== "gitwikiweb-content",
902 if (headElement
== null) {
904 "GitWikiWeb: Template must explicitly include a <head> element.",
907 domutils
.appendChild(
909 new Element("link", {
912 href
: `/${pageRef}/source.djot`,
915 if (titleElement
== null) {
916 domutils
.prependChild(
918 new Element("title", {}, [new Text(title
)]),
921 domutils
.prependChild(titleElement
, new Text(`${title} | `));
924 if (contentElement
== null) {
926 "GitWikiWeb: Template did not include a <gitwikiweb-content> element.",
929 for (const node
of result
) {
930 domutils
.prepend(contentElement
, node
);
932 domutils
.removeElement(contentElement
);
936 `${DESTINATION}/${pageRef}/index.html`,
939 encodeEntities
: "utf8",
940 selfClosingTags
: true,
948 `${DESTINATION}/${pageRef}/source.djot`,
954 await Promise
.allSettled(promises
).then(
955 logErrorsAndCollectResults
,
957 console
.log(`GitWikiWeb: Wrote ${pages.size} page(s).`);