The configuration and the command line
The tangler and the weaver are used through one command, literate, run at
the root of a project:
literate tangle write every file the documents define
literate tangle --check write nothing; fail if a file differs from its document
literate tangle --out DIR write the files under DIR instead
literate tangle --list list the files and the chunks
literate tangle --where FILE:LINE the document line a line of a file comes from
literate weave weave the website into site/
literate weave --branch B ... with the links to files pointing to branch B
literate build tangle, then weave if markdown and pygments are installed
python3 -m literate does the same as literate. What the commands need
to know about the project is in a small file at its root.
The package
The package is literate; its version is given here, once, and read from
here by pyproject.toml when the package is built.
"""Literate programming in Markdown: tangle programs and weave websites out of documents in which the code is indented and named in chunks.""" __version__ = "0.1.0"
python3 -m literate runs the command line.
import sys from .cli import main sys.exit(main())
The configuration
A project says what the tools need to know in literate.json, at its root.
It is JSON, which the standard library reads in every version of Python
the tools support (TOML only from 3.11). Every key is optional, and a
project without the file gets the defaults:
{
"name": "opensheaf-py",
"tagline": "the tools of <a href=\"https://opensheaf.org\">OpenSheaf</a>, a literate program",
"repository": "https://github.com/opensheaf/opensheaf-py",
"branch": "main",
"documents": "literate",
"site": "site",
"logo": "literate/opensheaf-symbol.svg",
"logoDark": "invert",
"links": {"the explorer": "../"},
"template": "literate/weave.html",
"stylesheet": "literate/weave.css",
"comments": {".html": "<!-- {} -->", ".js": null}
}
name: the name of the project, in the header of every page and in the titles of the pages; by default, the name of the folder of the project.tagline: a line about the project, in HTML, at the foot of every page.repository: the address of the repository, for the link to the source in the header and the links from every file chunk to the file; without it, there are no such links.branch: the branch those links point to (main).documents: the folder of the documents (literate).site: the folder the website is woven into (site).logo: an image shown on the left of the name in the header and above the title of the front page;logoDark: another image for dark backgrounds, or"invert".links: more links for the header, text to address, shown before those to the chunks and to the source.template,stylesheet: a template and a stylesheet of the project's own, in place of those of the weaver.comments: the comment pattern of the notice for some suffixes, with{}where the notice goes, added to those of the tangler;nulltakes the notice away from a suffix.
Paths are relative to the root of the project, where the commands are run.
"""The configuration of a project: literate.json at its root.""" import json from dataclasses import dataclass, field, fields from pathlib import Path from .tangle import COMMENTS, Error CONFIG = "literate.json" ⟨the configuration⟩ ⟨reading the configuration⟩
The keys of the file are the fields of the configuration, with their
defaults; logoDark keeps its JSON spelling.
@dataclass class Config: name: str = "" tagline: str = "a literate program" repository: str = "" branch: str = "main" documents: str = "literate" site: str = "site" logo: str = "" logoDark: str = "" links: dict = field(default_factory=dict) template: str = "" stylesheet: str = "" comments: dict = field(default_factory=dict) @property def notices(self): """The comment patterns of the notices, by suffix: the tangler's and the project's.""" patterns = dict(COMMENTS) patterns.update(self.comments) return {suffix: pattern for suffix, pattern in patterns.items() if pattern}
The file is read strictly: a key that is not one of the above is more
likely misspelt than meant, and a pattern without {} would lose the
notice.
def load(path=CONFIG): """The configuration in file `path`, or the defaults if there is none.""" path = Path(path) values = {} if path.exists(): try: values = json.loads(path.read_text(encoding="utf-8")) except ValueError as e: raise Error(f"{path}: {e}") if not isinstance(values, dict): raise Error(f"{path}: not a JSON object") unknown = sorted(set(values) - {f.name for f in fields(Config)}) if unknown: raise Error(f"{path}: unknown keys {', '.join(unknown)}") config = Config(**values) for suffix, pattern in config.comments.items(): if pattern is not None and "{}" not in pattern: raise Error(f"{path}: the comment pattern for {suffix!r} has no {{}}") if not config.name: config.name = path.resolve().parent.name return config
The command line
The command is a parser with three subcommands, each running a function of
its own; mistakes in the documents or the configuration are printed as
literate: ... and end the command with status 1.
"""The command line: literate tangle, literate weave, literate build.""" import argparse import sys from importlib.util import find_spec from pathlib import Path from . import __version__ from .config import load from .tangle import Error, FILE, documents, file_names, read_chunks, unused, update, where ⟨reading the documents of the project⟩ ⟨the subcommands⟩ ⟨the parser⟩ def main(argv=None): args = parser().parse_args(argv) try: args.run(args, load()) except Error as e: print(f"literate: {e}", file=sys.stderr) return 1 return 0
The documents are those named on the command line or, by default, those of the project's folder. A chunk that is never used is reported here, every time the documents are read to be tangled.
def project_documents(args, config): docs = args.documents or documents(config.documents) if not docs: raise Error(f"no documents in {config.documents}/") return docs def read_project(args, config): chunks = read_chunks(project_documents(args, config)) for name in unused(chunks): block = chunks[name][0] print(f"{block.doc}:{block.start + 1}: <<{name}>> is never used", file=sys.stderr) return chunks
Tangling
Listing shows each file with the document that starts it, then each chunk
with the places of its fragments; --where looks a line up; otherwise the
files are written, or, with --check, only compared, and the command fails
if one differs.
def tangle_command(args, config): chunks = read_project(args, config) if args.list: for name in file_names(chunks): print(f"{name} ({chunks[name][0].doc})") print() for name, fragments in chunks.items(): if not FILE.match(name): print(f"<<{name}>> " + ", ".join(f"{b.doc.name}:{b.start + 1}" for b in fragments)) return if args.where: name, _, line = args.where.rpartition(":") if not line.isdigit(): raise Error(f"--where wants FILE:LINE, not {args.where}") print(where(chunks, name, int(line), config.notices) or "a line added by the tangler") return stale = update(chunks, args.out, config.notices, check=args.check) if args.check and stale: raise Error("not as the documents say (run literate tangle): " + ", ".join(stale)) for name in stale: print("wrote", name)
Weaving
The weaver is imported only here, so that tangling works without the packages it needs; without them, the command says how to install them.
def weave_command(args, config): try: from .weave import weave except ImportError as e: raise Error(f"weaving needs markdown and pygments ({e}): " "pip install 'opensheaf-literate[weave]'") out = args.out or Path(config.site) pages = weave(config, project_documents(args, config), out, args.branch) print(f"wove {pages} pages into {out}")
Building
literate build is what one runs after editing the documents: it tangles
the files and weaves the website, when it can, to look at.
def build_command(args, config): tangle_command(argparse.Namespace(documents=args.documents, list=False, where=None, out=Path("."), check=False), config) if not (find_spec("markdown") and find_spec("pygments")): print("not weaving: pip install 'opensheaf-literate[weave]'", file=sys.stderr) return weave_command(argparse.Namespace(documents=args.documents, out=None, branch=None), config)
The parser
Every subcommand takes the documents as arguments, in case one wants to tangle or weave only some of them.
def parser(): p = argparse.ArgumentParser(prog="literate", description=__doc__.split("\n")[0]) p.add_argument("--version", action="version", version=f"opensheaf-literate {__version__}") sub = p.add_subparsers(title="commands", dest="command", metavar="COMMAND") sub.required = True ⟨the arguments of literate tangle⟩ ⟨the arguments of literate weave⟩ ⟨the arguments of literate build⟩ return p def documents_argument(command): command.add_argument("documents", nargs="*", type=Path, help="the literate documents (default: all those of the project)")
The options of tangle are those of the table at the top of this chapter.
t = sub.add_parser("tangle", help="write the files the documents define") documents_argument(t) t.add_argument("--out", type=Path, default=Path("."), help="where to write the files") t.add_argument("--check", action="store_true", help="write nothing; exit 1 if a file differs from its document") t.add_argument("--list", action="store_true", help="list the files and the chunks") t.add_argument("--where", metavar="FILE:LINE", help="the line of the document a line of a file comes from") t.set_defaults(run=tangle_command)
weave writes into the folder of the configuration unless told otherwise,
with links to the branch of the configuration unless told otherwise: the
continuous integration of a branch other than the main one may want its
own.
w = sub.add_parser("weave", help="weave the documents into a website") documents_argument(w) w.add_argument("--out", type=Path, help="where to write the website (default: site/)") w.add_argument("--branch", help="the branch the links to files point to (default: main)") w.set_defaults(run=weave_command)
build has nothing to choose.
b = sub.add_parser("build", help="tangle, then weave if markdown and pygments are installed") documents_argument(b) b.set_defaults(run=build_command)