use std::{
fs::{self, File},
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use toml::value::Datetime;
use crate::{
frontmatter::FrontMatter,
frontmatter_writeback::{read_linkedin_date_field, write_linkedin_date_field, FmWriteError},
};
pub const LINKEDIN_POST_MAX_CHARS: usize = 3_000;
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum DraftError {
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("json serialization error: {0}")]
Json(#[from] serde_json::Error),
#[error("frontmatter write error: {0}")]
FmWrite(#[from] FmWriteError),
#[error("toml parse error in {file:?}: {source}")]
Toml {
source: toml::de::Error,
file: PathBuf,
},
#[error("post too long in {file:?}: {chars} chars exceeds maximum {max}")]
PostTooLong {
chars: usize,
max: usize,
file: PathBuf,
},
#[error("no blog posts found matching the filter")]
BlogPostListEmpty,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinkedinFile {
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub link: Option<String>,
pub created_at: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source_path: Option<PathBuf>,
}
fn today() -> Datetime {
let today = chrono::Utc::now().date_naive();
today
.format("%Y-%m-%d")
.to_string()
.parse()
.expect("valid date string")
}
#[derive(Debug)]
struct BlogPost {
path: PathBuf,
text: String,
link: Option<String>,
}
#[derive(Debug)]
pub struct Draft {
posts: Vec<BlogPost>,
written: usize,
}
impl Draft {
pub fn new(
www_src_root: &Path,
blog_paths: &[PathBuf],
base_url: &str,
min_date: Option<Datetime>,
) -> Result<Self, DraftError> {
let mut posts = Vec::new();
for blog_path in blog_paths {
let dir = if blog_path.is_absolute() {
blog_path.clone()
} else {
www_src_root.join(blog_path)
};
collect_posts(&dir, www_src_root, base_url, min_date, &mut posts)?;
}
if posts.is_empty() {
return Err(DraftError::BlogPostListEmpty);
}
Ok(Self { posts, written: 0 })
}
pub fn write_linkedin_drafts(&mut self, store_dir: &Path) -> Result<&mut Self, DraftError> {
fs::create_dir_all(store_dir)?;
let today = today();
for post in &self.posts {
if read_linkedin_date_field(&post.path, "created").is_some() {
log::debug!(
"Skipping — [linkedin].created already set in {:?}",
post.path
);
continue;
}
write_linkedin_date_field(&post.path, "created", today)?;
let stem = post
.path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("post");
let filename = format!("{stem}.linkedin");
let file_path = store_dir.join(&filename);
let record = LinkedinFile {
text: post.text.clone(),
link: post.link.clone(),
created_at: today.to_string(),
source_path: Some(post.path.clone()),
};
let file = File::create(&file_path)?;
serde_json::to_writer_pretty(&file, &record)?;
log::debug!("Wrote LinkedIn draft: {file_path:?}");
self.written += 1;
}
Ok(self)
}
pub fn count_written(&self) -> usize {
self.written
}
}
fn collect_posts(
dir: &Path,
www_src_root: &Path,
base_url: &str,
min_date: Option<Datetime>,
out: &mut Vec<BlogPost>,
) -> Result<(), DraftError> {
if !dir.is_dir() {
if dir.extension().and_then(|e| e.to_str()) == Some("md") {
if let Some(post) = try_load_post(dir, www_src_root, base_url, min_date)? {
out.push(post);
}
}
return Ok(());
}
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
collect_posts(&path, www_src_root, base_url, min_date, out)?;
} else if path.extension().and_then(|e| e.to_str()) == Some("md") {
if let Some(post) = try_load_post(&path, www_src_root, base_url, min_date)? {
out.push(post);
}
}
}
Ok(())
}
fn try_load_post(
path: &Path,
www_src_root: &Path,
base_url: &str,
min_date: Option<Datetime>,
) -> Result<Option<BlogPost>, DraftError> {
let content = fs::read_to_string(path)?;
let fm = FrontMatter::from_content(&content).map_err(|e| DraftError::Toml {
source: e,
file: path.to_path_buf(),
})?;
let li = match fm.linkedin {
Some(ref li) => li,
None => return Ok(None),
};
if li.published.is_some() {
log::debug!("Skipping — [linkedin].published already set in {path:?}");
return Ok(None);
}
if let Some(min) = min_date {
match fm.date {
Some(d) if d < min => return Ok(None),
None => return Ok(None),
_ => {}
}
}
let dir = path.parent().unwrap_or(Path::new("."));
let text = match li.post_text(dir)? {
Some(t) if !t.is_empty() => t,
_ => return Ok(None), };
let link = derive_link(path, www_src_root, base_url);
let char_count = text.chars().count()
+ link
.as_deref()
.map(|l| 1 + l.chars().count()) .unwrap_or(0);
if char_count > LINKEDIN_POST_MAX_CHARS {
return Err(DraftError::PostTooLong {
chars: char_count,
max: LINKEDIN_POST_MAX_CHARS,
file: path.to_path_buf(),
});
}
Ok(Some(BlogPost {
path: path.to_path_buf(),
text,
link,
}))
}
fn derive_link(path: &Path, www_src_root: &Path, base_url: &str) -> Option<String> {
let rel = path.strip_prefix(www_src_root).ok()?;
let rel = rel.strip_prefix("content").unwrap_or(rel);
let without_ext = rel.with_extension("");
let slug = without_ext.to_string_lossy();
let base = base_url.trim_end_matches('/');
Some(format!("{base}/{slug}"))
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use tempfile::tempdir;
use super::*;
fn write_file(dir: &Path, name: &str, content: &str) -> PathBuf {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, content).unwrap();
path
}
fn md_with_linkedin(description: &str) -> String {
format!(
"+++\ntitle = \"Test\"\ndate = 2026-04-03\n\n[linkedin]\ndescription = \"{description}\"\n+++\n\nBody.\n"
)
}
fn md_with_linkedin_and_created(description: &str) -> String {
format!(
"+++\ntitle = \"Test\"\ndate = 2026-04-03\n\n[linkedin]\ndescription = \"{description}\"\ncreated = 2026-04-01\n+++\n\nBody.\n"
)
}
fn md_with_linkedin_and_published(description: &str) -> String {
format!(
"+++\ntitle = \"Test\"\ndate = 2026-04-03\n\n[linkedin]\ndescription = \"{description}\"\ncreated = 2026-04-01\npublished = 2026-04-02\n+++\n\nBody.\n"
)
}
fn md_without_linkedin() -> String {
"+++\ntitle = \"Test\"\ndate = 2026-04-03\n+++\n\nBody.\n".to_string()
}
#[test]
fn test_draft_new_empty_when_no_linkedin_section() {
let dir = tempdir().unwrap();
write_file(dir.path(), "post.md", &md_without_linkedin());
let result = Draft::new(
dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
);
assert!(
matches!(result, Err(DraftError::BlogPostListEmpty)),
"expected BlogPostListEmpty, got {result:?}"
);
}
#[test]
fn test_draft_new_collects_opted_in_posts() {
let dir = tempdir().unwrap();
write_file(dir.path(), "post.md", &md_with_linkedin("Hello LinkedIn"));
let result = Draft::new(
dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
);
assert!(result.is_ok(), "expected Ok, got {result:?}");
let draft = result.unwrap();
assert_eq!(draft.posts.len(), 1);
}
#[test]
fn test_write_linkedin_drafts_creates_file() {
let src_dir = tempdir().unwrap();
let store_dir = tempdir().unwrap();
write_file(
src_dir.path(),
"post.md",
&md_with_linkedin("Hello LinkedIn"),
);
let mut draft = Draft::new(
src_dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
)
.unwrap();
draft.write_linkedin_drafts(store_dir.path()).unwrap();
let files: Vec<_> = fs::read_dir(store_dir.path())
.unwrap()
.filter_map(|e| e.ok())
.collect();
assert_eq!(files.len(), 1, "expected 1 .linkedin file");
assert!(
files[0]
.file_name()
.to_string_lossy()
.ends_with(".linkedin"),
"expected .linkedin extension"
);
}
#[test]
fn test_write_linkedin_drafts_sets_created_in_frontmatter() {
let src_dir = tempdir().unwrap();
let store_dir = tempdir().unwrap();
let md_path = write_file(src_dir.path(), "post.md", &md_with_linkedin("Hello"));
let mut draft = Draft::new(
src_dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
)
.unwrap();
draft.write_linkedin_drafts(store_dir.path()).unwrap();
let content = fs::read_to_string(&md_path).unwrap();
assert!(
content.contains("created ="),
"frontmatter should contain created: {content}"
);
}
#[test]
fn test_write_linkedin_drafts_skips_when_created_set() {
let src_dir = tempdir().unwrap();
let store_dir = tempdir().unwrap();
write_file(
src_dir.path(),
"post.md",
&md_with_linkedin_and_created("Hello"),
);
let mut draft = Draft::new(
src_dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
)
.unwrap();
draft.write_linkedin_drafts(store_dir.path()).unwrap();
assert_eq!(
draft.count_written(),
0,
"should have skipped already-created post"
);
}
#[test]
fn test_linkedin_file_content() {
let src_dir = tempdir().unwrap();
let store_dir = tempdir().unwrap();
write_file(
src_dir.path(),
"my-post.md",
&md_with_linkedin("My post text"),
);
let mut draft = Draft::new(
src_dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
)
.unwrap();
draft.write_linkedin_drafts(store_dir.path()).unwrap();
let file_path = store_dir.path().join("my-post.linkedin");
let content = fs::read_to_string(&file_path).unwrap();
let record: LinkedinFile = serde_json::from_str(&content).unwrap();
assert_eq!(record.text, "My post text");
assert!(record.source_path.is_some());
}
#[test]
fn test_derive_link_strips_content_prefix() {
let root = Path::new("/site");
let path = Path::new("/site/content/blog/my-post.md");
let link = derive_link(path, root, "https://example.com");
assert_eq!(link.as_deref(), Some("https://example.com/blog/my-post"));
}
#[test]
fn test_draft_new_respects_min_date() {
let dir = tempdir().unwrap();
let old = "+++\ntitle = \"Old\"\ndate = 2026-01-01\n\n[linkedin]\ndescription = \"old\"\n+++\n\nBody.\n";
write_file(dir.path(), "old.md", old);
let min_date = Datetime::from_str("2026-04-01").unwrap();
let result = Draft::new(
dir.path(),
&[PathBuf::from(".")],
"https://example.com",
Some(min_date),
);
assert!(
matches!(result, Err(DraftError::BlogPostListEmpty)),
"old post should be filtered out: {result:?}"
);
}
#[test]
fn test_draft_new_skips_published_posts() {
let dir = tempdir().unwrap();
write_file(
dir.path(),
"post.md",
&md_with_linkedin_and_published("Hello"),
);
let result = Draft::new(
dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
);
assert!(
matches!(result, Err(DraftError::BlogPostListEmpty)),
"published post should be skipped: {result:?}"
);
}
#[test]
fn test_draft_new_reads_description_file() {
let dir = tempdir().unwrap();
fs::write(dir.path().join("linkedin.md"), "Text from file").unwrap();
let content = "+++\ntitle = \"T\"\ndate = 2026-04-03\n\n[linkedin]\ndescription_file = \"linkedin.md\"\n+++\n\nBody.\n";
write_file(dir.path(), "post.md", content);
let mut draft = Draft::new(
dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
)
.unwrap();
let store_dir = tempdir().unwrap();
draft.write_linkedin_drafts(store_dir.path()).unwrap();
let file_path = store_dir.path().join("post.linkedin");
let record: LinkedinFile =
serde_json::from_str(&fs::read_to_string(&file_path).unwrap()).unwrap();
assert_eq!(record.text, "Text from file");
}
#[test]
fn test_draft_new_fails_on_post_too_long() {
let dir = tempdir().unwrap();
let long_text: String = "a".repeat(LINKEDIN_POST_MAX_CHARS + 1);
let content = format!(
"+++\ntitle = \"T\"\ndate = 2026-04-03\n\n[linkedin]\ndescription = \"{long_text}\"\n+++\n\nBody.\n"
);
write_file(dir.path(), "post.md", &content);
let result = Draft::new(
dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
);
assert!(
matches!(result, Err(DraftError::PostTooLong { .. })),
"expected PostTooLong, got {result:?}"
);
}
#[test]
fn test_draft_new_accepts_text_within_limit() {
let dir = tempdir().unwrap();
let text: String = "a".repeat(100);
write_file(dir.path(), "post.md", &md_with_linkedin(&text));
let result = Draft::new(
dir.path(),
&[PathBuf::from(".")],
"https://example.com",
None,
);
assert!(
result.is_ok(),
"should accept text within limit: {result:?}"
);
}
#[test]
fn test_linkedin_file_includes_link() {
let src_dir = tempdir().unwrap();
let store_dir = tempdir().unwrap();
write_file(
src_dir.path(),
"content/blog/my-post.md",
&md_with_linkedin("Hello"),
);
let mut draft = Draft::new(
src_dir.path(),
&[PathBuf::from("content/blog")],
"https://example.com",
None,
)
.unwrap();
draft.write_linkedin_drafts(store_dir.path()).unwrap();
let file_path = store_dir.path().join("my-post.linkedin");
let record: LinkedinFile =
serde_json::from_str(&fs::read_to_string(&file_path).unwrap()).unwrap();
assert!(
record.link.is_some(),
"link should be set in .linkedin file"
);
assert!(
record.link.unwrap().contains("example.com"),
"link should contain base_url"
);
}
#[test]
fn test_linkedin_file_deserializes_without_source_path() {
let json = r#"{"text":"Hello","created_at":"2026-04-03"}"#;
let f: LinkedinFile = serde_json::from_str(json).unwrap();
assert!(f.source_path.is_none());
assert_eq!(f.text, "Hello");
}
}