import argparse
import os
import shutil
import re
def cleanup_artifacts(args):
"""
Cleans up artifacts based on command-line arguments.
Args:
args: argparse.Namespace object containing command-line arguments.
"""
if not args.force:
if not args.confirm:
print("Cleanup aborted.")
return
# Validate input (example: directory path)
if not args.target_dir:
raise ValueError("Target directory must be specified.")
if not os.path.isdir(args.target_dir):
raise ValueError("Target directory does not exist.")
# Define artifact paths based on arguments
artifact_paths = [
os.path.join(args.target_dir, args.artifact1),
os.path.join(args.target_dir, args.artifact2),
os.path.join(args.target_dir, args.log_file)
]
for path in artifact_paths:
if os.path.exists(path):
try:
if args.remove:
os.remove(path) # Delete the file
print(f"Removed: {path}")
else:
print(f"Found: {path}")
except Exception as e:
print(f"Error removing {path}: {e}")
# Cleanup directories
for path in artifact_paths:
if os.path.isdir(path):
try:
if args.remove_dir:
shutil.rmtree(path) # Remove directory and contents
print(f"Removed directory: {path}")
else:
print(f"Found directory: {path}")
except Exception as e:
print(f"Error removing directory {path}: {e}")
#Example regex validation
if args.regex_pattern:
if not re.match(args.regex_pattern, args.some_string):
raise ValueError("Input string does not match regex pattern.")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Cleanup artifacts.")
parser.add_argument("--target_dir", required=True, help="The directory to clean up.")
parser.add_argument("--artifact1", help="Name of the first artifact file.")
parser.add_argument("--artifact2", help="Name of the second artifact file.")
parser.add_argument("--log_file", help="Name of the log file.")
parser.add_argument("--remove", action="store_true", help="Remove artifacts.")
parser.add_argument("--remove_dir", action="store_true", help="Remove directories.")
parser.add_argument("--force", action="store_true", help="Force cleanup (skip confirmation).")
parser.add_argument("--confirm", action="store_true", help="Confirm cleanup before proceeding.")
parser.add_argument("--regex_pattern", help="Regex pattern for validating an input string.")
parser.add_argument("--some_string", help="String to validate against the regex pattern.")
args = parser.parse_args()
try:
cleanup_artifacts(args)
except ValueError as e:
print(f"Error: {e}")
Add your comment