package main import ( "bytes" "fmt" "io/ioutil" "os" "strings" "text/template" ) type createInfo struct { baseType string targetType string path string } var createFuncs = map[string][]*createInfo{ "scopes": { { baseType: "Scope", targetType: "Scope", path: `"scopes"`, }, }, "groups": { { baseType: "Group", targetType: "Group", path: `"groups"`, }, }, "users": { { baseType: "User", targetType: "User", path: `"users"`, }, }, "roles": { { baseType: "Role", targetType: "Role", path: `"roles"`, }, }, "hosts": { { baseType: "HostCatalog", targetType: "Host", path: `fmt.Sprintf("host-catalogs/%s/hosts", s.Id)`, }, { baseType: "HostCatalog", targetType: "HostSet", path: `fmt.Sprintf("host-catalogs/%s/host-sets", s.Id)`, }, }, } func writeCreateFuncs() { for outPkg, funcs := range createFuncs { outFile := os.Getenv("GEN_BASEPATH") + fmt.Sprintf("/api/%s/create.gen.go", outPkg) outBuf := bytes.NewBuffer([]byte(fmt.Sprintf( `// Code generated by "make api"; DO NOT EDIT. package %s `, outPkg))) for _, createInfo := range funcs { createFuncTemplate.Execute(outBuf, struct { BaseType string TargetType string TargetName string Path string }{ BaseType: createInfo.baseType, TargetType: createInfo.targetType, TargetName: strings.Split(createInfo.targetType, ".")[strings.Count(createInfo.targetType, ".")], Path: createInfo.path, }) } if err := ioutil.WriteFile(outFile, outBuf.Bytes(), 0644); err != nil { fmt.Printf("error writing file %q: %v\n", outFile, err) os.Exit(1) } } } var createFuncTemplate = template.Must(template.New("").Parse( ` func (s {{ .BaseType }}) Create{{ .TargetName }}(ctx context.Context, r *{{ .TargetType }}) (*{{ .TargetType }}, *api.Error, error) { if s.Client == nil { return nil, nil, fmt.Errorf("nil client in Create{{ .TargetName }} request") } var opts []api.Option if s.Scope.Id != "" { // If it's explicitly set here, override anything that might be in the // client opts = append(opts, api.WithScopeId(s.Scope.Id)) } req, err := s.Client.NewRequest(ctx, "POST", {{ .Path }}, r, opts...) if err != nil { return nil, nil, fmt.Errorf("error creating Create{{ .TargetName }} request: %w", err) } resp, err := s.Client.Do(req) if err != nil { return nil, nil, fmt.Errorf("error performing client request during Create{{ .TargetName }} call: %w", err) } target := new({{ .TargetType }}) apiErr, err := resp.Decode(target) if err != nil { return nil, nil, fmt.Errorf("error decoding Create{{ .TargetName }} repsonse: %w", err) } {{ if (eq .TargetType "Scope") }} target.Client = s.Client.Clone() target.Client.SetScopeId(target.Id) {{ else }} target.Client = s.Client {{ end }} return target, apiErr, nil } `))