2024-02-17 06:35:49 +00:00
|
|
|
// Package document enables simple HTML modification via callback via
|
|
|
|
// "goquery", an API similar to "jquery". This plugin is particularly useful
|
|
|
|
// adding classes to elements and performing other cleanup tasks which are too
|
|
|
|
// case-specific to warrant the creation of a new plugin.
|
|
|
|
package document
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"git.foosoft.net/alex/goldsmith"
|
|
|
|
"git.foosoft.net/alex/goldsmith/filters/wildcard"
|
|
|
|
"github.com/PuerkitoBio/goquery"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Processor callback function to modify documents.
|
2024-03-04 02:09:21 +00:00
|
|
|
type Processor func(*goldsmith.File, *goquery.Document) error
|
2024-02-17 06:35:49 +00:00
|
|
|
|
|
|
|
// Document plugin context.
|
|
|
|
type Document struct {
|
|
|
|
callback Processor
|
2024-03-04 02:09:21 +00:00
|
|
|
files []*goldsmith.File
|
2024-02-17 06:35:49 +00:00
|
|
|
mutex sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
// New creates a new instance of the Document plugin.
|
|
|
|
func New(callback Processor) *Document {
|
|
|
|
return &Document{callback: callback}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (*Document) Name() string {
|
|
|
|
return "document"
|
|
|
|
}
|
|
|
|
|
2024-03-04 01:46:38 +00:00
|
|
|
func (*Document) Initialize(context *goldsmith.Context) error {
|
2024-02-17 06:35:49 +00:00
|
|
|
context.Filter(wildcard.New("**/*.html", "**/*.htm"))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-03-04 02:09:21 +00:00
|
|
|
func (self *Document) Process(context *goldsmith.Context, inputFile *goldsmith.File) error {
|
2024-02-17 06:35:49 +00:00
|
|
|
doc, err := goquery.NewDocumentFromReader(inputFile)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := self.callback(inputFile, doc); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
html, err := doc.Html()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
outputFile, err := context.CreateFileFromReader(inputFile.Path(), bytes.NewReader([]byte(html)))
|
|
|
|
outputFile.CopyProps(inputFile)
|
|
|
|
|
|
|
|
self.mutex.Lock()
|
|
|
|
defer self.mutex.Unlock()
|
|
|
|
self.files = append(self.files, outputFile)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-03-04 01:46:38 +00:00
|
|
|
func (self *Document) Finalize(context *goldsmith.Context) error {
|
2024-02-17 06:35:49 +00:00
|
|
|
for _, file := range self.files {
|
|
|
|
context.DispatchFile(file)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|