Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ on:
pull_request:
branches: [main]

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
Expand All @@ -17,13 +20,13 @@ jobs:
node-version: [22.x]
steps:
- uses: actions/checkout@v4
- name: create env file
run: |
touch .env
echo TOKEN=${{ secrets.TOKEN }} >> .env
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
# Pass the secret through env rather than interpolating it into a
# script or writing it to a .env file on disk.
- run: npm test
env:
TOKEN: ${{ secrets.TOKEN }}
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Please refer to the updated link [here](#how-to-use)
- [Available Themes](#available-themes)
- [Customization](#customization)
- [Common Options](#common-options)
- [Use as a GitHub Action](#use-as-a-github-action)
- [Deploy on your own Replit instance](#deploy-on-your-own-replit-instance)
- [Follow the steps](#follow-the-steps)
- [Deploy on your own Vercel instance](#deploy-on-your-own-vercel-instance)
Expand Down Expand Up @@ -123,6 +124,49 @@ Example:
[![Ashutosh's github activity graph](https://github-readme-activity-graph.vercel.app/graph?username=ashutosh00710&bg_color=fffff0&color=708090&line=24292e&point=24292e&area=true&border_color=ff0000)](https://github.com/ashutosh00710/github-readme-activity-graph)
```

## Use as a GitHub Action

Instead of relying on a hosted instance, you can render the graph to an SVG file in your own workflow and commit it to your profile repository.

```yaml
name: Activity Graph

on:
schedule:
- cron: '0 0 * * *' # once a day
workflow_dispatch:

permissions:
contents: write

jobs:
graph:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: Ashutosh00710/github-readme-activity-graph@main
with:
username: ${{ github.repository_owner }}
token: ${{ secrets.GITHUB_TOKEN }}
output_path: profile/activity-graph.svg
theme: github-light
- name: Commit graph
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add profile/activity-graph.svg
git diff --cached --quiet || git commit -m "Update activity graph"
git push
```

Then reference the file from your README:

```md
![Activity Graph](profile/activity-graph.svg)
```

Every option from [Common Options](#common-options) is available as an input with the same name (`custom_title`, `hide_border`, `days`, `area`, `bg_color`, ...). See [`action.yml`](action.yml) for the full list. `secrets.GITHUB_TOKEN` only sees public activity; use a personal access token to include private contributions. If fetching fails, the step fails instead of writing an error image.

## Deploy on your own Replit instance

<details>
Expand Down
2 changes: 1 addition & 1 deletion __test__/__snapshots__/svgs.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ exports[`SVG Testing Test SVGs 1`] = `
graphSvg
</h1>
</foreignObject>
[object Promise]
line
</svg>
"
`;
Expand Down
86 changes: 86 additions & 0 deletions __test__/cli.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { promises as fs } from 'fs';
import os from 'os';
import path from 'path';
import { optionsFromEnv, run } from '../src/cli';
import { Fetcher } from '../src/fetcher';

jest.mock('../src/fetcher');
const mockFetch = Fetcher.prototype.fetchContributions as jest.Mock;

const contributions = Array.from({ length: 31 }, (_, i) => ({
contributionCount: i % 5,
date: String(i + 1),
}));

describe('CLI Tests', () => {
let dir: string;
beforeEach(async () => {
dir = await fs.mkdtemp(path.join(os.tmpdir(), 'activity-graph-'));
mockFetch.mockReset();
});
afterEach(() => fs.rm(dir, { recursive: true, force: true }));

it('maps ACTIVITY_* variables to query options', () => {
expect(
optionsFromEnv({
ACTIVITY_USERNAME: 'octocat',
ACTIVITY_THEME: 'github-light',
ACTIVITY_CUSTOM_TITLE: "Octocat's graph",
ACTIVITY_HIDE_BORDER: 'TRUE',
ACTIVITY_AREA: 'false',
ACTIVITY_RADIUS: '8',
ACTIVITY_DAYS: '60',
}),
).toEqual({
username: 'octocat',
theme: 'github-light',
custom_title: "Octocat's graph",
hide_border: true,
area: false,
radius: 8,
days: '60',
});
});

it('treats empty action inputs as unset', () => {
expect(
optionsFromEnv({
ACTIVITY_USERNAME: 'octocat',
ACTIVITY_THEME: '',
ACTIVITY_HEIGHT: '',
ACTIVITY_HIDE_TITLE: ' ',
}),
).toEqual({ username: 'octocat' });
});

it('writes the graph SVG to output_path, creating directories', async () => {
mockFetch.mockResolvedValue({ name: 'The Octocat', contributions });
const outputPath = path.join(dir, 'nested', 'graph.svg');

await run({
TOKEN: 'token',
ACTIVITY_USERNAME: 'octocat',
ACTIVITY_OUTPUT_PATH: outputPath,
});

const svg = await fs.readFile(outputPath, 'utf8');
expect(svg).toContain('<svg');
expect(svg).toContain("The Octocat's Contribution Graph");
expect(mockFetch).toHaveBeenCalledWith(31, '', '');
});

it('fails instead of writing the error SVG when fetching fails', async () => {
mockFetch.mockResolvedValue(`Can't fetch any contribution. Please check your username 😬`);
const outputPath = path.join(dir, 'graph.svg');

await expect(
run({ TOKEN: 'token', ACTIVITY_USERNAME: 'nobody', ACTIVITY_OUTPUT_PATH: outputPath }),
).rejects.toThrow("Can't fetch any contribution");
await expect(fs.access(outputPath)).rejects.toThrow();
});

it('requires a username and a token', async () => {
await expect(run({ TOKEN: 'token' })).rejects.toThrow('ACTIVITY_USERNAME is required');
await expect(run({ ACTIVITY_USERNAME: 'octocat' })).rejects.toThrow('TOKEN is required');
});
});
2 changes: 1 addition & 1 deletion __test__/fakeInputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ export let fakeGraphArgs: GraphArgs = {
pointColor: 'bd93f9',
},
title: 'graphSvg',
line: Promise.resolve('line'),
line: 'line',
};

export let options = {
Expand Down
35 changes: 35 additions & 0 deletions __test__/fetching.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { format } from 'util';
import { Fetcher } from '../src/fetcher';
import {
mockQueryCorrect,
Expand Down Expand Up @@ -51,3 +52,37 @@ describe('Fetching Tests', () => {
});
});
});

describe('Fetching error logging', () => {
// format() renders arguments the same way console.log does
const logged = (spy: jest.SpyInstance) =>
spy.mock.calls.map((args) => format(...args)).join('\n');

it('never logs the token carried on a failed request', async () => {
const token = 'ghp_secretTokenValue123';
// axios attaches the request config, including headers, to thrown errors
const error = Object.assign(new Error('Request failed with status code 401'), {
config: { headers: { Authorization: `bearer ${token}` } },
});
const fetcher = new Fetcher('octocat');
// @ts-ignore: mocking private method
fetcher.fetch = jest.fn().mockRejectedValue(error);
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});

try {
await fetcher.fetchContributions(31);
await fetcher.fetchContributions(31);
// @ts-ignore: mocking private method
fetcher.fetch = jest.fn().mockRejectedValue(error.config);
await fetcher.fetchContributions(31);

const output = logged(logSpy) + logged(errorSpy);
expect(output).toContain('Request failed with status code 401');
expect(output).not.toContain(token);
} finally {
logSpy.mockRestore();
errorSpy.mockRestore();
}
});
});
69 changes: 69 additions & 0 deletions __test__/injection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { Utilities } from '../src/utils';
import { escapeXml } from '../src/svgs';
import { selectColors } from '../src/styles/themes';

const contributions = Array.from({ length: 31 }, (_, i) => ({
contributionCount: i % 5,
date: String(i + 1),
}));

describe('SVG injection', () => {
it('escapes markup in text', () => {
expect(escapeXml('<script>alert("x")</script> & co')).toEqual(
'&lt;script&gt;alert("x")&lt;/script&gt; &amp; co',
);
});

it('escapes custom_title in the rendered graph', async () => {
const utils = new Utilities({
username: 'octocat',
custom_title: '<script>alert(1)</script>',
});
const { finalGraph } = await utils.buildGraph({ name: 'The Octocat', contributions });
expect(finalGraph).not.toContain('<script>');
expect(finalGraph).toContain('&lt;script&gt;alert(1)&lt;/script&gt;');
});

it('escapes the GitHub display name in the default title', async () => {
const utils = new Utilities({ username: 'octocat' });
const { finalGraph } = await utils.buildGraph({
name: '<img src=x onerror=alert(1)>',
contributions,
});
expect(finalGraph).not.toContain('<img');
});

it('ignores color values that are not hex codes', () => {
const injection = 'fff}</style><script>alert(1)</script><style>';
const { colors } = new Utilities({
username: 'octocat',
bg_color: injection,
color: injection,
title_color: injection,
line: 'red;background:url(x)',
point: '#fff',
area_color: '',
border_color: injection,
}).queryOptions();
expect(colors).toEqual(selectColors('default'));
});

it('keeps valid hex colors', () => {
const { colors } = new Utilities({
username: 'octocat',
bg_color: 'fffff0',
color: '708090',
line: '24292E',
point: 'abc',
border_color: 'ff000080',
}).queryOptions();
expect(colors).toMatchObject({
bgColor: 'fffff0',
color: '708090',
titleColor: '708090',
lineColor: '24292E',
pointColor: 'abc',
borderColor: 'ff000080',
});
});
});
2 changes: 1 addition & 1 deletion __test__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ describe('Utilities Test', () => {
date: '5',
},
];
const graph: Promise<string> = await createGraph('line', options, {
const graph: string = await createGraph('line', options, {
labels: days.map((day) => day.date),
series: [{ value: days.map((day) => day.contributionCount) }],
});
Expand Down
Loading