feat(engine): add Chromedp and Wkhtmltopdf engines for PDF conversion

* implement gopdfEngine for direct PDF rendering
* create HTML rendering function for markdown
* add tests for engine functionality
* remove main.go as entry point
This commit is contained in:
Hein committed 2026-10-08 16:42:47 +02:00
1 parent 73f258aa95
commit 50b7246c21
23 files changed
+1948 -393

No files matched your search

+186
View File
@@ -0,0 +1,186 @@
// Package converter finds Markdown files and converts them to PDF, HTML or DOCX.
package converter
import (
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/document"
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/engine"
)
// Output formats accepted by ParseFormats.
const (
FormatPDF = "pdf"
FormatHTML = "html"
FormatDOCX = "docx"
)
// FormatNames lists every supported output format.
var FormatNames = []string{FormatPDF, FormatHTML, FormatDOCX}
// ParseFormats turns a comma separated list such as "pdf,html" into validated, de-duplicated formats.
func ParseFormats(list string) ([]string, error) {
var formats []string
seen := map[string]bool{}
for _, f := range strings.Split(list, ",") {
f = strings.ToLower(strings.TrimSpace(f))
if f == "" || seen[f] {
continue
}
if !slices.Contains(FormatNames, f) {
return nil, fmt.Errorf("unknown format %q (available: %s)", f, strings.Join(FormatNames, ", "))
}
seen[f] = true
formats = append(formats, f)
}
if len(formats) == 0 {
return nil, fmt.Errorf("no output format given (available: %s)", strings.Join(FormatNames, ", "))
}
return formats, nil
}
// 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.
type Converter struct {
InputDir string
Recursive bool
Parallel bool
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
}
// Run converts every Markdown file under InputDir.
func (c *Converter) Run() error {
files, err := c.findMarkdownFiles()
if err != nil {
return fmt.Errorf("failed to find markdown files: %w", err)
}
if len(files) == 0 {
fmt.Println("No markdown files found")
return nil
}
return c.ConvertFiles(files)
}
// ConvertFiles converts the given Markdown files, in parallel when enabled.
func (c *Converter) ConvertFiles(files []string) error {
if c.Parallel {
return c.convertFilesParallel(files)
}
return c.convertFilesSerial(files)
}
func isMarkdown(path string) bool {
return strings.HasSuffix(path, ".md") || strings.HasSuffix(path, ".markdown")
}
func (c *Converter) findMarkdownFiles() ([]string, error) {
var files []string
walkFn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() && !c.Recursive && path != c.InputDir {
return filepath.SkipDir
}
if !info.IsDir() && isMarkdown(path) {
files = append(files, path)
}
return nil
}
if err := filepath.Walk(c.InputDir, walkFn); err != nil {
return nil, err
}
return files, nil
}
func (c *Converter) convertFilesParallel(files []string) error {
var wg sync.WaitGroup
errs := make(chan error, len(files))
for _, file := range files {
wg.Add(1)
go func(f string) {
defer wg.Done()
if err := c.convertFile(f); err != nil {
errs <- fmt.Errorf("failed to convert %s: %w", f, err)
}
}(file)
}
wg.Wait()
close(errs)
for err := range errs {
return err
}
return nil
}
func (c *Converter) convertFilesSerial(files []string) error {
for _, file := range files {
if err := c.convertFile(file); err != nil {
return fmt.Errorf("failed to convert %s: %w", file, err)
}
}
return nil
}
func (c *Converter) convertFile(inputFile string) error {
mdContent, err := os.ReadFile(inputFile)
if err != nil {
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)
if err := c.write(mdContent, format, outputFile); err != nil {
return fmt.Errorf("%s: %w", format, err)
}
fmt.Printf("Successfully converted %s to %s\n", inputFile, outputFile)
}
return nil
}
func (c *Converter) write(md []byte, format, outputFile string) error {
switch format {
case FormatPDF:
if c.Engine == nil {
return fmt.Errorf("no PDF engine configured")
}
return c.Engine.Render(md, outputFile)
case FormatHTML:
return os.WriteFile(outputFile, document.HTML(md), 0o644)
case FormatDOCX:
data, err := document.DOCX(md)
if err != nil {
return err
}
return os.WriteFile(outputFile, data, 0o644)
default:
return fmt.Errorf("unknown format %q", format)
}
}
+103
View File
@@ -0,0 +1,103 @@
package converter
import (
"bytes"
"os"
"path/filepath"
"slices"
"testing"
"github.com/Warky-Devs/go-mdtopdf-helper.git/internal/engine"
)
func TestRunConvertsMarkdownFiles(t *testing.T) {
tmpDir := t.TempDir()
content := "# Test Document\nThis is a basic test."
if err := os.WriteFile(filepath.Join(tmpDir, "test.md"), []byte(content), 0o644); err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
eng, err := engine.New(engine.Default)
if err != nil {
t.Fatal(err)
}
defer func() { _ = eng.Close() }()
conv := &Converter{InputDir: tmpDir, Engine: eng}
if err := conv.Run(); err != nil {
t.Fatalf("Conversion failed: %v", err)
}
pdf, err := os.ReadFile(filepath.Join(tmpDir, "test.pdf"))
if err != nil {
t.Fatalf("PDF file was not created: %v", err)
}
if !bytes.HasPrefix(pdf, []byte("%PDF")) {
t.Error("output is not a PDF")
}
}
func TestRunNonRecursiveSkipsSubdirs(t *testing.T) {
tmpDir := t.TempDir()
sub := filepath.Join(tmpDir, "sub")
if err := os.Mkdir(sub, 0o755); err != nil {
t.Fatal(err)
}
for _, p := range []string{filepath.Join(tmpDir, "a.md"), filepath.Join(sub, "b.md")} {
if err := os.WriteFile(p, []byte("# hi"), 0o644); err != nil {
t.Fatal(err)
}
}
eng, _ := engine.New(engine.Default)
conv := &Converter{InputDir: tmpDir, Engine: eng}
if err := conv.Run(); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(tmpDir, "a.pdf")); err != nil {
t.Errorf("expected a.pdf: %v", err)
}
if _, err := os.Stat(filepath.Join(sub, "b.pdf")); err == nil {
t.Error("b.pdf should not exist when not recursive")
}
}
func TestParseFormats(t *testing.T) {
got, err := ParseFormats("PDF, html,pdf,docx")
if err != nil {
t.Fatal(err)
}
if want := []string{FormatPDF, FormatHTML, FormatDOCX}; !slices.Equal(got, want) {
t.Errorf("got %v, want %v", got, want)
}
for _, bad := range []string{"", ",", "odt", "pdf,rtf"} {
if _, err := ParseFormats(bad); err == nil {
t.Errorf("ParseFormats(%q) should fail", bad)
}
}
}
func TestRunWritesAllFormats(t *testing.T) {
tmpDir := t.TempDir()
if err := os.WriteFile(filepath.Join(tmpDir, "doc.md"), []byte("# Hi\n\ntext"), 0o644); err != nil {
t.Fatal(err)
}
// No engine needed when PDF is not requested.
conv := &Converter{InputDir: tmpDir, Formats: []string{FormatHTML, FormatDOCX}}
if err := conv.Run(); err != nil {
t.Fatal(err)
}
for _, ext := range []string{"html", "docx"} {
if _, err := os.Stat(filepath.Join(tmpDir, "doc."+ext)); err != nil {
t.Errorf("expected doc.%s: %v", ext, err)
}
}
if _, err := os.Stat(filepath.Join(tmpDir, "doc.pdf")); err == nil {
t.Error("doc.pdf should not be written")
}
}
+81
View File
@@ -0,0 +1,81 @@
package converter
import (
"bufio"
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// RunAsHook converts the staged Markdown files and stages the generated output.
func (c *Converter) RunAsHook() error {
if !confirmConversion() {
fmt.Println("Skipping conversion")
return nil
}
files, err := stagedMarkdownFiles()
if err != nil {
return fmt.Errorf("failed to get staged files: %w", err)
}
if len(files) == 0 {
return nil
}
if err := c.ConvertFiles(files); err != nil {
return err
}
return c.stageGeneratedFiles(files)
}
func confirmConversion() bool {
fmt.Print("Convert Markdown files? [Y/n] ")
reader := bufio.NewReader(os.Stdin)
response, err := reader.ReadString('\n')
if err != nil {
return false
}
response = strings.ToLower(strings.TrimSpace(response))
return response == "" || response == "y" || response == "yes"
}
func stagedMarkdownFiles() ([]string, error) {
cmd := exec.Command("git", "diff", "--cached", "--name-only", "--diff-filter=d")
output, err := cmd.Output()
if err != nil {
return nil, err
}
var files []string
scanner := bufio.NewScanner(bytes.NewReader(output))
for scanner.Scan() {
if file := scanner.Text(); isMarkdown(file) {
files = append(files, file)
}
}
return files, scanner.Err()
}
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))
if err := exec.Command("git", "add", out).Run(); err != nil {
fmt.Printf("Warning: Could not stage %s\n", out)
}
}
}
return nil
}