|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/*! |
| 4 | + * Script to find unused Sass variables. |
| 5 | + * |
| 6 | + * Copyright 2017 The Bootstrap Authors |
| 7 | + * Copyright 2017 Twitter, Inc. |
| 8 | + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) |
| 9 | + */ |
| 10 | + |
| 11 | +'use strict' |
| 12 | + |
| 13 | +const fs = require('fs') |
| 14 | +const path = require('path') |
| 15 | +const glob = require('glob') |
| 16 | + |
| 17 | +// Blame TC39... https://github.com/benjamingr/RegExp.escape/issues/37 |
| 18 | +function regExpQuote(str) { |
| 19 | + return str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&') |
| 20 | +} |
| 21 | + |
| 22 | +let globalSuccess = true |
| 23 | + |
| 24 | +function findUnusedVars(dir) { |
| 25 | + if (!(fs.existsSync(dir) && fs.statSync(dir).isDirectory())) { |
| 26 | + console.log(`"${dir}": Not a valid directory!`) |
| 27 | + process.exit(1) |
| 28 | + } |
| 29 | + |
| 30 | + console.log(`Finding unused variables in "${dir}"...`) |
| 31 | + |
| 32 | + // A variable to handle success/failure message in this function |
| 33 | + let unusedVarsFound = false |
| 34 | + |
| 35 | + // Array of all Sass files' content |
| 36 | + const sassFiles = glob.sync(path.join(dir, '**/*.scss')) |
| 37 | + // String of all Sass files' content |
| 38 | + let sassFilesString = '' |
| 39 | + |
| 40 | + sassFiles.forEach((file) => { |
| 41 | + sassFilesString += fs.readFileSync(file, 'utf8') |
| 42 | + }) |
| 43 | + |
| 44 | + // Array of all Sass variables |
| 45 | + const variables = sassFilesString.match(/(^\$[a-zA-Z0-9_-]+[^:])/gm) |
| 46 | + |
| 47 | + console.log(`There's a total of ${variables.length} variables.`) |
| 48 | + |
| 49 | + // Loop through each variable |
| 50 | + variables.forEach((variable) => { |
| 51 | + const re = new RegExp(regExpQuote(variable), 'g') |
| 52 | + const count = (sassFilesString.match(re) || []).length |
| 53 | + |
| 54 | + if (count === 1) { |
| 55 | + console.log(`Variable "${variable}" is only used once!`) |
| 56 | + unusedVarsFound = true |
| 57 | + globalSuccess = false |
| 58 | + } |
| 59 | + }) |
| 60 | + |
| 61 | + if (unusedVarsFound === false) { |
| 62 | + console.log(`No unused variables found in "${dir}".`) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +function main(args) { |
| 67 | + if (args.length < 1) { |
| 68 | + console.log('Wrong arguments!') |
| 69 | + console.log('Usage: lint-vars.js folder [, folder2...]') |
| 70 | + process.exit(1) |
| 71 | + } |
| 72 | + |
| 73 | + args.forEach((arg) => { |
| 74 | + findUnusedVars(arg) |
| 75 | + }) |
| 76 | + |
| 77 | + if (globalSuccess === false) { |
| 78 | + process.exit(1) |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +// The first and second args are: path/to/node script.js |
| 83 | +main(process.argv.slice(2)) |
0 commit comments