Use backticks for code in red-knot messages (#13599)

## Summary

...and remove periods from messages that don't span more than a single
sentence.

This is more consistent with how we present user-facing messages in uv
(which has a defined style guide).
This commit is contained in:
Charlie Marsh 2024-10-01 23:14:28 -04:00 committed by GitHub
parent ef45185dbc
commit c3b40da0d2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 156 additions and 156 deletions

View file

@ -160,7 +160,7 @@ fn run() -> anyhow::Result<ExitStatus> {
SystemPathBuf::from_path_buf(cwd) SystemPathBuf::from_path_buf(cwd)
.map_err(|path| { .map_err(|path| {
anyhow!( anyhow!(
"The current working directory '{}' contains non-unicode characters. Red Knot only supports unicode paths.", "The current working directory `{}` contains non-Unicode characters. Red Knot only supports Unicode paths.",
path.display() path.display()
) )
})? })?
@ -174,7 +174,7 @@ fn run() -> anyhow::Result<ExitStatus> {
Ok(SystemPath::absolute(cwd, &cli_base_path)) Ok(SystemPath::absolute(cwd, &cli_base_path))
} else { } else {
Err(anyhow!( Err(anyhow!(
"Provided current-directory path '{cwd}' is not a directory." "Provided current-directory path `{cwd}` is not a directory"
)) ))
} }
}) })

View file

@ -42,14 +42,14 @@ impl TestCase {
fn stop_watch(&mut self) -> Vec<watch::ChangeEvent> { fn stop_watch(&mut self) -> Vec<watch::ChangeEvent> {
self.try_stop_watch(Duration::from_secs(10)) self.try_stop_watch(Duration::from_secs(10))
.expect("Expected watch changes but observed none.") .expect("Expected watch changes but observed none")
} }
fn try_stop_watch(&mut self, timeout: Duration) -> Option<Vec<watch::ChangeEvent>> { fn try_stop_watch(&mut self, timeout: Duration) -> Option<Vec<watch::ChangeEvent>> {
let watcher = self let watcher = self
.watcher .watcher
.take() .take()
.expect("Cannot call `stop_watch` more than once."); .expect("Cannot call `stop_watch` more than once");
let mut all_events = self let mut all_events = self
.changes_receiver .changes_receiver
@ -72,7 +72,7 @@ impl TestCase {
#[cfg(unix)] #[cfg(unix)]
fn take_watch_changes(&self) -> Vec<watch::ChangeEvent> { fn take_watch_changes(&self) -> Vec<watch::ChangeEvent> {
self.try_take_watch_changes(Duration::from_secs(10)) self.try_take_watch_changes(Duration::from_secs(10))
.expect("Expected watch changes but observed none.") .expect("Expected watch changes but observed none")
} }
fn try_take_watch_changes(&self, timeout: Duration) -> Option<Vec<watch::ChangeEvent>> { fn try_take_watch_changes(&self, timeout: Duration) -> Option<Vec<watch::ChangeEvent>> {
@ -150,14 +150,14 @@ where
let absolute_path = workspace_path.join(relative_path); let absolute_path = workspace_path.join(relative_path);
if let Some(parent) = absolute_path.parent() { if let Some(parent) = absolute_path.parent() {
std::fs::create_dir_all(parent).with_context(|| { std::fs::create_dir_all(parent).with_context(|| {
format!("Failed to create parent directory for file '{relative_path}'.",) format!("Failed to create parent directory for file `{relative_path}`")
})?; })?;
} }
let mut file = std::fs::File::create(absolute_path.as_std_path()) let mut file = std::fs::File::create(absolute_path.as_std_path())
.with_context(|| format!("Failed to open file '{relative_path}'"))?; .with_context(|| format!("Failed to open file `{relative_path}`"))?;
file.write_all(content.as_bytes()) file.write_all(content.as_bytes())
.with_context(|| format!("Failed to write to file '{relative_path}'"))?; .with_context(|| format!("Failed to write to file `{relative_path}`"))?;
file.sync_data()?; file.sync_data()?;
} }
@ -194,7 +194,7 @@ where
let root_path = SystemPath::from_std_path(temp_dir.path()).ok_or_else(|| { let root_path = SystemPath::from_std_path(temp_dir.path()).ok_or_else(|| {
anyhow!( anyhow!(
"Temp directory '{}' is not a valid UTF-8 path.", "Temporary directory `{}` is not a valid UTF-8 path.",
temp_dir.path().display() temp_dir.path().display()
) )
})?; })?;
@ -209,7 +209,7 @@ where
let workspace_path = root_path.join("workspace"); let workspace_path = root_path.join("workspace");
std::fs::create_dir_all(workspace_path.as_std_path()) std::fs::create_dir_all(workspace_path.as_std_path())
.with_context(|| format!("Failed to create workspace directory '{workspace_path}'",))?; .with_context(|| format!("Failed to create workspace directory `{workspace_path}`"))?;
setup_files setup_files
.setup(&root_path, &workspace_path) .setup(&root_path, &workspace_path)
@ -233,7 +233,7 @@ where
})) }))
{ {
std::fs::create_dir_all(path.as_std_path()) std::fs::create_dir_all(path.as_std_path())
.with_context(|| format!("Failed to create search path '{path}'"))?; .with_context(|| format!("Failed to create search path `{path}`"))?;
} }
let configuration = Configuration { let configuration = Configuration {
@ -665,7 +665,7 @@ fn directory_deleted() -> anyhow::Result<()> {
let bar = case.system_file(case.workspace_path("bar.py")).unwrap(); let bar = case.system_file(case.workspace_path("bar.py")).unwrap();
assert!(resolve_module(case.db().upcast(), ModuleName::new_static("sub.a").unwrap()).is_some(),); assert!(resolve_module(case.db().upcast(), ModuleName::new_static("sub.a").unwrap()).is_some());
let sub_path = case.workspace_path("sub"); let sub_path = case.workspace_path("sub");

View file

@ -36,14 +36,14 @@ pub(crate) fn resolve_module_query<'db>(
let _span = tracing::trace_span!("resolve_module", %name).entered(); let _span = tracing::trace_span!("resolve_module", %name).entered();
let Some((search_path, module_file, kind)) = resolve_name(db, name) else { let Some((search_path, module_file, kind)) = resolve_name(db, name) else {
tracing::debug!("Module '{name}' not found in the search paths."); tracing::debug!("Module `{name}` not found in search paths");
return None; return None;
}; };
let module = Module::new(name.clone(), kind, search_path, module_file); let module = Module::new(name.clone(), kind, search_path, module_file);
tracing::trace!( tracing::trace!(
"Resolved module '{name}' to '{path}'.", "Resolved module `{name}` to `{path}`",
path = module_file.path(db) path = module_file.path(db)
); );
@ -324,7 +324,7 @@ pub(crate) fn dynamic_resolution_paths(db: &dyn Db) -> Vec<SearchPath> {
let site_packages_root = files let site_packages_root = files
.root(db.upcast(), site_packages_dir) .root(db.upcast(), site_packages_dir)
.expect("Site-package root to have been created."); .expect("Site-package root to have been created");
// This query needs to be re-executed each time a `.pth` file // This query needs to be re-executed each time a `.pth` file
// is added, modified or removed from the `site-packages` directory. // is added, modified or removed from the `site-packages` directory.

View file

@ -192,7 +192,7 @@ impl VirtualEnvironment {
} else { } else {
tracing::warn!( tracing::warn!(
"Failed to resolve `sys.prefix` of the system Python installation \ "Failed to resolve `sys.prefix` of the system Python installation \
from the `home` value in the `pyvenv.cfg` file at '{}'. \ from the `home` value in the `pyvenv.cfg` file at `{}`. \
System site-packages will not be used for module resolution.", System site-packages will not be used for module resolution.",
venv_path.join("pyvenv.cfg") venv_path.join("pyvenv.cfg")
); );
@ -426,7 +426,7 @@ impl Deref for SysPrefixPath {
impl fmt::Display for SysPrefixPath { impl fmt::Display for SysPrefixPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "`sys.prefix` path '{}'", self.0) write!(f, "`sys.prefix` path `{}`", self.0)
} }
} }
@ -483,7 +483,7 @@ impl Deref for PythonHomePath {
impl fmt::Display for PythonHomePath { impl fmt::Display for PythonHomePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "`home` location '{}'", self.0) write!(f, "`home` location `{}`", self.0)
} }
} }

View file

@ -169,7 +169,7 @@ fn bindings_ty<'db>(
let first = all_types let first = all_types
.next() .next()
.expect("bindings_ty should never be called with zero definitions and no unbound_ty."); .expect("bindings_ty should never be called with zero definitions and no unbound_ty");
if let Some(second) = all_types.next() { if let Some(second) = all_types.next() {
UnionType::from_elements(db, [first, second].into_iter().chain(all_types)) UnionType::from_elements(db, [first, second].into_iter().chain(all_types))
@ -204,7 +204,7 @@ fn declarations_ty<'db>(
let mut all_types = undeclared_ty.into_iter().chain(decl_types); let mut all_types = undeclared_ty.into_iter().chain(decl_types);
let first = all_types.next().expect( let first = all_types.next().expect(
"declarations_ty must not be called with zero declarations and no may-be-undeclared.", "declarations_ty must not be called with zero declarations and no may-be-undeclared",
); );
let mut conflicting: Vec<Type<'db>> = vec![]; let mut conflicting: Vec<Type<'db>> = vec![];
@ -917,7 +917,7 @@ impl<'db> CallOutcome<'db> {
node, node,
"call-non-callable", "call-non-callable",
format_args!( format_args!(
"Object of type '{}' is not callable.", "Object of type `{}` is not callable",
not_callable_ty.display(db) not_callable_ty.display(db)
), ),
); );
@ -932,7 +932,7 @@ impl<'db> CallOutcome<'db> {
node, node,
"call-non-callable", "call-non-callable",
format_args!( format_args!(
"Object of type '{}' is not callable (due to union element '{}').", "Object of type `{}` is not callable (due to union element `{}`)",
called_ty.display(db), called_ty.display(db),
not_callable_ty.display(db), not_callable_ty.display(db),
), ),
@ -948,7 +948,7 @@ impl<'db> CallOutcome<'db> {
node, node,
"call-non-callable", "call-non-callable",
format_args!( format_args!(
"Object of type '{}' is not callable (due to union elements {}).", "Object of type `{}` is not callable (due to union elements {})",
called_ty.display(db), called_ty.display(db),
not_callable_tys.display(db), not_callable_tys.display(db),
), ),
@ -974,7 +974,7 @@ impl<'db> CallOutcome<'db> {
builder.add_diagnostic( builder.add_diagnostic(
node, node,
"revealed-type", "revealed-type",
format_args!("Revealed type is '{}'.", revealed_ty.display(db)), format_args!("Revealed type is `{}`", revealed_ty.display(db)),
); );
Ok(*return_ty) Ok(*return_ty)
} }

View file

@ -37,7 +37,7 @@ impl Display for DisplayType<'_> {
| Type::Class(_) | Type::Class(_)
| Type::Function(_) | Type::Function(_)
) { ) {
write!(f, "Literal[{representation}]",) write!(f, "Literal[{representation}]")
} else { } else {
representation.fmt(f) representation.fmt(f)
} }
@ -335,7 +335,7 @@ mod tests {
class B: ... class B: ...
", ",
)?; )?;
let mod_file = system_path_to_file(&db, "src/main.py").expect("Expected file to exist."); let mod_file = system_path_to_file(&db, "src/main.py").expect("file to exist");
let union_elements = &[ let union_elements = &[
Type::Unknown, Type::Unknown,

View file

@ -480,12 +480,12 @@ impl<'db> TypeInferenceBuilder<'db> {
match declared_ty { match declared_ty {
Type::Class(class) => { Type::Class(class) => {
self.add_diagnostic(node, "invalid-assignment", format_args!( self.add_diagnostic(node, "invalid-assignment", format_args!(
"Implicit shadowing of class '{}'; annotate to make it explicit if this is intentional.", "Implicit shadowing of class `{}`; annotate to make it explicit if this is intentional",
class.name(self.db))); class.name(self.db)));
} }
Type::Function(function) => { Type::Function(function) => {
self.add_diagnostic(node, "invalid-assignment", format_args!( self.add_diagnostic(node, "invalid-assignment", format_args!(
"Implicit shadowing of function '{}'; annotate to make it explicit if this is intentional.", "Implicit shadowing of function `{}`; annotate to make it explicit if this is intentional",
function.name(self.db))); function.name(self.db)));
} }
_ => { _ => {
@ -493,7 +493,7 @@ impl<'db> TypeInferenceBuilder<'db> {
node, node,
"invalid-assignment", "invalid-assignment",
format_args!( format_args!(
"Object of type '{}' is not assignable to '{}'.", "Object of type `{}` is not assignable to `{}`",
assigned_ty.display(self.db), assigned_ty.display(self.db),
declared_ty.display(self.db), declared_ty.display(self.db),
), ),
@ -515,9 +515,9 @@ impl<'db> TypeInferenceBuilder<'db> {
}; };
let (op, by_zero) = match expr.op { let (op, by_zero) = match expr.op {
ast::Operator::Div => ("divide", "by zero."), ast::Operator::Div => ("divide", "by zero"),
ast::Operator::FloorDiv => ("floor divide", "by zero."), ast::Operator::FloorDiv => ("floor divide", "by zero"),
ast::Operator::Mod => ("reduce", "modulo zero."), ast::Operator::Mod => ("reduce", "modulo zero"),
_ => return, _ => return,
}; };
@ -525,7 +525,7 @@ impl<'db> TypeInferenceBuilder<'db> {
expr.into(), expr.into(),
"division-by-zero", "division-by-zero",
format_args!( format_args!(
"Cannot {op} object of type '{}' {by_zero}", "Cannot {op} object of type `{}` {by_zero}",
left.display(self.db) left.display(self.db)
), ),
); );
@ -550,7 +550,7 @@ impl<'db> TypeInferenceBuilder<'db> {
node, node,
"conflicting-declarations", "conflicting-declarations",
format_args!( format_args!(
"Conflicting declared types for '{symbol_name}': {}.", "Conflicting declared types for `{symbol_name}`: {}",
conflicting.display(self.db) conflicting.display(self.db)
), ),
); );
@ -579,7 +579,7 @@ impl<'db> TypeInferenceBuilder<'db> {
node, node,
"invalid-declaration", "invalid-declaration",
format_args!( format_args!(
"Cannot declare type '{}' for inferred type '{}'.", "Cannot declare type `{}` for inferred type `{}`",
ty.display(self.db), ty.display(self.db),
inferred_ty.display(self.db) inferred_ty.display(self.db)
), ),
@ -1280,7 +1280,7 @@ impl<'db> TypeInferenceBuilder<'db> {
node, node,
"not-iterable", "not-iterable",
format_args!( format_args!(
"Object of type '{}' is not iterable.", "Object of type `{}` is not iterable",
not_iterable_ty.display(self.db) not_iterable_ty.display(self.db)
), ),
); );
@ -1298,7 +1298,7 @@ impl<'db> TypeInferenceBuilder<'db> {
node, node,
"index-out-of-bounds", "index-out-of-bounds",
format_args!( format_args!(
"Index {index} is out of bounds for tuple of type '{}' with length {length}.", "Index {index} is out of bounds for tuple of type `{}` with length {length}",
tuple_ty.display(self.db) tuple_ty.display(self.db)
), ),
); );
@ -1316,7 +1316,7 @@ impl<'db> TypeInferenceBuilder<'db> {
node, node,
"index-out-of-bounds", "index-out-of-bounds",
format_args!( format_args!(
"Index {index} is out of bounds for string '{}' with length {length}.", "Index {index} is out of bounds for string `{}` with length {length}",
string_ty.display(self.db) string_ty.display(self.db)
), ),
); );
@ -1333,7 +1333,7 @@ impl<'db> TypeInferenceBuilder<'db> {
node, node,
"non-subscriptable", "non-subscriptable",
format_args!( format_args!(
"Cannot subscript object of type '{}' with no `{method}` method.", "Cannot subscript object of type `{}` with no `{method}` method",
non_subscriptable_ty.display(self.db) non_subscriptable_ty.display(self.db)
), ),
); );
@ -1455,7 +1455,7 @@ impl<'db> TypeInferenceBuilder<'db> {
import_node.into(), import_node.into(),
"unresolved-import", "unresolved-import",
format_args!( format_args!(
"Cannot resolve import '{}{}'.", "Cannot resolve import `{}{}`",
".".repeat(level as usize), ".".repeat(level as usize),
module.unwrap_or_default() module.unwrap_or_default()
), ),
@ -1516,7 +1516,7 @@ impl<'db> TypeInferenceBuilder<'db> {
let module_name = if let Some(level) = NonZeroU32::new(*level) { let module_name = if let Some(level) = NonZeroU32::new(*level) {
tracing::trace!( tracing::trace!(
"Resolving imported object '{}' from module '{}' relative to file '{}'", "Resolving imported object `{}` from module `{}` relative to file `{}`",
alias.name, alias.name,
format_import_from_module(level.get(), module), format_import_from_module(level.get(), module),
self.file.path(self.db), self.file.path(self.db),
@ -1524,7 +1524,7 @@ impl<'db> TypeInferenceBuilder<'db> {
self.relative_module_name(module, level) self.relative_module_name(module, level)
} else { } else {
tracing::trace!( tracing::trace!(
"Resolving imported object '{}' from module '{}'", "Resolving imported object `{}` from module `{}`",
alias.name, alias.name,
format_import_from_module(*level, module), format_import_from_module(*level, module),
); );
@ -1549,7 +1549,7 @@ impl<'db> TypeInferenceBuilder<'db> {
} }
Err(ModuleNameResolutionError::TooManyDots) => { Err(ModuleNameResolutionError::TooManyDots) => {
tracing::debug!( tracing::debug!(
"Relative module resolution '{}' failed: too many leading dots", "Relative module resolution `{}` failed: too many leading dots",
format_import_from_module(*level, module), format_import_from_module(*level, module),
); );
self.unresolved_module_diagnostic(import_from, *level, module); self.unresolved_module_diagnostic(import_from, *level, module);
@ -1557,7 +1557,7 @@ impl<'db> TypeInferenceBuilder<'db> {
} }
Err(ModuleNameResolutionError::UnknownCurrentModule) => { Err(ModuleNameResolutionError::UnknownCurrentModule) => {
tracing::debug!( tracing::debug!(
"Relative module resolution '{}' failed; could not resolve file '{}' to a module", "Relative module resolution `{}` failed; could not resolve file `{}` to a module",
format_import_from_module(*level, module), format_import_from_module(*level, module),
self.file.path(self.db) self.file.path(self.db)
); );
@ -1580,7 +1580,7 @@ impl<'db> TypeInferenceBuilder<'db> {
AnyNodeRef::Alias(alias), AnyNodeRef::Alias(alias),
"unresolved-import", "unresolved-import",
format_args!( format_args!(
"Module '{}{}' has no member '{name}'", "Module `{}{}` has no member `{name}`",
".".repeat(*level as usize), ".".repeat(*level as usize),
module.unwrap_or_default() module.unwrap_or_default()
), ),
@ -2220,7 +2220,7 @@ impl<'db> TypeInferenceBuilder<'db> {
name_node.into(), name_node.into(),
"undefined-reveal", "undefined-reveal",
format_args!( format_args!(
"'reveal_type' used without importing it; this is allowed for debugging convenience but will fail at runtime."), "`reveal_type` used without importing it; this is allowed for debugging convenience but will fail at runtime"),
); );
builtin_ty = typing_extensions_symbol_ty(self.db, name); builtin_ty = typing_extensions_symbol_ty(self.db, name);
} }
@ -2622,7 +2622,7 @@ impl<'db> TypeInferenceBuilder<'db> {
(&**value).into(), (&**value).into(),
"call-non-callable", "call-non-callable",
format_args!( format_args!(
"Method `__getitem__` of type '{}' is not callable on object of type '{}'.", "Method `__getitem__` of type `{}` is not callable on object of type `{}`",
err.called_ty().display(self.db), err.called_ty().display(self.db),
value_ty.display(self.db), value_ty.display(self.db),
), ),
@ -2644,7 +2644,7 @@ impl<'db> TypeInferenceBuilder<'db> {
(&**value).into(), (&**value).into(),
"call-non-callable", "call-non-callable",
format_args!( format_args!(
"Method `__class_getitem__` of type '{}' is not callable on object of type '{}'.", "Method `__class_getitem__` of type `{}` is not callable on object of type `{}`",
err.called_ty().display(self.db), err.called_ty().display(self.db),
value_ty.display(self.db), value_ty.display(self.db),
), ),
@ -3065,7 +3065,7 @@ mod tests {
} }
fn assert_public_ty(db: &TestDb, file_name: &str, symbol_name: &str, expected: &str) { fn assert_public_ty(db: &TestDb, file_name: &str, symbol_name: &str, expected: &str) {
let file = system_path_to_file(db, file_name).expect("Expected file to exist."); let file = system_path_to_file(db, file_name).expect("file to exist");
let ty = global_symbol_ty(db, file, symbol_name); let ty = global_symbol_ty(db, file, symbol_name);
assert_eq!( assert_eq!(
@ -3082,7 +3082,7 @@ mod tests {
symbol_name: &str, symbol_name: &str,
expected: &str, expected: &str,
) { ) {
let file = system_path_to_file(db, file_name).expect("Expected file to exist."); let file = system_path_to_file(db, file_name).expect("file to exist");
let index = semantic_index(db, file); let index = semantic_index(db, file);
let mut file_scope_id = FileScopeId::global(); let mut file_scope_id = FileScopeId::global();
let mut scope = file_scope_id.to_scope_id(db, file); let mut scope = file_scope_id.to_scope_id(db, file);
@ -3129,7 +3129,7 @@ mod tests {
", ",
)?; )?;
assert_file_diagnostics(&db, "/src/a.py", &["Revealed type is 'Literal[1]'."]); assert_file_diagnostics(&db, "/src/a.py", &["Revealed type is `Literal[1]`"]);
Ok(()) Ok(())
} }
@ -3148,7 +3148,7 @@ mod tests {
", ",
)?; )?;
assert_file_diagnostics(&db, "/src/a.py", &["Revealed type is 'Literal[1]'."]); assert_file_diagnostics(&db, "/src/a.py", &["Revealed type is `Literal[1]`"]);
Ok(()) Ok(())
} }
@ -3167,7 +3167,7 @@ mod tests {
", ",
)?; )?;
assert_file_diagnostics(&db, "/src/a.py", &["Revealed type is 'Literal[1]'."]); assert_file_diagnostics(&db, "/src/a.py", &["Revealed type is `Literal[1]`"]);
Ok(()) Ok(())
} }
@ -3188,8 +3188,8 @@ mod tests {
&db, &db,
"/src/a.py", "/src/a.py",
&[ &[
"'reveal_type' used without importing it; this is allowed for debugging convenience but will fail at runtime.", "`reveal_type` used without importing it; this is allowed for debugging convenience but will fail at runtime",
"Revealed type is 'Literal[1]'.", "Revealed type is `Literal[1]`",
], ],
); );
@ -3395,7 +3395,7 @@ mod tests {
", ",
)?; )?;
let mod_file = system_path_to_file(&db, "src/mod.py").expect("Expected file to exist."); let mod_file = system_path_to_file(&db, "src/mod.py").expect("file to exist");
let ty = global_symbol_ty(&db, mod_file, "Sub"); let ty = global_symbol_ty(&db, mod_file, "Sub");
let class = ty.expect_class(); let class = ty.expect_class();
@ -4144,7 +4144,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"src/a.py", "src/a.py",
&["Object of type 'Literal[1] | Literal[f]' is not callable (due to union element 'Literal[1]')."], &["Object of type `Literal[1] | Literal[f]` is not callable (due to union element `Literal[1]`)"],
); );
assert_public_ty(&db, "src/a.py", "x", "Unknown | int"); assert_public_ty(&db, "src/a.py", "x", "Unknown | int");
@ -4173,7 +4173,7 @@ mod tests {
&db, &db,
"src/a.py", "src/a.py",
&[ &[
r#"Object of type 'Literal[1] | Literal["foo"] | Literal[f]' is not callable (due to union elements Literal[1], Literal["foo"])."#, r#"Object of type `Literal[1] | Literal["foo"] | Literal[f]` is not callable (due to union elements Literal[1], Literal["foo"])"#,
], ],
); );
assert_public_ty(&db, "src/a.py", "x", "Unknown | int"); assert_public_ty(&db, "src/a.py", "x", "Unknown | int");
@ -4199,7 +4199,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"src/a.py", "src/a.py",
&[r#"Object of type 'Literal[1] | Literal["foo"]' is not callable."#], &[r#"Object of type `Literal[1] | Literal["foo"]` is not callable"#],
); );
assert_public_ty(&db, "src/a.py", "x", "Unknown"); assert_public_ty(&db, "src/a.py", "x", "Unknown");
@ -4222,7 +4222,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Object of type 'Literal[123]' is not callable."], &["Object of type `Literal[123]` is not callable"],
); );
} }
@ -4297,11 +4297,11 @@ mod tests {
&db, &db,
"src/a.py", "src/a.py",
&[ &[
"Cannot divide object of type 'Literal[1]' by zero.", "Cannot divide object of type `Literal[1]` by zero",
"Cannot floor divide object of type 'Literal[2]' by zero.", "Cannot floor divide object of type `Literal[2]` by zero",
"Cannot reduce object of type 'Literal[3]' modulo zero.", "Cannot reduce object of type `Literal[3]` modulo zero",
"Cannot divide object of type 'int' by zero.", "Cannot divide object of type `int` by zero",
"Cannot divide object of type 'float' by zero.", "Cannot divide object of type `float` by zero",
], ],
); );
@ -4647,7 +4647,7 @@ mod tests {
", ",
)?; )?;
let a = system_path_to_file(&db, "src/a.py").expect("Expected file to exist."); let a = system_path_to_file(&db, "src/a.py").expect("file to exist");
let c_ty = global_symbol_ty(&db, a, "C"); let c_ty = global_symbol_ty(&db, a, "C");
let c_class = c_ty.expect_class(); let c_class = c_ty.expect_class();
let mut c_bases = c_class.bases(&db); let mut c_bases = c_class.bases(&db);
@ -4677,7 +4677,7 @@ mod tests {
", ",
)?; )?;
let file = system_path_to_file(&db, "src/a.py").expect("Expected file to exist."); let file = system_path_to_file(&db, "src/a.py").expect("file to exist");
let index = semantic_index(&db, file); let index = semantic_index(&db, file);
let function_scope = index let function_scope = index
.child_scopes(FileScopeId::global()) .child_scopes(FileScopeId::global())
@ -4708,7 +4708,7 @@ mod tests {
", ",
)?; )?;
let file = system_path_to_file(&db, "src/a.py").expect("Expected file to exist."); let file = system_path_to_file(&db, "src/a.py").expect("file to exist");
let index = semantic_index(&db, file); let index = semantic_index(&db, file);
let function_scope = index let function_scope = index
.child_scopes(FileScopeId::global()) .child_scopes(FileScopeId::global())
@ -4739,7 +4739,7 @@ mod tests {
", ",
)?; )?;
let file = system_path_to_file(&db, "src/a.py").expect("Expected file to exist."); let file = system_path_to_file(&db, "src/a.py").expect("file to exist");
let index = semantic_index(&db, file); let index = semantic_index(&db, file);
let function_scope = index let function_scope = index
.child_scopes(FileScopeId::global()) .child_scopes(FileScopeId::global())
@ -4773,7 +4773,7 @@ mod tests {
", ",
)?; )?;
let file = system_path_to_file(&db, "src/a.py").expect("Expected file to exist."); let file = system_path_to_file(&db, "src/a.py").expect("file to exist");
let index = semantic_index(&db, file); let index = semantic_index(&db, file);
let class_scope = index let class_scope = index
.child_scopes(FileScopeId::global()) .child_scopes(FileScopeId::global())
@ -4874,7 +4874,7 @@ mod tests {
assert_public_ty(&db, "/src/a.py", "x", "Literal[copyright]"); assert_public_ty(&db, "/src/a.py", "x", "Literal[copyright]");
// imported builtins module is the same file as the implicit builtins // imported builtins module is the same file as the implicit builtins
let file = system_path_to_file(&db, "/src/a.py").expect("Expected file to exist."); let file = system_path_to_file(&db, "/src/a.py").expect("file to exist");
let builtins_ty = global_symbol_ty(&db, file, "builtins"); let builtins_ty = global_symbol_ty(&db, file, "builtins");
let builtins_file = builtins_ty.expect_module(); let builtins_file = builtins_ty.expect_module();
let implicit_builtins_file = builtins_module_scope(&db) let implicit_builtins_file = builtins_module_scope(&db)
@ -5388,7 +5388,7 @@ mod tests {
db.write_file("src/foo.py", "import bar\n").unwrap(); db.write_file("src/foo.py", "import bar\n").unwrap();
assert_file_diagnostics(&db, "src/foo.py", &["Cannot resolve import 'bar'."]); assert_file_diagnostics(&db, "src/foo.py", &["Cannot resolve import `bar`"]);
} }
#[test] #[test]
@ -5397,7 +5397,7 @@ mod tests {
db.write_file("src/foo.py", "from bar import baz\n") db.write_file("src/foo.py", "from bar import baz\n")
.unwrap(); .unwrap();
assert_file_diagnostics(&db, "/src/foo.py", &["Cannot resolve import 'bar'."]); assert_file_diagnostics(&db, "/src/foo.py", &["Cannot resolve import `bar`"]);
} }
#[test] #[test]
@ -5407,7 +5407,7 @@ mod tests {
db.write_files([("/src/a.py", ""), ("/src/b.py", "from a import thing")]) db.write_files([("/src/a.py", ""), ("/src/b.py", "from a import thing")])
.unwrap(); .unwrap();
assert_file_diagnostics(&db, "/src/b.py", &["Module 'a' has no member 'thing'"]); assert_file_diagnostics(&db, "/src/b.py", &["Module `a` has no member `thing`"]);
} }
#[test] #[test]
@ -5420,7 +5420,7 @@ mod tests {
]) ])
.unwrap(); .unwrap();
assert_file_diagnostics(&db, "/src/a.py", &["Cannot resolve import 'foo'."]); assert_file_diagnostics(&db, "/src/a.py", &["Cannot resolve import `foo`"]);
// Importing the unresolved import into a second first-party file should not trigger // Importing the unresolved import into a second first-party file should not trigger
// an additional "unresolved import" violation // an additional "unresolved import" violation
@ -5658,7 +5658,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"src/a.py", "src/a.py",
&["Object of type 'NotIterable' is not iterable."], &["Object of type `NotIterable` is not iterable"],
); );
assert_public_ty(&db, "src/a.py", "x", "Unbound | Unknown"); assert_public_ty(&db, "src/a.py", "x", "Unbound | Unknown");
@ -5709,7 +5709,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"src/a.py", "src/a.py",
&["Cannot resolve import 'nonexistent_module'."], &["Cannot resolve import `nonexistent_module`"],
); );
assert_public_ty(&db, "src/a.py", "foo", "Unknown"); assert_public_ty(&db, "src/a.py", "foo", "Unknown");
assert_public_ty(&db, "src/a.py", "e", "Unknown"); assert_public_ty(&db, "src/a.py", "e", "Unknown");
@ -5969,7 +5969,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"src/a.py", "src/a.py",
&["Object of type 'Unbound' is not iterable."], &["Object of type `Unbound` is not iterable"],
); );
Ok(()) Ok(())
@ -5997,7 +5997,7 @@ mod tests {
assert_scope_ty(&db, "src/a.py", &["foo", "<listcomp>"], "x", "int"); assert_scope_ty(&db, "src/a.py", &["foo", "<listcomp>"], "x", "int");
assert_scope_ty(&db, "src/a.py", &["foo", "<listcomp>"], "z", "Unknown"); assert_scope_ty(&db, "src/a.py", &["foo", "<listcomp>"], "z", "Unknown");
assert_file_diagnostics(&db, "src/a.py", &["Object of type 'int' is not iterable."]); assert_file_diagnostics(&db, "src/a.py", &["Object of type `int` is not iterable"]);
Ok(()) Ok(())
} }
@ -6193,7 +6193,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Object of type 'Literal[123]' is not iterable."], &["Object of type `Literal[123]` is not iterable"],
); );
} }
@ -6219,7 +6219,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Object of type 'NotIterable' is not iterable."], &["Object of type `NotIterable` is not iterable"],
); );
} }
@ -6248,7 +6248,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Object of type 'NotIterable' is not iterable."], &["Object of type `NotIterable` is not iterable"],
); );
} }
@ -6278,7 +6278,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Object of type 'NotIterable' is not iterable."], &["Object of type `NotIterable` is not iterable"],
); );
} }
@ -6297,7 +6297,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&[r#"Object of type 'Literal["foo"]' is not assignable to 'int'."#], &[r#"Object of type `Literal["foo"]` is not assignable to `int`"#],
); );
} }
@ -6317,7 +6317,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&[r#"Object of type 'Literal["foo"]' is not assignable to 'int'."#], &[r#"Object of type `Literal["foo"]` is not assignable to `int`"#],
); );
} }
@ -6369,7 +6369,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&[r"Cannot declare type 'str' for inferred type 'Literal[1]'."], &[r"Cannot declare type `str` for inferred type `Literal[1]`"],
); );
} }
@ -6392,7 +6392,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&[r"Conflicting declared types for 'x': str, int."], &[r"Conflicting declared types for `x`: str, int"],
); );
} }
@ -6413,7 +6413,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&[r"Conflicting declared types for 'x': Unknown, int."], &[r"Conflicting declared types for `x`: Unknown, int"],
); );
} }
@ -6437,8 +6437,8 @@ mod tests {
&db, &db,
"/src/a.py", "/src/a.py",
&[ &[
r"Conflicting declared types for 'x': str, int.", r"Conflicting declared types for `x`: str, int",
r#"Object of type 'Literal[b"foo"]' is not assignable to 'str | int'."#, r#"Object of type `Literal[b"foo"]` is not assignable to `str | int`"#,
], ],
); );
} }
@ -6460,7 +6460,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&[r"Conflicting declared types for 'x': Unknown, int."], &[r"Conflicting declared types for `x`: Unknown, int"],
); );
} }
@ -6499,7 +6499,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Implicit shadowing of function 'f'; annotate to make it explicit if this is intentional."], &["Implicit shadowing of function `f`; annotate to make it explicit if this is intentional"],
); );
} }
@ -6519,7 +6519,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Implicit shadowing of class 'C'; annotate to make it explicit if this is intentional."], &["Implicit shadowing of class `C`; annotate to make it explicit if this is intentional"],
); );
} }
@ -6574,7 +6574,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&[r#"Object of type 'Literal["foo"]' is not assignable to 'int'."#], &[r#"Object of type `Literal["foo"]` is not assignable to `int`"#],
); );
} }
@ -6755,7 +6755,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"src/a.py", "src/a.py",
&["Index 4 is out of bounds for tuple of type 'tuple[Literal[1], Literal[\"a\"], Literal[\"b\"]]' with length 3.", "Index -4 is out of bounds for tuple of type 'tuple[Literal[1], Literal[\"a\"], Literal[\"b\"]]' with length 3."], &["Index 4 is out of bounds for tuple of type `tuple[Literal[1], Literal[\"a\"], Literal[\"b\"]]` with length 3", "Index -4 is out of bounds for tuple of type `tuple[Literal[1], Literal[\"a\"], Literal[\"b\"]]` with length 3"],
); );
Ok(()) Ok(())
@ -6790,8 +6790,8 @@ mod tests {
&db, &db,
"src/a.py", "src/a.py",
&[ &[
"Index 8 is out of bounds for string 'Literal[\"abcde\"]' with length 5.", "Index 8 is out of bounds for string `Literal[\"abcde\"]` with length 5",
"Index -8 is out of bounds for string 'Literal[\"abcde\"]' with length 5.", "Index -8 is out of bounds for string `Literal[\"abcde\"]` with length 5",
], ],
); );
@ -6816,7 +6816,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Cannot subscript object of type 'NotSubscriptable' with no `__getitem__` method."], &["Cannot subscript object of type `NotSubscriptable` with no `__getitem__` method"],
); );
Ok(()) Ok(())
@ -6840,7 +6840,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Cannot subscript object of type 'Literal[NotSubscriptable]' with no `__class_getitem__` method."], &["Cannot subscript object of type `Literal[NotSubscriptable]` with no `__class_getitem__` method"],
); );
Ok(()) Ok(())
@ -6864,7 +6864,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Method `__getitem__` of type 'None' is not callable on object of type 'NotSubscriptable'."], &["Method `__getitem__` of type `None` is not callable on object of type `NotSubscriptable`"],
); );
Ok(()) Ok(())
@ -7039,7 +7039,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Method `__class_getitem__` of type 'Literal[__class_getitem__] | Unbound' is not callable on object of type 'Literal[Identity, Identity]'."], &["Method `__class_getitem__` of type `Literal[__class_getitem__] | Unbound` is not callable on object of type `Literal[Identity, Identity]`"],
); );
Ok(()) Ok(())
@ -7071,7 +7071,7 @@ mod tests {
assert_file_diagnostics( assert_file_diagnostics(
&db, &db,
"/src/a.py", "/src/a.py",
&["Cannot subscript object of type 'Literal[Identity] | Literal[1]' with no `__getitem__` method."], &["Cannot subscript object of type `Literal[Identity] | Literal[1]` with no `__getitem__` method"],
); );
Ok(()) Ok(())
@ -7103,7 +7103,7 @@ mod tests {
assert_public_ty(&db, "/src/a.py", "a", "float"); assert_public_ty(&db, "/src/a.py", "a", "float");
assert_public_ty(&db, "/src/a.py", "b", "Unknown"); assert_public_ty(&db, "/src/a.py", "b", "Unknown");
assert_file_diagnostics(&db, "src/a.py", &["Object of type 'Unit' is not callable."]); assert_file_diagnostics(&db, "src/a.py", &["Object of type `Unit` is not callable"]);
Ok(()) Ok(())
} }

View file

@ -47,7 +47,7 @@ impl BackgroundDocumentRequestHandler for DocumentDiagnosticRequestHandler {
fn compute_diagnostics(snapshot: &DocumentSnapshot, db: &RootDatabase) -> Vec<Diagnostic> { fn compute_diagnostics(snapshot: &DocumentSnapshot, db: &RootDatabase) -> Vec<Diagnostic> {
let Some(file) = snapshot.file(db) else { let Some(file) = snapshot.file(db) else {
tracing::info!( tracing::info!(
"No file found for snapshot for '{}'", "No file found for snapshot for `{}`",
snapshot.query().file_url() snapshot.query().file_url()
); );
return vec![]; return vec![];

View file

@ -19,6 +19,6 @@ fn check() {
assert_eq!( assert_eq!(
result, result,
vec!["/test.py:1:8: Cannot resolve import 'random22'."] vec!["/test.py:1:8: Cannot resolve import `random22`"]
); );
} }

View file

@ -157,7 +157,7 @@ impl RootDatabase {
base_configuration.cloned(), base_configuration.cloned(),
) { ) {
Ok(metadata) => { Ok(metadata) => {
tracing::debug!("Reloading workspace after structural change."); tracing::debug!("Reloading workspace after structural change");
// TODO: Handle changes in the program settings. // TODO: Handle changes in the program settings.
workspace.reload(self, metadata); workspace.reload(self, metadata);
} }

View file

@ -118,13 +118,13 @@ fn lint_maybe_undefined(context: &SemanticLintContext, name: &ast::ExprName) {
if ty.is_unbound() { if ty.is_unbound() {
context.push_diagnostic(format_diagnostic( context.push_diagnostic(format_diagnostic(
context, context,
&format!("Name '{}' used when not defined.", &name.id), &format!("Name `{}` used when not defined", &name.id),
name.start(), name.start(),
)); ));
} else if ty.may_be_unbound(semantic.db()) { } else if ty.may_be_unbound(semantic.db()) {
context.push_diagnostic(format_diagnostic( context.push_diagnostic(format_diagnostic(
context, context,
&format!("Name '{}' used when possibly not defined.", &name.id), &format!("Name `{}` used when possibly not defined", &name.id),
name.start(), name.start(),
)); ));
} }
@ -304,13 +304,13 @@ mod tests {
*messages, *messages,
if cfg!(windows) { if cfg!(windows) {
vec![ vec![
"\\src\\a.py:3:4: Name 'flag' used when not defined.", "\\src\\a.py:3:4: Name `flag` used when not defined",
"\\src\\a.py:5:1: Name 'y' used when possibly not defined.", "\\src\\a.py:5:1: Name `y` used when possibly not defined",
] ]
} else { } else {
vec![ vec![
"/src/a.py:3:4: Name 'flag' used when not defined.", "/src/a.py:3:4: Name `flag` used when not defined",
"/src/a.py:5:1: Name 'y' used when possibly not defined.", "/src/a.py:5:1: Name `y` used when possibly not defined",
] ]
} }
); );

View file

@ -109,7 +109,7 @@ struct WatcherInner {
impl Watcher { impl Watcher {
/// Sets up file watching for `path`. /// Sets up file watching for `path`.
pub fn watch(&mut self, path: &SystemPath) -> notify::Result<()> { pub fn watch(&mut self, path: &SystemPath) -> notify::Result<()> {
tracing::debug!("Watching path: '{path}'."); tracing::debug!("Watching path: `{path}`");
self.inner_mut() self.inner_mut()
.watcher .watcher
@ -118,7 +118,7 @@ impl Watcher {
/// Stops file watching for `path`. /// Stops file watching for `path`.
pub fn unwatch(&mut self, path: &SystemPath) -> notify::Result<()> { pub fn unwatch(&mut self, path: &SystemPath) -> notify::Result<()> {
tracing::debug!("Unwatching path: '{path}'."); tracing::debug!("Unwatching path: `{path}`");
self.inner_mut().watcher.unwatch(path.as_std_path()) self.inner_mut().watcher.unwatch(path.as_std_path())
} }
@ -157,11 +157,11 @@ impl Watcher {
} }
fn inner(&self) -> &WatcherInner { fn inner(&self) -> &WatcherInner {
self.inner.as_ref().expect("Watcher to be running.") self.inner.as_ref().expect("Watcher to be running")
} }
fn inner_mut(&mut self) -> &mut WatcherInner { fn inner_mut(&mut self) -> &mut WatcherInner {
self.inner.as_mut().expect("Watcher to be running.") self.inner.as_mut().expect("Watcher to be running")
} }
} }
@ -179,7 +179,7 @@ struct Debouncer {
impl Debouncer { impl Debouncer {
fn add_result(&mut self, result: notify::Result<notify::Event>) { fn add_result(&mut self, result: notify::Result<notify::Event>) {
tracing::trace!("Handling file watcher event: {result:?}."); tracing::trace!("Handling file watcher event: {result:?}");
match result { match result {
Ok(event) => self.add_event(event), Ok(event) => self.add_event(event),
Err(error) => self.add_error(error), Err(error) => self.add_error(error),
@ -192,7 +192,7 @@ impl Debouncer {
// are IO errors. All other errors should really only happen when adding or removing a watched folders. // are IO errors. All other errors should really only happen when adding or removing a watched folders.
// It's not clear what an upstream handler should do in the case of an IOError (other than logging it). // It's not clear what an upstream handler should do in the case of an IOError (other than logging it).
// That's what we do for now as well. // That's what we do for now as well.
tracing::warn!("File watcher error: {error:?}."); tracing::warn!("File watcher error: {error:?}");
} }
fn add_event(&mut self, event: notify::Event) { fn add_event(&mut self, event: notify::Event) {
@ -214,7 +214,7 @@ impl Debouncer {
Ok(path) => path, Ok(path) => path,
Err(path) => { Err(path) => {
tracing::debug!( tracing::debug!(
"Ignore change to non-UTF8 path '{path}': {kind:?}", "Ignore change to non-UTF8 path `{path}`: {kind:?}",
path = path.display() path = path.display()
); );
@ -351,7 +351,7 @@ impl Debouncer {
} }
EventKind::Any => { EventKind::Any => {
tracing::debug!("Skipping any FS event for '{path}'."); tracing::debug!("Skipping any FS event for `{path}`");
return; return;
} }
}; };

View file

@ -62,7 +62,7 @@ impl WorkspaceWatcher {
// ``` // ```
for path in self.watched_paths.drain(..) { for path in self.watched_paths.drain(..) {
if let Err(error) = self.watcher.unwatch(&path) { if let Err(error) = self.watcher.unwatch(&path) {
info!("Failed to remove the file watcher for the path '{path}: {error}."); info!("Failed to remove the file watcher for path `{path}`: {error}");
} }
} }
@ -90,7 +90,7 @@ impl WorkspaceWatcher {
// Ruff otherwise stills works as expected. // Ruff otherwise stills works as expected.
if let Err(error) = self.watcher.watch(&path) { if let Err(error) = self.watcher.watch(&path) {
// TODO: Log a user-facing warning. // TODO: Log a user-facing warning.
tracing::warn!("Failed to setup watcher for path '{path}': {error}. You have to restart Ruff after making changes to files under this path or you might see stale results."); tracing::warn!("Failed to setup watcher for path `{path}`: {error}. You have to restart Ruff after making changes to files under this path or you might see stale results.");
self.has_errored_paths = true; self.has_errored_paths = true;
} else { } else {
self.watched_paths.push(path); self.watched_paths.push(path);

View file

@ -226,7 +226,7 @@ impl Workspace {
/// ///
/// This changes the behavior of `check` to only check the open files rather than all files in the workspace. /// This changes the behavior of `check` to only check the open files rather than all files in the workspace.
pub fn open_file(self, db: &mut dyn Db, file: File) { pub fn open_file(self, db: &mut dyn Db, file: File) {
tracing::debug!("Opening file '{}'", file.path(db)); tracing::debug!("Opening file `{}`", file.path(db));
let mut open_files = self.take_open_files(db); let mut open_files = self.take_open_files(db);
open_files.insert(file); open_files.insert(file);
@ -235,7 +235,7 @@ impl Workspace {
/// Closes a file in the workspace. /// Closes a file in the workspace.
pub fn close_file(self, db: &mut dyn Db, file: File) -> bool { pub fn close_file(self, db: &mut dyn Db, file: File) -> bool {
tracing::debug!("Closing file '{}'", file.path(db)); tracing::debug!("Closing file `{}`", file.path(db));
let mut open_files = self.take_open_files(db); let mut open_files = self.take_open_files(db);
let removed = open_files.remove(&file); let removed = open_files.remove(&file);
@ -310,7 +310,7 @@ impl Package {
#[tracing::instrument(level = "debug", skip(db))] #[tracing::instrument(level = "debug", skip(db))]
pub fn remove_file(self, db: &mut dyn Db, file: File) { pub fn remove_file(self, db: &mut dyn Db, file: File) {
tracing::debug!( tracing::debug!(
"Removing file '{}' from package '{}'", "Removing file `{}` from package `{}`",
file.path(db), file.path(db),
self.name(db) self.name(db)
); );
@ -324,7 +324,7 @@ impl Package {
pub fn add_file(self, db: &mut dyn Db, file: File) { pub fn add_file(self, db: &mut dyn Db, file: File) {
tracing::debug!( tracing::debug!(
"Adding file '{}' to package '{}'", "Adding file `{}` to package `{}`",
file.path(db), file.path(db),
self.name(db) self.name(db)
); );
@ -346,7 +346,7 @@ impl Package {
tracing::debug_span!("index_package_files", package = %self.name(db)).entered(); tracing::debug_span!("index_package_files", package = %self.name(db)).entered();
let files = discover_package_files(db, self.root(db)); let files = discover_package_files(db, self.root(db));
tracing::info!("Found {} files in package '{}'", files.len(), self.name(db)); tracing::info!("Found {} files in package `{}`", files.len(), self.name(db));
vacant.set(files) vacant.set(files)
} }
Index::Indexed(indexed) => indexed, Index::Indexed(indexed) => indexed,
@ -372,7 +372,7 @@ impl Package {
} }
pub fn reload_files(self, db: &mut dyn Db) { pub fn reload_files(self, db: &mut dyn Db) {
tracing::debug!("Reloading files for package '{}'", self.name(db)); tracing::debug!("Reloading files for package `{}`", self.name(db));
if !self.file_set(db).is_lazy() { if !self.file_set(db).is_lazy() {
// Force a re-index of the files in the next revision. // Force a re-index of the files in the next revision.

View file

@ -111,7 +111,7 @@ impl Cache {
return Cache::empty(path, package_root); return Cache::empty(path, package_root);
} }
Err(err) => { Err(err) => {
warn_user!("Failed to open cache file '{}': {err}", path.display()); warn_user!("Failed to open cache file `{}`: {err}", path.display());
return Cache::empty(path, package_root); return Cache::empty(path, package_root);
} }
}; };
@ -119,7 +119,7 @@ impl Cache {
let mut package: PackageCache = match bincode::deserialize_from(BufReader::new(file)) { let mut package: PackageCache = match bincode::deserialize_from(BufReader::new(file)) {
Ok(package) => package, Ok(package) => package,
Err(err) => { Err(err) => {
warn_user!("Failed parse cache file '{}': {err}", path.display()); warn_user!("Failed parse cache file `{}`: {err}", path.display());
return Cache::empty(path, package_root); return Cache::empty(path, package_root);
} }
}; };
@ -127,7 +127,7 @@ impl Cache {
// Sanity check. // Sanity check.
if package.package_root != package_root { if package.package_root != package_root {
warn_user!( warn_user!(
"Different package root in cache: expected '{}', got '{}'", "Different package root in cache: expected `{}`, got `{}`",
package_root.display(), package_root.display(),
package.package_root.display(), package.package_root.display(),
); );
@ -185,7 +185,7 @@ impl Cache {
// the user is running Ruff from multiple processes over the same directory). // the user is running Ruff from multiple processes over the same directory).
if cfg!(windows) && err.error.kind() == io::ErrorKind::PermissionDenied { if cfg!(windows) && err.error.kind() == io::ErrorKind::PermissionDenied {
warn_user!( warn_user!(
"Failed to write cache file '{}': {}", "Failed to write cache file `{}`: {}",
self.path.display(), self.path.display(),
err.error err.error
); );
@ -674,7 +674,7 @@ mod tests {
assert!( assert!(
cache.package.files.contains_key(relative_path), cache.package.files.contains_key(relative_path),
"missing file from cache: '{}'", "missing file from cache: `{}`",
relative_path.display() relative_path.display()
); );
} }

View file

@ -24,8 +24,8 @@ const TOMLLIB_312_URL: &str = "https://raw.githubusercontent.com/python/cpython/
// The failed import from 'collections.abc' is due to lack of support for 'import *'. // The failed import from 'collections.abc' is due to lack of support for 'import *'.
static EXPECTED_DIAGNOSTICS: &[&str] = &[ static EXPECTED_DIAGNOSTICS: &[&str] = &[
"/src/tomllib/__init__.py:10:30: Name '__name__' used when not defined.", "/src/tomllib/__init__.py:10:30: Name `__name__` used when not defined",
"/src/tomllib/_parser.py:7:29: Module 'collections.abc' has no member 'Iterable'", "/src/tomllib/_parser.py:7:29: Module `collections.abc` has no member `Iterable`",
"Line 69 is too long (89 characters)", "Line 69 is too long (89 characters)",
"Use double quotes for strings", "Use double quotes for strings",
"Use double quotes for strings", "Use double quotes for strings",

View file

@ -132,7 +132,7 @@ impl Files {
Err(_) => return Err(FileError::NotFound), Err(_) => return Err(FileError::NotFound),
}; };
tracing::trace!("Adding vendored file '{}'", path); tracing::trace!("Adding vendored file `{}`", path);
let file = File::builder(FilePath::Vendored(path.to_path_buf())) let file = File::builder(FilePath::Vendored(path.to_path_buf()))
.permissions(Some(0o444)) .permissions(Some(0o444))
.revision(metadata.revision()) .revision(metadata.revision())
@ -406,17 +406,17 @@ impl File {
}; };
if file.status(db) != status { if file.status(db) != status {
tracing::debug!("Updating the status of '{}'", file.path(db),); tracing::debug!("Updating the status of `{}`", file.path(db));
file.set_status(db).to(status); file.set_status(db).to(status);
} }
if file.revision(db) != revision { if file.revision(db) != revision {
tracing::debug!("Updating the revision of '{}'", file.path(db)); tracing::debug!("Updating the revision of `{}`", file.path(db));
file.set_revision(db).to(revision); file.set_revision(db).to(revision);
} }
if file.permissions(db) != permission { if file.permissions(db) != permission {
tracing::debug!("Updating the permissions of '{}'", file.path(db),); tracing::debug!("Updating the permissions of `{}`", file.path(db));
file.set_permissions(db).to(permission); file.set_permissions(db).to(permission);
} }
} }
@ -450,7 +450,7 @@ impl VirtualFile {
/// Increments the revision of the underlying [`File`]. /// Increments the revision of the underlying [`File`].
fn sync(&self, db: &mut dyn Db) { fn sync(&self, db: &mut dyn Db) {
let file = self.0; let file = self.0;
tracing::debug!("Updating the revision of '{}'", file.path(db)); tracing::debug!("Updating the revision of `{}`", file.path(db));
let current_revision = file.revision(db); let current_revision = file.revision(db);
file.set_revision(db) file.set_revision(db)
.to(FileRevision::new(current_revision.as_u128() + 1)); .to(FileRevision::new(current_revision.as_u128() + 1));
@ -458,7 +458,7 @@ impl VirtualFile {
/// Closes the virtual file. /// Closes the virtual file.
pub fn close(&self, db: &mut dyn Db) { pub fn close(&self, db: &mut dyn Db) {
tracing::debug!("Closing virtual file '{}'", self.0.path(db)); tracing::debug!("Closing virtual file `{}`", self.0.path(db));
self.0.set_status(db).to(FileStatus::NotFound); self.0.set_status(db).to(FileStatus::NotFound);
} }
} }

View file

@ -878,9 +878,9 @@ mod tests {
[group(&format_args![ [group(&format_args![
token("("), token("("),
soft_block_indent(&format_args![ soft_block_indent(&format_args![
source_text_slice(TextRange::at(TextSize::new(0), TextSize::new(19)),), source_text_slice(TextRange::at(TextSize::new(0), TextSize::new(19))),
space(), space(),
source_text_slice(TextRange::at(TextSize::new(20), TextSize::new(28)),), source_text_slice(TextRange::at(TextSize::new(20), TextSize::new(28))),
]) ])
])] ])]
) )

View file

@ -1718,7 +1718,7 @@ mod tests {
token("b"), token("b"),
soft_block_indent(&format_args!( soft_block_indent(&format_args!(
token("c"), token("c"),
soft_block_indent(&format_args!(token("d"), soft_line_break(), token("d"),)), soft_block_indent(&format_args!(token("d"), soft_line_break(), token("d"))),
token("c"), token("c"),
)), )),
token("b"), token("b"),

View file

@ -226,8 +226,8 @@ print("hello world")
assert_eq!( assert_eq!(
source_map.markers(), source_map.markers(),
&[ &[
SourceMarker::new(10.into(), 10.into(),), SourceMarker::new(10.into(), 10.into()),
SourceMarker::new(10.into(), 21.into(),), SourceMarker::new(10.into(), 21.into()),
] ]
); );
} }
@ -263,8 +263,8 @@ class A(Bar):
assert_eq!( assert_eq!(
source_map.markers(), source_map.markers(),
&[ &[
SourceMarker::new(8.into(), 8.into(),), SourceMarker::new(8.into(), 8.into()),
SourceMarker::new(14.into(), 11.into(),), SourceMarker::new(14.into(), 11.into()),
] ]
); );
} }
@ -335,8 +335,8 @@ class A(object):
&[ &[
SourceMarker::new(8.into(), 8.into()), SourceMarker::new(8.into(), 8.into()),
SourceMarker::new(16.into(), 8.into()), SourceMarker::new(16.into(), 8.into()),
SourceMarker::new(22.into(), 14.into(),), SourceMarker::new(22.into(), 14.into()),
SourceMarker::new(30.into(), 14.into(),), SourceMarker::new(30.into(), 14.into()),
] ]
); );
} }
@ -371,8 +371,8 @@ class A:
assert_eq!( assert_eq!(
source_map.markers(), source_map.markers(),
&[ &[
SourceMarker::new(7.into(), 7.into(),), SourceMarker::new(7.into(), 7.into()),
SourceMarker::new(15.into(), 7.into(),), SourceMarker::new(15.into(), 7.into()),
] ]
); );
} }

View file

@ -116,7 +116,7 @@ mod tests {
assert!(!comment_contains_code( assert!(!comment_contains_code(
"# pylint: disable=redefined-outer-name", "# pylint: disable=redefined-outer-name",
&[] &[]
),); ));
assert!(!comment_contains_code( assert!(!comment_contains_code(
"# Issue #999: This is not code", "# Issue #999: This is not code",
&[] &[]
@ -190,11 +190,11 @@ mod tests {
assert!(comment_contains_code( assert!(comment_contains_code(
"# user_content_type, _ = TimelineEvent.objects.using(db_alias).get_or_create(", "# user_content_type, _ = TimelineEvent.objects.using(db_alias).get_or_create(",
&[] &[]
),); ));
assert!(comment_contains_code( assert!(comment_contains_code(
"# (user_content_type, _) = TimelineEvent.objects.using(db_alias).get_or_create(", "# (user_content_type, _) = TimelineEvent.objects.using(db_alias).get_or_create(",
&[] &[]
),); ));
assert!(comment_contains_code( assert!(comment_contains_code(
"# ( user_content_type , _ )= TimelineEvent.objects.using(db_alias).get_or_create(", "# ( user_content_type , _ )= TimelineEvent.objects.using(db_alias).get_or_create(",
&[] &[]

View file

@ -181,7 +181,7 @@ impl AlwaysFixableViolation for MissingTrailingComma {
/// import json /// import json
/// ///
/// ///
/// foo = (json.dumps({"bar": 1}),) /// foo = (json.dumps({"bar": 1}))
/// ``` /// ```
#[violation] #[violation]
pub struct TrailingCommaOnBareTuple; pub struct TrailingCommaOnBareTuple;