Skip to content

Commit

Permalink
Merge pull request #77 from kreuzerk/feature/organizeImportsFunction
Browse files Browse the repository at this point in the history
Feature/organize imports function
  • Loading branch information
nivekcode authored Apr 5, 2022
2 parents f88771d + 049edc1 commit ad33da5
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 34 deletions.
8 changes: 4 additions & 4 deletions __tests__/optimize-imports.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { actions, optimizeImports } from '@ic/conductor/optimize-imports';
import { actions, organizeImports, organizeImportsForFile } from '@ic/conductor/organize-imports';
import * as config from '@ic/config';
import fs from 'fs';
import { Config } from '@ic/types';
Expand Down Expand Up @@ -30,7 +30,7 @@ describe('optimizeImports', () => {
const file = 'test.ts';
let result: string;
do {
result = await optimizeImports(file);
result = await organizeImportsForFile(file);
} while (--noOfRun > 0);

expect(fs.writeFileSync).toHaveBeenCalledWith(file, expected);
Expand Down Expand Up @@ -58,7 +58,7 @@ describe('optimizeImports', () => {
it('should not change conducted file', async () => {
(fs.readFileSync as any).mockReturnValue(Buffer.from(readmeExample.expected));
const file = 'test.ts';
await optimizeImports(file);
await organizeImports(file);
expect(fs.writeFileSync).not.toHaveBeenCalled();
});

Expand All @@ -67,7 +67,7 @@ describe('optimizeImports', () => {
for (const testCase of testCases) {
(fs.readFileSync as any).mockReturnValue(Buffer.from(testCase));
const file = 'test.ts';
const result = await optimizeImports(file);
const result = await organizeImportsForFile(file);
expect(result).toBe(actions.skipped);
expect(fs.writeFileSync).not.toHaveBeenCalled();
}
Expand Down
7 changes: 4 additions & 3 deletions src/conductor/conduct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import { resolveConfig, setConfig } from '../config';
import { log } from '../helpers/log';
import { Config } from '../types';

import { organizeImportsForFile } from './organize-imports';
import { getFilesPaths } from './get-files-paths';
import { actions, optimizeImports } from './optimize-imports';
import { actions } from './organize-imports';

export async function conduct(configuration: Partial<Config>): Promise<string[]> {
const config = resolveConfig(configuration);
Expand All @@ -32,11 +33,11 @@ export async function conduct(configuration: Partial<Config>): Promise<string[]>
const ignoreFile = ignore.includes(path) || ignore.some((p) => path.includes(p));
if (ignoreFile) {
results[actions.skipped]++;
log('gray', path, 'skipped (via ignore pattern)');
log('gray', 'skipped (via ignore pattern)', path);
continue;
}

const actionDone = await optimizeImports(path);
const actionDone = await organizeImportsForFile(path);
if (actionDone in results) {
results[actionDone]++;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,27 +31,49 @@ function getFileComment(fileContent: string): string {
return '';
}

export async function optimizeImports(filePath: string): Promise<string> {
export async function organizeImportsForFile(filePath: string): Promise<string> {
// staged files might also include deleted files, we need to verify they exist.
if (!/\.tsx?$/.test(filePath) || !existsSync(filePath)) {
return actions.none;
}

let fileContent = readFileSync(filePath).toString();
const lineEnding = detectLineEnding(fileContent);
if (/\/[/*]\s*import-conductor-skip/.test(fileContent)) {
log('gray', 'skipped (via comment)', filePath);
return actions.skipped;
}
const { staged, autoAdd, dryRun } = getConfig();
const fileWithOrganizedImports = await organizeImports(fileContent);
const fileHasChanged = fileWithOrganizedImports !== fileContent;

if (fileHasChanged) {
!dryRun && writeFileSync(filePath, fileWithOrganizedImports);
let msg = 'imports reordered';
if (staged && autoAdd) {
await git.add(filePath);
msg += ', added to git';
}
log('green', msg, filePath);
} else {
log('gray', 'no change needed', filePath);
}

return fileHasChanged ? actions.reordered : actions.none;
}

export async function organizeImports(fileContent: string): Promise<string> {
const lineEnding = detectLineEnding(fileContent);
if (/\/[/*]\s*import-conductor-skip/.test(fileContent)) {
log('gray', filePath, 'skipped (via comment)');
log('gray', 'Format skipped (via comment)');
return actions.skipped;
}

let fileComment = getFileComment(fileContent);
// Remove the comment from the file content.
if (fileComment) {
fileContent = fileContent.replace(fileComment, '');
}

const rootNode = ts.createSourceFile(filePath, fileContent, ts.ScriptTarget.Latest, true);
const rootNode = ts.createSourceFile('temp', fileContent, ts.ScriptTarget.Latest, true);
const importNodes = collectImportNodes(rootNode);
const importStatementMap = getImportStatementMap(importNodes);
if (importStatementMap.size === 0) {
Expand All @@ -65,7 +87,6 @@ export async function optimizeImports(filePath: string): Promise<string> {
const lastImport = importNodes.pop();
const contentWithoutImportStatements = fileContent.slice(lastImport.end);

// Add back code blocks that were between the import statements
const nonImportNodes = collectNonImportNodes(rootNode, lastImport);
if (nonImportNodes) {
updatedContent += nonImportNodes.map((n) => n.getFullText()).join('');
Expand All @@ -74,23 +95,7 @@ export async function optimizeImports(filePath: string): Promise<string> {
updatedContent += contentWithoutImportStatements;

if (fileComment) {
// Add the comment back to the file content.
fileContent = `${fileComment}${fileContent}`;
updatedContent = `${fileComment}\n` + updatedContent;
}

const fileHasChanged = updatedContent !== fileContent;
if (fileHasChanged) {
!dryRun && writeFileSync(filePath, updatedContent);
let msg = 'imports reordered';
if (staged && autoAdd) {
await git.add(filePath);
msg += ', added to git';
}
log('green', filePath, msg);
} else {
log('gray', filePath, 'no change needed');
}

return fileHasChanged ? actions.reordered : actions.none;
return updatedContent;
}
4 changes: 2 additions & 2 deletions src/helpers/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import chalk from 'chalk';

import { getConfig } from '../config';

export function log(color: string, file: string, message: string) {
getConfig().verbose && console.log(chalk[color](`${file} - ${message}`));
export function log(color: string, message: string, file?: string) {
getConfig().verbose && file ? console.log(chalk[color](`${file} - ${message}`)) : console.log(chalk[color](`${message}`));
}
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import commandLineArgs from 'command-line-args';
import commandLineUsage from 'command-line-usage';

import { packageVersion } from './version';
import chalk from 'chalk';

import { organizeImports } from './conductor/organize-imports';
import { optionDefinitions, sections } from './cliOptions';
import { conduct } from './conductor/conduct';
import chalk from 'chalk';

export { conduct };
export { conduct, organizeImports };

const cliConfig = commandLineArgs(optionDefinitions, {
camelCase: true,
Expand Down

0 comments on commit ad33da5

Please sign in to comment.