├── rollup.config.js ├── renovate.json ├── src ├── index.js ├── base-schema.js ├── files-and-ignores-schema.js └── config-array.js ├── .eslintrc.js ├── .github └── workflows │ ├── nodejs-test.yml │ └── release-please.yml ├── nitpik.config.js ├── .vscode └── launch.json ├── .gitignore ├── package.json ├── LICENSE ├── CHANGELOG.md ├── README.md └── tests └── config-array.test.js /rollup.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | input: 'src/index.js', 3 | output: { 4 | file: 'api.js', 5 | format: 'cjs' 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:base" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview Package API 3 | * @author Nicholas C. Zakas 4 | */ 5 | 6 | export { ConfigArray, ConfigArraySymbol } from './config-array.js'; 7 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | /*global module:true*/ 2 | module.exports = { 3 | 'env': { 4 | 'es6': true, 5 | }, 6 | 'extends': 'eslint:recommended', 7 | 'parserOptions': { 8 | 'ecmaVersion': 2020, 9 | 'sourceType': 'module' 10 | }, 11 | 'rules': { 12 | 'semi': [ 13 | 'error', 14 | 'always' 15 | ], 16 | quotes: ['error', 'single'], 17 | indent: ['error', 'tab'] 18 | }, 19 | overrides: [ 20 | { 21 | files: ['tests/*.js'], 22 | env: { 23 | mocha: true, 24 | node: true 25 | } 26 | }, 27 | { 28 | files: ['*.config.js'], 29 | parserOptions: { 30 | sourceType: 'script', 31 | }, 32 | env: { 33 | node: true 34 | } 35 | } 36 | ] 37 | }; 38 | -------------------------------------------------------------------------------- /.github/workflows/nodejs-test.yml: -------------------------------------------------------------------------------- 1 | name: Node CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ${{ matrix.os }} 9 | 10 | strategy: 11 | matrix: 12 | os: [windows-latest, macOS-latest, ubuntu-latest] 13 | node: [10.x, 12.x, 14.x] 14 | 15 | steps: 16 | - uses: actions/checkout@v4 17 | - name: Use Node.js ${{ matrix.node-version }} 18 | uses: actions/setup-node@v4 19 | with: 20 | node-version: ${{ matrix.node-version }} 21 | - name: npm install, build, and test 22 | run: | 23 | npm install 24 | npm run build --if-present 25 | npm test 26 | env: 27 | CI: true 28 | -------------------------------------------------------------------------------- /nitpik.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview Nitpik configuration file 3 | * @author Nicholas C. Zakas 4 | */ 5 | 6 | //----------------------------------------------------------------------------- 7 | // Requirements 8 | //----------------------------------------------------------------------------- 9 | 10 | const { JavaScriptFormatter } = require('@nitpik/javascript'); 11 | 12 | //----------------------------------------------------------------------------- 13 | // Config 14 | //----------------------------------------------------------------------------- 15 | 16 | module.exports = { 17 | files: ['**/*.js'], 18 | formatter: new JavaScriptFormatter({ 19 | style: { 20 | quotes: 'single', 21 | indent: '\t' 22 | } 23 | }) 24 | }; 25 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Attach by Process ID", 9 | "processId": "${command:PickProcess}", 10 | "request": "attach", 11 | "skipFiles": [ 12 | "/**" 13 | ], 14 | "type": "pwa-node" 15 | }, 16 | { 17 | "type": "pwa-node", 18 | "request": "launch", 19 | "name": "Launch Program", 20 | "skipFiles": [ 21 | "/**" 22 | ], 23 | "program": "${workspaceFolder}\\api.js" 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /src/base-schema.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview ConfigSchema 3 | * @author Nicholas C. Zakas 4 | */ 5 | 6 | //------------------------------------------------------------------------------ 7 | // Helpers 8 | //------------------------------------------------------------------------------ 9 | 10 | const NOOP_STRATEGY = { 11 | required: false, 12 | merge() { 13 | return undefined; 14 | }, 15 | validate() { } 16 | }; 17 | 18 | //------------------------------------------------------------------------------ 19 | // Exports 20 | //------------------------------------------------------------------------------ 21 | 22 | /** 23 | * The base schema that every ConfigArray uses. 24 | * @type Object 25 | */ 26 | export const baseSchema = Object.freeze({ 27 | name: { 28 | required: false, 29 | merge() { 30 | return undefined; 31 | }, 32 | validate(value) { 33 | if (typeof value !== 'string') { 34 | throw new TypeError('Property must be a string.'); 35 | } 36 | } 37 | }, 38 | files: NOOP_STRATEGY, 39 | ignores: NOOP_STRATEGY 40 | }); 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | # Main file 64 | api.js 65 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@humanwhocodes/config-array", 3 | "version": "0.13.0", 4 | "description": "Glob-based configuration matching.", 5 | "author": "Nicholas C. Zakas", 6 | "main": "api.js", 7 | "files": [ 8 | "api.js", 9 | "LICENSE", 10 | "README.md" 11 | ], 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/humanwhocodes/config-array.git" 15 | }, 16 | "bugs": { 17 | "url": "https://github.com/humanwhocodes/config-array/issues" 18 | }, 19 | "homepage": "https://github.com/humanwhocodes/config-array#readme", 20 | "scripts": { 21 | "build": "rollup -c", 22 | "format": "nitpik", 23 | "lint": "eslint *.config.js src/*.js tests/*.js", 24 | "lint:fix": "eslint --fix *.config.js src/*.js tests/*.js", 25 | "prepublish": "npm run build", 26 | "test:coverage": "nyc --include src/*.js npm run test", 27 | "test": "mocha -r esm tests/ --recursive" 28 | }, 29 | "gitHooks": { 30 | "pre-commit": "lint-staged" 31 | }, 32 | "lint-staged": { 33 | "*.js": [ 34 | "eslint --fix --ignore-pattern '!.eslintrc.js'" 35 | ] 36 | }, 37 | "keywords": [ 38 | "configuration", 39 | "configarray", 40 | "config file" 41 | ], 42 | "license": "Apache-2.0", 43 | "engines": { 44 | "node": ">=10.10.0" 45 | }, 46 | "dependencies": { 47 | "@humanwhocodes/object-schema": "^2.0.3", 48 | "debug": "^4.3.1", 49 | "minimatch": "^3.0.5" 50 | }, 51 | "devDependencies": { 52 | "@nitpik/javascript": "0.4.0", 53 | "@nitpik/node": "0.0.5", 54 | "chai": "4.3.10", 55 | "eslint": "8.52.0", 56 | "esm": "3.2.25", 57 | "lint-staged": "15.0.2", 58 | "mocha": "6.2.3", 59 | "nyc": "15.1.0", 60 | "rollup": "3.28.1", 61 | "yorkie": "2.0.0" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /.github/workflows/release-please.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - main 5 | pull_request: 6 | branches: 7 | - main 8 | name: release-please 9 | jobs: 10 | release-please: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: GoogleCloudPlatform/release-please-action@v3 14 | id: release 15 | with: 16 | release-type: node 17 | package-name: config-array 18 | # The logic below handles the npm publication: 19 | - uses: actions/checkout@v4 20 | # these if statements ensure that a publication only occurs when 21 | # a new release is created: 22 | if: ${{ steps.release.outputs.release_created }} 23 | - uses: actions/setup-node@v4 24 | with: 25 | node-version: lts/* 26 | registry-url: 'https://registry.npmjs.org' 27 | if: ${{ steps.release.outputs.release_created }} 28 | - run: npm ci 29 | if: ${{ steps.release.outputs.release_created }} 30 | - run: npm publish 31 | env: 32 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 33 | if: ${{ steps.release.outputs.release_created }} 34 | 35 | # Tweets out release announcement 36 | - run: 'npx @humanwhocodes/tweet "Config Array v${{ steps.release.outputs.major }}.${{ steps.release.outputs.minor }}.${{ steps.release.outputs.patch }} has been released!\n\nhttps://github.com/humanwhocodes/config-array/releases/tag/v${{ steps.release.outputs.major }}.${{ steps.release.outputs.minor }}.${{ steps.release.outputs.patch }}"' 37 | if: ${{ steps.release.outputs.release_created }} 38 | env: 39 | TWITTER_CONSUMER_KEY: ${{ secrets.TWITTER_CONSUMER_KEY }} 40 | TWITTER_CONSUMER_SECRET: ${{ secrets.TWITTER_CONSUMER_SECRET }} 41 | TWITTER_ACCESS_TOKEN_KEY: ${{ secrets.TWITTER_ACCESS_TOKEN_KEY }} 42 | TWITTER_ACCESS_TOKEN_SECRET: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }} 43 | -------------------------------------------------------------------------------- /src/files-and-ignores-schema.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview ConfigSchema 3 | * @author Nicholas C. Zakas 4 | */ 5 | 6 | //------------------------------------------------------------------------------ 7 | // Helpers 8 | //------------------------------------------------------------------------------ 9 | 10 | /** 11 | * Asserts that a given value is an array. 12 | * @param {*} value The value to check. 13 | * @returns {void} 14 | * @throws {TypeError} When the value is not an array. 15 | */ 16 | function assertIsArray(value) { 17 | if (!Array.isArray(value)) { 18 | throw new TypeError('Expected value to be an array.'); 19 | } 20 | } 21 | 22 | /** 23 | * Asserts that a given value is an array containing only strings and functions. 24 | * @param {*} value The value to check. 25 | * @returns {void} 26 | * @throws {TypeError} When the value is not an array of strings and functions. 27 | */ 28 | function assertIsArrayOfStringsAndFunctions(value, name) { 29 | assertIsArray(value, name); 30 | 31 | if (value.some(item => typeof item !== 'string' && typeof item !== 'function')) { 32 | throw new TypeError('Expected array to only contain strings and functions.'); 33 | } 34 | } 35 | 36 | /** 37 | * Asserts that a given value is a non-empty array. 38 | * @param {*} value The value to check. 39 | * @returns {void} 40 | * @throws {TypeError} When the value is not an array or an empty array. 41 | */ 42 | function assertIsNonEmptyArray(value) { 43 | if (!Array.isArray(value) || value.length === 0) { 44 | throw new TypeError('Expected value to be a non-empty array.'); 45 | } 46 | } 47 | 48 | //------------------------------------------------------------------------------ 49 | // Exports 50 | //------------------------------------------------------------------------------ 51 | 52 | /** 53 | * The schema for `files` and `ignores` that every ConfigArray uses. 54 | * @type Object 55 | */ 56 | export const filesAndIgnoresSchema = Object.freeze({ 57 | files: { 58 | required: false, 59 | merge() { 60 | return undefined; 61 | }, 62 | validate(value) { 63 | 64 | // first check if it's an array 65 | assertIsNonEmptyArray(value); 66 | 67 | // then check each member 68 | value.forEach(item => { 69 | if (Array.isArray(item)) { 70 | assertIsArrayOfStringsAndFunctions(item); 71 | } else if (typeof item !== 'string' && typeof item !== 'function') { 72 | throw new TypeError('Items must be a string, a function, or an array of strings and functions.'); 73 | } 74 | }); 75 | 76 | } 77 | }, 78 | ignores: { 79 | required: false, 80 | merge() { 81 | return undefined; 82 | }, 83 | validate: assertIsArrayOfStringsAndFunctions 84 | } 85 | }); 86 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [0.13.0](https://github.com/humanwhocodes/config-array/compare/v0.12.3...v0.13.0) (2024-04-17) 4 | 5 | 6 | ### Bug Fixes 7 | 8 | * Throw friendly message for non-object configs ([#136](https://github.com/humanwhocodes/config-array/issues/136)) ([be918b6](https://github.com/humanwhocodes/config-array/commit/be918b6fa636a671a025354af7bbc69fa02842f7)) 9 | * Update release version for breaking change ([0b803d4](https://github.com/humanwhocodes/config-array/commit/0b803d41db6c93051f48b65325cb1b438c4b550b)) 10 | 11 | 12 | ### Miscellaneous Chores 13 | 14 | * Update release version ([5cacca6](https://github.com/humanwhocodes/config-array/commit/5cacca6e005bd27ea08e2f03692232f915d1a7bb)) 15 | 16 | ## [0.12.3](https://github.com/humanwhocodes/config-array/compare/v0.12.2...v0.12.3) (2024-04-03) 17 | 18 | 19 | ### Bug Fixes 20 | 21 | * don't match config with `ignores` and `name` only ([#133](https://github.com/humanwhocodes/config-array/issues/133)) ([3dabb4d](https://github.com/humanwhocodes/config-array/commit/3dabb4db2072a86d9b567205626ba0ed537bea2f)) 22 | 23 | ## [0.12.2](https://github.com/humanwhocodes/config-array/compare/v0.12.1...v0.12.2) (2024-04-02) 24 | 25 | 26 | ### Bug Fixes 27 | 28 | * ignore `name` field for global `ignores` ([#131](https://github.com/humanwhocodes/config-array/issues/131)) ([286f489](https://github.com/humanwhocodes/config-array/commit/286f48970f2b2c35c3fae14c5081d29ac23d11cc)) 29 | 30 | ## [0.12.1](https://github.com/humanwhocodes/config-array/compare/v0.12.0...v0.12.1) (2024-04-01) 31 | 32 | 33 | ### Bug Fixes 34 | 35 | * **deps:** Ensure unnecessary files are not packaged ([6c26fef](https://github.com/humanwhocodes/config-array/commit/6c26fef4f5367eeba48ff782e44f914b47e278bf)) 36 | 37 | ## [0.12.0](https://github.com/humanwhocodes/config-array/compare/v0.11.14...v0.12.0) (2024-04-01) 38 | 39 | 40 | ### Features 41 | 42 | * Report config name in error messages ([#128](https://github.com/humanwhocodes/config-array/issues/128)) ([58f8c9f](https://github.com/humanwhocodes/config-array/commit/58f8c9f8c06cbc6c67dfefe71b719bc6a940b7b3)) 43 | 44 | ## [0.11.14](https://github.com/humanwhocodes/config-array/compare/v0.11.13...v0.11.14) (2024-01-10) 45 | 46 | 47 | ### Bug Fixes 48 | 49 | * behavior of global `ignores` ([#126](https://github.com/humanwhocodes/config-array/issues/126)) ([9b3c72c](https://github.com/humanwhocodes/config-array/commit/9b3c72c67ff41f77ee7df549d95c4ca45b36d1ed)) 50 | * **deps:** Update object-schema ([8f0950a](https://github.com/humanwhocodes/config-array/commit/8f0950a253fd117e787e71f0c3bffe33942ce3a1)) 51 | 52 | ## [0.11.13](https://github.com/humanwhocodes/config-array/compare/v0.11.12...v0.11.13) (2023-10-20) 53 | 54 | 55 | ### Bug Fixes 56 | 57 | * **deps:** Upgrade object-schema to restore custom properties on errors ([d6d0b6a](https://github.com/humanwhocodes/config-array/commit/d6d0b6a415ef191ef9acd9169aec0827b86dcad3)) 58 | 59 | ## [0.11.12](https://github.com/humanwhocodes/config-array/compare/v0.11.11...v0.11.12) (2023-10-19) 60 | 61 | 62 | ### Bug Fixes 63 | 64 | * caching of ignored files ([#111](https://github.com/humanwhocodes/config-array/issues/111)) ([839d838](https://github.com/humanwhocodes/config-array/commit/839d838e607cf5fb69d1acd314d6bb7aa20bc042)) 65 | 66 | ## [0.11.11](https://github.com/humanwhocodes/config-array/compare/v0.11.10...v0.11.11) (2023-08-29) 67 | 68 | 69 | ### Bug Fixes 70 | 71 | * validate `files` and `ignores` elements ([#103](https://github.com/humanwhocodes/config-array/issues/103)) ([c40894f](https://github.com/humanwhocodes/config-array/commit/c40894ff86d1635c45649ac1f3c03a274e2529d9)) 72 | 73 | ## [0.11.10](https://github.com/humanwhocodes/config-array/compare/v0.11.9...v0.11.10) (2023-06-01) 74 | 75 | 76 | ### Bug Fixes 77 | 78 | * Allow directory-based ignores for files matches ([0163f31](https://github.com/humanwhocodes/config-array/commit/0163f313dbfe50d283042141dbad5958f9d5d2ad)) 79 | * Revert allow directory-based ignores for files matches ([322ad01](https://github.com/humanwhocodes/config-array/commit/322ad011b7d4761205ae7f85c8fdb58574dbf388)) 80 | 81 | ## [0.11.9](https://github.com/humanwhocodes/config-array/compare/v0.11.8...v0.11.9) (2023-05-12) 82 | 83 | 84 | ### Bug Fixes 85 | 86 | * Config with just ignores should not always be applied ([#89](https://github.com/humanwhocodes/config-array/issues/89)) ([5ed9c2c](https://github.com/humanwhocodes/config-array/commit/5ed9c2c1a13afb42cd7e9d3b1b247761cb7aa040)) 87 | 88 | ## [0.11.8](https://github.com/humanwhocodes/config-array/compare/v0.11.7...v0.11.8) (2022-12-14) 89 | 90 | 91 | ### Bug Fixes 92 | 93 | * Ensure gitignore-style directory ignores ([#74](https://github.com/humanwhocodes/config-array/issues/74)) ([8e17f4a](https://github.com/humanwhocodes/config-array/commit/8e17f4a7378cb0b417e1103d60ef397b26d2f917)) 94 | 95 | ## [0.11.7](https://github.com/humanwhocodes/config-array/compare/v0.11.6...v0.11.7) (2022-10-28) 96 | 97 | 98 | ### Bug Fixes 99 | 100 | * **deps:** Update minimatch to secure version ([3219294](https://github.com/humanwhocodes/config-array/commit/3219294bf9170c500ee9e212b59e17ef205b7c3c)) 101 | 102 | ## [0.11.6](https://github.com/humanwhocodes/config-array/compare/v0.11.5...v0.11.6) (2022-10-21) 103 | 104 | 105 | ### Bug Fixes 106 | 107 | * Only apply universal patterns if others match. ([e69c8fd](https://github.com/humanwhocodes/config-array/commit/e69c8fdbb7696b406821bc723b86b4c5304c4260)) 108 | 109 | ## [0.11.5](https://github.com/humanwhocodes/config-array/compare/v0.11.4...v0.11.5) (2022-10-17) 110 | 111 | 112 | ### Bug Fixes 113 | 114 | * Unignoring of directories should work ([e1c9dcd](https://github.com/humanwhocodes/config-array/commit/e1c9dcd05534619effe258596191ea9dc5bb37af)) 115 | 116 | ## [0.11.4](https://github.com/humanwhocodes/config-array/compare/v0.11.3...v0.11.4) (2022-10-14) 117 | 118 | 119 | ### Bug Fixes 120 | 121 | * Ensure subdirectories of ignored directories are ignored ([0df450e](https://github.com/humanwhocodes/config-array/commit/0df450eabeb595ae22fe680ce3320dc47edb1e66)) 122 | 123 | ## [0.11.3](https://github.com/humanwhocodes/config-array/compare/v0.11.2...v0.11.3) (2022-10-13) 124 | 125 | 126 | ### Bug Fixes 127 | 128 | * Ensure directories can be unignored. ([206404c](https://github.com/humanwhocodes/config-array/commit/206404c490d354a4f39ef9b4a6d0ceaec119abc5)) 129 | 130 | ## [0.11.2](https://github.com/humanwhocodes/config-array/compare/v0.11.1...v0.11.2) (2022-10-03) 131 | 132 | 133 | ### Bug Fixes 134 | 135 | * Error conditions for isDirectoryIgnored ([0bd81f5](https://github.com/humanwhocodes/config-array/commit/0bd81f53b7c217d561f70709057c7d77f17e8c6d)) 136 | * isDirectoryIgnored should match on relative path. ([3d1eaf6](https://github.com/humanwhocodes/config-array/commit/3d1eaf6389056215e27793cde9c2954c01c78df8)) 137 | * isFileIgnored should call isDirectoryIgnored ([270d359](https://github.com/humanwhocodes/config-array/commit/270d359295f376edb0c73905f62a848284d34053)) 138 | 139 | 140 | ### Performance Improvements 141 | 142 | * Cache isDirectoryIgnored calls ([c5e6720](https://github.com/humanwhocodes/config-array/commit/c5e67208618e253c08bd320efeae4b1f63641e63)) 143 | 144 | ## [0.11.1](https://github.com/humanwhocodes/config-array/compare/v0.11.0...v0.11.1) (2022-09-30) 145 | 146 | 147 | ### Bug Fixes 148 | 149 | * isDirectoryIgnored should not test negated patterns ([f6cdb68](https://github.com/humanwhocodes/config-array/commit/f6cdb688784901970fda72eb688eb1a00c44b09a)) 150 | 151 | ## [0.11.0](https://github.com/humanwhocodes/config-array/compare/v0.10.7...v0.11.0) (2022-09-30) 152 | 153 | 154 | ### Features 155 | 156 | * Add isDirectoryIgnored; deprecated isIgnored ([e6942f2](https://github.com/humanwhocodes/config-array/commit/e6942f2ce075007d39f23530593b7adb19178a52)) 157 | 158 | ## [0.10.7](https://github.com/humanwhocodes/config-array/compare/v0.10.6...v0.10.7) (2022-09-29) 159 | 160 | 161 | ### Bug Fixes 162 | 163 | * Cache negated patterns separately ([fef617b](https://github.com/humanwhocodes/config-array/commit/fef617b6999f9a4b5871d4525c82c4181bc96fb7)) 164 | 165 | ## [0.10.6](https://github.com/humanwhocodes/config-array/compare/v0.10.5...v0.10.6) (2022-09-28) 166 | 167 | 168 | ### Performance Improvements 169 | 170 | * Cache Minimatch instances ([5cf9af7](https://github.com/humanwhocodes/config-array/commit/5cf9af7ecaf227d2106be0cebd92d7f5148867e6)) 171 | 172 | ## [0.10.5](https://github.com/humanwhocodes/config-array/compare/v0.10.4...v0.10.5) (2022-09-21) 173 | 174 | 175 | ### Bug Fixes 176 | 177 | * Improve caching to improve performance ([#50](https://github.com/humanwhocodes/config-array/issues/50)) ([8a7e8ab](https://github.com/humanwhocodes/config-array/commit/8a7e8ab499bcbb10d7cbdd676197fc686966a64e)) 178 | 179 | ### [0.10.4](https://www.github.com/humanwhocodes/config-array/compare/v0.10.3...v0.10.4) (2022-07-29) 180 | 181 | 182 | ### Bug Fixes 183 | 184 | * Global ignores only when no other keys ([1f6b6ae](https://www.github.com/humanwhocodes/config-array/commit/1f6b6ae89152c1ebe118f55e7ea05c37e7c960dc)) 185 | * Re-introduce ignores fixes ([b3ec560](https://www.github.com/humanwhocodes/config-array/commit/b3ec560c485bec2f7420fd63a939448b49a073e3)) 186 | 187 | ### [0.10.3](https://www.github.com/humanwhocodes/config-array/compare/v0.10.2...v0.10.3) (2022-07-20) 188 | 189 | 190 | ### Bug Fixes 191 | 192 | * Ensure preprocess method has correct 'this' value. ([f86933a](https://www.github.com/humanwhocodes/config-array/commit/f86933a072e5a4069bab2c1ce284dedf0efa715d)) 193 | 194 | ### [0.10.2](https://www.github.com/humanwhocodes/config-array/compare/v0.10.1...v0.10.2) (2022-03-18) 195 | 196 | 197 | ### Bug Fixes 198 | 199 | * Files outside of basePath should be ignored ([fc4d7b2](https://www.github.com/humanwhocodes/config-array/commit/fc4d7b2e851959ab9ab84305f6c78c52e9cc2c3c)) 200 | 201 | ### [0.10.1](https://www.github.com/humanwhocodes/config-array/compare/v0.10.0...v0.10.1) (2022-03-03) 202 | 203 | 204 | ### Bug Fixes 205 | 206 | * Explicit matching is required against files field ([ab4e428](https://www.github.com/humanwhocodes/config-array/commit/ab4e4282ecea994ef88d273dc47aa24bf3c6972e)) 207 | 208 | ## [0.10.0](https://www.github.com/humanwhocodes/config-array/compare/v0.9.5...v0.10.0) (2022-03-01) 209 | 210 | 211 | ### Features 212 | 213 | * Add isExplicitMatch() method ([9ecd90e](https://www.github.com/humanwhocodes/config-array/commit/9ecd90e2a3e984633f535daa4da3cbfb96964fdd)) 214 | 215 | ### [0.9.5](https://www.github.com/humanwhocodes/config-array/compare/v0.9.4...v0.9.5) (2022-02-23) 216 | 217 | 218 | ### Bug Fixes 219 | 220 | * Ensure dot directories are matched correctly ([6e8d180](https://www.github.com/humanwhocodes/config-array/commit/6e8d180f43cedf3c2072d8a1229470e9fafabf5b)) 221 | * preprocessConfig should have correct 'this' value ([9641540](https://www.github.com/humanwhocodes/config-array/commit/96415402cf0012ccf8e4af6c7b934dfc1a058986)) 222 | 223 | ### [0.9.4](https://www.github.com/humanwhocodes/config-array/compare/v0.9.3...v0.9.4) (2022-01-27) 224 | 225 | 226 | ### Bug Fixes 227 | 228 | * Negated patterns to work when files match ([398c811](https://www.github.com/humanwhocodes/config-array/commit/398c8119d359493dc7b82b40df4d92ea6528375f)) 229 | 230 | ### [0.9.3](https://www.github.com/humanwhocodes/config-array/compare/v0.9.2...v0.9.3) (2022-01-26) 231 | 232 | 233 | ### Bug Fixes 234 | 235 | * Make negated ignore patterns work like gitignore ([4ee8e99](https://www.github.com/humanwhocodes/config-array/commit/4ee8e998436e2c4538b06476e0bead8a44fe5a1b)) 236 | 237 | ### [0.9.2](https://www.github.com/humanwhocodes/config-array/compare/v0.9.1...v0.9.2) (2021-11-02) 238 | 239 | 240 | ### Bug Fixes 241 | 242 | * Object merging error by upgrading object-schema ([377d06d](https://www.github.com/humanwhocodes/config-array/commit/377d06d2a44d781b0bec70b3389c48b3d5a63f94)) 243 | 244 | ### [0.9.1](https://www.github.com/humanwhocodes/config-array/compare/v0.9.0...v0.9.1) (2021-10-05) 245 | 246 | 247 | ### Bug Fixes 248 | 249 | * Properly build package for release ([168155f](https://www.github.com/humanwhocodes/config-array/commit/168155f3fed91ab35566c452efd28debf8ec2b85)) 250 | 251 | ## [0.9.0](https://www.github.com/humanwhocodes/config-array/compare/v0.8.0...v0.9.0) (2021-10-04) 252 | 253 | 254 | ### Features 255 | 256 | * getConfig() now returns undefined when no configs match. ([a563b82](https://www.github.com/humanwhocodes/config-array/commit/a563b8255d4eb2bb7745314e3f00ef53792b343f)) 257 | 258 | ## [0.8.0](https://www.github.com/humanwhocodes/config-array/compare/v0.7.0...v0.8.0) (2021-10-01) 259 | 260 | 261 | ### Features 262 | 263 | * Add isIgnored() method ([343e5a0](https://www.github.com/humanwhocodes/config-array/commit/343e5a0a9e32028bfc6c0bf1ec0c6badf74f47f9)) 264 | 265 | 266 | ### Bug Fixes 267 | 268 | * Ensure global ignores are honored ([343e5a0](https://www.github.com/humanwhocodes/config-array/commit/343e5a0a9e32028bfc6c0bf1ec0c6badf74f47f9)) 269 | 270 | ## [0.7.0](https://www.github.com/humanwhocodes/config-array/compare/v0.6.0...v0.7.0) (2021-09-24) 271 | 272 | 273 | ### Features 274 | 275 | * Only object configs by default ([5645f24](https://www.github.com/humanwhocodes/config-array/commit/5645f241b2412a3263a02ef9e3a9bd19cc86035d)) 276 | 277 | ## [0.6.0](https://www.github.com/humanwhocodes/config-array/compare/v0.5.0...v0.6.0) (2021-04-20) 278 | 279 | 280 | ### Features 281 | 282 | * Add the normalizeSync() method ([3e347f9](https://www.github.com/humanwhocodes/config-array/commit/3e347f9d77c5ca2b15995e75ff7bc4fb96b7d66e)) 283 | * Allow async config functions ([a9def0f](https://www.github.com/humanwhocodes/config-array/commit/a9def0faf579c223349dfe08d2486756840538c3)) 284 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Config Array 2 | 3 | by [Nicholas C. Zakas](https://humanwhocodes.com) 4 | 5 | If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate). 6 | 7 | ## Description 8 | 9 | A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename. 10 | 11 | ## Background 12 | 13 | In 2019, I submitted an [ESLint RFC](https://github.com/eslint/rfcs/pull/9) proposing a new way of configuring ESLint. The goal was to streamline what had become an increasingly complicated configuration process. Over several iterations, this proposal was eventually born. 14 | 15 | The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example: 16 | 17 | ```js 18 | export default [ 19 | 20 | // match all JSON files 21 | { 22 | name: "JSON Handler", 23 | files: ["**/*.json"], 24 | handler: jsonHandler 25 | }, 26 | 27 | // match only package.json 28 | { 29 | name: "package.json Handler", 30 | files: ["package.json"], 31 | handler: packageJsonHandler 32 | } 33 | ]; 34 | ``` 35 | 36 | In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins). 37 | 38 | ## Installation 39 | 40 | You can install the package using npm or Yarn: 41 | 42 | ```bash 43 | npm install @humanwhocodes/config-array --save 44 | 45 | # or 46 | 47 | yarn add @humanwhocodes/config-array 48 | ``` 49 | 50 | ## Usage 51 | 52 | First, import the `ConfigArray` constructor: 53 | 54 | ```js 55 | import { ConfigArray } from "@humanwhocodes/config-array"; 56 | 57 | // or using CommonJS 58 | 59 | const { ConfigArray } = require("@humanwhocodes/config-array"); 60 | ``` 61 | 62 | When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example: 63 | 64 | ```js 65 | const configFilename = path.resolve(process.cwd(), "my.config.js"); 66 | const { default: rawConfigs } = await import(configFilename); 67 | const configs = new ConfigArray(rawConfigs, { 68 | 69 | // the path to match filenames from 70 | basePath: process.cwd(), 71 | 72 | // additional items in each config 73 | schema: mySchema 74 | }); 75 | ``` 76 | 77 | This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directory in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, and `name`. 78 | 79 | ### Specifying a Schema 80 | 81 | The `schema` option is required for you to use additional properties in config objects. The schema is an object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@humanwhocodes/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example: 82 | 83 | ```js 84 | const configFilename = path.resolve(process.cwd(), "my.config.js"); 85 | const { default: rawConfigs } = await import(configFilename); 86 | 87 | const mySchema = { 88 | 89 | // define the handler key in configs 90 | handler: { 91 | required: true, 92 | merge(a, b) { 93 | if (!b) return a; 94 | if (!a) return b; 95 | }, 96 | validate(value) { 97 | if (typeof value !== "function") { 98 | throw new TypeError("Function expected."); 99 | } 100 | } 101 | } 102 | }; 103 | 104 | const configs = new ConfigArray(rawConfigs, { 105 | 106 | // the path to match filenames from 107 | basePath: process.cwd(), 108 | 109 | // additional item schemas in each config 110 | schema: mySchema, 111 | 112 | // additional config types supported (default: []) 113 | extraConfigTypes: ["array", "function"]; 114 | }); 115 | ``` 116 | 117 | ### Config Arrays 118 | 119 | Config arrays can be multidimensional, so it's possible for a config array to contain another config array when `extraConfigTypes` contains `"array"`, such as: 120 | 121 | ```js 122 | export default [ 123 | 124 | // JS config 125 | { 126 | files: ["**/*.js"], 127 | handler: jsHandler 128 | }, 129 | 130 | // JSON configs 131 | [ 132 | 133 | // match all JSON files 134 | { 135 | name: "JSON Handler", 136 | files: ["**/*.json"], 137 | handler: jsonHandler 138 | }, 139 | 140 | // match only package.json 141 | { 142 | name: "package.json Handler", 143 | files: ["package.json"], 144 | handler: packageJsonHandler 145 | } 146 | ], 147 | 148 | // filename must match function 149 | { 150 | files: [ filePath => filePath.endsWith(".md") ], 151 | handler: markdownHandler 152 | }, 153 | 154 | // filename must match all patterns in subarray 155 | { 156 | files: [ ["*.test.*", "*.js"] ], 157 | handler: jsTestHandler 158 | }, 159 | 160 | // filename must not match patterns beginning with ! 161 | { 162 | name: "Non-JS files", 163 | files: ["!*.js"], 164 | settings: { 165 | js: false 166 | } 167 | } 168 | ]; 169 | ``` 170 | 171 | In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same. 172 | 173 | If the `files` array contains a function, then that function is called with the absolute path of the file and is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.) 174 | 175 | If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used. 176 | 177 | If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically get a `settings.js` property set to `false`. 178 | 179 | You can also specify an `ignores` key that will force files matching those patterns to not be included. If the `ignores` key is in a config object without any other keys, then those ignores will always be applied; otherwise those ignores act as exclusions. Here's an example: 180 | 181 | ```js 182 | export default [ 183 | 184 | // Always ignored 185 | { 186 | ignores: ["**/.git/**", "**/node_modules/**"] 187 | }, 188 | 189 | // .eslintrc.js file is ignored only when .js file matches 190 | { 191 | files: ["**/*.js"], 192 | ignores: [".eslintrc.js"] 193 | handler: jsHandler 194 | } 195 | ]; 196 | ``` 197 | 198 | You can use negated patterns in `ignores` to exclude a file that was already ignored, such as: 199 | 200 | ```js 201 | export default [ 202 | 203 | // Ignore all JSON files except tsconfig.json 204 | { 205 | files: ["**/*"], 206 | ignores: ["**/*.json", "!tsconfig.json"] 207 | }, 208 | 209 | ]; 210 | ``` 211 | 212 | ### Config Functions 213 | 214 | Config arrays can also include config functions when `extraConfigTypes` contains `"function"`. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example: 215 | 216 | ```js 217 | export default [ 218 | 219 | // JS config 220 | { 221 | files: ["**/*.js"], 222 | handler: jsHandler 223 | }, 224 | 225 | // JSON configs 226 | function (context) { 227 | return [ 228 | 229 | // match all JSON files 230 | { 231 | name: context.name + " JSON Handler", 232 | files: ["**/*.json"], 233 | handler: jsonHandler 234 | }, 235 | 236 | // match only package.json 237 | { 238 | name: context.name + " package.json Handler", 239 | files: ["package.json"], 240 | handler: packageJsonHandler 241 | } 242 | ]; 243 | } 244 | ]; 245 | ``` 246 | 247 | When a config array is normalized, each function is executed and replaced in the config array with the return value. 248 | 249 | **Note:** Config functions can also be async. 250 | 251 | ### Normalizing Config Arrays 252 | 253 | Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values. 254 | 255 | To normalize a config array, call the `normalize()` method and pass in a context object: 256 | 257 | ```js 258 | await configs.normalize({ 259 | name: "MyApp" 260 | }); 261 | ``` 262 | 263 | The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable. 264 | 265 | If you want to disallow async config functions, you can call `normalizeSync()` instead. This method is completely synchronous and does not require using the `await` operator as it does not return a promise: 266 | 267 | ```js 268 | await configs.normalizeSync({ 269 | name: "MyApp" 270 | }); 271 | ``` 272 | 273 | **Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy. 274 | 275 | ### Getting Config for a File 276 | 277 | To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for: 278 | 279 | ```js 280 | // pass in absolute filename 281 | const fileConfig = configs.getConfig(path.resolve(process.cwd(), "package.json")); 282 | ``` 283 | 284 | The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed. 285 | 286 | A few things to keep in mind: 287 | 288 | * You must pass in the absolute filename to get a config for. 289 | * The returned config object never has `files`, `ignores`, or `name` properties; the only properties on the object will be the other configuration options specified. 290 | * The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation. 291 | * A config will only be generated if the filename matches an entry in a `files` key. A config will not be generated without matching a `files` key (configs without a `files` key are only applied when another config with a `files` key is applied; configs without `files` are never applied on their own). Any config with a `files` key entry ending with `/**` or `/*` will only be applied if another entry in the same `files` key matches or another config matches. 292 | 293 | ## Determining Ignored Paths 294 | 295 | You can determine if a file is ignored by using the `isFileIgnored()` method and passing in the absolute path of any file, as in this example: 296 | 297 | ```js 298 | const ignored = configs.isFileIgnored('/foo/bar/baz.txt'); 299 | ``` 300 | 301 | A file is considered ignored if any of the following is true: 302 | 303 | * **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/a.js` is considered ignored. 304 | * **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/baz/a.js` is considered ignored. 305 | * **It matches an ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. 306 | * **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. 307 | * **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored. 308 | 309 | For directories, use the `isDirectoryIgnored()` method and pass in the absolute path of any directory, as in this example: 310 | 311 | ```js 312 | const ignored = configs.isDirectoryIgnored('/foo/bar/'); 313 | ``` 314 | 315 | A directory is considered ignored if any of the following is true: 316 | 317 | * **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/baz` is considered ignored. 318 | * **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/bar/baz/a.js` is considered ignored. 319 | * **It matches and ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. 320 | * **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. 321 | * **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored. 322 | 323 | **Important:** A pattern such as `foo/**` means that `foo` and `foo/` are *not* ignored whereas `foo/bar` is ignored. If you want to ignore `foo` and all of its subdirectories, use the pattern `foo` or `foo/` in `ignores`. 324 | 325 | ## Caching Mechanisms 326 | 327 | Each `ConfigArray` aggressively caches configuration objects to avoid unnecessary work. This caching occurs in two ways: 328 | 329 | 1. **File-based Caching.** For each filename that is passed into a method, the resulting config is cached against that filename so you're always guaranteed to get the same object returned from `getConfig()` whenever you pass the same filename in. 330 | 2. **Index-based Caching.** Whenever a config is calculated, the config elements that were used to create the config are also cached. So if a given filename matches elements 1, 5, and 7, the resulting config is cached with a key of `1,5,7`. That way, if another file is passed that matches the same config elements, the result is already known and doesn't have to be recalculated. That means two files that match all the same elements will return the same config from `getConfig()`. 331 | 332 | ## Acknowledgements 333 | 334 | The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from: 335 | 336 | * Teddy Katz (@not-an-aardvark) 337 | * Toru Nagashima (@mysticatea) 338 | * Kai Cataldo (@kaicataldo) 339 | 340 | ## License 341 | 342 | Apache 2.0 343 | -------------------------------------------------------------------------------- /src/config-array.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview ConfigArray 3 | * @author Nicholas C. Zakas 4 | */ 5 | 6 | //------------------------------------------------------------------------------ 7 | // Imports 8 | //------------------------------------------------------------------------------ 9 | 10 | import path from 'path'; 11 | import minimatch from 'minimatch'; 12 | import createDebug from 'debug'; 13 | 14 | import { ObjectSchema } from '@humanwhocodes/object-schema'; 15 | import { baseSchema } from './base-schema.js'; 16 | import { filesAndIgnoresSchema } from './files-and-ignores-schema.js'; 17 | 18 | //------------------------------------------------------------------------------ 19 | // Helpers 20 | //------------------------------------------------------------------------------ 21 | 22 | const Minimatch = minimatch.Minimatch; 23 | const minimatchCache = new Map(); 24 | const negatedMinimatchCache = new Map(); 25 | const debug = createDebug('@hwc/config-array'); 26 | 27 | const MINIMATCH_OPTIONS = { 28 | // matchBase: true, 29 | dot: true 30 | }; 31 | 32 | const CONFIG_TYPES = new Set(['array', 'function']); 33 | 34 | /** 35 | * Fields that are considered metadata and not part of the config object. 36 | */ 37 | const META_FIELDS = new Set(['name']); 38 | 39 | const FILES_AND_IGNORES_SCHEMA = new ObjectSchema(filesAndIgnoresSchema); 40 | 41 | /** 42 | * Wrapper error for config validation errors that adds a name to the front of the 43 | * error message. 44 | */ 45 | class ConfigError extends Error { 46 | 47 | /** 48 | * Creates a new instance. 49 | * @param {string} name The config object name causing the error. 50 | * @param {number} index The index of the config object in the array. 51 | * @param {Error} source The source error. 52 | */ 53 | constructor(name, index, { cause, message }) { 54 | 55 | 56 | const finalMessage = message || cause.message; 57 | 58 | super(`Config ${name}: ${finalMessage}`, { cause }); 59 | 60 | // copy over custom properties that aren't represented 61 | if (cause) { 62 | for (const key of Object.keys(cause)) { 63 | if (!(key in this)) { 64 | this[key] = cause[key]; 65 | } 66 | } 67 | } 68 | 69 | /** 70 | * The name of the error. 71 | * @type {string} 72 | * @readonly 73 | */ 74 | this.name = 'ConfigError'; 75 | 76 | /** 77 | * The index of the config object in the array. 78 | * @type {number} 79 | * @readonly 80 | */ 81 | this.index = index; 82 | } 83 | } 84 | 85 | /** 86 | * Gets the name of a config object. 87 | * @param {object} config The config object to get the name of. 88 | * @returns {string} The name of the config object. 89 | */ 90 | function getConfigName(config) { 91 | if (config && typeof config.name === 'string' && config.name) { 92 | return `"${config.name}"`; 93 | } 94 | 95 | return '(unnamed)'; 96 | } 97 | 98 | /** 99 | * Rethrows a config error with additional information about the config object. 100 | * @param {object} config The config object to get the name of. 101 | * @param {number} index The index of the config object in the array. 102 | * @param {Error} error The error to rethrow. 103 | * @throws {ConfigError} When the error is rethrown for a config. 104 | */ 105 | function rethrowConfigError(config, index, error) { 106 | const configName = getConfigName(config); 107 | throw new ConfigError(configName, index, error); 108 | } 109 | 110 | /** 111 | * Shorthand for checking if a value is a string. 112 | * @param {any} value The value to check. 113 | * @returns {boolean} True if a string, false if not. 114 | */ 115 | function isString(value) { 116 | return typeof value === 'string'; 117 | } 118 | 119 | /** 120 | * Creates a function that asserts that the config is valid 121 | * during normalization. This checks that the config is not nullish 122 | * and that files and ignores keys of a config object are valid as per base schema. 123 | * @param {Object} config The config object to check. 124 | * @param {number} index The index of the config object in the array. 125 | * @returns {void} 126 | * @throws {ConfigError} If the files and ignores keys of a config object are not valid. 127 | */ 128 | function assertValidBaseConfig(config, index) { 129 | 130 | if (config === null) { 131 | throw new ConfigError(getConfigName(config), index, { message: 'Unexpected null config.' }); 132 | } 133 | 134 | if (config === undefined) { 135 | throw new ConfigError(getConfigName(config), index, { message: 'Unexpected undefined config.' }); 136 | } 137 | 138 | if (typeof config !== 'object') { 139 | throw new ConfigError(getConfigName(config), index, { message: 'Unexpected non-object config.' }); 140 | } 141 | 142 | const validateConfig = { }; 143 | 144 | if ('files' in config) { 145 | validateConfig.files = config.files; 146 | } 147 | 148 | if ('ignores' in config) { 149 | validateConfig.ignores = config.ignores; 150 | } 151 | 152 | try { 153 | FILES_AND_IGNORES_SCHEMA.validate(validateConfig); 154 | } catch (validationError) { 155 | rethrowConfigError(config, index, { cause: validationError }); 156 | } 157 | } 158 | 159 | /** 160 | * Wrapper around minimatch that caches minimatch patterns for 161 | * faster matching speed over multiple file path evaluations. 162 | * @param {string} filepath The file path to match. 163 | * @param {string} pattern The glob pattern to match against. 164 | * @param {object} options The minimatch options to use. 165 | * @returns 166 | */ 167 | function doMatch(filepath, pattern, options = {}) { 168 | 169 | let cache = minimatchCache; 170 | 171 | if (options.flipNegate) { 172 | cache = negatedMinimatchCache; 173 | } 174 | 175 | let matcher = cache.get(pattern); 176 | 177 | if (!matcher) { 178 | matcher = new Minimatch(pattern, Object.assign({}, MINIMATCH_OPTIONS, options)); 179 | cache.set(pattern, matcher); 180 | } 181 | 182 | return matcher.match(filepath); 183 | } 184 | 185 | /** 186 | * Normalizes a `ConfigArray` by flattening it and executing any functions 187 | * that are found inside. 188 | * @param {Array} items The items in a `ConfigArray`. 189 | * @param {Object} context The context object to pass into any function 190 | * found. 191 | * @param {Array} extraConfigTypes The config types to check. 192 | * @returns {Promise} A flattened array containing only config objects. 193 | * @throws {TypeError} When a config function returns a function. 194 | */ 195 | async function normalize(items, context, extraConfigTypes) { 196 | 197 | const allowFunctions = extraConfigTypes.includes('function'); 198 | const allowArrays = extraConfigTypes.includes('array'); 199 | 200 | async function* flatTraverse(array) { 201 | for (let item of array) { 202 | if (typeof item === 'function') { 203 | if (!allowFunctions) { 204 | throw new TypeError('Unexpected function.'); 205 | } 206 | 207 | item = item(context); 208 | if (item.then) { 209 | item = await item; 210 | } 211 | } 212 | 213 | if (Array.isArray(item)) { 214 | if (!allowArrays) { 215 | throw new TypeError('Unexpected array.'); 216 | } 217 | yield* flatTraverse(item); 218 | } else if (typeof item === 'function') { 219 | throw new TypeError('A config function can only return an object or array.'); 220 | } else { 221 | yield item; 222 | } 223 | } 224 | } 225 | 226 | /* 227 | * Async iterables cannot be used with the spread operator, so we need to manually 228 | * create the array to return. 229 | */ 230 | const asyncIterable = await flatTraverse(items); 231 | const configs = []; 232 | 233 | for await (const config of asyncIterable) { 234 | configs.push(config); 235 | } 236 | 237 | return configs; 238 | } 239 | 240 | /** 241 | * Normalizes a `ConfigArray` by flattening it and executing any functions 242 | * that are found inside. 243 | * @param {Array} items The items in a `ConfigArray`. 244 | * @param {Object} context The context object to pass into any function 245 | * found. 246 | * @param {Array} extraConfigTypes The config types to check. 247 | * @returns {Array} A flattened array containing only config objects. 248 | * @throws {TypeError} When a config function returns a function. 249 | */ 250 | function normalizeSync(items, context, extraConfigTypes) { 251 | 252 | const allowFunctions = extraConfigTypes.includes('function'); 253 | const allowArrays = extraConfigTypes.includes('array'); 254 | 255 | function* flatTraverse(array) { 256 | for (let item of array) { 257 | if (typeof item === 'function') { 258 | 259 | if (!allowFunctions) { 260 | throw new TypeError('Unexpected function.'); 261 | } 262 | 263 | item = item(context); 264 | if (item.then) { 265 | throw new TypeError('Async config functions are not supported.'); 266 | } 267 | } 268 | 269 | if (Array.isArray(item)) { 270 | 271 | if (!allowArrays) { 272 | throw new TypeError('Unexpected array.'); 273 | } 274 | 275 | yield* flatTraverse(item); 276 | } else if (typeof item === 'function') { 277 | throw new TypeError('A config function can only return an object or array.'); 278 | } else { 279 | yield item; 280 | } 281 | } 282 | } 283 | 284 | return [...flatTraverse(items)]; 285 | } 286 | 287 | /** 288 | * Determines if a given file path should be ignored based on the given 289 | * matcher. 290 | * @param {Array boolean>} ignores The ignore patterns to check. 291 | * @param {string} filePath The absolute path of the file to check. 292 | * @param {string} relativeFilePath The relative path of the file to check. 293 | * @returns {boolean} True if the path should be ignored and false if not. 294 | */ 295 | function shouldIgnorePath(ignores, filePath, relativeFilePath) { 296 | 297 | // all files outside of the basePath are ignored 298 | if (relativeFilePath.startsWith('..')) { 299 | return true; 300 | } 301 | 302 | return ignores.reduce((ignored, matcher) => { 303 | 304 | if (!ignored) { 305 | 306 | if (typeof matcher === 'function') { 307 | return matcher(filePath); 308 | } 309 | 310 | // don't check negated patterns because we're not ignored yet 311 | if (!matcher.startsWith('!')) { 312 | return doMatch(relativeFilePath, matcher); 313 | } 314 | 315 | // otherwise we're still not ignored 316 | return false; 317 | 318 | } 319 | 320 | // only need to check negated patterns because we're ignored 321 | if (typeof matcher === 'string' && matcher.startsWith('!')) { 322 | return !doMatch(relativeFilePath, matcher, { 323 | flipNegate: true 324 | }); 325 | } 326 | 327 | return ignored; 328 | 329 | }, false); 330 | 331 | } 332 | 333 | /** 334 | * Determines if a given file path is matched by a config based on 335 | * `ignores` only. 336 | * @param {string} filePath The absolute file path to check. 337 | * @param {string} basePath The base path for the config. 338 | * @param {Object} config The config object to check. 339 | * @returns {boolean} True if the file path is matched by the config, 340 | * false if not. 341 | */ 342 | function pathMatchesIgnores(filePath, basePath, config) { 343 | 344 | /* 345 | * For both files and ignores, functions are passed the absolute 346 | * file path while strings are compared against the relative 347 | * file path. 348 | */ 349 | const relativeFilePath = path.relative(basePath, filePath); 350 | 351 | return Object.keys(config).filter(key => !META_FIELDS.has(key)).length > 1 && 352 | !shouldIgnorePath(config.ignores, filePath, relativeFilePath); 353 | } 354 | 355 | 356 | /** 357 | * Determines if a given file path is matched by a config. If the config 358 | * has no `files` field, then it matches; otherwise, if a `files` field 359 | * is present then we match the globs in `files` and exclude any globs in 360 | * `ignores`. 361 | * @param {string} filePath The absolute file path to check. 362 | * @param {string} basePath The base path for the config. 363 | * @param {Object} config The config object to check. 364 | * @returns {boolean} True if the file path is matched by the config, 365 | * false if not. 366 | */ 367 | function pathMatches(filePath, basePath, config) { 368 | 369 | /* 370 | * For both files and ignores, functions are passed the absolute 371 | * file path while strings are compared against the relative 372 | * file path. 373 | */ 374 | const relativeFilePath = path.relative(basePath, filePath); 375 | 376 | // match both strings and functions 377 | const match = pattern => { 378 | 379 | if (isString(pattern)) { 380 | return doMatch(relativeFilePath, pattern); 381 | } 382 | 383 | if (typeof pattern === 'function') { 384 | return pattern(filePath); 385 | } 386 | 387 | throw new TypeError(`Unexpected matcher type ${pattern}.`); 388 | }; 389 | 390 | // check for all matches to config.files 391 | let filePathMatchesPattern = config.files.some(pattern => { 392 | if (Array.isArray(pattern)) { 393 | return pattern.every(match); 394 | } 395 | 396 | return match(pattern); 397 | }); 398 | 399 | /* 400 | * If the file path matches the config.files patterns, then check to see 401 | * if there are any files to ignore. 402 | */ 403 | if (filePathMatchesPattern && config.ignores) { 404 | filePathMatchesPattern = !shouldIgnorePath(config.ignores, filePath, relativeFilePath); 405 | } 406 | 407 | return filePathMatchesPattern; 408 | } 409 | 410 | /** 411 | * Ensures that a ConfigArray has been normalized. 412 | * @param {ConfigArray} configArray The ConfigArray to check. 413 | * @returns {void} 414 | * @throws {Error} When the `ConfigArray` is not normalized. 415 | */ 416 | function assertNormalized(configArray) { 417 | // TODO: Throw more verbose error 418 | if (!configArray.isNormalized()) { 419 | throw new Error('ConfigArray must be normalized to perform this operation.'); 420 | } 421 | } 422 | 423 | /** 424 | * Ensures that config types are valid. 425 | * @param {Array} extraConfigTypes The config types to check. 426 | * @returns {void} 427 | * @throws {Error} When the config types array is invalid. 428 | */ 429 | function assertExtraConfigTypes(extraConfigTypes) { 430 | if (extraConfigTypes.length > 2) { 431 | throw new TypeError('configTypes must be an array with at most two items.'); 432 | } 433 | 434 | for (const configType of extraConfigTypes) { 435 | if (!CONFIG_TYPES.has(configType)) { 436 | throw new TypeError(`Unexpected config type "${configType}" found. Expected one of: "object", "array", "function".`); 437 | } 438 | } 439 | } 440 | 441 | //------------------------------------------------------------------------------ 442 | // Public Interface 443 | //------------------------------------------------------------------------------ 444 | 445 | export const ConfigArraySymbol = { 446 | isNormalized: Symbol('isNormalized'), 447 | configCache: Symbol('configCache'), 448 | schema: Symbol('schema'), 449 | finalizeConfig: Symbol('finalizeConfig'), 450 | preprocessConfig: Symbol('preprocessConfig') 451 | }; 452 | 453 | // used to store calculate data for faster lookup 454 | const dataCache = new WeakMap(); 455 | 456 | /** 457 | * Represents an array of config objects and provides method for working with 458 | * those config objects. 459 | */ 460 | export class ConfigArray extends Array { 461 | 462 | /** 463 | * Creates a new instance of ConfigArray. 464 | * @param {Iterable|Function|Object} configs An iterable yielding config 465 | * objects, or a config function, or a config object. 466 | * @param {string} [options.basePath=""] The path of the config file 467 | * @param {boolean} [options.normalized=false] Flag indicating if the 468 | * configs have already been normalized. 469 | * @param {Object} [options.schema] The additional schema 470 | * definitions to use for the ConfigArray schema. 471 | * @param {Array} [options.configTypes] List of config types supported. 472 | */ 473 | constructor(configs, { 474 | basePath = '', 475 | normalized = false, 476 | schema: customSchema, 477 | extraConfigTypes = [] 478 | } = {} 479 | ) { 480 | super(); 481 | 482 | /** 483 | * Tracks if the array has been normalized. 484 | * @property isNormalized 485 | * @type {boolean} 486 | * @private 487 | */ 488 | this[ConfigArraySymbol.isNormalized] = normalized; 489 | 490 | /** 491 | * The schema used for validating and merging configs. 492 | * @property schema 493 | * @type ObjectSchema 494 | * @private 495 | */ 496 | this[ConfigArraySymbol.schema] = new ObjectSchema( 497 | Object.assign({}, customSchema, baseSchema) 498 | ); 499 | 500 | /** 501 | * The path of the config file that this array was loaded from. 502 | * This is used to calculate filename matches. 503 | * @property basePath 504 | * @type {string} 505 | */ 506 | this.basePath = basePath; 507 | 508 | assertExtraConfigTypes(extraConfigTypes); 509 | 510 | /** 511 | * The supported config types. 512 | * @property configTypes 513 | * @type {Array} 514 | */ 515 | this.extraConfigTypes = Object.freeze([...extraConfigTypes]); 516 | 517 | /** 518 | * A cache to store calculated configs for faster repeat lookup. 519 | * @property configCache 520 | * @type {Map} 521 | * @private 522 | */ 523 | this[ConfigArraySymbol.configCache] = new Map(); 524 | 525 | // init cache 526 | dataCache.set(this, { 527 | explicitMatches: new Map(), 528 | directoryMatches: new Map(), 529 | files: undefined, 530 | ignores: undefined 531 | }); 532 | 533 | // load the configs into this array 534 | if (Array.isArray(configs)) { 535 | this.push(...configs); 536 | } else { 537 | this.push(configs); 538 | } 539 | 540 | } 541 | 542 | /** 543 | * Prevent normal array methods from creating a new `ConfigArray` instance. 544 | * This is to ensure that methods such as `slice()` won't try to create a 545 | * new instance of `ConfigArray` behind the scenes as doing so may throw 546 | * an error due to the different constructor signature. 547 | * @returns {Function} The `Array` constructor. 548 | */ 549 | static get [Symbol.species]() { 550 | return Array; 551 | } 552 | 553 | /** 554 | * Returns the `files` globs from every config object in the array. 555 | * This can be used to determine which files will be matched by a 556 | * config array or to use as a glob pattern when no patterns are provided 557 | * for a command line interface. 558 | * @returns {Array} An array of matchers. 559 | */ 560 | get files() { 561 | 562 | assertNormalized(this); 563 | 564 | // if this data has been cached, retrieve it 565 | const cache = dataCache.get(this); 566 | 567 | if (cache.files) { 568 | return cache.files; 569 | } 570 | 571 | // otherwise calculate it 572 | 573 | const result = []; 574 | 575 | for (const config of this) { 576 | if (config.files) { 577 | config.files.forEach(filePattern => { 578 | result.push(filePattern); 579 | }); 580 | } 581 | } 582 | 583 | // store result 584 | cache.files = result; 585 | dataCache.set(this, cache); 586 | 587 | return result; 588 | } 589 | 590 | /** 591 | * Returns ignore matchers that should always be ignored regardless of 592 | * the matching `files` fields in any configs. This is necessary to mimic 593 | * the behavior of things like .gitignore and .eslintignore, allowing a 594 | * globbing operation to be faster. 595 | * @returns {string[]} An array of string patterns and functions to be ignored. 596 | */ 597 | get ignores() { 598 | 599 | assertNormalized(this); 600 | 601 | // if this data has been cached, retrieve it 602 | const cache = dataCache.get(this); 603 | 604 | if (cache.ignores) { 605 | return cache.ignores; 606 | } 607 | 608 | // otherwise calculate it 609 | 610 | const result = []; 611 | 612 | for (const config of this) { 613 | 614 | /* 615 | * We only count ignores if there are no other keys in the object. 616 | * In this case, it acts list a globally ignored pattern. If there 617 | * are additional keys, then ignores act like exclusions. 618 | */ 619 | if (config.ignores && Object.keys(config).filter(key => !META_FIELDS.has(key)).length === 1) { 620 | result.push(...config.ignores); 621 | } 622 | } 623 | 624 | // store result 625 | cache.ignores = result; 626 | dataCache.set(this, cache); 627 | 628 | return result; 629 | } 630 | 631 | /** 632 | * Indicates if the config array has been normalized. 633 | * @returns {boolean} True if the config array is normalized, false if not. 634 | */ 635 | isNormalized() { 636 | return this[ConfigArraySymbol.isNormalized]; 637 | } 638 | 639 | /** 640 | * Normalizes a config array by flattening embedded arrays and executing 641 | * config functions. 642 | * @param {ConfigContext} context The context object for config functions. 643 | * @returns {Promise} The current ConfigArray instance. 644 | */ 645 | async normalize(context = {}) { 646 | 647 | if (!this.isNormalized()) { 648 | const normalizedConfigs = await normalize(this, context, this.extraConfigTypes); 649 | this.length = 0; 650 | this.push(...normalizedConfigs.map(this[ConfigArraySymbol.preprocessConfig].bind(this))); 651 | this.forEach(assertValidBaseConfig); 652 | this[ConfigArraySymbol.isNormalized] = true; 653 | 654 | // prevent further changes 655 | Object.freeze(this); 656 | } 657 | 658 | return this; 659 | } 660 | 661 | /** 662 | * Normalizes a config array by flattening embedded arrays and executing 663 | * config functions. 664 | * @param {ConfigContext} context The context object for config functions. 665 | * @returns {ConfigArray} The current ConfigArray instance. 666 | */ 667 | normalizeSync(context = {}) { 668 | 669 | if (!this.isNormalized()) { 670 | const normalizedConfigs = normalizeSync(this, context, this.extraConfigTypes); 671 | this.length = 0; 672 | this.push(...normalizedConfigs.map(this[ConfigArraySymbol.preprocessConfig].bind(this))); 673 | this.forEach(assertValidBaseConfig); 674 | this[ConfigArraySymbol.isNormalized] = true; 675 | 676 | // prevent further changes 677 | Object.freeze(this); 678 | } 679 | 680 | return this; 681 | } 682 | 683 | /** 684 | * Finalizes the state of a config before being cached and returned by 685 | * `getConfig()`. Does nothing by default but is provided to be 686 | * overridden by subclasses as necessary. 687 | * @param {Object} config The config to finalize. 688 | * @returns {Object} The finalized config. 689 | */ 690 | [ConfigArraySymbol.finalizeConfig](config) { 691 | return config; 692 | } 693 | 694 | /** 695 | * Preprocesses a config during the normalization process. This is the 696 | * method to override if you want to convert an array item before it is 697 | * validated for the first time. For example, if you want to replace a 698 | * string with an object, this is the method to override. 699 | * @param {Object} config The config to preprocess. 700 | * @returns {Object} The config to use in place of the argument. 701 | */ 702 | [ConfigArraySymbol.preprocessConfig](config) { 703 | return config; 704 | } 705 | 706 | /** 707 | * Determines if a given file path explicitly matches a `files` entry 708 | * and also doesn't match an `ignores` entry. Configs that don't have 709 | * a `files` property are not considered an explicit match. 710 | * @param {string} filePath The complete path of a file to check. 711 | * @returns {boolean} True if the file path matches a `files` entry 712 | * or false if not. 713 | */ 714 | isExplicitMatch(filePath) { 715 | 716 | assertNormalized(this); 717 | 718 | const cache = dataCache.get(this); 719 | 720 | // first check the cache to avoid duplicate work 721 | let result = cache.explicitMatches.get(filePath); 722 | 723 | if (typeof result == 'boolean') { 724 | return result; 725 | } 726 | 727 | // TODO: Maybe move elsewhere? Maybe combine with getConfig() logic? 728 | const relativeFilePath = path.relative(this.basePath, filePath); 729 | 730 | if (shouldIgnorePath(this.ignores, filePath, relativeFilePath)) { 731 | debug(`Ignoring ${filePath}`); 732 | 733 | // cache and return result 734 | cache.explicitMatches.set(filePath, false); 735 | return false; 736 | } 737 | 738 | // filePath isn't automatically ignored, so try to find a match 739 | 740 | for (const config of this) { 741 | 742 | if (!config.files) { 743 | continue; 744 | } 745 | 746 | if (pathMatches(filePath, this.basePath, config)) { 747 | debug(`Matching config found for ${filePath}`); 748 | cache.explicitMatches.set(filePath, true); 749 | return true; 750 | } 751 | } 752 | 753 | return false; 754 | } 755 | 756 | /** 757 | * Returns the config object for a given file path. 758 | * @param {string} filePath The complete path of a file to get a config for. 759 | * @returns {Object} The config object for this file. 760 | */ 761 | getConfig(filePath) { 762 | 763 | assertNormalized(this); 764 | 765 | const cache = this[ConfigArraySymbol.configCache]; 766 | 767 | // first check the cache for a filename match to avoid duplicate work 768 | if (cache.has(filePath)) { 769 | return cache.get(filePath); 770 | } 771 | 772 | let finalConfig; 773 | 774 | // next check to see if the file should be ignored 775 | 776 | // check if this should be ignored due to its directory 777 | if (this.isDirectoryIgnored(path.dirname(filePath))) { 778 | debug(`Ignoring ${filePath} based on directory pattern`); 779 | 780 | // cache and return result - finalConfig is undefined at this point 781 | cache.set(filePath, finalConfig); 782 | return finalConfig; 783 | } 784 | 785 | // TODO: Maybe move elsewhere? 786 | const relativeFilePath = path.relative(this.basePath, filePath); 787 | 788 | if (shouldIgnorePath(this.ignores, filePath, relativeFilePath)) { 789 | debug(`Ignoring ${filePath} based on file pattern`); 790 | 791 | // cache and return result - finalConfig is undefined at this point 792 | cache.set(filePath, finalConfig); 793 | return finalConfig; 794 | } 795 | 796 | // filePath isn't automatically ignored, so try to construct config 797 | 798 | const matchingConfigIndices = []; 799 | let matchFound = false; 800 | const universalPattern = /\/\*{1,2}$/; 801 | 802 | this.forEach((config, index) => { 803 | 804 | if (!config.files) { 805 | 806 | if (!config.ignores) { 807 | debug(`Anonymous universal config found for ${filePath}`); 808 | matchingConfigIndices.push(index); 809 | return; 810 | } 811 | 812 | if (pathMatchesIgnores(filePath, this.basePath, config)) { 813 | debug(`Matching config found for ${filePath} (based on ignores: ${config.ignores})`); 814 | matchingConfigIndices.push(index); 815 | return; 816 | } 817 | 818 | debug(`Skipped config found for ${filePath} (based on ignores: ${config.ignores})`); 819 | return; 820 | } 821 | 822 | /* 823 | * If a config has a files pattern ending in /** or /*, and the 824 | * filePath only matches those patterns, then the config is only 825 | * applied if there is another config where the filePath matches 826 | * a file with a specific extensions such as *.js. 827 | */ 828 | 829 | const universalFiles = config.files.filter( 830 | pattern => universalPattern.test(pattern) 831 | ); 832 | 833 | // universal patterns were found so we need to check the config twice 834 | if (universalFiles.length) { 835 | 836 | debug('Universal files patterns found. Checking carefully.'); 837 | 838 | const nonUniversalFiles = config.files.filter( 839 | pattern => !universalPattern.test(pattern) 840 | ); 841 | 842 | // check that the config matches without the non-universal files first 843 | if ( 844 | nonUniversalFiles.length && 845 | pathMatches( 846 | filePath, this.basePath, 847 | { files: nonUniversalFiles, ignores: config.ignores } 848 | ) 849 | ) { 850 | debug(`Matching config found for ${filePath}`); 851 | matchingConfigIndices.push(index); 852 | matchFound = true; 853 | return; 854 | } 855 | 856 | // if there wasn't a match then check if it matches with universal files 857 | if ( 858 | universalFiles.length && 859 | pathMatches( 860 | filePath, this.basePath, 861 | { files: universalFiles, ignores: config.ignores } 862 | ) 863 | ) { 864 | debug(`Matching config found for ${filePath}`); 865 | matchingConfigIndices.push(index); 866 | return; 867 | } 868 | 869 | // if we make here, then there was no match 870 | return; 871 | } 872 | 873 | // the normal case 874 | if (pathMatches(filePath, this.basePath, config)) { 875 | debug(`Matching config found for ${filePath}`); 876 | matchingConfigIndices.push(index); 877 | matchFound = true; 878 | return; 879 | } 880 | 881 | }); 882 | 883 | // if matching both files and ignores, there will be no config to create 884 | if (!matchFound) { 885 | debug(`No matching configs found for ${filePath}`); 886 | 887 | // cache and return result - finalConfig is undefined at this point 888 | cache.set(filePath, finalConfig); 889 | return finalConfig; 890 | } 891 | 892 | // check to see if there is a config cached by indices 893 | finalConfig = cache.get(matchingConfigIndices.toString()); 894 | 895 | if (finalConfig) { 896 | 897 | // also store for filename for faster lookup next time 898 | cache.set(filePath, finalConfig); 899 | 900 | return finalConfig; 901 | } 902 | 903 | // otherwise construct the config 904 | 905 | finalConfig = matchingConfigIndices.reduce((result, index) => { 906 | try { 907 | return this[ConfigArraySymbol.schema].merge(result, this[index]); 908 | } catch (validationError) { 909 | rethrowConfigError(this[index], index, { cause: validationError}); 910 | } 911 | }, {}, this); 912 | 913 | finalConfig = this[ConfigArraySymbol.finalizeConfig](finalConfig); 914 | 915 | cache.set(filePath, finalConfig); 916 | cache.set(matchingConfigIndices.toString(), finalConfig); 917 | 918 | return finalConfig; 919 | } 920 | 921 | /** 922 | * Determines if the given filepath is ignored based on the configs. 923 | * @param {string} filePath The complete path of a file to check. 924 | * @returns {boolean} True if the path is ignored, false if not. 925 | * @deprecated Use `isFileIgnored` instead. 926 | */ 927 | isIgnored(filePath) { 928 | return this.isFileIgnored(filePath); 929 | } 930 | 931 | /** 932 | * Determines if the given filepath is ignored based on the configs. 933 | * @param {string} filePath The complete path of a file to check. 934 | * @returns {boolean} True if the path is ignored, false if not. 935 | */ 936 | isFileIgnored(filePath) { 937 | return this.getConfig(filePath) === undefined; 938 | } 939 | 940 | /** 941 | * Determines if the given directory is ignored based on the configs. 942 | * This checks only default `ignores` that don't have `files` in the 943 | * same config. A pattern such as `/foo` be considered to ignore the directory 944 | * while a pattern such as `/foo/**` is not considered to ignore the 945 | * directory because it is matching files. 946 | * @param {string} directoryPath The complete path of a directory to check. 947 | * @returns {boolean} True if the directory is ignored, false if not. Will 948 | * return true for any directory that is not inside of `basePath`. 949 | * @throws {Error} When the `ConfigArray` is not normalized. 950 | */ 951 | isDirectoryIgnored(directoryPath) { 952 | 953 | assertNormalized(this); 954 | 955 | const relativeDirectoryPath = path.relative(this.basePath, directoryPath) 956 | .replace(/\\/g, '/'); 957 | 958 | if (relativeDirectoryPath.startsWith('..')) { 959 | return true; 960 | } 961 | 962 | // first check the cache 963 | const cache = dataCache.get(this).directoryMatches; 964 | 965 | if (cache.has(relativeDirectoryPath)) { 966 | return cache.get(relativeDirectoryPath); 967 | } 968 | 969 | const directoryParts = relativeDirectoryPath.split('/'); 970 | let relativeDirectoryToCheck = ''; 971 | let result = false; 972 | 973 | /* 974 | * In order to get the correct gitignore-style ignores, where an 975 | * ignored parent directory cannot have any descendants unignored, 976 | * we need to check every directory starting at the parent all 977 | * the way down to the actual requested directory. 978 | * 979 | * We aggressively cache all of this info to make sure we don't 980 | * have to recalculate everything for every call. 981 | */ 982 | do { 983 | 984 | relativeDirectoryToCheck += directoryParts.shift() + '/'; 985 | 986 | result = shouldIgnorePath( 987 | this.ignores, 988 | path.join(this.basePath, relativeDirectoryToCheck), 989 | relativeDirectoryToCheck 990 | ); 991 | 992 | cache.set(relativeDirectoryToCheck, result); 993 | 994 | } while (!result && directoryParts.length); 995 | 996 | // also cache the result for the requested path 997 | cache.set(relativeDirectoryPath, result); 998 | 999 | return result; 1000 | } 1001 | 1002 | } 1003 | -------------------------------------------------------------------------------- /tests/config-array.test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview Tests for ConfigArray object. 3 | * @author Nicholas C. Zakas 4 | */ 5 | 6 | //----------------------------------------------------------------------------- 7 | // Imports 8 | //----------------------------------------------------------------------------- 9 | 10 | import { ConfigArray, ConfigArraySymbol } from '../src/config-array.js'; 11 | import path from 'path'; 12 | import chai from 'chai'; 13 | 14 | const expect = chai.expect; 15 | 16 | //----------------------------------------------------------------------------- 17 | // Helpers 18 | //----------------------------------------------------------------------------- 19 | 20 | const basePath = __dirname; 21 | 22 | const schema = { 23 | language: { 24 | required: false, 25 | validate(value) { 26 | if (typeof value !== 'function') { 27 | throw new TypeError('Expected a function.'); 28 | } 29 | }, 30 | merge(a, b) { 31 | if (!b) { 32 | return a; 33 | } 34 | 35 | if (!a) { 36 | return b; 37 | } 38 | } 39 | }, 40 | defs: { 41 | required: false, 42 | validate(value) { 43 | if (!value || typeof value !== 'object') { 44 | throw new TypeError('Object expected.'); 45 | } 46 | }, 47 | merge(a, b) { 48 | return { 49 | ...a, 50 | ...b 51 | }; 52 | } 53 | } 54 | }; 55 | 56 | const JSLanguage = class {}; 57 | const CSSLanguage = class {}; 58 | const MarkdownLanguage = class {}; 59 | const JSONLanguage = class {}; 60 | 61 | function createConfigArray(options) { 62 | return new ConfigArray([ 63 | { 64 | files: ['**/*.js'], 65 | language: JSLanguage 66 | }, 67 | { 68 | files: ['**/*.json'], 69 | language: JSONLanguage 70 | }, 71 | { 72 | files: ['**/*.css'], 73 | language: CSSLanguage 74 | }, 75 | { 76 | files: ['**/*.md', '**/.markdown'], 77 | language: MarkdownLanguage 78 | }, 79 | {}, 80 | { 81 | files: ['!*.css'], 82 | defs: { 83 | css: false 84 | } 85 | }, 86 | { 87 | files: ['**/*.xsl'], 88 | ignores: ['fixtures/test.xsl'], 89 | defs: { 90 | xsl: true 91 | } 92 | }, 93 | { 94 | files: ['tests/**/*.xyz'], 95 | defs: { 96 | xyz: true 97 | } 98 | }, 99 | { 100 | ignores: ['tests/fixtures/**'], 101 | defs: { 102 | name: 'config-array' 103 | } 104 | }, 105 | { 106 | ignores: ['node_modules/**'] 107 | }, 108 | { 109 | files: ['foo.test.js'], 110 | defs: { 111 | name: 'config-array.test' 112 | } 113 | }, 114 | function(context) { 115 | return { 116 | files: ['bar.test.js'], 117 | defs: { 118 | name: context.name 119 | } 120 | }; 121 | }, 122 | function(context) { 123 | return [ 124 | { 125 | files: ['baz.test.js'], 126 | defs: { 127 | name: 'baz-' + context.name 128 | } 129 | }, 130 | { 131 | files: ['boom.test.js'], 132 | defs: { 133 | name: 'boom-' + context.name 134 | } 135 | } 136 | ]; 137 | }, 138 | { 139 | files: [['*.and.*', '*.js']], 140 | defs: { 141 | name: 'AND operator' 142 | } 143 | }, 144 | { 145 | files: [filePath => filePath.endsWith('.html')], 146 | defs: { 147 | name: 'HTML' 148 | } 149 | }, 150 | { 151 | ignores: [filePath => filePath.endsWith('.gitignore')] 152 | }, 153 | { 154 | files: ['**/*'], 155 | defs: { 156 | universal: true 157 | } 158 | } 159 | ], { 160 | basePath, 161 | schema, 162 | extraConfigTypes: ['array', 'function'], 163 | ...options 164 | }); 165 | } 166 | 167 | //----------------------------------------------------------------------------- 168 | // Tests 169 | //----------------------------------------------------------------------------- 170 | 171 | describe('ConfigArray', () => { 172 | 173 | let configs, 174 | unnormalizedConfigs; 175 | 176 | beforeEach(() => { 177 | unnormalizedConfigs = new ConfigArray([], { basePath, extraConfigTypes: ['array', 'function'] }); 178 | configs = createConfigArray(); 179 | return configs.normalize({ 180 | name: 'from-context' 181 | }); 182 | }); 183 | 184 | describe('Config Types Validation', () => { 185 | it('should not throw an error when objects are allowed', async () => { 186 | configs = new ConfigArray([ 187 | { 188 | files: ['*.js'] 189 | } 190 | ], { 191 | basePath 192 | }); 193 | await configs.normalize(); 194 | 195 | }); 196 | 197 | it('should not throw an error when arrays are allowed', async () => { 198 | configs = new ConfigArray([ 199 | [ 200 | { 201 | files: ['*.js'] 202 | } 203 | ] 204 | ], { 205 | basePath, 206 | extraConfigTypes: ['array'] 207 | }); 208 | await configs.normalize(); 209 | 210 | }); 211 | 212 | it('should not throw an error when functions are allowed', async () => { 213 | configs = new ConfigArray([ 214 | () => ({}) 215 | ], { 216 | basePath, 217 | extraConfigTypes: ['function'] 218 | }); 219 | await configs.normalize(); 220 | 221 | }); 222 | 223 | it('should throw an error in normalize() when arrays are not allowed', done => { 224 | 225 | configs = new ConfigArray([ 226 | [ 227 | { 228 | files: '*.js' 229 | } 230 | ] 231 | ], { 232 | basePath 233 | }); 234 | 235 | configs 236 | .normalize() 237 | .then(() => { 238 | throw new Error('Missing error.'); 239 | }) 240 | .catch(ex => { 241 | expect(ex).matches(/Unexpected array/); 242 | done(); 243 | }); 244 | 245 | }); 246 | 247 | it('should throw an error in normalizeSync() when arrays are not allowed', () => { 248 | 249 | configs = new ConfigArray([ 250 | [ 251 | { 252 | files: '*.js' 253 | } 254 | ] 255 | ], { 256 | basePath 257 | }); 258 | 259 | expect(() => { 260 | configs.normalizeSync(); 261 | }) 262 | .throws(/Unexpected array/); 263 | 264 | }); 265 | 266 | it('should throw an error in normalize() when functions are not allowed', done => { 267 | 268 | configs = new ConfigArray([ 269 | () => ({}) 270 | ], { 271 | basePath 272 | }); 273 | 274 | configs 275 | .normalize() 276 | .then(() => { 277 | throw new Error('Missing error.'); 278 | }) 279 | .catch(ex => { 280 | expect(ex).matches(/Unexpected function/); 281 | done(); 282 | }); 283 | 284 | }); 285 | 286 | it('should throw an error in normalizeSync() when functions are not allowed', () => { 287 | 288 | configs = new ConfigArray([ 289 | () => {} 290 | ], { 291 | basePath 292 | }); 293 | 294 | expect(() => { 295 | configs.normalizeSync(); 296 | }) 297 | .throws(/Unexpected function/); 298 | 299 | }); 300 | 301 | }); 302 | 303 | describe('Validation', () => { 304 | 305 | function testValidationError({ only = false, title, configs, expectedError }) { 306 | 307 | const localIt = only ? it.only : it; 308 | 309 | localIt(`${title} when calling normalize()`, async () => { 310 | const configArray = new ConfigArray(configs, { basePath }); 311 | 312 | let actualError; 313 | try { 314 | await configArray.normalize(); 315 | } catch (error) { 316 | actualError = error; 317 | } 318 | expect(() => { 319 | if (actualError) { 320 | throw actualError; 321 | } 322 | }) 323 | .to 324 | .throw(expectedError); 325 | 326 | }); 327 | 328 | localIt(`${title} when calling normalizeSync()`, () => { 329 | const configArray = new ConfigArray(configs, { basePath }); 330 | 331 | expect(() => configArray.normalizeSync()) 332 | .to 333 | .throw(expectedError); 334 | 335 | }); 336 | } 337 | 338 | testValidationError({ 339 | title: 'should throw an error when files is not an array', 340 | configs: [ 341 | { 342 | files: '*.js' 343 | } 344 | ], 345 | expectedError: /non-empty array/ 346 | }); 347 | 348 | testValidationError({ 349 | title: 'should throw an error when files is an empty array', 350 | configs: [ 351 | { 352 | files: [] 353 | } 354 | ], 355 | expectedError: /non-empty array/ 356 | }); 357 | 358 | testValidationError({ 359 | title: 'should throw an error when files is undefined', 360 | configs: [ 361 | { 362 | files: undefined 363 | } 364 | ], 365 | expectedError: /non-empty array/ 366 | }); 367 | 368 | testValidationError({ 369 | title: 'should throw an error when files contains an invalid element', 370 | configs: [ 371 | { 372 | name: '', 373 | files: ['*.js', undefined] 374 | } 375 | ], 376 | expectedError: 'Config (unnamed): Key "files": Items must be a string, a function, or an array of strings and functions.' 377 | }); 378 | 379 | testValidationError({ 380 | title: 'should throw an error when ignores is undefined', 381 | configs: [ 382 | { 383 | ignores: undefined 384 | } 385 | ], 386 | expectedError: 'Config (unnamed): Key "ignores": Expected value to be an array.' 387 | }); 388 | 389 | testValidationError({ 390 | title: 'should throw an error when a global ignores contains an invalid element', 391 | configs: [ 392 | { 393 | name: 'foo', 394 | ignores: ['ignored/**', -1] 395 | } 396 | ], 397 | expectedError: 'Config "foo": Key "ignores": Expected array to only contain strings and functions.' 398 | }); 399 | 400 | testValidationError({ 401 | title: 'should throw an error when a non-global ignores contains an invalid element', 402 | configs: [ 403 | { 404 | name: 'foo', 405 | files: ['*.js'], 406 | ignores: [-1] 407 | } 408 | ], 409 | expectedError: 'Config "foo": Key "ignores": Expected array to only contain strings and functions.' 410 | }); 411 | 412 | it('should throw an error when a config is not an object', async () => { 413 | configs = new ConfigArray([ 414 | { 415 | files: ['*.js'] 416 | }, 417 | 'eslint:reccommended' // typo 418 | ], { basePath }); 419 | 420 | expect(() => { 421 | configs.normalizeSync(); 422 | }) 423 | .to 424 | .throw('Config (unnamed): Unexpected non-object config.'); 425 | 426 | }); 427 | 428 | it('should throw an error when base config name is not a string', async () => { 429 | configs = new ConfigArray([ 430 | { 431 | files: ['**'], 432 | name: true 433 | } 434 | ], { basePath }); 435 | 436 | await configs.normalize(); 437 | 438 | expect(() => { 439 | configs.getConfig(path.resolve(basePath, 'foo.js')); 440 | }) 441 | .to 442 | .throw('Config (unnamed): Key "name": Property must be a string.'); 443 | 444 | }); 445 | 446 | it('should throw an error when additional config name is not a string', async () => { 447 | configs = new ConfigArray([{}], { basePath }); 448 | configs.push( 449 | { 450 | files: ['**'], 451 | name: true 452 | } 453 | ); 454 | 455 | await configs.normalize(); 456 | 457 | expect(() => { 458 | configs.getConfig(path.resolve(basePath, 'foo.js')); 459 | }) 460 | .to 461 | .throw('Config (unnamed): Key "name": Property must be a string.'); 462 | 463 | }); 464 | 465 | it('should throw an error when base config is undefined', async () => { 466 | configs = new ConfigArray([undefined], { basePath }); 467 | 468 | expect(() => { 469 | configs.normalizeSync(); 470 | }) 471 | .to 472 | .throw('Config (unnamed): Unexpected undefined config.'); 473 | 474 | }); 475 | 476 | it('should throw an error when base config is null', async () => { 477 | configs = new ConfigArray([null], { basePath }); 478 | 479 | expect(() => { 480 | configs.normalizeSync(); 481 | }) 482 | .to 483 | .throw('Config (unnamed): Unexpected null config.'); 484 | 485 | }); 486 | 487 | it('should throw an error when additional config is undefined', async () => { 488 | configs = new ConfigArray([{}], { basePath }); 489 | configs.push(undefined); 490 | 491 | expect(() => { 492 | configs.normalizeSync(); 493 | }) 494 | .to 495 | .throw('Config (unnamed): Unexpected undefined config.'); 496 | 497 | }); 498 | 499 | it('should throw an error when additional config is null', async () => { 500 | configs = new ConfigArray([{}], { basePath }); 501 | configs.push(null); 502 | 503 | expect(() => { 504 | configs.normalizeSync(); 505 | }) 506 | .to 507 | .throw('Config (unnamed): Unexpected null config.'); 508 | 509 | }); 510 | }); 511 | 512 | describe('ConfigArray members', () => { 513 | 514 | beforeEach(() => { 515 | configs = createConfigArray(); 516 | return configs.normalize({ 517 | name: 'from-context' 518 | }); 519 | }); 520 | 521 | describe('ConfigArraySymbol.finalizeConfig', () => { 522 | it('should allow finalizeConfig to alter config before returning when calling normalize()', async () => { 523 | 524 | configs = createConfigArray(); 525 | configs[ConfigArraySymbol.finalizeConfig] = () => { 526 | return { 527 | name: 'from-finalize' 528 | }; 529 | }; 530 | 531 | await configs.normalize({ 532 | name: 'from-context' 533 | }); 534 | 535 | const filename = path.resolve(basePath, 'foo.js'); 536 | const config = configs.getConfig(filename); 537 | expect(config.name).to.equal('from-finalize'); 538 | }); 539 | 540 | it('should allow finalizeConfig to alter config before returning when calling normalizeSync()', async () => { 541 | 542 | configs = createConfigArray(); 543 | configs[ConfigArraySymbol.finalizeConfig] = () => { 544 | return { 545 | name: 'from-finalize' 546 | }; 547 | }; 548 | 549 | configs.normalizeSync({ 550 | name: 'from-context' 551 | }); 552 | 553 | const filename = path.resolve(basePath, 'foo.js'); 554 | const config = configs.getConfig(filename); 555 | expect(config.name).to.equal('from-finalize'); 556 | }); 557 | 558 | }); 559 | 560 | describe('ConfigArraySymbol.preprocessConfig', () => { 561 | it('should allow preprocessConfig to alter config before returning', async () => { 562 | 563 | configs = createConfigArray(); 564 | configs.push('foo:bar'); 565 | 566 | configs[ConfigArraySymbol.preprocessConfig] = config => { 567 | 568 | if (config === 'foo:bar') { 569 | return { 570 | defs: { 571 | name: 'foo:bar' 572 | } 573 | }; 574 | } 575 | 576 | return config; 577 | }; 578 | 579 | await configs.normalize({ 580 | name: 'from-context' 581 | }); 582 | 583 | const filename = path.resolve(basePath, 'foo.js'); 584 | const config = configs.getConfig(filename); 585 | expect(config.defs.name).to.equal('foo:bar'); 586 | }); 587 | 588 | it('should have "this" inside of function be equal to config array when calling normalize()', async () => { 589 | 590 | configs = createConfigArray(); 591 | configs.push('foo:bar'); 592 | let internalThis; 593 | 594 | configs[ConfigArraySymbol.preprocessConfig] = function(config) { 595 | internalThis = this; 596 | 597 | if (config === 'foo:bar') { 598 | return { 599 | defs: { 600 | name: 'foo:bar' 601 | } 602 | }; 603 | } 604 | 605 | return config; 606 | }; 607 | 608 | await configs.normalize({ 609 | name: 'from-context' 610 | }); 611 | 612 | expect(internalThis).to.equal(configs); 613 | }); 614 | 615 | it('should have "this" inside of function be equal to config array when calling normalizeSync()', async () => { 616 | 617 | configs = createConfigArray(); 618 | configs.push('foo:bar'); 619 | let internalThis; 620 | 621 | configs[ConfigArraySymbol.preprocessConfig] = function(config) { 622 | internalThis = this; 623 | 624 | if (config === 'foo:bar') { 625 | return { 626 | defs: { 627 | name: 'foo:bar' 628 | } 629 | }; 630 | } 631 | 632 | return config; 633 | }; 634 | 635 | configs.normalizeSync({ 636 | name: 'from-context' 637 | }); 638 | 639 | expect(internalThis).to.equal(configs); 640 | }); 641 | 642 | }); 643 | 644 | describe('basePath', () => { 645 | it('should store basePath property when basePath is provided', () => { 646 | expect(unnormalizedConfigs.basePath).to.equal(basePath); 647 | expect(configs.basePath).to.equal(basePath); 648 | }); 649 | }); 650 | 651 | describe('isNormalized()', () => { 652 | it('should return true when the config array is normalized', () => { 653 | expect(configs.isNormalized()).to.be.true; 654 | }); 655 | 656 | it('should return false when the config array is not normalized', () => { 657 | expect(unnormalizedConfigs.isNormalized()).to.be.false; 658 | }); 659 | }); 660 | 661 | describe('getConfig()', () => { 662 | 663 | it('should throw an error when not normalized', () => { 664 | const filename = path.resolve(basePath, 'foo.js'); 665 | 666 | expect(() => { 667 | unnormalizedConfigs.getConfig(filename); 668 | }) 669 | .to 670 | .throw(/normalized/); 671 | }); 672 | 673 | it('should calculate correct config when passed JS filename', () => { 674 | const filename = path.resolve(basePath, 'foo.js'); 675 | const config = configs.getConfig(filename); 676 | 677 | expect(config.language).to.equal(JSLanguage); 678 | expect(config.defs).to.be.an('object'); 679 | expect(config.defs.name).to.equal('config-array'); 680 | expect(config.defs.universal).to.be.true; 681 | expect(config.defs.css).to.be.false; 682 | }); 683 | 684 | it('should calculate correct config when passed XYZ filename', () => { 685 | const filename = path.resolve(basePath, 'tests/.bar/foo.xyz'); 686 | 687 | const config = configs.getConfig(filename); 688 | 689 | expect(config.defs).to.be.an('object'); 690 | expect(config.defs.name).to.equal('config-array'); 691 | expect(config.defs.universal).to.be.true; 692 | expect(config.defs.xyz).to.be.true; 693 | }); 694 | 695 | it('should calculate correct config when passed HTML filename', () => { 696 | const filename = path.resolve(basePath, 'foo.html'); 697 | 698 | const config = configs.getConfig(filename); 699 | 700 | expect(config.defs).to.be.an('object'); 701 | expect(config.defs.name).to.equal('HTML'); 702 | expect(config.defs.universal).to.be.true; 703 | }); 704 | 705 | it('should return undefined when passed ignored .gitignore filename', () => { 706 | const filename = path.resolve(basePath, '.gitignore'); 707 | 708 | const config = configs.getConfig(filename); 709 | 710 | expect(config).to.be.undefined; 711 | }); 712 | 713 | it('should calculate correct config when passed JS filename that matches two configs', () => { 714 | const filename = path.resolve(basePath, 'foo.test.js'); 715 | 716 | const config = configs.getConfig(filename); 717 | 718 | expect(config.language).to.equal(JSLanguage); 719 | expect(config.defs).to.be.an('object'); 720 | expect(config.defs.name).to.equal('config-array.test'); 721 | expect(config.defs.css).to.be.false; 722 | expect(config.defs.universal).to.be.true; 723 | }); 724 | 725 | it('should calculate correct config when passed JS filename that matches a function config', () => { 726 | const filename = path.resolve(basePath, 'bar.test.js'); 727 | 728 | const config = configs.getConfig(filename); 729 | 730 | expect(config.language).to.equal(JSLanguage); 731 | expect(config.defs).to.be.an('object'); 732 | expect(config.defs.name).to.equal('from-context'); 733 | expect(config.defs.css).to.be.false; 734 | expect(config.defs.universal).to.be.true; 735 | }); 736 | 737 | it('should not match a filename that doesn\'t explicitly match a files pattern', () => { 738 | const matchingFilename = path.resolve(basePath, 'foo.js'); 739 | const notMatchingFilename = path.resolve(basePath, 'foo.md'); 740 | configs = new ConfigArray([ 741 | {}, 742 | { 743 | files: ['**/*.js'] 744 | } 745 | ], { basePath, schema }); 746 | 747 | configs.normalizeSync(); 748 | 749 | const config1 = configs.getConfig(matchingFilename); 750 | expect(config1).to.be.an('object'); 751 | 752 | const config2 = configs.getConfig(notMatchingFilename); 753 | expect(config2).to.be.undefined; 754 | }); 755 | 756 | it('should calculate correct config when passed JS filename that matches a async function config', () => { 757 | const configs = createConfigArray(); 758 | configs.push(context => { 759 | return Promise.resolve([ 760 | { 761 | files: ['async.test.js'], 762 | defs: { 763 | name: 'async-' + context.name 764 | } 765 | } 766 | ]); 767 | }); 768 | 769 | expect(() => { 770 | configs.normalizeSync(); 771 | }) 772 | .to 773 | .throw(/Async config functions are not supported/); 774 | }); 775 | 776 | it('should throw an error when passed JS filename that matches a async function config and normalizeSync() is called', async () => { 777 | const filename = path.resolve(basePath, 'async.test.js'); 778 | const configs = createConfigArray(); 779 | configs.push(context => { 780 | return Promise.resolve([ 781 | { 782 | files: ['async.test.js'], 783 | defs: { 784 | name: 'async-' + context.name 785 | } 786 | } 787 | ]); 788 | }); 789 | 790 | await configs.normalize({ 791 | name: 'from-context' 792 | }); 793 | 794 | const config = configs.getConfig(filename); 795 | 796 | expect(config.language).to.equal(JSLanguage); 797 | expect(config.defs).to.be.an('object'); 798 | expect(config.defs.name).to.equal('async-from-context'); 799 | expect(config.defs.css).to.be.false; 800 | expect(config.defs.universal).to.be.true; 801 | }); 802 | 803 | it('should throw an error when defs doesn\'t pass validation', async () => { 804 | const configs = new ConfigArray([ 805 | { 806 | files: ['**/*.js'], 807 | defs: 'foo', 808 | name: 'bar' 809 | } 810 | ], { basePath, schema }); 811 | 812 | await configs.normalize(); 813 | 814 | const filename = path.resolve(basePath, 'foo.js'); 815 | expect(() => { 816 | configs.getConfig(filename); 817 | }) 818 | .to 819 | .throw('Config "bar": Key "defs": Object expected.'); 820 | }); 821 | 822 | it('should calculate correct config when passed JS filename that matches a function config returning an array', () => { 823 | const filename1 = path.resolve(basePath, 'baz.test.js'); 824 | const config1 = configs.getConfig(filename1); 825 | 826 | expect(config1.language).to.equal(JSLanguage); 827 | expect(config1.defs).to.be.an('object'); 828 | expect(config1.defs.name).to.equal('baz-from-context'); 829 | 830 | const filename2 = path.resolve(basePath, 'baz.test.js'); 831 | const config2 = configs.getConfig(filename2); 832 | 833 | expect(config2.language).to.equal(JSLanguage); 834 | expect(config2.defs).to.be.an('object'); 835 | expect(config2.defs.name).to.equal('baz-from-context'); 836 | expect(config2.defs.css).to.be.false; 837 | }); 838 | 839 | it('should calculate correct config when passed CSS filename', () => { 840 | const filename = path.resolve(basePath, 'foo.css'); 841 | 842 | const config = configs.getConfig(filename); 843 | expect(config.language).to.equal(CSSLanguage); 844 | expect(config.defs).to.be.an('object'); 845 | expect(config.defs.name).to.equal('config-array'); 846 | expect(config.defs.universal).to.be.true; 847 | }); 848 | 849 | it('should calculate correct config when passed JS filename that matches AND pattern', () => { 850 | const filename = path.resolve(basePath, 'foo.and.js'); 851 | 852 | const config = configs.getConfig(filename); 853 | expect(config.language).to.equal(JSLanguage); 854 | expect(config.defs).to.be.an('object'); 855 | expect(config.defs.name).to.equal('AND operator'); 856 | expect(config.defs.css).to.be.false; 857 | expect(config.defs.universal).to.be.true; 858 | }); 859 | 860 | it('should return the same config when called with the same filename twice (caching)', () => { 861 | const filename = path.resolve(basePath, 'foo.js'); 862 | 863 | const config1 = configs.getConfig(filename); 864 | const config2 = configs.getConfig(filename); 865 | 866 | expect(config1).to.equal(config2); 867 | }); 868 | 869 | it('should return the same config when called with two filenames that match the same configs (caching)', () => { 870 | const filename1 = path.resolve(basePath, 'foo1.js'); 871 | const filename2 = path.resolve(basePath, 'foo2.js'); 872 | 873 | const config1 = configs.getConfig(filename1); 874 | const config2 = configs.getConfig(filename2); 875 | 876 | expect(config1).to.equal(config2); 877 | }); 878 | 879 | it('should return empty config when called with ignored node_modules filename', () => { 880 | const filename = path.resolve(basePath, 'node_modules/foo.js'); 881 | const config = configs.getConfig(filename); 882 | 883 | expect(config).to.be.undefined; 884 | }); 885 | 886 | // https://github.com/eslint/eslint/issues/17103 887 | describe('ignores patterns should be properly applied', () => { 888 | 889 | it('should return undefined when a filename matches an ignores pattern but not a files pattern', () => { 890 | const matchingFilename = path.resolve(basePath, 'foo.js'); 891 | const notMatchingFilename = path.resolve(basePath, 'foo.md'); 892 | configs = new ConfigArray([ 893 | { 894 | defs: { 895 | severity: 'error' 896 | } 897 | }, 898 | { 899 | ignores: ['**/*.md'], 900 | defs: { 901 | severity: 'warn' 902 | } 903 | } 904 | ], { basePath, schema }); 905 | 906 | configs.normalizeSync(); 907 | 908 | const config1 = configs.getConfig(matchingFilename); 909 | expect(config1).to.be.undefined; 910 | 911 | const config2 = configs.getConfig(notMatchingFilename); 912 | expect(config2).to.be.undefined; 913 | }); 914 | 915 | it('should apply config with only ignores when a filename matches a files pattern', () => { 916 | const matchingFilename = path.resolve(basePath, 'foo.js'); 917 | const notMatchingFilename = path.resolve(basePath, 'foo.md'); 918 | configs = new ConfigArray([ 919 | { 920 | files: ['**/*.js'], 921 | defs: { 922 | severity: 'error' 923 | } 924 | }, 925 | { 926 | ignores: ['**/*.md'], 927 | defs: { 928 | severity: 'warn' 929 | } 930 | } 931 | ], { basePath, schema }); 932 | 933 | configs.normalizeSync(); 934 | 935 | const config1 = configs.getConfig(matchingFilename); 936 | expect(config1).to.be.an('object'); 937 | expect(config1.defs.severity).to.equal('warn'); 938 | 939 | const config2 = configs.getConfig(notMatchingFilename); 940 | expect(config2).to.be.undefined; 941 | }); 942 | 943 | it('should not apply config with only ignores when a filename should be ignored', () => { 944 | const matchingFilename = path.resolve(basePath, 'foo.js'); 945 | const ignoredFilename = path.resolve(basePath, 'bar.js'); 946 | configs = new ConfigArray([ 947 | { 948 | files: ['**/*.js'], 949 | defs: { 950 | severity: 'error' 951 | } 952 | }, 953 | { 954 | ignores: ['**/bar.js'], 955 | defs: { 956 | severity: 'warn' 957 | } 958 | } 959 | ], { basePath, schema }); 960 | 961 | configs.normalizeSync(); 962 | 963 | const config1 = configs.getConfig(matchingFilename); 964 | expect(config1).to.be.an('object'); 965 | expect(config1.defs.severity).to.equal('warn'); 966 | 967 | const config2 = configs.getConfig(ignoredFilename); 968 | expect(config2).to.be.an('object'); 969 | expect(config2.defs.severity).to.equal('error'); 970 | }); 971 | 972 | }); 973 | 974 | }); 975 | 976 | describe('isIgnored()', () => { 977 | 978 | it('should throw an error when not normalized', () => { 979 | const filename = path.resolve(basePath, 'foo.js'); 980 | 981 | expect(() => { 982 | unnormalizedConfigs.isIgnored(filename); 983 | }) 984 | .to 985 | .throw(/normalized/); 986 | }); 987 | 988 | it('should return false when passed JS filename', () => { 989 | const filename = path.resolve(basePath, 'foo.js'); 990 | 991 | expect(configs.isIgnored(filename)).to.be.false; 992 | }); 993 | 994 | it('should return true when passed JS filename in parent directory', () => { 995 | const filename = path.resolve(basePath, '../foo.js'); 996 | 997 | expect(configs.isIgnored(filename)).to.be.true; 998 | }); 999 | 1000 | it('should return false when passed HTML filename', () => { 1001 | const filename = path.resolve(basePath, 'foo.html'); 1002 | 1003 | expect(configs.isIgnored(filename)).to.be.false; 1004 | }); 1005 | 1006 | it('should return true when passed ignored .gitignore filename', () => { 1007 | const filename = path.resolve(basePath, '.gitignore'); 1008 | 1009 | expect(configs.isIgnored(filename)).to.be.true; 1010 | }); 1011 | 1012 | it('should return false when passed CSS filename', () => { 1013 | const filename = path.resolve(basePath, 'foo.css'); 1014 | 1015 | expect(configs.isIgnored(filename)).to.be.false; 1016 | }); 1017 | 1018 | it('should return true when passed docx filename', () => { 1019 | const filename = path.resolve(basePath, 'sss.docx'); 1020 | 1021 | expect(configs.isIgnored(filename)).to.be.false; 1022 | }); 1023 | 1024 | it('should return true when passed ignored node_modules filename', () => { 1025 | const filename = path.resolve(basePath, 'node_modules/foo.js'); 1026 | 1027 | expect(configs.isIgnored(filename)).to.be.true; 1028 | }); 1029 | 1030 | it('should return true when passed matching both files and ignores in a config', () => { 1031 | configs = new ConfigArray([ 1032 | { 1033 | files: ['**/*.xsl'], 1034 | ignores: ['fixtures/test.xsl'], 1035 | defs: { 1036 | xsl: true 1037 | } 1038 | } 1039 | ], { basePath }); 1040 | 1041 | configs.normalizeSync(); 1042 | const filename = path.resolve(basePath, 'fixtures/test.xsl'); 1043 | 1044 | expect(configs.isIgnored(filename)).to.be.true; 1045 | }); 1046 | 1047 | it('should return false when negated pattern comes after matching pattern', () => { 1048 | configs = new ConfigArray([ 1049 | { 1050 | files: ['**/foo.*'], 1051 | ignores: ['**/*.txt', '!foo.txt'] 1052 | } 1053 | ], { 1054 | basePath 1055 | }); 1056 | 1057 | configs.normalizeSync(); 1058 | 1059 | expect(configs.isIgnored(path.join(basePath, 'bar.txt'))).to.be.true; 1060 | expect(configs.isIgnored(path.join(basePath, 'foo.txt'))).to.be.false; 1061 | }); 1062 | 1063 | it('should return true when negated pattern comes before matching pattern', () => { 1064 | configs = new ConfigArray([ 1065 | { 1066 | ignores: ['!foo.txt', '**/*.txt'] 1067 | } 1068 | ], { 1069 | basePath 1070 | }); 1071 | 1072 | configs.normalizeSync(); 1073 | 1074 | expect(configs.isIgnored(path.join(basePath, 'bar.txt'))).to.be.true; 1075 | expect(configs.isIgnored(path.join(basePath, 'foo.txt'))).to.be.true; 1076 | }); 1077 | 1078 | it('should return false when matching files and ignores has a negated pattern comes after matching pattern', () => { 1079 | configs = new ConfigArray([ 1080 | { 1081 | files: ['**/*.js'], 1082 | ignores: ['**/*.test.js', '!foo.test.js'] 1083 | } 1084 | ], { 1085 | basePath 1086 | }); 1087 | 1088 | configs.normalizeSync(); 1089 | 1090 | expect(configs.isIgnored(path.join(basePath, 'bar.test.js'))).to.be.true; 1091 | expect(configs.isIgnored(path.join(basePath, 'foo.test.js'))).to.be.false; 1092 | }); 1093 | 1094 | }); 1095 | 1096 | describe('isFileIgnored()', () => { 1097 | 1098 | it('should throw an error when not normalized', () => { 1099 | const filename = path.resolve(basePath, 'foo.js'); 1100 | 1101 | expect(() => { 1102 | unnormalizedConfigs.isFileIgnored(filename); 1103 | }) 1104 | .to 1105 | .throw(/normalized/); 1106 | }); 1107 | 1108 | it('should return false when passed JS filename', () => { 1109 | const filename = path.resolve(basePath, 'foo.js'); 1110 | 1111 | expect(configs.isFileIgnored(filename)).to.be.false; 1112 | }); 1113 | 1114 | it('should return true when passed JS filename in parent directory', () => { 1115 | const filename = path.resolve(basePath, '../foo.js'); 1116 | 1117 | expect(configs.isFileIgnored(filename)).to.be.true; 1118 | }); 1119 | 1120 | it('should return false when passed HTML filename', () => { 1121 | const filename = path.resolve(basePath, 'foo.html'); 1122 | 1123 | expect(configs.isFileIgnored(filename)).to.be.false; 1124 | }); 1125 | 1126 | it('should return true when passed ignored .gitignore filename', () => { 1127 | const filename = path.resolve(basePath, '.gitignore'); 1128 | 1129 | expect(configs.isFileIgnored(filename)).to.be.true; 1130 | }); 1131 | 1132 | it('should return false when passed CSS filename', () => { 1133 | const filename = path.resolve(basePath, 'foo.css'); 1134 | 1135 | expect(configs.isFileIgnored(filename)).to.be.false; 1136 | }); 1137 | 1138 | it('should return true when passed docx filename', () => { 1139 | const filename = path.resolve(basePath, 'sss.docx'); 1140 | 1141 | expect(configs.isFileIgnored(filename)).to.be.false; 1142 | }); 1143 | 1144 | it('should return true when passed ignored node_modules filename', () => { 1145 | const filename = path.resolve(basePath, 'node_modules/foo.js'); 1146 | 1147 | expect(configs.isFileIgnored(filename)).to.be.true; 1148 | }); 1149 | 1150 | it('should return true when passed matching both files and ignores in a config', () => { 1151 | configs = new ConfigArray([ 1152 | { 1153 | files: ['**/*.xsl'], 1154 | ignores: ['fixtures/test.xsl'], 1155 | defs: { 1156 | xsl: true 1157 | } 1158 | } 1159 | ], { basePath }); 1160 | 1161 | configs.normalizeSync(); 1162 | const filename = path.resolve(basePath, 'fixtures/test.xsl'); 1163 | 1164 | expect(configs.isFileIgnored(filename)).to.be.true; 1165 | }); 1166 | 1167 | it('should return false when negated pattern comes after matching pattern', () => { 1168 | configs = new ConfigArray([ 1169 | { 1170 | files: ['**/foo.*'], 1171 | ignores: ['**/*.txt', '!foo.txt'] 1172 | } 1173 | ], { 1174 | basePath 1175 | }); 1176 | 1177 | configs.normalizeSync(); 1178 | 1179 | expect(configs.isFileIgnored(path.join(basePath, 'bar.txt'))).to.be.true; 1180 | expect(configs.isFileIgnored(path.join(basePath, 'foo.txt'))).to.be.false; 1181 | }); 1182 | 1183 | it('should return true when negated pattern comes before matching pattern', () => { 1184 | configs = new ConfigArray([ 1185 | { 1186 | ignores: ['!foo.txt', '**/*.txt'] 1187 | } 1188 | ], { 1189 | basePath 1190 | }); 1191 | 1192 | configs.normalizeSync(); 1193 | 1194 | expect(configs.isFileIgnored(path.join(basePath, 'bar.txt'))).to.be.true; 1195 | expect(configs.isFileIgnored(path.join(basePath, 'foo.txt'))).to.be.true; 1196 | }); 1197 | 1198 | it('should return false when matching files and ignores has a negated pattern comes after matching pattern', () => { 1199 | configs = new ConfigArray([ 1200 | { 1201 | files: ['**/*.js'], 1202 | ignores: ['**/*.test.js', '!foo.test.js'] 1203 | } 1204 | ], { 1205 | basePath 1206 | }); 1207 | 1208 | configs.normalizeSync(); 1209 | 1210 | expect(configs.isFileIgnored(path.join(basePath, 'bar.test.js'))).to.be.true; 1211 | expect(configs.isFileIgnored(path.join(basePath, 'foo.test.js'))).to.be.false; 1212 | }); 1213 | 1214 | it('should return false when file is inside of ignored directory', () => { 1215 | configs = new ConfigArray([ 1216 | { 1217 | ignores: ['ignoreme'] 1218 | }, 1219 | { 1220 | files: ['**/*.js'] 1221 | } 1222 | ], { 1223 | basePath 1224 | }); 1225 | 1226 | configs.normalizeSync(); 1227 | 1228 | expect(configs.isFileIgnored(path.join(basePath, 'ignoreme/foo.js'))).to.be.true; 1229 | }); 1230 | 1231 | it('should return false when file is inside of ignored directory', () => { 1232 | configs = new ConfigArray([ 1233 | { 1234 | files: ['**/*.js'] 1235 | }, 1236 | { 1237 | ignores: [ 1238 | 'foo/*', 1239 | '!foo/bar' 1240 | ] 1241 | } 1242 | ], { 1243 | basePath 1244 | }); 1245 | 1246 | configs.normalizeSync(); 1247 | 1248 | expect(configs.isFileIgnored(path.join(basePath, 'foo/bar/a.js'))).to.be.false; 1249 | }); 1250 | 1251 | it('should return true when file is ignored, unignored, and then reignored', () => { 1252 | configs = new ConfigArray([ 1253 | { 1254 | files: ['**/*.js'] 1255 | }, 1256 | { 1257 | ignores: [ 1258 | 'a.js', 1259 | '!a*.js', 1260 | 'a.js' 1261 | ] 1262 | } 1263 | ], { 1264 | basePath 1265 | }); 1266 | 1267 | configs.normalizeSync(); 1268 | 1269 | expect(configs.isFileIgnored(path.join(basePath, 'a.js'))).to.be.true; 1270 | }); 1271 | 1272 | it('should return true when the parent directory of a file is ignored', () => { 1273 | configs = new ConfigArray([ 1274 | { 1275 | files: ['**/*.js'] 1276 | }, 1277 | { 1278 | ignores: [ 1279 | 'foo' 1280 | ] 1281 | } 1282 | ], { 1283 | basePath 1284 | }); 1285 | 1286 | configs.normalizeSync(); 1287 | 1288 | expect(configs.isFileIgnored(path.join(basePath, 'foo/bar/a.js'))).to.be.true; 1289 | }); 1290 | 1291 | it('should return true when an ignored directory is later negated with **', () => { 1292 | configs = new ConfigArray([ 1293 | { 1294 | files: ['**/*.js'] 1295 | }, 1296 | { 1297 | ignores: [ 1298 | '**/node_modules/**' 1299 | ] 1300 | }, 1301 | { 1302 | ignores: [ 1303 | '!node_modules/package/**' 1304 | ] 1305 | } 1306 | ], { 1307 | basePath 1308 | }); 1309 | 1310 | configs.normalizeSync(); 1311 | 1312 | expect(configs.isFileIgnored(path.join(basePath, 'node_modules/package/a.js'))).to.be.true; 1313 | }); 1314 | 1315 | it('should return true when an ignored directory is later negated with *', () => { 1316 | configs = new ConfigArray([ 1317 | { 1318 | files: ['**/*.js'] 1319 | }, 1320 | { 1321 | ignores: [ 1322 | '**/node_modules/**' 1323 | ] 1324 | }, 1325 | { 1326 | ignores: [ 1327 | '!node_modules/package/*' 1328 | ] 1329 | } 1330 | ], { 1331 | basePath 1332 | }); 1333 | 1334 | configs.normalizeSync(); 1335 | 1336 | expect(configs.isFileIgnored(path.join(basePath, 'node_modules/package/a.js'))).to.be.true; 1337 | }); 1338 | 1339 | it('should return true when there are only patterns ending with /*', () => { 1340 | configs = new ConfigArray([ 1341 | { 1342 | files: ['foo/*'] 1343 | } 1344 | ], { 1345 | basePath 1346 | }); 1347 | 1348 | configs.normalizeSync(); 1349 | 1350 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.true; 1351 | }); 1352 | 1353 | it('should return true when there are only patterns ending with /**', () => { 1354 | configs = new ConfigArray([ 1355 | { 1356 | files: ['foo/**'] 1357 | } 1358 | ], { 1359 | basePath 1360 | }); 1361 | 1362 | configs.normalizeSync(); 1363 | 1364 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.true; 1365 | }); 1366 | 1367 | it('should return false when files pattern matches and there is a pattern ending with /**', () => { 1368 | configs = new ConfigArray([ 1369 | { 1370 | files: ['foo/*.js', 'foo/**'] 1371 | } 1372 | ], { 1373 | basePath 1374 | }); 1375 | 1376 | configs.normalizeSync(); 1377 | 1378 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.false; 1379 | }); 1380 | 1381 | it('should return false when file has the same name as a directory that is ignored by a pattern that ends with `/`', () => { 1382 | configs = new ConfigArray([ 1383 | { 1384 | files: ['**/foo'] 1385 | }, 1386 | { 1387 | ignores: [ 1388 | 'foo/' 1389 | ] 1390 | } 1391 | ], { 1392 | basePath 1393 | }); 1394 | 1395 | configs.normalizeSync(); 1396 | 1397 | expect(configs.isFileIgnored(path.join(basePath, 'foo'))).to.be.false; 1398 | }); 1399 | 1400 | it('should return false when file is in the parent directory of directories that are ignored by a pattern that ends with `/`', () => { 1401 | configs = new ConfigArray([ 1402 | { 1403 | files: ['**/*.js'] 1404 | }, 1405 | { 1406 | ignores: [ 1407 | 'foo/*/' 1408 | ] 1409 | } 1410 | ], { 1411 | basePath 1412 | }); 1413 | 1414 | configs.normalizeSync(); 1415 | 1416 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.false; 1417 | }); 1418 | 1419 | it('should return true when file is in a directory that is ignored by a pattern that ends with `/`', () => { 1420 | configs = new ConfigArray([ 1421 | { 1422 | files: ['**/*.js'] 1423 | }, 1424 | { 1425 | ignores: [ 1426 | 'foo/' 1427 | ] 1428 | } 1429 | ], { 1430 | basePath 1431 | }); 1432 | 1433 | configs.normalizeSync(); 1434 | 1435 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.true; 1436 | }); 1437 | 1438 | it('should return true when file is in a directory that is ignored by a pattern that does not end with `/`', () => { 1439 | configs = new ConfigArray([ 1440 | { 1441 | files: ['**/*.js'] 1442 | }, 1443 | { 1444 | ignores: [ 1445 | 'foo' 1446 | ] 1447 | } 1448 | ], { 1449 | basePath 1450 | }); 1451 | 1452 | configs.normalizeSync(); 1453 | 1454 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.true; 1455 | }); 1456 | 1457 | it('should return false when file is in a directory that is ignored and then unignored by pattern that end with `/`', () => { 1458 | configs = new ConfigArray([ 1459 | { 1460 | files: ['**/*.js'] 1461 | }, 1462 | { 1463 | ignores: [ 1464 | 'foo/', 1465 | '!foo/' 1466 | ] 1467 | } 1468 | ], { 1469 | basePath 1470 | }); 1471 | 1472 | configs.normalizeSync(); 1473 | 1474 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.false; 1475 | }); 1476 | 1477 | it('should return true when file is in a directory that is ignored along with its files by a pattern that ends with `/**` and then unignored by pattern that ends with `/`', () => { 1478 | configs = new ConfigArray([ 1479 | { 1480 | files: ['**/*.js'] 1481 | }, 1482 | { 1483 | ignores: [ 1484 | 'foo/**', 1485 | 1486 | // only the directory is unignored, files are not 1487 | '!foo/' 1488 | ] 1489 | } 1490 | ], { 1491 | basePath 1492 | }); 1493 | 1494 | configs.normalizeSync(); 1495 | 1496 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.true; 1497 | }); 1498 | 1499 | it('should return true when file is in a directory that is ignored along with its files by a pattern that ends with `/**` and then unignored by pattern that does not end with `/`', () => { 1500 | configs = new ConfigArray([ 1501 | { 1502 | files: ['**/*.js'] 1503 | }, 1504 | { 1505 | ignores: [ 1506 | 'foo/**', 1507 | 1508 | // only the directory is unignored, files are not 1509 | '!foo' 1510 | ] 1511 | } 1512 | ], { 1513 | basePath 1514 | }); 1515 | 1516 | configs.normalizeSync(); 1517 | 1518 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.true; 1519 | }); 1520 | 1521 | it('should return false when file is in a directory that is ignored along its files by pattern that ends with `/**` and then unignored along its files by pattern that ends with `/**`', () => { 1522 | configs = new ConfigArray([ 1523 | { 1524 | files: ['**/*.js'] 1525 | }, 1526 | { 1527 | ignores: [ 1528 | 'foo/**', 1529 | 1530 | // both the directory and the files are unignored 1531 | '!foo/**' 1532 | ] 1533 | } 1534 | ], { 1535 | basePath 1536 | }); 1537 | 1538 | configs.normalizeSync(); 1539 | 1540 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.false; 1541 | }); 1542 | 1543 | it('should return true when file is ignored by a pattern and there are unignore patterns that target files of a directory with the same name', () => { 1544 | configs = new ConfigArray([ 1545 | { 1546 | files: ['**/foo'] 1547 | }, 1548 | { 1549 | ignores: [ 1550 | 'foo', 1551 | '!foo/*', 1552 | '!foo/**' 1553 | ] 1554 | } 1555 | ], { 1556 | basePath 1557 | }); 1558 | 1559 | configs.normalizeSync(); 1560 | 1561 | expect(configs.isFileIgnored(path.join(basePath, 'foo'))).to.be.true; 1562 | }); 1563 | 1564 | it('should return true when file is in a directory that is ignored even if an unignore pattern that ends with `/*` matches the file', () => { 1565 | configs = new ConfigArray([ 1566 | { 1567 | files: ['**/*.js'] 1568 | }, 1569 | { 1570 | ignores: [ 1571 | 'foo', 1572 | '!foo/*' 1573 | ] 1574 | } 1575 | ], { 1576 | basePath 1577 | }); 1578 | 1579 | configs.normalizeSync(); 1580 | 1581 | expect(configs.isFileIgnored(path.join(basePath, 'foo/a.js'))).to.be.true; 1582 | }); 1583 | 1584 | // https://github.com/eslint/eslint/issues/17964#issuecomment-1879840650 1585 | it('should return true for all files ignored in a directory tree except for explicitly unignored ones', () => { 1586 | configs = new ConfigArray([ 1587 | { 1588 | files: ['**/*.js'] 1589 | }, 1590 | { 1591 | ignores: [ 1592 | 1593 | // ignore all files and directories 1594 | 'tests/format/**/*', 1595 | 1596 | // unignore all directories 1597 | '!tests/format/**/*/', 1598 | 1599 | // unignore specific files 1600 | '!tests/format/**/jsfmt.spec.js' 1601 | ] 1602 | } 1603 | ], { 1604 | basePath 1605 | }); 1606 | 1607 | configs.normalizeSync(); 1608 | 1609 | expect(configs.isFileIgnored(path.join(basePath, 'tests/format/foo.js'))).to.be.true; 1610 | expect(configs.isFileIgnored(path.join(basePath, 'tests/format/jsfmt.spec.js'))).to.be.false; 1611 | expect(configs.isFileIgnored(path.join(basePath, 'tests/format/subdir/foo.js'))).to.be.true; 1612 | expect(configs.isFileIgnored(path.join(basePath, 'tests/format/subdir/jsfmt.spec.js'))).to.be.false; 1613 | }); 1614 | 1615 | // https://github.com/eslint/eslint/pull/16579/files 1616 | describe('gitignore-style unignores', () => { 1617 | 1618 | it('should return true when a subdirectory is ignored and then we try to unignore a directory', () => { 1619 | configs = new ConfigArray([ 1620 | { 1621 | ignores: [ 1622 | '/**/node_modules/*', 1623 | '!/node_modules/foo' 1624 | ], 1625 | } 1626 | ], { basePath }); 1627 | 1628 | configs.normalizeSync(); 1629 | const filename = path.resolve(basePath, 'node_modules/foo/bar.js'); 1630 | 1631 | expect(configs.isFileIgnored(filename)).to.be.true; 1632 | }); 1633 | 1634 | it('should return true when a subdirectory is ignored and then we try to unignore a file', () => { 1635 | configs = new ConfigArray([ 1636 | { 1637 | ignores: [ 1638 | '/**/node_modules/*', 1639 | '!/node_modules/foo/**' 1640 | ], 1641 | } 1642 | ], { basePath }); 1643 | 1644 | configs.normalizeSync(); 1645 | const filename = path.resolve(basePath, 'node_modules/foo/bar.js'); 1646 | 1647 | expect(configs.isFileIgnored(filename)).to.be.true; 1648 | }); 1649 | 1650 | it('should return true when all descendant directories are ignored and then we try to unignore a file', () => { 1651 | configs = new ConfigArray([ 1652 | { 1653 | ignores: [ 1654 | '/**/node_modules/**', 1655 | '!/node_modules/foo/**' 1656 | ], 1657 | } 1658 | ], { basePath }); 1659 | 1660 | configs.normalizeSync(); 1661 | const filename = path.resolve(basePath, 'node_modules/foo/bar.js'); 1662 | 1663 | expect(configs.isFileIgnored(filename)).to.be.true; 1664 | }); 1665 | 1666 | it('should return true when all descendant directories are ignored without leading slash and then we try to unignore a file', () => { 1667 | configs = new ConfigArray([ 1668 | { 1669 | ignores: [ 1670 | '**/node_modules/**', 1671 | '!/node_modules/foo/**' 1672 | ], 1673 | } 1674 | ], { basePath }); 1675 | 1676 | configs.normalizeSync(); 1677 | const filename = path.resolve(basePath, 'node_modules/foo/bar.js'); 1678 | 1679 | expect(configs.isFileIgnored(filename)).to.be.true; 1680 | }); 1681 | }); 1682 | 1683 | }); 1684 | 1685 | describe('isDirectoryIgnored()', () => { 1686 | 1687 | it('should return true when a function return false in ignores', () => { 1688 | configs = new ConfigArray([ 1689 | { 1690 | ignores: [directoryPath => directoryPath.includes('node_modules')] 1691 | } 1692 | ], { 1693 | basePath 1694 | }); 1695 | 1696 | configs.normalizeSync(); 1697 | 1698 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules')), 'No trailing slash').to.be.true; 1699 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/'), 'Trailing slash').to.be.true; 1700 | 1701 | }); 1702 | 1703 | it('should return true when a directory is in ignores', () => { 1704 | configs = new ConfigArray([ 1705 | { 1706 | ignores: ['**/node_modules'] 1707 | } 1708 | ], { 1709 | basePath 1710 | }); 1711 | 1712 | configs.normalizeSync(); 1713 | 1714 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules')), 'No trailing slash').to.be.true; 1715 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/'), 'Trailing slash').to.be.true; 1716 | 1717 | }); 1718 | 1719 | it('should return true when a directory with a trailing slash is in ignores', () => { 1720 | configs = new ConfigArray([ 1721 | { 1722 | ignores: ['**/node_modules/'] 1723 | } 1724 | ], { 1725 | basePath 1726 | }); 1727 | 1728 | configs.normalizeSync(); 1729 | 1730 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules'))).to.be.true; 1731 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/'), 'Trailing slash').to.be.true; 1732 | }); 1733 | 1734 | it('should return true when a directory followed by ** is in ignores', () => { 1735 | configs = new ConfigArray([ 1736 | { 1737 | ignores: ['**/node_modules/**'] 1738 | } 1739 | ], { 1740 | basePath 1741 | }); 1742 | 1743 | configs.normalizeSync(); 1744 | 1745 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules'))).to.be.true; 1746 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/')).to.be.true; 1747 | 1748 | }); 1749 | 1750 | it('should return false when there is a files entry', () => { 1751 | configs = new ConfigArray([ 1752 | { 1753 | files: ['**/*.js'], 1754 | ignores: ['**/node_modules'] 1755 | } 1756 | ], { 1757 | basePath 1758 | }); 1759 | 1760 | configs.normalizeSync(); 1761 | 1762 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules'))).to.be.false; 1763 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/'), 'Trailing slash').to.be.false; 1764 | }); 1765 | 1766 | it('should return true when directory matches and there is a negated pattern', () => { 1767 | configs = new ConfigArray([ 1768 | { 1769 | ignores: ['**/foo/', '!**/node_modules'] 1770 | } 1771 | ], { 1772 | basePath 1773 | }); 1774 | 1775 | configs.normalizeSync(); 1776 | 1777 | expect(configs.isDirectoryIgnored(path.join(basePath, 'foo'))).to.be.true; 1778 | expect(configs.isDirectoryIgnored(path.join(basePath, 'foo') + '/'), 'Trailing slash').to.be.true; 1779 | }); 1780 | 1781 | it('should return false when directory doesn\'t match and there is a negated pattern', () => { 1782 | configs = new ConfigArray([ 1783 | { 1784 | ignores: ['**/foo/', '!**/node_modules'] 1785 | } 1786 | ], { 1787 | basePath 1788 | }); 1789 | 1790 | configs.normalizeSync(); 1791 | 1792 | expect(configs.isDirectoryIgnored(path.join(basePath, 'bar'))).to.be.false; 1793 | expect(configs.isDirectoryIgnored(path.join(basePath, 'bar') + '/'), 'Trailing slash').to.be.false; 1794 | }); 1795 | 1796 | it('should return false when ignored directory is unignored', () => { 1797 | configs = new ConfigArray([ 1798 | { 1799 | ignores: [ 1800 | 'foo/*', 1801 | '!foo/bar' 1802 | ] 1803 | } 1804 | ], { 1805 | basePath 1806 | }); 1807 | 1808 | configs.normalizeSync(); 1809 | 1810 | expect(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar'))).to.be.false; 1811 | expect(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar/'))).to.be.false; 1812 | }); 1813 | 1814 | 1815 | it('should return true when there is a directory relative to basePath in ignores', () => { 1816 | configs = new ConfigArray([ 1817 | { 1818 | ignores: ['foo/bar'] 1819 | } 1820 | ], { 1821 | basePath 1822 | }); 1823 | 1824 | configs.normalizeSync(); 1825 | 1826 | expect(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar'))).to.be.true; 1827 | expect(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar') + '/'), 'Trailing slash').to.be.true; 1828 | }); 1829 | 1830 | it('should throw an error when the config array isn\'t normalized', () => { 1831 | configs = new ConfigArray([ 1832 | { 1833 | ignores: ['foo/bar'] 1834 | } 1835 | ], { 1836 | basePath 1837 | }); 1838 | 1839 | expect(() => { 1840 | configs.isDirectoryIgnored('foo/bar'); 1841 | }).throws(/normalized/); 1842 | }); 1843 | 1844 | it('should return true when the directory is outside of the basePath', () => { 1845 | configs = new ConfigArray([ 1846 | { 1847 | ignores: ['foo/bar'] 1848 | } 1849 | ], { 1850 | basePath 1851 | }); 1852 | 1853 | configs.normalizeSync(); 1854 | 1855 | expect(configs.isDirectoryIgnored(path.resolve(basePath, '../foo/bar'))).to.be.true; 1856 | }); 1857 | 1858 | it('should return true when the parent directory of a directory is ignored', () => { 1859 | configs = new ConfigArray([ 1860 | { 1861 | files: ['**/*.js'] 1862 | }, 1863 | { 1864 | ignores: [ 1865 | 'foo' 1866 | ] 1867 | } 1868 | ], { 1869 | basePath 1870 | }); 1871 | 1872 | configs.normalizeSync(); 1873 | 1874 | expect(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar'))).to.be.true; 1875 | expect(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar/'))).to.be.true; 1876 | }); 1877 | 1878 | 1879 | it('should return true when a directory in an ignored directory is later negated with **', () => { 1880 | configs = new ConfigArray([ 1881 | { 1882 | files: ['**/*.js'] 1883 | }, 1884 | { 1885 | ignores: [ 1886 | '**/node_modules/**' 1887 | ] 1888 | }, 1889 | { 1890 | ignores: [ 1891 | 1892 | // this unignores `node_modules/package/`, but its parent `node_modules/` is still ignored 1893 | '!node_modules/package/**' 1894 | ] 1895 | } 1896 | ], { 1897 | basePath 1898 | }); 1899 | 1900 | configs.normalizeSync(); 1901 | 1902 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/package'))).to.be.true; 1903 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/package/'))).to.be.true; 1904 | }); 1905 | 1906 | it('should return false when a directory is later negated with **', () => { 1907 | configs = new ConfigArray([ 1908 | { 1909 | files: ['**/*.js'] 1910 | }, 1911 | { 1912 | ignores: [ 1913 | '**/node_modules/**' 1914 | ] 1915 | }, 1916 | { 1917 | ignores: [ 1918 | '!node_modules/**' 1919 | ] 1920 | } 1921 | ], { 1922 | basePath 1923 | }); 1924 | 1925 | configs.normalizeSync(); 1926 | 1927 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules'))).to.be.false; 1928 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/'))).to.be.false; 1929 | }); 1930 | 1931 | it('should return true when a directory\'s content is later negated with *', () => { 1932 | configs = new ConfigArray([ 1933 | { 1934 | files: ['**/*.js'] 1935 | }, 1936 | { 1937 | ignores: [ 1938 | '**/node_modules/**' 1939 | ] 1940 | }, 1941 | { 1942 | ignores: [ 1943 | '!node_modules/*' 1944 | ] 1945 | } 1946 | ], { 1947 | basePath 1948 | }); 1949 | 1950 | configs.normalizeSync(); 1951 | 1952 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules'))).to.be.true; 1953 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/'))).to.be.true; 1954 | }); 1955 | 1956 | it('should return true when an ignored directory is later unignored with *', () => { 1957 | configs = new ConfigArray([ 1958 | { 1959 | files: ['**/*.js'] 1960 | }, 1961 | { 1962 | ignores: [ 1963 | '**/node_modules/**' 1964 | ] 1965 | }, 1966 | { 1967 | ignores: [ 1968 | '!node_modules/package/*' 1969 | ] 1970 | } 1971 | ], { 1972 | basePath 1973 | }); 1974 | 1975 | configs.normalizeSync(); 1976 | 1977 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/package'))).to.be.true; 1978 | expect(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/package/'))).to.be.true; 1979 | }); 1980 | 1981 | // https://github.com/eslint/eslint/pull/16579/files 1982 | describe('gitignore-style unignores', () => { 1983 | 1984 | it('should return false when first-level subdirectories are ignored and then one is negated', () => { 1985 | configs = new ConfigArray([ 1986 | { 1987 | ignores: [ 1988 | '**/node_modules/*', 1989 | '!**/node_modules/foo/' 1990 | ], 1991 | } 1992 | ], { basePath }); 1993 | 1994 | configs.normalizeSync(); 1995 | const directoryPath = path.resolve(basePath, 'node_modules/foo'); 1996 | 1997 | expect(configs.isDirectoryIgnored(directoryPath)).to.be.false; 1998 | }); 1999 | 2000 | it('should return false when first-level subdirectories are ignored with leading slash and then one is negated', () => { 2001 | configs = new ConfigArray([ 2002 | { 2003 | ignores: [ 2004 | '/**/node_modules/*', 2005 | '!**/node_modules/foo/' 2006 | ], 2007 | } 2008 | ], { basePath }); 2009 | 2010 | configs.normalizeSync(); 2011 | const directoryPath = path.resolve(basePath, 'node_modules/foo'); 2012 | 2013 | expect(configs.isDirectoryIgnored(directoryPath)).to.be.false; 2014 | }); 2015 | 2016 | it('should return true when all descendant subdirectories are ignored and then one is negated', () => { 2017 | configs = new ConfigArray([ 2018 | { 2019 | ignores: [ 2020 | '**/node_modules/**', 2021 | '!**/node_modules/foo/' 2022 | ], 2023 | } 2024 | ], { basePath }); 2025 | 2026 | configs.normalizeSync(); 2027 | const directoryPath = path.resolve(basePath, 'node_modules/foo'); 2028 | 2029 | expect(configs.isDirectoryIgnored(directoryPath)).to.be.true; 2030 | }); 2031 | 2032 | it('should return true when all descendant subdirectories are ignored and then other descendants are negated', () => { 2033 | configs = new ConfigArray([ 2034 | { 2035 | ignores: [ 2036 | '**/node_modules/**', 2037 | '!**/node_modules/foo/**' 2038 | ], 2039 | } 2040 | ], { basePath }); 2041 | 2042 | configs.normalizeSync(); 2043 | const directoryPath = path.resolve(basePath, 'node_modules/foo'); 2044 | 2045 | expect(configs.isDirectoryIgnored(directoryPath)).to.be.true; 2046 | }); 2047 | }); 2048 | 2049 | }); 2050 | 2051 | describe('isExplicitMatch()', () => { 2052 | 2053 | it('should throw an error when not normalized', () => { 2054 | const filename = path.resolve(basePath, 'foo.js'); 2055 | 2056 | expect(() => { 2057 | unnormalizedConfigs.isExplicitMatch(filename); 2058 | }) 2059 | .to 2060 | .throw(/normalized/); 2061 | }); 2062 | 2063 | it('should return true when passed JS filename', () => { 2064 | const filename = path.resolve(basePath, 'foo.js'); 2065 | 2066 | expect(configs.isExplicitMatch(filename)).to.be.true; 2067 | }); 2068 | 2069 | it('should return true when passed HTML filename', () => { 2070 | const filename = path.resolve(basePath, 'foo.html'); 2071 | 2072 | expect(configs.isExplicitMatch(filename)).to.be.true; 2073 | }); 2074 | 2075 | it('should return true when passed CSS filename', () => { 2076 | const filename = path.resolve(basePath, 'foo.css'); 2077 | 2078 | expect(configs.isExplicitMatch(filename)).to.be.true; 2079 | }); 2080 | 2081 | it('should return true when passed EXE filename because it matches !.css', () => { 2082 | const filename = path.resolve(basePath, 'foo.exe'); 2083 | 2084 | expect(configs.isExplicitMatch(filename)).to.be.true; 2085 | }); 2086 | 2087 | it('should return false when passed EXE filename because no explicit matches', () => { 2088 | const filename = path.resolve(basePath, 'foo.exe'); 2089 | configs = new ConfigArray([ 2090 | { 2091 | files: ['*.js'] 2092 | } 2093 | ], { 2094 | basePath 2095 | }); 2096 | configs.normalizeSync(); 2097 | 2098 | expect(configs.isExplicitMatch(filename)).to.be.false; 2099 | }); 2100 | 2101 | it('should return false when passed matching both files and ignores in a config', () => { 2102 | configs = new ConfigArray([ 2103 | { 2104 | files: ['**/*.xsl'], 2105 | ignores: ['fixtures/test.xsl'], 2106 | defs: { 2107 | xsl: true 2108 | } 2109 | } 2110 | ], { basePath }); 2111 | 2112 | configs.normalizeSync(); 2113 | const filename = path.resolve(basePath, 'fixtures/test.xsl'); 2114 | 2115 | expect(configs.isExplicitMatch(filename)).to.be.false; 2116 | }); 2117 | 2118 | }); 2119 | 2120 | describe('files', () => { 2121 | 2122 | it('should throw an error when not normalized', () => { 2123 | expect(() => { 2124 | unnormalizedConfigs.files; 2125 | }) 2126 | .to 2127 | .throw(/normalized/); 2128 | }); 2129 | 2130 | it('should return all string pattern file from all configs when called', () => { 2131 | const expectedFiles = configs.reduce((list, config) => { 2132 | if (config.files) { 2133 | list.push(...config.files); 2134 | } 2135 | 2136 | return list; 2137 | }, []); 2138 | const files = configs.files; 2139 | expect(files).to.deep.equal(expectedFiles); 2140 | 2141 | }); 2142 | }); 2143 | 2144 | describe('ignores', () => { 2145 | 2146 | it('should throw an error when not normalized', () => { 2147 | expect(() => { 2148 | unnormalizedConfigs.ignores; 2149 | }) 2150 | .to 2151 | .throw(/normalized/); 2152 | }); 2153 | 2154 | it('should return all ignores from all configs without files when called', () => { 2155 | const expectedIgnores = configs.reduce((list, config) => { 2156 | if (config.ignores && Object.keys(config).length === 1) { 2157 | list.push(...config.ignores); 2158 | } 2159 | 2160 | return list; 2161 | }, []); 2162 | const ignores = configs.ignores; 2163 | expect(ignores).to.deep.equal(expectedIgnores); 2164 | 2165 | }); 2166 | 2167 | it('should ignore name field for when considering global ignores', () => { 2168 | configs = new ConfigArray([ 2169 | { 2170 | name: 'foo', 2171 | ignores: ['ignoreme'] 2172 | }, 2173 | ], { 2174 | basePath 2175 | }); 2176 | 2177 | configs.normalizeSync(); 2178 | 2179 | expect(configs.isFileIgnored(path.join(basePath, 'ignoreme/foo.js'))).to.be.true; 2180 | expect(configs.ignores).to.eql(['ignoreme']); 2181 | }); 2182 | }); 2183 | 2184 | describe('push()', () => { 2185 | 2186 | it('should throw an error when normalized', () => { 2187 | expect(() => { 2188 | configs.push({}); 2189 | }) 2190 | .to 2191 | .throw(/extensible/); 2192 | }); 2193 | 2194 | }); 2195 | 2196 | }); 2197 | 2198 | }); 2199 | --------------------------------------------------------------------------------