Skip to content

Commit 4eb8e6c

Browse files
committed
fix(@angular/cli): explain how to pick a project when a schematic cannot determine one
when project can't be resolved from cwd, like at root of workspace with no root project, schematics fail with raw `Data path "" must have required property 'project'` from schema validation now that error is replaced with message that says to pass `--project` or cd into project and lists available projects like architect commands do, empty workspace gets hint to generate application or libary first Fixes #25402
1 parent 193abc0 commit 4eb8e6c

3 files changed

Lines changed: 143 additions & 1 deletion

File tree

‎packages/angular/cli/src/command-builder/schematics-command-module.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ export abstract class SchematicsCommandModule
387387
logger.fatal('The Schematic workflow failed. See above.');
388388
} else {
389389
assertIsError(err);
390-
logger.fatal(err.message);
390+
logger.fatal(this.getMissingProjectMessage(err) ?? err.message);
391391
}
392392

393393
return 1;
@@ -396,6 +396,44 @@ export abstract class SchematicsCommandModule
396396
}
397397
}
398398

399+
/**
400+
* Explains how to select a project when a schematic requires one and the project cannot be
401+
* determined from the current working directory.
402+
*/
403+
private getMissingProjectMessage(error: Error): string | undefined {
404+
const { workspace } = this.context;
405+
if (
406+
!workspace ||
407+
this.getProjectName() !== undefined ||
408+
!(error instanceof schema.SchemaValidationException) ||
409+
!error.errors.some(
410+
({ keyword, instancePath, params }) =>
411+
keyword === 'required' && instancePath === '' && params?.missingProperty === 'project',
412+
)
413+
) {
414+
return undefined;
415+
}
416+
417+
if (workspace.projects.size === 0) {
418+
return (
419+
'Cannot determine project for command.\n' +
420+
'This workspace does not contain any projects. ' +
421+
'Run "ng generate application" or "ng generate library" to create one.'
422+
);
423+
}
424+
425+
return (
426+
'Cannot determine project for command.\n' +
427+
'This is a multi-project workspace and the current working directory is not inside a single ' +
428+
'project. Use the "--project" option to specify a project or change the current working ' +
429+
'directory to a project directory.\n\n' +
430+
`Available projects are:\n${[...workspace.projects.keys()]
431+
.sort()
432+
.map((p) => `- ${p}`)
433+
.join('\n')}`
434+
);
435+
}
436+
399437
private getProjectName(): string | undefined {
400438
const { workspace } = this.context;
401439
if (!workspace) {
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import { logging, workspaces } from '@angular-devkit/core';
10+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
11+
import { tmpdir } from 'node:os';
12+
import { join } from 'node:path';
13+
import { PackageManager } from '../package-managers';
14+
import { AngularWorkspace } from '../utilities/config';
15+
import { CommandContext } from './definitions';
16+
import { SchematicsCommandModule } from './schematics-command-module';
17+
18+
class TestCommandModule extends SchematicsCommandModule {
19+
command = 'test';
20+
describe = false as const;
21+
22+
run(): Promise<number> {
23+
return this.runSchematic({
24+
collectionName: './collection.json',
25+
schematicName: 'test',
26+
schematicOptions: {},
27+
executionOptions: { interactive: false, defaults: false, force: false, dryRun: true },
28+
});
29+
}
30+
}
31+
32+
describe('SchematicsCommandModule', () => {
33+
let root: string;
34+
35+
beforeAll(() => {
36+
root = mkdtempSync(join(tmpdir(), 'angular-cli-schematics-command-'));
37+
writeFileSync(
38+
join(root, 'collection.json'),
39+
JSON.stringify({
40+
schematics: { test: { description: 'Test', factory: './index', schema: './schema.json' } },
41+
}),
42+
);
43+
writeFileSync(
44+
join(root, 'schema.json'),
45+
JSON.stringify({
46+
type: 'object',
47+
properties: { project: { type: 'string', $default: { $source: 'projectName' } } },
48+
required: ['project'],
49+
}),
50+
);
51+
writeFileSync(join(root, 'index.js'), 'exports.default = () => (tree) => tree;');
52+
});
53+
54+
afterAll(() => {
55+
rmSync(root, { recursive: true, force: true });
56+
});
57+
58+
async function runWithProjects(projectNames: string[]): Promise<[number, string]> {
59+
const projects = new workspaces.ProjectDefinitionCollection();
60+
for (const name of projectNames) {
61+
projects.add({ name, root: `projects/${name}` });
62+
}
63+
64+
const logger = new logging.Logger('test');
65+
const messages: string[] = [];
66+
logger.subscribe(({ message }) => messages.push(message));
67+
68+
const command = new TestCommandModule({
69+
root,
70+
logger,
71+
workspace: new AngularWorkspace({ extensions: {}, projects }, join(root, 'angular.json')),
72+
packageManager: { name: 'npm' } as PackageManager,
73+
} as CommandContext);
74+
75+
const exitCode = await command.run();
76+
77+
return [exitCode, messages.join('\n')];
78+
}
79+
80+
it('should explain how to pick a project when it cannot be determined from the cwd', async () => {
81+
const [exitCode, output] = await runWithProjects(['second-app', 'first-app']);
82+
83+
expect(exitCode).toBe(1);
84+
expect(output).toContain('Cannot determine project for command.');
85+
expect(output).toContain('Use the "--project" option to specify a project');
86+
expect(output).toContain('Available projects are:\n- first-app\n- second-app');
87+
expect(output).not.toContain(`must have required property 'project'`);
88+
});
89+
90+
it('should explain that the workspace has no projects', async () => {
91+
const [exitCode, output] = await runWithProjects([]);
92+
93+
expect(exitCode).toBe(1);
94+
expect(output).toContain('This workspace does not contain any projects.');
95+
expect(output).not.toContain('Available projects are:');
96+
});
97+
});

‎tests/e2e/tests/commands/project-cannot-be-determined-by-cwd.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@ export default async function () {
2323
const { message } = await expectToFail(() => ng('build'));
2424
assert.match(message, new RegExp(errorMessage));
2525

26+
// Schematics that require a project should explain how to select one
27+
const { message: generateMessage } = await expectToFail(() =>
28+
ng('generate', 'component', 'foo'),
29+
);
30+
assert.match(generateMessage, /Use the "--project" option to specify a project/);
31+
assert.match(generateMessage, /Available projects are:\n- second-app\n- third-app/);
32+
2633
// Help should still work
2734
await execAndWaitForOutputToMatch('ng', ['build', '--help'], /--configuration/);
2835

0 commit comments

Comments
 (0)