fix(rust): handle missing crates file

When no packages have been installed yet using cargo-install, the rust
backend has errored out until now when trying to load the file. If the
file does not exist, we assume it is empty and that no packages have
been installed for cargo.
This commit is contained in:
steven-omaha
2023-05-31 13:08:46 +02:00
parent dcd85f0156
commit 3b8e8c180f
+14 -2
View File
@@ -1,9 +1,10 @@
use std::collections::HashSet; use std::collections::HashSet;
use std::fs::read_to_string; use std::fs::read_to_string;
use std::io::ErrorKind::NotFound;
use std::path::PathBuf; use std::path::PathBuf;
use std::process::ExitStatus; use std::process::ExitStatus;
use anyhow::{Context, Result}; use anyhow::{bail, Context, Result};
use serde_json::Value; use serde_json::Value;
use crate::backend::backend_trait::{Backend, Switches, Text}; use crate::backend::backend_trait::{Backend, Switches, Text};
@@ -31,7 +32,18 @@ impl Backend for Rust {
fn get_all_installed_packages(&self) -> Result<HashSet<Package>> { fn get_all_installed_packages(&self) -> Result<HashSet<Package>> {
let file = get_crates_file().context("getting path to crates file")?; let file = get_crates_file().context("getting path to crates file")?;
let content = read_to_string(file).context("reading crates file")?;
let content = match read_to_string(file) {
Ok(string) => string,
Err(err) if err.kind() == NotFound => {
eprintln!(
"WARNING: no crates file foud for cargo. Assuming no crates installed yet."
);
return Ok(HashSet::new());
}
Err(err) => bail!(err),
};
let json: Value = let json: Value =
serde_json::from_str(&content).context("parsing JSON from crates file")?; serde_json::from_str(&content).context("parsing JSON from crates file")?;
extract_packages(&json).context("extracing packages from crates file") extract_packages(&json).context("extracing packages from crates file")