8000 rework error handling to make the errors more helpful by figsoda · Pull Request #668 · nix-community/nix-init · GitHub
[go: up one dir, main page]

Skip to content
8000
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 0 additions & 18 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ expand = "0.3.0"
flate2 = "1.1.5"
heck = "0.5.0"
indoc = "2.0.7"
is-terminal = "0.4.17"
itertools = "0.14.0"
once_cell = "1.21.3"
owo-colors = "4.2.3"
Expand Down
16 changes: 12 additions & 4 deletions src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use rustc_hash::FxHashMap;
use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;
use tokio::process::Command;
use tracing::warn;
use xdg::BaseDirectories;

use crate::utils::{CommandExt, ResultExt};
Expand All @@ -32,17 +33,24 @@ impl AccessTokens {
let Some(cmd) = args.next() else {
return;
};
let Some(stdout) = Command::new(cmd).args(args).get_stdout().await.ok_warn() else {

let Some(stdout) = Command::new(cmd)
.args(args)
.get_stdout()
.await
.ok_inspect(|e| warn!("{e}"))
else {
return;
};
let Some(token) = String::from_utf8(stdout).ok_warn() else {

let Some(token) = String::from_utf8(stdout).ok_inspect(|e| warn!("{e}")) else {
return;
};
format!("Bearer {}", token.trim())
}

Some(AccessToken::File { file }) => {
let Some(token) = fs::read_to_string(file).ok_warn() else {
let Some(token) = fs::read_to_string(file).ok_inspect(|e| warn!("{e}")) else {
return;
};
format!("Bearer {}", token.trim())
Expand All @@ -51,7 +59,7 @@ impl AccessTokens {
None => return,
};

let Some(mut value) = HeaderValue::from_str(&value).ok_warn() else {
let Some(mut value) = HeaderValue::from_str(&value).ok_inspect(|e| warn!("{e}")) else {
return;
};
value.set_sensitive(true);
Expand Down
9 changes: 8 additions & 1 deletion src/fetcher/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use reqwest::{Client, IntoUrl, header::HeaderMap};
use rustc_hash::FxHashMap;
use rustyline::completion::Pair;
use serde::{Deserialize, Serialize};
use tracing::{error, warn};

use crate::{cfg::AccessTokens, lang::python::PythonDependencies, utils::ResultExt};

Expand Down Expand Up @@ -194,7 +195,13 @@ impl Fetcher {
}

pub async fn json<T: for<'a> Deserialize<'a>>(cl: &Client, url: impl IntoUrl) -> Option<T> {
cl.get(url).send().await.ok_error()?.json().await.ok_warn()
cl.get(url)
.send()
.await
.ok_inspect(|e| error!("{e}"))?
.json()
.await
.ok_inspect(|e| warn!("{e}"))
}

pub async fn success(cl: &Client, url: impl IntoUrl) -> bool {
Expand Down
5 changes: 3 additions & 2 deletions src/lang/go/goreleaser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use heck::ToLowerCamelCase;
use regex::{Captures, Regex};
use serde::Deserialize;
use serde_with::{OneOrMany, serde_as};
use tracing::warn;

use crate::utils::ResultExt;

Expand Down Expand Up @@ -78,15 +79,15 @@ fn get_ldflags(src_dir: &Path) -> Option<Vec<String>> {
.find_map(|name| File::open(src_dir.join(name)).ok())?;

serde_yaml::from_reader::<_, GoReleaser>(file)
.ok_warn()?
.ok_inspect(|e| warn!("{e}"))?
.builds
.into_iter()
.next()?
.ldflags
}

fn regex() -> Option<Regex> {
Regex::new(r"\{\{\s*(.*?)\s*}}").ok_warn()
Regex::new(r"\{\{\s*(.*?)\s*}}").ok_inspect(|e| warn!("{e}"))
}

fn parse_ldflags<'a>(re: &Regex, ldflags: &'a str) -> Cow<'a, str> {
Expand Down
7 changes: 5 additions & 2 deletions src/lang/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use heck::{AsKebabCase, ToKebabCase};
use pep_508::{Comparator, Dependency, Marker, Operator, Variable};
use serde::Deserialize;
use serde_with::{DefaultOnError, serde_as};
use tracing::warn;

use crate::{inputs::AllInputs, license::parse_spdx_expression, utils::ResultExt};

Expand Down Expand Up @@ -76,7 +77,9 @@ impl Pyproject {
let Ok(content) = &fs::read_to_string(path) else {
return Default::default();
};
toml::from_str(content).ok_warn().unwrap_or_default()
toml::from_str(content)
.ok_inspect(|e| warn!("{e}"))
.unwrap_or_default()
}

pub fn get_name(&mut self) -> Option<String> {
Expand Down Expand Up @@ -176,7 +179,7 @@ pub fn parse_requirements_txt(src: &Path) -> Option<PythonDependencies> {
get_python_dependencies(
BufReader::new(file)
.lines()
.filter_map(|line| line.ok_warn()),
.filter_map(|line| line.ok_inspect(|e| warn!("{e}"))),
)
})
}
Expand Down
19 changes: 10 additions & 9 deletions src/lang/rust/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use cargo::{
use indoc::writedoc;
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use rustc_hash::FxHashMap;
use tracing::error;
use tracing::{error, warn};

use crate::{
cmd::NURL,
Expand Down Expand Up @@ -152,8 +152,8 @@ pub async fn write_cargo_lock(
.arg("-Hf")
.arg("fetchgit")
.get_stdout()
.ok_error()?;
let hash = String::from_utf8(hash).ok_warn()?;
.ok_inspect(|e| error!("{e}"))?;
let hash = String::from_utf8(hash).ok_inspect(|e| warn!("{e}"))?;
Some((format!("{}-{}", pkg.name(), pkg.version()), hash))
})
.collect();
Expand Down Expand Up @@ -183,15 +183,16 @@ pub async fn write_cargo_lock(
}

fn resolve_workspace(src_dir: &Path) -> Option<Resolve> {
let mut cfg = cargo_config(src_dir).ok_error()?;
let mut cfg = cargo_config(src_dir).ok_inspect(|e| error!("{e}"))?;
cfg.configure(0, false, None, false, true, false, &None, &[], &[])
.ok_error()?;
.ok_inspect(|e| error!("{e}"))?;

let ws = Workspace::new(&src_dir.join("Cargo.toml"), &cfg).ok_inspect(|e| error!("{e}"))?;
let lock = load_pkg_lockfile(&ws).ok_inspect(|e| error!("{e}"))?;

let ws = Workspace::new(&src_dir.join("Cargo.toml"), &cfg).ok_error()?;
let lock = load_pkg_lockfile(&ws).ok_error()?;
let mut registry =
PackageRegistry::new_with_source_config(&cfg, SourceConfigMap::new(&cfg).ok()?)
.ok_error()?;
.ok_inspect(|e| error!("{e}"))?;

resolve_with_previous(
&mut registry,
Expand All @@ -203,7 +204,7 @@ fn resolve_workspace(src_dir: &Path) -> Option<Resolve> {
&[],
true,
)
.ok_error()
.ok_inspect(|e| error!("{e}"))
}

fn cargo_config(src_dir: &Path) -> Result<GlobalContext> {
Expand Down
7 changes: 4 additions & 3 deletions src/license.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
use askalono::Store;
use once_cell::sync::Lazy;
use spdx::{Expression, ParseMode};
use tracing::debug;
use tracing::{debug, warn};

use crate::utils::ResultExt;

pub static LICENSE_STORE: Lazy<Option<Store>> = Lazy::new(|| {
Store::from_cache(include_bytes!("../data/license-store-cache.zstd") as &[_]).ok_warn()
Store::from_cache(include_bytes!("../data/license-store-cache.zstd") as &[_])
.ok_inspect(|e| warn!("{e}"))
});

include!("../data/get_nix_license.rs");

pub fn parse_spdx_expression(license: &str, source: &'static str) -> Vec<&'static str> {
Expression::parse_mode(license, ParseMode::LAX)
.ok_warn()
.ok_inspect(|e| warn!("{e}"))
.map_or_else(Vec::new, |expr| {
expr.requirements()
.filter_map(|req| {
Expand Down
37 changes: 23 additions & 14 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::{
collections::{BTreeMap, BTreeSet},
fmt::Write as _,
fs::{File, create_dir_all, metadata, read_dir, read_to_string},
io::{Write as _, stderr},
io::{IsTerminal, Write as _, stderr},
path::{Component, Path, PathBuf},
};

Expand All @@ -28,13 +28,12 @@ use expand::expand;
use flate2::read::GzDecoder;
use heck::{AsSnakeCase, ToKebabCase};
use indoc::{formatdoc, writedoc};
use is_terminal::IsTerminal;
use itertools::Itertools;
use once_cell::sync::Lazy;
use serde::Deserialize;
use tempfile::tempdir;
use tokio::process::Command;
use tracing::debug;
use tracing::{debug, warn};
use tracing_subscriber::EnvFilter;
use zip::ZipArchive;

Expand Down Expand Up @@ -81,6 +80,8 @@ async fn run() -> Result<()> {
tracing_subscriber::fmt()
.with_ansi(stderr().is_terminal())
.with_env_filter(EnvFilter::from_env("NIX_INIT_LOG"))
.with_file(true)
.with_line_number(true)
.with_writer(stderr)
.init();

Expand Down Expand Up @@ -192,11 +193,14 @@ async fn run() -> Result<()> {
python_dependencies,
)
} else {
let pname = url.parse::<url::Url>().ok_warn().and_then(|url| {
url.path_segments()
.and_then(|mut xs| xs.next_back())
.map(|pname| pname.strip_suffix(".git").unwrap_or(pname).into())
});
let pname = url
.parse::<url::Url>()
.ok_inspect(|e| warn!("{e}"))
.and_then(|url| {
url.path_segments()
.and_then(|mut xs| xs.next_back())
.map(|pname| pname.strip_suffix(".git").unwrap_or(pname).into())
});

let rev = match opts.rev {
Some(rev) => rev,
Expand Down Expand Up @@ -536,14 +540,14 @@ async fn run() -> Result<()> {
let mut python_import = None;
let (native_build_inputs, build_inputs) = match builder {
Builder::BuildGoModule => {
let go_sum = File::open(src_dir.join("go.sum")).ok_warn();
let go_sum = File::open(src_dir.join("go.sum")).ok_inspect(|e| warn!("{e}"));

if let Some(go_sum) = &go_sum {
load_go_dependencies(&mut inputs, go_sum);
}

let hash = if src_dir.join("vendor").is_dir()
|| go_sum.and_then(|go_sum| go_sum.metadata().ok_warn())
|| go_sum.and_then(|go_sum| go_sum.metadata().ok_inspect(|e| warn!("{e}")))
.is_none_or(|metadata| metadata.len() == 0)
{
"null".into()
Expand Down Expand Up @@ -913,7 +917,7 @@ async fn run() -> Result<()> {
"}?;

if let Some(prefix) = prefix
&& let Some(walk) = read_dir(&src_dir).ok_warn()
&& let Some(walk) = read_dir(&src_dir).ok_inspect(|e| warn!("{e}"))
{
for entry in walk {
let Ok(entry) = entry else {
Expand All @@ -939,7 +943,10 @@ async fn run() -> Result<()> {
}
}

if let (Some(store), Some(walk)) = (&*LICENSE_STORE, read_dir(src_dir).ok_warn()) {
if let (Some(store), Some(walk)) = (
&*LICENSE_STORE,
read_dir(src_dir).ok_inspect(|e| warn!("{e}")),
) {
let strategy = ScanStrategy::new(store).confidence_threshold(0.8);

for entry in walk {
Expand All @@ -961,14 +968,16 @@ async fn run() -> Result<()> {
continue;
}

let Some(text) = read_to_string(&path).ok_warn() else {
let Some(text) = read_to_string(&path).ok_inspect(|e| warn!("{e}")) else {
continue;
};
let Some(ScanResult {
score,
license: Some(IdentifiedLicense { name, .. }),
..
}) = strategy.scan(&TextData::from(text)).ok_warn()
}) = strategy
.scan(&TextData::from(text))
.ok_inspect(|e| warn!("{e}"))
else {
continue;
};
Expand Down
Loading
0