示例#1
0
文件: print.go 项目: Congenital/msgp
func generate(f *parse.FileSet, mode gen.Method) (*bytes.Buffer, *bytes.Buffer, error) {
	outbuf := bytes.NewBuffer(make([]byte, 0, 4096))
	writePkgHeader(outbuf, f.Package)

	myImports := []string{"github.com/tinylib/msgp/msgp"}
	for _, imp := range f.Imports {
		if imp.Name != nil {
			// have an alias, include it.
			myImports = append(myImports, imp.Name.Name+` `+imp.Path.Value)
		} else {
			myImports = append(myImports, imp.Path.Value)
		}
	}
	dedup := dedupImports(myImports)
	writeImportHeader(outbuf, dedup...)

	var testbuf *bytes.Buffer
	var testwr io.Writer
	if mode&gen.Test == gen.Test {
		testbuf = bytes.NewBuffer(make([]byte, 0, 4096))
		writePkgHeader(testbuf, f.Package)
		if mode&(gen.Encode|gen.Decode) != 0 {
			writeImportHeader(testbuf, "bytes", "github.com/tinylib/msgp/msgp", "testing")
		} else {
			writeImportHeader(testbuf, "github.com/tinylib/msgp/msgp", "testing")
		}
		testwr = testbuf
	}
	return outbuf, testbuf, f.PrintTo(gen.NewPrinter(mode, outbuf, testwr))
}
示例#2
0
文件: msgp.go 项目: themakers/red-go
func Msgpack(file, pkg string) error {
	fset, err := parse.File(file, true)
	if err != nil {
		return err
	}

	buf := bytes.NewBuffer([]byte{})

	wt := iox.NewWriteTransformer(buf, func() iox.WriteTransformerFunc {
		done := false
		return func(s *iox.WriteTransformerState) {
			if res := iox.StrictMatchFinder([]byte("package "+pkg), 0, s.Buffer); res != nil {
				if done {
					s.Pass(-1)
					return
				}
				if res.Partial {
				} else {
					s.Drop(res.End + 1)
					done = true
				}
			} else {
				s.Drop(-1)
			}
		}
	}())

	_ = wt

	prntr := gen.NewPrinter(gen.Encode|gen.Decode|gen.Marshal|gen.Unmarshal|gen.Size, buf, nil)
	err = fset.PrintTo(prntr)
	if err != nil {
		return err
	}

	data := buf.Bytes()
	data, err = format.Source(data)
	if err != nil {
		return err
	}

	f, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = io.Copy(f, bytes.NewReader(data))
	if err != nil {
		return err
	}

	return nil
}
示例#3
0
文件: print.go 项目: kgrz/msgp
func generate(f *parse.FileSet, mode gen.Method) (*bytes.Buffer, *bytes.Buffer, error) {
	outbuf := bytes.NewBuffer(make([]byte, 0, 4096))
	writePkgHeader(outbuf, f.Package)
	writeImportHeader(outbuf, "github.com/tinylib/msgp/msgp")

	var testbuf *bytes.Buffer
	var testwr io.Writer
	if mode&gen.Test == gen.Test {
		testbuf = bytes.NewBuffer(make([]byte, 0, 4096))
		writePkgHeader(testbuf, f.Package)
		if mode&(gen.Encode|gen.Decode) != 0 {
			writeImportHeader(testbuf, "bytes", "github.com/tinylib/msgp/msgp", "testing")
		} else {
			writeImportHeader(testbuf, "github.com/tinylib/msgp/msgp", "testing")
		}
		testwr = testbuf
	}
	return outbuf, testbuf, f.PrintTo(gen.NewPrinter(mode, outbuf, testwr))
}