Skip to content

Commit ad33da5

Browse files
authored
Merge pull request #77 from kreuzerk/feature/organizeImportsFunction
Feature/organize imports function
2 parents f88771d + 049edc1 commit ad33da5

File tree

5 files changed

+41
-34
lines changed

5 files changed

+41
-34
lines changed

__tests__/optimize-imports.spec.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { actions, optimizeImports } from '@ic/conductor/optimize-imports';
1+
import { actions, organizeImports, organizeImportsForFile } from '@ic/conductor/organize-imports';
22
import * as config from '@ic/config';
33
import fs from 'fs';
44
import { Config } from '@ic/types';
@@ -30,7 +30,7 @@ describe('optimizeImports', () => {
3030
const file = 'test.ts';
3131
let result: string;
3232
do {
33-
result = await optimizeImports(file);
33+
result = await organizeImportsForFile(file);
3434
} while (--noOfRun > 0);
3535

3636
expect(fs.writeFileSync).toHaveBeenCalledWith(file, expected);
@@ -58,7 +58,7 @@ describe('optimizeImports', () => {
5858
it('should not change conducted file', async () => {
5959
(fs.readFileSync as any).mockReturnValue(Buffer.from(readmeExample.expected));
6060
const file = 'test.ts';
61-
await optimizeImports(file);
61+
await organizeImports(file);
6262
expect(fs.writeFileSync).not.toHaveBeenCalled();
6363
});
6464

@@ -67,7 +67,7 @@ describe('optimizeImports', () => {
6767
for (const testCase of testCases) {
6868
(fs.readFileSync as any).mockReturnValue(Buffer.from(testCase));
6969
const file = 'test.ts';
70-
const result = await optimizeImports(file);
70+
const result = await organizeImportsForFile(file);
7171
expect(result).toBe(actions.skipped);
7272
expect(fs.writeFileSync).not.toHaveBeenCalled();
7373
}

src/conductor/conduct.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ import { resolveConfig, setConfig } from '../config';
66
import { log } from '../helpers/log';
77
import { Config } from '../types';
88

9+
import { organizeImportsForFile } from './organize-imports';
910
import { getFilesPaths } from './get-files-paths';
10-
import { actions, optimizeImports } from './optimize-imports';
11+
import { actions } from './organize-imports';
1112

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

39-
const actionDone = await optimizeImports(path);
40+
const actionDone = await organizeImportsForFile(path);
4041
if (actionDone in results) {
4142
results[actionDone]++;
4243
}

src/conductor/optimize-imports.ts renamed to src/conductor/organize-imports.ts

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -31,27 +31,49 @@ function getFileComment(fileContent: string): string {
3131
return '';
3232
}
3333

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

4040
let fileContent = readFileSync(filePath).toString();
41-
const lineEnding = detectLineEnding(fileContent);
41+
if (/\/[/*]\s*import-conductor-skip/.test(fileContent)) {
42+
log('gray', 'skipped (via comment)', filePath);
43+
return actions.skipped;
44+
}
4245
const { staged, autoAdd, dryRun } = getConfig();
46+
const fileWithOrganizedImports = await organizeImports(fileContent);
47+
const fileHasChanged = fileWithOrganizedImports !== fileContent;
48+
49+
if (fileHasChanged) {
50+
!dryRun && writeFileSync(filePath, fileWithOrganizedImports);
51+
let msg = 'imports reordered';
52+
if (staged && autoAdd) {
53+
await git.add(filePath);
54+
msg += ', added to git';
55+
}
56+
log('green', msg, filePath);
57+
} else {
58+
log('gray', 'no change needed', filePath);
59+
}
60+
61+
return fileHasChanged ? actions.reordered : actions.none;
62+
}
63+
64+
export async function organizeImports(fileContent: string): Promise<string> {
65+
const lineEnding = detectLineEnding(fileContent);
4366
if (/\/[/*]\s*import-conductor-skip/.test(fileContent)) {
44-
log('gray', filePath, 'skipped (via comment)');
67+
log('gray', 'Format skipped (via comment)');
4568
return actions.skipped;
4669
}
4770

4871
let fileComment = getFileComment(fileContent);
49-
// Remove the comment from the file content.
5072
if (fileComment) {
5173
fileContent = fileContent.replace(fileComment, '');
5274
}
5375

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

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

7697
if (fileComment) {
77-
// Add the comment back to the file content.
78-
fileContent = `${fileComment}${fileContent}`;
7998
updatedContent = `${fileComment}\n` + updatedContent;
8099
}
81-
82-
const fileHasChanged = updatedContent !== fileContent;
83-
if (fileHasChanged) {
84-
!dryRun && writeFileSync(filePath, updatedContent);
85-
let msg = 'imports reordered';
86-
if (staged && autoAdd) {
87-
await git.add(filePath);
88-
msg += ', added to git';
89-
}
90-
log('green', filePath, msg);
91-
} else {
92-
log('gray', filePath, 'no change needed');
93-
}
94-
95-
return fileHasChanged ? actions.reordered : actions.none;
100+
return updatedContent;
96101
}

src/helpers/log.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@ import chalk from 'chalk';
22

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

5-
export function log(color: string, file: string, message: string) {
6-
getConfig().verbose && console.log(chalk[color](`${file} - ${message}`));
5+
export function log(color: string, message: string, file?: string) {
6+
getConfig().verbose && file ? console.log(chalk[color](`${file} - ${message}`)) : console.log(chalk[color](`${message}`));
77
}

src/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ import commandLineArgs from 'command-line-args';
55
import commandLineUsage from 'command-line-usage';
66

77
import { packageVersion } from './version';
8+
import chalk from 'chalk';
89

10+
import { organizeImports } from './conductor/organize-imports';
911
import { optionDefinitions, sections } from './cliOptions';
1012
import { conduct } from './conductor/conduct';
11-
import chalk from 'chalk';
1213

13-
export { conduct };
14+
export { conduct, organizeImports };
1415

1516
const cliConfig = commandLineArgs(optionDefinitions, {
1617
camelCase: true,

0 commit comments

Comments
 (0)