lighthouse_score_upload.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. """Runs the benchmarks and inserts the results into the database."""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import sys
  6. from datetime import datetime
  7. import psycopg2
  8. def insert_benchmarking_data(
  9. db_connection_url: str,
  10. lighthouse_data: dict,
  11. commit_sha: str,
  12. pr_title: str,
  13. ):
  14. """Insert the benchmarking data into the database.
  15. Args:
  16. db_connection_url: The URL to connect to the database.
  17. lighthouse_data: The Lighthouse data to insert.
  18. commit_sha: The commit SHA to insert.
  19. pr_title: The PR title to insert.
  20. """
  21. # Serialize the JSON data
  22. lighthouse_json = json.dumps(lighthouse_data)
  23. # Get the current timestamp
  24. current_timestamp = datetime.now()
  25. # Connect to the database and insert the data
  26. with psycopg2.connect(db_connection_url) as conn, conn.cursor() as cursor:
  27. insert_query = """
  28. INSERT INTO benchmarks (lighthouse, commit_sha, pr_title, time)
  29. VALUES (%s, %s, %s, %s);
  30. """
  31. cursor.execute(
  32. insert_query,
  33. (
  34. lighthouse_json,
  35. commit_sha,
  36. pr_title,
  37. current_timestamp,
  38. ),
  39. )
  40. # Commit the transaction
  41. conn.commit()
  42. def get_lighthouse_scores(directory_path: str) -> dict:
  43. """Extracts the Lighthouse scores from the JSON files in the specified directory.
  44. Args:
  45. directory_path (str): The path to the directory containing the JSON files.
  46. Returns:
  47. dict: The Lighthouse scores.
  48. """
  49. scores = {}
  50. try:
  51. for filename in os.listdir(directory_path):
  52. if filename.endswith(".json") and filename != "manifest.json":
  53. file_path = os.path.join(directory_path, filename)
  54. with open(file_path, "r") as file:
  55. data = json.load(file)
  56. # Extract scores and add them to the dictionary with the filename as key
  57. scores[data["finalUrl"].replace("http://localhost:3000/", "")] = {
  58. "performance_score": data["categories"]["performance"]["score"],
  59. "accessibility_score": data["categories"]["accessibility"][
  60. "score"
  61. ],
  62. "best_practices_score": data["categories"]["best-practices"][
  63. "score"
  64. ],
  65. "seo_score": data["categories"]["seo"]["score"],
  66. "pwa_score": data["categories"]["pwa"]["score"],
  67. }
  68. except Exception as e:
  69. print(e)
  70. return {"error": "Error parsing JSON files"}
  71. return scores
  72. def main():
  73. """Runs the benchmarks and inserts the results into the database."""
  74. # Get the commit SHA and JSON directory from the command line arguments
  75. commit_sha = sys.argv[1]
  76. json_dir = sys.argv[2]
  77. # Get the PR title and database URL from the environment variables
  78. pr_title = os.environ.get("PR_TITLE")
  79. db_url = os.environ.get("DATABASE_URL")
  80. if db_url is None or pr_title is None:
  81. sys.exit("Missing environment variables")
  82. # Get the Lighthouse scores
  83. lighthouse_scores = get_lighthouse_scores(json_dir)
  84. # Insert the data into the database
  85. insert_benchmarking_data(db_url, lighthouse_scores, commit_sha, pr_title)
  86. if __name__ == "__main__":
  87. main()