This repository has been archived by the owner on Apr 17, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 95
/
executePrettier.js
85 lines (69 loc) · 2.42 KB
/
executePrettier.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// @flow
const prettierEslint = require('prettier-eslint');
const { allowUnsafeNewFunction } = require('loophole');
const {
getPrettierOptions,
getPrettierEslintOptions,
getCurrentFilePath,
getPrettier,
shouldDisplayErrors,
shouldUseEslint,
runLinter,
} = require('./helpers');
const EMBEDDED_JS_REGEX = /<script\b[^>]*>([\s\S]*?)(?=<\/script>)/gi;
const displayError = (error) => {
atom.notifications.addError('prettier-atom failed!', {
detail: error,
stack: error.stack,
dismissable: true,
});
};
const handleError = (error) => {
if (shouldDisplayErrors()) displayError(error);
return false;
};
const executePrettier = (editor, text) => {
try {
const prettierOptions = getPrettierOptions(editor);
if (shouldUseEslint()) {
return allowUnsafeNewFunction(() =>
prettierEslint({
...getPrettierEslintOptions(),
text,
filePath: getCurrentFilePath(editor),
fallbackPrettierOptions: prettierOptions,
}),
);
}
const prettier = getPrettier(getCurrentFilePath(editor));
return prettier.format(text, prettierOptions);
} catch (error) {
return handleError(error);
}
};
const executePrettierOnBufferRange = (editor: TextEditor, bufferRange: Range) => {
const cursorPositionPriorToFormat = editor.getCursorScreenPosition();
const textToTransform = editor.getTextInBufferRange(bufferRange);
const transformed = executePrettier(editor, textToTransform);
const isTextUnchanged = transformed === textToTransform;
if (!transformed || isTextUnchanged) return;
editor.setTextInBufferRange(bufferRange, transformed);
editor.setCursorScreenPosition(cursorPositionPriorToFormat);
runLinter(editor);
};
const executePrettierOnEmbeddedScripts = (editor: TextEditor) =>
editor.backwardsScanInBufferRange(EMBEDDED_JS_REGEX, editor.getBuffer().getRange(), (iter) => {
const { start, end } = iter.range;
// Skip formatting when <script> and </script> on the same line
if (start.row === end.row) return;
// Create new range with start row advanced by 1,
// since we cannot use look-behind on variable-length starting
// <script ...> tag
const startModified = [start.row + 1, start.column];
const bufferRange = new iter.range.constructor(startModified, end);
executePrettierOnBufferRange(editor, bufferRange);
});
module.exports = {
executePrettierOnBufferRange,
executePrettierOnEmbeddedScripts,
};