From cb1cc280edd6504a8fa079c46bd076997bc9bbe3 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 1 Feb 2022 02:05:08 +0530 Subject: [PATCH] Convert CLI parsing from DIY to argparse --- BackupRotator.py | 37 +++++++------------------------------ main.py | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 32 deletions(-) diff --git a/BackupRotator.py b/BackupRotator.py index c4b9652..96f6ddd 100755 --- a/BackupRotator.py +++ b/BackupRotator.py @@ -29,10 +29,13 @@ class BackupRotator: self.__config_paths = [] self.__calculated_actions = [] - def run(self): + def run(self, configs, dry_run: bool = False): self.log("Begin") - self.consume_arguments() + + self.__dry_run = dry_run + self.__config_paths = configs + self.consume_configs(self.__config_paths) # Rotate once per config @@ -64,36 +67,10 @@ class BackupRotator: print(to_log) - def consume_arguments(self): - - self.__config_paths = [] - - for i in range(1, len(sys.argv)): - - arg = sys.argv[i] - - if arg == "--config": - i, one_path = self.consume_argument_companion(i) - self.__config_paths.append(one_path) - self.log("Found config path argument:", one_path) - - elif arg == "--dry-run": - self.__dry_run = True - self.log("Activating global dry-run mode") - - @staticmethod - def consume_argument_companion(arg_index): - - companion_index = arg_index + 1 - if companion_index >= len(sys.argv): - raise Exception("Expected argument after", sys.argv[arg_index]) - - return companion_index, sys.argv[companion_index] - def consume_configs(self, paths: list=None): - if paths is None: - raise Exception("Auto-finding of config file not implemented") + assert paths is not None, "Config paths cannot be None" + assert len(paths) > 0, "Must provide at least one config file path" # Use each config path for path in paths: diff --git a/main.py b/main.py index 3161e0c..98dfede 100755 --- a/main.py +++ b/main.py @@ -3,13 +3,41 @@ from BackupRotator import BackupRotator +import argparse + # def main(): + parser = argparse.ArgumentParser( + description="Mike's Backup Rotator. Helps automatically remove old backup files or folders." + ) + + parser.add_argument( + "--config", "-c", + dest="config_files", + default=[], + action="append", + type=str, + help="Specify a configuration file. Can be called multiple times." + ) + parser.add_argument( + "--dry-run", "-d", + dest="dry_run", + default=False, + action="store_true", + help="Only perform an analysis; Don't delete anything." + ) + + args = parser.parse_args() + rotator = BackupRotator() - rotator.run() - + rotator.run( + configs=args.config_files, + dry_run=args.dry_run + ) + if __name__ == "__main__": main() +