web/src/components/things/ItemGitHubMetrics.astro

163 lines · 4457 bytes

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