github.com/turingchain2020/turingchain@v1.1.21/cmd/tools/tasks/replace_target_task.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package tasks 6 7 import ( 8 "os" 9 "path/filepath" 10 "strings" 11 12 "github.com/turingchain2020/turingchain/cmd/tools/types" 13 "github.com/turingchain2020/turingchain/cmd/tools/util" 14 ) 15 16 // ReplaceTargetTask 替换指定目录下所有文件的标志性文字 17 // 可替换的名字列表如下: 18 // ${PROJECTNAME} 19 // ${CLASSNAME} 20 // ${ACTIONNAME} 21 // ${EXECNAME} 22 type ReplaceTargetTask struct { 23 TaskBase 24 OutputPath string 25 ProjectName string 26 ClassName string 27 ActionName string 28 ExecName string 29 } 30 31 //GetName 获取name 32 func (r *ReplaceTargetTask) GetName() string { 33 return "ReplaceTargetTask" 34 } 35 36 // Execute 执行具体的替换动作 37 // 1. 扫描指定的output路径 38 // 2. 打开每一个文件,根据替换规则替换内部的所有标签 39 // 3. 保存时查看文件名是否要替换,如果要则替换后保存,否则直接保存 40 // 4. 一直到所有的文件都替换完毕 41 func (r *ReplaceTargetTask) Execute() error { 42 mlog.Info("Execute replace target task.") 43 err := filepath.Walk(r.OutputPath, func(path string, info os.FileInfo, err error) error { 44 if info == nil { 45 return err 46 } 47 if info.IsDir() { 48 return nil 49 } 50 if err := r.replaceTarget(path); err != nil { 51 mlog.Error("replaceTarget error", "error", err, "path", path) 52 return err 53 } 54 return nil 55 }) 56 return err 57 } 58 59 func (r *ReplaceTargetTask) replaceTarget(file string) error { 60 replacePairs := []struct { 61 src string 62 dst string 63 }{ 64 {src: types.TagProjectName, dst: r.ProjectName}, 65 {src: types.TagClassName, dst: r.ClassName}, 66 {src: types.TagActionName, dst: r.ActionName}, 67 {src: types.TagExecName, dst: r.ExecName}, 68 } 69 bcontent, err := util.ReadFile(file) 70 if err != nil { 71 return err 72 } 73 content := string(bcontent) 74 for _, pair := range replacePairs { 75 content = strings.Replace(content, pair.src, pair.dst, -1) 76 } 77 util.DeleteFile(file) 78 _, err = util.WriteStringToFile(file, content) 79 return err 80 }