forked from gokcehan/lf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
misc.go
380 lines (333 loc) · 8.6 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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package main
import (
"bufio"
"fmt"
"io"
"io/fs"
"path/filepath"
"regexp"
"strconv"
"strings"
"unicode"
"github.com/Xuanwo/go-locale"
"github.com/mattn/go-runewidth"
"golang.org/x/text/collate"
"golang.org/x/text/language"
)
const (
localeStrDisable = "" // disable locale ordering for this locale value
localeStrSys = "*" // replace this locale value with locale value read from environment
)
func isRoot(name string) bool { return filepath.Dir(name) == name }
func replaceTilde(s string) string {
if strings.HasPrefix(s, "~") {
return gUser.HomeDir + s[1:]
}
return s
}
func runeSliceWidth(rs []rune) int {
w := 0
for _, r := range rs {
w += runewidth.RuneWidth(r)
}
return w
}
func runeSliceWidthRange(rs []rune, beg, end int) []rune {
if beg == end {
return []rune{}
}
curr := 0
b := 0
foundb := false
for i, r := range rs {
w := runewidth.RuneWidth(r)
if curr >= beg && !foundb {
b = i
foundb = true
}
if curr == end || curr+w > end {
return rs[b:i]
}
curr += w
}
return rs[b:]
}
// Returns the last runes of `rs` that take up at most `maxWidth` space.
func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune {
lastWidth := 0
for i := len(rs) - 1; i >= 0; i-- {
w := runewidth.RuneWidth(rs[i])
if lastWidth+w > maxWidth {
return rs[i+1:]
}
lastWidth += w
}
return rs
}
// This function is used to escape whitespaces and special characters with
// backslashes in a given string.
func escape(s string) string {
buf := make([]rune, 0, len(s))
for _, r := range s {
if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' {
buf = append(buf, '\\')
}
buf = append(buf, r)
}
return string(buf)
}
// This function is used to remove backslashes that are used to escape
// whitespaces and special characters in a given string.
func unescape(s string) string {
esc := false
buf := make([]rune, 0, len(s))
for _, r := range s {
if esc {
if !unicode.IsSpace(r) && r != '\\' && r != ';' && r != '#' {
buf = append(buf, '\\')
}
buf = append(buf, r)
esc = false
continue
}
if r == '\\' {
esc = true
continue
}
esc = false
buf = append(buf, r)
}
if esc {
buf = append(buf, '\\')
}
return string(buf)
}
// This function splits the given string by whitespaces. It is aware of escaped
// whitespaces so that they are not split unintentionally.
func tokenize(s string) []string {
esc := false
var buf []rune
var toks []string
for _, r := range s {
if r == '\\' {
esc = true
buf = append(buf, r)
continue
}
if esc {
esc = false
buf = append(buf, r)
continue
}
if !unicode.IsSpace(r) {
buf = append(buf, r)
} else {
toks = append(toks, string(buf))
buf = nil
}
}
return append(toks, string(buf))
}
// This function splits the first word of a string delimited by whitespace from
// the rest. This is used to tokenize a string one by one without touching the
// rest. Whitespace on the left side of both the word and the rest are trimmed.
func splitWord(s string) (word, rest string) {
s = strings.TrimLeftFunc(s, unicode.IsSpace)
ind := len(s)
for i, c := range s {
if unicode.IsSpace(c) {
ind = i
break
}
}
word = s[0:ind]
rest = strings.TrimLeftFunc(s[ind:], unicode.IsSpace)
return
}
// This function reads whitespace separated string arrays at each line. Single
// or double quotes can be used to escape whitespaces. Hash characters can be
// used to add a comment until the end of line. Leading and trailing space is
// trimmed. Empty lines are skipped.
func readArrays(r io.Reader, min_cols, max_cols int) ([][]string, error) {
var arrays [][]string
s := bufio.NewScanner(r)
for s.Scan() {
line := s.Text()
squote, dquote := false, false
for i := 0; i < len(line); i++ {
if line[i] == '\'' && !dquote {
squote = !squote
} else if line[i] == '"' && !squote {
dquote = !dquote
}
if !squote && !dquote && line[i] == '#' {
line = line[:i]
break
}
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
squote, dquote = false, false
arr := strings.FieldsFunc(line, func(r rune) bool {
if r == '\'' && !dquote {
squote = !squote
} else if r == '"' && !squote {
dquote = !dquote
}
return !squote && !dquote && unicode.IsSpace(r)
})
arrlen := len(arr)
if arrlen < min_cols || arrlen > max_cols {
if min_cols == max_cols {
return nil, fmt.Errorf("expected %d columns but found: %s", min_cols, s.Text())
}
return nil, fmt.Errorf("expected %d~%d columns but found: %s", min_cols, max_cols, s.Text())
}
for i := 0; i < arrlen; i++ {
squote, dquote = false, false
buf := make([]rune, 0, len(arr[i]))
for _, r := range arr[i] {
if r == '\'' && !dquote {
squote = !squote
continue
}
if r == '"' && !squote {
dquote = !dquote
continue
}
buf = append(buf, r)
}
arr[i] = string(buf)
}
arrays = append(arrays, arr)
}
return arrays, nil
}
func readPairs(r io.Reader) ([][]string, error) {
return readArrays(r, 2, 2)
}
// This function converts a size in bytes to a human readable form using metric
// suffixes (e.g. 1K = 1000). For values less than 10 the first significant
// digit is shown, otherwise it is hidden. Numbers are always rounded down.
// This should be fine for most human beings.
func humanize(size int64) string {
if size < 1000 {
return fmt.Sprintf("%dB", size)
}
suffix := []string{
"K", // kilo
"M", // mega
"G", // giga
"T", // tera
"P", // peta
"E", // exa
"Z", // zeta
"Y", // yotta
}
curr := float64(size) / 1000
for _, s := range suffix {
if curr < 10 {
return fmt.Sprintf("%.1f%s", curr-0.0499, s)
}
if curr < 1000 {
return fmt.Sprintf("%d%s", int(curr), s)
}
curr /= 1000
}
return ""
}
// This function compares two strings for natural sorting which takes into
// account values of numbers in strings. For example, '2' is less than '10',
// and similarly 'foo2bar' is less than 'foo10bar', but 'bar2bar' is greater
// than 'foo10bar'.
func naturalLess(s1, s2 string) bool {
lo1, lo2, hi1, hi2 := 0, 0, 0, 0
s1len := len(s1)
s2len := len(s2)
for {
if hi1 >= s1len {
return hi2 != s2len
}
if hi2 >= s2len {
return false
}
isDigit1 := isDigit(s1[hi1])
isDigit2 := isDigit(s2[hi2])
for lo1 = hi1; hi1 < s1len && isDigit(s1[hi1]) == isDigit1; hi1++ {
}
for lo2 = hi2; hi2 < s2len && isDigit(s2[hi2]) == isDigit2; hi2++ {
}
if s1[lo1:hi1] == s2[lo2:hi2] {
continue
}
if isDigit1 && isDigit2 {
num1, err1 := strconv.Atoi(s1[lo1:hi1])
num2, err2 := strconv.Atoi(s2[lo2:hi2])
if err1 == nil && err2 == nil {
return num1 < num2
}
}
return s1[lo1:hi1] < s2[lo2:hi2]
}
}
// This function returns the extension of a file with a leading dot
// it returns an empty string if extension could not be determined
// i.e. directories, filenames without extensions
func getFileExtension(file fs.FileInfo) string {
if file.IsDir() {
return ""
}
if strings.Count(file.Name(), ".") == 1 && file.Name()[0] == '.' {
// hidden file without extension
return ""
}
return filepath.Ext(file.Name())
}
var (
reModKey = regexp.MustCompile(`<(c|s|a)-(.+)>`)
reRulerSub = regexp.MustCompile(`%[apmcsfithd]|%\{[^}]+\}`)
)
var (
reWord = regexp.MustCompile(`(\pL|\pN)+`)
reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`)
reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`)
)
// This function parses given locale string into language tag value. Passing empty
// string as locale means reading locale value from environment.
func getLocaleTag(localeStr string) (language.Tag, error) {
if localeStr == localeStrSys {
// read environment locale
return locale.Detect()
}
localeTag, err := language.Parse(localeStr)
if err != nil {
return localeTag, fmt.Errorf("invalid locale %q: %s", localeStr, err)
}
return localeTag, nil
}
// This function creates new collator for given locale. Passing empty string as
// as locale means reading locale value from environment.
//
// *Note*: this function returns error when given `localeStr` has value `localeStrDisable`
// or is an invalid locale tag.
func makeCollator(localeStr string, opts ...collate.Option) (*collate.Collator, error) {
if localeStr == localeStrDisable {
return nil, fmt.Errorf("locale is disabled")
}
localeTag, err := getLocaleTag(localeStr)
if err != nil {
return nil, err
}
return collate.New(localeTag, opts...), nil
}
// We don't need no generic code
// We don't need no type control
// No dark templates in compiler
// Haskell leave them kids alone
// Hey Bjarne leave them kids alone
// All in all it's just another brick in the code
// All in all you're just another brick in the code
//
// -- Pink Trolled --