benchmark_lighthouse.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. file_path = directory_path / filename
  35. data = json.loads(file_path.read_text())
  36. # Extract scores and add them to the dictionary with the filename as key
  37. scores[data["finalUrl"].replace("http://localhost:3000/", "/")] = {
  38. "performance_score": data["categories"]["performance"]["score"],
  39. "accessibility_score": data["categories"]["accessibility"]["score"],
  40. "best_practices_score": data["categories"]["best-practices"][
  41. "score"
  42. ],
  43. "seo_score": data["categories"]["seo"]["score"],
  44. }
  45. except Exception as e:
  46. return {"error": e}
  47. return scores
  48. def main():
  49. """Runs the benchmarks and inserts the results into the database."""
  50. # Get the commit SHA and JSON directory from the command line arguments
  51. commit_sha = sys.argv[1]
  52. json_dir = sys.argv[2]
  53. # Get the Lighthouse scores
  54. lighthouse_scores = get_lighthouse_scores(json_dir)
  55. # Insert the data into the database
  56. insert_benchmarking_data(lighthouse_scores, commit_sha)
  57. if __name__ == "__main__":
  58. main()