github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/codegen/gen.go (about)

     1  package codegen
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"reflect"
     7  	"strings"
     8  
     9  	"golang.org/x/tools/imports"
    10  
    11  	"github.com/johnnyeven/libtools/duration"
    12  	"github.com/johnnyeven/libtools/format"
    13  )
    14  
    15  type Outputs map[string]string
    16  
    17  func (outputs Outputs) Add(filename string, content string) {
    18  	outputs[filename] = content
    19  }
    20  
    21  func (outputs Outputs) WriteFile(filename string, content string) {
    22  	if IsGoFile(filename) {
    23  		bytes, err := imports.Process(filename, []byte(content), nil)
    24  		if err != nil {
    25  			lines := strings.Split(content, "\n")
    26  			lengthOfLines := len(lines)
    27  			lengthOfLastLineString := len(fmt.Sprintf("%d", lengthOfLines+1))
    28  			for i, line := range lines {
    29  				lineString := fmt.Sprintf("%d", i+1)
    30  				lineString = strings.Repeat(" ", lengthOfLastLineString-len(lineString)) + lineString
    31  
    32  				fmt.Printf("%s: %s\n", lineString, line)
    33  			}
    34  			panic(err.Error())
    35  		} else {
    36  			bytes, err := format.Process(filename, bytes)
    37  			if err != nil {
    38  				panic(err.Error())
    39  			}
    40  			content = string(bytes)
    41  		}
    42  	}
    43  	WriteFile(filename, content)
    44  	delete(outputs, filename)
    45  }
    46  
    47  func (outputs Outputs) WriteFiles() {
    48  	for filename, content := range outputs {
    49  		outputs.WriteFile(filename, content)
    50  	}
    51  }
    52  
    53  type Generator interface {
    54  	Load(cwd string)
    55  	Pick()
    56  	Output(cwd string) Outputs
    57  }
    58  
    59  func Generate(generator Generator) {
    60  	cost := duration.NewDuration()
    61  	defer func() {
    62  		cost.ToLogger().Infof("generate by %s done", reflect.TypeOf(generator).String())
    63  	}()
    64  
    65  	cwd, _ := os.Getwd()
    66  	generator.Load(cwd)
    67  	generator.Pick()
    68  	outputs := generator.Output(cwd)
    69  	outputs.WriteFiles()
    70  }