1. import argparse
  2. import os
  3. import shutil
  4. import re
  5. def cleanup_artifacts(args):
  6. """
  7. Cleans up artifacts based on command-line arguments.
  8. Args:
  9. args: argparse.Namespace object containing command-line arguments.
  10. """
  11. if not args.force:
  12. if not args.confirm:
  13. print("Cleanup aborted.")
  14. return
  15. # Validate input (example: directory path)
  16. if not args.target_dir:
  17. raise ValueError("Target directory must be specified.")
  18. if not os.path.isdir(args.target_dir):
  19. raise ValueError("Target directory does not exist.")
  20. # Define artifact paths based on arguments
  21. artifact_paths = [
  22. os.path.join(args.target_dir, args.artifact1),
  23. os.path.join(args.target_dir, args.artifact2),
  24. os.path.join(args.target_dir, args.log_file)
  25. ]
  26. for path in artifact_paths:
  27. if os.path.exists(path):
  28. try:
  29. if args.remove:
  30. os.remove(path) # Delete the file
  31. print(f"Removed: {path}")
  32. else:
  33. print(f"Found: {path}")
  34. except Exception as e:
  35. print(f"Error removing {path}: {e}")
  36. # Cleanup directories
  37. for path in artifact_paths:
  38. if os.path.isdir(path):
  39. try:
  40. if args.remove_dir:
  41. shutil.rmtree(path) # Remove directory and contents
  42. print(f"Removed directory: {path}")
  43. else:
  44. print(f"Found directory: {path}")
  45. except Exception as e:
  46. print(f"Error removing directory {path}: {e}")
  47. #Example regex validation
  48. if args.regex_pattern:
  49. if not re.match(args.regex_pattern, args.some_string):
  50. raise ValueError("Input string does not match regex pattern.")
  51. if __name__ == '__main__':
  52. parser = argparse.ArgumentParser(description="Cleanup artifacts.")
  53. parser.add_argument("--target_dir", required=True, help="The directory to clean up.")
  54. parser.add_argument("--artifact1", help="Name of the first artifact file.")
  55. parser.add_argument("--artifact2", help="Name of the second artifact file.")
  56. parser.add_argument("--log_file", help="Name of the log file.")
  57. parser.add_argument("--remove", action="store_true", help="Remove artifacts.")
  58. parser.add_argument("--remove_dir", action="store_true", help="Remove directories.")
  59. parser.add_argument("--force", action="store_true", help="Force cleanup (skip confirmation).")
  60. parser.add_argument("--confirm", action="store_true", help="Confirm cleanup before proceeding.")
  61. parser.add_argument("--regex_pattern", help="Regex pattern for validating an input string.")
  62. parser.add_argument("--some_string", help="String to validate against the regex pattern.")
  63. args = parser.parse_args()
  64. try:
  65. cleanup_artifacts(args)
  66. except ValueError as e:
  67. print(f"Error: {e}")

Add your comment