b2e/main.go
2016-08-02 15:31:30 +02:00

84 lines
1.7 KiB
Go

package main
import (
"bufio"
"flag"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
var (
srcPath = flag.String("s", "./", "source path")
destPath = flag.String("d", "./bash.go", "output file")
out = "package bash\n\n" + "import (\n\t" + `"os"` + "\n\t" + `"os/exec"` + "\n" + ")" + "\n\n"
)
func main() {
flag.Parse()
if e := filepath.Walk(*srcPath, walkfn); e != nil {
log.Fatalln(e.Error())
}
if e := ioutil.WriteFile(*destPath, []byte(out), 0664); e != nil {
log.Fatalln(e.Error())
}
}
func walkfn(path string, info os.FileInfo, err error) error {
if strings.Contains(info.Name(), ".") {
return nil
}
fp, e := os.Open(path)
if e != nil {
return e
}
defer fp.Close()
out += `func ` + strings.Title(info.Name()) + `Command() error {` + "\n"
scanner := bufio.NewScanner(fp)
first := true
for scanner.Scan() {
if strings.HasPrefix(scanner.Text(), "#") {
continue
}
if scanner.Text() == "" {
continue
}
if first {
out += "\t" + "cmd := exec.Command("
} else {
out += "\t" + "cmd = exec.Command("
}
splt := strings.Split(scanner.Text(), " ")
for c, t := range splt {
if c != len(splt)-1 {
out += `"` + t + `", `
} else {
out += `"` + t + `"`
}
}
out += ")\n"
out += "\t" + `cmd.Stdout = os.Stdout` + "\n"
out += "\t" + `cmd.Stderr = os.Stderr` + "\n"
out += "\t" + `if e := cmd.Start(); e != nil {` + "\n"
out += "\t" + "\t" + "return e" + "\n"
out += "\t" + "}" + "\n"
out += "\t" + `if e := cmd.Wait(); e != nil {` + "\n"
out += "\t" + "\t" + "return e" + "\n"
out += "\t" + "}" + "\n\n"
first = false
}
if e := scanner.Err(); e != nil {
return e
}
out += "\t" + "return nil" + "\n"
out += "}\n\n"
return nil
}