import os
import sys
import json
import argparse
def validate_filename(filename):
"""Basic filename validation."""
if not filename:
return False, "Filename cannot be empty."
if not filename.endswith(('.bin')):
return False, "Filename must end with .bin"
return True, None
def extract_metadata(filepath):
"""Extracts metadata from a binary file (simulated)."""
try:
with open(filepath, 'rb') as f:
# Simulate reading metadata - replace with actual parsing logic
metadata = {
"size": os.path.getsize(filepath),
"creation_date": file_creation_date(filepath),
"author": "Unknown",
"description": "Binary file metadata"
}
return metadata
except FileNotFoundError:
return None
except Exception as e:
print(f"Error reading file {filepath}: {e}")
return None
def file_creation_date(filepath):
"""Simulates getting creation date."""
return os.path.getctime(filepath)
def attach_metadata(filepath, metadata_file):
"""Attaches metadata to a binary file."""
is_valid, error_message = validate_filename(filepath)
if not is_valid:
print(f"Error: {error_message}")
return False
metadata = extract_metadata(filepath)
if metadata is None:
return False
try:
with open(metadata_file, 'r') as f:
try:
metadata_data = json.load(f)
except json.JSONDecodeError:
print(f"Error: Invalid JSON in {metadata_file}. Creating a new metadata file.")
metadata_data = {}
except FileNotFoundError:
print(f"Creating new metadata file {metadata_file}")
metadata_data = {}
except Exception as e:
print(f"Error reading metadata file {metadata_file}: {e}")
return False
metadata_data[os.path.basename(filepath)] = metadata
try:
with open(metadata_file, 'w') as f:
json.dump(metadata_data, f, indent=4)
print(f"Metadata attached to {filepath} and saved to {metadata_file}")
return True
except Exception as e:
print(f"Error writing to metadata file {metadata_file}: {e}")
return False
def main():
parser = argparse.ArgumentParser(description="Attach metadata to binary files.")
parser.add_argument("binary_files", nargs="+", help="List of binary files to process.")
parser.add_argument("-m", "--metadata_file", default="metadata.json", help="File to store metadata.")
args = parser.parse_args()
for binary_file in args.binary_files:
attach_metadata(binary_file, args.metadata_file)
if __name__ == "__main__":
main()
Add your comment