-
Notifications
You must be signed in to change notification settings - Fork 142
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: STRF-10507 Scss autofix issue: Undefined variable
- Loading branch information
Showing
3 changed files
with
75 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
const fs = require('fs'); | ||
const BaseFixer = require('./BaseFixer'); | ||
|
||
class UndefinedVariableFixer extends BaseFixer { | ||
async run(errorMessage) { | ||
const varName = this.getUndefinedVariableName(errorMessage); | ||
const value = await this.guessVariableValue(varName); | ||
|
||
const scss = fs.readFileSync(this.filePath, 'utf8'); | ||
const processedFile = await this.processCss(scss, this.transform(varName, value)); | ||
|
||
return [{ filePath: this.filePath, data: processedFile.css }]; | ||
} | ||
|
||
getUndefinedVariableName(errorMessage) { | ||
const match = errorMessage.match(/\$([a-zA-Z]{1,})/gi); | ||
if (!match) { | ||
throw new Error("Couldn't detemine undefined variable name!"); | ||
} | ||
return match[0]; | ||
} | ||
|
||
transform(varName, value) { | ||
return { | ||
postcssPlugin: 'Declare unvariable variable value', | ||
Once(root, { Declaration }) { | ||
const newRule = new Declaration({ | ||
value, | ||
prop: varName, | ||
source: '', | ||
}); | ||
root.prepend(newRule); | ||
}, | ||
}; | ||
} | ||
|
||
async guessVariableValue(varName) { | ||
const scss = fs.readFileSync(this.filePath, 'utf8'); | ||
const processedFile = await this.processCss( | ||
scss, | ||
this.transformForGuessingVariableValue(varName), | ||
); | ||
return processedFile.varValue; | ||
} | ||
|
||
transformForGuessingVariableValue(varName) { | ||
return { | ||
postcssPlugin: 'Get first variable value found in the file', | ||
Declaration: (decl, { result }) => { | ||
if (decl.prop === varName) { | ||
// eslint-disable-next-line no-param-reassign | ||
result.varValue = decl.value; | ||
// todo propertly break on first found declaration | ||
} | ||
}, | ||
}; | ||
} | ||
} | ||
|
||
module.exports = UndefinedVariableFixer; |