Compare commits

..
Author SHA1 Message Date
rickstaa 533fe040a6 test: add missing utils tests 2022-10-15 12:03:30 +02:00
61 changed files with 579 additions and 2123 deletions
-2
View File
@@ -11,8 +11,6 @@ body:
attributes: attributes:
label: Describe the bug label: Describe the bug
description: A clear and concise description of what the bug is. description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea - type: textarea
attributes: attributes:
label: Expected behaviour label: Expected behaviour
@@ -9,8 +9,6 @@ body:
description: description:
A clear and concise description of what the problem is. Ex. I'm always A clear and concise description of what the problem is. Ex. I'm always
frustrated when [...] frustrated when [...]
validations:
required: true
- type: textarea - type: textarea
attributes: attributes:
label: Describe the solution you'd like label: Describe the solution you'd like
-1
View File
@@ -1,4 +1,3 @@
themes: themes/index.js themes: themes/index.js
doc-translation: docs/* doc-translation: docs/*
card-i18n: src/translations.js card-i18n: src/translations.js
documentation: readme.md
-10
View File
@@ -1,10 +0,0 @@
import os
file = open('./vercel.json', 'r')
str = file.read()
file = open('./vercel.json', 'w')
str = str.replace('"maxDuration": 10', '"maxDuration": 30')
file.write(str)
file.close()
-20
View File
@@ -1,20 +0,0 @@
name: Deployment Prep
on:
workflow_dispatch:
push:
branches:
- master
jobs:
config:
if: github.repository == 'anuraghazra/github-readme-stats'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deployment Prep
run: python ./.github/workflows/deploy-prep.py
- uses: stefanzweifel/git-auto-commit-action@v4
with:
branch: vercel
create_branch: true
push_options: "--force"
-1
View File
@@ -5,7 +5,6 @@ on:
jobs: jobs:
e2eTests: e2eTests:
if: if:
github.repository == 'anuraghazra/github-readme-stats' &&
github.event_name == 'deployment_status' && github.event_name == 'deployment_status' &&
github.event.deployment_status.state == 'success' github.event.deployment_status.state == 'success'
name: Perform 2e2 tests name: Perform 2e2 tests
@@ -8,7 +8,6 @@ on:
jobs: jobs:
closeEmptyIssuesAndTemplates: closeEmptyIssuesAndTemplates:
if: github.repository == 'anuraghazra/github-readme-stats'
name: Close empty issues name: Close empty issues
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
-4
View File
@@ -23,10 +23,6 @@ jobs:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
cache: npm cache: npm
# Fix the unsafe repo error which was introduced by the CVE-2022-24765 git patches.
- name: Fix unsafe repo error
run: git config --global --add safe.directory ${{ github.workspace }}
- name: npm install, generate readme - name: npm install, generate readme
run: | run: |
npm ci npm ci
-1
View File
@@ -4,7 +4,6 @@ on:
jobs: jobs:
triage: triage:
if: github.repository == 'anuraghazra/github-readme-stats'
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/labeler@v4 - uses: actions/labeler@v4
+1 -2
View File
@@ -5,7 +5,6 @@ on:
jobs: jobs:
closeOldThemePrs: closeOldThemePrs:
if: github.repository == 'anuraghazra/github-readme-stats'
name: Close stale 'invalid' theme PRs name: Close stale 'invalid' theme PRs
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
@@ -27,5 +26,5 @@ jobs:
- run: npm run close-stale-theme-prs - run: npm run close-stale-theme-prs
env: env:
STALE_DAYS: 20 STALE_DAYS: 15
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -5,7 +5,6 @@ on:
jobs: jobs:
showAndLabelTopIssues: showAndLabelTopIssues:
if: github.repository == 'anuraghazra/github-readme-stats'
name: Update top issues Dashboard. name: Update top issues Dashboard.
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
-44
View File
@@ -1,44 +0,0 @@
name: Update supported languages
on:
schedule:
- cron: "0 0 */30 * *"
jobs:
updateLanguages:
if: github.repository == 'anuraghazra/github-readme-stats'
name: Update supported languages
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: npm
- name: Install dependencies
run: npm ci
env:
CI: true
- name: Run update-languages-json.js script
run: npm run generate-langs-json
- name: Create Pull Request if upstream language file is changed
uses: peter-evans/create-pull-request@v4
with:
commit-message: "refactor: update languages JSON"
branch: "update_langs/patch"
delete-branch: true
title: Update languages JSON
body:
"The
[update-langs](https://github.com/anuraghazra/github-readme-stats/actions/workflows/update-langs.yaml)
action found new/updated languages in the [upstream languages JSON
file](https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml)."
labels: "ci, lang-card"
-2
View File
@@ -10,5 +10,3 @@ vercel_token
# IDE # IDE
.vscode .vscode
*.code-workspace *.code-workspace
.vercel
+1 -5
View File
@@ -47,11 +47,7 @@ All you need to do is edit the [themes/index.js](./themes/index.js) file and add
While creating the Pull request to add a new theme **don't forget to add a screenshot of how your theme looks**, you can also test how it looks using custom URL parameters like `title_color`, `icon_color`, `bg_color`, `text_color`, `border_color` While creating the Pull request to add a new theme **don't forget to add a screenshot of how your theme looks**, you can also test how it looks using custom URL parameters like `title_color`, `icon_color`, `bg_color`, `text_color`, `border_color`
> **Note** > NOTE: If you are contributing your theme just because you are using it personally, then you can [customize the looks](./readme.md#customization) of your card with URL params instead.
> If you are contributing your theme just because you are using it personally, then you can [customize the looks](./readme.md#customization) of your card with URL params instead.
> **Note**
> If your theme name contains multiple words (ie, hyphenated or underscor-ed theme names), please add two versions of theme: one with hyphens and one with underscores. This is to ensure backward-compatability with when we had hyphens for some themes and underscores for others.
## Any contributions you make will be under the MIT Software License ## Any contributions you make will be under the MIT Software License
+5 -9
View File
@@ -1,3 +1,4 @@
import * as dotenv from "dotenv";
import { renderStatsCard } from "../src/cards/stats-card.js"; import { renderStatsCard } from "../src/cards/stats-card.js";
import { blacklist } from "../src/common/blacklist.js"; import { blacklist } from "../src/common/blacklist.js";
import { import {
@@ -10,6 +11,8 @@ import {
import { fetchStats } from "../src/fetchers/stats-fetcher.js"; import { fetchStats } from "../src/fetchers/stats-fetcher.js";
import { isLocaleAvailable } from "../src/translations.js"; import { isLocaleAvailable } from "../src/translations.js";
dotenv.config();
export default async (req, res) => { export default async (req, res) => {
const { const {
username, username,
@@ -23,7 +26,6 @@ export default async (req, res) => {
include_all_commits, include_all_commits,
line_height, line_height,
title_color, title_color,
ring_color,
icon_color, icon_color,
text_color, text_color,
text_bold, text_bold,
@@ -61,12 +63,7 @@ export default async (req, res) => {
CONSTANTS.ONE_DAY, CONSTANTS.ONE_DAY,
); );
res.setHeader( res.setHeader("Cache-Control", `public, max-age=${cacheSeconds}`);
"Cache-Control",
`max-age=${
cacheSeconds / 2
}, s-maxage=${cacheSeconds}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
);
return res.send( return res.send(
renderStatsCard(stats, { renderStatsCard(stats, {
@@ -79,7 +76,6 @@ export default async (req, res) => {
include_all_commits: parseBoolean(include_all_commits), include_all_commits: parseBoolean(include_all_commits),
line_height, line_height,
title_color, title_color,
ring_color,
icon_color, icon_color,
text_color, text_color,
text_bold: parseBoolean(text_bold), text_bold: parseBoolean(text_bold),
@@ -93,7 +89,7 @@ export default async (req, res) => {
}), }),
); );
} catch (err) { } catch (err) {
res.setHeader("Cache-Control", `no-cache, no-store, must-revalidate`); // Don't cache error responses. res.setHeader("Cache-Control", `no-store`); // Don't cache error responses.
return res.send(renderError(err.message, err.secondaryMessage)); return res.send(renderError(err.message, err.secondaryMessage));
} }
}; };
+2 -7
View File
@@ -58,12 +58,7 @@ export default async (req, res) => {
cacheSeconds = CONSTANTS.FOUR_HOURS; cacheSeconds = CONSTANTS.FOUR_HOURS;
} }
res.setHeader( res.setHeader("Cache-Control", `public, max-age=${cacheSeconds}`);
"Cache-Control",
`max-age=${
cacheSeconds / 2
}, s-maxage=${cacheSeconds}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
);
return res.send( return res.send(
renderRepoCard(repoData, { renderRepoCard(repoData, {
@@ -80,7 +75,7 @@ export default async (req, res) => {
}), }),
); );
} catch (err) { } catch (err) {
res.setHeader("Cache-Control", `no-cache, no-store, must-revalidate`); // Don't cache error responses. res.setHeader("Cache-Control", `no-store`); // Don't cache error responses.
return res.send(renderError(err.message, err.secondaryMessage)); return res.send(renderError(err.message, err.secondaryMessage));
} }
}; };
-139
View File
@@ -1,139 +0,0 @@
/**
* @file Contains a simple cloud function that can be used to check which PATs are no
* longer working. It returns a list of valid PATs, expired PATs and PATs with errors.
*
* @description This function is currently rate limited to 1 request per 10 minutes.
*/
import { logger, request, dateDiff } from "../../src/common/utils.js";
export const RATE_LIMIT_SECONDS = 60 * 5; // 1 request per 10 minutes
/**
* Simple uptime check fetcher for the PATs.
*
* @param {import('axios').AxiosRequestHeaders} variables
* @param {string} token
*/
const uptimeFetcher = (variables, token) => {
return request(
{
query: `
query {
rateLimit {
remaining
resetAt
},
}`,
variables,
},
{
Authorization: `bearer ${token}`,
},
);
};
const getAllPATs = () => {
return Object.keys(process.env).filter((key) => /PAT_\d*$/.exec(key));
};
/**
* Check whether any of the PATs is expired.
*/
const getPATInfo = async (fetcher, variables) => {
const details = {};
const PATs = getAllPATs();
for (const pat of PATs) {
try {
const response = await fetcher(variables, process.env[pat]);
const errors = response.data.errors;
const hasErrors = Boolean(errors);
const errorType = errors?.[0]?.type;
const isRateLimited =
(hasErrors && errorType === "RATE_LIMITED") ||
response.data.data?.rateLimit?.remaining === 0;
// Store PATs with errors.
if (hasErrors && errorType !== "RATE_LIMITED") {
details[pat] = {
status: "error",
error: {
type: errors[0].type,
message: errors[0].message,
},
};
continue;
} else if (isRateLimited) {
const date1 = new Date();
const date2 = new Date(response.data?.data?.rateLimit?.resetAt);
details[pat] = {
status: "exhausted",
remaining: 0,
resetIn: dateDiff(date2, date1) + " minutes",
};
} else {
details[pat] = {
status: "valid",
remaining: response.data.data.rateLimit.remaining,
};
}
} catch (err) {
// Store the PAT if it is expired.
const errorMessage = err.response?.data?.message?.toLowerCase();
if (errorMessage === "bad credentials") {
details[pat] = {
status: "expired",
};
} else if (errorMessage === "sorry. your account was suspended.") {
details[pat] = {
status: "suspended",
};
} else {
throw err;
}
}
}
const filterPATsByStatus = (status) => {
return Object.keys(details).filter((pat) => details[pat].status === status);
};
const sortedDetails = Object.keys(details)
.sort()
.reduce((obj, key) => {
obj[key] = details[key];
return obj;
}, {});
return {
validPATs: filterPATsByStatus("valid"),
expiredPATs: filterPATsByStatus("expired"),
exhaustedPATs: filterPATsByStatus("exhausted"),
suspendedPATs: filterPATsByStatus("suspended"),
errorPATs: filterPATsByStatus("error"),
details: sortedDetails,
};
};
/**
* Cloud function that returns information about the used PATs.
*/
export default async (_, res) => {
res.setHeader("Content-Type", "application/json");
try {
// Add header to prevent abuse.
const PATsInfo = await getPATInfo(uptimeFetcher, {});
if (PATsInfo) {
res.setHeader(
"Cache-Control",
`max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`,
);
}
res.send(JSON.stringify(PATsInfo, null, 2));
} catch (err) {
// Throw error if something went wrong.
logger.error(err);
res.setHeader("Cache-Control", "no-store");
res.send("Something went wrong: " + err.message);
}
};
-103
View File
@@ -1,103 +0,0 @@
/**
* @file Contains a simple cloud function that can be used to check if the PATs are still
* functional.
*
* @description This function is currently rate limited to 1 request per 10 minutes.
*/
import retryer from "../../src/common/retryer.js";
import { logger, request } from "../../src/common/utils.js";
export const RATE_LIMIT_SECONDS = 60 * 10; // 1 request per 10 minutes
/**
* Simple uptime check fetcher for the PATs.
*
* @param {import('axios').AxiosRequestHeaders} variables
* @param {string} token
*/
const uptimeFetcher = (variables, token) => {
return request(
{
query: `
query {
rateLimit {
remaining
}
}
`,
variables,
},
{
Authorization: `bearer ${token}`,
},
);
};
/**
* Creates Json response that can be used for shields.io dynamic card generation.
*
* @param {*} up Whether the PATs are up or not.
* @returns Dynamic shields.io JSON response object.
*
* @see https://shields.io/endpoint.
*/
const shieldsUptimeBadge = (up) => {
const schemaVersion = 1;
const isError = true;
const label = "Public Instance";
const message = up ? "up" : "down";
const color = up ? "brightgreen" : "red";
return {
schemaVersion,
label,
message,
color,
isError,
};
};
/**
* Cloud function that returns whether the PATs are still functional.
*/
export default async (req, res) => {
let { type } = req.query;
type = type ? type.toLowerCase() : "boolean";
res.setHeader("Content-Type", "application/json");
try {
let PATsValid = true;
try {
await retryer(uptimeFetcher, {});
} catch (err) {
PATsValid = false;
}
if (PATsValid) {
res.setHeader(
"Cache-Control",
`max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`,
);
} else {
res.setHeader("Cache-Control", "no-store");
}
switch (type) {
case "shields":
res.send(shieldsUptimeBadge(PATsValid));
break;
case "json":
res.send({ up: PATsValid });
break;
default:
res.send(PATsValid);
break;
}
} catch (err) {
// Return fail boolean if something went wrong.
logger.error(err);
res.setHeader("Cache-Control", "no-store");
res.send("Something went wrong: " + err.message);
}
};
+5 -11
View File
@@ -1,3 +1,4 @@
import * as dotenv from "dotenv";
import { renderTopLanguages } from "../src/cards/top-languages-card.js"; import { renderTopLanguages } from "../src/cards/top-languages-card.js";
import { blacklist } from "../src/common/blacklist.js"; import { blacklist } from "../src/common/blacklist.js";
import { import {
@@ -10,6 +11,8 @@ import {
import { fetchTopLanguages } from "../src/fetchers/top-languages-fetcher.js"; import { fetchTopLanguages } from "../src/fetchers/top-languages-fetcher.js";
import { isLocaleAvailable } from "../src/translations.js"; import { isLocaleAvailable } from "../src/translations.js";
dotenv.config();
export default async (req, res) => { export default async (req, res) => {
const { const {
username, username,
@@ -29,8 +32,6 @@ export default async (req, res) => {
locale, locale,
border_radius, border_radius,
border_color, border_color,
disable_animations,
hide_progress,
} = req.query; } = req.query;
res.setHeader("Content-Type", "image/svg+xml"); res.setHeader("Content-Type", "image/svg+xml");
@@ -54,12 +55,7 @@ export default async (req, res) => {
CONSTANTS.ONE_DAY, CONSTANTS.ONE_DAY,
); );
res.setHeader( res.setHeader("Cache-Control", `public, max-age=${cacheSeconds}`);
"Cache-Control",
`max-age=${
cacheSeconds / 2
}, s-maxage=${cacheSeconds}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
);
return res.send( return res.send(
renderTopLanguages(topLangs, { renderTopLanguages(topLangs, {
@@ -77,12 +73,10 @@ export default async (req, res) => {
border_radius, border_radius,
border_color, border_color,
locale: locale ? locale.toLowerCase() : null, locale: locale ? locale.toLowerCase() : null,
disable_animations: parseBoolean(disable_animations),
hide_progress: parseBoolean(hide_progress),
}), }),
); );
} catch (err) { } catch (err) {
res.setHeader("Cache-Control", `no-cache, no-store, must-revalidate`); // Don't cache error responses. res.setHeader("Cache-Control", `no-store`); // Don't cache error responses.
return res.send(renderError(err.message, err.secondaryMessage)); return res.send(renderError(err.message, err.secondaryMessage));
} }
}; };
+5 -7
View File
@@ -1,3 +1,4 @@
import * as dotenv from "dotenv";
import { renderWakatimeCard } from "../src/cards/wakatime-card.js"; import { renderWakatimeCard } from "../src/cards/wakatime-card.js";
import { import {
clampValue, clampValue,
@@ -9,6 +10,8 @@ import {
import { fetchWakatimeStats } from "../src/fetchers/wakatime-fetcher.js"; import { fetchWakatimeStats } from "../src/fetchers/wakatime-fetcher.js";
import { isLocaleAvailable } from "../src/translations.js"; import { isLocaleAvailable } from "../src/translations.js";
dotenv.config();
export default async (req, res) => { export default async (req, res) => {
const { const {
username, username,
@@ -52,12 +55,7 @@ export default async (req, res) => {
cacheSeconds = CONSTANTS.FOUR_HOURS; cacheSeconds = CONSTANTS.FOUR_HOURS;
} }
res.setHeader( res.setHeader("Cache-Control", `public, max-age=${cacheSeconds}`);
"Cache-Control",
`max-age=${
cacheSeconds / 2
}, s-maxage=${cacheSeconds}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
);
return res.send( return res.send(
renderWakatimeCard(stats, { renderWakatimeCard(stats, {
@@ -80,7 +78,7 @@ export default async (req, res) => {
}), }),
); );
} catch (err) { } catch (err) {
res.setHeader("Cache-Control", `no-cache, no-store, must-revalidate`); // Don't cache error responses. res.setHeader("Cache-Control", `no-store`); // Don't cache error responses.
return res.send(renderError(err.message, err.secondaryMessage)); return res.send(renderError(err.message, err.secondaryMessage));
} }
}; };
+3 -3
View File
@@ -1,7 +1,7 @@
<p align="center"> <p align="center">
<img width="100px" src="https://res.cloudinary.com/anuraghazra/image/upload/v1594908242/logo_ccswme.svg" align="center" alt="GitHub Readme Stats" /> <img width="100px" src="https://res.cloudinary.com/anuraghazra/image/upload/v1594908242/logo_ccswme.svg" align="center" alt="GitHub Readme Stats" />
<h2 align="center">GitHub Readme Stats</h2> <h2 align="center">GitHub Readme Stats</h2>
<p align="center">동적으로 생성되는 GitHub 사용량 통계를 여러분의 README 에 추가해보세요!</p> <p align="center">동적으로 생성되는 Github 사용량 통계를 여러분의 README 에 추가해보세요!</p>
</p> </p>
<p align="center"> <p align="center">
<a href="https://github.com/anuraghazra/github-readme-stats/actions"> <a href="https://github.com/anuraghazra/github-readme-stats/actions">
@@ -72,7 +72,7 @@
아래 코드를 복사해서 마크다운 파일에 붙여넣으면 끝이에요, 아주 간단해요! 아래 코드를 복사해서 마크다운 파일에 붙여넣으면 끝이에요, 아주 간단해요!
`?username=` 속성의 값을 GitHub 계정의 사용자 명(닉네임)으로 바꿔주세요. `?username=` 속성의 값을 Github 계정의 사용자 명(닉네임)으로 바꿔주세요.
```md ```md
[![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats) [![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats)
@@ -235,7 +235,7 @@ GitHub 저장소 여분 핀을 이용하면, 6개 이상의 저장소 핀을 여
# 언어 사용량 통계 # 언어 사용량 통계
언어 사용량 통계 카드는 GitHub 사용자가 가장 많이 사용한 언어가 표시됩니다. 언어 사용량 통계 카드는 Github 사용자가 가장 많이 사용한 언어가 표시됩니다.
_참고: _참고:
언어 사용량 통계는 GitHub 에서 가장 많이 사용된 언어의 표기일 뿐입니다. 언어 사용량 통계는 GitHub 에서 가장 많이 사용된 언어의 표기일 뿐입니다.
+2 -2
View File
@@ -219,7 +219,7 @@ Use [show_owner](#customization) variable to include the repo's owner username
टोप भाषाकार्डले github परयोग गर्नेहरुको प्रोग्रम्मिंग भाषाहरु देखाऊने गर्दछ |. टोप भाषाकार्डले github परयोग गर्नेहरुको प्रोग्रम्मिंग भाषाहरु देखाऊने गर्दछ |.
_NOTE: टोप भाषाहरुले आफ्नो सिपलाए संकेत गरेको होईन | योचै GitHub Metricबाट धेरै कुन भाषा परयोग भाकोलाए संकेत गरेको हो | _NOTE: टोप भाषाहरुले आफ्नो सिपलाए संकेत गरेको होईन | योचै Github Metricबाट धेरै कुन भाषा परयोग भाकोलाए संकेत गरेको हो |
### प्रयोग ### प्रयोग
कोदलाए कपी- पेसेत readme मा गर्नु होला र लिंक परिवतन गर्नु होला | कोदलाए कपी- पेसेत readme मा गर्नु होला र लिंक परिवतन गर्नु होला |
@@ -389,7 +389,7 @@ NOTE: Since [#58](https://github.com/anuraghazra/github-readme-stats/pull/58) we
येदि तपाइले यो प्रोजेक्ट चलाउनु बाकोक्ष बने र मलाई अझै प्रसंसा गर्ने हो बने तपाइले थुप्रै तरिका ले गर्नु सक्नु हुने छ :- येदि तपाइले यो प्रोजेक्ट चलाउनु बाकोक्ष बने र मलाई अझै प्रसंसा गर्ने हो बने तपाइले थुप्रै तरिका ले गर्नु सक्नु हुने छ :-
- यो प्रोजेक्टमा तपाइले प्रहयोग गर्दा मलाई क्रेडिट दिन सक्नु हुनेक्ष । - यो प्रोजेक्टमा तपाइले प्रहयोग गर्दा मलाई क्रेडिट दिन सक्नु हुनेक्ष ।
- तपाइले GitHub ReadMe Stats स्तार्रेड गर्न सक्नु हुनेक्ष :rocket: - तपाइले Github ReadMe Stats स्तार्रेड गर्न सक्नु हुनेक्ष :rocket:
- [![paypal.me/anuraghazra](https://ionicabizau.github.io/badges/paypal.svg)](https://www.paypal.me/anuraghazra) - तपाइले पेपाल बाट पनि सहयोग (डक्क्षिन) गर्न सक्नु हुनेक्ष | म ~~कोफी ~~ चिया . :tea: किन्न सक्क्षु । - [![paypal.me/anuraghazra](https://ionicabizau.github.io/badges/paypal.svg)](https://www.paypal.me/anuraghazra) - तपाइले पेपाल बाट पनि सहयोग (डक्क्षिन) गर्न सक्नु हुनेक्ष | म ~~कोफी ~~ चिया . :tea: किन्न सक्क्षु ।
धन्याबाद! :heart: धन्याबाद! :heart:
+2 -4
View File
@@ -53,8 +53,6 @@
<a href="/docs/readme_nl.md">Nederlands</a> <a href="/docs/readme_nl.md">Nederlands</a>
. .
<a href="/docs/readme_np.md">नेपाली</a> <a href="/docs/readme_np.md">नेपाली</a>
.
<a href="/docs/readme_tr.md">Türkçe</a>
</p> </p>
</p> </p>
<p align="center">Gostou do projeto? Por favor considere <a href="https://www.paypal.me/anuraghazra">fazer uma doação</a> para ajudar a melhorá-lo! <p align="center">Gostou do projeto? Por favor considere <a href="https://www.paypal.me/anuraghazra">fazer uma doação</a> para ajudar a melhorá-lo!
@@ -144,7 +142,7 @@ Personalize a aparência do seu `Stats Card` ou `Repo Card` da maneira que desej
- `cache_seconds` - Defina o cabeçalho do cache manualmente _(min: 1800, max: 86400)_ - `cache_seconds` - Defina o cabeçalho do cache manualmente _(min: 1800, max: 86400)_
- `locale` - defina o idioma no cartão _(por exemplo. cn, de, es, etc.)_ - `locale` - defina o idioma no cartão _(por exemplo. cn, de, es, etc.)_
> Nota sobre o cache: Cartões de repositório tem um cache padrão de 30 minutos (1800 segundos), se o número a contagem de forks e contagem de estrelas é menor que 1 mil o padrão é 2 horas (7200 segundos). Note também que o cache é limitado a um mínimo de 30 minutos e um máximo de 24 horas. > Nota sobre o cache: Cartões de repositório tem um cache padrão de 30 minutos (1800 segundos), se o número a contagem de forks e contagem de estrelas é menor que 1 mil o padrão é 2 horas (7200). Note também que o cache é limitado a um mínimo de 30 minutos e um máximo de 24 horas.
#### Opções exclusivas do cartão de estatísticas: #### Opções exclusivas do cartão de estatísticas:
@@ -169,7 +167,7 @@ Personalize a aparência do seu `Stats Card` ou `Repo Card` da maneira que desej
> :warning: **Importante:** > :warning: **Importante:**
> Nomes de linguagens devem ser uma sequência escapada de URI, como específicado em [Codificação por cento](https://pt.wikipedia.org/wiki/Codificação_por_cento) > Nomes de linguagens devem ser uma sequência escapada de URI, como específicado em [Codificação por cento](https://pt.wikipedia.org/wiki/Codificação_por_cento)
> (Ou seja: `c++` deve se tornar `c%2B%2B`, `jupyter notebook` deve se tornar `jupyter%20notebook`, etc.) > (Isso é: `c++` deve se tornar `c%2B%2B`, `jupyter notebook` deve se tornar `jupyter%20notebook`, etc.)
--- ---
+7 -7
View File
@@ -73,10 +73,10 @@
Alt kısımdaki kodu Kopyalayın ve yapıştırın. İşte bu kadar. Çok basit! Alt kısımdaki kodu Kopyalayın ve yapıştırın. İşte bu kadar. Çok basit!
`?username=` değerini kendi GitHub kullanıcı adınız ile değiştirin. `?username=` değerini kendi Github kullanıcı adınız ile değiştirin.
```md ```md
[![Anurag'nın GitHub İstatistikleri](https://github-readme-stats.vercel.app/api?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats) [![Anurag'nın Github İstatistikleri](https://github-readme-stats.vercel.app/api?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats)
``` ```
_Not: Şu sıralamalar mevcut: S+ (en üst 1%), S (en üst 25%), A++ (en üst 45%), A+ (en üst 60%), and B+ (herkes). _Not: Şu sıralamalar mevcut: S+ (en üst 1%), S (en üst 25%), A++ (en üst 45%), A+ (en üst 60%), and B+ (herkes).
Buradaki değerler [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) ile hesaplanırken; commitler, katkılar, hatalar, yıldızlar, çekme istekleri, takipçiler ve sahip olunan depolar (repository) göz önünde bulundurulamaktadır. Buradaki değerler [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) ile hesaplanırken; commitler, katkılar, hatalar, yıldızlar, çekme istekleri, takipçiler ve sahip olunan depolar (repository) göz önünde bulundurulamaktadır.
@@ -199,7 +199,7 @@ bg_color içerisinde birden fazla rengi gradient olarak göstermek için virgül
# GitHub Ekstra Pinler # GitHub Ekstra Pinler
GitHub ekstra pinler profilinize 6'dan fazla repoyu / depoyu profilinizde pinleyebilirsiniz. Github ekstra pinler profilinize 6'dan fazla repoyu / depoyu profilinizde pinleyebilirsiniz.
Hey! Artık 6 pin ile kısıtlı kalmayacaksınız! Hey! Artık 6 pin ile kısıtlı kalmayacaksınız!
@@ -225,7 +225,7 @@ Endpoint: `api/pin?username=mustafacagri&repo=github-readme-stats`
En çok kullanılan diller kartı kullanıcının en çok kullandığı dilleri gösterir. En çok kullanılan diller kartı kullanıcının en çok kullandığı dilleri gösterir.
_NOTE: En çok kullanılan dillerde yer alan bilgiler sizin yeteneğinizi ve benzeri şeyleri göstermek. Bu, kodlarınızda en çok kullandığınız dilleri gösteren bir GitHub metriğidir. Ayrıca, github-readme-stats'ın yeni özelliğidir. _NOTE: En çok kullanılan dillerde yer alan bilgiler sizin yeteneğinizi ve benzeri şeyleri göstermek. Bu, kodlarınızda en çok kullandığınız dilleri gösteren bir Github metriğidir. Ayrıca, github-readme-stats'ın yeni özelliğidir.
### Kullanım ### Kullanım
@@ -365,7 +365,7 @@ Genellikle resimleri yan yana düzenleyemezsiniz. Bunu yapmak için şu yaklaş
#### [@codeSTACKr'ın Yayınladığı Video Eğitimine Göz Atın](https://youtu.be/n6d4KHSKqGk?t=107) #### [@codeSTACKr'ın Yayınladığı Video Eğitimine Göz Atın](https://youtu.be/n6d4KHSKqGk?t=107)
GitHub API saatte sadece 5.000 isteğe izin verdiği için `https://github-readme-stats.vercel.app/api` adresindeki API'm bu limite muhtemelen takılmış olabilir. Eğer projeyi kendi Vercel sunucunuzda yayınlarsanız, böyle bir sorun yaşamayabilirsiniz. Deploy butonuna tıkla ve deploy başlasın! Github API saatte sadece 5.000 isteğe izin verdiği için `https://github-readme-stats.vercel.app/api` adresindeki API'm bu limite muhtemelen takılmış olabilir. Eğer projeyi kendi Vercel sunucunuzda yayınlarsanız, böyle bir sorun yaşamayabilirsiniz. Deploy butonuna tıkla ve deploy başlasın!
NOT: [#58](https://github.com/anuraghazra/github-readme-stats/pull/58) geliştirmesi sonrasında anlamadığımız bir şekilde 5.000 istek limitine takılmıyoruz :) NOT: [#58](https://github.com/anuraghazra/github-readme-stats/pull/58) geliştirmesi sonrasında anlamadığımız bir şekilde 5.000 istek limitine takılmıyoruz :)
@@ -378,9 +378,9 @@ NOT: [#58](https://github.com/anuraghazra/github-readme-stats/pull/58) geliştir
1. [vercel.com](https://vercel.com/) adresine gidin 1. [vercel.com](https://vercel.com/) adresine gidin
1. `Log in`'e tıklayın 1. `Log in`'e tıklayın
![](https://files.catbox.moe/tct1wg.png) ![](https://files.catbox.moe/tct1wg.png)
1. `Continue with GitHub`'e basarak GitHub ile giriş yapın 1. `Continue with GitHub`'e basarak Github ile giriş yapın
![](https://files.catbox.moe/btd78j.jpeg) ![](https://files.catbox.moe/btd78j.jpeg)
1. GitHub'a giriş yapın ve eğer çıkarsa tüm repolara izin verin. 1. Github'a giriş yapın ve eğer çıkarsa tüm repolara izin verin.
1. Bu repoyu fork'layın 1. Bu repoyu fork'layın
1. [Vercel dashboard](https://vercel.com/dashboard)'unuza geri dönün. 1. [Vercel dashboard](https://vercel.com/dashboard)'unuza geri dönün.
1. `Import Project`'i seçin. 1. `Import Project`'i seçin.
-15
View File
@@ -1,15 +0,0 @@
import statsCard from "./api/index.js";
import repoCard from "./api/pin.js";
import langCard from "./api/top-langs.js";
import wakatimeCard from "./api/wakatime.js";
import express from "express";
import dotenv from "dotenv";
dotenv.config();
const app = express();
app.listen(process.env.port || 9000);
app.get("/", statsCard);
app.get("/pin", repoCard);
app.get("/top-langs", langCard);
app.get("/wakatime", wakatimeCard);
+1 -1
View File
@@ -22,7 +22,7 @@
"@testing-library/dom": "^8.17.1", "@testing-library/dom": "^8.17.1",
"@testing-library/jest-dom": "^5.16.5", "@testing-library/jest-dom": "^5.16.5",
"@uppercod/css-to-object": "^1.1.1", "@uppercod/css-to-object": "^1.1.1",
"axios-mock-adapter": "^1.21.2", "axios-mock-adapter": "^1.18.1",
"color-contrast-checker": "^2.1.0", "color-contrast-checker": "^2.1.0",
"hjson": "^3.2.2", "hjson": "^3.2.2",
"husky": "^8.0.0", "husky": "^8.0.0",
+1 -1
View File
@@ -39,7 +39,7 @@
"@testing-library/dom": "^8.17.1", "@testing-library/dom": "^8.17.1",
"@testing-library/jest-dom": "^5.16.5", "@testing-library/jest-dom": "^5.16.5",
"@uppercod/css-to-object": "^1.1.1", "@uppercod/css-to-object": "^1.1.1",
"axios-mock-adapter": "^1.21.2", "axios-mock-adapter": "^1.18.1",
"color-contrast-checker": "^2.1.0", "color-contrast-checker": "^2.1.0",
"hjson": "^3.2.2", "hjson": "^3.2.2",
"husky": "^8.0.0", "husky": "^8.0.0",
+10 -136
View File
@@ -85,17 +85,14 @@ Visit <https://indiafightscorona.giveindia.org> and make a small donation to hel
- [Top Languages Card](#top-languages-card) - [Top Languages Card](#top-languages-card)
- [Wakatime Week Stats](#wakatime-week-stats) - [Wakatime Week Stats](#wakatime-week-stats)
- [Themes](#themes) - [Themes](#themes)
- [Responsive Card Theme](#responsive-card-theme)
- [Customization](#customization) - [Customization](#customization)
- [Common Options](#common-options) - [Common Options](#common-options)
- [Stats Card Exclusive Options](#stats-card-exclusive-options) - [Stats Card Exclusive Options](#stats-card-exclusive-options)
- [Repo Card Exclusive Options](#repo-card-exclusive-options) - [Repo Card Exclusive Options](#repo-card-exclusive-options)
- [Language Card Exclusive Options](#language-card-exclusive-options) - [Language Card Exclusive Options](#language-card-exclusive-options)
- [Wakatime Card Exclusive Option](#wakatime-card-exclusive-options) - [Wakatime Card Exclusive Option](#wakatime-card-exclusive-options)
- [Deploy Yourself](#deploy-on-your-own) - [Deploy Yourself](#deploy-on-your-own-vercel-instance)
- [On Vercel](#on-vercel) - [Keep your fork up to date](#keep-your-fork-up-to-date)
- [On other platforms](#on-other-platforms)
- [Keep your fork up to date](#keep-your-fork-up-to-date)
# GitHub Stats Card # GitHub Stats Card
@@ -135,7 +132,7 @@ You can add the count of all your private contributions to the total commits cou
### Showing icons ### 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 ```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true) ![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true)
@@ -153,101 +150,12 @@ Use `&theme=THEME_NAME` parameter like so :
#### All inbuilt themes #### All inbuilt themes
GitHub readme stats comes with several built-in themes (e.g. `dark`, `radical`, `merko`, `gruvbox`, `tokyonight`, `onedark`, `cobalt`, `synthwave`, `highcontrast`, `dracula`). Github readme stats comes with several built-in themes (e.g. `dark`, `radical`, `merko`, `gruvbox`, `tokyonight`, `onedark`, `cobalt`, `synthwave`, `highcontrast`, `dracula`).
<img src="https://res.cloudinary.com/anuraghazra/image/upload/v1595174536/grs-themes_l4ynja.png" alt="GitHub Readme Stats Themes" width="600px"/> <img src="https://res.cloudinary.com/anuraghazra/image/upload/v1595174536/grs-themes_l4ynja.png" alt="GitHub Readme Stats Themes" width="600px"/>
You can look at a preview for [all available themes](./themes/README.md) or checkout the [theme config file](./themes/index.js) & **you can also contribute new themes** if you like :D You can look at a preview for [all available themes](./themes/README.md) or checkout the [theme config file](./themes/index.js) & **you can also contribute new themes** if you like :D
#### Responsive Card Theme
[![Anurag's GitHub stats-Dark](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=dark#gh-dark-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-dark-mode-only)
[![Anurag's GitHub stats-Light](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=default#gh-light-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-light-mode-only)
Since GitHub will re-upload the cards and serve them from their [CDN](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/about-anonymized-urls), we can not infer the browser/GitHub theme on the server side. There are, however, four methods you can use to create dynamics themes on the client side.
##### Use the transparent theme
We have included a `transparent` theme that has a transparent background. This theme is optimized to look good on GitHub's dark and light default themes. You can enable this theme using the `&theme=transparent` parameter like so:
```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=transparent)
```
<details>
<summary>:eyes: Show example</summary>
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=transparent)
</details>
##### Add transparent alpha channel to a themes bg_color
You can use the `bg_color` parameter to make any of [the available themes](./themes/README.md) transparent. This is done by setting the `bg_color` to a colour with a transparent alpha channel (i.e. `bg_color=00000000`):
```md
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&bg_color=00000000)
```
<details>
<summary>:eyes: Show example</summary>
![Anurag's GitHub stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&bg_color=00000000)
</details>
##### Use GitHub's theme context tag
You can use [GitHub's theme context](https://github.blog/changelog/2021-11-24-specify-theme-context-for-images-in-markdown/) tags to switch the theme based on the user GitHub theme automatically. This is done by appending `#gh-dark-mode-only` or `#gh-light-mode-only` to the end of an image URL. This tag will define whether the image specified in the markdown is only shown to viewers using a light or a dark GitHub theme:
```md
[![Anurag's GitHub stats-Dark](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=dark#gh-dark-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-dark-mode-only)
[![Anurag's GitHub stats-Light](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=default#gh-light-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-light-mode-only)
```
<details>
<summary>:eyes: Show example</summary>
[![Anurag's GitHub stats-Dark](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=dark#gh-dark-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-dark-mode-only)
[![Anurag's GitHub stats-Light](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=default#gh-light-mode-only)](https://github.com/anuraghazra/github-readme-stats#gh-light-mode-only)
</details>
##### Use GitHub's new media feature
You can use [GitHub's new media feature](https://github.blog/changelog/2022-05-19-specify-theme-context-for-images-in-markdown-beta/) in HTML to specify whether to display images for light or dark themes. This is done using the HTML `<picture>` element in combination with the `prefers-color-scheme` media feature.
```html
<picture>
<source
srcset="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=dark"
media="(prefers-color-scheme: dark)"
/>
<source
srcset="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true"
media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)"
/>
<img src="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true" />
</picture>
```
<details>
<summary>:eyes: Show example</summary>
<picture>
<source
srcset="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true&theme=dark"
media="(prefers-color-scheme: dark)"
/>
<source
srcset="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true"
media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)"
/>
<img src="https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true" />
</picture>
</details>
### Customization ### Customization
You can customize the appearance of your `Stats Card` or `Repo Card` however you wish with URL parameters. You can customize the appearance of your `Stats Card` or `Repo Card` however you wish with URL parameters.
@@ -261,12 +169,12 @@ You can customize the appearance of your `Stats Card` or `Repo Card` however you
- `bg_color` - Card's background color _(hex color)_ **or** a gradient in the form of _angle,start,end_. Default: `fffefe` - `bg_color` - Card's background color _(hex color)_ **or** a gradient in the form of _angle,start,end_. Default: `fffefe`
- `hide_border` - Hides the card's border _(boolean)_. Default: `false` - `hide_border` - Hides the card's border _(boolean)_. Default: `false`
- `theme` - name of the theme, choose from [all available themes](./themes/README.md). Default: `default` theme. - `theme` - name of the theme, choose from [all available themes](./themes/README.md). Default: `default` theme.
- `cache_seconds` - set the cache header manually _(min: 14400, max: 86400)_. Default: `14400 seconds (4 hours)`. - `cache_seconds` - set the cache header manually _(min: 7200, max: 86400)_. Default: `14400 seconds (4 hours)`.
- `locale` - set the language in the card _(e.g. cn, de, es, etc.)_. Default: `en`. - `locale` - set the language in the card _(e.g. cn, de, es, etc.)_. Default: `en`.
- `border_radius` - Corner rounding on the card. Default: `4.5`. - `border_radius` - Corner rounding on the card. Default: `4.5`.
> **Warning** > **Warning**
> We use caching to decrease the load on our servers (see <https://github.com/anuraghazra/github-readme-stats/issues/1471#issuecomment-1271551425>). Our cards have a default cache of 4 hours (14400 seconds). Also, note that the cache is clamped to a minimum of 4 hours and a maximum of 24 hours. > We use caching to decrease the load on our servers (see https://github.com/anuraghazra/github-readme-stats/issues/1471#issuecomment-1271551425). Our cards have a default cache of 4 hours (14400 seconds). Also, note that the cache is clamped to a minimum of 4 hours and a maximum of 24 hours.
##### Gradient in bg_color ##### Gradient in bg_color
@@ -285,10 +193,9 @@ You can provide multiple comma-separated values in the bg_color option to render
- `count_private` - Count private commits _(boolean)_. Default: `false`. - `count_private` - Count private commits _(boolean)_. Default: `false`.
- `line_height` - Sets the line height between text _(number)_. Default: `25`. - `line_height` - Sets the line height between text _(number)_. Default: `25`.
- `exclude_repo` - Exclude stars from specified repositories _(Comma-separated values)_. Default: `[] (blank array)`. - `exclude_repo` - Exclude stars from specified repositories _(Comma-separated values)_. Default: `[] (blank array)`.
- `custom_title` - Sets a custom title for the card. Default: `<username> GitHub Stats`. - `custom_title` - Sets a custom title for the card. Default: `<username> Github Stats`.
- `text_bold` - Use bold text _(boolean)_. Default: `true`. - `text_bold` - Use bold text _(boolean)_. Default: `true`.
- `disable_animations` - Disables all animations in the card _(boolean)_. Default: `false`. - `disable_animations` - Disables all animations in the card _(boolean)_. Default: `false`.
- `ring_color` - Color of the rank circle _(hex color)_. Defaults to the theme ring color if it exists and otherwise the title color.
> **Note** > **Note**
> When hide_rank=`true`, the minimum card width is 270 px + the title length and padding. > When hide_rank=`true`, the minimum card width is 270 px + the title length and padding.
@@ -306,8 +213,6 @@ You can provide multiple comma-separated values in the bg_color option to render
- `langs_count` - Show more languages on the card, between 1-10 _(number)_. Default `5`. - `langs_count` - Show more languages on the card, between 1-10 _(number)_. Default `5`.
- `exclude_repo` - Exclude specified repositories _(Comma-separated values)_. Default: `[] (blank array)`. - `exclude_repo` - Exclude specified repositories _(Comma-separated values)_. Default: `[] (blank array)`.
- `custom_title` - Sets a custom title for the card _(string)_. Default `Most Used Languages`. - `custom_title` - Sets a custom title for the card _(string)_. Default `Most Used Languages`.
- `disable_animations` - Disables all animations in the card _(boolean)_. Default: `false`.
- `hide_progress` - It uses the compact layout option, hides percentages, and removes the bars. Default: `false`.
> **Warning** > **Warning**
> Language names should be URI-escaped, as specified in [Percent Encoding](https://en.wikipedia.org/wiki/Percent-encoding) > Language names should be URI-escaped, as specified in [Percent Encoding](https://en.wikipedia.org/wiki/Percent-encoding)
@@ -357,7 +262,7 @@ Use [show_owner](#customization) variable to include the repo's owner username
The top languages card shows a GitHub user's most frequently used top language. The top languages card shows a GitHub user's most frequently used top language.
> **Note** > **Note**
> Top Languages does not indicate my skill level or anything like that; it's a GitHub metric to determine which languages have the most code on GitHub. It is a new feature of github-readme-stats. > Top Languages does not indicate my skill level or anything like that; it's a GitHub metric to determine which languages have the most code on GitHub. It is a new feature of github-readme-stats._
### Usage ### Usage
@@ -401,14 +306,6 @@ You can use the `&layout=compact` option to change the card design.
[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&layout=compact)](https://github.com/anuraghazra/github-readme-stats) [![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&layout=compact)](https://github.com/anuraghazra/github-readme-stats)
``` ```
### Hide Progress Bars
You can use the `&hide_progress=true` option to hide the percentages and the progress bars (layout will be automatically set to `compact`).
```md
[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&hide_progress=true)](https://github.com/anuraghazra/github-readme-stats)
```
### Demo ### Demo
[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats) [![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats)
@@ -417,10 +314,6 @@ You can use the `&hide_progress=true` option to hide the percentages and the pro
[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&layout=compact)](https://github.com/anuraghazra/github-readme-stats) [![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&layout=compact)](https://github.com/anuraghazra/github-readme-stats)
- Hidden progress bars
[![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=anuraghazra&hide_progress=true)](https://github.com/anuraghazra/github-readme-stats)
# Wakatime Week Stats # Wakatime Week Stats
Change the `?username=` value to your [Wakatime](https://wakatime.com) username. Change the `?username=` value to your [Wakatime](https://wakatime.com) username.
@@ -511,11 +404,9 @@ By default, GitHub does not lay out the cards side by side. To do that, you can
</a> </a>
``` ```
## Deploy on your own ## Deploy on your own Vercel instance
### On Vercel #### [Check Out Step By Step Video Tutorial By @codeSTACKr](https://youtu.be/n6d4KHSKqGk?t=107)
#### :film_projector: [Check Out Step By Step Video Tutorial By @codeSTACKr](https://youtu.be/n6d4KHSKqGk?t=107)
> **Warning** > **Warning**
> If you are on the [hobby (i.e. free)](https://vercel.com/pricing) Vercel plan, please make sure you change the `maxDuration` parameter in the [vercel.json](https://github.com/anuraghazra/github-readme-stats/blob/master/vercel.json) file from `30` to `10` (see [#1416](https://github.com/anuraghazra/github-readme-stats/issues/1416#issuecomment-950275476) for more information). > If you are on the [hobby (i.e. free)](https://vercel.com/pricing) Vercel plan, please make sure you change the `maxDuration` parameter in the [vercel.json](https://github.com/anuraghazra/github-readme-stats/blob/master/vercel.json) file from `30` to `10` (see [#1416](https://github.com/anuraghazra/github-readme-stats/issues/1416#issuecomment-950275476) for more information).
@@ -550,23 +441,6 @@ Since the GitHub API only allows 5k requests per hour, my `https://github-readme
</details> </details>
### On other platforms
> **Warning**
> This way of using GRS is not officially supported and was added to cater to some particular use cases where Vercel could not be used (e.g. #2341). The support for this method, therefore, is limited.
<details>
<summary><b>:hammer_and_wrench: Step-by-step guide for deploying on other platforms</b></summary>
1. Fork or clone this repo as per your needs
2. Add `express` to the dependencies section of `package.json`
https://github.com/anuraghazra/github-readme-stats/blob/ba7c2f8b55eac8452e479c8bd38b044d204d0424/package.json#L54-L61
3. Run `npm i` if needed (initial setup)
4. Run `node express.js` to start the server, or set the entry point to `express.js` in `package.json` if you're deploying on a managed service
https://github.com/anuraghazra/github-readme-stats/blob/ba7c2f8b55eac8452e479c8bd38b044d204d0424/package.json#L11
5. You're done 🎉
</details>
### Keep your fork up to date ### Keep your fork up to date
You can keep your fork, and thus your private Vercel instance up to date with the upstream using GitHubs' [Sync Fork button](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork). You can also use the [pull](https://github.com/wei/pull) package created by [@wei](https://github.com/wei) to automate this process. You can keep your fork, and thus your private Vercel instance up to date with the upstream using GitHubs' [Sync Fork button](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork). You can also use the [pull](https://github.com/wei/pull) package created by [@wei](https://github.com/wei) to automate this process.
+9 -21
View File
@@ -9,28 +9,19 @@ import github from "@actions/github";
import { RequestError } from "@octokit/request-error"; import { RequestError } from "@octokit/request-error";
import { getGithubToken, getRepoInfo } from "./helpers.js"; import { getGithubToken, getRepoInfo } from "./helpers.js";
// Script parameters
const CLOSING_COMMENT = ` const CLOSING_COMMENT = `
\rThis theme PR has been automatically closed due to inactivity. Please reopen it if you want to continue working on it.\ \rThis PR has been automatically closed due to inactivity. Please feel free to reopen it if you need to continue working on it.\
\rThank you for your contributions. \rThank you for your contributions.
`; `;
const REVIEWER = "github-actions[bot]";
/**
* Retrieve the review user.
* @returns {string} review user.
*/
const getReviewer = () => {
return process.env.REVIEWER ? process.env.REVIEWER : REVIEWER;
};
/** /**
* Fetch open PRs from a given repository. * Fetch open PRs from a given repository.
* @param user The user name of the repository owner. * @param user The user name of the repository owner.
* @param repo The name of the repository. * @param repo The name of the repository.
* @param reviewer The reviewer to filter by.
* @returns The open PRs. * @returns The open PRs.
*/ */
export const fetchOpenPRs = async (octokit, user, repo, reviewer) => { export const fetchOpenPRs = async (octokit, user, repo) => {
const openPRs = []; const openPRs = [];
let hasNextPage = true; let hasNextPage = true;
let endCursor; let endCursor;
@@ -58,9 +49,9 @@ export const fetchOpenPRs = async (octokit, user, repo, reviewer) => {
name name
} }
} }
reviews(first: 100, states: CHANGES_REQUESTED, author: "${reviewer}") { reviews(first: 1, states: CHANGES_REQUESTED, author: "github-actions[bot]") {
nodes { nodes {
submittedAt updatedAt
} }
} }
} }
@@ -108,13 +99,11 @@ const isStale = (pullRequest, staleDays) => {
pullRequest.commits.nodes[0].commit.pushedDate, pullRequest.commits.nodes[0].commit.pushedDate,
); );
if (pullRequest.reviews.nodes[0]) { if (pullRequest.reviews.nodes[0]) {
const lastReviewDate = new Date( const lastReviewDate = new Date(pullRequest.reviews.nodes[0].updatedAt);
pullRequest.reviews.nodes.sort((a, b) => (a < b ? 1 : -1))[0].submittedAt,
);
const lastUpdateDate = const lastUpdateDate =
lastCommitDate >= lastReviewDate ? lastCommitDate : lastReviewDate; lastCommitDate >= lastReviewDate ? lastCommitDate : lastReviewDate;
const now = new Date(); const now = new Date();
return (now - lastUpdateDate) / (1000 * 60 * 60 * 24) >= staleDays; return now - lastUpdateDate > 1000 * 60 * 60 * 24 * staleDays;
} else { } else {
return false; return false;
} }
@@ -127,15 +116,14 @@ const run = async () => {
try { try {
// Create octokit client. // Create octokit client.
const dryRun = process.env.DRY_RUN === "true" || false; const dryRun = process.env.DRY_RUN === "true" || false;
const staleDays = process.env.STALE_DAYS || 20; const staleDays = process.env.STALE_DAYS || 15;
debug("Creating octokit client..."); debug("Creating octokit client...");
const octokit = github.getOctokit(getGithubToken()); const octokit = github.getOctokit(getGithubToken());
const { owner, repo } = getRepoInfo(github.context); const { owner, repo } = getRepoInfo(github.context);
const reviewer = getReviewer();
// Retrieve all theme pull requests. // Retrieve all theme pull requests.
debug("Retrieving all theme pull requests..."); debug("Retrieving all theme pull requests...");
const prs = await fetchOpenPRs(octokit, owner, repo, reviewer); const prs = await fetchOpenPRs(octokit, owner, repo);
const themePRs = pullsWithLabel(prs, "themes"); const themePRs = pullsWithLabel(prs, "themes");
const invalidThemePRs = pullsWithLabel(themePRs, "invalid"); const invalidThemePRs = pullsWithLabel(themePRs, "invalid");
debug("Retrieving stale theme PRs..."); debug("Retrieving stale theme PRs...");
+1 -2
View File
@@ -56,7 +56,6 @@ const createStatMdLink = (theme) => {
const generateLinks = (fn) => { const generateLinks = (fn) => {
return Object.keys(themes) return Object.keys(themes)
.map((name) => fn(name)) .map((name) => fn(name))
.filter((name) => !name.includes('-'))
.join(""); .join("");
}; };
@@ -68,7 +67,7 @@ const generateTable = ({ isRepoCard }) => {
const rows = []; const rows = [];
const themesFiltered = Object.keys(themes).filter( const themesFiltered = Object.keys(themes).filter(
(name) => name !== (!isRepoCard ? "default_repocard" : "default"), (name) => name !== (!isRepoCard ? "default_repocard" : "default"),
).filter((name) => !name.includes('-')); );
for (let i = 0; i < themesFiltered.length; i += 3) { for (let i = 0; i < themesFiltered.length; i += 3) {
const one = themesFiltered[i]; const one = themesFiltered[i];
+2 -1
View File
@@ -4,6 +4,7 @@
import { getInput } from "@actions/core"; import { getInput } from "@actions/core";
// Script variables.
const OWNER = "anuraghazra"; const OWNER = "anuraghazra";
const REPO = "github-readme-stats"; const REPO = "github-readme-stats";
@@ -30,7 +31,7 @@ export const getRepoInfo = (ctx) => {
/** /**
* Retrieve github token and throw error if it is not found. * Retrieve github token and throw error if it is not found.
* *
* @returns {string} GitHub token. * @returns {string} Github token.
*/ */
export const getGithubToken = () => { export const getGithubToken = () => {
const token = getInput("github_token") || process.env.GITHUB_TOKEN; const token = getInput("github_token") || process.env.GITHUB_TOKEN;
+7 -7
View File
@@ -16,6 +16,7 @@ import { isValidHexColor } from "../src/common/utils.js";
import { themes } from "../themes/index.js"; import { themes } from "../themes/index.js";
import { getGithubToken, getRepoInfo } from "./helpers.js"; import { getGithubToken, getRepoInfo } from "./helpers.js";
// Script variables.
const COMMENTER = "github-actions[bot]"; const COMMENTER = "github-actions[bot]";
const COMMENT_TITLE = "Automated Theme Preview"; const COMMENT_TITLE = "Automated Theme Preview";
@@ -24,7 +25,7 @@ const THEME_PR_SUCCESS_TEXT =
":heavy_check_mark: Theme PR does adhere to our guidelines."; ":heavy_check_mark: Theme PR does adhere to our guidelines.";
const FAIL_TEXT = ` const FAIL_TEXT = `
\rUnfortunately, your theme PR contains an error or does not adhere to our [theme guidelines](https://github.com/anuraghazra/github-readme-stats/blob/master/CONTRIBUTING.md#themes-contribution). Please fix the issues below, and we will review your\ \rUnfortunately, your theme PR contains an error or does not adhere to our [theme guidelines](https://github.com/anuraghazra/github-readme-stats/blob/master/CONTRIBUTING.md#themes-contribution). Please fix the issues below, and we will review your\
\r PR again. This pull request will **automatically close in 20 days** if no changes are made. After this time, you must re-open the PR for it to be reviewed. \r PR again. This pull request will **automatically close in 15 days** if no changes are made. After this time, you must re-open the PR for it to be reviewed.
`; `;
const THEME_CONTRIB_GUIDELINESS = ` const THEME_CONTRIB_GUIDELINESS = `
\rHi, thanks for the theme contribution. Please read our theme [contribution guidelines](https://github.com/anuraghazra/github-readme-stats/blob/master/CONTRIBUTING.md#themes-contribution). \rHi, thanks for the theme contribution. Please read our theme [contribution guidelines](https://github.com/anuraghazra/github-readme-stats/blob/master/CONTRIBUTING.md#themes-contribution).
@@ -92,7 +93,7 @@ const isPreviewComment = (inputs, comment) => {
* @param {number} issueNumber Issue number. * @param {number} issueNumber Issue number.
* @param {string} repo Repository name. * @param {string} repo Repository name.
* @param {string} owner Owner of the repository. * @param {string} owner Owner of the repository.
* @returns {Object} The GitHub comment object. * @returns {Object} The Github comment object.
*/ */
const findComment = async (octokit, issueNumber, owner, repo, commenter) => { const findComment = async (octokit, issueNumber, owner, repo, commenter) => {
const parameters = { const parameters = {
@@ -298,13 +299,12 @@ const themeNameAlreadyExists = (name) => {
return themes[name] !== undefined; return themes[name] !== undefined;
}; };
const DRY_RUN = process.env.DRY_RUN === "true" || false;
/** /**
* Main function. * Main function.
*/ */
export const run = async (prNumber) => { export const run = async (prNumber) => {
try { try {
const dryRun = process.env.DRY_RUN === "true" || false;
debug("Retrieve action information from context..."); debug("Retrieve action information from context...");
debug(`Context: ${inspect(github.context)}`); debug(`Context: ${inspect(github.context)}`);
let commentBody = ` let commentBody = `
@@ -514,7 +514,7 @@ export const run = async (prNumber) => {
// Create or update theme-preview comment. // Create or update theme-preview comment.
debug("Create or update theme-preview comment..."); debug("Create or update theme-preview comment...");
let comment_url; let comment_url;
if (!DRY_RUN) { if (!dryRun) {
comment_url = await upsertComment(octokit, { comment_url = await upsertComment(octokit, {
comment_id: comment?.id, comment_id: comment?.id,
issue_number: pullRequestId, issue_number: pullRequestId,
@@ -536,7 +536,7 @@ export const run = async (prNumber) => {
const reviewReason = themesValid const reviewReason = themesValid
? undefined ? undefined
: INVALID_REVIEW_COMMENT(comment_url); : INVALID_REVIEW_COMMENT(comment_url);
if (!DRY_RUN) { if (!dryRun) {
await addReview( await addReview(
octokit, octokit,
pullRequestId, pullRequestId,
@@ -559,7 +559,7 @@ export const run = async (prNumber) => {
} }
} catch (error) { } catch (error) {
debug("Set review state to `REQUEST_CHANGES` and add `invalid` label..."); debug("Set review state to `REQUEST_CHANGES` and add `invalid` label...");
if (!DRY_RUN) { if (!dryRun) {
await addReview( await addReview(
octokit, octokit,
pullRequestId, pullRequestId,
+2 -2
View File
@@ -5,10 +5,10 @@ set -e
export BRANCH_NAME=updated-theme-readme export BRANCH_NAME=updated-theme-readme
git --version git --version
git config --global user.email "no-reply@githubreadmestats.com" git config --global user.email "no-reply@githubreadmestats.com"
git config --global user.name "GitHub Readme Stats Bot" git config --global user.name "Github Readme Stats Bot"
git branch -d $BRANCH_NAME || true git branch -d $BRANCH_NAME || true
git checkout -b $BRANCH_NAME git checkout -b $BRANCH_NAME
git add --all git add --all
git commit --no-verify --message "docs(theme): Auto update theme readme" git commit --message "docs(theme): Auto update theme readme" || exit 0
git remote add origin-$BRANCH_NAME https://${PERSONAL_TOKEN}@github.com/${GH_REPO}.git git remote add origin-$BRANCH_NAME https://${PERSONAL_TOKEN}@github.com/${GH_REPO}.git
git push --force --quiet --set-upstream origin-$BRANCH_NAME $BRANCH_NAME git push --force --quiet --set-upstream origin-$BRANCH_NAME $BRANCH_NAME
+6 -10
View File
@@ -9,7 +9,7 @@
* @param {number} to The value to calculate the probability for. * @param {number} to The value to calculate the probability for.
* @returns {number} Probability. * @returns {number} Probability.
*/ */
const normalcdf = (mean, sigma, to) => { function normalcdf(mean, sigma, to) {
var z = (to - mean) / Math.sqrt(2 * sigma * sigma); var z = (to - mean) / Math.sqrt(2 * sigma * sigma);
var t = 1 / (1 + 0.3275911 * Math.abs(z)); var t = 1 / (1 + 0.3275911 * Math.abs(z));
var a1 = 0.254829592; var a1 = 0.254829592;
@@ -24,7 +24,7 @@ const normalcdf = (mean, sigma, to) => {
sign = -1; sign = -1;
} }
return (1 / 2) * (1 + sign * erf); return (1 / 2) * (1 + sign * erf);
}; }
/** /**
* Calculates the users rank. * Calculates the users rank.
@@ -38,7 +38,7 @@ const normalcdf = (mean, sigma, to) => {
* @param {number} stargazers The number of stars. * @param {number} stargazers The number of stars.
* @returns {{level: string, score: number}}} The users rank. * @returns {{level: string, score: number}}} The users rank.
*/ */
const calculateRank = ({ function calculateRank({
totalRepos, totalRepos,
totalCommits, totalCommits,
contributions, contributions,
@@ -46,7 +46,7 @@ const calculateRank = ({
prs, prs,
issues, issues,
stargazers, stargazers,
}) => { }) {
const COMMITS_OFFSET = 1.65; const COMMITS_OFFSET = 1.65;
const CONTRIBS_OFFSET = 1.65; const CONTRIBS_OFFSET = 1.65;
const ISSUES_OFFSET = 1; const ISSUES_OFFSET = 1;
@@ -70,11 +70,7 @@ const calculateRank = ({
const RANK_B_VALUE = 100; const RANK_B_VALUE = 100;
const TOTAL_VALUES = const TOTAL_VALUES =
RANK_S_VALUE + RANK_S_VALUE + RANK_A2_VALUE + RANK_A3_VALUE + RANK_B_VALUE;
RANK_DOUBLE_A_VALUE +
RANK_A2_VALUE +
RANK_A3_VALUE +
RANK_B_VALUE;
// prettier-ignore // prettier-ignore
const score = ( const score = (
@@ -98,7 +94,7 @@ const calculateRank = ({
})(); })();
return { level, score: normalizedScore }; return { level, score: normalizedScore };
}; }
export { calculateRank }; export { calculateRank };
export default calculateRank; export default calculateRank;
+16 -33
View File
@@ -12,11 +12,6 @@ import {
import { getStyles } from "../getStyles.js"; import { getStyles } from "../getStyles.js";
import { statCardLocales } from "../translations.js"; import { statCardLocales } from "../translations.js";
const CARD_MIN_WIDTH = 287;
const CARD_DEFAULT_WIDTH = 287;
const RANK_CARD_MIN_WIDTH = 420;
const RANK_CARD_DEFAULT_WIDTH = 450;
/** /**
* Create a stats card text item. * Create a stats card text item.
* *
@@ -94,7 +89,6 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
include_all_commits = false, include_all_commits = false,
line_height = 25, line_height = 25,
title_color, title_color,
ring_color,
icon_color, icon_color,
text_color, text_color,
text_bold = true, text_bold = true,
@@ -110,14 +104,13 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
const lheight = parseInt(String(line_height), 10); const lheight = parseInt(String(line_height), 10);
// returns theme based colors with proper overrides and defaults // returns theme based colors with proper overrides and defaults
const { titleColor, iconColor, textColor, bgColor, borderColor, ringColor } = const { titleColor, textColor, iconColor, bgColor, borderColor } =
getCardColors({ getCardColors({
title_color, title_color,
text_color,
icon_color, icon_color,
text_color,
bg_color, bg_color,
border_color, border_color,
ring_color,
theme, theme,
}); });
@@ -159,7 +152,7 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
}, },
contribs: { contribs: {
icon: icons.contribs, icon: icons.contribs,
label: i18n.t("statcard.contribs") + " (last year)", label: i18n.t("statcard.contribs"),
value: contributedTo, value: contributedTo,
id: "contribs", id: "contribs",
}, },
@@ -177,7 +170,6 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
"pl", "pl",
"de", "de",
"nl", "nl",
"zh-tw",
]; ];
const isLongLocale = longLocales.includes(locale) === true; const isLongLocale = longLocales.includes(locale) === true;
@@ -190,7 +182,8 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
...STATS[key], ...STATS[key],
index, index,
showIcons: show_icons, showIcons: show_icons,
shiftValuePos: 79.01 + (isLongLocale ? 50 : 0), shiftValuePos:
(!include_all_commits ? 50 : 35) + (isLongLocale ? 50 : 0),
bold: text_bold, bold: text_bold,
}), }),
); );
@@ -207,7 +200,6 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
const progress = 100 - rank.score; const progress = 100 - rank.score;
const cssStyles = getStyles({ const cssStyles = getStyles({
titleColor, titleColor,
ringColor,
textColor, textColor,
iconColor, iconColor,
show_icons, show_icons,
@@ -223,17 +215,11 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
When hide_rank=false, the minimum card_width is 340 px + the icon width (if show_icons=true). When hide_rank=false, the minimum card_width is 340 px + the icon width (if show_icons=true).
Numbers are picked by looking at existing dimensions on production. Numbers are picked by looking at existing dimensions on production.
*/ */
const iconWidth = show_icons ? 16 + /* padding */ 1 : 0; const iconWidth = show_icons ? 16 : 0;
const minCardWidth = const minCardWidth = hide_rank
(hide_rank ? clampValue(50 /* padding */ + calculateTextWidth() * 2, 270, Infinity)
? clampValue( : 340 + iconWidth;
50 /* padding */ + calculateTextWidth() * 2, const defaultCardWidth = hide_rank ? 270 : 495;
CARD_MIN_WIDTH,
Infinity,
)
: RANK_CARD_MIN_WIDTH) + iconWidth;
const defaultCardWidth =
(hide_rank ? CARD_DEFAULT_WIDTH : RANK_CARD_DEFAULT_WIDTH) + iconWidth;
let width = isNaN(card_width) ? defaultCardWidth : card_width; let width = isNaN(card_width) ? defaultCardWidth : card_width;
if (width < minCardWidth) { if (width < minCardWidth) {
width = minCardWidth; width = minCardWidth;
@@ -262,21 +248,18 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
/** /**
* Calculates the right rank circle translation values such that the rank circle * Calculates the right rank circle translation values such that the rank circle
* keeps respecting the following padding: * keeps respecting the padding.
* *
* width > RANK_CARD_DEFAULT_WIDTH: The default right padding of 70 px will be used. * width > 450: The default left padding of 50 px will be used.
* width < RANK_CARD_DEFAULT_WIDTH: The left and right padding will be enlarged * width < 450: The left and right padding will shrink equally.
* equally from a certain minimum at RANK_CARD_MIN_WIDTH.
* *
* @returns {number} - Rank circle translation value. * @returns {number} - Rank circle translation value.
*/ */
const calculateRankXTranslation = () => { const calculateRankXTranslation = () => {
const minXTranslation = RANK_CARD_MIN_WIDTH + iconWidth - 70; if (width < 450) {
if (width > RANK_CARD_DEFAULT_WIDTH) { return width - 95 + (45 * (450 - 340)) / 110;
const xMaxExpansion = minXTranslation + (450 - minCardWidth) / 2;
return xMaxExpansion + width - RANK_CARD_DEFAULT_WIDTH;
} else { } else {
return minXTranslation + (width - minCardWidth) / 2; return width - 95;
} }
}; };
+32 -88
View File
@@ -13,7 +13,7 @@ import {
import { langCardLocales } from "../translations.js"; import { langCardLocales } from "../translations.js";
const DEFAULT_CARD_WIDTH = 300; const DEFAULT_CARD_WIDTH = 300;
const MIN_CARD_WIDTH = 280; const MIN_CARD_WIDTH = 230;
const DEFAULT_LANGS_COUNT = 5; const DEFAULT_LANGS_COUNT = 5;
const DEFAULT_LANG_COLOR = "#858585"; const DEFAULT_LANG_COLOR = "#858585";
const CARD_PADDING = 25; const CARD_PADDING = 25;
@@ -39,57 +39,49 @@ const getLongestLang = (arr) =>
* Creates a node to display usage of a programming language in percentage * Creates a node to display usage of a programming language in percentage
* using text and a horizontal progress bar. * using text and a horizontal progress bar.
* *
* @param {object} props Function properties. * @param {object[]} props Function properties.
* @param {number} props.width The card width * @param {number} props.width The card width
* @param {string} props.name Name of the programming language. * @param {string} props.name Name of the programming language.
* @param {string} props.color Color of the programming language. * @param {string} props.color Color of the programming language.
* @param {string} props.progress Usage of the programming language in percentage. * @param {string} props.progress Usage of the programming language in percentage.
* @param {number} props.index Index of the programming language.
* @returns {string} Programming language SVG node. * @returns {string} Programming language SVG node.
*/ */
const createProgressTextNode = ({ width, color, name, progress, index }) => { const createProgressTextNode = ({ width, color, name, progress }) => {
const staggerDelay = (index + 3) * 150;
const paddingRight = 95; const paddingRight = 95;
const progressTextX = width - paddingRight + 10; const progressTextX = width - paddingRight + 10;
const progressWidth = width - paddingRight; const progressWidth = width - paddingRight;
return ` return `
<g class="stagger" style="animation-delay: ${staggerDelay}ms"> <text data-testid="lang-name" x="2" y="15" class="lang-name">${name}</text>
<text data-testid="lang-name" x="2" y="15" class="lang-name">${name}</text> <text x="${progressTextX}" y="34" class="lang-name">${progress}%</text>
<text x="${progressTextX}" y="34" class="lang-name">${progress}%</text> ${createProgressNode({
${createProgressNode({ x: 0,
x: 0, y: 25,
y: 25, color,
color, width: progressWidth,
width: progressWidth, progress,
progress, progressBarBackgroundColor: "#ddd",
progressBarBackgroundColor: "#ddd", })}
delay: staggerDelay + 300,
})}
</g>
`; `;
}; };
/** /**
* Creates a text only node to display usage of a programming language in percentage. * Creates a text only node to display usage of a programming language in percentage.
* *
* @param {object} props Function properties. * @param {object[]} props Function properties.
* @param {Lang} props.lang Programming language object. * @param {Lang} props.lang Programming language object.
* @param {number} props.totalSize Total size of all languages. * @param {number} props.totalSize Total size of all languages.
* @param {boolean} props.hideProgress Whether to hide percentage.
* @param {number} props.index Index of the programming language.
* @returns {string} Compact layout programming language SVG node. * @returns {string} Compact layout programming language SVG node.
*/ */
const createCompactLangNode = ({ lang, totalSize, hideProgress, index }) => { const createCompactLangNode = ({ lang, totalSize }) => {
const percentage = ((lang.size / totalSize) * 100).toFixed(2); const percentage = ((lang.size / totalSize) * 100).toFixed(2);
const staggerDelay = (index + 3) * 150;
const color = lang.color || "#858585"; const color = lang.color || "#858585";
return ` return `
<g class="stagger" style="animation-delay: ${staggerDelay}ms"> <g>
<circle cx="5" cy="6" r="5" fill="${color}" /> <circle cx="5" cy="6" r="5" fill="${color}" />
<text data-testid="lang-name" x="15" y="10" class='lang-name'> <text data-testid="lang-name" x="15" y="10" class='lang-name'>
${lang.name} ${hideProgress ? "" : percentage + "%"} ${lang.name} ${percentage}%
</text> </text>
</g> </g>
`; `;
@@ -101,10 +93,9 @@ const createCompactLangNode = ({ lang, totalSize, hideProgress, index }) => {
* @param {object[]} props Function properties. * @param {object[]} props Function properties.
* @param {Lang[]} props.langs Array of programming languages. * @param {Lang[]} props.langs Array of programming languages.
* @param {number} props.totalSize Total size of all languages. * @param {number} props.totalSize Total size of all languages.
* @param {boolean} props.hideProgress Whether to hide percentage.
* @returns {string} Programming languages SVG node. * @returns {string} Programming languages SVG node.
*/ */
const createLanguageTextNode = ({ langs, totalSize, hideProgress }) => { const createLanguageTextNode = ({ langs, totalSize }) => {
const longestLang = getLongestLang(langs); const longestLang = getLongestLang(langs);
const chunked = chunkArray(langs, langs.length / 2); const chunked = chunkArray(langs, langs.length / 2);
const layouts = chunked.map((array) => { const layouts = chunked.map((array) => {
@@ -113,7 +104,7 @@ const createLanguageTextNode = ({ langs, totalSize, hideProgress }) => {
createCompactLangNode({ createCompactLangNode({
lang, lang,
totalSize, totalSize,
hideProgress, // @ts-ignore
index, index,
}), }),
); );
@@ -143,13 +134,12 @@ const createLanguageTextNode = ({ langs, totalSize, hideProgress }) => {
*/ */
const renderNormalLayout = (langs, width, totalLanguageSize) => { const renderNormalLayout = (langs, width, totalLanguageSize) => {
return flexLayout({ return flexLayout({
items: langs.map((lang, index) => { items: langs.map((lang) => {
return createProgressTextNode({ return createProgressTextNode({
width, width: width,
name: lang.name, name: lang.name,
color: lang.color || DEFAULT_LANG_COLOR, color: lang.color || DEFAULT_LANG_COLOR,
progress: ((lang.size / totalLanguageSize) * 100).toFixed(2), progress: ((lang.size / totalLanguageSize) * 100).toFixed(2),
index,
}); });
}), }),
gap: 40, gap: 40,
@@ -163,10 +153,9 @@ const renderNormalLayout = (langs, width, totalLanguageSize) => {
* @param {Lang[]} langs Array of programming languages. * @param {Lang[]} langs Array of programming languages.
* @param {number} width Card width. * @param {number} width Card width.
* @param {number} totalLanguageSize Total size of all languages. * @param {number} totalLanguageSize Total size of all languages.
* @param {boolean} hideProgress Whether to hide progress bar.
* @returns {string} Compact layout card SVG object. * @returns {string} Compact layout card SVG object.
*/ */
const renderCompactLayout = (langs, width, totalLanguageSize, hideProgress) => { const renderCompactLayout = (langs, width, totalLanguageSize) => {
const paddingRight = 50; const paddingRight = 50;
const offsetWidth = width - paddingRight; const offsetWidth = width - paddingRight;
// progressOffset holds the previous language's width and used to offset the next language // progressOffset holds the previous language's width and used to offset the next language
@@ -197,21 +186,15 @@ const renderCompactLayout = (langs, width, totalLanguageSize, hideProgress) => {
.join(""); .join("");
return ` return `
${ <mask id="rect-mask">
!hideProgress <rect x="0" y="0" width="${offsetWidth}" height="8" fill="white" rx="5" />
? `
<mask id="rect-mask">
<rect x="0" y="0" width="${offsetWidth}" height="8" fill="white" rx="5"/>
</mask> </mask>
${compactProgressBar} ${compactProgressBar}
`
: "" <g transform="translate(0, 25)">
}
<g transform="translate(0, ${hideProgress ? "0" : "25"})">
${createLanguageTextNode({ ${createLanguageTextNode({
langs, langs,
totalSize: totalLanguageSize, totalSize: totalLanguageSize,
hideProgress: hideProgress,
})} })}
</g> </g>
`; `;
@@ -286,7 +269,6 @@ const renderTopLanguages = (topLangs, options = {}) => {
text_color, text_color,
bg_color, bg_color,
hide, hide,
hide_progress,
theme, theme,
layout, layout,
custom_title, custom_title,
@@ -294,7 +276,6 @@ const renderTopLanguages = (topLangs, options = {}) => {
langs_count = DEFAULT_LANGS_COUNT, langs_count = DEFAULT_LANGS_COUNT,
border_radius, border_radius,
border_color, border_color,
disable_animations,
} = options; } = options;
const i18n = new I18n({ const i18n = new I18n({
@@ -316,16 +297,11 @@ const renderTopLanguages = (topLangs, options = {}) => {
let height = calculateNormalLayoutHeight(langs.length); let height = calculateNormalLayoutHeight(langs.length);
let finalLayout = ""; let finalLayout = "";
if (layout === "compact" || hide_progress == true) { if (layout === "compact") {
height = width = width + 50; // padding
calculateCompactLayoutHeight(langs.length) + (hide_progress ? -25 : 0); height = calculateCompactLayoutHeight(langs.length);
finalLayout = renderCompactLayout( finalLayout = renderCompactLayout(langs, width, totalLanguageSize);
langs,
width,
totalLanguageSize,
hide_progress,
);
} else { } else {
finalLayout = renderNormalLayout(langs, width, totalLanguageSize); finalLayout = renderNormalLayout(langs, width, totalLanguageSize);
} }
@@ -348,43 +324,11 @@ const renderTopLanguages = (topLangs, options = {}) => {
colors, colors,
}); });
if (disable_animations) card.disableAnimations(); card.disableAnimations();
card.setHideBorder(hide_border); card.setHideBorder(hide_border);
card.setHideTitle(hide_title); card.setHideTitle(hide_title);
card.setCSS( card.setCSS(
` `.lang-name { font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${colors.textColor} }`,
@keyframes slideInAnimation {
from {
width: 0;
}
to {
width: calc(100%-100px);
}
}
@keyframes growWidthAnimation {
from {
width: 0;
}
to {
width: 100%;
}
}
.lang-name {
font: 400 11px "Segoe UI", Ubuntu, Sans-Serif;
fill: ${colors.textColor};
}
.stagger {
opacity: 0;
animation: fadeInAnimation 0.3s ease-in-out forwards;
}
#rect-mask rect{
animation: slideInAnimation 1s ease-in-out forwards;
}
.lang-progress{
animation: growWidthAnimation 0.6s ease-in-out forwards;
}
`,
); );
return card.render(` return card.render(`
-2
View File
@@ -37,8 +37,6 @@ export type TopLangOptions = CommonOptions & {
layout: "compact" | "normal"; layout: "compact" | "normal";
custom_title: string; custom_title: string;
langs_count: number; langs_count: number;
disable_animations: boolean;
hide_progress: boolean;
}; };
type WakaTimeOptions = CommonOptions & { type WakaTimeOptions = CommonOptions & {
+9 -35
View File
@@ -118,7 +118,6 @@ const createTextNode = ({
// @ts-ignore // @ts-ignore
name: label, name: label,
progressBarBackgroundColor, progressBarBackgroundColor,
delay: staggerDelay + 300,
}); });
return ` return `
@@ -160,7 +159,7 @@ const recalculatePercentages = (languages) => {
* @returns {string} WakaTime card SVG. * @returns {string} WakaTime card SVG.
*/ */
const renderWakatimeCard = (stats = {}, options = { hide: [] }) => { const renderWakatimeCard = (stats = {}, options = { hide: [] }) => {
let { languages = [] } = stats; let { languages } = stats;
const { const {
hide_title = false, hide_title = false,
hide_border = false, hide_border = false,
@@ -175,24 +174,20 @@ const renderWakatimeCard = (stats = {}, options = { hide: [] }) => {
custom_title, custom_title,
locale, locale,
layout, layout,
langs_count = languages.length, langs_count = languages ? languages.length : 0,
border_radius, border_radius,
border_color, border_color,
} = options; } = options;
const shouldHideLangs = Array.isArray(hide) && hide.length > 0; const shouldHideLangs = Array.isArray(hide) && hide.length > 0;
if (shouldHideLangs) { if (shouldHideLangs && languages !== undefined) {
const languagesToHide = new Set(hide.map((lang) => lowercaseTrim(lang))); const languagesToHide = new Set(hide.map((lang) => lowercaseTrim(lang)));
languages = languages.filter( languages = languages.filter(
(lang) => !languagesToHide.has(lowercaseTrim(lang.name)), (lang) => !languagesToHide.has(lowercaseTrim(lang.name)),
); );
recalculatePercentages(languages);
} }
// Since the percentages are sorted in descending order, we can just
// slice from the beginning without sorting.
languages = languages.slice(0, langs_count);
recalculatePercentages(languages);
const i18n = new I18n({ const i18n = new I18n({
locale, locale,
translations: wakatimeCardLocales, translations: wakatimeCardLocales,
@@ -214,8 +209,10 @@ const renderWakatimeCard = (stats = {}, options = { hide: [] }) => {
}); });
const filteredLanguages = languages const filteredLanguages = languages
.filter((language) => language.hours || language.minutes) ? languages
.slice(0, langsCount); .filter((language) => language.hours || language.minutes)
.slice(0, langsCount)
: [];
// Calculate the card height depending on how many items there are // Calculate the card height depending on how many items there are
// but if rank circle is visible clamp the minimum height to `150` // but if rank circle is visible clamp the minimum height to `150`
@@ -277,12 +274,11 @@ const renderWakatimeCard = (stats = {}, options = { hide: [] }) => {
} else { } else {
finalLayout = flexLayout({ finalLayout = flexLayout({
items: filteredLanguages.length items: filteredLanguages.length
? filteredLanguages.map((language, index) => { ? filteredLanguages.map((language) => {
return createTextNode({ return createTextNode({
id: language.name, id: language.name,
label: language.name, label: language.name,
value: language.text, value: language.text,
index: index,
percent: language.percent, percent: language.percent,
// @ts-ignore // @ts-ignore
progressBarColor: titleColor, progressBarColor: titleColor,
@@ -323,29 +319,7 @@ const renderWakatimeCard = (stats = {}, options = { hide: [] }) => {
card.setCSS( card.setCSS(
` `
${cssStyles} ${cssStyles}
@keyframes slideInAnimation {
from {
width: 0;
}
to {
width: calc(100%-100px);
}
}
@keyframes growWidthAnimation {
from {
width: 0;
}
to {
width: 100%;
}
}
.lang-name { font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} } .lang-name { font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor} }
#rect-mask rect{
animation: slideInAnimation 1s ease-in-out forwards;
}
.lang-progress{
animation: growWidthAnimation 0.6s ease-in-out forwards;
}
`, `,
); );
+8 -11
View File
@@ -10,7 +10,6 @@ import { clampValue } from "./utils.js";
* @param {string} createProgressNodeParams.color Progress color. * @param {string} createProgressNodeParams.color Progress color.
* @param {string} createProgressNodeParams.progress Progress value. * @param {string} createProgressNodeParams.progress Progress value.
* @param {string} createProgressNodeParams.progressBarBackgroundColor Progress bar bg color. * @param {string} createProgressNodeParams.progressBarBackgroundColor Progress bar bg color.
* @param {number} createProgressNodeParams.delay Delay before animation starts.
* @returns {string} Progress node. * @returns {string} Progress node.
*/ */
const createProgressNode = ({ const createProgressNode = ({
@@ -20,22 +19,20 @@ const createProgressNode = ({
color, color,
progress, progress,
progressBarBackgroundColor, progressBarBackgroundColor,
delay,
}) => { }) => {
const progressPercentage = clampValue(progress, 2, 100); const progressPercentage = clampValue(progress, 2, 100);
return ` return `
<svg width="${width}" x="${x}" y="${y}"> <svg width="${width}" x="${x}" y="${y}">
<rect rx="5" ry="5" x="0" y="0" width="${width}" height="8" fill="${progressBarBackgroundColor}"></rect> <rect rx="5" ry="5" x="0" y="0" width="${width}" height="8" fill="${progressBarBackgroundColor}"></rect>
<svg data-testid="lang-progress" width="${progressPercentage}%"> <rect
<rect height="8"
height="8" fill="${color}"
fill="${color}" rx="5" ry="5" x="0" y="0"
rx="5" ry="5" x="0" y="0" data-testid="lang-progress"
class="lang-progress" width="${progressPercentage}%"
style="animation-delay: ${delay}ms;" >
/> </rect>
</svg>
</svg> </svg>
`; `;
}; };
+1 -27
View File
@@ -79,7 +79,6 @@
"Ceylon": "#dfa535", "Ceylon": "#dfa535",
"Chapel": "#8dc63f", "Chapel": "#8dc63f",
"ChucK": "#3f8000", "ChucK": "#3f8000",
"Circom": "#707575",
"Cirru": "#ccccff", "Cirru": "#ccccff",
"Clarion": "#db901e", "Clarion": "#db901e",
"Clarity": "#5546ff", "Clarity": "#5546ff",
@@ -103,7 +102,6 @@
"Csound Score": "#1a1a1a", "Csound Score": "#1a1a1a",
"Cuda": "#3A4E3A", "Cuda": "#3A4E3A",
"Curry": "#531242", "Curry": "#531242",
"Cypher": "#34c0eb",
"Cython": "#fedf5b", "Cython": "#fedf5b",
"D": "#ba595e", "D": "#ba595e",
"DM": "#447265", "DM": "#447265",
@@ -117,7 +115,6 @@
"DirectX 3D File": "#aace60", "DirectX 3D File": "#aace60",
"Dockerfile": "#384d54", "Dockerfile": "#384d54",
"Dogescript": "#cca760", "Dogescript": "#cca760",
"Dotenv": "#e5d559",
"Dylan": "#6c616e", "Dylan": "#6c616e",
"E": "#ccce35", "E": "#ccce35",
"ECL": "#8a1267", "ECL": "#8a1267",
@@ -127,7 +124,6 @@
"Earthly": "#2af0ff", "Earthly": "#2af0ff",
"Easybuild": "#069406", "Easybuild": "#069406",
"Ecere Projects": "#913960", "Ecere Projects": "#913960",
"Ecmarkup": "#eb8131",
"EditorConfig": "#fff1f2", "EditorConfig": "#fff1f2",
"Eiffel": "#4d6977", "Eiffel": "#4d6977",
"Elixir": "#6e4a7e", "Elixir": "#6e4a7e",
@@ -151,7 +147,7 @@
"Forth": "#341708", "Forth": "#341708",
"Fortran": "#4d41b1", "Fortran": "#4d41b1",
"Fortran Free Form": "#4d41b1", "Fortran Free Form": "#4d41b1",
"FreeBasic": "#141AC9", "FreeBasic": "#867db1",
"FreeMarker": "#0050b2", "FreeMarker": "#0050b2",
"Frege": "#00cafe", "Frege": "#00cafe",
"Futhark": "#5f021f", "Futhark": "#5f021f",
@@ -184,7 +180,6 @@
"Go": "#00ADD8", "Go": "#00ADD8",
"Go Checksums": "#00ADD8", "Go Checksums": "#00ADD8",
"Go Module": "#00ADD8", "Go Module": "#00ADD8",
"Godot Resource": "#355570",
"Golo": "#88562A", "Golo": "#88562A",
"Gosu": "#82937f", "Gosu": "#82937f",
"Grace": "#615f8b", "Grace": "#615f8b",
@@ -195,7 +190,6 @@
"Groovy": "#4298b8", "Groovy": "#4298b8",
"Groovy Server Pages": "#4298b8", "Groovy Server Pages": "#4298b8",
"HAProxy": "#106da9", "HAProxy": "#106da9",
"HCL": "#844FBA",
"HLSL": "#aace60", "HLSL": "#aace60",
"HOCON": "#9ff8ee", "HOCON": "#9ff8ee",
"HTML": "#e34c26", "HTML": "#e34c26",
@@ -221,7 +215,6 @@
"Idris": "#b30000", "Idris": "#b30000",
"Ignore List": "#000000", "Ignore List": "#000000",
"ImageJ Macro": "#99AAFF", "ImageJ Macro": "#99AAFF",
"Imba": "#16cec6",
"Inno Setup": "#264b99", "Inno Setup": "#264b99",
"Io": "#a9188d", "Io": "#a9188d",
"Ioke": "#078193", "Ioke": "#078193",
@@ -229,7 +222,6 @@
"Isabelle ROOT": "#FEFE00", "Isabelle ROOT": "#FEFE00",
"J": "#9EEDFF", "J": "#9EEDFF",
"JAR Manifest": "#b07219", "JAR Manifest": "#b07219",
"JCL": "#d90e09",
"JFlex": "#DBCA00", "JFlex": "#DBCA00",
"JSON": "#292929", "JSON": "#292929",
"JSON with Comments": "#292929", "JSON with Comments": "#292929",
@@ -252,11 +244,9 @@
"Jsonnet": "#0064bd", "Jsonnet": "#0064bd",
"Julia": "#a270ba", "Julia": "#a270ba",
"Jupyter Notebook": "#DA5B0B", "Jupyter Notebook": "#DA5B0B",
"Just": "#384d54",
"KRL": "#28430A", "KRL": "#28430A",
"Kaitai Struct": "#773b37", "Kaitai Struct": "#773b37",
"KakouneScript": "#6f8042", "KakouneScript": "#6f8042",
"KerboScript": "#41adf0",
"KiCad Layout": "#2f4aab", "KiCad Layout": "#2f4aab",
"KiCad Legacy Layout": "#2f4aab", "KiCad Legacy Layout": "#2f4aab",
"KiCad Schematic": "#2f4aab", "KiCad Schematic": "#2f4aab",
@@ -296,7 +286,6 @@
"Mathematica": "#dd1100", "Mathematica": "#dd1100",
"Max": "#c4a79c", "Max": "#c4a79c",
"Mercury": "#ff2b2b", "Mercury": "#ff2b2b",
"Mermaid": "#ff3670",
"Meson": "#007800", "Meson": "#007800",
"Metal": "#8f14e9", "Metal": "#8f14e9",
"MiniYAML": "#ff1111", "MiniYAML": "#ff1111",
@@ -329,10 +318,6 @@
"Nu": "#c9df40", "Nu": "#c9df40",
"NumPy": "#9C8AF9", "NumPy": "#9C8AF9",
"Nunjucks": "#3d8137", "Nunjucks": "#3d8137",
"OASv2-json": "#85ea2d",
"OASv2-yaml": "#85ea2d",
"OASv3-json": "#85ea2d",
"OASv3-yaml": "#85ea2d",
"OCaml": "#3be133", "OCaml": "#3be133",
"ObjectScript": "#424893", "ObjectScript": "#424893",
"Objective-C": "#438eff", "Objective-C": "#438eff",
@@ -342,18 +327,14 @@
"Omgrofl": "#cabbff", "Omgrofl": "#cabbff",
"Opal": "#f7ede0", "Opal": "#f7ede0",
"Open Policy Agent": "#7d9199", "Open Policy Agent": "#7d9199",
"OpenAPI Specification v2": "#85ea2d",
"OpenAPI Specification v3": "#85ea2d",
"OpenCL": "#ed2e2d", "OpenCL": "#ed2e2d",
"OpenEdge ABL": "#5ce600", "OpenEdge ABL": "#5ce600",
"OpenQASM": "#AA70FF", "OpenQASM": "#AA70FF",
"OpenSCAD": "#e5cd45", "OpenSCAD": "#e5cd45",
"Option List": "#476732",
"Org": "#77aa99", "Org": "#77aa99",
"Oxygene": "#cdd0e3", "Oxygene": "#cdd0e3",
"Oz": "#fab738", "Oz": "#fab738",
"P4": "#7055b5", "P4": "#7055b5",
"PDDL": "#0d00ff",
"PEG.js": "#234d6b", "PEG.js": "#234d6b",
"PHP": "#4F5D95", "PHP": "#4F5D95",
"PLSQL": "#dad8d8", "PLSQL": "#dad8d8",
@@ -369,9 +350,7 @@
"PicoLisp": "#6067af", "PicoLisp": "#6067af",
"PigLatin": "#fcd7de", "PigLatin": "#fcd7de",
"Pike": "#005390", "Pike": "#005390",
"PlantUML": "#fbbd16",
"PogoScript": "#d80074", "PogoScript": "#d80074",
"Polar": "#ae81ff",
"Portugol": "#f8bd00", "Portugol": "#f8bd00",
"PostCSS": "#dc3a0c", "PostCSS": "#dc3a0c",
"PostScript": "#da291c", "PostScript": "#da291c",
@@ -387,7 +366,6 @@
"Puppet": "#302B6D", "Puppet": "#302B6D",
"PureBasic": "#5a6986", "PureBasic": "#5a6986",
"PureScript": "#1D222D", "PureScript": "#1D222D",
"Pyret": "#ee1e10",
"Python": "#3572A5", "Python": "#3572A5",
"Python console": "#3572A5", "Python console": "#3572A5",
"Python traceback": "#3572A5", "Python traceback": "#3572A5",
@@ -436,7 +414,6 @@
"Sass": "#a53b70", "Sass": "#a53b70",
"Scala": "#c22d40", "Scala": "#c22d40",
"Scaml": "#bd181a", "Scaml": "#bd181a",
"Scenic": "#fdc700",
"Scheme": "#1e4aec", "Scheme": "#1e4aec",
"Scilab": "#ca0f21", "Scilab": "#ca0f21",
"Self": "#0579aa", "Self": "#0579aa",
@@ -444,7 +421,6 @@
"Shell": "#89e051", "Shell": "#89e051",
"ShellCheck Config": "#cecfcb", "ShellCheck Config": "#cecfcb",
"Shen": "#120F14", "Shen": "#120F14",
"Simple File Verification": "#C9BFED",
"Singularity": "#64E6AD", "Singularity": "#64E6AD",
"Slash": "#007eff", "Slash": "#007eff",
"Slice": "#003fa2", "Slice": "#003fa2",
@@ -452,7 +428,6 @@
"SmPL": "#c94949", "SmPL": "#c94949",
"Smalltalk": "#596706", "Smalltalk": "#596706",
"Smarty": "#f0c040", "Smarty": "#f0c040",
"Smithy": "#c44536",
"Solidity": "#AA6746", "Solidity": "#AA6746",
"SourcePawn": "#f69e1d", "SourcePawn": "#f69e1d",
"Squirrel": "#800000", "Squirrel": "#800000",
@@ -503,7 +478,6 @@
"Vim Script": "#199f4b", "Vim Script": "#199f4b",
"Vim Snippet": "#199f4b", "Vim Snippet": "#199f4b",
"Visual Basic .NET": "#945db7", "Visual Basic .NET": "#945db7",
"Visual Basic 6.0": "#2c6353",
"Volt": "#1F1F1F", "Volt": "#1F1F1F",
"Vue": "#41b883", "Vue": "#41b883",
"Vyper": "#2980b9", "Vyper": "#2980b9",
+2 -11
View File
@@ -1,11 +1,5 @@
import { CustomError, logger } from "./utils.js"; import { CustomError, logger } from "./utils.js";
// Script variables.
const PATs = Object.keys(process.env).filter((key) =>
/PAT_\d*$/.exec(key),
).length;
const RETRIES = PATs ? PATs : 7;
/** /**
* Try to execute the fetcher function until it succeeds or the max number of retries is reached. * Try to execute the fetcher function until it succeeds or the max number of retries is reached.
* *
@@ -16,7 +10,7 @@ const RETRIES = PATs ? PATs : 7;
* @returns Promise<retryer> * @returns Promise<retryer>
*/ */
const retryer = async (fetcher, variables, retries = 0) => { const retryer = async (fetcher, variables, retries = 0) => {
if (retries > RETRIES) { if (retries > 7) {
throw new CustomError("Maximum retries exceeded", CustomError.MAX_RETRY); throw new CustomError("Maximum retries exceeded", CustomError.MAX_RETRY);
} }
try { try {
@@ -45,11 +39,8 @@ const retryer = async (fetcher, variables, retries = 0) => {
// prettier-ignore // prettier-ignore
// also checking for bad credentials if any tokens gets invalidated // also checking for bad credentials if any tokens gets invalidated
const isBadCredential = err.response.data && err.response.data.message === "Bad credentials"; const isBadCredential = err.response.data && err.response.data.message === "Bad credentials";
const isAccountSuspended =
err.response.data &&
err.response.data.message === "Sorry. Your account was suspended.";
if (isBadCredential || isAccountSuspended) { if (isBadCredential) {
logger.log(`PAT_${retries + 1} Failed`); logger.log(`PAT_${retries + 1} Failed`);
retries++; retries++;
// directly return from the function // directly return from the function
+49 -71
View File
@@ -42,13 +42,13 @@ const renderError = (message, secondaryMessage = "") => {
* @param {string} str String to encode. * @param {string} str String to encode.
* @returns {string} Encoded string. * @returns {string} Encoded string.
*/ */
const encodeHTML = (str) => { function encodeHTML(str) {
return str return str
.replace(/[\u00A0-\u9999<>&](?!#)/gim, (i) => { .replace(/[\u00A0-\u9999<>&](?!#)/gim, (i) => {
return "&#" + i.charCodeAt(0) + ";"; return "&#" + i.charCodeAt(0) + ";";
}) })
.replace(/\u0008/gim, ""); .replace(/\u0008/gim, "");
}; }
/** /**
* Retrieves num with suffix k(thousands) precise to 1 decimal if greater than 999. * Retrieves num with suffix k(thousands) precise to 1 decimal if greater than 999.
@@ -56,42 +56,41 @@ const encodeHTML = (str) => {
* @param {number} num The number to format. * @param {number} num The number to format.
* @returns {string|number} The formatted number. * @returns {string|number} The formatted number.
*/ */
const kFormatter = (num) => { function kFormatter(num) {
return Math.abs(num) > 999 return Math.abs(num) > 999
? Math.sign(num) * parseFloat((Math.abs(num) / 1000).toFixed(1)) + "k" ? Math.sign(num) * parseFloat((Math.abs(num) / 1000).toFixed(1)) + "k"
: Math.sign(num) * Math.abs(num); : Math.sign(num) * Math.abs(num);
}; }
/** /**
* Checks if a string is a valid hex color. * Checks if a string is a valid hex color.
* *
* @param {string} hexColor String to check. * @param {string} hexColor String to check.
* @returns {boolean} True if the given string is a valid hex color. * @returns {boolean} True if the given string is a valid hex color.
*
* @description: Tests color codes without the hash (#) prefix.
*/ */
const isValidHexColor = (hexColor) => { function isValidHexColor(hexColor) {
return new RegExp( return new RegExp(
/^([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}|[A-Fa-f0-9]{4})$/, /^([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}|[A-Fa-f0-9]{4})$/,
).test(hexColor); ).test(hexColor);
}; }
/** /**
* Returns boolean if value is either "true" or "false" else the value as it is. * Returns boolean if value is either "true" or "false" else the value as it is.
* *
* @param {string | boolean} value The value to parse. * @param {string} value The value to parse.
* @returns {boolean | undefined } The parsed value. * @returns {boolean | string} The parsed value.
*/ */
const parseBoolean = (value) => { function parseBoolean(value) {
if (typeof value === "boolean") return value; if (value === "true") {
return true;
if (typeof value === "string") { } else if (value === "false") {
if (value.toLowerCase() === "true") { return false;
return true; } else {
} else if (value.toLowerCase() === "false") { return value;
return false;
}
} }
return undefined; }
};
/** /**
* Parse string to array of strings. * Parse string to array of strings.
@@ -99,10 +98,10 @@ const parseBoolean = (value) => {
* @param {string} str The string to parse. * @param {string} str The string to parse.
* @returns {string[]} The array of strings. * @returns {string[]} The array of strings.
*/ */
const parseArray = (str) => { function parseArray(str) {
if (!str) return []; if (!str) return [];
return str.split(","); return str.split(",");
}; }
/** /**
* Clamp the given number between the given range. * Clamp the given number between the given range.
@@ -112,11 +111,11 @@ const parseArray = (str) => {
* @param {number} max The maximum value. * @param {number} max The maximum value.
* returns {number} The clamped number. * returns {number} The clamped number.
*/ */
const clampValue = (number, min, max) => { function clampValue(number, min, max) {
// @ts-ignore // @ts-ignore
if (Number.isNaN(parseInt(number))) return min; if (Number.isNaN(parseInt(number))) return min;
return Math.max(min, Math.min(number, max)); return Math.max(min, Math.min(number, max));
}; }
/** /**
* Check if the given string is a valid gradient. * Check if the given string is a valid gradient.
@@ -124,9 +123,10 @@ const clampValue = (number, min, max) => {
* @param {string[]} colors Array of colors. * @param {string[]} colors Array of colors.
* @returns {boolean} True if the given string is a valid gradient. * @returns {boolean} True if the given string is a valid gradient.
*/ */
const isValidGradient = (colors) => { function isValidGradient(colors) {
return isValidHexColor(colors[1]) && isValidHexColor(colors[2]); if (isNaN(colors[0])) return false;
}; return colors.slice(1).every((color) => isValidHexColor(color));
}
/** /**
* Retrieves a gradient if color has more than one valid hex codes else a single color. * Retrieves a gradient if color has more than one valid hex codes else a single color.
@@ -135,10 +135,10 @@ const isValidGradient = (colors) => {
* @param {string} fallbackColor The fallback color. * @param {string} fallbackColor The fallback color.
* @returns {string | string[]} The gradient or color. * @returns {string | string[]} The gradient or color.
*/ */
const fallbackColor = (color, fallbackColor) => { function fallbackColor(color, fallbackColor) {
let colors = color.split(",");
let gradient = null; let gradient = null;
let colors = color ? color.split(",") : [];
if (colors.length > 1 && isValidGradient(colors)) { if (colors.length > 1 && isValidGradient(colors)) {
gradient = colors; gradient = colors;
} }
@@ -147,7 +147,7 @@ const fallbackColor = (color, fallbackColor) => {
(gradient ? gradient : isValidHexColor(color) && `#${color}`) || (gradient ? gradient : isValidHexColor(color) && `#${color}`) ||
fallbackColor fallbackColor
); );
}; }
/** /**
* Send GraphQL request to GitHub API. * Send GraphQL request to GitHub API.
@@ -156,7 +156,7 @@ const fallbackColor = (color, fallbackColor) => {
* @param {import('axios').AxiosRequestConfig['headers']} headers Request headers. * @param {import('axios').AxiosRequestConfig['headers']} headers Request headers.
* @returns {Promise<any>} Request response. * @returns {Promise<any>} Request response.
*/ */
const request = (data, headers) => { function request(data, headers) {
// @ts-ignore // @ts-ignore
return axios({ return axios({
url: "https://api.github.com/graphql", url: "https://api.github.com/graphql",
@@ -164,7 +164,7 @@ const request = (data, headers) => {
headers, headers,
data, data,
}); });
}; }
/** /**
* Auto layout utility, allows us to layout things vertically or horizontally with * Auto layout utility, allows us to layout things vertically or horizontally with
@@ -173,11 +173,11 @@ const request = (data, headers) => {
* @param {object} props Function properties. * @param {object} props Function properties.
* @param {string[]} props.items Array of items to layout. * @param {string[]} props.items Array of items to layout.
* @param {number} props.gap Gap between items. * @param {number} props.gap Gap between items.
* @param {number[]?=} props.sizes Array of sizes for each item.
* @param {"column" | "row"?=} props.direction Direction to layout items. * @param {"column" | "row"?=} props.direction Direction to layout items.
* @param {number[]?=} props.sizes Array of sizes for each item.
* @returns {string[]} Array of items with proper layout. * @returns {string[]} Array of items with proper layout.
*/ */
const flexLayout = ({ items, gap, direction, sizes = [] }) => { function flexLayout({ items, gap, direction, sizes = [] }) {
let lastSize = 0; let lastSize = 0;
// filter() for filtering out empty strings // filter() for filtering out empty strings
return items.filter(Boolean).map((item, i) => { return items.filter(Boolean).map((item, i) => {
@@ -189,7 +189,7 @@ const flexLayout = ({ items, gap, direction, sizes = [] }) => {
lastSize += size + gap; lastSize += size + gap;
return `<g transform="${transform}">${item}</g>`; return `<g transform="${transform}">${item}</g>`;
}); });
}; }
/** /**
* Returns theme based colors with proper overrides and defaults. * Returns theme based colors with proper overrides and defaults.
@@ -204,16 +204,15 @@ const flexLayout = ({ items, gap, direction, sizes = [] }) => {
* @param {string} args.fallbackTheme Fallback theme. * @param {string} args.fallbackTheme Fallback theme.
* *
*/ */
const getCardColors = ({ function getCardColors({
title_color, title_color,
text_color, text_color,
icon_color, icon_color,
bg_color, bg_color,
border_color, border_color,
ring_color,
theme, theme,
fallbackTheme = "default", fallbackTheme = "default",
}) => { }) {
const defaultTheme = themes[fallbackTheme]; const defaultTheme = themes[fallbackTheme];
const selectedTheme = themes[theme] || defaultTheme; const selectedTheme = themes[theme] || defaultTheme;
const defaultBorderColor = const defaultBorderColor =
@@ -225,13 +224,6 @@ const getCardColors = ({
title_color || selectedTheme.title_color, title_color || selectedTheme.title_color,
"#" + defaultTheme.title_color, "#" + defaultTheme.title_color,
); );
// get the color provided by the user else the theme color
// finally if both colors are invalid we use the titleColor
const ringColor = fallbackColor(
ring_color || selectedTheme.ring_color,
titleColor,
);
const iconColor = fallbackColor( const iconColor = fallbackColor(
icon_color || selectedTheme.icon_color, icon_color || selectedTheme.icon_color,
"#" + defaultTheme.icon_color, "#" + defaultTheme.icon_color,
@@ -250,8 +242,8 @@ const getCardColors = ({
"#" + defaultBorderColor, "#" + defaultBorderColor,
); );
return { titleColor, iconColor, textColor, bgColor, borderColor, ringColor }; return { titleColor, iconColor, textColor, bgColor, borderColor };
}; }
/** /**
* Split text over multiple lines based on the card width. * Split text over multiple lines based on the card width.
@@ -261,7 +253,7 @@ const getCardColors = ({
* @param {number} maxLines Maximum number of lines. * @param {number} maxLines Maximum number of lines.
* @returns {string[]} Array of lines. * @returns {string[]} Array of lines.
*/ */
const wrapTextMultiline = (text, width = 59, maxLines = 3) => { function wrapTextMultiline(text, width = 59, maxLines = 3) {
const fullWidthComma = ""; const fullWidthComma = "";
const encoded = encodeHTML(text); const encoded = encodeHTML(text);
const isChinese = encoded.includes(fullWidthComma); const isChinese = encoded.includes(fullWidthComma);
@@ -286,7 +278,7 @@ const wrapTextMultiline = (text, width = 59, maxLines = 3) => {
// Remove empty lines if text fits in less than maxLines lines // Remove empty lines if text fits in less than maxLines lines
const multiLineText = lines.filter(Boolean); const multiLineText = lines.filter(Boolean);
return multiLineText; return multiLineText;
}; }
const noop = () => {}; const noop = () => {};
// return console instance based on the environment // return console instance based on the environment
@@ -352,7 +344,7 @@ class MissingParamError extends Error {
* @param {number} fontSize Font size. * @param {number} fontSize Font size.
* @returns {number} Text length. * @returns {number} Text length.
*/ */
const measureText = (str, fontSize = 10) => { function measureText(str, fontSize = 10) {
// prettier-ignore // prettier-ignore
const widths = [ const widths = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -384,20 +376,20 @@ const measureText = (str, fontSize = 10) => {
) )
.reduce((cur, acc) => acc + cur) * fontSize .reduce((cur, acc) => acc + cur) * fontSize
); );
}; }
/** @param {string} name */ /** @param {string} name */
const lowercaseTrim = (name) => name.toLowerCase().trim(); const lowercaseTrim = (name) => name.toLowerCase().trim();
/** /**
* Split array of languages in two columns. * Split array of languages in columns.
* *
* @template T Langauge object. * @template T Langauge object.
* @param {Array<T>} arr Array of languages. * @param {Array<T>} arr Array of languages.
* @param {number} perChunk Number of languages per column. * @param {number} perChunk Number of languages per column.
* @returns {Array<T>} Array of languages split in two columns. * @returns {Array<T>} Array of languages split in columns.
*/ */
const chunkArray = (arr, perChunk) => { function chunkArray(arr, perChunk) {
return arr.reduce((resultArray, item, index) => { return arr.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index / perChunk); const chunkIndex = Math.floor(index / perChunk);
@@ -409,7 +401,7 @@ const chunkArray = (arr, perChunk) => {
return resultArray; return resultArray;
}, []); }, []);
}; }
/** /**
* Parse emoji from string. * Parse emoji from string.
@@ -417,25 +409,12 @@ const chunkArray = (arr, perChunk) => {
* @param {string} str String to parse emoji from. * @param {string} str String to parse emoji from.
* @returns {string} String with emoji parsed. * @returns {string} String with emoji parsed.
*/ */
const parseEmojis = (str) => { function parseEmojis(str) {
if (!str) throw new Error("[parseEmoji]: str argument not provided"); if (!str) throw new Error("[parseEmoji]: str argument not provided");
return str.replace(/:\w+:/gm, (emoji) => { return str.replace(/:[\w+-]+:/gm, (emoji) => {
return toEmoji.get(emoji) || ""; return toEmoji.get(emoji) || "";
}); });
}; }
/**
* Get diff in minutes
* @param {Date} d1
* @param {Date} d2
* @returns {number}
*/
const dateDiff = (d1, d2) => {
const date1 = new Date(d1);
const date2 = new Date(d2);
const diff = date1.getTime() - date2.getTime();
return Math.round(diff / (1000 * 60));
};
export { export {
ERROR_CARD_LENGTH, ERROR_CARD_LENGTH,
@@ -460,5 +439,4 @@ export {
lowercaseTrim, lowercaseTrim,
chunkArray, chunkArray,
parseEmojis, parseEmojis,
dateDiff,
}; };
+5 -5
View File
@@ -6,7 +6,7 @@ import { MissingParamError, request } from "../common/utils.js";
* Repo data fetcher. * Repo data fetcher.
* *
* @param {import('Axios').AxiosRequestHeaders} variables Fetcher variables. * @param {import('Axios').AxiosRequestHeaders} variables Fetcher variables.
* @param {string} token GitHub token. * @param {string} token Github token.
* @returns {Promise<import('Axios').AxiosResponse>} The response. * @returns {Promise<import('Axios').AxiosResponse>} The response.
*/ */
const fetcher = (variables, token) => { const fetcher = (variables, token) => {
@@ -56,11 +56,11 @@ const urlExample = "/api/pin?username=USERNAME&amp;repo=REPO_NAME";
/** /**
* Fetch repository data. * Fetch repository data.
* *
* @param {string} username GitHub username. * @param {string} username Github username.
* @param {string} reponame GitHub repository name. * @param {string} reponame Github repository name.
* @returns {Promise<import("./types").RepositoryData>} Repository data. * @returns {Promise<import("./types").RepositoryData>} Repository data.
*/ */
const fetchRepo = async (username, reponame) => { async function fetchRepo(username, reponame) {
if (!username && !reponame) { if (!username && !reponame) {
throw new MissingParamError(["username", "repo"], urlExample); throw new MissingParamError(["username", "repo"], urlExample);
} }
@@ -100,7 +100,7 @@ const fetchRepo = async (username, reponame) => {
starCount: data.organization.repository.stargazers.totalCount, starCount: data.organization.repository.stargazers.totalCount,
}; };
} }
}; }
export { fetchRepo }; export { fetchRepo };
export default fetchRepo; export default fetchRepo;
+111 -107
View File
@@ -14,72 +14,46 @@ import {
dotenv.config(); dotenv.config();
// GraphQL queries.
const GRAPHQL_REPOS_FIELD = `
repositories(first: 100, ownerAffiliations: OWNER, orderBy: {direction: DESC, field: STARGAZERS}, after: $after) {
totalCount
nodes {
name
stargazers {
totalCount
}
}
pageInfo {
hasNextPage
endCursor
}
}
`;
const GRAPHQL_REPOS_QUERY = `
query userInfo($login: String!, $after: String) {
user(login: $login) {
${GRAPHQL_REPOS_FIELD}
}
}
`;
const GRAPHQL_STATS_QUERY = `
query userInfo($login: String!, $after: String) {
user(login: $login) {
name
login
contributionsCollection {
totalCommitContributions
restrictedContributionsCount
}
repositoriesContributedTo(first: 1, contributionTypes: [COMMIT, ISSUE, PULL_REQUEST, REPOSITORY]) {
totalCount
}
pullRequests(first: 1) {
totalCount
}
openIssues: issues(states: OPEN) {
totalCount
}
closedIssues: issues(states: CLOSED) {
totalCount
}
followers {
totalCount
}
${GRAPHQL_REPOS_FIELD}
}
}
`;
/** /**
* Stats fetcher object. * Stats fetcher object.
* *
* @param {import('axios').AxiosRequestHeaders} variables Fetcher variables. * @param {import('axios').AxiosRequestHeaders} variables Fetcher variables.
* @param {string} token GitHub token. * @param {string} token Github token.
* @returns {Promise<import('../common/types').Fetcher>} Stats fetcher response. * @returns {Promise<import('../common/types').StatsFetcherResponse>} Stats fetcher response.
*/ */
const fetcher = (variables, token) => { const fetcher = (variables, token) => {
const query = !variables.after ? GRAPHQL_STATS_QUERY : GRAPHQL_REPOS_QUERY;
return request( return request(
{ {
query, query: `
query userInfo($login: String!) {
user(login: $login) {
name
login
contributionsCollection {
totalCommitContributions
restrictedContributionsCount
}
repositoriesContributedTo(contributionTypes: [COMMIT, ISSUE, PULL_REQUEST, REPOSITORY]) {
totalCount
}
pullRequests {
totalCount
}
openIssues: issues(states: OPEN) {
totalCount
}
closedIssues: issues(states: CLOSED) {
totalCount
}
followers {
totalCount
}
repositories(ownerAffiliations: OWNER) {
totalCount
}
}
}
`,
variables, variables,
}, },
{ {
@@ -89,51 +63,48 @@ const fetcher = (variables, token) => {
}; };
/** /**
* Fetch stats information for a given username. * Fetch first 100 repositories for a given username.
* *
* @param {string} username Github username. * @param {import('axios').AxiosRequestHeaders} variables Fetcher variables.
* @returns {Promise<import('../common/types').StatsFetcher>} GraphQL Stats object. * @param {string} token Github token.
* * @returns {Promise<import('../common/types').StatsFetcherResponse>} Repositories fetcher response.
* @description This function supports multi-page fetching if the 'FETCH_MULTI_PAGE_STARS' environment variable is set to true.
*/ */
const statsFetcher = async (username) => { const repositoriesFetcher = (variables, token) => {
let stats; return request(
let hasNextPage = true; {
let endCursor = null; query: `
while (hasNextPage) { query userInfo($login: String!, $after: String) {
const variables = { login: username, first: 100, after: endCursor }; user(login: $login) {
let res = await retryer(fetcher, variables); repositories(first: 100, ownerAffiliations: OWNER, orderBy: {direction: DESC, field: STARGAZERS}, after: $after) {
if (res.data.errors) return res; nodes {
name
// Store stats data. stargazers {
const repoNodes = res.data.data.user.repositories.nodes; totalCount
if (!stats) { }
stats = res; }
} else { pageInfo {
stats.data.data.user.repositories.nodes.push(...repoNodes); hasNextPage
} endCursor
}
// Disable multi page fetching on public Vercel instance due to rate limits. }
const repoNodesWithStars = repoNodes.filter( }
(node) => node.stargazers.totalCount !== 0, }
); `,
hasNextPage = variables,
process.env.FETCH_MULTI_PAGE_STARS === "true" && },
repoNodes.length === repoNodesWithStars.length && {
res.data.data.user.repositories.pageInfo.hasNextPage; Authorization: `bearer ${token}`,
endCursor = res.data.data.user.repositories.pageInfo.endCursor; },
} );
return stats;
}; };
/** /**
* Fetch all the commits for all the repositories of a given username. * Fetch all the commits for all the repositories of a given username.
* *
* @param {*} username GitHub username. * @param {*} username Github username.
* @returns {Promise<number>} Total commits. * @returns {Promise<number>} Total commits.
* *
* @description Done like this because the GitHub API does not provide a way to fetch all the commits. See * @description Done like this because the Github API does not provide a way to fetch all the commits. See
* #92#issuecomment-661026467 and #211 for more information. * #92#issuecomment-661026467 and #211 for more information.
*/ */
const totalCommitsFetcher = async (username) => { const totalCommitsFetcher = async (username) => {
@@ -169,20 +140,60 @@ const totalCommitsFetcher = async (username) => {
return 0; return 0;
}; };
/**
* Fetch all the stars for all the repositories of a given username.
*
* @param {string} username Github username.
* @param {array} repoToHide Repositories to hide.
* @returns {Promise<number>} Total stars.
*/
const totalStarsFetcher = async (username, repoToHide) => {
let nodes = [];
let hasNextPage = true;
let endCursor = null;
while (hasNextPage) {
const variables = { login: username, first: 100, after: endCursor };
let res = await retryer(repositoriesFetcher, variables);
if (res.data.errors) {
logger.error(res.data.errors);
throw new CustomError(
res.data.errors[0].message || "Could not fetch user",
CustomError.USER_NOT_FOUND,
);
}
const allNodes = res.data.data.user.repositories.nodes;
const nodesWithStars = allNodes.filter(
(node) => node.stargazers.totalCount !== 0,
);
nodes.push(...nodesWithStars);
// hasNextPage =
// allNodes.length === nodesWithStars.length &&
// res.data.data.user.repositories.pageInfo.hasNextPage;
hasNextPage = false; // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
endCursor = res.data.data.user.repositories.pageInfo.endCursor;
}
return nodes
.filter((data) => !repoToHide[data.name])
.reduce((prev, curr) => prev + curr.stargazers.totalCount, 0);
};
/** /**
* Fetch stats for a given username. * Fetch stats for a given username.
* *
* @param {string} username GitHub username. * @param {string} username Github username.
* @param {boolean} count_private Include private contributions. * @param {boolean} count_private Include private contributions.
* @param {boolean} include_all_commits Include all commits. * @param {boolean} include_all_commits Include all commits.
* @returns {Promise<import("./types").StatsData>} Stats data. * @returns {Promise<import("./types").StatsData>} Stats data.
*/ */
const fetchStats = async ( async function fetchStats(
username, username,
count_private = false, count_private = false,
include_all_commits = false, include_all_commits = false,
exclude_repo = [], exclude_repo = [],
) => { ) {
if (!username) throw new MissingParamError(["username"]); if (!username) throw new MissingParamError(["username"]);
const stats = { const stats = {
@@ -195,7 +206,7 @@ const fetchStats = async (
rank: { level: "C", score: 0 }, rank: { level: "C", score: 0 },
}; };
let res = await statsFetcher(username); let res = await retryer(fetcher, { login: username });
// Catch GraphQL errors. // Catch GraphQL errors.
if (res.data.errors) { if (res.data.errors) {
@@ -251,15 +262,8 @@ const fetchStats = async (
stats.contributedTo = user.repositoriesContributedTo.totalCount; stats.contributedTo = user.repositoriesContributedTo.totalCount;
// Retrieve stars while filtering out repositories to be hidden // Retrieve stars while filtering out repositories to be hidden
stats.totalStars = user.repositories.nodes stats.totalStars = await totalStarsFetcher(username, repoToHide);
.filter((data) => {
return !repoToHide[data.name];
})
.reduce((prev, curr) => {
return prev + curr.stargazers.totalCount;
}, 0);
// @ts-ignore // TODO: Fix this.
stats.rank = calculateRank({ stats.rank = calculateRank({
totalCommits: stats.totalCommits, totalCommits: stats.totalCommits,
totalRepos: user.repositories.totalCount, totalRepos: user.repositories.totalCount,
@@ -271,7 +275,7 @@ const fetchStats = async (
}); });
return stats; return stats;
}; }
export { fetchStats }; export { fetchStats };
export default fetchStats; export default fetchStats;
+7 -4
View File
@@ -1,4 +1,5 @@
// @ts-check // @ts-check
import * as dotenv from "dotenv";
import { retryer } from "../common/retryer.js"; import { retryer } from "../common/retryer.js";
import { import {
CustomError, CustomError,
@@ -8,11 +9,13 @@ import {
wrapTextMultiline, wrapTextMultiline,
} from "../common/utils.js"; } from "../common/utils.js";
dotenv.config();
/** /**
* Top languages fetcher object. * Top languages fetcher object.
* *
* @param {import('Axios').AxiosRequestHeaders} variables Fetcher variables. * @param {import('Axios').AxiosRequestHeaders} variables Fetcher variables.
* @param {string} token GitHub token. * @param {string} token Github token.
* @returns {Promise<import('../common/types').StatsFetcherResponse>} Languages fetcher response. * @returns {Promise<import('../common/types').StatsFetcherResponse>} Languages fetcher response.
*/ */
const fetcher = (variables, token) => { const fetcher = (variables, token) => {
@@ -50,11 +53,11 @@ const fetcher = (variables, token) => {
/** /**
* Fetch top languages for a given username. * Fetch top languages for a given username.
* *
* @param {string} username GitHub username. * @param {string} username Github username.
* @param {string[]} exclude_repo List of repositories to exclude. * @param {string[]} exclude_repo List of repositories to exclude.
* @returns {Promise<import("./types").TopLangData>} Top languages data. * @returns {Promise<import("./types").TopLangData>} Top languages data.
*/ */
const fetchTopLanguages = async (username, exclude_repo = []) => { async function fetchTopLanguages(username, exclude_repo = []) {
if (!username) throw new MissingParamError(["username"]); if (!username) throw new MissingParamError(["username"]);
const res = await retryer(fetcher, { login: username }); const res = await retryer(fetcher, { login: username });
@@ -133,7 +136,7 @@ const fetchTopLanguages = async (username, exclude_repo = []) => {
}, {}); }, {});
return topLangs; return topLangs;
}; }
export { fetchTopLanguages }; export { fetchTopLanguages };
export default fetchTopLanguages; export default fetchTopLanguages;
+2 -3
View File
@@ -77,7 +77,6 @@ const getStyles = ({
titleColor, titleColor,
textColor, textColor,
iconColor, iconColor,
ringColor,
show_icons, show_icons,
progress, progress,
}) => { }) => {
@@ -106,13 +105,13 @@ const getStyles = ({
} }
.rank-circle-rim { .rank-circle-rim {
stroke: ${ringColor}; stroke: ${titleColor};
fill: none; fill: none;
stroke-width: 6; stroke-width: 6;
opacity: 0.2; opacity: 0.2;
} }
.rank-circle { .rank-circle {
stroke: ${ringColor}; stroke: ${titleColor};
stroke-dasharray: 250; stroke-dasharray: 250;
fill: none; fill: none;
stroke-width: 6; stroke-width: 6;
+6 -6
View File
@@ -37,7 +37,7 @@ const statCardLocales = ({ name, apostrophe }) => {
sk: `GitHub štatistiky používateľa ${encodedName}`, sk: `GitHub štatistiky používateľa ${encodedName}`,
tr: `${encodedName} Hesabının GitHub Yıldızları`, tr: `${encodedName} Hesabının GitHub Yıldızları`,
pl: `Statystyki GitHub użytkownika ${encodedName}`, pl: `Statystyki GitHub użytkownika ${encodedName}`,
uz: `${encodedName}ning GitHub'dagi statistikasi`, uz: `${encodedName}ning Github'dagi statistikasi`,
vi: `Thống Kê GitHub ${encodedName}`, vi: `Thống Kê GitHub ${encodedName}`,
se: `GitHubstatistik för ${encodedName}`, se: `GitHubstatistik för ${encodedName}`,
}, },
@@ -67,7 +67,7 @@ const statCardLocales = ({ name, apostrophe }) => {
my: "Jumlah Bintang", my: "Jumlah Bintang",
sk: "Hviezdy", sk: "Hviezdy",
tr: "Toplam Yıldız", tr: "Toplam Yıldız",
pl: "Liczba otrzymanych gwiazdek", pl: "Liczba Gwiazdek dostanych",
uz: "Yulduzchalar", uz: "Yulduzchalar",
vi: "Tổng Số Sao", vi: "Tổng Số Sao",
se: "Antal intjänade stjärnor", se: "Antal intjänade stjärnor",
@@ -160,7 +160,7 @@ const statCardLocales = ({ name, apostrophe }) => {
my: "Jumlah Isu Dilaporkan", my: "Jumlah Isu Dilaporkan",
sk: "Všetky problémy", sk: "Všetky problémy",
tr: "Toplam Hata", tr: "Toplam Hata",
pl: "Wszystkie problemy", pl: "Wszystkie Issues",
uz: "'Issue'lar", uz: "'Issue'lar",
vi: "Tổng Số Vấn Đề", vi: "Tổng Số Vấn Đề",
se: "Total antal issues", se: "Total antal issues",
@@ -322,7 +322,7 @@ const wakatimeCardLocales = {
my: "Statistik Wakatime", my: "Statistik Wakatime",
sk: "Wakatime štatistika", sk: "Wakatime štatistika",
tr: "Waketime İstatistikler", tr: "Waketime İstatistikler",
pl: "Statystyki Wakatime", pl: "statystyki Wakatime",
vi: "Thống Kê Wakatime", vi: "Thống Kê Wakatime",
se: "Wakatime statistik", se: "Wakatime statistik",
}, },
@@ -367,9 +367,9 @@ const availableLocales = Object.keys(repoCardLocales["repocard.archived"]);
* @param {string} locale The locale to check. * @param {string} locale The locale to check.
* @returns {boolean} Boolean specifying whether the locale is available or not. * @returns {boolean} Boolean specifying whether the locale is available or not.
*/ */
const isLocaleAvailable = (locale) => { function isLocaleAvailable(locale) {
return availableLocales.includes(locale.toLowerCase()); return availableLocales.includes(locale.toLowerCase());
}; }
export { export {
isLocaleAvailable, isLocaleAvailable,
@@ -51,13 +51,13 @@ exports[`Test Render Wakatime Card should render correctly with compact layout 1
} }
.rank-circle-rim { .rank-circle-rim {
stroke: undefined; stroke: #2f80ed;
fill: none; fill: none;
stroke-width: 6; stroke-width: 6;
opacity: 0.2; opacity: 0.2;
} }
.rank-circle { .rank-circle {
stroke: undefined; stroke: #2f80ed;
stroke-dasharray: 250; stroke-dasharray: 250;
fill: none; fill: none;
stroke-width: 6; stroke-width: 6;
@@ -69,29 +69,7 @@ exports[`Test Render Wakatime Card should render correctly with compact layout 1
} }
@keyframes slideInAnimation {
from {
width: 0;
}
to {
width: calc(100%-100px);
}
}
@keyframes growWidthAnimation {
from {
width: 0;
}
to {
width: 100%;
}
}
.lang-name { font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif; fill: #434d58 } .lang-name { font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif; fill: #434d58 }
#rect-mask rect{
animation: slideInAnimation 1s ease-in-out forwards;
}
.lang-progress{
animation: growWidthAnimation 0.6s ease-in-out forwards;
}
@@ -144,7 +122,7 @@ exports[`Test Render Wakatime Card should render correctly with compact layout 1
data-testid="lang-progress" data-testid="lang-progress"
x="0" x="0"
y="0" y="0"
width="415.61699999999996" width="6.6495"
height="8" height="8"
fill="#858585" fill="#858585"
/> />
@@ -152,189 +130,9 @@ exports[`Test Render Wakatime Card should render correctly with compact layout 1
<rect <rect
mask="url(#rect-mask)" mask="url(#rect-mask)"
data-testid="lang-progress" data-testid="lang-progress"
x="415.61699999999996" x="6.6495"
y="0" y="0"
width="29.0625" width="0.465"
height="8"
fill="#3178c6"
/>
<g transform="translate(25, 25)">
<circle cx="5" cy="6" r="5" fill="#858585" />
<text data-testid="lang-name" x="15" y="10" class='lang-name'>
Other - 19 mins
</text>
</g>
<g transform="translate(230, 25)">
<circle cx="5" cy="6" r="5" fill="#3178c6" />
<text data-testid="lang-name" x="15" y="10" class='lang-name'>
TypeScript - 1 min
</text>
</g>
</svg>
</g>
</svg>
"
`;
exports[`Test Render Wakatime Card should render correctly with compact layout when langs_count is set 1`] = `
"
<svg
width="495"
height="115"
viewBox="0 0 495 115"
fill="none"
xmlns="http://www.w3.org/2000/svg"
role="img"
aria-labelledby="descId"
>
<title id="titleId"></title>
<desc id="descId"></desc>
<style>
.header {
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
fill: #2f80ed;
animation: fadeInAnimation 0.8s ease-in-out forwards;
}
@supports(-moz-appearance: auto) {
/* Selector detects Firefox */
.header { font-size: 15.5px; }
}
.stat {
font: 600 14px 'Segoe UI', Ubuntu, "Helvetica Neue", Sans-Serif; fill: #434d58;
}
@supports(-moz-appearance: auto) {
/* Selector detects Firefox */
.stat { font-size:12px; }
}
.stagger {
opacity: 0;
animation: fadeInAnimation 0.3s ease-in-out forwards;
}
.rank-text {
font: 800 24px 'Segoe UI', Ubuntu, Sans-Serif; fill: #434d58;
animation: scaleInAnimation 0.3s ease-in-out forwards;
}
.not_bold { font-weight: 400 }
.bold { font-weight: 700 }
.icon {
fill: #4c71f2;
display: none;
}
.rank-circle-rim {
stroke: undefined;
fill: none;
stroke-width: 6;
opacity: 0.2;
}
.rank-circle {
stroke: undefined;
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;
}
@keyframes slideInAnimation {
from {
width: 0;
}
to {
width: calc(100%-100px);
}
}
@keyframes growWidthAnimation {
from {
width: 0;
}
to {
width: 100%;
}
}
.lang-name { font: 400 11px 'Segoe UI', Ubuntu, Sans-Serif; fill: #434d58 }
#rect-mask rect{
animation: slideInAnimation 1s ease-in-out forwards;
}
.lang-progress{
animation: growWidthAnimation 0.6s ease-in-out forwards;
}
</style>
<rect
data-testid="card-bg"
x="0.5"
y="0.5"
rx="4.5"
height="99%"
stroke="#e4e2e2"
width="494"
fill="#fffefe"
stroke-opacity="1"
/>
<g
data-testid="card-title"
transform="translate(25, 35)"
>
<g transform="translate(0, 0)">
<text
x="0"
y="0"
class="header"
data-testid="header"
>Wakatime Stats</text>
</g>
</g>
<g
data-testid="main-card-body"
transform="translate(0, 55)"
>
<svg x="0" y="0" width="100%">
<mask id="rect-mask">
<rect x="25" y="0" width="440" height="8" fill="white" rx="5" />
</mask>
<rect
mask="url(#rect-mask)"
data-testid="lang-progress"
x="0"
y="0"
width="436.4025"
height="8"
fill="#858585"
/>
<rect
mask="url(#rect-mask)"
data-testid="lang-progress"
x="436.4025"
y="0"
width="30.503999999999998"
height="8" height="8"
fill="#3178c6" fill="#3178c6"
/> />
+29 -76
View File
@@ -25,7 +25,7 @@ stats.rank = calculateRank({
issues: stats.totalIssues, issues: stats.totalIssues,
}); });
const data_stats = { const data = {
data: { data: {
user: { user: {
name: stats.name, name: stats.name,
@@ -40,6 +40,15 @@ const data_stats = {
followers: { totalCount: 0 }, followers: { totalCount: 0 },
repositories: { repositories: {
totalCount: 1, totalCount: 1,
},
},
},
};
const repositoriesData = {
data: {
user: {
repositories: {
nodes: [{ stargazers: { totalCount: 100 } }], nodes: [{ stargazers: { totalCount: 100 } }],
pageInfo: { pageInfo: {
hasNextPage: false, hasNextPage: false,
@@ -74,7 +83,11 @@ const faker = (query, data) => {
setHeader: jest.fn(), setHeader: jest.fn(),
send: jest.fn(), send: jest.fn(),
}; };
mock.onPost("https://api.github.com/graphql").replyOnce(200, data); mock
.onPost("https://api.github.com/graphql")
.replyOnce(200, data)
.onPost("https://api.github.com/graphql")
.replyOnce(200, repositoriesData);
return { req, res }; return { req, res };
}; };
@@ -85,7 +98,7 @@ afterEach(() => {
describe("Test /api/", () => { describe("Test /api/", () => {
it("should test the request", async () => { it("should test the request", async () => {
const { req, res } = faker({}, data_stats); const { req, res } = faker({}, data);
await api(req, res); await api(req, res);
@@ -120,7 +133,7 @@ describe("Test /api/", () => {
text_color: "fff", text_color: "fff",
bg_color: "fff", bg_color: "fff",
}, },
data_stats, data,
); );
await api(req, res); await api(req, res);
@@ -141,33 +154,23 @@ describe("Test /api/", () => {
}); });
it("should have proper cache", async () => { it("should have proper cache", async () => {
const { req, res } = faker({}, data_stats); const { req, res } = faker({}, data);
await api(req, res); await api(req, res);
expect(res.setHeader.mock.calls).toEqual([ expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"], ["Content-Type", "image/svg+xml"],
[ ["Cache-Control", `public, max-age=${CONSTANTS.FOUR_HOURS}`],
"Cache-Control",
`max-age=${CONSTANTS.FOUR_HOURS / 2}, s-maxage=${
CONSTANTS.FOUR_HOURS
}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
],
]); ]);
}); });
it("should set proper cache", async () => { it("should set proper cache", async () => {
const { req, res } = faker({ cache_seconds: 15000 }, data_stats); const { req, res } = faker({ cache_seconds: 15000 }, data);
await api(req, res); await api(req, res);
expect(res.setHeader.mock.calls).toEqual([ expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"], ["Content-Type", "image/svg+xml"],
[ ["Cache-Control", `public, max-age=${15000}`],
"Cache-Control",
`max-age=7500, s-maxage=${15000}, stale-while-revalidate=${
CONSTANTS.ONE_DAY
}`,
],
]); ]);
}); });
@@ -177,54 +180,39 @@ describe("Test /api/", () => {
expect(res.setHeader.mock.calls).toEqual([ expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"], ["Content-Type", "image/svg+xml"],
["Cache-Control", `no-cache, no-store, must-revalidate`], ["Cache-Control", `no-store`],
]); ]);
}); });
it("should set proper cache with clamped values", async () => { it("should set proper cache with clamped values", async () => {
{ {
let { req, res } = faker({ cache_seconds: 200000 }, data_stats); let { req, res } = faker({ cache_seconds: 200000 }, data);
await api(req, res); await api(req, res);
expect(res.setHeader.mock.calls).toEqual([ expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"], ["Content-Type", "image/svg+xml"],
[ ["Cache-Control", `public, max-age=${CONSTANTS.ONE_DAY}`],
"Cache-Control",
`max-age=${CONSTANTS.ONE_DAY / 2}, s-maxage=${
CONSTANTS.ONE_DAY
}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
],
]); ]);
} }
// note i'm using block scoped vars // note i'm using block scoped vars
{ {
let { req, res } = faker({ cache_seconds: 0 }, data_stats); let { req, res } = faker({ cache_seconds: 0 }, data);
await api(req, res); await api(req, res);
expect(res.setHeader.mock.calls).toEqual([ expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"], ["Content-Type", "image/svg+xml"],
[ ["Cache-Control", `public, max-age=${CONSTANTS.FOUR_HOURS}`],
"Cache-Control",
`max-age=${CONSTANTS.FOUR_HOURS / 2}, s-maxage=${
CONSTANTS.FOUR_HOURS
}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
],
]); ]);
} }
{ {
let { req, res } = faker({ cache_seconds: -10000 }, data_stats); let { req, res } = faker({ cache_seconds: -10000 }, data);
await api(req, res); await api(req, res);
expect(res.setHeader.mock.calls).toEqual([ expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "image/svg+xml"], ["Content-Type", "image/svg+xml"],
[ ["Cache-Control", `public, max-age=${CONSTANTS.FOUR_HOURS}`],
"Cache-Control",
`max-age=${CONSTANTS.FOUR_HOURS / 2}, s-maxage=${
CONSTANTS.FOUR_HOURS
}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
],
]); ]);
} }
}); });
@@ -235,7 +223,7 @@ describe("Test /api/", () => {
username: "anuraghazra", username: "anuraghazra",
count_private: true, count_private: true,
}, },
data_stats, data,
); );
await api(req, res); await api(req, res);
@@ -260,39 +248,4 @@ describe("Test /api/", () => {
), ),
); );
}); });
it("should allow changing ring_color", async () => {
const { req, res } = faker(
{
username: "anuraghazra",
hide: "issues,prs,contribs",
show_icons: true,
hide_border: true,
line_height: 100,
title_color: "fff",
ring_color: "0000ff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
},
data_stats,
);
await api(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toBeCalledWith(
renderStatsCard(stats, {
hide: ["issues", "prs", "contribs"],
show_icons: true,
hide_border: true,
line_height: 100,
title_color: "fff",
ring_color: "0000ff",
icon_color: "fff",
text_color: "fff",
bg_color: "fff",
}),
);
});
}); });
+1 -1
View File
@@ -13,6 +13,6 @@ describe("Test calculateRank", () => {
prs: 300, prs: 300,
issues: 200, issues: 200,
}), }),
).toStrictEqual({ level: "A+", score: 49.25629684876535 }); ).toStrictEqual({ level: "A+", score: 49.16605417270399 });
}); });
}); });
+1
View File
@@ -145,6 +145,7 @@ describe("Card", () => {
"#fff", "#fff",
); );
}); });
it("should render gradient backgrounds", () => { it("should render gradient backgrounds", () => {
const { titleColor, textColor, iconColor, bgColor } = getCardColors({ const { titleColor, textColor, iconColor, bgColor } = getCardColors({
title_color: "f00", title_color: "f00",
+24 -19
View File
@@ -11,22 +11,27 @@ import { renderStatsCard } from "../../src/cards/stats-card.js";
import { renderTopLanguages } from "../../src/cards/top-languages-card.js"; import { renderTopLanguages } from "../../src/cards/top-languages-card.js";
import { renderWakatimeCard } from "../../src/cards/wakatime-card.js"; import { renderWakatimeCard } from "../../src/cards/wakatime-card.js";
const REPO = "curly-fiesta"; const REPO = "dummy-cra";
const USER = "catelinemnemosyne"; const USER = "grsdummy";
const STATS_DATA = { const STATS_DATA = {
name: "Cateline Mnemosyne", name: "grsdummy",
totalPRs: 2, totalPRs: 2,
totalCommits: 8, totalCommits: 2,
totalIssues: 1, totalIssues: 1,
totalStars: 1, totalStars: 1,
contributedTo: 1, contributedTo: 2,
rank: { rank: {
level: "A+", level: "A+",
score: 50.88831151384285, score: 51.01013099671447,
}, },
}; };
const LANGS_DATA = { const LANGS_DATA = {
TypeScript: {
color: "#3178c6",
name: "TypeScript",
size: 2049,
},
HTML: { HTML: {
color: "#e34c26", color: "#e34c26",
name: "HTML", name: "HTML",
@@ -37,19 +42,19 @@ const LANGS_DATA = {
name: "CSS", name: "CSS",
size: 930, size: 930,
}, },
JavaScript: { Python: {
color: "#f1e05a", color: "#3572A5",
name: "JavaScript", name: "Python",
size: 1912, size: 671,
}, },
}; };
const WAKATIME_DATA = { const WAKATIME_DATA = {
human_readable_range: "last week", human_readable_range: "last week",
is_already_updating: false, is_already_updating: false,
is_coding_activity_visible: true, is_coding_activity_visible: false,
is_including_today: false, is_including_today: false,
is_other_usage_visible: true, is_other_usage_visible: false,
is_stuck: false, is_stuck: false,
is_up_to_date: false, is_up_to_date: false,
is_up_to_date_pending_future: false, is_up_to_date_pending_future: false,
@@ -57,24 +62,24 @@ const WAKATIME_DATA = {
range: "last_7_days", range: "last_7_days",
status: "pending_update", status: "pending_update",
timeout: 15, timeout: 15,
username: USER, username: "grsdummy",
writes_only: false, writes_only: false,
}; };
const REPOSITORY_DATA = { const REPOSITORY_DATA = {
name: REPO, name: "dummy-cra",
nameWithOwner: `${USER}/cra-test`, nameWithOwner: "grsdummy/dummy-cra",
isPrivate: false, isPrivate: false,
isArchived: false, isArchived: false,
isTemplate: false, isTemplate: false,
stargazers: { stargazers: {
totalCount: 1, totalCount: 1,
}, },
description: "Simple cra test repo.", description: "Dummy create react app.",
primaryLanguage: { primaryLanguage: {
color: "#f1e05a", color: "#3178c6",
id: "MDg6TGFuZ3VhZ2UxNDA=", id: "MDg6TGFuZ3VhZ2UyODc=",
name: "JavaScript", name: "TypeScript",
}, },
forkCount: 0, forkCount: 0,
starCount: 1, starCount: 1,
+34 -92
View File
@@ -4,8 +4,7 @@ import MockAdapter from "axios-mock-adapter";
import { calculateRank } from "../src/calculateRank.js"; import { calculateRank } from "../src/calculateRank.js";
import { fetchStats } from "../src/fetchers/stats-fetcher.js"; import { fetchStats } from "../src/fetchers/stats-fetcher.js";
// Test parameters. const data = {
const data_stats = {
data: { data: {
user: { user: {
name: "Anurag Hazra", name: "Anurag Hazra",
@@ -20,6 +19,15 @@ const data_stats = {
followers: { totalCount: 100 }, followers: { totalCount: 100 },
repositories: { repositories: {
totalCount: 5, totalCount: 5,
},
},
},
};
const firstRepositoriesData = {
data: {
user: {
repositories: {
nodes: [ nodes: [
{ name: "test-repo-1", stargazers: { totalCount: 100 } }, { name: "test-repo-1", stargazers: { totalCount: 100 } },
{ name: "test-repo-2", stargazers: { totalCount: 100 } }, { name: "test-repo-2", stargazers: { totalCount: 100 } },
@@ -34,7 +42,7 @@ const data_stats = {
}, },
}; };
const data_repo = { const secondRepositoriesData = {
data: { data: {
user: { user: {
repositories: { repositories: {
@@ -51,7 +59,7 @@ const data_repo = {
}, },
}; };
const data_repo_zero_stars = { const repositoriesWithZeroStarsData = {
data: { data: {
user: { user: {
repositories: { repositories: {
@@ -85,12 +93,13 @@ const error = {
const mock = new MockAdapter(axios); const mock = new MockAdapter(axios);
beforeEach(() => { beforeEach(() => {
process.env.FETCH_MULTI_PAGE_STARS = "false"; // Set to `false` to fetch only one page of stars.
mock mock
.onPost("https://api.github.com/graphql") .onPost("https://api.github.com/graphql")
.replyOnce(200, data_stats) .replyOnce(200, data)
.onPost("https://api.github.com/graphql") .onPost("https://api.github.com/graphql")
.replyOnce(200, data_repo); .replyOnce(200, firstRepositoriesData);
// .onPost("https://api.github.com/graphql") // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
// .replyOnce(200, secondRepositoriesData); // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
}); });
afterEach(() => { afterEach(() => {
@@ -105,7 +114,8 @@ describe("Test fetchStats", () => {
totalRepos: 5, totalRepos: 5,
followers: 100, followers: 100,
contributions: 61, contributions: 61,
stargazers: 300, // stargazers: 400, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
stargazers: 300, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
prs: 300, prs: 300,
issues: 200, issues: 200,
}); });
@@ -116,7 +126,8 @@ describe("Test fetchStats", () => {
totalCommits: 100, totalCommits: 100,
totalIssues: 200, totalIssues: 200,
totalPRs: 300, totalPRs: 300,
totalStars: 300, // totalStars: 400, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
totalStars: 300, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
rank, rank,
}); });
}); });
@@ -125,9 +136,9 @@ describe("Test fetchStats", () => {
mock.reset(); mock.reset();
mock mock
.onPost("https://api.github.com/graphql") .onPost("https://api.github.com/graphql")
.replyOnce(200, data_stats) .replyOnce(200, data)
.onPost("https://api.github.com/graphql") .onPost("https://api.github.com/graphql")
.replyOnce(200, data_repo_zero_stars); .replyOnce(200, repositoriesWithZeroStarsData);
let stats = await fetchStats("anuraghazra"); let stats = await fetchStats("anuraghazra");
const rank = calculateRank({ const rank = calculateRank({
@@ -167,7 +178,8 @@ describe("Test fetchStats", () => {
totalRepos: 5, totalRepos: 5,
followers: 100, followers: 100,
contributions: 61, contributions: 61,
stargazers: 300, // stargazers: 400, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
stargazers: 300, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
prs: 300, prs: 300,
issues: 200, issues: 200,
}); });
@@ -178,7 +190,8 @@ describe("Test fetchStats", () => {
totalCommits: 150, totalCommits: 150,
totalIssues: 200, totalIssues: 200,
totalPRs: 300, totalPRs: 300,
totalStars: 300, // totalStars: 400, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
totalStars: 300, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
rank, rank,
}); });
}); });
@@ -194,7 +207,8 @@ describe("Test fetchStats", () => {
totalRepos: 5, totalRepos: 5,
followers: 100, followers: 100,
contributions: 61, contributions: 61,
stargazers: 300, // stargazers: 400, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
stargazers: 300, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
prs: 300, prs: 300,
issues: 200, issues: 200,
}); });
@@ -205,7 +219,8 @@ describe("Test fetchStats", () => {
totalCommits: 1050, totalCommits: 1050,
totalIssues: 200, totalIssues: 200,
totalPRs: 300, totalPRs: 300,
totalStars: 300, // totalStars: 400, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
totalStars: 300, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
rank, rank,
}); });
}); });
@@ -221,7 +236,8 @@ describe("Test fetchStats", () => {
totalRepos: 5, totalRepos: 5,
followers: 100, followers: 100,
contributions: 61, contributions: 61,
stargazers: 200, // stargazers: 300, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
stargazers: 200, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
prs: 300, prs: 300,
issues: 200, issues: 200,
}); });
@@ -232,82 +248,8 @@ describe("Test fetchStats", () => {
totalCommits: 1050, totalCommits: 1050,
totalIssues: 200, totalIssues: 200,
totalPRs: 300, totalPRs: 300,
totalStars: 200, // totalStars: 300, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
rank, totalStars: 200, // NOTE: Temporarily disable fetching of multiple pages. Done because of #2130.
});
});
it("should fetch two pages of stars if 'FETCH_MULTI_PAGE_STARS' env variable is set to `true`", async () => {
process.env.FETCH_MULTI_PAGE_STARS = true;
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",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalStars: 400,
rank,
});
});
it("should fetch one page of stars if 'FETCH_MULTI_PAGE_STARS' env variable is set to `false`", async () => {
process.env.FETCH_MULTI_PAGE_STARS = "false";
let stats = await fetchStats("anuraghazra");
const rank = calculateRank({
totalCommits: 100,
totalRepos: 5,
followers: 100,
contributions: 61,
stargazers: 300,
prs: 300,
issues: 200,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalStars: 300,
rank,
});
});
it("should fetch one page of stars if 'FETCH_MULTI_PAGE_STARS' env variable is not set", async () => {
process.env.FETCH_MULTI_PAGE_STARS = undefined;
let stats = await fetchStats("anuraghazra");
const rank = calculateRank({
totalCommits: 100,
totalRepos: 5,
followers: 100,
contributions: 61,
stargazers: 300,
prs: 300,
issues: 200,
});
expect(stats).toStrictEqual({
contributedTo: 61,
name: "Anurag Hazra",
totalCommits: 100,
totalIssues: 200,
totalPRs: 300,
totalStars: 300,
rank, rank,
}); });
}); });
-244
View File
@@ -1,244 +0,0 @@
/**
* @file Tests for the status/pat-info cloud function.
*/
import dotenv from "dotenv";
dotenv.config();
import { jest } from "@jest/globals";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import patInfo, { RATE_LIMIT_SECONDS } from "../api/status/pat-info.js";
const mock = new MockAdapter(axios);
const successData = {
data: {
rateLimit: {
remaining: 4986,
},
},
};
const faker = (query) => {
const req = {
query: { ...query },
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
return { req, res };
};
const rate_limit_error = {
errors: [
{
type: "RATE_LIMITED",
message: "API rate limit exceeded for user ID.",
},
],
data: {
rateLimit: {
resetAt: Date.now(),
},
},
};
const other_error = {
errors: [
{
type: "SOME_ERROR",
message: "This is a error",
},
],
};
const bad_credentials_error = {
message: "Bad credentials",
};
afterEach(() => {
mock.reset();
});
describe("Test /api/status/pat-info", () => {
beforeAll(() => {
// reset patenv first so that dotenv doesn't populate them with local envs
process.env = {};
process.env.PAT_1 = "testPAT1";
process.env.PAT_2 = "testPAT2";
process.env.PAT_3 = "testPAT3";
process.env.PAT_4 = "testPAT4";
});
it("should return only 'validPATs' if all PATs are valid", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(200, rate_limit_error)
.onPost("https://api.github.com/graphql")
.reply(200, successData);
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(
JSON.stringify(
{
validPATs: ["PAT_2", "PAT_3", "PAT_4"],
expiredPATs: [],
exhaustedPATs: ["PAT_1"],
suspendedPATs: [],
errorPATs: [],
details: {
PAT_1: {
status: "exhausted",
remaining: 0,
resetIn: "0 minutes",
},
PAT_2: {
status: "valid",
remaining: 4986,
},
PAT_3: {
status: "valid",
remaining: 4986,
},
PAT_4: {
status: "valid",
remaining: 4986,
},
},
},
null,
2,
),
);
});
it("should return `errorPATs` if a PAT causes an error to be thrown", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(200, other_error)
.onPost("https://api.github.com/graphql")
.reply(200, successData);
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(
JSON.stringify(
{
validPATs: ["PAT_2", "PAT_3", "PAT_4"],
expiredPATs: [],
exhaustedPATs: [],
suspendedPATs: [],
errorPATs: ["PAT_1"],
details: {
PAT_1: {
status: "error",
error: {
type: "SOME_ERROR",
message: "This is a error",
},
},
PAT_2: {
status: "valid",
remaining: 4986,
},
PAT_3: {
status: "valid",
remaining: 4986,
},
PAT_4: {
status: "valid",
remaining: 4986,
},
},
},
null,
2,
),
);
});
it("should return `expiredPaths` if a PAT returns a 'Bad credentials' error", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(404, bad_credentials_error)
.onPost("https://api.github.com/graphql")
.reply(200, successData);
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(
JSON.stringify(
{
validPATs: ["PAT_2", "PAT_3", "PAT_4"],
expiredPATs: ["PAT_1"],
exhaustedPATs: [],
suspendedPATs: [],
errorPATs: [],
details: {
PAT_1: {
status: "expired",
},
PAT_2: {
status: "valid",
remaining: 4986,
},
PAT_3: {
status: "valid",
remaining: 4986,
},
PAT_4: {
status: "valid",
remaining: 4986,
},
},
},
null,
2,
),
);
});
it("should throw an error if something goes wrong", async () => {
mock.onPost("https://api.github.com/graphql").networkError();
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith("Something went wrong: Network Error");
});
it("should have proper cache when no error is thrown", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, successData);
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "application/json"],
["Cache-Control", `max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`],
]);
});
it("should have proper cache when error is thrown", async () => {
mock.reset();
mock.onPost("https://api.github.com/graphql").networkError();
const { req, res } = faker({}, {});
await patInfo(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "application/json"],
["Cache-Control", "no-store"],
]);
});
});
+10 -47
View File
@@ -78,17 +78,16 @@ describe("Test renderStatsCard", () => {
it("should render with custom width set", () => { it("should render with custom width set", () => {
document.body.innerHTML = renderStatsCard(stats); document.body.innerHTML = renderStatsCard(stats);
expect(document.querySelector("svg")).toHaveAttribute("width", "450"); expect(document.querySelector("svg")).toHaveAttribute("width", "495");
document.body.innerHTML = renderStatsCard(stats, { card_width: 500 }); document.body.innerHTML = renderStatsCard(stats, { card_width: 400 });
expect(document.querySelector("svg")).toHaveAttribute("width", "500"); expect(document.querySelector("svg")).toHaveAttribute("width", "400");
}); });
it("should render with custom width set and limit minimum width", () => { it("should render with custom width set and limit minimum width", () => {
document.body.innerHTML = renderStatsCard(stats, { card_width: 1 }); document.body.innerHTML = renderStatsCard(stats, { card_width: 1 });
expect(document.querySelector("svg")).toHaveAttribute("width", "420"); expect(document.querySelector("svg")).toHaveAttribute("width", "340");
// Test default minimum card width without rank circle.
document.body.innerHTML = renderStatsCard(stats, { document.body.innerHTML = renderStatsCard(stats, {
card_width: 1, card_width: 1,
hide_rank: true, hide_rank: true,
@@ -98,7 +97,6 @@ describe("Test renderStatsCard", () => {
"305.81250000000006", "305.81250000000006",
); );
// Test minimum card width with rank and icons.
document.body.innerHTML = renderStatsCard(stats, { document.body.innerHTML = renderStatsCard(stats, {
card_width: 1, card_width: 1,
hide_rank: true, hide_rank: true,
@@ -106,24 +104,22 @@ describe("Test renderStatsCard", () => {
}); });
expect(document.querySelector("svg")).toHaveAttribute( expect(document.querySelector("svg")).toHaveAttribute(
"width", "width",
"322.81250000000006", "305.81250000000006",
); );
// Test minimum card width with icons but without rank.
document.body.innerHTML = renderStatsCard(stats, { document.body.innerHTML = renderStatsCard(stats, {
card_width: 1, card_width: 1,
hide_rank: false, hide_rank: false,
show_icons: true, show_icons: true,
}); });
expect(document.querySelector("svg")).toHaveAttribute("width", "437"); expect(document.querySelector("svg")).toHaveAttribute("width", "356");
// Test minimum card width without icons or rank.
document.body.innerHTML = renderStatsCard(stats, { document.body.innerHTML = renderStatsCard(stats, {
card_width: 1, card_width: 1,
hide_rank: false, hide_rank: false,
show_icons: false, show_icons: false,
}); });
expect(document.querySelector("svg")).toHaveAttribute("width", "420"); expect(document.querySelector("svg")).toHaveAttribute("width", "340");
}); });
it("should render default colors properly", () => { it("should render default colors properly", () => {
@@ -243,39 +239,6 @@ describe("Test renderStatsCard", () => {
); );
}); });
it("should render custom ring_color properly", () => {
const customColors = {
title_color: "5a0",
ring_color: "0000ff",
icon_color: "1b998b",
text_color: "9991",
bg_color: "252525",
};
document.body.innerHTML = renderStatsCard(stats, { ...customColors });
const styleTag = document.querySelector("style");
const stylesObject = cssToObject(styleTag.innerHTML);
const headerClassStyles = stylesObject[":host"][".header "];
const statClassStyles = stylesObject[":host"][".stat "];
const iconClassStyles = stylesObject[":host"][".icon "];
const rankCircleStyles = stylesObject[":host"][".rank-circle "];
const rankCircleRimStyles = stylesObject[":host"][".rank-circle-rim "];
expect(headerClassStyles.fill.trim()).toBe(`#${customColors.title_color}`);
expect(statClassStyles.fill.trim()).toBe(`#${customColors.text_color}`);
expect(iconClassStyles.fill.trim()).toBe(`#${customColors.icon_color}`);
expect(rankCircleStyles.stroke.trim()).toBe(`#${customColors.ring_color}`);
expect(rankCircleRimStyles.stroke.trim()).toBe(
`#${customColors.ring_color}`,
);
expect(queryByTestId(document.body, "card-bg")).toHaveAttribute(
"fill",
"#252525",
);
});
it("should render icons correctly", () => { it("should render icons correctly", () => {
document.body.innerHTML = renderStatsCard(stats, { document.body.innerHTML = renderStatsCard(stats, {
show_icons: true, show_icons: true,
@@ -316,7 +279,7 @@ describe("Test renderStatsCard", () => {
expect( expect(
document.body.getElementsByTagName("svg")[0].getAttribute("width"), document.body.getElementsByTagName("svg")[0].getAttribute("width"),
).toBe("287"); ).toBe("270");
}); });
it("should render translations", () => { it("should render translations", () => {
@@ -333,7 +296,7 @@ describe("Test renderStatsCard", () => {
document.querySelector( document.querySelector(
'g[transform="translate(0, 25)"]>.stagger>.stat.bold', 'g[transform="translate(0, 25)"]>.stagger>.stat.bold',
).textContent, ).textContent,
).toMatchInlineSnapshot(`"累计提交数(commit (2023):"`); ).toMatchInlineSnapshot(`"累计提交数(commit (2022):"`);
expect( expect(
document.querySelector( document.querySelector(
'g[transform="translate(0, 50)"]>.stagger>.stat.bold', 'g[transform="translate(0, 50)"]>.stagger>.stat.bold',
@@ -348,7 +311,7 @@ describe("Test renderStatsCard", () => {
document.querySelector( document.querySelector(
'g[transform="translate(0, 100)"]>.stagger>.stat.bold', 'g[transform="translate(0, 100)"]>.stagger>.stat.bold',
).textContent, ).textContent,
).toMatchInlineSnapshot(`"参与项目数 (last year):"`); ).toMatchInlineSnapshot(`"参与项目数:"`);
}); });
it("should render without rounding", () => { it("should render without rounding", () => {
+3 -3
View File
@@ -216,7 +216,7 @@ describe("Test renderTopLanguages", () => {
); );
expect(queryAllByTestId(document.body, "lang-progress")[0]).toHaveAttribute( expect(queryAllByTestId(document.body, "lang-progress")[0]).toHaveAttribute(
"width", "width",
"100", "120",
); );
expect(queryAllByTestId(document.body, "lang-name")[1]).toHaveTextContent( expect(queryAllByTestId(document.body, "lang-name")[1]).toHaveTextContent(
@@ -224,7 +224,7 @@ describe("Test renderTopLanguages", () => {
); );
expect(queryAllByTestId(document.body, "lang-progress")[1]).toHaveAttribute( expect(queryAllByTestId(document.body, "lang-progress")[1]).toHaveAttribute(
"width", "width",
"100", "120",
); );
expect(queryAllByTestId(document.body, "lang-name")[2]).toHaveTextContent( expect(queryAllByTestId(document.body, "lang-name")[2]).toHaveTextContent(
@@ -232,7 +232,7 @@ describe("Test renderTopLanguages", () => {
); );
expect(queryAllByTestId(document.body, "lang-progress")[2]).toHaveAttribute( expect(queryAllByTestId(document.body, "lang-progress")[2]).toHaveAttribute(
"width", "width",
"50", "60",
); );
}); });
-9
View File
@@ -16,15 +16,6 @@ describe("Test Render Wakatime Card", () => {
expect(card).toMatchSnapshot(); expect(card).toMatchSnapshot();
}); });
it("should render correctly with compact layout when langs_count is set", () => {
const card = renderWakatimeCard(wakaTimeData.data, {
layout: "compact",
langs_count: 2,
});
expect(card).toMatchSnapshot();
});
it("should hide languages when hide is passed", () => { it("should hide languages when hide is passed", () => {
document.body.innerHTML = renderWakatimeCard(wakaTimeData.data, { document.body.innerHTML = renderWakatimeCard(wakaTimeData.data, {
hide: ["YAML", "Other"], hide: ["YAML", "Other"],
-194
View File
@@ -1,194 +0,0 @@
/**
* @file Tests for the status/up cloud function.
*/
import { jest } from "@jest/globals";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import up, { RATE_LIMIT_SECONDS } from "../api/status/up.js";
const mock = new MockAdapter(axios);
const successData = {
rateLimit: {
remaining: 4986,
},
};
const faker = (query) => {
const req = {
query: { ...query },
};
const res = {
setHeader: jest.fn(),
send: jest.fn(),
};
return { req, res };
};
const rate_limit_error = {
errors: [
{
type: "RATE_LIMITED",
},
],
};
const bad_credentials_error = {
message: "Bad credentials",
};
const shields_up = {
schemaVersion: 1,
label: "Public Instance",
isError: true,
message: "up",
color: "brightgreen",
};
const shields_down = {
schemaVersion: 1,
label: "Public Instance",
isError: true,
message: "down",
color: "red",
};
afterEach(() => {
mock.reset();
});
describe("Test /api/status/up", () => {
it("should return `true` if request was successful", async () => {
mock.onPost("https://api.github.com/graphql").replyOnce(200, successData);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(true);
});
it("should return `false` if all PATs are rate limited", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, rate_limit_error);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(false);
});
it("should return JSON `true` if request was successful and type='json'", async () => {
mock.onPost("https://api.github.com/graphql").replyOnce(200, successData);
const { req, res } = faker({ type: "json" }, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith({ up: true });
});
it("should return JSON `false` if all PATs are rate limited and type='json'", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, rate_limit_error);
const { req, res } = faker({ type: "json" }, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith({ up: false });
});
it("should return UP shields.io config if request was successful and type='shields'", async () => {
mock.onPost("https://api.github.com/graphql").replyOnce(200, successData);
const { req, res } = faker({ type: "shields" }, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(shields_up);
});
it("should return DOWN shields.io config if all PATs are rate limited and type='shields'", async () => {
mock.onPost("https://api.github.com/graphql").reply(200, rate_limit_error);
const { req, res } = faker({ type: "shields" }, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(shields_down);
});
it("should return `true` if the first PAT is rate limited but the second PATs works", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(200, rate_limit_error)
.onPost("https://api.github.com/graphql")
.replyOnce(200, successData);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(true);
});
it("should return `true` if the first PAT has 'Bad credentials' but the second PAT works", async () => {
mock
.onPost("https://api.github.com/graphql")
.replyOnce(404, bad_credentials_error)
.onPost("https://api.github.com/graphql")
.replyOnce(200, successData);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(true);
});
it("should return `false` if all pats have 'Bad credentials'", async () => {
mock
.onPost("https://api.github.com/graphql")
.reply(404, bad_credentials_error);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(false);
});
it("should throw an error if the request fails", async () => {
mock.onPost("https://api.github.com/graphql").networkError();
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader).toBeCalledWith("Content-Type", "application/json");
expect(res.send).toBeCalledWith(false);
});
it("should have proper cache when no error is thrown", async () => {
mock.onPost("https://api.github.com/graphql").replyOnce(200, successData);
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "application/json"],
["Cache-Control", `max-age=0, s-maxage=${RATE_LIMIT_SECONDS}`],
]);
});
it("should have proper cache when error is thrown", async () => {
mock.onPost("https://api.github.com/graphql").networkError();
const { req, res } = faker({}, {});
await up(req, res);
expect(res.setHeader.mock.calls).toEqual([
["Content-Type", "application/json"],
["Cache-Control", "no-store"],
]);
});
});
+151 -62
View File
@@ -1,48 +1,25 @@
import { queryByTestId } from "@testing-library/dom"; import { queryByTestId } from "@testing-library/dom";
import "@testing-library/jest-dom"; import "@testing-library/jest-dom";
import { import {
chunkArray,
clampValue,
encodeHTML, encodeHTML,
fallbackColor,
flexLayout,
getCardColors, getCardColors,
isValidGradient,
isValidHexColor,
kFormatter, kFormatter,
lowercaseTrim,
measureText,
parseArray,
parseBoolean, parseBoolean,
parseEmojis,
renderError, renderError,
wrapTextMultiline, wrapTextMultiline,
} from "../src/common/utils.js"; } from "../src/common/utils.js";
describe("Test utils.js", () => { describe("Test utils.js", () => {
it("should test kFormatter", () => {
expect(kFormatter(1)).toBe(1);
expect(kFormatter(-1)).toBe(-1);
expect(kFormatter(500)).toBe(500);
expect(kFormatter(1000)).toBe("1k");
expect(kFormatter(10000)).toBe("10k");
expect(kFormatter(12345)).toBe("12.3k");
expect(kFormatter(9900000)).toBe("9900k");
});
it("should test parseBoolean", () => {
expect(parseBoolean(true)).toBe(true);
expect(parseBoolean(false)).toBe(false);
expect(parseBoolean("true")).toBe(true);
expect(parseBoolean("false")).toBe(false);
expect(parseBoolean("True")).toBe(true);
expect(parseBoolean("False")).toBe(false);
expect(parseBoolean("TRUE")).toBe(true);
expect(parseBoolean("FALSE")).toBe(false);
expect(parseBoolean("1")).toBe(undefined);
expect(parseBoolean("0")).toBe(undefined);
expect(parseBoolean("")).toBe(undefined);
expect(parseBoolean(undefined)).toBe(undefined);
});
it("should test encodeHTML", () => {
expect(encodeHTML(`<html>hello world<,.#4^&^@%!))`)).toBe(
"&#60;html&#62;hello world&#60;,.#4^&#38;^@%!))",
);
});
it("should test renderError", () => { it("should test renderError", () => {
document.body.innerHTML = renderError("Something went wrong"); document.body.innerHTML = renderError("Something went wrong");
expect( expect(
@@ -62,11 +39,115 @@ describe("Test utils.js", () => {
).toHaveTextContent(/Secondary Message/gim); ).toHaveTextContent(/Secondary Message/gim);
}); });
it("should test encodeHTML", () => {
expect(encodeHTML(`<html>hello world<,.#4^&^@%!))`)).toBe(
"&#60;html&#62;hello world&#60;,.#4^&#38;^@%!))",
);
});
it("should test kFormatter", () => {
expect(kFormatter(1)).toBe(1);
expect(kFormatter(-1)).toBe(-1);
expect(kFormatter(500)).toBe(500);
expect(kFormatter(1000)).toBe("1k");
expect(kFormatter(10000)).toBe("10k");
expect(kFormatter(12345)).toBe("12.3k");
expect(kFormatter(9900000)).toBe("9900k");
});
it("should test isValidHexColor", () => {
expect(isValidHexColor("00f000")).toBe(true);
expect(isValidHexColor("00f0003f")).toBe(true);
expect(isValidHexColor("0f03")).toBe(true);
expect(isValidHexColor("0f0")).toBe(true);
expect(isValidHexColor("00f00X")).toBe(false);
expect(isValidHexColor("#")).toBe(false);
expect(isValidHexColor("")).toBe(false);
expect(isValidHexColor("0")).toBe(false);
expect(isValidHexColor("00")).toBe(false);
expect(isValidHexColor("00f00")).toBe(false);
expect(isValidHexColor("00f00")).toBe(false);
});
it("should test parseBoolean", () => {
expect(parseBoolean(true)).toBe(true);
expect(parseBoolean(false)).toBe(false);
expect(parseBoolean("true")).toBe(true);
expect(parseBoolean("false")).toBe(false);
expect(parseBoolean(undefined)).toBe(undefined);
});
it("should test parseArray", () => {
expect(parseArray("1")).toEqual(["1"]);
expect(parseArray("1,2,3")).toEqual(["1", "2", "3"]);
expect(parseArray("test")).toEqual(["test"]);
});
it("should test clampValue", () => {
expect(clampValue(1, 0, 2)).toBe(1);
expect(clampValue(1, 2, 3)).toBe(2);
expect(clampValue(1, 0, 0)).toBe(0);
expect(clampValue(1, 0, -1)).toBe(0);
});
it("should test isValidGradient", () => {
expect(isValidGradient(["90", "fff", "000"])).toBe(true);
expect(isValidGradient(["90", "fff", "000", "fff"])).toBe(true);
expect(isValidGradient(["fff", "fff", "fxf"])).toBe(false);
expect(isValidGradient(["90", "fff", "fxf"])).toBe(false);
expect(isValidGradient(["90", "fxf", ""])).toBe(false);
});
it("should test fallbackColor", () => {
expect(fallbackColor("fff", "000")).toBe("#fff");
expect(fallbackColor("fxf", "#000")).toBe("#000");
expect(fallbackColor("90,fff,000", "#000")).toStrictEqual([
"90",
"fff",
"000",
]);
expect(fallbackColor("90,fff,fxf", "#000")).toBe("#000");
});
it("should test flexLayout", () => {
const items = Array(2).fill(`<g></g>`);
const columnLayout = flexLayout({
items,
gap: 25,
direction: "column",
sizes: [],
});
expect(columnLayout[0]).toContain("translate(0, 0)");
expect(columnLayout[1]).toContain("translate(0, 25)");
const rowLayout = flexLayout({
items,
gap: 25,
direction: "row",
sizes: [],
});
expect(rowLayout[0]).toContain("translate(0, 0)");
expect(rowLayout[1]).toContain("translate(25, 0)");
const sizedLayout = flexLayout({
items,
gap: 25,
direction: "row",
sizes: [25, 0],
});
expect(sizedLayout[0]).toContain("translate(0, 0)");
expect(sizedLayout[1]).toContain("translate(50, 0)");
});
it("getCardColors: should return expected values", () => { it("getCardColors: should return expected values", () => {
let colors = getCardColors({ let colors = getCardColors({
title_color: "f00", title_color: "f00",
text_color: "0f0", text_color: "0f0",
ring_color: "0000ff",
icon_color: "00f", icon_color: "00f",
bg_color: "fff", bg_color: "fff",
border_color: "fff", border_color: "fff",
@@ -76,7 +157,6 @@ describe("Test utils.js", () => {
titleColor: "#f00", titleColor: "#f00",
textColor: "#0f0", textColor: "#0f0",
iconColor: "#00f", iconColor: "#00f",
ringColor: "#0000ff",
bgColor: "#fff", bgColor: "#fff",
borderColor: "#fff", borderColor: "#fff",
}); });
@@ -95,7 +175,6 @@ describe("Test utils.js", () => {
titleColor: "#2f80ed", titleColor: "#2f80ed",
textColor: "#0f0", textColor: "#0f0",
iconColor: "#00f", iconColor: "#00f",
ringColor: "#2f80ed",
bgColor: "#fff", bgColor: "#fff",
borderColor: "#e4e2e2", borderColor: "#e4e2e2",
}); });
@@ -108,41 +187,20 @@ describe("Test utils.js", () => {
expect(colors).toStrictEqual({ expect(colors).toStrictEqual({
titleColor: "#fff", titleColor: "#fff",
textColor: "#9f9f9f", textColor: "#9f9f9f",
ringColor: "#fff",
iconColor: "#79ff97", iconColor: "#79ff97",
bgColor: "#151515", bgColor: "#151515",
borderColor: "#e4e2e2", borderColor: "#e4e2e2",
}); });
}); });
it("getCardColors: should return ring color equal to title color if not ring color is defined", () => { it("wrapTextMultiline: should not wrap small texts", () => {
let colors = getCardColors({
title_color: "f00",
text_color: "0f0",
icon_color: "00f",
bg_color: "fff",
border_color: "fff",
theme: "dark",
});
expect(colors).toStrictEqual({
titleColor: "#f00",
textColor: "#0f0",
iconColor: "#00f",
ringColor: "#f00",
bgColor: "#fff",
borderColor: "#fff",
});
});
});
describe("wrapTextMultiline", () => {
it("should not wrap small texts", () => {
{ {
let multiLineText = wrapTextMultiline("Small text should not wrap"); let multiLineText = wrapTextMultiline("Small text should not wrap");
expect(multiLineText).toEqual(["Small text should not wrap"]); expect(multiLineText).toEqual(["Small text should not wrap"]);
} }
}); });
it("should wrap large texts", () => {
it("wrapTextMultiline: should wrap large texts", () => {
let multiLineText = wrapTextMultiline( let multiLineText = wrapTextMultiline(
"Hello world long long long text", "Hello world long long long text",
20, 20,
@@ -150,7 +208,8 @@ describe("wrapTextMultiline", () => {
); );
expect(multiLineText).toEqual(["Hello world long", "long long text"]); expect(multiLineText).toEqual(["Hello world long", "long long text"]);
}); });
it("should wrap large texts and limit max lines", () => {
it("wrapTextMultiline: should wrap large texts and limit max lines", () => {
let multiLineText = wrapTextMultiline( let multiLineText = wrapTextMultiline(
"Hello world long long long text", "Hello world long long long text",
10, 10,
@@ -158,11 +217,41 @@ describe("wrapTextMultiline", () => {
); );
expect(multiLineText).toEqual(["Hello", "world long..."]); expect(multiLineText).toEqual(["Hello", "world long..."]);
}); });
it("should wrap chinese by punctuation", () => {
it("wrapTextMultiline: should wrap chinese by punctuation", () => {
let multiLineText = wrapTextMultiline( let multiLineText = wrapTextMultiline(
"专门为刚开始刷题的同学准备的算法基地,没有最细只有更细,立志用动画将晦涩难懂的算法说的通俗易懂!", "专门为刚开始刷题的同学准备的算法基地,没有最细只有更细,立志用动画将晦涩难懂的算法说的通俗易懂!",
); );
expect(multiLineText.length).toEqual(3); expect(multiLineText.length).toEqual(3);
expect(multiLineText[0].length).toEqual(18 * 8); // &#xxxxx; x 8 expect(multiLineText[0].length).toEqual(18 * 8); // &#xxxxx; x 8
}); });
it("should test measureText", () => {
expect(measureText("test")).toEqual(16.078125);
expect(measureText("test", 12)).toEqual(19.293750000000003);
});
it("should test lowercaseTrim", () => {
expect(lowercaseTrim("test")).toEqual("test");
expect(lowercaseTrim(" test ")).toEqual("test");
expect(lowercaseTrim(" Test ")).toEqual("test");
});
it("should test chunkArray", () => {
expect(chunkArray([1, 2, 3], 1)).toEqual([[1], [2], [3]]);
expect(chunkArray([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
expect(chunkArray([1, 2, 3, 4, 5, 6, 7], 3)).toEqual([
[1, 2, 3],
[4, 5, 6],
[7],
]);
});
it("should test parseEmojis", () => {
expect(parseEmojis("test")).toEqual("test");
expect(parseEmojis("test :smile:")).toEqual("test 😄");
expect(parseEmojis("test :smile: :+1:")).toEqual("test 😄 👍");
expect(parseEmojis("test :smile: :+1: :smile:")).toEqual("test 😄 👍 😄");
});
}); });
-181
View File
@@ -12,12 +12,6 @@ export const themes = {
text_color: "434d58", text_color: "434d58",
bg_color: "fffefe", bg_color: "fffefe",
}, },
"default-repocard": {
title_color: "2f80ed",
icon_color: "586069", // icon color is different
text_color: "434d58",
bg_color: "fffefe",
},
transparent: { transparent: {
title_color: "006AFF", title_color: "006AFF",
icon_color: "0579C3", icon_color: "0579C3",
@@ -54,12 +48,6 @@ export const themes = {
text_color: "427b58", text_color: "427b58",
bg_color: "fbf1c7", bg_color: "fbf1c7",
}, },
"gruvbox-light": {
title_color: "b57614",
icon_color: "af3a03",
text_color: "427b58",
bg_color: "fbf1c7",
},
tokyonight: { tokyonight: {
title_color: "70a5fd", title_color: "70a5fd",
icon_color: "bf91f3", icon_color: "bf91f3",
@@ -120,24 +108,12 @@ export const themes = {
text_color: "fffefe", text_color: "fffefe",
bg_color: "273849", bg_color: "273849",
}, },
vue_dark: {
title_color: "41b883",
icon_color: "41b883",
text_color: "fffefe",
bg_color: "273849",
},
"shades-of-purple": { "shades-of-purple": {
title_color: "fad000", title_color: "fad000",
icon_color: "b362ff", icon_color: "b362ff",
text_color: "a599e9", text_color: "a599e9",
bg_color: "2d2b55", bg_color: "2d2b55",
}, },
shades_of_purple: {
title_color: "fad000",
icon_color: "b362ff",
text_color: "a599e9",
bg_color: "2d2b55",
},
nightowl: { nightowl: {
title_color: "c792ea", title_color: "c792ea",
icon_color: "ffeb95", icon_color: "ffeb95",
@@ -156,12 +132,6 @@ export const themes = {
text_color: "0cf574", text_color: "0cf574",
bg_color: "040f0f", bg_color: "040f0f",
}, },
blue_green: {
title_color: "2f97c1",
icon_color: "f5b700",
text_color: "0cf574",
bg_color: "040f0f",
},
algolia: { algolia: {
title_color: "00AEFF", title_color: "00AEFF",
icon_color: "2DDE98", icon_color: "2DDE98",
@@ -174,12 +144,6 @@ export const themes = {
text_color: "ffd95b", text_color: "ffd95b",
bg_color: "000000", bg_color: "000000",
}, },
great_gatsby: {
title_color: "ffa726",
icon_color: "ffb74d",
text_color: "ffd95b",
bg_color: "000000",
},
darcula: { darcula: {
title_color: "BA5F17", title_color: "BA5F17",
icon_color: "84628F", icon_color: "84628F",
@@ -210,24 +174,6 @@ export const themes = {
text_color: "fff", text_color: "fff",
bg_color: "000", bg_color: "000",
}, },
solarized_dark: {
title_color: "268bd2",
icon_color: "b58900",
text_color: "859900",
bg_color: "002b36",
},
solarized_light: {
title_color: "268bd2",
icon_color: "b58900",
text_color: "859900",
bg_color: "fdf6e3",
},
chartreuse_dark: {
title_color: "7fff00",
icon_color: "00AEFF",
text_color: "fff",
bg_color: "000",
},
nord: { nord: {
title_color: "81a1c1", title_color: "81a1c1",
text_color: "d8dee9", text_color: "d8dee9",
@@ -246,12 +192,6 @@ export const themes = {
text_color: "a6accd", text_color: "a6accd",
bg_color: "292d3e", bg_color: "292d3e",
}, },
material_palenight: {
title_color: "c792ea",
icon_color: "89ddff",
text_color: "a6accd",
bg_color: "292d3e",
},
graywhite: { graywhite: {
title_color: "24292e", title_color: "24292e",
icon_color: "24292e", icon_color: "24292e",
@@ -276,24 +216,6 @@ export const themes = {
text_color: "ffffff", text_color: "ffffff",
bg_color: "000000", bg_color: "000000",
}, },
vision_friendly_dark: {
title_color: "ffb000",
icon_color: "785ef0",
text_color: "ffffff",
bg_color: "000000",
},
ayu_mirage: {
title_color: "f4cd7c",
icon_color: "73d0ff",
text_color: "c7c8c2",
bg_color: "1f2430",
},
midnight_purple: {
title_color: "9745f5",
icon_color: "9f4bff",
text_color: "ffffff",
bg_color: "000000",
},
calm: { calm: {
title_color: "e07a5f", title_color: "e07a5f",
icon_color: "edae49", icon_color: "edae49",
@@ -306,12 +228,6 @@ export const themes = {
text_color: "509E2F", text_color: "509E2F",
bg_color: "ffffff", bg_color: "ffffff",
}, },
flag_india: {
title_color: "ff8f1c",
icon_color: "250E62",
text_color: "509E2F",
bg_color: "ffffff",
},
omni: { omni: {
title_color: "FF79C6", title_color: "FF79C6",
icon_color: "e7de79", icon_color: "e7de79",
@@ -360,12 +276,6 @@ export const themes = {
text_color: "d9c8a9", text_color: "d9c8a9",
bg_color: "402b23", bg_color: "402b23",
}, },
"kacho-ga": {
title_color: "bf4a3f",
icon_color: "a64833",
text_color: "d9c8a9",
bg_color: "402b23",
},
outrun: { outrun: {
title_color: "ffcc00", title_color: "ffcc00",
icon_color: "ff1aff", icon_color: "ff1aff",
@@ -384,18 +294,6 @@ export const themes = {
text_color: "718CA1", text_color: "718CA1",
bg_color: "1D252C", bg_color: "1D252C",
}, },
"ocean-dark": {
title_color: "8957B2",
icon_color: "FFFFFF",
text_color: "92D534",
bg_color: "151A28",
},
"city-lights": {
title_color: "5D8CB3",
icon_color: "4798FF",
text_color: "718CA1",
bg_color: "1D252C",
},
github_dark: { github_dark: {
title_color: "58A6FF", title_color: "58A6FF",
icon_color: "1F6FEB", icon_color: "1F6FEB",
@@ -414,24 +312,6 @@ export const themes = {
text_color: "dbdbdb", text_color: "dbdbdb",
bg_color: "252334", bg_color: "252334",
}, },
"github-dark": {
title_color: "58A6FF",
icon_color: "1F6FEB",
text_color: "C3D1D9",
bg_color: "0D1117",
},
"discord-old-blurple": {
title_color: "7289DA",
icon_color: "7289DA",
text_color: "FFFFFF",
bg_color: "2C2F33",
},
"aura-dark": {
title_color: "ff7372",
icon_color: "6cffd0",
text_color: "dbdbdb",
bg_color: "252334",
},
panda: { panda: {
title_color: "19f9d899", title_color: "19f9d899",
icon_color: "19f9d899", icon_color: "19f9d899",
@@ -444,12 +324,6 @@ export const themes = {
text_color: "c5cdd3", text_color: "c5cdd3",
bg_color: "1b2932", bg_color: "1b2932",
}, },
"noctis-minimus": {
title_color: "d3b692",
icon_color: "72b7c0",
text_color: "c5cdd3",
bg_color: "1b2932",
},
cobalt2: { cobalt2: {
title_color: "ffc600", title_color: "ffc600",
icon_color: "ffffff", icon_color: "ffffff",
@@ -493,61 +367,6 @@ export const themes = {
text_color: "e0def4", text_color: "e0def4",
bg_color: "191724", bg_color: "191724",
}, },
date_night: {
title_color: "DA7885",
text_color: "E1B2A2",
icon_color: "BB8470",
border_color: "170F0C",
bg_color: "170F0C",
},
one_dark_pro: {
title_color: "61AFEF",
text_color: "E5C06E",
icon_color: "C678DD",
border_color: "3B4048",
bg_color: "23272E",
},
"rose-pine": {
title_color: "9ccfd8",
icon_color: "ebbcba",
text_color: "e0def4",
bg_color: "191724",
},
"date-night": {
title_color: "DA7885",
text_color: "E1B2A2",
icon_color: "BB8470",
border_color: "170F0C",
bg_color: "170F0C",
},
"one-dark-pro": {
title_color: "61AFEF",
text_color: "E5C06E",
icon_color: "C678DD",
border_color: "3B4048",
bg_color: "23272E",
},
rose: {
title_color: "8d192b",
text_color: "862931",
icon_color: "B71F36",
border_color: "e9d8d4",
bg_color: "e9d8d4",
},
holi_theme: {
title_color: "5FABEE",
text_color: "D6E7FF",
icon_color: "5FABEE",
border_color: "85A4C0",
bg_color: "030314",
},
"holi-theme": {
title_color: "5FABEE",
text_color: "D6E7FF",
icon_color: "5FABEE",
border_color: "85A4C0",
bg_color: "030314",
},
}; };
export default themes; export default themes;
+1 -1
View File
@@ -2,7 +2,7 @@
"functions": { "functions": {
"api/*.js": { "api/*.js": {
"memory": 128, "memory": 128,
"maxDuration": 10 "maxDuration": 30
} }
}, },
"redirects": [ "redirects": [