forked from tkrajina/ftmpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
misc.go
92 lines (75 loc) · 1.78 KB
/
misc.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
package ftmplting
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"path"
"path/filepath"
"strings"
)
const randomStringChars = "qwertyuiopasdfghjklzxcvbnm1234567890"
func getRandomString(length int) string {
result := ""
for i := 0; i < length; i++ {
result += string(randomStringChars[rand.Int()%len(randomStringChars)])
}
return result
}
func getLastPathElements(path string) (string, string) {
absPath, err := filepath.Abs(path)
HandleError(err, "Error getting absolute path from "+path)
pathParts := strings.Split(absPath, string(os.PathSeparator))
var elements []string
for _, part := range pathParts {
part = strings.TrimSpace(part)
if len(part) > 0 {
elements = append(elements, part)
}
}
if len(pathParts) == 0 {
return "", ""
}
if len(elements) == 1 {
return "", elements[len(elements)-1]
}
return elements[len(elements)-2], elements[len(elements)-1]
}
func quote(s string) string {
return strings.Replace(s, "`", "`+\"`\"+`", -1)
}
func HandleError(err error, message string) {
if err == nil {
return
}
panic(message + ":" + err.Error())
}
func handleLineError(err error, line string) {
if err == nil {
return
}
panic("Error " + err.Error() + " in line:" + line)
}
func rmDoubleImports(list []string) []string {
var result []string
existing := make(map[string]bool)
for _, i := range list {
if _, ok := existing[i]; !ok {
result = append(result, i)
}
existing[i] = true
}
return result
}
func loadFile(filename string) (string, error) {
f, err := os.Open(path.Join(filename))
if err != nil {
return "", fmt.Errorf("Error reading %s: %s", filename, err.Error())
}
defer f.Close()
byts, err := ioutil.ReadAll(f)
if err != nil {
return "", fmt.Errorf("Error reading %s: %s", filename, err.Error())
}
return string(byts), nil
}