#!/usr/bin/env node const fse = require('fs-extra') const minimatch = require('minimatch') const select = require('unist-util-select') const {parseFile, jsonify, stringify} = require('..') const YAML = require('js-yaml') const yargs = require('yargs') .usage('$0 [options] []') .option('syntax', { desc: `The specific syntax to parse as, or 'auto' to determine from the filename.`, alias: 's', }) .option('format', { desc: 'Output format', alias: 'f', default: 'json', }) .option('pretty', { desc: 'Prettify output', alias: 'p', type: 'boolean', }) .option('grep', { desc: 'Only include variable names that match the given glob-like pattern.', alias: 'g', type: 'string', }) const formatters = { 'json': (data, {pretty}) => { const indent = pretty ? 2 : 0 return JSON.stringify(data, null, ' '.repeat(indent)) }, 'yaml': (data, {pretty}) => { const indent = pretty ? 2 : 0 const opts = {indent} return YAML.safeDump(data, 'utf8', opts) }, } const options = yargs.argv const args = options._ const STDIN = '/dev/stdin' const DASH = '-' const STDIN_OVERRIDES = { syntax: options.syntax === 'auto' ? 'scss' : options.syntax } const reads = (args.length ? args : [STDIN]) .map(file => file === DASH ? STDIN : file) .map(file => { const opts = file === STDIN ? Object.assign({}, options, STDIN_OVERRIDES) : options return parseFile(file, opts, 'utf8') }) const getVariables = tree => { return select(tree, 'stylesheet > declaration') .reduce((acc, node) => { const {name, value} = jsonify(node) if (name) { acc[name] = value } return acc }, {}) } Promise.all(reads) .then(files => { return files.reduce((acc, tree) => { const vars = getVariables(tree) console.warn('found %d variable declarations in %s', Object.keys(vars).length, tree.source) return Object.assign(acc, vars) }, {}) }) .catch(error => { console.error(error) process.exit(1) }) .then(vars => { const {grep, format} = options if (grep) { console.warn('grepping: "%s"', grep) vars = Object.keys(vars) .filter(key => minimatch(key, grep)) .reduce((filtered, key) => { filtered[key] = vars[key] return filtered }, {}) } const fmt = formatters[format] const output = fmt(vars, options) console.log(output) }) .catch(error => { console.error(error) process.exit(1) })