From 59d196ccf22a7130e112455f1e1bed82a150e8f4 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:24:45 +0000 Subject: [PATCH] feat(changelog): Let workspaces own or exclude unowned paths Add changelog.unownedPaths (include, exclude, own) so a root application can claim files outside every workspace, or a package can ignore them. Start a workspace's first changelog at the commit that added it to .craft.yml instead of the full repository history, and log how many commits Craft reads when no previous tag exists. Co-Authored-By: BYK --- docs/src/content/docs/configuration.md | 32 +++++ src/__tests__/config.test.ts | 12 ++ src/config.ts | 78 ++++++++-- src/schemas/project_config.ts | 11 ++ .../__tests__/changelog-generate.test.ts | 2 + src/utils/__tests__/git.test.ts | 134 ++++++++++++++++++ src/utils/git.ts | 129 ++++++++++++++++- 7 files changed, 381 insertions(+), 17 deletions(-) diff --git a/docs/src/content/docs/configuration.md b/docs/src/content/docs/configuration.md index 9e9867598..509760d85 100644 --- a/docs/src/content/docs/configuration.md +++ b/docs/src/content/docs/configuration.md @@ -590,6 +590,37 @@ workspaces: Most workspaces need no `includePaths` setting. +Files outside every workspace, such as root build files or an application that +lives at the repository root, count as shared by default. Use +`changelog.unownedPaths` to change that: + +- `include` (default): shared files appear in this workspace's changelog. +- `exclude`: this workspace ignores shared files. +- `own`: this workspace owns them, and every other workspace ignores them. At + most one workspace can use `own`. + +For example, when the main application lives at the repository root next to +independently released packages: + +```yaml +workspaces: + app: + changelog: + policy: auto + unownedPaths: own + packages/ui: + changelog: + policy: auto +``` + +`app` gets commits to root files, and `packages/ui` gets only commits that touch +`packages/ui`. + +A workspace's first release has no previous tag. Craft then starts its +changelog at the commit that added the workspace to `.craft.yml` instead of the +start of the repository history. Push a tag with the workspace's tag prefix to +start from a different commit. + ### Title Stripping (Default Behavior) By default, conventional commit prefixes are stripped from changelog entries. @@ -656,6 +687,7 @@ changelog: | `changelog.policy` | Mode: `none`, `simple`, or `auto`. Default: `none` | | `changelog.scopeGrouping` | Enable scope-based grouping. Default: `true` | | `changelog.includePaths` | Extra workspace directories to include in automatic changelogs. Default: `[]` | +| `changelog.unownedPaths` | `include`, `exclude`, or `own` files outside every workspace. Default: `include` | | `changelog.aiSummary` | Opt-in HTTP release, category, and scope summaries. Default: disabled. | ## Versioning diff --git a/src/__tests__/config.test.ts b/src/__tests__/config.test.ts index 1b3ae6c9b..5558f0ae9 100644 --- a/src/__tests__/config.test.ts +++ b/src/__tests__/config.test.ts @@ -94,6 +94,7 @@ describe('validateConfiguration', () => { policy: 'auto', scopeGrouping: true, includePaths: ['apps/cli-docs'], + unownedPaths: 'own', }, }; @@ -299,6 +300,17 @@ describe('validateConfiguration', () => { validateConfiguration({ changelog: { includePaths: [includePath] } }), ).toThrow(/changelog/); }); + + test('rejects an unknown unowned paths policy', () => { + expect(() => + validateConfiguration({ changelog: { unownedPaths: 'shared' } }), + ).toThrow(/changelog/); + }); + + test('includes unowned paths by default', () => { + loadConfigurationFromString('changelog:\n policy: auto'); + expect(getChangelogConfig().unownedPaths).toBe('include'); + }); }); describe('CraftProjectConfigSchema', () => { diff --git a/src/config.ts b/src/config.ts index a444c37ff..940cb9c4c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -19,6 +19,7 @@ import { VersioningPolicy, Workspace, type AiSummaryConfig, + type UnownedPathsPolicy, } from './schemas/project_config'; import { ConfigurationError } from './utils/errors'; import { isCompiledGitHubAction } from './utils/detection'; @@ -622,21 +623,71 @@ export function loadConfigurationFromString( * file, allowing external controllers to discover valid release paths. */ export function getWorkspaceNames(): string[] { + const { config, directory } = loadUnselectedConfiguration(); + const workspaceNames = getWorkspaceNamesFromConfig(config, directory); + if (workspaceNames.length > 0) { + checkWorkspacesMinVersion(config); + } + return workspaceNames; +} + +/** + * Returns the `.craft.yml` key that defines a workspace: the name itself, or + * the glob pattern it expands from. + */ +export function getWorkspaceConfigKey( + workspaceName: string, +): string | undefined { + const { config, directory } = loadUnselectedConfiguration(); + return Object.keys(config.workspaces || {}).find(key => + workspaceKeyMatches(key, workspaceName, directory), + ); +} + +/** + * Returns the workspace that owns files outside every workspace + * (`changelog.unownedPaths: own`), if one is configured. + */ +export function getUnownedPathsOwner(): string | undefined { + const { config, directory } = loadUnselectedConfiguration(); + const owners: string[] = []; + for (const [key, workspace] of Object.entries(config.workspaces || {})) { + // Workspaces without their own changelog block inherit the top-level one. + const changelog = workspace.changelog ?? config.changelog; + if (typeof changelog !== 'object' || changelog.unownedPaths !== 'own') { + continue; + } + owners.push( + ...(isWorkspacePattern(key) + ? getWorkspaceGlobMatches(key, directory) + : [key]), + ); + } + if (owners.length > 1) { + throw new ConfigurationError( + 'Only one workspace can set changelog.unownedPaths to "own". ' + + `Found: ${owners.join(', ')}.`, + ); + } + return owners[0]; +} + +/** + * Reads and validates the configuration file without applying the active + * workspace selection. + */ +function loadUnselectedConfiguration(): { + config: CraftProjectConfig; + directory: string; +} { const configPath = getConfigFilePath(); const rawConfig = load(readFileSync(configPath, 'utf-8')) as Record< string, any >; - const parsed = validateConfiguration(rawConfig); - checkMinimalConfigVersion(parsed); - const workspaceNames = getWorkspaceNamesFromConfig( - parsed, - path.dirname(configPath), - ); - if (workspaceNames.length > 0) { - checkWorkspacesMinVersion(parsed); - } - return workspaceNames; + const config = validateConfiguration(rawConfig); + checkMinimalConfigVersion(config); + return { config, directory: path.dirname(configPath) }; } /** @@ -903,6 +954,8 @@ export interface NormalizedChangelogConfig { scopeGrouping: boolean; /** Additional workspace paths to include in automatic changelogs */ includePaths: string[]; + /** How automatic changelogs treat files outside every workspace */ + unownedPaths: UnownedPathsPolicy; /** Optional summaries; omitted unless configured explicitly. */ aiSummary?: AiSummaryConfig | false; } @@ -950,6 +1003,7 @@ export function getChangelogConfig(): NormalizedChangelogConfig { let policy = ChangelogPolicy.None; let scopeGrouping = true; let includePaths: string[] = []; + let unownedPaths: UnownedPathsPolicy = 'include'; // Handle legacy changelogPolicy (deprecated) if (config.changelogPolicy !== undefined) { @@ -978,6 +1032,9 @@ export function getChangelogConfig(): NormalizedChangelogConfig { if (config.changelog.includePaths !== undefined) { includePaths = config.changelog.includePaths; } + if (config.changelog.unownedPaths !== undefined) { + unownedPaths = config.changelog.unownedPaths; + } } } @@ -986,6 +1043,7 @@ export function getChangelogConfig(): NormalizedChangelogConfig { policy, scopeGrouping, includePaths, + unownedPaths, aiSummary: typeof config.changelog === 'object' ? config.changelog.aiSummary diff --git a/src/schemas/project_config.ts b/src/schemas/project_config.ts index 3c68c0f30..1060ae3bc 100644 --- a/src/schemas/project_config.ts +++ b/src/schemas/project_config.ts @@ -216,6 +216,10 @@ export const AiSummaryConfigSchema = z export type AiSummaryConfig = z.infer; +const UnownedPathsPolicySchema = z.enum(['include', 'exclude', 'own']); + +export type UnownedPathsPolicy = z.infer; + /** * Changelog configuration */ @@ -248,6 +252,13 @@ export const ChangelogConfigSchema = z.union([ ), ) .optional(), + /** + * How a workspace changelog treats files outside every workspace: + * `include` keeps them as shared (default), `exclude` ignores them, and + * `own` claims them for this workspace so every other workspace ignores + * them. At most one workspace can use `own`. + */ + unownedPaths: UnownedPathsPolicySchema.optional(), }), ]); diff --git a/src/utils/__tests__/changelog-generate.test.ts b/src/utils/__tests__/changelog-generate.test.ts index c5ec96b93..bd66bc45f 100644 --- a/src/utils/__tests__/changelog-generate.test.ts +++ b/src/utils/__tests__/changelog-generate.test.ts @@ -181,6 +181,7 @@ describe('generateChangesetFromGit', () => { policy: ChangelogPolicy.Auto, scopeGrouping: true, includePaths: [], + unownedPaths: 'include' as const, aiSummary: { llm: { endpoint: 'https://api.githubcopilot.com/responses', @@ -1382,6 +1383,7 @@ changelog: policy: ChangelogPolicy.Auto, scopeGrouping: false, includePaths: [], + unownedPaths: 'include', aiSummary: false, }); setup( diff --git a/src/utils/__tests__/git.test.ts b/src/utils/__tests__/git.test.ts index ca90264eb..efab3d4d9 100644 --- a/src/utils/__tests__/git.test.ts +++ b/src/utils/__tests__/git.test.ts @@ -310,6 +310,140 @@ describe('getChangesSince', () => { rmSync(dir, { recursive: true, force: true }); } }); + + describe('with workspace fixtures', () => { + let dir: string; + let previousDirectory: string; + const git = (...args: string[]) => + execFileSync('git', ['-C', dir, ...args], { + env: { + ...process.env, + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_CONFIG_NOSYSTEM: '1', + }, + }); + const commit = (title: string, files: Record) => { + for (const [file, content] of Object.entries(files)) { + mkdirSync(join(dir, file, '..'), { recursive: true }); + writeFileSync(join(dir, file), content); + git('add', '--', file); + } + git('-c', 'commit.gpgsign=false', 'commit', '--quiet', '-m', title); + }; + const titles = async (rev: string) => + (await getChangesSince(createGitClient(dir), rev)).map( + ({ title }) => title, + ); + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'craft-changelog-unowned-')); + previousDirectory = process.cwd(); + git('init', '--quiet'); + git('config', 'user.name', 'Craft Test'); + git('config', 'user.email', 'craft-test@example.com'); + process.chdir(dir); + }); + + afterEach(() => { + setActiveWorkspace(undefined); + process.chdir(previousDirectory); + rmSync(dir, { recursive: true, force: true }); + }); + + it('lets one workspace own unowned paths or a workspace exclude them', async () => { + const ownConfig = + 'minVersion: 2.29.0\nworkspaces:\n app:\n changelog:\n unownedPaths: own\n packages/cli: {}\n'; + commit('initial', { + '.craft.yml': ownConfig, + 'pnpm-workspace.yaml': 'packages:\n - packages/*\n', + 'packages/cli/package.json': '{"name":"cli"}', + 'packages/mcp/package.json': '{"name":"mcp"}', + }); + git('tag', 'start'); + commit('cli change', { 'packages/cli/cli.ts': 'cli' }); + commit('mcp change', { 'packages/mcp/mcp.ts': 'mcp' }); + commit('root change', { 'src/server.ts': 'server' }); + commit('root and cli change', { + 'src/server.ts': 'server 2', + 'packages/cli/cli.ts': 'cli 2', + }); + + setActiveWorkspace('app'); + expect(await titles('start')).toEqual([ + 'root and cli change', + 'root change', + ]); + setActiveWorkspace('packages/cli'); + expect(await titles('start')).toEqual([ + 'root and cli change', + 'cli change', + ]); + + writeFileSync( + join(dir, '.craft.yml'), + 'minVersion: 2.29.0\nworkspaces:\n packages/cli:\n changelog:\n unownedPaths: exclude\n packages/mcp: {}\n', + ); + setActiveWorkspace('packages/cli'); + expect(await titles('start')).toEqual([ + 'root and cli change', + 'cli change', + ]); + setActiveWorkspace('packages/mcp'); + expect(await titles('start')).toEqual([ + 'root and cli change', + 'root change', + 'mcp change', + ]); + + writeFileSync( + join(dir, '.craft.yml'), + 'minVersion: 2.29.0\nchangelog:\n unownedPaths: own\nworkspaces:\n app: {}\n packages/cli: {}\n', + ); + setActiveWorkspace('app'); + await expect(titles('start')).rejects.toThrow( + 'Only one workspace can set changelog.unownedPaths to "own". Found: app, packages/cli.', + ); + }); + + it('starts a first workspace release where the workspace was configured', async () => { + const infoSpy = vi.spyOn(loggerModule.logger, 'info'); + const config = 'minVersion: 2.29.0\nworkspaces:\n packages/cli: {}\n'; + commit('before workspace', { + '.craft.yml': 'minVersion: 2.29.0\n', + 'root.txt': 'root', + }); + commit('unrelated root change', { 'root.txt': 'root 2' }); + commit('add cli workspace', { + '.craft.yml': config, + 'packages/cli/cli.ts': 'cli', + }); + commit('edit cli workspace', { + '.craft.yml': `${config}# comment\n`, + }); + commit('cli change', { 'packages/cli/cli.ts': 'cli 2' }); + + setActiveWorkspace('packages/cli'); + expect(await titles('')).toEqual([ + 'cli change', + 'edit cli workspace', + 'add cli workspace', + ]); + expect(infoSpy).toHaveBeenCalledWith( + expect.stringContaining( + 'reading 3 commits since workspace "packages/cli" was added', + ), + ); + + // Without a workspace there is no configuration boundary. + writeFileSync(join(dir, '.craft.yml'), 'minVersion: 2.29.0\n'); + setActiveWorkspace(undefined); + const warnSpy = vi.spyOn(loggerModule.logger, 'warn'); + expect(await titles('')).toHaveLength(5); + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining('reading the full history (5 commits)'), + ); + }); + }); }); describe('isRepoDirty', () => { diff --git a/src/utils/git.ts b/src/utils/git.ts index 35f31dbea..7c18d5771 100644 --- a/src/utils/git.ts +++ b/src/utils/git.ts @@ -6,10 +6,16 @@ import { type StatusResult, } from 'simple-git'; +import { realpathSync } from 'node:fs'; +import { load } from 'js-yaml'; + import { getActiveWorkspace, getChangelogConfig, getConfigFileDir, + getConfigFilePath, + getUnownedPathsOwner, + getWorkspaceConfigKey, getWorkspaceNames, } from '../config'; import { ConfigurationError } from './errors'; @@ -110,18 +116,44 @@ export async function getChangesSince( file: '.', }; + const workspace = getActiveWorkspace(); + // A workspace's first release has no previous tag. Its history cannot + // predate the workspace's Craft configuration, so start there instead of + // reading the entire repository history. + let since = rev; + const introduction = + !rev && workspace + ? await findWorkspaceIntroduction(git, workspace, until) + : undefined; + if (introduction && (await hasParent(git, introduction))) { + since = `${introduction}^`; + } + // simple-git interprets `to` without `from` as HEAD..HEAD and returns no - // commits. A first release has no previous tag, so log the full history. - const { all: commits } = rev - ? await git.log({ ...gitLogArgs, from: rev }) + // commits. Without a starting point, log the full history. + const { all: commits } = since + ? await git.log({ ...gitLogArgs, from: since }) : await git.log(['--no-merges', until || 'HEAD', '--', '.']); + if (!rev) { + if (since) { + logger.info( + `No previous release tag found; reading ${commits.length} commits since ` + + `workspace "${workspace}" was added to the Craft configuration in ` + + `${introduction?.slice(0, 12)}.`, + ); + } else { + logger.warn( + 'No previous release tag found; reading the full history ' + + `(${commits.length} commits) for the changelog.`, + ); + } + } const changes = commits.map(commit => ({ hash: commit.hash, title: commit.message, body: commit.body, pr: commit.message.match(PRExtractor)?.[0] || null, })); - const workspace = getActiveWorkspace(); if (!workspace || changes.length === 0) { return changes; } @@ -144,7 +176,13 @@ export async function getChangesSince( const orderedOwners = [...ownedPaths].sort( (left, right) => right.length - left.length, ); - const { includePaths } = getChangelogConfig(); + const { includePaths, unownedPaths } = getChangelogConfig(); + const unownedPathsOwner = getUnownedPathsOwner(); + // Files outside every workspace belong to the configured owner. Without one, + // they are shared unless this workspace excludes them. + const includesUnowned = unownedPathsOwner + ? unownedPathsOwner === workspace + : unownedPaths !== 'exclude'; const contains = (directory: string, file: string) => file === directory || file.startsWith(`${directory}/`); @@ -158,7 +196,7 @@ export async function getChangesSince( '--name-only', '-z', '--end-of-options', - rev ? `${rev}..${until || 'HEAD'}` : until || 'HEAD', + since ? `${since}..${until || 'HEAD'}` : until || 'HEAD', '--', '.', ]); @@ -187,11 +225,88 @@ export async function getChangesSince( return true; } const owner = orderedOwners.find(directory => contains(directory, file)); - return owner === undefined || owner === workspace; + return owner === undefined ? includesUnowned : owner === workspace; }); }); } +/** + * Finds the commit that added a workspace to the Craft configuration file. + * + * Walks the configuration file's history from `until` backwards and returns + * the oldest commit of the latest uninterrupted run that defines the + * workspace's key. + */ +async function findWorkspaceIntroduction( + git: SimpleGit, + workspace: string, + until?: string, +): Promise { + const key = getWorkspaceConfigKey(workspace); + if (!key) { + return undefined; + } + const top = (await git.revparse(['--show-toplevel'])).trim(); + const configPath = path + .relative(realpathSync(top), realpathSync(getConfigFilePath())) + .split(path.sep) + .join('/'); + const hashes = ( + await git.raw([ + 'log', + '--format=%H', + '--end-of-options', + until || 'HEAD', + '--', + `:(top)${configPath}`, + ]) + ) + .split('\n') + .filter(Boolean); + + let introduction: string | undefined; + for (const hash of hashes) { + if (!(await definesWorkspace(git, `${hash}:${configPath}`, key))) { + break; + } + introduction = hash; + } + return introduction; +} + +async function definesWorkspace( + git: SimpleGit, + object: string, + key: string, +): Promise { + try { + const config = load(await git.show([object])) as { + workspaces?: unknown; + } | null; + const workspaces = config?.workspaces; + return ( + typeof workspaces === 'object' && + workspaces !== null && + Object.prototype.hasOwnProperty.call(workspaces, key) + ); + } catch { + // Unreadable or invalid historical configuration ends the search. + return false; + } +} + +async function hasParent(git: SimpleGit, commit: string): Promise { + const parents = await git.raw([ + 'rev-list', + '--parents', + '-n', + '1', + '--end-of-options', + commit, + ]); + return parents.trim().split(' ').length > 1; +} + export function stripRemoteName( branch: string | undefined, remoteName: string,