-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
115 lines (105 loc) · 2.58 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func main() {
fmt.Println(os.Args)
if len(os.Args) > 1 {
for i := 1; i < len(os.Args); i++ {
path := os.Args[i]
if err := TransPy(path); err != nil {
fmt.Println("TransPy error:", err)
return
}
}
} else {
if err := ScanDir("./res/"); err != nil {
fmt.Println("ScanDir error:", err)
return
}
if err := ScanDir("./"); err != nil {
fmt.Println("ScanDir error:", err)
return
}
}
}
func ScanDir(dir string) error {
files, err := ListDir(dir, ".py")
if err != nil {
//fmt.Println("ListDir error:", err)
return nil
}
for _, path := range files {
if err := TransPy(path); err != nil {
return err
}
}
return nil
}
//获取指定目录下的所有文件,不进入下一级目录搜索,可以匹配后缀过滤。
func ListDir(dirPth string, suffix string) (files []string, err error) {
files = make([]string, 0, 10)
dir, err := ioutil.ReadDir(dirPth)
if err != nil {
return nil, err
}
PthSep := string(os.PathSeparator)
suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写
for _, fi := range dir {
if fi.IsDir() { // 忽略目录
continue
}
if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) { //匹配文件
files = append(files, dirPth+PthSep+fi.Name())
}
}
return files, nil
}
func TransPy(path string) error {
fmt.Println("translate:", path)
data, err := ioutil.ReadFile(path)
if err != nil {
fmt.Println("ReadFile fail:", path, err)
return err
}
buf := bytes.NewBuffer(data)
var part = new(CodePart)
part.partType = CodePart_Root
err = part.Parse(buf)
if err != nil {
fmt.Println("Parse fail:", err)
return err
}
r := part.Translate()
last := strings.LastIndex(path, ".py")
newPath := path[0:last] + ".go"
fmt.Println("write file:", newPath)
err = ioutil.WriteFile(newPath, []byte(r), os.ModeType)
if err != nil {
fmt.Println("WriteFile error:", err)
}
return err
}
//获取指定目录及所有子目录下的所有文件,可以匹配后缀过滤。
func WalkDir(dirPth, suffix string) (files []string, err error) {
files = make([]string, 0, 30)
suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写
err = filepath.Walk(dirPth, func(filename string, fi os.FileInfo, err error) error { //遍历目录
//if err != nil { //忽略错误
// return err
//}
if fi.IsDir() { // 忽略目录
return nil
}
if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
files = append(files, filename)
}
return nil
})
return files, err
}