How to turn a directory into a git branch
Table of contents
tl;dr
DIR=_site
BRANCH=pages
REMOTE=$(git remote get-url origin)
cd $DIR
git init .
git add .
git commit -m "push directory $DIR as branch $BRANCH"
git switch -c $BRANCH
git push --set-upstream --force "$REMOTE" $BRANCHIn order to host a website from a git repository with services like github pages or grebedoc.dev you need to have a branch (usually named pages), which contains only the contents of said site.
As far as I know, most often this branch is created in a CI/CD workflow with third-party build utilities for common SSG, which handle both building the website from sources and creating the branch.
My site will be updated at most weekly, thus I don’t want to bother with setting up CI. Whenever I’m ready to publish a post, I can build it locally into a directory and push it somehow to codeberg, and let the webhook update the site.
Let’s assume the following directory structure:
blog // current working directory
├── .git
├── upload.sh // script to push the branch
├── _site // output directory
└── src // site source
First I thought there might be a git subcommand that might do something like this, but after a quick web search there seems to be none. Then I decided to check how Zola does this in their github CI action. It turns out the simplest solution is to initialize a local git repository in the new directory, add and commit all files in that directory, and then force push to the remote repository. There’s no need to involve the git repository in blog at all.
DIR=_site
BRANCH=pages
REMOTE=$(git remote get-url origin)
cd $DIR
git init .
git add .
git commit -m "push directory $DIR as branch $BRANCH"
git switch -c $BRANCH
git push --set-upstream --force "$REMOTE" $BRANCH