Compare commits

...
33 Commits
Author SHA1 Message Date
anuraghazra a726e8dbaf chore: added funding link
Test / build (push) Canceled after 0s
2020-07-16 14:02:15 +05:30
Anurag Hazra 817f736b4e Merge pull request #61 from JounQin/patch-1
chore: remove redundant codes
2020-07-15 20:37:42 +05:30
Anurag Hazra 987fb0c30d Merge pull request #49 from anuraghazra/ranking-algo
improve: improved rating algorithm wip

fix: fixed #39
2020-07-15 20:10:53 +05:30
anuraghazra 96d37c706f fix: fixed stars count #39 & fixed progressbar percentage
Test / build (push) Canceled after 0s
2020-07-15 20:00:22 +05:30
anuraghazra 3a24ad62b1 Merge branch 'master' into ranking-algo 2020-07-15 19:47:07 +05:30
Anurag Hazra 989079e4fd Merge pull request #64 from anuraghazra/fix-nolang
fix: fixed repo card breaking in absence of primaryLanguage
2020-07-15 19:39:40 +05:30
anuraghazra 20bddc3a0c fix: fixed repo card breaking in absence of primaryLanguage
Test / build (push) Canceled after 0s
2020-07-15 19:37:04 +05:30
JounQin 95f1233ab9 chore: rebase from master 2020-07-15 21:55:04 +08:00
JounQin 1a53fb9a84 Merge branch 'master' into patch-1 2020-07-15 21:41:48 +08:00
Anurag Hazra 19bacf780a Merge pull request #63 from anuraghazra/fix-rank-alignment
design: fixed rank alignment
2020-07-15 19:01:39 +05:30
anuraghazra 89bb8fea42 design: fixed rank alignment 2020-07-15 18:59:38 +05:30
Anurag Hazra 0bade9be77 Merge pull request #62 from anuraghazra/fix-queryparams
fix: query param booleans
2020-07-15 18:34:19 +05:30
anuraghazra 5fce46d67c fix: query param booleans
Test / build (push) Canceled after 0s
2020-07-15 18:32:16 +05:30
Anurag Hazra 00ce9d37d2 Merge pull request #54 from MicaelJarniac/patch-1
docs: Fixed typos, punctuation
2020-07-15 18:16:27 +05:30
Anurag Hazra 9328a57ea6 Merge pull request #58 from anuraghazra/fix-ratelimit
fix: increase github rate limit with multiple PATs

- special thanks to @filiptronicek @ApurvShah007 @garvit-joshi for helping out :D
2020-07-15 17:53:43 +05:30
JounQin 579ed2bab8 chore: remove redundant codes
`axios` is Promise based, there is no need to wrap it into a Promise constructor again
2020-07-15 20:22:06 +08:00
anuraghazra 429d65a52b refactor: refactored retryer logic & handled invalid tokens
Test / build (push) Canceled after 0s
2020-07-15 17:46:31 +05:30
anuraghazra 3d8dea90e2 fix: github rate limiter with multiple PATs 2020-07-15 14:59:25 +05:30
Micael Jarniac 47370adbbb Fixed typos, punctuation [...]
Corrected many instances of "Github" to "GitHub", fixed the punctuation on some sections, fixed the ~lack of~ uppercase chars in others, tweaked the grammar a bit, and added the Vercel guide to a spoiler-ish section so it's only visible if you click to expand.

<3
2020-07-14 18:08:52 -03:00
Anurag Hazra 2efb399f33 Merge pull request #53 from filiptronicek/master
docs: Add "Host yourself" docs
2020-07-15 01:19:12 +05:30
Filip Troníček dcde5f8205 Crop the image a bit 2020-07-14 21:40:38 +02:00
Filip Troníček 3b3ce41ae4 Fix img positions 2020-07-14 21:32:06 +02:00
Filip Troníček e3519ceb4c Add documentation for Vercel setup 2020-07-14 21:30:03 +02:00
Anurag Hazra c297798889 Merge pull request #50 from anuraghazra/animations
feat: added animations!
2020-07-14 21:04:11 +05:30
anuraghazra 6059cb1691 feat: added animations!
Test / build (push) Canceled after 0s
2020-07-14 20:04:36 +05:30
anuraghazra 2658a8737d improve: improved rating algorithm wip 2020-07-14 14:08:57 +05:30
Anurag Hazra cbd0e583ff Merge pull request #48 from anuraghazra/fix-circl-rank-rim
design: added a rim to circle rank's progress
2020-07-14 13:12:56 +05:30
anuraghazra 6f79b495a6 design: added a rim to circle rank's progress 2020-07-14 13:02:45 +05:30
Anurag Hazra 014f710e12 fix: firefox layout breaking (#45)
* fix: firefox layout breaking

* refactor: refactored code and added comments

* chore: remove useragent dep
2020-07-13 23:47:04 +05:30
Anurag Hazra 29d3ea63f8 Merge pull request #40 from anuraghazra/ranking
feat: added rankings
2020-07-13 20:04:52 +05:30
anuraghazra c272a21342 docs: added rank docs
Test / build (push) Canceled after 0s
2020-07-13 19:50:43 +05:30
anuraghazra db49ca7b71 feat: added rankings 2020-07-13 19:41:47 +05:30
Anurag Hazra 8e8d7dd64d Merge pull request #37 from anuraghazra/fix-name-null
fix: fallback to login if name not found
2020-07-13 16:15:50 +05:30
17 changed files with 597 additions and 121 deletions
+12
View File
@@ -0,0 +1,12 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: ["https://www.paypal.me/anuraghazra"] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+7 -3
View File
@@ -1,5 +1,5 @@
require("dotenv").config();
const { renderError } = require("../src/utils");
const { renderError, parseBoolean } = require("../src/utils");
const fetchStats = require("../src/fetchStats");
const renderStatsCard = require("../src/renderStatsCard");
@@ -8,6 +8,7 @@ module.exports = async (req, res) => {
username,
hide,
hide_border,
hide_rank,
show_icons,
line_height,
title_color,
@@ -17,7 +18,9 @@ module.exports = async (req, res) => {
} = req.query;
let stats;
res.setHeader("Cache-Control", "public, max-age=1800");
res.setHeader("Content-Type", "image/svg+xml");
try {
stats = await fetchStats(username);
} catch (err) {
@@ -27,8 +30,9 @@ module.exports = async (req, res) => {
res.send(
renderStatsCard(stats, {
hide: JSON.parse(hide || "[]"),
show_icons,
hide_border,
show_icons: parseBoolean(show_icons),
hide_border: parseBoolean(hide_border),
hide_rank: parseBoolean(hide_rank),
line_height,
title_color,
icon_color,
+2
View File
@@ -14,6 +14,8 @@ module.exports = async (req, res) => {
} = req.query;
let repoData;
res.setHeader("Cache-Control", "public, max-age=1800");
res.setHeader("Content-Type", "image/svg+xml");
try {
+41 -19
View File
@@ -1,6 +1,7 @@
<p align="center">
<h2 align="center">Github Readme Stats</h2>
<h2 align="center">GitHub Readme Stats</h2>
<p align="center">Get dynamically generated GitHub stats on your readmes!</p>
</p>
<p align="center">
<a href="https://github.com/anuraghazra/github-readme-stats/actions">
@@ -22,27 +23,30 @@
<a href="https://github.com/anuraghazra/github-readme-stats/issues">Request Feature</a>
</p>
</p>
<p align="center">Loved the project? Please consider <a href="https://www.paypal.me/anuraghazra">donating</a> to help it improve!
# Features
- [Github Stats Card](#github-stats-card)
- [Github Extra Pins](#github-extra-pins)
- [GitHub Stats Card](#github-stats-card)
- [GitHub Extra Pins](#github-extra-pins)
- [Customization](#customization)
- [Deploy Yourself](#deploy-on-your-own-vercel-instance)
# Github Stats Card
# GitHub Stats Card
Copy paste this into your markdown content, and that's it. Simple!
change the `?username=` value to your GitHubs's username
Change the `?username=` value to your GitHub's username.
```md
[![Anurag's github stats](https://github-readme-stats.vercel.app/api?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats)
```
_Note: Ranks are calculated based on user's stats, see [src/calculateRank.js](./src/calculateRank.js)_
### Hiding individual stats
To hide any specific stats, you can pass a query parameter `?hide=` with an array of items, you wanna hide.
To hide any specific stats, you can pass a query parameter `?hide=` with an array of items you wanna hide.
> Options: `&hide=["stars","prs","issues","contribs"]`
@@ -52,7 +56,7 @@ To hide any specific stats, you can pass a query parameter `?hide=` with an arra
### Showing icons
To enable icons, you can pass `show_icons=true` in the query param like so
To enable icons, you can pass `show_icons=true` in the query param, like so:
```md
![Anurag's github stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true)
@@ -60,12 +64,13 @@ To enable icons, you can pass `show_icons=true` in the query param like so
Other options:
- `&hide_border=true` hide the border box if you don't like it :D.
- `&line_height=30` control the line-height between text.
- `&hide_border=true` hide the border box if you don't like it :D
- `&line_height=30` control the line-height between text
- `&hide_rank=true` hides the ranking
### Customization
You can customize the appearance of your `Stats Card` or `Repo Card` however you want with url params.
You can customize the appearance of your `Stats Card` or `Repo Card` however you want with URL params.
Customization Options:
@@ -104,11 +109,11 @@ Customization Options:
![Customized Card](https://github-readme-stats.vercel.app/api/pin?username=anuraghazra&repo=github-readme-stats&title_color=fff&icon_color=f9f9f9&text_color=9f9f9f&bg_color=151515)
# Github Extra Pins
# GitHub Extra Pins
Github extra pins allow you to pin more than 6 repositories in your profile using a GitHub readme profile.
GitHub extra pins allow you to pin more than 6 repositories in your profile using a GitHub readme profile.
Yey! you are no longer limited to 6 pinned repositories.
Yey! You are no longer limited to 6 pinned repositories.
### Usage
@@ -126,7 +131,7 @@ Endpoint: `api/pin?username=anuraghazra&repo=github-readme-stats`
### Quick Tip (Align The Repo Cards)
You usually won't be able to layout the images side by side to do that you can use this approach
You usually won't be able to layout the images side by side. To do that you can use this approach:
```md
<a href="https://github.com/anuraghazra/github-readme-stats">
@@ -137,15 +142,32 @@ You usually won't be able to layout the images side by side to do that you can u
</a>
```
## Deploy on your own vercel instance
## Deploy on your own Vercel instance
Since Github API only allows 5k requests per hour it is possible that my `https://github-readme-stats.vercel.app/api` could hit the rate limiter thats why if you want to host it on your own vercel server then you don't have to worry about anything. click on the deploy button to get started
Since the GitHub API only allows 5k requests per hour, it is possible that my `https://github-readme-stats.vercel.app/api` could hit the rate limiter. If you host it on your own Vercel server, then you don't have to worry about anything. Click on the deploy button to get started!
[![Deploy to Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/anuraghazra/github-readme-stats)
Make sure to add your own `GITHUB_TOKEN` in `Environment Variables`
[Github Docs: Creating a github personal token](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token)
<details>
<summary>Guide on setting up Vercel</summary>
1. Go to [vercel.com](https://vercel.com/)
1. Click on `Log in`
![](https://files.catbox.moe/tct1wg.png)
1. Sign in with GitHub by pressing `Continue with GitHub`
![](https://files.catbox.moe/btd78j.jpeg)
1. Sign into GitHub and allow access to all repositories, if prompted
1. Fork this repo
1. Go back to your [Vercel dashboard](https://vercel.com/dashboard)
1. Select `Import Project`
![](https://files.catbox.moe/qckos0.png)
1. Select `Import Git Repository`
![](https://files.catbox.moe/pqub9q.png)
1. Select root and keep everything as is, just add your environment variable named GITHUB_TOKEN (as shown), which will contain a personal access token (PAT), which you can easily create [here](https://github.com/settings/tokens/new) (leave everything as is, just name it something, it can be anything you want)
![](https://files.catbox.moe/caem5b.png)
1. Click deploy, and you're good to go. See your domains to use the API!
</details>
Contributions are welcomed! <3
Made with :heart: and javascript.
Made with :heart: and JavaScript.
+93
View File
@@ -0,0 +1,93 @@
// https://stackoverflow.com/a/5263759/10629172
function normalcdf(mean, sigma, to) {
var z = (to - mean) / Math.sqrt(2 * sigma * sigma);
var t = 1 / (1 + 0.3275911 * Math.abs(z));
var a1 = 0.254829592;
var a2 = -0.284496736;
var a3 = 1.421413741;
var a4 = -1.453152027;
var a5 = 1.061405429;
var erf =
1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-z * z);
var sign = 1;
if (z < 0) {
sign = -1;
}
return (1 / 2) * (1 + sign * erf);
}
function calculateRank({
totalRepos,
totalCommits,
contributions,
followers,
prs,
issues,
stargazers,
}) {
const COMMITS_OFFSET = 1.65;
const CONTRIBS_OFFSET = 1.65;
const ISSUES_OFFSET = 1;
const STARS_OFFSET = 0.75;
const PRS_OFFSET = 0.5;
const FOLLOWERS_OFFSET = 0.45;
const REPO_OFFSET = 1;
const ALL_OFFSETS =
CONTRIBS_OFFSET +
ISSUES_OFFSET +
STARS_OFFSET +
PRS_OFFSET +
FOLLOWERS_OFFSET +
REPO_OFFSET;
const RANK_S_VALUE = 1;
const RANK_DOUBLE_A_VALUE = 25;
const RANK_A2_VALUE = 45;
const RANK_A3_VALUE = 60;
const RANK_B_VALUE = 100;
const TOTAL_VALUES =
RANK_S_VALUE + RANK_A2_VALUE + RANK_A3_VALUE + RANK_B_VALUE;
// prettier-ignore
const score = (
totalCommits * COMMITS_OFFSET +
contributions * CONTRIBS_OFFSET +
issues * ISSUES_OFFSET +
stargazers * STARS_OFFSET +
prs * PRS_OFFSET +
followers * FOLLOWERS_OFFSET +
totalRepos * REPO_OFFSET
) / 100;
const normalizedScore = normalcdf(score, TOTAL_VALUES, ALL_OFFSETS) * 100;
let level = "";
if (normalizedScore < RANK_S_VALUE) {
level = "S+";
}
if (
normalizedScore >= RANK_S_VALUE &&
normalizedScore < RANK_DOUBLE_A_VALUE
) {
level = "S";
}
if (
normalizedScore >= RANK_DOUBLE_A_VALUE &&
normalizedScore < RANK_A2_VALUE
) {
level = "A++";
}
if (normalizedScore >= RANK_A2_VALUE && normalizedScore < RANK_A3_VALUE) {
level = "A+";
}
if (normalizedScore >= RANK_A3_VALUE && normalizedScore < RANK_B_VALUE) {
level = "B+";
}
return { level, score: normalizedScore };
}
module.exports = calculateRank;
+18 -11
View File
@@ -1,12 +1,10 @@
const { request } = require("./utils");
const retryer = require("./retryer");
async function fetchRepo(username, reponame) {
if (!username || !reponame) {
throw new Error("Invalid username or reponame");
}
const res = await request({
query: `
const fetcher = (variables, token) => {
return request(
{
query: `
fragment RepoInfo on Repository {
name
stargazers {
@@ -33,11 +31,20 @@ async function fetchRepo(username, reponame) {
}
}
`,
variables: {
login: username,
repo: reponame,
variables,
},
});
{
Authorization: `bearer ${token}`,
}
);
};
async function fetchRepo(username, reponame) {
if (!username || !reponame) {
throw new Error("Invalid username or reponame");
}
let res = await retryer(fetcher, { login: username, repo: reponame });
const data = res.data.data;
+41 -15
View File
@@ -1,28 +1,33 @@
const { request } = require("./utils");
const retryer = require("./retryer");
const calculateRank = require("./calculateRank");
require("dotenv").config();
async function fetchStats(username) {
if (!username) throw Error("Invalid username");
const res = await request({
query: `
const fetcher = (variables, token) => {
return request(
{
query: `
query userInfo($login: String!) {
user(login: $login) {
name
login
repositoriesContributedTo(first: 100, contributionTypes: [COMMIT, ISSUE, PULL_REQUEST, REPOSITORY]) {
totalCount
}
contributionsCollection {
totalCommitContributions
}
pullRequests(first: 100) {
repositoriesContributedTo(first: 1, contributionTypes: [COMMIT, ISSUE, PULL_REQUEST, REPOSITORY]) {
totalCount
}
issues(first: 100) {
pullRequests(first: 1) {
totalCount
}
repositories(first: 100, orderBy: { direction: DESC, field: STARGAZERS }) {
issues(first: 1) {
totalCount
}
followers {
totalCount
}
repositories(first: 100, ownerAffiliations: OWNER, isFork: false, orderBy: {direction: DESC, field: STARGAZERS}) {
totalCount
nodes {
stargazers {
totalCount
@@ -31,9 +36,17 @@ async function fetchStats(username) {
}
}
}
`,
variables: { login: username },
});
`,
variables,
},
{
Authorization: `bearer ${token}`,
}
);
};
async function fetchStats(username) {
if (!username) throw Error("Invalid username");
const stats = {
name: "",
@@ -42,11 +55,14 @@ async function fetchStats(username) {
totalIssues: 0,
totalStars: 0,
contributedTo: 0,
rank: { level: "C", score: 0 },
};
let res = await retryer(fetcher, { login: username });
if (res.data.errors) {
console.log(res.data.errors);
throw Error("Could not fetch user");
throw Error(res.data.errors[0].message || "Could not fetch user");
}
const user = res.data.data.user;
@@ -61,6 +77,16 @@ async function fetchStats(username) {
return prev + curr.stargazers.totalCount;
}, 0);
stats.rank = calculateRank({
totalCommits: stats.totalCommits,
totalRepos: user.repositories.totalCount,
followers: user.followers.totalCount,
contributions: stats.contributedTo,
stargazers: stats.totalStars,
prs: stats.totalPRs,
issues: stats.totalIssues,
});
return stats;
}
+97
View File
@@ -0,0 +1,97 @@
const calculateCircleProgress = (value) => {
let radius = 40;
let c = Math.PI * (radius * 2);
if (value < 0) value = 0;
if (value > 100) value = 100;
let percentage = ((100 - value) / 100) * c;
return percentage;
};
const getAnimations = ({ progress }) => {
return `
/* Animations */
@keyframes scaleIn {
from {
transform: translate(-5px, 5px) scale(0);
}
to {
transform: translate(-5px, 5px) scale(1);
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes rankAnimation {
from {
stroke-dashoffset: ${calculateCircleProgress(0)};
}
to {
stroke-dashoffset: ${calculateCircleProgress(progress)};
}
}
`;
};
const getStyles = ({
titleColor,
textColor,
iconColor,
show_icons,
progress,
}) => {
return `
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor};
animation: fadeIn 0.8s ease-in-out forwards;
}
.stat {
font: 600 14px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor};
}
.stagger {
opacity: 0;
animation: fadeIn 0.3s ease-in-out forwards;
}
.rank-text {
font: 800 24px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor};
animation: scaleIn 0.3s ease-in-out forwards;
}
.bold { font-weight: 700 }
.star-icon {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
}
.icon {
fill: ${iconColor};
display: ${!!show_icons ? "block" : "none"};
}
.rank-circle-rim {
stroke: ${titleColor};
fill: none;
stroke-width: 6;
opacity: 0.2;
}
.rank-circle {
stroke: ${titleColor};
stroke-dasharray: 250;
fill: none;
stroke-width: 6;
stroke-linecap: round;
opacity: 0.8;
transform-origin: -10px 8px;
transform: rotate(-90deg);
animation: rankAnimation 1s forwards ease-in-out;
}
${process.env.NODE_ENV === "test" ? "" : getAnimations({ progress })}
`;
};
module.exports = getStyles;
+11 -14
View File
@@ -1,23 +1,24 @@
const { kFormatter, encodeHTML, isValidHexColor } = require("../src/utils");
const { kFormatter, encodeHTML, fallbackColor } = require("../src/utils");
const renderRepoCard = (repo, options = {}) => {
const { name, description, primaryLanguage, stargazers, forkCount } = repo;
const { title_color, icon_color, text_color, bg_color } = options;
const langName = primaryLanguage ? primaryLanguage.name : "Unspecified";
const langColor = primaryLanguage ? primaryLanguage.color : "#333";
const height = 120;
const shiftText = primaryLanguage.name.length > 15 ? 0 : 30;
const shiftText = langName.length > 15 ? 0 : 30;
let desc = description || "No description provided";
if (desc.length > 55) {
desc = `${description.slice(0, 55)}..`;
}
const titleColor =
(isValidHexColor(title_color) && `#${title_color}`) || "#2f80ed";
const iconColor =
(isValidHexColor(icon_color) && `#${icon_color}`) || "#586069";
const textColor = (isValidHexColor(text_color) && `#${text_color}`) || "#333";
const bgColor = (isValidHexColor(bg_color) && `#${bg_color}`) || "#FFFEFE";
const titleColor = fallbackColor(title_color, "#2f80ed");
const iconColor = fallbackColor(icon_color, "#586069");
const textColor = fallbackColor(text_color, "#333");
const bgColor = fallbackColor(bg_color, "#FFFEFE");
const totalStars = kFormatter(stargazers.totalCount);
const totalForks = kFormatter(forkCount);
@@ -38,12 +39,8 @@ const renderRepoCard = (repo, options = {}) => {
<text class="description" x="25" y="70">${encodeHTML(desc)}</text>
<g transform="translate(30, 100)">
<circle data-testid="lang-color" cx="0" cy="-5" r="6" fill="${
primaryLanguage.color
}" />
<text data-testid="lang" class="gray" x="15">${
primaryLanguage.name
}</text>
<circle data-testid="lang-color" cx="0" cy="-5" r="6" fill="${langColor}" />
<text data-testid="lang" class="gray" x="15">${langName}</text>
</g>
<g transform="translate(${155 - shiftText}, 100)">
+94 -42
View File
@@ -1,12 +1,21 @@
const { kFormatter, isValidHexColor } = require("../src/utils");
const { kFormatter, fallbackColor } = require("../src/utils");
const getStyles = require("./getStyles");
const createTextNode = ({ icon, label, value, lineHeight, id }) => {
const createTextNode = ({ icon, label, value, id, index, lineHeight }) => {
const classname = icon === "★" && "star-icon";
const kValue = kFormatter(value);
const staggerDelay = (index + 3) * 150;
// manually calculating lineHeight based on index instead of using <tspan dy="" />
// to fix firefox layout bug
const lheight = lineHeight * (index + 1);
return `
<tspan x="25" dy="${lineHeight}" class="stat bold">
<tspan data-testid="icon" class="icon ${classname}">${icon}</tspan> ${label}:</tspan>
<tspan data-testid="${id}" x="155" dy="0" class="stat">${kValue}</tspan>
<text class="stagger" style="animation-delay: ${staggerDelay}ms" x="25" y="${lheight}">
<tspan dx="0" data-testid="icon" class="icon ${classname}">${icon}</tspan>
<tspan dx="0" class="stat bold">
${label}:
</tspan>
<tspan x="160" data-testid="${id}" class="stat">${kValue}</tspan>
</text>
`;
};
@@ -18,11 +27,13 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
totalIssues,
totalPRs,
contributedTo,
rank,
} = stats;
const {
hide = [],
show_icons = false,
hide_border = false,
hide_rank = false,
line_height = 25,
title_color,
icon_color,
@@ -32,76 +43,117 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
const lheight = parseInt(line_height);
const titleColor =
(isValidHexColor(title_color) && `#${title_color}`) || "#2f80ed";
const iconColor =
(isValidHexColor(icon_color) && `#${icon_color}`) || "#4c71f2";
const textColor = (isValidHexColor(text_color) && `#${text_color}`) || "#333";
const bgColor = (isValidHexColor(bg_color) && `#${bg_color}`) || "#FFFEFE";
const titleColor = fallbackColor(title_color, "#2f80ed");
const iconColor = fallbackColor(icon_color, "#4c71f2");
const textColor = fallbackColor(text_color, "#333");
const bgColor = fallbackColor(bg_color, "#FFFEFE");
const STAT_MAP = {
stars: createTextNode({
const STATS = {
stars: {
icon: "★",
label: "Total Stars",
value: totalStars,
lineHeight: lheight,
id: "stars",
}),
commits: createTextNode({
},
commits: {
icon: "🕗",
label: "Total Commits",
value: totalCommits,
lineHeight: lheight,
id: "commits",
}),
prs: createTextNode({
},
prs: {
icon: "🔀",
label: "Total PRs",
value: totalPRs,
lineHeight: lheight,
id: "prs",
}),
issues: createTextNode({
},
issues: {
icon: "ⓘ",
label: "Total Issues",
value: totalIssues,
lineHeight: lheight,
id: "issues",
}),
contribs: createTextNode({
},
contribs: {
icon: "📕",
label: "Contributed to",
value: contributedTo,
lineHeight: lheight,
id: "contribs",
}),
},
};
const statItems = Object.keys(STAT_MAP)
const statItems = Object.keys(STATS)
.filter((key) => !hide.includes(key))
.map((key) => STAT_MAP[key]);
.map((key, index) =>
// create the text nodes, and pass index so that we can calculate the line spacing
createTextNode({ ...STATS[key], index, lineHeight: lheight })
);
const height = 45 + (statItems.length + 1) * lheight;
// Calculate the card height depending on how many items there are
// but if rank circle is visible clamp the minimum height to `150`
const height = Math.max(
45 + (statItems.length + 1) * lheight,
hide_rank ? 0 : 150
);
const border = `
<rect
data-testid="card-border"
x="0.5"
y="0.5"
width="494"
height="99%"
rx="4.5"
fill="${bgColor}"
stroke="#E4E2E2"
/>
`;
const rankCircle = hide_rank
? ""
: `<g data-testid="rank-circle" transform="translate(400, ${
height / 1.85
})">
<circle class="rank-circle-rim" cx="-10" cy="8" r="40" />
<circle class="rank-circle" cx="-10" cy="8" r="40" />
<text
x="${rank.level.length === 1 ? "-4" : "0"}"
y="0"
alignment-baseline="central"
dominant-baseline="central"
text-anchor="middle"
class="rank-text"
>
${rank.level}
</text>
</g>`;
// the better user's score the the rank will be closer to zero so
// subtracting 100 to get the progress in 100%
let progress = 100 - rank.score;
const styles = getStyles({
titleColor,
textColor,
iconColor,
show_icons,
progress,
});
const border = `<rect data-testid="card-border" x="0.5" y="0.5" width="494" height="99%" rx="4.5" fill="${bgColor}" stroke="#E4E2E2"/>`;
return `
<svg width="495" height="${height}" viewBox="0 0 495 ${height}" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
.header { font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor}; }
.stat { font: 600 14px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor}; }
.star-icon { font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif; }
.bold { font-weight: 700 }
.icon {
fill: ${iconColor};
display: ${!!show_icons ? "block" : "none"};
}
${styles}
</style>
${hide_border ? "" : border}
${rankCircle}
<text x="25" y="35" class="header">${name}'s GitHub Stats</text>
<text y="45">
<svg x="0" y="45">
${statItems.toString().replace(/\,/gm, "")}
</text>
</svg>
</svg>
`;
};
+43
View File
@@ -0,0 +1,43 @@
const retryer = async (fetcher, variables, retries = 0) => {
if (retries > 7) {
throw new Error("Maximum retries exceeded");
}
try {
console.log(`Trying PAT_${retries + 1}`);
// try to fetch with the first token since RETRIES is 0 index i'm adding +1
let response = await fetcher(
variables,
process.env[`PAT_${retries + 1}`],
retries
);
// prettier-ignore
const isRateExceeded = response.data.errors && response.data.errors[0].type === "RATE_LIMITED";
// if rate limit is hit increase the RETRIES and recursively call the retryer
// with username, and current RETRIES
if (isRateExceeded) {
console.log(`PAT_${retries + 1} Failed`);
retries++;
// directly return from the function
return retryer(fetcher, variables, retries);
}
// finally return the response
return response;
} catch (err) {
// prettier-ignore
// also checking for bad credentials if any tokens gets invalidated
const isBadCredential = err.response.data && err.response.data.message === "Bad credentials";
if (isBadCredential) {
console.log(`PAT_${retries + 1} Failed`);
retries++;
// directly return from the function
return retryer(fetcher, variables, retries);
}
}
};
module.exports = retryer;
+29 -13
View File
@@ -33,19 +33,35 @@ function isValidHexColor(hexColor) {
).test(hexColor);
}
function request(data) {
return new Promise((resolve, reject) => {
axios({
url: "https://api.github.com/graphql",
method: "post",
headers: {
Authorization: `bearer ${process.env.GITHUB_TOKEN}`,
},
data,
})
.then((response) => resolve(response))
.catch((error) => reject(error));
function parseBoolean(value) {
if (value === "true") {
return true;
} else if (value === "false") {
return false;
} else {
return value;
}
}
function fallbackColor(color, fallbackColor) {
return (isValidHexColor(color) && `#${color}`) || fallbackColor;
}
function request(data, headers) {
return axios({
url: "https://api.github.com/graphql",
method: "post",
headers,
data,
});
}
module.exports = { renderError, kFormatter, encodeHTML, isValidHexColor, request };
module.exports = {
renderError,
kFormatter,
encodeHTML,
isValidHexColor,
request,
parseBoolean,
fallbackColor,
};
+13
View File
@@ -4,6 +4,7 @@ const MockAdapter = require("axios-mock-adapter");
const api = require("../api/index");
const renderStatsCard = require("../src/renderStatsCard");
const { renderError } = require("../src/utils");
const calculateRank = require("../src/calculateRank");
const stats = {
name: "Anurag Hazra",
@@ -12,7 +13,17 @@ const stats = {
totalIssues: 300,
totalPRs: 400,
contributedTo: 500,
rank: null,
};
stats.rank = calculateRank({
totalCommits: stats.totalCommits,
totalRepos: 1,
followers: 0,
contributions: stats.contributedTo,
stargazers: stats.totalStars,
prs: stats.totalPRs,
issues: stats.totalIssues,
});
const data = {
data: {
@@ -22,7 +33,9 @@ const data = {
contributionsCollection: { totalCommitContributions: stats.totalCommits },
pullRequests: { totalCount: stats.totalPRs },
issues: { totalCount: stats.totalIssues },
followers: { totalCount: 0 },
repositories: {
totalCount: 1,
nodes: [{ stargazers: { totalCount: 100 } }],
},
},
+18
View File
@@ -0,0 +1,18 @@
require("@testing-library/jest-dom");
const calculateRank = require("../src/calculateRank");
describe("Test calculateRank", () => {
it("should calculate rank correctly", () => {
expect(
calculateRank({
totalCommits: 100,
totalRepos: 5,
followers: 100,
contributions: 61,
stargazers: 400,
prs: 300,
issues: 200,
})
).toStrictEqual({ level: "A+", score: 49.16605417270399 });
});
});
+16 -2
View File
@@ -2,6 +2,7 @@ require("@testing-library/jest-dom");
const axios = require("axios");
const MockAdapter = require("axios-mock-adapter");
const fetchStats = require("../src/fetchStats");
const calculateRank = require("../src/calculateRank");
const data = {
data: {
@@ -11,7 +12,9 @@ const data = {
contributionsCollection: { totalCommitContributions: 100 },
pullRequests: { totalCount: 300 },
issues: { totalCount: 200 },
followers: { totalCount: 100 },
repositories: {
totalCount: 5,
nodes: [
{ stargazers: { totalCount: 100 } },
{ stargazers: { totalCount: 100 } },
@@ -46,6 +49,16 @@ describe("Test fetchStats", () => {
mock.onPost("https://api.github.com/graphql").reply(200, data);
let stats = await fetchStats("anuraghazra");
const rank = calculateRank({
totalCommits: 100,
totalRepos: 5,
followers: 100,
contributions: 61,
stargazers: 400,
prs: 300,
issues: 200,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
@@ -53,6 +66,7 @@ describe("Test fetchStats", () => {
totalIssues: 200,
totalPRs: 300,
totalStars: 400,
rank,
});
});
@@ -60,7 +74,7 @@ describe("Test fetchStats", () => {
mock.onPost("https://api.github.com/graphql").reply(200, error);
await expect(fetchStats("anuraghazra")).rejects.toThrow(
"Could not fetch user"
"Could not resolve to a User with the login of 'noname'."
);
});
});
});
+12 -2
View File
@@ -12,6 +12,7 @@ describe("Test renderStatsCard", () => {
totalIssues: 300,
totalPRs: 400,
contributedTo: 500,
rank: { level: "A+", score: 40 },
};
it("should render correctly", () => {
@@ -30,6 +31,7 @@ describe("Test renderStatsCard", () => {
expect(getByTestId(document.body, "prs").textContent).toBe("400");
expect(getByTestId(document.body, "contribs").textContent).toBe("500");
expect(queryByTestId(document.body, "card-border")).toBeInTheDocument();
expect(queryByTestId(document.body, "rank-circle")).toBeInTheDocument();
});
it("should hide individual stats", () => {
@@ -39,7 +41,8 @@ describe("Test renderStatsCard", () => {
expect(
document.body.getElementsByTagName("svg")[0].getAttribute("height")
).toBe("120");
).toBe("150"); // height should be 150 because we clamped it.
expect(queryByTestId(document.body, "stars")).toBeDefined();
expect(queryByTestId(document.body, "commits")).toBeDefined();
expect(queryByTestId(document.body, "issues")).toBeNull();
@@ -53,11 +56,18 @@ describe("Test renderStatsCard", () => {
expect(queryByTestId(document.body, "card-border")).not.toBeInTheDocument();
});
it("should hide_rank", () => {
document.body.innerHTML = renderStatsCard(stats, { hide_rank: true });
expect(queryByTestId(document.body, "rank-circle")).not.toBeInTheDocument();
});
it("should render default colors properly", () => {
document.body.innerHTML = renderStatsCard(stats);
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
console.log(styleTag.textContent);
const stylesObject = cssToObject(styleTag.textContent);
const headerClassStyles = stylesObject[".header"];
const statClassStyles = stylesObject[".stat"];
+50
View File
@@ -0,0 +1,50 @@
require("@testing-library/jest-dom");
const retryer = require("../src/retryer");
const fetcher = jest.fn((variables, token) => {
console.log(variables, token);
return new Promise((res, rej) => res({ data: "ok" }));
});
const fetcherFail = jest.fn(() => {
return new Promise((res, rej) =>
res({ data: { errors: [{ type: "RATE_LIMITED" }] } })
);
});
const fetcherFailOnSecondTry = jest.fn((_vars, _token, retries) => {
return new Promise((res, rej) => {
// faking rate limit
if (retries < 1) {
return res({ data: { errors: [{ type: "RATE_LIMITED" }] } });
}
return res({ data: "ok" });
});
});
describe("Test Retryer", () => {
it("retryer should return value and have zero retries on first try", async () => {
let res = await retryer(fetcher, {});
expect(fetcher).toBeCalledTimes(1);
expect(res).toStrictEqual({ data: "ok" });
});
it("retryer should return value and have 2 retries", async () => {
let res = await retryer(fetcherFailOnSecondTry, {});
expect(fetcherFailOnSecondTry).toBeCalledTimes(2);
expect(res).toStrictEqual({ data: "ok" });
});
it("retryer should throw error if maximum retries reached", async () => {
let res;
try {
res = await retryer(fetcherFail, {});
} catch (err) {
expect(fetcherFail).toBeCalledTimes(8);
expect(err.message).toBe("Maximum retries exceeded");
}
});
});