Skip to content

Commit

Permalink
add format plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
electrovir committed Jul 29, 2024
1 parent 463208f commit 87034cc
Show file tree
Hide file tree
Showing 35 changed files with 880 additions and 80 deletions.
4 changes: 3 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@
**/package-lock.json
**/ts.out/
**/tsconfig.tsbuildinfo
/Icon?
/Icon?

packages/format/test-files/bad-format
23 changes: 23 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 30 additions & 30 deletions packages/core/src/api/copy-configs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {extractErrorMessage, MaybePromise} from '@augment-vir/common';
import {Logger} from '@augment-vir/node-js';
import {awaitedBlockingMap, extractErrorMessage, MaybePromise} from '@augment-vir/common';
import {existsSync} from 'node:fs';
import {mkdir, readFile, writeFile} from 'node:fs/promises';
import {basename, dirname, join} from 'node:path';
Expand All @@ -10,6 +9,7 @@ import {
UsedVirmatorPluginCommands,
VirmatorPluginResolvedConfigs,
} from '../plugin/plugin-executor';
import {PluginLogger} from '../plugin/plugin-logger';

export function flattenConfigs(
usedCommands: Readonly<UsedVirmatorPluginCommands<any>>,
Expand Down Expand Up @@ -42,40 +42,40 @@ export async function copyPluginConfigs(
resolvedConfigs: Readonly<VirmatorPluginResolvedConfigs<any>>,
packageType: PackageType,
monoRepoPackages: MonoRepoPackage[],
log: Logger,
log: PluginLogger,
) {
const configs = flattenConfigs(usedCommands, resolvedConfigs);

await Promise.all(
Object.values(configs).map(async (config) => {
if (
packageType === PackageType.MonoRoot &&
!config.packageType.includes(PackageType.MonoRoot) &&
config.packageType.includes(PackageType.MonoPackage)
) {
await Promise.all(
monoRepoPackages.map(async (repoPackage) => {
await copyConfigFile(
{
...config,
fullCopyToPath: join(repoPackage.fullPath, config.copyToPath),
},
log,
);
}),
);
} else if (!config.required || !config.packageType.includes(packageType)) {
return;
} else {
await copyConfigFile(config, log);
}
}),
const configs = flattenConfigs(usedCommands, resolvedConfigs).sort((a, b) =>
basename(a.copyToPath).localeCompare(basename(b.copyToPath)),
);

await awaitedBlockingMap(Object.values(configs), async (config) => {
if (
packageType === PackageType.MonoRoot &&
!config.packageType.includes(PackageType.MonoRoot) &&
config.packageType.includes(PackageType.MonoPackage)
) {
await Promise.all(
monoRepoPackages.map(async (repoPackage) => {
await copyConfigFile(
{
...config,
fullCopyToPath: join(repoPackage.fullPath, config.copyToPath),
},
log,
);
}),
);
} else if (!config.required || !config.packageType.includes(packageType)) {
return;
} else {
await copyConfigFile(config, log);
}
});
}

export async function copyConfigFile(
config: Readonly<Pick<VirmatorPluginResolvedConfigFile, 'fullCopyFromPath' | 'fullCopyToPath'>>,
log: Logger,
log: PluginLogger,
/**
* If `true`, the config will be copied even if the copy destination already exists.
*
Expand Down
14 changes: 0 additions & 14 deletions packages/core/src/api/empty-logger.ts

This file was deleted.

50 changes: 32 additions & 18 deletions packages/core/src/api/execute-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import {
wrapInTry,
} from '@augment-vir/common';
import {
log,
Logger,
LogOutputType,
readPackageJson,
runShellCommand,
type createLogger,
Expand All @@ -30,13 +29,14 @@ import {VirmatorPlugin} from '../plugin/plugin';
import {VirmatorPluginResolvedConfigFile} from '../plugin/plugin-configs';
import {PackageType} from '../plugin/plugin-env';
import {
ExtraRunShellCommandOptions,
MonoRepoPackage,
VirmatorPluginExecutorParams,
VirmatorPluginResolvedConfigs,
} from '../plugin/plugin-executor';
import {VirmatorPluginCliCommands} from '../plugin/plugin-init';
import {log, PluginLogger} from '../plugin/plugin-logger';
import {copyPluginConfigs} from './copy-configs';
import type {emptyLogger} from './empty-logger';
import {parseCliArgs} from './parse-args';

export type ExecuteCommandParams = {
Expand Down Expand Up @@ -91,7 +91,7 @@ export type ExecuteCommandParams = {
* logger.
* - Use {@link emptyLogger} from the `@virmator/core` npm package to easily block all logging.
*/
log: Logger;
log: PluginLogger;
/**
* The maximum number of concurrent processes that can run at the same time when running a
* command per mono-repo sub package.
Expand Down Expand Up @@ -201,6 +201,30 @@ async function findMonoRepoDir(cwdPackagePath: string) {
return cwdPackagePath;
}

function writeLog(
arg: string,
log: PluginLogger,
logType: LogOutputType,
extraOptions: PartialAndUndefined<ExtraRunShellCommandOptions> | undefined,
) {
const transformed = extraOptions?.logTransform?.[logType]
? extraOptions.logTransform[logType](arg)
: log;
if (!transformed) {
return;
}
const finalLog = [
extraOptions?.logPrefix || '',
transformed,
].join('');

if (logType === LogOutputType.error) {
log.error(finalLog);
} else {
log.plain(finalLog);
}
}

/** The entry point to virmator. Runs a virmator command. */
export async function executeVirmatorCommand({
log: logParam = log,
Expand Down Expand Up @@ -239,7 +263,7 @@ export async function executeVirmatorCommand({

const executorParams: VirmatorPluginExecutorParams<any> = {
cliInputs: {
filteredArgs: args.filteredCommandArgs,
filteredArgs: args.filteredCommandArgs.filter(isTruthy),
usedCommands: args.usedCommands,
},
log,
Expand All @@ -256,26 +280,16 @@ export async function executeVirmatorCommand({
allPlugins: params.plugins,
pluginPackagePath,
},
async runShellCommand(command, options, prefix?: string | undefined) {
async runShellCommand(command, options, extraOptions) {
log.faint(`> ${command}`);
const result = await runShellCommand(command, {
cwd,
shell: 'bash',
stderrCallback(stderr) {
process.stderr.write(
[
prefix || '',
chalk.red(stderr),
].join(''),
);
writeLog(stderr, log, LogOutputType.error, extraOptions);
},
stdoutCallback(stdout) {
process.stdout.write(
[
prefix || '',
stdout,
].join(''),
);
writeLog(stdout, log, LogOutputType.standard, extraOptions);
},
...options,
});
Expand Down
1 change: 0 additions & 1 deletion packages/core/src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
export * from './copy-configs';
export * from './empty-logger';
export * from './execute-command';
export * from './parse-args';
export * from './typescript-config-file';
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/api/parse-args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import {
mapObjectValues,
wrapInTry,
} from '@augment-vir/common';
import {Logger} from '@augment-vir/node-js';
import {extractRelevantArgs} from 'cli-args-vir';
import {isRunTimeType} from 'run-time-assertions';
import {Writable} from 'type-fest';
import {accessAtKeys} from '../augments/object/access';
import {VirmatorPlugin} from '../plugin/plugin';
import {UsedVirmatorPluginCommands} from '../plugin/plugin-executor';
import {VirmatorPluginCliCommands} from '../plugin/plugin-init';
import {PluginLogger} from '../plugin/plugin-logger';
import {SetVirmatorFlags, virmatorFlags} from './virmator-flags';

export type ParsedArgs = {
Expand Down Expand Up @@ -116,7 +116,7 @@ export function parseCliArgs({
plugins: ReadonlyArray<Readonly<VirmatorPlugin>>;
cliCommand: string | ReadonlyArray<string>;
entryPointFilePath: string;
log: Logger;
log: PluginLogger;
}): ParsedArgs {
const rawArgs: ReadonlyArray<string> = isRunTimeType(cliCommand, 'array')
? cliCommand
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/augments/stream/callback-writable.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Logger} from '@augment-vir/node-js';
import {Writable} from 'stream';
import {PluginLogger} from '../../plugin/plugin-logger';

export class CallbackWritable extends Writable {
private chunks: string[] = [];
Expand All @@ -19,7 +19,7 @@ export class CallbackWritable extends Writable {
callback();
}

constructor(private readonly logger: Logger) {
constructor(private readonly logger: PluginLogger) {
super();
}
}
1 change: 1 addition & 0 deletions packages/core/src/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './plugin-configs';
export * from './plugin-env';
export * from './plugin-executor';
export * from './plugin-init';
export * from './plugin-logger';
19 changes: 15 additions & 4 deletions packages/core/src/plugin/plugin-executor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import type {AnyObject, MaybePromise, TypedFunction} from '@augment-vir/common';
import type {Logger, runShellCommand} from '@augment-vir/node-js';
import type {
AnyObject,
MaybePromise,
PartialAndUndefined,
TypedFunction,
} from '@augment-vir/common';
import type {LogOutputType, runShellCommand} from '@augment-vir/node-js';
import {ChalkInstance} from 'chalk';
import {EmptyObject, PackageJson} from 'type-fest';
import {VirmatorPluginResolvedConfigFile} from './plugin-configs';
Expand All @@ -9,6 +14,7 @@ import {
VirmatorPluginCliCommands,
VirmatorPluginInit,
} from './plugin-init';
import {PluginLogger} from './plugin-logger';

export type UsedVirmatorPluginCommands<
Commands extends VirmatorPluginCliCommands = VirmatorPluginCliCommands,
Expand Down Expand Up @@ -59,6 +65,11 @@ export type RunPerPackage = (
maxProcesses?: number | undefined,
) => Promise<void>;

export type ExtraRunShellCommandOptions = {
logPrefix: string | undefined;
logTransform: Partial<Record<LogOutputType, (log: string) => string>>;
};

export type VirmatorPluginExecutorParams<
Commands extends VirmatorPluginCliCommands = VirmatorPluginCliCommands,
> = Readonly<{
Expand All @@ -82,12 +93,12 @@ export type VirmatorPluginExecutorParams<

/** Run a shell command with sensible defaults. */
runShellCommand: TypedFunction<
[...Parameters<typeof runShellCommand>, (string | undefined)?],
[...Parameters<typeof runShellCommand>, PartialAndUndefined<ExtraRunShellCommandOptions>?],
ReturnType<typeof runShellCommand>
>;
runPerPackage: RunPerPackage;

log: Logger;
log: PluginLogger;

configs: VirmatorPluginResolvedConfigs<Commands>;

Expand Down
28 changes: 28 additions & 0 deletions packages/core/src/plugin/plugin-logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import {createLogger, Logger, toLogString} from '@augment-vir/node-js';

export type PluginLogger = Logger & {plain: Logger['faint']};

export function createPluginLogger(params: Parameters<typeof createLogger>[0]) {
const logger = createLogger(params);
return {
...logger,
plain(...args: ReadonlyArray<any>) {
params.stdout.write(toLogString({args, colors: []}));
},
};
}

export const emptyLogger: PluginLogger = createPluginLogger({
stderr: {
write() {
return true;
},
},
stdout: {
write() {
return true;
},
},
});

export const log = createPluginLogger(process);
4 changes: 2 additions & 2 deletions packages/core/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": "./src",
"composite": true
"rootDir": "./src"
},
"exclude": [
"./configs",
Expand Down
Loading

0 comments on commit 87034cc

Please sign in to comment.