From 5d938325c457e37e7dcc283b264c5f40e371c8b7 Mon Sep 17 00:00:00 2001 From: Christian Taedcke Date: Fri, 29 Nov 2024 13:19:53 +0100 Subject: [PATCH] implement support for yaml !Env tag This way environment variables van be referenced in the .pre-commit-config.yaml, e.g. cfg: !Env "${PRE_COMMIT_CONFIG_PATH}/.oelint-adv.yaml" --- pre_commit/yaml.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/pre_commit/yaml.py b/pre_commit/yaml.py index a5bbbc99..7a5c7b04 100644 --- a/pre_commit/yaml.py +++ b/pre_commit/yaml.py @@ -1,11 +1,26 @@ from __future__ import annotations import functools +import os +import re from typing import Any import yaml + +def env_constructor(loader: yaml.Loader, node: yaml.ScalarNode) -> str: + """Load !Env tag""" + value = str(loader.construct_scalar(node)) + match = re.compile('.*?\\${(\\w+)}.*?').findall(value) + if match: + for key in match: + value = value.replace(f'${{{key}}}', os.getenv(key, '')) + return value + + Loader = getattr(yaml, 'CSafeLoader', yaml.SafeLoader) +Loader.add_constructor(tag='!Env', constructor=env_constructor) + yaml_compose = functools.partial(yaml.compose, Loader=Loader) yaml_load = functools.partial(yaml.load, Loader=Loader) Dumper = getattr(yaml, 'CSafeDumper', yaml.SafeDumper)