Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix local config search #218

Merged
merged 2 commits into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fair-flowers-sing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hypermod/cli': patch
---

Patches selection of transform via local config prompt
5 changes: 5 additions & 0 deletions .changeset/spotty-parrots-move.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hypermod/fetcher': minor
---

Adds typescript support for config requires. Now a config can be in TS/TSX etc.
8 changes: 8 additions & 0 deletions .changeset/stupid-mice-lay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@hypermod/validator': patch
'@hypermod/fetcher': patch
'@hypermod/types': patch
'@hypermod/cli': patch
---

Renames type `CodeshiftConfig` to `Config` (with backwards compatible alias)
10 changes: 6 additions & 4 deletions packages/cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { PluginManager, PluginManagerOptions } from 'live-plugin-manager';
import { installPackage } from '@antfu/install-pkg';

import * as core from '@hypermod/core';
import { CodeshiftConfig } from '@hypermod/types';
import { Config } from '@hypermod/types';
import { fetchConfigAtPath, fetchConfigs } from '@hypermod/fetcher';

import { InvalidUserInputError } from './errors';
Expand Down Expand Up @@ -78,7 +78,7 @@ export default async function main(

if (rootPackageJson && rootPackageJson.workspaces) {
const configs = await (rootPackageJson.workspaces as string[]).reduce<
Promise<{ filePath: string; config: CodeshiftConfig }[]>
Promise<{ filePath: string; config: Config }[]>
>(async (accum, filePath) => {
const configs = await fetchConfigs(filePath);
if (!configs.length) return accum;
Expand Down Expand Up @@ -164,9 +164,11 @@ export default async function main(
if (config.transforms && config.transforms[answers.codemod]) {
Object.entries(config.transforms)
.filter(([key]) => semver.satisfies(key, `>=${answers.codemod}`))
.forEach(([, path]) => transforms.push(path));
.forEach(([, codemod]) =>
transforms.push(`${configFilePath}@${codemod}`),
);
} else if (config.presets && config.presets[answers.codemod]) {
transforms.push(config.presets[answers.codemod]);
transforms.push(`${configFilePath}#${answers.codemod}`);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/prompt.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import inquirer from 'inquirer';

import { CodeshiftConfig } from '@hypermod/types';
import { Config } from '@hypermod/types';

export const getConfigPrompt = (config: CodeshiftConfig) => {
export const getConfigPrompt = (config: Config) => {
const transforms = Object.keys(config.transforms || {});
const presets = Object.keys(config.presets || {});

Expand All @@ -22,7 +22,7 @@ export const getConfigPrompt = (config: CodeshiftConfig) => {
};

export const getMultiConfigPrompt = (
configs: { filePath: string; config: CodeshiftConfig }[],
configs: { filePath: string; config: Config }[],
) => {
const choices = configs.reduce<any[]>((accum, { filePath, config }) => {
function mapToConfig(codemods: Record<string, string> = {}) {
Expand Down
10 changes: 10 additions & 0 deletions packages/fetcher/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,17 @@
"license": "MIT",
"repository": "https://github.com/hypermod-io/hypermod-community/tree/main/packages/fetcher",
"dependencies": {
"@babel/core": "^7.13.16",
"@babel/parser": "^7.13.16",
"@babel/plugin-proposal-class-properties": "^7.13.0",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.13.8",
"@babel/plugin-proposal-optional-chaining": "^7.13.12",
"@babel/plugin-transform-modules-commonjs": "^7.13.8",
"@babel/preset-flow": "^7.13.13",
"@babel/preset-typescript": "^7.13.16",
"@babel/register": "^7.13.16",
"@hypermod/types": "*",
"babel-core": "^7.0.0-bridge.0",
"chalk": "^4.1.0",
"fs-extra": "^9.1.0",
"globby": "^11.1.0",
Expand Down
44 changes: 38 additions & 6 deletions packages/fetcher/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,50 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import fs from 'fs';
import path from 'path';
import globby from 'globby';
import { PluginManager } from 'live-plugin-manager';

import { CodeshiftConfig } from '@hypermod/types';
import { Config } from '@hypermod/types';

// This configuration allows us to require TypeScript config files directly
const { DEFAULT_EXTENSIONS } = require('@babel/core');
const presets = [];

let presetEnv;
try {
presetEnv = require('@babel/preset-env');
presets.push([presetEnv.default, { targets: { node: true } }]);
} catch (_) {}

require('@babel/register')({
configFile: false,
babelrc: false,
presets: [...presets, require('@babel/preset-typescript').default],
plugins: [
require('@babel/plugin-transform-class-properties').default,
require('@babel/plugin-transform-nullish-coalescing-operator').default,
require('@babel/plugin-transform-optional-chaining').default,
require('@babel/plugin-transform-modules-commonjs').default,
require('@babel/plugin-transform-private-methods').default,
],
extensions: [...DEFAULT_EXTENSIONS, '.ts', '.tsx'],
// By default, babel register only compiles things inside the current working directory.
// https://github.com/babel/babel/blob/2a4f16236656178e84b05b8915aab9261c55782c/packages/babel-register/src/node.js#L140-L157
ignore: [
// Ignore parser related files
/@babel\/parser/,
/\/flow-parser\//,
/\/recast\//,
/\/ast-types\//,
],
});

export interface ConfigMeta {
filePath: string;
config: CodeshiftConfig;
config: Config;
}

function resolveConfigExport(pkg: any): CodeshiftConfig {
function resolveConfigExport(pkg: any): Config {
return pkg.default ? pkg.default : pkg;
}

Expand Down Expand Up @@ -62,9 +96,7 @@ export async function fetchConfigs(filePath: string): Promise<ConfigMeta[]> {
return configs;
}

export async function fetchConfigAtPath(
filePath: string,
): Promise<CodeshiftConfig> {
export async function fetchConfigAtPath(filePath: string): Promise<Config> {
const resolvedFilePath = path.resolve(filePath);
const exists = fs.existsSync(resolvedFilePath);

Expand Down
4 changes: 3 additions & 1 deletion packages/types/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
export interface CodeshiftConfig {
export interface Config {
targets?: string[];
maintainers?: string[];
description?: string;
transforms?: Record<string, string>;
presets?: Record<string, string>;
}

export type CodeshiftConfig = Config;
16 changes: 8 additions & 8 deletions packages/validator/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import semver from 'semver';

import { CodeshiftConfig } from '@hypermod/types';
import { Config } from '@hypermod/types';
import { fetchConfig } from '@hypermod/fetcher';

function hasValidTransforms(config: CodeshiftConfig) {
function hasValidTransforms(config: Config) {
if (!config.transforms) return true;

return Object.entries(config.transforms).every(([key]) => semver.valid(key));
}

function hasValidPresets(config: CodeshiftConfig): boolean {
function hasValidPresets(config: Config): boolean {
if (!config.presets) return true;

return Object.entries(config.presets).every(([key]) =>
key.match(/^[0-9a-zA-Z\-]+$/),
);
}

function getInvalidProperties(config: CodeshiftConfig) {
function getInvalidProperties(config: Config) {
const validProperties = [
'maintainers',
'description',
Expand All @@ -33,7 +33,7 @@ export function isValidPackageName(dir: string): boolean {
return !!dir.match(/^(@[a-z0-9-~][a-z0-9-._~]*__)?[a-z0-9-~][a-z0-9-._~]*$/);
}

export function isValidConfig(config: CodeshiftConfig) {
export function isValidConfig(config: Config) {
return hasValidTransforms(config) && hasValidPresets(config);
}

Expand All @@ -44,10 +44,10 @@ export async function isValidConfigAtPath(filePath: string) {
throw new Error(`Unable to locate config file at path: ${filePath}`);
}

const invalidProperites = getInvalidProperties(configMeta.config);
if (invalidProperites.length) {
const invalidProperties = getInvalidProperties(configMeta.config);
if (invalidProperties.length) {
throw new Error(
`Invalid transform ids found: ${invalidProperites.join(', ')}`,
`Invalid transform ids found: ${invalidProperties.join(', ')}`,
);
}

Expand Down
Loading