开发过程中部分代码加了前缀,现在想都加上,网上找都是Shell和Python,试了下都不太符合要求,于是用golang写了一个简单的替换方法,代码如下:
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"encoding/json"
"time"
)
type ConfigType int32
const (
Config ConfigType = 0
BackList ConfigType = 1
)
var suffix = [7]string{".h", ".m", ".swift", ".pbxproj", ".pch", ".storyboard", ".xib"}
var config = make(map[string]string)
var backlist = make(map[string][]string)
var ch = make(chan int, 512)
func checkExt(ext string) bool {
for i := 0; i < len(suffix); i++ {
if suffix[i] == ext {
return true
}
}
return false
}
func isInBackListDir(fileName string) bool {
dirs := backlist["dir"]
for i := 0; i < len(dirs); i++ {
if dirs[i] == fileName {
return true
}
}
return false
}
func isInBackListFile(fileName string) bool {
arr := backlist["file"]
for i := 0; i < len(arr); i++ {
if arr[i] == fileName {
return true
}
}
return false
}
func loadConfig(fileName string, ctype ConfigType) {
data, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Println("load file err:", fileName, err)
panic(err);
}
if ctype == Config {
err = json.Unmarshal(data, &config)
} else {
err = json.Unmarshal(data, &backlist)
}
if err != nil {
fmt.Println("file parse err:", fileName, err)
panic(err);
}
}
func renameFile(path string) {
filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fileName := info.Name()
if info.IsDir() {
if isInBackListDir(fileName) {
return filepath.SkipDir
}
return nil
} else {
isExtIn := checkExt(filepath.Ext(fileName))
if !isExtIn || isInBackListFile(fileName) {
return nil
}
newFileName := ""
key := strings.TrimSuffix(fileName, filepath.Ext(fileName))
if config[key] != "" {
newFileName = config[key] + filepath.Ext(fileName)
}
if newFileName != "" {
newPath := strings.Replace(path, fileName, newFileName, -1)
err = os.Rename(path, newPath)
fmt.Println(fileName, "->", newFileName)
go replace(newPath)
<- ch
return nil
}
go replace(path)
<- ch
}
return nil
})
}
func replace(fileName string) {
buf, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Println("read file err:", fileName, err)
}
content := string(buf)
for key, value := range config {
content = strings.Replace(content, key, value, -1)
}
ioutil.WriteFile(fileName, []byte(content), 0)
ch <- 1
}
func main() {
start := time.Now()
fmt.Println("starting......")
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
fmt.Println(err)
}
configPath := dir + "/config.json"
loadConfig(configPath, Config)
backlistPath := dir + "/backlist.json"
loadConfig(backlistPath, BackList)
renameFile(dir)
fmt.Println("ending.....\n用时:", time.Since(start))
}
其中config.json和backlist.json格式分别如下
config.json:
{
"test": "Ctest",
"xml": "XML"
}
backlist.json:
{
"dir": ["Pods"],
"file": ["test.h"]
}
替换方法:将编译出来的文件和config.json、backlist.json放入项目文件夹中,config.json前面是原始类名,后面是替换后的类名,backlist.json是黑名单,dir中的文件夹不会被遍历,file中的文件不会被替换。
最后,有兴趣或者需要更改的可以自己编译,如果想直接用附上链接点击这里 提取码: 7h39
有疑问加站长微信联系(非本文作者)