Distributing a git repository as a single plain-text file
Michael NeumannWhen writing a blog post which contains code snippets more than a few lines long, I consider it good practice to provide the source code to the reader as download in some way or another. One possible solution is to create a public git repository hosted on Github or Codeberg which contains the code and it's history. But will Github still be around in 10 years from now? Will I still be using Github next month? What if I write many blog posts? Does each post get it's own git repository? And what about self-hosting, or the desire to migrate from Github to Codeberg? In the long run, this all ends up to be very painful... fortunately, there exists a very simple solution!
Let's imagine for a moment that we are writing an article about Parsing JSON
in OCaml and that we have already created a local git repository under
code-of-parsing-json-in-ocaml/, which contains all the code related to the
article as a series of commits in branch main, as that's how we develop code
normally.
With the following command we convert the whole repository into a single plain-text patch file:
# cd code-of-parsing-json-in-ocaml/
git format-patch --root main --stdout > code-of-parsing-json-in-ocaml.patch
We publish this patch file somewhere, ideally as part of our static website and blog. Then, we refer to it from our blog post including instructions on how to recreate a git repository from it:
# Instructions to recreate git repo from patch file
git init /tmp/code-of-parsing-json-in-ocaml
cd /tmp/code-of-parsing-json-in-ocaml
git am /tmp/code-of-parsing-json-in-ocaml.patch
The reader will be thankful to be able to follow our blog post easily by running the code locally and playing with it.