Use context manager for switching umask

This commit is contained in:
Eric Torres 2019-04-16 17:12:06 -07:00
parent 2587619009
commit ae08caa6be

View File

@ -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. files are hardlinked into the new snapshot.
""" """
import argparse import argparse
from contextlib import contextmanager
import logging import logging
import os import os
import sys import sys
@ -102,11 +103,18 @@ def parse_cmdline_arguments(**kwargs):
return parser.parse_args(**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 ========== # ========== Main Script ==========
if __name__ == "__main__": 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() args = parse_cmdline_arguments()
parsed_config = config.parse_configfile() parsed_config = config.parse_configfile()
repo = Repository(args.repository) repo = Repository(args.repository)
@ -133,7 +141,7 @@ if __name__ == "__main__":
curr_snapshot = None 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: try:
curr_snapshot = repo.create_snapshot(args.name) curr_snapshot = repo.create_snapshot(args.name)
rbackup.rsync.rsync( rbackup.rsync.rsync(
@ -146,16 +154,12 @@ if __name__ == "__main__":
) )
except ValueError as e: except ValueError as e:
syslog.critical(e) syslog.critical(e)
os.umask(old_umask)
exit(E_INVALID_SNAPSHOT_NAME) exit(E_INVALID_SNAPSHOT_NAME)
except CalledProcessError as e: except CalledProcessError as e:
syslog.critical("Backup process failed") syslog.critical("Backup process failed")
syslog.critical(f"Failing command: {e.cmd}") syslog.critical(f"Failing command: {e.cmd}")
os.umask(old_umask)
exit(E_FAILED_PROCESS) exit(E_FAILED_PROCESS)
if args.run_post_sync: if args.run_post_sync:
syslog.info("Running sync operation") syslog.info("Running sync operation")
os.sync() os.sync()
os.umask(old_umask)