implement optional binary files copy

This commit is contained in:
postscriptum 2025-07-01 20:13:44 +03:00
parent cf8c676732
commit ef1ba39589
5 changed files with 101 additions and 43 deletions

View file

@ -1,6 +1,11 @@
use anyhow::{Result, bail};
use chrono::{DateTime, Utc};
use std::{collections::HashMap, path::PathBuf, str::FromStr};
use std::{collections::HashMap, fs, path::PathBuf, str::FromStr};
pub enum Source {
Url(String),
File(PathBuf),
}
pub struct Nex {
filename: String,
@ -27,7 +32,7 @@ impl Nex {
for u in user_names {
let mut p = PathBuf::from(&target);
p.push(u);
std::fs::create_dir_all(&p)?;
fs::create_dir_all(&p)?;
users.insert(u.clone(), p);
}
@ -44,10 +49,17 @@ impl Nex {
name: &str,
content: String,
link: String,
attachments: Option<Vec<(String, String, String)>>,
attachments: Option<Vec<(String, String, Source)>>,
tags: Option<Vec<String>>,
(published, updated): (DateTime<Utc>, Option<DateTime<Utc>>),
) -> Result<()> {
// prepare destination
let mut p = PathBuf::from(self.users.get(name).unwrap());
p.push(published.format("%Y").to_string());
p.push(published.format("%m").to_string());
p.push(published.format("%d").to_string());
fs::create_dir_all(&p)?;
// format content pattern
let c = self
.pattern
@ -65,9 +77,30 @@ impl Nex {
.map(|a| {
let mut b = Vec::with_capacity(a.len());
b.push("\n".to_string());
for (name, media_type, link) in a {
for (name, media_type, source) in a {
let mut t = Vec::with_capacity(3);
t.push(format!("=> {link}"));
t.push(format!(
"=> {}",
match source {
Source::Url(url) => url,
Source::File(from) => {
let d = format!(".{}", published.format(&self.filename));
let mut to = PathBuf::from(&p);
to.push(&d);
fs::create_dir_all(&to).unwrap();
let f = from
.file_name()
.unwrap()
.to_string_lossy()
.replace("post-", "");
to.push(&f);
if !to.exists() {
fs::copy(&from, &to).unwrap();
}
format!("{d}/{f}")
}
}
));
if !name.is_empty() {
t.push(name)
}
@ -94,16 +127,9 @@ impl Nex {
.unwrap_or_default(),
);
// prepare destination
let mut p = PathBuf::from(self.users.get(name).unwrap());
p.push(published.format("%Y").to_string());
p.push(published.format("%m").to_string());
p.push(published.format("%d").to_string());
std::fs::create_dir_all(&p)?;
// write the data
p.push(published.format(&self.filename).to_string());
std::fs::write(p, c)?; // @TODO skip overwrite operations
fs::write(p, c)?; // @TODO skip overwrite operations
Ok(())
}