Skip to content

Automated Deployment: GitHub Pages (Deploy from branch)

Chad Baker edited this page Oct 5, 2023 · 8 revisions

The following contains general instructions on how to deploy to GitHub Pages from a branch.

See Automated Deployment: GitHub Actions#GitHub Pages Deploy for instructions if you are using GitHub Actions.

note: you may want to use different tmp dirs:

git worktree add /tmp/book gh-pages
mdbook build
rm -rf /tmp/book/* # this won't delete the .git directory
cp -rp book/* /tmp/book/
cd /tmp/book
git add -A
git commit -m 'deploy new book'
git push origin gh-pages
cd -

Or put this into a Makefile rule:

.PHONY: deploy
deploy: book
    @echo "====> deploying to github"
    git worktree add /tmp/book gh-pages
    mdbook build
    rm -rf /tmp/book/*
    cp -rp book/* /tmp/book/
    cd /tmp/book && \
        git add -A && \
        git commit -m "deployed on $(shell date) by ${USER}" && \
        git push origin gh-pages

You may want to delete history on the gh-pages branch to avoid increasing the size of the repository significantly. To do that, the following command can be run before calling git add:

git update-ref -d refs/heads/gh-pages

This will also require adding the --force flag to git push.

Working Script

I'm not sure what the formal process for editing this is and am also surprised I have permissions to do this, but based on the above, this is a script that I got to actually work reliably:

rm -rf ./mdbook-publish/
# Create `./mdbook-publish` and then checkout the corresponding branch in that worktree folder
git worktree add -f ./mdbook-publish mdbook-publish
mdbook build
cd mdbook-publish
# make sure the branch is up to date
git pull origin mdbook-publish
cp -rp ../book/* ./
git add -fA
# commit without appending to index to prevent tracking history of binary files
git commit --amend --no-edit
git push -f origin mdbook-publish
cd ..