github.com/vugu/vugu@v0.3.6-0.20240430171613-3f6f402e014b/domrender/renderer-js-script-maker.go (about)

     1  //go:build ignore
     2  // +build ignore
     3  
     4  package main
     5  
     6  import (
     7  	"bufio"
     8  	"bytes"
     9  	"errors"
    10  	"flag"
    11  	"fmt"
    12  	"io"
    13  	"os"
    14  	"strings"
    15  
    16  	"github.com/tdewolff/minify/v2"
    17  	"github.com/tdewolff/minify/v2/js"
    18  )
    19  
    20  func main() {
    21  
    22  	debug := flag.Bool("debug", false, "Keep debug lines in output")
    23  	flag.Parse()
    24  
    25  	// *debug = true
    26  
    27  	f, err := os.Open("renderer-js-script.js")
    28  	if err != nil {
    29  		panic(err)
    30  	}
    31  	defer f.Close()
    32  
    33  	opcodeMap := make(map[string]bool, 42)
    34  
    35  	var buf bytes.Buffer
    36  
    37  	br := bufio.NewReader(f)
    38  	for {
    39  		bline, err := br.ReadBytes('\n')
    40  		if errors.Is(err, io.EOF) {
    41  			if len(bline) == 0 {
    42  				break
    43  			}
    44  			continue
    45  		} else if err != nil {
    46  			panic(err)
    47  		}
    48  
    49  		// keep a map of the opcodes
    50  		if bytes.HasPrefix(bytes.TrimSpace(bline), []byte("const opcode")) {
    51  			fields := strings.Fields(string(bline))
    52  			opcodeMap[fields[1]] = true
    53  		}
    54  
    55  		// only include debug lines if in debug mode
    56  		if bytes.HasPrefix(bytes.TrimSpace(bline), []byte("/*DEBUG*/")) {
    57  			if *debug {
    58  				buf.Write(bline)
    59  			}
    60  			continue
    61  		}
    62  
    63  		// map of opcodes as text
    64  		if bytes.Compare(bytes.TrimSpace(bline), []byte("/*DEBUG OPCODE STRINGS*/")) == 0 {
    65  			if *debug {
    66  				fmt.Fprintf(&buf, "let textOpcodes = [];\n")
    67  				for k := range opcodeMap {
    68  					fmt.Fprintf(&buf, "textOpcodes[%s] = %q; ", k, k)
    69  				}
    70  				fmt.Fprintf(&buf, "\n")
    71  			}
    72  			continue
    73  		}
    74  
    75  		// anything else just goes as-is
    76  		buf.Write(bline)
    77  
    78  	}
    79  
    80  	b := buf.Bytes()
    81  
    82  	// minify the JS
    83  	m := minify.New()
    84  	m.AddFunc("text/javascript", js.Minify)
    85  	mr := m.Reader("text/javascript", bytes.NewReader(b))
    86  	b, err = io.ReadAll(mr)
    87  	if err != nil {
    88  		panic(err)
    89  	}
    90  
    91  	buf.Reset()
    92  
    93  	fmt.Fprintf(&buf, "package domrender\n\n// GENERATED FILE, DO NOT EDIT!  See renderer-js-script-maker.go\n\nconst jsHelperScript = %q\n", b)
    94  
    95  	err = os.WriteFile("renderer-js-script.go", buf.Bytes(), 0644)
    96  	if err != nil {
    97  		panic(err)
    98  	}
    99  
   100  }