Skip to content

Commit

Permalink
refactor static methods
Browse files Browse the repository at this point in the history
  • Loading branch information
mshima committed May 18, 2023
1 parent a5b3b5f commit 16ae1bd
Show file tree
Hide file tree
Showing 12 changed files with 112 additions and 217 deletions.
3 changes: 1 addition & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ $ npm install yeoman-environment
Full documentation available [here](http://yeoman.io/authoring/integrating-yeoman.html).

```js
import yeoman from 'yeoman-environment';
const env = yeoman.createEnv();
import { createEnv } from 'yeoman-environment';

// The #lookup() method will search the user computer for installed generators
// The search if done from the current working directory
Expand Down
6 changes: 3 additions & 3 deletions src/cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import process from 'node:process';
import YeomanCommand, { addEnvironmentOptions } from '../util/command.js';
import packageJson from '../package.json';
import Env from '../index.js';
import { createEnv } from '../index.js';
import { printGroupedGenerator, environmentAction } from './utils.js';

const program = new YeomanCommand();
Expand All @@ -25,7 +25,7 @@ program
.command('find')
.description('Find installed generators')
.action(async () => {
const env = Env.createEnv();
const env = createEnv();
const generators = await env.lookup();
printGroupedGenerator(generators, env);
});
Expand All @@ -34,7 +34,7 @@ program
.command('list')
.description('List generators available to be used')
.action(async () => {
const env = Env.createEnv();
const env = createEnv();
await env.lookup();
printGroupedGenerator(Object.values(env.getGeneratorsMeta()), env);
});
Expand Down
4 changes: 2 additions & 2 deletions src/cli/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { requireNamespace } from '@yeoman/namespace';
import { groupBy } from 'lodash-es';
import createLogger from 'debug';
import Environment from '../index.js';
import Environment, { createEnv } from '../index.js';

const debug = createLogger('yeoman:yoe');

Expand Down Expand Up @@ -33,7 +33,7 @@ export const environmentAction = async function (this: any, generatorNamespace:
return;
}

this.env = Environment.createEnv([], { ...options, command: this });
this.env = createEnv({ ...options, command: this });
await this.env.lookupLocalPackages();

return this.env.execute(generatorNamespace, command.args.splice(1));
Expand Down
38 changes: 38 additions & 0 deletions src/commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import YeomanCommand, { addEnvironmentOptions } from './util/command.js';
import { createEnv } from './index.js';

/**
* Prepare a commander instance for cli support.
*
* @param {Command} command - Command to be prepared
* @param generatorPath - Generator to create Command
* @return {Command} return command
*/
export const prepareGeneratorCommand = async (command: YeomanCommand, generatorPath: string, namespace?: string) => {
const env = createEnv();
const meta = env.register(generatorPath, { namespace });
command.env = env;
command.registerGenerator(await meta.instantiateHelp());
command.action(async function (this: YeomanCommand) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let rootCommand: YeomanCommand = this;
while (rootCommand.parent) {
rootCommand = rootCommand.parent as YeomanCommand;
}

const generator = await meta.instantiate(this.args, this.opts());
await env.runGenerator(generator);
});
return command;
};

/**
* Prepare a commander instance for cli support.
*
* @param generatorPaht - Generator to create Command
* @return Return a Command instance
*/
export const prepareCommand = async (generatorPath: string, command = new YeomanCommand()) => {
command = addEnvironmentOptions(command);
return prepareGeneratorCommand(command, generatorPath);
};
37 changes: 23 additions & 14 deletions src/environment-base.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import EventEmitter from 'node:events';
import { createRequire } from 'node:module';
import { basename, isAbsolute, join, relative, resolve } from 'node:path';
import process from 'node:process';
Expand Down Expand Up @@ -35,13 +34,13 @@ import { type ConflicterOptions } from '@yeoman/conflicter';
import { defaults, pick } from 'lodash-es';
import { ComposedStore } from './composed-store.js';
import Store from './store.js';
import Environment from './environment.js';
import type YeomanCommand from './util/command.js';
import { asNamespace, defaultLookups } from './util/namespace.js';
import { type LookupOptions, lookupGenerators } from './generator-lookup.js';
import { UNKNOWN_NAMESPACE, UNKNOWN_RESOLVED, defaultQueues } from './constants.js';
import { resolveModulePath } from './util/resolve.js';
import { commitSharedFsTask } from './commit.js';
// eslint-disable-next-line import/order
import { packageManagerInstallTask } from './package-manager.js';

const require = createRequire(import.meta.url);
Expand All @@ -51,7 +50,7 @@ const ENVIRONMENT_VERSION = require('../package.json').version;

const debug = createdLogger('yeoman:environment');

type EnvironmentOptions = BaseEnvironmentOptions &
export type EnvironmentOptions = BaseEnvironmentOptions &
Omit<TerminalAdapterOptions, 'promptModule'> & {
adapter?: InputOutputAdapter;
logCwd?: string;
Expand Down Expand Up @@ -116,7 +115,7 @@ const getInstantiateOptions = (args?: any, options?: any): InstantiateOptions =>
return { generatorOptions: options };
};

export default class EnvironmentBase extends EventEmitter implements BaseEnvironment {
export default class EnvironmentBase extends Environment implements BaseEnvironment {
cwd: string;
adapter: QueuedAdapter;
sharedFs: MemFs<MemFsEditorFile>;
Expand All @@ -137,7 +136,12 @@ export default class EnvironmentBase extends EventEmitter implements BaseEnviron
protected _rootGenerator?: BaseGenerator;
protected compatibilityMode?: false | 'v4';

constructor(options: EnvironmentOptions = {}) {
constructor(options?: EnvironmentOptions);
constructor(options: EnvironmentOptions = {}, adapterCompat?: InputOutputAdapter) {
if (adapterCompat) {
options.adapter = adapterCompat;
}

super();

this.setMaxListeners(100);
Expand Down Expand Up @@ -198,6 +202,11 @@ export default class EnvironmentBase extends EventEmitter implements BaseEnviron
this.experimental = experimental || process.argv.includes('--experimental');

this.alias(/^([^:]+)$/, '$1:app');

this.loadSharedOptions(this.options);
if (this.sharedOptions.skipLocalCache === undefined) {
this.sharedOptions.skipLocalCache = true;
}
}

async applyTransforms(transformStreams: Transform[], options: ApplyTransformsOptions = {}): Promise<void> {
Expand Down Expand Up @@ -546,9 +555,9 @@ export default class EnvironmentBase extends EventEmitter implements BaseEnviron
* @param packagePath - PackagePath to the generator npm package (optional)
* @return environment - This environment
*/
register(filePath: string, meta?: Partial<BaseGeneratorMeta> | undefined): void;
register(generator: unknown, meta: BaseGeneratorMeta): void;
register(pathOrStub: unknown, meta?: Partial<BaseGeneratorMeta> | BaseGeneratorMeta, ...args: any[]): this {
register(filePath: string, meta?: Partial<BaseGeneratorMeta> | undefined): GeneratorMeta;
register(generator: unknown, meta: BaseGeneratorMeta): GeneratorMeta;
register(pathOrStub: unknown, meta?: Partial<BaseGeneratorMeta> | BaseGeneratorMeta, ...args: any[]): GeneratorMeta {
if (typeof pathOrStub === 'string') {
if (typeof meta === 'object') {
return this.registerGeneratorPath(pathOrStub, meta.namespace, meta.packagePath);
Expand Down Expand Up @@ -832,7 +841,7 @@ export default class EnvironmentBase extends EventEmitter implements BaseEnviron
* @param packagePath - PackagePath to the generator npm package (optional)
* @return environment - This environment
*/
protected registerGeneratorPath(generatorPath: string, namespace?: string, packagePath?: string): this {
protected registerGeneratorPath(generatorPath: string, namespace?: string, packagePath?: string): GeneratorMeta {
if (typeof generatorPath !== 'string') {
throw new TypeError('You must provide a generator name to register.');
}
Expand All @@ -850,13 +859,13 @@ export default class EnvironmentBase extends EventEmitter implements BaseEnviron
// Generator is already registered and matches the current namespace.
const generatorMeta = this.store.getMeta(namespace);
if (generatorMeta && generatorMeta.resolved === generatorPath) {
return this;
return generatorMeta;
}

const meta = this.store.add({ namespace, resolved: generatorPath, packagePath });

debug('Registered %s (%s) on package %s (%s)', namespace, generatorPath, meta.packageNamespace, packagePath);
return this;
return meta;
}

/**
Expand All @@ -869,7 +878,7 @@ export default class EnvironmentBase extends EventEmitter implements BaseEnviron
* @param resolved - The file path to the generator
* @param packagePath - The generator's package path
*/
protected registerStub(Generator: any, namespace: string, resolved = UNKNOWN_RESOLVED, packagePath?: string): this {
protected registerStub(Generator: any, namespace: string, resolved = UNKNOWN_RESOLVED, packagePath?: string): GeneratorMeta {
if (typeof Generator !== 'function' && typeof Generator.createGenerator !== 'function') {
throw new TypeError('You must provide a stub function to register.');
}
Expand All @@ -878,9 +887,9 @@ export default class EnvironmentBase extends EventEmitter implements BaseEnviron
throw new TypeError('You must provide a namespace to register.');
}

this.store.add({ namespace, resolved, packagePath }, Generator);
const meta = this.store.add({ namespace, resolved, packagePath }, Generator);

debug('Registered %s (%s) on package (%s)', namespace, resolved, packagePath);
return this;
return meta;
}
}
4 changes: 2 additions & 2 deletions src/environment-full.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { join } from 'node:path';
import { flyImport } from 'fly-import';
import semver from 'semver';
import { type YeomanNamespace, requireNamespace } from '@yeoman/namespace';
import Environment from './environment.js';
import { type LookupOptions } from './generator-lookup.js';
import YeomanCommand from './util/command.js';
import EnvironmentBase from './environment-base.js';

class FullEnvironment extends Environment {
class FullEnvironment extends EnvironmentBase {
/**
* Generate a command for the generator and execute.
*
Expand Down
Loading

0 comments on commit 16ae1bd

Please sign in to comment.