Skip to content

Instantly share code, notes, and snippets.

@josketres
Created March 15, 2021 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josketres/75f5b43434ea155c84ac4285c0ee6fef to your computer and use it in GitHub Desktop.
Save josketres/75f5b43434ea155c84ac4285c0ee6fef to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
// utility script to count the max. nesting level on a sass file
const fs = require('fs');
const { parse } = require('scss-parser');
const createQueryWrapper = require('query-ast');
const files = process.argv.slice(2);
files.forEach(file => {
const max = maxNesting(file);
console.log(`${max} ${file}`);
});
function maxNesting(file) {
const scss = String(fs.readFileSync(file));
const ast = parse(scss);
const $ = createQueryWrapper(ast, {});
const declarations = $('declaration');
return declarations.reduce((acc, next) => {
const nesting = countBlocks(next);
return Math.max(acc, nesting);
}, 0);
}
function countBlocks(nodeWrapper, acc = 0) {
if (nodeWrapper.node.type === 'stylesheet') {
return acc;
}
if (nodeWrapper.parent.node.type === 'block') {
return acc + 1 + countBlocks(nodeWrapper.parent);
}
return acc + countBlocks(nodeWrapper.parent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment