Debian Codegraph @

misc.go

raw
1 package main
2
3 import (
4 "bufio"
5 "bytes"
6 "cmp"
7 "fmt"
8 "io"
9 "io/fs"
10 "math/big"
11 "os"
12 "path/filepath"
13 "regexp"
14 "strconv"
15 "strings"
16 "unicode"
17
18 "github.com/clipperhouse/displaywidth"
19 )
20
21 var (
22 reRulerSub = regexp.MustCompile(`%[apmcsvfithPd]|%\{[^}]+\}`)
23 reSixelSize = regexp.MustCompile(`"1;1;(\d+);(\d+)`)
24 )
25
26 var (
27 reWord = regexp.MustCompile(`(\pL|\pN)+`)
28 reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`)
29 reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`)
30 )
31
32 func isRoot(name string) bool { return filepath.Dir(name) == name }
33
34 func replaceTilde(s string) string {
35 if strings.HasPrefix(s, "~") {
36 return gUser.HomeDir + s[1:]
37 }
38 return s
39 }
40
41 // firstGraphemeCluster returns the string containing the first grapheme cluster
42 // of the input.
43 func firstGraphemeCluster(s string) string {
44 gr := displaywidth.StringGraphemes(s)
45 gr.Next()
46 return gr.Value()
47 }
48
49 // lastGraphemeCluster returns the string containing the last grapheme cluster
50 // of the input.
51 func lastGraphemeCluster(s string) string {
52 gr := displaywidth.StringGraphemes(s)
53 var last string
54 for gr.Next() {
55 last = gr.Value()
56 }
57 return last
58 }
59
60 // truncateRight truncates a string from the right based on Unicode widths,
61 // taking into account grapheme clusters.
62 func truncateRight(s string, maxWidth int) string {
63 buf := make([]byte, 0, len(s))
64 width := 0
65
66 gr := displaywidth.StringGraphemes(s)
67 for gr.Next() {
68 width += gr.Width()
69 if width > maxWidth {
70 break
71 }
72
73 buf = append(buf, gr.Value()...)
74 }
75
76 return string(buf)
77 }
78
79 // truncateLeft truncates a string from the left based on Unicode widths,
80 // taking into account grapheme clusters.
81 func truncateLeft(s string, maxWidth int) string {
82 type cluster struct {
83 bytes []byte
84 width int
85 }
86
87 var clusters []cluster
88 totalWidth := 0
89 gr := displaywidth.StringGraphemes(s)
90 for gr.Next() {
91 clusters = append(clusters, cluster{[]byte(gr.Value()), gr.Width()})
92 totalWidth += gr.Width()
93 }
94
95 buf := make([]byte, 0, len(s))
96 width := 0
97 for _, cluster := range clusters {
98 if totalWidth-width <= maxWidth {
99 buf = append(buf, cluster.bytes...)
100 }
101
102 width += cluster.width
103 }
104
105 return string(buf)
106 }
107
108 // cmdEscape is used to escape whitespace and special characters with
109 // backslashes in a given string.
110 func cmdEscape(s string) string {
111 buf := make([]rune, 0, len(s))
112 for _, r := range s {
113 if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' {
114 buf = append(buf, '\\')
115 }
116 buf = append(buf, r)
117 }
118 return string(buf)
119 }
120
121 // cmdUnescape is used to remove backslashes that are used to escape
122 // whitespace and special characters in a given string.
123 func cmdUnescape(s string) string {
124 esc := false
125 buf := make([]rune, 0, len(s))
126 for _, r := range s {
127 if esc {
128 if !unicode.IsSpace(r) && r != '\\' && r != ';' && r != '#' {
129 buf = append(buf, '\\')
130 }
131 buf = append(buf, r)
132 esc = false
133 continue
134 }
135 if r == '\\' {
136 esc = true
137 continue
138 }
139 esc = false
140 buf = append(buf, r)
141 }
142 if esc {
143 buf = append(buf, '\\')
144 }
145 return string(buf)
146 }
147
148 // tokenize splits the given string by whitespace. It is aware of escaped
149 // and quoted whitespace so that they are not split unintentionally.
150 func tokenize(s string) []string {
151 esc := false
152 quote := false
153 var buf []rune
154 var toks []string
155 for _, r := range s {
156 switch {
157 case esc:
158 esc = false
159 buf = append(buf, r)
160 case r == '\\':
161 esc = true
162 buf = append(buf, r)
163 case r == '"':
164 quote = !quote
165 buf = append(buf, r)
166 case unicode.IsSpace(r) && !quote:
167 toks = append(toks, string(buf))
168 buf = nil
169 default:
170 buf = append(buf, r)
171 }
172 }
173 return append(toks, string(buf))
174 }
175
176 // splitWord splits the first word of a string delimited by whitespace from
177 // the rest. This is used to tokenize a string one by one without touching the
178 // rest. Whitespace on the left side of both the word and the rest are trimmed.
179 func splitWord(s string) (word, rest string) {
180 s = strings.TrimLeftFunc(s, unicode.IsSpace)
181 ind := len(s)
182 for i, c := range s {
183 if unicode.IsSpace(c) {
184 ind = i
185 break
186 }
187 }
188 word = s[0:ind]
189 rest = strings.TrimLeftFunc(s[ind:], unicode.IsSpace)
190 return
191 }
192
193 // readArrays reads whitespace-separated string arrays on each line. Single
194 // or double quotes can be used to escape whitespace. Hash characters can be
195 // used to add a comment until the end of line. Leading and trailing space is
196 // trimmed. Empty lines are skipped.
197 func readArrays(r io.Reader, minCols, maxCols int) ([][]string, error) {
198 var arrays [][]string
199 s := bufio.NewScanner(r)
200 for s.Scan() {
201 line := s.Text()
202
203 squote, dquote := false, false
204 for i := range len(line) {
205 if line[i] == '\'' && !dquote {
206 squote = !squote
207 } else if line[i] == '"' && !squote {
208 dquote = !dquote
209 }
210 if !squote && !dquote && line[i] == '#' {
211 line = line[:i]
212 break
213 }
214 }
215
216 line = strings.TrimSpace(line)
217
218 if line == "" {
219 continue
220 }
221
222 squote, dquote = false, false
223 arr := strings.FieldsFunc(line, func(r rune) bool {
224 if r == '\'' && !dquote {
225 squote = !squote
226 } else if r == '"' && !squote {
227 dquote = !dquote
228 }
229 return !squote && !dquote && unicode.IsSpace(r)
230 })
231 arrlen := len(arr)
232
233 if arrlen < minCols || arrlen > maxCols {
234 if minCols == maxCols {
235 return nil, fmt.Errorf("expected %d columns but found: %s", minCols, s.Text())
236 }
237 return nil, fmt.Errorf("expected %d~%d columns but found: %s", minCols, maxCols, s.Text())
238 }
239
240 for i := range arrlen {
241 squote, dquote = false, false
242 buf := make([]rune, 0, len(arr[i]))
243 for _, r := range arr[i] {
244 if r == '\'' && !dquote {
245 squote = !squote
246 continue
247 }
248 if r == '"' && !squote {
249 dquote = !dquote
250 continue
251 }
252 buf = append(buf, r)
253 }
254 arr[i] = string(buf)
255 }
256
257 arrays = append(arrays, arr)
258 }
259
260 return arrays, s.Err()
261 }
262
263 func readPairs(r io.Reader) ([][]string, error) {
264 return readArrays(r, 2, 2)
265 }
266
267 // humanize converts a size in bytes to a human-readable form using
268 // prefixes for either binary (1 KiB = 1024 B) or decimal (1 KB = 1000 B)
269 // multiples. The output should be no more than 5 characters long.
270 func humanize(size int64) string {
271 var base int64 = 1024
272 if gOpts.sizeunits == "decimal" {
273 base = 1000
274 }
275
276 if size < base {
277 return fmt.Sprintf("%dB", size)
278 }
279
280 // Note: due to [fs.FileInfo.Size] being `int64`, the maximum
281 // possible representable value would be 8 EiB or 9.2 EB.
282 prefixes := []string{
283 "K", // kibi (2^10) or kilo (10^3)
284 "M", // mebi (2^20) or mega (10^6)
285 "G", // gibi (2^30) or giga (10^9)
286 "T", // tebi (2^40) or tera (10^12)
287 "P", // pebi (2^50) or peta (10^15)
288 "E", // exbi (2^60) or exa (10^18)
289 "Z", // zebi (2^70) or zetta (10^21)
290 "Y", // yobi (2^80) or yotta (10^24)
291 "R", // robi (2^90) or ronna (10^27)
292 "Q", // quebi (2^100) or quetta (10^30)
293 }
294
295 curr := big.NewRat(size, base)
296
297 for _, prefix := range prefixes {
298 // if curr < 99.95 then round to 1 decimal place
299 if curr.Cmp(big.NewRat(9995, 100)) < 0 {
300 return fmt.Sprintf("%s%s", curr.FloatString(1), prefix)
301 }
302
303 // if curr < base-0.5 then round to the nearest integer
304 if curr.Cmp(new(big.Rat).Sub(big.NewRat(base, 1), big.NewRat(1, 2))) < 0 {
305 return fmt.Sprintf("%s%s", curr.FloatString(0), prefix)
306 }
307
308 curr.Quo(curr, big.NewRat(base, 1))
309 }
310
311 return fmt.Sprintf("+999%s", prefixes[len(prefixes)-1])
312 }
313
314 // permString returns an ls(1)-style string representation of the given file
315 // mode, to avoid using [fs.FileMode.String], which differs slightly.
316 func permString(m os.FileMode) string {
317 // re-use Perm()'s "-rwxrwxrwx" output and write type into b[0]
318 b := []byte(m.Perm().String())
319 switch {
320 case m&os.ModeSymlink != 0:
321 b[0] = 'l'
322 case m&os.ModeDir != 0:
323 b[0] = 'd'
324 case m&os.ModeNamedPipe != 0:
325 b[0] = 'p'
326 case m&os.ModeSocket != 0:
327 b[0] = 's'
328 case m&os.ModeCharDevice != 0:
329 b[0] = 'c'
330 case m&os.ModeDevice != 0:
331 b[0] = 'b'
332 default:
333 b[0] = '-'
334 }
335 // patch exec slots with suid/sgid/sticky flags
336 if m&os.ModeSetuid != 0 {
337 if b[3] == 'x' {
338 b[3] = 's'
339 } else {
340 b[3] = 'S'
341 }
342 }
343 if m&os.ModeSetgid != 0 {
344 if b[6] == 'x' {
345 b[6] = 's'
346 } else {
347 b[6] = 'S'
348 }
349 }
350 if m&os.ModeSticky != 0 {
351 if b[9] == 'x' {
352 b[9] = 't'
353 } else {
354 b[9] = 'T'
355 }
356 }
357
358 return string(b)
359 }
360
361 // naturalCmp compares two strings for natural sorting which takes into
362 // account the values of numbers in strings. For example, '2' is ordered before
363 // '10', and similarly 'foo2bar' ordered before 'foo10bar'. When comparing
364 // numbers, if they have the same value then the length of the string is also
365 // compared, so '0' is ordered before '00'.
366 func naturalCmp(s1, s2 string) int {
367 s1len := len(s1)
368 s2len := len(s2)
369
370 var lo1, lo2, hi1, hi2 int
371 for {
372 switch {
373 case hi1 >= s1len && hi2 >= s2len:
374 return 0
375 case hi1 >= s1len && hi2 < s2len:
376 return -1
377 case hi1 < s1len && hi2 >= s2len:
378 return 1
379 }
380
381 lo1 = hi1
382 isDigit1 := isDigit(s1[hi1])
383 for hi1 < s1len && isDigit(s1[hi1]) == isDigit1 {
384 hi1++
385 }
386 tok1 := s1[lo1:hi1]
387
388 lo2 = hi2
389 isDigit2 := isDigit(s2[hi2])
390 for hi2 < s2len && isDigit(s2[hi2]) == isDigit2 {
391 hi2++
392 }
393 tok2 := s2[lo2:hi2]
394
395 if isDigit1 && isDigit2 {
396 num1, err1 := strconv.Atoi(tok1)
397 num2, err2 := strconv.Atoi(tok2)
398 if err1 == nil && err2 == nil {
399 if num1 != num2 {
400 return cmp.Compare(num1, num2)
401 } else if len(tok1) != len(tok2) {
402 return cmp.Compare(len(tok1), len(tok2))
403 }
404 }
405 }
406
407 if tok1 != tok2 {
408 return cmp.Compare(tok1, tok2)
409 }
410 }
411 }
412
413 // getFileExtension returns the extension of a file with a leading dot.
414 // It returns an empty string if extension could not be determined
415 // i.e. directories, filenames without extensions
416 func getFileExtension(file fs.FileInfo) string {
417 if file.IsDir() {
418 return ""
419 }
420 if strings.Count(file.Name(), ".") == 1 && file.Name()[0] == '.' {
421 // hidden file without extension
422 return ""
423 }
424 return filepath.Ext(file.Name())
425 }
426
427 // truncateFilename truncates a filename at a given position.
428 // The position is specified as percentage indicating where the truncation
429 // character will appear (0 means left, 50 means middle, 100 means right).
430 // The file extension is not affected by truncation, however it will be clipped
431 // if it exceeds the allowed width.
432 func truncateFilename(file fs.FileInfo, maxWidth, truncatePct int, truncateChar string) string {
433 filename := sanitizeName(file.Name())
434 if displaywidth.String(filename) <= maxWidth {
435 return filename
436 }
437
438 ext := sanitizeName(getFileExtension(file))
439 avail := maxWidth - displaywidth.String(truncateChar) - displaywidth.String(ext)
440 if avail < 0 {
441 return truncateRight(truncateChar+ext, maxWidth)
442 }
443
444 basename := strings.TrimSuffix(filename, ext)
445 left := truncateRight(basename, avail*truncatePct/100)
446 right := truncateLeft(basename, avail-displaywidth.String(left))
447 return left + truncateChar + right + ext
448 }
449
450 // deletePathRecursive deletes entries from a map if the key is either the given
451 // path or a subpath of it.
452 // This is useful for clearing cached data when a directory is moved or deleted.
453 func deletePathRecursive[T any](m map[string]T, path string) {
454 delete(m, path)
455 prefix := path + string(filepath.Separator)
456 for k := range m {
457 if strings.HasPrefix(k, prefix) {
458 delete(m, k)
459 }
460 }
461 }
462
463 // readLines reads lines from a file to be displayed as a preview.
464 // The number of lines to read is capped since files can be very large.
465 // Lines are split on `\n` characters, and `\r` characters are discarded.
466 // Individual lines are truncated to avoid unbounded memory usage on files
467 // with very long or no newlines.
468 // Sixel images are also detected and stored as separate lines.
469 // C0 control bytes outside of \a \b \t \n \v \f \r \033 and DEL indicate binary content.
470 func readLines(reader io.ByteReader, maxLines int) (lines []string, binary bool, sixel bool) {
471 const maxLineBytes = 1 << 16 // 64 KiB per line
472
473 type state int
474 const (
475 stateNormal state = iota
476 stateEsc
477 stateSixel
478 stateSixelEsc
479 )
480 currState := stateNormal
481
482 var buf bytes.Buffer
483 maxLinesReached := false
484 flush := func(force bool) {
485 if buf.Len() > 0 || force {
486 lines = append(lines, buf.String())
487 }
488 buf.Reset()
489 if len(lines) >= maxLines {
490 maxLinesReached = true
491 }
492 }
493
494 for !maxLinesReached {
495 b, err := reader.ReadByte()
496 if err != nil {
497 flush(false)
498 return
499 }
500
501 switch currState {
502 case stateNormal:
503 // C0 control bytes outside of \a \b \t \n \v \f \r \033 and DEL indicate binary content.
504 if b < 0x07 || (b > 0x0D && b < 0x1B) || (b > 0x1B && b < 0x20) || b == 0x7F {
505 return nil, true, false
506 }
507 switch b {
508 case '\033':
509 currState = stateEsc
510 case '\r':
511 // filter out carriage return
512 case '\n':
513 flush(true)
514 default:
515 if buf.Len() >= maxLineBytes {
516 flush(true)
517 }
518 buf.WriteByte(b)
519 }
520 case stateEsc:
521 if b == 'P' {
522 flush(false)
523 buf.WriteString("\033P")
524 currState = stateSixel
525 } else {
526 buf.WriteByte('\033')
527 buf.WriteByte(b)
528 currState = stateNormal
529 }
530 case stateSixel:
531 // Inside the DCS frame, accept only printable bytes. Tolerate
532 // '\r'/'\n' (some encoders insert them for readability) by
533 // silently dropping them. Anything else aborts the frame so
534 // that an attacker cannot smuggle CSI/OSC/DCS through it.
535 switch {
536 case b == '\033':
537 buf.WriteByte(b)
538 currState = stateSixelEsc
539 case b == '\r' || b == '\n':
540 case b >= 0x20 && b <= 0x7E:
541 buf.WriteByte(b)
542 default:
543 buf.Reset()
544 currState = stateNormal
545 }
546 case stateSixelEsc:
547 if b == '\\' {
548 buf.WriteByte(b)
549 flush(true)
550 sixel = true
551 currState = stateNormal
552 } else {
553 buf.Reset()
554 currState = stateNormal
555 }
556 }
557 }
558
559 return
560 }
561
562 // getWidths calculates the widths of windows as the result of applying the
563 // `ratios` option to the screen width. One column is allocated for each divider
564 // between windows. When `drawbox` is enabled and `borderstyle` includes an outline,
565 // getWidths reserves two additional columns for the left and right borders.
566 func getWidths(wtot int, ratios []int, drawbox bool, borderstyle borderStyle) []int {
567 rlen := len(ratios)
568 wtot -= rlen - 1
569 if drawbox && borderstyle&borderOutline != 0 {
570 wtot -= 2
571 }
572 wtot = max(wtot, 0)
573
574 rtot := 0
575 for _, r := range ratios {
576 rtot += r
577 }
578
579 divround := func(x, y int) int {
580 return (x + y/2) / y
581 }
582
583 widths := make([]int, rlen)
584 rsum := 0
585 wsum := 0
586 for i, r := range ratios {
587 rsum += r
588 widths[i] = divround(wtot*rsum, rtot) - wsum
589 wsum += widths[i]
590 }
591
592 return widths
593 }
594
595 // We don't need no generic code
596 // We don't need no type control
597 // No dark templates in compiler
598 // Haskell leave them kids alone
599 // Hey Bjarne leave them kids alone
600 // All in all it's just another brick in the code
601 // All in all you're just another brick in the code
602 //
603 // -- Pink Trolled --