Keeping documentation maintained is hard enough. Keeping code samples in the documentation current and working makes it even harder. Until...

We recently added an autofix to our documentation's delivery machine, and some extra markup, that keeps our code examples synchronized to working code. No more manually editing the docs when code changes!

What Is This Sorcery?

Our docs are written in Markdown and compiled with mkdocs into a static website. We use the same delivery toolchain for docs as for our software products because the docs are products. This means we use Atomist on them.

Our code samples live in this repo: https://github.com/atomist/samples. We enclose a code snippet with a specially formatted comment, like this:

// atomist:code-snippet:start=helloWorldCommand
import { NoParameters } from "@atomist/automation-client";
import { CommandListenerInvocation } from "@atomist/sdm";

export async function helloWorldListener(ci: CommandListenerInvocation<NoParameters>): Promise<void> {
    return ci.addressChannels("Hello, world");
}
// atomist:code-snippet:end

Then our delivery machine knows how this code relates to examples in the docs, because we reference that code snippet in html comments within Markdown. The SDM embeds the latest sample code in the Markdown, plus a link to its source.

on a push to atomist/docs or atomist/samples, the Atomist service triggers the docs-sdm to update the sample snippets in the documentation.

As we're updating the docs, the SDM checks all the sample references and pulls in any updates. When we make changes to our sample code, it gets tested with our regular workflow (which is in a different SDM). Then, the documentation delivery machine notices that the samples changed, and updates the documentation too.

Neat!

Write Once, Run Anywhere

Because this is Atomist, we've linked this code transform to a bot command, so we can run update code snippets on any, or all, of our repositories and keep all of our documentation up to date. It works on markdown, including the README of other repositories.