Hi!
I'm currently writing an addon for Blender (calculation of CNC path for rotary module/Snapmaker) and there is this "bl_info" structure you need to enter at the beginning of the addon code.
This contains a version number and I thought it would be better that this is increased automatically each time I commit a change using git.
Fortunately there is a mechanism in git for that purpose: "pre-commit". This can be found in the hidden folder ".git" in the git repository folder locally.
There are several examples in the folder what you can do with the different files. They have in common that you must not use a file extension for the real file, so if you want to use "pre-commit" it need to be exactly this filename so that git can find and use it.
The other thing is that the contents needs to be a batch file, in Windows it seems to work with CMD, but it needs "#!/bin/sh" as first line to run. The file needs to be saved as UTF-8 with no BOM (you can check that in Notepad++ for example).
To run a Python script in the pre-commit batch, simply use "python C:/path/to/your/pythonfile.py" as second line and it runs every time you commit a change using i.e. VSCode with source code maintenance or Git Desktop etc. (I think it also runs when you do the commit manually in CMD, I don't use that way.)
Here's the script I made to increase the bl_info version string (the last of the three parts). It first creates a backup of the desired file into a folder "Backup" which needs to be inside of the repository folder (otherwise you get a permission denied error, I guess git does not allow accessing anything outside the repository). To not upload the "Backup" folder you need to create a file ".gitignore" in the main folder of the repository where you add the line "Backup/".
The script (don't know if this forum can use code tags, I simply add some and see if it works... ):
[code]
import re
import shutil
import os
from datetime import datetime
# path to the addon file
# Backup folder outside GIT repository
backup_folder = r"C:\Path\To\GitRepository\Backup"
def create_backup():
"""
Creates a backup of the addon file before changing the version number.
"""
try:
if not os.path.exists(backup_folder):
os.makedirs(backup_folder)
backup_path = os.path.join(backup_folder, f"FileWithBLInfo_backup_{timestamp}.py")
shutil.copy(addon_file, backup_path)
print(f"Created backup: {backup_path}")
return True
except Exception as e:
print(f"Error creating backup: {e}")
return False
def increment_version():
"""
Increments the version number in the 'bl_info' structure.
"""
with open(addon_file, "r", encoding="utf-8") as file:
lines = file.readlines()
new_lines = []
version_updated = False
for line in lines:
# search for the version line
match = re.match(r"\s*\"version\": \((\d+), (\d+), (\d+)\),", line) # "version": (0, 0, 12),
if match:
major, minor, patch = map(int, match.groups())
patch += 1 # increment patch level
new_line = f" \"version\": ({major}, {minor}, {patch}),\n"
new_lines.append(new_line)
version_updated = True
print(f"Changed version number to: ({major}, {minor}, {patch})")
else:
new_lines.append(line)
if not version_updated:
raise ValueError("No version number found in the file!")
with open(addon_file, "w", encoding="utf-8") as file:
file.writelines(new_lines)
def main():
try:
if create_backup():
increment_version()
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
[/code]
So if the script runs it tries to create a backup, if that doesn't work for any reason, the version number will not be changed. This is to avoid that something happens while changing the version number - you would have a backup of the current, uncommitted file which you can restore.
The problem is: When you commit that, the files version number will be changed but that sets the file again as "modified". So to include the modified version number in the commit it must be staged after processing. This must be done in the file "pre-commit" after starting the Python file. So the complete code in "pre-commit" should be (assuming the Python script is named "pre-commit.py" in the same folder): [code]
#!/bin/sh
git add C:/Path/To/GitRepository/FileWithBLInfo.py [/code]
Took me some hours to find that out so maybe this is useful for some of you.
(My first try with GitHub.)
After that each commit creates a new bl_info-Version number and the local and committed file has the same version number then. Of course you can still manually change the number like you want as it only increases the existing number by 1.