-
Notifications
You must be signed in to change notification settings - Fork 0
/
include_files.go
82 lines (69 loc) · 1.78 KB
/
include_files.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
package protocli
import (
"io/ioutil"
"os"
"strings"
"github.com/yoozoo/protocli/util"
)
var protocliIncPath string
var includeFiles = make(map[string]string)
const embeddedDir = "/proto/"
// RegisterIncludeFile add file into includeFiles map
func RegisterIncludeFile(name string, content string) {
includeFiles[name] = content
}
// GetIncludePath returns the actual include path
func GetIncludePath(userPath string, filePath string) string {
// extract common includes if needed
protocliIncPath := util.GetProtocliHome() + util.ProtocliCommonInclude
if !CheckIncludesExist() {
path, err := ioutil.TempDir("", "protoapi_inc_")
if err != nil {
panic(err)
}
err = ExtractIncludes(path)
if err != nil {
panic(err)
}
protocliIncPath = path
}
// return path concatenated with user include path
var result = protocliIncPath + string(os.PathListSeparator) + filePath
if len(userPath) > 0 {
result += string(os.PathListSeparator) + userPath
}
return result
}
// CheckIncludesExist check if include files all exists
func CheckIncludesExist() bool {
for n := range includeFiles {
if _, err := os.Stat(protocliIncPath + n); err != nil {
return false
}
}
return true
}
// CleanIncludePath cleanup include path if needed
func CleanIncludePath() {
// make sure we remove the dir under os.TempDir only
if len(protocliIncPath) > 0 && strings.HasPrefix(protocliIncPath, os.TempDir()) {
os.RemoveAll(protocliIncPath)
}
}
// ExtractIncludes extract common protoconf includes
func ExtractIncludes(path string) error {
needClean := true
defer func() {
if needClean {
os.RemoveAll(path)
}
}()
for n, c := range includeFiles {
err := ioutil.WriteFile(path+string(os.PathSeparator)+n, []byte(c), 0666)
if err != nil {
return err
}
}
needClean = false
return nil
}