Last active
November 9, 2017 16:21
-
-
Save jrick/b8ad2a10956a01954028a8107b5ee860 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"go/parser" | |
"go/printer" | |
"go/token" | |
"log" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
var ( | |
inFlag = flag.String("in", "", "input directory") | |
outFlag = flag.String("out", "", "output directory") | |
inDir string | |
outDir string | |
) | |
func main() { | |
flag.Parse() | |
if *inFlag == "" { | |
fmt.Println("must set -in") | |
return | |
} | |
if *outFlag == "" { | |
fmt.Println("must set -out") | |
return | |
} | |
inDir = filepath.Clean(*inFlag) | |
outDir = filepath.Clean(*outFlag) | |
err := filepath.Walk(inDir, walk) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
} | |
func replace(path string) string { | |
if strings.HasPrefix(path, inDir) { | |
path = filepath.Join(outDir, path[len(inDir):]) | |
} | |
return path | |
} | |
func walk(in string, info os.FileInfo, err error) error { | |
if err != nil { | |
panic(err) | |
} | |
out := replace(in) | |
if in == out { | |
log.Fatalf("failed to determine output file for %v", in) | |
} | |
if info.IsDir() { | |
log.Printf("creating directory %v", out) | |
return os.Mkdir(out, 0744) | |
} | |
if !strings.HasSuffix(in, ".go") { | |
log.Printf("ignoring file %v", in) | |
return nil | |
} | |
fset := token.NewFileSet() | |
astFi, err := parser.ParseFile(fset, in, nil, 0) // don't parse comments | |
if err != nil { | |
log.Fatalf("parse source file %v: %v", in, err) | |
} | |
outFi, err := os.Create(out) | |
if err != nil { | |
log.Fatalf("create output file %v: %v", out, err) | |
} | |
err = printer.Fprint(outFi, fset, astFi) | |
if err != nil { | |
log.Fatalf("failed to write output file %v: %v", out, err) | |
} | |
log.Printf("rewrote %v to %v", in, out) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment