web/src/components/things/ItemGitHubMetrics.astro

155 lines · 4146 bytes

  1---
  2import FontAwesome from "@components/form/FontAwesome.svelte";
  3const { github } = Astro.props;
  4
  5// const [user, repo] = github.split("/");
  6
  7/**
  8 * For a given `user/repo` fetch repository stats from the GitHub API data
  9 * If API key is available through env var, use it to increase rate limit
 10 * Returns the response data and status code (200 == success)
 11 * @param repo 
 12 */
 13const fetchGitHubData = async (repo: string) => {
 14  const apiKey = import.meta.env.GITHUB_API_KEY;
 15  const headers = new Headers();
 16  if (apiKey) {
 17    headers.append("Authorization", `token ${apiKey}`);
 18  }
 19
 20  let data = {};
 21  let statusCode = 0;
 22
 23  const response = await fetch(`https://api.github.com/repos/${repo}`, {
 24    headers: headers,
 25  }).catch((e) => {
 26    console.error(`Network error: ${e.message}`);
 27    // Return a placeholder response to handle this gracefully
 28    return null;
 29  });
 30
 31  // Check if fetch was successful but caught by the catch block
 32  if (!response) {
 33    return { data, statusCode: 503 }; // Use an appropriate error status code
 34  }
 35
 36  statusCode = response.status;
 37
 38  // Only attempt to parse JSON if the response was OK
 39  if (response.ok) {
 40    data = await response.json();
 41  } else {
 42    console.error(`HTTP error: Received status code ${response.status}`);
 43  }
 44
 45  return { data, statusCode };
 46};
 47
 48
 49/**
 50 * Given a license object, return SPDX ID, or a formatted name
 51 * @param license 
 52 */
 53const formatLicense = (license: { spdx_id?: string, name?: string }) => {
 54  if (!license) {
 55    return "Unknown";
 56  }
 57  if (license.spdx_id === "NOASSERTION") {
 58    return "No License";
 59  }
 60  return license.spdx_id;
 61}
 62
 63/**
 64 * Given a (possibly large) number, return a formatted string
 65 * E.g. If greater than thousand, then return in k format
 66 * @param num 
 67 */
 68const formatBigNumber = (num: number) => {
 69  if (num > 1000) {
 70    return `${(num / 1000).toFixed(1)}k`;
 71  }
 72  return num;
 73}
 74
 75// Initiate GitHub fetch, and make available to the component
 76const stats = (await fetchGitHubData(github)) as any;
 77
 78const {
 79  stargazers_count, forks_count, open_issues_count, language, license,
 80} = stats.data;
 81
 82
 83---
 84
 85<div class="github-metrics">
 86  <!-- <span title={`Built / owned by @${user}`}>
 87    <img src={`https://github.com/${user}.png`} alt={user || owner?.login} width="20" height="20" />
 88  </span> -->
 89  <!-- <span title={`${repo} is open source, with code published on GitHub`}>
 90    <FontAwesome iconName="openSource" /> Open Source
 91  </span> -->
 92  <span title={`GitHub repository:  ${github}`}>
 93    <a href={`https://github.com/${github}`} target="_blank"><FontAwesome iconName="github" /> {github}</a>
 94  </span>
 95  { stats.statusCode === 200 && stats.data && (
 96    <span title={`GitHub Star Count: ${stargazers_count}`}>
 97      <FontAwesome iconName="stars" /> {formatBigNumber(stargazers_count)}
 98    </span>
 99    <span title={`GitHub Fork Count: ${forks_count}`}>
100      <FontAwesome iconName="forks" /> {formatBigNumber(forks_count)}
101    </span>
102    <span title={`Open Issues / Bugs: ${open_issues_count}`}>
103      <FontAwesome iconName="issues" /> {formatBigNumber(open_issues_count)}
104    </span>
105    <span title={`Code licensed under ${license?.name}`}>
106      <FontAwesome iconName="license" /> {formatLicense(license)}
107    </span>
108    <span title={`Primary programming language ${language}`}>
109      <FontAwesome iconName="language" /> {language}
110    </span>
111  )}
112</div>
113
114
115<style lang="scss">
116.github-metrics {
117  display: flex;
118  align-items: center;
119  gap: 1rem;
120  font-size: 0.9rem;
121  opacity: 0.6;
122  flex-wrap: wrap;
123  span {
124    display: flex;
125    align-items: center;
126    justify-content: center;
127    color: var(--foreground);
128    gap: 0.25rem;
129    padding: 0.5rem 0;
130
131    a {
132      color: var(--foreground);
133      text-decoration: none;
134      align-items: center;
135      display: flex;
136      gap: 0.25rem;
137      transition: all 0.2s ease-in-out;
138      color: var(--accent-3);
139      &:hover {
140        color: var(--accent-3);
141        text-decoration: underline;
142      }
143    }
144
145    img {
146      border-radius: var(--curve-md);
147    }
148  }
149  :global(svg) {
150    color: var(--foregroung);
151    width: 1.1rem;
152    height: 1.1rem;
153  }
154}
155</style>