github.com/SupersunnySea/draft@v0.16.0/pkg/linguist/generate_static.go (about)

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build ignore
     6  
     7  // Command bake reads a set of files and writes a Go source file to "static.go"
     8  // that declares a map of string constants containing contents of the input files.
     9  package main
    10  
    11  import (
    12  	"bufio"
    13  	"bytes"
    14  	"fmt"
    15  	"io/ioutil"
    16  	"os"
    17  	"unicode/utf8"
    18  )
    19  
    20  func main() {
    21  	if err := bake(); err != nil {
    22  		fmt.Fprintln(os.Stderr, err)
    23  		os.Exit(1)
    24  	}
    25  }
    26  
    27  func bake() error {
    28  	f, err := os.Create("static.go")
    29  	if err != nil {
    30  		return err
    31  	}
    32  	defer f.Close()
    33  	w := bufio.NewWriter(f)
    34  	fmt.Fprintf(w, "%v\n\npackage linguist\n\n", warning)
    35  	fmt.Fprintf(w, "var files = map[string]string{\n")
    36  	for i := 1; i < len(os.Args); i++ {
    37  		fn := os.Args[i]
    38  		b, err := ioutil.ReadFile(fn)
    39  		if err != nil {
    40  			return err
    41  		}
    42  		fmt.Fprintf(w, "\t%q: ", fn)
    43  		if utf8.Valid(b) {
    44  			fmt.Fprintf(w, "`%s`", sanitize(b))
    45  		} else {
    46  			fmt.Fprintf(w, "%q", b)
    47  		}
    48  		fmt.Fprintf(w, ",\n\n")
    49  	}
    50  	fmt.Fprintln(w, "}")
    51  	if err := w.Flush(); err != nil {
    52  		return err
    53  	}
    54  	return f.Close()
    55  }
    56  
    57  // sanitize prepares a valid UTF-8 string as a raw string constant.
    58  func sanitize(b []byte) []byte {
    59  	// Replace ` with `+"`"+`
    60  	b = bytes.Replace(b, []byte("`"), []byte("`+\"`\"+`"), -1)
    61  
    62  	// Replace BOM with `+"\xEF\xBB\xBF"+`
    63  	// (A BOM is valid UTF-8 but not permitted in Go source files.
    64  	// I wouldn't bother handling this, but for some insane reason
    65  	// jquery.js has a BOM somewhere in the middle.)
    66  	return bytes.Replace(b, []byte("\xEF\xBB\xBF"), []byte("`+\"\\xEF\\xBB\\xBF\"+`"), -1)
    67  }
    68  
    69  const warning = "// DO NOT EDIT ** This file was generated with the bake tool ** DO NOT EDIT //"