Skip to content

Commit

Permalink
refactor(@angular/cli): validate global cli options with config set
Browse files Browse the repository at this point in the history
  • Loading branch information
clydin authored and hansl committed Mar 29, 2018
1 parent cbc824a commit 1a01b1e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
25 changes: 24 additions & 1 deletion packages/@angular/cli/commands/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ export interface ConfigOptions {
global?: boolean;
}

const validCliPaths = new Map([
['cli.warnings.versionMismatch', 'boolean'],
['cli.warnings.typescriptMismatch', 'boolean'],
['cli.defaultCollection', 'string'],
['cli.packageManager', 'string'],
]);

/**
* Splits a JSON path string into fragments. Fragments can be used to get the value referenced
* by the path. For example, a path of "a[3].foo.bar[2]" would give you a fragment array of
Expand Down Expand Up @@ -157,12 +164,28 @@ export default class ConfigCommand extends Command {
}

private set(options: ConfigOptions) {
if (!options.jsonPath || !options.jsonPath.trim()) {
throw new Error('Invalid Path.');
}
if (options.global
&& !options.jsonPath.startsWith('schematics.')
&& !validCliPaths.has(options.jsonPath)) {
throw new Error('Invalid Path.');
}

const [config, configPath] = getWorkspaceRaw(options.global ? 'global' : 'local');

// TODO: Modify & save without destroying comments
const configValue = config.value;

const value = parseJson(options.value, JsonParseMode.Loose);
const pathType = validCliPaths.get(options.jsonPath);
if (pathType) {
if (typeof value != pathType) {
throw new Error(`Invalid value type; expected a ${pathType}.`);
}
}

const result = setValueFromPath(configValue, options.jsonPath, value);

if (result === undefined) {
Expand All @@ -176,7 +199,7 @@ export default class ConfigCommand extends Command {
throw new SilentError();
}

const output = JSON.stringify(configValue);
const output = JSON.stringify(configValue, null, 2);
writeFileSync(configPath, output);
}

Expand Down
3 changes: 2 additions & 1 deletion tests/e2e/tests/commands/config/config-global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export default function() {
throw new Error(`Expected "true", received "${JSON.stringify(stdout)}".`);
}
})
.then(() => ng('config', '--global', 'schematics.@schematics/angular.component.inlineStyle', 'false'))
.then(() => expectToFail(() => ng('config', '--global', 'cli.warnings.notreal', 'true')))
.then(() => ng('config', '--global', 'cli.warnings.versionMismatch', 'false'))
.then(() => expectFileToExist(path.join(homedir(), '.angular.json')));
}

0 comments on commit 1a01b1e

Please sign in to comment.