Skip to content

Instantly share code, notes, and snippets.

@antonagestam
Last active December 19, 2018 17:11
Show Gist options
  • Save antonagestam/46375f252c453523bb837b29d8a6e208 to your computer and use it in GitHub Desktop.
Save antonagestam/46375f252c453523bb837b29d8a6e208 to your computer and use it in GitHub Desktop.
Diff MySQL .cnf files
import re
import sys
import json
var_pattern = re.compile(r'^(?!\[)(?P<var>[A-z_-]+)\s*(?:=\s*(?P<val>.*))?$')
scope_pattern = re.compile(r'^\s*\[(?P<scope>[A-z_-]+)\]\s*$')
def get_lines(file_path):
with open(file_path, 'r') as f:
yield from (l.strip() for l in f.readlines())
def normalize_var_name(var: str) -> str:
return var.lower().replace('_', '-')
def get_vars(file_path):
scope = ''
for line in get_lines(file_path):
if not line or line.startswith('#'):
continue
var_match = var_pattern.match(line)
scope_match = scope_pattern.match(line)
if var_match:
var, val = var_match.groups()
var = normalize_var_name(var)
yield f'{scope}{var}', val
elif scope_match:
scope = f'{scope_match.groups()[0]}.'
else:
print(f'line did not match pattern: {line}')
def get_diff(first_vars, second_vars):
first = set(first_vars)
second = set(second_vars)
return {k for k, v in (first ^ second)}, dict(first), dict(second)
def get_value(key, vars):
try:
return f'"{vars[key]}"'
except KeyError:
return 'missing'
if __name__ == '__main__':
fst_file, snd_file = sys.argv[1:3]
diff, first, second = get_diff(get_vars(fst_file), get_vars(snd_file))
for var in diff:
print(var)
print(f'\t{get_value(var, first)} in {fst_file}')
print(f'\t{get_value(var, second)} in {snd_file}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment