Skip to content
This repository was archived by the owner on Apr 4, 2025. It is now read-only.

Commit 2fe2836

Browse files
committed
refactor: refactor interfaces
Better separation of concern between tooling and schematic library. Engine, Collection and Schematic now take a generic type that can add tooling-specific metadata to each parts, in a type-safe manner. Context exposed to schematics is a context of <any, any>, while the tool should use TypedContext for better support internally. The Engine Host now only deals with Descriptions of collection and schematics, does not deal with actual implementation. Renamed CliEngineHost to NodeModulesEngineHost, since its kind of reusable if you only implement a NodeModules schematic tool. Tempted to move this into the schematics library as its highly reusable. Added tooling/ in the schematics package, which contains implementations of some interfaces that should contain conventions.
1 parent d422f9b commit 2fe2836

30 files changed

+485
-391
lines changed

lib/packages.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@ const packages =
2323
glob.sync(path.join(packageRoot, '*/package.json')),
2424
glob.sync(path.join(packageRoot, '*/*/package.json')))
2525
.filter(p => !p.match(/blueprints/))
26-
.map(pkgPath => path.relative(packageRoot, path.dirname(pkgPath)))
27-
.map(pkgName => {
28-
return { name: pkgName, root: path.join(packageRoot, pkgName) };
26+
.map(pkgPath => [pkgPath, path.relative(packageRoot, path.dirname(pkgPath))])
27+
.map(([pkgPath, pkgName]) => {
28+
return { name: pkgName, root: path.dirname(pkgPath) };
2929
})
3030
.reduce((packages, pkg) => {
3131
let pkgJson = JSON.parse(fs.readFileSync(path.join(pkg.root, 'package.json'), 'utf8'));

packages/schematics/BUILD

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ ts_library(
1515
"//packages/schematics/src/rules",
1616
"//packages/schematics/src/sink",
1717
"//packages/schematics/src/tree",
18+
"//packages/schematics/tooling",
1819
],
1920
tsconfig = "//:tsconfig.json",
2021
visibility = [ "//visibility:public" ],

packages/schematics/README.md

Lines changed: 8 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -26,94 +26,15 @@ The tooling is responsible for the following tasks:
2626

2727
1. Create the Schematic Engine, and pass in a Collection and Schematic loader.
2828
1. Understand and respect the Schematics metadata and dependencies between collections. Schematics can refer to dependencies, and it's the responsibility of the tool to honor those dependencies. The reference CLI uses NPM packages for its collections.
29-
1. Create the Options object. Options can be anything, but the schematics can specify a JSON Schema that should be respected. The reference CLI, for example, parses the arguments as a JSON object and validate it with the Schema specified by the collection.
29+
1. Create the Options object. Options can be anything, but the schematics can specify a JSON Schema that should be respected. The reference CLI, for example, parse the arguments as a JSON object and validate it with the Schema specified by the collection.
3030
1. Call the schematics with the original Tree. The tree should represent the initial state of the filesystem. The reference CLI uses the current directory for this.
3131
1. Create a Sink and commit the result of the schematics to the Sink. Many sinks are provided by the library; FileSystemSink and DryRunSink are examples.
3232
1. Output any logs propagated by the library, including debugging information.
3333

3434
The tooling API is composed of the following pieces:
3535

36-
## EngineHost
37-
The `SchematicEngine` is responsible for loading and constructing `Collection`s and `Schematics`'. When creating an engine, the tooling provides an `EngineHost` interface that understands how to create a `CollectionDescription` from a name, how to create a `SchematicDescription` from a `CollectionDescription` and a name, as well as how to create the `Rule` factory for that Schematics. Both of which are information necessary for the `Engine` to work properly.
38-
39-
All Description interfaces are generics that take interfaces as type parameters. Those interfaces can be used by the tooling to store additional information in the `CollectionDescription` and the `SchematicDescription`. The descriptions returned by the host are guaranteed to be the same objects when passing them as input.
40-
41-
### CollectionDescription
42-
A `CollectionDescription` is the minimum amount of information that `Engine` needs to create a collection. It is currently only a `name`, which is used to validate the collection and cache it.
43-
44-
### SchematicDescription
45-
A `SchematicDescription` is the minimum amount of information that `Engine` needs to create a schematic. It is currently a `name` (which is used to be cached), and a `CollectionDescription`. The collection description is asserted to be the same description as passed in. It is used later on to reference collections when schematics are created by name only.
46-
47-
### Source from URL
48-
It is possible for schematics to create `Source`s from a URL. These are useful when we want to load a list of template files. There are 3 default URL protocols supported by the Engine:
49-
50-
- `null:` returns a Tree that's invalid and will throw exceptions.
51-
- `empty:` returns a Tree that's empty.
52-
- `host:` returns a copy of the host passed to this schematic, from the context.
53-
54-
### RuleFactory
55-
The other method necessary to resolve a schematics is the `RuleFactory`, a function that takes an option argument and returns a `Rule`. That factory is created from both descriptions by the host and the result will be called by the Engine when necessary. Please note that the engine cache this `RuleFactory` based on both descriptions, so if a schematic is created twice the `getSchematicRuleFactory` host function will only be called once.
56-
57-
### Default MergeStrategy
58-
The `EngineHost` can have an optional `defaultMergeStrategy` to specify how the tooling wants to set the default `MergeStrategy`. This will be used if schematics don't specify a merge strategy on their own.
59-
60-
## EngineHost Implementations
61-
62-
### NodeModulesEngineHost
63-
The Schematics library provides an EngineHost that understands NPM node modules, using node modules to define collections and schematics.
64-
65-
This engine host use the following conventions:
66-
67-
1. A node package needs to define a `schematics` key in its `package.json`, which points to a JSON file that contains collection metadata. This metadata is of the follpwing type:
68-
69-
```typescript
70-
interface NodeModuleCollectionJson {
71-
name: string;
72-
version?: string;
73-
description: string;
74-
schematics: {
75-
[name: string]: {
76-
factory: string;
77-
description: string;
78-
schema?: string;
79-
}
80-
};
81-
}
82-
```
83-
84-
The name must be the same name as the NPM package.
85-
1. The `schematics` dictionary is used to resolve schematics information.
86-
- The `factory` is a string of the form `modulePath#ExportName`. It is resolved relative to the collection JSON file, and the `ExportName` will be `default` if not specified.
87-
- The `schema` is a string that points to a JSON Schema file (relative to the collection JSON file).
88-
- The `description` field is a description that can be used by the tooling to show to the user.
89-
1. The `RuleFactory` is loaded from the `factory` field above by using `require()`. The `SchematicDescription` contains the name and more information necessary for the Host to resolve more.
90-
1. This EngineHost also registers some URLs:
91-
- `file:` (or not specifying a protocol) supports loading a file system from the disk.
92-
93-
# Schematics
94-
A schematics is defined by the `RuleFactory` and its `SchematicDescription`, which contains the name and collection.
95-
96-
## Tree
97-
By definition, a schematic is a transformation between a `Tree` and another `Tree`. It receives a host `Tree`, and applies a list of actions to it, potentially returning it at the end.
98-
99-
## Action
100-
A tree is transformed by staging actions, which can write over a file, create new files, rename or delete existing files.
101-
102-
## Branching
103-
A tree can be branched, keeping its history, then adding actions on top of it. Two trees that are being merged will ignore their common history.
104-
105-
## Merging
106-
Merging two trees results in a tree containing all actions. If two actions apply on the same path, it is automatically considered a conflict and needs to be resolved.
107-
108-
### Conflicts
109-
Merge conflicts are resolved using the chosen `MergeStrategy` (with the default set by the tooling):
110-
111-
1. `MergeStrategy.Error`. Throw an exception and stops creating the schematic.
112-
1. `MergeStrategy.Overwrite`. The action from the last merge argument is preferred.
113-
1. `MergeStrategy.ContentOnly`. Creation or Renaming the same file will throw an exception, but overwriting its content will resolve as if `MergeStrategy.Overwrite` is chosen.
114-
115-
## Optimize
116-
Optimizing a tree results in the tree with a smaller staging; actions that overrules each other within the same tree are removed or simplified. The history of the tree is NOT preserved, but only the staged actions are changed.
36+
## Engine
37+
The `SchematicEngine` is responsible for loading and constructing `Collection`s and `Schematics`'. When creating an engine, the tooling provides an `EngineHost` interface that understands how to create a `CollectionDescription` from a name, and how to create a `Schematic
11738

11839
# Examples
11940

@@ -131,20 +52,11 @@ export default function MySchematic(options: any) {
13152
}
13253
```
13354

134-
## Templated Source
135-
An example of a simple Schematics which reads a directory and apply templates to its content and path.
55+
A few things from this example:
56+
57+
1. The function receives the list of options from the tooling.
58+
1. It returns a [`Rule`](src/engine/interface.ts#L73), which is a transformation from a `Tree` to another `Tree`.
13659

137-
```typescript
138-
import {apply, mergeWith, template, url} from '@angular/schematics';
139-
140-
export default function(options: any) {
141-
return mergeWith([
142-
apply(url('./files'), [
143-
template({ utils: stringUtils, ...options })
144-
])
145-
]);
146-
};
147-
```
14860

14961

15062
# Future Work
@@ -154,5 +66,4 @@ Schematics is not done yet. Here's a list of things we are considering:
15466
* Smart defaults for Options. Having a JavaScript function for default values based on other default values.
15567
* Prompt for input options. This should only be prompted for the original schematics, dependencies to other schematics should not trigger another prompting.
15668
* Tasks for running tooling-specific jobs before and after a schematics has been scaffolded. Such tasks can involve initialize git, or npm install. A specific list of tasks should be provided by the tool, with unsupported tasks generating an error.
157-
* Better URL support for more consistency. Right now tools define their own URLs without having consistency between two tools, which means that there is still some cohesion between the schematic and the tool.
158-
* Annotation support. Annotations are being designed right now, but they will be a type-safe way to attach metadata to a file that is updated if the file changes content. Such Annotation could tell if a file is, e.g., a test file, or binary, or the annotation could be the TypeScript AST of the file itself.
69+

packages/schematics/src/engine/collection.ts

Lines changed: 9 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -6,55 +6,19 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88
import {SchematicEngine} from './engine';
9-
import {Collection, CollectionDescription, Schematic, SchematicDescription} from './interface';
10-
import {BaseException} from '../exception/exception';
9+
import {Collection, CollectionDescription, Schematic} from './interface';
1110

1211

13-
14-
export class UnknownSchematicNameException extends BaseException {
15-
constructor(collection: string, name: string) {
16-
super(`Schematic named "${name}" could not be found in collection "${collection}".`);
17-
}
18-
}
19-
export class InvalidSchematicException extends BaseException {
20-
constructor(name: string) { super(`Invalid schematic: "${name}".`); }
21-
}
22-
23-
24-
export class CollectionImpl implements Collection {
25-
private _schematics: { [name: string]: (options: any) => Schematic | null } = {};
26-
27-
constructor(private _description: CollectionDescription,
28-
private _engine: SchematicEngine) {
29-
Object.keys(this._description.schematics).forEach(name => {
30-
this._schematics[name] = (options: any) => this._engine.createSchematic(name, this, options);
31-
});
32-
}
33-
34-
get engine() { return this._engine; }
35-
get name() { return this._description.name || '<unknown>'; }
36-
get path() { return this._description.path || '<unknown>'; }
37-
38-
listSchematicNames(): string[] {
39-
return Object.keys(this._schematics);
40-
}
41-
42-
getSchematicDescription(name: string): SchematicDescription | null {
43-
if (!(name in this._description.schematics)) {
44-
return null;
45-
}
46-
return this._description.schematics[name];
12+
export class CollectionImpl<CollectionT, SchematicT>
13+
implements Collection<CollectionT, SchematicT> {
14+
constructor(private _description: CollectionDescription<CollectionT>,
15+
private _engine: SchematicEngine<CollectionT, SchematicT>) {
4716
}
4817

49-
createSchematic<T>(name: string, options: T): Schematic {
50-
if (!(name in this._schematics)) {
51-
throw new UnknownSchematicNameException(this.name, name);
52-
}
18+
get description() { return this._description; }
19+
get name() { return this.description.name || '<unknown>'; }
5320

54-
const schematic = this._schematics[name](options);
55-
if (!schematic) {
56-
throw new InvalidSchematicException(name);
57-
}
58-
return schematic;
21+
createSchematic(name: string): Schematic<CollectionT, SchematicT> {
22+
return this._engine.createSchematic(name, this);
5923
}
6024
}

packages/schematics/src/engine/context.ts

Lines changed: 0 additions & 23 deletions
This file was deleted.

packages/schematics/src/engine/engine.ts

Lines changed: 76 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -8,71 +8,108 @@
88
import {CollectionImpl} from './collection';
99
import {
1010
Collection,
11-
Engine, EngineHost,
12-
ProtocolHandler,
11+
Engine,
12+
EngineHost,
1313
Schematic,
14-
SchematicContext,
15-
Source
14+
Source,
15+
TypedSchematicContext
1616
} from './interface';
1717
import {SchematicImpl} from './schematic';
1818
import {BaseException} from '../exception/exception';
19-
import {empty} from '../tree/static';
19+
import {MergeStrategy} from '../tree/interface';
20+
import {NullTree} from '../tree/null';
21+
import {branch, empty} from '../tree/static';
2022

2123
import {Url, parse, format} from 'url';
24+
import 'rxjs/add/operator/map';
2225

2326

24-
export class InvalidSourceUrlException extends BaseException {
25-
constructor(url: string) { super(`Invalid source url: "${url}".`); }
26-
}
2727
export class UnknownUrlSourceProtocol extends BaseException {
2828
constructor(url: string) { super(`Unknown Protocol on url "${url}".`); }
2929
}
3030

31+
export class UnknownCollectionException extends BaseException {
32+
constructor(name: string) { super(`Unknown collection "${name}".`); }
33+
}
34+
export class UnknownSchematicException extends BaseException {
35+
constructor(name: string, collection: Collection<any, any>) {
36+
super(`Schematic "${name}" not found in collection "${collection.name}".`);
37+
}
38+
}
39+
40+
41+
export class SchematicEngine<CollectionT, SchematicT> implements Engine<CollectionT, SchematicT> {
42+
private _collectionCache = new Map<string, CollectionImpl<CollectionT, SchematicT>>();
43+
private _schematicCache
44+
= new Map<string, Map<string, SchematicImpl<CollectionT, SchematicT>>>();
3145

32-
export class SchematicEngine implements Engine {
33-
private _protocolMap = new Map<string, ProtocolHandler>();
34-
35-
constructor(private _options: EngineHost) {
36-
// Default implementations.
37-
this._protocolMap.set('null', () => {
38-
return () => empty();
39-
});
40-
this._protocolMap.set('', (url: Url) => {
41-
// Make a copy, change the protocol.
42-
const fileUrl = parse(format(url));
43-
fileUrl.protocol = 'file:';
44-
return (context: SchematicContext) => context.engine.createSourceFromUrl(fileUrl)(context);
45-
});
46+
constructor(private _host: EngineHost<CollectionT, SchematicT>) {
4647
}
4748

48-
createCollection(name: string): Collection | null {
49-
const description = this._options.loadCollection(name);
49+
get defaultMergeStrategy() { return this._host.defaultMergeStrategy || MergeStrategy.Default; }
50+
51+
createCollection(name: string): Collection<CollectionT, SchematicT> {
52+
let collection = this._collectionCache.get(name);
53+
if (collection) {
54+
return collection;
55+
}
56+
57+
const description = this._host.createCollectionDescription(name);
5058
if (!description) {
51-
return null;
59+
throw new UnknownCollectionException(name);
5260
}
5361

54-
return new CollectionImpl(description, this);
62+
collection = new CollectionImpl<CollectionT, SchematicT>(description, this);
63+
this._collectionCache.set(name, collection);
64+
this._schematicCache.set(name, new Map());
65+
return collection;
5566
}
5667

57-
createSchematic<T>(name: string, collection: Collection, options: T): Schematic | null {
58-
const description = this._options.loadSchematic<T>(name, collection, options);
59-
if (!description) {
60-
return null;
68+
createSchematic(
69+
name: string,
70+
collection: Collection<CollectionT, SchematicT>): Schematic<CollectionT, SchematicT> {
71+
const collectionImpl = this._collectionCache.get(collection.name);
72+
const schematicMap = this._schematicCache.get(collection.name);
73+
if (!collectionImpl || !schematicMap || collectionImpl !== collection) {
74+
// This is weird, maybe the collection was created by another engine?
75+
throw new UnknownCollectionException(collection.name);
6176
}
6277

63-
return new SchematicImpl(description, collection);
64-
}
78+
let schematic = schematicMap.get(name);
79+
if (schematic) {
80+
return schematic;
81+
}
82+
83+
const description = this._host.createSchematicDescription(name, collection.description);
84+
if (!description) {
85+
throw new UnknownSchematicException(name, collection);
86+
}
87+
const factory = this._host.getSchematicRuleFactory(description, collection.description);
88+
schematic = new SchematicImpl<CollectionT, SchematicT>(description, factory, collection, this);
6589

66-
registerUrlProtocolHandler(protocol: string, handler: ProtocolHandler) {
67-
this._protocolMap.set(protocol, handler);
90+
schematicMap.set(name, schematic);
91+
return schematic;
6892
}
6993

7094
createSourceFromUrl(url: Url): Source {
71-
const protocol = (url.protocol || '').replace(/:$/, '');
72-
const handler = this._protocolMap.get(protocol);
73-
if (!handler) {
74-
throw new UnknownUrlSourceProtocol(url.toString());
95+
switch (url.protocol) {
96+
case 'null:': return () => new NullTree();
97+
case 'empty:': return () => empty();
98+
case 'host:': return (context: TypedSchematicContext<CollectionT, SchematicT>) => {
99+
return context.host.map(tree => branch(tree));
100+
};
101+
case '':
102+
const fileUrl = parse(format(url));
103+
fileUrl.protocol = 'file:';
104+
return (context: TypedSchematicContext<CollectionT, SchematicT>) => {
105+
return context.engine.createSourceFromUrl(fileUrl)(context);
106+
};
107+
default:
108+
const hostSource = this._host.createSourceFromUrl(url);
109+
if (!hostSource) {
110+
throw new UnknownUrlSourceProtocol(url.toString());
111+
}
112+
return hostSource;
75113
}
76-
return handler(url);
77114
}
78115
}

0 commit comments

Comments
 (0)