3 Tool to create overview.json files and update the config.js.
6 from pathlib
import Path
16 SUPPORTED_METADATA_VERSION
= 1
18 assert sys
.version_info
>= (3, 5), "Python version too old. Python >=3.5.0 needed."
21 # accepts {<file-path>: <file-content>}
22 def merge_profiles(profiles
, download_url
):
30 return "{} {} {}".format(
31 title
.get("vendor", ""), title
["model"], title
.get("variant", "")
34 def add_profile(path
, id, target
, profile
, code
=None):
36 for image
in profile
["images"]:
37 images
.append({"name": image
["name"], "type": image
["type"]})
40 target
= profile
["target"]
42 for entry
in profile
["titles"]:
43 title
= get_title(entry
)
47 "Empty title. Skip title for {} in {}\n".format(id, path
)
51 output
["models"][title
] = {"id": id, "target": target
, "images": images
}
54 output
["models"][title
]["code"] = code
56 for path
, content
in profiles
.items():
57 obj
= json
.loads(content
)
59 if obj
["metadata_version"] != SUPPORTED_METADATA_VERSION
:
61 "{} has unsupported metadata version: {} => skip\n".format(
62 path
, obj
["metadata_version"]
67 code
= obj
.get("version_code", obj
.get("version_commit"))
69 if "version_code" not in output
:
70 output
= {"version_code": code
, "download_url": download_url
, "models": {}}
72 # if we have mixed codes/commits, store in device object
73 if output
["version_code"] == code
:
78 for id in obj
["profiles"]:
79 add_profile(path
, id, obj
.get("target"), obj
["profiles"][id], code
)
81 add_profile(path
, obj
["id"], obj
["target"], obj
, code
)
82 except json
.decoder
.JSONDecodeError
as e
:
83 sys
.stderr
.write("Skip {}\n {}\n".format(path
, e
))
85 sys
.stderr
.write("Abort on {}\n Missing key {}\n".format(path
, e
))
91 def update_config(config_path
, versions
):
93 with
open(str(config_path
), "r") as file:
96 content
= re
.sub("versions:[\\s]*{[^}]*}", "versions: {}".format(versions
), content
)
97 with
open(str(config_path
), "w+") as file:
102 Scrape profiles.json using links like https://downloads.openwrt.org/releases/19.07.3/targets/?json
103 Merge into overview.json files.
110 selector_path
= args
.selector
111 config_path
= "{}/config.js".format(selector_path
)
112 data_path
= "{}/data".format(selector_path
)
115 def handle_release(target
):
117 with urllib
.request
.urlopen("{}/?json".format(target
)) as file:
118 array
= json
.loads(file.read().decode("utf-8"))
119 for profile
in filter(lambda x
: x
.endswith("/profiles.json"), array
):
120 with urllib
.request
.urlopen("{}/{}".format(target
, profile
)) as file:
121 profiles
["{}/{}".format(target
, profile
)] = file.read().decode(
126 if not os
.path
.isfile(config_path
):
127 print("file not found: {}".format(config_path
))
131 with urllib
.request
.urlopen(url
) as infile
:
132 for path
in re
.findall(r
"href=[\"']?([^'\" >]+)", str(infile.read())):
133 if not path.startswith("/") and path.endswith("targets
/"):
134 release = path.strip("/").split("/")[-2]
135 download_url = "{}/{}/{{target}
}".format(url, path)
137 profiles = handle_release("{}/{}".format(url, path))
138 output = merge_profiles(profiles, download_url)
140 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
141 # write overview.json
143 "{}/{}/overview
.json
".format(data_path, release), "w
"
146 json.dump(output, outfile, indent=" ", sort_keys=True)
148 json.dump(output, outfile, sort_keys=True)
150 versions[release] = "data
/{}/overview
.json
".format(release)
152 update_config(config_path, versions)
156 Scrape profiles.json using wget (slower but more generic).
157 Merge into overview.json files.
162 def scrape_wget(args):
164 selector_path = args.selector
165 config_path = "{}/config
.js
".format(selector_path)
166 data_path = "{}/data
".format(selector_path)
169 with tempfile.TemporaryDirectory() as tmp_dir:
170 # download all profiles.json files
172 "wget
-c
-r
-P
{} -A
'profiles.json' --reject
-regex
'kmods|packages' --no
-parent
{}".format(
177 # delete empty folders
178 os.system("find
{}/* -type d
-empty
-delete
".format(tmp_dir))
180 # create overview.json files
181 for path in glob.glob("{}/*/snapshots
".format(tmp_dir)) + glob.glob(
182 "{}/*/releases
/*".format(tmp_dir)
184 release = os.path.basename(path)
185 base = path[len(tmp_dir) + 1 :]
188 for ppath in Path(path).rglob("profiles
.json
"):
189 with open(str(ppath), "r
") as file:
190 profiles[ppath] = file.read()
192 if len(profiles) == 0:
195 versions[release] = "data
/{}/overview
.json
".format(release)
197 output = merge_profiles(
198 profiles, "https
://{}/targets
/{{target}
}".format(base)
200 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
202 # write overview.json
203 with open("{}/{}/overview
.json
".format(data_path, release), "w
") as outfile:
205 json.dump(output, outfile, indent=" ", sort_keys=True)
207 json.dump(output, outfile, sort_keys=True)
209 update_config(config_path, versions)
213 Find and merge json files for a single release.
218 input_paths = args.input_path
219 # OpenWrt JSON device files
223 with open(str(path), "r
") as file:
224 profiles[path] = file.read()
226 for path in input_paths:
227 if os.path.isdir(path):
228 for filepath in Path(path).rglob("*.json
"):
231 if not path.endswith(".json
"):
232 sys.stderr.write("Folder does
not exists
: {}\n".format(path))
236 output = merge_profiles(profiles, args.download_url)
239 json.dump(output, sys.stdout, indent=" ", sort_keys=True)
241 json.dump(output, sys.stdout, sort_keys=True)
245 Scan local directory for releases with profiles.json.
246 Merge into overview.json files.
252 selector_path = args.selector
253 config_path = "{}/config
.js
".format(selector_path)
254 data_path = "{}/data
".format(selector_path)
257 # create overview.json files
258 for path in glob.glob("{}/snapshots
".format(args.directory)) + glob.glob(
259 "{}/releases
/*".format(args.directory)
261 release = os.path.basename(path)
262 base_dir = path[len(args.directory) + 1 :]
265 for ppath in Path(path).rglob("profiles
.json
"):
266 with open(str(ppath), "r
", encoding="utf
-8") as file:
267 profiles[ppath] = file.read()
269 if len(profiles) == 0:
272 versions[release] = "data
/{}/overview
.json
".format(release)
274 output = merge_profiles(
275 profiles, "https
://{}/{}/targets
/{{target}
}".format(args.domain, base_dir)
277 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
279 # write overview.json
280 with open("{}/{}/overview
.json
".format(data_path, release), "w
") as outfile:
282 json.dump(output, outfile, indent=" ", sort_keys=True)
284 json.dump(output, outfile, sort_keys=True)
286 update_config(config_path, versions)
290 parser = argparse.ArgumentParser()
292 "--formatted
", action="store_true
", help="Output formatted JSON data
."
294 subparsers = parser.add_subparsers(dest="action
")
295 subparsers.required = True
297 parser_merge = subparsers.add_parser(
299 help="Create a grid structure with horizontal
and vertical connections
.",
301 parser_merge.add_argument(
304 help="Input folder that
is traversed
for OpenWrt JSON device files
.",
306 parser_merge.add_argument(
310 help="Link to get the image
from. May contain {target}
, {version}
and {commit}
",
313 parser_scrape = subparsers.add_parser("scrape
", help="Scrape webpage
for releases
.")
314 parser_scrape.add_argument(
315 "domain
", help="Domain to scrape
. E
.g
. https
://downloads
.openwrt
.org
"
317 parser_scrape.add_argument("selector
", help="Path the config
.js
file is in.")
318 parser_scrape.add_argument(
319 "--use
-wget
", action="store_true
", help="Use wget to scrape the site
."
322 parser_scan = subparsers.add_parser("scan
", help="Scan directory
for releases
.")
323 parser_scan.add_argument(
325 help="Domain
for download_url attribute
in overview
.json
. E
.g
. https
://downloads
.openwrt
.org
",
327 parser_scan.add_argument("directory
", help="Directory to scan
for releases
.")
328 parser_scan.add_argument("selector
", help="Path the config
.js
file is in.")
330 args = parser.parse_args()
332 if args.action == "merge
":
335 if args.action == "scan
":
338 if args.action == "scrape
":
345 if __name__ == "__main__
":