Refactor dryrun safe commands

This commit is contained in:
Daniel_I_Am 2021-12-27 15:35:38 +01:00
parent d592dc49b8
commit 78302888dd

40
run.py
View File

@ -86,7 +86,7 @@ def convert_template(env, template, key_value_store, out):
out_dir_name = os.path.dirname(out)
if not os.path.isdir(out_dir_name):
os.makedirs(out_dir_name)
dryrun_safe_mkdir(out_dir_name)
if os.path.isfile(out) and not args.force:
if args.diff:
@ -100,11 +100,7 @@ def convert_template(env, template, key_value_store, out):
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}`.')
dryrun_safe_write(out, rendered)
if args.link:
first_line = source.split('\n')[0]
@ -123,11 +119,34 @@ def create_symlink(source, destination):
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}`.')
dryrun_safe_remove(destination)
dest_dir_name = os.path.dirname(destination)
if not os.path.isdir(dest_dir_name):
dryrun_safe_mkdir(dest_dir_name)
dryrun_safe_create_symlink(source, destination)
def dryrun_safe_write(location, content):
if not args.dryrun:
with open(location, 'w') as file:
file.write(content)
else:
print(f'Would write to `{location}`.')
def dryrun_safe_remove(location):
if not args.dryrun:
os.remove(location)
else:
print(f'Would remove `{location}`.')
def dryrun_safe_mkdir(dir):
if not args.dryrun:
os.makedirs(dir)
else:
print(f'Would create directory `{dir}`.')
def dryrun_safe_create_symlink(source, destination):
if not args.dryrun:
os.symlink(source, destination)
else:
@ -135,4 +154,3 @@ def create_symlink(source, destination):
if __name__ == '__main__':
main()