-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext.go
88 lines (76 loc) · 2.01 KB
/
text.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
package makefile
import "strings"
//Text is an interface for a text value in a Makefile
type Text interface {
Convert() string //return a string, panic to pass error
}
//RawText is a Text type which converts to the unmodified string
type RawText string
//Convert returns the unmodified string
func (raw RawText) Convert() string {
return string(raw)
}
//ExtPattern is a simple Makefile pattern which matches an extension
//NOTE: no leading .
//TODO: error checking
//E.g. makefile.ExtPattern("go") -> %.go
type ExtPattern string
//Convert formats the ExtPattern as a Makefile pattern
func (ep ExtPattern) Convert() string {
return "%." + string(ep)
}
//FilePath is a file path which can be used as Text
type FilePath string
//CheckValid does a validity check of a FilePath
//currently allows alphanumeric and "_ -.\/" runes
func (fp FilePath) CheckValid() error {
if len(fp) == 0 {
return ErrEmpty{"FilePath"}
}
for _, c := range fp {
switch {
case (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'):
case c >= '0' && c <= '9':
case c == '_':
case c == ' ':
case c == '-':
case c == '.':
case c == '\\':
case c == '+':
case c == '/':
default:
return ErrIllegalRune{
Rune: c,
SrcString: string(fp),
SrcType: "FilePath",
}
}
}
return nil
}
//Convert converts a FilePath to a string suitable for a Makefile
//currently replaces ' ' -> '\ ' and '\' -> '\\'
func (fp FilePath) Convert() string {
err := fp.CheckValid()
if err != nil {
panic(err)
}
return strings.Replace(strings.Replace(string(fp), " ", "\\ ", -1), "\\", "\\\\", -1)
}
//Join is a piece of text formed by joining other pieces of text
type Join struct {
Sep string
Txt []Text
}
//JoinText returns a Join formed by joining the txt values by the sep seperator
func JoinText(sep string, txt ...Text) Text {
return Join{sep, txt}
}
//Convert returns the joined text
func (j Join) Convert() string {
strs := make([]string, len(j.Txt))
for i, v := range j.Txt {
strs[i] = v.Convert()
}
return strings.Join(strs, j.Sep)
}