Skip to content

GitLab runners#

To perform an operation using GitLab runners, use this .gitlab-ci.yml file we've written.

This runs on each commit, loads the file into the script, and saves the file.

This expects you to have written a Python script using the following conditions:

  • automations/ folder in your repo directory containing:
    • requirements.txt python dependency file
    • myScript.py python script (in this case, testVerifResults.py)
  • Python script with the following command line arguments:
    • <input_file> input sysml file. positional argument and immediately
    • -o <output_file> output file name, defaults to <input_file>.new
    • -v for verbose logging
    • -s for silent logging

Python Stub#

from sysgit import sysml as sysml
import random
import difflib
import argparse
import logging


# Set up logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description='Randomize verification results in a SysML file.'
    )
    parser.add_argument(
        'sysml_file',
        help='Path to the target SysML file'
    )
    parser.add_argument(
        '-o', '--output',
        help='Output file path (default: <input>.new)',
        default=None
    )
    parser.add_argument(
        '-v', '--verbose',
        action='store_true',
        help='Enable verbose logging'
    )
    parser.add_argument(
        '-s', '--silent',
        action='store_true',
        help='Silent mode (only show errors)'
    )
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()

    if args.silent:
        logger.setLevel(logging.ERROR)
    elif args.verbose:
        logger.setLevel(logging.DEBUG)

    rawModelLoc = args.sysml_file
    output_file = args.output if args.output else f"{rawModelLoc}.new"

    logger.info(f"Reading SysML file: {rawModelLoc}")

    ## Open with our main library
    model = sysml.read(rawModelLoc)
    logger.debug(f"Model loaded successfully")

    ##
    ## do stuff
    ##

    ## Save the SysML file
    logger.info(f"Writing modified SysML to: {output_file}")
    with open(output_file, "w") as f:
        f.write(model.print())

    logger.info("Done!")

Runner#

stages:
  - run-verification

run-verification:
  stage: run-verification
  image: 
    name: registry.gitlab.com/prewittridge/tools/sysgit-py/sysgit-py:0.1.5-amd64
    entrypoint: [""]
  variables:
    SYSML_FILE_PATH: "sysgit/requirements.sysml"
    AUTOMATION_SCRIPT: "testVerifResults.py"
    GIT_STRATEGY: clone
    GIT_DEPTH: 0
  rules:
    - if: '$CI_COMMIT_AUTHOR == "GitLab Runner <noreply@gitlab.com>"'
      when: never
    - when: always
  before_script:
    - apt-get update && apt-get install -y git
  script:
    - ls
    - pwd
    - echo "Env vars..."
    - echo "printenv AZURE_CLIENT_ID"
    - echo "Running Automations again!"
    - echo "Tilde"
    - echo ~
    - |
        # Fix git ownership issue
        git config --global --add safe.directory ${CI_PROJECT_DIR} 

        # get the actual branch (fixes detached head)
        git checkout ${CI_COMMIT_REF_NAME}

        # Check if git is available and we're in a git repo
        git --version
        git status
        pwd
        ls -la

    - |
        # Install SysMelt library (optional, once sysgit-py is fully operational)
        pip install git+https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/prewittridge/tools/sysmelt.git@9c8e999f465234d5d55a3ef86e42e650a365e8b9

        # Install any additional requirements (likely not needed, as this image has as lot already)
        # pip install -r automations/requirements.txt

        # Ensure any custom pip install'ed libraries 
        export PYTHONPATH="$(python3 -m site --user-site):${PYTHONPATH}"

        # run the script. assume target input sysml file as first argument, and -o argument as output argument
        python3 ${PWD}/automations/${AUTOMATION_SCRIPT} ${PWD}/${SYSML_FILE_PATH} -o ${PWD}/${SYSML_FILE_PATH}

    - |
        # Configure git
        git config user.name "GitLab Runner"
        git config user.email "noreply@gitlab.com"

        # Check if there are changes
        if git diff --quiet; then
          echo "No changes to commit"
        else
          echo "Changes detected, committing..."
          git add ${PWD}/${SYSML_FILE_PATH}
          git commit -m "chore: auto-update verification results [skip ci] ${CI_RUNNER_ID}"

          # Push changes using CI_JOB_TOKEN
          git push ${CI_REPOSITORY_URL} HEAD:${CI_COMMIT_REF_NAME}

        fi