Skip to content

Commit eb8d7da

Browse files
committed
refactor: simplify error messages and string formatting in devspace and image modules
1 parent 574e5b9 commit eb8d7da

File tree

3 files changed

+40
-54
lines changed

3 files changed

+40
-54
lines changed

xtask/src/devspace.rs

Lines changed: 35 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -117,12 +117,12 @@ fn remove_submodules(modules: &HashMap<String, ManagedModule>) -> Result<()> {
117117
let git_modules_dir = Path::new(".git/modules").join(path);
118118
if git_modules_dir.exists() {
119119
fs::remove_dir_all(&git_modules_dir)
120-
.with_context(|| format!("Failed to remove {:?}", git_modules_dir))?;
120+
.with_context(|| format!("Failed to remove {git_modules_dir:?}"))?;
121121
}
122122
if Path::new(path).exists() {
123123
let _ = run_git(&["rm", "-f", "--", path]);
124124
if Path::new(path).exists() {
125-
fs::remove_dir_all(path).with_context(|| format!("Failed to remove {}", path))?;
125+
fs::remove_dir_all(path).with_context(|| format!("Failed to remove {path}"))?;
126126
}
127127
}
128128
}
@@ -134,7 +134,7 @@ fn compute_patch_specs(metadata: &Metadata, repos: &[DevRepo]) -> Result<Vec<Pat
134134
let mut specs = BTreeMap::new();
135135

136136
for pkg in &metadata.packages {
137-
if let Some(spec) = package_patch_spec(&pkg, &repo_map) {
137+
if let Some(spec) = package_patch_spec(pkg, &repo_map) {
138138
specs
139139
.entry((spec.source.clone(), spec.crate_name.clone()))
140140
.or_insert(spec);
@@ -154,10 +154,7 @@ fn compute_patch_specs(metadata: &Metadata, repos: &[DevRepo]) -> Result<Vec<Pat
154154
Ok(specs.into_values().collect())
155155
}
156156

157-
fn package_patch_spec<'a>(
158-
pkg: &Package,
159-
repo_map: &HashMap<String, &'a DevRepo>,
160-
) -> Option<PatchSpec> {
157+
fn package_patch_spec(pkg: &Package, repo_map: &HashMap<String, &DevRepo>) -> Option<PatchSpec> {
161158
let source_raw = pkg.source.as_ref()?.to_string();
162159
let normalized = normalize_source(&source_raw)?;
163160
let key = repo_lookup_key(&normalized, pkg.name.as_str());
@@ -182,7 +179,7 @@ fn apply_patches(specs: &[PatchSpec]) -> Result<()> {
182179
let config_path = Path::new(".cargo/config.toml");
183180
let mut contents = if config_path.exists() {
184181
fs::read_to_string(config_path)
185-
.with_context(|| format!("Failed to read {:?}", config_path))?
182+
.with_context(|| format!("Failed to read {config_path:?}"))?
186183
} else {
187184
String::new()
188185
};
@@ -202,8 +199,7 @@ fn apply_patches(specs: &[PatchSpec]) -> Result<()> {
202199
contents.push('\n');
203200
}
204201

205-
fs::write(config_path, contents)
206-
.with_context(|| format!("Failed to write {:?}", config_path))?;
202+
fs::write(config_path, contents).with_context(|| format!("Failed to write {config_path:?}"))?;
207203
Ok(())
208204
}
209205

@@ -214,12 +210,12 @@ fn remove_patches(_: &[PatchRecord]) -> Result<()> {
214210
}
215211

216212
let original = fs::read_to_string(config_path)
217-
.with_context(|| format!("Failed to read {:?}", config_path))?;
213+
.with_context(|| format!("Failed to read {config_path:?}"))?;
218214
let (cleaned, removed) = strip_devspace_section(&original);
219215

220216
if removed {
221217
fs::write(config_path, cleaned)
222-
.with_context(|| format!("Failed to write {:?}", config_path))?;
218+
.with_context(|| format!("Failed to write {config_path:?}"))?;
223219
}
224220
Ok(())
225221
}
@@ -230,10 +226,9 @@ fn load_state() -> Result<DevspaceState> {
230226
return Ok(DevspaceState::default());
231227
}
232228

233-
let contents =
234-
fs::read_to_string(path).with_context(|| format!("Failed to read {:?}", path))?;
229+
let contents = fs::read_to_string(path).with_context(|| format!("Failed to read {path:?}"))?;
235230
let state =
236-
serde_json::from_str(&contents).with_context(|| format!("Failed to parse {:?}", path))?;
231+
serde_json::from_str(&contents).with_context(|| format!("Failed to parse {path:?}"))?;
237232
Ok(state)
238233
}
239234

@@ -260,8 +255,7 @@ fn resolve_dev_repos(metadata: &Metadata) -> Result<Vec<DevRepo>> {
260255

261256
if matches.is_empty() {
262257
return Err(anyhow!(
263-
"crate {} not found in workspace metadata",
264-
crate_name
258+
"crate {crate_name} not found in workspace metadata"
265259
));
266260
}
267261

@@ -280,7 +274,7 @@ fn resolve_dev_repos(metadata: &Metadata) -> Result<Vec<DevRepo>> {
280274
.source
281275
.as_ref()
282276
.map(|s| s.to_string())
283-
.ok_or_else(|| anyhow!("crate {} has no source information", crate_name))?;
277+
.ok_or_else(|| anyhow!("crate {crate_name} has no source information"))?;
284278

285279
let (patch_source, git_url) = if source_raw.starts_with("git+") {
286280
let normalized = normalize_source(&source_raw).ok_or_else(|| {
@@ -303,36 +297,32 @@ fn resolve_dev_repos(metadata: &Metadata) -> Result<Vec<DevRepo>> {
303297
url
304298
} else if let Some(url) = override_url {
305299
println!(
306-
"crate {} is missing repository metadata; using override {}",
307-
crate_name, url
300+
"crate {crate_name} is missing repository metadata; using override {url}"
308301
);
309302
url.to_string()
310303
} else {
311304
return Err(anyhow!(
312-
"crate {} is from crates.io but missing repository metadata",
313-
crate_name
305+
"crate {crate_name} is from crates.io but missing repository metadata"
314306
));
315307
};
316308
(CRATES_IO_SOURCE_KEY.to_string(), repo_url)
317309
} else {
318310
return Err(anyhow!(
319-
"crate {} uses unsupported source {}",
320-
crate_name,
321-
source_raw
311+
"crate {crate_name} uses unsupported source {source_raw}"
322312
));
323313
};
324314

325315
Ok(DevRepo {
326316
name: crate_name.to_string(),
327317
git_url,
328318
source: patch_source,
329-
dest: format!("modules/{}", crate_name),
319+
dest: format!("modules/{crate_name}"),
330320
})
331321
})
332322
.collect()
333323
}
334324

335-
fn build_repo_lookup<'a>(repos: &'a [DevRepo]) -> HashMap<String, &'a DevRepo> {
325+
fn build_repo_lookup(repos: &[DevRepo]) -> HashMap<String, &DevRepo> {
336326
repos
337327
.iter()
338328
.map(|repo| (repo_lookup_key(&repo.source, &repo.name), repo))
@@ -364,8 +354,7 @@ fn manifest_relative_dir(path: &Path) -> Option<PathBuf> {
364354
}
365355

366356
fn normalize_source(raw: &str) -> Option<String> {
367-
if raw.starts_with("git+") {
368-
let trimmed = &raw[4..];
357+
if let Some(trimmed) = raw.strip_prefix("git+") {
369358
let no_fragment = trimmed.split('#').next().unwrap_or(trimmed);
370359
let no_query = no_fragment.split('?').next().unwrap_or(no_fragment);
371360
let without_git = no_query.trim_end_matches(".git");
@@ -405,9 +394,9 @@ fn render_devspace_section(specs: &[PatchSpec]) -> String {
405394

406395
let mut iter = grouped.iter().peekable();
407396
while let Some((source, crates)) = iter.next() {
408-
section.push_str(&format!("[patch.\"{}\"]\n", source));
397+
section.push_str(&format!("[patch.\"{source}\"]\n"));
409398
for (crate_name, path) in crates {
410-
section.push_str(&format!("{} = {{ path = \"{}\" }}\n", crate_name, path));
399+
section.push_str(&format!("{crate_name} = {{ path = \"{path}\" }}\n"));
411400
}
412401
if iter.peek().is_some() {
413402
section.push('\n');
@@ -421,21 +410,21 @@ fn render_devspace_section(specs: &[PatchSpec]) -> String {
421410
}
422411

423412
fn strip_devspace_section(contents: &str) -> (String, bool) {
424-
if let Some(start_idx) = contents.find(PATCH_BEGIN_MARKER) {
425-
if let Some(end_rel) = contents[start_idx..].find(PATCH_END_MARKER) {
426-
let end_idx = start_idx + end_rel + PATCH_END_MARKER.len();
427-
let mut removal_end = end_idx;
428-
let tail = &contents[removal_end..];
429-
if tail.starts_with("\r\n") {
430-
removal_end += 2;
431-
} else if tail.starts_with('\n') {
432-
removal_end += 1;
433-
}
434-
let mut result = String::with_capacity(contents.len());
435-
result.push_str(&contents[..start_idx]);
436-
result.push_str(&contents[removal_end..]);
437-
return (result, true);
413+
if let Some(start_idx) = contents.find(PATCH_BEGIN_MARKER)
414+
&& let Some(end_rel) = contents[start_idx..].find(PATCH_END_MARKER)
415+
{
416+
let end_idx = start_idx + end_rel + PATCH_END_MARKER.len();
417+
let mut removal_end = end_idx;
418+
let tail = &contents[removal_end..];
419+
if tail.starts_with("\r\n") {
420+
removal_end += 2;
421+
} else if tail.starts_with('\n') {
422+
removal_end += 1;
438423
}
424+
let mut result = String::with_capacity(contents.len());
425+
result.push_str(&contents[..start_idx]);
426+
result.push_str(&contents[removal_end..]);
427+
return (result, true);
439428
}
440429
(contents.to_string(), false)
441430
}
@@ -494,5 +483,5 @@ struct DevRepo {
494483
}
495484

496485
fn repo_lookup_key(source: &str, crate_name: &str) -> String {
497-
format!("{}::{}", source, crate_name)
486+
format!("{source}::{crate_name}")
498487
}

xtask/src/image.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -402,18 +402,15 @@ async fn image_download(image_name: &str, output_dir: Option<String>, extract: b
402402
writer
403403
.write_all(&chunk)
404404
.await
405-
.map_err(|e| anyhow!("Error writing to file: {}", e))?;
405+
.map_err(|e| anyhow!("Error writing to file: {e}"))?;
406406

407407
// Update progress
408408
downloaded += chunk.len() as u64;
409409
if let Some(total) = content_length {
410410
let percent = (downloaded * 100) / total;
411-
print!(
412-
"\rDownloading: {}% ({}/{} bytes)",
413-
percent, downloaded, total
414-
);
411+
print!("\rDownloading: {percent}% ({downloaded}/{total} bytes)");
415412
} else {
416-
print!("\rDownloaded: {} bytes", downloaded);
413+
print!("\rDownloaded: {downloaded} bytes");
417414
}
418415
std::io::Write::flush(&mut std::io::stdout()).unwrap();
419416
}
@@ -422,7 +419,7 @@ async fn image_download(image_name: &str, output_dir: Option<String>, extract: b
422419
writer
423420
.flush()
424421
.await
425-
.map_err(|e| anyhow!("Error flushing file: {}", e))?;
422+
.map_err(|e| anyhow!("Error flushing file: {e}"))?;
426423

427424
println!("\nDownload completed");
428425

xtask/src/tbuld.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ impl Context {
7979

8080
if !vm_config_paths.is_empty() {
8181
let value = std::env::join_paths(&vm_config_paths)
82-
.map_err(|e| anyhow::anyhow!("Failed to join VM config paths: {}", e))?
82+
.map_err(|e| anyhow::anyhow!("Failed to join VM config paths: {e}"))?
8383
.to_string_lossy()
8484
.into_owned();
8585
cargo.env.insert("AXVISOR_VM_CONFIGS".to_string(), value);

0 commit comments

Comments
 (0)