Commit 4213c223 authored by Robert Griesemer's avatar Robert Griesemer

Updated and simplified gofmt.

- operates on stdin, a single file, or all files in a file tree
- setting -w flag writes to (source) file instead of stdout
- setting -l flag lists files whose formatting has changed

R=rsc
DELTA=201  (102 added, 71 deleted, 28 changed)
OCL=35890
CL=35926
parent fcc4be8c
...@@ -5,40 +5,45 @@ ...@@ -5,40 +5,45 @@
package main package main
import ( import (
"bytes";
"flag"; "flag";
"fmt"; "fmt";
"go/ast";
"go/parser"; "go/parser";
"go/printer"; "go/printer";
"go/scanner"; "go/scanner";
"io";
"os"; "os";
pathutil "path"; pathutil "path";
"strings"; "strings";
) )
const pkgDir = "src/pkg" // relative to $GOROOT
var ( var (
goroot = flag.String("goroot", os.Getenv("GOROOT"), "Go root directory"); // main operation modes
list = flag.Bool("l", false, "list files whose formatting differs from gofmt's");
write = flag.Bool("w", false, "write result to (source) file instead of stdout");
// operation modes // debugging support
allgo = flag.Bool("a", false, "include all .go files for package"); comments = flag.Bool("comments", true, "print comments");
comments = flag.Bool("c", false, "omit comments"); trace = flag.Bool("trace", false, "print names of processed files to stderr and parse traces to stdout");
silent = flag.Bool("s", false, "silent mode: parsing only");
verbose = flag.Bool("v", false, "verbose mode: trace parsing");
exports = flag.Bool("x", false, "show exports only");
// layout control // layout control
align = flag.Bool("align", true, "align columns");
tabwidth = flag.Int("tabwidth", 8, "tab width"); tabwidth = flag.Int("tabwidth", 8, "tab width");
rawformat = flag.Bool("rawformat", false, "do not use a tabwriter"); usespaces = flag.Bool("spaces", false, "align with spaces instead of tabs");
usespaces = flag.Bool("spaces", false, "align with blanks instead of tabs");
) )
var exitCode = 0
func report(err os.Error) {
scanner.PrintError(os.Stderr, err);
exitCode = 2;
}
func usage() { func usage() {
fmt.Fprintf(os.Stderr, "usage: gofmt [flags] [file.go | pkgpath]\n"); fmt.Fprintf(os.Stderr, "usage: gofmt [flags] [path ...]\n");
flag.PrintDefaults(); flag.PrintDefaults();
os.Exit(2); os.Exit(2);
} }
...@@ -46,67 +51,106 @@ func usage() { ...@@ -46,67 +51,106 @@ func usage() {
func parserMode() uint { func parserMode() uint {
mode := uint(0); mode := uint(0);
if !*comments { if *comments {
mode |= parser.ParseComments; mode |= parser.ParseComments;
} }
if *verbose { if *trace {
mode |= parser.Trace; mode |= parser.Trace;
} }
return mode; return mode;
} }
func isPkgFile(d *os.Dir) bool { func printerMode() uint {
// ignore non-Go files mode := uint(0);
if !d.IsRegular() || strings.HasPrefix(d.Name, ".") || !strings.HasSuffix(d.Name, ".go") { if !*align {
return false; mode |= printer.RawFormat;
}
if *usespaces {
mode |= printer.UseSpaces;
} }
return mode;
}
// ignore test files unless explicitly included
return *allgo || !strings.HasSuffix(d.Name, "_test.go"); func isGoFile(d *os.Dir) bool {
// ignore non-Go files
return d.IsRegular() && !strings.HasPrefix(d.Name, ".") && strings.HasSuffix(d.Name, ".go");
} }
func getPackage(path string) (*ast.Package, os.Error) { func processFile(filename string) os.Error {
if len(path) == 0 { if *trace {
return nil, os.NewError("no path specified"); fmt.Fprintln(os.Stderr, filename);
} }
if strings.HasSuffix(path, ".go") || path == "/dev/stdin" { src, err := io.ReadFile(filename);
// single go file
src, err := parser.ParseFile(path, nil, parserMode());
if err != nil { if err != nil {
return nil, err; return err;
} }
dirname, filename := pathutil.Split(path);
return &ast.Package{src.Name.Value, dirname, map[string]*ast.File{filename: src}}, nil; file, err := parser.ParseFile(filename, src, parserMode());
if err != nil {
return err;
} }
// len(path) > 0 var res bytes.Buffer;
switch ch := path[0]; { _, err = printer.Fprint(&res, file, printerMode(), *tabwidth);
case ch == '.': if err != nil {
// cwd-relative path return err;
if cwd, err := os.Getwd(); err == nil { }
path = pathutil.Join(cwd, path);
if bytes.Compare(src, res.Bytes()) != 0 {
// formatting has changed
if *list {
fmt.Fprintln(os.Stdout, filename);
}
if *write {
err = io.WriteFile(filename, res.Bytes(), 0);
if err != nil {
return err;
}
}
} }
case ch != '/':
// goroot/pkgDir-relative path if !*list && !*write {
path = pathutil.Join(pathutil.Join(*goroot, pkgDir), path); _, err = os.Stdout.Write(res.Bytes());
} }
return parser.ParsePackage(path, isPkgFile, parserMode()); return err;
} }
func printerMode() uint { type fileVisitor chan os.Error
mode := uint(0);
if *rawformat { func (v fileVisitor) VisitDir(path string, d *os.Dir) bool {
mode |= printer.RawFormat; return true;
}
func (v fileVisitor) VisitFile(path string, d *os.Dir) {
if isGoFile(d) {
v <- nil; // synchronize error handler
if err := processFile(path); err != nil {
v <- err;
} }
if *usespaces {
mode |= printer.UseSpaces;
} }
return mode; }
func walkDir(path string) {
// start an error handler
v := make(fileVisitor);
go func() {
for err := range v {
if err != nil {
report(err);
}
}
}();
// walk the tree
pathutil.Walk(path, v, v);
close(v);
} }
...@@ -114,38 +158,25 @@ func main() { ...@@ -114,38 +158,25 @@ func main() {
flag.Usage = usage; flag.Usage = usage;
flag.Parse(); flag.Parse();
path := ""; if flag.NArg() == 0 {
switch flag.NArg() { if err := processFile("/dev/stdin"); err != nil {
case 0: report(err);
path = "/dev/stdin";
case 1:
path = flag.Arg(0);
default:
usage();
} }
pkg, err := getPackage(path);
if err != nil {
scanner.PrintError(os.Stderr, err);
os.Exit(1);
} }
if !*silent { for i := 0; i < flag.NArg(); i++ {
if *exports { path := flag.Arg(i);
ast.PackageExports(pkg); switch dir, err := os.Stat(path); {
_, err := printer.Fprint(os.Stdout, ast.MergePackageFiles(pkg), printerMode(), *tabwidth); case err != nil:
if err != nil { report(err);
fmt.Fprint(os.Stderr, err); case dir.IsRegular():
os.Exit(2); if err := processFile(path); err != nil {
} report(err);
} else {
for _, src := range pkg.Files {
_, err := printer.Fprint(os.Stdout, src, printerMode(), *tabwidth);
if err != nil {
fmt.Fprint(os.Stderr, err);
os.Exit(2);
}
} }
case dir.IsDirectory():
walkDir(path);
} }
} }
os.Exit(exitCode);
} }
...@@ -70,7 +70,7 @@ cleanup() { ...@@ -70,7 +70,7 @@ cleanup() {
silent() { silent() {
cleanup cleanup
$CMD -s $1 > $TMP1 $CMD $1 > /dev/null 2> $TMP1
if [ $? != 0 ]; then if [ $? != 0 ]; then
cat $TMP1 cat $TMP1
echo "Error (silent mode test): test.sh $1" echo "Error (silent mode test): test.sh $1"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment