Skip to content

Commit

Permalink
chore: create isImportPresent
Browse files Browse the repository at this point in the history
  • Loading branch information
rishabh3112 committed May 31, 2019
1 parent 6a7e662 commit a89645a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 17 deletions.
37 changes: 20 additions & 17 deletions packages/utils/ast-utils.ts
@@ -1,6 +1,17 @@
import { JSCodeshift, Node, valueType } from "./types/NodePath";
import * as validateIdentifier from "./validate-identifier";


function isImportPresent (j: JSCodeshift, ast: Node, path: string): boolean {
let isPresent: boolean = false;
ast.find(j.CallExpression).forEach(callExp => {
if ((callExp.value as Node).callee.name === 'require' && (callExp.value as Node).arguments[0].value === path) {
isPresent = true;
}
})
return isPresent;
}

/**
*
* Traverse safely over a path object for array for paths
Expand Down Expand Up @@ -629,31 +640,23 @@ function parseMerge(j: JSCodeshift, ast: Node, value: string[], action: string):
right: j.callExpression(j.identifier("merge"), [j.identifier(configIdentifier), exportsDecl.pop()]),
type: "AssignmentExpression"
};

(p.value as Node).body[bodyLength - 1] = newVal;
return false; // TODO: debug later
}

function addMergeImports(ast: Node, mergeImports: string[]) {
ast.find(j.Program).filter((program: Node): boolean => {
mergeImports.forEach(
(imp: string): void => {
if ((program.value as Node).body.indexOf(imp) === -1){
(program.value as Node).body.splice(-1, 0, imp);
}
}
)
return false;
});
return ast;
function addMergeImports(configIdentifier: string, configPath: string) {
ast.find(j.Program).forEach(p => {
if (!isImportPresent(j, ast, 'webpack-merge')) {
(p.value as Node).body.splice(-1, 0, `const merge = require('webpack-merge')`);
}
(p.value as Node).body.splice(-1, 0, `const ${configIdentifier} = require('${configPath}')`);
})
}

if (value) {
const [configIdentifier, configPath] = value;
const mergeImports = [
`const ${configIdentifier} = require('${configPath}')`,
`const merge = require('webpack-merge')`
];
ast.replaceWith(addMergeImports(ast, mergeImports));
addMergeImports(configIdentifier, configPath);
return ast.find(j.Program).filter((p: Node): boolean => createMergeProperty(p, configIdentifier));
} else {
return ast;
Expand Down
1 change: 1 addition & 0 deletions packages/utils/types/NodePath.ts
Expand Up @@ -2,6 +2,7 @@ export interface Node extends Object {
id?: {
name: string;
};
callee?: Node;
arguments?: Node[];
body?: Node[];
elements?: Node[];
Expand Down

0 comments on commit a89645a

Please sign in to comment.