-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
309 lines (282 loc) · 5.69 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// This code is under BSD license. See license-bsd.txt
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
)
func must(err error, args ...interface{}) {
if err == nil {
return
}
if len(args) == 0 {
panic(err)
}
s := args[0].(string)
if len(args) > 1 {
args = args[1:]
s = fmt.Sprintf(s, args)
}
panic(s + " err: " + err.Error())
}
func panicIfErr(err error) {
if err != nil {
panic(err.Error())
}
}
/*
func panicMsg(format string, args ...interface{}) {
s := fmt.Sprintf(format, args...)
fmt.Printf("%s\n", s)
panic(s)
}
*/
// FmtArgs formats args as a string. First argument should be format string
// and the rest are arguments to the format
func FmtArgs(args ...interface{}) string {
if len(args) == 0 {
return ""
}
format := args[0].(string)
if len(args) == 1 {
return format
}
return fmt.Sprintf(format, args[1:]...)
}
func panicWithMsg(defaultMsg string, args ...interface{}) {
s := FmtArgs(args...)
if s == "" {
s = defaultMsg
}
fmt.Printf("%s\n", s)
panic(s)
}
func panicIf(cond bool, args ...interface{}) {
if !cond {
return
}
panicWithMsg("PanicIf: condition failed", args...)
}
func logIfError(err error) {
if err != nil {
fmt.Printf("%s\n", err)
}
}
// whitelisted characters valid in url
func validateRune(c rune) byte {
if c >= 'a' && c <= 'z' {
return byte(c)
}
if c >= '0' && c <= '9' {
return byte(c)
}
if c == '-' || c == '_' || c == '.' {
return byte(c)
}
if c == ' ' {
return '-'
}
return 0
}
func charCanRepeat(c byte) bool {
if c >= 'a' && c <= 'z' {
return true
}
if c >= '0' && c <= '9' {
return true
}
return false
}
// urlify generates safe url from tile by removing hazardous characters
func urlify(title string) string {
s := strings.TrimSpace(title)
s = strings.ToLower(s)
var res []byte
for _, r := range s {
c := validateRune(r)
if c == 0 {
continue
}
// eliminute duplicate consequitive characters
var prev byte
if len(res) > 0 {
prev = res[len(res)-1]
}
if c == prev && !charCanRepeat(c) {
continue
}
res = append(res, c)
}
s = string(res)
if len(s) > 128 {
s = s[:128]
}
return s
}
func trimEmptyLines(a []string) []string {
var res []string
// remove empty lines from beginning and duplicated empty lines
prevWasEmpty := true
for _, s := range a {
currIsEmpty := (len(s) == 0)
if currIsEmpty && prevWasEmpty {
continue
}
res = append(res, s)
prevWasEmpty = currIsEmpty
}
// remove empty lines from end
for len(res) > 0 {
lastIdx := len(res) - 1
if len(res[lastIdx]) != 0 {
break
}
res = res[:lastIdx]
}
return res
}
func findWordEnd(s string, start int) int {
for i := start; i < len(s); i++ {
c := s[i]
if c == ' ' {
return i + 1
}
}
return -1
}
// remove #tag from start and end
func removeHashTags(s string) (string, []string) {
var tags []string
defer func() {
for i, tag := range tags {
tags[i] = strings.ToLower(tag)
}
}()
// remove hashtags from start
for strings.HasPrefix(s, "#") {
idx := findWordEnd(s, 0)
if idx == -1 {
tags = append(tags, s[1:])
return "", tags
}
tags = append(tags, s[1:idx-1])
s = strings.TrimLeft(s[idx:], " ")
}
// remove hashtags from end
s = strings.TrimRight(s, " ")
for {
idx := strings.LastIndex(s, "#")
if idx == -1 {
return s, tags
}
// tag from the end must not have space after it
if -1 != findWordEnd(s, idx) {
return s, tags
}
// tag from the end must start at the beginning of line
// or be proceded by space
if idx > 0 && s[idx-1] != ' ' {
return s, tags
}
tags = append(tags, s[idx+1:])
s = strings.TrimRight(s[:idx], " ")
}
}
func normalizeNewlines(d []byte) []byte {
// replace CR LF (windows) with LF (unix)
d = bytes.Replace(d, []byte{13, 10}, []byte{10}, -1)
// replace CF (mac) with LF (unix)
d = bytes.Replace(d, []byte{13}, []byte{10}, -1)
return d
}
func replaceExt(fileName, newExt string) string {
ext := filepath.Ext(fileName)
if ext == "" {
return fileName
}
n := len(fileName)
s := fileName[:n-len(ext)]
return s + newExt
}
// foo => Foo, BAR => Bar etc.
func capitalize(s string) string {
if len(s) == 0 {
return s
}
s = strings.ToLower(s)
return strings.ToUpper(s[0:1]) + s[1:]
}
func mkdirForFile(filePath string) error {
dir := filepath.Dir(filePath)
return os.MkdirAll(dir, 0755)
}
func copyFile(dst string, src string) error {
err := mkdirForFile(dst)
if err != nil {
return err
}
fin, err := os.Open(src)
if err != nil {
return err
}
defer fin.Close()
fout, err := os.Create(dst)
if err != nil {
return err
}
_, err = io.Copy(fout, fin)
err2 := fout.Close()
if err != nil || err2 != nil {
os.Remove(dst)
}
return err
}
func dirCopyRecur(dst string, src string, shouldSkipFile func(string) bool) (int, error) {
nFilesCopied := 0
dirsToVisit := []string{src}
for len(dirsToVisit) > 0 {
n := len(dirsToVisit)
dir := dirsToVisit[n-1]
dirsToVisit = dirsToVisit[:n-1]
fileInfos, err := ioutil.ReadDir(dir)
if err != nil {
return nFilesCopied, err
}
for _, fi := range fileInfos {
path := filepath.Join(dir, fi.Name())
if fi.IsDir() {
dirsToVisit = append(dirsToVisit, path)
continue
}
if shouldSkipFile != nil && shouldSkipFile(path) {
continue
}
dstPath := dst + path[len(src):]
err := copyFile(dstPath, path)
if err != nil {
return nFilesCopied, err
}
verbose("Copied %s => %s\n", path, dstPath)
nFilesCopied++
}
}
return nFilesCopied, nil
}
func fileExists(path string) bool {
st, err := os.Stat(path)
if err != nil {
return false
}
return st.Mode().IsRegular()
}
func waitForCtrlC() {
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt /* SIGINT */, syscall.SIGTERM)
<-c
}