bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/bosun/web/embed.go (about) 1 package web 2 3 import ( 4 "bufio" 5 "bytes" 6 "log" 7 "os" 8 "os/exec" 9 "path/filepath" 10 "sort" 11 12 "github.com/mjibson/esc/embed" 13 ) 14 15 // Functions to run tsc to compile typescript and esc to embed static assests. 16 // Assume that working path is set to `cmd/bosun` 17 18 // Run esc to embed entire static directory into static.go 19 func RunEsc() { 20 cfg := &embed.Config{ 21 ModTime: "0", 22 OutputFile: "web/static.go", 23 Package: "web", 24 Prefix: "web/static", 25 Ignore: `.*\.ts`, 26 Files: []string{"web/static"}, 27 } 28 embed.Run(cfg) 29 } 30 31 // Run tsc to compile all ts files into bosun.js 32 func RunTsc() { 33 base := filepath.Join("web", "static", "js") 34 tmp := filepath.Join(base, "bosun-new.js") 35 dst := filepath.Join(base, "bosun.js") 36 args := []string{ 37 "--out", tmp, 38 } 39 matches, _ := filepath.Glob(filepath.Join(base, "*.ts")) 40 sort.Strings(matches) 41 args = append(args, matches...) 42 run("tsc", args...) 43 if _, err := os.Stat(dst); os.IsNotExist(err) { 44 overwriteFile(tmp, dst) 45 } else { 46 if deepCompareDifferent(tmp, dst) { 47 overwriteFile(tmp, dst) 48 } else { 49 err := os.Remove(tmp) 50 if err != nil { 51 log.Println(err) 52 return 53 } 54 } 55 } 56 } 57 58 func run(name string, arg ...string) { 59 log.Println("running", name, arg) 60 c := exec.Command(name, arg...) 61 c.Stderr = os.Stderr 62 c.Stdout = os.Stdout 63 if err := c.Run(); err != nil { 64 log.Printf("run error: %v: %v", name, err) 65 } 66 } 67 68 func deepCompareDifferent(file1, file2 string) bool { 69 sf, err := os.Open(file1) 70 if err != nil { 71 log.Fatal(err) 72 } 73 df, err := os.Open(file2) 74 if err != nil { 75 log.Fatal(err) 76 } 77 defer sf.Close() 78 defer df.Close() 79 sscan := bufio.NewScanner(sf) 80 dscan := bufio.NewScanner(df) 81 for sscan.Scan() { 82 dscan.Scan() 83 if !bytes.Equal(sscan.Bytes(), dscan.Bytes()) { 84 return true 85 } 86 } 87 return false 88 } 89 90 func overwriteFile(filesrc, filedst string) { 91 err := os.Rename(filesrc, filedst) 92 if err != nil { 93 log.Println(err) 94 return 95 } 96 }