Skip to content

Commit

Permalink
Inline stylelint-vscode into this repository
Browse files Browse the repository at this point in the history
* tmp/master: (108 commits)
  7.0.0-21
  update dependencies and devDependencies
  7.0.0-20
  use `if` field to simplify Travis CI branch exclusion
  update dependencies and devDependencies
  test on Ubuntu 16.04.5 LTS (Xenial Xerus)
  7.0.0-19
  update dependencies and devDependencies
  7.0.0-18
  use Travis CI Windows build instead of AppVeyor
  update dependencies and devDependencies
  7.0.0-17
  support newly created Svelte documents
  7.0.0-16
  downgrade @babel/core from v7.0.0-rc.2 to rc.1
  introduce stylelint-formatter-simplest
  7.0.0-15
  add a workaround for the .stylelintignore bug
  7.0.0-14
  update dependencies and devDependencies
  ...
  • Loading branch information
thibaudcolas committed Dec 2, 2019
2 parents ec6ee9a + fa7d97f commit e9a6894
Show file tree
Hide file tree
Showing 12 changed files with 5,502 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/stylelint-vscode/.editorconfig
@@ -0,0 +1,15 @@
root = true

[*]
charset = utf-8
end_of_line = lf
indent_style = tab
tab_width = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.{md,yml}]
indent_style = space

[*.md]
trim_trailing_whitespace = false
1 change: 1 addition & 0 deletions lib/stylelint-vscode/.gitattributes
@@ -0,0 +1 @@
* text=auto
2 changes: 2 additions & 0 deletions lib/stylelint-vscode/.gitignore
@@ -0,0 +1,2 @@
coverage
node_modules
8 changes: 8 additions & 0 deletions lib/stylelint-vscode/.travis.yml
@@ -0,0 +1,8 @@
if: branch !~ ^v\d
language: node_js
node_js: node
jobs:
include:
- dist: xenial
- os: windows
script: node test\\test.js
6 changes: 6 additions & 0 deletions lib/stylelint-vscode/LICENSE
@@ -0,0 +1,6 @@
ISC License (ISC)
Copyright 2018 - 2019 Shinnosuke Watanabe

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
130 changes: 130 additions & 0 deletions lib/stylelint-vscode/README.md
@@ -0,0 +1,130 @@
# stylelint-vscode

[![npm version](https://img.shields.io/npm/v/stylelint-vscode.svg)](https://www.npmjs.com/package/stylelint-vscode)
[![Build Status](https://travis-ci.com/shinnn/stylelint-vscode.svg?branch=master)](https://travis-ci.com/shinnn/stylelint-vscode)
[![codecov](https://codecov.io/gh/shinnn/stylelint-vscode/branch/master/graph/badge.svg)](https://codecov.io/gh/shinnn/stylelint-vscode)

A [stylelint](https://github.com/stylelint/stylelint) wrapper to easily integrate with [Visual Studio Code](https://code.visualstudio.com/) [language server](https://github.com/Microsoft/vscode-languageserver-node)

```javascript
const stylelintVSCode = require('stylelint-vscode');
const {TextDocument} = require('vscode-languageserver-types');

(async () => {
await stylelintVSCode(TextDocument.create('file:///Users/me/0.css', 'css', 1, `
p {
line-height: .8;
color: red;
}`), {
code,
config: {
rules: {
'number-leading-zero': 'always',
'color-named': ['never', {severity: 'warning'}]
}
}
}); /* => [{
range: {
start: {line: 2, character: 14},
end: {line: 2, character: 14}
},
message: 'Expected a leading zero (number-leading-zero)',
severity: 1,
code: 'number-leading-zero',
source: 'stylelint'
}, {
range: {
start: {line: 3, character: 9},
end: {line: 3, character: 9}
},
message: 'Unexpected named color "red" (color-no-named)',
severity: 2,
code: 'color-no-named',
source: 'stylelint'
}] */
})();
```

## Installation

[Use](https://docs.npmjs.com/cli/install) [npm](https://docs.npmjs.com/getting-started/what-is-npm).

```
npm install stylelint-vscode
```

## API

```javascript
const stylelintVSCode = require('stylelint-vscode');
```

### stylelintVSCode(*textDocument* [, *options*])

*textDocument*: [`TextDocument`](https://code.visualstudio.com/docs/extensionAPI/vscode-api#TextDocument)
*options*: `Object` (directly passed to [`stylelint.lint`](https://github.com/stylelint/stylelint/blob/master/docs/user-guide/node-api.md#the-stylelint-nodejs-api))
Return: `Promise<Array<Object>>`

It works like [`stylelint.lint()`](https://github.com/stylelint/stylelint/blob/10.0.1/lib/index.js#L31), except for:

* [`code`](https://github.com/stylelint/stylelint/blob/master/docs/user-guide/node-api.md#code) and [`codeFilename`](https://github.com/stylelint/stylelint/blob/master/docs/user-guide/node-api.md#codefilename) option values are derived from a `TextDocument` passed to the first argument.
* It will be resolved with an `Array` of [VS Code `Diagnostic`](https://github.com/Microsoft/vscode-languageserver-node/blob/release/types/3.14/types/src/main.ts#L508-L546) instances.
* It will be *rejected* (not resolved) when it takes invalid configs.
* In this case, it joins config errors into a single error object by using [array-to-error](https://github.com/shinnn/array-to-error).
* It suppresses `No configuration found` error.
* Doing nothing when there is no configuration is a common behavior of editor plugins.
* [`files`](https://github.com/stylelint/stylelint/blob/master/docs/user-guide/node-api.md#files) and [`formatter`](https://github.com/stylelint/stylelint/blob/master/docs/user-guide/node-api.md#formatter) options are not supported.

```javascript
const stylelintVSCode = require('stylelint-vscode');

(async () => {
await stylelintVSCode(TextDocument.create('file:///Users/me/1.css', 'css', 1, '{foo}')); /*=> [{
range: {
start: {line: 0, character: 1},
end: {line: 0, character: 1}
},
message: 'Unknown word (CssSyntaxError)',
severity: 1,
code: 'CssSyntaxError',
source: 'stylelint'
}] */
});
```

```javascript
(async () => {
try {
await stylelintVSCode(TextDocument.create('file:///Users/me/2.css', 'css', 1, 'a {}'), {
config: {
rules: {
indentation: 2,
'function-comma-space-before': 'foo'
}
}
});
} catch (err) {
err.name;
//=> 'SyntaxError'

err.message;
//=> 'Expected option value for rule "indentation"\nInvalid option value "foo" for rule "function-comma-space-before"'

err.reasons;
/* =>
[
'Expected option value for rule "indentation"',
'Invalid option value "foo" for rule "function-comma-space-before"'
]
*/
}
})();
```

## Related project

* [vscode-stylelint](https://github.com/shinnn/vscode-stylelint) — A VS Code extension powered by this module

## License

[ISC License](./LICENSE) © 2018 - 2019 Shinnosuke Watanabe
145 changes: 145 additions & 0 deletions lib/stylelint-vscode/index.js
@@ -0,0 +1,145 @@
'use strict';

const arrayToError = require('array-to-error');
const arrayToSentence = require('array-to-sentence');
const {at, has, intersection, isPlainObject, map, stubString} = require('lodash');
const {Files, TextDocument} = require('vscode-languageserver');
const inspectWithKind = require('inspect-with-kind');
const {lint} = require('stylelint');
const stylelintWarningToVscodeDiagnostic = require('stylelint-warning-to-vscode-diagnostic');

// https://github.com/stylelint/stylelint/blob/10.0.1/lib/getPostcssResult.js#L69-L81
const SUPPORTED_SYNTAXES = new Set([
'css-in-js',
'html',
'less',
'markdown',
'sass',
'scss',
'sugarss'
]);

const LANGUAGE_EXTENSION_EXCEPTION_PAIRS = new Map([
['javascript', 'css-in-js'],
['javascriptreact', 'css-in-js'],
['source.css.styled', 'css-in-js'],
['source.markdown.math', 'markdown'],
['styled-css', 'css-in-js'],
['svelte', 'html'],
['typescript', 'css-in-js'],
['typescriptreact', 'css-in-js'],
['vue-html', 'html'],
['xml', 'html'],
['xsl', 'html']
]);

const UNSUPPORTED_OPTIONS = [
'code',
'codeFilename',
'files',
'formatter'
];

function quote(str) {
return `\`${str}\``;
}

function processResults({results}) {
// https://github.com/stylelint/stylelint/blob/10.0.1/lib/standalone.js#L114-L122
if (results.length === 0) {
return [];
}

const [{invalidOptionWarnings, warnings}] = results;

if (invalidOptionWarnings.length !== 0) {
throw arrayToError(map(invalidOptionWarnings, 'text'), SyntaxError);
}

return warnings.map(stylelintWarningToVscodeDiagnostic);
}

module.exports = async function stylelintVSCode(...args) {
const argLen = args.length;

if (argLen !== 1 && argLen !== 2) {
throw new RangeError(`Expected 1 or 2 arguments (<TextDocument>[, <Object>]), but got ${
argLen === 0 ? 'no' : argLen
} arguments.`);
}

const [textDocument, options = {}] = args;

if (!TextDocument.is(textDocument)) {
throw new TypeError(`Expected a TextDocument https://code.visualstudio.com/docs/extensionAPI/vscode-api#TextDocument, but got ${
inspectWithKind(textDocument)
}.`);
}

if (argLen === 2) {
if (!isPlainObject(options)) {
throw new TypeError(`Expected an object containing stylelint API options, but got ${
inspectWithKind(options)
}.`);
}

const providedUnsupportedOptions = intersection(Object.keys(options), UNSUPPORTED_OPTIONS);

if (providedUnsupportedOptions.length !== 0) {
throw new TypeError(`${
arrayToSentence(map(UNSUPPORTED_OPTIONS, quote))
} options are not supported because they will be derived from a document and there is no need to set them manually, but ${
arrayToSentence(map(providedUnsupportedOptions, quote))
} was provided.`);
}
}

const priorOptions = {
code: textDocument.getText(),
formatter: stubString
};
const codeFilename = Files.uriToFilePath(textDocument.uri);
let resultContainer;

if (codeFilename) {
priorOptions.codeFilename = codeFilename;
} else {
if (!has(options, 'syntax')) {
if (SUPPORTED_SYNTAXES.has(textDocument.languageId)) {
priorOptions.syntax = textDocument.languageId;
} else {
const syntax = LANGUAGE_EXTENSION_EXCEPTION_PAIRS.get(textDocument.languageId);

if (syntax) {
priorOptions.syntax = syntax;
}
}
}

if (!at(options, 'config.rules')[0]) {
priorOptions.config = {rules: {}};
}
}

try {
resultContainer = await lint({...options, ...priorOptions});
} catch (err) {
if (
err.message.startsWith('No configuration provided for') ||
err.message.includes('No rules found within configuration')
) {
// Check only CSS syntax errors without applying any stylelint rules
return processResults(await lint({
...options,
...priorOptions,
config: {
rules: {}
}
}));
}

throw err;
}

return processResults(resultContainer);
};

0 comments on commit e9a6894

Please sign in to comment.