github.com/brandur/modulir@v0.0.0-20240305213423-94ee82929cbd/scripts/embed_js/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "strings" 8 9 "github.com/brandur/modulir" 10 "github.com/brandur/modulir/modules/mfile" 11 ) 12 13 ////////////////////////////////////////////////////////////////////////////// 14 // 15 // 16 // 17 // Main 18 // 19 // 20 // 21 ////////////////////////////////////////////////////////////////////////////// 22 23 func main() { 24 goStr := goHeader 25 26 sources, err := mfile.ReadDir(newContext(), jsSource) 27 if err != nil { 28 exitWithError(err) 29 } 30 31 for _, source := range sources { 32 file := filepath.Base(source) 33 name := strings.TrimSuffix(file, filepath.Ext(file)) 34 35 data, err := os.ReadFile(source) 36 if err != nil { 37 exitWithError(err) 38 } 39 40 str := string(data) 41 str = strings.ReplaceAll(str, `"`, `\"`) 42 str = strings.ReplaceAll(str, "\n", "\\n\" +\n\t\"") 43 44 goStr += fmt.Sprintf(goTemplate, file, name, str) 45 } 46 47 // Add one trailing newline to make the final format more agreeable to 48 // Gofmt 49 goStr += "\n" 50 51 if err := os.WriteFile(goTarget, []byte(goStr), 0o600); err != nil { 52 exitWithError(err) 53 } 54 } 55 56 ////////////////////////////////////////////////////////////////////////////// 57 // 58 // 59 // 60 // Private 61 // 62 // 63 // 64 ////////////////////////////////////////////////////////////////////////////// 65 66 // The header frontmatter that will go in our generate .go file. 67 const goHeader = `// 68 // 69 // Code generated by: scripts/embed_js/main.go 70 // DO NOT EDIT. Run go generate instead. 71 // 72 // 73 74 package modulir` 75 76 // Target Go file to generate containing JS sources. 77 const goTarget = "./js.go" 78 79 // Go code for each file. Note that we have leading newlines instead of 80 // trailing so that Gofmt doesn't have to change anything. 81 const goTemplate = ` 82 83 // Source: %s 84 const %sJS = "%s"` 85 86 // Directory containing JavaScript sources. 87 const jsSource = "./js" 88 89 // Exits with status 1 after printing the given error to stderr. 90 func exitWithError(err error) { 91 fmt.Fprintf(os.Stderr, "error: %v\n", err) 92 os.Exit(1) 93 } 94 95 // Helper to easily create a new Modulir context. 96 func newContext() *modulir.Context { 97 return modulir.NewContext(&modulir.Args{Log: &modulir.Logger{Level: modulir.LevelInfo}}) 98 }