utils

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 31, 2024 License: GPL-3.0 Imports: 41 Imported by: 0

Documentation

Overview

License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>

Index

Constants

View Source
const (
	ESCAPE_CODE_SAFE_ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ "
	HUMAN_ALPHABET            = "23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
View Source
const (
	DEFAULT_IO_BUFFER_SIZE = 8192
)

Variables

View Source
var CacheDir = sync.OnceValue(func() (cache_dir string) {
	candidate := ""
	if edir := os.Getenv("KITTY_CACHE_DIRECTORY"); edir != "" {
		candidate = Abspath(Expanduser(edir))
	} else if runtime.GOOS == "darwin" {
		candidate = Expanduser("~/Library/Caches/kitty")
	} else {
		candidate = os.Getenv("XDG_CACHE_HOME")
		if candidate == "" {
			candidate = "~/.cache"
		}
		candidate = filepath.Join(Expanduser(candidate), "kitty")
	}
	_ = os.MkdirAll(candidate, 0o755)
	return candidate
})
View Source
var ConfigDir = sync.OnceValue(func() (config_dir string) {
	return ConfigDirForName("kitty.conf")
})
View Source
var DefaultExeSearchPaths = sync.OnceValue(func() []string {
	candidates := [...]string{"/usr/local/bin", "/opt/bin", "/opt/homebrew/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"}
	ans := make([]string, 0, len(candidates))
	for _, x := range candidates {
		if s, err := os.Stat(x); err == nil && s.IsDir() {
			ans = append(ans, x)
		}
	}
	return ans
})
View Source
var Hostname = sync.OnceValue(func() string {
	h, err := os.Hostname()
	if err == nil {
		return h
	}
	return ""
})
View Source
var KittyExe = sync.OnceValue(func() string {
	if kitty_pid := os.Getenv("KITTY_PID"); kitty_pid != "" {
		if kp, err := strconv.Atoi(kitty_pid); err == nil {
			if p, err := process.NewProcess(int32(kp)); err == nil {
				if exe, err := p.Exe(); err == nil && filepath.IsAbs(exe) && filepath.Base(exe) == "kitty" {
					return exe
				}
			}
		}
	}
	if exe, err := os.Executable(); err == nil {
		ans := filepath.Join(filepath.Dir(exe), "kitty")
		if s, err := os.Stat(ans); err == nil && !s.IsDir() {
			return ans
		}
	}
	return os.Getenv("KITTY_PATH_TO_KITTY_EXE")
})
View Source
var RuntimeDir = sync.OnceValue(func() (runtime_dir string) {
	var candidate string
	if q := os.Getenv("KITTY_RUNTIME_DIRECTORY"); q != "" {
		candidate = q
	} else if runtime.GOOS == "darwin" {
		candidate = macos_user_cache_dir()
	} else if q := os.Getenv("XDG_RUNTIME_DIR"); q != "" {
		candidate = q
	}
	candidate = strings.TrimRight(candidate, "/")
	if candidate == "" {
		q := fmt.Sprintf("/run/user/%d", os.Geteuid())
		if s, err := os.Stat(q); err == nil && s.IsDir() && unix.Access(q, unix.X_OK|unix.R_OK|unix.W_OK) == nil {
			candidate = q
		} else {
			candidate = filepath.Join(CacheDir(), "run")
		}
	}
	os.MkdirAll(candidate, 0o700)
	if s, err := os.Stat(candidate); err == nil && s.Mode().Perm() != 0o700 {
		os.Chmod(candidate, 0o700)
	}
	return candidate
})
View Source
var UserMimeMap = sync.OnceValue(func() map[string]string {
	conf_path := filepath.Join(ConfigDir(), "mime.types")
	ans := make(map[string]string, 32)
	err := load_mime_file(conf_path, ans)
	if err != nil && !errors.Is(err, fs.ErrNotExist) {
		fmt.Fprintln(os.Stderr, "Failed to parse", conf_path, "for MIME types with error:", err)
	}
	return ans
})

Functions

func Abs

func Abs[T constraints.Integer](x T) T

func Abspath

func Abspath(path string) string
func AtomicCreateSymlink(oldname, newname string) (err error)

func AtomicUpdateFile

func AtomicUpdateFile(path string, data io.Reader, perms ...fs.FileMode) (err error)

func AtomicWriteFile

func AtomicWriteFile(path string, data io.Reader, perm os.FileMode) (err error)

func Capitalize

func Capitalize(x string) string

func Commonpath

func Commonpath(paths ...string) (longest_prefix string)

Longest common path. Must be passed paths that have been cleaned by filepath.Clean

func Compile

func Compile(pat string) (*regexp.Regexp, error)

func Concat

func Concat[T any](slices ...[]T) []T

func ConfigDirForName

func ConfigDirForName(name string) (config_dir string)

func CreateAnonymousTemp

func CreateAnonymousTemp(dir string, perms ...fs.FileMode) (*os.File, error)

func CurrentUser

func CurrentUser() (ans *user.User, err error)

func DownloadAsSlice

func DownloadAsSlice(url string, progress_callback ReportFunc) (data []byte, err error)

func DownloadToFile

func DownloadToFile(destpath, url string, progress_callback ReportFunc, temp_file_path_callback func(string)) error

func DownloadToWriter

func DownloadToWriter(url string, dest io.Writer, progress_callback ReportFunc) error

func EncodeUtf8

func EncodeUtf8(ch UTF8State, dest []byte) int

func EscapeSHMetaCharacters

func EscapeSHMetaCharacters(x string) string

Escapes common shell meta characters

func Expanduser

func Expanduser(path string) string

func ExtractAllFromTar

func ExtractAllFromTar(tr *tar.Reader, dest_path string, optss ...TarExtractOptions) (count int, err error)

func Filter

func Filter[T any](s []T, f func(x T) bool) []T

func FindExe

func FindExe(name string) string

func FunctionName

func FunctionName(a any) string

func GuessMimeType

func GuessMimeType(filename string) string

func GuessMimeTypeWithFileSystemAccess

func GuessMimeTypeWithFileSystemAccess(filename string) string

func HumanRandomId

func HumanRandomId(num_bits int64) (string, error)

func HumanUUID4

func HumanUUID4() (string, error)

func ISO8601Format

func ISO8601Format(x time.Time) string

func ISO8601Parse

func ISO8601Parse(raw string) (time.Time, error)

func IfElse

func IfElse[T any](condition bool, if_val T, else_val T) T

func Keys

func Keys[M ~map[K]V, K comparable, V any](m M) []K

func LevenshteinDistance

func LevenshteinDistance(s, t string, ignore_case bool) int

compares two strings and returns the Levenshtein distance between them.

func LockFileExclusive

func LockFileExclusive(f *os.File) error

func LockFileShared

func LockFileShared(f *os.File) error

func LoginShellForCurrentUser

func LoginShellForCurrentUser() (ans string, err error)

func LoginShellForUser

func LoginShellForUser(u *user.User) (ans string, err error)

func LongestCommon

func LongestCommon(next func() (string, bool), prefix bool) string

func Map

func Map[T any, O any](f func(x T) O, s []T) []O

func Max

func Max[T constraints.Ordered](a T, items ...T) (ans T)

func Memset

func Memset[T any](dest []T, pattern ...T) []T

func Min

func Min[T constraints.Ordered](a T, items ...T) (ans T)

func MonotonicRaw

func MonotonicRaw() (time.Time, error)

func MustCompile

func MustCompile(pat string) *regexp.Regexp

func ParsePasswdDatabase

func ParsePasswdDatabase(raw string) (ans map[string]PasswdEntry)

func ParsePasswdFile

func ParsePasswdFile(path string) (ans map[string]PasswdEntry, err error)

func ParseSocketAddress

func ParseSocketAddress(spec string) (network string, addr string, err error)

func Prefix

func Prefix(strs []string) string

Prefix returns the longest common prefix of the provided strings

func QuoteStringForFish

func QuoteStringForFish(x string) string

Quotes arbitrary strings for fish

func QuoteStringForSH

func QuoteStringForSH(x string) string

Quotes arbitrary strings for bash, dash and zsh

func RandomFilename

func RandomFilename() string

func ReadAll

func ReadAll(r io.Reader, expected_size int) ([]byte, error)

func ReadCompressedEmbeddedData

func ReadCompressedEmbeddedData(raw string) []byte

func ReaderForCompressedEmbeddedData

func ReaderForCompressedEmbeddedData(raw string) io.Reader

func Remove

func Remove[T comparable](s []T, q T) []T

func RemoveAll

func RemoveAll[T comparable](s []T, q T) []T

func Repeat

func Repeat[T any](x T, n int) []T

func ReplaceAll

func ReplaceAll(cpat *regexp.Regexp, str string, repl func(full_match string, groupdict map[string]SubMatch) string) string

func Repr

func Repr(x any) string

func ResolveConfPath

func ResolveConfPath(path string) string

func Reverse

func Reverse[T any](s []T) []T

func Reversed

func Reversed[T any](s []T) []T

func RuneOffsetsToByteOffsets

func RuneOffsetsToByteOffsets(text string) func(int) int

Return a function that can be called sequentially with rune based offsets converting them to byte based offsets. The rune offsets must be monotonic, otherwise the function returns -1

func Samefile

func Samefile(a, b any) bool

func Select

func Select(nfd int, r *unix.FdSet, w *unix.FdSet, e *unix.FdSet, timeout time.Duration) (n int, err error)

func SetStructDefaults

func SetStructDefaults(v reflect.Value) (err error)

func ShiftLeft

func ShiftLeft[T any](s []T, amt int) []T

func Sort

func Sort[T any](s []T, cmp func(a, b T) int) []T

func SortWithKey

func SortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T

func SourceLine

func SourceLine(skip_frames ...int) int

func SourceLoc

func SourceLoc(skip_frames ...int) string

func Splitlines

func Splitlines(x string, expected_number_of_lines ...int) (ans []string)

func StableSort

func StableSort[T any](s []T, cmp func(a, b T) int) []T

func StableSortWithKey

func StableSortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T

func Suffix

func Suffix(strs []string) string

Suffix returns the longest common suffix of the provided strings

func UnlockFile

func UnlockFile(f *os.File) error

func UnsafeBytesToString

func UnsafeBytesToString(b []byte) (s string)

Unsafely converts b into a string. If you modify b, then s will also be modified. This violates the property that strings are immutable.

func UnsafeStringToBytes

func UnsafeStringToBytes(s string) (b []byte)

Unsafely converts s into a byte slice. If you modify b, then s will also be modified. This violates the property that strings are immutable.

func Values

func Values[M ~map[K]V, K comparable, V any](m M) []V
func WalkWithSymlink(dirpath string, callback Walk_callback, transformers ...func(string) string) error

Walk, recursing into symlinks that point to directories. Ignores directories that could not be read.

func Which

func Which(cmd string, paths ...string) string

Types

type CachedValues

type CachedValues[T any] struct {
	Name string
	Opts T
}

func NewCachedValues

func NewCachedValues[T any](name string, initial_val T) *CachedValues[T]

func (*CachedValues[T]) Load

func (self *CachedValues[T]) Load() T

func (*CachedValues[T]) Path

func (self *CachedValues[T]) Path() string

func (*CachedValues[T]) Save

func (self *CachedValues[T]) Save()

type EncryptedRemoteControlCmd

type EncryptedRemoteControlCmd struct {
	Version   [3]int `json:"version"`
	IV        string `json:"iv"`
	Tag       string `json:"tag"`
	Pubkey    string `json:"pubkey"`
	Encrypted string `json:"encrypted"`
	EncProto  string `json:"enc_proto,omitempty"`
}

type LRUCache

type LRUCache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewLRUCache

func NewLRUCache[K comparable, V any](max_size int) *LRUCache[K, V]

func (*LRUCache[K, V]) Get

func (self *LRUCache[K, V]) Get(key K) (ans V, found bool)

func (*LRUCache[K, V]) GetOrCreate

func (self *LRUCache[K, V]) GetOrCreate(key K, create func(key K) (V, error)) (V, error)

func (*LRUCache[K, V]) MustGetOrCreate

func (self *LRUCache[K, V]) MustGetOrCreate(key K, create func(key K) V) V

func (*LRUCache[K, V]) Set

func (self *LRUCache[K, V]) Set(key K, val V)

type PasswdEntry

type PasswdEntry struct {
	Username, Pass, Uid, Gid, Gecos, Home, Shell string
}

func ParsePasswdLine

func ParsePasswdLine(line string) (PasswdEntry, error)

func PwdEntryForUid

func PwdEntryForUid(uid string) (ans PasswdEntry, err error)

type RemoteControlCmd

type RemoteControlCmd struct {
	Cmd           string `json:"cmd"`
	Version       [3]int `json:"version"`
	NoResponse    bool   `json:"no_response,omitempty"`
	Timestamp     int64  `json:"timestamp,omitempty"`
	Password      string `json:"password,omitempty"`
	Async         string `json:"async,omitempty"`
	CancelAsync   bool   `json:"cancel_async,omitempty"`
	Stream        bool   `json:"stream,omitempty"`
	StreamId      string `json:"stream_id,omitempty"`
	KittyWindowId uint   `json:"kitty_window_id,omitempty"`
	Payload       any    `json:"payload,omitempty"`
}

type ReportFunc

type ReportFunc = func(done, total uint64) error

type RingBuffer

type RingBuffer[T any] struct {
	// contains filtered or unexported fields
}

func NewRingBuffer

func NewRingBuffer[T any](size uint64) *RingBuffer[T]

func (*RingBuffer[T]) Capacity

func (self *RingBuffer[T]) Capacity() uint64

func (*RingBuffer[T]) Clear

func (self *RingBuffer[T]) Clear()

func (*RingBuffer[T]) Grow

func (self *RingBuffer[T]) Grow(new_size uint64)

func (*RingBuffer[T]) Len

func (self *RingBuffer[T]) Len() uint64

func (*RingBuffer[T]) ReadAll

func (self *RingBuffer[T]) ReadAll() []T

func (*RingBuffer[T]) ReadTillEmpty

func (self *RingBuffer[T]) ReadTillEmpty(p []T) uint64

func (*RingBuffer[T]) WriteAllAndDiscardOld

func (self *RingBuffer[T]) WriteAllAndDiscardOld(p ...T)

func (*RingBuffer[T]) WriteTillFull

func (self *RingBuffer[T]) WriteTillFull(p ...T) uint64

type ScanLines

type ScanLines struct {
	// contains filtered or unexported fields
}

func NewScanLines

func NewScanLines(entries ...string) *ScanLines

func (*ScanLines) Scan

func (self *ScanLines) Scan() bool

func (*ScanLines) Text

func (self *ScanLines) Text() string

type Selector

type Selector struct {
	// contains filtered or unexported fields
}

func CreateSelect

func CreateSelect(expected_number_of_fds int) *Selector

func (*Selector) IsErrored

func (self *Selector) IsErrored(fd int) bool

func (*Selector) IsReadyToRead

func (self *Selector) IsReadyToRead(fd int) bool

func (*Selector) IsReadyToWrite

func (self *Selector) IsReadyToWrite(fd int) bool

func (*Selector) RegisterError

func (self *Selector) RegisterError(fd int)

func (*Selector) RegisterRead

func (self *Selector) RegisterRead(fd int)

func (*Selector) RegisterWrite

func (self *Selector) RegisterWrite(fd int)

func (*Selector) UnRegisterError

func (self *Selector) UnRegisterError(fd int)

func (*Selector) UnRegisterRead

func (self *Selector) UnRegisterRead(fd int)

func (*Selector) UnRegisterWrite

func (self *Selector) UnRegisterWrite(fd int)

func (*Selector) UnregisterAll

func (self *Selector) UnregisterAll()

func (*Selector) Wait

func (self *Selector) Wait(timeout time.Duration) (num_ready int, err error)

func (*Selector) WaitForever

func (self *Selector) WaitForever() (num_ready int, err error)

type Set

type Set[T comparable] struct {
	// contains filtered or unexported fields
}

func NewSet

func NewSet[T comparable](capacity ...int) (ans *Set[T])

func NewSetWithItems

func NewSetWithItems[T comparable](items ...T) (ans *Set[T])

func (*Set[T]) Add

func (self *Set[T]) Add(val T)

func (*Set[T]) AddItems

func (self *Set[T]) AddItems(val ...T)

func (*Set[T]) AsSlice

func (self *Set[T]) AsSlice() []T

func (*Set[T]) Clear

func (self *Set[T]) Clear()

func (*Set[T]) Discard

func (self *Set[T]) Discard(val T)

func (*Set[T]) Equal

func (self *Set[T]) Equal(other *Set[T]) bool

func (*Set[T]) ForEach

func (self *Set[T]) ForEach(f func(T))

func (*Set[T]) Has

func (self *Set[T]) Has(val T) bool

func (*Set[T]) Intersect

func (self *Set[T]) Intersect(other *Set[T]) (ans *Set[T])

func (*Set[T]) IsSubsetOf

func (self *Set[T]) IsSubsetOf(other *Set[T]) bool

func (*Set[T]) Iterable

func (self *Set[T]) Iterable() map[T]struct{}

func (*Set[T]) Len

func (self *Set[T]) Len() int

func (*Set[T]) Remove

func (self *Set[T]) Remove(val T)

func (*Set[T]) String

func (self *Set[T]) String() string

func (*Set[T]) Subtract

func (self *Set[T]) Subtract(other *Set[T]) (ans *Set[T])

type ShortUUID

type ShortUUID struct {
	// contains filtered or unexported fields
}
var HumanUUID *ShortUUID

func CreateShortUUID

func CreateShortUUID(alphabet string) *ShortUUID

func (*ShortUUID) Random

func (self *ShortUUID) Random(num_bits int64) (string, error)

func (*ShortUUID) Uuid4

func (self *ShortUUID) Uuid4() (string, error)

type StreamDecompressor

type StreamDecompressor = func(chunk []byte, is_last bool) error

func NewStreamDecompressor

func NewStreamDecompressor(constructor func(io.Reader) (io.ReadCloser, error), output io.Writer) StreamDecompressor

Wrap Go's awful decompressor routines to allow feeding them data in chunks. For example: sd := NewStreamDecompressor(zlib.NewReader, output) sd(chunk, false) ... sd(last_chunk, true) after this call, calling sd() further will just return io.EOF. To close the decompressor at any time, call sd(nil, true). Note: output.Write() may be called from a different thread, but only while the main thread is in sd()

type StringScanner

type StringScanner struct {
	ScanFunc             StringScannerScanFunc
	PostProcessTokenFunc StringScannerPostprocessFunc
	// contains filtered or unexported fields
}

Faster, better designed, zero-allocation version of bufio.Scanner for strings

func NewLineScanner

func NewLineScanner(text string) *StringScanner

func NewSeparatorScanner

func NewSeparatorScanner(text, separator string) *StringScanner

func (*StringScanner) Err

func (self *StringScanner) Err() error

func (*StringScanner) Scan

func (self *StringScanner) Scan() bool

func (*StringScanner) Split

func (self *StringScanner) Split(data string, expected_number ...int) (ans []string)

func (*StringScanner) Text

func (self *StringScanner) Text() string

type StringScannerPostprocessFunc

type StringScannerPostprocessFunc = func(token string) string

type StringScannerScanFunc

type StringScannerScanFunc = func(data string) (remaining_data, token string)

func ScanFuncForSeparator

func ScanFuncForSeparator(sep string) StringScannerScanFunc

type SubMatch

type SubMatch struct {
	Text       string
	Start, End int
}

type TarExtractOptions

type TarExtractOptions struct {
	DontPreservePermissions bool
}

type UTF8State

type UTF8State uint32
const (
	UTF8_ACCEPT UTF8State = 0
	UTF8_REJECT UTF8State = 1
)

func DecodeUtf8

func DecodeUtf8(state *UTF8State, codep *UTF8State, byte_ byte) UTF8State

type Walk_callback

type Walk_callback func(path, abspath string, d fs.DirEntry, err error) error

Directories

Path Synopsis
package base85 This package provides a RFC1924 implementation of base85 encoding.
package base85 This package provides a RFC1924 implementation of base85 encoding.
Package shlex implements a simple lexer which splits input in to tokens using shell-style rules for quoting.
Package shlex implements a simple lexer which splits input in to tokens using shell-style rules for quoting.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL