github.com/yunabe/lgo@v0.0.0-20190709125917-42c42d410fdf/converter/format.go (about)

     1  package converter
     2  
     3  import (
     4  	"bytes"
     5  	"github.com/yunabe/lgo/go/go/printer"
     6  	"go/ast"
     7  	"go/token"
     8  	"strings"
     9  )
    10  
    11  // Format formats lgo src code like go fmt command.
    12  func Format(src string) (string, error) {
    13  	fset, blk, err := parseLesserGoString(src)
    14  	if err != nil {
    15  		return "", err
    16  	}
    17  	var imports []ast.Decl
    18  	for _, s := range blk.Stmts {
    19  		decl, ok := s.(*ast.DeclStmt)
    20  		if !ok {
    21  			continue
    22  		}
    23  		if gen, _ := decl.Decl.(*ast.GenDecl); gen != nil && gen.Tok == token.IMPORT {
    24  			imports = append(imports, decl.Decl)
    25  		}
    26  	}
    27  	ast.SortImports(fset, &ast.File{
    28  		Decls: imports,
    29  	})
    30  
    31  	cn := &printer.CommentedNode{
    32  		Comments: blk.Comments,
    33  		Node:     printer.LGOStmtList(blk.Stmts),
    34  	}
    35  	config := printer.Config{
    36  		Mode:     printer.UseSpaces,
    37  		Tabwidth: 4,
    38  	}
    39  	var buf bytes.Buffer
    40  	if err := config.Fprint(&buf, fset, cn); err != nil {
    41  		return "", err
    42  	}
    43  	return strings.TrimSpace(buf.String()), nil
    44  }