github.com/kotovmak/go-admin@v1.1.1/adm/generate.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"os/exec"
     8  	"runtime"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/AlecAivazis/survey/v2"
    13  	"github.com/AlecAivazis/survey/v2/core"
    14  	"github.com/kotovmak/go-admin/modules/db"
    15  	"github.com/kotovmak/go-admin/plugins/admin/modules"
    16  	"github.com/kotovmak/go-admin/plugins/admin/modules/tools"
    17  	"github.com/mgutz/ansi"
    18  	"github.com/schollz/progressbar"
    19  	"gopkg.in/ini.v1"
    20  )
    21  
    22  var systemGoAdminTables = []string{
    23  	"goadmin_menu",
    24  	"goadmin_operation_log",
    25  	"goadmin_permissions",
    26  	"goadmin_role_menu",
    27  	"goadmin_site",
    28  	"goadmin_roles",
    29  	"goadmin_session",
    30  	"goadmin_users",
    31  	"goadmin_role_permissions",
    32  	"goadmin_role_users",
    33  	"goadmin_user_permissions",
    34  }
    35  
    36  func generating(cfgFile, connName string) {
    37  
    38  	clear(runtime.GOOS)
    39  	cliInfo()
    40  
    41  	var (
    42  		info = new(dbInfo)
    43  
    44  		connection, packageName, outputPath, generatePermissionFlag string
    45  
    46  		chooseTables = make([]string, 0)
    47  
    48  		cfgModel *ini.File
    49  		err      error
    50  	)
    51  
    52  	if cfgFile != "" {
    53  		cfgModel, err = ini.Load(cfgFile)
    54  
    55  		if err != nil {
    56  			panic(errors.New("wrong config file path"))
    57  		}
    58  
    59  		languageCfg, err := cfgModel.GetSection("language")
    60  
    61  		if err == nil {
    62  			setDefaultLangSet(languageCfg.Key("language").Value())
    63  		}
    64  
    65  		modelCfgModel, exist2 := cfgModel.GetSection("model")
    66  
    67  		if exist2 == nil {
    68  			connection = modelCfgModel.Key("connection").Value()
    69  			packageName = modelCfgModel.Key("package").Value()
    70  			outputPath = modelCfgModel.Key("output").Value()
    71  			generatePermissionFlag = modelCfgModel.Key("generate_permission_flag").Value()
    72  		}
    73  
    74  		if connection == "" {
    75  			connection = connName
    76  		}
    77  
    78  		info = getDBInfoFromINIConfig(cfgModel, connection)
    79  	}
    80  
    81  	// step 1. get connection
    82  	conn := askForDBConnection(info)
    83  
    84  	// step 2. show tables
    85  	if len(chooseTables) == 0 {
    86  		tables, err := db.WithDriver(conn).Table(info.Database).ShowTables()
    87  
    88  		if err != nil {
    89  			panic(err)
    90  		}
    91  
    92  		tables = filterTables(tables)
    93  
    94  		if len(tables) == 0 {
    95  			panic(newError(`no tables, you should build a table of your own business first.`))
    96  		}
    97  		tables = append([]string{"[" + getWord("select all") + "]"}, tables...)
    98  
    99  		survey.SelectQuestionTemplate = strings.ReplaceAll(survey.SelectQuestionTemplate, "<enter> to select",
   100  			"<space> to select")
   101  
   102  		chooseTables = selects(tables)
   103  		if len(chooseTables) == 0 {
   104  			panic(newError("no table is selected"))
   105  		}
   106  		if modules.InArray(chooseTables, "["+getWord("select all")+"]") {
   107  			chooseTables = tables[1:]
   108  		}
   109  	}
   110  
   111  	if packageName == "" {
   112  		packageName = promptWithDefault("set package name", "main")
   113  	}
   114  
   115  	if connection == "" {
   116  		connection = promptWithDefault("set connection name", "default")
   117  	}
   118  
   119  	if outputPath == "" {
   120  		outputPath = promptWithDefault("set file output path", "./")
   121  	}
   122  
   123  	if generatePermissionFlag == "" {
   124  		generatePermissionFlag = singleSelect(getWord("generate permission records for tables"),
   125  			[]string{getWord("yes"), getWord("no")}, getWord("yes"))
   126  	}
   127  
   128  	if generatePermissionFlag == getWord("yes") {
   129  		if connection == "default" {
   130  			for _, table := range chooseTables {
   131  				insertPermissionOfTable(conn, table)
   132  			}
   133  		} else {
   134  			var defInfo = new(dbInfo)
   135  			if cfgFile != "" {
   136  				defInfo = getDBInfoFromINIConfig(cfgModel, "")
   137  			}
   138  			defConn := askForDBConnection(defInfo)
   139  			for _, table := range chooseTables {
   140  				insertPermissionOfTable(defConn, table)
   141  			}
   142  		}
   143  	}
   144  
   145  	fmt.Println()
   146  	fmt.Println(ansi.Color("βœ”", "green") + " " + getWord("generating: "))
   147  	fmt.Println()
   148  
   149  	bar := progressbar.New(len(chooseTables))
   150  	for i := 0; i < len(chooseTables); i++ {
   151  		_ = bar.Add(1)
   152  		time.Sleep(10 * time.Millisecond)
   153  		checkError(tools.Generate(tools.NewParam(tools.Config{
   154  			Connection:     connection,
   155  			Driver:         info.DriverName,
   156  			Package:        packageName,
   157  			HideFilterArea: true,
   158  			Table:          chooseTables[i],
   159  			Schema:         info.Schema,
   160  			Output:         outputPath,
   161  			Conn:           conn,
   162  		})))
   163  	}
   164  
   165  	if err := tools.GenerateTables(outputPath, packageName, chooseTables, true); err != nil {
   166  		panic(err)
   167  	}
   168  
   169  	fmt.Println()
   170  	fmt.Println()
   171  	fmt.Println(ansi.Color(getWord("Generate data table models success~~🍺🍺"), "green"))
   172  	fmt.Println()
   173  	if defaultLang == "cn" {
   174  		fmt.Println(getWord("see the docs: ") + ansi.Color("http://doc.go-admin.cn",
   175  			"blue"))
   176  	} else {
   177  		fmt.Println(getWord("see the docs: ") + ansi.Color("https://book.go-admin.com",
   178  			"blue"))
   179  	}
   180  	fmt.Println(getWord("visit forum: ") + ansi.Color("http://discuss.go-admin.com",
   181  		"blue"))
   182  	fmt.Println()
   183  	fmt.Println()
   184  }
   185  
   186  func clear(osName string) {
   187  
   188  	if osName == "linux" || osName == "darwin" {
   189  		cmd := exec.Command("clear") //Linux example, its tested
   190  		cmd.Stdout = os.Stdout
   191  		_ = cmd.Run()
   192  	}
   193  
   194  	if osName == "windows" {
   195  		cmd := exec.Command("cmd", "/c", "cls") //Windows example, its tested
   196  		cmd.Stdout = os.Stdout
   197  		_ = cmd.Run()
   198  	}
   199  }
   200  
   201  func filterTables(models []string) []string {
   202  	tables := make([]string, 0)
   203  
   204  	for i := 0; i < len(models); i++ {
   205  		// skip goadmin system tables
   206  		if isSystemTable(models[i]) {
   207  			continue
   208  		}
   209  		tables = append(tables, models[i])
   210  	}
   211  
   212  	return tables
   213  }
   214  
   215  func isSystemTable(name string) bool {
   216  	for _, v := range systemGoAdminTables {
   217  		if name == v {
   218  			return true
   219  		}
   220  	}
   221  
   222  	return false
   223  }
   224  
   225  func prompt(label string) string {
   226  
   227  	var qs = []*survey.Question{
   228  		{
   229  			Name:     label,
   230  			Prompt:   &survey.Input{Message: getWord(label)},
   231  			Validate: survey.Required,
   232  		},
   233  	}
   234  
   235  	var result = make(map[string]interface{})
   236  
   237  	err := survey.Ask(qs, &result)
   238  
   239  	checkError(err)
   240  
   241  	return result[label].(string)
   242  }
   243  
   244  func promptWithDefault(label string, defaultValue string) string {
   245  
   246  	var qs = []*survey.Question{
   247  		{
   248  			Name:     label,
   249  			Prompt:   &survey.Input{Message: getWord(label), Default: defaultValue},
   250  			Validate: survey.Required,
   251  		},
   252  	}
   253  
   254  	var result = make(map[string]interface{})
   255  
   256  	err := survey.Ask(qs, &result)
   257  
   258  	checkError(err)
   259  
   260  	return result[label].(string)
   261  }
   262  
   263  func promptPassword() string {
   264  
   265  	password := ""
   266  	prompt := &survey.Password{
   267  		Message: getWord("sql password"),
   268  	}
   269  	err := survey.AskOne(prompt, &password, nil)
   270  
   271  	checkError(err)
   272  
   273  	return password
   274  }
   275  
   276  func selects(tables []string) []string {
   277  
   278  	chooseTables := make([]string, 0)
   279  	prompt := &survey.MultiSelect{
   280  		Message:  getWord("choose table to generate"),
   281  		Options:  tables,
   282  		PageSize: 10,
   283  	}
   284  	err := survey.AskOne(prompt, &chooseTables, nil)
   285  
   286  	checkError(err)
   287  
   288  	return chooseTables
   289  }
   290  
   291  func singleSelect(msg string, options []string, def string) string {
   292  	var qs = []*survey.Question{
   293  		{
   294  			Name: "question",
   295  			Prompt: &survey.Select{
   296  				Message: msg,
   297  				Options: options,
   298  				Default: def,
   299  			},
   300  		},
   301  	}
   302  	var result = make(map[string]interface{})
   303  	err := survey.Ask(qs, &result)
   304  	checkError(err)
   305  
   306  	return result["question"].(core.OptionAnswer).Value
   307  
   308  }