qurl/togo/main.go

89 lines
1.4 KiB
Go

package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"time"
)
func main() {
pkg := flag.String("p", "", "package")
name := flag.String("n", "", "const name")
inputfn := flag.String("i", "", "input file")
outputfn := flag.String("o", "", "output file")
flag.Parse()
if *pkg == "" {
log.Fatal("pkg required")
}
if *name == "" {
log.Fatal("name required")
}
if *inputfn == "" {
log.Fatal("input file required")
}
if *outputfn == "" {
*outputfn = *inputfn + ".go"
}
omod := fmod(*outputfn)
imod := fmod(*inputfn)
if omod.After(imod) {
log.Printf("Refusing to update %s\n", *outputfn)
return
}
ifile, err := os.Open(*inputfn)
if err != nil {
log.Fatal(err)
}
defer ifile.Close()
ofile, err := os.OpenFile(*outputfn, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0660)
if err != nil {
log.Fatal(err)
}
defer ofile.Close()
fmt.Fprintf(ofile, "package %s\n\nvar %s = []byte{", *pkg, *name)
buf := make([]byte, 4096)
for c := 0; ; {
i, err := ifile.Read(buf)
if err != nil {
if err != io.EOF {
log.Fatal(err)
}
break
}
for j := 0; j < i; j++ {
if (c % 13) == 0 {
fmt.Fprintf(ofile, "\n\t")
} else {
fmt.Fprintf(ofile, " ")
}
fmt.Fprintf(ofile, "0x%02x,", buf[j])
c++
}
}
fmt.Fprintf(ofile, "\n}\n")
}
func fmod(fn string) time.Time {
fi, err := os.Stat(fn)
if err != nil {
if os.IsNotExist(err) {
return time.Time{}
}
log.Fatal(err)
}
return fi.ModTime()
}