Skip to content

Commit c9ae44d

Browse files
Merge pull request #117 from CodeshiftCommunity/abstract-fetching-logic
Internal refactor of package fetching logic, which is now also reused…
2 parents a90c7a2 + 1d034ab commit c9ae44d

File tree

6 files changed

+107
-98
lines changed

6 files changed

+107
-98
lines changed

.changeset/stupid-jokes-yell.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@codeshift/cli': patch
3+
---
4+
5+
The internal package fetching logic has now been abstracted and reused in both the list and main CLI commands

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
"monorepo:fix": "manypkg fix && preconstruct fix",
2525
"cli:start": "node packages/cli/bin/codeshift-cli.js",
2626
"cli:validate": "node packages/cli/bin/codeshift-cli.js validate",
27+
"cli:list": "node packages/cli/bin/codeshift-cli.js list",
2728
"init:codemods": "ts-node scripts/initialize.ts",
2829
"validate:codemods": "ts-node scripts/validate.ts ./community",
2930
"release:codemods": "ts-node scripts/publish.ts ./community .tmp",

packages/cli/src/fetch-package.ts

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import ora from 'ora';
2+
import chalk from 'chalk';
3+
import merge from 'lodash/merge';
4+
import { PluginManager } from 'live-plugin-manager';
5+
6+
import { fetchPackage, fetchRemotePackage } from '@codeshift/fetcher';
7+
import { isValidConfig } from '@codeshift/validator';
8+
import { CodeshiftConfig } from '@codeshift/types';
9+
10+
function getCodeshiftPackageName(packageName: string) {
11+
return `@codeshift/mod-${packageName.replace('@', '').replace('/', '__')}`;
12+
}
13+
14+
export async function fetchPackageConfig(
15+
packageName: string,
16+
packageManager: PluginManager,
17+
) {
18+
let codeshiftConfig: CodeshiftConfig | undefined;
19+
let remoteConfig: CodeshiftConfig | undefined;
20+
21+
const spinner = ora(
22+
`${chalk.green('Attempting to download package:')} ${packageName}`,
23+
).start();
24+
25+
try {
26+
codeshiftConfig = await fetchPackage(
27+
getCodeshiftPackageName(packageName),
28+
packageManager,
29+
);
30+
spinner.succeed(
31+
`${chalk.green(
32+
`Found CodeshiftCommunity package: `,
33+
)} ${getCodeshiftPackageName(packageName)}`,
34+
);
35+
} catch (error) {
36+
spinner.warn(
37+
`${chalk.yellow(
38+
`Unable to locate CodeshiftCommunity package: `,
39+
)} ${getCodeshiftPackageName(packageName)}`,
40+
);
41+
}
42+
43+
try {
44+
remoteConfig = await fetchRemotePackage(packageName, packageManager);
45+
spinner.succeed(
46+
`${chalk.green(`Found codeshift package: `)} ${packageName}`,
47+
);
48+
} catch (error) {
49+
spinner.warn(
50+
`${chalk.yellow(`Unable to locate codeshift package: `)} ${packageName}`,
51+
);
52+
}
53+
54+
if (!codeshiftConfig && !remoteConfig) {
55+
throw new Error(
56+
`Unable to locate package from codeshift-community or NPM.
57+
Make sure the package name "${packageName}" is correct and try again.`,
58+
);
59+
}
60+
61+
const config: CodeshiftConfig = merge({}, remoteConfig, codeshiftConfig);
62+
63+
if (!isValidConfig(config)) {
64+
throw new Error(
65+
`Unable to locate a valid codeshift.config in package ${packageName}`,
66+
);
67+
}
68+
69+
return config;
70+
}

packages/cli/src/list.spec.ts

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -110,18 +110,11 @@ ${chalk.bold('@foo/bar')}
110110

111111
it('should continue if one or more packages are not found', async () => {
112112
(PluginManager as jest.Mock).mockImplementation(() => ({
113-
install: jest
114-
.fn()
115-
.mockImplementationOnce(() => {
113+
install: jest.fn().mockImplementation((packageName: string) => {
114+
if (packageName.includes('unknown') || packageName.includes('dunno')) {
116115
throw new Error('404 not found');
117-
})
118-
.mockResolvedValueOnce(undefined)
119-
.mockResolvedValueOnce(undefined)
120-
.mockImplementationOnce(() => {
121-
throw new Error('404 not found');
122-
})
123-
.mockResolvedValueOnce(undefined)
124-
.mockResolvedValueOnce(undefined),
116+
}
117+
}),
125118
require: jest.fn().mockImplementation(() => ({
126119
transforms: {
127120
'18.0.0': 'path/to/18.js',

packages/cli/src/list.ts

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
import chalk from 'chalk';
22
import { PluginManager } from 'live-plugin-manager';
3-
import { CodeshiftConfig } from '@codeshift/types';
3+
4+
import { fetchPackageConfig } from './fetch-package';
45

56
export default async function list(packages: string[]) {
67
const packageManager = new PluginManager();
8+
const configs = [];
79

810
for (const packageName of packages) {
9-
const pkgSplit = packageName.split('@').filter(str => !!str);
10-
const name = pkgSplit[0].replace('/', '__');
11-
const codemodName = `@codeshift/mod-${name}`;
12-
1311
try {
14-
await packageManager.install(codemodName);
12+
const config = await fetchPackageConfig(packageName, packageManager);
13+
configs.push({ packageName, config });
1514
} catch (error) {
1615
console.warn(
1716
chalk.red(
@@ -21,33 +20,31 @@ export default async function list(packages: string[]) {
2120

2221
continue;
2322
}
23+
}
2424

25-
await packageManager.install(codemodName);
26-
const pkg = packageManager.require(codemodName);
27-
const config: CodeshiftConfig = pkg.default ? pkg.default : pkg;
28-
25+
configs.forEach(({ packageName, config }) => {
2926
console.log(chalk.bold(packageName));
3027

3128
if (config.transforms) {
32-
console.log(`├─ transforms`),
33-
Object.keys(config.transforms).forEach((transform, index, array) => {
34-
if (index + 1 === array.length) {
35-
console.log(`| └─ ${transform}`);
36-
return;
37-
}
38-
console.log(`| ├─ ${transform}`);
39-
});
29+
console.log(`├─ transforms`);
30+
Object.keys(config.transforms).forEach((transform, index, array) => {
31+
if (index + 1 === array.length) {
32+
console.log(`| └─ ${transform}`);
33+
return;
34+
}
35+
console.log(`| ├─ ${transform}`);
36+
});
4037
}
4138

4239
if (config.presets) {
43-
console.log(`└─ presets`),
44-
Object.keys(config.presets).forEach((transform, index, array) => {
45-
if (index + 1 === array.length) {
46-
console.log(` └─ ${transform}`);
47-
return;
48-
}
49-
console.log(`| ├─ ${transform}`);
50-
});
40+
console.log(`└─ presets`);
41+
Object.keys(config.presets).forEach((transform, index, array) => {
42+
if (index + 1 === array.length) {
43+
console.log(` └─ ${transform}`);
44+
return;
45+
}
46+
console.log(`| ├─ ${transform}`);
47+
});
5148
}
52-
}
49+
});
5350
}

packages/cli/src/main.ts

Lines changed: 3 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,14 @@
11
import path from 'path';
22
import semver from 'semver';
33
import chalk from 'chalk';
4-
import ora from 'ora';
54
import { PluginManager } from 'live-plugin-manager';
6-
import merge from 'lodash/merge';
5+
76
// @ts-ignore Run transform(s) on path https://github.com/facebook/jscodeshift/issues/398
87
import * as jscodeshift from 'jscodeshift/src/Runner';
98

10-
import { fetchPackage, fetchRemotePackage } from '@codeshift/fetcher';
11-
import { isValidConfig } from '@codeshift/validator';
12-
import { CodeshiftConfig } from '@codeshift/types';
13-
149
import { Flags } from './types';
1510
import { InvalidUserInputError } from './errors';
16-
17-
function getCodeshiftPackageName(packageName: string) {
18-
return `@codeshift/mod-${packageName.replace('@', '').replace('/', '__')}`;
19-
}
11+
import { fetchPackageConfig } from './fetch-package';
2012

2113
export default async function main(paths: string[], flags: Flags) {
2214
const packageManager = new PluginManager({
@@ -53,56 +45,7 @@ export default async function main(paths: string[], flags: Flags) {
5345
const pkgName =
5446
shouldPrependAtSymbol + pkg.split(/[@#]/).filter(str => !!str)[0];
5547

56-
let codeshiftConfig: CodeshiftConfig | undefined;
57-
let remoteConfig: CodeshiftConfig | undefined;
58-
59-
const spinner = ora(
60-
`${chalk.green('Attempting to download package:')}, ${pkgName}`,
61-
).start();
62-
63-
try {
64-
codeshiftConfig = await fetchPackage(
65-
getCodeshiftPackageName(pkgName),
66-
packageManager,
67-
);
68-
spinner.succeed(
69-
`${chalk.green(
70-
`Found CodeshiftCommunity package: `,
71-
)} ${getCodeshiftPackageName(pkgName)}`,
72-
);
73-
} catch (error) {
74-
spinner.warn(
75-
`${chalk.yellow(
76-
`Unable to locate CodeshiftCommunity package: `,
77-
)} ${getCodeshiftPackageName(pkgName)}`,
78-
);
79-
}
80-
81-
try {
82-
remoteConfig = await fetchRemotePackage(pkgName, packageManager);
83-
spinner.succeed(
84-
`${chalk.green(`Found codeshift package: `)} ${pkgName}`,
85-
);
86-
} catch (error) {
87-
spinner.warn(
88-
`${chalk.yellow(`Unable to locate codeshift package: `)} ${pkgName}`,
89-
);
90-
}
91-
92-
if (!codeshiftConfig && !remoteConfig) {
93-
throw new Error(
94-
`Unable to locate package from codeshift-community or NPM.
95-
Make sure the package name "${pkgName}" is correct and try again.`,
96-
);
97-
}
98-
99-
const config: CodeshiftConfig = merge({}, remoteConfig, codeshiftConfig);
100-
101-
if (!isValidConfig(config)) {
102-
throw new Error(
103-
`Unable to locate a valid codeshift.config in package ${pkgName}`,
104-
);
105-
}
48+
const config = await fetchPackageConfig(pkgName, packageManager);
10649

10750
const rawTransformIds = pkg.split(/(?=[@#])/).filter(str => !!str);
10851
rawTransformIds.shift();

0 commit comments

Comments
 (0)