commit f389fab3d75b317111683a1b733b8deb81b92003 Author: Darko Luketic Date: Tue Aug 2 15:31:30 2016 +0200 initial diff --git a/README.md b/README.md new file mode 100644 index 0000000..615aeec --- /dev/null +++ b/README.md @@ -0,0 +1,20 @@ +# b2e + +simple tool to translate bash scripts to embedded go commands + +## usage + +b2e -s="source path" -d="destination file" + +default values are + +s = ".\" +d = ".\bash.go" + +## licence + +MIT + +## Author + +Darko Luketic \ No newline at end of file diff --git a/main.go b/main.go new file mode 100644 index 0000000..85f1cd7 --- /dev/null +++ b/main.go @@ -0,0 +1,83 @@ +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 +}