Skip to content

Commit

Permalink
feat(generate): add guard generation
Browse files Browse the repository at this point in the history
  • Loading branch information
delasteve committed Feb 17, 2017
1 parent 9d29cbc commit 73a9273
Show file tree
Hide file tree
Showing 11 changed files with 394 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/documentation/generate.md
Expand Up @@ -10,6 +10,7 @@
- [component](generate/component)
- [directive](generate/directive)
- [enum](generate/enum)
- [guard](generate/guard)
- [interface](generate/interface)
- [module](generate/module)
- [pipe](generate/pipe)
Expand Down
11 changes: 11 additions & 0 deletions docs/documentation/generate/guard.md
@@ -0,0 +1,11 @@
# ng generate guard

## Overview
`ng generate guard [name]` generates a guard

## Options
`--flat` flag to indicate if a dir is created

`--spec` specifies if a spec file is generated

`--module` (`-m`) allows specification of the declaring module
@@ -0,0 +1,16 @@
/* tslint:disable:no-unused-variable */

import { TestBed, async, inject } from '@angular/core/testing';
import { <%= classifiedModuleName %>Guard } from './<%= dasherizedModuleName %>.guard';

describe('<%= classifiedModuleName %>Guard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [<%= classifiedModuleName %>Guard]
});
});

it('should ...', inject([<%= classifiedModuleName %>Guard], (guard: <%= classifiedModuleName %>Guard) => {
expect(guard).toBeTruthy();
}));
});
@@ -0,0 +1,12 @@
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class <%= classifiedModuleName %>Guard implements CanActivate {
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return true;
}
}
107 changes: 107 additions & 0 deletions packages/@angular/cli/blueprints/guard/index.ts
@@ -0,0 +1,107 @@
import {NodeHost} from '../../lib/ast-tools';
import { oneLine } from 'common-tags';

const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const dynamicPathParser = require('../../utilities/dynamic-path-parser');
const Blueprint = require('../../ember-cli/lib/models/blueprint');
const stringUtils = require('ember-cli-string-utils');
const astUtils = require('../../utilities/ast-utils');
const getFiles = Blueprint.prototype.files;

export default Blueprint.extend({
description: '',

availableOptions: [
{ name: 'flat', type: Boolean },
{ name: 'spec', type: Boolean },
{ name: 'module', type: String, aliases: ['m'] }
],

beforeInstall: function(options: any) {
if (options.module) {
// Resolve path to module
const modulePath = options.module.endsWith('.ts') ? options.module : `${options.module}.ts`;
const parsedPath = dynamicPathParser(this.project, modulePath);
this.pathToModule = path.join(this.project.root, parsedPath.dir, parsedPath.base);

if (!fs.existsSync(this.pathToModule)) {
throw 'Module specified does not exist';
}
}
},

normalizeEntityName: function (entityName: string) {
const parsedPath = dynamicPathParser(this.project, entityName);

this.dynamicPath = parsedPath;
return parsedPath.name;
},

locals: function (options: any) {
options.flat = options.flat !== undefined ?
options.flat :
this.project.ngConfigObj.get('defaults.guard.flat');

options.spec = options.spec !== undefined ?
options.spec :
this.project.ngConfigObj.get('defaults.guard.spec');

return {
dynamicPath: this.dynamicPath.dir,
flat: options.flat
};
},

files: function() {
let fileList = getFiles.call(this) as Array<string>;

if (this.options && !this.options.spec) {
fileList = fileList.filter(p => p.indexOf('__name__.guard.spec.ts') < 0);
}

return fileList;
},

fileMapTokens: function (options: any) {
// Return custom template variables here.
return {
__path__: () => {
let dir = this.dynamicPath.dir;
if (!options.locals.flat) {
dir += path.sep + options.dasherizedModuleName;
}
this.generatePath = dir;
return dir;
}
};
},

afterInstall(options: any) {
const returns: Array<any> = [];

if (!this.pathToModule) {
const warningMessage = oneLine`
Guard is generated but not provided,
it must be provided to be used
`;
this._writeStatusToUI(chalk.yellow, 'WARNING', warningMessage);
} else {
const className = stringUtils.classify(`${options.entity.name}Guard`);
const fileName = stringUtils.dasherize(`${options.entity.name}.guard`);
const fullGeneratePath = path.join(this.project.root, this.generatePath);
const moduleDir = path.parse(this.pathToModule).dir;
const relativeDir = path.relative(moduleDir, fullGeneratePath);
const importPath = relativeDir ? `./${relativeDir}/${fileName}` : `./${fileName}`;
returns.push(
astUtils.addProviderToModule(this.pathToModule, className, importPath)
.then((change: any) => change.apply(NodeHost)));
this._writeStatusToUI(chalk.yellow,
'update',
path.relative(this.project.root, this.pathToModule));
}

return Promise.all(returns);
}
});
18 changes: 18 additions & 0 deletions packages/@angular/cli/lib/config/schema.json
Expand Up @@ -319,6 +319,21 @@
"default": true
},
"spec": {
"description": "Generate a directive spec file",
"type": "boolean",
"default": true
}
}
},
"guard": {
"type": "object",
"properties": {
"flat": {
"type": "boolean",
"default": true
},
"spec": {
"description": "Generate a guard spec file",
"type": "boolean",
"default": true
}
Expand All @@ -341,6 +356,7 @@
"default": false
},
"spec": {
"description": "Generate a module spec file",
"type": "boolean",
"default": false
}
Expand All @@ -354,6 +370,7 @@
"default": true
},
"spec": {
"description": "Generate a pipe spec file",
"type": "boolean",
"default": true
}
Expand All @@ -367,6 +384,7 @@
"default": true
},
"spec": {
"description": "Generate a service spec file",
"type": "boolean",
"default": true
}
Expand Down
4 changes: 4 additions & 0 deletions packages/@ngtools/json-schema/tests/serializer/schema3.json
Expand Up @@ -212,6 +212,10 @@
"type": "boolean",
"default": true
},
"guard": {
"type": "boolean",
"default": true
},
"module": {
"type": "boolean",
"default": false
Expand Down

0 comments on commit 73a9273

Please sign in to comment.