github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/src/go/printer/example_test.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package printer_test
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"go/ast"
    11  	"go/parser"
    12  	"go/printer"
    13  	"go/token"
    14  	"strings"
    15  	"testing"
    16  )
    17  
    18  // Dummy test function so that godoc does not use the entire file as example.
    19  func Test(*testing.T) {}
    20  
    21  func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
    22  	fset = token.NewFileSet()
    23  	if file, err := parser.ParseFile(fset, filename, nil, 0); err == nil {
    24  		for _, d := range file.Decls {
    25  			if f, ok := d.(*ast.FuncDecl); ok && f.Name.Name == functionname {
    26  				fun = f
    27  				return
    28  			}
    29  		}
    30  	}
    31  	panic("function not found")
    32  }
    33  
    34  func ExampleFprint() {
    35  	// Parse source file and extract the AST without comments for
    36  	// this function, with position information referring to the
    37  	// file set fset.
    38  	funcAST, fset := parseFunc("example_test.go", "ExampleFprint")
    39  
    40  	// Print the function body into buffer buf.
    41  	// The file set is provided to the printer so that it knows
    42  	// about the original source formatting and can add additional
    43  	// line breaks where they were present in the source.
    44  	var buf bytes.Buffer
    45  	printer.Fprint(&buf, fset, funcAST.Body)
    46  
    47  	// Remove braces {} enclosing the function body, unindent,
    48  	// and trim leading and trailing white space.
    49  	s := buf.String()
    50  	s = s[1 : len(s)-1]
    51  	s = strings.TrimSpace(strings.Replace(s, "\n\t", "\n", -1))
    52  
    53  	// Print the cleaned-up body text to stdout.
    54  	fmt.Println(s)
    55  
    56  	// output:
    57  	// funcAST, fset := parseFunc("example_test.go", "ExampleFprint")
    58  	//
    59  	// var buf bytes.Buffer
    60  	// printer.Fprint(&buf, fset, funcAST.Body)
    61  	//
    62  	// s := buf.String()
    63  	// s = s[1 : len(s)-1]
    64  	// s = strings.TrimSpace(strings.Replace(s, "\n\t", "\n", -1))
    65  	//
    66  	// fmt.Println(s)
    67  }