1
1
mirror of https://github.com/primer/css.git synced 2024-12-25 15:14:59 +03:00
css/script/analyze-variables.js

86 lines
2.4 KiB
JavaScript
Raw Normal View History

2019-10-19 02:20:56 +03:00
#!/usr/bin/env node
const postcss = require('postcss')
2021-04-09 05:34:17 +03:00
const {join} = require('path')
const fs = require('fs')
2019-10-19 02:20:56 +03:00
const atImport = require('postcss-import')
const syntax = require('postcss-scss')
2021-04-09 05:34:17 +03:00
const processor = postcss([
atImport({path: ['src']}),
collectVariables(),
require('postcss-simple-vars')({includePaths: [join(__dirname, '../src/support/variables')]})
])
2019-10-19 02:20:56 +03:00
2021-04-09 05:34:17 +03:00
async function analyzeVariables(fileName) {
const contents = await fs.readFileSync(fileName, 'utf8')
2019-10-19 02:20:56 +03:00
2021-04-09 05:34:17 +03:00
const result = await processor.process(contents, {from: fileName, map: false, syntax})
for (const message of result.messages) {
if (message.plugin === 'postcss-simple-vars' && message.type === 'variable') {
if (!result.variables[`$${message.name}`].values.includes(message.value)) {
result.variables[`$${message.name}`].values.push(message.value)
2019-10-19 02:20:56 +03:00
}
2021-04-09 05:34:17 +03:00
const computed = message.value
result.variables[`$${message.name}`].computed = computed
}
}
return result.variables
2019-10-19 02:20:56 +03:00
}
2021-04-09 05:34:17 +03:00
function checkNode(node) {
const allowedFuncts = ['var', 'round', 'cubic-bezier']
const functMatch = node.value.match(/([^\s]*)\(/)
let approvedMatch = true
if (functMatch && !allowedFuncts.includes(functMatch[1])) {
approvedMatch = false
}
return node.variable && approvedMatch
}
2019-10-19 02:20:56 +03:00
2021-04-09 05:34:17 +03:00
function collectVariables() {
return {
postcssPlugin: 'prepare-contents',
prepare(result) {
const variables = {}
return {
AtRule(atRule) {
atRule.remove()
},
Comment(comment) {
comment.remove()
},
Declaration(node) {
if (checkNode(node)) {
node.value = node.value.replace(' !default', '')
const fileName = node.source.input.file.replace(`${process.cwd()}/`, '')
variables[node.prop] = {
// computed: value,
values: [node.value],
source: {
path: fileName,
line: node.source.start.line
2021-04-08 20:27:54 +03:00
}
2019-10-19 02:20:56 +03:00
}
2021-04-09 05:34:17 +03:00
} else {
node.remove()
2019-10-19 02:20:56 +03:00
}
2021-04-09 05:34:17 +03:00
},
OnceExit() {
result.variables = variables
2019-10-19 02:20:56 +03:00
}
}
}
2021-04-08 20:27:54 +03:00
}
2019-10-19 02:20:56 +03:00
}
2021-04-09 05:34:17 +03:00
if (module.parent) {
module.exports = analyzeVariables
} else {
;(async () => {
const args = process.argv.slice(2)
const file = args.length ? args.shift() : 'src/support/index.scss'
const variables = await analyzeVariables(file)
console.log(JSON.stringify(variables, null, 2))
})()
2019-10-19 02:20:56 +03:00
}