From b41671b9a6a0dbb9ee6320d865836857d51d1bb3 Mon Sep 17 00:00:00 2001 From: Romein van Buren Date: Fri, 28 Feb 2025 15:03:42 +0100 Subject: [PATCH] Add file add script --- write_file_to_riskset.py | 51 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100755 write_file_to_riskset.py diff --git a/write_file_to_riskset.py b/write_file_to_riskset.py new file mode 100755 index 0000000..ff15634 --- /dev/null +++ b/write_file_to_riskset.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python + +import base64 +import json +import os +import argparse + + +def encode_file_to_base64(file_path, json_path): + ''' + Reads a file, encodes its content in Base64, and writes it to a JSON file under ['files'][filename]. + ''' + if not os.path.isfile(file_path): + print(f'Error: File "{file_path}" not found.') + return + + with open(file_path, 'rb') as f: + encoded_content = base64.b64encode(f.read()).decode('utf-8') + + filename = os.path.basename(file_path) + json_data = {} + + # Read existing JSON if the file exists + if os.path.exists(json_path): + with open(json_path, 'r', encoding='utf-8') as json_file: + try: + json_data = json.load(json_file) + except json.JSONDecodeError: + print('Warning: JSON file is empty or invalid. Creating a new structure.') + + # Ensure 'files' key exists + if 'files' not in json_data: + json_data['files'] = {} + + # Add Base64 content under filename + json_data['files'][filename] = encoded_content + + # Write updated data back to JSON file + with open(json_path, 'w', encoding='utf-8') as json_file: + json.dump(json_data, json_file, indent=4) + + print(f'Successfully encoded "{filename}" and saved to "{json_path}".') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Encode a file to Base64 and store it in a JSON file.') + parser.add_argument('file_path', help='Path to the file to encode.') + parser.add_argument('json_path', help='Path to the JSON output file.') + + args = parser.parse_args() + encode_file_to_base64(args.file_path, args.json_path)