Skip to content

Commit

Permalink
feat(schematics): Allow users to set prettier config, add relevant mi…
Browse files Browse the repository at this point in the history
…gration
  • Loading branch information
JamesHenry authored and vsavkin committed Mar 11, 2018
1 parent b17b186 commit 56a6611
Show file tree
Hide file tree
Showing 11 changed files with 151 additions and 19 deletions.
10 changes: 1 addition & 9 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,11 +1,3 @@
{
"singleQuote": true,
"overrides": [
{
"files": "*.ts",
"options": {
"parser": "typescript"
}
}
]
"singleQuote": true
}
4 changes: 2 additions & 2 deletions e2e/schematics/workspace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ describe('Nrwl Convert to Nx Workspace', () => {
// run the command
runCLI('generate workspace proj --npmScope=proj --collection=@nrwl/schematics');

// check that files have been moved!
checkFilesExist('apps/proj/src/main.ts', 'apps/proj/src/app/app.module.ts');
// check that prettier config exits and that files have been moved!
checkFilesExist('.prettierrc', 'apps/proj/src/main.ts', 'apps/proj/src/app/app.module.ts');

// check that package.json got merged
const updatedPackageJson = JSON.parse(readFile('package.json'));
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@
"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"@types/prettier": "^1.10.0",
"angular": "1.6.6",
"app-root-path": "^2.0.1",
"cosmiconfig": "^4.0.0",
"husky": "^0.14.3",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
Expand All @@ -53,7 +56,6 @@
"rxjs": "^5.5.6",
"semver": "5.4.1",
"strip-json-comments": "2.0.1",
"app-root-path": "^2.0.1",
"tmp": "0.0.33",
"tslint": "5.9.1",
"typescript": "2.6.2",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { writeFileSync, readFileSync, readdirSync, unlinkSync } from 'fs';
import { join } from 'path';

import { updateJsonFile } from '../../shared/fileutils';
import { ExistingPrettierConfig, resolveUserExistingPrettierConfig } from '../../shared/common';

export default {
description: 'Create or update prettier configuration',
run: async () => {
const resolvedExisting = await resolveUserExistingPrettierConfig();
const existingUserConfig = {
...(resolvedExisting ? resolvedExisting.config : null)
};
const PREVIOUSLY_HARDCODED_NRWL_CONFIG = {
singleQuote: true,
printWidth: 120
};
const finalConfig = {
...existingUserConfig,
...PREVIOUSLY_HARDCODED_NRWL_CONFIG
};
// cleanup old configuration source, if applicable
if (resolvedExisting) {
cleanUpExistingConfig(resolvedExisting);
}
// create new configuration file
writeFileSync('.prettierrc', JSON.stringify(finalConfig, null, 2));
}
};

function cleanUpExistingConfig(resolvedExisting: ExistingPrettierConfig): void {
switch (resolvedExisting.sourceFilepath) {
case join(process.cwd(), 'package.json'):
return updateJsonFile('package.json', json => {
delete json.prettier;
});
default:
return unlinkSync(resolvedExisting.sourceFilepath);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ describe('application', () => {
it('should generate files', () => {
const tree = schematicRunner.runSchematic('application', { name: 'myApp', directory: 'my-app' }, appTree);
expect(tree.files).toEqual([
'/my-app/.prettierrc',
'/my-app/README.md',
'/my-app/.angular-cli.json',
'/my-app/.editorconfig',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<%= defaultNrwlPrettierConfig %>
4 changes: 3 additions & 1 deletion packages/schematics/src/collection/application/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {Schema} from './schema';
import {strings} from '@angular-devkit/core';
import {NodePackageInstallTask, RepositoryInitializerTask} from '@angular-devkit/schematics/tasks';
import {libVersions} from '../../../../shared/lib-versions';
import { DEFAULT_NRWL_PRETTIER_CONFIG } from '../../../../shared/common';

export default function(options: Schema): Rule {
return (host: Tree, context: SchematicContext) => {
Expand All @@ -24,7 +25,8 @@ export default function(options: Schema): Rule {
dot: '.',
...libVersions,
...(options as object),
npmScope
npmScope,
defaultNrwlPrettierConfig: JSON.stringify(DEFAULT_NRWL_PRETTIER_CONFIG, null, 2)
})
]);
return chain([branchAndMerge(chain([mergeWith(templateSource)]))])(host, context);
Expand Down
25 changes: 23 additions & 2 deletions packages/schematics/src/collection/workspace/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import {
import * as fs from 'fs';
import { copyFile, serializeJson, updateJsonFile } from '../../../../shared/fileutils';
import { toFileName } from '@nrwl/schematics';
import { resolveUserExistingPrettierConfig, DEFAULT_NRWL_PRETTIER_CONFIG } from '../../../../shared/common';
import { Observable } from 'rxjs/Observable';
import { fromPromise } from 'rxjs/observable/fromPromise'
import { tap, map } from 'rxjs/operators';

function updatePackageJson() {
return (host: Tree) => {
Expand Down Expand Up @@ -225,7 +229,7 @@ function setUpCompilerOptions(tsconfig: any, npmScope: string, offset: string):
tsconfig.compilerOptions.paths[`@${npmScope}/*`] = [`${offset}libs/*`];
}

function moveFiles(options: Schema) {
function moveExistingFiles(options: Schema) {
return (host: Tree) => {
const angularCliJson = JSON.parse(host.read('.angular-cli.json')!.toString('utf-8'));
const app = angularCliJson.apps[0];
Expand All @@ -242,6 +246,22 @@ function moveFiles(options: Schema) {
};
}

function createAdditionalFiles(options: Schema) {
return (host: Tree): Observable<Tree> => {
// if the user does not already have a prettier configuration
// of any kind, create one
return fromPromise(resolveUserExistingPrettierConfig())
.pipe(
tap((resolvedExistingConfig) => {
if (!resolvedExistingConfig) {
fs.writeFileSync('.prettierrc', JSON.stringify(DEFAULT_NRWL_PRETTIER_CONFIG, null, 2));
}
}),
map(() => host)
);
};
}

function dedup(array: any[]): any[] {
const res = [];

Expand Down Expand Up @@ -276,7 +296,8 @@ export default function(schema: Schema): Rule {
const options = { ...schema, name: toFileName(schema.name) };
return chain([
checkCanConvertToWorkspace(options),
moveFiles(options),
moveExistingFiles(options),
createAdditionalFiles(options),
branchAndMerge(chain([mergeWith(apply(url('./files'), []))])),
updatePackageJson(),
updateAngularCLIJson(options),
Expand Down
4 changes: 2 additions & 2 deletions packages/schematics/src/command-line/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function printError(command: string, e: any) {

function write(patterns: string[]) {
if (patterns.length > 0) {
execSync(`node ${prettierPath()} --single-quote --print-width 120 --write ${patterns.join(' ')}`, {
execSync(`node ${prettierPath()} --write ${patterns.join(' ')}`, {
stdio: [0, 1, 2]
});
}
Expand All @@ -65,7 +65,7 @@ function write(patterns: string[]) {
function check(patterns: string[]) {
if (patterns.length > 0) {
try {
execSync(`node ${prettierPath()} --single-quote --print-width 120 --list-different ${patterns.join(' ')}`, {
execSync(`node ${prettierPath()} --list-different ${patterns.join(' ')}`, {
stdio: [0, 1, 2]
});
} catch (e) {
Expand Down
40 changes: 39 additions & 1 deletion packages/shared/common.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { Tree, Rule } from '@angular-devkit/schematics';
import { readdirSync, readFileSync } from 'fs';
import { Options } from 'prettier';
import * as cosmiconfig from 'cosmiconfig';

import { angularJsVersion } from './lib-versions';
import { serializeJson } from './fileutils';
import { Schema } from '../schematics/src/collection/app/schema';
Expand All @@ -14,7 +18,8 @@ export function addUpgradeToPackageJson(): Rule {
}

if (!json['dependencies']['@angular/upgrade']) {
json['dependencies']['@angular/upgrade'] = json['dependencies']['@angular/core'];
json['dependencies']['@angular/upgrade'] =
json['dependencies']['@angular/core'];
}
if (!json['dependencies']['angular']) {
json['dependencies']['angular'] = angularJsVersion;
Expand All @@ -33,3 +38,36 @@ export function offsetFromRoot(fullPathToSourceDir: string): string {
}
return offset;
}

export const DEFAULT_NRWL_PRETTIER_CONFIG = {
singleQuote: true
};

export interface ExistingPrettierConfig {
sourceFilepath: string;
config: Options;
}

export function resolveUserExistingPrettierConfig(): Promise<ExistingPrettierConfig | null> {
const explorer = cosmiconfig('prettier', {
sync: true,
cache: false,
rcExtensions: true,
stopDir: process.cwd(),
transform: result => {
if (result && result.config) {
delete result.config.$schema;
}
return result;
}
});
return Promise.resolve(explorer.load(process.cwd())).then(result => {
if (!result) {
return null;
}
return {
sourceFilepath: result.filepath,
config: result.config
};
});
}
37 changes: 36 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,10 @@
version "6.0.101"
resolved "https://registry.yarnpkg.com/@types/node/-/node-6.0.101.tgz#0c5911cfb434af4a51c0a499931fe6423207d921"

"@types/prettier@^1.10.0":
version "1.10.0"
resolved "https://registry.yarnpkg.com/@types/prettier/-/prettier-1.10.0.tgz#5abf1ec0a6e904fe2490cc2068f36a38e4a63c42"

JSONStream@^1.0.3:
version "1.3.2"
resolved "https://registry.yarnpkg.com/JSONStream/-/JSONStream-1.3.2.tgz#c102371b6ec3a7cf3b847ca00c20bb0fce4c6dea"
Expand Down Expand Up @@ -1576,6 +1580,15 @@ cosmiconfig@^2.1.0, cosmiconfig@^2.1.1:
parse-json "^2.2.0"
require-from-string "^1.1.0"

cosmiconfig@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-4.0.0.tgz#760391549580bbd2df1e562bc177b13c290972dc"
dependencies:
is-directory "^0.3.1"
js-yaml "^3.9.0"
parse-json "^4.0.0"
require-from-string "^2.0.1"

create-ecdh@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/create-ecdh/-/create-ecdh-4.0.0.tgz#888c723596cdf7612f6498233eebd7a35301737d"
Expand Down Expand Up @@ -2092,7 +2105,7 @@ errno@^0.1.1, errno@^0.1.3, errno@^0.1.4:
dependencies:
prr "~1.0.1"

error-ex@^1.2.0:
error-ex@^1.2.0, error-ex@^1.3.1:
version "1.3.1"
resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.1.tgz#f855a86ce61adc4e8621c3cda21e7a7612c3a8dc"
dependencies:
Expand Down Expand Up @@ -3865,6 +3878,13 @@ js-yaml@^3.4.3, js-yaml@^3.7.0:
argparse "^1.0.7"
esprima "^4.0.0"

js-yaml@^3.9.0:
version "3.11.0"
resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.11.0.tgz#597c1a8bd57152f26d622ce4117851a51f5ebaef"
dependencies:
argparse "^1.0.7"
esprima "^4.0.0"

jsbn@~0.1.0:
version "0.1.1"
resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513"
Expand Down Expand Up @@ -3901,6 +3921,10 @@ json-loader@^0.5.4:
version "0.5.7"
resolved "https://registry.yarnpkg.com/json-loader/-/json-loader-0.5.7.tgz#dca14a70235ff82f0ac9a3abeb60d337a365185d"

json-parse-better-errors@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.1.tgz#50183cd1b2d25275de069e9e71b467ac9eab973a"

json-schema-traverse@^0.3.0:
version "0.3.1"
resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340"
Expand Down Expand Up @@ -5091,6 +5115,13 @@ parse-json@^2.2.0:
dependencies:
error-ex "^1.2.0"

parse-json@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0"
dependencies:
error-ex "^1.3.1"
json-parse-better-errors "^1.0.1"

parse5@^1.5.1:
version "1.5.1"
resolved "https://registry.yarnpkg.com/parse5/-/parse5-1.5.1.tgz#9b7f3b0de32be78dc2401b17573ccaf0f6f59d94"
Expand Down Expand Up @@ -5807,6 +5838,10 @@ require-from-string@^1.1.0:
version "1.2.1"
resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-1.2.1.tgz#529c9ccef27380adfec9a2f965b649bbee636418"

require-from-string@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.1.tgz#c545233e9d7da6616e9d59adfb39fc9f588676ff"

require-main-filename@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1"
Expand Down

0 comments on commit 56a6611

Please sign in to comment.