Skip to content

Commit

Permalink
Merge pull request #20 from victorsoares96/v0.3.1
Browse files Browse the repository at this point in the history
v0.3.1
  • Loading branch information
victorsoares96 authored Jul 18, 2022
2 parents aef8be7 + 6fe96ce commit af73abb
Show file tree
Hide file tree
Showing 24 changed files with 559 additions and 461 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
*.test.js
*.test.ts
dist
bin
22 changes: 2 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ This file will be used by the generator, it represents a set of instructions tha
],
"extensions": ["js", "jsx", "ts", "tsx"],
"outputDir": "out",
"outputFormat": "json", // can be xml to
"debug": false,
"analyzer": {
"mode": "jsx-text-only",
Expand Down Expand Up @@ -148,26 +149,7 @@ That asynchronous function above mentioned receives as argument:

That asynchronous function above mentioned returns:

- `result`: The result of the analysis. [See the result structure](#result-structure)

### Result Structure

```ts
type Result = {
/**
* Number of occurrences of non-internationalized strings.
*/
notInternationalizedCount: number;
/**
* Number of occurrences of internationalized strings.
*/
internationalizedCount: number;
/**
* Percentage of occurrences of internationalized strings.
*/
percentage: number;
};
```
- `result`: The result of the analysis. [See the result structure](src/types.ts#L36)

## Help to improve this project

Expand Down
2 changes: 1 addition & 1 deletion bin/intl-report
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
#!/usr/bin/env node
require('../dist/cjs/index.js')
require('../dist/cjs/cli.js')
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-intl-universal-reporter",
"version": "0.2.1",
"version": "0.3.1",
"description": "An report generator to measure the number of internationalized and non-internationalized occurrences of a project.",
"main": "dist/cjs/index.js",
"bin": {
Expand Down Expand Up @@ -68,24 +68,26 @@
]
},
"peerDependencies": {
"eslint": "^8.0.0",
"@typescript-eslint/parser": "^5.0.0"
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.0"
},
"dependencies": {
"@typescript-eslint/parser": "^5.28.0",
"eslint-plugin-react-intl-universal": "^1.0.4",
"glob-promise": "^4.2.2",
"gulp": "^4.0.2",
"gulp-eslint-new": "^1.5.1",
"jstoxml": "^1.0.1",
"lodash": "^4.17.21",
"ora": "5.4.1",
"@typescript-eslint/parser": "^5.28.0",
"typescript": "4.4.4"
},
"devDependencies": {
"@commitlint/cli": "^17.0.3",
"@commitlint/config-conventional": "^17.0.3",
"@types/gulp": "^4.0.9",
"@types/jest": "^28.1.3",
"@types/jstoxml": "^2.0.2",
"@types/lodash": "^4.14.182",
"@typescript-eslint/eslint-plugin": "^5.28.0",
"commitizen": "^4.2.4",
Expand Down
6 changes: 6 additions & 0 deletions renovate.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base"
]
}
37 changes: 37 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { generateReport } from './generateReport';
import { generateResult } from './generateResult';
import { getArguments } from './getArguments';
import { getSettings } from './getSettings';
import { saveReport } from './saveReport';

(async () => {
try {
const args = getArguments(process.argv.slice(2));

const source = args['--source'];
const configFile = args['--config-file'];

const settings = await getSettings(configFile);

const results = await generateResult(
source,
settings,
// ! The parameter in this function has been changed to json if the user wants to have the output in xml or js(json) if he uses this function outside the cli
settings.outputFormat === 'html' ? 'json' : 'xml'
);

let report: string;

if (settings.outputFormat === 'html') {
report = await generateReport(results, settings);
await saveReport(settings.outputDir, report, settings.outputFormat);
}

if (settings.outputFormat === 'xml') {
report = String(results);
await saveReport(settings.outputDir, report, settings.outputFormat);
}
} catch (error: any) {
throw new Error(error);
}
})();
92 changes: 38 additions & 54 deletions src/generateReport.ts
Original file line number Diff line number Diff line change
@@ -1,58 +1,42 @@
import gulp from 'gulp';
import gulpESLintNew from 'gulp-eslint-new';
import path from 'path';
import fs from 'fs';
import ora from 'ora';
import generateTemplate from './templates/template-generator';
import eslintConfig from './eslint_config';
import { Analyzer, ReporterSettings } from './types';
import path from 'path';
import _ from 'lodash';

import { renderSummaryTemplate } from './templates/summary.template';

import { ReporterSettings, Results } from './types';
import { renderResultsTemplate } from './templates/results.template';

const pageTemplate = _.template(
fs.readFileSync(path.join(__dirname, 'templates', 'main-page.html'), 'utf-8')
);

const styles = _.template(
fs.readFileSync(path.join(__dirname, 'helpers/styles.html'), 'utf-8')
);

const scripts = _.template(
fs.readFileSync(path.join(__dirname, 'helpers/scripts.html'), 'utf-8')
);

export async function generateReport(
files: string[],
output: string,
debug: boolean,
analyzer: Analyzer,
reporterSettings: ReporterSettings
): Promise<NodeJS.ReadWriteStream> {
let filesProcessed = 0;
const totalFiles = files.length;

const spinner = ora('Generating report').start();
return gulp
.src(files)
.pipe(
gulpESLintNew({
useEslintrc: false,
allowInlineConfig: false,
baseConfig: {
...eslintConfig,
rules: {
...eslintConfig.rules,
'react-intl-universal/no-literal-string': ['error', analyzer],
},
},
})
)
.pipe(
gulpESLintNew
.format(
(results) => generateTemplate(results, reporterSettings),
(results) => {
const reportName = `intl-report-${new Date().getTime()}.html`;
if (!fs.existsSync(output)) fs.mkdirSync(output);
fs.writeFileSync(path.join(output, reportName), results);
spinner.succeed(
`Generated report for ${totalFiles} files. See ${output}/${reportName}`
);
}
)
.on('data', (file) => {
filesProcessed += 1;
spinner.text = `Generating report (${filesProcessed}/${totalFiles})`;

if (debug) {
console.log(`\nFile processed: ${file.path}`);
}
})
);
result: Results,
config: ReporterSettings
) {
const { template } = config;

const { internationalizedCount, notInternationalizedCount, results } = result;

const currentDir = process.cwd() || '';

return pageTemplate({
title: template.title,
reportSummary: renderSummaryTemplate(
notInternationalizedCount,
internationalizedCount
),
results: renderResultsTemplate(results, currentDir),
styles: styles(),
scripts: scripts(),
});
}
88 changes: 80 additions & 8 deletions src/generateResult.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,33 @@
import gulp from 'gulp';
import gulpESLintNew from 'gulp-eslint-new';
import ora from 'ora';
import _ from 'lodash';
import { toXML } from 'jstoxml';
import eslintConfig from './eslint_config';
import { Result } from './types';
import { Occurrence, ReporterSettings, Results } from './types';
import { findFiles } from './findFiles';
import { getSettings } from './getSettings';

export async function generateResult(
source: string,
configFile?: string
): Promise<Result> {
config?: string | ReporterSettings,
outputFormat?: 'json' | 'xml'
): Promise<Results> {
let filesProcessed = 0;

const reporterSettings = await getSettings(configFile);
let reporterSettings: ReporterSettings;

if (config) {
if (typeof config === 'string') {
reporterSettings = await getSettings(config);
} else {
reporterSettings = config;
}
} else {
reporterSettings = await getSettings();
}

const spinner = ora('Finding files').start();

const files = await findFiles(
source,
Expand All @@ -21,9 +36,16 @@ export async function generateResult(
reporterSettings.debug
);

if (_.isEmpty(files)) {
spinner.fail('No files found!');
process.exit(0);
}

const totalFiles = files.length;

const spinner = ora('Generating results').start();
spinner.succeed(`Found ${totalFiles} files`);

spinner.start('Analyzing files');

return new Promise((resolve, reject) => {
gulp
Expand Down Expand Up @@ -62,14 +84,64 @@ export async function generateResult(
100
);

return {
const result: Results = {
notInternationalizedCount,
internationalizedCount,
percentage,
} as any;
results: results.map(
({
filePath,
messages,
errorCount,
warningCount,
source: fileSource,
}) => {
const filePercentage = Math.round(
(warningCount / (errorCount + warningCount)) * 100
);
return {
filePath,
occurrences: messages.map(
({
ruleId,
line,
endLine,
column,
endColumn,
message,
}) =>
({
type:
ruleId ===
'react-intl-universal/no-literal-string'
? 'not-internationalized'
: 'internationalized',
line,
endLine,
column,
endColumn,
message,
} as Occurrence)
),
notInternationalizedCount: errorCount,
internationalizedCount: warningCount,
percentage: filePercentage,
source: fileSource,
};
}
),
};
return result as any;
},
(results) => {
resolve(results as unknown as Result);
if (outputFormat === 'xml') {
resolve(
toXML(
{ intl: { results } },
{ indent: ' ', header: true }
) as any
);
} else resolve(results as unknown as Results);
spinner.succeed(`Finish! ${totalFiles} files processed`);
}
)
Expand Down
40 changes: 3 additions & 37 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,5 @@
import _ from 'lodash';
import ora from 'ora';
import { findFiles } from './findFiles';
import { generateReport } from './generateReport';
import { getArguments } from './getArguments';
import { getSettings } from './getSettings';
import { generateResult } from './generateResult';

(async () => {
const spinner = ora('Finding files').start();
try {
const args = getArguments(process.argv.slice(2));
export * from './types';

const reporterSettings = await getSettings(args['--config-file']);

const files = await findFiles(
args['--source'],
reporterSettings.ignorePatterns,
reporterSettings.extensions,
reporterSettings.debug
);
spinner.succeed(`Found ${files.length} files`);

if (_.isEmpty(files)) {
spinner.fail('No files found!');
process.exit(0);
}

generateReport(
files,
reporterSettings.outputDir,
reporterSettings.debug,
reporterSettings.analyzer,
reporterSettings
);
} catch (error: any) {
spinner.stop();
throw new Error(error);
}
})();
export { generateResult };
1 change: 1 addition & 0 deletions src/intlrc-default.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
],
"extensions": ["js", "jsx", "ts", "tsx"],
"outputDir": "out",
"outputFormat": "html",
"debug": false,
"analyzer": {
"mode": "jsx-text-only",
Expand Down
Loading

0 comments on commit af73abb

Please sign in to comment.