mirror of
https://github.com/Warky-Devs/go-mdtopdf-helper.git
synced 2026-11-25 13:48:47 +00:00
feat: add DOCX/HTML output, go-tomd reverse converter, and input/output flags
- go-mdtopdf-helper: -format pdf,html,docx; new internal/document writers (standalone HTML, pure Go DOCX) - new go-tomd command converting PDF/HTML/DOCX back to Markdown, skipping existing .md files unless -force - -input/-output on both commands (single file with chosen name, or output directory mirroring the scan layout) - restructure README and build config (Makefile, goreleaser) for both binaries
This commit is contained in:
1 parent
50b7246c21
commit
5bf9c3673d
17 files changed
+1903
-84
No files matched your search
@@ -0,0 +1,426 @@
|
||||
package tomd
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// node is a namespace-less XML element, enough to walk WordprocessingML.
|
||||
type node struct {
|
||||
name string
|
||||
attrs map[string]string
|
||||
children []*node
|
||||
text string
|
||||
}
|
||||
|
||||
func parseXML(data []byte) (*node, error) {
|
||||
dec := xml.NewDecoder(bytes.NewReader(data))
|
||||
root := &node{}
|
||||
stack := []*node{root}
|
||||
|
||||
for {
|
||||
tok, err := dec.Token()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch t := tok.(type) {
|
||||
case xml.StartElement:
|
||||
n := &node{name: t.Name.Local, attrs: map[string]string{}}
|
||||
for _, a := range t.Attr {
|
||||
n.attrs[a.Name.Local] = a.Value
|
||||
}
|
||||
parent := stack[len(stack)-1]
|
||||
parent.children = append(parent.children, n)
|
||||
stack = append(stack, n)
|
||||
case xml.EndElement:
|
||||
stack = stack[:len(stack)-1]
|
||||
case xml.CharData:
|
||||
stack[len(stack)-1].text += string(t)
|
||||
}
|
||||
}
|
||||
return root, nil
|
||||
}
|
||||
|
||||
func (n *node) child(name string) *node {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
for _, c := range n.children {
|
||||
if c.name == name {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *node) attr(name string) string {
|
||||
if n == nil {
|
||||
return ""
|
||||
}
|
||||
return n.attrs[name]
|
||||
}
|
||||
|
||||
// docxDoc holds what is needed from the package to interpret the body.
|
||||
type docxDoc struct {
|
||||
styles map[string]string // styleId -> lower-cased style name
|
||||
listKinds map[string]bool // "numId:ilvl" -> ordered
|
||||
links map[string]string // relationship id -> target
|
||||
}
|
||||
|
||||
// DOCX converts a Word document to Markdown.
|
||||
func DOCX(data []byte) ([]byte, error) {
|
||||
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("not a valid docx file: %w", err)
|
||||
}
|
||||
|
||||
parts := map[string][]byte{}
|
||||
for _, f := range zr.File {
|
||||
switch f.Name {
|
||||
case "word/document.xml", "word/styles.xml", "word/numbering.xml", "word/_rels/document.xml.rels":
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := io.ReadAll(rc)
|
||||
_ = rc.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts[f.Name] = b
|
||||
}
|
||||
}
|
||||
if parts["word/document.xml"] == nil {
|
||||
return nil, fmt.Errorf("docx has no word/document.xml")
|
||||
}
|
||||
|
||||
doc := &docxDoc{styles: map[string]string{}, listKinds: map[string]bool{}, links: map[string]string{}}
|
||||
doc.loadStyles(parts["word/styles.xml"])
|
||||
doc.loadNumbering(parts["word/numbering.xml"])
|
||||
doc.loadLinks(parts["word/_rels/document.xml.rels"])
|
||||
|
||||
root, err := parseXML(parts["word/document.xml"])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse document.xml: %w", err)
|
||||
}
|
||||
|
||||
w := &mdWriter{}
|
||||
w.body(doc, root.child("document").child("body"))
|
||||
return []byte(w.String()), nil
|
||||
}
|
||||
|
||||
func (d *docxDoc) loadStyles(data []byte) {
|
||||
root, err := parseXML(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, s := range root.child("styles").children {
|
||||
if s.name == "style" {
|
||||
d.styles[s.attr("styleId")] = strings.ToLower(s.child("name").attr("val"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *docxDoc) loadNumbering(data []byte) {
|
||||
root, err := parseXML(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// abstractNumId -> level -> ordered
|
||||
abstract := map[string]map[string]bool{}
|
||||
var nums []*node
|
||||
for _, n := range root.child("numbering").children {
|
||||
switch n.name {
|
||||
case "abstractNum":
|
||||
levels := map[string]bool{}
|
||||
for _, lvl := range n.children {
|
||||
if lvl.name == "lvl" {
|
||||
levels[lvl.attr("ilvl")] = lvl.child("numFmt").attr("val") != "bullet"
|
||||
}
|
||||
}
|
||||
abstract[n.attr("abstractNumId")] = levels
|
||||
case "num":
|
||||
nums = append(nums, n)
|
||||
}
|
||||
}
|
||||
|
||||
for _, n := range nums {
|
||||
for lvl, ordered := range abstract[n.child("abstractNumId").attr("val")] {
|
||||
d.listKinds[n.attr("numId")+":"+lvl] = ordered
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *docxDoc) loadLinks(data []byte) {
|
||||
root, err := parseXML(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, r := range root.child("Relationships").children {
|
||||
if r.attr("TargetMode") == "External" {
|
||||
d.links[r.attr("Id")] = r.attr("Target")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var headingStyle = regexp.MustCompile(`^heading (\d)$`)
|
||||
|
||||
type paraKind int
|
||||
|
||||
const (
|
||||
kindParagraph paraKind = iota
|
||||
kindHeading
|
||||
kindList
|
||||
kindCode
|
||||
kindQuote
|
||||
kindRule
|
||||
)
|
||||
|
||||
// mdWriter assembles blocks, keeping consecutive code lines and list items together.
|
||||
type mdBlock struct {
|
||||
kind paraKind
|
||||
text string
|
||||
}
|
||||
|
||||
type mdWriter struct {
|
||||
blocks []mdBlock
|
||||
last paraKind
|
||||
// code and list blocks grow as consecutive paragraphs arrive.
|
||||
open bool
|
||||
}
|
||||
|
||||
func (w *mdWriter) String() string {
|
||||
texts := make([]string, len(w.blocks))
|
||||
for i, b := range w.blocks {
|
||||
texts[i] = b.text
|
||||
if b.kind == kindCode {
|
||||
texts[i] = "```\n" + b.text + "\n```"
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(strings.Join(texts, "\n\n")) + "\n"
|
||||
}
|
||||
|
||||
func (w *mdWriter) add(kind paraKind, text string) {
|
||||
w.blocks = append(w.blocks, mdBlock{kind, text})
|
||||
w.last, w.open = kind, kind == kindCode || kind == kindList
|
||||
}
|
||||
|
||||
// extend appends to the previous block when it is of the same grouped kind.
|
||||
func (w *mdWriter) extend(kind paraKind, text, sep string) {
|
||||
if w.open && w.last == kind {
|
||||
w.blocks[len(w.blocks)-1].text += sep + text
|
||||
return
|
||||
}
|
||||
w.add(kind, text)
|
||||
}
|
||||
|
||||
func (w *mdWriter) body(d *docxDoc, body *node) {
|
||||
if body == nil {
|
||||
return
|
||||
}
|
||||
for _, n := range body.children {
|
||||
switch n.name {
|
||||
case "p":
|
||||
w.paragraph(d, n)
|
||||
case "tbl":
|
||||
if t := d.table(n); t != "" {
|
||||
w.add(kindParagraph, t)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *mdWriter) paragraph(d *docxDoc, p *node) {
|
||||
ppr := p.child("pPr")
|
||||
styleID := ppr.child("pStyle").attr("val")
|
||||
style := d.styles[styleID]
|
||||
if style == "" {
|
||||
style = strings.ToLower(styleID)
|
||||
}
|
||||
|
||||
segs := d.runs(p)
|
||||
text := strings.TrimSpace(renderSegs(segs))
|
||||
plain := plainText(segs)
|
||||
|
||||
switch {
|
||||
case ppr.child("pBdr").child("bottom") != nil && plain == "":
|
||||
w.add(kindRule, "---")
|
||||
case isCodeStyle(style):
|
||||
w.extend(kindCode, plain, "\n")
|
||||
case plain == "":
|
||||
w.open = false
|
||||
default:
|
||||
if m := headingStyle.FindStringSubmatch(style); m != nil {
|
||||
level, _ := strconv.Atoi(m[1])
|
||||
w.add(kindHeading, strings.Repeat("#", min(max(level, 1), 6))+" "+collapseSpace(text))
|
||||
} else if style == "title" {
|
||||
w.add(kindHeading, "# "+collapseSpace(text))
|
||||
} else if numPr := ppr.child("numPr"); numPr != nil {
|
||||
w.extend(kindList, d.listItem(numPr, text), "\n")
|
||||
} else if strings.Contains(style, "quote") {
|
||||
w.add(kindQuote, "> "+strings.ReplaceAll(text, "\n", "\n> "))
|
||||
} else {
|
||||
w.add(kindParagraph, escapeBlockStart(text))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isCodeStyle(style string) bool {
|
||||
return style == "code" || strings.Contains(style, "source code") || strings.Contains(style, "preformatted") ||
|
||||
strings.Contains(style, "html code")
|
||||
}
|
||||
|
||||
func (d *docxDoc) listItem(numPr *node, text string) string {
|
||||
level, _ := strconv.Atoi(numPr.child("ilvl").attr("val"))
|
||||
numID := numPr.child("numId").attr("val")
|
||||
marker := "-"
|
||||
if d.listKinds[numID+":"+strconv.Itoa(level)] {
|
||||
marker = "1."
|
||||
}
|
||||
return strings.Repeat(" ", level) + marker + " " + collapseSpace(text)
|
||||
}
|
||||
|
||||
// runs collects the formatted text of a paragraph, resolving hyperlinks.
|
||||
func (d *docxDoc) runs(p *node) []seg {
|
||||
var segs []seg
|
||||
var walk func(n *node, href string)
|
||||
walk = func(n *node, href string) {
|
||||
for _, c := range n.children {
|
||||
switch c.name {
|
||||
case "r":
|
||||
segs = append(segs, d.run(c, href)...)
|
||||
case "hyperlink":
|
||||
walk(c, d.links[c.attr("id")])
|
||||
case "ins", "smartTag", "sdt", "sdtContent":
|
||||
walk(c, href)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(p, "")
|
||||
return segs
|
||||
}
|
||||
|
||||
func (d *docxDoc) run(r *node, href string) []seg {
|
||||
rpr := r.child("rPr")
|
||||
base := seg{
|
||||
bold: on(rpr.child("b")),
|
||||
italic: on(rpr.child("i")),
|
||||
strike: on(rpr.child("strike")),
|
||||
code: isMono(rpr.child("rFonts").attr("ascii")),
|
||||
href: href,
|
||||
}
|
||||
|
||||
var out []seg
|
||||
for _, c := range r.children {
|
||||
s := base
|
||||
switch c.name {
|
||||
case "t":
|
||||
s.text = c.text
|
||||
case "tab":
|
||||
s.text = " "
|
||||
case "br":
|
||||
s.text = "\n"
|
||||
default:
|
||||
continue
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// on reports whether a toggle property such as <w:b/> is switched on.
|
||||
func on(n *node) bool {
|
||||
if n == nil {
|
||||
return false
|
||||
}
|
||||
switch n.attr("val") {
|
||||
case "0", "false", "off":
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func isMono(font string) bool {
|
||||
f := strings.ToLower(font)
|
||||
for _, m := range []string{"courier", "consolas", "mono", "menlo", "lucida console"} {
|
||||
if strings.Contains(f, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func plainText(segs []seg) string {
|
||||
var b strings.Builder
|
||||
for _, s := range segs {
|
||||
b.WriteString(s.text)
|
||||
}
|
||||
return strings.TrimRight(b.String(), "\n")
|
||||
}
|
||||
|
||||
func (d *docxDoc) table(tbl *node) string {
|
||||
var rows [][]string
|
||||
for _, tr := range tbl.children {
|
||||
if tr.name != "tr" {
|
||||
continue
|
||||
}
|
||||
var cells []string
|
||||
for _, tc := range tr.children {
|
||||
if tc.name != "tc" {
|
||||
continue
|
||||
}
|
||||
var parts []string
|
||||
for _, p := range tc.children {
|
||||
if p.name == "p" {
|
||||
segs := d.runs(p)
|
||||
if len(rows) == 0 {
|
||||
// The first row becomes the Markdown header, which is already bold.
|
||||
for i := range segs {
|
||||
segs[i].bold = false
|
||||
}
|
||||
}
|
||||
if t := collapseSpace(renderSegs(segs)); t != "" {
|
||||
parts = append(parts, t)
|
||||
}
|
||||
}
|
||||
}
|
||||
cell := strings.Join(parts, "<br>")
|
||||
cells = append(cells, strings.ReplaceAll(cell, "|", `\|`))
|
||||
}
|
||||
rows = append(rows, cells)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
cols := 0
|
||||
for _, r := range rows {
|
||||
cols = max(cols, len(r))
|
||||
}
|
||||
|
||||
line := func(cells []string) string {
|
||||
for len(cells) < cols {
|
||||
cells = append(cells, "")
|
||||
}
|
||||
return "| " + strings.Join(cells, " | ") + " |"
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString(line(rows[0]) + "\n")
|
||||
b.WriteString("|" + strings.Repeat(" --- |", cols))
|
||||
for _, r := range rows[1:] {
|
||||
b.WriteString("\n" + line(r))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package tomd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/JohannesKaufmann/html-to-markdown/v2/converter"
|
||||
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/base"
|
||||
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/commonmark"
|
||||
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/strikethrough"
|
||||
"github.com/JohannesKaufmann/html-to-markdown/v2/plugin/table"
|
||||
)
|
||||
|
||||
// HTML converts an HTML document or fragment to Markdown.
|
||||
func HTML(data []byte) ([]byte, error) {
|
||||
conv := converter.NewConverter(converter.WithPlugins(
|
||||
base.NewBasePlugin(),
|
||||
commonmark.NewCommonmarkPlugin(),
|
||||
strikethrough.NewStrikethroughPlugin(),
|
||||
table.NewTablePlugin(),
|
||||
))
|
||||
|
||||
md, err := conv.ConvertString(string(data))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert HTML: %w", err)
|
||||
}
|
||||
return []byte(strings.TrimSpace(md) + "\n"), nil
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package tomd
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// seg is a run of text with uniform inline formatting.
|
||||
type seg struct {
|
||||
text string
|
||||
bold, italic, code, strike bool
|
||||
href string
|
||||
}
|
||||
|
||||
func (s seg) sameFormat(o seg) bool {
|
||||
return s.bold == o.bold && s.italic == o.italic && s.code == o.code && s.strike == o.strike && s.href == o.href
|
||||
}
|
||||
|
||||
// renderSegs turns formatted runs into inline Markdown. Adjacent runs with the same formatting
|
||||
// are merged first, because sources such as Word split text into many runs.
|
||||
func renderSegs(segs []seg) string {
|
||||
var merged []seg
|
||||
for _, s := range segs {
|
||||
if s.text == "" {
|
||||
continue
|
||||
}
|
||||
if n := len(merged); n > 0 && merged[n-1].sameFormat(s) {
|
||||
merged[n-1].text += s.text
|
||||
continue
|
||||
}
|
||||
merged = append(merged, s)
|
||||
}
|
||||
|
||||
var out strings.Builder
|
||||
for i := 0; i < len(merged); {
|
||||
// Group consecutive runs of one link so the whole group sits inside a single [..](..).
|
||||
j := i + 1
|
||||
if merged[i].href != "" {
|
||||
for j < len(merged) && merged[j].href == merged[i].href {
|
||||
j++
|
||||
}
|
||||
}
|
||||
|
||||
var inner strings.Builder
|
||||
for _, s := range merged[i:j] {
|
||||
inner.WriteString(renderSeg(s))
|
||||
}
|
||||
if href := merged[i].href; href != "" {
|
||||
lead, core, trail := splitSpace(inner.String())
|
||||
out.WriteString(lead + "[" + core + "](" + href + ")" + trail)
|
||||
} else {
|
||||
out.WriteString(inner.String())
|
||||
}
|
||||
i = j
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func renderSeg(s seg) string {
|
||||
lead, core, trail := splitSpace(s.text)
|
||||
if core == "" {
|
||||
return s.text
|
||||
}
|
||||
|
||||
if s.code {
|
||||
fence := "`"
|
||||
if strings.Contains(core, "`") {
|
||||
fence = "``"
|
||||
}
|
||||
return lead + fence + core + fence + trail
|
||||
}
|
||||
|
||||
core = escapeInline(core)
|
||||
switch {
|
||||
case s.bold && s.italic:
|
||||
core = "***" + core + "***"
|
||||
case s.bold:
|
||||
core = "**" + core + "**"
|
||||
case s.italic:
|
||||
core = "*" + core + "*"
|
||||
}
|
||||
if s.strike {
|
||||
core = "~~" + core + "~~"
|
||||
}
|
||||
return lead + core + trail
|
||||
}
|
||||
|
||||
// splitSpace separates leading and trailing whitespace, which must stay outside emphasis markers.
|
||||
func splitSpace(s string) (lead, core, trail string) {
|
||||
core = strings.TrimLeftFunc(s, unicode.IsSpace)
|
||||
lead = s[:len(s)-len(core)]
|
||||
trimmed := strings.TrimRightFunc(core, unicode.IsSpace)
|
||||
return lead, trimmed, core[len(trimmed):]
|
||||
}
|
||||
|
||||
// escapeInline backslash-escapes characters that would otherwise be read as Markdown.
|
||||
func escapeInline(s string) string {
|
||||
runes := []rune(s)
|
||||
var b strings.Builder
|
||||
for i, r := range runes {
|
||||
switch r {
|
||||
case '\\', '*', '`', '[', ']', '<':
|
||||
b.WriteByte('\\')
|
||||
case '_':
|
||||
// Underscores inside a word are literal in CommonMark.
|
||||
inWord := i > 0 && i < len(runes)-1 && isAlnum(runes[i-1]) && isAlnum(runes[i+1])
|
||||
if !inWord {
|
||||
b.WriteByte('\\')
|
||||
}
|
||||
}
|
||||
b.WriteRune(r)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func isAlnum(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) }
|
||||
|
||||
var blockStart = regexp.MustCompile(`^(#{1,6}\s|[-+*]\s|\d+[.)]\s|>)`)
|
||||
|
||||
// escapeBlockStart stops a paragraph from being read as a heading, list or quote.
|
||||
func escapeBlockStart(s string) string {
|
||||
if blockStart.MatchString(s) {
|
||||
return `\` + s
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// collapseSpace squeezes runs of whitespace (including newlines) into single spaces.
|
||||
func collapseSpace(s string) string {
|
||||
return strings.Join(strings.Fields(s), " ")
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package tomd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/ledongthuc/pdf"
|
||||
)
|
||||
|
||||
// pdfLine is one visual line of text on a page.
|
||||
type pdfLine struct {
|
||||
x, y, size float64
|
||||
segs []seg
|
||||
plain string
|
||||
raw string // like plain but keeps leading indentation, for code
|
||||
mono bool
|
||||
}
|
||||
|
||||
// PDF converts a PDF to Markdown on a best-effort basis. PDFs carry no document structure, so
|
||||
// headings are inferred from font size, code from monospaced fonts, and lists from bullet or
|
||||
// number prefixes. Tables and images are not recovered.
|
||||
func PDF(data []byte) (out []byte, err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("failed to read PDF: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
r, err := pdf.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read PDF: %w", err)
|
||||
}
|
||||
|
||||
var pages [][]pdfLine
|
||||
for i := 1; i <= r.NumPage(); i++ {
|
||||
page := r.Page(i)
|
||||
if page.V.IsNull() {
|
||||
continue
|
||||
}
|
||||
if lines := groupLines(page.Content().Text); len(lines) > 0 {
|
||||
pages = append(pages, lines)
|
||||
}
|
||||
}
|
||||
|
||||
return []byte(buildMarkdown(pages)), nil
|
||||
}
|
||||
|
||||
func fontFlags(font string) (bold, italic, mono bool) {
|
||||
f := strings.ToLower(font)
|
||||
has := func(subs ...string) bool {
|
||||
for _, s := range subs {
|
||||
if strings.Contains(f, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
return has("bold", "black", "heavy"), has("italic", "oblique"), isMono(f)
|
||||
}
|
||||
|
||||
// groupLines clusters text items into lines and turns them into formatted runs.
|
||||
func groupLines(items []pdf.Text) []pdfLine {
|
||||
items = append([]pdf.Text(nil), items...)
|
||||
sort.SliceStable(items, func(i, j int) bool { return items[i].Y > items[j].Y })
|
||||
|
||||
var clusters [][]pdf.Text
|
||||
for _, it := range items {
|
||||
n := len(clusters)
|
||||
if n > 0 && math.Abs(clusters[n-1][0].Y-it.Y) <= math.Max(2, 0.35*it.FontSize) {
|
||||
clusters[n-1] = append(clusters[n-1], it)
|
||||
continue
|
||||
}
|
||||
clusters = append(clusters, []pdf.Text{it})
|
||||
}
|
||||
|
||||
var lines []pdfLine
|
||||
for _, c := range clusters {
|
||||
if l, ok := buildLine(c); ok {
|
||||
lines = append(lines, l)
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func buildLine(items []pdf.Text) (pdfLine, bool) {
|
||||
sort.SliceStable(items, func(i, j int) bool { return items[i].X < items[j].X })
|
||||
|
||||
line := pdfLine{x: items[0].X, y: items[0].Y}
|
||||
sizeChars := map[float64]int{}
|
||||
monoChars, chars := 0, 0
|
||||
|
||||
var prev *pdf.Text
|
||||
for i := range items {
|
||||
it := items[i]
|
||||
if it.S == "�" || it.S == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
bold, italic, mono := fontFlags(it.Font)
|
||||
s := seg{text: it.S, bold: bold, italic: italic, code: mono}
|
||||
if prev != nil && needsSpace(*prev, it) {
|
||||
s.text = " " + s.text
|
||||
}
|
||||
prev = &items[i]
|
||||
|
||||
if n := len(line.segs); n > 0 && line.segs[n-1].sameFormat(s) {
|
||||
line.segs[n-1].text += s.text
|
||||
} else {
|
||||
line.segs = append(line.segs, s)
|
||||
}
|
||||
|
||||
if !unicode.IsSpace([]rune(it.S)[0]) {
|
||||
sizeChars[math.Round(it.FontSize*2)/2]++
|
||||
chars++
|
||||
if mono {
|
||||
monoChars++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
line.raw = strings.TrimRight(plainText(line.segs), " \t")
|
||||
line.plain = strings.TrimSpace(line.raw)
|
||||
if line.plain == "" {
|
||||
return line, false
|
||||
}
|
||||
|
||||
best := 0
|
||||
for size, n := range sizeChars {
|
||||
if n > best {
|
||||
best, line.size = n, size
|
||||
}
|
||||
}
|
||||
line.mono = monoChars == chars
|
||||
return line, true
|
||||
}
|
||||
|
||||
// needsSpace decides whether a space separates two consecutive text items. When the extractor knows
|
||||
// glyph widths the real gap is used; otherwise (positions only advance per text-show operator) any
|
||||
// new position starts a new word, except before closing punctuation.
|
||||
func needsSpace(prev, next pdf.Text) bool {
|
||||
if unicode.IsSpace([]rune(prev.S)[0]) || unicode.IsSpace([]rune(next.S)[0]) {
|
||||
return false
|
||||
}
|
||||
if prev.W > 0 {
|
||||
return next.X-(prev.X+prev.W) > 0.2*next.FontSize
|
||||
}
|
||||
if next.X-prev.X < 0.01 {
|
||||
return false // same show operator: part of the same word
|
||||
}
|
||||
|
||||
first := []rune(next.S)[0]
|
||||
last := []rune(prev.S)[len([]rune(prev.S))-1]
|
||||
return !strings.ContainsRune(",.;:!?)]}%’”", first) && !strings.ContainsRune("([{‘“", last)
|
||||
}
|
||||
|
||||
var listMarker = regexp.MustCompile(`^([•·▪‣◦●○▫–\-*]|\d{1,3}[.)])\s+`)
|
||||
|
||||
// trimPrefix removes the first n runes from the runs.
|
||||
func trimPrefix(segs []seg, n int) []seg {
|
||||
out := make([]seg, 0, len(segs))
|
||||
for _, s := range segs {
|
||||
r := []rune(s.text)
|
||||
switch {
|
||||
case n >= len(r):
|
||||
n -= len(r)
|
||||
continue
|
||||
case n > 0:
|
||||
s.text = string(r[n:])
|
||||
n = 0
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func buildMarkdown(pages [][]pdfLine) string {
|
||||
body := bodySize(pages)
|
||||
headings := headingSizes(pages, body)
|
||||
|
||||
w := &mdWriter{}
|
||||
var (
|
||||
para []seg // paragraph or list item being accumulated
|
||||
paraKind paraKind
|
||||
paraMark string // list marker line prefix
|
||||
textX float64
|
||||
lastY float64
|
||||
codeX float64
|
||||
)
|
||||
|
||||
flush := func() {
|
||||
if len(para) == 0 {
|
||||
return
|
||||
}
|
||||
text := collapseSpace(renderSegs(para))
|
||||
if paraKind == kindList {
|
||||
w.extend(kindList, paraMark+text, "\n")
|
||||
} else {
|
||||
w.add(kindParagraph, escapeBlockStart(text))
|
||||
}
|
||||
para = nil
|
||||
}
|
||||
|
||||
for _, page := range pages {
|
||||
if paraKind != kindCode {
|
||||
flush()
|
||||
}
|
||||
|
||||
left := page[0].x
|
||||
for _, l := range page {
|
||||
left = math.Min(left, l.x)
|
||||
}
|
||||
|
||||
for _, l := range page {
|
||||
switch level := headingLevel(l, headings); {
|
||||
case l.mono:
|
||||
flush()
|
||||
if paraKind != kindCode {
|
||||
codeX = l.x
|
||||
}
|
||||
if blanks := int(math.Round((lastY-l.y)/(l.size*1.4))) - 1; paraKind == kindCode && blanks > 0 && lastY > l.y {
|
||||
for range blanks {
|
||||
w.extend(kindCode, "", "\n")
|
||||
}
|
||||
}
|
||||
indent := strings.Repeat(" ", max(0, int(math.Round((l.x-codeX)/(l.size*0.6)))))
|
||||
w.extend(kindCode, indent+l.raw, "\n")
|
||||
paraKind = kindCode
|
||||
|
||||
case level > 0:
|
||||
flush()
|
||||
w.add(kindHeading, strings.Repeat("#", level)+" "+collapseSpace(renderSegs(stripCode(l.segs))))
|
||||
paraKind = kindHeading
|
||||
|
||||
default:
|
||||
segs := l.segs
|
||||
if m := listMarker.FindString(l.plain); m != "" {
|
||||
flush()
|
||||
depth := int(math.Round((l.x - left) / (l.size * 1.6)))
|
||||
paraKind = kindList
|
||||
paraMark = strings.Repeat(" ", max(depth, 0)) + markdownMarker(strings.TrimSpace(m))
|
||||
segs = trimPrefix(trimLeadingSpace(segs), len([]rune(strings.TrimSpace(m))))
|
||||
textX = l.x + l.size
|
||||
} else if len(para) > 0 && paraKind != kindCode && lastY-l.y > 0 && lastY-l.y <= l.size*1.7 &&
|
||||
(paraKind != kindList || l.x >= textX-2) {
|
||||
segs = append([]seg{{text: " "}}, segs...)
|
||||
} else {
|
||||
flush()
|
||||
paraKind = kindParagraph
|
||||
}
|
||||
para = append(para, segs...)
|
||||
}
|
||||
lastY = l.y
|
||||
}
|
||||
}
|
||||
flush()
|
||||
|
||||
return w.String()
|
||||
}
|
||||
|
||||
func trimLeadingSpace(segs []seg) []seg {
|
||||
if len(segs) > 0 {
|
||||
segs = append([]seg(nil), segs...)
|
||||
segs[0].text = strings.TrimLeftFunc(segs[0].text, unicode.IsSpace)
|
||||
}
|
||||
return segs
|
||||
}
|
||||
|
||||
func markdownMarker(m string) string {
|
||||
if n, err := strconv.Atoi(strings.TrimRight(m, ".)")); err == nil {
|
||||
return strconv.Itoa(n) + ". "
|
||||
}
|
||||
return "- "
|
||||
}
|
||||
|
||||
// stripCode removes inline-code styling, which is meaningless inside a heading.
|
||||
func stripCode(segs []seg) []seg {
|
||||
out := append([]seg(nil), segs...)
|
||||
for i := range out {
|
||||
out[i].code, out[i].bold = false, false
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// bodySize is the font size that carries the most (non-code) text.
|
||||
func bodySize(pages [][]pdfLine) float64 {
|
||||
counts := map[float64]int{}
|
||||
for _, p := range pages {
|
||||
for _, l := range p {
|
||||
if !l.mono {
|
||||
counts[l.size] += len([]rune(l.plain))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var body float64
|
||||
best := 0
|
||||
for size, n := range counts {
|
||||
if n > best || (n == best && size < body) {
|
||||
body, best = size, n
|
||||
}
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// headingSizes lists the distinct sizes clearly larger than body text, largest first.
|
||||
func headingSizes(pages [][]pdfLine, body float64) []float64 {
|
||||
seen := map[float64]bool{}
|
||||
for _, p := range pages {
|
||||
for _, l := range p {
|
||||
if !l.mono && l.size > body*1.12 {
|
||||
seen[l.size] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sizes := make([]float64, 0, len(seen))
|
||||
for s := range seen {
|
||||
sizes = append(sizes, s)
|
||||
}
|
||||
sort.Sort(sort.Reverse(sort.Float64Slice(sizes)))
|
||||
return sizes
|
||||
}
|
||||
|
||||
func headingLevel(l pdfLine, headings []float64) int {
|
||||
if l.mono {
|
||||
return 0
|
||||
}
|
||||
for i, s := range headings {
|
||||
if l.size == s {
|
||||
return min(i+1, 6)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
// Package tomd converts PDF, HTML and DOCX documents back into Markdown.
|
||||
package tomd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Input formats accepted by ParseFormats, in order of preference when several files share a name.
|
||||
const (
|
||||
FormatDOCX = "docx"
|
||||
FormatHTML = "html"
|
||||
FormatPDF = "pdf"
|
||||
)
|
||||
|
||||
// FormatNames lists every supported input format.
|
||||
var FormatNames = []string{FormatDOCX, FormatHTML, FormatPDF}
|
||||
|
||||
// ParseFormats turns a comma separated list such as "html,docx" into validated formats.
|
||||
func ParseFormats(list string) ([]string, error) {
|
||||
var formats []string
|
||||
for _, f := range strings.Split(list, ",") {
|
||||
f = strings.ToLower(strings.TrimSpace(f))
|
||||
if f == "" || slices.Contains(formats, f) {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(FormatNames, f) {
|
||||
return nil, fmt.Errorf("unknown format %q (available: %s)", f, strings.Join(FormatNames, ", "))
|
||||
}
|
||||
formats = append(formats, f)
|
||||
}
|
||||
if len(formats) == 0 {
|
||||
return nil, fmt.Errorf("no input format given (available: %s)", strings.Join(FormatNames, ", "))
|
||||
}
|
||||
return formats, nil
|
||||
}
|
||||
|
||||
// formatOf returns the format of path from its extension, or "" when it is not a supported input.
|
||||
func formatOf(path string) string {
|
||||
switch strings.ToLower(filepath.Ext(path)) {
|
||||
case ".docx":
|
||||
return FormatDOCX
|
||||
case ".html", ".htm":
|
||||
return FormatHTML
|
||||
case ".pdf":
|
||||
return FormatPDF
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func isMarkdownName(path string) bool {
|
||||
ext := strings.ToLower(filepath.Ext(path))
|
||||
return ext == ".md" || ext == ".markdown"
|
||||
}
|
||||
|
||||
// OutputPath returns the Markdown file written next to input.
|
||||
func OutputPath(input string) string {
|
||||
return strings.TrimSuffix(input, filepath.Ext(input)) + ".md"
|
||||
}
|
||||
|
||||
// Convert converts the file at path to Markdown according to its extension.
|
||||
func Convert(path string) ([]byte, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read file: %w", err)
|
||||
}
|
||||
|
||||
switch formatOf(path) {
|
||||
case FormatDOCX:
|
||||
return DOCX(data)
|
||||
case FormatHTML:
|
||||
return HTML(data)
|
||||
case FormatPDF:
|
||||
return PDF(data)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported file type %q", filepath.Ext(path))
|
||||
}
|
||||
}
|
||||
|
||||
// Runner converts documents to Markdown.
|
||||
//
|
||||
// When InputFile is set only that file is converted (regardless of Formats) and Output, if given,
|
||||
// is the name of the Markdown file to write; ".md" is added unless it already ends in .md or
|
||||
// .markdown. Otherwise every matching document under InputDir is converted, and Output, if given,
|
||||
// is a directory that receives the results, mirroring the layout under InputDir. With neither,
|
||||
// each Markdown file is written next to its source.
|
||||
type Runner struct {
|
||||
InputDir string
|
||||
Recursive bool
|
||||
Parallel bool
|
||||
InputFile string
|
||||
Output string
|
||||
// Force overwrites Markdown files that already exist; otherwise they are skipped.
|
||||
Force bool
|
||||
Formats []string
|
||||
}
|
||||
|
||||
// Validate checks the input and output options before any work is done.
|
||||
func (r *Runner) Validate() error {
|
||||
if r.InputFile != "" {
|
||||
info, err := os.Stat(r.InputFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("input file: %w", err)
|
||||
}
|
||||
if info.IsDir() {
|
||||
return fmt.Errorf("input %s is a directory; use -dir to scan a directory", r.InputFile)
|
||||
}
|
||||
if formatOf(r.InputFile) == "" {
|
||||
return fmt.Errorf("input %s must be a .pdf, .html, .htm or .docx file", r.InputFile)
|
||||
}
|
||||
}
|
||||
|
||||
if r.Output == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
info, err := os.Stat(r.Output)
|
||||
exists := err == nil
|
||||
if r.InputFile == "" {
|
||||
if exists && !info.IsDir() {
|
||||
return fmt.Errorf("output %s exists and is not a directory", r.Output)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if exists && info.IsDir() {
|
||||
return fmt.Errorf("output %s is a directory; give a file name when using -input", r.Output)
|
||||
}
|
||||
if formatOf(r.Output) != "" {
|
||||
return fmt.Errorf("output %s must be a Markdown file, not a %s file", r.Output, filepath.Ext(r.Output))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// outputFor returns the Markdown file written for input.
|
||||
func (r *Runner) outputFor(input string) string {
|
||||
switch {
|
||||
case r.InputFile != "" && r.Output != "":
|
||||
if isMarkdownName(r.Output) {
|
||||
return r.Output
|
||||
}
|
||||
return r.Output + ".md"
|
||||
case r.InputFile == "" && r.Output != "":
|
||||
rel, err := filepath.Rel(r.InputDir, input)
|
||||
if err != nil {
|
||||
rel = filepath.Base(input)
|
||||
}
|
||||
return filepath.Join(r.Output, OutputPath(rel))
|
||||
default:
|
||||
return OutputPath(input)
|
||||
}
|
||||
}
|
||||
|
||||
// Run converts InputFile, or all matching documents under InputDir.
|
||||
func (r *Runner) Run() error {
|
||||
if err := r.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
files, err := r.inputFiles()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to find documents: %w", err)
|
||||
}
|
||||
if len(files) == 0 {
|
||||
fmt.Println("No documents found")
|
||||
return nil
|
||||
}
|
||||
return r.convertFiles(files)
|
||||
}
|
||||
|
||||
func (r *Runner) inputFiles() ([]string, error) {
|
||||
if r.InputFile != "" {
|
||||
return []string{r.InputFile}, nil
|
||||
}
|
||||
return r.findFiles()
|
||||
}
|
||||
|
||||
func (r *Runner) findFiles() ([]string, error) {
|
||||
byOutput := map[string]string{}
|
||||
var order []string
|
||||
|
||||
walkFn := func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.IsDir() {
|
||||
if !r.Recursive && path != r.InputDir {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
format := formatOf(path)
|
||||
// Skip Word's "~$" owner files, which carry a .docx extension but are not documents.
|
||||
if format == "" || !slices.Contains(r.Formats, format) || strings.HasPrefix(info.Name(), "~$") {
|
||||
return nil
|
||||
}
|
||||
|
||||
out := r.outputFor(path)
|
||||
prev, clash := byOutput[out]
|
||||
switch {
|
||||
case !clash:
|
||||
byOutput[out] = path
|
||||
order = append(order, out)
|
||||
case slices.Index(FormatNames, format) < slices.Index(FormatNames, formatOf(prev)):
|
||||
fmt.Printf("Warning: %s and %s both produce %s, using %s\n", prev, path, out, path)
|
||||
byOutput[out] = path
|
||||
default:
|
||||
fmt.Printf("Warning: %s and %s both produce %s, using %s\n", prev, path, out, prev)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := filepath.Walk(r.InputDir, walkFn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
files := make([]string, 0, len(order))
|
||||
for _, out := range order {
|
||||
files = append(files, byOutput[out])
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (r *Runner) convertFiles(files []string) error {
|
||||
if !r.Parallel {
|
||||
for _, f := range files {
|
||||
if err := r.convertFile(f); err != nil {
|
||||
return fmt.Errorf("failed to convert %s: %w", f, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, len(files))
|
||||
for _, f := range files {
|
||||
wg.Add(1)
|
||||
go func(f string) {
|
||||
defer wg.Done()
|
||||
if err := r.convertFile(f); err != nil {
|
||||
errs <- fmt.Errorf("failed to convert %s: %w", f, err)
|
||||
}
|
||||
}(f)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
|
||||
for err := range errs {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Runner) convertFile(input string) error {
|
||||
output := r.outputFor(input)
|
||||
if _, err := os.Stat(output); err == nil && !r.Force {
|
||||
fmt.Printf("Skipping %s: %s already exists (use -force to overwrite)\n", input, output)
|
||||
return nil
|
||||
}
|
||||
|
||||
md, err := Convert(input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil {
|
||||
return fmt.Errorf("failed to create output directory: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(output, md, 0o644); err != nil {
|
||||
return fmt.Errorf("failed to write %s: %w", output, err)
|
||||
}
|
||||
|
||||
fmt.Printf("Successfully converted %s to %s\n", input, output)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package tomd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/document"
|
||||
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/engine"
|
||||
)
|
||||
|
||||
const sample = "# Title\n\nSome **bold**, *italic* and `code` with a [link](http://example.com).\n\n" +
|
||||
"## Lists\n\n- one\n- two\n - nested\n\n1. first\n2. second\n\n" +
|
||||
"```\nfunc main() {\n run()\n}\n```\n\n| a | b |\n|---|---|\n| 1 | 2 |\n"
|
||||
|
||||
func requireContains(t *testing.T, got string, wants ...string) {
|
||||
t.Helper()
|
||||
for _, want := range wants {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("output missing %q\n--- output ---\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDOCXRoundTrip(t *testing.T) {
|
||||
data, err := document.DOCX([]byte(sample))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
md, err := DOCX(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireContains(t, string(md),
|
||||
"# Title", "## Lists", "**bold**", "*italic*", "`code`", "[link](http://example.com)",
|
||||
"- one\n- two\n - nested", "1. first\n1. second",
|
||||
"```\nfunc main() {\n run()\n}\n```", "| a | b |\n| --- | --- |\n| 1 | 2 |")
|
||||
}
|
||||
|
||||
func TestHTMLRoundTrip(t *testing.T) {
|
||||
md, err := HTML(document.HTML([]byte(sample)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireContains(t, string(md),
|
||||
"# Title", "## Lists", "**bold**", "*italic*", "`code`", "[link](http://example.com)", "- one", "1. first", "```")
|
||||
if strings.Contains(string(md), "font-family") {
|
||||
t.Error("stylesheet leaked into Markdown")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPDFRoundTrip(t *testing.T) {
|
||||
eng, err := engine.New(engine.GoPDF)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := filepath.Join(t.TempDir(), "doc.pdf")
|
||||
if err := eng.Render([]byte(sample), out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := os.ReadFile(out)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
md, err := PDF(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireContains(t, string(md),
|
||||
"# Title", "## Lists", "**bold**", "*italic*", "`code`", "- one", " - nested", "1. first", "2. second",
|
||||
"```\nfunc main() {\n run()\n}\n```")
|
||||
}
|
||||
|
||||
func TestInvalidInputs(t *testing.T) {
|
||||
if _, err := DOCX([]byte("not a zip")); err == nil {
|
||||
t.Error("expected error for invalid docx")
|
||||
}
|
||||
if _, err := PDF([]byte("not a pdf")); err == nil {
|
||||
t.Error("expected error for invalid pdf")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFormats(t *testing.T) {
|
||||
got, err := ParseFormats("HTML, docx,html")
|
||||
if err != nil || len(got) != 2 || got[0] != FormatHTML || got[1] != FormatDOCX {
|
||||
t.Errorf("got %v, %v", got, err)
|
||||
}
|
||||
for _, bad := range []string{"", "md", "pdf,txt"} {
|
||||
if _, err := ParseFormats(bad); err == nil {
|
||||
t.Errorf("ParseFormats(%q) should fail", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerSkipsExistingUnlessForced(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(name, content string) {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write("page.html", "<h1>From HTML</h1>")
|
||||
write("page.md", "original")
|
||||
|
||||
r := &Runner{InputDir: dir, Recursive: true, Formats: FormatNames}
|
||||
if err := r.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := os.ReadFile(filepath.Join(dir, "page.md")); string(got) != "original" {
|
||||
t.Errorf("existing markdown was overwritten: %q", got)
|
||||
}
|
||||
|
||||
r.Force = true
|
||||
if err := r.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := os.ReadFile(filepath.Join(dir, "page.md")); !strings.Contains(string(got), "# From HTML") {
|
||||
t.Errorf("force did not overwrite: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerPrefersFormatOnClash(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
docx, err := document.DOCX([]byte("# From DOCX"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "x.docx"), docx, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "x.html"), []byte("<h1>From HTML</h1>"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := &Runner{InputDir: dir, Recursive: true, Formats: FormatNames}
|
||||
if err := r.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := os.ReadFile(filepath.Join(dir, "x.md"))
|
||||
if !strings.Contains(string(got), "From DOCX") {
|
||||
t.Errorf("expected docx to win the clash, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerFormatFilter(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "a.html"), []byte("<p>hi</p>"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r := &Runner{InputDir: dir, Formats: []string{FormatDOCX}}
|
||||
if err := r.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "a.md")); err == nil {
|
||||
t.Error("html should be ignored when only docx is selected")
|
||||
}
|
||||
}
|
||||
|
||||
func writeDoc(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func TestInputFileWithOutputName(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeDoc(t, filepath.Join(dir, "a.html"), "<h1>A</h1>")
|
||||
writeDoc(t, filepath.Join(dir, "b.html"), "<h1>B</h1>")
|
||||
|
||||
// The format filter does not apply to an explicit input.
|
||||
r := &Runner{InputFile: filepath.Join(dir, "a.html"), Output: filepath.Join(dir, "out", "notes"), Formats: []string{FormatDOCX}}
|
||||
if err := r.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := os.ReadFile(filepath.Join(dir, "out", "notes.md"))
|
||||
if err != nil || !strings.Contains(string(got), "# A") {
|
||||
t.Fatalf("expected out/notes.md with the converted content: %v %q", err, got)
|
||||
}
|
||||
if fileExists(filepath.Join(dir, "a.md")) || fileExists(filepath.Join(dir, "b.md")) {
|
||||
t.Error("only the named output should be written")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutputNameKeepsMarkdownExtension(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeDoc(t, filepath.Join(dir, "a.html"), "<h1>A</h1>")
|
||||
|
||||
r := &Runner{InputFile: filepath.Join(dir, "a.html"), Output: filepath.Join(dir, "x.markdown")}
|
||||
if err := r.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !fileExists(filepath.Join(dir, "x.markdown")) || fileExists(filepath.Join(dir, "x.markdown.md")) {
|
||||
t.Error("a .markdown output name should be used as is")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutputValidation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeDoc(t, filepath.Join(dir, "a.html"), "<p>x</p>")
|
||||
writeDoc(t, filepath.Join(dir, "notes.txt"), "text")
|
||||
in := filepath.Join(dir, "a.html")
|
||||
|
||||
cases := map[string]*Runner{
|
||||
"missing input": {InputFile: filepath.Join(dir, "nope.html")},
|
||||
"input is a dir": {InputFile: dir},
|
||||
"unsupported input": {InputFile: filepath.Join(dir, "notes.txt")},
|
||||
"output is a dir": {InputFile: in, Output: dir},
|
||||
"output not markdown": {InputFile: in, Output: filepath.Join(dir, "x.pdf")},
|
||||
"scan output is file": {InputDir: dir, Output: in},
|
||||
}
|
||||
for name, r := range cases {
|
||||
if err := r.Validate(); err == nil {
|
||||
t.Errorf("%s: expected a validation error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutputDirMirrorsLayout(t *testing.T) {
|
||||
src, out := t.TempDir(), filepath.Join(t.TempDir(), "docs")
|
||||
writeDoc(t, filepath.Join(src, "a.html"), "<h1>A</h1>")
|
||||
writeDoc(t, filepath.Join(src, "sub", "b.html"), "<h1>B</h1>")
|
||||
|
||||
r := &Runner{InputDir: src, Recursive: true, Output: out, Formats: FormatNames}
|
||||
if err := r.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, want := range []string{"a.md", "sub/b.md"} {
|
||||
if !fileExists(filepath.Join(out, want)) {
|
||||
t.Errorf("expected %s in output dir", want)
|
||||
}
|
||||
}
|
||||
if fileExists(filepath.Join(src, "a.md")) {
|
||||
t.Error("nothing should be written next to the sources when -output is a directory")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user