mod_bundled_packages_json.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python3
  2. #
  3. # This script removes the given package entries in the bundled_packages JSON files. This is used by the PluginInstall
  4. # CMake module.
  5. #
  6. import argparse
  7. import collections
  8. import json
  9. import os
  10. import sys
  11. def find_json_files(work_dir: str) -> list:
  12. """Finds all JSON files in the given directory recursively and returns a list of those files in absolute paths.
  13. :param work_dir: The directory to look for JSON files recursively.
  14. :return: A list of JSON files in absolute paths that are found in the given directory.
  15. """
  16. json_file_list = []
  17. for root, dir_names, file_names in os.walk(work_dir):
  18. for file_name in file_names:
  19. abs_path = os.path.abspath(os.path.join(root, file_name))
  20. json_file_list.append(abs_path)
  21. return json_file_list
  22. def remove_entries_from_json_file(file_path: str, entries: list) -> None:
  23. """Removes the given entries from the given JSON file. The file will modified in-place.
  24. :param file_path: The JSON file to modify.
  25. :param entries: A list of strings as entries to remove.
  26. :return: None
  27. """
  28. try:
  29. with open(file_path, "r", encoding = "utf-8") as f:
  30. package_dict = json.load(f, object_hook = collections.OrderedDict)
  31. except Exception as e:
  32. msg = "Failed to load '{file_path}' as a JSON file. This file will be ignored Exception: {e}"\
  33. .format(file_path = file_path, e = e)
  34. sys.stderr.write(msg + os.linesep)
  35. return
  36. for entry in entries:
  37. if entry in package_dict:
  38. del package_dict[entry]
  39. print("[INFO] Remove entry [{entry}] from [{file_path}]".format(file_path = file_path, entry = entry))
  40. try:
  41. with open(file_path, "w", encoding = "utf-8", newline = "\n") as f:
  42. json.dump(package_dict, f, indent = 4)
  43. except Exception as e:
  44. msg = "Failed to write '{file_path}' as a JSON file. Exception: {e}".format(file_path = file_path, e = e)
  45. raise IOError(msg)
  46. def main() -> None:
  47. parser = argparse.ArgumentParser("mod_bundled_packages_json")
  48. parser.add_argument("-d", "--dir", dest = "work_dir",
  49. help = "The directory to look for bundled packages JSON files, recursively.")
  50. parser.add_argument("entries", metavar = "ENTRIES", type = str, nargs = "+")
  51. args = parser.parse_args()
  52. json_file_list = find_json_files(args.work_dir)
  53. for json_file_path in json_file_list:
  54. remove_entries_from_json_file(json_file_path, args.entries)
  55. if __name__ == "__main__":
  56. main()