Reviewers:
golang-dev_googlegroups.com,
Message:
Hello
golan...@googlegroups.com (cc:
golan...@googlegroups.com),
I'd like you to review this change.
Description:
Add option to gofmt to help build tools that need package name and
imports.
Please review this at
http://codereview.appspot.com/2220045/
Affected files:
M src/cmd/gofmt/gofmt.go
Index: src/cmd/gofmt/gofmt.go
===================================================================
--- a/src/cmd/gofmt/gofmt.go
+++ b/src/cmd/gofmt/gofmt.go
@@ -12,6 +12,7 @@
"go/parser"
"go/printer"
"go/scanner"
+ "go/token"
"io/ioutil"
"os"
pathutil "path"
@@ -26,6 +27,7 @@
rewriteRule = flag.String("r", "", "rewrite rule (e.g., 'α[β:len(α)] ->
α[β:]')")
// debugging support
+ build = flag.Bool("build", false, "print code useful for build tools")
comments = flag.Bool("comments", true, "print comments")
trace = flag.Bool("trace", false, "print parse trace")
printAST = flag.Bool("ast", false, "print AST (before rewrites)")
@@ -66,6 +68,9 @@
if *trace {
parserMode |= parser.Trace
}
+ if *build && !*write {
+ parserMode |= parser.ImportsOnly
+ }
}
@@ -86,6 +91,22 @@
}
+func extractImports(file *ast.File) <-chan *ast.ImportSpec {
+ ch := make(chan *ast.ImportSpec)
+ go func() {
+ defer close(ch)
+ for _, decl := range file.Decls {
+ if gd, ok := decl.(*ast.GenDecl); ok && gd.Tok == token.IMPORT {
+ for _, spec := range gd.Specs {
+ ch <- spec.(*ast.ImportSpec)
+ }
+ }
+ }
+ }()
+ return ch
+}
+
+
func processFile(f *os.File) os.Error {
src, err := ioutil.ReadAll(f)
if err != nil {
@@ -98,6 +119,14 @@
return err
}
+ if *build && !*write {
+ fmt.Printf("package %s\n",
file.Name.Name)
+ for spec := range extractImports(file) {
+ fmt.Printf("import %s\n", string(spec.Path.Value))
+ }
+ return err
+ }
+
if *printAST {
ast.Print(file)
}