go-translator/cmd/go-tr/main.go

62 строки
1,5 КиБ
Go

package main
import (
"flag"
"fmt"
"my/go-translator/transpile"
"os"
)
func main() {
source, target := getFlags()
checkFlagsAreValid(source, target)
safeTranspile(source, target)
}
func checkFlagsAreValid(source, target string) {
if source == "" || target == "" {
printUsage()
os.Exit(1)
}
}
func getFlags() (string, string) {
// source := flag.String("source", "", "Golang source file")
// target := flag.String("target", "", "Arduino sketch file")
flag.Parse()
source := flag.Arg(0)
target := flag.Arg(1)
return source, target
}
func printUsage() {
fmt.Print("This program transpiles Golang source into corresponding C code.\n\n")
fmt.Print("Options:\n")
flag.PrintDefaults()
fmt.Print("\n")
fmt.Print("Example:\n")
fmt.Printf("\tgo-tr controller.go controller.ino\n\n")
}
func safeTranspile(source, target string) {
// Read the Golang source file.
in, err := os.Open(source)
if err != nil {
fmt.Fprintf(os.Stderr, "Go source file [%s] could not be opened! %v", source, err)
os.Exit(1)
}
defer in.Close()
// Create the Arduino sketch file.
os.Remove(target)
out, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR|os.O_SYNC, 0666)
if err != nil {
fmt.Fprintf(os.Stderr, "Arduino sketch file [%s] could not be opened! %v", target, err)
os.Exit(1)
}
// Transpiles the Golang source into Arduino sketch.
service := transpile.NewService(in, out)
if err := service.Start(); err != nil {
fmt.Fprintf(os.Stderr, "%v", err)
os.Exit(1)
}
}