3 const fs = require('fs');
4 const path = require('path');
5 const resolveFrom = require('resolve-from');
6 const debug = require('debug')('prettier-stylelint:main');
9 * Resolve Config for the given file
12 * @param {string} file - filepath
13 * @param {Object} options - options
14 * @returns {Promise} -
16 function resolveConfig({
22 const resolve = resolveConfig.resolve;
23 const stylelint = requireRelative(stylelintPath, filePath, 'stylelint');
24 const linterAPI = stylelint.createLinter();
26 if (stylelintConfig) {
27 return Promise.resolve(resolve(stylelintConfig, prettierOptions));
31 .getConfigForFile(filePath)
32 .then(({ config }) => resolve(config, prettierOptions));
35 resolveConfig.resolve = (stylelintConfig, prettierOptions = {}) => {
36 const { rules } = stylelintConfig;
38 if (rules['max-line-length']) {
39 const printWidth = rules['max-line-length'][0];
41 prettierOptions.printWidth = printWidth;
44 if (rules['string-quotes']) {
45 const quotes = rules['string-quotes'][0];
47 if (quotes === 'single') {
48 prettierOptions.singleQuote = true;
52 if (rules.indentation) {
53 const indentation = rules.indentation[0];
55 if (indentation === 'tab') {
56 prettierOptions.useTabs = true;
57 prettierOptions.tabWidth = 2;
59 prettierOptions.useTabs = false;
60 prettierOptions.tabWidth = indentation;
63 prettierOptions.parser = 'postcss';
64 debug('prettier %O', prettierOptions);
65 debug('linter %O', stylelintConfig);
67 return [prettierOptions, stylelintConfig];
70 function stylelinter(code, { filePath, stylelintPath }) {
71 const stylelint = requireRelative(stylelintPath, filePath, 'stylelint');
72 const linterAPI = stylelint.createLinter({ fix: true });
77 codeFilename: filePath
80 const fixed = result.root.toString(result.opts.syntax);
86 function requireRelative(path, filePath, packageName) {
89 return require(resolveFrom(path, packageName));
92 return require(resolveFrom(filePath, packageName));
94 return require(packageName);
98 function getPrettierConfig(filePath, prettierPath) {
99 const prettier = requireRelative(prettierPath, filePath, 'prettier');
101 // NOTE: Backward-compatibility with old prettier versions (<1.7)
102 // that don't have ``resolveConfig.sync` method.
103 return typeof prettier.resolveConfig.sync === 'undefined' ?
105 prettier.resolveConfig.sync(filePath);
110 text = fs.readFileSync(filePath, 'utf8'),
113 prettierOptions = getPrettierConfig(filePath, prettierPath),
117 filePath: path.isAbsolute(filePath) ?
119 path.resolve(process.cwd(), filePath),
126 const prettier = requireRelative(prettierPath, filePath, 'prettier');
128 return resolveConfig(options).then(([prettierConfig]) =>
129 stylelinter(prettier.format(text, prettierConfig), options)
133 exports.format = format;
134 exports.resolveConfig = resolveConfig;
135 exports.getPrettierConfig = getPrettierConfig;