-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathruff_settings.rs
More file actions
477 lines (427 loc) · 17.6 KB
/
ruff_settings.rs
File metadata and controls
477 lines (427 loc) · 17.6 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use std::collections::BTreeMap;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use anyhow::Context;
use ignore::{WalkBuilder, WalkState};
use ruff_linter::{
fs::normalize_path_to, settings::types::FilePattern, settings::types::PreviewMode,
};
use ruff_workspace::resolver::match_exclusion;
use ruff_workspace::Settings;
use ruff_workspace::{
configuration::{Configuration, FormatConfiguration, LintConfiguration, RuleSelection},
pyproject::{find_user_settings_toml, settings_toml},
resolver::{ConfigurationTransformer, Relativity},
};
use crate::session::settings::{
ConfigurationPreference, ResolvedConfiguration, ResolvedEditorSettings,
};
#[derive(Debug)]
pub struct RuffSettings {
/// The path to this configuration file, used for debugging.
/// The default fallback configuration does not have a file path.
path: Option<PathBuf>,
/// The resolved settings.
settings: Settings,
}
impl RuffSettings {
pub(crate) fn path(&self) -> Option<&Path> {
self.path.as_deref()
}
}
impl Deref for RuffSettings {
type Target = Settings;
fn deref(&self) -> &Settings {
&self.settings
}
}
pub(super) struct RuffSettingsIndex {
/// Index from folder to the resolved ruff settings.
index: BTreeMap<PathBuf, Arc<RuffSettings>>,
fallback: Arc<RuffSettings>,
}
impl std::fmt::Display for RuffSettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.settings, f)
}
}
impl RuffSettings {
pub(crate) fn fallback(editor_settings: &ResolvedEditorSettings, root: &Path) -> RuffSettings {
let mut path = None;
let fallback = find_user_settings_toml()
.and_then(|user_settings| {
let settings = ruff_workspace::resolver::resolve_root_settings(
&user_settings,
Relativity::Cwd,
&EditorConfigurationTransformer(editor_settings, root),
)
.ok();
path = Some(user_settings);
settings
})
.unwrap_or_else(|| {
let default_configuration = Configuration::default();
EditorConfigurationTransformer(editor_settings, root)
.transform(default_configuration)
.into_settings(root)
.expect(
"editor configuration should merge successfully with default configuration",
)
});
RuffSettings {
path,
settings: fallback,
}
}
}
impl RuffSettingsIndex {
/// Create the settings index for the given workspace root.
///
/// This will create the index in the following order:
/// 1. Resolve any settings from above the workspace root
/// 2. Resolve any settings from the workspace root itself
/// 3. Resolve any settings from within the workspace directory tree
///
/// If this is the default workspace i.e., the client did not specify any workspace and so the
/// server will be running in a single file mode, then only (1) and (2) will be resolved,
/// skipping (3).
pub(super) fn new(
root: &Path,
editor_settings: &ResolvedEditorSettings,
is_default_workspace: bool,
) -> Self {
tracing::debug!("Indexing settings for workspace: {}", root.display());
let mut has_error = false;
let mut index = BTreeMap::default();
let mut respect_gitignore = None;
// If this is *not* the default workspace, then we should skip the workspace root itself
// because it will be resolved when walking the workspace directory tree. This is done by
// the `WalkBuilder` below.
let should_skip_workspace = usize::from(!is_default_workspace);
// Add any settings from above the workspace root, skipping the workspace root itself if
// this is *not* the default workspace.
for directory in root.ancestors().skip(should_skip_workspace) {
match settings_toml(directory) {
Ok(Some(pyproject)) => {
match ruff_workspace::resolver::resolve_root_settings(
&pyproject,
Relativity::Parent,
&EditorConfigurationTransformer(editor_settings, root),
) {
Ok(settings) => {
respect_gitignore = Some(settings.file_resolver.respect_gitignore);
index.insert(
directory.to_path_buf(),
Arc::new(RuffSettings {
path: Some(pyproject),
settings,
}),
);
break;
}
error => {
tracing::error!(
"{:#}",
error
.with_context(|| {
format!(
"Failed to resolve settings for {}",
pyproject.display()
)
})
.unwrap_err()
);
has_error = true;
continue;
}
}
}
Ok(None) => continue,
Err(err) => {
tracing::error!("{err:#}");
has_error = true;
continue;
}
}
}
let fallback = Arc::new(RuffSettings::fallback(editor_settings, root));
// If this is the default workspace, the server is running in single-file mode. What this
// means is that the user opened a file directly (not the folder) in the editor and the
// server didn't receive a workspace folder during initialization. In this case, we default
// to the current working directory and skip walking the workspace directory tree for any
// settings.
//
// Refer to https://github.com/astral-sh/ruff/pull/13770 to understand what this behavior
// means for different editors.
if is_default_workspace {
if has_error {
show_err_msg!(
"Error while resolving settings from workspace {}. Please refer to the logs for more details.",
root.display()
);
}
return RuffSettingsIndex { index, fallback };
}
// Add any settings within the workspace itself
let mut builder = WalkBuilder::new(root);
builder.standard_filters(
respect_gitignore.unwrap_or_else(|| fallback.file_resolver.respect_gitignore),
);
builder.hidden(false);
builder.threads(
std::thread::available_parallelism()
.map_or(1, std::num::NonZeroUsize::get)
.min(12),
);
let walker = builder.build_parallel();
let index = std::sync::RwLock::new(index);
let has_error = AtomicBool::new(has_error);
walker.run(|| {
Box::new(|result| {
let Ok(entry) = result else {
return WalkState::Continue;
};
// Skip non-directories.
if !entry
.file_type()
.is_some_and(|file_type| file_type.is_dir())
{
return WalkState::Continue;
}
let directory = entry.into_path();
// If the directory is excluded from the workspace, skip it.
if let Some(file_name) = directory.file_name() {
let settings = index
.read()
.unwrap()
.range(..directory.clone())
.rfind(|(path, _)| directory.starts_with(path))
.map(|(_, settings)| settings.clone())
.unwrap_or_else(|| fallback.clone());
if match_exclusion(&directory, file_name, &settings.file_resolver.exclude) {
tracing::debug!("Ignored path via `exclude`: {}", directory.display());
return WalkState::Skip;
} else if match_exclusion(
&directory,
file_name,
&settings.file_resolver.extend_exclude,
) {
tracing::debug!(
"Ignored path via `extend-exclude`: {}",
directory.display()
);
return WalkState::Skip;
}
}
match settings_toml(&directory) {
Ok(Some(pyproject)) => {
match ruff_workspace::resolver::resolve_root_settings(
&pyproject,
Relativity::Parent,
&EditorConfigurationTransformer(editor_settings, root),
) {
Ok(settings) => {
index.write().unwrap().insert(
directory,
Arc::new(RuffSettings {
path: Some(pyproject),
settings,
}),
);
}
error => {
tracing::error!(
"{:#}",
error
.with_context(|| {
format!(
"Failed to resolve settings for {}",
pyproject.display()
)
})
.unwrap_err()
);
has_error.store(true, Ordering::Relaxed);
}
}
}
Ok(None) => {}
Err(err) => {
tracing::error!("{err:#}");
has_error.store(true, Ordering::Relaxed);
}
}
WalkState::Continue
})
});
if has_error.load(Ordering::Relaxed) {
show_err_msg!(
"Error while resolving settings from workspace {}. Please refer to the logs for more details.",
root.display()
);
}
RuffSettingsIndex {
index: index.into_inner().unwrap(),
fallback,
}
}
pub(super) fn get(&self, document_path: &Path) -> Arc<RuffSettings> {
self.index
.range(..document_path.to_path_buf())
.rfind(|(path, _)| document_path.starts_with(path))
.map(|(_, settings)| settings)
.unwrap_or_else(|| &self.fallback)
.clone()
}
pub(super) fn fallback(&self) -> Arc<RuffSettings> {
self.fallback.clone()
}
/// Returns an iterator over the paths to the configuration files in the index.
pub(crate) fn config_file_paths(&self) -> impl Iterator<Item = &Path> {
self.index
.values()
.filter_map(|settings| settings.path.as_deref())
}
}
struct EditorConfigurationTransformer<'a>(&'a ResolvedEditorSettings, &'a Path);
impl ConfigurationTransformer for EditorConfigurationTransformer<'_> {
fn transform(&self, filesystem_configuration: Configuration) -> Configuration {
let ResolvedEditorSettings {
configuration,
format_preview,
lint_preview,
select,
extend_select,
ignore,
exclude,
line_length,
configuration_preference,
} = self.0.clone();
let project_root = self.1;
let editor_configuration = Configuration {
lint: LintConfiguration {
preview: lint_preview.map(PreviewMode::from),
rule_selections: vec![RuleSelection {
select,
extend_select: extend_select.unwrap_or_default(),
ignore: ignore.unwrap_or_default(),
..RuleSelection::default()
}],
..LintConfiguration::default()
},
format: FormatConfiguration {
preview: format_preview.map(PreviewMode::from),
..FormatConfiguration::default()
},
exclude: exclude.map(|exclude| {
exclude
.into_iter()
.map(|pattern| {
let absolute = normalize_path_to(&pattern, project_root);
FilePattern::User(pattern, absolute)
})
.collect()
}),
line_length,
..Configuration::default()
};
// Merge in the editor-specified configuration.
let editor_configuration = if let Some(configuration) = configuration {
match configuration {
ResolvedConfiguration::FilePath(path) => {
tracing::debug!(
"Combining settings from editor-specified configuration file at: {}",
path.display()
);
match open_configuration_file(&path) {
Ok(config_from_file) => editor_configuration.combine(config_from_file),
err => {
tracing::error!(
"{:?}",
err.context("Unable to load editor-specified configuration file")
.unwrap_err()
);
editor_configuration
}
}
}
ResolvedConfiguration::Inline(options) => {
tracing::debug!(
"Combining settings from editor-specified inline configuration"
);
match Configuration::from_options(options, None, project_root) {
Ok(configuration) => editor_configuration.combine(configuration),
Err(err) => {
tracing::error!(
"Unable to load editor-specified inline configuration: {err:?}",
);
editor_configuration
}
}
}
}
} else {
editor_configuration
};
match configuration_preference {
ConfigurationPreference::EditorFirst => {
editor_configuration.combine(filesystem_configuration)
}
ConfigurationPreference::FilesystemFirst => {
filesystem_configuration.combine(editor_configuration)
}
ConfigurationPreference::EditorOnly => editor_configuration,
}
}
}
fn open_configuration_file(config_path: &Path) -> crate::Result<Configuration> {
ruff_workspace::resolver::resolve_configuration(
config_path,
Relativity::Cwd,
&IdentityTransformer,
)
}
struct IdentityTransformer;
impl ConfigurationTransformer for IdentityTransformer {
fn transform(&self, config: Configuration) -> Configuration {
config
}
}
#[cfg(test)]
mod tests {
use ruff_linter::line_width::LineLength;
use ruff_workspace::options::Options;
use super::*;
/// This test ensures that the inline configuration is correctly applied to the configuration.
#[test]
fn inline_settings() {
let editor_settings = ResolvedEditorSettings {
configuration: Some(ResolvedConfiguration::Inline(Options {
line_length: Some(LineLength::try_from(120).unwrap()),
..Default::default()
})),
..Default::default()
};
let config = EditorConfigurationTransformer(&editor_settings, Path::new("/src/project"))
.transform(Configuration::default());
assert_eq!(config.line_length.unwrap().value(), 120);
}
/// This test ensures that between the inline configuration and specific settings, the specific
/// settings is prioritized.
#[test]
fn inline_and_specific_settings_resolution_order() {
let editor_settings = ResolvedEditorSettings {
configuration: Some(ResolvedConfiguration::Inline(Options {
line_length: Some(LineLength::try_from(120).unwrap()),
..Default::default()
})),
line_length: Some(LineLength::try_from(100).unwrap()),
..Default::default()
};
let config = EditorConfigurationTransformer(&editor_settings, Path::new("/src/project"))
.transform(Configuration::default());
assert_eq!(config.line_length.unwrap().value(), 100);
}
}