github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/pkg/utils/stdin/stdin.go (about)

     1  package stdinUtils
     2  
     3  import (
     4  	"bufio"
     5  	"os"
     6  	"regexp"
     7  	"strings"
     8  
     9  	fileUtils "github.com/easysoft/zendata/pkg/utils/file"
    10  	i118Utils "github.com/easysoft/zendata/pkg/utils/i118"
    11  	logUtils "github.com/easysoft/zendata/pkg/utils/log"
    12  	"github.com/fatih/color"
    13  )
    14  
    15  func GetInput(regx string, defaultVal string, fmtStr string, params ...interface{}) string {
    16  	var ret string
    17  
    18  	msg := i118Utils.I118Prt.Sprintf(fmtStr, params...)
    19  
    20  	for {
    21  		logUtils.PrintToWithColor("\n"+msg, color.FgCyan)
    22  		// fmt.Scanln(&ret)
    23  		Scanf(&ret)
    24  
    25  		//logUtils.PrintToWithColor(fmt.Sprintf("%v", ret), -1)
    26  
    27  		if strings.TrimSpace(ret) == "" && defaultVal != "" {
    28  			ret = defaultVal
    29  
    30  			logUtils.PrintTo(ret)
    31  		}
    32  
    33  		temp := strings.ToLower(ret)
    34  		if temp == "exit" {
    35  			color.Unset()
    36  			os.Exit(0)
    37  		}
    38  
    39  		//logUtils.PrintToWithColor(ret, -1)
    40  
    41  		if regx == "" {
    42  			return ret
    43  		}
    44  
    45  		var pass bool
    46  		var msg string
    47  		if regx == "is_dir" {
    48  			pass = fileUtils.IsDir(ret)
    49  			msg = "dir_not_exist"
    50  		} else {
    51  			pass, _ = regexp.MatchString("^"+regx+"$", temp)
    52  			msg = "invalid_input"
    53  		}
    54  
    55  		if pass {
    56  			return ret
    57  		} else {
    58  			ret = ""
    59  			logUtils.PrintToWithColor(i118Utils.I118Prt.Sprintf(msg), color.FgRed)
    60  		}
    61  	}
    62  }
    63  
    64  func InputForBool(in *bool, defaultVal bool, fmtStr string, fmtParam ...interface{}) {
    65  	str := GetInput("(yes|no|y|n|)", "", fmtStr, fmtParam...)
    66  
    67  	if str == "" {
    68  		*in = defaultVal
    69  
    70  		msg := ""
    71  		if *in {
    72  			msg = "yes"
    73  		} else {
    74  			msg = "no"
    75  		}
    76  		logUtils.PrintTo(msg)
    77  		return
    78  	}
    79  
    80  	if str == "y" && str != "yes" {
    81  		*in = true
    82  	} else {
    83  		*in = false
    84  	}
    85  }
    86  
    87  func Scanf(a *string) {
    88  	reader := bufio.NewReader(os.Stdin)
    89  	data, _, _ := reader.ReadLine()
    90  	*a = string(data)
    91  }