summaryrefslogtreecommitdiff
path: root/src/go/format/format.go
diff options
context:
space:
mode:
Diffstat (limited to 'src/go/format/format.go')
-rw-r--r--src/go/format/format.go36
1 files changed, 29 insertions, 7 deletions
diff --git a/src/go/format/format.go b/src/go/format/format.go
index 08a9047b9..668a42df2 100644
--- a/src/go/format/format.go
+++ b/src/go/format/format.go
@@ -87,7 +87,13 @@ func Source(src []byte) ([]byte, error) {
return nil, err
}
- return format(fset, file, sourceAdj, indentAdj, src)
+ if sourceAdj == nil {
+ // Complete source file.
+ // TODO(gri) consider doing this always.
+ ast.SortImports(fset, file)
+ }
+
+ return format(fset, file, sourceAdj, indentAdj, src, config)
}
func hasUnsortedImports(file *ast.File) bool {
@@ -108,8 +114,16 @@ func hasUnsortedImports(file *ast.File) bool {
return false
}
-// parse parses src, which was read from filename,
-// as a Go source file or statement list.
+// ----------------------------------------------------------------------------
+// Support functions
+//
+// The functions parse, format, and isSpace below are identical to the
+// respective functions in cmd/gofmt/gofmt.go - keep them in sync!
+//
+// TODO(gri) Factor out this functionality, eventually.
+
+// parse parses src, which was read from the named file,
+// as a Go source file, declaration, or statement list.
func parse(fset *token.FileSet, filename string, src []byte, fragmentOk bool) (
file *ast.File,
sourceAdj func(src []byte, indent int) []byte,
@@ -176,12 +190,21 @@ func parse(fset *token.FileSet, filename string, src []byte, fragmentOk bool) (
return
}
-func format(fset *token.FileSet, file *ast.File, sourceAdj func(src []byte, indent int) []byte, indentAdj int, src []byte) ([]byte, error) {
+// format formats the given package file originally obtained from src
+// and adjusts the result based on the original source via sourceAdj
+// and indentAdj.
+func format(
+ fset *token.FileSet,
+ file *ast.File,
+ sourceAdj func(src []byte, indent int) []byte,
+ indentAdj int,
+ src []byte,
+ cfg printer.Config,
+) ([]byte, error) {
if sourceAdj == nil {
// Complete source file.
- ast.SortImports(fset, file)
var buf bytes.Buffer
- err := config.Fprint(&buf, fset, file)
+ err := cfg.Fprint(&buf, fset, file)
if err != nil {
return nil, err
}
@@ -222,7 +245,6 @@ func format(fset *token.FileSet, file *ast.File, sourceAdj func(src []byte, inde
// Format the source.
// Write it without any leading and trailing space.
- cfg := config
cfg.Indent = indent + indentAdj
var buf bytes.Buffer
err := cfg.Fprint(&buf, fset, file)