1use std::{
24 fs::{self, File},
25 path::{Path, PathBuf},
26};
27
28use serde::{Deserialize, Serialize};
29use thiserror::Error;
30use toml::value::Datetime;
31
32use crate::{
33 frontmatter::FrontMatter,
34 frontmatter_writeback::{read_linkedin_date_field, write_linkedin_date_field, FmWriteError},
35};
36
37pub const LINKEDIN_POST_MAX_CHARS: usize = 3_000;
44
45#[non_exhaustive]
47#[derive(Debug, Error)]
48pub enum DraftError {
49 #[error("io error: {0}")]
51 Io(#[from] std::io::Error),
52 #[error("json serialization error: {0}")]
54 Json(#[from] serde_json::Error),
55 #[error("frontmatter write error: {0}")]
57 FmWrite(#[from] FmWriteError),
58 #[error("toml parse error in {file:?}: {source}")]
60 Toml {
61 source: toml::de::Error,
63 file: PathBuf,
65 },
66 #[error("post too long in {file:?}: {chars} chars exceeds maximum {max}")]
71 PostTooLong {
72 chars: usize,
74 max: usize,
76 file: PathBuf,
78 },
79 #[error("no blog posts found matching the filter")]
81 BlogPostListEmpty,
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct LinkedinFile {
90 pub text: String,
92 #[serde(skip_serializing_if = "Option::is_none")]
94 pub link: Option<String>,
95 pub created_at: String,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub source_path: Option<PathBuf>,
101}
102
103fn today() -> Datetime {
105 let today = chrono::Utc::now().date_naive();
106 today
107 .format("%Y-%m-%d")
108 .to_string()
109 .parse()
110 .expect("valid date string")
111}
112
113#[derive(Debug)]
115struct BlogPost {
116 path: PathBuf,
118 text: String,
120 link: Option<String>,
122}
123
124#[derive(Debug)]
130pub struct Draft {
131 posts: Vec<BlogPost>,
132 written: usize,
133}
134
135impl Draft {
136 pub fn new(
152 www_src_root: &Path,
153 blog_paths: &[PathBuf],
154 base_url: &str,
155 min_date: Option<Datetime>,
156 ) -> Result<Self, DraftError> {
157 let mut posts = Vec::new();
158
159 for blog_path in blog_paths {
160 let dir = if blog_path.is_absolute() {
161 blog_path.clone()
162 } else {
163 www_src_root.join(blog_path)
164 };
165 collect_posts(&dir, www_src_root, base_url, min_date, &mut posts)?;
166 }
167
168 if posts.is_empty() {
169 return Err(DraftError::BlogPostListEmpty);
170 }
171
172 Ok(Self { posts, written: 0 })
173 }
174
175 pub fn write_linkedin_drafts(&mut self, store_dir: &Path) -> Result<&mut Self, DraftError> {
182 fs::create_dir_all(store_dir)?;
183 let today = today();
184
185 for post in &self.posts {
186 if read_linkedin_date_field(&post.path, "created").is_some() {
188 log::debug!(
189 "Skipping — [linkedin].created already set in {:?}",
190 post.path
191 );
192 continue;
193 }
194
195 write_linkedin_date_field(&post.path, "created", today)?;
197
198 let stem = post
200 .path
201 .file_stem()
202 .and_then(|s| s.to_str())
203 .unwrap_or("post");
204 let filename = format!("{stem}.linkedin");
205 let file_path = store_dir.join(&filename);
206
207 let record = LinkedinFile {
208 text: post.text.clone(),
209 link: post.link.clone(),
210 created_at: today.to_string(),
211 source_path: Some(post.path.clone()),
212 };
213
214 let file = File::create(&file_path)?;
215 serde_json::to_writer_pretty(&file, &record)?;
216 log::debug!("Wrote LinkedIn draft: {file_path:?}");
217 self.written += 1;
218 }
219
220 Ok(self)
221 }
222
223 pub fn count_written(&self) -> usize {
226 self.written
227 }
228}
229
230fn collect_posts(
232 dir: &Path,
233 www_src_root: &Path,
234 base_url: &str,
235 min_date: Option<Datetime>,
236 out: &mut Vec<BlogPost>,
237) -> Result<(), DraftError> {
238 if !dir.is_dir() {
239 if dir.extension().and_then(|e| e.to_str()) == Some("md") {
240 if let Some(post) = try_load_post(dir, www_src_root, base_url, min_date)? {
241 out.push(post);
242 }
243 }
244 return Ok(());
245 }
246
247 for entry in fs::read_dir(dir)? {
248 let entry = entry?;
249 let path = entry.path();
250 if path.is_dir() {
251 collect_posts(&path, www_src_root, base_url, min_date, out)?;
252 } else if path.extension().and_then(|e| e.to_str()) == Some("md") {
253 if let Some(post) = try_load_post(&path, www_src_root, base_url, min_date)? {
254 out.push(post);
255 }
256 }
257 }
258
259 Ok(())
260}
261
262fn try_load_post(
267 path: &Path,
268 www_src_root: &Path,
269 base_url: &str,
270 min_date: Option<Datetime>,
271) -> Result<Option<BlogPost>, DraftError> {
272 let content = fs::read_to_string(path)?;
273 let fm = FrontMatter::from_content(&content).map_err(|e| DraftError::Toml {
274 source: e,
275 file: path.to_path_buf(),
276 })?;
277
278 let li = match fm.linkedin {
280 Some(ref li) => li,
281 None => return Ok(None),
282 };
283
284 if li.published.is_some() {
286 log::debug!("Skipping — [linkedin].published already set in {path:?}");
287 return Ok(None);
288 }
289
290 if let Some(min) = min_date {
292 match fm.date {
293 Some(d) if d < min => return Ok(None),
294 None => return Ok(None),
295 _ => {}
296 }
297 }
298
299 let dir = path.parent().unwrap_or(Path::new("."));
301 let text = match li.post_text(dir)? {
302 Some(t) if !t.is_empty() => t,
303 _ => return Ok(None), };
305
306 let link = derive_link(path, www_src_root, base_url);
308
309 let char_count = text.chars().count()
311 + link
312 .as_deref()
313 .map(|l| 1 + l.chars().count()) .unwrap_or(0);
315
316 if char_count > LINKEDIN_POST_MAX_CHARS {
317 return Err(DraftError::PostTooLong {
318 chars: char_count,
319 max: LINKEDIN_POST_MAX_CHARS,
320 file: path.to_path_buf(),
321 });
322 }
323
324 Ok(Some(BlogPost {
325 path: path.to_path_buf(),
326 text,
327 link,
328 }))
329}
330
331fn derive_link(path: &Path, www_src_root: &Path, base_url: &str) -> Option<String> {
336 let rel = path.strip_prefix(www_src_root).ok()?;
337 let rel = rel.strip_prefix("content").unwrap_or(rel);
338 let without_ext = rel.with_extension("");
339 let slug = without_ext.to_string_lossy();
340 let base = base_url.trim_end_matches('/');
341 Some(format!("{base}/{slug}"))
342}
343
344#[cfg(test)]
345mod tests {
346 use std::str::FromStr;
347
348 use tempfile::tempdir;
349
350 use super::*;
351
352 fn write_file(dir: &Path, name: &str, content: &str) -> PathBuf {
353 let path = dir.join(name);
354 fs::create_dir_all(path.parent().unwrap()).unwrap();
355 fs::write(&path, content).unwrap();
356 path
357 }
358
359 fn md_with_linkedin(description: &str) -> String {
360 format!(
361 "+++\ntitle = \"Test\"\ndate = 2026-04-03\n\n[linkedin]\ndescription = \"{description}\"\n+++\n\nBody.\n"
362 )
363 }
364
365 fn md_with_linkedin_and_created(description: &str) -> String {
366 format!(
367 "+++\ntitle = \"Test\"\ndate = 2026-04-03\n\n[linkedin]\ndescription = \"{description}\"\ncreated = 2026-04-01\n+++\n\nBody.\n"
368 )
369 }
370
371 fn md_with_linkedin_and_published(description: &str) -> String {
372 format!(
373 "+++\ntitle = \"Test\"\ndate = 2026-04-03\n\n[linkedin]\ndescription = \"{description}\"\ncreated = 2026-04-01\npublished = 2026-04-02\n+++\n\nBody.\n"
374 )
375 }
376
377 fn md_without_linkedin() -> String {
378 "+++\ntitle = \"Test\"\ndate = 2026-04-03\n+++\n\nBody.\n".to_string()
379 }
380
381 #[test]
384 fn test_draft_new_empty_when_no_linkedin_section() {
385 let dir = tempdir().unwrap();
386 write_file(dir.path(), "post.md", &md_without_linkedin());
387
388 let result = Draft::new(
389 dir.path(),
390 &[PathBuf::from(".")],
391 "https://example.com",
392 None,
393 );
394 assert!(
395 matches!(result, Err(DraftError::BlogPostListEmpty)),
396 "expected BlogPostListEmpty, got {result:?}"
397 );
398 }
399
400 #[test]
401 fn test_draft_new_collects_opted_in_posts() {
402 let dir = tempdir().unwrap();
403 write_file(dir.path(), "post.md", &md_with_linkedin("Hello LinkedIn"));
404
405 let result = Draft::new(
406 dir.path(),
407 &[PathBuf::from(".")],
408 "https://example.com",
409 None,
410 );
411 assert!(result.is_ok(), "expected Ok, got {result:?}");
412 let draft = result.unwrap();
413 assert_eq!(draft.posts.len(), 1);
414 }
415
416 #[test]
417 fn test_write_linkedin_drafts_creates_file() {
418 let src_dir = tempdir().unwrap();
419 let store_dir = tempdir().unwrap();
420
421 write_file(
422 src_dir.path(),
423 "post.md",
424 &md_with_linkedin("Hello LinkedIn"),
425 );
426
427 let mut draft = Draft::new(
428 src_dir.path(),
429 &[PathBuf::from(".")],
430 "https://example.com",
431 None,
432 )
433 .unwrap();
434 draft.write_linkedin_drafts(store_dir.path()).unwrap();
435
436 let files: Vec<_> = fs::read_dir(store_dir.path())
437 .unwrap()
438 .filter_map(|e| e.ok())
439 .collect();
440 assert_eq!(files.len(), 1, "expected 1 .linkedin file");
441 assert!(
442 files[0]
443 .file_name()
444 .to_string_lossy()
445 .ends_with(".linkedin"),
446 "expected .linkedin extension"
447 );
448 }
449
450 #[test]
451 fn test_write_linkedin_drafts_sets_created_in_frontmatter() {
452 let src_dir = tempdir().unwrap();
453 let store_dir = tempdir().unwrap();
454
455 let md_path = write_file(src_dir.path(), "post.md", &md_with_linkedin("Hello"));
456
457 let mut draft = Draft::new(
458 src_dir.path(),
459 &[PathBuf::from(".")],
460 "https://example.com",
461 None,
462 )
463 .unwrap();
464 draft.write_linkedin_drafts(store_dir.path()).unwrap();
465
466 let content = fs::read_to_string(&md_path).unwrap();
467 assert!(
468 content.contains("created ="),
469 "frontmatter should contain created: {content}"
470 );
471 }
472
473 #[test]
474 fn test_write_linkedin_drafts_skips_when_created_set() {
475 let src_dir = tempdir().unwrap();
476 let store_dir = tempdir().unwrap();
477
478 write_file(
481 src_dir.path(),
482 "post.md",
483 &md_with_linkedin_and_created("Hello"),
484 );
485
486 let mut draft = Draft::new(
487 src_dir.path(),
488 &[PathBuf::from(".")],
489 "https://example.com",
490 None,
491 )
492 .unwrap();
493 draft.write_linkedin_drafts(store_dir.path()).unwrap();
494
495 assert_eq!(
496 draft.count_written(),
497 0,
498 "should have skipped already-created post"
499 );
500 }
501
502 #[test]
503 fn test_linkedin_file_content() {
504 let src_dir = tempdir().unwrap();
505 let store_dir = tempdir().unwrap();
506
507 write_file(
508 src_dir.path(),
509 "my-post.md",
510 &md_with_linkedin("My post text"),
511 );
512
513 let mut draft = Draft::new(
514 src_dir.path(),
515 &[PathBuf::from(".")],
516 "https://example.com",
517 None,
518 )
519 .unwrap();
520 draft.write_linkedin_drafts(store_dir.path()).unwrap();
521
522 let file_path = store_dir.path().join("my-post.linkedin");
523 let content = fs::read_to_string(&file_path).unwrap();
524 let record: LinkedinFile = serde_json::from_str(&content).unwrap();
525
526 assert_eq!(record.text, "My post text");
527 assert!(record.source_path.is_some());
528 }
529
530 #[test]
531 fn test_derive_link_strips_content_prefix() {
532 let root = Path::new("/site");
533 let path = Path::new("/site/content/blog/my-post.md");
534 let link = derive_link(path, root, "https://example.com");
535 assert_eq!(link.as_deref(), Some("https://example.com/blog/my-post"));
536 }
537
538 #[test]
539 fn test_draft_new_respects_min_date() {
540 let dir = tempdir().unwrap();
541 let old = "+++\ntitle = \"Old\"\ndate = 2026-01-01\n\n[linkedin]\ndescription = \"old\"\n+++\n\nBody.\n";
542 write_file(dir.path(), "old.md", old);
543
544 let min_date = Datetime::from_str("2026-04-01").unwrap();
545 let result = Draft::new(
546 dir.path(),
547 &[PathBuf::from(".")],
548 "https://example.com",
549 Some(min_date),
550 );
551 assert!(
552 matches!(result, Err(DraftError::BlogPostListEmpty)),
553 "old post should be filtered out: {result:?}"
554 );
555 }
556
557 #[test]
561 fn test_draft_new_skips_published_posts() {
562 let dir = tempdir().unwrap();
563 write_file(
564 dir.path(),
565 "post.md",
566 &md_with_linkedin_and_published("Hello"),
567 );
568
569 let result = Draft::new(
570 dir.path(),
571 &[PathBuf::from(".")],
572 "https://example.com",
573 None,
574 );
575 assert!(
576 matches!(result, Err(DraftError::BlogPostListEmpty)),
577 "published post should be skipped: {result:?}"
578 );
579 }
580
581 #[test]
583 fn test_draft_new_reads_description_file() {
584 let dir = tempdir().unwrap();
585 fs::write(dir.path().join("linkedin.md"), "Text from file").unwrap();
586 let content = "+++\ntitle = \"T\"\ndate = 2026-04-03\n\n[linkedin]\ndescription_file = \"linkedin.md\"\n+++\n\nBody.\n";
587 write_file(dir.path(), "post.md", content);
588
589 let mut draft = Draft::new(
590 dir.path(),
591 &[PathBuf::from(".")],
592 "https://example.com",
593 None,
594 )
595 .unwrap();
596 let store_dir = tempdir().unwrap();
597 draft.write_linkedin_drafts(store_dir.path()).unwrap();
598
599 let file_path = store_dir.path().join("post.linkedin");
600 let record: LinkedinFile =
601 serde_json::from_str(&fs::read_to_string(&file_path).unwrap()).unwrap();
602 assert_eq!(record.text, "Text from file");
603 }
604
605 #[test]
607 fn test_draft_new_fails_on_post_too_long() {
608 let dir = tempdir().unwrap();
609 let long_text: String = "a".repeat(LINKEDIN_POST_MAX_CHARS + 1);
611 let content = format!(
612 "+++\ntitle = \"T\"\ndate = 2026-04-03\n\n[linkedin]\ndescription = \"{long_text}\"\n+++\n\nBody.\n"
613 );
614 write_file(dir.path(), "post.md", &content);
615
616 let result = Draft::new(
617 dir.path(),
618 &[PathBuf::from(".")],
619 "https://example.com",
620 None,
621 );
622 assert!(
623 matches!(result, Err(DraftError::PostTooLong { .. })),
624 "expected PostTooLong, got {result:?}"
625 );
626 }
627
628 #[test]
630 fn test_draft_new_accepts_text_within_limit() {
631 let dir = tempdir().unwrap();
632 let text: String = "a".repeat(100);
634 write_file(dir.path(), "post.md", &md_with_linkedin(&text));
635
636 let result = Draft::new(
637 dir.path(),
638 &[PathBuf::from(".")],
639 "https://example.com",
640 None,
641 );
642 assert!(
643 result.is_ok(),
644 "should accept text within limit: {result:?}"
645 );
646 }
647
648 #[test]
650 fn test_linkedin_file_includes_link() {
651 let src_dir = tempdir().unwrap();
652 let store_dir = tempdir().unwrap();
653
654 write_file(
655 src_dir.path(),
656 "content/blog/my-post.md",
657 &md_with_linkedin("Hello"),
658 );
659
660 let mut draft = Draft::new(
661 src_dir.path(),
662 &[PathBuf::from("content/blog")],
663 "https://example.com",
664 None,
665 )
666 .unwrap();
667 draft.write_linkedin_drafts(store_dir.path()).unwrap();
668
669 let file_path = store_dir.path().join("my-post.linkedin");
670 let record: LinkedinFile =
671 serde_json::from_str(&fs::read_to_string(&file_path).unwrap()).unwrap();
672 assert!(
673 record.link.is_some(),
674 "link should be set in .linkedin file"
675 );
676 assert!(
677 record.link.unwrap().contains("example.com"),
678 "link should contain base_url"
679 );
680 }
681
682 #[test]
684 fn test_linkedin_file_deserializes_without_source_path() {
685 let json = r#"{"text":"Hello","created_at":"2026-04-03"}"#;
686 let f: LinkedinFile = serde_json::from_str(json).unwrap();
687 assert!(f.source_path.is_none());
688 assert_eq!(f.text, "Hello");
689 }
690}