benchmark_lighthouse.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """Extracts the Lighthouse scores from the JSON files in the specified directory and inserts them into the database."""
  2. from __future__ import annotations
  3. import json
  4. import sys
  5. from pathlib import Path
  6. from utils import send_data_to_posthog
  7. def insert_benchmarking_data(
  8. lighthouse_data: dict,
  9. commit_sha: str,
  10. ):
  11. """Insert the benchmarking data into the database.
  12. Args:
  13. lighthouse_data: The Lighthouse data to insert.
  14. commit_sha: The commit SHA to insert.
  15. """
  16. properties = {
  17. "distinct_id": commit_sha,
  18. "lighthouse_data": lighthouse_data,
  19. }
  20. # Send the data to PostHog
  21. send_data_to_posthog("lighthouse_benchmark", properties)
  22. def get_lighthouse_scores(directory_path: str | Path) -> dict:
  23. """Extracts the Lighthouse scores from the JSON files in the specified directory.
  24. Args:
  25. directory_path (str): The path to the directory containing the JSON files.
  26. Returns:
  27. dict: The Lighthouse scores.
  28. """
  29. scores = {}
  30. directory_path = Path(directory_path)
  31. try:
  32. for filename in directory_path.iterdir():
  33. if filename.suffix == ".json" and filename.stem != "manifest":
  34. data = json.loads(filename.read_text())
  35. # Extract scores and add them to the dictionary with the filename as key
  36. scores[data["finalUrl"].replace("http://localhost:3000/", "/")] = {
  37. "performance_score": data["categories"]["performance"]["score"],
  38. "accessibility_score": data["categories"]["accessibility"]["score"],
  39. "best_practices_score": data["categories"]["best-practices"][
  40. "score"
  41. ],
  42. "seo_score": data["categories"]["seo"]["score"],
  43. }
  44. except Exception as e:
  45. return {"error": e}
  46. return scores
  47. def main():
  48. """Runs the benchmarks and inserts the results into the database."""
  49. # Get the commit SHA and JSON directory from the command line arguments
  50. commit_sha = sys.argv[1]
  51. json_dir = sys.argv[2]
  52. # Get the Lighthouse scores
  53. lighthouse_scores = get_lighthouse_scores(json_dir)
  54. # Insert the data into the database
  55. insert_benchmarking_data(lighthouse_scores, commit_sha)
  56. if __name__ == "__main__":
  57. main()