Skip to content

Commit

Permalink
Detect: import util from "util"
Browse files Browse the repository at this point in the history
Refs #33
  • Loading branch information
nene committed Sep 18, 2016
1 parent d38812c commit 52c5bc7
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/transform/class/inheritance/ImportUtilDetector.js
@@ -0,0 +1,50 @@
import {isAstMatch, extract, matchesLength} from '../../../utils/matchesAst';

/**
* Detects variable name imported from: import <name> from "util"
*/
export default class ImportUtilDetector {
/**
* Detects: import <identifier> from "util"
*
* @param {Object} node
* @return {Object} MemberExpression of <identifier>.inherits
*/
detect(node) {
const m = this.matchImportUtil(node);
if (m) {
return {
type: 'MemberExpression',
computed: false,
object: {
type: 'Identifier',
name: m.name,
},
property: {
type: 'Identifier',
name: 'inherits'
}
};
}
}

// Matches: import <name> from "util"
matchImportUtil(node) {
return isAstMatch(node, {
type: 'ImportDeclaration',
specifiers: matchesLength([
{
type: 'ImportDefaultSpecifier',
local: {
type: 'Identifier',
name: extract('name')
}
}
]),
source: {
type: 'Literal',
value: 'util'
}
});
}
}
2 changes: 2 additions & 0 deletions src/transform/class/inheritance/UtilInherits.js
@@ -1,6 +1,7 @@
import {isAstMatch, extract} from '../../../utils/matchesAst';
import RequireUtilDetector from './RequireUtilDetector';
import RequireUtilInheritsDetector from './RequireUtilInheritsDetector';
import ImportUtilDetector from './ImportUtilDetector';

/**
* Processes nodes to detect super classes and return information for later
Expand All @@ -18,6 +19,7 @@ export default class UtilInherits {
this.detectors = [
new RequireUtilDetector(),
new RequireUtilInheritsDetector(),
new ImportUtilDetector(),
];
}

Expand Down
30 changes: 30 additions & 0 deletions test/transform/classInheritanceTest.js
Expand Up @@ -27,6 +27,36 @@ describe('Class Inheritance', () => {
);
});

it('supports import from "util"', () => {
expectTransform(
'import util from "util";\n' +
'function MyClass() {\n' +
'}\n' +
'util.inherits(MyClass, ParentClass);'
).toReturn(
'import util from "util";\n' +
'class MyClass extends ParentClass {}'
);
});

it('ignores import of anything else than "util"', () => {
expectNoChange(
'import util from "./util";\n' +
'function MyClass() {\n' +
'}\n' +
'util.inherits(MyClass, ParentClass);'
);
});

it('ignores named imports from "util"', () => {
expectNoChange(
'import {util} from "util";\n' +
'function MyClass() {\n' +
'}\n' +
'util.inherits(MyClass, ParentClass);'
);
});

it('preserves inheritance when the inherited class is a member expression', () => {
expectTransform(
'var util = require("util");\n' +
Expand Down

0 comments on commit 52c5bc7

Please sign in to comment.