hwp2md 0.5.0

HWP/HWPX ↔ Markdown bidirectional converter
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! High-level conversion entry points for HWP/HWPX ↔ Markdown.

use std::collections::HashMap;
use std::fs;
use std::path::Path;

/// Maximum permitted size for a Markdown file passed to [`check`].
///
/// Mirrors the 256 MB decompressed-stream limit used for HWP CFB streams so
/// that the `check` function never allocates an unbounded amount of heap memory
/// for a plain-text input.
const MAX_MD_FILE_SIZE: u64 = 256 * 1024 * 1024; // 268_435_456 bytes

use crate::error::Hwp2MdError;
use crate::hwp;
use crate::hwpx;
use crate::ir;
use crate::md;

/// Convert an HWP or HWPX document to Markdown.
///
/// Reads `input` (`.hwp` or `.hwpx`), converts it to Markdown, and writes the
/// result to `output` (or stdout when `None`).  Embedded images are extracted
/// to `assets_dir` when provided.  Set `frontmatter` to `true` to prepend a
/// YAML front-matter block with document metadata.
///
/// # Errors
///
/// Returns [`Hwp2MdError::UnsupportedFormat`] for unknown extensions and
/// propagates I/O or parse errors from the underlying readers.
pub fn to_markdown(
    input: &Path,
    output: Option<&Path>,
    assets_dir: Option<&Path>,
    frontmatter: bool,
) -> Result<(), Hwp2MdError> {
    let ext = input
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    let doc = match ext.as_str() {
        "hwp" => {
            tracing::info!("Parsing HWP 5.0: {:?}", input);
            hwp::read_hwp(input)?
        }
        "hwpx" => {
            tracing::info!("Parsing HWPX: {:?}", input);
            hwpx::read_hwpx(input)?
        }
        _ => {
            return Err(Hwp2MdError::UnsupportedFormat(format!(
                ".{ext}. Expected .hwp or .hwpx"
            )))
        }
    };

    if let Some(dir) = assets_dir {
        write_assets(&doc, dir)?;
    }

    let markdown = md::write_markdown(&doc, frontmatter);

    match output {
        Some(path) => {
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(path, &markdown)?;
            tracing::info!("Written to {:?}", path);
        }
        None => {
            print!("{markdown}");
        }
    }

    Ok(())
}

/// Convert a Markdown file to HWPX format.
///
/// Reads `input` (`.md` or `.markdown`), parses it into the intermediate
/// representation, and writes a conformant HWPX archive to `output`.  When
/// `output` is `None` the output path is derived by replacing the input
/// extension with `.hwpx`.  The optional `style` argument points to a YAML
/// style template that overrides page dimensions, margins, fonts, and heading
/// line spacing in the generated HWPX output.
///
/// # Errors
///
/// Returns [`Hwp2MdError::UnsupportedFormat`] when `input` does not have a
/// Markdown extension, and propagates I/O or write errors.
pub fn to_hwpx(
    input: &Path,
    output: Option<&Path>,
    style: Option<&Path>,
) -> Result<(), Hwp2MdError> {
    let ext = input
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    if ext != "md" && ext != "markdown" {
        return Err(Hwp2MdError::UnsupportedFormat(format!(
            "Expected .md or .markdown file, got .{ext}"
        )));
    }

    let content = fs::read_to_string(input)?;
    let doc = md::parse_markdown(&content);

    let out_path = output.map_or_else(
        || input.with_extension("hwpx"),
        std::path::Path::to_path_buf,
    );

    if let Some(parent) = out_path.parent() {
        fs::create_dir_all(parent)?;
    }

    hwpx::write_hwpx(&doc, &out_path, style)?;
    tracing::info!("Written to {:?}", out_path);

    Ok(())
}

/// Print human-readable metadata and statistics for an HWP or HWPX file.
///
/// Writes a summary (format, title, author, section count, block count,
/// estimated character count, asset count) to stdout.
///
/// # Errors
///
/// Returns [`Hwp2MdError::UnsupportedFormat`] for unknown extensions and
/// propagates parse errors from the underlying readers.
pub fn show_info(input: &Path) -> Result<(), Hwp2MdError> {
    let ext = input
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    match ext.as_str() {
        "hwp" => {
            let doc = hwp::read_hwp(input)?;
            print_info(&doc, input);
        }
        "hwpx" => {
            let doc = hwpx::read_hwpx(input)?;
            print_info(&doc, input);
        }
        _ => return Err(Hwp2MdError::UnsupportedFormat(format!(".{ext}"))),
    }

    Ok(())
}

/// Auto-detect the conversion direction from the input/output file extensions
/// and dispatch to [`to_markdown`] or [`to_hwpx`].
///
/// Supported extension pairs (case-insensitive):
///
/// | Input ext            | Output ext           | Action       |
/// | -------------------- | -------------------- | ------------ |
/// | `.hwp`, `.hwpx`      | `.md`, `.markdown`   | [`to_markdown`] |
/// | `.md`, `.markdown`   | `.hwpx`              | [`to_hwpx`]  |
///
/// `.hwp` is a **read-only** format here β€” Markdown can never be written to
/// a `.hwp` output, only `.hwpx`.  The legacy binary HWP writer is out of
/// scope for this crate.
///
/// Any other combination β€” including same-format pairs, `.hwp` as the
/// output extension, or unknown extensions β€” returns
/// [`Hwp2MdError::UnsupportedFormat`] with a message describing the
/// offending pair.  The function never queries the network and never
/// inspects file contents to determine the direction; only the file
/// extensions are consulted.
///
/// When `force` is `false` and `output` already exists the function
/// returns [`Hwp2MdError::OutputExists`] instead of silently overwriting.
/// Pass `true` to permit overwriting.
///
/// # Errors
///
/// Returns [`Hwp2MdError::OutputExists`] when `force` is `false` and
/// `output` already exists.  Returns [`Hwp2MdError::UnsupportedFormat`]
/// for unrecognised extension pairs.  I/O and parse errors from the
/// underlying readers are propagated as-is.
pub fn convert_auto(input: &Path, output: &Path, force: bool) -> Result<(), Hwp2MdError> {
    if !force && output.exists() {
        return Err(Hwp2MdError::OutputExists {
            path: output.to_path_buf(),
        });
    }

    let in_ext = input
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();
    let out_ext = output
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    let in_kind = classify_format(&in_ext);
    let out_kind = classify_format(&out_ext);

    match (in_kind, out_kind) {
        (FormatKind::Hwp | FormatKind::Hwpx, FormatKind::Markdown) => {
            to_markdown(input, Some(output), None, false)
        }
        (FormatKind::Markdown, FormatKind::Hwpx) => to_hwpx(input, Some(output), None),
        _ => Err(Hwp2MdError::UnsupportedFormat(format!(
            "cannot infer conversion direction from .{in_ext} -> .{out_ext}; \
             expected .hwp/.hwpx -> .md/.markdown or .md/.markdown -> .hwpx"
        ))),
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum FormatKind {
    Hwp,
    Hwpx,
    Markdown,
    Unknown,
}

fn classify_format(ext: &str) -> FormatKind {
    match ext {
        "hwp" => FormatKind::Hwp,
        "hwpx" => FormatKind::Hwpx,
        "md" | "markdown" => FormatKind::Markdown,
        _ => FormatKind::Unknown,
    }
}

/// Validate a file by parsing it into the IR without producing any output.
///
/// Detects the format from the file extension, reads the file, and attempts
/// to parse it.  Returns `Ok(())` if parsing succeeds, or an [`Hwp2MdError`]
/// with details if the file cannot be read or is structurally invalid.
///
/// Supported extensions: `.hwp`, `.hwpx`, `.md`, `.markdown`.
///
/// # Errors
///
/// Returns an error if the file cannot be read, the extension is
/// unrecognised, or the content fails structural validation.
pub fn check(input: &Path) -> Result<(), Hwp2MdError> {
    let ext = input
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    match ext.as_str() {
        "hwp" => {
            tracing::info!("Checking HWP 5.0: {:?}", input);
            hwp::read_hwp(input)?;
        }
        "hwpx" => {
            tracing::info!("Checking HWPX: {:?}", input);
            hwpx::read_hwpx(input)?;
        }
        "md" | "markdown" => {
            tracing::info!("Checking Markdown: {:?}", input);
            let file_size = fs::metadata(input)?.len();
            if file_size > MAX_MD_FILE_SIZE {
                return Err(Hwp2MdError::FileTooLarge {
                    path: input.to_path_buf(),
                    size: file_size,
                    limit: MAX_MD_FILE_SIZE,
                });
            }
            let content = fs::read_to_string(input)?;
            let _doc = md::parse_markdown(&content);
        }
        _ => {
            return Err(Hwp2MdError::UnsupportedFormat(format!(
                ".{ext}. Expected .hwp, .hwpx, .md, or .markdown"
            )));
        }
    }

    Ok(())
}

fn print_info(doc: &ir::Document, path: &Path) {
    println!("File: {}", path.display());
    println!(
        "Format: {}",
        path.extension()
            .and_then(|e| e.to_str())
            .unwrap_or("unknown")
    );

    if let Some(ref title) = doc.metadata.title {
        println!("Title: {title}");
    }
    if let Some(ref author) = doc.metadata.author {
        println!("Author: {author}");
    }

    println!("Sections: {}", doc.sections.len());

    let block_count: usize = doc.sections.iter().map(|s| s.blocks.len()).sum();
    println!("Blocks: {block_count}");

    let char_count: usize = doc
        .sections
        .iter()
        .flat_map(|s| &s.blocks)
        .map(count_chars)
        .sum();
    println!("Characters: ~{char_count}");
    println!("Assets: {}", doc.assets.len());
}

fn count_chars(block: &ir::Block) -> usize {
    match block {
        ir::Block::Heading { inlines, .. } | ir::Block::Paragraph { inlines } => {
            inlines.iter().map(|i| i.text.chars().count()).sum()
        }
        ir::Block::CodeBlock { code, .. } => code.chars().count(),
        ir::Block::BlockQuote { blocks } => blocks.iter().map(count_chars).sum(),
        ir::Block::List { items, .. } => {
            items.iter().flat_map(|i| &i.blocks).map(count_chars).sum()
        }
        ir::Block::Table { rows, .. } => rows
            .iter()
            .flat_map(|r| &r.cells)
            .flat_map(|c| &c.blocks)
            .map(count_chars)
            .sum(),
        ir::Block::Math { tex, .. } => tex.chars().count(),
        ir::Block::Footnote { content, .. } => content.iter().map(count_chars).sum(),
        ir::Block::Image { .. } | ir::Block::HorizontalRule | ir::Block::PageBreak => 0,
    }
}

/// Sanitise an asset filename so that it is safe to write to the filesystem.
///
/// The function:
/// 1. Takes only the basename component (strips any directory prefix).
/// 2. Replaces NUL bytes and path-separator characters (`/`, `\`) with `_`.
/// 3. Prepends `_` when the stem matches a Windows reserved device name
///    (`CON`, `PRN`, `AUX`, `NUL`, `COM1`–`COM9`, `LPT1`–`LPT9`).
/// 4. Falls back to `"asset"` when the result is empty, `"."`, or `".."`.
///
/// # Examples
///
/// ```
/// use hwp2md::convert::sanitize_asset_name;
///
/// assert_eq!(sanitize_asset_name("../../etc/passwd"), "passwd");
/// assert_eq!(sanitize_asset_name("CON.png"), "_CON.png");
/// assert_eq!(sanitize_asset_name(""), "asset");
/// ```
#[must_use]
pub fn sanitize_asset_name(raw: &str) -> String {
    // Windows reserved device names β€” defined first to satisfy items_after_statements.
    const RESERVED: &[&str] = &[
        "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7",
        "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
    ];

    // Step 1: basename only β€” strip any directory prefix.
    let base = Path::new(raw)
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();

    // Step 2: replace dangerous characters (NUL, path separators, ASCII control chars).
    let base: String = base
        .chars()
        .map(|c| {
            if c == '\0' || c == '/' || c == '\\' || (c as u32) < 0x20 || c == '\x7F' {
                '_'
            } else {
                c
            }
        })
        .collect();

    // Step 2b: strip trailing dots and spaces (Windows rejects these).
    let base = base.trim_end_matches(['.', ' ']).to_string();

    // Step 3: Windows reserved device-name check (case-insensitive).
    let stem = base.rsplit_once('.').map_or(base.as_str(), |(s, _)| s);
    let base = if RESERVED.iter().any(|&r| stem.eq_ignore_ascii_case(r)) {
        format!("_{base}")
    } else {
        base
    };

    // Step 4: fallback for empty or dot-only names.
    if base.is_empty() || base == "." || base == ".." {
        "asset".to_string()
    } else {
        base
    }
}

/// Resolve a collision-free filename given a set of already-used names.
///
/// The first occurrence keeps its name unchanged.  Subsequent occurrences
/// receive a ` (N)` suffix inserted before the extension, where N counts up
/// from 2 (matching common operating-system behaviour).
fn next_available_name(name: &str, seen: &mut HashMap<String, u32>) -> String {
    let count = seen.entry(name.to_string()).or_insert(0);
    *count += 1;
    if *count == 1 {
        return name.to_string();
    }
    // Use Path to correctly handle dotfiles (.htaccess) and multi-extension files.
    let p = std::path::Path::new(name);
    match (
        p.file_stem().and_then(|s| s.to_str()),
        p.extension().and_then(|e| e.to_str()),
    ) {
        (Some(stem), Some(ext)) if !stem.is_empty() => {
            format!("{stem} ({count}).{ext}")
        }
        _ => format!("{name} ({count})"),
    }
}

fn write_assets(doc: &ir::Document, dir: &Path) -> Result<(), Hwp2MdError> {
    if doc.assets.is_empty() {
        return Ok(());
    }

    fs::create_dir_all(dir)?;

    let mut seen: HashMap<String, u32> = HashMap::new();

    for asset in &doc.assets {
        let raw_name = sanitize_asset_name(&asset.name);
        let final_name = next_available_name(&raw_name, &mut seen);
        let path = dir.join(&final_name);
        fs::write(&path, &asset.data)?;
        tracing::info!("Extracted: {:?}", path);
    }

    Ok(())
}

// ── ConvertOptions builder ────────────────────────────────────────────────────

/// A builder for configuring and executing a single HWP/HWPX ↔ Markdown
/// conversion.
///
/// `ConvertOptions` provides a fluent API that is easier to use than the
/// individual [`to_markdown`] / [`to_hwpx`] functions when several optional
/// parameters are needed.  The conversion direction is inferred automatically
/// from the `input` and `output` file extensions, identical to
/// [`convert_auto`].
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// use hwp2md::convert::ConvertOptions;
///
/// // HWPX β†’ Markdown with frontmatter and image extraction
/// ConvertOptions::new(Path::new("doc.hwpx"), Path::new("doc.md"))
///     .frontmatter(true)
///     .assets_dir(Path::new("images"))
///     .execute()
///     .expect("conversion failed");
///
/// // Markdown β†’ HWPX, overwrite if output already exists
/// ConvertOptions::new(Path::new("doc.md"), Path::new("doc.hwpx"))
///     .force(true)
///     .execute()
///     .expect("conversion failed");
/// ```
#[derive(Debug)]
pub struct ConvertOptions<'a> {
    input: &'a Path,
    output: &'a Path,
    assets_dir: Option<&'a Path>,
    frontmatter: bool,
    style: Option<&'a Path>,
    force: bool,
}

impl<'a> ConvertOptions<'a> {
    /// Create a new builder for the given `input` β†’ `output` conversion.
    ///
    /// The conversion direction is inferred from the file extensions:
    ///
    /// | `input` extension     | `output` extension    | Action           |
    /// | --------------------- | --------------------- | ---------------- |
    /// | `.hwp`, `.hwpx`       | `.md`, `.markdown`    | β†’ Markdown       |
    /// | `.md`, `.markdown`    | `.hwpx`               | β†’ HWPX           |
    ///
    /// All optional settings default to their "off" value; call the builder
    /// methods to customise them before calling [`execute`](Self::execute).
    #[must_use]
    pub fn new(input: &'a Path, output: &'a Path) -> Self {
        Self {
            input,
            output,
            assets_dir: None,
            frontmatter: false,
            style: None,
            force: false,
        }
    }

    /// Set the directory into which embedded images are extracted.
    ///
    /// Only used when converting HWP/HWPX β†’ Markdown.  Ignored for the
    /// reverse direction.
    #[must_use]
    pub fn assets_dir(mut self, dir: &'a Path) -> Self {
        self.assets_dir = Some(dir);
        self
    }

    /// Prepend a YAML front-matter block with document metadata.
    ///
    /// Only used when converting HWP/HWPX β†’ Markdown.  Defaults to `false`.
    #[must_use]
    pub fn frontmatter(mut self, enabled: bool) -> Self {
        self.frontmatter = enabled;
        self
    }

    /// Use `path` as the YAML style template for the generated HWPX.
    ///
    /// Only used when converting Markdown β†’ HWPX.  Ignored for the reverse
    /// direction.
    #[must_use]
    pub fn style(mut self, path: &'a Path) -> Self {
        self.style = Some(path);
        self
    }

    /// Allow overwriting an existing output file.
    ///
    /// When `false` (the default) [`execute`](Self::execute) returns
    /// [`Hwp2MdError::OutputExists`] if the output path already exists.
    /// Set to `true` to permit overwriting.
    #[must_use]
    pub fn force(mut self, enabled: bool) -> Self {
        self.force = enabled;
        self
    }

    /// Execute the conversion described by this builder.
    ///
    /// # Errors
    ///
    /// - [`Hwp2MdError::UnsupportedFormat`] β€” unknown extension pair.
    /// - [`Hwp2MdError::OutputExists`] β€” output exists and `force` is `false`.
    /// - [`Hwp2MdError::Io`] β€” file read/write failure.
    /// - [`Hwp2MdError::HwpParse`] / [`Hwp2MdError::HwpxParse`] β€” parse error
    ///   in the input document.
    /// - [`Hwp2MdError::HwpxWrite`] β€” error while generating the HWPX output.
    pub fn execute(self) -> Result<(), Hwp2MdError> {
        if !self.force && self.output.exists() {
            return Err(Hwp2MdError::OutputExists {
                path: self.output.to_path_buf(),
            });
        }

        let in_ext = self
            .input
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase();
        let out_ext = self
            .output
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase();

        match (classify_format(&in_ext), classify_format(&out_ext)) {
            (FormatKind::Hwp | FormatKind::Hwpx, FormatKind::Markdown) => to_markdown(
                self.input,
                Some(self.output),
                self.assets_dir,
                self.frontmatter,
            ),
            (FormatKind::Markdown, FormatKind::Hwpx) => {
                to_hwpx(self.input, Some(self.output), self.style)
            }
            _ => Err(Hwp2MdError::UnsupportedFormat(format!(
                "cannot infer conversion direction from .{in_ext} -> .{out_ext}; \
                 expected .hwp/.hwpx -> .md/.markdown or .md/.markdown -> .hwpx"
            ))),
        }
    }
}

#[cfg(test)]
#[path = "convert_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "convert_tests_count.rs"]
mod tests_count;

#[cfg(test)]
#[path = "convert_tests_builder.rs"]
mod tests_builder;

#[cfg(test)]
#[path = "convert_tests_sanitize.rs"]
mod tests_sanitize;