package util import ( "bytes" "fmt" "os" "strings" "text/template" "github.com/fatih/color" "github.com/sergi/go-diff/diffmatchpatch" ) func TemplateToFile(desFile string, templateContent string, data interface{}) error { tpl := template.New("template") tpl, err := tpl.Parse(templateContent) if err != nil { return err } b := bytes.Buffer{} err = tpl.Execute(&b, data) if err != nil { return err } err = WriteFile(desFile, b.Bytes()) if err != nil { return err } return nil } var defaultPrintDiff = color.WhiteString func IsChange(diff []diffmatchpatch.Diff) bool { for _, d := range diff { if d.Type != diffmatchpatch.DiffEqual { return true } } return false } // AddLine 增加行号 TODO: 颜色不完美 func AddLine(s string) string { lines := strings.Split(s, "\n") for i, line := range lines { // lines[i] = fmt.Sprintf("%s %s", defaultPrintDiff("%4d.", i+1), line) lines[i] = fmt.Sprintf("%4d. %s", i+1, line) } return strings.Join(lines, "\n") } func WriteFile(filePath string, data []byte) error { color.Green("写入[%s]文件...", filePath) toFileContent, err := os.ReadFile(filePath) if err == nil { dmp := diffmatchpatch.New() diffContent := dmp.DiffMain(string(toFileContent), string(data), true) if IsChange(diffContent) { color.Red("文件[%s]已存在:", filePath) b := bytes.Buffer{} diffContent = dmp.DiffCleanupSemanticLossless(diffContent) for _, diff := range diffContent { switch diff.Type { case diffmatchpatch.DiffDelete: b.WriteString(color.RedString(diff.Text)) case diffmatchpatch.DiffInsert: b.WriteString(color.GreenString(diff.Text)) case diffmatchpatch.DiffEqual: b.WriteString(diff.Text) } } fmt.Println(AddLine(b.String())) if !ReadBoolWithMessage("是否确认此次修改(y修改/n跳过): ") { color.Red("跳过文件: %s\n\n", filePath) return nil } } else { color.Red("文件已存在且无变动,跳过文件: %s\n\n", filePath) return nil } } file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm) if err != nil { return err } defer file.Close() _, err = file.Write(data) color.Red("写入文件完成: %s\n\n", filePath) return err } func WriteFileWithNotEdit(filePath string, data []byte) error { notEdit := "# Code generated by wujian-develop_tool. DO NOT EDIT.\n\n" return WriteFile(filePath, []byte(notEdit+string(data))) } // ExistFile 文件是否存在 func ExistFile(filePath string) bool { info, err := os.Stat(filePath) return err == nil && !info.IsDir() } // ExistDir 目录是否存在 func ExistDir(dirPath string) bool { info, err := os.Stat(dirPath) return err == nil && info.IsDir() }