ImportExtractor implements Serializable { List<String> getImportedPaths() { List<String> imports = new ArrayList<>(); String strippedContent = removeComments(); int indexFrom; int index = 0; while (index >= 0) { indexFrom = index; index = strippedContent.indexOf(IMPORT, indexFrom); if (index < 0) { break; } String betweenImports = strippedContent.substring(indexFrom, index) .trim(); if (!betweenImports.isEmpty() && !betweenImports.equals(";")) { break; } indexFrom = index + IMPORT.length(); index = strippedContent.indexOf(";", indexFrom); if (index < 0) { index = strippedContent.indexOf("\n", indexFrom); } if (index < 0) { index = strippedContent.length(); } String importStatement = strippedContent.substring(indexFrom, index) .trim(); int fromIndex = importStatement.indexOf(FROM); String path = importStatement; if (fromIndex >= 0) { path = importStatement.substring(fromIndex + FROM.length(), importStatement.length()).trim(); } imports.add(strip(path)); } return imports; } ImportExtractor(String polymerCode);   }
@Test public void getImportsWithBlockComment() { ImportExtractor extractor = new ImportExtractor( " import 'foo.js';"); List<String> importedPaths = extractor.getImportedPaths(); Assert.assertEquals(1, importedPaths.size()); Assert.assertEquals("foo.js", importedPaths.get(0)); }
@Test public void getImportsWithLineComments() { ImportExtractor extractor = new ImportExtractor( " List<String> importedPaths = extractor.getImportedPaths(); Assert.assertEquals(2, importedPaths.size()); Assert.assertEquals("foo.js", importedPaths.get(0)); Assert.assertEquals("bar.js", importedPaths.get(1)); }
@Test public void getImport_lineHasNoSemicolon() { ImportExtractor extractor = new ImportExtractor( "import {A} from 'foo.js'; import from 'bar.js'\n import from 'baz.js'"); List<String> importedPaths = extractor.getImportedPaths(); Assert.assertEquals(3, importedPaths.size()); Assert.assertEquals("foo.js", importedPaths.get(0)); Assert.assertEquals("bar.js", importedPaths.get(1)); Assert.assertEquals("baz.js", importedPaths.get(2)); }
@Test public void getImports_thereAreNoImportsAtAll_noImportsFound() { ImportExtractor extractor = new ImportExtractor( "const container = document.createElement('template');\n" + "\n" + " container.innerHTML = `\n" + " <dom-module id=\"gui-styles\">\n" + " <template>\n" + " <style>\n" + " @import url('https: + " </style>\n" + " </template>\n" + " </dom-module>`;\n" + " document.head.appendChild(container.content);"); Assert.assertEquals(0, extractor.getImportedPaths().size()); }
@Test public void getImports_onlyImportAsFirstStatementsAreCounted() { ImportExtractor extractor = new ImportExtractor( "import {A} from 'foo.js'; \n some text \n import from 'ignored.js';"); List<String> importedPaths = extractor.getImportedPaths(); Assert.assertEquals(1, importedPaths.size()); Assert.assertEquals("foo.js", importedPaths.get(0)); }