-
Notifications
You must be signed in to change notification settings - Fork 682
Expand file tree
/
Copy pathhooks.ts
More file actions
154 lines (118 loc) · 4.39 KB
/
hooks.ts
File metadata and controls
154 lines (118 loc) · 4.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import { conform } from '@ionic/utils-array';
import { prettyPath } from '@ionic/utils-terminal';
import * as Debug from 'debug';
import * as lodash from 'lodash';
import * as path from 'path';
import { HookFn, HookInput, HookName, IConfig, IProject, IShell } from '../definitions';
import { ancillary, failure, strong } from './color';
import { HookException } from './errors';
const debug = Debug('ionic:lib:hooks');
export interface HookDeps {
readonly config: IConfig;
readonly project: IProject;
readonly shell: IShell;
}
export abstract class Hook {
abstract readonly name: HookName;
get script() {
return `ionic:${this.name}`;
}
constructor(protected readonly e: HookDeps) {}
async run(input: HookInput) {
const { pkgManagerArgs } = await import('./utils/npm');
const type = this.e.project.type;
if (!type || !this.e.project.directory) {
return; // TODO: will we need hooks outside a project?
}
const [ pkg ] = await this.e.project.getPackageJson(undefined, { logErrors: false });
if (!pkg) {
return;
}
debug(`Looking for ${ancillary(this.script)} npm script.`);
const ctxEnvironment = this.generateCTXEnvironment(input);
if (pkg.scripts && pkg.scripts[this.script]) {
debug(`Invoking ${ancillary(this.script)} npm script.`);
const [ pkgManager, ...pkgArgs ] = await pkgManagerArgs(this.e.config.get('npmClient'), { command: 'run', script: this.script });
await this.e.shell.run(pkgManager, pkgArgs, {
env: ctxEnvironment,
});
}
const projectHooks = this.e.project.config.get('hooks');
const hooks = projectHooks ? conform(projectHooks[this.name]) : [];
for (const h of hooks) {
const p = path.resolve(this.e.project.directory, h);
try {
if (path.extname(p) !== '.js') {
throw new Error(`Hooks must be .js files with a function for its default export.`);
}
const hook = await this.loadHookFn(p);
if (!hook) {
throw new Error(`Module must have a function for its default export.`);
}
await hook(lodash.assign({}, input, {
project: {
type,
dir: this.e.project.directory,
srcDir: await this.e.project.getSourceDir(),
},
argv: process.argv,
env: {
...process.env,
...ctxEnvironment,
},
}));
} catch (e) {
throw new HookException(
`An error occurred while running an Ionic CLI hook defined in ${strong(prettyPath(this.e.project.filePath))}.\n` +
`Hook: ${strong(this.name)}\n` +
`File: ${strong(p)}\n\n` +
`${failure(e.stack ? e.stack : e)}`
);
}
}
}
protected async loadHookFn(p: string): Promise<HookFn | undefined> {
const module = require(p);
if (typeof module === 'function') {
return module;
} else if (typeof module.default === 'function') {
return module.default;
}
debug(`Could not load hook function ${strong(p)}: %o not a function`, module);
}
private generateCTXEnvironment(input: HookInput, path: string[] = []): NodeJS.ProcessEnv {
let environment: NodeJS.ProcessEnv = {};
input = !input ? {} : input;
for (const [key, value] of Object.entries(input)) {
if (typeof value === 'object') {
environment = {
...environment,
...this.generateCTXEnvironment(value, [...path, key]),
};
} else {
const name = [...path, key].join('_');
environment[`IONIC_CLI_HOOK_CTX_${lodash.snakeCase(name)}`.toUpperCase()] = value;
}
}
return environment;
}
}
export function addHook(baseDir: string, hooks: string | string[] | undefined, hook: string): string[] {
const hookPaths = conform(hooks);
const resolvedHookPaths = hookPaths.map(p => path.resolve(baseDir, p));
if (!resolvedHookPaths.includes(path.resolve(baseDir, hook))) {
hookPaths.push(hook);
}
return hookPaths;
}
export function removeHook(baseDir: string, hooks: string | string[] | undefined, hook: string): string[] {
const hookPaths = conform(hooks);
const i = locateHook(baseDir, hookPaths, hook);
if (i >= 0) {
hookPaths.splice(i, 1);
}
return hookPaths;
}
export function locateHook(baseDir: string, hooks: string[], hook: string): number {
return conform(hooks).map(p => path.resolve(baseDir, p)).indexOf(path.resolve(baseDir, hook));
}