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

Feat add codemod check to doctor package #870

Merged
merged 5 commits into from
Jun 29, 2021
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
12 changes: 6 additions & 6 deletions packages/doctor/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# changelog

## 0.4.8
- update eslint to version 7.0
## 0.2.0

## 0.4.7
- support scan `unknown` framework project
- Remove codemod CLI usage.
- Add codemod check and fix reports to `scan`.

## 0.4.6
- fix can't catch timeout error
## 0.1.0

- Init
38 changes: 4 additions & 34 deletions packages/doctor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,13 @@ $ appworks-doctor -s ./ --ignore types mock

* fix?: boolean, whether fix ESLint fixable problems.
* framework?: string, target project framework, default is `react`.
* transforms?: string[], you want to run code transform keys, from [@appworks/codemod](https://github.com/appworks-lab/codemod/)
* languageType?: 'js'|'ts', target project languageType, default is `js`.
* tempFileDir?: string, set temp reporters file directory, default is `node_modules/@appworks/doctor/tmp/`.
* disableESLint?: boolean, whether disable ESLint part reports.
* disableMaintainability?: boolean, whether disable maintainability part reports.
* disableRepeatability?: boolean, whether disable repeatability part reports.

* disableCodemod?: boolean, whether disable codemod part reports.
### Result

#### ESLint
Expand Down Expand Up @@ -84,39 +85,8 @@ Use [typhonjs-escomplex](https://www.npmjs.com/package/typhonjs-escomplex) calcu

Use [jscpd](https://www.npmjs.com/package/jscpd) calculate repeatability reports.

## 2. Codemod

This repository also contains a collection of codemod scripts that help update React([ICE](https://ice.work/)) and [Rax](https://rax.js.org/) APIs.

### Installation

Install [jscodeshift](https://www.npmjs.com/package/jscodeshift) and @appworks/doctor.

```shell
$ npm i -g jscodeshift @appworks/doctor
```

### Usage (CLI)
#### Codemod

`appworks-doctor -c <transform> <path?> [...options?]`

* `transform` - name of transform, see available transforms below.
* `path?` - files or directory to transform.
* `options?` - some rule's options.

This will start an interactive wizard, and then run the specified transform.

PS: You can also clone this repository then use [jscodeshift](https://www.npmjs.com/package/jscodeshift)'s CLI API.

### Included Transforms

#### `plugin-rax-component-to-component`

Update `plugin-rax-component` to `plugin-component`.
See: https://rax.js.org/docs/guide/com-migration

```shell
appworks-doctor -c plugin-rax-component-to-component ./
```
Use [@appworks/codemod](https://www.npmjs.com/package/@appworks/codemod) check and update Rax and React deprecated usages.

Enjoy!
37 changes: 1 addition & 36 deletions packages/doctor/bin/appworks-doctor
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,12 @@
'use strict';

const argv = require('argv-parse');
const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const options = require('./options.json');
const pkg = require('../package.json');
const { Doctor } = require('../lib/index');

const args = argv(options);

const transformerDirectory = path.join(__dirname, '../lib/', 'transforms');

// Show version
if (args.version) {
console.log(pkg.version);
Expand Down Expand Up @@ -50,7 +45,7 @@ if (args.scan) {
},
score: result.score || 0,
};
['ESLint', 'maintainability', 'repeatability'].forEach(key => {
['ESLint', 'maintainability', 'repeatability'].forEach((key) => {
if (result[key]) {
report[key] = result[key].score;
}
Expand All @@ -62,33 +57,3 @@ if (args.scan) {
console.error(err);
});
}

// codemod
if (args.codemod) {
args.supportExts = (args.supportExts || []).concat(['json']);
const [transformer, targetPath = process.cwd()] = args.codemod;

const doctor = new Doctor(args);
doctor.ignore = doctor.ignore.filter(i => i !== 'demo');
const files = doctor.getFiles(targetPath).map(file => file.path);

let transformerArgs = ['-p'];
const transformerPath = path.join(transformerDirectory, `${transformer}.js`);

if (!files.length) {
console.log(`No files found matching ${targetPath}`);
} else if (!fs.existsSync(transformerPath)) {
console.log(`No transformer found matching ${transformer}`);
} else {
transformerArgs = transformerArgs.concat(['--transform', transformerPath]);
transformerArgs = transformerArgs.concat(files);

// jscodeshift has too large size as node dependencies and better use in CLI env.
// Suggest user to install jscodeshift in codemod case.
spawnSync('jscodeshift', transformerArgs,
{
stdio: 'inherit',
stripEof: false,
});
}
}
5 changes: 0 additions & 5 deletions packages/doctor/bin/options.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,6 @@
"desc": "Scan target project directory.",
"type": "string"
},
"codemod":{
"alias": "c",
"desc": "codemod scripts that help update React(ICE) and Rax APIs.",
"type": "array"
},
"ignore": {
"desc": "Ignore directories when scan.",
"type": "array"
Expand Down
3 changes: 2 additions & 1 deletion packages/doctor/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@appworks/doctor",
"description": "Analyse and running codemods over react/rax projects, troubleshooting and automatically fixing errors",
"version": "0.1.0",
"version": "0.2.0",
"keywords": [
"doctor",
"analysis",
Expand All @@ -25,6 +25,7 @@
"prepublishOnly": "npm run compile"
},
"dependencies": {
"@appworks/codemod": "^0.1.0",
"@babel/parser": "^7.12.5",
"@babel/traverse": "^7.12.5",
"@iceworks/spec": "^1.0.2",
Expand Down
4 changes: 2 additions & 2 deletions packages/doctor/src/Analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ const LANGUAGE_MAP = {
const UNKNOWN_LANGUAGE = 'Other';

export default class Analyzer {
public options: IAnalyzerOptions;
options: IAnalyzerOptions;

constructor(options: IAnalyzerOptions) {
this.options = options;
}

public analyse(directory: string): IAnalyzerReport {
analyse(directory: string): IAnalyzerReport {
const report = { languages: [] } as IAnalyzerReport;
const languageCache = {};
const files: IFileInfo[] = getFiles(directory, this.options.ignore);
Expand Down
13 changes: 11 additions & 2 deletions packages/doctor/src/Scanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ import getFinalScore from './getFinalScore';
const tempDir = path.join(__dirname, 'tmp/');

export default class Scanner {
public options: IScannerOptions;
options: IScannerOptions;

constructor(options: IScannerOptions) {
this.options = options;
}

// Entry
public async scan(directory: string, options?: IScanOptions): Promise<IScannerReports> {
async scan(directory: string, options?: IScanOptions): Promise<IScannerReports> {
const timer = new Timer();
const reports = {} as IScannerReports;
const tempFileDir = options?.tempFileDir || tempDir;
Expand Down Expand Up @@ -67,6 +67,14 @@ export default class Scanner {
});
}

// Run Codemod
if (!options || options.disableCodemod !== true) {
subprocessList.push(execa.node(path.join(__dirname, './workers/codemod/index.js'), [`${directory} ${tempFileDir} ${options?.transforms}`]));
processReportList.push(async () => {
reports.codemod = await fs.readJSON(path.join(tempFileDir, config.tmpFiles.report.codemod));
});
}

async function process() {
// Check
await Promise.all(subprocessList);
Expand All @@ -79,6 +87,7 @@ export default class Scanner {
(reports.ESLint || {}).score,
(reports.maintainability || {}).score,
(reports.repeatability || {}).score,
(reports.codemod || {}).score,
].filter((score) => !isNaN(score)),
);

Expand Down
8 changes: 4 additions & 4 deletions packages/doctor/src/Scorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ export default class Scanner {
this.currentScore = options.start || this.highestScore;
}

public plus(score: number): number {
plus(score: number): number {
this.currentScore += score;
return this.getScore();
}

public minus(score: number): number {
minus(score: number): number {
this.currentScore -= score;
return this.getScore();
}

public getAverage(list: number[]): number {
getAverage(list: number[]): number {
if (list.length) {
let sum = 0;

Expand All @@ -46,7 +46,7 @@ export default class Scanner {
return this.getScore();
}

public getScore(): number {
getScore(): number {
if (this.currentScore > this.highestScore) {
return this.highestScore;
} else if (this.currentScore < this.lowestScore) {
Expand Down
6 changes: 3 additions & 3 deletions packages/doctor/src/Timer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ export default class Timer {
this.startTime = Date.now();
}

public async raceTimeout(ms: number) {
await new Promise(resolve => {
async raceTimeout(ms: number) {
await new Promise((resolve) => {
this.timer = setTimeout(resolve, ms);
});
throw new Error('@appworks/doctor time out!');
}

public duration(): number {
duration(): number {
if (this.timer) {
clearTimeout(this.timer);
}
Expand Down
1 change: 1 addition & 0 deletions packages/doctor/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export default {
eslint: 'eslint-result.json',
escomplex: 'escomplex-result.json',
jscpd: 'jscpd-result.json',
codemod: 'codemod-result.json',
},
},
};
4 changes: 2 additions & 2 deletions packages/doctor/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { IFileInfo } from './types/File';
// Ignore directories
const defaultignore = ['.faas_debug_tmp', '.ice', '.rax', 'build', 'es', 'dist', 'lib', 'mocks', 'logs', 'coverage', 'node_modules', 'demo', 'examples', 'public', 'test', '__tests__'];
class Doctor {
public options: any;
options: any;

public ignore: string[];
ignore: string[];

private scanner: any;

Expand Down
Loading