Migration von Kirby auf Hugo

Meine Kirby Installation dieses Blogs hat leider seit einiger Zeit nicht mehr funktioniert. Ich hatte Kirby zwar als Docker installiert, hatte aber vergessen die Kirby Version sauber zu pinnen. Dann hat mir leider die neue Version von Kirby das Genick gebrochen und ich habe es trotz einiger Versuche nicht mehr geschafft die alte Version sauber zu installieren. Also jetzt hier der neue Versuch als Migration auf Hugo.

import os
import glob
import pathlib
import sys
import re

kirby_files = '/Users/danst/gedankenexperiment/content/post'
image_files = '/Users/danst/gedankenexperiment/content'


def check_if_still_txt(name):
    found = name.find('.txt') != -1 and name.find('.jpg') == -1 and name.find('.png') == -1
    return found

def move_any_images_to_static_subfolder(root, images):
    new_images = []
    for image in images:
        print(f'alt: {image}')
        neu = image_files + image[len(kirby_files):]
        print(f'neu: {neu}')
        print(pathlib.Path(neu).parents[0])
        #os.makedirs(pathlib.Path(neu).parents[0], exist_ok=True)
        #os.rename(image, neu)
        new_images.append(image)
    return  new_images


def make_header(root, txt_file):
    print(txt_file)

    with open(os.path.join(root, txt_file), "r") as kirby_file:
        # Read the contents of the file
        content = kirby_file.read()

        # Split the content into sections based on the Kirby formatting
        sections = content.split("----")

        # Create a dictionary to store the metadata
        metadata = {}

        # Loop through each section of the content
        for section in sections:
            # Split the section into lines
            #print(section)
            lines = section.split("\n")

            found = False
            first = False
            # Check if the section contains metadata
            if len(lines) > 1:

                # Loop through each line of the section
                value = ''
                for line in lines:
                    if len(line) > 1 and line.find(':') != -1 and not found:
                        found = True
                        first = True
                        # Split the line into key and value
                        key, value = line.split(":", 1)


                        # Add the key and value to the metadata dictionary
                    if found and not first:
                        value += '\n' + line
                    if first:
                        first = False
            if found:
                #print(key, value)
                if key.strip().lower() not in ['text', 'tags']:
                    metadata[key.strip()] = '"' + value.strip() + '"'
                else:
                    metadata[key.strip()] = value.strip()

        # Create the filename for the Hugo file
        #hugo_filename = metadata["date"][:10] + "-" + metadata["slug"] + ".md"

        # Create the content for the Hugo file
        hugo_content = "---\n"
        #print(sections)
        for key, value in metadata.items():
            if key != 'Text':
                hugo_content += key + ": " + value + "\n"
        hugo_content += "---\n\n"
        try:
            hugo_content += metadata['Text']
        except:
            pass

        # Save the Hugo file
        #print(os.path.join(root, pathlib.Path(txt_file).stem + '.md'))
        with open(os.path.join(root, pathlib.Path(txt_file).stem + '.md'), "w") as hugo_file:
            hugo_file.write(hugo_content)


def replace_links(root, txt_file):
    # Öffne die Datei zum Lesen
    with open(os.path.join(root, txt_file), 'r') as f:
        # Lese den gesamten Inhalt der Datei ein
        text = f.read()

    # Ersetze alle Vorkommen von "(\(image: )(.*)( alt: )(.*)(\))" durch "![$4]($2)"
    ersetzt_text = re.sub(r'\(link: (.*) text: (.*)\)', r'[\2](\1)', text, flags=re.IGNORECASE)
    # (\(image:)(. *)(alt:)(. *)(\))
    # ![$4]($2)

    # Öffne die Datei zum Schreiben
    with open(os.path.join(root, txt_file), 'w') as f:
        # Schreibe den ersetzen Text in die Datei
        f.write(ersetzt_text)


def add_images(root, txt_file, new_images):
    # Öffne die Datei zum Lesen
    with open(os.path.join(root, txt_file), 'r') as f:
        # Lese den gesamten Inhalt der Datei ein
        text = f.read()

    print(os.path.join(root, txt_file))
    text = ''
    for image in new_images:
        #found = re.search(r'\(image: (.*) text: (.*)\)', line)
        path = image[len(image_files):]
        print(path)
        text += f'![{path}]({path})\n'
        # < img src = "http://....jpg" width = "200" / >
        #text += f'<img src = "{path}" width = "200" / >\n'
        # Ersetze alle Vorkommen von "(\(image: )(.*)( alt: )(.*)(\))" durch "![$4]($2)"
        #ersetzt_text = re.sub(r'\(image: (.*) text: (.*)\)', r'![\2](\1)', text, flags=re.IGNORECASE)


    if text != '':
        text = '\n\n' + text
    # Öffne die Datei zum Schreiben
        with open(os.path.join(root, txt_file), 'a') as f:
            # Schreibe den ersetzten Text in die Datei
            f.write(text)


def reformat_txt_file(root, txt_file, new_images):
    replace_links(root, txt_file)
    make_header(root, txt_file)
    add_images(root, pathlib.Path(txt_file).stem + '.md', new_images)


def rename_txt_to_md(root, name):
    os.remove(os.path.join(root, name))
    os.rename(os.path.join(root, pathlib.Path(name).stem) + '.md', os.path.join(root, 'index.md'))
    pass


def find_any_images(root):
    files_list = []
    for root2, directories, files in os.walk(root):
        for name in files:
            file_extension = pathlib.Path(name).suffix
            #print(file_extension)
            if file_extension.lower() in ['.jpg', '.jpeg', '.png']:
                files_list.append(os.path.join(root2, name))
    return files_list

if __name__ == '__main__':
    files_list = []

    for root, directories, files in os.walk(kirby_files):
        for name in files:
            files_list.append(os.path.join(root, name))
            if check_if_still_txt(name):
                #print(f'now {root} -- {name}')
                images = find_any_images(root)
                #print('Images', images)
                new_images = []
                if len(images)>0:
                    new_images = move_any_images_to_static_subfolder(root, images)
                reformat_txt_file(root, name, new_images)
                rename_txt_to_md(root, name)