merge-db.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import json
  2. from argparse import ArgumentParser
  3. from pathlib import Path
  4. def read(f: str) -> dict[str, dict]:
  5. with open(f) as infile:
  6. next(infile)
  7. return {
  8. (d := json.loads(s))["name"]: d
  9. for line in infile
  10. if (s := line.strip().strip(",")) != "]"
  11. }
  12. parser = ArgumentParser(
  13. prog="DB Merger",
  14. description="Merge database files",
  15. )
  16. parser.add_argument(
  17. "-d", "--pokedex", help="Pokedex file"
  18. )
  19. parser.add_argument(
  20. "-o", "--output", default="data/latest.db", help="Output database file"
  21. )
  22. parser.add_argument("sources", metavar="file", type=Path, nargs="+")
  23. args = parser.parse_args()
  24. db = {}
  25. for s in args.sources:
  26. db.update(read(s))
  27. if args.pokedex is not None:
  28. with open(args.pokedex) as dex_file:
  29. dex = json.load(dex_file)
  30. for name, info in db.items():
  31. traits = next(
  32. f["traits"]
  33. for f in dex[str(info["num"])]["forms"]
  34. if f["name"] == name
  35. )
  36. db[name] = {
  37. **info,
  38. "traits": sorted(set([*info["traits"], *traits])),
  39. }
  40. output = [
  41. f" {json.dumps(s)},\n"
  42. for s in sorted(
  43. db.values(),
  44. key=lambda x: (x["num"], x["name"])
  45. )
  46. ]
  47. if args.output == "-":
  48. for o in output:
  49. print(o)
  50. else:
  51. with open(args.output, "w") as outfile:
  52. outfile.write("const database = [\n")
  53. outfile.writelines(output)
  54. outfile.write("]\n")