Skip to content
Snippets Groups Projects
cut.go 3.36 KiB
package html

import (
	"github.com/andybalholm/cascadia"
	"gitlab.schukai.com/oss/bob/types"
	"gitlab.schukai.com/oss/libraries/go/markup/html/engine"
	"golang.org/x/net/html"
	"gopkg.in/yaml.v3"
	"os"
	"path/filepath"
	"strings"
)

func CutHtml(p string) error {

	content, err := os.ReadFile(p)
	if err != nil {
		return err
	}

	currentDir, _ := os.Getwd()
	os.Chdir(filepath.Dir(p))
	defer os.Chdir(currentDir)

	specification := types.SnippetsSpecification{}

	if err := yaml.Unmarshal(content, &specification); err != nil {
		return err
	}

	sourceFiles := make(map[string]*html.Node)

	for _, r := range specification.Snippets {

		source := r.Source

		absSource, err := filepath.Abs(source)
		if err != nil {
			return err
		}

		if sourceFiles[absSource], err = readHTML(absSource); err != nil {
			return err
		}
	}

	for _, r := range specification.Snippets {

		source := r.Source
		destination := r.Destination

		absSource, err := filepath.Abs(source)
		if err != nil {
			return err
		}

		sourceNode, ok := sourceFiles[absSource]
		if !ok {
			continue
		}

		replacedNodes, err := replaceNodes(sourceNode, r.Replacement)
		if err != nil {
			return err
		}

		err = setAttributes(replacedNodes, r.Attributes)
		if err != nil {
			return err
		}