diff --git a/.goreleaser.yml b/.goreleaser.yml index aec8224..51b9138 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -18,6 +18,23 @@ builds: binary: go-mdtopdf-helper ldflags: - -s -w -X main.version={{.Version}} -X main.commit={{.ShortCommit}} -X main.date={{.Date}} + - id: go-tomd + env: + - CGO_ENABLED=0 + goos: + - linux + - windows + - darwin + goarch: + - amd64 + - arm64 + ignore: + - goos: windows + goarch: arm64 + main: ./cmd/go-tomd + binary: go-tomd + ldflags: + - -s -w -X main.version={{.Version}} -X main.commit={{.ShortCommit}} -X main.date={{.Date}} archives: - id: default diff --git a/Makefile b/Makefile index b3744e2..42e836b 100644 --- a/Makefile +++ b/Makefile @@ -1,17 +1,23 @@ BINARY := go-mdtopdf-helper +TOMD_BINARY := go-tomd BIN_DIR := bin CMD := ./cmd/go-mdtopdf-helper +TOMD_CMD := ./cmd/go-tomd -.PHONY: all build run test lint format clean +.PHONY: all build run run-tomd test lint format clean all: format lint test build build: go build -o $(BIN_DIR)/$(BINARY) $(CMD) + go build -o $(BIN_DIR)/$(TOMD_BINARY) $(TOMD_CMD) run: go run $(CMD) $(ARGS) +run-tomd: + go run $(TOMD_CMD) $(ARGS) + test: go test ./... diff --git a/README.md b/README.md index e6053f6..5b71e68 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,79 @@ # go-mdtopdf-helper -A command-line tool that automatically converts Markdown files to PDF. Perfect for maintaining PDF documentation alongside your Markdown files in Git repositories. +Two command-line tools for keeping documentation in sync with your Markdown: + +- **`go-mdtopdf-helper`** converts Markdown files to PDF, HTML or DOCX. +- **`go-tomd`** does the reverse, converting PDF, HTML and DOCX documents back to Markdown. + +Perfect for maintaining PDF documentation alongside your Markdown files in Git repositories. ## Features -- Converts Markdown files to PDF, HTML or DOCX (one or several at once) -- Choice of PDF rendering engines -- Works out of the box: the default engine is pure Go with no external dependencies +- Markdown to PDF, HTML or DOCX, one or several formats at once +- Documents back to Markdown (`go-tomd`) +- Works out of the box: the default PDF engine, the DOCX writer and the DOCX reader are pure Go with no external dependencies +- Choice of PDF engines (pure Go, headless Chrome, or wkhtmltopdf) +- Convert a single file or scan a directory; choose where the output goes - Can run as a Git pre-commit hook -- Recursive directory scanning -- Parallel file processing +- Recursive directory scanning and parallel processing - Cross-platform support (Windows, Linux, macOS) -## Output Formats +## Installation -Select formats with `-format`, for example `-format pdf,html,docx`. Each file is written next to its Markdown source with the matching extension (`README.md` → `README.pdf`, `README.html`, `README.docx`). +Download the archive for your platform from the project's GitHub releases. Each archive contains both `go-mdtopdf-helper` and `go-tomd`. -- **pdf**: rendered by the selected engine (see below). +Or build from source (requires Go and, optionally, `golangci-lint` for `make lint`): + +```bash +git clone https://github.com/Warky-Devs/go-mdtopdf-helper.git +cd go-mdtopdf-helper +make build # writes bin/go-mdtopdf-helper and bin/go-tomd +``` + +## go-mdtopdf-helper: Markdown to PDF, HTML and DOCX + +Convert every Markdown file under the current directory to PDF: + +```bash +go-mdtopdf-helper +``` + +### Options + +``` +go-mdtopdf-helper [options] + +Options: + -dir string + Directory to scan for markdown files (default ".") + -input string + Convert only this markdown file (instead of scanning -dir) + -output string + With -input: output file name, extension added per format + Without -input: directory to write results to + -recursive + Scan directories recursively (default true) + -parallel + Convert files in parallel (default true) + -format string + Output formats, comma separated: pdf, html, docx (default "pdf") + -engine string + PDF engine: gopdf, wkhtmltopdf, chromedp (default "gopdf") + -hook + Run as git pre-commit hook +``` + +### Output formats + +Select formats with `-format`, for example `-format pdf,html,docx`. By default each file is written next to its Markdown source with the matching extension (`README.md` becomes `README.pdf`, `README.html` and `README.docx`). + +- **pdf**: rendered by the selected engine (see below). A4 with 15mm margins. - **html**: a standalone page with embedded CSS. - **docx**: a Word document generated in pure Go (no Word or other tools needed). Supports headings, paragraphs, bold/italic/code, links, bulleted and numbered lists, code blocks, quotes, rules and tables. Images are written as `[image: alt]` text. -In pre-commit hook mode every generated file is staged. +### PDF engines -## Engines - -The engine only applies to PDF output. - -Select an engine with `-engine`: +The engine only applies to PDF output. Select one with `-engine`: | Engine | Needs | Notes | |--------|-------|-------| @@ -34,45 +81,9 @@ Select an engine with `-engine`: | `chromedp` | Chrome or Chromium | Best rendering (full HTML/CSS). Runs headless Chrome; the sandbox is disabled automatically when running as root, as in most CI containers. | | `wkhtmltopdf` | [wkhtmltopdf](https://wkhtmltopdf.org/) | Legacy engine. Looked up in the standard install locations (Windows: `C:\Program Files\wkhtmltopdf\bin`, Linux/macOS: `/usr/local/bin`, `/usr/bin`, Homebrew). | -## Installation +### Git pre-commit hook -```bash -go get github.com/Warky-Devs/go-mdtopdf-helper -``` - -## Usage - -### Basic Usage - -Convert Markdown files in the current directory: - -```bash -go-mdtopdf-helper -``` - -### Command Line Options - -```bash -go-mdtopdf-helper [options] - -Options: - -dir string - Directory to scan for markdown files (default ".") - -recursive - Scan directories recursively (default true) - -parallel - Convert files in parallel (default true) - -hook - Run as git pre-commit hook - -engine string - PDF engine: gopdf, wkhtmltopdf, chromedp (default "gopdf") - -format string - Output formats, comma separated: pdf, html, docx (default "pdf") -``` - -### Git Pre-commit Hook - -To use as a Git pre-commit hook: +To run it as a Git pre-commit hook: 1. Create a file named `pre-commit` in your repository's `.git/hooks/` directory 2. Add the following content: @@ -91,20 +102,83 @@ chmod +x .git/hooks/pre-commit When enabled as a pre-commit hook, the tool will: 1. Detect staged Markdown files 2. Ask for confirmation before conversion -3. Convert files to PDF -4. Automatically stage the generated PDFs +3. Convert the files to the formats given by `-format` (PDF by default) +4. Automatically stage every generated file -## PDF Output Configuration +To keep HTML or DOCX copies up to date as well, add the formats to the hook, for example `go-mdtopdf-helper -hook -format pdf,html`. The hook cannot be combined with `-input` or `-output`. -Generated PDFs are A4 with 15mm margins on all sides. The `chromedp` and `wkhtmltopdf` engines render the full Markdown-to-HTML output, so they support everything the Markdown parser's common extensions produce. +## go-tomd: documents to Markdown -## Project Layout +`go-tomd` scans a directory for `.pdf`, `.html`/`.htm` and `.docx` files and writes `.md` next to each one. + +```bash +go-tomd +``` + +### Options ``` -cmd/go-mdtopdf-helper/ CLI entry point (flags, hook mode) +go-tomd [options] + +Options: + -dir string + Directory to scan for documents (default ".") + -input string + Convert only this document (instead of scanning -dir); -format is ignored + -output string + With -input: Markdown file name to write (.md added if missing) + Without -input: directory to write results to + -recursive + Scan directories recursively (default true) + -parallel + Convert files in parallel (default true) + -format string + Input formats to convert, comma separated: docx, html, pdf (default "docx,html,pdf") + -force + Overwrite Markdown files that already exist +``` + +An existing `.md` is never overwritten unless you pass `-force`, so converting `doc.html` will not clobber a `doc.md` you wrote by hand. If several documents map to the same Markdown file (for example `doc.docx` and `doc.pdf`), one is chosen in the order docx, html, pdf and a warning is printed. + +### How each format is read + +| Input | How | Fidelity | +|-------|-----|----------| +| `docx` | Parsed directly (no Word needed). Headings, bold/italic/code, links, nested bulleted and numbered lists, code blocks, quotes, rules and tables. | High | +| `html` | [html-to-markdown](https://github.com/JohannesKaufmann/html-to-markdown), including tables and strikethrough. | High | +| `pdf` | Best effort, pure Go. PDFs have no real 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, and text in multi-column layouts may interleave. | Good on PDFs made by this tool, rougher on arbitrary ones | + +## Input and output names + +Both commands take `-input` and `-output`: + +```bash +# Convert one file, choosing the output name (the extension is added per format) +go-mdtopdf-helper -input docs/guide.md -output build/manual -format pdf,html +# -> build/manual.pdf, build/manual.html + +# Scan a directory but write results elsewhere, mirroring the folder layout +go-mdtopdf-helper -dir docs -output build + +# And the reverse +go-tomd -input report.docx -output notes/report # -> notes/report.md +go-tomd -dir exports -output imported +``` + +- `-input` replaces the directory scan, so it cannot be combined with `-dir` or `-recursive` (or `-hook`). `go-mdtopdf-helper` expects a `.md`/`.markdown` file, and `go-tomd` a `.pdf`, `.html`/`.htm` or `.docx` file. +- With `-input`, `-output` is a file name. For `go-mdtopdf-helper` it is a base name that gets each format's extension; a name that already ends in the extension of the single requested format (`-output out.pdf -format pdf`) is used as is, and a mismatched extension is an error. For `go-tomd`, `.md` is added unless the name already ends in `.md` or `.markdown`. +- Without `-input`, `-output` is a directory, created if needed. +- Parent directories of the output are created automatically. + +## Project layout + +``` +cmd/go-mdtopdf-helper/ Markdown to PDF/HTML/DOCX CLI (flags, hook mode) +cmd/go-tomd/ PDF/HTML/DOCX to Markdown CLI internal/converter/ File discovery, parallel conversion, git hook internal/document/ HTML and DOCX writers internal/engine/ Engine interface and the gopdf, wkhtmltopdf and chromedp backends +internal/tomd/ PDF, HTML and DOCX readers (to Markdown) ``` ## Contributing @@ -117,7 +191,7 @@ Contributions are welcome! Please feel free to submit a Pull Request. Here's how 4. Push to the branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request -### Development Setup +### Development setup 1. Clone the repository 2. Install dependencies: @@ -125,12 +199,12 @@ Contributions are welcome! Please feel free to submit a Pull Request. Here's how go mod download ``` 3. Make your changes -4. Run tests: +4. Run the checks: ```bash - make test + make all ``` -`make` also provides `build`, `lint` (golangci-lint), `format` (gofmt) and `all`. Tests for the `chromedp` and `wkhtmltopdf` engines are skipped when the tool is not installed. +Make targets: `build` (both binaries into `bin/`), `run` and `run-tomd` (pass arguments with `ARGS="..."`), `test`, `lint` (golangci-lint), `format` (gofmt), `clean`, and `all` (format, lint, test, build). Tests for the `chromedp` and `wkhtmltopdf` engines are skipped when the tool is not installed. ## Dependencies @@ -138,6 +212,8 @@ Contributions are welcome! Please feel free to submit a Pull Request. Here's how - [chromedp](https://github.com/chromedp/chromedp) - Headless Chrome driver - [go-wkhtmltopdf](https://github.com/SebastiaanKlippert/go-wkhtmltopdf) - Go wrapper for wkhtmltopdf - [gomarkdown](https://github.com/gomarkdown/markdown) - Markdown parser and HTML renderer +- [pdf](https://github.com/ledongthuc/pdf) - Pure Go PDF text extraction (go-tomd) +- [html-to-markdown](https://github.com/JohannesKaufmann/html-to-markdown) - HTML to Markdown (go-tomd) ## License @@ -146,4 +222,4 @@ This project is licensed under the MIT License - see the LICENSE file for detail ## Acknowledgments - Thanks to [SebastiaanKlippert](https://github.com/SebastiaanKlippert) for the go-wkhtmltopdf library -- Thanks to the gomarkdown team for their Markdown parser \ No newline at end of file +- Thanks to the gomarkdown team for their Markdown parser diff --git a/README.pdf b/README.pdf index d0b99aa..5efc4d4 100644 Binary files a/README.pdf and b/README.pdf differ diff --git a/cmd/go-mdtopdf-helper/main.go b/cmd/go-mdtopdf-helper/main.go index 3a62181..141d2b6 100644 --- a/cmd/go-mdtopdf-helper/main.go +++ b/cmd/go-mdtopdf-helper/main.go @@ -21,6 +21,11 @@ func run() int { var engineName, formatList string flag.StringVar(&conv.InputDir, "dir", ".", "Directory to scan for markdown files") + flag.StringVar(&conv.InputFile, "input", "", + "Convert only this markdown file (instead of scanning -dir)") + flag.StringVar(&conv.Output, "output", "", + "With -input: output file name, extension added per format (-output report -> report.pdf). "+ + "Without -input: directory to write results to instead of next to the sources") flag.BoolVar(&conv.Recursive, "recursive", true, "Scan directories recursively") flag.BoolVar(&conv.Parallel, "parallel", true, "Convert files in parallel") flag.BoolVar(&hookMode, "hook", false, "Run as git pre-commit hook") @@ -30,12 +35,25 @@ func run() int { "Output formats, comma separated: "+strings.Join(converter.FormatNames, ", ")) flag.Parse() + set := map[string]bool{} + flag.Visit(func(f *flag.Flag) { set[f.Name] = true }) + if conv.InputFile != "" && (set["dir"] || set["recursive"]) { + fmt.Fprintln(os.Stderr, "Error: -input cannot be combined with -dir or -recursive") + return 2 + } + formats, err := converter.ParseFormats(formatList) if err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) return 2 } conv.Formats = formats + if !hookMode { + if err := conv.Validate(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return 2 + } + } // The engine only matters for PDF output. if slices.Contains(formats, converter.FormatPDF) { diff --git a/cmd/go-tomd/main.go b/cmd/go-tomd/main.go new file mode 100644 index 0000000..3ad3bf6 --- /dev/null +++ b/cmd/go-tomd/main.go @@ -0,0 +1,57 @@ +// Command go-tomd converts PDF, HTML and DOCX documents to Markdown. +package main + +import ( + "flag" + "fmt" + "os" + "strings" + + "github.com/Warky-Devs/go-mdtopdf-helper.git/internal/tomd" +) + +func main() { + os.Exit(run()) +} + +func run() int { + r := &tomd.Runner{} + var formatList string + + flag.StringVar(&r.InputDir, "dir", ".", "Directory to scan for documents") + flag.StringVar(&r.InputFile, "input", "", + "Convert only this document (instead of scanning -dir); -format is ignored") + flag.StringVar(&r.Output, "output", "", + "With -input: Markdown file name to write (.md added if missing). "+ + "Without -input: directory to write results to instead of next to the sources") + flag.BoolVar(&r.Recursive, "recursive", true, "Scan directories recursively") + flag.BoolVar(&r.Parallel, "parallel", true, "Convert files in parallel") + flag.BoolVar(&r.Force, "force", false, "Overwrite Markdown files that already exist") + flag.StringVar(&formatList, "format", strings.Join(tomd.FormatNames, ","), + "Input formats to convert, comma separated: "+strings.Join(tomd.FormatNames, ", ")) + flag.Parse() + + set := map[string]bool{} + flag.Visit(func(f *flag.Flag) { set[f.Name] = true }) + if r.InputFile != "" && (set["dir"] || set["recursive"]) { + fmt.Fprintln(os.Stderr, "Error: -input cannot be combined with -dir or -recursive") + return 2 + } + + formats, err := tomd.ParseFormats(formatList) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return 2 + } + r.Formats = formats + if err := r.Validate(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return 2 + } + + if err := r.Run(); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return 1 + } + return 0 +} diff --git a/go.mod b/go.mod index f25b5ba..4d6b2d6 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,11 @@ require ( ) require ( + github.com/JohannesKaufmann/dom v0.3.1 // indirect + github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2 // indirect github.com/go-json-experiment/json v0.0.0-20260213210345-44df1a37e875 // indirect + github.com/ledongthuc/pdf v0.0.0-20260907135840-6c8c28e0e8a0 // indirect github.com/phpdave11/gofpdi v1.0.14-0.20211212211723-1f10f9844311 // indirect github.com/pkg/errors v0.8.1 // indirect + golang.org/x/net v0.55.0 // indirect ) diff --git a/go.sum b/go.sum index 3ab5952..7c8f9ed 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,7 @@ +github.com/JohannesKaufmann/dom v0.3.1 h1:J16l9JAHWgkFPR3VIPbQ1gvS0cWab6laK1q7PFL3qh0= +github.com/JohannesKaufmann/dom v0.3.1/go.mod h1:BZPkf8ZeYrBgABjwJn9iiKt8aiCtkxpHkevms+Yp2DE= +github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2 h1:XFJZFWESIWlUEHHjzBuv8RvrtCWnSGlimEX17ysSDb8= +github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2/go.mod h1:BHWO8lJzttJLqwuV8Rb1B3OG2OSzLbssZDI1FRg2eAA= github.com/SebastiaanKlippert/go-wkhtmltopdf v1.9.3 h1:vrA6+R1BMLKMTbos8jAeuBrImHPGtY4gTlcue3OIej8= github.com/SebastiaanKlippert/go-wkhtmltopdf v1.9.3/go.mod h1:SQq4xfIdvf6WYKSDxAJc+xOJdolt+/bc1jnQKMtPMvQ= github.com/chromedp/cdproto v0.157.8 h1:Tkq0AjsUlC3Z4sJfHBzV/uAAxnTF/AZyuSTjfV/1gvk= @@ -10,6 +14,8 @@ github.com/go-json-experiment/json v0.0.0-20260213210345-44df1a37e875 h1:XGPtjxq github.com/go-json-experiment/json v0.0.0-20260213210345-44df1a37e875/go.mod h1:uNVvRXArCGbZ508SxYYTC5v1JWoz2voff5pm25jU1Ok= github.com/gomarkdown/markdown v0.0.0-20241205020045-f7e15b2f3e62 h1:pbAFUZisjG4s6sxvRJvf2N7vhpCvx2Oxb3PmS6pDO1g= github.com/gomarkdown/markdown v0.0.0-20241205020045-f7e15b2f3e62/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA= +github.com/ledongthuc/pdf v0.0.0-20260907135840-6c8c28e0e8a0 h1:7Q+xNAZFmnfYOMweHN3c/PDFUKKfY1pVJ26K++QvVfU= +github.com/ledongthuc/pdf v0.0.0-20260907135840-6c8c28e0e8a0/go.mod h1:1fEHWurg7pvf5SG6XNE5Q8UZmOwex51Mkx3SLhrW5B4= github.com/phpdave11/gofpdi v1.0.14-0.20211212211723-1f10f9844311 h1:zyWXQ6vu27ETMpYsEMAsisQ+GqJ4e1TPvSNfdOPF0no= github.com/phpdave11/gofpdi v1.0.14-0.20211212211723-1f10f9844311/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= @@ -22,5 +28,7 @@ github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMT github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ= golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/converter/converter.go b/internal/converter/converter.go index 2861cc1..16a6996 100644 --- a/internal/converter/converter.go +++ b/internal/converter/converter.go @@ -46,22 +46,97 @@ func ParseFormats(list string) ([]string, error) { // Converter converts Markdown files found under InputDir into each of Formats. // Engine renders the PDF format and may be nil when PDF is not requested. +// +// When InputFile is set only that file is converted and Output, if given, is the output name: +// a base name that gets the format's extension (or a full name when it already has the extension +// of the single requested format). Otherwise Output, if given, is a directory that receives the +// results, mirroring the layout under InputDir. With neither, output goes next to each source. type Converter struct { InputDir string Recursive bool Parallel bool + InputFile string + Output string Formats []string Engine engine.Engine } -// outputPath returns the file written for inputFile in the given format. -func outputPath(inputFile, format string) string { - return strings.TrimSuffix(inputFile, filepath.Ext(inputFile)) + "." + format +func (c *Converter) formats() []string { + if len(c.Formats) == 0 { + return []string{FormatPDF} + } + return c.Formats } -// Run converts every Markdown file under InputDir. +// Validate checks the input and output options before any work is done. +func (c *Converter) Validate() error { + if c.InputFile != "" { + info, err := os.Stat(c.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", c.InputFile) + } + if !isMarkdown(c.InputFile) { + return fmt.Errorf("input %s must be a .md or .markdown file", c.InputFile) + } + } + + if c.Output == "" { + return nil + } + + if c.InputFile == "" { + if info, err := os.Stat(c.Output); err == nil && !info.IsDir() { + return fmt.Errorf("output %s exists and is not a directory", c.Output) + } + return nil + } + + if info, err := os.Stat(c.Output); err == nil && info.IsDir() { + return fmt.Errorf("output %s is a directory; give a file name when using -input", c.Output) + } + if ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(c.Output)), "."); slices.Contains(FormatNames, ext) { + if formats := c.formats(); len(formats) != 1 || formats[0] != ext { + return fmt.Errorf("output %s has a .%s extension but the requested formats are %s", + c.Output, ext, strings.Join(formats, ",")) + } + } + return nil +} + +// outputFor returns the file written for input in the given format. +func (c *Converter) outputFor(input, format string) string { + switch { + case c.InputFile != "" && c.Output != "": + ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(c.Output)), ".") + if ext == format { + return c.Output + } + return c.Output + "." + format + case c.InputFile == "" && c.Output != "": + rel, err := filepath.Rel(c.InputDir, input) + if err != nil { + rel = filepath.Base(input) + } + return filepath.Join(c.Output, replaceExt(rel, format)) + default: + return replaceExt(input, format) + } +} + +func replaceExt(path, ext string) string { + return strings.TrimSuffix(path, filepath.Ext(path)) + "." + ext +} + +// Run converts InputFile, or every Markdown file under InputDir. func (c *Converter) Run() error { - files, err := c.findMarkdownFiles() + if err := c.Validate(); err != nil { + return err + } + + files, err := c.inputFiles() if err != nil { return fmt.Errorf("failed to find markdown files: %w", err) } @@ -86,6 +161,13 @@ func isMarkdown(path string) bool { return strings.HasSuffix(path, ".md") || strings.HasSuffix(path, ".markdown") } +func (c *Converter) inputFiles() ([]string, error) { + if c.InputFile != "" { + return []string{c.InputFile}, nil + } + return c.findMarkdownFiles() +} + func (c *Converter) findMarkdownFiles() ([]string, error) { var files []string @@ -150,13 +232,11 @@ func (c *Converter) convertFile(inputFile string) error { return fmt.Errorf("failed to read file: %w", err) } - formats := c.Formats - if len(formats) == 0 { - formats = []string{FormatPDF} - } - - for _, format := range formats { - outputFile := outputPath(inputFile, format) + for _, format := range c.formats() { + outputFile := c.outputFor(inputFile, format) + if err := os.MkdirAll(filepath.Dir(outputFile), 0o755); err != nil { + return fmt.Errorf("failed to create output directory: %w", err) + } if err := c.write(mdContent, format, outputFile); err != nil { return fmt.Errorf("%s: %w", format, err) } diff --git a/internal/converter/converter_test.go b/internal/converter/converter_test.go index de95452..08a349f 100644 --- a/internal/converter/converter_test.go +++ b/internal/converter/converter_test.go @@ -101,3 +101,103 @@ func TestRunWritesAllFormats(t *testing.T) { t.Error("doc.pdf should not be written") } } + +func writeFile(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 exists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +func TestInputFileWithOutputName(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.md"), "# A") + writeFile(t, filepath.Join(dir, "b.md"), "# B") + + conv := &Converter{ + InputFile: filepath.Join(dir, "a.md"), + Output: filepath.Join(dir, "out", "report"), + Formats: []string{FormatHTML, FormatDOCX}, + } + if err := conv.Run(); err != nil { + t.Fatal(err) + } + + for _, want := range []string{"out/report.html", "out/report.docx"} { + if !exists(filepath.Join(dir, want)) { + t.Errorf("expected %s", want) + } + } + if exists(filepath.Join(dir, "b.html")) || exists(filepath.Join(dir, "a.html")) { + t.Error("only the output name should be written, and only the input file converted") + } +} + +func TestInputFileOutputWithMatchingExtension(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.md"), "# A") + + conv := &Converter{InputFile: filepath.Join(dir, "a.md"), Output: filepath.Join(dir, "x.html"), Formats: []string{FormatHTML}} + if err := conv.Run(); err != nil { + t.Fatal(err) + } + if !exists(filepath.Join(dir, "x.html")) || exists(filepath.Join(dir, "x.html.html")) { + t.Error("an output name that already has the format's extension should be used as is") + } +} + +func TestOutputValidation(t *testing.T) { + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "a.md"), "# A") + writeFile(t, filepath.Join(dir, "notes.txt"), "text") + md := filepath.Join(dir, "a.md") + + cases := map[string]*Converter{ + "missing input": {InputFile: filepath.Join(dir, "nope.md")}, + "input is a dir": {InputFile: dir}, + "input not markdown": {InputFile: filepath.Join(dir, "notes.txt")}, + "output is a dir": {InputFile: md, Output: dir}, + "extension mismatch": {InputFile: md, Output: filepath.Join(dir, "x.docx"), Formats: []string{FormatHTML}}, + "ext with many fmts": {InputFile: md, Output: filepath.Join(dir, "x.html"), Formats: []string{FormatHTML, FormatDOCX}}, + "scan output is file": {InputDir: dir, Output: md}, + } + for name, c := range cases { + if err := c.Validate(); err == nil { + t.Errorf("%s: expected a validation error", name) + } + } +} + +func TestOutputDirMirrorsLayout(t *testing.T) { + src, out := t.TempDir(), filepath.Join(t.TempDir(), "dist") + writeFile(t, filepath.Join(src, "a.md"), "# A") + writeFile(t, filepath.Join(src, "sub", "b.md"), "# B") + + conv := &Converter{InputDir: src, Recursive: true, Output: out, Formats: []string{FormatHTML}} + if err := conv.Run(); err != nil { + t.Fatal(err) + } + + for _, want := range []string{"a.html", "sub/b.html"} { + if !exists(filepath.Join(out, want)) { + t.Errorf("expected %s in output dir", want) + } + } + if exists(filepath.Join(src, "a.html")) { + t.Error("nothing should be written next to the sources when -output is a directory") + } +} + +func TestHookRejectsInputAndOutput(t *testing.T) { + if err := (&Converter{InputFile: "a.md"}).RunAsHook(); err == nil { + t.Error("expected error combining hook with -input") + } +} diff --git a/internal/converter/hook.go b/internal/converter/hook.go index af3f529..13f31e0 100644 --- a/internal/converter/hook.go +++ b/internal/converter/hook.go @@ -12,6 +12,10 @@ import ( // RunAsHook converts the staged Markdown files and stages the generated output. func (c *Converter) RunAsHook() error { + if c.InputFile != "" || c.Output != "" { + return fmt.Errorf("-input and -output cannot be combined with -hook") + } + if !confirmConversion() { fmt.Println("Skipping conversion") return nil @@ -64,14 +68,9 @@ func stagedMarkdownFiles() ([]string, error) { } func (c *Converter) stageGeneratedFiles(files []string) error { - formats := c.Formats - if len(formats) == 0 { - formats = []string{FormatPDF} - } - for _, file := range files { - for _, format := range formats { - out := filepath.FromSlash(outputPath(file, format)) + for _, format := range c.formats() { + out := filepath.FromSlash(c.outputFor(file, format)) if err := exec.Command("git", "add", out).Run(); err != nil { fmt.Printf("Warning: Could not stage %s\n", out) } diff --git a/internal/tomd/docx.go b/internal/tomd/docx.go new file mode 100644 index 0000000..c26f364 --- /dev/null +++ b/internal/tomd/docx.go @@ -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 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, "
") + 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() +} diff --git a/internal/tomd/html.go b/internal/tomd/html.go new file mode 100644 index 0000000..c6432c7 --- /dev/null +++ b/internal/tomd/html.go @@ -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 +} diff --git a/internal/tomd/inline.go b/internal/tomd/inline.go new file mode 100644 index 0000000..a047473 --- /dev/null +++ b/internal/tomd/inline.go @@ -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), " ") +} diff --git a/internal/tomd/pdf.go b/internal/tomd/pdf.go new file mode 100644 index 0000000..a28c5ac --- /dev/null +++ b/internal/tomd/pdf.go @@ -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 +} diff --git a/internal/tomd/runner.go b/internal/tomd/runner.go new file mode 100644 index 0000000..73de0d4 --- /dev/null +++ b/internal/tomd/runner.go @@ -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 +} diff --git a/internal/tomd/tomd_test.go b/internal/tomd/tomd_test.go new file mode 100644 index 0000000..dc11c33 --- /dev/null +++ b/internal/tomd/tomd_test.go @@ -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", "

From HTML

") + 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("

From HTML

"), 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("

hi

"), 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"), "

A

") + writeDoc(t, filepath.Join(dir, "b.html"), "

B

") + + // 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"), "

A

") + + 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"), "

x

") + 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"), "

A

") + writeDoc(t, filepath.Join(src, "sub", "b.html"), "

B

") + + 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") + } +}