Commit 16e89bcf authored by Nikos Psaromanolakis's avatar Nikos Psaromanolakis
Browse files

Add helm_update file for the ETSI ci/cd

parent 724ad9f1
Loading
Loading
Loading
Loading
+135 −0
Original line number Diff line number Diff line
import sys
import os
import shutil
import ruamel.yaml
from datetime import datetime

BUMP_CHART = "--bump-chart" in sys.argv
if BUMP_CHART:
    sys.argv.remove("--bump-chart")

def update_yaml_values(yaml_file, temp_file, microservices, image_name, new_tag):
    yaml = ruamel.yaml.YAML()
    yaml.allow_duplicate_keys = True
    yaml.preserve_quotes = True

    # Open YAML file
    with open(yaml_file, 'r') as file:
        yaml_data = yaml.load(file)

    # Match each microservice from the file with the image
    for service in microservices:
        service_data = yaml_data[service]
        image_section = service_data.get('image')

        if image_section['repository'] == image_name:
            print("Old tag: ", image_section['tag'], "New tag: ", new_tag)
            if image_section['tag'] != new_tag:
                image_section['tag'] = new_tag
                print("YAML file updated successfully for image: ", image_section['repository'], " with tag: ", image_section['tag'])

    with open(temp_file, 'w') as file:
        yaml.dump(yaml_data, file)

def increment_ver(current_version):
    """
    Increment version in SemVer-like format: YYYY.M.D
    (e.g., 2025.9.1, 2025.9.2).
    If the current version matches this year+month, bump the day counter.
    Otherwise, reset to YYYY.M.1.
    """
    now = datetime.now()
    year = now.year
    month = now.month

    # Expected format: YYYY.M.D
    prefix = f"{year}.{month}"

    if current_version and current_version.startswith(prefix + "."):
        try:
            day = int(current_version.split(".")[2])
        except (IndexError, ValueError):
            day = 0
        day += 1
    else:
        day = 1

    return f"{prefix}.{day}"


def update_chart(chart_file):
    yaml = ruamel.yaml.YAML()
    yaml.allow_duplicate_keys = True
    yaml.preserve_quotes = True

    # Open YAML file
    with open(chart_file, 'r') as file:
        yaml_data = yaml.load(file)

    yaml_data['version'] = increment_ver(yaml_data['version'])
    print("The Chart.yaml file has been updated successfully.")

    with open(chart_file, 'w') as file:
        yaml.dump(yaml_data, file)

def compare_yaml(yaml_file, temp_file):
    contents_changed = not os.system(f'diff {yaml_file} {temp_file} > /dev/null 2>&1')
    return contents_changed

def main():
    # Default YAML files
    yaml_files = ["./charts/hypo/values-cd.yaml"]

    # Look for --file arguments anywhere in the command-line arguments
    file_args = [arg.split('=')[1] for arg in sys.argv if arg.startswith('--file=')]

    # If --file arguments are found, use them instead of the default yaml_files
    if file_args:
        yaml_files = file_args
        # Remove the --file arguments from sys.argv to handle only image args
        sys.argv = [arg for arg in sys.argv if not arg.startswith('--file=')]

    chart_file = "./charts/hypo/Chart.yaml"

    print("YAML files to be processed: ", yaml_files)
    print("--------------------------------------")

    # Adding all of our microservices
    microservices = ["pkg-manager", "oss-client", "tmf-api", "sonata", "portal-cart", "telemetry-client", "peering-api", "registry-api", "fabric-api", "portal"]

    tag_changed = False
    chart_updated = False  # Track if chart has been updated already

    for yaml_file in yaml_files:

        print("YAML currently processed: ", yaml_file)
        print("--------------------------------------")

        temp_file = yaml_file.replace('.yaml', '-temp.yaml')

        for image in sys.argv[1:]:
            # Getting image by command line args
            image_name, image_tag = image.rsplit(':', 1)

            # Update YAML values
            print("Processing image:", image_name, "for YAML file:", yaml_file)
            update_yaml_values(yaml_file, temp_file, microservices, image_name, image_tag)

            if compare_yaml(yaml_file, temp_file):
                print(f"The YAML files are exactly the same for image: {image_name} in {yaml_file}.")
                os.remove(temp_file)
            else:
                print(f"The YAML files are different for image: {image_name} in {yaml_file}.")
                shutil.move(temp_file, yaml_file)
                tag_changed = True
                if not chart_updated and BUMP_CHART:
                    # Update chart only once, when the first change occurs
                    update_chart(chart_file)
                    chart_updated = True
            print("--------------------------------------")

    if not tag_changed:
        print("No changes were made to any YAML files.")

if __name__ == "__main__":
    main()