Skip to main content

gen_linkedin/
draft.rs

1//! LinkedIn draft generation from blog post frontmatter.
2//!
3//! Scans a content directory for Markdown files that have a `[linkedin]`
4//! frontmatter section with post text, builds [`LinkedinFile`] JSON draft
5//! files in a store directory, and records the draft date in the source
6//! frontmatter for idempotency.
7//!
8//! # Workflow
9//!
10//! 1. Author writes a blog post and adds a `[linkedin]` section with either
11//!    `description` (inline) or `description_file` (path to a separate file).
12//! 2. `pcu linkedin draft` calls [`Draft::new`] then
13//!    [`Draft::write_linkedin_drafts`].
14//! 3. Draft files (`.linkedin` JSON) appear in the store directory.
15//! 4. `pcu linkedin post` reads the store and publishes each draft.
16//!
17//! # Character limit
18//!
19//! LinkedIn posts are validated against [`LINKEDIN_POST_MAX_CHARS`] (default
20//! 3 000). The generated link is included in the count. Adjust the constant if
21//! LinkedIn changes its limit.
22
23use 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
37/// Maximum number of Unicode characters allowed in a LinkedIn post, including
38/// the appended link.
39///
40/// LinkedIn's documented limit as of 2025 is 3 000 characters. The value is
41/// exposed as a public constant so callers can surface it in error messages or
42/// UI. Override at the application level if LinkedIn updates its limit.
43pub const LINKEDIN_POST_MAX_CHARS: usize = 3_000;
44
45/// Errors that can occur during LinkedIn draft generation.
46#[non_exhaustive]
47#[derive(Debug, Error)]
48pub enum DraftError {
49    /// I/O error reading or writing files.
50    #[error("io error: {0}")]
51    Io(#[from] std::io::Error),
52    /// JSON serialization error writing the `.linkedin` file.
53    #[error("json serialization error: {0}")]
54    Json(#[from] serde_json::Error),
55    /// Frontmatter write-back error.
56    #[error("frontmatter write error: {0}")]
57    FmWrite(#[from] FmWriteError),
58    /// TOML parse error reading a blog post's frontmatter.
59    #[error("toml parse error in {file:?}: {source}")]
60    Toml {
61        /// Source TOML error.
62        source: toml::de::Error,
63        /// Path of the offending file.
64        file: PathBuf,
65    },
66    /// Post text exceeds the LinkedIn character limit.
67    ///
68    /// The character count includes the post text and the appended link
69    /// (separated by a single space).
70    #[error("post too long in {file:?}: {chars} chars exceeds maximum {max}")]
71    PostTooLong {
72        /// Total character count (text + space + link).
73        chars: usize,
74        /// Configured maximum ([`LINKEDIN_POST_MAX_CHARS`]).
75        max: usize,
76        /// Path of the offending source file.
77        file: PathBuf,
78    },
79    /// No blog posts found matching the filter criteria.
80    #[error("no blog posts found matching the filter")]
81    BlogPostListEmpty,
82}
83
84/// The JSON file written to the LinkedIn store directory.
85///
86/// Each `.linkedin` file corresponds to one staged post. [`crate::Post`] reads
87/// these files and publishes them via the LinkedIn API.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct LinkedinFile {
90    /// Text of the LinkedIn post.
91    pub text: String,
92    /// Optional URL appended to the post (derived from `base_url` + slug).
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub link: Option<String>,
95    /// ISO date the draft was created (`YYYY-MM-DD`).
96    pub created_at: String,
97    /// Absolute path to the source markdown file (used for `published`
98    /// write-back).
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub source_path: Option<PathBuf>,
101}
102
103/// Return today's date as a TOML `Datetime` (date-only).
104fn 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/// An internal representation of a qualifying blog post.
114#[derive(Debug)]
115struct BlogPost {
116    /// Absolute path to the `.md` file.
117    path: PathBuf,
118    /// Post text (from `description` or `description_file`).
119    text: String,
120    /// Derived post URL.
121    link: Option<String>,
122}
123
124/// Manages staged LinkedIn drafts for a set of blog posts.
125///
126/// Create with [`Draft::new`], then call [`Draft::write_linkedin_drafts`] to
127/// write `.linkedin` JSON files to the store directory and stamp the source
128/// frontmatter with the creation date.
129#[derive(Debug)]
130pub struct Draft {
131    posts: Vec<BlogPost>,
132    written: usize,
133}
134
135impl Draft {
136    /// Scan `blog_paths` under `www_src_root`, collect posts that have a
137    /// `[linkedin]` section with post text, and validate their length.
138    ///
139    /// Posts are skipped when:
140    /// - The `[linkedin]` section is absent.
141    /// - Neither `description` nor `description_file` yields text.
142    /// - `[linkedin].created` is already set (already drafted).
143    /// - `[linkedin].published` is already set (already posted).
144    /// - The post's `date` field predates `min_date` (when provided).
145    ///
146    /// Returns [`DraftError::PostTooLong`] if any post's text + link exceeds
147    /// [`LINKEDIN_POST_MAX_CHARS`] characters.
148    ///
149    /// Returns [`DraftError::BlogPostListEmpty`] when no qualifying posts
150    /// remain.
151    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    /// Write `.linkedin` JSON files to `store_dir` for all collected posts,
176    /// and write `created = <today>` into each source file's `[linkedin]`
177    /// section.
178    ///
179    /// Posts that already have `[linkedin].created` set are skipped
180    /// (idempotent). The store directory is created if absent.
181    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            // Idempotency guard: skip if created is already stamped.
187            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            // Stamp the creation date into the source frontmatter.
196            write_linkedin_date_field(&post.path, "created", today)?;
197
198            // Derive a filename from the source file stem.
199            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    /// Number of `.linkedin` files written in the last call to
224    /// [`Draft::write_linkedin_drafts`].
225    pub fn count_written(&self) -> usize {
226        self.written
227    }
228}
229
230/// Walk `dir` recursively and add qualifying posts to `out`.
231fn 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
262/// Try to load a `BlogPost` from `path`, applying all skip conditions.
263///
264/// Returns `None` when the post should be skipped (no `[linkedin]` section,
265/// no text, already drafted/published, or predates `min_date`).
266fn 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    // Skip posts with no [linkedin] section.
279    let li = match fm.linkedin {
280        Some(ref li) => li,
281        None => return Ok(None),
282    };
283
284    // Skip already-published posts.
285    if li.published.is_some() {
286        log::debug!("Skipping — [linkedin].published already set in {path:?}");
287        return Ok(None);
288    }
289
290    // Apply minimum date filter.
291    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    // Resolve post text (description_file takes precedence over description).
300    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), // No text — not opted in.
304    };
305
306    // Derive the post link.
307    let link = derive_link(path, www_src_root, base_url);
308
309    // Validate character count: text + space + link.
310    let char_count = text.chars().count()
311        + link
312            .as_deref()
313            .map(|l| 1 + l.chars().count()) // " " + link
314            .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
331/// Derive a public URL for the post from its filesystem path.
332///
333/// Strips `www_src_root` and a leading `content/` segment, removes the `.md`
334/// extension, then prepends `base_url`.
335fn 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    // ── existing tests (must stay GREEN) ────────────────────────────────────
382
383    #[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        // Post with created already set is included in Draft::new (we keep
479        // it) but write_linkedin_drafts skips writing it.
480        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    // ── new tests ────────────────────────────────────────────────────────────
558
559    // RED: posts with [linkedin].published are skipped entirely
560    #[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    // RED: description_file is read and used as post text
582    #[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    // RED: post text that exceeds LINKEDIN_POST_MAX_CHARS returns PostTooLong
606    #[test]
607    fn test_draft_new_fails_on_post_too_long() {
608        let dir = tempdir().unwrap();
609        // Generate text longer than the limit
610        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    // RED: text within limit (no link) is accepted
629    #[test]
630    fn test_draft_new_accepts_text_within_limit() {
631        let dir = tempdir().unwrap();
632        // Text at exactly the limit minus space+link chars still fits
633        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    // RED: link is appended to the .linkedin file
649    #[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    // RED: LinkedinFile deserializes without source_path
683    #[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}