use crate::cache::Cache;
use crate::client::{add_form_field, build_form_with_file, DatalabClient};
use crate::error::{DatalabError, Result};
use crate::output::Progress;
use clap::Args;
use reqwest::multipart::Form;
use serde_json::json;
use std::fs;
use std::path::PathBuf;
#[derive(Args, Debug)]
pub struct TrackChangesArgs {
#[arg(value_name = "FILE|URL")]
pub input: String,
#[arg(
long,
default_value = "html,markdown",
value_name = "FORMATS",
help_heading = "Output Options"
)]
pub output_format: String,
#[arg(long, help_heading = "Output Options")]
pub paginate: bool,
#[arg(long, help_heading = "Cache Options")]
pub skip_cache: bool,
#[arg(long, short, value_name = "FILE", help_heading = "Output Options")]
pub output: Option<PathBuf>,
#[arg(
long,
default_value = "300",
value_name = "SECS",
help_heading = "Advanced Options"
)]
pub timeout: u64,
}
impl TrackChangesArgs {
fn to_cache_params(&self) -> serde_json::Value {
json!({
"output_format": self.output_format,
"paginate": self.paginate,
})
}
fn add_to_form(&self, mut form: Form) -> Form {
form = add_form_field(form, "output_format", &self.output_format);
if self.paginate {
form = add_form_field(form, "paginate", "true");
}
form
}
}
pub async fn execute(args: TrackChangesArgs, progress: &Progress) -> Result<()> {
let client = DatalabClient::new(Some(args.timeout))?;
let cache = Cache::new()?;
let is_url = args.input.starts_with("http://") || args.input.starts_with("https://");
let file_path = if is_url {
None
} else {
Some(PathBuf::from(&args.input))
};
let file_str = file_path.as_ref().map(|p| p.to_string_lossy().to_string());
progress.start("track-changes", file_str.as_deref());
let file_hash = if let Some(ref path) = file_path {
if !path.exists() {
return Err(DatalabError::FileNotFound(path.clone()));
}
Some(Cache::hash_file(path)?)
} else {
None
};
let cache_params = args.to_cache_params();
let cache_key = Cache::generate_key(
file_hash.as_deref(),
if is_url { Some(&args.input) } else { None },
"track-changes",
&cache_params,
);
if !args.skip_cache {
if let Some(cached) = cache.get(&cache_key) {
progress.cache_hit(&cache_key);
output_result(&cached, args.output.as_ref())?;
return Ok(());
}
}
let form = if let Some(ref path) = file_path {
let (form, _) = build_form_with_file(path)?;
args.add_to_form(form)
} else {
let form = Form::new().text("file_url", args.input.clone());
args.add_to_form(form)
};
let result = client
.submit_and_poll("track-changes", form, progress)
.await?;
let file_path_str = file_path.as_ref().map(|p| p.to_string_lossy().to_string());
cache.set(
&cache_key,
&result,
"track-changes",
file_hash.as_deref(),
file_path_str.as_deref(),
)?;
output_result(&result, args.output.as_ref())?;
Ok(())
}
fn output_result(result: &serde_json::Value, output_file: Option<&PathBuf>) -> Result<()> {
let json_output = serde_json::to_string_pretty(result)?;
if let Some(path) = output_file {
fs::write(path, &json_output)?;
} else {
println!("{}", json_output);
}
Ok(())
}