commit c61b08ec1c7da57161413d05b3978bbcc4f5847d Author: Fatih Arslan Date: Sat Oct 3 01:11:30 2015 +0300 hclfmt: initial skeleton diff --git a/hclfmt.go b/hclfmt.go new file mode 100644 index 0000000..5b3a2e2 --- /dev/null +++ b/hclfmt.go @@ -0,0 +1,101 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "go/scanner" + "io" + "os" + "path/filepath" + "runtime/pprof" + "strings" +) + +func main() { + if err := realMain(); err != nil { + fmt.Fprintln(os.Stderr, err.Error()) + os.Exit(1) + } +} + +func realMain() error { + var ( + write = flag.Bool("w", false, "write result to (source) file instead of stdout") + + // debugging + cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file") + ) + + flag.Usage = usage + flag.Parse() + + if *cpuprofile != "" { + f, err := os.Create(*cpuprofile) + if err != nil { + return fmt.Errorf("creating cpu profile: %s\n", err) + } + defer f.Close() + pprof.StartCPUProfile(f) + defer pprof.StopCPUProfile() + } + + if flag.NArg() == 0 { + if *write { + return errors.New("error: cannot use -w with standard input") + } + + return processFile("", os.Stdin, os.Stdout, true) + } + + for i := 0; i < flag.NArg(); i++ { + path := flag.Arg(i) + switch dir, err := os.Stat(path); { + case err != nil: + report(err) + case dir.IsDir(): + walkDir(path) + default: + if err := processFile(path, nil, os.Stdout, false); err != nil { + report(err) + } + } + } + + return nil +} + +func usage() { + fmt.Fprintf(os.Stderr, "usage: hclfmt [flags] [path ...]\n") + flag.PrintDefaults() + os.Exit(2) +} + +func isGoFile(f os.FileInfo) bool { + // ignore non-Go files + name := f.Name() + return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") +} + +func report(err error) { + scanner.PrintError(os.Stderr, err) +} + +func walkDir(path string) { + filepath.Walk(path, visitFile) +} + +func visitFile(path string, f os.FileInfo, err error) error { + if err == nil && isGoFile(f) { + err = processFile(path, nil, os.Stdout, false) + } + if err != nil { + report(err) + } + return nil +} + +// If in == nil, the source is the contents of the file with the given filename. +func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error { + return errors.New("not imlemented yet") +}