Hugo script to easily add images to your blog

This script can be used to automatically copy images to the static directory and generate the correct markdown for them.

Use like this:

./add-image.py ~/Downloads/new-image.svg

Script source code

#!/usr/bin/env python3
from datetime import datetime
import argparse
import os.path
import subprocess
import shutil

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Create a new post")
    parser.add_argument("imagefile", help="The image to import")
    args = parser.parse_args()

    now = datetime.now()
    
    filename = os.path.join("static", "images", f"{now.year}", f"{now.month}", os.path.basename(args.imagefile))
    print(f"Adding image to {filename}")
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    
    shutil.copy(args.imagefile, filename)
    
    # Add to git
    subprocess.run(["git", "add", filename], check=True)
    
    # User guidance on how to use the path
    fileurl = filename.partition("/")[-1]
    print("Use the image like this:")
    print(f"![Caption](/{fileurl})")

Example output

Adding image to static/images/2024/6/new-image.svg
Use the image like this:
![Caption](/images/2024/6/new-image.svg)