123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- package middleware
- import (
- "fmt"
- "os"
- "path/filepath"
- "regexp"
- "sort"
- "xg_dba/internal/models"
- "github.com/BurntSushi/toml"
- )
- func Cache() {
- // 指定需要查找的根文件夹路径
- folderPath := "C:\\Program_GT\\Code\\Go\\Work\\xugu\\xg_dba\\config"
- packageModels := make(map[string]models.Cache)
- err := filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
- if info.IsDir() {
- listenFilePath := filepath.Join(path, "listen.toml")
- var connectInfo models.ConnectInfo
- var systemMetaInfo models.SystemMetaInfo
- if fileExists(listenFilePath) {
- if _, err := parseTomlFile(listenFilePath, &connectInfo); err != nil {
- return err
- }
- }
- latestOsInfoFilePath, err := getLatestOsInfoFile(path)
- if err != nil {
- return err
- }
- if latestOsInfoFilePath != "" {
- if _, err := parseTomlFile(latestOsInfoFilePath, &systemMetaInfo); err != nil {
- return err
- }
- }
- host := connectInfo.Ssh.Host
- if host != "" {
- packageModels[host] = models.Cache{
- ConnectInfo: connectInfo,
- SystemMetaInfo: systemMetaInfo,
- }
- }
- }
- return nil
- })
- if err != nil {
- fmt.Printf("Error walking the path %q: %v\n", folderPath, err)
- return
- }
- for host, cache := range packageModels {
- fmt.Printf("Host: %s, Cache: %+v\n", host, cache)
- }
- }
- func fileExists(filename string) bool {
- info, err := os.Stat(filename)
- if os.IsNotExist(err) {
- return false
- }
- return !info.IsDir()
- }
- func parseTomlFile(filePath string, v interface{}) (toml.MetaData, error) {
- file, err := os.Open(filePath)
- if err != nil {
- return toml.MetaData{}, err
- }
- defer file.Close()
- decoder := toml.NewDecoder(file)
- metaData, err := decoder.Decode(v)
- if err != nil {
- return toml.MetaData{}, err
- }
- return metaData, nil
- }
- func getLatestOsInfoFile(dirPath string) (string, error) {
- pattern := regexp.MustCompile(`^os_info(?:_\d{8}_\d{6})?\.toml$`)
- files, err := os.ReadDir(dirPath)
- if err != nil {
- return "", err
- }
- var matchingFiles []string
- for _, file := range files {
- if !file.IsDir() && pattern.MatchString(file.Name()) {
- matchingFiles = append(matchingFiles, filepath.Join(dirPath, file.Name()))
- }
- }
- if len(matchingFiles) == 0 {
- return "", nil
- }
- sort.Slice(matchingFiles, func(i, j int) bool {
- return matchingFiles[i] > matchingFiles[j]
- })
- return matchingFiles[0], nil
- }
|