github.com/robotn/xgb@v0.0.0-20190912153532-2cb92d044934/xgbgen/main.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"io/ioutil"
     6  	"log"
     7  	"os"
     8  	"os/exec"
     9  	"strings"
    10  )
    11  
    12  var (
    13  	protoPath = flag.String("proto-path",
    14  		"/usr/share/xcb", "path to directory of X protocol XML files")
    15  	gofmt = flag.Bool("gofmt", true,
    16  		"When disabled, gofmt will not be run before outputting Go code")
    17  )
    18  
    19  func usage() {
    20  	basename := os.Args[0]
    21  	if lastSlash := strings.LastIndex(basename, "/"); lastSlash > -1 {
    22  		basename = basename[lastSlash+1:]
    23  	}
    24  	log.Printf("Usage: %s [flags] xml-file", basename)
    25  	flag.PrintDefaults()
    26  	os.Exit(1)
    27  }
    28  
    29  func init() {
    30  	log.SetFlags(0)
    31  }
    32  
    33  func main() {
    34  	flag.Usage = usage
    35  	flag.Parse()
    36  
    37  	if flag.NArg() != 1 {
    38  		log.Printf("A single XML protocol file can be processed at once.")
    39  		flag.Usage()
    40  	}
    41  
    42  	// Read the single XML file into []byte
    43  	xmlBytes, err := ioutil.ReadFile(flag.Arg(0))
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  
    48  	// Initialize the buffer, parse it, and filter it through gofmt.
    49  	c := newContext()
    50  	c.Morph(xmlBytes)
    51  
    52  	if !*gofmt {
    53  		c.out.WriteTo(os.Stdout)
    54  	} else {
    55  		cmdGofmt := exec.Command("gofmt")
    56  		cmdGofmt.Stdin = c.out
    57  		cmdGofmt.Stdout = os.Stdout
    58  		cmdGofmt.Stderr = os.Stderr
    59  		err = cmdGofmt.Run()
    60  		if err != nil {
    61  			log.Fatal(err)
    62  		}
    63  	}
    64  }