Exemple #1
0
func (a *appGenerator) Generate() error {
	app := a.makeCodegenApp()

	if a.DumpData {
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(app), "", "  ")
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	if err := a.generateAPIBuilder(&app); err != nil {
		return err
	}
	importPath := filepath.ToSlash(filepath.Join(baseImport(a.Target), a.ServerPackage, a.APIPackage))
	app.DefaultImports = append(app.DefaultImports, importPath)

	if err := a.generateConfigureAPI(&app); err != nil {
		return err
	}

	if err := a.generateMain(&app); err != nil {
		return err
	}

	return nil
}
Exemple #2
0
// Validate validates the data against the schema
func (s *SchemaValidator) Validate(data interface{}) *Result {
	if data == nil {
		v := s.validators[0].Validate(data)
		v.Merge(s.validators[6].Validate(data))
		return v
	}
	result := new(Result)

	tpe := reflect.TypeOf(data)
	kind := tpe.Kind()
	for kind == reflect.Ptr {
		tpe = tpe.Elem()
		kind = tpe.Kind()
	}
	d := data
	if kind == reflect.Struct {
		d = swag.ToDynamicJSON(data)
	}

	for _, v := range s.validators {
		if !v.Applies(s.Schema, kind) {
			continue
		}

		err := v.Validate(d)
		result.Merge(err)
		result.Inc()
	}
	result.Inc()
	return result
}
Exemple #3
0
func (t *testGenerator) GenerateTest() error {
	test := t.makeCodegenTest()

	if t.DumpData {
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(test), "", "  ")
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	test.DefaultImports = append(test.DefaultImports, filepath.Join(baseImport(t.Target), t.ServerPackage, t.APIPackage))

	if t.IncludeTCK {
		if err := t.generateTCK(&test); err != nil {
			return err
		}
	}
	if err := t.generateSuiteTest(&test); err != nil {
		return err
	}
	for _, operation := range test.Operations {
		test.OperationID = operation.Name
		if err := t.generateTest(&operation, &test); err != nil {
			return err
		}
	}

	return nil
}
Exemple #4
0
func (m *modelGenerator) Generate() error {
	mod := makeCodegenModel(m.Name, m.Target, m.Model, m.SpecDoc)
	if m.DumpData {
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(mod), "", " ")
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	m.Data = mod

	if m.IncludeModel {
		if err := m.generateModel(); err != nil {
			return fmt.Errorf("model: %s", err)
		}
	}
	log.Println("generated model", m.Name)

	if m.IncludeValidator {
		if err := m.generateValidator(); err != nil {
			return fmt.Errorf("validator: %s", err)
		}
	}
	log.Println("generated validator", m.Name)
	return nil
}
Exemple #5
0
func (c *clientGenerator) Generate() error {
	app, err := c.makeCodegenApp()
	app.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ModelsPackage))}
	if err != nil {
		return err
	}

	if c.DumpData {
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(app), "", "  ")
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	for _, mod := range app.Models {
		mod.IncludeValidator = true // a.GenOpts.IncludeValidator
		gen := &definitionGenerator{
			Name:    mod.Name,
			SpecDoc: c.SpecDoc,
			Target:  filepath.Join(c.Target, c.ModelsPackage),
			Data:    &mod,
		}
		if err := gen.generateModel(); err != nil {
			return err
		}
	}

	for i := range app.OperationGroups {
		opGroup := app.OperationGroups[i]
		opGroup.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ModelsPackage))}
		opGroup.RootPackage = c.ClientPackage
		app.OperationGroups[i] = opGroup
		sort.Sort(opGroup.Operations)
		for _, op := range opGroup.Operations {
			if op.Package == "" {
				op.Package = c.Package
			}
			if err := c.generateParameters(&op); err != nil {
				return err
			}

			if err := c.generateResponses(&op); err != nil {
				return err
			}
		}
		app.DefaultImports = append(app.DefaultImports, filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ClientPackage, opGroup.Name)))
		if err := c.generateGroupClient(opGroup); err != nil {
			return err
		}
	}

	sort.Sort(app.OperationGroups)

	if err := c.generateFacade(&app); err != nil {
		return err
	}

	return nil
}
Exemple #6
0
func (a *appGenerator) Generate() error {

	app, err := a.makeCodegenApp()
	if err != nil {
		return err
	}

	if a.DumpData {
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(app), "", "  ")
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	if a.GenOpts.IncludeModel {
		log.Printf("rendering %d models", len(app.Models))
		for _, mod := range app.Models {
			mod.IncludeValidator = true // a.GenOpts.IncludeValidator
			gen := &definitionGenerator{
				Name:    mod.Name,
				SpecDoc: a.SpecDoc,
				Target:  filepath.Join(a.Target, a.ModelsPackage),
				Data:    &mod,
			}
			if err := gen.generateModel(); err != nil {
				return err
			}
		}
	}

	if a.GenOpts.IncludeHandler {
		for _, opg := range app.OperationGroups {
			for _, op := range opg.Operations {
				gen := &opGen{
					data:              &op,
					pkg:               opg.Name,
					cname:             swag.ToGoName(op.Name),
					IncludeHandler:    a.GenOpts.IncludeHandler,
					IncludeParameters: a.GenOpts.IncludeParameters,
					IncludeResponses:  a.GenOpts.IncludeResponses,
					Doc:               a.SpecDoc,
					Target:            filepath.Join(a.Target, a.ServerPackage),
					APIPackage:        a.APIPackage,
				}

				if err := gen.Generate(); err != nil {
					return err
				}
			}
		}
	}

	if a.GenOpts.IncludeSupport {
		return a.GenerateSupport(&app)
	}
	return nil
}
Exemple #7
0
func (o *operationGenerator) Generate() error {
	// Build a list of codegen operations based on the tags,
	// the tag decides the actual package for an operation
	// the user specified package serves as root for generating the directory structure
	var operations []genOperation
	authed := len(o.SecurityRequirements) > 0
	for _, tag := range o.Operation.Tags {
		if len(o.Tags) == 0 {
			operations = append(operations, makeCodegenOperation(o.Name, tag, o.ModelsPackage, o.Principal, o.Target, o.Operation, authed))
			continue
		}
		for _, ft := range o.Tags {
			if ft == tag {
				operations = append(operations, makeCodegenOperation(o.Name, tag, o.ModelsPackage, o.Principal, o.Target, o.Operation, authed))
				break
			}
		}

	}
	if len(operations) == 0 {
		operations = append(operations, makeCodegenOperation(o.Name, o.APIPackage, o.ModelsPackage, o.Principal, o.Target, o.Operation, authed))
	}

	for _, op := range operations {
		if o.DumpData {
			bb, _ := json.MarshalIndent(swag.ToDynamicJSON(op), "", " ")
			fmt.Fprintln(os.Stdout, string(bb))
			continue
		}
		o.data = op
		o.pkg = op.Package
		o.cname = op.ClassName

		if o.IncludeHandler {
			if err := o.generateHandler(); err != nil {
				return fmt.Errorf("handler: %s", err)
			}
			log.Println("generated handler", op.Package+"."+op.ClassName)
		}

		if o.IncludeParameters && len(o.Operation.Parameters) > 0 {
			if err := o.generateParameterModel(); err != nil {
				return fmt.Errorf("parameters: %s", err)
			}
			log.Println("generated parameters", op.Package+"."+op.ClassName+"Parameters")
		}

		if len(o.Operation.Parameters) == 0 {
			log.Println("no parameters for operation", op.Package+"."+op.ClassName)
		}
	}

	return nil
}
Exemple #8
0
func (c *clientGenerator) Generate() error {
	app, err := c.makeCodegenApp()
	app.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ModelsPackage))}
	if err != nil {
		return err
	}

	if c.DumpData {
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(app), "", "  ")
		fmt.Fprintln(os.Stdout, string(bb))
		return nil
	}

	opsGroupedByTag := make(map[string]GenOperations)
	for _, operation := range app.Operations {
		if operation.Package == "" {
			operation.Package = c.Package
		}
		if err := c.generateParameters(&operation); err != nil {
			return err
		}

		if err := c.generateResponses(&operation); err != nil {
			return err
		}
		opsGroupedByTag[operation.Package] = append(opsGroupedByTag[operation.Package], operation)
	}

	for k, v := range opsGroupedByTag {
		sort.Sort(v)
		opGroup := GenOperationGroup{
			Name:           k,
			Operations:     v,
			DefaultImports: []string{filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ModelsPackage))},
		}
		app.OperationGroups = append(app.OperationGroups, opGroup)
		app.DefaultImports = append(app.DefaultImports, filepath.ToSlash(filepath.Join(baseImport(c.Target), c.ClientPackage, k)))
		if err := c.generateGroupClient(opGroup); err != nil {
			return err
		}
	}
	sort.Sort(app.OperationGroups)

	if err := c.generateEmbeddedSwaggerJSON(&app); err != nil {
		return err
	}

	if err := c.generateFacade(&app); err != nil {
		return err
	}

	return nil
}
Exemple #9
0
func (m *definitionGenerator) generateModel() error {
	buf := bytes.NewBuffer(nil)

	if Debug {
		log.Printf("rendering model template: %s", m.Name)
		bb, _ := json.MarshalIndent(swag.ToDynamicJSON(m.Data), "", " ")
		fmt.Fprintln(os.Stdout, string(bb))
	}
	if err := modelTemplate.Execute(buf, m.Data); err != nil {
		return err
	}
	log.Println("rendered model template:", m.Name)

	return writeToFile(m.Target, m.Name, buf.Bytes())
}
Exemple #10
0
func (o *operationGenerator) Generate() error {
	// Build a list of codegen operations based on the tags,
	// the tag decides the actual package for an operation
	// the user specified package serves as root for generating the directory structure
	var operations GenOperations
	authed := len(o.SecurityRequirements) > 0

	var bldr codeGenOpBuilder
	bldr.Name = o.Name
	bldr.Method = o.Method
	bldr.Path = o.Path
	bldr.ModelsPackage = o.ModelsPackage
	bldr.Principal = o.Principal
	bldr.Target = o.Target
	bldr.Operation = o.Operation
	bldr.Authed = authed
	bldr.Doc = o.Doc
	bldr.DefaultScheme = o.DefaultScheme
	bldr.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(o.Base), o.ModelsPackage))}

	for _, tag := range o.Operation.Tags {
		if len(o.Tags) == 0 {
			bldr.APIPackage = mangleName(swag.ToFileName(tag), o.APIPackage)
			op, err := bldr.MakeOperation()
			if err != nil {
				return err
			}
			operations = append(operations, op)
			continue
		}
		for _, ft := range o.Tags {
			if ft == tag {
				bldr.APIPackage = mangleName(swag.ToFileName(tag), o.APIPackage)
				op, err := bldr.MakeOperation()
				if err != nil {
					return err
				}
				operations = append(operations, op)
				break
			}
		}
	}
	if len(operations) == 0 {
		bldr.APIPackage = o.APIPackage
		op, err := bldr.MakeOperation()
		if err != nil {
			return err
		}
		operations = append(operations, op)
	}
	sort.Sort(operations)

	for _, op := range operations {
		if o.DumpData {
			bb, _ := json.MarshalIndent(swag.ToDynamicJSON(op), "", " ")
			fmt.Fprintln(os.Stdout, string(bb))
			continue
		}
		o.data = op
		o.pkg = op.Package
		o.cname = swag.ToGoName(op.Name)

		if o.IncludeHandler {
			if err := o.generateHandler(); err != nil {
				return fmt.Errorf("handler: %s", err)
			}
			log.Println("generated handler", op.Package+"."+o.cname)
		}

		opParams := o.Doc.ParametersFor(o.Operation.ID)
		if o.IncludeParameters && len(opParams) > 0 {
			if err := o.generateParameterModel(); err != nil {
				return fmt.Errorf("parameters: %s", err)
			}
			log.Println("generated parameters", op.Package+"."+o.cname+"Parameters")
		}

		if o.IncludeResponses && len(op.Responses) > 0 {
			if err := o.generateResponses(); err != nil {
				return fmt.Errorf("responses: %s", err)
			}
			log.Println("generated responses", op.Package+"."+o.cname+"Responses")
		}

		if len(opParams) == 0 {
			log.Println("no parameters for operation", op.Package+"."+o.cname)
		}
	}

	return nil
}
func (o *operationGenerator) Generate() error {
	// Build a list of codegen operations based on the tags,
	// the tag decides the actual package for an operation
	// the user specified package serves as root for generating the directory structure
	var operations GenOperations
	authed := len(o.SecurityRequirements) > 0

	var bldr codeGenOpBuilder
	bldr.Name = o.Name
	bldr.Method = o.Method
	bldr.Path = o.Path
	bldr.ModelsPackage = o.ModelsPackage
	bldr.Principal = o.Principal
	bldr.Target = o.Target
	bldr.Operation = o.Operation
	bldr.Authed = authed
	bldr.Doc = o.Doc
	bldr.DefaultScheme = o.DefaultScheme
	bldr.DefaultProduces = o.DefaultProduces
	bldr.DefaultImports = []string{filepath.ToSlash(filepath.Join(baseImport(o.Base), o.ModelsPackage))}
	bldr.RootAPIPackage = o.APIPackage

	for _, tag := range o.Operation.Tags {
		if len(o.Tags) == 0 {
			bldr.APIPackage = mangleName(swag.ToFileName(tag), o.APIPackage)
			op, err := bldr.MakeOperation()
			if err != nil {
				return err
			}
			operations = append(operations, op)
			continue
		}
		for _, ft := range o.Tags {
			if ft == tag {
				bldr.APIPackage = mangleName(swag.ToFileName(tag), o.APIPackage)
				op, err := bldr.MakeOperation()
				if err != nil {
					return err
				}
				operations = append(operations, op)
				break
			}
		}
	}
	if len(operations) == 0 {
		bldr.APIPackage = o.APIPackage
		op, err := bldr.MakeOperation()
		if err != nil {
			return err
		}
		operations = append(operations, op)
	}
	sort.Sort(operations)

	for _, op := range operations {
		if o.DumpData {
			bb, _ := json.MarshalIndent(swag.ToDynamicJSON(op), "", " ")
			fmt.Fprintln(os.Stdout, string(bb))
			continue
		}
		og := new(opGen)
		og.IncludeHandler = o.IncludeHandler
		og.IncludeParameters = o.IncludeParameters
		og.IncludeResponses = o.IncludeResponses
		og.data = &op
		og.pkg = op.Package
		og.cname = swag.ToGoName(op.Name)
		og.Doc = o.Doc
		og.Target = o.Target
		og.APIPackage = o.APIPackage
		return og.Generate()
	}

	return nil
}
Exemple #12
0
// Execute this command
func (s *Spec) Execute(args []string) error {
	targetPath := "."
	if len(args) > 0 {
		targetPath = args[0]
	}
	realPath, err := filepath.Abs(targetPath)
	if err != nil {
		return err
	}
	var file *os.File
	switch s.Format {
	case "json":
		file, err = os.Create(filepath.Join(realPath, "swagger.json"))
		if err != nil {
			return err
		}
	case "yaml", "yml":
		file, err = os.Create(filepath.Join(realPath, "swagger.yml"))
		if err != nil {
			return err
		}
	default:
		return fmt.Errorf("invalid format: %s", s.Format)
	}
	defer file.Close()
	log.Println("creating specification document in", filepath.Join(targetPath, file.Name()))

	var doc spec.Swagger
	info := new(spec.Info)
	doc.Info = info

	doc.Swagger = "2.0"
	doc.Paths = new(spec.Paths)
	doc.Definitions = make(spec.Definitions)

	info.Title = s.Title
	if info.Title == "" {
		info.Title = swag.ToHumanNameTitle(filepath.Base(realPath))
	}
	info.Description = s.Description
	info.Version = s.Version
	info.TermsOfService = s.Terms
	if s.Contact.Name != "" || s.Contact.Email != "" || s.Contact.URL != "" {
		var contact spec.ContactInfo
		contact.Name = s.Contact.Name
		contact.Email = s.Contact.Email
		contact.URL = s.Contact.URL
		info.Contact = &contact
	}
	if s.License.Name != "" || s.License.URL != "" {
		var license spec.License
		license.Name = s.License.Name
		license.URL = s.License.URL
		info.License = &license
	}

	for _, cons := range s.Consumes {
		doc.Consumes = append(doc.Consumes, cons)
	}
	for _, prods := range s.Produces {
		doc.Produces = append(doc.Produces, prods)
	}
	for _, scheme := range s.Schemes {
		doc.Schemes = append(doc.Schemes, scheme)
	}

	if s.Format == "json" {
		enc := json.NewEncoder(file)
		if err := enc.Encode(doc); err != nil {
			return err
		}
		return nil
	}

	b, err := yaml.Marshal(swag.ToDynamicJSON(doc))
	if err != nil {
		return err
	}
	if _, err := file.Write(b); err != nil {
		return err
	}
	return nil
}