use clap::Parser;
use clap::builder::Styles;
use clap::builder::styling::AnsiColor;
use clap_complete::generate;
use miette::Result as MietteResult;
use tale_ndjson::config::{CliOptions, ConfigOpts, InputMode};
#[cfg(debug_assertions)]
use tale_ndjson::json_profiler;
use tale_ndjson::{colors, config, multiplexed, readers};
#[derive(Debug, Clone, Parser, Default)]
#[clap(name="tale", version, styles = v3_styles(), max_term_width = 100)]
pub struct Args {
#[arg(short, long)]
pub follow: bool,
#[arg(short = 'F', long)]
pub sticky: bool,
#[arg(short, long, group = "units")]
pub blocks: Option<i64>,
#[arg(short = 'c', long, group = "units")]
pub bytes: Option<i64>,
#[arg(short = 'n', long, group = "units")]
pub offset: Option<i64>,
#[arg(short, long)]
pub verbose: bool,
#[arg(short, long, conflicts_with = "verbose")]
pub quiet: bool,
#[arg(short, long)]
pub timestamps: bool,
#[arg(long, default_value = "250", hide = true)]
pub window: u64,
#[arg(long, hide = true)]
pub completions: Option<clap_complete::Shell>,
#[arg(long, hide = true)]
pub chunked: bool,
#[arg(long, conflicts_with = "chunked", hide = true)]
pub no_chunked: bool,
#[arg(short, long, hide = true)]
pub max_memory: Option<usize>,
#[cfg(debug_assertions)]
#[arg(long, hide = true)]
pub profile_json: bool,
#[arg(allow_hyphen_values = true)]
pub args: Vec<String>,
}
impl CliOptions for Args {
fn follow(&self) -> bool {
self.follow
}
fn sticky(&self) -> bool {
self.sticky
}
fn bytes(&self) -> Option<i64> {
self.bytes
}
fn offset(&self) -> Option<i64> {
self.offset
}
fn verbose(&self) -> bool {
self.verbose
}
fn quiet(&self) -> bool {
self.quiet
}
fn timestamps(&self) -> bool {
self.timestamps
}
fn window(&self) -> u64 {
self.window
}
fn chunked(&self) -> bool {
self.chunked
}
fn no_chunked(&self) -> bool {
self.no_chunked
}
fn max_memory(&self) -> Option<usize> {
self.max_memory
}
fn args(&self) -> &[String] {
&self.args
}
#[cfg(debug_assertions)]
fn profile_json(&self) -> bool {
self.profile_json
}
}
fn v3_styles() -> Styles {
Styles::styled()
.header(AnsiColor::Yellow.on_default())
.usage(AnsiColor::Green.on_default())
.literal(AnsiColor::Green.on_default())
.placeholder(AnsiColor::Green.on_default())
}
#[tokio::main]
async fn main() -> MietteResult<()> {
colors::detect_colors();
let args = Args::parse();
if let Some(shell) = args.completions {
use clap::CommandFactory;
let mut app = Args::command();
generate(shell, &mut app, "tale", &mut std::io::stdout());
return Ok(());
}
let config = ConfigOpts::new(&args).unwrap_or_else(|e| {
eprintln!("Configuration error: {}", e);
std::process::exit(1);
});
config::set(config).expect("Quite improbably failed to set config OnceLock on process start.");
let mode = config::mode();
let result = match mode {
InputMode::Stdin => readers::handle_stdin(),
InputMode::SingleFile { path } => readers::handle_file(&path).await,
InputMode::MultiFile { paths } => {
if args.follow || args.sticky {
multiplexed::handle_tailing(paths).await
} else {
multiplexed::handle_static(paths)
}
}
};
#[cfg(debug_assertions)]
{
eprintln!();
json_profiler::print_report();
}
match result {
Ok(()) => Ok(()),
Err(report) => {
let broken_pipe = report
.chain()
.filter_map(|cause| cause.downcast_ref::<std::io::Error>())
.any(|err| err.kind() == std::io::ErrorKind::BrokenPipe);
if broken_pipe {
std::process::exit(141); }
Err(report)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_cli() {
use clap::CommandFactory;
Args::command().debug_assert();
}
#[test]
fn offset_unit_args() {
use tale_ndjson::config::OffsetUnit;
let args = Args {
bytes: Some(100),
args: vec!["test.log".to_string()],
..Default::default()
};
let config = ConfigOpts::new(&args).expect("Config should be valid for test");
assert!(matches!(config.offset_unit, OffsetUnit::Bytes));
assert_eq!(config.offset, 100);
let args = Args {
offset: Some(5),
args: vec!["test.log".to_string()],
..Default::default()
};
let config = ConfigOpts::new(&args).expect("Config should be valid for test");
assert!(matches!(config.offset_unit, OffsetUnit::Lines));
assert_eq!(config.offset, 5);
}
#[test]
fn can_run_cli_and_emit_help() {
let output = std::process::Command::new("cargo")
.args(["run", "--", "--help"])
.output()
.expect("failed to execute");
assert!(output.status.success());
}
}