package main import ( "bytes" "fmt" "io/ioutil" "os" "strings" "text/template" ) type readInfo struct { baseType string targetType string path string } var readFuncs = map[string][]*readInfo{ "scopes": { { baseType: "Scope", targetType: "Scope", path: "scopes", }, }, "authtokens": { { baseType: "AuthToken", targetType: "AuthToken", path: "auth-tokens", }, }, "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: "HostCatalog", path: "host-catalogs", }, }, } func writeReadFuncs() { for outPkg, funcs := range readFuncs { outFile := os.Getenv("GEN_BASEPATH") + fmt.Sprintf("/api/%s/read.gen.go", outPkg) outBuf := bytes.NewBuffer([]byte(fmt.Sprintf( `// Code generated by "make api"; DO NOT EDIT. package %s `, outPkg))) for _, readInfo := range funcs { readFuncTemplate.Execute(outBuf, struct { BaseType string TargetType string TargetName string Path string }{ BaseType: readInfo.baseType, TargetType: readInfo.targetType, TargetName: strings.Split(readInfo.targetType, ".")[strings.Count(readInfo.targetType, ".")], Path: readInfo.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 readFuncTemplate = template.Must(template.New("").Parse( ` func (s {{ .BaseType }}) Read{{ .TargetName }}(ctx context.Context, id string) (*{{ .TargetType }}, *api.Error, error) { if id == "" { return nil, nil, fmt.Errorf("empty ID value passed into Read{{ .TargetName }} request") } if s.Client == nil { return nil, nil, fmt.Errorf("nil client in Read{{ .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, "GET", fmt.Sprintf("%s/%s", "{{ .Path }}", id), nil, opts...) if err != nil { return nil, nil, fmt.Errorf("error creating Read{{ .TargetName }} request: %w", err) } resp, err := s.Client.Do(req) if err != nil { return nil, nil, fmt.Errorf("error performing client request during Read{{ .TargetName }} call: %w", err) } target := new({{ .TargetType }}) apiErr, err := resp.Decode(target) if err != nil { return nil, nil, fmt.Errorf("error decoding Read{{ .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 } `))