merge-db.py 1.7 KB

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