use crate::{AppendAsLine, PatternIOProcessor, PatternWriter, Prefer};
use clap::{Parser, Subcommand};
use std::{io::BufRead, path::PathBuf};
use sysexits::Result;
#[derive(Subcommand)]
pub enum Action {
Cffreference(crate::Cffreference),
#[command(visible_aliases = ["cffrel", "cff-rel", "cffreleasetoday"])]
CffReleaseToday {
file_to_edit: PathBuf,
},
CommentChanges(crate::CommentChanges),
IncrementVersion(crate::IncrementVersion),
Ronlog(crate::Ronlog),
Rs2md {
#[arg(long = "inner")]
extract_inner: bool,
#[arg(long = "outer")]
extract_outer: bool,
#[arg(long = "input", short)]
input_file: Vec<PathBuf>,
#[arg(long = "output", short)]
output_file: Option<PathBuf>,
},
Uncrlf {
#[arg(long = "edit", short = 'e')]
file_to_edit: Option<PathBuf>,
#[arg(long = "input", short)]
input_file: Option<PathBuf>,
#[arg(long = "output", short)]
output_file: Option<PathBuf>,
},
}
impl Action {
fn rs2md(s: &str, extract_inner: bool, extract_outer: bool) -> String {
s.lines()
.map(str::trim_start)
.filter(|l| {
(extract_inner && l.starts_with("///"))
|| (extract_outer && l.starts_with("//!"))
})
.map(|l| {
if l.len() > 3 {
l.split_at(4).1.trim_end().to_string() + "\n"
} else {
"\n".to_string()
}
})
.collect::<String>()
}
pub fn run(&self) -> Result<()> {
match self {
Self::Cffreference(c) => c.main(),
Self::CffReleaseToday { file_to_edit } => {
let mut buffer = String::new();
for line in
std::io::BufReader::new(std::fs::File::open(file_to_edit)?)
.lines()
{
let line = line?;
if line.starts_with("date-released:") {
buffer.append_as_line(format!(
"date-released: {}",
chrono::Local::now()
.date_naive()
.format("%Y-%m-%d")
));
} else {
buffer.append_as_line(line);
}
}
file_to_edit.truncate(Box::new(buffer))
}
Self::CommentChanges(c) => c.main(),
Self::IncrementVersion(i) => i.main(),
Self::Ronlog(r) => r.main(),
Self::Rs2md {
extract_inner,
extract_outer,
input_file,
output_file,
} => (|s: String| -> String {
Self::rs2md(&s, *extract_inner, *extract_outer)
})
.io(input_file, output_file),
Self::Uncrlf {
file_to_edit,
input_file,
output_file,
} => |mut s: String| -> String {
s.retain(|c| c != '\r');
s
}
.io(
input_file.prefer(file_to_edit.clone()),
output_file.prefer(file_to_edit.clone()),
),
}
}
}
#[derive(Parser)]
#[clap(about, version)]
pub struct Clap {
#[clap(subcommand)]
action: Action,
}
crate::getters!(@ref Clap { action: Action });