This article is written for my Future Self. It’s the information I wish I’d had at the time I needed it.
My WordPress infrastructure requires me to update the version number of a plugin or theme in order to deploy it to a production environment. (The tag kicks off an automatic process that creates a ZIP file and uploads it to a server.) For a time this meant I had to update the plugin or theme header and tag the commit in git. This cluttered up my commit history with many “Added version X.X.X” commits. Not a huge deal, but the redundancy lead to the question that all developers who are repeating themselves ask: can I do this just once? Could I dynamically obtain the tag name and insert it in the plugin or theme header?
The answer, it turns out, is yes. The secret is in git archive
‘s ability to substitute commit information in a file. Here’s how I did it.
First, add a placeholder in your file. This one substitutes the name of an annotated tag:
$Format:%(describe:tags=true)$
These placeholders use the same syntax as git log
‘s pretty formats.
The next step is to add the following to .gitattributes
:
filename.txt export-subst
The file “filename.txt” is the file that contains the placeholder. The “export-subst” attribute activates the substitution magic. Lastly, commit the files.
You can substitute all sort of information, such as the committer’s name and email address. You can even substitute the commit message.
limitations
Now, there are some caveats to this feature:
- The substitution only works when using the
git archive
command. - Older versions of git do not support this feature. Make sure you’re using a recent version of git.
- Within a file, only the first instance of a placeholder will be substituted. Additional identical placeholders will appear in their original form.