switch templating to tera

This commit is contained in:
nora 2024-01-21 21:58:02 +01:00
parent 2d2c820510
commit fa7baa71cc
8 changed files with 603 additions and 151 deletions

View file

@ -2,8 +2,7 @@ use color_eyre::{
eyre::{bail, Context},
Result,
};
use fs_extra::dir::CopyOptions;
use std::{path::Path, process::Command};
use std::{fs, io, os::unix::ffi::OsStrExt, path::{Path, PathBuf}, process::Command};
pub fn run_process(cmd: &mut Command) -> Result<String> {
fn run_process_inner(cmd: &mut Command) -> Result<String> {
@ -41,30 +40,58 @@ pub fn create_dir_if_not_exist(p: &Path) -> Result<()> {
}
pub fn cp_r(from: &Path, to: &Path) -> Result<()> {
fs_extra::copy_items(
&[from],
to,
&CopyOptions {
overwrite: true,
copy_inside: true,
..CopyOptions::default()
},
)
.wrap_err(format!("copying to {}", to.display()))?;
Ok(())
copy_fn(from, to, |content, _, _| Ok(content))
}
pub fn cp_content(from: &Path, to: &Path) -> Result<()> {
fs_extra::dir::copy(
from,
to,
&CopyOptions {
overwrite: true,
copy_inside: true,
content_only: true,
..CopyOptions::default()
},
)
.wrap_err(format!("copying to {}", to.display()))?;
pub struct CopyOpts {
pub dest_path: PathBuf,
}
pub fn copy_fn(
from: &Path,
to: &Path,
mut map: impl FnMut(Vec<u8>, Option<&str>, &mut CopyOpts) -> Result<Vec<u8>>,
) -> Result<()> {
let mut worklist = vec![from.to_owned()];
while let Some(ref item) = worklist.pop() {
let mut process = || -> Result<()> {
let meta = fs::metadata(item).wrap_err("getting metadata")?;
let relative = item.strip_prefix(from).wrap_err("subpath stripping")?;
let dest = to.join(relative);
if meta.is_dir() {
let items = fs::read_dir(item).wrap_err("read_dir")?;
for item in items {
let item = item.wrap_err("entry")?;
worklist.push(item.path());
}
match fs::create_dir_all(&dest) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
e => return e.wrap_err_with(|| format!("creating {}", dest.display())),
}
} else {
let content = fs::read(item).wrap_err("reading file")?;
let ext = match item.extension() {
Some(ext) => Some(
std::str::from_utf8(ext.as_bytes())
.wrap_err("file extension is invalid UTF-8")?,
),
None => None,
};
let mut opts = CopyOpts {
dest_path: dest.clone(),
};
let result = map(content, ext, &mut opts).wrap_err("applying mapping")?;
fs::write(opts.dest_path, result)
.wrap_err_with(|| format!("creating {}", dest.display()))?;
}
Ok(())
};
process().wrap_err_with(|| format!("copying {}", item.display()))?;
}
Ok(())
}