Skip to content

Commit 061e5c5

Browse files
fixup! fix(@angular/cli): explain how to pick a project when a schematic cannot determine one
Co-authored-by: Alan Agius <alanagius@google.com>
1 parent 4eb8e6c commit 061e5c5

3 files changed

Lines changed: 184 additions & 113 deletions

File tree

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

Lines changed: 83 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,15 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9-
import { JsonValue, normalize as devkitNormalize, schema } from '@angular-devkit/core';
9+
import {
10+
JsonObject,
11+
JsonValue,
12+
normalize as devkitNormalize,
13+
isJsonArray,
14+
isJsonObject,
15+
schema,
16+
strings,
17+
} from '@angular-devkit/core';
1018
import { Collection, UnsuccessfulWorkflowExecution, formats } from '@angular-devkit/schematics';
1119
import {
1220
FileSystemCollectionDescription,
@@ -17,13 +25,14 @@ import { relative } from 'node:path';
1725
import { Argv } from 'yargs';
1826
import { isPackageNameSafeForAnalytics } from '../analytics/analytics';
1927
import { EventCustomDimension } from '../analytics/analytics-parameters';
20-
import { getProjectByCwd, getSchematicDefaults } from '../utilities/config';
28+
import { AngularWorkspace, getProjectByCwd, getSchematicDefaults } from '../utilities/config';
2129
import { assertIsError } from '../utilities/error';
2230
import { memoize } from '../utilities/memoize';
2331
import { formatFiles } from '../utilities/prettier';
2432
import { isTTY } from '../utilities/tty';
2533
import {
2634
CommandModule,
35+
CommandModuleError,
2736
CommandModuleImplementation,
2837
CommandScope,
2938
Options,
@@ -131,6 +140,20 @@ export abstract class SchematicsCommandModule
131140
...current,
132141
};
133142
},
143+
// Fail before smart defaults and prompts are applied when a required option relies on the
144+
// `projectName` smart default and the project cannot be determined.
145+
(schematic, current) => {
146+
const { workspace } = this.context;
147+
const message =
148+
workspace && this.getProjectName() === undefined
149+
? getMissingProjectMessage(workspace, schematic.schemaJson, current)
150+
: undefined;
151+
if (message) {
152+
throw new CommandModuleError(message);
153+
}
154+
155+
return current ?? {};
156+
},
134157
],
135158
engineHostCreator: (options) => new SchematicEngineHost(options.resolvePaths),
136159
});
@@ -387,7 +410,7 @@ export abstract class SchematicsCommandModule
387410
logger.fatal('The Schematic workflow failed. See above.');
388411
} else {
389412
assertIsError(err);
390-
logger.fatal(this.getMissingProjectMessage(err) ?? err.message);
413+
logger.fatal(err.message);
391414
}
392415

393416
return 1;
@@ -396,44 +419,6 @@ export abstract class SchematicsCommandModule
396419
}
397420
}
398421

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-
437422
private getProjectName(): string | undefined {
438423
const { workspace } = this.context;
439424
if (!workspace) {
@@ -465,3 +450,60 @@ export abstract class SchematicsCommandModule
465450
[import.meta.dirname, process.cwd()];
466451
}
467452
}
453+
454+
/**
455+
* Returns an error message when a schematic requires an option that uses the `projectName` smart
456+
* default, the option has no value and the project cannot be determined from the current working
457+
* directory. Otherwise schema validation fails later with a generic "must have required property"
458+
* error, after prompting for other options.
459+
*/
460+
export function getMissingProjectMessage(
461+
workspace: AngularWorkspace,
462+
schemaJson: JsonObject | undefined,
463+
options: Record<string, unknown> | null,
464+
): string | undefined {
465+
if (!schemaJson) {
466+
return undefined;
467+
}
468+
469+
const { properties, required } = schemaJson;
470+
if (!isJsonObject(properties) || !isJsonArray(required)) {
471+
return undefined;
472+
}
473+
474+
const optionName = Object.keys(properties).find((name) => {
475+
const property = properties[name];
476+
477+
return (
478+
required.includes(name) &&
479+
options?.[name] === undefined &&
480+
isJsonObject(property) &&
481+
isJsonObject(property.$default) &&
482+
property.$default.$source === 'projectName' &&
483+
property['x-prompt'] === undefined
484+
);
485+
});
486+
487+
if (optionName === undefined) {
488+
return undefined;
489+
}
490+
491+
if (workspace.projects.size === 0) {
492+
return (
493+
'Cannot determine project for command.\n' +
494+
'This workspace does not contain any projects. ' +
495+
'Run "ng generate application" or "ng generate library" to create one.'
496+
);
497+
}
498+
499+
return (
500+
'Cannot determine project for command.\n' +
501+
'This is a multi-project workspace and the current working directory is not inside a single ' +
502+
`project. Use the "--${strings.dasherize(optionName)}" option to specify a project or change ` +
503+
'the current working directory to a project directory.\n\n' +
504+
`Available projects are:\n${[...workspace.projects.keys()]
505+
.sort()
506+
.map((p) => `- ${p}`)
507+
.join('\n')}`
508+
);
509+
}

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

Lines changed: 72 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -6,92 +6,93 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

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';
9+
import { JsonObject, workspaces } from '@angular-devkit/core';
1410
import { AngularWorkspace } from '../utilities/config';
15-
import { CommandContext } from './definitions';
16-
import { SchematicsCommandModule } from './schematics-command-module';
11+
import { getMissingProjectMessage } from './schematics-command-module';
1712

18-
class TestCommandModule extends SchematicsCommandModule {
19-
command = 'test';
20-
describe = false as const;
13+
describe('getMissingProjectMessage', () => {
14+
const projectOption = { type: 'string', $default: { $source: 'projectName' } };
15+
const schemaJson: JsonObject = {
16+
type: 'object',
17+
properties: { name: { type: 'string' }, project: projectOption },
18+
required: ['name', 'project'],
19+
};
2120

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]> {
21+
function createWorkspace(...projectNames: string[]): AngularWorkspace {
5922
const projects = new workspaces.ProjectDefinitionCollection();
6023
for (const name of projectNames) {
6124
projects.add({ name, root: `projects/${name}` });
6225
}
6326

64-
const logger = new logging.Logger('test');
65-
const messages: string[] = [];
66-
logger.subscribe(({ message }) => messages.push(message));
27+
return new AngularWorkspace({ extensions: {}, projects }, '/angular.json');
28+
}
6729

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);
30+
it('should list the available projects when the project cannot be determined', () => {
31+
expect(getMissingProjectMessage(createWorkspace('second', 'first'), schemaJson, {})).toBe(
32+
'Cannot determine project for command.\n' +
33+
'This is a multi-project workspace and the current working directory is not inside a ' +
34+
'single project. Use the "--project" option to specify a project or change the current ' +
35+
'working directory to a project directory.\n\n' +
36+
'Available projects are:\n- first\n- second',
37+
);
38+
});
7439

75-
const exitCode = await command.run();
40+
it('should explain how to create a project when the workspace has none', () => {
41+
expect(getMissingProjectMessage(createWorkspace(), schemaJson, {})).toBe(
42+
'Cannot determine project for command.\n' +
43+
'This workspace does not contain any projects. ' +
44+
'Run "ng generate application" or "ng generate library" to create one.',
45+
);
46+
});
7647

77-
return [exitCode, messages.join('\n')];
78-
}
48+
it('should use the name of the option that relies on the smart default', () => {
49+
const message = getMissingProjectMessage(
50+
createWorkspace('first', 'second'),
51+
{ properties: { targetProject: projectOption }, required: ['targetProject'] },
52+
{},
53+
);
7954

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']);
55+
expect(message).toContain('Use the "--target-project" option');
56+
});
8257

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'`);
58+
it('should not return a message when the option has a value', () => {
59+
expect(
60+
getMissingProjectMessage(createWorkspace('first', 'second'), schemaJson, {
61+
project: 'first',
62+
}),
63+
).toBeUndefined();
8864
});
8965

90-
it('should explain that the workspace has no projects', async () => {
91-
const [exitCode, output] = await runWithProjects([]);
66+
it('should not return a message when the option is not required', () => {
67+
expect(
68+
getMissingProjectMessage(
69+
createWorkspace('first', 'second'),
70+
{ ...schemaJson, required: ['name'] },
71+
{},
72+
),
73+
).toBeUndefined();
74+
});
75+
76+
it('should not return a message when the option does not use the smart default', () => {
77+
expect(
78+
getMissingProjectMessage(
79+
createWorkspace('first', 'second'),
80+
{ ...schemaJson, properties: { project: { type: 'string' } } },
81+
{},
82+
),
83+
).toBeUndefined();
84+
});
9285

93-
expect(exitCode).toBe(1);
94-
expect(output).toContain('This workspace does not contain any projects.');
95-
expect(output).not.toContain('Available projects are:');
86+
it('should not return a message when the option can be prompted for', () => {
87+
expect(
88+
getMissingProjectMessage(
89+
createWorkspace('first', 'second'),
90+
{
91+
...schemaJson,
92+
properties: { project: { ...projectOption, 'x-prompt': 'Which project?' } },
93+
},
94+
{},
95+
),
96+
).toBeUndefined();
9697
});
9798
});

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

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import assert from 'node:assert/strict';
22
import { join } from 'node:path';
3-
import { execAndWaitForOutputToMatch, ng } from '../../utils/process';
3+
import { execAndCaptureError, execAndWaitForOutputToMatch, ng } from '../../utils/process';
44
import { updateJsonFile } from '../../utils/project';
55
import { expectToFail } from '../../utils/utils';
66

@@ -30,6 +30,21 @@ export default async function () {
3030
assert.match(generateMessage, /Use the "--project" option to specify a project/);
3131
assert.match(generateMessage, /Available projects are:\n- second-app\n- third-app/);
3232

33+
// The project is checked before prompting for other options
34+
const { message: interactiveMessage } = await execAndCaptureError(
35+
'ng',
36+
['generate', 'component'],
37+
{
38+
...process.env,
39+
NG_FORCE_TTY: '1',
40+
NG_CLI_ANALYTICS: 'false',
41+
NG_FORCE_AUTOCOMPLETE: 'false',
42+
},
43+
'foo\n',
44+
);
45+
assert.match(interactiveMessage, /Use the "--project" option to specify a project/);
46+
assert.doesNotMatch(interactiveMessage, /What name would you like to use for the component/);
47+
3348
// Help should still work
3449
await execAndWaitForOutputToMatch('ng', ['build', '--help'], /--configuration/);
3550

@@ -38,8 +53,21 @@ export default async function () {
3853

3954
process.chdir(join(startCwd, 'projects/second-app'));
4055
await ng('build', '--configuration=development');
56+
await ng('generate', 'component', 'foo', '--dry-run');
4157
} finally {
4258
// Restore path
4359
process.chdir(startCwd);
4460
}
61+
62+
// A project from the workspace schematic options is used and other validation errors are kept
63+
await updateJsonFile('angular.json', (workspaceJson) => {
64+
workspaceJson.schematics ??= {};
65+
workspaceJson.schematics['@schematics/angular:component'] = { project: 'second-app' };
66+
});
67+
const { message: selectorMessage } = await expectToFail(() =>
68+
ng('generate', 'component', 'foo', '--selector=1foo'),
69+
);
70+
assert.match(selectorMessage, /must match format "html-selector"/);
71+
assert.doesNotMatch(selectorMessage, /Cannot determine project/);
72+
await ng('generate', 'component', 'foo', '--dry-run');
4573
}

0 commit comments

Comments
 (0)