@biorate/hygen 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +25 -0
- package/README.md +146 -2
- package/dist/cjs/bin.js +26 -0
- package/dist/cjs/index.js +17 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/src/cli-help.js +19 -0
- package/dist/cjs/src/config-resolver.js +66 -0
- package/dist/cjs/src/config.js +37 -0
- package/dist/cjs/src/context.js +37 -0
- package/dist/cjs/src/engine.js +149 -0
- package/dist/cjs/src/errors.js +116 -0
- package/dist/cjs/src/execute.js +48 -0
- package/dist/cjs/src/help.js +89 -0
- package/dist/cjs/src/helpers.js +24 -0
- package/dist/cjs/src/index.js +42 -0
- package/dist/cjs/src/logger.js +28 -0
- package/dist/cjs/src/newline.js +13 -0
- package/dist/cjs/src/ops/add.js +74 -0
- package/dist/cjs/src/ops/anchors.js +45 -0
- package/dist/cjs/src/ops/echo.js +17 -0
- package/dist/cjs/src/ops/index.js +51 -0
- package/dist/cjs/src/ops/inject.js +37 -0
- package/dist/cjs/src/ops/injector.js +49 -0
- package/dist/cjs/src/ops/result.js +9 -0
- package/dist/cjs/src/ops/setup.js +52 -0
- package/dist/cjs/src/ops/shell.js +38 -0
- package/dist/cjs/src/params.js +77 -0
- package/dist/cjs/src/path-macros.js +30 -0
- package/dist/cjs/src/prompt.js +111 -0
- package/dist/cjs/src/render.js +189 -0
- package/dist/cjs/src/runner.js +38 -0
- package/dist/cjs/src/types.js +2 -0
- package/dist/cjs/templates/init/repo/new-repo.ejs.t +4 -0
- package/dist/cjs/templates/init/self/new-generator-help.ejs.t +8 -0
- package/dist/cjs/templates/init/self/new-generator-with-prompt.ejs.t +21 -0
- package/dist/cjs/templates/init/self/new-generator-with-prompt.prompt.ejs.t +17 -0
- package/dist/cjs/templates/init/self/new-generator.ejs.t +21 -0
- package/dist/cjs/templates/init/self/new-repo.ejs.t +7 -0
- package/dist/esm/bin.js +21 -0
- package/dist/esm/index.js +1 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/src/cli-help.js +14 -0
- package/dist/esm/src/config-resolver.js +37 -0
- package/dist/esm/src/config.js +29 -0
- package/dist/esm/src/context.js +32 -0
- package/dist/esm/src/engine.js +118 -0
- package/dist/esm/src/errors.js +98 -0
- package/dist/esm/src/execute.js +41 -0
- package/dist/esm/src/help.js +78 -0
- package/dist/esm/src/helpers.js +19 -0
- package/dist/esm/src/index.js +6 -0
- package/dist/esm/src/logger.js +23 -0
- package/dist/esm/src/newline.js +11 -0
- package/dist/esm/src/ops/add.js +69 -0
- package/dist/esm/src/ops/anchors.js +41 -0
- package/dist/esm/src/ops/echo.js +12 -0
- package/dist/esm/src/ops/index.js +26 -0
- package/dist/esm/src/ops/inject.js +32 -0
- package/dist/esm/src/ops/injector.js +44 -0
- package/dist/esm/src/ops/result.js +7 -0
- package/dist/esm/src/ops/setup.js +47 -0
- package/dist/esm/src/ops/shell.js +33 -0
- package/dist/esm/src/params.js +71 -0
- package/dist/esm/src/path-macros.js +24 -0
- package/dist/esm/src/prompt.js +81 -0
- package/dist/esm/src/render.js +182 -0
- package/dist/esm/src/runner.js +32 -0
- package/dist/esm/src/types.js +1 -0
- package/dist/esm/templates/init/repo/new-repo.ejs.t +4 -0
- package/dist/esm/templates/init/self/new-generator-help.ejs.t +8 -0
- package/dist/esm/templates/init/self/new-generator-with-prompt.ejs.t +21 -0
- package/dist/esm/templates/init/self/new-generator-with-prompt.prompt.ejs.t +17 -0
- package/dist/esm/templates/init/self/new-generator.ejs.t +21 -0
- package/dist/esm/templates/init/self/new-repo.ejs.t +7 -0
- package/dist/types/bin.d.ts +2 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/src/cli-help.d.ts +3 -0
- package/dist/types/src/config-resolver.d.ts +4 -0
- package/dist/types/src/config.d.ts +14 -0
- package/dist/types/src/context.d.ts +12 -0
- package/dist/types/src/engine.d.ts +6 -0
- package/dist/types/src/errors.d.ts +50 -0
- package/dist/types/src/execute.d.ts +5 -0
- package/dist/types/src/help.d.ts +8 -0
- package/dist/types/src/helpers.d.ts +22 -0
- package/dist/types/src/index.d.ts +6 -0
- package/dist/types/src/logger.d.ts +10 -0
- package/dist/types/src/newline.d.ts +2 -0
- package/dist/types/src/ops/add.d.ts +3 -0
- package/dist/types/src/ops/anchors.d.ts +4 -0
- package/dist/types/src/ops/echo.d.ts +3 -0
- package/dist/types/src/ops/index.d.ts +4 -0
- package/dist/types/src/ops/inject.d.ts +3 -0
- package/dist/types/src/ops/injector.d.ts +3 -0
- package/dist/types/src/ops/result.d.ts +3 -0
- package/dist/types/src/ops/setup.d.ts +3 -0
- package/dist/types/src/ops/shell.d.ts +3 -0
- package/dist/types/src/params.d.ts +4 -0
- package/dist/types/src/path-macros.d.ts +3 -0
- package/dist/types/src/prompt.d.ts +8 -0
- package/dist/types/src/render.d.ts +2 -0
- package/dist/types/src/runner.d.ts +3 -0
- package/dist/types/src/types.d.ts +94 -0
- package/package.json +82 -4
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import helpers from './helpers.js';
|
|
2
|
+
const localsToCapitalize = ['name'];
|
|
3
|
+
const localsToPluralize = ['name'];
|
|
4
|
+
const localsDefaults = {
|
|
5
|
+
name: 'unnamed',
|
|
6
|
+
};
|
|
7
|
+
const processLocals = (hsh, [key, value]) => {
|
|
8
|
+
hsh[key] = value;
|
|
9
|
+
if (localsToCapitalize.includes(key)) {
|
|
10
|
+
hsh[helpers.capitalize(key)] = helpers.capitalize(value);
|
|
11
|
+
}
|
|
12
|
+
if (localsToPluralize.includes(key)) {
|
|
13
|
+
hsh[helpers.inflection.pluralize(key)] = helpers.inflection.pluralize(value);
|
|
14
|
+
hsh[helpers.capitalize(helpers.inflection.pluralize(key))] = helpers.capitalize(helpers.inflection.pluralize(value));
|
|
15
|
+
}
|
|
16
|
+
return hsh;
|
|
17
|
+
};
|
|
18
|
+
const processedLocals = (locals) => Object.entries(locals).reduce(processLocals, {});
|
|
19
|
+
const context = (locals, config = {}) => {
|
|
20
|
+
const localsWithDefaults = {
|
|
21
|
+
...localsDefaults,
|
|
22
|
+
...config.localsDefaults,
|
|
23
|
+
...locals,
|
|
24
|
+
};
|
|
25
|
+
const configHelpers = typeof config.helpers === 'function'
|
|
26
|
+
? config.helpers(locals, config)
|
|
27
|
+
: config.helpers ?? {};
|
|
28
|
+
return Object.assign(localsWithDefaults, processedLocals(localsWithDefaults), {
|
|
29
|
+
h: { ...helpers, ...configHelpers },
|
|
30
|
+
});
|
|
31
|
+
};
|
|
32
|
+
export default context;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import fs from 'fs-extra';
|
|
3
|
+
import params from './params.js';
|
|
4
|
+
import prompt, { pickGeneratorAction } from './prompt.js';
|
|
5
|
+
import { ShowHelpError, KeepGoingError } from './errors.js';
|
|
6
|
+
import { isHelpFlag, printUsage } from './cli-help.js';
|
|
7
|
+
const isInteractive = ({ interactive }) => interactive === true
|
|
8
|
+
? true
|
|
9
|
+
: interactive === false
|
|
10
|
+
? false
|
|
11
|
+
: Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
12
|
+
const engine = async (argv, config) => {
|
|
13
|
+
const { cwd, templates, logger } = config;
|
|
14
|
+
let base = Object.assign(await params(config, argv), { cwd });
|
|
15
|
+
let { generator, actions, names } = base;
|
|
16
|
+
if (isHelpFlag(argv)) {
|
|
17
|
+
printUsage(logger);
|
|
18
|
+
}
|
|
19
|
+
if (!generator && isInteractive(config) && templates && fs.pathExistsSync(templates)) {
|
|
20
|
+
const picked = await pickGeneratorAction(config);
|
|
21
|
+
if (picked) {
|
|
22
|
+
base = Object.assign(await params(config, [picked.generator, picked.action, ...argv]), {
|
|
23
|
+
cwd,
|
|
24
|
+
});
|
|
25
|
+
({ generator, actions, names } = base);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const cleanArgv = (base.cleanArgv ?? {});
|
|
29
|
+
logger.log(base.dry ? '(dry mode)' : '');
|
|
30
|
+
if (!generator) {
|
|
31
|
+
throw new ShowHelpError('please specify a generator.\n\nTip: running `hygen` with no arguments in a terminal opens an interactive generator/action picker (requires a TTY).');
|
|
32
|
+
}
|
|
33
|
+
if (!actions || actions.length === 0) {
|
|
34
|
+
throw new ShowHelpError(`please specify an action for ${generator}.`);
|
|
35
|
+
}
|
|
36
|
+
logger.log(`Loaded templates: ${templates.replace(`${cwd}/`, '')}`);
|
|
37
|
+
const nameList = names ?? [undefined];
|
|
38
|
+
const keepGoing = Boolean(cleanArgv['keep-going']);
|
|
39
|
+
const failures = [];
|
|
40
|
+
const results = [];
|
|
41
|
+
const statuses = [];
|
|
42
|
+
const execute = (await import('./execute.js')).execute;
|
|
43
|
+
const render = (await import('./render.js')).render;
|
|
44
|
+
for (const name of nameList) {
|
|
45
|
+
for (const action of actions) {
|
|
46
|
+
const [mainAction, subaction] = action.split(':');
|
|
47
|
+
const actionfolder = path.join(base.templates, generator, mainAction);
|
|
48
|
+
const pairLabel = `action '${action}'${name !== undefined ? ` for name '${name}'` : ''}`;
|
|
49
|
+
const statusPair = {
|
|
50
|
+
action,
|
|
51
|
+
...(name !== undefined ? { name } : {}),
|
|
52
|
+
};
|
|
53
|
+
const singleRun = nameList.length === 1 && actions.length === 1;
|
|
54
|
+
if (!(await fs.pathExists(actionfolder))) {
|
|
55
|
+
const err = new ShowHelpError(`I can't find action '${action}' for generator '${generator}'.
|
|
56
|
+
|
|
57
|
+
You can try:
|
|
58
|
+
1. 'hygen init self' to initialize your project, and
|
|
59
|
+
2. 'hygen generator new ${generator}' to build the generator you wanted.
|
|
60
|
+
|
|
61
|
+
Check out the quickstart for more: http://www.hygen.io/docs/quick-start
|
|
62
|
+
`);
|
|
63
|
+
if (singleRun)
|
|
64
|
+
throw err;
|
|
65
|
+
if (!keepGoing)
|
|
66
|
+
throw err;
|
|
67
|
+
failures.push({
|
|
68
|
+
action,
|
|
69
|
+
...(name !== undefined ? { name } : {}),
|
|
70
|
+
error: err.message,
|
|
71
|
+
});
|
|
72
|
+
statuses.push({ ...statusPair, status: 'failed' });
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
const promptArgs = await prompt(config.createPrompter, actionfolder, {
|
|
77
|
+
...(name ? { name } : {}),
|
|
78
|
+
...cleanArgv,
|
|
79
|
+
});
|
|
80
|
+
const args = Object.assign({
|
|
81
|
+
templates: base.templates,
|
|
82
|
+
actionfolder,
|
|
83
|
+
generator,
|
|
84
|
+
action,
|
|
85
|
+
subaction,
|
|
86
|
+
}, { _: base._, ts: base.ts }, cleanArgv, name ? { name } : {}, promptArgs);
|
|
87
|
+
const el = await execute(await render(args, config), args, config);
|
|
88
|
+
for (const pairResult of el.results) {
|
|
89
|
+
results.push({
|
|
90
|
+
...pairResult,
|
|
91
|
+
action,
|
|
92
|
+
...(name !== undefined ? { name } : {}),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
statuses.push(...el.statuses);
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
const e = err;
|
|
99
|
+
if (singleRun)
|
|
100
|
+
throw err;
|
|
101
|
+
if (!keepGoing) {
|
|
102
|
+
throw new ShowHelpError(`${pairLabel} failed: ${e.message}`);
|
|
103
|
+
}
|
|
104
|
+
failures.push({
|
|
105
|
+
action,
|
|
106
|
+
...(name !== undefined ? { name } : {}),
|
|
107
|
+
error: e.message,
|
|
108
|
+
});
|
|
109
|
+
statuses.push({ ...statusPair, status: 'failed' });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (failures.length > 0) {
|
|
114
|
+
throw new KeepGoingError(failures, results, statuses);
|
|
115
|
+
}
|
|
116
|
+
return Object.assign(results, { statuses });
|
|
117
|
+
};
|
|
118
|
+
export { engine, ShowHelpError, KeepGoingError };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { BaseError } from '@biorate/errors';
|
|
2
|
+
export class ShowHelpError extends BaseError {
|
|
3
|
+
constructor(message) {
|
|
4
|
+
super('%s', [message]);
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
export class KeepGoingError extends ShowHelpError {
|
|
8
|
+
constructor(failures, results, statuses = []) {
|
|
9
|
+
super(`the run failed for ${failures.length} pair(s):\n${failures
|
|
10
|
+
.map((f) => `action '${f.action}'${f.name !== undefined ? ` for name '${f.name}'` : ''}: ${f.error}`)
|
|
11
|
+
.join('\n')}`);
|
|
12
|
+
this.results = results;
|
|
13
|
+
this.failures = failures;
|
|
14
|
+
this.statuses = statuses;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export class TemplateRenderError extends BaseError {
|
|
18
|
+
constructor(file, cause) {
|
|
19
|
+
super('Template render error in [%s]: [%s]', [
|
|
20
|
+
file,
|
|
21
|
+
cause?.message ?? cause,
|
|
22
|
+
]);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export class TemplateNotFoundError extends BaseError {
|
|
26
|
+
constructor(generator, action) {
|
|
27
|
+
super(`I can't find action [%s] for generator [%s]`, [action, generator]);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export class InjectionTargetNotFoundError extends BaseError {
|
|
31
|
+
constructor(to) {
|
|
32
|
+
super('Cannot inject to [%s]: file does not exist', [to]);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export class InjectionAnchorNotFoundError extends BaseError {
|
|
36
|
+
constructor(anchor, to) {
|
|
37
|
+
super('Injection anchor [%s] not found in [%s]', [anchor, to]);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export class TemplateConfigError extends BaseError {
|
|
41
|
+
constructor(message) {
|
|
42
|
+
super('%s', [message]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export class ShellCommandError extends BaseError {
|
|
46
|
+
constructor(command, cause) {
|
|
47
|
+
super('Shell command [%s] failed: [%s]', [
|
|
48
|
+
command,
|
|
49
|
+
cause?.message ?? cause,
|
|
50
|
+
]);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export class PathMacroResolutionError extends BaseError {
|
|
54
|
+
constructor(file, segment, identifier) {
|
|
55
|
+
super('Template [%s] has a mirrored path segment [%s] with the macro $%s$, which ' +
|
|
56
|
+
'cannot be resolved from the run locals. Define it in the prompt hook, pass ' +
|
|
57
|
+
'it as a CLI flag, or export it from the config helpers factory.', [file, segment, identifier]);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export class GlobMirrorConflictError extends BaseError {
|
|
61
|
+
constructor(file) {
|
|
62
|
+
super('Template [%s] declares both `mirror: true` and `glob:`, which are incompatible: ' +
|
|
63
|
+
"mirroring derives a target path from the template's own name, but a glob " +
|
|
64
|
+
'expands into multiple files. Remove one of the two attributes.', [file]);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export class ConfigTsNodeError extends BaseError {
|
|
68
|
+
constructor(file, cause) {
|
|
69
|
+
super('TypeScript config [%s] requires ts-node: install it with `npm i -D ts-node` (error: [%s])', [file, cause?.message ?? cause]);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export class UnknownTransformError extends BaseError {
|
|
73
|
+
constructor(name) {
|
|
74
|
+
super('Unknown transform [%s]: register it under the `transforms` config key', [
|
|
75
|
+
name,
|
|
76
|
+
]);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export class SetupRepositoryError extends BaseError {
|
|
80
|
+
constructor(setup) {
|
|
81
|
+
super('[%s] must be a repo', [setup]);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export class CliArgumentError extends BaseError {
|
|
85
|
+
constructor(message) {
|
|
86
|
+
super('%s', [message]);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
export class NameFlagRemovedError extends BaseError {
|
|
90
|
+
constructor(name) {
|
|
91
|
+
const shown = Array.isArray(name) ? name.join(', ') : String(name);
|
|
92
|
+
super(`the '--name' flag is no longer supported (received '--name %s'). ` +
|
|
93
|
+
`Pass the name as a positional argument instead: ` +
|
|
94
|
+
`hygen <generator> <action[,action...]> <name[,name...]> (e.g. 'hygen mailer new fancy'). ` +
|
|
95
|
+
`To keep using '--name' during migration, enable the legacy escape: ` +
|
|
96
|
+
`set HYGEN_LEGACY_NAME=1, or pass legacyNameFlag: true in the RunnerConfig.`, [shown]);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import createDebug from 'debug';
|
|
2
|
+
import resolve from './ops/index.js';
|
|
3
|
+
const debug = createDebug('hygen:execute');
|
|
4
|
+
export const execute = async (renderedActions, args, config) => {
|
|
5
|
+
const { logger } = config;
|
|
6
|
+
const messages = [];
|
|
7
|
+
const results = [];
|
|
8
|
+
const statuses = [];
|
|
9
|
+
for (const action of renderedActions) {
|
|
10
|
+
const pair = {
|
|
11
|
+
action: args.action,
|
|
12
|
+
...(args.name !== undefined ? { name: args.name } : {}),
|
|
13
|
+
};
|
|
14
|
+
if (action.skip !== undefined) {
|
|
15
|
+
logger.warn(action.skip === true ? ' skipped' : ` skipped: ${action.skip}`);
|
|
16
|
+
statuses.push({
|
|
17
|
+
...pair,
|
|
18
|
+
status: 'skipped',
|
|
19
|
+
...(typeof action.skip === 'string' ? { reason: action.skip } : {}),
|
|
20
|
+
});
|
|
21
|
+
debug('skipping action: %o', action.file);
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
const { message } = action.attributes;
|
|
25
|
+
if (message) {
|
|
26
|
+
messages.push(message);
|
|
27
|
+
}
|
|
28
|
+
const ops = await resolve(action.attributes);
|
|
29
|
+
debug('executing %o ops', ops.length);
|
|
30
|
+
for (const op of ops) {
|
|
31
|
+
debug('executing: %o', op);
|
|
32
|
+
results.push(await op(action, args, config));
|
|
33
|
+
}
|
|
34
|
+
statuses.push({ ...pair, status: 'ok' });
|
|
35
|
+
debug('executing ops: done');
|
|
36
|
+
}
|
|
37
|
+
if (messages.length > 0) {
|
|
38
|
+
logger.colorful(`${args.action}:\n${messages.join('\n')}`);
|
|
39
|
+
}
|
|
40
|
+
return { results, statuses };
|
|
41
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
import { DEFAULT_ACTION } from './params.js';
|
|
5
|
+
const readVersion = () => {
|
|
6
|
+
let dir = `${process.platform === 'win32' ? '' : '/'}${/file:\/{2,3}(.+)\/[^/]/.exec(import.meta.url)[1]}`;
|
|
7
|
+
while (true) {
|
|
8
|
+
const candidate = path.join(dir, 'package.json');
|
|
9
|
+
if (fs.existsSync(candidate)) {
|
|
10
|
+
try {
|
|
11
|
+
const pkg = JSON.parse(fs.readFileSync(candidate, 'utf8'));
|
|
12
|
+
if (typeof pkg.version === 'string' && pkg.version.length > 0)
|
|
13
|
+
return pkg.version;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const parent = path.dirname(dir);
|
|
19
|
+
if (parent === dir)
|
|
20
|
+
break;
|
|
21
|
+
dir = parent;
|
|
22
|
+
}
|
|
23
|
+
return 'unknown';
|
|
24
|
+
};
|
|
25
|
+
const VERSION = readVersion();
|
|
26
|
+
const isVersionFlag = (args) => args.includes('--version') || args.includes('-v');
|
|
27
|
+
const availableActions = (templates) => {
|
|
28
|
+
const generators = fs
|
|
29
|
+
.readdirSync(templates)
|
|
30
|
+
.filter((_) => fs.lstatSync(path.join(templates, _)).isDirectory());
|
|
31
|
+
return generators.reduce((acc, generator) => {
|
|
32
|
+
const actions = fs.readdirSync(path.join(templates, generator));
|
|
33
|
+
acc[generator] = actions;
|
|
34
|
+
return acc;
|
|
35
|
+
}, {});
|
|
36
|
+
};
|
|
37
|
+
const pickableGenerators = (templates) => fs.readdirSync(templates).filter((entry) => {
|
|
38
|
+
const full = path.join(templates, entry);
|
|
39
|
+
if (!fs.lstatSync(full).isDirectory())
|
|
40
|
+
return false;
|
|
41
|
+
return fs
|
|
42
|
+
.readdirSync(full)
|
|
43
|
+
.some((sub) => fs.lstatSync(path.join(full, sub)).isDirectory());
|
|
44
|
+
});
|
|
45
|
+
const generatorActions = (templates, generator) => fs
|
|
46
|
+
.readdirSync(path.join(templates, generator))
|
|
47
|
+
.filter((entry) => fs.lstatSync(path.join(templates, generator, entry)).isDirectory());
|
|
48
|
+
const printHelp = (templates, logger) => {
|
|
49
|
+
logger.log(`Hygen v${VERSION}`);
|
|
50
|
+
logger.log('\nAvailable actions:');
|
|
51
|
+
if (!templates) {
|
|
52
|
+
logger.log(`No generators or actions found.
|
|
53
|
+
|
|
54
|
+
This means I didn't find a _templates folder right here,
|
|
55
|
+
or anywhere up the folder tree starting here.
|
|
56
|
+
|
|
57
|
+
Here's how to start using Hygen:
|
|
58
|
+
|
|
59
|
+
$ hygen init self
|
|
60
|
+
$ hygen with-prompt new my-generator
|
|
61
|
+
|
|
62
|
+
(edit your generator in _templates/my-generator)
|
|
63
|
+
|
|
64
|
+
$ hygen my-generator
|
|
65
|
+
|
|
66
|
+
See http://hygen.io for more.
|
|
67
|
+
|
|
68
|
+
`);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
Object.entries(availableActions(templates)).forEach(([k, v]) => {
|
|
72
|
+
logger.log(`${chalk.bold(k)}: ${v.find((a) => a === DEFAULT_ACTION) ? `${k}${v.length > 1 ? ',' : ''} ` : ''}${v
|
|
73
|
+
.filter((a) => a !== DEFAULT_ACTION)
|
|
74
|
+
.map((a) => `${k} ${a}`)
|
|
75
|
+
.join(', ')}`);
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
export { availableActions, pickableGenerators, generatorActions, printHelp, VERSION, isVersionFlag, };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import inflection from 'inflection';
|
|
3
|
+
import changeCase from 'change-case';
|
|
4
|
+
const undasherize = (str) => str
|
|
5
|
+
.split(/[-_]/)
|
|
6
|
+
.map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase())
|
|
7
|
+
.join('');
|
|
8
|
+
inflection.undasherize = undasherize;
|
|
9
|
+
const inflected = inflection;
|
|
10
|
+
const helpers = {
|
|
11
|
+
capitalize(str) {
|
|
12
|
+
const toBeCapitalized = String(str);
|
|
13
|
+
return toBeCapitalized.charAt(0).toUpperCase() + toBeCapitalized.slice(1);
|
|
14
|
+
},
|
|
15
|
+
inflection: inflected,
|
|
16
|
+
changeCase,
|
|
17
|
+
path,
|
|
18
|
+
};
|
|
19
|
+
export default helpers;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { runner } from './runner.js';
|
|
2
|
+
export { engine } from './engine.js';
|
|
3
|
+
export { default as resolve } from './config-resolver.js';
|
|
4
|
+
export { printHelp, availableActions, VERSION } from './help.js';
|
|
5
|
+
export { default as Logger } from './logger.js';
|
|
6
|
+
export * as errors from './errors.js';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
const { yellow, red, green, magenta, template } = chalk;
|
|
3
|
+
class Logger {
|
|
4
|
+
constructor(log) {
|
|
5
|
+
this.log = log;
|
|
6
|
+
}
|
|
7
|
+
colorful(msg) {
|
|
8
|
+
this.log(template(chalk, msg));
|
|
9
|
+
}
|
|
10
|
+
notice(msg) {
|
|
11
|
+
this.log(magenta(msg));
|
|
12
|
+
}
|
|
13
|
+
warn(msg) {
|
|
14
|
+
this.log(yellow(msg));
|
|
15
|
+
}
|
|
16
|
+
err(msg) {
|
|
17
|
+
this.log(red(msg));
|
|
18
|
+
}
|
|
19
|
+
ok(msg) {
|
|
20
|
+
this.log(green(msg));
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export default Logger;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { EOL } from 'os';
|
|
2
|
+
const newline = (string) => {
|
|
3
|
+
const newlines = string.match(/(?:\r?\n)/g) || [];
|
|
4
|
+
if (newlines.length === 0) {
|
|
5
|
+
return EOL;
|
|
6
|
+
}
|
|
7
|
+
const crlf = newlines.filter((newline) => newline === '\r\n').length;
|
|
8
|
+
const lf = newlines.length - crlf;
|
|
9
|
+
return crlf > lf ? '\r\n' : '\n';
|
|
10
|
+
};
|
|
11
|
+
export default newline;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import fs from 'fs-extra';
|
|
3
|
+
import { red } from 'chalk';
|
|
4
|
+
import createResult from './result.js';
|
|
5
|
+
import { resolvePathMacros } from '../path-macros.js';
|
|
6
|
+
const targetPath = (action, args, config) => {
|
|
7
|
+
const { attributes } = action;
|
|
8
|
+
if (attributes.to)
|
|
9
|
+
return attributes.to;
|
|
10
|
+
if (attributes.mirror !== true || attributes.sh !== undefined || !action.file) {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
const rel = path.relative(args.actionfolder, action.file);
|
|
14
|
+
const stripped = process.env.HYGEN_MIRROR_EJS_SUFFIX === '1'
|
|
15
|
+
? rel.replace(/\.ejs\.t$/, '')
|
|
16
|
+
: rel.replace(/\.t$/, '');
|
|
17
|
+
return resolvePathMacros(stripped, args, config, action.file);
|
|
18
|
+
};
|
|
19
|
+
const add = async (action, args, config) => {
|
|
20
|
+
const { logger, cwd, createPrompter } = config;
|
|
21
|
+
const { attributes: { inject, unless_exists, force, from, skip_if, skipIfExists }, } = action;
|
|
22
|
+
const to = targetPath(action, args, config);
|
|
23
|
+
const result = createResult('add', to);
|
|
24
|
+
const prompter = createPrompter();
|
|
25
|
+
if (!to || inject) {
|
|
26
|
+
return result('ignored');
|
|
27
|
+
}
|
|
28
|
+
const absTo = path.resolve(cwd, to);
|
|
29
|
+
const shouldNotOverwrite = !force && unless_exists !== undefined && unless_exists === true;
|
|
30
|
+
const fileExists = await fs.pathExists(absTo);
|
|
31
|
+
if (skipIfExists === true && fileExists) {
|
|
32
|
+
logger.warn(` skipped: ${to}`);
|
|
33
|
+
return result('skipped');
|
|
34
|
+
}
|
|
35
|
+
if (shouldNotOverwrite && fileExists) {
|
|
36
|
+
logger.warn(` skipped: ${to}`);
|
|
37
|
+
return result('skipped');
|
|
38
|
+
}
|
|
39
|
+
if (!process.env.HYGEN_OVERWRITE && fileExists && !force) {
|
|
40
|
+
if (!(await prompter
|
|
41
|
+
.prompt({
|
|
42
|
+
prefix: '',
|
|
43
|
+
type: 'confirm',
|
|
44
|
+
name: 'overwrite',
|
|
45
|
+
message: red(` exists: ${to}. Overwrite? (y/N): `),
|
|
46
|
+
})
|
|
47
|
+
.then(({ overwrite }) => overwrite))) {
|
|
48
|
+
logger.warn(` skipped: ${to}`);
|
|
49
|
+
return result('skipped');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const shouldSkip = skip_if === 'true';
|
|
53
|
+
if (shouldSkip) {
|
|
54
|
+
return result('skipped');
|
|
55
|
+
}
|
|
56
|
+
if (from) {
|
|
57
|
+
const from_path = path.join(args.templates, from);
|
|
58
|
+
const file = fs.readFileSync(from_path).toString();
|
|
59
|
+
action.body = file;
|
|
60
|
+
}
|
|
61
|
+
if (!args.dry) {
|
|
62
|
+
await fs.ensureDir(path.dirname(absTo));
|
|
63
|
+
await fs.writeFile(absTo, action.body);
|
|
64
|
+
}
|
|
65
|
+
const pathToLog = process.env.HYGEN_OUTPUT_ABS_PATH ? absTo : to;
|
|
66
|
+
logger.ok(` ${force ? 'FORCED' : 'added'}: ${pathToLog}`);
|
|
67
|
+
return result('added');
|
|
68
|
+
};
|
|
69
|
+
export default add;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { InjectionAnchorNotFoundError } from '../errors.js';
|
|
2
|
+
const EOLRegex = /\r?\n/;
|
|
3
|
+
const pragmaticIndex = (pattern, lines, isBefore, anchor, to) => {
|
|
4
|
+
const oneLineMatchIndex = lines.findIndex((l) => l.match(pattern));
|
|
5
|
+
if (oneLineMatchIndex < 0) {
|
|
6
|
+
const fullText = lines.join('\n');
|
|
7
|
+
const fullMatch = fullText.match(new RegExp(pattern, 'm'));
|
|
8
|
+
if (fullMatch && fullMatch.length) {
|
|
9
|
+
if (isBefore) {
|
|
10
|
+
const fullTextUntilMatchStart = fullText.substring(0, fullMatch.index);
|
|
11
|
+
return fullTextUntilMatchStart.split(EOLRegex).length - 1;
|
|
12
|
+
}
|
|
13
|
+
const matchEndIndex = (fullMatch.index ?? 0) + fullMatch.toString().length;
|
|
14
|
+
const fullTextUntilMatchEnd = fullText.substring(0, matchEndIndex);
|
|
15
|
+
return fullTextUntilMatchEnd.split(EOLRegex).length;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
if (oneLineMatchIndex < 0) {
|
|
19
|
+
throw new InjectionAnchorNotFoundError(anchor, to);
|
|
20
|
+
}
|
|
21
|
+
return oneLineMatchIndex + (isBefore ? 0 : 1);
|
|
22
|
+
};
|
|
23
|
+
const locatorByKind = {
|
|
24
|
+
at_line: (l) => ({ locate: () => l }),
|
|
25
|
+
prepend: () => ({ locate: () => 0 }),
|
|
26
|
+
append: () => ({ locate: (lines) => lines.length - 1 }),
|
|
27
|
+
before: (v, to) => ({
|
|
28
|
+
locate: (lines) => pragmaticIndex(String(v), lines, true, 'before', to),
|
|
29
|
+
}),
|
|
30
|
+
after: (v, to) => ({
|
|
31
|
+
locate: (lines) => pragmaticIndex(String(v), lines, false, 'after', to),
|
|
32
|
+
}),
|
|
33
|
+
};
|
|
34
|
+
export const indexByLocation = (attributes, lines, to) => {
|
|
35
|
+
const pair = Object.entries(attributes).find(([k]) => locatorByKind[k]);
|
|
36
|
+
if (pair) {
|
|
37
|
+
const [k, v] = pair;
|
|
38
|
+
return locatorByKind[k](v, to).locate(lines);
|
|
39
|
+
}
|
|
40
|
+
return -1;
|
|
41
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import createResult from './result.js';
|
|
2
|
+
const notEmpty = (x) => x && x.length > 0;
|
|
3
|
+
const echo = async ({ attributes: { echo } }, _args, { logger }) => {
|
|
4
|
+
const result = createResult('shell', echo);
|
|
5
|
+
const echoStr = echo;
|
|
6
|
+
if (notEmpty(echoStr)) {
|
|
7
|
+
logger.colorful(echoStr);
|
|
8
|
+
return result('executed');
|
|
9
|
+
}
|
|
10
|
+
return result('ignored');
|
|
11
|
+
};
|
|
12
|
+
export default echo;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const resolve = async (attributes) => {
|
|
2
|
+
const ops = [];
|
|
3
|
+
const isAddTarget = Boolean(attributes.to) || (attributes.mirror === true && !attributes.sh);
|
|
4
|
+
if (isAddTarget && !attributes.inject && !attributes.replace) {
|
|
5
|
+
const add = (await import('./add.js')).default;
|
|
6
|
+
ops.push(add);
|
|
7
|
+
}
|
|
8
|
+
if (attributes.to && (attributes.inject || attributes.replace)) {
|
|
9
|
+
const inject = (await import('./inject.js')).default;
|
|
10
|
+
ops.push(inject);
|
|
11
|
+
}
|
|
12
|
+
if (attributes.echo) {
|
|
13
|
+
const echo = (await import('./echo.js')).default;
|
|
14
|
+
ops.push(echo);
|
|
15
|
+
}
|
|
16
|
+
if (attributes.sh) {
|
|
17
|
+
const shell = (await import('./shell.js')).default;
|
|
18
|
+
ops.push(shell);
|
|
19
|
+
}
|
|
20
|
+
if (attributes.setup) {
|
|
21
|
+
const setup = (await import('./setup.js')).default;
|
|
22
|
+
ops.push(setup);
|
|
23
|
+
}
|
|
24
|
+
return ops;
|
|
25
|
+
};
|
|
26
|
+
export default resolve;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import fs from 'fs-extra';
|
|
3
|
+
import createResult from './result.js';
|
|
4
|
+
import injector from './injector.js';
|
|
5
|
+
const injectOp = async (action, args, { logger, cwd }) => {
|
|
6
|
+
const { attributes: { to, inject, replace, create_if_missing }, } = action;
|
|
7
|
+
const result = createResult('inject', to);
|
|
8
|
+
if (!((inject || replace) && to)) {
|
|
9
|
+
return result('ignored');
|
|
10
|
+
}
|
|
11
|
+
const absTo = path.resolve(cwd, to);
|
|
12
|
+
if (!(await fs.pathExists(absTo))) {
|
|
13
|
+
if (create_if_missing) {
|
|
14
|
+
await fs.ensureFile(absTo);
|
|
15
|
+
}
|
|
16
|
+
else {
|
|
17
|
+
logger.err(`Cannot inject to ${to}: doesn't exist.`);
|
|
18
|
+
return result('error', {
|
|
19
|
+
error: `Cannot inject to ${to}: doesn't exist.`,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const content = (await fs.readFile(absTo)).toString();
|
|
24
|
+
const injectResult = injector(action, content, to);
|
|
25
|
+
if (!args.dry) {
|
|
26
|
+
await fs.writeFile(absTo, injectResult);
|
|
27
|
+
}
|
|
28
|
+
const pathToLog = process.env.HYGEN_OUTPUT_ABS_PATH ? absTo : to;
|
|
29
|
+
logger.notice(` inject: ${pathToLog}`);
|
|
30
|
+
return result('inject');
|
|
31
|
+
};
|
|
32
|
+
export default injectOp;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import newline from '../newline.js';
|
|
2
|
+
import { InjectionAnchorNotFoundError, TemplateConfigError } from '../errors.js';
|
|
3
|
+
import { indexByLocation } from './anchors.js';
|
|
4
|
+
const REPLACE_ANCHORS = ['before', 'after'];
|
|
5
|
+
const injector = (action, content, to = '') => {
|
|
6
|
+
const { attributes: { skip_if, eof_last, replace }, attributes, body, } = action;
|
|
7
|
+
const skipIf = typeof skip_if === 'string' ? skip_if : '';
|
|
8
|
+
const skipIfNot = attributes.skip_if_not === true;
|
|
9
|
+
const shouldSkip = skipIf ? !!content.match(skipIf) !== skipIfNot : false;
|
|
10
|
+
if (shouldSkip) {
|
|
11
|
+
return content;
|
|
12
|
+
}
|
|
13
|
+
if (replace) {
|
|
14
|
+
if (attributes.inject) {
|
|
15
|
+
throw new TemplateConfigError('`inject: true` and `replace: true` are mutually exclusive: use exactly one');
|
|
16
|
+
}
|
|
17
|
+
const activeAnchor = REPLACE_ANCHORS.find((anchor) => attributes[anchor] !== undefined);
|
|
18
|
+
if (!activeAnchor) {
|
|
19
|
+
throw new TemplateConfigError('`replace: true` requires a `before` or `after` anchor');
|
|
20
|
+
}
|
|
21
|
+
const pattern = String(attributes[activeAnchor]);
|
|
22
|
+
const regex = new RegExp(pattern, 'm');
|
|
23
|
+
if (!regex.test(content)) {
|
|
24
|
+
throw new InjectionAnchorNotFoundError(pattern, to);
|
|
25
|
+
}
|
|
26
|
+
return content.replace(regex, () => body);
|
|
27
|
+
}
|
|
28
|
+
const NL = newline(content);
|
|
29
|
+
const lines = content.split(NL);
|
|
30
|
+
const idx = indexByLocation(attributes, lines, to);
|
|
31
|
+
const trimEOF = idx >= 0 && eof_last === false && /\r?\n$/.test(body);
|
|
32
|
+
const insertEOF = idx >= 0 && eof_last === true && !/\r?\n$/.test(body);
|
|
33
|
+
if (trimEOF) {
|
|
34
|
+
lines.splice(idx, 0, body.replace(/\r?\n$/, ''));
|
|
35
|
+
}
|
|
36
|
+
else if (insertEOF) {
|
|
37
|
+
lines.splice(idx, 0, `${body}${NL}`);
|
|
38
|
+
}
|
|
39
|
+
else if (idx >= 0) {
|
|
40
|
+
lines.splice(idx, 0, body);
|
|
41
|
+
}
|
|
42
|
+
return lines.join(NL);
|
|
43
|
+
};
|
|
44
|
+
export default injector;
|