Skip to content

Instantly share code, notes, and snippets.

@Tranquility2
Created November 9, 2023 09:22
Show Gist options
  • Save Tranquility2/2affc474c68179ad5e8e3d516b855126 to your computer and use it in GitHub Desktop.
Save Tranquility2/2affc474c68179ad5e8e3d516b855126 to your computer and use it in GitHub Desktop.
Script to update values in a YAML file
from argparse import ArgumentParser
from pathlib import Path
from ruamel.yaml import YAML
yaml = YAML()
yaml.preserve_quotes = True
yaml.width = 4096
yaml.boolean_representation = ["false", "true"]
# from ruamel.yaml util
# config, ind, bsi = util.load_yaml_guess_indent(open(yaml_path))
# print(f"{ind=} {bsi=}")
yaml.indent(mapping=2, sequence=4, offset=2)
def lookup(search_key, data, path=None):
"""
Look up the values for the given search key(s) in the data structure and return
a list of tuples containing the path to the value and the value itself.
"""
if path is None:
path = []
if isinstance(data, dict):
for key, value in data.items():
if key == search_key:
yield data, value
for result in lookup(search_key, value, path + [key]):
yield result
elif isinstance(data, list):
for item in data:
for result in lookup(search_key, item, path + [item]):
yield result
def cli():
parser = ArgumentParser(description="Formatter")
parser.add_argument(
"-i",
dest="filename",
required=True,
help="target yaml file",
metavar="FILE",
)
parser.add_argument("-lk", dest="lookup_key", required=True, help="Key to search")
parser.add_argument("-lv", dest="lookup_value", required=True, help="Value to compare")
parser.add_argument("-tk", dest="target_key", required=True, help="Key to replace")
parser.add_argument("-tv", dest="target_value", required=True, help="Value to replace")
args = parser.parse_args()
run(args)
def run(args):
file_path = Path(args.filename)
with file_path.open("r") as yaml_reader:
yaml_file = yaml.load(yaml_reader)
for d, value in lookup(args.lookup_key, yaml_file):
if value == args.lookup_value:
d[args.target_key] = args.target_value
"""
jobs:
do_something:
steps:
- name: Checkout
uses: something
with:
repo: my_repo
ref: branch
misc: na
"""
# python yaml_updater.py -i file.yml -lk "repo" -lv "my_repo" -tk "ref" -tv "new_branch"
with file_path.open("w") as yaml_writer:
yaml.dump(yaml_file, yaml_writer)
if __name__ == "__main__":
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment