Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(logging): print to stderr and file when -v,-vv #4

Merged
merged 1 commit into from
Sep 4, 2024
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
14 changes: 13 additions & 1 deletion src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ use std::{
time,
};

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 All @@ -28,7 +30,17 @@ use crate::{args::ProgressStyle, format_duration};
pub const TICK_CHARS: &str = "⠷⠯⠟⠻⠽⠾⠿";

#[must_use]
pub fn current(progress: &ProgressStyle) -> Progress {
pub fn current(progress: &ProgressStyle, verbose: &Verbosity<InfoLevel>) -> Progress {
verbose.log_level().map_or_else(
|| current_style(progress),
|level| match level {
Level::Debug | Level::Trace => Progress::Plain(Plain::default()),
_ => current_style(progress),
},
)
}

fn current_style(progress: &ProgressStyle) -> Progress {
if match progress {
ProgressStyle::Auto => atty::is(atty::Stream::Stdout),
ProgressStyle::Fancy => true,
Expand Down
4 changes: 0 additions & 4 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ impl fmt::Display for Tag {
}
}

#[tracing::instrument]
pub async fn clone_fast(repo: &str, git_ref: &str, cwd: &Path) -> Result<()> {
if cwd.exists() {
let head_sha1 = String::from_utf8(
Expand Down Expand Up @@ -88,7 +87,6 @@ pub async fn clone_fast(repo: &str, git_ref: &str, cwd: &Path) -> Result<()> {
Ok(())
}

#[tracing::instrument]
async fn fetch_and_checkout(cwd: &Path, git_ref: &str) -> Result<()> {
Command::new("git")
.env("GIT_TERMINAL_PROMPT", "0")
Expand All @@ -104,7 +102,6 @@ async fn fetch_and_checkout(cwd: &Path, git_ref: &str) -> Result<()> {
Ok(())
}

#[tracing::instrument]
pub async fn fetch_tags(cwd: &Path) -> Result<()> {
Command::new("git")
.current_dir(cwd)
Expand All @@ -114,7 +111,6 @@ pub async fn fetch_tags(cwd: &Path) -> Result<()> {
.and(Ok(()))
}

#[tracing::instrument]
pub async fn tag_for_ref(cwd: &Path, git_ref: &str) -> Result<String> {
let output = Command::new("git")
.current_dir(cwd)
Expand Down
56 changes: 25 additions & 31 deletions src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ use std::{
use miette::{Context, IntoDiagnostic as _, Result};
use tracing::level_filters::LevelFilter;
use tracing_appender::non_blocking::WorkerGuard;
#[cfg(debug_assertions)]
use tracing_error::ErrorLayer;
use tracing_log::AsTrace;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use tracing_subscriber::{layer::SubscriberExt, Layer};

use crate::{
args::{Args, LogColor},
Expand All @@ -26,46 +24,42 @@ pub fn init(args: &Args) -> Result<WorkerGuard> {
};
console::set_colors_enabled(color);
let filter = args.verbose.log_level_filter().as_trace();
let without_time = std::env::var("TSDL_LOG_TIME")
.map(|v| !matches!(v.to_lowercase().as_str(), "1" | "y" | "yes"))
.unwrap_or(true);
let file = init_log_file(args)?;
Ok(init_tracing(file, color, filter, without_time))
Ok(init_tracing(file, color, filter))
}

fn init_tracing(file: File, color: bool, filter: LevelFilter, without_time: bool) -> WorkerGuard {
fn init_tracing(file: File, color: bool, filter: LevelFilter) -> WorkerGuard {
let (writer, guard) = tracing_appender::non_blocking(file);
let fmt_layer = tracing_subscriber::fmt::layer()
let stdout_layer = tracing_subscriber::fmt::layer()
.compact()
.with_ansi(color)
.with_file(true)
.with_level(true)
.with_line_number(true)
.with_target(true)
.with_thread_ids(false)
.with_writer(std::io::stderr)
.without_time()
.with_filter(filter);
let file_layer = tracing_subscriber::fmt::layer()
.compact()
.with_ansi(color)
.with_file(true)
.with_level(true)
.with_line_number(true)
.with_target(true)
.with_thread_ids(true)
.with_writer(writer);
if without_time {
let fmt_layer = fmt_layer.without_time();
let registry = tracing_subscriber::registry().with(fmt_layer).with(filter);
#[cfg(debug_assertions)]
{
registry.with(ErrorLayer::default()).init();
}
#[cfg(not(debug_assertions))]
{
registry.init();
}
.with_writer(writer)
.with_filter(filter);
if filter == LevelFilter::DEBUG || filter == LevelFilter::TRACE {
let subscriber = tracing_subscriber::registry()
.with(file_layer)
.with(stdout_layer);
tracing::subscriber::set_global_default(subscriber).unwrap();
} else {
let registry = tracing_subscriber::registry().with(fmt_layer).with(filter);
#[cfg(debug_assertions)]
{
registry.with(ErrorLayer::default()).init();
}
#[cfg(not(debug_assertions))]
{
registry.init();
}
};
let subscriber = tracing_subscriber::registry().with(file_layer);
tracing::subscriber::set_global_default(subscriber).unwrap();
}
guard
}

Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ fn run(args: &args::Args) -> Result<()> {
match &args.command {
args::Command::Build(command) => build::run(
&config::current(&args.config, Some(command))?,
display::current(&args.progress),
display::current(&args.progress, &args.verbose),
),
args::Command::Config { command } => config::run(command, &args.config),
}
Expand Down
7 changes: 0 additions & 7 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ use crate::{

pub const NUM_STEPS: usize = 3;

#[tracing::instrument]
pub async fn build_languages(languages: Vec<Language>) -> Result<()> {
let buffer = if languages.is_empty() {
64
Expand Down Expand Up @@ -88,7 +87,6 @@ impl Language {
}
}

#[tracing::instrument(skip(self))]
async fn process(&mut self, tx: mpsc::Sender<Result<()>>) {
let res = self.steps().await;
if res.is_err() {
Expand All @@ -100,7 +98,6 @@ impl Language {
}
}

#[tracing::instrument(skip(self))]
async fn steps(&mut self) -> Result<()> {
self.handle.start(format!("Cloning {}", self.git_ref));
self.clone().await?;
Expand All @@ -116,7 +113,6 @@ impl Language {
Ok(())
}

#[tracing::instrument(skip(self))]
async fn build_grammar(&self, dir: PathBuf) -> Result<()> {
if self.build_script.is_none() {
self.generate(&dir).await?;
Expand All @@ -138,7 +134,6 @@ impl Language {
Ok(())
}

#[tracing::instrument(skip(self))]
async fn build(&self, dir: &Path) -> Result<()> {
self.build_script
.as_ref()
Expand Down Expand Up @@ -263,7 +258,6 @@ impl Language {
.and(Ok(()))
}

#[tracing::instrument(skip(self))]
async fn clone(&self) -> Result<()> {
clone_fast(self.repo.as_str(), &self.git_ref, &self.build_dir)
.await
Expand All @@ -279,7 +273,6 @@ impl Language {
})
}

#[tracing::instrument(skip(self))]
async fn generate(&self, dir: &Path) -> Result<()> {
Command::new(&*self.ts_cli)
.current_dir(dir)
Expand Down
8 changes: 3 additions & 5 deletions src/sh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::{

use miette::{miette, IntoDiagnostic, Result};
use tokio::process::Command;
use tracing::error;
use tracing::{error, trace};

use crate::{error, relative_to_cwd};

Expand All @@ -24,6 +24,7 @@ pub trait Script {
impl Exec for Command {
#[tracing::instrument(skip(self))]
async fn exec(&mut self) -> Result<Output> {
trace!("{}", self.display());
let output = self.output().await.into_diagnostic()?;
if output.status.success() {
Ok(output)
Expand Down Expand Up @@ -93,20 +94,17 @@ impl Script for Command {
/// Your local hometown one-eyed which.
///
/// stdin, stdout, and stderr are ignored.
#[tracing::instrument]
pub async fn which(prog: &str) -> Result<PathBuf> {
let output = Command::new("which").arg(prog).exec().await?;
Ok(PathBuf::from(
String::from_utf8_lossy(&output.stdout).trim(),
))
}

#[tracing::instrument]
pub async fn chmod_x(prog: &Path) -> Result<Output> {
Command::new("chmod").arg("+x").arg(prog).exec().await
}

#[tracing::instrument]
pub async fn download(out: &Path, url: &str) -> Result<Output> {
let which_prog = match which("curl").await {
Ok(path) => Ok(path),
Expand All @@ -116,6 +114,7 @@ pub async fn download(out: &Path, url: &str) -> Result<Output> {
.file_name()
.and_then(|p| p.to_str())
.ok_or(miette!("Could not find curl or wget"))?;
trace!("using {prog} as a downloader");
let out = out
.to_str()
.ok_or(miette!("Retrieving string from out path"))?;
Expand All @@ -126,7 +125,6 @@ pub async fn download(out: &Path, url: &str) -> Result<Output> {
}
}

#[tracing::instrument]
pub async fn gunzip(gz: &Path) -> Result<Output> {
Command::new("gunzip").arg(gz).exec().await
}
9 changes: 3 additions & 6 deletions src/tree_sitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex};

use miette::{miette, Context, IntoDiagnostic, Result};
use tokio::process::Command;
use tracing::debug;
use tracing::trace;
use url::Url;

use crate::display::ProgressHandle;
Expand All @@ -20,7 +20,6 @@ use crate::{
};

#[allow(clippy::missing_panics_doc)]
#[tracing::instrument]
pub async fn tag(repo: &str, version: &str) -> Result<Tag> {
let output = Command::new("git")
.args(["ls-remote", "--refs", "--tags", repo])
Expand All @@ -32,7 +31,7 @@ pub async fn tag(repo: &str, version: &str) -> Result<Tag> {
let ref_line = line.split('\t').map(str::trim).collect::<Vec<_>>();
let (sha1, full_ref) = (ref_line[0], ref_line[1]);
if let Some(tag) = full_ref.split('/').last() {
debug!("insert {tag} -> {sha1}");
trace!("insert {tag} -> {sha1}");
refs.insert(tag.to_string(), sha1.to_string());
}
}
Expand All @@ -42,7 +41,7 @@ pub async fn tag(repo: &str, version: &str) -> Result<Tag> {
.map_or_else(
|| Tag::Ref(Ref::from_str(version).unwrap()),
|(k, v)| {
debug!("Found! {k} -> {v}");
trace!("Found! {k} -> {v}");
Tag::Exact {
sha1: Ref::from_str(v).unwrap(),
label: k.to_string(),
Expand All @@ -51,7 +50,6 @@ pub async fn tag(repo: &str, version: &str) -> Result<Tag> {
))
}

#[tracing::instrument]
async fn cli(args: &BuildCommand, tag: &Tag, handle: &ProgressHandle) -> Result<PathBuf> {
let build_dir = &args.build_dir;
let platform = &args.tree_sitter.platform;
Expand Down Expand Up @@ -81,7 +79,6 @@ async fn cli(args: &BuildCommand, tag: &Tag, handle: &ProgressHandle) -> Result<
Ok(res)
}

#[tracing::instrument]
pub async fn prepare(args: &BuildCommand, progress: Arc<Mutex<Progress>>) -> Result<PathBuf> {
let mut handle = {
progress
Expand Down