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 {
) {
Ok(specifier) => specifier,
Err(err) => {
// ast-grep-ignore: no-context-turbofmt
return Err(err.context(
turbofmt!(
"NftJsonAsset: cannot handle filepath '{referenced_chunk_path}' \
......
......@@ -108,18 +108,22 @@ async fn get_font_adjustment(
let font_file_binary = font_file_rope.to_bytes();
let scope = allsorts::binary::read::ReadScope::new(&font_file_binary);
let mut font = Font::new(scope.read::<FontData>()?.table_provider(0)?)?.context(format!(
"Unable to read font metrics from font file at {}",
&main_descriptor.path,
))?;
let mut font = Font::new(scope.read::<FontData>()?.table_provider(0)?)?.with_context(|| {
format!(
"Unable to read font metrics from font file at {}",
&main_descriptor.path,
)
})?;
let az_avg_width = calc_average_width(&mut font);
let units_per_em = font
.head_table()?
.context(format!(
"Unable to read font scale from font file at {}",
&main_descriptor.path
))?
.with_context(|| {
format!(
"Unable to read font scale from font file at {}",
&main_descriptor.path
)
})?
.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 {
}
if let Err(e) = res {
// ast-grep-ignore: no-context-turbofmt
return Err(e)
.context(turbofmt!("unable to read {} for env vars", self.path).await?);
}
......
......@@ -386,6 +386,7 @@ impl<'a> Parser<'a> {
}
}
fn error(&self, kind: ErrorKind) -> Error {
// ast-grep-ignore: no-context-format
Error::msg(kind.description(self.char_pos))
.context(format!("Parsing glob pattern: {}", self.glob))
}
......
......@@ -786,6 +786,7 @@ impl FileSystem for DiskFileSystem {
Err(e) if e.kind() == ErrorKind::NotFound || e.kind() == ErrorKind::InvalidFilename => {
FileContent::NotFound
}
// ast-grep-ignore: no-context-format
Err(e) => return Err(anyhow!(e).context(format!("reading file {full_path:?}"))),
};
Ok(content.cell())
......@@ -818,6 +819,7 @@ impl FileSystem for DiskFileSystem {
return Ok(RawDirectoryContent::not_found());
}
Err(e) => {
// ast-grep-ignore: no-context-format
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
match value {
Ok(v) => Ok(Some(v)),
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()))),
}
}
......
......@@ -276,6 +276,7 @@ mod non_recursive_helpers {
..
}) => Ok(()),
Err(err) => {
// ast-grep-ignore: no-context-format
return Err(err).context(format!("Unable to watch {}", dir_path.display(),));
}
}
......
......@@ -277,6 +277,8 @@ async fn module_factory_with_code_generation_issue(
Err(error) => {
let id = chunk_item.asset_ident().to_string().await;
let id = id.as_ref().map_or_else(|_| "unknown", |id| &**id);
// ast-grep-ignore: no-context-format
let error = error.context(format!(
"An error occurred while generating the chunk item {id}"
));
......
......@@ -1520,7 +1520,8 @@ async fn merge_modules(
Ok(v) => v,
Err((content_idx, 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(
.await
{
Ok(result) => Ok(result),
// ast-grep-ignore: no-context-turbofmt
Err(error) => Err(error.context(turbofmt!("failed to parse {}", source.ident()).await?)),
}
}
......@@ -344,6 +345,7 @@ async fn parse_internal(
{
Ok(result) => result,
Err(e) => {
// ast-grep-ignore: no-context-turbofmt
return Err(e).context(
turbofmt!(
"Transforming and/or parsing of {} failed",
......
......@@ -541,6 +541,7 @@ pub async fn analyze_ecmascript_module(
match result {
Ok(result) => Ok(result),
// ast-grep-ignore: no-context-turbofmt
Err(err) => Err(err
.context(turbofmt!("failed to analyze ecmascript module '{}'", module.ident()).await?)),
}
......
use std::{env, path::PathBuf};
use anyhow::{Context, Result, bail};
use anyhow::{Result, bail};
use once_cell::sync::Lazy;
use regex::Regex;
use rustc_hash::{FxHashMap, FxHashSet};
use similar::TextDiff;
use turbo_rcstr::RcStr;
use turbo_tasks::{ReadRef, TryJoinIterExt, Vc, turbofmt};
use turbo_tasks::{ReadRef, TryJoinIterExt, Vc};
use turbo_tasks_fs::{
DirectoryContent, DirectoryEntry, File, FileContent, FileSystemEntryType, FileSystemPath,
};
......@@ -121,8 +121,8 @@ pub async fn diff(path: FileSystemPath, actual: Vc<AssetContent>) -> Result<()>
let path_str = &path.path;
let expected = AssetContent::file(path.read());
let actual = get_contents(actual, path.clone()).await?;
let expected = get_contents(expected, path.clone()).await?;
let actual = get_contents(actual).await?;
let expected = get_contents(expected).await?;
if actual != expected {
if let Some(actual) = actual {
......@@ -154,34 +154,26 @@ pub async fn diff(path: FileSystemPath, actual: Vc<AssetContent>) -> Result<()>
Ok(())
}
async fn get_contents(file: Vc<AssetContent>, path: FileSystemPath) -> Result<Option<String>> {
Ok(
match &*file
.await
.context(turbofmt!("Unable to read AssetContent of {path}").await?)?
{
AssetContent::File(file) => match &*file
.await
.context(turbofmt!("Unable to read FileContent of {path}").await?)?
{
FileContent::NotFound => None,
FileContent::Content(expected) => {
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}"))
}
async fn get_contents(file: Vc<AssetContent>) -> Result<Option<String>> {
Ok(match &*file.await? {
AssetContent::File(file) => match &*file.await? {
FileContent::NotFound => None,
FileContent::Content(expected) => {
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<()> {
......
......@@ -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_root = project_fs.root().owned().await?;
let relative_path = resource_path.strip_prefix(&*REPO_ROOT).context(format!(
"stripping repo root {:?} from resource path {:?}",
&*REPO_ROOT,
resource_path.display()
))?;
let relative_path = resource_path.strip_prefix(&*REPO_ROOT).with_context(|| {
format!(
"stripping repo root {:?} from resource path {:?}",
&*REPO_ROOT,
resource_path.display()
)
})?;
let relative_path = RcStr::from(sys_to_unix(relative_path.to_str().unwrap()));
let path = root_fs.root().await?.join(&relative_path)?;
let project_path = project_root.join(&relative_path)?;
......
......@@ -11,7 +11,7 @@ use rustc_hash::FxHashSet;
use serde::Deserialize;
use serde_json::json;
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_env::DotenvProcessEnv;
use turbo_tasks_fs::{
......@@ -613,12 +613,10 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
let output_path = project_path.clone();
while let Some(asset) = queue.pop_front() {
walk_asset(asset, &output_path, &mut seen, &mut queue)
.await
.context(format!(
"Failed to walk asset {}",
asset.path().to_string().await.context("to_string failed")?
))?;
if let Err(error) = walk_asset(asset, &output_path, &mut seen, &mut queue).await {
// ast-grep-ignore: no-context-turbofmt
return Err(error.context(turbofmt!("Failed to walk asset {}", asset.path()).await?));
}
}
matches_expected(expected_paths, seen)
......
......@@ -459,7 +459,7 @@ fn node_file_trace<B: Backend + 'static>(
Err(err)
}
})
.context(format!("Failed to remove directory: {directory}"))
.with_context(|| format!("Failed to remove directory: {directory}"))
.unwrap();
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