Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .agents/skills/beachball-change-file/SKILL.md
12 changes: 2 additions & 10 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,6 @@ jobs:
# Don't save creds in the git config (so it's easier to override later)
persist-credentials: false

# Prereleases from main are disabled until the canary/prerelease flow is fixed
- name: Verify v2 branch
run: |
if [[ "${GITHUB_REF}" != "refs/heads/v2" ]]; then
echo "Releases can only be triggered from the v2 branch."
exit 1
fi

- name: Install Node.js ${{ env.nodeVersion }}
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
with:
Expand All @@ -54,7 +46,8 @@ jobs:
- run: yarn test --verbose

# TODO (release): switch back to regular release
- name: Publish packages
# (temporarily add yarn release:canary when ready)
- name: Publish packages (non-prerelease)
run: |
git config user.email "kchau@microsoft.com"
Comment thread
ecraig12345 marked this conversation as resolved.
Comment on lines 48 to 52
git config user.name "Ken Chau"
Expand All @@ -66,7 +59,6 @@ jobs:
# Add a token to the remote URL for auth during release
git remote set-url origin "https://$REPO_PAT@github.com/$GITHUB_REPOSITORY"

yarn release:canary
yarn release:others
env:
REPO_PAT: ${{ secrets.REPO_PAT }}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "Initial release",
"packageName": "proper-changelog",
"email": "elcraig@microsoft.com",
"dependentChangeType": "patch"
}
7 changes: 7 additions & 0 deletions packages/proper-changelog/.depcheckrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
ignore-path: ../../.gitignore

ignores:
# used in scripts
- cross-env
# specified at root
- '@jest/globals'
63 changes: 63 additions & 0 deletions packages/proper-changelog/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# proper-changelog

GitHub releases are useful in some ways, but they're horrible as changelogs if you need to look at changes across multiple versions or figure out when a specific change was introduced. This tool reads GitHub releases and generates a single markdown changelog.

## Usage

```bash
# By GitHub repository
npx proper-changelog --repo <owner>/<repo>

# By npm package name (the GitHub repository is read from the latest published version)
npx proper-changelog --package <package-name>
```

Exactly one of `--repo` or `--package` is required.

Releases are listed newest-first by published date. Draft releases are always excluded, and prereleases are excluded unless `--include-prereleases` is passed.

By default this writes the changelog to `CHANGELOG-<package-or-repo>.md` in the current directory (using the package name when `--package` is given, otherwise the repo name). Use `--stdout` to print it instead, or `--out` to choose a different file name.

```bash
# Write to a custom file
npx proper-changelog --repo microsoft/beachball --out CHANGELOG.md

# Print to stdout
npx proper-changelog --repo microsoft/beachball --stdout

# Resolve the repository from an npm package
npx proper-changelog --package @fluentui/react --stdout
```

## Options

Either `--package` or `--repo` is required, and they're mutually exclusive.

<!-- prettier-ignore -->
| Option | Description |
| ------ | ----------- |
| `--repo <owner/repo>` | GitHub repository to read releases from. |
| `--package <name>` | npm package whose GitHub repository should be used (read from the latest published version on npmjs.com; only supports github.com repos). Note that for a monorepo, this does **not** do any filtering of releases by package. |
| `-o, --out <file>` | Output file name (default: `CHANGELOG-<package-or-repo>.md`). Mutually exclusive with `--stdout`. |
| `--stdout` | Write the changelog to stdout instead of a file. Mutually exclusive with `--out`. |
| `--token <token>` | GitHub token (see [Authentication](#authentication)). |
| `--include-prereleases` | Include prerelease releases. Draft releases are always excluded. |
| `--from <tag>` | Include releases up to and including this tag (based on date, **not** semver). |
| `--to <tag>` | Include releases down to and including this tag (based on date, **not** semver). |
| `--limit <n>` | Maximum number of releases to include. |
| `--filter <pattern>` | Only include releases whose **tag** matches `<pattern>`. A plain string matches tags containing it (case-insensitive); wrap the value in slashes (e.g. `/^v1\./i`) to match with a regular expression. Useful for monorepos that tag releases per package. (Warning: this is _not_ sanitized, so ReDOS yourself at will.) |
| `--since <date>` | Only include releases published after this date. Accepts any value parseable by `new Date()`, such as `2024-01-01`. |

## Authentication

The GitHub API is rate-limited for unauthenticated requests. To use a token, the tool checks the following in order:

1. The `--token` option
2. The `GITHUB_TOKEN` or `GH_TOKEN` environment variables
3. The output of `gh auth token` (if the [GitHub CLI](https://cli.github.com/) is installed and authenticated)

If no token is found, the tool prints a warning and continues unauthenticated.

## API

The package currently does not have an importable API. If you want this, please open a feature request describing your use case.
4 changes: 4 additions & 0 deletions packages/proper-changelog/bin/proper-changelog.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env node
import { cli } from '../lib/cli.js';

cli();
4 changes: 4 additions & 0 deletions packages/proper-changelog/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// @ts-check
import { getConfig } from '@microsoft/beachball-scripts/config/eslint.ts';

export default getConfig(import.meta.dirname);
4 changes: 4 additions & 0 deletions packages/proper-changelog/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// @ts-check
import { getESMConfig } from '@microsoft/beachball-scripts/config/jest.cjs';

export default getESMConfig();
40 changes: 40 additions & 0 deletions packages/proper-changelog/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "proper-changelog",
"version": "0.1.0",
"description": "Make a readable changelog from GitHub releases",
"type": "module",
"repository": {
"type": "git",
"url": "https://github.com/microsoft/beachball",
"directory": "packages/proper-changelog"
},
"license": "MIT",
"exports": {
".": null
},
"bin": "./bin/proper-changelog.js",
"engines": {
"node": ">=22.18.0"
},
"files": [
"bin",
"lib/!(__*)",
"lib/!(__*)/**/*"
],
"scripts": {
"build": "yarn run -T tsc --pretty",
"depcheck": "yarn run -T depcheck .",
"lint": "yarn run -T eslint --color --max-warnings=0 src",
"test": "cross-env NODE_OPTIONS='--experimental-vm-modules' yarn run -T jest",
"update-snapshots": "yarn test -u"
},
"devDependencies": {
"@microsoft/beachball-scripts": "workspace:^",
"@octokit/openapi-types": "^27.0.0",
"cross-env": "^10.1.0"
},
"dependencies": {
"commander": "^15.0.0",
"nano-spawn": "^2.1.0"
}
}
17 changes: 17 additions & 0 deletions packages/proper-changelog/src/__fixtures__/getContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { jest } from '@jest/globals';
import type { CliContext } from '../types.ts';

/** Get a context which mocks all functions and throws on `exitOverride` */
export function getContext(args: string[], env: NodeJS.ProcessEnv = {}): jest.Mocked<Required<CliContext>> {
return {
argv: ['node', 'proper-changelog.js', ...args],
env,
log: jest.fn(),
warn: jest.fn(),
writeFile: jest.fn(),
writeErr: jest.fn(),
exitOverride: jest.fn(err => {
throw err;
}),
};
}
30 changes: 30 additions & 0 deletions packages/proper-changelog/src/__fixtures__/makeRelease.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { GitHubRelease } from '../types.ts';

/**
* Create a {@link GitHubRelease} fixture with sensible defaults, overriding only the fields
* relevant to a given test.
*/
export function makeRelease(overrides: Partial<GitHubRelease> = {}): GitHubRelease {
const tag = overrides.tag_name ?? 'v1.0.0';
return {
url: 'https://api.github.com/repos/microsoft/some-repo/releases/1',
html_url: `https://github.com/microsoft/some-repo/releases/tag/${tag}`,
assets_url: '',
upload_url: '',
tarball_url: null,
zipball_url: null,
id: 1,
node_id: 'node',
tag_name: tag,
target_commitish: 'main',
name: tag,
body: '',
draft: false,
prerelease: false,
created_at: '2024-01-01T00:00:00Z',
published_at: '2024-01-01T00:00:00Z',
author: {} as GitHubRelease['author'], // not used
assets: [],
...overrides,
};
}
82 changes: 82 additions & 0 deletions packages/proper-changelog/src/__tests__/cli.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { afterEach, describe, expect, it, jest } from '@jest/globals';
import { makeRelease } from '../__fixtures__/makeRelease.ts';
import type * as fetchReleasesModule from '../fetchReleases.ts';
import { getContext } from '../__fixtures__/getContext.ts';

jest.unstable_mockModule<typeof fetchReleasesModule>('../fetchReleases.ts', () => ({
fetchReleases: jest.fn(() => Promise.resolve([])),
}));
const mockFetchReleases = (await import('../fetchReleases.ts')).fetchReleases as jest.MockedFunction<
typeof fetchReleasesModule.fetchReleases
>;

const { _generateChangelog } = await import('../cli.ts');

describe('cli _generateChangelog', () => {
const repo = { owner: 'microsoft', repo: 'beachball' };

afterEach(() => {
mockFetchReleases.mockResolvedValue([]);
});

it('warns and writes nothing when there are no releases', async () => {
mockFetchReleases.mockResolvedValue([]);
const context = getContext([]);
await _generateChangelog({ repo }, context);

expect(mockFetchReleases).toHaveBeenCalledWith(repo, undefined);
expect(context.warn).toHaveBeenCalledWith('No releases found for microsoft/beachball');
expect(context.writeFile).not.toHaveBeenCalled();
expect(context.log).not.toHaveBeenCalled();
});

it('writes to the default CHANGELOG-<repo>.md file and logs the path', async () => {
mockFetchReleases.mockResolvedValue([makeRelease({ tag_name: 'v1.0.0' })]);
const context = getContext([]);
await _generateChangelog({ repo }, context);

expect(context.writeFile).toHaveBeenCalledWith(
'CHANGELOG-beachball.md',
expect.stringContaining('# Changelog - beachball')
);
expect(context.log).toHaveBeenCalledWith('Wrote changelog to CHANGELOG-beachball.md');
});

it('derives the default file name from the package name when given', async () => {
mockFetchReleases.mockResolvedValue([makeRelease({ tag_name: 'v1.0.0' })]);
const context = getContext([]);
await _generateChangelog({ repo, package: '@fluentui/react' }, context);

expect(context.writeFile).toHaveBeenCalledWith(
'CHANGELOG-fluentui-react.md',
expect.stringContaining('# Changelog -')
);
expect(context.log).toHaveBeenCalledWith('Wrote changelog to CHANGELOG-fluentui-react.md');
});

it('writes to a custom file name when --out is given', async () => {
mockFetchReleases.mockResolvedValue([makeRelease({ tag_name: 'v1.0.0' })]);
const context = getContext([]);
await _generateChangelog({ repo, out: 'CUSTOM.md' }, context);

expect(context.writeFile).toHaveBeenCalledWith('CUSTOM.md', expect.stringContaining('# Changelog -'));
expect(context.log).toHaveBeenCalledWith('Wrote changelog to CUSTOM.md');
});

it('writes to stdout instead of a file when stdout is set', async () => {
mockFetchReleases.mockResolvedValue([makeRelease({ tag_name: 'v1.0.0' })]);
const context = getContext([]);
await _generateChangelog({ repo, stdout: true }, context);

expect(context.writeFile).not.toHaveBeenCalled();
expect(context.log).toHaveBeenCalledWith(expect.stringContaining('# Changelog -'));
});

it('passes the token to fetchReleases', async () => {
mockFetchReleases.mockResolvedValue([makeRelease({ tag_name: 'v1.0.0' })]);
const context = getContext([]);
await _generateChangelog({ repo, token: 'secret-token' }, context);

expect(mockFetchReleases).toHaveBeenCalledWith(repo, 'secret-token');
});
});
80 changes: 80 additions & 0 deletions packages/proper-changelog/src/__tests__/fetchReleases.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
import { fetchReleases } from '../fetchReleases.ts';
import { makeRelease } from '../__fixtures__/makeRelease.ts';

const repo = { owner: 'microsoft', repo: 'some-repo' };
const apiUrl = `https://api.github.com/repos/${repo.owner}/${repo.repo}/releases?per_page=100`;

describe('fetchReleases', () => {
const originalFetch = global.fetch;

beforeEach(() => {
global.fetch = jest.fn() as typeof fetch;
});

afterEach(() => {
global.fetch = originalFetch;
});

function mockResponse(body: unknown, init: { link?: string; ok?: boolean; status?: number } = {}): Response {
const headers = new Headers();
if (init.link) {
headers.set('link', init.link);
}
return {
ok: init.ok ?? true,
status: init.status ?? 200,
statusText: 'OK',
headers,
json: () => Promise.resolve(body),
text: () => Promise.resolve(JSON.stringify(body)),
} as Response;
}

it('requests the releases endpoint without an Authorization header when no token is given', async () => {
const fetchMock = global.fetch as jest.MockedFunction<typeof fetch>;
fetchMock.mockResolvedValueOnce(mockResponse([makeRelease({ tag_name: 'v1.0.0' })]));

const releases = await fetchReleases(repo);

expect(releases.map(r => r.tag_name)).toEqual(['v1.0.0']);
const [url, requestInit] = fetchMock.mock.calls[0];
expect(url).toBe(apiUrl);
const headers = (requestInit as RequestInit).headers as Record<string, string>;
expect(headers.Authorization).toBeUndefined();
});

it('sends a bearer token when one is provided', async () => {
const fetchMock = global.fetch as jest.MockedFunction<typeof fetch>;
fetchMock.mockResolvedValueOnce(mockResponse([]));

await fetchReleases(repo, 'secret-token');

const headers = (fetchMock.mock.calls[0][1] as RequestInit).headers as Record<string, string>;
expect(headers.Authorization).toBe('Bearer secret-token');
});

it('follows pagination via the Link header', async () => {
const fetchMock = global.fetch as jest.MockedFunction<typeof fetch>;
fetchMock
.mockResolvedValueOnce(
mockResponse([makeRelease({ tag_name: 'v2.0.0' })], {
link: `<${apiUrl}&page=2>; rel="next"`,
})
)
.mockResolvedValueOnce(mockResponse([makeRelease({ tag_name: 'v1.0.0' })]));

const releases = await fetchReleases(repo);

expect(releases.map(r => r.tag_name)).toEqual(['v2.0.0', 'v1.0.0']);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock.mock.calls[1][0]).toBe(`${apiUrl}&page=2`);
});

it('throws a descriptive error on a non-OK response', async () => {
const fetchMock = global.fetch as jest.MockedFunction<typeof fetch>;
fetchMock.mockResolvedValueOnce(mockResponse({ message: 'Not Found' }, { ok: false, status: 404 }));

await expect(fetchReleases(repo)).rejects.toThrow('Failed to fetch releases for microsoft/some-repo: 404');
});
});
Loading
Loading