feat: add dump/check command function

This commit is contained in:
LinkinStar 2022-10-12 11:49:28 +08:00 committed by mingcheng
parent c59889939b
commit 333bd72cde
5 changed files with 101 additions and 11 deletions

View File

@ -8,10 +8,19 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var (
// confFlag is the config flag.
confFlag string
// dumpDataPath dump data path
dumpDataPath string
)
func init() { func init() {
rootCmd.Version = Version rootCmd.Version = Version
runCmd.Flags().StringVarP(&confFlag, "config", "c", "data/config.yaml", "config path, eg: -c config.yaml") runCmd.Flags().StringVarP(&confFlag, "config", "c", "data/config.yaml", "config path, eg: -c config.yaml")
dumpCmd.Flags().StringVarP(&dumpDataPath, "path", "p", "./", "dump data path, eg: -p ./dump/data/")
rootCmd.AddCommand(initCmd) rootCmd.AddCommand(initCmd)
rootCmd.AddCommand(checkCmd) rootCmd.AddCommand(checkCmd)
rootCmd.AddCommand(runCmd) rootCmd.AddCommand(runCmd)
@ -78,6 +87,16 @@ To run answer, use:
Long: `back up data`, Long: `back up data`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Answer is backing up data") fmt.Println("Answer is backing up data")
c, err := readConfig()
if err != nil {
fmt.Println("read config failed: ", err.Error())
return
}
err = cli.DumpAllData(c.Data.Database, dumpDataPath)
if err != nil {
fmt.Println("dump failed: ", err.Error())
return
}
fmt.Println("Answer backed up the data successfully.") fmt.Println("Answer backed up the data successfully.")
}, },
} }
@ -89,10 +108,30 @@ To run answer, use:
Long: `Check if the current environment meets the startup requirements`, Long: `Check if the current environment meets the startup requirements`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Start checking the required environment...") fmt.Println("Start checking the required environment...")
fmt.Println("config file exists [✔]") if cli.CheckConfigFile() {
fmt.Println("db connection successfully [✔]") fmt.Println("config file exists [✔]")
fmt.Println("cache directory exists [✔]") } else {
fmt.Println("Successful! The current environment meets the startup requirements.") fmt.Println("config file not exists [x]")
}
if cli.CheckUploadDir() {
fmt.Println("upload directory exists [✔]")
} else {
fmt.Println("upload directory not exists [x]")
}
c, err := readConfig()
if err != nil {
fmt.Println("read config failed: ", err.Error())
return
}
if cli.CheckDB(c.Data.Database) {
fmt.Println("db connection successfully [✔]")
} else {
fmt.Println("db connection failed [x]")
}
fmt.Println("check environment all done")
}, },
} }
) )

View File

@ -18,8 +18,6 @@ var (
Name = "answer" Name = "answer"
// Version is the version of the project // Version is the version of the project
Version = "unknown" Version = "unknown"
// confFlag is the config flag.
confFlag string
// log level // log level
logLevel = os.Getenv("LOG_LEVEL") logLevel = os.Getenv("LOG_LEVEL")
// log path // log path

24
internal/cli/dump.go Normal file
View File

@ -0,0 +1,24 @@
package cli
import (
"fmt"
"path/filepath"
"time"
"github.com/segmentfault/answer/internal/base/data"
"xorm.io/xorm/schemas"
)
// DumpAllData dump all database data to sql
func DumpAllData(dataConf *data.Database, dumpDataPath string) error {
db, err := data.NewDB(false, dataConf)
if err != nil {
return err
}
if err = db.Ping(); err != nil {
return err
}
name := filepath.Join(dumpDataPath, fmt.Sprintf("answer_dump_data_%s.sql", time.Now().Format("2006-01-02")))
return db.DumpAllToFile(name, schemas.MYSQL)
}

View File

@ -16,6 +16,8 @@ import (
const ( const (
defaultConfigFilePath = "data/config.yaml" defaultConfigFilePath = "data/config.yaml"
defaultUploadFilePath = "data/upfiles"
defaultI18nPath = "data/i18n"
) )
// InstallAllInitialEnvironment install all initial environment // InstallAllInitialEnvironment install all initial environment
@ -38,7 +40,7 @@ func installDataDir() {
func installConfigFile() { func installConfigFile() {
fmt.Println("[config-file] try to install...") fmt.Println("[config-file] try to install...")
if dir.CheckPathExist(defaultConfigFilePath) { if CheckConfigFile() {
fmt.Println("[config-file] already exists") fmt.Println("[config-file] already exists")
return return
} }
@ -51,7 +53,7 @@ func installConfigFile() {
func installUploadDir() { func installUploadDir() {
fmt.Println("[upload-dir] try to install...") fmt.Println("[upload-dir] try to install...")
if _, err := dir.CreatePathIsNotExist("data/upfiles"); err != nil { if _, err := dir.CreatePathIsNotExist(defaultUploadFilePath); err != nil {
fmt.Printf("[upload-dir] install fail %s\n", err.Error()) fmt.Printf("[upload-dir] install fail %s\n", err.Error())
} else { } else {
fmt.Printf("[upload-dir] install success\n") fmt.Printf("[upload-dir] install success\n")
@ -60,7 +62,7 @@ func installUploadDir() {
func installI18nBundle() { func installI18nBundle() {
fmt.Println("[i18n] try to install i18n bundle...") fmt.Println("[i18n] try to install i18n bundle...")
if _, err := dir.CreatePathIsNotExist("data/i18n"); err != nil { if _, err := dir.CreatePathIsNotExist(defaultI18nPath); err != nil {
fmt.Println(err.Error()) fmt.Println(err.Error())
return return
} }
@ -72,7 +74,7 @@ func installI18nBundle() {
} }
fmt.Printf("[i18n] find i18n bundle %d\n", len(i18nList)) fmt.Printf("[i18n] find i18n bundle %d\n", len(i18nList))
for _, item := range i18nList { for _, item := range i18nList {
path := fmt.Sprintf("data/i18n/%s", item.Name()) path := fmt.Sprintf("%s/%s", defaultI18nPath, item.Name())
content, err := i18n.I18n.ReadFile(item.Name()) content, err := i18n.I18n.ReadFile(item.Name())
if err != nil { if err != nil {
continue continue
@ -92,7 +94,9 @@ func WriterFile(filePath, content string) error {
if err != nil { if err != nil {
return err return err
} }
defer file.Close() defer func() {
_ = file.Close()
}()
writer := bufio.NewWriter(file) writer := bufio.NewWriter(file)
if _, err := writer.WriteString(content); err != nil { if _, err := writer.WriteString(content); err != nil {
return err return err

View File

@ -0,0 +1,25 @@
package cli
import (
"github.com/segmentfault/answer/internal/base/data"
"github.com/segmentfault/answer/pkg/dir"
)
func CheckConfigFile() bool {
return dir.CheckPathExist(defaultConfigFilePath)
}
func CheckUploadDir() bool {
return dir.CheckPathExist(defaultConfigFilePath)
}
func CheckDB(dataConf *data.Database) bool {
db, err := data.NewDB(false, dataConf)
if err != nil {
return false
}
if err = db.Ping(); err != nil {
return false
}
return true
}