Path: blob/main/cad/cura/files/mod_bundled_packages_json.py
16461 views
#!/usr/bin/env python31#2# This script removes the given package entries in the bundled_packages JSON files. This is used by the PluginInstall3# CMake module.4#56import argparse7import collections8import json9import os10import sys111213def find_json_files(work_dir: str) -> list:14"""Finds all JSON files in the given directory recursively and returns a list of those files in absolute paths.1516:param work_dir: The directory to look for JSON files recursively.17:return: A list of JSON files in absolute paths that are found in the given directory.18"""1920json_file_list = []21for root, dir_names, file_names in os.walk(work_dir):22for file_name in file_names:23abs_path = os.path.abspath(os.path.join(root, file_name))24json_file_list.append(abs_path)25return json_file_list262728def remove_entries_from_json_file(file_path: str, entries: list) -> None:29"""Removes the given entries from the given JSON file. The file will modified in-place.3031:param file_path: The JSON file to modify.32:param entries: A list of strings as entries to remove.33:return: None34"""3536try:37with open(file_path, "r", encoding = "utf-8") as f:38package_dict = json.load(f, object_hook = collections.OrderedDict)39except Exception as e:40msg = "Failed to load '{file_path}' as a JSON file. This file will be ignored Exception: {e}"\41.format(file_path = file_path, e = e)42sys.stderr.write(msg + os.linesep)43return4445for entry in entries:46if entry in package_dict:47del package_dict[entry]48print("[INFO] Remove entry [{entry}] from [{file_path}]".format(file_path = file_path, entry = entry))4950try:51with open(file_path, "w", encoding = "utf-8", newline = "\n") as f:52json.dump(package_dict, f, indent = 4)53except Exception as e:54msg = "Failed to write '{file_path}' as a JSON file. Exception: {e}".format(file_path = file_path, e = e)55raise IOError(msg)565758def main() -> None:59parser = argparse.ArgumentParser("mod_bundled_packages_json")60parser.add_argument("-d", "--dir", dest = "work_dir",61help = "The directory to look for bundled packages JSON files, recursively.")62parser.add_argument("entries", metavar = "ENTRIES", type = str, nargs = "+")6364args = parser.parse_args()6566json_file_list = find_json_files(args.work_dir)67for json_file_path in json_file_list:68remove_entries_from_json_file(json_file_path, args.entries)697071if __name__ == "__main__":72main()737475