Skip to content

[FEATURE] Add the option to restore original values for saving a modified configuration. #32

@harleypig

Description

@harleypig

I need to save a modified configuration back to the configuration file. Saving values instead of variables defeats the purpose of putting variables there in the first place. :/

I'd like to have a way to restore the original values before writing changes back to the configuration file.

I considered 'pre-loading' the file and looking for the various formats this can appear in, but that got hairy quickly. I then re-did your library in a relatively simplistic way in hopes of just grabbing the key and saving it and its value in another dict, but I can't figure out how to grab the key for the current value.

A stripped down example looks like this.

original_values = {}

def regex_resolver():
  # regex built here, pretty much untouched from your code

def substitute_variable_values(value: str):
  # again, match and replace ripped from your code

def load_yaml(filename):
  def resolve_env_vars(loader, node):
    value = loader.construct_scalar(node)
    return substitute_variable_values(value)

  def store_values(loader, node):
    # this is where things bogged down
    # I've gotten to this point, but I have no clue how to proceed
    value = loader.construct_mappings(node)
    # somehow, grab the key, but by this point, it's buried in the
    # object and I can see it, but I can't see how to pull it out via
    # code
    original_values[key] = value

    loader = yaml.SafeLoader
    loader.add_implicit_resolver(tag, regex_resolver(), None)
    loader.add_constructor(tag, resolve_env_vars)
    loader.add_constructor(tag, store_values)

    with open(yamlfile, 'r', encoding='utf-8') as raw:
      cfg = yaml.load(raw, Loader=loader)

    return cfg

# Writing the config would be easy.
def write_config(filename, data):
  if original_values.keys():
    data | original_values

  with open(filename, 'w', encoding='utf-8') as raw:
    yaml.dump(data, fh)

Though, it would be nice to include that in the library so the dev wouldn't have to remember to do that final step.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions