Skip to content

Commit

Permalink
Add file extension support (#144)
Browse files Browse the repository at this point in the history
Co-authored-by: XhmikosR <xhmikosr@gmail.com>
  • Loading branch information
GeoSot and XhmikosR authored Aug 3, 2021
1 parent 402d81b commit 4bd4e68
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 12 deletions.
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ npm install find-unused-sass-variables --save-dev
## Usage

```shell
find-unused-sass-variables folder [, folder2...] --ignore "$my-var,$my-second-var"
find-unused-sass-variables folder [, folder2...] --ignore "$my-var,$my-second-var" -e scss -e css
# or
fusv folder [, folder2...]
```
Expand All @@ -38,9 +38,13 @@ console.log(unused.total);
const ignoredVars = ['$my-var', '$my-second-var']
unused = fusv.find('scss', { ignore: ignoredVars })

// Use Asynchornous
// specifing file extensions
unused = fusv.find('scss', { fileExtensions: ['css','scss']})

// asynchornous usage
let unused = await fusv.findAsync('directory')
// or like Promise

// or like a Promise
let unused = fusv.findAsync('directory').then(result => {
console.log(unused.unused);
})
Expand All @@ -65,6 +69,10 @@ Returns a Promise which resolves result; is the same as `find(dir, options)` res

Array of strings of the variables to ignore, e.g. `['$my-var', '$my-second-var']`

#### options.fileExtensions

Array of file extensions to search for unused variables in. e.g. `['scss']`

## Disable & enable

Disable or enable `fusv` with the `fusv-disable` and `fusv-enable` comments:
Expand Down
15 changes: 10 additions & 5 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,20 @@ program
.arguments('[folders]')
.version(version, '-v, --version')
.option('-i, --ignore <ignoredVars>', 'ignore variables, comma separated', '')
.option('-e, --extension [fileTypes...]', 'file extension to search', ['scss'])
.parse();

async function main() {
const directories = program.args;
const ignore = program.opts().ignore.split(',');
const programOptions = program.opts();
const options = {
ignore: programOptions.ignore.split(','),
fileExtensions: programOptions.extension
};

console.log('Looking for unused variables');

const executions = await Promise.allSettled(directories.map(path => executeForPath(path, ignore)));
const executions = await Promise.allSettled(directories.map(path => executeForPath(path, options)));

let status = 0;

Expand All @@ -36,11 +41,11 @@ async function main() {
process.exit(status);
}

const executeForPath = async(arg, ignore) => {
const executeForPath = async(arg, options) => {
const dir = path.resolve(arg);
const unusedVars = await fusv.findAsync(dir, { ignore });
const unusedVars = await fusv.findAsync(dir, options);

console.log(`Finding unused variables in "${chalk.cyan.bold(dir)}"...`);
console.log(`Searching for unused variables in "${chalk.cyan.bold(dir)}" folder, ${chalk.cyan.bold(options.fileExtensions.join(', '))} files...`);
console.log(`${chalk.cyan.bold(unusedVars.total)} total variables.`);

if (unusedVars.unused.length > 0) {
Expand Down
14 changes: 11 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ import parse from './lib/parse-variable.js';
const globP = promisify(glob);

const defaultOptions = {
ignore: []
ignore: [],
fileExtensions: ['scss']
};

const findUnusedVarsAsync = async(strDir, opts) => {
const options = parseOptions(opts);
const dir = await sanitizeDirAsync(strDir);
// Array of all Sass files
const sassFiles = await globP(path.join(dir, '**/*.scss'));
const sassFiles = await globP(path.join(dir, `**/*.${options.fileExtensions}`));

const executions = sassFiles.map(file => parseFileAsync(file, options));
// String of all Sass files' content
Expand All @@ -27,7 +28,7 @@ const findUnusedVarsSync = (strDir, opts) => {
const options = parseOptions(opts);
const dir = sanitizeDirSync(strDir);
// Array of all Sass files
const sassFiles = glob.sync(path.join(dir, '**/*.scss'));
const sassFiles = glob.sync(path.join(dir, `**/*.${options.fileExtensions}`));

const sassFilesAsStrings = sassFiles.map(file => parseFileSync(file, options));

Expand Down Expand Up @@ -94,6 +95,13 @@ const parseOptions = opts => {
// Trim list of ignored variables
options.ignore = options.ignore.map(val => val.trim());

let extensions = options.fileExtensions;

extensions = Array.isArray(extensions) ? extensions : [extensions];
// Replace possible fullstop prefix
extensions = extensions.map(ext => ext.startsWith('.') ? ext.slice(1) : ext);
options.fileExtensions = extensions.length > 1 ? `+(${extensions.join('|')})` : extensions;

return options;
};

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@
},
"scripts": {
"lint": "npm run xo",
"test": "npm run test:integration",
"test": "npm run test:integration && npm run test:options",
"test:integration": "node tests/integration.js",
"test:cli": "node ./cli.js tests/ --ignore=\"$a,$b\"",
"test:options": "node tests/options.js",
"xo": "xo"
},
"repository": {
Expand Down
52 changes: 52 additions & 0 deletions tests/options.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/env node

import fusv from '../index.js';

console.log('Running "Options" tests...');

const runTests = async(description, dir, options, expectedUnused) => {
const result = await fusv.findAsync(dir, options);
try {
console.log(`Running, ${description}...`);
if (result.unused.length === expectedUnused.length) {
console.log('Test passed!');
} else {
throw new Error(
`Expected ${expectedUnused.length} unused variables and got ${result.unused.length}.\n` +
`Expected: ${expectedUnused.join(', ')}\n` +
`Got: ${result.unused.join(', ')}`
);
}
} catch (error) {
console.error(error);
process.exit(1);
}
};

const allExpectedUnused = [
'$a',
'$b',
'$unused',
'$black',
'$nestedVar',
'$nestNestedVar',
'$enabled-variable',
'$ignored-variable'
];

const expectedUnused = [
'$unused',
'$black',
'$nestedVar',
'$nestNestedVar',
'$enabled-variable'
];
const ignore = ['$ignored-variable', '$a', '$b'];

runTests('"ignore" option test', './tests/', { ignore }, expectedUnused);

runTests('"fileExtension" option test with fullstop prefix', './tests/', { fileExtensions: '.scss' }, allExpectedUnused);

runTests('"fileExtensions" option test', './tests/', { fileExtensions: ['css'] }, []);

runTests('"fileExtensions" option test', './tests/', { fileExtensions: ['css', 'scss'] }, allExpectedUnused);

0 comments on commit 4bd4e68

Please sign in to comment.