-
Notifications
You must be signed in to change notification settings - Fork 0
/
gofile.go
81 lines (70 loc) · 1.37 KB
/
gofile.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
package main
import (
"bufio"
"os"
"path/filepath"
ss "strings"
)
type GoFile struct {
fname, pkg string
imports, code []string
}
func ReadGoFile(path, fname string) (GoFile, error) {
pkg := ""
imports := make([]string, 0, 10)
code := make([]string, 0, 200)
file, err := os.Open(path + string(filepath.Separator) + fname)
if err != nil {
return GoFile{}, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
inImport := false
for scanner.Scan() {
line := scanner.Text()
trm := ss.TrimSpace(line)
if len(trm) == 0 && ss.HasPrefix(trm, "//") {
continue
}
if ss.HasPrefix(trm, "package ") {
pkg = line
continue
}
if inImport {
imp := takeImport(trm)
if len(imp) > 0 {
imports = append(imports, imp)
}
if ss.HasSuffix(trm, ")") {
inImport = false
}
continue
}
if ss.HasPrefix(trm, "import ") {
if ss.Contains(trm, "(") {
imp := takeImport(trm)
if len(imp) > 0 {
imports = append(imports, imp)
}
inImport = true
} else {
imports = append(imports, takeImport(trm))
}
continue
}
code = append(code, line)
}
if err := scanner.Err(); err != nil {
return GoFile{}, err
}
print(fname)
return GoFile{fname, pkg, imports, code}, nil
}
func takeImport(s string) string {
fi := ss.Index(s, "\"")
li := ss.LastIndex(s, "\"") + 1
if fi == -1 {
return ""
}
return s[fi:li]
}