From ae08caa6be5b5023ce8ed94614f4c9a7342cca2e Mon Sep 17 00:00:00 2001 From: Eric Torres Date: Tue, 16 Apr 2019 17:12:06 -0700 Subject: [PATCH] Use context manager for switching umask --- bin/backup | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/bin/backup b/bin/backup index 6d933c6..30d89a6 100644 --- a/bin/backup +++ b/bin/backup @@ -18,6 +18,7 @@ On each run of this script, a new snapshot is made and any unchanged files are hardlinked into the new snapshot. """ import argparse +from contextlib import contextmanager import logging import os import sys @@ -102,11 +103,18 @@ def parse_cmdline_arguments(**kwargs): return parser.parse_args(**kwargs) +@contextmanager +def change_umask(): + """Creates a context manager in which the umask is changed. This is to ensure that + the script's desired umask is not visible to the user. + """ + old_umask = os.umask(SCRIPT_UMASK) + yield + os.umask(old_umask) + + # ========== Main Script ========== if __name__ == "__main__": - # Create some sort of cleanup routine for resetting the umask to previous value - old_umask = os.umask(SCRIPT_UMASK) - args = parse_cmdline_arguments() parsed_config = config.parse_configfile() repo = Repository(args.repository) @@ -133,7 +141,7 @@ if __name__ == "__main__": curr_snapshot = None - with config.merge_include_files() as include_file, config.merge_exclude_files() as exclude_file: + with change_umask(), config.merge_include_files() as include_file, config.merge_exclude_files() as exclude_file: try: curr_snapshot = repo.create_snapshot(args.name) rbackup.rsync.rsync( @@ -146,16 +154,12 @@ if __name__ == "__main__": ) except ValueError as e: syslog.critical(e) - os.umask(old_umask) exit(E_INVALID_SNAPSHOT_NAME) except CalledProcessError as e: syslog.critical("Backup process failed") syslog.critical(f"Failing command: {e.cmd}") - os.umask(old_umask) exit(E_FAILED_PROCESS) if args.run_post_sync: syslog.info("Running sync operation") os.sync() - - os.umask(old_umask)