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", encoding
="utf-8") 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 www_path
= args
.www_path
111 config_path
= "{}/config.js".format(www_path
)
112 data_path
= "{}/data".format(www_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 www_path = args.www_path
165 config_path = "{}/config
.js
".format(www_path)
166 data_path = "{}/data
".format(www_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
", encoding="utf
-8") 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
", encoding="utf
-8") 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 # firmware selector config
253 config_path = "{}/config
.js
".format(args.www_path)
254 # the overview.json files are placed here
255 data_path = "{}/data
".format(args.www_path)
258 # args.images_path => args.releases_path
260 for path in Path(args.images_path).rglob("profiles
.json
"):
261 with open(str(path), "r
", encoding="utf
-8") as file:
262 content = file.read()
263 obj = json.loads(content)
264 release = obj["version_number
"]
265 releases.setdefault(release, {})[path] = content
267 for release, profiles in releases.items():
268 output = merge_profiles(profiles, args.download_url)
270 versions[release] = "data
/{}/overview
.json
".format(release)
271 os.makedirs("{}/{}".format(data_path, release), exist_ok=True)
273 # write overview.json
274 with open("{}/{}/overview
.json
".format(data_path, release), "w
") as outfile:
276 json.dump(output, outfile, indent=" ", sort_keys=True)
278 json.dump(output, outfile, sort_keys=True)
280 update_config(config_path, versions)
284 parser = argparse.ArgumentParser()
286 "--formatted
", action="store_true
", help="Output formatted JSON data
."
288 subparsers = parser.add_subparsers(dest="action
")
289 subparsers.required = True
291 parser_merge = subparsers.add_parser(
292 "merge
", help="Search
for profiles
.json files
and output an overview
.json
."
294 parser_merge.add_argument(
297 help="Input folder that
is traversed
for OpenWrt JSON device files
.",
299 parser_merge.add_argument(
303 help="Link to get the image
from. May contain {target}
(replaced by e
.g
. ath79
/generic
), {version}
(replace by the version key
from config
.js
) and {commit}
(git commit
in hex notation
).",
306 parser_scrape = subparsers.add_parser("scrape
", help="Scrape webpage
for releases
.")
307 parser_scrape.add_argument(
308 "domain
", help="Domain to scrape
. E
.g
. https
://downloads
.openwrt
.org
"
310 parser_scrape.add_argument("www_path
", help="Path the config
.js
file is in.")
311 parser_scrape.add_argument(
312 "--use
-wget
", action="store_true
", help="Use wget to scrape the site
."
315 parser_scan = subparsers.add_parser("scan
", help="Scan directory
for releases
.")
316 parser_scan.add_argument(
317 "download_url
", help="Download
for images
. E
.g
. https
://downloads
.openwrt
.org
"
319 parser_scan.add_argument("images_path
", help="Directory to scan
for releases
.")
320 parser_scan.add_argument("www_path
", help="Path the config
.js
file is in.")
322 args = parser.parse_args()
324 if args.action == "merge
":
327 if args.action == "scan
":
330 if args.action == "scrape
":
337 if __name__ == "__main__
":