Skip to content

Rendering your static website into a separate branch in a subdirectory

When you're using a static site generator, a common workflow is that you have a Git repo with your source documents, run the SSG on it, which will render your site's HTML into an output directory, and then you take that directory and push it to a separate branch (usually called pages) in the same directory.

But how do you switch branches, especially if you might have uncommitted changes? And how do you make the output subdirectory the top-level directory in the other branch?

A simple web search took me to How to push a directory to a separate git branch? by Leon Scherer. It introduced me to the git worktree command, which is perfect for that kind of thing.

The following commands check out the pages branch into the site directory and then run MkDocs (which is the SSG I'm using) to put the rendered HTML into site.

$ git worktree add site pages
$ mkdocs build

This assumes that

  • the site directory doesn't exist yet (else git worktree add refuses to work),
  • and that the pages branch already exists (if it doesn't, check out the -b option, and maybe the --orphan option, too).

As Leon points out, Git will create a site/.git file with a pointer to the worktree directory:

site/.git
gitdir: /home/scy/proj/scy.name/.git/worktrees/site

If your SSG deletes that file on build, you'll need to copy it somewhere else and restore it after the build. (MkDocs leaves the file alone, nothing to do for me!)

Afterwards, you can just cd site, and it's as if you're in a working copy of your pages branch. You can then do other Git operations like git add . and git commit followed by git push to commit and push the resulting HTML.