Something went wrong. Try again.
Fork of micro-editor/micro
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771package util
import ( "archive/zip" "bytes" "crypto/md5" "errors" "fmt" "io" "io/fs" "net/http" "net/url" "os" "os/user" "path/filepath" "regexp" "runtime" "strconv" "strings" "time" "unicode" "unicode/utf8"
"github.com/blang/semver" runewidth "github.com/mattn/go-runewidth")
var ( // These variables should be set by the linker when compiling
// Version is the version number or commit hash Version = "0.0.0-unknown" // SemVersion is the Semantic version SemVersion semver.Version // CommitHash is the commit this version was built on CommitHash = "Unknown" // CompileDate is the date this binary was compiled on CompileDate = "Unknown" // Debug logging Debug = "OFF"
// Stdout is a buffer that is written to stdout when micro closes Stdout *bytes.Buffer // Sigterm is a channel where micro exits when written Sigterm chan os.Signal
// To be used for fails on (over-)write with safe writes ErrOverwrite = OverwriteError{})
// To be used for file writes before umask is appliedconst FileMode os.FileMode = 0666
const BackupSuffix = ".micro-backup"
const OverwriteFailMsg = `An error occurred while writing to the file:
%s
The file may be corrupted now. The good news is that it has beensuccessfully backed up. Next time you open this file with Micro,Micro will ask if you want to recover it from the backup.
The backup path is:
%s`
// OverwriteError is a custom error to add additional informationtype OverwriteError struct { What error BackupName string}
func (e OverwriteError) Error() string { return fmt.Sprintf(OverwriteFailMsg, e.What, e.BackupName)}
func (e OverwriteError) Is(target error) bool { return target == ErrOverwrite}
func (e OverwriteError) Unwrap() error { return e.What}
func init() { var err error SemVersion, err = semver.Make(Version) if err != nil { fmt.Println("Invalid version: ", Version, err) }
Stdout = new(bytes.Buffer)}
// SliceEnd returns a byte slice where the index is a rune index// Slices off the start of the slicefunc SliceEnd(slc []byte, index int) []byte { len := len(slc) i := 0 totalSize := 0 for totalSize < len { if i >= index { return slc[totalSize:] }
_, _, size := DecodeCharacter(slc[totalSize:]) totalSize += size i++ }
return slc[totalSize:]}
// SliceEndStr is the same as SliceEnd but for stringsfunc SliceEndStr(str string, index int) string { len := len(str) i := 0 totalSize := 0 for totalSize < len { if i >= index { return str[totalSize:] }
_, _, size := DecodeCharacterInString(str[totalSize:]) totalSize += size i++ }
return str[totalSize:]}
// SliceStart returns a byte slice where the index is a rune index// Slices off the end of the slicefunc SliceStart(slc []byte, index int) []byte { len := len(slc) i := 0 totalSize := 0 for totalSize < len { if i >= index { return slc[:totalSize] }
_, _, size := DecodeCharacter(slc[totalSize:]) totalSize += size i++ }
return slc[:totalSize]}
// SliceStartStr is the same as SliceStart but for stringsfunc SliceStartStr(str string, index int) string { len := len(str) i := 0 totalSize := 0 for totalSize < len { if i >= index { return str[:totalSize] }
_, _, size := DecodeCharacterInString(str[totalSize:]) totalSize += size i++ }
return str[:totalSize]}
// SliceVisualEnd will take a byte slice and slice off the start// up to a given visual index. If the index is in the middle of a// rune the number of visual columns into the rune will be returned// It will also return the char pos of the first character of the slicefunc SliceVisualEnd(b []byte, n, tabsize int) ([]byte, int, int) { width := 0 i := 0 for len(b) > 0 { r, _, size := DecodeCharacter(b)
w := 0 switch r { case '\t': ts := tabsize - (width % tabsize) w = ts default: w = runewidth.RuneWidth(r) } if width+w > n { return b, n - width, i } width += w b = b[size:] i++ } return b, n - width, i}
// Abs is a simple absolute value function for intsfunc Abs(n int) int { if n < 0 { return -n } return n}
// StringWidth returns the visual width of a byte array indexed from 0 to n (rune index)// with a given tabsizefunc StringWidth(b []byte, n, tabsize int) int { if n <= 0 { return 0 } i := 0 width := 0 for len(b) > 0 { r, _, size := DecodeCharacter(b) b = b[size:]
switch r { case '\t': ts := tabsize - (width % tabsize) width += ts default: width += runewidth.RuneWidth(r) }
i++
if i == n { return width } } return width}
// Min takes the min of two intsfunc Min(a, b int) int { if a > b { return b } return a}
// Max takes the max of two intsfunc Max(a, b int) int { if a > b { return a } return b}
// FSize gets the size of a filefunc FSize(f *os.File) int64 { fi, _ := f.Stat() return fi.Size()}
// IsWordChar returns whether or not a rune is a 'word character'// Word characters are defined as numbers, letters or sub-word delimitersfunc IsWordChar(r rune) bool { return IsAlphanumeric(r) || IsSubwordDelimiter(r)}
// IsNonWordChar returns whether or not a rune is not a 'word character'// Non word characters are defined as all characters not being numbers, letters or sub-word delimiters// See IsWordChar()func IsNonWordChar(r rune) bool { return !IsWordChar(r)}
// IsSubwordDelimiter returns whether or not a rune is a 'sub-word delimiter character'// i.e. is considered a part of the word and is used as a delimiter between sub-words of the word.// For now the only sub-word delimiter character is '_'.func IsSubwordDelimiter(r rune) bool { return r == '_'}
// IsAlphanumeric returns whether or not a rune is an 'alphanumeric character'// Alphanumeric characters are defined as numbers or lettersfunc IsAlphanumeric(r rune) bool { return unicode.IsLetter(r) || unicode.IsNumber(r)}
// IsUpperAlphanumeric returns whether or not a rune is an 'upper alphanumeric character'// Upper alphanumeric characters are defined as numbers or upper-case lettersfunc IsUpperAlphanumeric(r rune) bool { return IsUpperLetter(r) || unicode.IsNumber(r)}
// IsLowerAlphanumeric returns whether or not a rune is a 'lower alphanumeric character'// Lower alphanumeric characters are defined as numbers or lower-case lettersfunc IsLowerAlphanumeric(r rune) bool { return IsLowerLetter(r) || unicode.IsNumber(r)}
// IsUpperLetter returns whether or not a rune is an 'upper letter character'// Upper letter characters are defined as upper-case lettersfunc IsUpperLetter(r rune) bool { // unicode.IsUpper() returns true for letters only return unicode.IsUpper(r)}
// IsLowerLetter returns whether or not a rune is a 'lower letter character'// Lower letter characters are defined as lower-case lettersfunc IsLowerLetter(r rune) bool { // unicode.IsLower() returns true for letters only return unicode.IsLower(r)}
// Spaces returns a string with n spacesfunc Spaces(n int) string { return strings.Repeat(" ", n)}
// IsSpaces checks if a given string is only spacesfunc IsSpaces(str []byte) bool { for _, c := range str { if c != ' ' { return false } }
return true}
// IsSpacesOrTabs checks if a given string contains only spaces and tabsfunc IsSpacesOrTabs(str []byte) bool { for _, c := range str { if c != ' ' && c != '\t' { return false } }
return true}
// IsWhitespace returns true if the given rune is a space, tab, or newlinefunc IsWhitespace(c rune) bool { return unicode.IsSpace(c)}
// IsBytesWhitespace returns true if the given bytes are all whitespacefunc IsBytesWhitespace(b []byte) bool { for _, c := range b { if !IsWhitespace(rune(c)) { return false } } return true}
// RunePos returns the rune index of a given byte index// Make sure the byte index is not between code pointsfunc RunePos(b []byte, i int) int { return CharacterCount(b[:i])}
// IndexAnyUnquoted returns the first position in s of a character from chars.// Escaped (with backslash) and quoted (with single or double quotes) characters// are ignored. Returns -1 if not successfulfunc IndexAnyUnquoted(s, chars string) int { var e bool var q rune for i, r := range s { if e { e = false } else if (q == 0 || q == '"') && r == '\\' { e = true } else if r == q { q = 0 } else if q == 0 && (r == '\'' || r == '"') { q = r } else if q == 0 && strings.IndexRune(chars, r) >= 0 { return i } } return -1}
// MakeRelative will attempt to make a relative path between path and basefunc MakeRelative(path, base string) (string, error) { if len(path) > 0 { rel, err := filepath.Rel(base, path) if err != nil { return path, err } return rel, nil } return path, nil}
// ReplaceHome takes a path as input and replaces ~ at the start of the path with the user's// home directory. Does nothing if the path does not start with '~'.func ReplaceHome(path string) (string, error) { if !strings.HasPrefix(path, "~") { return path, nil }
var userData *user.User var err error
homeString := strings.Split(path, "/")[0] if homeString == "~" { userData, err = user.Current() if err != nil { return "", errors.New("Could not find user: " + err.Error()) } } else { userData, err = user.Lookup(homeString[1:]) if err != nil { return "", errors.New("Could not find user: " + err.Error()) } }
home := userData.HomeDir
return strings.Replace(path, homeString, home, 1), nil}
// GetPathAndCursorPosition returns a filename without everything following a `:`// This is used for opening files like util.go:10:5 to specify a line and column// Special cases like Windows Absolute path (C:\myfile.txt:10:5) are handled correctly.func GetPathAndCursorPosition(path string) (string, []string) { re := regexp.MustCompile(`([\s\S]+?)(?::(\d+))(?::(\d+))?$`) match := re.FindStringSubmatch(path) // no lines/columns were specified in the path, return just the path with no cursor location if len(match) == 0 { return path, nil } else if match[len(match)-1] != "" { // if the last capture group match isn't empty then both line and column were provided return match[1], match[2:] } // if it was empty, then only a line was provided, so default to column 0 return match[1], []string{match[2], "0"}}
// GetModTime returns the last modification time for a given filefunc GetModTime(path string) (time.Time, error) { info, err := os.Stat(path) if err != nil { return time.Now(), err } return info.ModTime(), nil}
func HashStringMd5(str string) string { return fmt.Sprintf("%x", md5.Sum([]byte(str)))}
// EscapePathUrl encodes the path in URL query formfunc EscapePathUrl(path string) string { return url.QueryEscape(filepath.ToSlash(path))}
// EscapePathLegacy replaces every path separator in a given path with a %func EscapePathLegacy(path string) string { path = filepath.ToSlash(path) if runtime.GOOS == "windows" { // ':' is not valid in a path name on Windows but is ok on Unix path = strings.ReplaceAll(path, ":", "%") } return strings.ReplaceAll(path, "/", "%")}
// DetermineEscapePath escapes a path, determining whether it should be escaped// using URL encoding (preferred, since it encodes unambiguously) or// legacy encoding with '%' (for backward compatibility, if the legacy-escaped// path exists in the given directory).// In case the length of the escaped path (plus the backup extension) exceeds// the filename length limit, a hash of the path is returned instead. In such// case the second return value is the name of a file the original path should// be saved to (since the original path cannot be derived from its hash).// Otherwise the second return value is an empty string.func DetermineEscapePath(dir string, path string) (string, string) { url := filepath.Join(dir, EscapePathUrl(path)) if _, err := os.Stat(url); err == nil { return url, "" }
legacy := filepath.Join(dir, EscapePathLegacy(path)) if _, err := os.Stat(legacy); err == nil { return legacy, "" }
if len(url)+len(BackupSuffix) > 255 { hash := HashStringMd5(path) return filepath.Join(dir, hash), filepath.Join(dir, hash+".path") }
return url, ""}
// ResolvePath provides the absolute file path for the given relative file path// as well as resolves symlinks. If it fails to get the absolute path or to// resolve symlinks, it returns unresolved path in place of resolved one.func ResolvePath(path string) string { absPath, err := filepath.Abs(path) if err != nil { absPath = path }
var remainder []string for { resolvedPath, err := filepath.EvalSymlinks(absPath) if err == nil { absPath = resolvedPath break } if !errors.Is(err, fs.ErrNotExist) { break }
remainder = append([]string{filepath.Base(absPath)}, remainder...) absPath = filepath.Dir(absPath) }
if len(remainder) > 0 { remainder = append([]string{absPath}, remainder...) absPath = filepath.Join(remainder...) absPath = filepath.Clean(absPath) }
return absPath}
// GetLeadingWhitespace returns the leading whitespace of the given byte arrayfunc GetLeadingWhitespace(b []byte) []byte { ws := []byte{} for len(b) > 0 { r, _, size := DecodeCharacter(b) if r == ' ' || r == '\t' { ws = append(ws, byte(r)) } else { break }
b = b[size:] } return ws}
// GetTrailingWhitespace returns the trailing whitespace of the given byte arrayfunc GetTrailingWhitespace(b []byte) []byte { ws := []byte{} for len(b) > 0 { r, size := utf8.DecodeLastRune(b) if IsWhitespace(r) { ws = append([]byte(string(r)), ws...) } else { break }
b = b[:len(b)-size] } return ws}
// HasTrailingWhitespace returns true if the given byte array ends with a whitespacefunc HasTrailingWhitespace(b []byte) bool { r, _ := utf8.DecodeLastRune(b) return IsWhitespace(r)}
// IntOpt turns a float64 setting to an intfunc IntOpt(opt any) int { return int(opt.(float64))}
// GetCharPosInLine gets the char position of a visual x y// coordinate (this is necessary because tabs are 1 char but// 4 visual spaces)func GetCharPosInLine(b []byte, visualPos int, tabsize int) int { // Scan rune by rune until we exceed the visual width that we are // looking for. Then we can return the character position we have found i := 0 // char pos width := 0 // string visual width for len(b) > 0 { r, _, size := DecodeCharacter(b) b = b[size:]
switch r { case '\t': ts := tabsize - (width % tabsize) width += ts default: width += runewidth.RuneWidth(r) }
if width >= visualPos { if width == visualPos { i++ } break } i++ }
return i}
// ParseBool is almost exactly like strconv.ParseBool, except it also accepts 'on' and 'off'// as 'true' and 'false' respectivelyfunc ParseBool(str string) (bool, error) { if str == "on" { return true, nil } if str == "off" { return false, nil } return strconv.ParseBool(str)}
// Clamp clamps a value between min and maxfunc Clamp(val, min, max int) int { if val < min { val = min } else if val > max { val = max } return val}
// IsAutocomplete returns whether a character should begin an autocompletion.func IsAutocomplete(c rune) bool { return c == '.' || IsWordChar(c)}
// String converts a byte array to a string (for lua plugins)func String(s []byte) string { return string(s)}
// Unzip unzips a file to given folderfunc Unzip(src, dest string) error { r, err := zip.OpenReader(src) if err != nil { return err } defer r.Close()
os.MkdirAll(dest, 0755)
// Closure to address file descriptors issue with all the deferred .Close() methods extractAndWriteFile := func(f *zip.File) error { rc, err := f.Open() if err != nil { return err } defer rc.Close()
path := filepath.Join(dest, f.Name)
// Check for ZipSlip (Directory traversal) if !strings.HasPrefix(path, filepath.Clean(dest)+string(os.PathSeparator)) { return fmt.Errorf("illegal file path: %s", path) }
if f.FileInfo().IsDir() { os.MkdirAll(path, f.Mode()) } else { os.MkdirAll(filepath.Dir(path), f.Mode()) f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { return err } defer f.Close()
_, err = io.Copy(f, rc) if err != nil { return err } } return nil }
for _, f := range r.File { err := extractAndWriteFile(f) if err != nil { return err } }
return nil}
// HttpRequest returns a new http.Client for making custom requests (for lua plugins)func HttpRequest(method string, url string, headers []string) (resp *http.Response, err error) { client := http.Client{} req, err := http.NewRequest(method, url, nil) if err != nil { return nil, err } for i := 0; i < len(headers); i += 2 { req.Header.Add(headers[i], headers[i+1]) } return client.Do(req)}
// SafeWrite writes bytes to a file in a "safe" way, preventing loss of the// contents of the file if it fails to write the new contents.// This means that the file is not overwritten directly but by writing to a// temporary file first.//// If rename is true, write is performed atomically, by renaming the temporary// file to the target file after the data is successfully written to the// temporary file. This guarantees that the file will not remain in a corrupted// state, but it also has limitations, e.g. the file should not be a symlink// (otherwise SafeWrite silently replaces this symlink with a regular file),// the file creation date in Linux is not preserved (since the file inode// changes) etc. Use SafeWrite with rename=true for files that are only created// and used by micro for its own needs and are not supposed to be used directly// by the user.//// If rename is false, write is performed by overwriting the target file after// the data is successfully written to the temporary file.// This means that the target file may remain corrupted if overwrite fails,// but in such case the temporary file is preserved as a backup so the file// can be recovered later. So it is less convenient than atomic write but more// universal. Use SafeWrite with rename=false for files that may be managed// directly by the user, like settings.json and bindings.json.func SafeWrite(path string, bytes []byte, rename bool) error { var err error if _, err = os.Stat(path); err != nil { if !errors.Is(err, fs.ErrNotExist) { return err } // Force rename for new files! rename = true }
var file *os.File if !rename { file, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE, FileMode) if err != nil { return err } defer file.Close() }
tmp := path + BackupSuffix err = os.WriteFile(tmp, bytes, FileMode) if err != nil { os.Remove(tmp) return err }
if rename { err = os.Rename(tmp, path) } else { err = file.Truncate(0) if err == nil { _, err = file.Write(bytes) } if err == nil { err = file.Sync() } } if err != nil { if rename { os.Remove(tmp) } else { err = OverwriteError{err, tmp} } return err }
if !rename { os.Remove(tmp) } return nil}