Skip to content
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ repo = "https://github.com/tree-sitter/tree-sitter"
version = "0.24.7"

[dependencies]
anyhow = "1.0"
async-compression = { version = "0.4.12", features = ["tokio", "gzip"] }
atty = "0.2"
better-panic = "0.3.0"
Expand All @@ -56,7 +57,6 @@ human-panic = "2.0.1"
ignore = "0.4"
indicatif = "0.17"
log = "0.4"
miette = { version = "7.2.0", features = ["fancy"] }
num_cpus = "1.16"
reqwest = { version = "0.12.7", default-features = false, features = [
"http2",
Expand Down
30 changes: 8 additions & 22 deletions src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{
sync::{Arc, Mutex},
};

use miette::{Context, IntoDiagnostic, Result};
use anyhow::{Context, Result};
use tokio::time;
use url::Url;

Expand Down Expand Up @@ -34,13 +34,10 @@ fn clear(command: &BuildCommand, progress: &mut Progress) -> Result<()> {
let handle = progress.register("Fresh Build", 1);
let disp = &command.build_dir.display();
fs::remove_dir_all(&command.build_dir)
.into_diagnostic()
.wrap_err(format!("Removing the build_dir {disp} for a fresh build"))?;
.with_context(|| format!("Removing the build_dir {disp} for a fresh build"))?;
handle.fin(format!("Cleaned {disp}"));
}
fs::create_dir_all(&command.build_dir)
.into_diagnostic()
.wrap_err("Creating the build dir")?;
fs::create_dir_all(&command.build_dir).context("Creating the build dir")?;
Ok(())
}

Expand All @@ -49,14 +46,13 @@ fn build(command: &BuildCommand, progress: Progress) -> Result<()> {
.enable_all()
.worker_threads(command.ncpus)
.build()
.into_diagnostic()
.wrap_err("Failed to initialize tokio runtime")?;
.context("Failed to initialize tokio runtime")?;
let _guard = rt.enter();
let screen = Arc::new(Mutex::new(progress));
rt.spawn(update_screen(screen.clone()));
let ts_cli = rt
.block_on(tree_sitter::prepare(command, screen.clone()))
.wrap_err("Preparing tree-sitter")?;
.context("Preparing tree-sitter")?;
let languages = collect_languages(
ts_cli,
screen,
Expand All @@ -67,11 +63,7 @@ fn build(command: &BuildCommand, progress: Progress) -> Result<()> {
&command.prefix,
)?;
create_dir_all(&command.out_dir)
.into_diagnostic()
.wrap_err(format!(
"Creating output dir {}",
&command.out_dir.display()
))?;
.with_context(|| format!("Creating output dir {}", &command.out_dir.display()))?;
rt.block_on(build_languages(languages))
}

Expand Down Expand Up @@ -183,11 +175,7 @@ fn get_language_coords(
resolve_git_ref(git_ref),
from.as_ref().map_or_else(
|| default_repo(language),
|f| {
Url::parse(f)
.into_diagnostic()
.wrap_err(format!("Parsing {f} for {language}"))
},
|f| Url::parse(f).with_context(|| format!("Parsing {f} for {language}")),
),
),
_ => (None, String::from("HEAD").into(), default_repo(language)),
Expand All @@ -210,7 +198,5 @@ fn resolve_git_ref(git_ref: &str) -> Ref {

fn default_repo(language: &str) -> Result<Url> {
let url = format!("{TSDL_FROM}{language}");
Url::parse(&url)
.into_diagnostic()
.wrap_err(format!("Creating url {url} for {language}"))
Url::parse(&url).with_context(|| format!("Creating url {url} for {language}"))
}
26 changes: 7 additions & 19 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::path::Path;

use anyhow::{Context, Result};
use diff::Diff;
use figment::{
providers::{Format, Serialized, Toml},
Figment,
};
use miette::{Context, IntoDiagnostic, Result};
use tracing::debug;

use crate::{
Expand All @@ -19,15 +19,10 @@ pub fn run(command: &ConfigCommand, config: &Path) -> Result<()> {
let config: BuildCommand = current(config, None)?;
println!(
"{}",
toml::to_string(&config)
.into_diagnostic()
.wrap_err("Generating default TOML config")?
toml::to_string(&config).context("Generating default TOML config")?
);
}
ConfigCommand::Default => println!(
"{}",
toml::to_string(&BuildCommand::default()).into_diagnostic()?
),
ConfigCommand::Default => println!("{}", toml::to_string(&BuildCommand::default())?),
};
Ok(())
}
Expand All @@ -38,8 +33,7 @@ pub fn current(config: &Path, command: Option<&BuildCommand>) -> Result<BuildCom
.merge(Serialized::defaults(from_default.clone()))
.merge(Toml::file(config))
.extract()
.into_diagnostic()
.wrap_err("Merging default and config file")?;
.context("Merging default and config file")?;
match command {
Some(from_command) => {
debug!("Merging cli args + config files");
Expand Down Expand Up @@ -73,24 +67,18 @@ pub fn show(command: &BuildCommand) -> Result<()> {
"{}",
String::from_utf8(
git::column(&langs.join(" "), " ", 80)
.wrap_err("Printing requested languages")?
.context("Printing requested languages")?
.stdout
)
.into_diagnostic()
.wrap_err("Converting column-formatted languages to a string for printing")?
.context("Converting column-formatted languages to a string for printing")?
);
} else {
println!("Building all languages.");
println!();
}
println!("Running with the following configuration:");
println!();
print_indent(
&toml::to_string(&command)
.into_diagnostic()
.wrap_err("Showing config")?,
" ",
);
print_indent(&toml::to_string(&command).context("Showing config")?, " ");
println!();
Ok(())
}
5 changes: 2 additions & 3 deletions src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ use std::{
time,
};

use anyhow::{Context, Result};
use clap_verbosity_flag::{InfoLevel, Verbosity};
use console::style;
use enum_dispatch::enum_dispatch;
use log::Level;
use miette::{Context, IntoDiagnostic, Result};

use crate::{args::ProgressStyle, format_duration};

Expand Down Expand Up @@ -143,8 +143,7 @@ impl ProgressState for Fancy {
fn clear(&self) -> Result<()> {
self.multi
.clear()
.into_diagnostic()
.wrap_err("Clearing the multi-progress bar")
.context("Clearing the multi-progress bar")
}

fn register(&mut self, name: impl Into<String>, num_tasks: usize) -> ProgressHandle {
Expand Down
46 changes: 27 additions & 19 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,48 +1,41 @@
use std::path::PathBuf;

use derive_more::derive::Display;
use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Diagnostic, Error)]
#[derive(Debug, Error)]
#[error("{msg}\nStdOut:\n{stdout}\nStdErr:\n{stderr}")]
pub struct Command {
pub msg: String,
pub stderr: String,
pub stdout: String,
}

#[derive(Debug, Diagnostic, Error)]
#[error("Could not figure out all languages")]
#[derive(Debug, Error)]
#[error("Could not figure out all languages:\n{}", format_languages(.related))]
pub struct LanguageCollection {
#[related]
pub related: Vec<Language>,
}

#[derive(Debug, Error, Diagnostic)]
#[error("{name}")]
#[derive(Debug, Error)]
#[error("{name}.\n{source:?}")]
pub struct Language {
pub name: String,
#[source]
#[diagnostic_source]
pub source: Box<dyn Diagnostic + Send + Sync + 'static>,
pub source: Box<dyn std::error::Error + Send + Sync + 'static>,
}

#[derive(Debug, Diagnostic, Error)]
#[error("Could not build all parsers")]
#[derive(Debug, Error)]
#[error("Could not build all parsers.\n{}", format_errors(.related))]
pub struct Parser {
#[related]
pub related: Vec<Box<dyn Diagnostic + Send + Sync + 'static>>,
pub related: Vec<Box<dyn std::error::Error + Send + Sync + 'static>>,
}

#[derive(Debug, Error, Diagnostic)]
#[error("{name}: {kind}")]
#[derive(Debug, Error)]
#[error("{name}: {kind}.\n{source:?}")]
pub struct Step {
pub name: String,
pub kind: ParserOp,
#[source]
#[diagnostic_source]
pub source: Box<dyn Diagnostic + Send + Sync + 'static>,
pub source: Box<dyn std::error::Error + Send + Sync + 'static>,
}

#[derive(Debug, Display)]
Expand All @@ -56,3 +49,18 @@ pub enum ParserOp {
#[display("Could not generate in {}", dir.display())]
Generate { dir: PathBuf },
}

fn format_languages(langs: &[Language]) -> String {
langs
.iter()
.map(std::string::ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
}

fn format_errors(errs: &Vec<Box<dyn std::error::Error + Send + Sync + 'static>>) -> String {
errs.iter()
.map(|e| format!("{e:?}"))
.collect::<Vec<_>>()
.join("\n")
}
23 changes: 11 additions & 12 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use std::{
process::{Output, Stdio},
};

use anyhow::{Context, Result};
use derive_more::{AsRef, Deref, From, FromStr, Into};
use miette::{IntoDiagnostic, Result};
use tokio::{fs, process::Command};

use crate::sh::Exec;
Expand Down Expand Up @@ -81,7 +81,7 @@ pub async fn clone_fast(repo: &str, git_ref: &str, cwd: &Path) -> Result<()> {

async fn init_fetch_and_checkout(cwd: &Path, repo: &str, git_ref: &str) -> Result<()> {
clean_anyway(cwd).await?;
fs::create_dir_all(cwd).await.into_diagnostic()?;
fs::create_dir_all(cwd).await?;

Command::new("git")
.current_dir(cwd)
Expand Down Expand Up @@ -120,7 +120,7 @@ async fn get_head_sha1(cwd: &Path) -> Result<String> {
.await?
.stdout,
)
.into_diagnostic()
.context("rev-parse HEAD is not a valid utf-8")
}

async fn clean_anyway(cwd: &Path) -> Result<()> {
Expand All @@ -129,8 +129,7 @@ async fn clean_anyway(cwd: &Path) -> Result<()> {
fs::remove_dir_all(cwd).await
} else {
fs::remove_file(cwd).await
}
.into_diagnostic()?;
}?;
}
Ok(())
}
Expand All @@ -148,7 +147,7 @@ async fn get_remote_url(cwd: &Path) -> Result<String> {
.await?
.stdout,
)
.into_diagnostic()
.context("remote get-url origin did not return a valid utf-8")
}

async fn is_valid_git_dir(cwd: &Path) -> bool {
Expand Down Expand Up @@ -191,8 +190,7 @@ pub async fn tag_for_ref(cwd: &Path, git_ref: &str) -> Result<String> {
.exec()
.await?
.stdout,
)
.into_diagnostic()?
)?
.trim()
.to_string())
}
Expand All @@ -205,10 +203,11 @@ pub fn column(input: &str, indent: &str, width: usize) -> Result<Output> {
.arg(format!("--width={width}",))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.into_diagnostic()?;
.spawn()?;
if let Some(mut stdin) = child.stdin.take() {
stdin.write_all(input.as_bytes()).into_diagnostic()?;
stdin.write_all(input.as_bytes())?;
}
child.wait_with_output().into_diagnostic()
child
.wait_with_output()
.context("git column did not finish normally")
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ use std::{
time,
};

use miette::{IntoDiagnostic, Result};
use anyhow::Result;

extern crate log;

Expand All @@ -81,7 +81,7 @@ impl SafeCanonicalize for Path {
if self.is_absolute() {
Ok(self.to_path_buf())
} else {
let current_dir = env::current_dir().into_diagnostic()?;
let current_dir = env::current_dir()?;
Ok(current_dir.join(self))
}
}
Expand Down
10 changes: 3 additions & 7 deletions src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{
path::{Path, PathBuf},
};

use miette::{Context, IntoDiagnostic as _, Result};
use anyhow::{Context, Result};
use tracing::level_filters::LevelFilter;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_log::AsTrace;
Expand Down Expand Up @@ -74,11 +74,7 @@ fn init_log_file(args: &Args) -> Result<File> {
);
let parent = log.parent().unwrap_or(Path::new("."));
if !parent.exists() {
fs::create_dir_all(parent)
.into_diagnostic()
.wrap_err("Preparing log directory")?;
fs::create_dir_all(parent).context("Preparing log directory")?;
}
File::create(&log)
.into_diagnostic()
.wrap_err("Creating log file")
File::create(&log).context("Creating log file")
}
Loading