Ejemplo n.º 1
0
func (im *InceptionMain) Generate(packageName string, si []*StructInfo) error {
	var err error

	importName, err := getImportName(im.inputPath)

	if err != nil {
		return err
	}

	// for `go run` to work, we must have a file ending in ".go".
	im.tempMain, err = TempFileWithPostfix("", "ffjson-inception", ".go")
	if err != nil {
		return err
	}

	im.TempMainPath = im.tempMain.Name()
	sn := make([]string, 0)
	for _, st := range si {
		sn = append(sn, st.Name)
	}

	tc := &templateCtx{
		ImportName:  importName,
		PackageName: packageName,
		StructNames: sn,
		InputPath:   im.inputPath,
		OutputPath:  im.outputPath,
	}

	t := template.Must(template.New("inception.go").Parse(inceptionMainTemplate))
	err = t.Execute(im.tempMain, tc)
	if err != nil {
		return err
	}

	out, err := shared.GoFmt(im.TempMainPath)
	if err != nil {
		return err
	}

	_, err = im.tempMain.Seek(0, 0)
	if err != nil {
		return err
	}

	err = im.tempMain.Truncate(0)
	if err != nil {
		return err
	}

	_, err = im.tempMain.Write(out.Bytes())
	if err != nil {
		return err
	}

	return nil
}
Ejemplo n.º 2
0
func RenderTemplate(ic *Inception) ([]byte, error) {
	var keep = false
	f, err := ioutil.TempFile("", "ffjson-fmt")
	if err != nil {
		return nil, err
	}
	defer func() {
		if !keep {
			os.Remove(f.Name())
		}
	}()

	for pill, _ := range ic.OutputPills {
		imports, funcBody, err := pills.GetPill(pill)
		if err != nil {
			return nil, err
		}

		for _, module := range imports {
			ic.OutputImports[module] = true
		}

		ic.OutputFuncs = append(ic.OutputFuncs, funcBody)
	}

	t := template.Must(template.New("ffjson.go").Parse(ffjsonTemplate))

	err = t.Execute(f, ic)

	if err != nil {
		return nil, err
	}

	out, err := shared.GoFmt(f.Name())
	if err != nil {
		keep = true
		return nil, errors.New(fmt.Sprintf("Error formating: %s\n%v", f.Name(), err))

	}

	return out.Bytes(), nil
}