-
Notifications
You must be signed in to change notification settings - Fork 13
/
util.go
80 lines (67 loc) · 1.43 KB
/
util.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
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
)
const (
packageName = "main"
)
var (
regexPackageLine = regexp.MustCompile(`package (.+)`)
)
func mustCreateOutDir(customOutputDir string, isMockServer bool) string {
dir, err := createOutDir(customOutputDir, isMockServer)
if err != nil {
log.Fatal(err)
}
return dir
}
func createOutDir(customOutputDir string, isMockServer bool) (string, error) {
outputName := customOutputDir
if outputName == "" {
outputName = "arion_"
}
if isMockServer {
return ioutil.TempDir(".", outputName+"mock")
}
return ioutil.TempDir(".", outputName)
}
func mustCopySource(src, destDir string) {
if err := copySource(src, destDir); err != nil {
log.Fatal(err)
}
}
func copySource(src, destDir string) error {
log.Printf("Copy pb file %s to %s:", src, destDir)
s, err := os.Open(src)
if err != nil {
return err
}
defer s.Close()
fileName := filepath.Base(src)
newFile := filepath.Join(destDir, fileName)
newFile = strings.TrimRight(newFile, ".go") + ".go"
f, err := os.Create(newFile)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(s)
writer := bufio.NewWriter(f)
hasChanged := false
for scanner.Scan() {
line := scanner.Text()
if !hasChanged && regexPackageLine.MatchString(line) {
line = "package " + packageName
hasChanged = true
}
fmt.Fprintln(writer, line)
}
return writer.Flush()
}