use std::fs;
use std::io::{self, Read, Write};
use std::path::PathBuf;
use aozora_core::zip::{is_zip_file, read_first_txt_from_zip};
use clap::Args as ClapArgs;
use encoding_rs::SHIFT_JIS;
use aozora2::html::{self, RenderOptions};
#[derive(ClapArgs, Debug)]
pub struct Args {
pub input: Option<PathBuf>,
#[arg(short, long)]
pub output: Option<PathBuf>,
#[arg(short, long)]
pub zip: bool,
#[arg(long, default_value = "../../../gaiji/")]
pub gaiji_dir: String,
#[arg(long, default_value = "../../aozora.css")]
pub css_files: String,
#[arg(long)]
pub use_jisx0213: bool,
#[arg(long)]
pub use_unicode: bool,
#[arg(long)]
pub title: Option<String>,
#[arg(long, default_value = "shift_jis")]
pub encoding: String,
}
pub fn run(args: Args) -> io::Result<()> {
let bytes = if args.zip {
let path = args.input.as_ref().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"ZIP mode requires an input file",
)
})?;
read_first_txt_from_zip(path)?
} else {
match &args.input {
Some(path) => {
let bytes = fs::read(path)?;
if is_zip_file(&bytes) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"input appears to be a ZIP file; use --zip option",
));
}
bytes
}
None => {
let mut buf = Vec::new();
io::stdin().read_to_end(&mut buf)?;
buf
}
}
};
let input = aozora_core::encoding::decode_to_utf8(&bytes);
let css_files: Vec<String> = args
.css_files
.split(',')
.map(|s| s.trim().to_string())
.collect();
let options = RenderOptions::new()
.with_gaiji_dir(&args.gaiji_dir)
.with_css_files(css_files)
.with_jisx0213(args.use_jisx0213)
.with_unicode(args.use_unicode);
let options = if let Some(title) = &args.title {
options.with_title(title)
} else {
options
};
let output_html = html::convert(&input, &options);
let output_bytes = if args.encoding.to_lowercase() == "shift_jis" {
let (encoded, _, _) = SHIFT_JIS.encode(&output_html);
encoded.into_owned()
} else {
output_html.into_bytes()
};
match &args.output {
Some(path) => {
fs::write(path, &output_bytes)?;
}
None => {
io::stdout().write_all(&output_bytes)?;
}
}
Ok(())
}