From b84a1a9fa4ba04f0be6562f00523ab7ba34f5f9d Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Tue, 14 Oct 2014 21:42:56 -0500 Subject: [PATCH] backup: Make configuration file argument optional If not specified, a file named `backups.ini` in the directory specified by the `XDG_CONFIG_DIR` environment variable (or `~/.config` if it is not set). --- backup.py | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/backup.py b/backup.py index 2120e5a..af71ff5 100755 --- a/backup.py +++ b/backup.py @@ -18,15 +18,30 @@ class Backup(object): RSYNC_DEFAULT_ARGS = ['-aO', '--partial', '--delete'] RSYNC_EXTRA_ARGS = shlex.split(os.environ.get('RSYNC_EXTRA_ARGS', '')) + DEFAULT_CONFIG_FILENAME = 'backups.ini' + log = logging.getLogger('backup') - def __init__(self, config, destination, pretend=False): - self.config = config + def __init__(self, destination, config=None, pretend=False): + self.config = configparser.ConfigParser() + print(config) + if not config: + config = open(self.default_config) + self.config.read_file(config) + self.config.filename = config.name self.destination = destination self.pretend = pretend self.stdout = sys.stdout self.stderr = sys.stderr + @property + def default_config(self): + try: + config_dir = os.environ['XDG_CONFIG_DIR'] + except KeyError: + config_dir = os.path.expanduser('~/.config') + return os.path.join(config_dir, self.DEFAULT_CONFIG_FILENAME) + def logsetup(self, log_file=None, log_level='INFO'): if not log_file: return @@ -134,7 +149,7 @@ def _parse_args(): help='Only back up specific items') parser.add_argument('--exclude', '-X', action='append', help='Do not back up specific items') - parser.add_argument('config', type=argparse.FileType('r'), + parser.add_argument('--config', '-c', type=argparse.FileType('r'), metavar='FILENAME', help='Path to configuration file') parser.add_argument('destination', metavar='FILENAME', @@ -144,12 +159,10 @@ def _parse_args(): def main(): args = _parse_args() - config = configparser.ConfigParser() - config.read_file(args.config) + backup = Backup(args.destination, args.config, args.pretend) if not args.quiet: print('Backing up to {} using configuration from {}'.format( - args.destination, args.config.name)) - backup = Backup(config, args.destination, args.pretend) + args.destination, backup.config.filename)) backup.logsetup(args.log_file, args.log_level) if not backup.backup_all(args.include, args.exclude): sys.stderr.write('Errors occurred during backup\n')