Add support for automatically symlinking

This commit is contained in:
Daniel_I_Am 2021-12-27 15:27:29 +01:00
parent d60ee02cb5
commit d592dc49b8

57
run.py
View File

@ -9,10 +9,21 @@ out_directory = './out/'
# Applied in order, later files override earlier files
env_files = ['./vars.env', './local.env']
import argparse
import difflib
import jinja2
import sys
import re
import os
parser = argparse.ArgumentParser(description='Fill out configuration templates.')
parser.add_argument('-f', '--force', default=False, action=argparse.BooleanOptionalAction, help='Force overwriting of existing files in output')
parser.add_argument('-l', '--link', default=False, action=argparse.BooleanOptionalAction, help='Automatically create symlinks (based on the symlink comment in the templates, must be on first line of template)')
parser.add_argument('-d', '--diff', default=False, action=argparse.BooleanOptionalAction, help='Show the diff of configuration files if file already exists')
parser.add_argument('--dryrun', default=False, action=argparse.BooleanOptionalAction, help='Do not modify any files.')
args = parser.parse_args()
del parser
def main():
key_value_store = create_key_value_store()
template_files = find_all_templates()
@ -77,8 +88,50 @@ def convert_template(env, template, key_value_store, out):
if not os.path.isdir(out_dir_name):
os.makedirs(out_dir_name)
with open(out, 'w') as file:
file.write(rendered)
if os.path.isfile(out) and not args.force:
if args.diff:
with open(out) as file:
current = file.read()
for line in difflib.unified_diff(current.split('\n'), rendered.split('\n'), fromfile=out, tofile=out+'.new', lineterm=''):
print(line, file=sys.stderr)
if not args.force:
print(f"File `{out}` already exists, will not overwrite. Rerun with `-f` to force overwriting existing files.", file=sys.stderr)
return
if not args.dryrun:
with open(out, 'w') as file:
file.write(rendered)
else:
print(f'Would write rendered template to `{out}`.')
if args.link:
first_line = source.split('\n')[0]
m = re.search(r'symlink\{([^}]+)\}', first_line)
if m is None:
return
symlink_location = os.path.expanduser(m.group(1))
create_symlink(out, symlink_location)
def create_symlink(source, destination):
if os.path.exists(destination):
if not args.force:
print('`{destination}` already exists, will not overwrite. Rerun with `-f` to force overwiring existing files.', file=sys.stderr)
return
if not args.dryrun:
os.remove(destination)
else:
print(f'Would remove `{destination}`.')
if not args.dryrun:
os.symlink(source, destination)
else:
print(f'Would create symlink `{destination}`->`{source}`.')
if __name__ == '__main__':
main()