//NewBuilder creates a build instance using the JSON schema data from the given filename. If modelName and/or pkgName
//are left empty the title-attribute of the JSON schema is used for:
// => struct-name (singular, camelcase e.g contact => Contact)
// => package name (pluralize, lowercased e.g. payment_reminder => paymentreminders)
func NewBuilder(inputFile string, modelName string, pkgName string) (builder Builder) {
	builder = Builder{}
	// try to read input file
	raw, err := ioutil.ReadFile(inputFile)
	if err != nil {
		msg := fmt.Sprintf("File error: %s", err)
		builder.Errors = append(builder.Errors, msg)
		return
	}
	builder.InputFile = inputFile
	builder.SchemaRaw = raw
	// try parsing json
	if err := json.Unmarshal(builder.SchemaRaw, &builder.SchemaJSON); err != nil {
		msg := fmt.Sprintf("JSON error: %s", err)
		builder.Errors = append(builder.Errors, msg)
		return
	}

	// defer model name from schema.title if not given as argument, schema['title'] MUST be set
	if len(modelName) > 0 {
		builder.ModelName = modelName
	} else {
		builder.ModelName = inflect.Typeify(builder.SchemaJSON["title"].(string))
	}
	// defer package name from schema.title if not given as argument
	if len(pkgName) > 0 {
		builder.PkgName = pkgName
	} else {
		//Pluralize no underscores
		builder.PkgName = strings.ToLower(inflect.Camelize(inflect.Pluralize(builder.SchemaJSON["title"].(string))))
	}

	return
}
Beispiel #2
0
// writeConst is a helper function that writes the
// body string to a Go const variable.
func writeConst(w io.Writer, body string, label ...string) {
	// create a snake case variable name from
	// the specified labels. Then convert the
	// variable name to a quoted, camel case string.
	name := strings.Join(label, "_")
	name = inflect.Typeify(name)

	// quote the body using multi-line quotes
	body = fmt.Sprintf(sQuote, body)

	fmt.Fprintf(w, sConst, name, body)
}