Unverified Commit 19ff1bab authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Lint against `.context(format!(...))` (#91122)

There are unfortunately a few false-positives, because this isn't aware of type information of course.
parent c65b4347
id: no-context-format
snapshots:
foo.bar().context(format!("{} failed", name)):
fixed: foo.bar().with_context(|| format!("{} failed", name))
labels:
- source: foo.bar().context(format!("{} failed", name))
style: primary
start: 0
end: 45
'foo.context(format!("error: {}", msg))':
fixed: 'foo.with_context(|| format!("error: {}", msg))'
labels:
- source: 'foo.context(format!("error: {}", msg))'
style: primary
start: 0
end: 38
foo.context(format!("simple message")):
fixed: foo.with_context(|| format!("simple message"))
labels:
- source: foo.context(format!("simple message"))
style: primary
start: 0
end: 38
id: no-context-turbofmt
snapshots:
foo.bar().context(turbofmt!("{} failed", name)):
fixed: foo.bar().with_context(|| turbofmt!("{} failed", name))
labels:
- source: foo.bar().context(turbofmt!("{} failed", name))
style: primary
start: 0
end: 47
foo.bar().context(turbofmt!("{} failed", name).await?):
labels:
- source: foo.bar().context(turbofmt!("{} failed", name).await?)
style: primary
start: 0
end: 54
'foo.context(turbofmt!("error: {}", msg))':
fixed: 'foo.with_context(|| turbofmt!("error: {}", msg))'
labels:
- source: 'foo.context(turbofmt!("error: {}", msg))'
style: primary
start: 0
end: 40
'foo.context(turbofmt!("error: {}", msg).await?)':
labels:
- source: 'foo.context(turbofmt!("error: {}", msg).await?)'
style: primary
start: 0
end: 47
foo.context(turbofmt!("simple message")):
fixed: foo.with_context(|| turbofmt!("simple message"))
labels:
- source: foo.context(turbofmt!("simple message"))
style: primary
start: 0
end: 40
foo.context(turbofmt!("simple message").await?):
labels:
- source: foo.context(turbofmt!("simple message").await?)
style: primary
start: 0
end: 47
id: no-context-format
valid:
- 'foo.context("static string")'
- 'foo.with_context(|| format!("error: {}", msg))'
- 'foo.context(msg)'
invalid:
- 'foo.context(format!("error: {}", msg))'
- 'foo.context(format!("simple message"))'
- 'foo.bar().context(format!("{} failed", name))'
---
id: no-context-turbofmt
valid:
- 'foo.context("static string")'
- 'foo.context(msg)'
invalid:
- 'foo.context(turbofmt!("error: {}", msg).await?)'
- 'foo.context(turbofmt!("simple message").await?)'
- 'foo.bar().context(turbofmt!("{} failed", name).await?)'
# yaml-language-server: $schema=https://raw.githubusercontent.com/ast-grep/ast-grep/main/schemas/rule.json
id: no-context-format
message: Use `.with_context(|| format!(...))` instead of `.context(format!(...))`.
note: >
`.context(format!(...))` eagerly allocates the formatted string even when there is no error.
Use `.with_context(|| format!(...))` for lazy evaluation.
severity: error
language: Rust
rule:
pattern: $OBJ.context(format!($$$ARGS))
fix: $OBJ.with_context(|| format!($$$ARGS))
---
id: no-context-turbofmt
message: >
`.context(turbofmt!(...).await?)` eagerly creates the formatted string even when there is no error.
severity: error
language: Rust
rule:
pattern: $OBJ.context(turbofmt!($$$ARGS).await?)
...@@ -307,6 +307,7 @@ impl Asset for NftJsonAsset { ...@@ -307,6 +307,7 @@ impl Asset for NftJsonAsset {
) { ) {
Ok(specifier) => specifier, Ok(specifier) => specifier,
Err(err) => { Err(err) => {
// ast-grep-ignore: no-context-turbofmt
return Err(err.context( return Err(err.context(
turbofmt!( turbofmt!(
"NftJsonAsset: cannot handle filepath '{referenced_chunk_path}' \ "NftJsonAsset: cannot handle filepath '{referenced_chunk_path}' \
......
...@@ -108,18 +108,22 @@ async fn get_font_adjustment( ...@@ -108,18 +108,22 @@ async fn get_font_adjustment(
let font_file_binary = font_file_rope.to_bytes(); let font_file_binary = font_file_rope.to_bytes();
let scope = allsorts::binary::read::ReadScope::new(&font_file_binary); let scope = allsorts::binary::read::ReadScope::new(&font_file_binary);
let mut font = Font::new(scope.read::<FontData>()?.table_provider(0)?)?.context(format!( let mut font = Font::new(scope.read::<FontData>()?.table_provider(0)?)?.with_context(|| {
"Unable to read font metrics from font file at {}", format!(
&main_descriptor.path, "Unable to read font metrics from font file at {}",
))?; &main_descriptor.path,
)
})?;
let az_avg_width = calc_average_width(&mut font); let az_avg_width = calc_average_width(&mut font);
let units_per_em = font let units_per_em = font
.head_table()? .head_table()?
.context(format!( .with_context(|| {
"Unable to read font scale from font file at {}", format!(
&main_descriptor.path "Unable to read font scale from font file at {}",
))? &main_descriptor.path
)
})?
.units_per_em as f64; .units_per_em as f64;
let fallback_avg_width = fallback_font.az_avg_width / fallback_font.units_per_em as f64; let fallback_avg_width = fallback_font.az_avg_width / fallback_font.units_per_em as f64;
......
...@@ -62,6 +62,7 @@ impl DotenvProcessEnv { ...@@ -62,6 +62,7 @@ impl DotenvProcessEnv {
} }
if let Err(e) = res { if let Err(e) = res {
// ast-grep-ignore: no-context-turbofmt
return Err(e) return Err(e)
.context(turbofmt!("unable to read {} for env vars", self.path).await?); .context(turbofmt!("unable to read {} for env vars", self.path).await?);
} }
......
...@@ -386,6 +386,7 @@ impl<'a> Parser<'a> { ...@@ -386,6 +386,7 @@ impl<'a> Parser<'a> {
} }
} }
fn error(&self, kind: ErrorKind) -> Error { fn error(&self, kind: ErrorKind) -> Error {
// ast-grep-ignore: no-context-format
Error::msg(kind.description(self.char_pos)) Error::msg(kind.description(self.char_pos))
.context(format!("Parsing glob pattern: {}", self.glob)) .context(format!("Parsing glob pattern: {}", self.glob))
} }
......
...@@ -786,6 +786,7 @@ impl FileSystem for DiskFileSystem { ...@@ -786,6 +786,7 @@ impl FileSystem for DiskFileSystem {
Err(e) if e.kind() == ErrorKind::NotFound || e.kind() == ErrorKind::InvalidFilename => { Err(e) if e.kind() == ErrorKind::NotFound || e.kind() == ErrorKind::InvalidFilename => {
FileContent::NotFound FileContent::NotFound
} }
// ast-grep-ignore: no-context-format
Err(e) => return Err(anyhow!(e).context(format!("reading file {full_path:?}"))), Err(e) => return Err(anyhow!(e).context(format!("reading file {full_path:?}"))),
}; };
Ok(content.cell()) Ok(content.cell())
...@@ -818,6 +819,7 @@ impl FileSystem for DiskFileSystem { ...@@ -818,6 +819,7 @@ impl FileSystem for DiskFileSystem {
return Ok(RawDirectoryContent::not_found()); return Ok(RawDirectoryContent::not_found());
} }
Err(e) => { Err(e) => {
// ast-grep-ignore: no-context-format
return Err(anyhow!(e).context(format!("reading dir {full_path:?}"))); return Err(anyhow!(e).context(format!("reading dir {full_path:?}")));
} }
}; };
......
...@@ -15,6 +15,7 @@ pub fn extract_disk_access<T>(value: io::Result<T>, path: &Path) -> Result<Optio ...@@ -15,6 +15,7 @@ pub fn extract_disk_access<T>(value: io::Result<T>, path: &Path) -> Result<Optio
match value { match value {
Ok(v) => Ok(Some(v)), Ok(v) => Ok(Some(v)),
Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::InvalidFilename) => Ok(None), Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::InvalidFilename) => Ok(None),
// ast-grep-ignore: no-context-format
Err(e) => Err(anyhow!(e).context(format!("reading file {}", path.display()))), Err(e) => Err(anyhow!(e).context(format!("reading file {}", path.display()))),
} }
} }
......
...@@ -276,6 +276,7 @@ mod non_recursive_helpers { ...@@ -276,6 +276,7 @@ mod non_recursive_helpers {
.. ..
}) => Ok(()), }) => Ok(()),
Err(err) => { Err(err) => {
// ast-grep-ignore: no-context-format
return Err(err).context(format!("Unable to watch {}", dir_path.display(),)); return Err(err).context(format!("Unable to watch {}", dir_path.display(),));
} }
} }
......
...@@ -277,6 +277,8 @@ async fn module_factory_with_code_generation_issue( ...@@ -277,6 +277,8 @@ async fn module_factory_with_code_generation_issue(
Err(error) => { Err(error) => {
let id = chunk_item.asset_ident().to_string().await; let id = chunk_item.asset_ident().to_string().await;
let id = id.as_ref().map_or_else(|_| "unknown", |id| &**id); let id = id.as_ref().map_or_else(|_| "unknown", |id| &**id);
// ast-grep-ignore: no-context-format
let error = error.context(format!( let error = error.context(format!(
"An error occurred while generating the chunk item {id}" "An error occurred while generating the chunk item {id}"
)); ));
......
...@@ -1520,7 +1520,8 @@ async fn merge_modules( ...@@ -1520,7 +1520,8 @@ async fn merge_modules(
Ok(v) => v, Ok(v) => v,
Err((content_idx, err)) => { Err((content_idx, err)) => {
return Err( return Err(
err.context(turbofmt!("Processing {}", contents[content_idx].0.ident()).await?) // ast-grep-ignore: no-context-turbofmt
err.context(turbofmt!("Processing {}", contents[content_idx].0.ident()).await?),
); );
} }
}; };
......
...@@ -284,6 +284,7 @@ pub async fn parse( ...@@ -284,6 +284,7 @@ pub async fn parse(
.await .await
{ {
Ok(result) => Ok(result), Ok(result) => Ok(result),
// ast-grep-ignore: no-context-turbofmt
Err(error) => Err(error.context(turbofmt!("failed to parse {}", source.ident()).await?)), Err(error) => Err(error.context(turbofmt!("failed to parse {}", source.ident()).await?)),
} }
} }
...@@ -344,6 +345,7 @@ async fn parse_internal( ...@@ -344,6 +345,7 @@ async fn parse_internal(
{ {
Ok(result) => result, Ok(result) => result,
Err(e) => { Err(e) => {
// ast-grep-ignore: no-context-turbofmt
return Err(e).context( return Err(e).context(
turbofmt!( turbofmt!(
"Transforming and/or parsing of {} failed", "Transforming and/or parsing of {} failed",
......
...@@ -541,6 +541,7 @@ pub async fn analyze_ecmascript_module( ...@@ -541,6 +541,7 @@ pub async fn analyze_ecmascript_module(
match result { match result {
Ok(result) => Ok(result), Ok(result) => Ok(result),
// ast-grep-ignore: no-context-turbofmt
Err(err) => Err(err Err(err) => Err(err
.context(turbofmt!("failed to analyze ecmascript module '{}'", module.ident()).await?)), .context(turbofmt!("failed to analyze ecmascript module '{}'", module.ident()).await?)),
} }
......
use std::{env, path::PathBuf}; use std::{env, path::PathBuf};
use anyhow::{Context, Result, bail}; use anyhow::{Result, bail};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use similar::TextDiff; use similar::TextDiff;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ReadRef, TryJoinIterExt, Vc, turbofmt}; use turbo_tasks::{ReadRef, TryJoinIterExt, Vc};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
DirectoryContent, DirectoryEntry, File, FileContent, FileSystemEntryType, FileSystemPath, DirectoryContent, DirectoryEntry, File, FileContent, FileSystemEntryType, FileSystemPath,
}; };
...@@ -121,8 +121,8 @@ pub async fn diff(path: FileSystemPath, actual: Vc<AssetContent>) -> Result<()> ...@@ -121,8 +121,8 @@ pub async fn diff(path: FileSystemPath, actual: Vc<AssetContent>) -> Result<()>
let path_str = &path.path; let path_str = &path.path;
let expected = AssetContent::file(path.read()); let expected = AssetContent::file(path.read());
let actual = get_contents(actual, path.clone()).await?; let actual = get_contents(actual).await?;
let expected = get_contents(expected, path.clone()).await?; let expected = get_contents(expected).await?;
if actual != expected { if actual != expected {
if let Some(actual) = actual { if let Some(actual) = actual {
...@@ -154,34 +154,26 @@ pub async fn diff(path: FileSystemPath, actual: Vc<AssetContent>) -> Result<()> ...@@ -154,34 +154,26 @@ pub async fn diff(path: FileSystemPath, actual: Vc<AssetContent>) -> Result<()>
Ok(()) Ok(())
} }
async fn get_contents(file: Vc<AssetContent>, path: FileSystemPath) -> Result<Option<String>> { async fn get_contents(file: Vc<AssetContent>) -> Result<Option<String>> {
Ok( Ok(match &*file.await? {
match &*file AssetContent::File(file) => match &*file.await? {
.await FileContent::NotFound => None,
.context(turbofmt!("Unable to read AssetContent of {path}").await?)? FileContent::Content(expected) => {
{ let rope = expected.content();
AssetContent::File(file) => match &*file let str = rope.to_str();
.await match str {
.context(turbofmt!("Unable to read FileContent of {path}").await?)? Ok(str) => Some(str.trim().to_string()),
{ Err(_) => {
FileContent::NotFound => None, let hash = hash_xxh3_hash64(rope);
FileContent::Content(expected) => { Some(format!("Binary content {hash:016x}"))
let rope = expected.content();
let str = rope.to_str();
match str {
Ok(str) => Some(str.trim().to_string()),
Err(_) => {
let hash = hash_xxh3_hash64(rope);
Some(format!("Binary content {hash:016x}"))
}
} }
} }
}, }
AssetContent::Redirect { target, link_type } => Some(format!(
"Redirect {{ target: {target}, link_type: {link_type:?} }}"
)),
}, },
) AssetContent::Redirect { target, link_type } => Some(format!(
"Redirect {{ target: {target}, link_type: {link_type:?} }}"
)),
})
} }
async fn remove_file(path: FileSystemPath) -> Result<()> { async fn remove_file(path: FileSystemPath) -> Result<()> {
......
...@@ -300,11 +300,13 @@ async fn prepare_test(resource: RcStr) -> Result<Vc<PreparedTest>> { ...@@ -300,11 +300,13 @@ async fn prepare_test(resource: RcStr) -> Result<Vc<PreparedTest>> {
let project_fs = DiskFileSystem::new(rcstr!("project"), REPO_ROOT.clone()); let project_fs = DiskFileSystem::new(rcstr!("project"), REPO_ROOT.clone());
let project_root = project_fs.root().owned().await?; let project_root = project_fs.root().owned().await?;
let relative_path = resource_path.strip_prefix(&*REPO_ROOT).context(format!( let relative_path = resource_path.strip_prefix(&*REPO_ROOT).with_context(|| {
"stripping repo root {:?} from resource path {:?}", format!(
&*REPO_ROOT, "stripping repo root {:?} from resource path {:?}",
resource_path.display() &*REPO_ROOT,
))?; resource_path.display()
)
})?;
let relative_path = RcStr::from(sys_to_unix(relative_path.to_str().unwrap())); let relative_path = RcStr::from(sys_to_unix(relative_path.to_str().unwrap()));
let path = root_fs.root().await?.join(&relative_path)?; let path = root_fs.root().await?.join(&relative_path)?;
let project_path = project_root.join(&relative_path)?; let project_path = project_root.join(&relative_path)?;
......
...@@ -11,7 +11,7 @@ use rustc_hash::FxHashSet; ...@@ -11,7 +11,7 @@ use rustc_hash::FxHashSet;
use serde::Deserialize; use serde::Deserialize;
use serde_json::json; use serde_json::json;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Effects, ResolvedVc, TurboTasks, ValueToString, Vc, get_effects}; use turbo_tasks::{Effects, ResolvedVc, TurboTasks, Vc, get_effects, turbofmt};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_env::DotenvProcessEnv; use turbo_tasks_env::DotenvProcessEnv;
use turbo_tasks_fs::{ use turbo_tasks_fs::{
...@@ -613,12 +613,10 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -613,12 +613,10 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
let output_path = project_path.clone(); let output_path = project_path.clone();
while let Some(asset) = queue.pop_front() { while let Some(asset) = queue.pop_front() {
walk_asset(asset, &output_path, &mut seen, &mut queue) if let Err(error) = walk_asset(asset, &output_path, &mut seen, &mut queue).await {
.await // ast-grep-ignore: no-context-turbofmt
.context(format!( return Err(error.context(turbofmt!("Failed to walk asset {}", asset.path()).await?));
"Failed to walk asset {}", }
asset.path().to_string().await.context("to_string failed")?
))?;
} }
matches_expected(expected_paths, seen) matches_expected(expected_paths, seen)
......
...@@ -459,7 +459,7 @@ fn node_file_trace<B: Backend + 'static>( ...@@ -459,7 +459,7 @@ fn node_file_trace<B: Backend + 'static>(
Err(err) Err(err)
} }
}) })
.context(format!("Failed to remove directory: {directory}")) .with_context(|| format!("Failed to remove directory: {directory}"))
.unwrap(); .unwrap();
for _ in 0..run_count { for _ in 0..run_count {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment