micropub 0.1.1

Ultra-compliant Micropub CLI for creating, updating, and managing IndieWeb posts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// ABOUTME: Draft management for micropub CLI
// ABOUTME: Handles draft creation, parsing, serialization, and lifecycle

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use is_terminal::IsTerminal;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::Command;
use uuid::Uuid;

use crate::config::{get_archive_dir, get_drafts_dir, Config};

/// Helper function to prompt user for showing more results
fn prompt_for_more() -> Result<bool> {
    if !io::stdout().is_terminal() {
        return Ok(false);
    }

    print!("Show more results? [y/n]: ");
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    Ok(input.trim().eq_ignore_ascii_case("y"))
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct DraftMetadata {
    #[serde(rename = "type")]
    pub post_type: String,
    pub name: Option<String>,
    pub published: Option<DateTime<Utc>>,
    #[serde(default)]
    pub category: Vec<String>,
    #[serde(default)]
    pub syndicate_to: Vec<String>,
    pub profile: Option<String>,
    #[serde(default)]
    pub photo: Vec<String>,
    pub status: Option<String>,
    pub url: Option<String>,
    pub published_at: Option<DateTime<Utc>>,
}

impl Default for DraftMetadata {
    fn default() -> Self {
        Self {
            post_type: "note".to_string(),
            name: None,
            published: None,
            category: Vec::new(),
            syndicate_to: Vec::new(),
            profile: None,
            photo: Vec::new(),
            status: None,
            url: None,
            published_at: None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Draft {
    pub id: String,
    pub metadata: DraftMetadata,
    pub content: String,
}

impl Draft {
    /// Create a new draft with default metadata
    pub fn new(id: String) -> Self {
        Self {
            id,
            metadata: DraftMetadata::default(),
            content: String::new(),
        }
    }

    /// Parse a draft from a string (YAML frontmatter + content)
    pub fn from_string(id: String, source: String) -> Result<Self> {
        // Split on --- delimiters
        let parts: Vec<&str> = source.splitn(3, "---").collect();

        if parts.len() < 3 {
            anyhow::bail!("Invalid draft format: missing frontmatter delimiters");
        }

        let frontmatter = parts[1].trim();
        let content = parts[2].trim().to_string();

        let metadata: DraftMetadata =
            serde_yaml::from_str(frontmatter).context("Failed to parse frontmatter")?;

        Ok(Self {
            id,
            metadata,
            content,
        })
    }

    /// Load a draft from file
    pub fn load(id: &str) -> Result<Self> {
        // Validate draft ID to prevent path traversal
        if id.contains('/') || id.contains('\\') || id.contains("..") {
            anyhow::bail!("Invalid draft ID: {}", id);
        }

        let path = get_drafts_dir()?.join(format!("{}.md", id));
        let contents = fs::read_to_string(&path).context("Failed to read draft file")?;
        Self::from_string(id.to_string(), contents)
    }

    /// Serialize draft to string (YAML frontmatter + content)
    pub fn to_string(&self) -> Result<String> {
        let frontmatter =
            serde_yaml::to_string(&self.metadata).context("Failed to serialize frontmatter")?;

        Ok(format!("---\n{}---\n\n{}", frontmatter, self.content))
    }

    /// Save draft to file
    pub fn save(&self) -> Result<PathBuf> {
        let path = get_drafts_dir()?.join(format!("{}.md", self.id));
        let contents = self.to_string()?;
        fs::write(&path, contents).context("Failed to write draft file")?;
        Ok(path)
    }

    /// Archive this draft (move to archive directory)
    pub fn archive(&self) -> Result<PathBuf> {
        let archive_path = get_archive_dir()?.join(format!("{}.md", self.id));
        let contents = self.to_string()?;
        fs::write(&archive_path, contents).context("Failed to write archived draft")?;

        // Remove from drafts directory
        let draft_path = get_drafts_dir()?.join(format!("{}.md", self.id));
        if draft_path.exists() {
            fs::remove_file(&draft_path)?;
        }

        Ok(archive_path)
    }

    /// List all draft IDs
    pub fn list_all() -> Result<Vec<String>> {
        let drafts_dir = get_drafts_dir()?;
        let mut draft_ids = Vec::new();

        for entry in fs::read_dir(drafts_dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.extension().and_then(|s| s.to_str()) == Some("md") {
                if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                    draft_ids.push(stem.to_string());
                }
            }
        }

        Ok(draft_ids)
    }
}

/// Generate a new draft ID
pub fn generate_draft_id() -> String {
    Uuid::new_v4().to_string()
}

/// Create a new draft and open in editor
pub fn cmd_new() -> Result<()> {
    let id = generate_draft_id();
    let draft = Draft::new(id.clone());

    // Save initial draft
    let path = draft.save()?;

    // Open in editor
    let config = Config::load()?;
    let editor = config
        .editor
        .or_else(|| std::env::var("EDITOR").ok())
        .unwrap_or_else(|| "vim".to_string());

    Command::new(&editor)
        .arg(&path)
        .status()
        .context("Failed to open editor")?;

    println!("Draft created: {}", id);
    println!("Path: {}", path.display());

    Ok(())
}

/// Edit an existing draft
pub fn cmd_edit(draft_id: &str) -> Result<()> {
    // Validate draft ID to prevent path traversal
    if draft_id.contains('/') || draft_id.contains('\\') || draft_id.contains("..") {
        anyhow::bail!("Invalid draft ID: {}", draft_id);
    }

    let path = get_drafts_dir()?.join(format!("{}.md", draft_id));

    if !path.exists() {
        anyhow::bail!("Draft not found: {}", draft_id);
    }

    let config = Config::load()?;
    let editor = config
        .editor
        .or_else(|| std::env::var("EDITOR").ok())
        .unwrap_or_else(|| "vim".to_string());

    Command::new(&editor)
        .arg(&path)
        .status()
        .context("Failed to open editor")?;

    Ok(())
}

/// List all drafts with optional category filter
pub fn cmd_list(category_filter: Option<&str>, limit: usize, offset: usize) -> Result<()> {
    let mut all_draft_ids = Draft::list_all()?;

    if all_draft_ids.is_empty() {
        println!("No drafts found.");
        return Ok(());
    }

    // Sort for consistent ordering
    all_draft_ids.sort();

    // Apply category filter first to get filtered list
    let filtered_drafts: Vec<_> = if let Some(filter) = category_filter {
        all_draft_ids
            .into_iter()
            .filter_map(|id| {
                Draft::load(&id).ok().and_then(|draft| {
                    if draft.metadata.category.iter().any(|c| c == filter) {
                        Some((id, draft))
                    } else {
                        None
                    }
                })
            })
            .collect()
    } else {
        all_draft_ids
            .into_iter()
            .filter_map(|id| Draft::load(&id).ok().map(|draft| (id, draft)))
            .collect()
    };

    if filtered_drafts.is_empty() {
        if category_filter.is_some() {
            println!("No drafts found with that category.");
        } else {
            println!("No drafts found.");
        }
        return Ok(());
    }

    let mut current_offset = offset;
    let mut first_page = true;

    loop {
        let page_items: Vec<_> = filtered_drafts
            .iter()
            .skip(current_offset)
            .take(limit)
            .collect();

        if page_items.is_empty() {
            if first_page {
                println!("No drafts found at offset {}.", current_offset);
            } else {
                println!("No more drafts.");
            }
            return Ok(());
        }

        if first_page {
            if let Some(filter) = category_filter {
                println!("Drafts with category '{}':", filter);
            } else {
                println!("Drafts:");
            }
        }

        for (id, draft) in page_items {
            let title = draft.metadata.name.as_deref().unwrap_or("[untitled]");
            let post_type = &draft.metadata.post_type;
            let categories = if draft.metadata.category.is_empty() {
                String::new()
            } else {
                format!(" [{}]", draft.metadata.category.join(", "))
            };
            println!("  {} - {} ({}){}", id, title, post_type, categories);
        }

        // Check if there are more results
        let remaining = filtered_drafts.len().saturating_sub(current_offset + limit);
        if remaining == 0 {
            // No more results
            return Ok(());
        }

        // Prompt for more results if in TTY mode
        if !prompt_for_more()? {
            return Ok(());
        }

        current_offset += limit;
        first_page = false;
    }
}

/// Search drafts by content or metadata
pub fn cmd_search(query: &str) -> Result<()> {
    let draft_ids = Draft::list_all()?;

    if draft_ids.is_empty() {
        println!("No drafts found.");
        return Ok(());
    }

    let query_lower = query.to_lowercase();
    let mut found_count = 0;

    println!("Searching for '{}'...\n", query);

    for id in draft_ids {
        match Draft::load(&id) {
            Ok(draft) => {
                let mut matches = Vec::new();

                // Search in title
                if let Some(ref title) = draft.metadata.name {
                    if title.to_lowercase().contains(&query_lower) {
                        matches.push("title");
                    }
                }

                // Search in content
                if draft.content.to_lowercase().contains(&query_lower) {
                    matches.push("content");
                }

                // Search in categories
                if draft
                    .metadata
                    .category
                    .iter()
                    .any(|c| c.to_lowercase().contains(&query_lower))
                {
                    matches.push("category");
                }

                if !matches.is_empty() {
                    found_count += 1;
                    let title = draft
                        .metadata
                        .name
                        .unwrap_or_else(|| "[untitled]".to_string());
                    println!("{} - {}", id, title);
                    println!("  Matched in: {}", matches.join(", "));

                    // Show a snippet of content if it matched
                    if matches.contains(&"content") {
                        let snippet = draft
                            .content
                            .lines()
                            .find(|line| line.to_lowercase().contains(&query_lower))
                            .map(|line| {
                                if line.len() > 80 {
                                    format!("{}...", &line[..77])
                                } else {
                                    line.to_string()
                                }
                            })
                            .unwrap_or_default();
                        if !snippet.is_empty() {
                            println!("  {}", snippet);
                        }
                    }
                    println!();
                }
            }
            Err(_) => continue,
        }
    }

    if found_count == 0 {
        println!("No drafts found matching '{}'.", query);
    } else {
        println!("Found {} draft(s).", found_count);
    }

    Ok(())
}

/// Show a draft's content
pub fn cmd_show(draft_id: &str) -> Result<()> {
    // Validate draft ID to prevent path traversal
    if draft_id.contains('/') || draft_id.contains('\\') || draft_id.contains("..") {
        anyhow::bail!("Invalid draft ID: {}", draft_id);
    }

    let draft = Draft::load(draft_id)?;
    println!("{}", draft.to_string()?);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_draft_roundtrip() {
        let original = Draft {
            id: "test".to_string(),
            metadata: DraftMetadata {
                post_type: "article".to_string(),
                name: Some("Test Post".to_string()),
                category: vec!["test".to_string()],
                ..Default::default()
            },
            content: "Test content".to_string(),
        };

        let serialized = original.to_string().unwrap();
        let parsed = Draft::from_string("test".to_string(), serialized).unwrap();

        assert_eq!(parsed.metadata.name, original.metadata.name);
        assert_eq!(parsed.content, original.content);
    }
}