Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-ports-kde
Path: blob/main/cad/cura/files/mod_bundled_packages_json.py
16461 views
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
7
import argparse
8
import collections
9
import json
10
import os
11
import sys
12
13
14
def find_json_files(work_dir: str) -> list:
15
"""Finds all JSON files in the given directory recursively and returns a list of those files in absolute paths.
16
17
:param work_dir: The directory to look for JSON files recursively.
18
:return: A list of JSON files in absolute paths that are found in the given directory.
19
"""
20
21
json_file_list = []
22
for root, dir_names, file_names in os.walk(work_dir):
23
for file_name in file_names:
24
abs_path = os.path.abspath(os.path.join(root, file_name))
25
json_file_list.append(abs_path)
26
return json_file_list
27
28
29
def remove_entries_from_json_file(file_path: str, entries: list) -> None:
30
"""Removes the given entries from the given JSON file. The file will modified in-place.
31
32
:param file_path: The JSON file to modify.
33
:param entries: A list of strings as entries to remove.
34
:return: None
35
"""
36
37
try:
38
with open(file_path, "r", encoding = "utf-8") as f:
39
package_dict = json.load(f, object_hook = collections.OrderedDict)
40
except Exception as e:
41
msg = "Failed to load '{file_path}' as a JSON file. This file will be ignored Exception: {e}"\
42
.format(file_path = file_path, e = e)
43
sys.stderr.write(msg + os.linesep)
44
return
45
46
for entry in entries:
47
if entry in package_dict:
48
del package_dict[entry]
49
print("[INFO] Remove entry [{entry}] from [{file_path}]".format(file_path = file_path, entry = entry))
50
51
try:
52
with open(file_path, "w", encoding = "utf-8", newline = "\n") as f:
53
json.dump(package_dict, f, indent = 4)
54
except Exception as e:
55
msg = "Failed to write '{file_path}' as a JSON file. Exception: {e}".format(file_path = file_path, e = e)
56
raise IOError(msg)
57
58
59
def main() -> None:
60
parser = argparse.ArgumentParser("mod_bundled_packages_json")
61
parser.add_argument("-d", "--dir", dest = "work_dir",
62
help = "The directory to look for bundled packages JSON files, recursively.")
63
parser.add_argument("entries", metavar = "ENTRIES", type = str, nargs = "+")
64
65
args = parser.parse_args()
66
67
json_file_list = find_json_files(args.work_dir)
68
for json_file_path in json_file_list:
69
remove_entries_from_json_file(json_file_path, args.entries)
70
71
72
if __name__ == "__main__":
73
main()
74
75