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
32 changes: 32 additions & 0 deletions docs/src/content/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions src/__tests__/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ describe('validateConfiguration', () => {
policy: 'auto',
scopeGrouping: true,
includePaths: ['apps/cli-docs'],
unownedPaths: 'own',
},
};

Expand Down Expand Up @@ -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', () => {
Expand Down
78 changes: 68 additions & 10 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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) };
}

/**
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
}
}
}

Expand All @@ -986,6 +1043,7 @@ export function getChangelogConfig(): NormalizedChangelogConfig {
policy,
scopeGrouping,
includePaths,
unownedPaths,
aiSummary:
typeof config.changelog === 'object'
? config.changelog.aiSummary
Expand Down
11 changes: 11 additions & 0 deletions src/schemas/project_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,10 @@ export const AiSummaryConfigSchema = z

export type AiSummaryConfig = z.infer<typeof AiSummaryConfigSchema>;

const UnownedPathsPolicySchema = z.enum(['include', 'exclude', 'own']);

export type UnownedPathsPolicy = z.infer<typeof UnownedPathsPolicySchema>;

/**
* Changelog configuration
*/
Expand Down Expand Up @@ -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(),
}),
]);

Expand Down
2 changes: 2 additions & 0 deletions src/utils/__tests__/changelog-generate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ describe('generateChangesetFromGit', () => {
policy: ChangelogPolicy.Auto,
scopeGrouping: true,
includePaths: [],
unownedPaths: 'include' as const,
aiSummary: {
llm: {
endpoint: 'https://api.githubcopilot.com/responses',
Expand Down Expand Up @@ -1382,6 +1383,7 @@ changelog:
policy: ChangelogPolicy.Auto,
scopeGrouping: false,
includePaths: [],
unownedPaths: 'include',
aiSummary: false,
});
setup(
Expand Down
134 changes: 134 additions & 0 deletions src/utils/__tests__/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>) => {
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', () => {
Expand Down
Loading
Loading