github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/cmd/cli/commands/generate/adaptor/generator.go (about)

     1  // This file is part of the Smart Home
     2  // Program complex distribution https://github.com/e154/smart-home
     3  // Copyright (C) 2016-2023, Filippov Alex
     4  //
     5  // This library is free software: you can redistribute it and/or
     6  // modify it under the terms of the GNU Lesser General Public
     7  // License as published by the Free Software Foundation; either
     8  // version 3 of the License, or (at your option) any later version.
     9  //
    10  // This library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13  // Library General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public
    16  // License along with this library.  If not, see
    17  // <https://www.gnu.org/licenses/>.
    18  
    19  package adaptor
    20  
    21  import (
    22  	"os"
    23  	"path"
    24  	"strings"
    25  	"text/template"
    26  
    27  	"github.com/e154/smart-home/common/logger"
    28  
    29  	"github.com/e154/smart-home/cmd/cli/commands/generate"
    30  	"github.com/e154/smart-home/common"
    31  	"github.com/spf13/cobra"
    32  )
    33  
    34  var (
    35  	log = logger.MustGetLogger("adaptor")
    36  )
    37  
    38  var adaptorTpl = `//CODE GENERATED AUTOMATICALLY
    39  
    40  package {{.Package}}
    41  
    42  import (
    43  	"{{.Dir}}/common"
    44  	"{{.Dir}}/db"
    45  	m "{{.Dir}}/models"
    46  	"gorm.io/gorm"
    47  )
    48  
    49  type I{{.Name}} interface {
    50  	AddEntity(ver *m.{{.ModelName}}) (id int64, err error)
    51  	GetBy{{.Name}}Name(imageName string) (ver *m.{{.ModelName}}, err error)
    52  	GetById(mapId int64) (ver *m.{{.ModelName}}, err error)
    53  	UpdateEntity(ver *m.{{.ModelName}}) (err error)
    54  	Delete(mapId int64) (err error)
    55  	List(limit, offset int64, orderBy, sort string) (list []*m.{{.ModelName}}, total int64, err error)
    56  	fromDb(*db.{{.ModelName}}) *m.{{.ModelName}}
    57  	toDb(*m.{{.ModelName}}) *db.{{.ModelName}}
    58  }
    59  
    60  // {{.Name}} ...
    61  type {{.Name}} struct {
    62  	I{{.Name}}
    63  	table *db.{{.Name}}s
    64  	db    *gorm.DB
    65  }
    66  
    67  // Get{{.Name}}Adaptor ...
    68  func Get{{.Name}}Adaptor(d *gorm.DB) I{{.Name}} {
    69  	return &{{.Name}}{
    70  		table: &db.{{.ModelName}}s{Db: d},
    71  		db:    d,
    72  	}
    73  }
    74  
    75  // AddEntity ...
    76  func (n *{{.Name}}) AddEntity(ver *m.{{.ModelName}}) (id int64, err error) {
    77  
    78  	dbVer := n.toDb(ver)
    79  	if id, err = n.table.AddEntity(dbVer); err != nil {
    80  		return
    81  	}
    82  
    83  	return
    84  }
    85  
    86  // GetById ...
    87  func (n *{{.Name}}) GetById(mapId int64) (ver *m.{{.ModelName}}, err error) {
    88  
    89  	var dbVer *db.{{.ModelName}}
    90  	if dbVer, err = n.table.GetById(mapId); err != nil {
    91  		return
    92  	}
    93  
    94  	ver = n.fromDb(dbVer)
    95  
    96  	return
    97  }
    98  
    99  // UpdateEntity ...
   100  func (n *{{.Name}}) UpdateEntity(ver *m.{{.ModelName}}) (err error) {
   101  	dbVer := n.toDb(ver)
   102  	err = n.table.UpdateEntity(dbVer)
   103  	return
   104  }
   105  
   106  // Delete ...
   107  func (n *{{.Name}}) Delete(mapId int64) (err error) {
   108  	err = n.table.Delete(mapId)
   109  	return
   110  }
   111  
   112  // List ...
   113  func (n *{{.Name}}) List(limit, offset int64, orderBy, sort string) (list []*m.{{.ModelName}}, total int64, err error) {
   114  
   115  	if sort == "" {
   116  		sort = "id"
   117  	}
   118  	if orderBy == "" {
   119  		orderBy = "desc"
   120  	}
   121  
   122  	var dbList []*db.{{.ModelName}}
   123  	if dbList, total, err = n.table.List(limit, offset, orderBy, sort); err != nil {
   124  		return
   125  	}
   126  
   127  	list = make([]*m.{{.ModelName}}, 0)
   128  	for _, dbVer := range dbList {
   129  		ver := n.fromDb(dbVer)
   130  		list = append(list, ver)
   131  	}
   132  
   133  	return
   134  }
   135  
   136  func (n *{{.Name}}) fromDb(dbVer *db.{{.ModelName}}) (ver *m.{{.ModelName}}) {
   137  	ver = &m.{{.ModelName}}{
   138  		Id:        dbVer.Id,
   139  		UpdatedAt: dbVer.UpdatedAt,
   140  		CreatedAt: dbVer.CreatedAt,
   141  	}
   142  	return
   143  }
   144  
   145  func (n *{{.Name}}) toDb(ver *m.{{.ModelName}}) (dbVer *db.{{.ModelName}}) {
   146  	dbVer = &db.{{.ModelName}}{
   147  		Id:       ver.Id,
   148  		CreatedAt:     ver.CreatedAt,
   149  		UpdatedAt:     ver.UpdatedAt,
   150  	}
   151  	return
   152  }
   153  
   154  `
   155  
   156  var (
   157  	adaptorCmd = &cobra.Command{
   158  		Use:   "a",
   159  		Short: "adaptor generator",
   160  		Long:  "$ cli g a [-m=ModelName] [adaptorName]",
   161  	}
   162  	modelName string
   163  	//adaptorName string
   164  	packageName = "adaptors"
   165  )
   166  
   167  func init() {
   168  	generate.Generate.AddCommand(adaptorCmd)
   169  	adaptorCmd.Flags().StringVarP(&modelName, "model", "m", "interface{}", "interface{}")
   170  	adaptorCmd.Run = func(cmd *cobra.Command, args []string) {
   171  
   172  		if len(args) == 0 {
   173  			log.Error("Wrong number of arguments. Run: cli help generate")
   174  			return
   175  		}
   176  
   177  		currpath, _ := os.Getwd()
   178  
   179  		g := Generator{}
   180  		g.Generate(args[0], currpath)
   181  	}
   182  }
   183  
   184  // Generator ...
   185  type Generator struct{}
   186  
   187  // Generate ...
   188  func (e Generator) Generate(adaptorName, currpath string) {
   189  
   190  	log.Infof("Using '%s' as adaptor name", adaptorName)
   191  	log.Infof("Using '%s' as package name", packageName)
   192  
   193  	fp := path.Join(currpath, "adaptors")
   194  
   195  	e.addAdaptor(fp, adaptorName)
   196  }
   197  
   198  func (e Generator) addAdaptor(fp, adaptorName string) {
   199  
   200  	if _, err := os.Stat(fp); os.IsNotExist(err) {
   201  		// Create the adaptor's directory
   202  		if err := os.MkdirAll(fp, 0777); err != nil {
   203  			log.Errorf("Could not create adaptors directory: %s", err.Error())
   204  			return
   205  		}
   206  	}
   207  
   208  	fpath := path.Join(fp, strings.ToLower(adaptorName)+".go")
   209  	f, err := os.OpenFile(fpath, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666)
   210  	if err != nil {
   211  		log.Errorf("Could not create adaptor file: %s", err.Error())
   212  		return
   213  	}
   214  	defer f.Close()
   215  
   216  	templateData := struct {
   217  		Package     string
   218  		Name        string
   219  		List        string
   220  		ModelName   string
   221  		AdaptorName string
   222  		Dir         string
   223  	}{
   224  		Dir:         common.Dir(),
   225  		Package:     packageName,
   226  		Name:        adaptorName,
   227  		ModelName:   modelName,
   228  		AdaptorName: adaptorName,
   229  	}
   230  	t := template.Must(template.New("adaptor").Parse(adaptorTpl))
   231  
   232  	if t.Execute(f, templateData) != nil {
   233  		log.Error(err.Error())
   234  	}
   235  
   236  	common.FormatSourceCode(fpath)
   237  }