Debian Codegraph @

internal/util/util.go

raw
1 package util
2
3 import (
4 "archive/zip"
5 "bytes"
6 "crypto/md5"
7 "errors"
8 "fmt"
9 "io"
10 "io/fs"
11 "net/http"
12 "net/url"
13 "os"
14 "os/user"
15 "path/filepath"
16 "regexp"
17 "runtime"
18 "strconv"
19 "strings"
20 "time"
21 "unicode"
22 "unicode/utf8"
23
24 "github.com/blang/semver"
25 runewidth "github.com/mattn/go-runewidth"
26 )
27
28 var (
29 // These variables should be set by the linker when compiling
30
31 // Version is the version number or commit hash
32 Version = "0.0.0-unknown"
33 // SemVersion is the Semantic version
34 SemVersion semver.Version
35 // CommitHash is the commit this version was built on
36 CommitHash = "Unknown"
37 // CompileDate is the date this binary was compiled on
38 CompileDate = "Unknown"
39 // Debug logging
40 Debug = "OFF"
41 // FakeCursor is used to disable the terminal cursor and have micro
42 // draw its own (enabled for windows consoles where the cursor is slow)
43 FakeCursor = false
44
45 // Stdout is a buffer that is written to stdout when micro closes
46 Stdout *bytes.Buffer
47 // Sigterm is a channel where micro exits when written
48 Sigterm chan os.Signal
49
50 // To be used for fails on (over-)write with safe writes
51 ErrOverwrite = OverwriteError{}
52 )
53
54 // To be used for file writes before umask is applied
55 const FileMode os.FileMode = 0666
56
57 const BackupSuffix = ".micro-backup"
58
59 const OverwriteFailMsg = `An error occurred while writing to the file:
60
61 %s
62
63 The file may be corrupted now. The good news is that it has been
64 successfully backed up. Next time you open this file with Micro,
65 Micro will ask if you want to recover it from the backup.
66
67 The backup path is:
68
69 %s`
70
71 // OverwriteError is a custom error to add additional information
72 type OverwriteError struct {
73 What error
74 BackupName string
75 }
76
77 func (e OverwriteError) Error() string {
78 return fmt.Sprintf(OverwriteFailMsg, e.What, e.BackupName)
79 }
80
81 func (e OverwriteError) Is(target error) bool {
82 return target == ErrOverwrite
83 }
84
85 func (e OverwriteError) Unwrap() error {
86 return e.What
87 }
88
89 func init() {
90 var err error
91 SemVersion, err = semver.Make(Version)
92 if err != nil {
93 fmt.Println("Invalid version: ", Version, err)
94 }
95
96 _, wt := os.LookupEnv("WT_SESSION")
97 if runtime.GOOS == "windows" && !wt {
98 FakeCursor = true
99 }
100 Stdout = new(bytes.Buffer)
101 }
102
103 // SliceEnd returns a byte slice where the index is a rune index
104 // Slices off the start of the slice
105 func SliceEnd(slc []byte, index int) []byte {
106 len := len(slc)
107 i := 0
108 totalSize := 0
109 for totalSize < len {
110 if i >= index {
111 return slc[totalSize:]
112 }
113
114 _, _, size := DecodeCharacter(slc[totalSize:])
115 totalSize += size
116 i++
117 }
118
119 return slc[totalSize:]
120 }
121
122 // SliceEndStr is the same as SliceEnd but for strings
123 func SliceEndStr(str string, index int) string {
124 len := len(str)
125 i := 0
126 totalSize := 0
127 for totalSize < len {
128 if i >= index {
129 return str[totalSize:]
130 }
131
132 _, _, size := DecodeCharacterInString(str[totalSize:])
133 totalSize += size
134 i++
135 }
136
137 return str[totalSize:]
138 }
139
140 // SliceStart returns a byte slice where the index is a rune index
141 // Slices off the end of the slice
142 func SliceStart(slc []byte, index int) []byte {
143 len := len(slc)
144 i := 0
145 totalSize := 0
146 for totalSize < len {
147 if i >= index {
148 return slc[:totalSize]
149 }
150
151 _, _, size := DecodeCharacter(slc[totalSize:])
152 totalSize += size
153 i++
154 }
155
156 return slc[:totalSize]
157 }
158
159 // SliceStartStr is the same as SliceStart but for strings
160 func SliceStartStr(str string, index int) string {
161 len := len(str)
162 i := 0
163 totalSize := 0
164 for totalSize < len {
165 if i >= index {
166 return str[:totalSize]
167 }
168
169 _, _, size := DecodeCharacterInString(str[totalSize:])
170 totalSize += size
171 i++
172 }
173
174 return str[:totalSize]
175 }
176
177 // SliceVisualEnd will take a byte slice and slice off the start
178 // up to a given visual index. If the index is in the middle of a
179 // rune the number of visual columns into the rune will be returned
180 // It will also return the char pos of the first character of the slice
181 func SliceVisualEnd(b []byte, n, tabsize int) ([]byte, int, int) {
182 width := 0
183 i := 0
184 for len(b) > 0 {
185 r, _, size := DecodeCharacter(b)
186
187 w := 0
188 switch r {
189 case '\t':
190 ts := tabsize - (width % tabsize)
191 w = ts
192 default:
193 w = runewidth.RuneWidth(r)
194 }
195 if width+w > n {
196 return b, n - width, i
197 }
198 width += w
199 b = b[size:]
200 i++
201 }
202 return b, n - width, i
203 }
204
205 // Abs is a simple absolute value function for ints
206 func Abs(n int) int {
207 if n < 0 {
208 return -n
209 }
210 return n
211 }
212
213 // StringWidth returns the visual width of a byte array indexed from 0 to n (rune index)
214 // with a given tabsize
215 func StringWidth(b []byte, n, tabsize int) int {
216 if n <= 0 {
217 return 0
218 }
219 i := 0
220 width := 0
221 for len(b) > 0 {
222 r, _, size := DecodeCharacter(b)
223 b = b[size:]
224
225 switch r {
226 case '\t':
227 ts := tabsize - (width % tabsize)
228 width += ts
229 default:
230 width += runewidth.RuneWidth(r)
231 }
232
233 i++
234
235 if i == n {
236 return width
237 }
238 }
239 return width
240 }
241
242 // Min takes the min of two ints
243 func Min(a, b int) int {
244 if a > b {
245 return b
246 }
247 return a
248 }
249
250 // Max takes the max of two ints
251 func Max(a, b int) int {
252 if a > b {
253 return a
254 }
255 return b
256 }
257
258 // FSize gets the size of a file
259 func FSize(f *os.File) int64 {
260 fi, _ := f.Stat()
261 return fi.Size()
262 }
263
264 // IsWordChar returns whether or not a rune is a 'word character'
265 // Word characters are defined as numbers, letters or sub-word delimiters
266 func IsWordChar(r rune) bool {
267 return IsAlphanumeric(r) || IsSubwordDelimiter(r)
268 }
269
270 // IsNonWordChar returns whether or not a rune is not a 'word character'
271 // Non word characters are defined as all characters not being numbers, letters or sub-word delimiters
272 // See IsWordChar()
273 func IsNonWordChar(r rune) bool {
274 return !IsWordChar(r)
275 }
276
277 // IsSubwordDelimiter returns whether or not a rune is a 'sub-word delimiter character'
278 // i.e. is considered a part of the word and is used as a delimiter between sub-words of the word.
279 // For now the only sub-word delimiter character is '_'.
280 func IsSubwordDelimiter(r rune) bool {
281 return r == '_'
282 }
283
284 // IsAlphanumeric returns whether or not a rune is an 'alphanumeric character'
285 // Alphanumeric characters are defined as numbers or letters
286 func IsAlphanumeric(r rune) bool {
287 return unicode.IsLetter(r) || unicode.IsNumber(r)
288 }
289
290 // IsUpperAlphanumeric returns whether or not a rune is an 'upper alphanumeric character'
291 // Upper alphanumeric characters are defined as numbers or upper-case letters
292 func IsUpperAlphanumeric(r rune) bool {
293 return IsUpperLetter(r) || unicode.IsNumber(r)
294 }
295
296 // IsLowerAlphanumeric returns whether or not a rune is a 'lower alphanumeric character'
297 // Lower alphanumeric characters are defined as numbers or lower-case letters
298 func IsLowerAlphanumeric(r rune) bool {
299 return IsLowerLetter(r) || unicode.IsNumber(r)
300 }
301
302 // IsUpperLetter returns whether or not a rune is an 'upper letter character'
303 // Upper letter characters are defined as upper-case letters
304 func IsUpperLetter(r rune) bool {
305 // unicode.IsUpper() returns true for letters only
306 return unicode.IsUpper(r)
307 }
308
309 // IsLowerLetter returns whether or not a rune is a 'lower letter character'
310 // Lower letter characters are defined as lower-case letters
311 func IsLowerLetter(r rune) bool {
312 // unicode.IsLower() returns true for letters only
313 return unicode.IsLower(r)
314 }
315
316 // Spaces returns a string with n spaces
317 func Spaces(n int) string {
318 return strings.Repeat(" ", n)
319 }
320
321 // IsSpaces checks if a given string is only spaces
322 func IsSpaces(str []byte) bool {
323 for _, c := range str {
324 if c != ' ' {
325 return false
326 }
327 }
328
329 return true
330 }
331
332 // IsSpacesOrTabs checks if a given string contains only spaces and tabs
333 func IsSpacesOrTabs(str []byte) bool {
334 for _, c := range str {
335 if c != ' ' && c != '\t' {
336 return false
337 }
338 }
339
340 return true
341 }
342
343 // IsWhitespace returns true if the given rune is a space, tab, or newline
344 func IsWhitespace(c rune) bool {
345 return unicode.IsSpace(c)
346 }
347
348 // IsBytesWhitespace returns true if the given bytes are all whitespace
349 func IsBytesWhitespace(b []byte) bool {
350 for _, c := range b {
351 if !IsWhitespace(rune(c)) {
352 return false
353 }
354 }
355 return true
356 }
357
358 // RunePos returns the rune index of a given byte index
359 // Make sure the byte index is not between code points
360 func RunePos(b []byte, i int) int {
361 return CharacterCount(b[:i])
362 }
363
364 // IndexAnyUnquoted returns the first position in s of a character from chars.
365 // Escaped (with backslash) and quoted (with single or double quotes) characters
366 // are ignored. Returns -1 if not successful
367 func IndexAnyUnquoted(s, chars string) int {
368 var e bool
369 var q rune
370 for i, r := range s {
371 if e {
372 e = false
373 } else if (q == 0 || q == '"') && r == '\\' {
374 e = true
375 } else if r == q {
376 q = 0
377 } else if q == 0 && (r == '\'' || r == '"') {
378 q = r
379 } else if q == 0 && strings.IndexRune(chars, r) >= 0 {
380 return i
381 }
382 }
383 return -1
384 }
385
386 // MakeRelative will attempt to make a relative path between path and base
387 func MakeRelative(path, base string) (string, error) {
388 if len(path) > 0 {
389 rel, err := filepath.Rel(base, path)
390 if err != nil {
391 return path, err
392 }
393 return rel, nil
394 }
395 return path, nil
396 }
397
398 // ReplaceHome takes a path as input and replaces ~ at the start of the path with the user's
399 // home directory. Does nothing if the path does not start with '~'.
400 func ReplaceHome(path string) (string, error) {
401 if !strings.HasPrefix(path, "~") {
402 return path, nil
403 }
404
405 var userData *user.User
406 var err error
407
408 homeString := strings.Split(path, "/")[0]
409 if homeString == "~" {
410 userData, err = user.Current()
411 if err != nil {
412 return "", errors.New("Could not find user: " + err.Error())
413 }
414 } else {
415 userData, err = user.Lookup(homeString[1:])
416 if err != nil {
417 return "", errors.New("Could not find user: " + err.Error())
418 }
419 }
420
421 home := userData.HomeDir
422
423 return strings.Replace(path, homeString, home, 1), nil
424 }
425
426 // GetPathAndCursorPosition returns a filename without everything following a `:`
427 // This is used for opening files like util.go:10:5 to specify a line and column
428 // Special cases like Windows Absolute path (C:\myfile.txt:10:5) are handled correctly.
429 func GetPathAndCursorPosition(path string) (string, []string) {
430 re := regexp.MustCompile(`([\s\S]+?)(?::(\d+))(?::(\d+))?$`)
431 match := re.FindStringSubmatch(path)
432 // no lines/columns were specified in the path, return just the path with no cursor location
433 if len(match) == 0 {
434 return path, nil
435 } else if match[len(match)-1] != "" {
436 // if the last capture group match isn't empty then both line and column were provided
437 return match[1], match[2:]
438 }
439 // if it was empty, then only a line was provided, so default to column 0
440 return match[1], []string{match[2], "0"}
441 }
442
443 // GetModTime returns the last modification time for a given file
444 func GetModTime(path string) (time.Time, error) {
445 info, err := os.Stat(path)
446 if err != nil {
447 return time.Now(), err
448 }
449 return info.ModTime(), nil
450 }
451
452 func HashStringMd5(str string) string {
453 return fmt.Sprintf("%x", md5.Sum([]byte(str)))
454 }
455
456 // EscapePathUrl encodes the path in URL query form
457 func EscapePathUrl(path string) string {
458 return url.QueryEscape(filepath.ToSlash(path))
459 }
460
461 // EscapePathLegacy replaces every path separator in a given path with a %
462 func EscapePathLegacy(path string) string {
463 path = filepath.ToSlash(path)
464 if runtime.GOOS == "windows" {
465 // ':' is not valid in a path name on Windows but is ok on Unix
466 path = strings.ReplaceAll(path, ":", "%")
467 }
468 return strings.ReplaceAll(path, "/", "%")
469 }
470
471 // DetermineEscapePath escapes a path, determining whether it should be escaped
472 // using URL encoding (preferred, since it encodes unambiguously) or
473 // legacy encoding with '%' (for backward compatibility, if the legacy-escaped
474 // path exists in the given directory).
475 // In case the length of the escaped path (plus the backup extension) exceeds
476 // the filename length limit, a hash of the path is returned instead. In such
477 // case the second return value is the name of a file the original path should
478 // be saved to (since the original path cannot be derived from its hash).
479 // Otherwise the second return value is an empty string.
480 func DetermineEscapePath(dir string, path string) (string, string) {
481 url := filepath.Join(dir, EscapePathUrl(path))
482 if _, err := os.Stat(url); err == nil {
483 return url, ""
484 }
485
486 legacy := filepath.Join(dir, EscapePathLegacy(path))
487 if _, err := os.Stat(legacy); err == nil {
488 return legacy, ""
489 }
490
491 if len(url)+len(BackupSuffix) > 255 {
492 hash := HashStringMd5(path)
493 return filepath.Join(dir, hash), filepath.Join(dir, hash+".path")
494 }
495
496 return url, ""
497 }
498
499 // GetLeadingWhitespace returns the leading whitespace of the given byte array
500 func GetLeadingWhitespace(b []byte) []byte {
501 ws := []byte{}
502 for len(b) > 0 {
503 r, _, size := DecodeCharacter(b)
504 if r == ' ' || r == '\t' {
505 ws = append(ws, byte(r))
506 } else {
507 break
508 }
509
510 b = b[size:]
511 }
512 return ws
513 }
514
515 // GetTrailingWhitespace returns the trailing whitespace of the given byte array
516 func GetTrailingWhitespace(b []byte) []byte {
517 ws := []byte{}
518 for len(b) > 0 {
519 r, size := utf8.DecodeLastRune(b)
520 if IsWhitespace(r) {
521 ws = append([]byte(string(r)), ws...)
522 } else {
523 break
524 }
525
526 b = b[:len(b)-size]
527 }
528 return ws
529 }
530
531 // HasTrailingWhitespace returns true if the given byte array ends with a whitespace
532 func HasTrailingWhitespace(b []byte) bool {
533 r, _ := utf8.DecodeLastRune(b)
534 return IsWhitespace(r)
535 }
536
537 // IntOpt turns a float64 setting to an int
538 func IntOpt(opt any) int {
539 return int(opt.(float64))
540 }
541
542 // GetCharPosInLine gets the char position of a visual x y
543 // coordinate (this is necessary because tabs are 1 char but
544 // 4 visual spaces)
545 func GetCharPosInLine(b []byte, visualPos int, tabsize int) int {
546 // Scan rune by rune until we exceed the visual width that we are
547 // looking for. Then we can return the character position we have found
548 i := 0 // char pos
549 width := 0 // string visual width
550 for len(b) > 0 {
551 r, _, size := DecodeCharacter(b)
552 b = b[size:]
553
554 switch r {
555 case '\t':
556 ts := tabsize - (width % tabsize)
557 width += ts
558 default:
559 width += runewidth.RuneWidth(r)
560 }
561
562 if width >= visualPos {
563 if width == visualPos {
564 i++
565 }
566 break
567 }
568 i++
569 }
570
571 return i
572 }
573
574 // ParseBool is almost exactly like strconv.ParseBool, except it also accepts 'on' and 'off'
575 // as 'true' and 'false' respectively
576 func ParseBool(str string) (bool, error) {
577 if str == "on" {
578 return true, nil
579 }
580 if str == "off" {
581 return false, nil
582 }
583 return strconv.ParseBool(str)
584 }
585
586 // Clamp clamps a value between min and max
587 func Clamp(val, min, max int) int {
588 if val < min {
589 val = min
590 } else if val > max {
591 val = max
592 }
593 return val
594 }
595
596 // IsAutocomplete returns whether a character should begin an autocompletion.
597 func IsAutocomplete(c rune) bool {
598 return c == '.' || IsWordChar(c)
599 }
600
601 // String converts a byte array to a string (for lua plugins)
602 func String(s []byte) string {
603 return string(s)
604 }
605
606 // Unzip unzips a file to given folder
607 func Unzip(src, dest string) error {
608 r, err := zip.OpenReader(src)
609 if err != nil {
610 return err
611 }
612 defer r.Close()
613
614 os.MkdirAll(dest, 0755)
615
616 // Closure to address file descriptors issue with all the deferred .Close() methods
617 extractAndWriteFile := func(f *zip.File) error {
618 rc, err := f.Open()
619 if err != nil {
620 return err
621 }
622 defer rc.Close()
623
624 path := filepath.Join(dest, f.Name)
625
626 // Check for ZipSlip (Directory traversal)
627 if !strings.HasPrefix(path, filepath.Clean(dest)+string(os.PathSeparator)) {
628 return fmt.Errorf("illegal file path: %s", path)
629 }
630
631 if f.FileInfo().IsDir() {
632 os.MkdirAll(path, f.Mode())
633 } else {
634 os.MkdirAll(filepath.Dir(path), f.Mode())
635 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
636 if err != nil {
637 return err
638 }
639 defer f.Close()
640
641 _, err = io.Copy(f, rc)
642 if err != nil {
643 return err
644 }
645 }
646 return nil
647 }
648
649 for _, f := range r.File {
650 err := extractAndWriteFile(f)
651 if err != nil {
652 return err
653 }
654 }
655
656 return nil
657 }
658
659 // HttpRequest returns a new http.Client for making custom requests (for lua plugins)
660 func HttpRequest(method string, url string, headers []string) (resp *http.Response, err error) {
661 client := http.Client{}
662 req, err := http.NewRequest(method, url, nil)
663 if err != nil {
664 return nil, err
665 }
666 for i := 0; i < len(headers); i += 2 {
667 req.Header.Add(headers[i], headers[i+1])
668 }
669 return client.Do(req)
670 }
671
672 // SafeWrite writes bytes to a file in a "safe" way, preventing loss of the
673 // contents of the file if it fails to write the new contents.
674 // This means that the file is not overwritten directly but by writing to a
675 // temporary file first.
676 //
677 // If rename is true, write is performed atomically, by renaming the temporary
678 // file to the target file after the data is successfully written to the
679 // temporary file. This guarantees that the file will not remain in a corrupted
680 // state, but it also has limitations, e.g. the file should not be a symlink
681 // (otherwise SafeWrite silently replaces this symlink with a regular file),
682 // the file creation date in Linux is not preserved (since the file inode
683 // changes) etc. Use SafeWrite with rename=true for files that are only created
684 // and used by micro for its own needs and are not supposed to be used directly
685 // by the user.
686 //
687 // If rename is false, write is performed by overwriting the target file after
688 // the data is successfully written to the temporary file.
689 // This means that the target file may remain corrupted if overwrite fails,
690 // but in such case the temporary file is preserved as a backup so the file
691 // can be recovered later. So it is less convenient than atomic write but more
692 // universal. Use SafeWrite with rename=false for files that may be managed
693 // directly by the user, like settings.json and bindings.json.
694 func SafeWrite(path string, bytes []byte, rename bool) error {
695 var err error
696 if _, err = os.Stat(path); err != nil {
697 if !errors.Is(err, fs.ErrNotExist) {
698 return err
699 }
700 // Force rename for new files!
701 rename = true
702 }
703
704 var file *os.File
705 if !rename {
706 file, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE, FileMode)
707 if err != nil {
708 return err
709 }
710 defer file.Close()
711 }
712
713 tmp := path + BackupSuffix
714 err = os.WriteFile(tmp, bytes, FileMode)
715 if err != nil {
716 os.Remove(tmp)
717 return err
718 }
719
720 if rename {
721 err = os.Rename(tmp, path)
722 } else {
723 err = file.Truncate(0)
724 if err == nil {
725 _, err = file.Write(bytes)
726 }
727 if err == nil {
728 err = file.Sync()
729 }
730 }
731 if err != nil {
732 if rename {
733 os.Remove(tmp)
734 } else {
735 err = OverwriteError{err, tmp}
736 }
737 return err
738 }
739
740 if !rename {
741 os.Remove(tmp)
742 }
743 return nil
744 }