github.com/sacloud/iaas-api-go@v1.12.0/internal/tools/gen-api-fake-store/main.go (about)

     1  // Copyright 2022-2023 The sacloud/iaas-api-go Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"log"
    19  	"path/filepath"
    20  
    21  	"github.com/sacloud/iaas-api-go/internal/define"
    22  	"github.com/sacloud/iaas-api-go/internal/dsl"
    23  	"github.com/sacloud/iaas-api-go/internal/tools"
    24  )
    25  
    26  const destination = "fake/zz_store.go"
    27  
    28  func init() {
    29  	log.SetFlags(0)
    30  	log.SetPrefix("gen-api-fake-store: ")
    31  }
    32  
    33  func main() {
    34  	dsl.IsOutOfSacloudPackage = true
    35  
    36  	tools.WriteFileWithTemplate(&tools.TemplateConfig{
    37  		OutputPath: filepath.Join(tools.ProjectRootPath(), destination),
    38  		Template:   tmpl,
    39  		Parameter:  define.APIs,
    40  	})
    41  	log.Printf("generated: %s\n", filepath.Join(tools.ProjectRootPath(), destination))
    42  }
    43  
    44  const tmpl = `// generated by 'github.com/sacloud/iaas-api-go/internal/tools/gen-fake-store'; DO NOT EDIT
    45  
    46  package fake
    47  
    48  import (
    49  	"github.com/sacloud/iaas-api-go"
    50  	"github.com/sacloud/iaas-api-go/types"
    51  	"github.com/sacloud/iaas-api-go/accessor"
    52  )
    53  
    54  {{ range . }} 
    55  func get{{.TypeName}}(zone string) []*iaas.{{.TypeName}} {
    56  	values := ds().List(Resource{{.TypeName}}, zone)
    57  	var ret []*iaas.{{.TypeName}}
    58  	for _ , v := range values {
    59  		if v, ok := v.(*iaas.{{.TypeName}}); ok {
    60  			ret = append(ret, v)
    61  		}
    62  	}
    63  	return ret
    64  }
    65  
    66  func get{{.TypeName}}ByID(zone string, id types.ID) *iaas.{{.TypeName}} {
    67  	v := ds().Get(Resource{{.TypeName}}, zone, id)
    68  	if v, ok := v.(*iaas.{{.TypeName}}); ok {
    69  		return v
    70  	}
    71  	return nil
    72  }
    73  
    74  func put{{.TypeName}}(zone string, value *iaas.{{.TypeName}}) {
    75  	var v interface{} = value
    76  	if id, ok := v.(accessor.ID); ok {
    77  		ds().Put(Resource{{.TypeName}}, zone, id.GetID(), value)
    78  		return
    79  	}
    80  	ds().Put(Resource{{.TypeName}}, zone, 0, value)
    81  }
    82  {{ end }}
    83  `