-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy patheditorConfig.ts
178 lines (157 loc) · 6.29 KB
/
editorConfig.ts
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
import * as fs from 'fs';
import * as path from 'path';
export const cachedEditorConfigSettings: Map<string, any> = new Map<string, any>();
export function mapIndentationReferenceToEditorConfig(value: string | undefined): string {
if (value !== undefined) {
// Will never actually be undefined, as these settings have default values.
if (value === "statementBegin") {
return "statement_begin";
}
if (value === "outermostParenthesis") {
return "outermost_parenthesis";
}
}
return "innermost_parenthesis";
}
export function mapIndentToEditorConfig(value: string | undefined): string {
if (value !== undefined) {
// Will never actually be undefined, as these settings have default values.
if (value === "leftmostColumn") {
return "leftmost_column";
}
if (value === "oneLeft") {
return "one_left";
}
}
return "none";
}
export function mapNewOrSameLineToEditorConfig(value: string | undefined): string {
if (value !== undefined) {
// Will never actually be undefined, as these settings have default values.
if (value === "newLine") {
return "new_line";
}
if (value === "sameLine") {
return "same_line";
}
}
return "ignore";
}
export function mapWrapToEditorConfig(value: string | undefined): string {
if (value !== undefined) {
// Will never actually be undefined, as these settings have default values.
if (value === "allOneLineScopes") {
return "all_one_line_scopes";
}
if (value === "oneLiners") {
return "one_liners";
}
}
return "never";
}
function matchesSection(filePath: string, section: string): boolean {
const fileName: string = path.basename(filePath);
// Escape all regex special characters except '*' and '?'.
// Convert wildcards '*' to '.*' and '?' to '.'.
const sectionPattern = section.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
const regex: RegExp = new RegExp(`^${sectionPattern}$`);
return regex.test(fileName);
}
function parseEditorConfigContent(content: string): Record<string, any> {
const lines = content.split(/\r?\n/);
const config: Record<string, any> = {};
let currentSection: string | null = '*'; // Use '*' for sectionless (global) settings.
lines.forEach(line => {
line = line.trim();
if (!line || line.startsWith('#') || line.startsWith(';')) {
// Skip empty lines and comments.
return;
}
if (line.startsWith('[') && line.endsWith(']')) {
// New section (e.g., [*.js])
currentSection = line.slice(1, -1).trim();
config[currentSection] = config[currentSection] || {};
} else {
// Key-value pair (e.g., indent_style = space).
const [key, ...values] = line.split('=');
if (key && values.length > 0) {
const trimmedKey = key.trim();
let value: any = values.join('=').trim();
// Convert boolean-like and numeric values.
if (value.toLowerCase() === 'true') {
value = true;
} else if (value.toLowerCase() === 'false') {
value = false;
} else if (!isNaN(Number(value))) {
value = Number(value);
}
if (currentSection) {
// Ensure the current section is initialized.
if (!config[currentSection]) {
config[currentSection] = {};
}
config[currentSection][trimmedKey] = value;
}
}
}
});
return config;
}
function getEditorConfig(filePath: string): any {
let combinedConfig: any = {};
let globalConfig: any = {};
let currentDir: string = path.dirname(filePath);
const rootDir: string = path.parse(currentDir).root;
// Traverse from the file's directory to the root directory.
for (; ;) {
const editorConfigPath: string = path.join(currentDir, '.editorconfig');
if (fs.existsSync(editorConfigPath)) {
const configFileContent: string = fs.readFileSync(editorConfigPath, 'utf-8');
const configData = parseEditorConfigContent(configFileContent);
// Extract global (sectionless) entries.
if (configData['*']) {
globalConfig = {
...globalConfig,
...configData['*']
};
}
// Match sections and combine configurations.
Object.keys(configData).forEach((section: string) => {
if (section !== '*' && matchesSection(filePath, section)) {
combinedConfig = {
...combinedConfig,
...configData[section]
};
}
});
// Check if the current .editorconfig is the root.
if (configData['*']?.root) {
break; // Stop searching after processing the root = true file.
}
}
if (currentDir === rootDir) {
break; // Stop the loop after checking the root directory.
}
currentDir = path.dirname(currentDir);
}
// Merge global config with section-based config.
return {
...globalConfig,
...combinedConfig
};
}
// Look up the appropriate .editorconfig settings for the specified file.
// This is intentionally not async to avoid races due to multiple entrancy.
export function getEditorConfigSettings(fsPath: string): Promise<any> {
let editorConfigSettings: any = cachedEditorConfigSettings.get(fsPath);
if (!editorConfigSettings) {
editorConfigSettings = getEditorConfig(fsPath);
cachedEditorConfigSettings.set(fsPath, editorConfigSettings);
}
return editorConfigSettings;
}