41 Commits
Author SHA1 Message Date
Gajus Kuizinas 2450b7202e chore: use semantic-release 2016-11-29 17:51:38 +00:00
Gajus Kuizinas 707ae70240 style: sort properties alphabetically 2016-11-29 17:50:16 +00:00
Gajus Kuizinas c6952fa1e1 chore: add a precommit hook 2016-11-29 17:49:57 +00:00
Gajus Kuizinas e6ebaec387 chore: setup env when running scripts 2016-11-29 17:49:44 +00:00
Gajus Kuizinas 1f0a517797 style: fix style issues 2016-11-29 17:49:05 +00:00
Gajus Kuizinas 7867b8f8c7 chore: use default travis test script 2016-11-29 17:48:50 +00:00
Gajus Kuizinas 9cfc2ad367 Merge branch 'master' of github.com:gajus/create-index 2016-11-29 17:45:58 +00:00
Gajus Kuizinas ab6c399241 fix: correct all the references to @create-index 2016-11-29 17:45:54 +00:00
laggingreflexandGajus Kuizinas fdb17d0179 feat: ability to add banner (#20)
Lets you add a custom banner.

```sh
create-index src -u --banner "/* eslint-disable */"
```
```js
/* eslint-disable */

// @create-index

import xxx ...
```
2016-11-29 17:45:23 +00:00
laggingreflexandGajus Kuizinas d7e2528999 fix: rename --update-index to --update (fixes #10) (#15) 2016-11-28 15:36:37 +00:00
laggingreflexandGajus Kuizinas 974142c38c fix: use comment to target files (fixes #5) (#17) 2016-11-28 15:35:43 +00:00
Gajus Kuizinas be0e6fdc75 1.0.0 2016-11-01 15:59:44 +00:00
Gajus Kuizinas 91c2e4eae3 feat: use comment to target files (fixes #5) 2016-11-01 15:58:31 +00:00
Gajus Kuizinas c41edde1cd docs: update documentation to reflect new option names (fixes #10) 2016-11-01 15:57:08 +00:00
Gajus Kuizinas d05b635834 feat: add alias -u to --update (fixes #10) 2016-11-01 15:50:18 +00:00
Gajus Kuizinas 9278b25dcd feat: rename --update-index to --update (fixes #10) 2016-11-01 15:50:02 +00:00
Gajus Kuizinas 3c5e96f8c0 chore: ignore ./test instead of ./tests 2016-11-01 15:46:36 +00:00
Gajus Kuizinas 696b817ce4 chore: add missing babel plugins 2016-11-01 15:45:29 +00:00
Gajus Kuizinas 2faeba74b3 chore: fix the build script 2016-11-01 15:36:19 +00:00
Gajus Kuizinas eac728be0b chore: add missing babel plugins 2016-11-01 15:36:09 +00:00
Gajus Kuizinas 2fa0d6635f chore: update dependencies 2016-11-01 15:33:28 +00:00
Gajus Kuizinas 08b9abc45a chore: define .travis.yml test scripts 2016-11-01 15:33:05 +00:00
Gajus Kuizinas a61cb3a14e chore: add .eslintignore 2016-11-01 15:31:41 +00:00
Gajus Kuizinas 272a836c96 chore: rename ./tests to ./test 2016-11-01 15:31:00 +00:00
Gajus Kuizinas 78109764f7 chore: move ./fixtures folder under ./tests 2016-11-01 15:30:04 +00:00
Gajus Kuizinas 335152f0d4 chore: replace pragmatist with Mocha, ESLint, Babel 2016-11-01 15:27:12 +00:00
Gajus Kuizinas 858085656b style: fix code style 2016-11-01 15:26:29 +00:00
Gajus Kuizinas 7990da993f chore: define minimum node requirement v5 2016-11-01 14:55:36 +00:00
Gajus Kuizinas 057949b3db chore: define .eslintrc 2016-11-01 14:43:19 +00:00
Gajus Kuizinas 9579637f8e chore: enable tests for node.js 5, 6 and 7 2016-11-01 14:40:09 +00:00
Gajus Kuizinas 0fa96772a8 chore: define .editorconfig 2016-11-01 14:39:30 +00:00
Gajus Kuizinas 99fd807dfb 0.1.3 2016-04-10 18:03:22 +01:00
Gajus Kuizinas 67be5ec70c Updated dependencies. 2016-04-10 18:03:16 +01:00
Gajus Kuizinas a8a5332d5c Code style preferences. 2016-03-19 13:01:04 +02:00
Gajus Kuizinas 329533a130 Use type assertions for tests. 2016-03-19 12:56:31 +02:00
Gajus Kuizinas c5f0452f10 Updated dependencies. 2016-03-19 12:54:13 +02:00
Gajus Kuizinas 00c8312dc1 0.1.2 2016-01-29 21:40:21 +00:00
Gajus Kuizinas 36ea8228ee Name can include an underscore character. 2016-01-29 21:40:16 +00:00
Gajus Kuizinas f41753b978 Added example to the docs. 2016-01-29 13:22:39 +00:00
Gajus Kuizinas a23c3ad866 0.1.1 2016-01-29 13:15:56 +00:00
Gajus Kuizinas dc80afa816 Corrected dependencies. 2016-01-29 13:15:50 +00:00
91 changed files with 643 additions and 594 deletions
+8
View File
@@ -0,0 +1,8 @@
{
"plugins": [
"transform-es2015-modules-commonjs",
"transform-export-extensions",
"transform-es2015-destructuring",
"transform-es2015-parameters"
]
}
+7
View File
@@ -0,0 +1,7 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
+1
View File
@@ -0,0 +1 @@
./test/fixtures
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "canonical"
}
+5 -2
View File
@@ -1,9 +1,12 @@
node_modules
coverage coverage
dist dist
node_modules
*.log *.log
.* .*
!.babelrc
!.editorconfig
!.eslintignore
!.eslintrc
!.gitignore !.gitignore
!.npmignore !.npmignore
!.babelrc
!.travis.yml !.travis.yml
+2 -2
View File
@@ -1,6 +1,6 @@
coverage
fixtures fixtures
src src
tests test
coverage
.* .*
*.log *.log
+7 -3
View File
@@ -1,7 +1,11 @@
language: node_js language: node_js
node_js: node_js:
- '5.0' - node
- '4.0' - 7
- 6
- 5
after_success:
- semantic-release pre && npm publish && semantic-release post
notifications: notifications:
email: false email: false
sudo: false sudo: false
+82 -17
View File
@@ -6,6 +6,72 @@
`create-index` program creates (and maintains) ES6 `./index.js` file in target directories that imports and exports sibling files and directories. `create-index` program creates (and maintains) ES6 `./index.js` file in target directories that imports and exports sibling files and directories.
## Example
```sh
> tree ./
./
├── bar.js
└── foo.js
0 directories, 2 files
> create-index ./
[13:17:34] Target directories [ './' ]
[13:17:34] Update index: false
[13:17:34] ./index.js [created index]
[13:17:34] Done
> tree
.
├── bar.js
├── foo.js
└── index.js
0 directories, 3 files
```
This created `index.js` with:
```js
// @create-index
export bar from './bar.js';
export foo from './foo.js';
```
Lets create a new file and re-run `create-index`:
```js
> touch baz.js
> tree ./
./
├── bar.js
├── baz.js
├── foo.js
└── index.js
0 directories, 4 files
> create-index ./
[13:21:55] Target directories [ './' ]
[13:21:55] Update index: false
[13:21:55] ./index.js [updated index]
[13:21:55] Done
```
This have updated `index.js` file:
```js
// @create-index
export bar from './bar.js';
export baz from './baz.js';
export foo from './foo.js';
```
## Usage ## Usage
### Using CLI Program ### Using CLI Program
@@ -16,20 +82,19 @@ npm install create-index
create-index --help create-index --help
Options: Options:
--update-index Recursively iterates target directories looking for "index.js" --update, -u Recursively iterates target directories looking for "index.js"
files that start with "'create index';\n" (create-index index files that start with "// @create-index\n" (create-index index
file). Updates found index files. Does not create new index file). Updates found index files. Does not create new index
files. [boolean] [default: false] files. [boolean] [default: false]
--banner Add a custom banner at the top of the index file [string]
Examples: Examples:
create-index ./src ./src/utilities Creates or updates an existing create-index ./src ./src/utilities Creates or updates an existing
create-index index file in the create-index index file in the target
target (./src, ./src/utilities) (./src, ./src/utilities) directories.
directories. create-index --update ./src ./tests Finds all create-index index files in the
create-index --update-index ./src Finds all create-index index files target directories and descending
./tests in the target directories and directories. Updates found index files.
descending directories. Updates
found index files.
``` ```
### Using `create-index` Programmatically ### Using `create-index` Programmatically
@@ -88,10 +153,10 @@ Note that the `writeIndex` function is synchronous.
If there is no `./index.js`, it will create a new file, e.g. If there is no `./index.js`, it will create a new file, e.g.
```js ```js
'create index'; // @create-index
``` ```
Created index file must start with `'create index';\n\n`. This is used to make sure that `create-index` does not accidentally overwrite your local files. Created index file must start with `// @create-index\n\n`. This is used to make sure that `create-index` does not accidentally overwrite your local files.
If there are sibling files, index file will `import` them and `export`, e.g. If there are sibling files, index file will `import` them and `export`, e.g.
@@ -108,7 +173,7 @@ drwxr-xr-x 2 gajus staff 68B 6 Jan 15:29 foo
Given the above directory contents, `./index.js` will be: Given the above directory contents, `./index.js` will be:
```js ```js
'create index'; // @create-index
import bar from './bar'; import bar from './bar';
import foo from './foo.js'; import foo from './foo.js';
@@ -123,6 +188,6 @@ When file has the same name as a sibling directory, file `import` takes preceden
Directories that do not have `./index.js` in themselves will be excluded. Directories that do not have `./index.js` in themselves will be excluded.
When run again, `create-index` will update existing `./index.js` if it starts with `'create index';\n\n`. When run again, `create-index` will update existing `./index.js` if it starts with `// @create-index\n\n`.
If `create-index` is executed against a directory that contains `./index.js`, which does not start with `'create index';\n\n`, an error will be thrown. If `create-index` is executed against a directory that contains `./index.js`, which does not start with `// @create-index\n\n`, an error will be thrown.
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
// 'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
// 'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
@@ -1 +0,0 @@
'create index';
-1
View File
@@ -1 +0,0 @@
'create index';
-1
View File
@@ -1 +0,0 @@
'create index';
+41 -32
View File
@@ -1,44 +1,53 @@
{ {
"name": "create-index", "author": {
"description": "Creates ES6 ./index.js file in target directories that imports and exports all sibling files and directories.", "email": "gajus@gajus.com",
"version": "0.1.0", "name": "Gajus Kuizinas",
"main": "./dist/index.js", "url": "http://gajus.com"
},
"bin": "./dist/bin/create-index.js", "bin": "./dist/bin/create-index.js",
"repository": { "dependencies": {
"type": "git", "chalk": "^1.1.3",
"url": "https://github.com/gajus/create-index" "glob": "^7.1.1",
"lodash": "^4.16.6",
"moment": "^2.15.2",
"yargs": "^6.3.0"
},
"description": "Creates ES6 ./index.js file in target directories that imports and exports all sibling files and directories.",
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-plugin-transform-es2015-destructuring": "^6.18.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.18.0",
"babel-plugin-transform-es2015-parameters": "^6.18.0",
"babel-plugin-transform-export-extensions": "^6.8.0",
"babel-register": "^6.18.0",
"chai": "^3.5.0",
"eslint": "^3.9.1",
"eslint-config-canonical": "^4.0.0",
"husky": "^0.11.9",
"mocha": "^3.1.2",
"semantic-release": "^6.3.2"
},
"engines": {
"node": ">=5"
}, },
"keywords": [ "keywords": [
"index", "index",
"import", "import",
"export" "export"
], ],
"author": {
"name": "Gajus Kuizinas",
"email": "gajus@gajus.com",
"url": "http://gajus.com"
},
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"main": "./dist/index.js",
"name": "create-index",
"repository": {
"type": "git",
"url": "https://github.com/gajus/create-index"
},
"scripts": { "scripts": {
"pragmatist": "node ./node_modules/.bin/pragmatist --es5", "build": "NODE_ENV=production babel --source-maps --copy-files ./src --out-dir ./dist",
"lint": "npm run pragmatist lint", "create-index": "node ./dist/bin/create-index ./src/utilities",
"test": "npm run pragmatist test", "lint": "NODE_ENV=development eslint ./src ./tests",
"build": "npm run pragmatist build", "precommit": "npm run test",
"watch": "npm run pragmatist watch", "test": "npm run build && npm run lint && NODE_ENV=development mocha --compilers js:babel-register"
"watch-lint": "npm run pragmatist watch-lint",
"watch-test": "npm run pragmatist watch-test",
"watch-build": "npm run pragmatist watch-build",
"create-index": "node ./dist/bin/create-index ./src/utilities"
}, },
"devDependencies": { "version": "1.0.0"
"chai": "^3.5.0",
"chalk": "^1.1.1",
"moment": "^2.11.1",
"pragmatist": "^3.0.3"
},
"dependencies": {
"glob": "^6.0.4",
"lodash": "^4.0.1",
"yargs": "^4.0.0-alpha1"
}
} }
+22 -16
View File
@@ -3,23 +3,29 @@
import yargs from 'yargs'; import yargs from 'yargs';
import { import {
writeIndexCli writeIndexCli
} from './../utilities'; } from '../utilities';
let argv; const argv = yargs
.demand(1)
argv = yargs .options({
.demand(1) update: {
.options({ alias: 'u',
'update-index': { default: false,
default: false, description: 'Recursively iterates target directories looking for "index.js" files that start with "// @create-index\\n" (create-index index file). Updates found index files. Does not create new index files.',
description: 'Recursively iterates target directories looking for "index.js" files that start with "\'create index\';\\n" (create-index index file). Updates found index files. Does not create new index files.', type: 'boolean'
type: 'boolean' }
} })
}) .options({
.example('create-index ./src ./src/utilities', 'Creates or updates an existing create-index index file in the target (./src, ./src/utilities) directories.') banner: {
.example('create-index --update-index ./src ./tests', 'Finds all create-index index files in the target directories and descending directories. Updates found index files.') description: 'Add a custom banner at the top of the index file',
.argv; type: 'string'
}
})
.example('create-index ./src ./src/utilities', 'Creates or updates an existing create-index index file in the target (./src, ./src/utilities) directories.')
.example('create-index --update ./src ./tests', 'Finds all create-index index files in the target directories and descending directories. Updates found index files.')
.argv;
writeIndexCli(argv._, { writeIndexCli(argv._, {
updateIndex: argv.updateIndex banner: argv.banner,
updateIndex: argv.update
}); });
+2 -2
View File
@@ -1,4 +1,4 @@
export { export {
findIndexFiles, findIndexFiles,
writeIndex writeIndex
} from './utilities'; } from './utilities';
+36 -30
View File
@@ -1,43 +1,49 @@
import _ from 'lodash'; import _ from 'lodash';
let buildExportBlock, const safeVariableName = (fileName) => {
safeVariableName; const indexOfDot = fileName.indexOf('.');
safeVariableName = (fileName) => { if (indexOfDot === -1) {
let indexOfDot; return fileName;
} else {
indexOfDot = fileName.indexOf('.'); return fileName.slice(0, indexOfDot);
}
if (indexOfDot === -1) {
return fileName;
} else {
return fileName.slice(0, indexOfDot);
}
}; };
buildExportBlock = (files) => { const buildExportBlock = (files) => {
let importBlock; let importBlock;
importBlock = _.map(files, (fileName) => { importBlock = _.map(files, (fileName) => {
return 'export ' + safeVariableName(fileName) + ' from \'./' + fileName + '\';'; return 'export ' + safeVariableName(fileName) + ' from \'./' + fileName + '\';';
});
importBlock = importBlock.join('\n');
return importBlock;
};
export default (filePaths, options = {}) => {
let code;
code = '';
if (options.banner) {
const banners = _.isArray(options.banner) ? options.banner : [options.banner];
banners.forEach((banner) => {
code += banner + '\n';
}); });
importBlock = importBlock.join('\n'); code += '\n';
}
return importBlock; code += '// @create-index\n\n';
};
export default (filePaths) => { if (filePaths.length) {
let code, const sortedFilePaths = filePaths.sort();
sortedFilePaths;
code = '\'create index\';\n\n'; code += buildExportBlock(sortedFilePaths) + '\n\n';
}
if (filePaths.length) { return code;
sortedFilePaths = filePaths.sort();
code += buildExportBlock(sortedFilePaths) + '\n\n';
}
return code;
}; };
+15 -15
View File
@@ -1,28 +1,28 @@
import path from 'path';
import _ from 'lodash'; import _ from 'lodash';
import glob from 'glob'; import glob from 'glob';
import path from 'path';
import validateTargetDirectory from './validateTargetDirectory'; import validateTargetDirectory from './validateTargetDirectory';
export default (directoryPath) => { export default (directoryPath) => {
let targetDirectories; let targetDirectories;
targetDirectories = glob.sync(path.join(directoryPath, './**/index.js')); targetDirectories = glob.sync(path.join(directoryPath, './**/index.js'));
targetDirectories = _.filter(targetDirectories, (targetDirectoryPath) => { targetDirectories = _.filter(targetDirectories, (targetDirectoryPath) => {
try { try {
validateTargetDirectory(path.dirname(targetDirectoryPath)); validateTargetDirectory(path.dirname(targetDirectoryPath));
return true; return true;
/* eslint-disable no-empty */
} catch (error) {
} // eslint-disable-next-line no-empty
/* eslint-enable no-empty */ } catch (error) {
return false; }
});
targetDirectories = _.map(targetDirectories, path.dirname); return false;
});
return targetDirectories; targetDirectories = _.map(targetDirectories, path.dirname);
return targetDirectories;
}; };
+1 -2
View File
@@ -1,4 +1,4 @@
'create index'; // @create-index
export createIndexCode from './createIndexCode.js'; export createIndexCode from './createIndexCode.js';
export findIndexFiles from './findIndexFiles.js'; export findIndexFiles from './findIndexFiles.js';
@@ -8,4 +8,3 @@ export sortByDepth from './sortByDepth.js';
export validateTargetDirectory from './validateTargetDirectory.js'; export validateTargetDirectory from './validateTargetDirectory.js';
export writeIndex from './writeIndex.js'; export writeIndex from './writeIndex.js';
export writeIndexCli from './writeIndexCli.js'; export writeIndexCli from './writeIndexCli.js';
+2 -1
View File
@@ -3,6 +3,7 @@ import moment from 'moment';
export default (...append) => { export default (...append) => {
/* eslint-disable no-console */ /* eslint-disable no-console */
console.log(chalk.dim('[' + moment().format('HH:mm:ss') + ']'), ...append); console.log(chalk.dim('[' + moment().format('HH:mm:ss') + ']'), ...append);
/* eslint-enable no-console */ /* eslint-enable no-console */
}; };
+49 -65
View File
@@ -1,97 +1,81 @@
import fs from 'fs'; import fs from 'fs';
import _ from 'lodash';
import path from 'path'; import path from 'path';
import _ from 'lodash';
import validateTargetDirectory from './validateTargetDirectory'; import validateTargetDirectory from './validateTargetDirectory';
let hasIndex, const hasIndex = (directoryPath) => {
hasMultipleExtensions, const indexPath = path.resolve(directoryPath, 'index.js');
hasNoExtension,
isSafeName,
removeDuplicates;
hasIndex = (directoryPath) => { try {
let indexPath; fs.statSync(indexPath);
indexPath = path.resolve(directoryPath, 'index.js'); return true;
} catch (error) {
try { return false;
fs.statSync(indexPath); }
return true;
} catch (error) {
return false;
}
}; };
hasNoExtension = (fileName) => { const hasNoExtension = (fileName) => {
let matches; const matches = fileName.match(/\./g);
matches = fileName.match(/\./g); return !matches;
return !matches;
}; };
hasMultipleExtensions = (fileName) => { const hasMultipleExtensions = (fileName) => {
let matches; const matches = fileName.match(/\./g);
matches = fileName.match(/\./g); return matches && matches.length > 1;
return matches && matches.length > 1;
}; };
isSafeName = (fileName) => { const isSafeName = (fileName) => {
return /^[a-z][a-z0-9\.]+$/i.test(fileName); return /^[a-z][a-z0-9._]+$/i.test(fileName);
}; };
removeDuplicates = (files) => { const removeDuplicates = (files) => {
return _.filter(files, (fileName) => { return _.filter(files, (fileName) => {
return !_.includes(files, fileName + '.js'); return !_.includes(files, fileName + '.js');
}); });
}; };
export default (directoryPath) => { export default (directoryPath) => {
let children; let children;
validateTargetDirectory(directoryPath); validateTargetDirectory(directoryPath);
children = fs.readdirSync(directoryPath); children = fs.readdirSync(directoryPath);
children = _.filter(children, (fileName) => { children = _.filter(children, (fileName) => {
let absolutePath, const absolutePath = path.resolve(directoryPath, fileName);
isDirectory; const isDirectory = fs.statSync(absolutePath).isDirectory();
absolutePath = path.resolve(directoryPath, fileName); if (!isSafeName(fileName)) {
return false;
}
isDirectory = fs.statSync(absolutePath).isDirectory(); if (hasNoExtension(fileName) && !isDirectory) {
return false;
}
if (!isSafeName(fileName)) { if (hasMultipleExtensions(fileName)) {
return false; return false;
} }
if (hasNoExtension(fileName) && !isDirectory) { if (_.startsWith(fileName, 'index.js')) {
return false; return false;
} }
if (hasMultipleExtensions(fileName)) { if (!isDirectory && !_.endsWith(fileName, '.js')) {
return false; return false;
} }
if (_.startsWith(fileName, 'index.js')) { if (isDirectory && !hasIndex(absolutePath)) {
return false; return false;
} }
if (!isDirectory && !_.endsWith(fileName, '.js')) { return true;
return false; });
}
if (isDirectory && !hasIndex(absolutePath)) { children = removeDuplicates(children);
return false;
}
return true; return children.sort();
});
children = removeDuplicates(children);
return children.sort();
}; };
+3 -3
View File
@@ -1,7 +1,7 @@
import _ from 'lodash'; import _ from 'lodash';
export default (paths) => { export default (paths) => {
return _.sortBy(paths, (path) => { return _.sortBy(paths, (path) => {
return -path.split('/').length; return -path.split('/').length;
}); });
}; };
+23 -25
View File
@@ -1,35 +1,33 @@
import _ from 'lodash';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import _ from 'lodash';
export default (targetDirectory) => { export default (targetDirectory) => {
let indexFile, let stats;
indexFilePath,
stats;
try { try {
stats = fs.statSync(targetDirectory); stats = fs.statSync(targetDirectory);
} catch (error) { } catch (error) {
throw new Error('Directory "' + targetDirectory + '" does not exist.'); throw new Error('Directory "' + targetDirectory + '" does not exist.');
} }
if (!stats.isDirectory()) { if (!stats.isDirectory()) {
throw new Error('"' + targetDirectory + '" is not a directory.'); throw new Error('"' + targetDirectory + '" is not a directory.');
} }
indexFilePath = path.resolve(targetDirectory, './index.js'); const indexFilePath = path.resolve(targetDirectory, './index.js');
try {
fs.statSync(indexFilePath);
} catch (error) {
return true;
}
indexFile = fs.readFileSync(indexFilePath, 'utf8');
if (!_.startsWith(indexFile, '\'create index\';\n')) {
throw new Error('"' + indexFilePath + '" unsafe index.');
}
try {
fs.statSync(indexFilePath);
} catch (error) {
return true; return true;
}
const indexFile = fs.readFileSync(indexFilePath, 'utf8');
if (!_.startsWith(indexFile, '// @create-index\n')) {
throw new Error('"' + indexFilePath + '" unsafe index.');
}
return true;
}; };
+12 -20
View File
@@ -1,31 +1,23 @@
import _ from 'lodash';
import createIndexCode from './createIndexCode';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import _ from 'lodash';
import createIndexCode from './createIndexCode';
import validateTargetDirectory from './validateTargetDirectory'; import validateTargetDirectory from './validateTargetDirectory';
import readDirectory from './readDirectory'; import readDirectory from './readDirectory';
import sortByDepth from './sortByDepth'; import sortByDepth from './sortByDepth';
export default (directoryPaths) => { export default (directoryPaths) => {
let sortedDirectoryPaths; const sortedDirectoryPaths = sortByDepth(directoryPaths);
sortedDirectoryPaths = sortByDepth(directoryPaths); _.forEach(sortedDirectoryPaths, (directoryPath) => {
validateTargetDirectory(directoryPath);
});
_.forEach(sortedDirectoryPaths, (directoryPath) => { _.forEach(sortedDirectoryPaths, (directoryPath) => {
validateTargetDirectory(directoryPath); const siblings = readDirectory(directoryPath);
}); const indexCode = createIndexCode(siblings);
const indexFilePath = path.resolve(directoryPath, 'index.js');
_.forEach(sortedDirectoryPaths, (directoryPath) => { fs.writeFileSync(indexFilePath, indexCode);
let indexCode, });
indexFilePath,
siblings;
siblings = readDirectory(directoryPath);
indexCode = createIndexCode(siblings);
indexFilePath = path.resolve(directoryPath, 'index.js');
fs.writeFileSync(indexFilePath, indexCode);
});
}; };
+46 -45
View File
@@ -1,65 +1,66 @@
import _ from 'lodash';
import createIndexCode from './createIndexCode';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import _ from 'lodash';
import chalk from 'chalk';
import createIndexCode from './createIndexCode';
import validateTargetDirectory from './validateTargetDirectory'; import validateTargetDirectory from './validateTargetDirectory';
import readDirectory from './readDirectory'; import readDirectory from './readDirectory';
import sortByDepth from './sortByDepth'; import sortByDepth from './sortByDepth';
import log from './log'; import log from './log';
import findIndexFiles from './findIndexFiles'; import findIndexFiles from './findIndexFiles';
import chalk from 'chalk';
export default (directoryPaths, options = {}) => { export default (directoryPaths, options = {}) => {
let sortedDirectoryPaths; let sortedDirectoryPaths;
sortedDirectoryPaths = sortByDepth(directoryPaths); sortedDirectoryPaths = sortByDepth(directoryPaths);
log('Target directories', sortedDirectoryPaths); log('Target directories', sortedDirectoryPaths);
log('Update index:', options.updateIndex ? chalk.green('true') : chalk.red('false')); log('Update index:', options.updateIndex ? chalk.green('true') : chalk.red('false'));
if (options.updateIndex) { if (options.updateIndex) {
sortedDirectoryPaths = _.map(sortedDirectoryPaths, findIndexFiles); sortedDirectoryPaths = _.map(sortedDirectoryPaths, findIndexFiles);
sortedDirectoryPaths = _.flatten(sortedDirectoryPaths); sortedDirectoryPaths = _.flatten(sortedDirectoryPaths);
sortedDirectoryPaths = _.uniq(sortedDirectoryPaths); sortedDirectoryPaths = _.uniq(sortedDirectoryPaths);
sortedDirectoryPaths = sortByDepth(sortedDirectoryPaths); sortedDirectoryPaths = sortByDepth(sortedDirectoryPaths);
log('Found index file in:', sortedDirectoryPaths);
}
_.forEach(sortedDirectoryPaths, (directoryPath) => {
validateTargetDirectory(directoryPath);
});
_.forEach(sortedDirectoryPaths, (directoryPath) => {
let existingIndexCode;
const siblings = readDirectory(directoryPath);
const indexCode = createIndexCode(siblings, {
banner: options.banner
});
const indexFilePath = path.resolve(directoryPath, 'index.js');
try {
existingIndexCode = fs.readFileSync(indexFilePath, 'utf8');
/* eslint-disable no-empty */
} catch (error) {
log('Found index file in:', sortedDirectoryPaths);
} }
_.forEach(sortedDirectoryPaths, (directoryPath) => {
validateTargetDirectory(directoryPath);
});
_.forEach(sortedDirectoryPaths, (directoryPath) => {
let existingIndexCode,
indexCode,
indexFilePath,
siblings;
siblings = readDirectory(directoryPath);
indexCode = createIndexCode(siblings);
indexFilePath = path.resolve(directoryPath, 'index.js');
try {
existingIndexCode = fs.readFileSync(indexFilePath, 'utf8');
/* eslint-disable no-empty */
} catch (error) {
}
/* eslint-enable no-empty */ /* eslint-enable no-empty */
fs.writeFileSync(indexFilePath, indexCode); fs.writeFileSync(indexFilePath, indexCode);
if (existingIndexCode && existingIndexCode === indexCode) { if (existingIndexCode && existingIndexCode === indexCode) {
log(indexFilePath, chalk.yellow('[index have not changed]')); log(indexFilePath, chalk.yellow('[index have not changed]'));
} else if (existingIndexCode && existingIndexCode !== indexCode) { } else if (existingIndexCode && existingIndexCode !== indexCode) {
log(indexFilePath, chalk.green('[updated index]')); log(indexFilePath, chalk.green('[updated index]'));
} else { } else {
log(indexFilePath, chalk.green('[created index]')); log(indexFilePath, chalk.green('[created index]'));
} }
}); });
log('Done'); log('Done');
}; };
+1 -1
View File
@@ -1,5 +1,5 @@
import _ from 'lodash'; import _ from 'lodash';
export default (code) => { export default (code) => {
return _.trim(code) + '\n\n'; return _.trim(code) + '\n\n';
}; };
+59
View File
@@ -0,0 +1,59 @@
/* eslint-disable no-restricted-syntax */
import {
expect
} from 'chai';
import createIndexCode from '../src/utilities/createIndexCode';
import codeExample from './codeExample';
describe('createIndexCode()', () => {
it('describes no children', () => {
const indexCode = createIndexCode([]);
expect(indexCode).to.equal(codeExample(`
// @create-index
`));
});
it('describes a single child', () => {
const indexCode = createIndexCode(['foo']);
expect(indexCode).to.equal(codeExample(`
// @create-index
export foo from './foo';
`));
});
it('describes multiple children', () => {
const indexCode = createIndexCode(['bar', 'foo']);
expect(indexCode).to.equal(codeExample(`
// @create-index
export bar from './bar';
export foo from './foo';
`));
});
context('file with extension', () => {
it('removes the extension from the export statement', () => {
const indexCode = createIndexCode(['foo.js']);
expect(indexCode).to.equal(codeExample(`
// @create-index
export foo from './foo.js';
`));
});
});
context('multiple, unsorted', () => {
it('sorts the files', () => {
const indexCode = createIndexCode(['foo', 'bar']);
expect(indexCode).to.equal(codeExample(`
// @create-index
export bar from './bar';
export foo from './foo';
`));
});
});
});
+19
View File
@@ -0,0 +1,19 @@
import path from 'path';
import {
expect
} from 'chai';
import glob from 'glob';
import findIndexFiles from '../src/utilities/findIndexFiles';
const fixturesPath = path.resolve(__dirname, '../../fixtures/find-index-files');
describe('findIndexFiles()', () => {
it('finds only the directories that have an existing valid index file', () => {
let names;
names = findIndexFiles(path.resolve(fixturesPath));
names = names.sort();
expect(names).to.deep.equal(glob.sync(path.resolve(fixturesPath, '**/find-*')));
});
});
@@ -0,0 +1 @@
// @create-index
+1
View File
@@ -0,0 +1 @@
// create-index
+1
View File
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// create-index
+1
View File
@@ -0,0 +1 @@
// @create-index
+1
View File
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
+1
View File
@@ -0,0 +1 @@
// @create-index
@@ -0,0 +1 @@
// @create-index
+1
View File
@@ -0,0 +1 @@
// @create-index
+1
View File
@@ -0,0 +1 @@
// @create-index
@@ -1,4 +1,4 @@
'create index'; // @create-index
export bar from './bar'; export bar from './bar';
export foo from './foo.js'; export foo from './foo.js';
+73
View File
@@ -0,0 +1,73 @@
import path from 'path';
import {
expect
} from 'chai';
import readDirectory from '../src/utilities/readDirectory';
const fixturesPath = path.resolve(__dirname, 'fixtures/read-directory');
describe('readDirectory()', () => {
context('target directory contains child directories', () => {
it('gets names of the children directories', () => {
const names = readDirectory(path.resolve(fixturesPath, 'children-directories'));
expect(names).to.deep.equal(['bar', 'foo']);
});
});
context('target directory contains child directories that do not contain index', () => {
it('gets names of the children directories', () => {
const names = readDirectory(path.resolve(fixturesPath, 'children-directories-without-index'));
expect(names).to.deep.equal(['present.js']);
});
});
context('target directory contains child directories (unsafe name)', () => {
it('gets names of the children directories', () => {
const names = readDirectory(path.resolve(fixturesPath, 'children-directories-unsafe-name'));
expect(names).to.deep.equal(['present']);
});
});
context('target directory contains ./index.js', () => {
it('does not include ./index.js', () => {
const names = readDirectory(path.resolve(fixturesPath, 'children-index'));
expect(names).to.deep.equal(['bar', 'foo']);
});
});
context('target directory contains files', () => {
it('refers to the files (with extension)', () => {
const names = readDirectory(path.resolve(fixturesPath, 'children-files'));
expect(names).to.deep.equal(['bar.js', 'foo.js']);
});
});
context('target directory contains dot files', () => {
it('ignores files', () => {
const names = readDirectory(path.resolve(fixturesPath, 'children-dot-files'));
expect(names).to.deep.equal(['present.js']);
});
});
context('target directory contains files with no extension', () => {
it('ignores files', () => {
const names = readDirectory(path.resolve(fixturesPath, 'children-files-no-extension'));
expect(names).to.deep.equal(['present.js']);
});
});
context('target directory contains files with multiple extensions', () => {
it('ignores files', () => {
const names = readDirectory(path.resolve(fixturesPath, 'children-files-multiple-extensions'));
expect(names).to.deep.equal(['present.js']);
});
});
context('target directory contains directories and files with the same name', () => {
it('prefers file', () => {
const names = readDirectory(path.resolve(fixturesPath, 'children-directories-and-files'));
expect(names).to.deep.equal(['foo.js', 'present.js']);
});
});
});
+19
View File
@@ -0,0 +1,19 @@
import {
expect
} from 'chai';
import sortByDepth from './../src/utilities/sortByDepth';
describe('sortByDepth()', () => {
it('sorts from deepest to the most shallow', () => {
const paths = [
'/b',
'/a',
'/a/b/c',
'/a/b'
];
const sortedPaths = sortByDepth(paths);
expect(sortedPaths).to.deep.equal(['/a/b/c', '/a/b', '/b', '/a']);
});
});
+47
View File
@@ -0,0 +1,47 @@
/* eslint-disable max-nested-callbacks */
import path from 'path';
import {
expect
} from 'chai';
import validateTargetDirectory from '../src/utilities/validateTargetDirectory';
const fixturesPath = path.resolve(__dirname, 'fixtures/validate-target-directory');
describe('validateTargetDirectory()', () => {
describe('directory path', () => {
context('refers to a directory that does not exist', () => {
it('throws an error', () => {
expect(() => {
validateTargetDirectory(path.resolve(fixturesPath, 'does-not-exist'));
}).to.throw(Error, 'Directory "' + path.resolve(fixturesPath, 'does-not-exist') + '" does not exist.');
});
});
context('refers to a file', () => {
it('throws an error', () => {
expect(() => {
validateTargetDirectory(path.resolve(fixturesPath, 'not-a-directory.js'));
}).to.throw(Error, '"' + path.resolve(fixturesPath, 'not-a-directory.js') + '" is not a directory.');
});
});
});
describe('target index', () => {
context('no index', () => {
it('returns true', () => {
expect(validateTargetDirectory(path.resolve(fixturesPath, 'no-index'))).to.equal(true);
});
});
context('safe', () => {
it('returns true', () => {
expect(validateTargetDirectory(path.resolve(fixturesPath, 'safe-index'))).to.equal(true);
});
});
context('unsafe', () => {
it('throws an error', () => {
expect(() => {
validateTargetDirectory(path.resolve(fixturesPath, 'unsafe-index'));
}).to.throw(Error, '"' + path.resolve(fixturesPath, 'unsafe-index/index.js') + '" unsafe index.');
});
});
});
});
+36
View File
@@ -0,0 +1,36 @@
/* eslint-disable no-restricted-syntax */
import fs from 'fs';
import path from 'path';
import {
expect
} from 'chai';
import writeIndex from '../src/utilities/writeIndex';
import codeExample from './codeExample';
const fixturesPath = path.resolve(__dirname, 'fixtures/write-index');
describe('writeIndex()', () => {
it('creates index in target directory', () => {
const indexFilePath = path.resolve(fixturesPath, 'mixed/index.js');
try {
fs.unlinkSync(indexFilePath);
// eslint-disable-next-line no-empty
} catch (error) {
}
writeIndex([path.resolve(fixturesPath, 'mixed')]);
const indexCode = fs.readFileSync(indexFilePath, 'utf8');
expect(indexCode).to.equal(codeExample(`
// @create-index
export bar from './bar';
export foo from './foo.js';
`));
});
});
-71
View File
@@ -1,71 +0,0 @@
/* eslint-disable no-restricted-syntax */
import {
expect
} from 'chai';
import createIndexCode from './../src/utilities/createIndexCode';
import codeExample from './codeExample';
describe('createIndexCode()', () => {
it('describes no children', () => {
let indexCode;
indexCode = createIndexCode([]);
expect(indexCode).to.equal(codeExample(`
'create index';
`));
});
it('describes a single child', () => {
let indexCode;
indexCode = createIndexCode(['foo']);
expect(indexCode).to.equal(codeExample(`
'create index';
export foo from './foo';
`));
});
it('describes multiple children', () => {
let indexCode;
indexCode = createIndexCode(['bar', 'foo']);
expect(indexCode).to.equal(codeExample(`
'create index';
export bar from './bar';
export foo from './foo';
`));
});
context('file with extension', () => {
it('removes the extension from the export statement', () => {
let indexCode;
indexCode = createIndexCode(['foo.js']);
expect(indexCode).to.equal(codeExample(`
'create index';
export foo from './foo.js';
`));
});
});
context('multiple, unsorted', () => {
it('sorts the files', () => {
let indexCode;
indexCode = createIndexCode(['foo', 'bar']);
expect(indexCode).to.equal(codeExample(`
'create index';
export bar from './bar';
export foo from './foo';
`));
});
});
});
-20
View File
@@ -1,20 +0,0 @@
import {
expect
} from 'chai';
import path from 'path';
import glob from 'glob';
import findIndexFiles from './../src/utilities/findIndexFiles';
const fixturesPath = path.resolve(__dirname, './../../fixtures/find-index-files');
describe('findIndexFiles()', () => {
it('finds only the directories that have an existing valid index file', () => {
let names;
names = findIndexFiles(path.resolve(fixturesPath));
names = names.sort();
expect(names).to.deep.equal(glob.sync(path.resolve(fixturesPath, './**/find-*')));
});
});
-92
View File
@@ -1,92 +0,0 @@
import {
expect
} from 'chai';
import path from 'path';
import readDirectory from './../src/utilities/readDirectory';
const fixturesPath = path.resolve(__dirname, './../../fixtures/read-directory');
describe('readDirectory()', () => {
context('target directory contains child directories', () => {
it('gets names of the children directories', () => {
let names;
names = readDirectory(path.resolve(fixturesPath, 'children-directories'));
expect(names).to.deep.equal(['bar', 'foo']);
});
});
context('target directory contains child directories that do not contain index', () => {
it('gets names of the children directories', () => {
let names;
names = readDirectory(path.resolve(fixturesPath, 'children-directories-without-index'));
expect(names).to.deep.equal(['present.js']);
});
});
context('target directory contains child directories (unsafe name)', () => {
it('gets names of the children directories', () => {
let names;
names = readDirectory(path.resolve(fixturesPath, 'children-directories-unsafe-name'));
expect(names).to.deep.equal(['present']);
});
});
context('target directory contains ./index.js', () => {
it('does not include ./index.js', () => {
let names;
names = readDirectory(path.resolve(fixturesPath, 'children-index'));
expect(names).to.deep.equal(['bar', 'foo']);
});
});
context('target directory contains files', () => {
it('refers to the files (with extension)', () => {
let names;
names = readDirectory(path.resolve(fixturesPath, 'children-files'));
expect(names).to.deep.equal(['bar.js', 'foo.js']);
});
});
context('target directory contains dot files', () => {
it('ignores files', () => {
let names;
names = readDirectory(path.resolve(fixturesPath, 'children-dot-files'));
expect(names).to.deep.equal(['present.js']);
});
});
context('target directory contains files with no extension', () => {
it('ignores files', () => {
let names;
names = readDirectory(path.resolve(fixturesPath, 'children-files-no-extension'));
expect(names).to.deep.equal(['present.js']);
});
});
context('target directory contains files with multiple extensions', () => {
it('ignores files', () => {
let names;
names = readDirectory(path.resolve(fixturesPath, 'children-files-multiple-extensions'));
expect(names).to.deep.equal(['present.js']);
});
});
context('target directory contains directories and files with the same name', () => {
it('prefers file', () => {
let names;
names = readDirectory(path.resolve(fixturesPath, 'children-directories-and-files'));
expect(names).to.deep.equal(['foo.js', 'present.js']);
});
});
});
-22
View File
@@ -1,22 +0,0 @@
import {
expect
} from 'chai';
import sortByDepth from './../src/utilities/sortByDepth';
describe('sortByDepth()', () => {
it('sorts from deepest to the most shallow', () => {
let paths,
sortedPaths;
paths = [
'/b',
'/a',
'/a/b/c',
'/a/b'
];
sortedPaths = sortByDepth(paths);
expect(sortedPaths).to.deep.equal(['/a/b/c', '/a/b', '/b', '/a']);
});
});
-47
View File
@@ -1,47 +0,0 @@
/* eslint-disable max-nested-callbacks */
import {
expect
} from 'chai';
import path from 'path';
import validateTargetDirectory from './../src/utilities/validateTargetDirectory';
const fixturesPath = path.resolve(__dirname, './../../fixtures/validate-target-directory');
describe('validateTargetDirectory()', () => {
describe('directory path', () => {
context('refers to a directory that does not exist', () => {
it('throws an error', () => {
expect(() => {
validateTargetDirectory(path.resolve(fixturesPath, 'does-not-exist'));
}).to.throw(Error, 'Directory "' + path.resolve(fixturesPath, 'does-not-exist') + '" does not exist.');
});
});
context('refers to a file', () => {
it('throws an error', () => {
expect(() => {
validateTargetDirectory(path.resolve(fixturesPath, 'not-a-directory.js'));
}).to.throw(Error, '"' + path.resolve(fixturesPath, 'not-a-directory.js') + '" is not a directory.');
});
});
});
describe('target index', () => {
context('no index', () => {
it('returns true', () => {
expect(validateTargetDirectory(path.resolve(fixturesPath, 'no-index'))).to.equal(true);
});
});
context('safe', () => {
it('returns true', () => {
expect(validateTargetDirectory(path.resolve(fixturesPath, 'safe-index'))).to.equal(true);
});
});
context('unsafe', () => {
it('throws an error', () => {
expect(() => {
validateTargetDirectory(path.resolve(fixturesPath, 'unsafe-index'));
}).to.throw(Error, '"' + path.resolve(fixturesPath, 'unsafe-index/index.js') + '" unsafe index.');
});
});
});
});
-39
View File
@@ -1,39 +0,0 @@
/* eslint-disable no-restricted-syntax */
import {
expect
} from 'chai';
import fs from 'fs';
import path from 'path';
import codeExample from './codeExample';
import writeIndex from './../src/utilities/writeIndex';
const fixturesPath = path.resolve(__dirname, './../../fixtures/write-index');
describe('writeIndex()', () => {
it('creates index in target directory', () => {
let indexCode,
indexFilePath;
indexFilePath = path.resolve(fixturesPath, './mixed/index.js');
try {
fs.unlinkSync(indexFilePath);
/* eslint-disable no-empty */
} catch (error) {
}
/* eslint-enable no-empty */
writeIndex([path.resolve(fixturesPath, './mixed')]);
indexCode = fs.readFileSync(indexFilePath, 'utf8');
expect(indexCode).to.equal(codeExample(`
'create index';
export bar from './bar';
export foo from './foo.js';
`));
});
});