Skip to content

Commit

Permalink
feat(@schematics/angular): change layout for root applications
Browse files Browse the repository at this point in the history
This change aligns the file layout of applications generated with `ng new` and `ng generate`

Ref: TOOL-686
  • Loading branch information
Alan authored and hansl committed Mar 6, 2019
1 parent bf1c069 commit a7d095d
Show file tree
Hide file tree
Showing 15 changed files with 169 additions and 120 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
"outDir": "<%= relativePathToWorkspaceRoot %>/out-tsc/app",
"types": []
},
"include": [
"src/**/*.ts"
],
"exclude": [
"test.ts",
"**/*.spec.ts",
"e2e/**"
"src/test.ts",
"src/**/*.spec.ts"
]<% if (enableIvy) { %>,
"angularCompilerOptions": {
"enableIvy": true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
]
},
"files": [
"<%= rootInSrc ? '' : 'src/' %>test.ts",
"<%= rootInSrc ? '' : 'src/' %>polyfills.ts"
"src/test.ts",
"src/polyfills.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"extends": "<%= relativePathToWorkspaceRoot %>/tslint.json",
{<% if (!isRootApp) { %>
"extends": "<%= relativePathToWorkspaceRoot %>/tslint.json",<%
} %>
"rules": {
"directive-selector": [
true,
Expand Down
202 changes: 117 additions & 85 deletions packages/schematics/angular/application/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
* found in the LICENSE file at https://angular.io/license
*/
import {
JsonAstObject,
JsonObject,
JsonParseMode,
join,
normalize,
parseJsonAst,
relative,
strings,
} from '@angular-devkit/core';
import {
Expand Down Expand Up @@ -103,6 +103,78 @@ function addDependenciesToPackageJson(options: ApplicationOptions) {
};
}

function readTsLintConfig(host: Tree, path: string): JsonAstObject {
const buffer = host.read(path);
if (!buffer) {
throw new SchematicsException(`Could not read ${path}.`);
}

const config = parseJsonAst(buffer.toString(), JsonParseMode.Loose);
if (config.kind !== 'object') {
throw new SchematicsException(`Invalid ${path}. Was expecting an object.`);
}

return config;
}

/**
* Merges the application tslint.json with the workspace tslint.json
* when the application being created is a root application
*
* @param {Tree} parentHost The root host of the schematic
*/
function mergeWithRootTsLint(parentHost: Tree) {
return (host: Tree) => {
const tsLintPath = '/tslint.json';
if (!host.exists(tsLintPath)) {
return;
}

const rootTslintConfig = readTsLintConfig(parentHost, tsLintPath);
const appTslintConfig = readTsLintConfig(host, tsLintPath);

const recorder = host.beginUpdate(tsLintPath);
rootTslintConfig.properties.forEach(prop => {
if (findPropertyInAstObject(appTslintConfig, prop.key.value)) {
// property already exists. Skip!
return;
}

insertPropertyInAstObjectInOrder(
recorder,
appTslintConfig,
prop.key.value,
prop.value.value,
2,
);
});

const rootRules = findPropertyInAstObject(rootTslintConfig, 'rules');
const appRules = findPropertyInAstObject(appTslintConfig, 'rules');

if (!appRules || appRules.kind !== 'object' || !rootRules || rootRules.kind !== 'object') {
// rules are not valid. Skip!
return;
}

rootRules.properties.forEach(prop => {
insertPropertyInAstObjectInOrder(
recorder,
appRules,
prop.key.value,
prop.value.value,
4,
);
});

host.commitUpdate(recorder);

// this shouldn't be needed but at the moment without this formatting is not correct.
const content = readTsLintConfig(host, tsLintPath);
host.overwrite(tsLintPath, JSON.stringify(content.value, undefined, 2));
};
}

function addPostInstallScript() {
return (host: Tree) => {
const pkgJsonPath = '/package.json';
Expand Down Expand Up @@ -148,15 +220,14 @@ function addAppToWorkspaceFile(options: ApplicationOptions, workspace: Workspace
// if (workspaceJson.value === null) {
// throw new SchematicsException(`Unable to parse configuration file (${workspacePath}).`);
// }

let projectRoot = options.projectRoot !== undefined
? options.projectRoot
: `${workspace.newProjectRoot || ''}/${options.name}`;
: `${workspace.newProjectRoot}/${options.name}`;

if (projectRoot !== '' && !projectRoot.endsWith('/')) {
projectRoot += '/';
}
const rootFilesRoot = options.projectRoot === undefined
? projectRoot
: projectRoot + 'src/';

const schematics: JsonObject = {};

Expand Down Expand Up @@ -186,9 +257,10 @@ function addAppToWorkspaceFile(options: ApplicationOptions, workspace: Workspace
});
}

const sourceRoot = join(normalize(projectRoot), 'src');
const project: WorkspaceProject = {
root: projectRoot,
sourceRoot: join(normalize(projectRoot), 'src'),
sourceRoot,
projectType: ProjectType.Application,
prefix: options.prefix || 'app',
schematics,
Expand All @@ -197,25 +269,25 @@ function addAppToWorkspaceFile(options: ApplicationOptions, workspace: Workspace
builder: Builders.Browser,
options: {
outputPath: `dist/${options.name}`,
index: `${projectRoot}src/index.html`,
main: `${projectRoot}src/main.ts`,
polyfills: `${projectRoot}src/polyfills.ts`,
tsConfig: `${rootFilesRoot}tsconfig.app.json`,
index: `${sourceRoot}/index.html`,
main: `${sourceRoot}/main.ts`,
polyfills: `${sourceRoot}/polyfills.ts`,
tsConfig: `${projectRoot}tsconfig.app.json`,
assets: [
join(normalize(projectRoot), 'src', 'favicon.ico'),
join(normalize(projectRoot), 'src', 'assets'),
`${sourceRoot}/favicon.ico`,
`${sourceRoot}/assets`,
],
styles: [
`${projectRoot}src/styles.${options.style}`,
`${sourceRoot}/styles.${options.style}`,
],
scripts: [],
es5BrowserSupport: true,
},
configurations: {
production: {
fileReplacements: [{
replace: `${projectRoot}src/environments/environment.ts`,
with: `${projectRoot}src/environments/environment.prod.ts`,
replace: `${sourceRoot}/environments/environment.ts`,
with: `${sourceRoot}/environments/environment.prod.ts`,
}],
optimization: true,
outputHashing: 'all',
Expand Down Expand Up @@ -254,26 +326,26 @@ function addAppToWorkspaceFile(options: ApplicationOptions, workspace: Workspace
test: {
builder: Builders.Karma,
options: {
main: `${projectRoot}src/test.ts`,
polyfills: `${projectRoot}src/polyfills.ts`,
tsConfig: `${rootFilesRoot}tsconfig.spec.json`,
karmaConfig: `${rootFilesRoot}karma.conf.js`,
main: `${sourceRoot}/test.ts`,
polyfills: `${sourceRoot}/polyfills.ts`,
tsConfig: `${projectRoot}tsconfig.spec.json`,
karmaConfig: `${projectRoot}karma.conf.js`,
assets: [
`${sourceRoot}/favicon.ico`,
`${sourceRoot}/assets`,
],
styles: [
`${projectRoot}src/styles.${options.style}`,
`${sourceRoot}/styles.${options.style}`,
],
scripts: [],
assets: [
join(normalize(projectRoot), 'src', 'favicon.ico'),
join(normalize(projectRoot), 'src', 'assets'),
],
},
},
lint: {
builder: Builders.TsLint,
options: {
tsConfig: [
`${rootFilesRoot}tsconfig.app.json`,
`${rootFilesRoot}tsconfig.spec.json`,
`${projectRoot}tsconfig.app.json`,
`${projectRoot}tsconfig.spec.json`,
],
exclude: [
'**/node_modules/**',
Expand All @@ -282,19 +354,12 @@ function addAppToWorkspaceFile(options: ApplicationOptions, workspace: Workspace
},
},
};
// tslint:disable-next-line:no-any
// const projects: JsonObject = (<any> workspaceAst.value).projects || {};
// tslint:disable-next-line:no-any
// if (!(<any> workspaceAst.value).projects) {
// // tslint:disable-next-line:no-any
// (<any> workspaceAst.value).projects = projects;
// }

return addProjectToWorkspace(workspace, options.name, project);
}

function minimalPathFilter(path: string): boolean {
const toRemoveList = /(test.ts|tsconfig.spec.json|karma.conf.js).template$/;
const toRemoveList = /(test.ts|tsconfig.spec.json|karma.conf.js|tslint.json).template$/;

return !toRemoveList.test(path);
}
Expand All @@ -305,8 +370,8 @@ export default function (options: ApplicationOptions): Rule {
throw new SchematicsException(`Invalid options, "name" is required.`);
}
validateProjectName(options.name);
const prefix = options.prefix || 'app';
const appRootSelector = `${prefix}-root`;
options.prefix = options.prefix || 'app';
const appRootSelector = `${options.prefix}-root`;
const componentOptions: Partial<ComponentOptions> = !options.minimal ?
{
inlineStyle: options.inlineStyle,
Expand All @@ -323,23 +388,15 @@ export default function (options: ApplicationOptions): Rule {
};

const workspace = getWorkspace(host);
let newProjectRoot = workspace.newProjectRoot || '';
let appDir = `${newProjectRoot}/${options.name}`;
let sourceRoot = `${appDir}/src`;
let sourceDir = `${sourceRoot}/app`;
let relativePathToWorkspaceRoot = appDir.split('/').map(x => '..').join('/');
const rootInSrc = options.projectRoot !== undefined;
if (options.projectRoot !== undefined) {
newProjectRoot = options.projectRoot;
appDir = `${newProjectRoot}/src`;
sourceRoot = appDir;
sourceDir = `${sourceRoot}/app`;
relativePathToWorkspaceRoot = relative(normalize('/' + sourceRoot), normalize('/'));
if (relativePathToWorkspaceRoot === '') {
relativePathToWorkspaceRoot = '.';
}
}
const tsLintRoot = appDir;
const newProjectRoot = workspace.newProjectRoot || '';
const isRootApp = options.projectRoot !== undefined;
const appDir = isRootApp
? options.projectRoot as string
: `${newProjectRoot}/${options.name}`;
const relativePathToWorkspaceRoot = appDir
? appDir.split('/').map(() => '..').join('/')
: '.';
const sourceDir = `${appDir}/src/app`;

const e2eOptions: E2eOptions = {
relatedAppName: options.name,
Expand All @@ -349,43 +406,18 @@ export default function (options: ApplicationOptions): Rule {
return chain([
addAppToWorkspaceFile(options, workspace),
mergeWith(
apply(url('./files/src'), [
options.minimal ? filter(minimalPathFilter) : noop(),
applyTemplates({
utils: strings,
...options,
'dot': '.',
relativePathToWorkspaceRoot,
}),
move(sourceRoot),
])),
mergeWith(
apply(url('./files/root'), [
apply(url('./files'), [
options.minimal ? filter(minimalPathFilter) : noop(),
applyTemplates({
utils: strings,
...options,
'dot': '.',
relativePathToWorkspaceRoot,
rootInSrc,
appName: options.name,
isRootApp,
}),
isRootApp ? mergeWithRootTsLint(host) : noop(),
move(appDir),
])),
options.minimal ? noop() : mergeWith(
apply(url('./files/lint'), [
applyTemplates({
utils: strings,
...options,
tsLintRoot,
relativePathToWorkspaceRoot,
prefix,
}),
// TODO: Moving should work but is bugged right now.
// The __tsLintRoot__ is being used meanwhile.
// Otherwise the tslint.json file could be inside of the root folder and
// this block and the lint folder could be removed.
])),
]), MergeStrategy.Overwrite),
schematic('module', {
name: 'app',
commonModule: false,
Expand All @@ -410,11 +442,11 @@ export default function (options: ApplicationOptions): Rule {
? filter(path => !path.endsWith('.html.template'))
: noop(),
componentOptions.skipTests
? filter(path => !/[.|-]spec.ts.template$/.test(path))
? filter(path => !path.endsWith('.spec.ts.template'))
: noop(),
applyTemplates({
utils: strings,
...options as any, // tslint:disable-line:no-any
...options,
selector: appRootSelector,
...componentOptions,
}),
Expand All @@ -423,7 +455,7 @@ export default function (options: ApplicationOptions): Rule {
options.minimal ? noop() : schematic('e2e', e2eOptions),
options.enableIvy ? addPostInstallScript() : noop(),
options.skipPackageJson ? noop() : addDependenciesToPackageJson(options),
options.lintFix ? applyLintFix(sourceDir) : noop(),
options.lintFix ? applyLintFix(appDir) : noop(),
]);
};
}
Loading

0 comments on commit a7d095d

Please sign in to comment.