chore: import official kitty sources from upstream

Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty,
vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
BlackAngelTV committed 2026-11-04 11:20:47 +01:00
commit 7e7d249099
1134 files changed
+433629

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
package utils
import (
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sync"
"sync/atomic"
)
var _ = fmt.Print
type worker struct {
cmd *exec.Cmd
stdin_pipe io.WriteCloser
}
var worker_started atomic.Bool
// IsTesting returns true if the code is being run by "go test".
func IsTesting() bool {
return flag.Lookup("test.v") != nil
}
var get_worker = sync.OnceValues(func() (*worker, error) {
exe, err := os.Executable()
if err != nil {
return nil, err
}
if IsTesting() {
if exe, err = filepath.Abs("../../kitty/launcher/kitten"); err != nil {
return nil, err
}
}
cmd := exec.Command(exe, "__atexit__")
cmd.Stdout = nil
cmd.Stderr = os.Stderr
ans := worker{cmd: cmd}
si, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
ans.stdin_pipe = si
if err = cmd.Start(); err != nil {
return nil, err
}
worker_started.Store(true)
return &ans, nil
})
func WaitForAtexitWorkerToFinish() error {
if worker_started.Load() {
if w, err := get_worker(); err == nil {
w.stdin_pipe.Close()
return w.cmd.Wait()
} else {
return err
}
}
return nil
}
func register(prefix, path string) error {
// no atexit cleanup is done as we dont have a good place to run
// WaitForAtexitWorkerToFinish() and anyway we may want to run tests in
// parallel, etc.
if IsTesting() {
return nil
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
if w, err := get_worker(); err == nil {
_, err = fmt.Fprintln(w.stdin_pipe, prefix+" "+path)
return err
} else {
return err
}
}
func AtExitUnlink(path string) error {
return register("unlink", path)
}
func AtExitShmUnlink(path string) error {
return register("shm_unlink", path)
}
func AtExitRmtree(path string) error {
return register("rmtree", path)
}
+89
View File
@@ -0,0 +1,89 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
)
var _ = fmt.Print
func AtomicCreateSymlink(oldname, newname string) (err error) {
err = os.Symlink(oldname, newname)
if err == nil {
return nil
}
if !errors.Is(err, fs.ErrExist) {
return err
}
if et, err := os.Readlink(newname); err == nil && et == oldname {
return nil
}
for {
tempname := newname + RandomFilename()
err = os.Symlink(oldname, tempname)
if err == nil {
err = os.Rename(tempname, newname)
if err != nil {
os.Remove(tempname)
}
return err
}
if !errors.Is(err, fs.ErrExist) {
return err
}
}
}
func AtomicWriteFile(path string, data io.Reader, perm os.FileMode) (err error) {
npath, err := EvalSymlinksThatExist(path)
if err == nil {
path = npath
path, err = filepath.Abs(path)
if err == nil {
var f *os.File
f, err = os.CreateTemp(filepath.Dir(path), filepath.Base(path)+".atomic-write-")
if err == nil {
removed := false
defer func() {
if err == nil {
err = f.Close()
} else {
f.Close()
}
if !removed {
os.Remove(f.Name())
removed = true
}
}()
if _, err = io.Copy(f, data); err == nil {
if err = f.Chmod(perm); err == nil {
if err = f.Sync(); err == nil { // Sync before rename to ensure we dont end up with a zero sized file
if err = os.Rename(f.Name(), path); err == nil {
removed = true
}
}
}
}
}
}
}
return
}
func AtomicUpdateFile(path string, data io.Reader, perms ...fs.FileMode) (err error) {
perm := fs.FileMode(0o644)
if len(perms) > 0 {
perm = perms[0]
}
s, err := os.Stat(path)
if err == nil {
perm = s.Mode().Perm()
}
return AtomicWriteFile(path, data, perm)
}
+64
View File
@@ -0,0 +1,64 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestAtomicWriteFileSymlinkChain(t *testing.T) {
dir := t.TempDir()
t.Chdir(dir)
for _, name := range []string{"nested", "real"} {
if err := os.Mkdir(name, 0o700); err != nil {
t.Fatal(err)
}
}
// nested/link -> link -> parent/target where parent -> real and real/target does not exist
links := []struct{ path, target string }{{"nested/link", "../link"}, {"link", "parent/target"}, {"parent", "real"}}
for _, l := range links {
if err := os.Symlink(l.target, l.path); err != nil {
t.Fatal(err)
}
}
if err := AtomicWriteFile(filepath.Join("nested", "link"), strings.NewReader("new contents"), 0o640); err != nil {
t.Fatal(err)
}
for _, l := range links {
if actual, err := os.Readlink(l.path); err != nil || actual != l.target {
t.Errorf("Symlink %s changed: %q %v", l.path, actual, err)
}
}
target := filepath.Join("real", "target")
assert_file_contents(t, target, "new contents")
if st, err := os.Stat(target); err != nil || st.Mode().Perm() != 0o640 {
t.Fatalf("Incorrect target permissions: %v %v", st, err)
}
if entries, err := os.ReadDir("real"); err != nil || len(entries) != 1 || entries[0].Name() != "target" {
t.Fatalf("Stray files left behind after write: %v %v", entries, err)
}
}
func TestAtomicWriteFileSymlinkFailure(t *testing.T) {
for _, link := range []string{"missing/target", "link"} {
t.Run(link, func(t *testing.T) {
dir := t.TempDir()
dest := filepath.Join(dir, "link")
if err := os.Symlink(link, dest); err != nil {
t.Fatal(err)
}
if err := AtomicWriteFile(dest, strings.NewReader("new contents"), 0o600); err == nil {
t.Error("Expected write to fail with a missing parent directory or a symlink loop")
}
if actual, err := os.Readlink(dest); err != nil || actual != link {
t.Errorf("Symlink at destination changed: %q %v", actual, err)
}
if entries, err := os.ReadDir(dir); err != nil || len(entries) != 1 || entries[0].Name() != "link" {
t.Fatalf("Stray files left behind after failed write: %v %v", entries, err)
}
})
}
}
+346
View File
@@ -0,0 +1,346 @@
// package base85
// This package provides a RFC1924 implementation of base85 encoding.
//
// See http://www.ietf.org/rfc/rfc1924.txt
// Based on: https://pkg.go.dev/github.com/jamesruan/go-rfc1924
package base85
import (
"bufio"
"errors"
"io"
"strconv"
"sync"
"github.com/kovidgoyal/kitty/tools/utils"
)
// 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~
var encode = [85]byte{
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, //0
0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, //1
0x57, 0x58, 0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, //2
0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x21, 0x23, //3
0x24, 0x25, 0x26, 0x28, 0x29, 0x2A, 0x2B, 0x2D, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x5E, 0x5F, //4
0x60, 0x7B, 0x7C, 0x7D, 0x7E,
}
var decoder_array = sync.OnceValue(func() *[256]byte {
var decode = [256]byte{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
}
for i := range len(encode) {
decode[encode[i]] = byte(i)
}
return &decode
})
// encodeChunk encodes 4 byte-chunk to 5 byte
// if chunk size is less then 4, then it is padded before encoding.
// return written bytes
func encodeChunk(dst, src []byte) int {
if len(src) == 0 {
return 0
}
//read 4 byte as big-endian uint32 into small endian uint32
var val uint32
switch len(src) {
default:
val |= uint32(src[3])
fallthrough
case 3:
val |= uint32(src[2]) << 8
fallthrough
case 2:
val |= uint32(src[1]) << 16
fallthrough
case 1:
val |= uint32(src[0]) << 24
}
buf := [5]byte{0, 0, 0, 0, 0}
for i := 4; i >= 0; i-- {
r := val % 85
val /= 85
buf[i] = encode[r]
}
m := EncodedLen(len(src))
copy(dst[:], buf[:m])
return m
}
var decode_base = [5]uint32{85 * 85 * 85 * 85, 85 * 85 * 85, 85 * 85, 85, 1}
// decodeChunk decodes 5 byte-chunk to 4 byte
// if chunk size is less then 5, then it is padded before convertion.
// return written bytes and error input index
func decodeChunk(decode *[256]byte, dst, src []byte) (int, int) {
if len(src) == 0 {
return 0, 0
}
var val uint32
m := DecodedLen(len(src))
buf := [5]byte{84, 84, 84, 84, 84}
for i := range src {
e := decode[src[i]]
if e == 0xFF {
return 0, i + 1
}
buf[i] = e
}
for i := range 5 {
r := buf[i]
val += uint32(r) * decode_base[i]
}
//small endian uint32 to big endian uint32 in bytes
switch m {
default:
dst[3] = byte(val & 0xff)
fallthrough
case 3:
dst[2] = byte((val >> 8) & 0xff)
fallthrough
case 2:
dst[1] = byte((val >> 16) & 0xff)
fallthrough
case 1:
dst[0] = byte((val >> 24) & 0xff)
}
return m, 0
}
// Encode encodes src into dst, return the bytes written
// The dst must have size of EncodedLen(len(src))
func Encode(dst, src []byte) int {
n := 0
for len(src) > 0 {
if len(src) < 4 {
n += encodeChunk(dst, src)
return n
}
n += encodeChunk(dst[:5], src[:4])
src = src[4:]
dst = dst[5:]
}
return n
}
// EncodeToString returns the base85 encoding of src.
func EncodeToString(src []byte) string {
buf := make([]byte, EncodedLen(len(src)))
Encode(buf, src)
return utils.UnsafeBytesToString(buf)
}
// DecodeString returns the bytes represented by the base85 string s.
func DecodeString(src string) ([]byte, error) {
buf := make([]byte, DecodedLen(len(src)))
_, err := Decode(buf, utils.UnsafeStringToBytes(src))
return buf, err
}
// Decode decodes src into dst, return the bytes written
// The dst must have size of DecodedLen(len(src))
// An CorruptInputError is returned when invalid character is found in src.
func Decode(dst, src []byte) (int, error) {
f := 0
t := 0
decode := decoder_array()
for len(src) > 0 {
if len(src) < 5 {
w, err := decodeChunk(decode, dst, src)
if err > 0 {
return t, CorruptInputError(f + err)
}
return t + w, nil
}
_, err := decodeChunk(decode, dst[:4], src[:5])
if err > 0 {
return t, CorruptInputError(f + err)
} else {
t += 4
f += 5
src = src[5:]
dst = dst[4:]
}
}
return t, nil
}
// EncodedLen returns the length in bytes of the base85 encoding of an input
// buffer of length n.
func EncodedLen(n int) int {
s := n / 4
r := n % 4
if r > 0 {
return s*5 + 5 - (4 - r)
} else {
return s * 5
}
}
// DecodedLen returns the maximum length in bytes of the decoded data
// corresponding to n bytes of base85-encoded data.
func DecodedLen(n int) int {
s := n / 5
r := n % 5
if r > 0 {
return s*4 + 4 - (5 - r)
} else {
return s * 4
}
}
type encoder struct {
w io.Writer
bufin [4]byte
encoded [5]byte
fill int
err error
}
func (e *encoder) Write(p []byte) (n int, err error) {
if e.err != nil {
return 0, e.err
}
for len(p) >= len(e.bufin)-e.fill {
//copy len(e.buf) - fill bytes into e.buf to make it full
to_copy := len(e.bufin) - e.fill
copy(e.bufin[e.fill:], p[:to_copy])
p = p[to_copy:]
//write the encoded whole buffer
encodeChunk(e.encoded[:], e.bufin[:])
_, e.err = e.w.Write(e.encoded[:])
if e.err != nil {
return n, e.err
}
n += 4
e.fill = 0
}
for i := 0; i < len(p); i++ {
e.bufin[e.fill] = p[i]
e.fill += 1
}
return n, e.w.(*bufio.Writer).Flush()
}
func (e *encoder) Close() error {
if e.err == nil && e.fill > 0 {
m := EncodedLen(e.fill)
encodeChunk(e.encoded[:m], e.bufin[:e.fill])
_, e.err = e.w.Write(e.encoded[:m])
if e.err != nil {
return e.err
}
e.err = e.w.(*bufio.Writer).Flush()
}
err := e.err
e.err = errors.New("encoder closed")
return err
}
// NewEncoder returns a stream encoder of w.
// All write to the encoder is encoded into base85 and write to w.
// The writer should call Close() to indicate the end of stream
func NewEncoder(w io.Writer) io.WriteCloser {
encoder := new(encoder)
encoder.w = bufio.NewWriterSize(w, 1000)
return encoder
}
type decoder struct {
r io.Reader
bufin [1000]byte
decoded []byte
fill int
err error
}
// NewDecoder returns a stream decoder of r.
// All read from the reader will read the base85 encoded string from r and decode it.
func NewDecoder(r io.Reader) io.Reader {
decoder := new(decoder)
decoder.r = bufio.NewReaderSize(r, 1000)
return decoder
}
func (d *decoder) Read(p []byte) (n int, err error) {
if d.err != nil {
return 0, d.err
}
for len(p) > 0 {
// try filling the buffer
m, err := d.r.Read(d.bufin[d.fill:])
d.fill += m
if err != nil {
// no further input, decode and copy into p
d.decoded = make([]byte, DecodedLen(d.fill))
if d.err == io.EOF {
k, err := Decode(d.decoded, d.bufin[:d.fill])
copy(p, d.decoded[:k])
n += k
d.fill -= EncodedLen(k)
if err != nil {
d.err = err
return n, err
}
} else {
k, err := Decode(d.decoded, d.bufin[:d.fill-d.fill%5])
copy(p, d.decoded[:k])
n += k
d.fill -= EncodedLen(k)
if err != nil {
d.err = err
return n, err
}
}
d.err = err
return n, d.err
}
//decode d.fill - d.fill % 5 byte of d.bufin
chunked_max := d.fill
d.fill = d.fill % 5
chunked_max -= d.fill
d.decoded = make([]byte, DecodedLen(chunked_max))
k, err := Decode(d.decoded, d.bufin[:chunked_max])
copy(p, d.decoded[:k])
p = p[k:]
n += k
if err != nil {
d.err = err
return n, d.err
}
}
return n, d.err
}
type CorruptInputError int64
func (e CorruptInputError) Error() string {
return "illegal base85 data at input byte " + strconv.FormatInt(int64(e), 10)
}
+61
View File
@@ -0,0 +1,61 @@
package base85
import (
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
type pair struct {
src, encoded string
}
func TestBase85(t *testing.T) {
dst, dst2 := [8]byte{}, [8]byte{}
decode := decoder_array()
var el int
for _, x := range []string{"M", "Ma", "Man", "Man "} {
a := []byte(x)
if el = encodeChunk(dst[:], a); el != EncodedLen(len(a)) {
t.Fatalf("Encoded len for %#v wrong: %d != %d", x, el, EncodedLen(len(a)))
}
encoded := dst[:el]
dl, bad_idx := decodeChunk(decode, dst2[:], encoded)
if bad_idx != 0 {
t.Fatalf("Decode for %#v returned bad data at: %d (%#v)", x, bad_idx, encoded)
}
if dl != DecodedLen(len(encoded)) {
t.Fatalf("Decoded len for %#v wrong: %d != %d", x, dl, DecodedLen(len(a)))
}
decoded := string(dst2[:dl])
if diff := cmp.Diff(x, decoded); diff != "" {
t.Fatalf("Roundtrip failed for %#v: %s", x, diff)
}
}
for _, p := range []pair{
{"M", "O#"},
{"Manual", "O<`_zVQc"},
{
"Man is distinguished, not only by his reason, but by this singular passion from " +
"other animals, which is a lust of the mind, that by a perseverance of delight in " +
"the continued and indefatigable generation of knowledge, exceeds the short " +
"vehemence of any carnal pleasure.",
"O<`^zX>%ZCX>)XGZfA9Ab7*B`EFf-gbRchTY<VDJc_3(Mb0BhMVRLV8EFfZabRc4RAarPHb0BkRZfA9DVR9gFVRLh7Z*CxFa&K)QZ**v7av))DX>DO_b1WctXlY|;AZc?TVIXXEb95kYW*~HEWgu;7Ze%PVbZB98AYyqSVIXj2a&u*NWpZI|V`U(3W*}r`Y-wj`bRcPNAarPDAY*TCbZKsNWn>^>Ze$>7Ze(R<VRUI{VPb4$AZKN6WpZJ3X>V>IZ)PBCZf|#NWn^b%EFfigV`XJzb0BnRWgv5CZ*p`Xc4cT~ZDnp_Wgu^6AYpEKAY);2ZeeU7aBO8^b9HiME&",
},
} {
q := EncodeToString([]byte(p.src))
if diff := cmp.Diff(p.encoded, q); diff != "" {
t.Fatalf("Incorrect encoding of: %#v\n%s", p.src, diff)
}
sc, err := DecodeString(q)
if err != nil {
t.Fatalf("Failed to decode %#v with error: %s", p.src, err)
}
if diff := cmp.Diff(p.src, string(sc)); diff != "" {
t.Fatalf("Failed to roundtrip %#v\n%s", p.src, diff)
}
}
}
+77
View File
@@ -0,0 +1,77 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"container/list"
"fmt"
"sync"
)
var _ = fmt.Print
type LRUCache[K comparable, V any] struct {
data map[K]V
lock sync.RWMutex
max_size int
lru *list.List
}
func NewLRUCache[K comparable, V any](max_size int) *LRUCache[K, V] {
ans := LRUCache[K, V]{data: map[K]V{}, max_size: max_size, lru: list.New()}
return &ans
}
func (self *LRUCache[K, V]) Clear() {
self.lock.Lock()
clear(self.data)
self.lock.Unlock()
}
func (self *LRUCache[K, V]) Get(key K) (ans V, found bool) {
self.lock.RLock()
ans, found = self.data[key]
self.lock.RUnlock()
return
}
func (self *LRUCache[K, V]) Set(key K, val V) {
self.lock.Lock()
self.data[key] = val
self.lock.Unlock()
}
func (self *LRUCache[K, V]) GetOrCreate(key K, create func(key K) (V, error)) (V, error) {
self.lock.RLock()
ans, found := self.data[key]
self.lock.RUnlock()
if found {
return ans, nil
}
ans, err := create(key)
if err == nil {
self.lock.Lock()
self.data[key] = ans
self.lru.PushFront(key)
if self.max_size > 0 && self.lru.Len() > self.max_size {
k := self.lru.Remove(self.lru.Back())
delete(self.data, k.(K))
}
self.lock.Unlock()
}
return ans, err
}
func (self *LRUCache[K, V]) MustGetOrCreate(key K, create func(key K) V) V {
self.lock.RLock()
ans, found := self.data[key]
self.lock.RUnlock()
if found {
return ans
}
ans = create(key)
self.lock.Lock()
self.data[key] = ans
self.lock.Unlock()
return ans
}
+41
View File
@@ -0,0 +1,41 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
)
var _ = fmt.Print
type CachedValues[T any] struct {
Name string
Opts T
}
func (self *CachedValues[T]) Path() string {
return filepath.Join(CacheDir(), self.Name+".json")
}
func (self *CachedValues[T]) Load() T {
raw, err := os.ReadFile(self.Path())
if err == nil {
json.Unmarshal(raw, self.Opts)
}
return self.Opts
}
func (self *CachedValues[T]) Save() {
raw, err := json.Marshal(self.Opts)
if err == nil {
AtomicUpdateFile(self.Path(), bytes.NewReader(raw), 0o600)
}
}
func NewCachedValues[T any](name string, initial_val T) *CachedValues[T] {
return &CachedValues[T]{Name: name, Opts: initial_val}
}
+18
View File
@@ -0,0 +1,18 @@
//go:build linux || darwin
package utils
import (
"time"
"golang.org/x/sys/unix"
)
func MonotonicRaw() (time.Time, error) {
ts := unix.Timespec{}
if err := unix.ClockGettime(unix.CLOCK_MONOTONIC_RAW, &ts); err != nil {
return time.Time{}, err
}
s, ns := ts.Unix()
return time.Unix(s, ns), nil
}
+11
View File
@@ -0,0 +1,11 @@
//go:build !linux && !darwin
package utils
import (
"time"
)
func MonotonicRaw() (time.Time, error) {
return time.Now(), nil
}
+21
View File
@@ -0,0 +1,21 @@
package utils
import (
"fmt"
)
var _ = fmt.Print
func RGBLuminance(r, g, b float32) float32 {
// From ITU BT 601 https://www.itu.int/rec/R-REC-BT.601
return 0.299*r + 0.587*g + 0.114*b
}
func RGBContrast(r1, g1, b1, r2, g2, b2 float32) float32 {
al := RGBLuminance(r1, g1, b1)
bl := RGBLuminance(r2, g2, b2)
if al < bl {
al, bl = bl, al
}
return (al + 0.05) / (bl + 0.05)
}
+107
View File
@@ -0,0 +1,107 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
)
var _ = fmt.Print
type ReportFunc = func(done, total uint64) error
type write_counter struct {
done, total uint64
report ReportFunc
}
func (self *write_counter) Write(p []byte) (int, error) {
n := len(p)
self.done += uint64(n)
if self.report != nil {
err := self.report(self.done, self.total)
if err != nil {
return 0, err
}
}
return n, nil
}
func DownloadToWriter(url string, dest io.Writer, progress_callback ReportFunc) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("The server responded with the HTTP error: %s", resp.Status)
}
wc := write_counter{report: progress_callback}
cl, err := strconv.Atoi(resp.Header.Get("Content-Length"))
if err == nil {
wc.total = uint64(cl)
}
_, err = io.Copy(dest, io.TeeReader(resp.Body, &wc))
if err != nil {
return err
}
return nil
}
func DownloadAsSlice(url string, progress_callback ReportFunc) (data []byte, err error) {
b := bytes.Buffer{}
b.Grow(4096)
err = DownloadToWriter(url, &b, progress_callback)
if err == nil {
return b.Bytes(), nil
}
return nil, err
}
func DownloadToFile(destpath, url string, progress_callback ReportFunc, temp_file_path_callback func(string)) error {
destpath, err := filepath.EvalSymlinks(destpath)
if err != nil {
return err
}
dest, err := os.CreateTemp(filepath.Dir(destpath), filepath.Base(destpath)+".partial-download.")
if err != nil {
return err
}
if temp_file_path_callback != nil {
temp_file_path_callback(dest.Name())
}
dest_removed := false
defer func() {
dest.Close()
if !dest_removed {
os.Remove(dest.Name())
}
}()
err = DownloadToWriter(url, dest, progress_callback)
if err != nil {
return err
}
dest.Close()
fi, err := os.Stat(destpath)
if err == nil {
err = os.Chmod(dest.Name(), fi.Mode().Perm())
if err != nil {
return err
}
}
if err != nil {
return err
}
err = os.Rename(dest.Name(), destpath)
if err != nil {
return err
}
dest_removed = true
return nil
}
+46
View File
@@ -0,0 +1,46 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"bytes"
"compress/bzip2"
"encoding/binary"
"fmt"
"io"
)
var _ = fmt.Print
func ReadAll(r io.Reader, expected_size int) ([]byte, error) {
b := make([]byte, 0, expected_size)
for {
if len(b) == cap(b) {
// Add more capacity (let append pick how much).
b = append(b, 0)[:len(b)]
}
n, err := r.Read(b[len(b):cap(b)])
b = b[:len(b)+n]
if err != nil {
if err == io.EOF {
err = nil
}
return b, err
}
}
}
func ReadCompressedEmbeddedData(raw string) []byte {
compressed := UnsafeStringToBytes(raw)
uncompressed_size := binary.LittleEndian.Uint32(compressed)
r := bzip2.NewReader(bytes.NewReader(compressed[4:]))
ans, err := ReadAll(r, int(uncompressed_size))
if err != nil {
panic(err)
}
return ans
}
func ReaderForCompressedEmbeddedData(raw string) io.Reader {
return bzip2.NewReader(bytes.NewReader(UnsafeStringToBytes(raw)[4:]))
}
+710
View File
@@ -0,0 +1,710 @@
package utils
import (
"container/list"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sync/atomic"
"syscall"
"time"
"github.com/kovidgoyal/go-parallel"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
// MkdirAt creates a new subdirectory named 'name' inside the directory
// pointed to by parentDir.
func MkdirAt(parentDir *os.File, name string, perm os.FileMode) (err error) {
// parentDir.Fd() gives us the base directory handle
fd := int(parentDir.Fd())
// unix.Mkdirat(dirfd, path, mode)
// We convert the os.FileMode to a uint32 for the syscall
for {
if err = unix.Mkdirat(fd, name, uint32(perm)); err != unix.EINTR {
break
}
}
if err != nil {
return &fs.PathError{
Op: "mkdirat",
Path: filepath.Join(parentDir.Name(), name),
Err: err,
}
}
return nil
}
// OpenAt opens a file relative to the directory pointed to by dirFile.
// Matches the behavior of os.Open (read-only).
func OpenAt(dirFile *os.File, name string) (*os.File, error) {
return openAt(dirFile, name, unix.O_RDONLY, 0)
}
// Opens a directory relative to the directory pointed to by dirFile.
// Matches the behavior of os.Open (read-only).
func OpenDirAt(dirFile *os.File, name string) (*os.File, error) {
return openAt(dirFile, name, unix.O_RDONLY|unix.O_DIRECTORY, 0)
}
// Create a symlink named name in the directory pointed to by dirFile. The
// target of the symlink is set to target
func SymlinkAt(dirFile *os.File, name, target string) (err error) {
for {
if err = unix.Symlinkat(target, int(dirFile.Fd()), name); err != unix.EINTR {
break
}
}
if err != nil {
return &fs.PathError{
Op: "symlinkat",
Path: filepath.Join(dirFile.Name(), name),
Err: err,
}
}
return
}
// CreateAt creates or truncates a file relative to the directory pointed to by dirFile.
// Matches the behavior of os.Create (read-write, creates if doesn't exist, truncates).
func CreateAt(dirFile *os.File, name string, permissions os.FileMode) (*os.File, error) {
return openAt(dirFile, name, unix.O_RDWR|unix.O_CREAT|unix.O_TRUNC, permissions)
}
// CreateExclusiveAt creates a file relative to the directory pointed to by
// dirFile. Fails if a directory entry with the same name already exists.
func CreateExclusiveAt(dirFile *os.File, name string, permissions os.FileMode) (*os.File, error) {
return openAt(dirFile, name, unix.O_RDWR|unix.O_CREAT|unix.O_EXCL, permissions)
}
// Create the specified directory, open it and return the file object. If the
// directory already exists, it is opened and returned, without changing its
// permissions, matching the behavior of CreateAt().
func CreateDirAt(parent *os.File, name string, permissions os.FileMode) (*os.File, error) {
if err := MkdirAt(parent, name, permissions); err != nil {
if errors.Is(err, unix.EEXIST) {
return OpenDirAt(parent, name)
}
return nil, err
}
return OpenDirAt(parent, name)
}
// Internal helper to wrap the unix.Openat syscall
func openAt(dirFile *os.File, name string, flags int, perm os.FileMode) (ans *os.File, err error) {
dirFd := int(dirFile.Fd())
// Call the underlying system call
var fd int
for {
if fd, err = unix.Openat(dirFd, name, flags|unix.O_CLOEXEC, uint32(perm)); err != unix.EINTR {
break
}
}
name = filepath.Join(dirFile.Name(), name)
if err != nil {
return nil, &os.PathError{Op: "openat", Path: name, Err: err}
}
return os.NewFile(uintptr(fd), name), nil
}
type UnixFileInfo struct {
name string
stat *unix.Stat_t
mode os.FileMode
}
func NewUnixFileInfo(name string, stat *unix.Stat_t) os.FileInfo {
rawMode := stat.Mode
// Start with the standard 9-bit permissions
mode := os.FileMode(rawMode & 0777)
// Map the file type bits using S_IFMT
switch rawMode & unix.S_IFMT {
case unix.S_IFDIR:
mode |= os.ModeDir
case unix.S_IFLNK:
mode |= os.ModeSymlink
case unix.S_IFBLK:
mode |= os.ModeDevice
case unix.S_IFCHR:
// Go uses ModeDevice | ModeCharDevice for character devices
mode |= os.ModeDevice | os.ModeCharDevice
case unix.S_IFIFO:
mode |= os.ModeNamedPipe
case unix.S_IFSOCK:
mode |= os.ModeSocket
}
// Map setuid, setgid, and sticky bits
if rawMode&unix.S_ISUID != 0 {
mode |= os.ModeSetuid
}
if rawMode&unix.S_ISGID != 0 {
mode |= os.ModeSetgid
}
if rawMode&unix.S_ISVTX != 0 {
mode |= os.ModeSticky
}
return &UnixFileInfo{name, stat, mode}
}
func (m *UnixFileInfo) Name() string { return m.name }
func (m *UnixFileInfo) Size() int64 { return m.stat.Size }
func (m *UnixFileInfo) Mode() os.FileMode { return m.mode }
func (m *UnixFileInfo) ModTime() time.Time { return time.Unix(m.stat.Mtim.Unix()) }
func (m *UnixFileInfo) IsDir() bool { return m.Mode().IsDir() }
func (m *UnixFileInfo) Sys() any { return m.stat }
func (m *UnixFileInfo) Dev() uint64 { return uint64(m.stat.Rdev) }
// Get file info relative to the parent FD, follows symlinks
func StatAt(dirFile *os.File, name string) (ans os.FileInfo, err error) {
var stat unix.Stat_t
for {
if err = unix.Fstatat(int(dirFile.Fd()), name, &stat, 0); err != unix.EINTR {
break
}
}
if err != nil {
name = filepath.Join(dirFile.Name(), name)
return nil, &os.PathError{Op: "statat", Path: name, Err: err}
}
return NewUnixFileInfo(name, &stat), nil
}
// Get file info relative to the parent FD, do not follows symlinks
func LstatAt(dirFile *os.File, name string) (ans os.FileInfo, err error) {
var stat unix.Stat_t
for {
if err = unix.Fstatat(int(dirFile.Fd()), name, &stat, unix.AT_SYMLINK_NOFOLLOW); err != unix.EINTR {
break
}
}
if err != nil {
name = filepath.Join(dirFile.Name(), name)
return nil, &os.PathError{Op: "lstatat", Path: name, Err: err}
}
return NewUnixFileInfo(name, &stat), nil
}
// Remove file relative to parent fd
func UnlinkAt(parent *os.File, name string) (err error) {
for {
if err = unix.Unlinkat(int(parent.Fd()), name, 0); err != unix.EINTR {
break
}
}
if err != nil {
err = &os.PathError{Op: "unlinkat", Path: filepath.Join(parent.Name(), name), Err: err}
}
return
}
// Remove empty directory relative to parent fd
func RemoveDirAt(parent *os.File, name string) (err error) {
for {
if err = unix.Unlinkat(int(parent.Fd()), name, unix.AT_REMOVEDIR); err != unix.EINTR {
break
}
}
if err != nil {
err = &os.PathError{Op: "unlinkat", Path: filepath.Join(parent.Name(), name), Err: err}
}
return
}
// Create a hardlink pointing to oldname called newname relative to the
// specified directories. If oldname is a symlink,
// a new symlink is created pointing to its target when follow_symlinks is true otherwise to it.
func LinkAt(oldparent *os.File, oldname string, newparent *os.File, newname string, follow_symlinks bool) (err error) {
flags := IfElse(follow_symlinks, unix.AT_SYMLINK_FOLLOW, 0)
for {
if err = unix.Linkat(int(oldparent.Fd()), oldname, int(newparent.Fd()), newname, flags); err != unix.EINTR {
break
}
}
if err != nil {
err = &os.PathError{Op: "linkat", Path: fmt.Sprintf("%s -> %s", filepath.Join(newparent.Name(), newname), filepath.Join(oldparent.Name(), oldname)), Err: err}
}
return
}
// RemoveChildren removes all files and subdirectories within the directory
// pointed to by dirFile using an explicit stack instead of recursion. Removes
// all it can but returns the first error, if any.
func RemoveChildren(dirFile *os.File) error {
var firstErr error
// Each stack frame is one of two kinds:
// expand: dir != nil – read dir's children, unlink files, push subdirs
// rmdir: dir == nil – rmdir name from parent, then Unref parent
type frame struct {
dir *RefCountedFile // non-nil: expand this directory (Unref when done)
name string // rmdir sentinel: child name to remove from parent
parent *RefCountedFile // rmdir sentinel: ref to parent dir (Unref after rmdir)
}
// Only the root directory needs rewinding; it was passed in from outside
// and may have been read before. Child dirs are freshly opened by us.
if _, err := dirFile.Seek(0, io.SeekStart); err != nil {
return err
}
rcRoot := NewRefCountedFile(dirFile)
// Extra ref so the expand frame's Unref doesn't close the caller's fd.
rcRoot.NewRef()
stack := []frame{{dir: rcRoot}}
for len(stack) > 0 {
f := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if f.dir == nil {
// rmdir sentinel: the subdirectory is now empty, remove it.
if err := RemoveDirAt(f.parent.File(), f.name); err != nil && firstErr == nil {
firstErr = err
}
f.parent.Unref()
continue
}
for {
// Read entries in small chunks to handle very large directories.
entries, err := f.dir.File().ReadDir(64)
for _, entry := range entries {
name := entry.Name()
if entry.IsDir() {
childFile, openErr := OpenDirAt(f.dir.File(), name)
if openErr != nil {
if firstErr == nil {
firstErr = openErr
}
continue
}
// Push rmdir sentinel first; LIFO ensures the child expand
// frame is processed before this rmdir sentinel.
// f.dir.NewRef() adds a ref to the parent for the sentinel.
stack = append(stack, frame{name: name, parent: f.dir.NewRef()}, frame{dir: NewRefCountedFile(childFile)})
} else {
if unlinkErr := UnlinkAt(f.dir.File(), name); unlinkErr != nil && firstErr == nil {
firstErr = unlinkErr
}
}
}
if err != nil {
if !errors.Is(err, io.EOF) && firstErr == nil {
firstErr = &os.PathError{Op: "readdir", Path: f.dir.File().Name(), Err: err}
}
break
}
}
f.dir.Unref()
}
_, _ = dirFile.Seek(0, io.SeekStart)
return firstErr
}
func DupFile(f *os.File) (ans *os.File, err error) {
var fd int
for {
if fd, err = unix.Dup(int(f.Fd())); err != unix.EINTR {
break
}
}
if err != nil {
return nil, &os.PathError{Op: "dup", Path: f.Name(), Err: err}
}
return os.NewFile(uintptr(fd), f.Name()), nil
}
func ReadLinkAt(parent *os.File, name string) (ans string, err error) {
buf := [unix.PathMax]byte{}
n, err := readLinkAt(parent, name, buf[:])
if err != nil {
return "", &os.PathError{Op: "readlinkat", Path: filepath.Join(parent.Name(), name), Err: err}
}
return UnsafeBytesToString(buf[:n]), nil
}
func RenameAt(old_parent *os.File, old_name string, new_parent *os.File, new_name string) (err error) {
for {
if err = unix.Renameat(int(old_parent.Fd()), old_name, int(new_parent.Fd()), new_name); err != unix.EINTR {
break
}
}
if err != nil {
err = &os.LinkError{Op: "renameat", Old: filepath.Join(old_parent.Name(), old_name), New: filepath.Join(new_parent.Name(), new_name), Err: err}
}
return
}
func ConvertFileModeToUnix(goMode os.FileMode) uint32 {
// 1. Start with the basic permission bits (0777)
unixMode := uint32(goMode.Perm())
// 2. Map the type bits
// We use the os.ModeXXX constants to identify the type
switch {
case goMode.IsDir():
unixMode |= unix.S_IFDIR
case goMode&os.ModeSymlink != 0:
unixMode |= unix.S_IFLNK
case goMode&os.ModeNamedPipe != 0:
unixMode |= unix.S_IFIFO
case goMode&os.ModeSocket != 0:
unixMode |= unix.S_IFSOCK
case goMode&os.ModeDevice != 0:
if goMode&os.ModeCharDevice != 0 {
unixMode |= unix.S_IFCHR
} else {
unixMode |= unix.S_IFBLK
}
default:
// Default to a regular file
unixMode |= unix.S_IFREG
}
// 3. Map special bits
if goMode&os.ModeSetuid != 0 {
unixMode |= unix.S_ISUID
}
if goMode&os.ModeSetgid != 0 {
unixMode |= unix.S_ISGID
}
if goMode&os.ModeSticky != 0 {
unixMode |= unix.S_ISVTX
}
return unixMode
}
func MknodAt(parent *os.File, name string, mode os.FileMode, dev uint64) (err error) {
unix_mode := ConvertFileModeToUnix(mode)
if err = mknodAt(parent, name, unix_mode, dev); err != nil {
err = &os.PathError{Op: "mknodat", Path: filepath.Join(parent.Name(), name), Err: err}
}
return
}
// Not thread safe reference counted wrapper for os.File
type RefCountedFile struct {
f *os.File
refcnt atomic.Int32
}
func NewRefCountedFile(f *os.File) *RefCountedFile {
ans := RefCountedFile{f: f}
ans.refcnt.Add(1)
return &ans
}
func (f *RefCountedFile) NewRef() *RefCountedFile {
f.refcnt.Add(1)
return f
}
func (f *RefCountedFile) Unref() *RefCountedFile {
if f.refcnt.Add(-1) == 0 {
f.f.Close()
f.f = nil
}
return nil
}
func (f *RefCountedFile) File() *os.File { return f.f }
type CopyFolderOptions struct {
Disallow_hardlinks bool
Follow_symlinks bool
Filter_files func(parent *os.File, child os.FileInfo) bool
}
// Copy the file objects as efficiently as possible with cancellation. The
// files are always closed before this function returns.
func CopyFileAndClose(ctx context.Context, src *os.File, dest *os.File) (err error) {
err_chan := make(chan error)
go func() {
defer func() {
if r := recover(); r != nil {
err_chan <- parallel.Format_stacktrace_on_panic(r, 1)
}
}()
// this go routine will automatically exit when src/dest are closed
// even if copying is not complete. io.Copy() automatically use
// sendfile() or similar mechanisms for efficiency.
_, err := io.Copy(dest, src)
err_chan <- err
}()
select {
case <-ctx.Done():
src.Close()
dest.Close()
// wait for go routine to exit
<-err_chan
return ctx.Err()
case err := <-err_chan:
src.Close()
dest.Close()
return err
}
}
// Copy the contents of src_folder to dest_folder, recursively, preserving file
// permissions. Behavior around hard and symbolic links and filtering is
// controlled via the provided options. When symlink following is enabled,
// symlink loops are avoided and any sumlink that points to an already copied
// entry becomes a symlink pointing to the copied entry using a relative path.
// Existing regular files are overwritten, without changing their permissions.
// Existing directories also do not have their permissions updated.
func CopyFolderContents(ctx context.Context, src_folder *os.File, dest_folder *os.File, opts CopyFolderOptions) (final_error error) {
// Ensure we get all dir contents
_, err := src_folder.Seek(0, io.SeekStart)
if err != nil {
return err
}
// When following symlinks, store previously seen source items with the
// abspaths they have been copied to in dest. Items are identified with
// device + inode number which should be globally unique. This ensures 1)
// no file/dir is copied more than once because of a symlink 2) symlinks
// are changed to point to the relative location of the previously copied
// target
type dir_ident struct{ dev, inode uint64 }
get_dir_ident := func(i os.FileInfo) dir_ident {
switch s := i.Sys().(type) {
case *syscall.Stat_t:
return dir_ident{uint64(s.Dev), uint64(s.Ino)}
case *unix.Stat_t:
return dir_ident{uint64(s.Dev), uint64(s.Ino)}
}
panic("unknown stat result type from os.FileInfo")
}
var seen_map map[dir_ident]string
if opts.Follow_symlinks {
seen_map = make(map[dir_ident]string)
if s, err := src_folder.Stat(); err != nil {
return err
} else {
seen_map[get_dir_ident(s)] = dest_folder.Name()
}
}
is_ok := opts.Filter_files
if is_ok == nil {
is_ok = func(*os.File, os.FileInfo) bool { return true }
}
type item struct {
src_parent, dest_parent *RefCountedFile
child os.FileInfo
}
queue := list.New()
is_cancelled := func() bool {
select {
case <-ctx.Done():
final_error = ctx.Err()
return true
default:
return false
}
}
defer func() {
for {
v := queue.Front()
if v == nil {
break
}
item := queue.Remove(v).(*item)
if item.src_parent != nil {
item.src_parent.Unref()
}
if item.dest_parent != nil {
item.dest_parent.Unref()
}
}
}()
src, dest := NewRefCountedFile(src_folder), NewRefCountedFile(dest_folder)
// Add an extra reference so that the files passed into this function are
// not closed in do_one()
src.NewRef()
dest.NewRef()
fail := func(lerr error) bool {
final_error = lerr
return false
}
mark_as_seen := func(dest_parent *os.File, child os.FileInfo) {
if opts.Follow_symlinks {
path := filepath.Join(dest_parent.Name(), child.Name())
seen_map[get_dir_ident(child)] = filepath.Clean(path)
}
}
var do_one_child func(src *RefCountedFile, dest *RefCountedFile, child os.FileInfo, from_symlink bool) bool
do_one_child = func(src *RefCountedFile, dest *RefCountedFile, child os.FileInfo, from_symlink bool) bool {
if child.IsDir() {
queue.PushBack(&item{src.NewRef(), dest.NewRef(), child})
return true
}
mark_as_seen(dest.File(), child)
// First try a hardlink which works for regular files and symlinks at least
if !opts.Disallow_hardlinks && LinkAt(src.File(), child.Name(), dest.File(), child.Name(), opts.Follow_symlinks) == nil {
return true
}
t := child.Mode().Type()
switch {
case t.IsRegular():
sf, err := OpenAt(src.File(), child.Name())
if err != nil {
return fail(err)
}
df, err := CreateAt(dest.File(), child.Name(), child.Mode().Perm())
if err != nil {
sf.Close()
return fail(err)
}
if err = CopyFileAndClose(ctx, sf, df); err != nil {
UnlinkAt(dest.File(), child.Name()) // dont leave partially copied files around
return fail(err)
}
case t&os.ModeSymlink != 0:
if opts.Follow_symlinks && !from_symlink {
rpath, err := filepath.EvalSymlinks(filepath.Join(src.File().Name(), child.Name()))
if err != nil {
return do_one_child(src, dest, child, true)
}
parent_dir := filepath.Dir(rpath)
pfd, err := unix.Open(parent_dir, unix.O_DIRECTORY|unix.O_RDONLY|unix.O_CLOEXEC, 0)
if err != nil {
return do_one_child(src, dest, child, true)
}
child_name := filepath.Base(rpath)
return func() bool {
pdf := os.NewFile(uintptr(pfd), parent_dir)
// Use a RefCountedFile so that if st is a directory the fd
// stays alive until the queued item is processed by next_dir.
rcf := NewRefCountedFile(pdf)
defer rcf.Unref()
st, err := StatAt(pdf, child_name)
if err != nil {
return do_one_child(src, dest, child, true)
}
id := get_dir_ident(st)
if existing_path, found := seen_map[id]; found {
target, err := filepath.Rel(dest.File().Name(), existing_path)
if err != nil {
return do_one_child(src, dest, child, true)
}
if err = SymlinkAt(dest.File(), child.Name(), target); err != nil {
return fail(err)
}
return true
}
return do_one_child(rcf, dest, st, true)
}()
} else {
target, err := ReadLinkAt(src.File(), child.Name())
if err != nil {
return fail(err)
}
if err = SymlinkAt(dest.File(), child.Name(), target); err != nil {
return fail(err)
}
}
case t&os.ModeDevice != 0:
if err := MknodAt(dest.File(), child.Name(), child.Mode(), child.(*UnixFileInfo).Dev()); err != nil {
return fail(err)
}
}
return true
}
do_one := func(src *RefCountedFile, dest *RefCountedFile) bool {
defer func() {
src = src.Unref()
dest = dest.Unref()
}()
if is_cancelled() {
return false
}
for {
dir_entries, err := src.File().ReadDir(64)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return fail(err)
}
for _, entry := range dir_entries {
if is_cancelled() {
return false
}
child, err := entry.Info()
if err != nil {
return fail(err)
}
if !is_ok(src.File(), child) {
continue
}
if !do_one_child(src, dest, child, false) {
return false
}
}
}
return true
}
next_dir := func(src_parent *RefCountedFile, dest_parent *RefCountedFile, child os.FileInfo) (ok bool) {
src, dest = nil, nil
mark_as_seen(dest_parent.File(), child)
defer func() {
src_parent.Unref()
dest_parent.Unref()
if !ok {
if src != nil {
src = src.Unref()
}
if dest != nil {
dest = dest.Unref()
}
}
}()
sf, err := OpenDirAt(src_parent.File(), child.Name())
if err != nil {
final_error = err
return false
}
df, err := CreateDirAt(dest_parent.File(), child.Name(), child.Mode().Perm())
if err != nil {
sf.Close()
final_error = err
return false
}
src, dest = NewRefCountedFile(sf), NewRefCountedFile(df)
ok = true
return
}
for {
if !do_one(src, dest) {
return
}
v := queue.Front()
if v == nil {
break
}
n := queue.Remove(v).(*item)
if !next_dir(n.src_parent, n.dest_parent, n.child) {
return
}
}
return
}
+30
View File
@@ -0,0 +1,30 @@
package utils
import (
"fmt"
"os"
"path/filepath"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func mknodAt(parent *os.File, name string, mode uint32, dev uint64) (err error) {
path := filepath.Join(parent.Name(), name)
for {
if err = unix.Mknod(path, mode, int(dev)); err != unix.EINTR {
break
}
}
return
}
func readLinkAt(parent *os.File, name string, buf []byte) (n int, err error) {
for {
if n, err = unix.Readlinkat(int(parent.Fd()), name, buf[:]); err != unix.EINTR {
break
}
}
return
}
+30
View File
@@ -0,0 +1,30 @@
package utils
import (
"fmt"
"os"
"path/filepath"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func mknodAt(parent *os.File, name string, mode uint32, dev uint64) (err error) {
for {
if err = unix.Mknodat(int(parent.Fd()), name, mode, int(dev)); err != unix.EINTR {
break
}
}
return
}
func readLinkAt(parent *os.File, name string, buf []byte) (n int, err error) {
path := filepath.Join(parent.Name(), name)
for {
if n, err = unix.Readlink(path, buf[:]); err != unix.EINTR {
break
}
}
return
}
+28
View File
@@ -0,0 +1,28 @@
package utils
import (
"fmt"
"os"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func mknodAt(parent *os.File, name string, mode uint32, dev uint64) (err error) {
for {
if err = unix.Mknodat(int(parent.Fd()), name, mode, dev); err != unix.EINTR {
break
}
}
return
}
func readLinkAt(parent *os.File, name string, buf []byte) (n int, err error) {
for {
if n, err = unix.Readlinkat(int(parent.Fd()), name, buf[:]); err != unix.EINTR {
break
}
}
return
}
+30
View File
@@ -0,0 +1,30 @@
//go:build !darwin && !freebsd && !dragonfly
package utils
import (
"fmt"
"os"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func mknodAt(parent *os.File, name string, mode uint32, dev uint64) (err error) {
for {
if err = unix.Mknodat(int(parent.Fd()), name, mode, int(dev)); err != unix.EINTR {
break
}
}
return
}
func readLinkAt(parent *os.File, name string, buf []byte) (n int, err error) {
for {
if n, err = unix.Readlinkat(int(parent.Fd()), name, buf[:]); err != unix.EINTR {
break
}
}
return
}
+829
View File
@@ -0,0 +1,829 @@
// License: GPLv3 Copyright: 2025, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"runtime"
"syscall"
"testing"
)
// openTestDir opens the directory at path for the test, closing it on cleanup.
func openTestDir(t *testing.T, path string) *os.File {
t.Helper()
d, err := os.Open(path)
if err != nil {
t.Fatalf("openTestDir %s: %v", path, err)
}
t.Cleanup(func() { d.Close() })
return d
}
// mustReadFile returns the contents of path or fatals the test.
func mustReadFile(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatalf("ReadFile %s: %v", path, err)
}
return string(b)
}
// countOpenFDs returns the number of open file descriptors in the process.
// It uses /proc/self/fd and is only meaningful on Linux; returns -1 elsewhere.
func countOpenFDs() int {
if runtime.GOOS != "linux" {
return -1
}
entries, err := os.ReadDir("/proc/self/fd")
if err != nil {
return -1
}
return len(entries)
}
// --- Tests for individual API functions ---
func TestMkdirAt(t *testing.T) {
tmp := t.TempDir()
d := openTestDir(t, tmp)
if err := MkdirAt(d, "newdir", 0755); err != nil {
t.Fatalf("MkdirAt: %v", err)
}
info, err := os.Stat(filepath.Join(tmp, "newdir"))
if err != nil {
t.Fatalf("stat after MkdirAt: %v", err)
}
if !info.IsDir() {
t.Error("expected a directory")
}
// Creating same directory again should return a PathError wrapping EEXIST.
err = MkdirAt(d, "newdir", 0755)
if err == nil {
t.Fatal("expected error for duplicate MkdirAt")
}
var pe *fs.PathError
if !errors.As(err, &pe) {
t.Errorf("expected *fs.PathError, got %T: %v", err, err)
}
}
func TestOpenAt(t *testing.T) {
tmp := t.TempDir()
os.WriteFile(filepath.Join(tmp, "hello.txt"), []byte("world"), 0644)
d := openTestDir(t, tmp)
f, err := OpenAt(d, "hello.txt")
if err != nil {
t.Fatalf("OpenAt: %v", err)
}
defer f.Close()
buf := make([]byte, 5)
n, _ := f.Read(buf)
if got := string(buf[:n]); got != "world" {
t.Errorf("OpenAt read: got %q, want %q", got, "world")
}
if _, err = OpenAt(d, "nonexistent.txt"); err == nil {
t.Error("expected error for non-existent file")
}
}
func TestOpenDirAt(t *testing.T) {
tmp := t.TempDir()
os.Mkdir(filepath.Join(tmp, "subdir"), 0755)
os.WriteFile(filepath.Join(tmp, "file.txt"), []byte("x"), 0644)
d := openTestDir(t, tmp)
sub, err := OpenDirAt(d, "subdir")
if err != nil {
t.Fatalf("OpenDirAt: %v", err)
}
defer sub.Close()
info, _ := sub.Stat()
if !info.IsDir() {
t.Error("OpenDirAt: expected directory")
}
// Opening a regular file as a directory should fail.
if _, err = OpenDirAt(d, "file.txt"); err == nil {
t.Error("expected error opening regular file as directory")
}
}
func TestCreateAt(t *testing.T) {
tmp := t.TempDir()
d := openTestDir(t, tmp)
f, err := CreateAt(d, "new.txt", 0644)
if err != nil {
t.Fatalf("CreateAt: %v", err)
}
f.WriteString("hello")
f.Close()
if got := mustReadFile(t, filepath.Join(tmp, "new.txt")); got != "hello" {
t.Errorf("CreateAt content: got %q, want %q", got, "hello")
}
// CreateAt on an existing file should truncate it.
f2, err := CreateAt(d, "new.txt", 0644)
if err != nil {
t.Fatalf("CreateAt (truncate): %v", err)
}
f2.WriteString("bye")
f2.Close()
if got := mustReadFile(t, filepath.Join(tmp, "new.txt")); got != "bye" {
t.Errorf("CreateAt truncate: got %q, want %q", got, "bye")
}
}
func TestCreateDirAt(t *testing.T) {
tmp := t.TempDir()
d := openTestDir(t, tmp)
sub, err := CreateDirAt(d, "mydir", 0755)
if err != nil {
t.Fatalf("CreateDirAt new: %v", err)
}
sub.Close()
// Should succeed when the directory already exists.
sub2, err := CreateDirAt(d, "mydir", 0700)
if err != nil {
t.Fatalf("CreateDirAt existing: %v", err)
}
sub2.Close()
}
func TestSymlinkAt(t *testing.T) {
tmp := t.TempDir()
os.WriteFile(filepath.Join(tmp, "target.txt"), []byte("data"), 0644)
d := openTestDir(t, tmp)
if err := SymlinkAt(d, "link.txt", "target.txt"); err != nil {
t.Fatalf("SymlinkAt: %v", err)
}
got, err := os.Readlink(filepath.Join(tmp, "link.txt"))
if err != nil {
t.Fatalf("Readlink: %v", err)
}
if got != "target.txt" {
t.Errorf("symlink target: got %q, want %q", got, "target.txt")
}
// Duplicate symlink should fail.
if err = SymlinkAt(d, "link.txt", "target.txt"); err == nil {
t.Error("expected error for duplicate symlink")
}
}
func TestStatAt(t *testing.T) {
tmp := t.TempDir()
os.WriteFile(filepath.Join(tmp, "file.txt"), []byte("content"), 0644)
os.Symlink("file.txt", filepath.Join(tmp, "link.txt"))
d := openTestDir(t, tmp)
// StatAt follows symlinks.
info, err := StatAt(d, "link.txt")
if err != nil {
t.Fatalf("StatAt: %v", err)
}
if info.Mode()&os.ModeSymlink != 0 {
t.Error("StatAt should dereference symlinks")
}
if !info.Mode().IsRegular() {
t.Error("StatAt: expected regular file after following symlink")
}
if _, err = StatAt(d, "nonexistent"); err == nil {
t.Error("expected error for non-existent file")
}
}
func TestLstatAt(t *testing.T) {
tmp := t.TempDir()
os.WriteFile(filepath.Join(tmp, "file.txt"), []byte("content"), 0644)
os.Symlink("file.txt", filepath.Join(tmp, "link.txt"))
d := openTestDir(t, tmp)
// LstatAt must not follow symlinks.
info, err := LstatAt(d, "link.txt")
if err != nil {
t.Fatalf("LstatAt symlink: %v", err)
}
if info.Mode()&os.ModeSymlink == 0 {
t.Error("LstatAt should not dereference symlinks")
}
info2, err := LstatAt(d, "file.txt")
if err != nil {
t.Fatalf("LstatAt file: %v", err)
}
if !info2.Mode().IsRegular() {
t.Error("LstatAt file: expected regular file")
}
}
func TestUnlinkAt(t *testing.T) {
tmp := t.TempDir()
os.WriteFile(filepath.Join(tmp, "todelete.txt"), []byte("x"), 0644)
d := openTestDir(t, tmp)
if err := UnlinkAt(d, "todelete.txt"); err != nil {
t.Fatalf("UnlinkAt: %v", err)
}
if _, err := os.Stat(filepath.Join(tmp, "todelete.txt")); !os.IsNotExist(err) {
t.Error("file should be removed after UnlinkAt")
}
if err := UnlinkAt(d, "nonexistent"); err == nil {
t.Error("expected error for non-existent file")
}
}
func TestRemoveDirAt(t *testing.T) {
tmp := t.TempDir()
os.Mkdir(filepath.Join(tmp, "empty"), 0755)
os.Mkdir(filepath.Join(tmp, "nonempty"), 0755)
os.WriteFile(filepath.Join(tmp, "nonempty", "f"), []byte(""), 0644)
d := openTestDir(t, tmp)
if err := RemoveDirAt(d, "empty"); err != nil {
t.Fatalf("RemoveDirAt empty: %v", err)
}
if _, err := os.Stat(filepath.Join(tmp, "empty")); !os.IsNotExist(err) {
t.Error("empty dir should be removed")
}
// Non-empty directory must fail.
if err := RemoveDirAt(d, "nonempty"); err == nil {
t.Error("expected error removing non-empty directory")
}
}
func TestLinkAt(t *testing.T) {
tmp := t.TempDir()
os.WriteFile(filepath.Join(tmp, "original.txt"), []byte("data"), 0644)
d := openTestDir(t, tmp)
if err := LinkAt(d, "original.txt", d, "hardlink.txt", false); err != nil {
t.Fatalf("LinkAt: %v", err)
}
info1, _ := os.Stat(filepath.Join(tmp, "original.txt"))
info2, _ := os.Stat(filepath.Join(tmp, "hardlink.txt"))
s1 := info1.Sys().(*syscall.Stat_t)
s2 := info2.Sys().(*syscall.Stat_t)
if s1.Ino != s2.Ino {
t.Error("hard link should share the same inode")
}
}
func TestReadLinkAt(t *testing.T) {
tmp := t.TempDir()
os.Symlink("/absolute/path", filepath.Join(tmp, "abslink"))
os.Symlink("relative/path", filepath.Join(tmp, "rellink"))
os.WriteFile(filepath.Join(tmp, "regular"), []byte("x"), 0644)
d := openTestDir(t, tmp)
abs, err := ReadLinkAt(d, "abslink")
if err != nil {
t.Fatalf("ReadLinkAt abs: %v", err)
}
if abs != "/absolute/path" {
t.Errorf("abs link: got %q, want %q", abs, "/absolute/path")
}
rel, err := ReadLinkAt(d, "rellink")
if err != nil {
t.Fatalf("ReadLinkAt rel: %v", err)
}
if rel != "relative/path" {
t.Errorf("rel link: got %q, want %q", rel, "relative/path")
}
// ReadLinkAt on a regular file must fail.
if _, err = ReadLinkAt(d, "regular"); err == nil {
t.Error("expected error for ReadLinkAt on regular file")
}
}
func TestDupFile(t *testing.T) {
tmp := t.TempDir()
f, err := os.CreateTemp(tmp, "dup")
if err != nil {
t.Fatal(err)
}
defer f.Close()
f.WriteString("original")
dup, err := DupFile(f)
if err != nil {
t.Fatalf("DupFile: %v", err)
}
defer dup.Close()
// Read from the duplicate.
dup.Seek(0, 0)
buf := make([]byte, 8)
n, _ := dup.Read(buf)
if got := string(buf[:n]); got != "original" {
t.Errorf("dup read: got %q, want %q", got, "original")
}
// Closing the dup should not affect the original.
dup.Close()
f.Seek(0, 0)
buf2 := make([]byte, 8)
n2, _ := f.Read(buf2)
if got := string(buf2[:n2]); got != "original" {
t.Errorf("original after dup close: got %q, want %q", got, "original")
}
}
func TestRenameAt(t *testing.T) {
tmp := t.TempDir()
os.WriteFile(filepath.Join(tmp, "src.txt"), []byte("hello"), 0644)
d := openTestDir(t, tmp)
// Rename within the same directory.
if err := RenameAt(d, "src.txt", d, "dst.txt"); err != nil {
t.Fatalf("RenameAt same dir: %v", err)
}
if _, err := os.Stat(filepath.Join(tmp, "src.txt")); !os.IsNotExist(err) {
t.Error("src.txt should no longer exist after rename")
}
if got := mustReadFile(t, filepath.Join(tmp, "dst.txt")); got != "hello" {
t.Errorf("dst.txt after rename: got %q, want %q", got, "hello")
}
// Rename to a different directory.
sub := filepath.Join(tmp, "subdir")
os.Mkdir(sub, 0755)
subDir := openTestDir(t, sub)
if err := RenameAt(d, "dst.txt", subDir, "moved.txt"); err != nil {
t.Fatalf("RenameAt cross-dir: %v", err)
}
if _, err := os.Stat(filepath.Join(tmp, "dst.txt")); !os.IsNotExist(err) {
t.Error("dst.txt should no longer exist after cross-dir rename")
}
if got := mustReadFile(t, filepath.Join(sub, "moved.txt")); got != "hello" {
t.Errorf("moved.txt: got %q, want %q", got, "hello")
}
// Renaming a non-existent file should return an error.
if err := RenameAt(d, "nonexistent.txt", d, "out.txt"); err == nil {
t.Error("expected error when renaming non-existent file")
}
// Rename overwrites an existing destination file.
os.WriteFile(filepath.Join(tmp, "a.txt"), []byte("aaa"), 0644)
os.WriteFile(filepath.Join(tmp, "b.txt"), []byte("bbb"), 0644)
if err := RenameAt(d, "a.txt", d, "b.txt"); err != nil {
t.Fatalf("RenameAt overwrite: %v", err)
}
if _, err := os.Stat(filepath.Join(tmp, "a.txt")); !os.IsNotExist(err) {
t.Error("a.txt should be gone after overwrite rename")
}
if got := mustReadFile(t, filepath.Join(tmp, "b.txt")); got != "aaa" {
t.Errorf("b.txt after overwrite: got %q, want %q", got, "aaa")
}
// Renaming a symlink should move the symlink itself, not the target.
os.WriteFile(filepath.Join(tmp, "target.txt"), []byte("target"), 0644)
os.Symlink("target.txt", filepath.Join(tmp, "link.txt"))
if err := RenameAt(d, "link.txt", d, "renamedlink.txt"); err != nil {
t.Fatalf("RenameAt symlink: %v", err)
}
linkTarget, err := os.Readlink(filepath.Join(tmp, "renamedlink.txt"))
if err != nil {
t.Fatalf("Readlink after rename: %v", err)
}
if linkTarget != "target.txt" {
t.Errorf("renamed symlink target: got %q, want %q", linkTarget, "target.txt")
}
}
// --- RemoveChildren tests (pre-existing, kept for reference) ---
func TestRemoveChildren(t *testing.T) {
tmpDir := t.TempDir()
subDir := filepath.Join(tmpDir, "subdir")
os.Mkdir(subDir, 0755)
os.WriteFile(filepath.Join(tmpDir, "file1.txt"), []byte("data"), 0644)
os.WriteFile(filepath.Join(subDir, "file2.txt"), []byte("data"), 0644)
d, err := os.Open(tmpDir)
if err != nil {
t.Fatal(err)
}
defer d.Close()
if err := RemoveChildren(d); err != nil {
t.Errorf("expected no error, got %v", err)
}
entries, _ := os.ReadDir(tmpDir)
if len(entries) != 0 {
t.Errorf("expected 0 entries after RemoveChildren, got %d", len(entries))
}
}
func TestRemoveChildren_FirstError(t *testing.T) {
tmpDir := t.TempDir()
lockedFile := filepath.Join(tmpDir, "locked")
os.WriteFile(lockedFile, nil, 0000)
d, _ := os.Open(tmpDir)
defer d.Close()
err := RemoveChildren(d)
if err != nil {
if _, ok := err.(*os.PathError); !ok {
t.Errorf("expected *os.PathError, got %T", err)
}
}
}
// --- CopyFolderContents tests ---
// buildDeepTree creates the following 3-level structure under base:
//
// base/
//
// file1.txt ("level1")
// link_to_file1 -> file1.txt
// subdir1/
// file2.txt ("level2")
// subdir2/
// file3.txt ("level3")
// link_to_top -> ../../file1.txt
// subdir3/
// file4.txt ("deepest")
func buildDeepTree(t *testing.T, base string) {
t.Helper()
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
must(os.WriteFile(filepath.Join(base, "file1.txt"), []byte("level1"), 0644))
must(os.Symlink("file1.txt", filepath.Join(base, "link_to_file1")))
sub1 := filepath.Join(base, "subdir1")
must(os.Mkdir(sub1, 0755))
must(os.WriteFile(filepath.Join(sub1, "file2.txt"), []byte("level2"), 0644))
sub2 := filepath.Join(sub1, "subdir2")
must(os.Mkdir(sub2, 0755))
must(os.WriteFile(filepath.Join(sub2, "file3.txt"), []byte("level3"), 0644))
must(os.Symlink("../../file1.txt", filepath.Join(sub2, "link_to_top")))
sub3 := filepath.Join(sub2, "subdir3")
must(os.Mkdir(sub3, 0755))
must(os.WriteFile(filepath.Join(sub3, "file4.txt"), []byte("deepest"), 0644))
}
func TestCopyFolderContents_NoHardlinks_NoFollowSymlinks(t *testing.T) {
tmp := t.TempDir()
src := filepath.Join(tmp, "src")
dst := filepath.Join(tmp, "dst")
os.MkdirAll(src, 0755)
os.MkdirAll(dst, 0755)
buildDeepTree(t, src)
srcDir := openTestDir(t, src)
dstDir := openTestDir(t, dst)
err := CopyFolderContents(context.Background(), srcDir, dstDir, CopyFolderOptions{
Disallow_hardlinks: true,
Follow_symlinks: false,
})
if err != nil {
t.Fatalf("CopyFolderContents: %v", err)
}
// All files should be present with correct contents.
cases := []struct{ path, want string }{
{"file1.txt", "level1"},
{"subdir1/file2.txt", "level2"},
{"subdir1/subdir2/file3.txt", "level3"},
{"subdir1/subdir2/subdir3/file4.txt", "deepest"},
}
for _, c := range cases {
got := mustReadFile(t, filepath.Join(dst, c.path))
if got != c.want {
t.Errorf("%s: got %q, want %q", c.path, got, c.want)
}
}
// Symlinks should be copied verbatim (not resolved).
symlinks := []struct{ path, want string }{
{"link_to_file1", "file1.txt"},
{"subdir1/subdir2/link_to_top", "../../file1.txt"},
}
for _, s := range symlinks {
got, err := os.Readlink(filepath.Join(dst, s.path))
if err != nil {
t.Fatalf("readlink %s: %v", s.path, err)
}
if got != s.want {
t.Errorf("symlink %s: got target %q, want %q", s.path, got, s.want)
}
}
// With Disallow_hardlinks, files must have different inodes from source.
srcInfo, _ := os.Stat(filepath.Join(src, "file1.txt"))
dstInfo, _ := os.Stat(filepath.Join(dst, "file1.txt"))
if srcInfo.Sys().(*syscall.Stat_t).Ino == dstInfo.Sys().(*syscall.Stat_t).Ino {
t.Error("files should not share inodes when Disallow_hardlinks=true")
}
}
func TestCopyFolderContents_WithHardlinks(t *testing.T) {
tmp := t.TempDir()
src := filepath.Join(tmp, "src")
dst := filepath.Join(tmp, "dst")
os.MkdirAll(src, 0755)
os.MkdirAll(dst, 0755)
os.WriteFile(filepath.Join(src, "file.txt"), []byte("data"), 0644)
os.Mkdir(filepath.Join(src, "sub"), 0755)
os.WriteFile(filepath.Join(src, "sub", "file2.txt"), []byte("data2"), 0644)
srcDir := openTestDir(t, src)
dstDir := openTestDir(t, dst)
err := CopyFolderContents(context.Background(), srcDir, dstDir, CopyFolderOptions{
Disallow_hardlinks: false,
Follow_symlinks: false,
})
if err != nil {
t.Fatalf("CopyFolderContents: %v", err)
}
// Regular files must share inodes (hardlinked).
for _, name := range []string{"file.txt", "sub/file2.txt"} {
sInfo, _ := os.Stat(filepath.Join(src, name))
dInfo, _ := os.Stat(filepath.Join(dst, name))
sIno := sInfo.Sys().(*syscall.Stat_t).Ino
dIno := dInfo.Sys().(*syscall.Stat_t).Ino
if sIno != dIno {
t.Errorf("%s: expected same inode (hardlink), got src=%d dst=%d", name, sIno, dIno)
}
}
}
// TestCopyFolderContents_SymlinkLoop verifies that a symlink creating a
// directory loop (a -> .) is correctly handled: the already-copied directory
// appears as a relative symlink in the destination.
func TestCopyFolderContents_SymlinkLoop(t *testing.T) {
tmp := t.TempDir()
src := filepath.Join(tmp, "src")
dst := filepath.Join(tmp, "dst")
os.MkdirAll(src, 0755)
os.MkdirAll(dst, 0755)
// src/loop -> . (points back to src itself, creating a loop)
os.Symlink(".", filepath.Join(src, "loop"))
os.WriteFile(filepath.Join(src, "file.txt"), []byte("hello"), 0644)
srcDir := openTestDir(t, src)
dstDir := openTestDir(t, dst)
err := CopyFolderContents(context.Background(), srcDir, dstDir, CopyFolderOptions{
Disallow_hardlinks: true,
Follow_symlinks: true,
})
if err != nil {
t.Fatalf("CopyFolderContents with loop: %v", err)
}
// file.txt must be present with correct content.
if got := mustReadFile(t, filepath.Join(dst, "file.txt")); got != "hello" {
t.Errorf("file.txt: got %q, want %q", got, "hello")
}
// loop must exist and be a symlink (not cause infinite recursion).
linfo, err := os.Lstat(filepath.Join(dst, "loop"))
if err != nil {
t.Fatalf("lstat dst/loop: %v", err)
}
if linfo.Mode()&os.ModeSymlink == 0 {
t.Error("dst/loop should be a symlink (loop broken by relative back-reference)")
}
}
// TestCopyFolderContents_FollowSymlinks_DirectorySymlink tests that when
// Follow_symlinks is true and a symlink points to a subdirectory, the
// directory contents are copied (and the underlying fd is kept alive long
// enough for next_dir to process the queued item — the key bug being tested).
func TestCopyFolderContents_FollowSymlinks_DirectorySymlink(t *testing.T) {
tmp := t.TempDir()
src := filepath.Join(tmp, "src")
dst := filepath.Join(tmp, "dst")
os.MkdirAll(src, 0755)
os.MkdirAll(dst, 0755)
// src/subdir/ with a file, and src/link_to_subdir -> subdir
subdir := filepath.Join(src, "subdir")
os.Mkdir(subdir, 0755)
os.WriteFile(filepath.Join(subdir, "inner.txt"), []byte("inner"), 0644)
os.Symlink("subdir", filepath.Join(src, "link_to_subdir"))
srcDir := openTestDir(t, src)
dstDir := openTestDir(t, dst)
err := CopyFolderContents(context.Background(), srcDir, dstDir, CopyFolderOptions{
Disallow_hardlinks: true,
Follow_symlinks: true,
})
if err != nil {
t.Fatalf("CopyFolderContents (follow symlink to dir): %v", err)
}
// The real subdir must be copied.
if got := mustReadFile(t, filepath.Join(dst, "subdir", "inner.txt")); got != "inner" {
t.Errorf("subdir/inner.txt: got %q, want %q", got, "inner")
}
}
// TestCopyFolderContents_DeepTree_FollowSymlinks copies the 3-level tree
// with Follow_symlinks=true. Symlinks that cross directory boundaries are
// resolved; symlinks whose targets resolve to the same source file become a
// relative symlink in the destination pointing at the already-copied file.
func TestCopyFolderContents_DeepTree_FollowSymlinks(t *testing.T) {
tmp := t.TempDir()
src := filepath.Join(tmp, "src")
dst := filepath.Join(tmp, "dst")
os.MkdirAll(src, 0755)
os.MkdirAll(dst, 0755)
buildDeepTree(t, src)
srcDir := openTestDir(t, src)
dstDir := openTestDir(t, dst)
err := CopyFolderContents(context.Background(), srcDir, dstDir, CopyFolderOptions{
Disallow_hardlinks: true,
Follow_symlinks: true,
})
if err != nil {
t.Fatalf("CopyFolderContents (follow): %v", err)
}
// Deep regular files must be present.
for _, c := range []struct{ path, want string }{
{"file1.txt", "level1"},
{"subdir1/file2.txt", "level2"},
{"subdir1/subdir2/file3.txt", "level3"},
{"subdir1/subdir2/subdir3/file4.txt", "deepest"},
} {
got := mustReadFile(t, filepath.Join(dst, c.path))
if got != c.want {
t.Errorf("%s: got %q, want %q", c.path, got, c.want)
}
}
}
// TestCopyFolderContents_FilterFiles checks that Filter_files can exclude entries.
func TestCopyFolderContents_FilterFiles(t *testing.T) {
tmp := t.TempDir()
src := filepath.Join(tmp, "src")
dst := filepath.Join(tmp, "dst")
os.MkdirAll(src, 0755)
os.MkdirAll(dst, 0755)
os.WriteFile(filepath.Join(src, "keep.txt"), []byte("keep"), 0644)
os.WriteFile(filepath.Join(src, "skip.txt"), []byte("skip"), 0644)
srcDir := openTestDir(t, src)
dstDir := openTestDir(t, dst)
err := CopyFolderContents(context.Background(), srcDir, dstDir, CopyFolderOptions{
Disallow_hardlinks: true,
Filter_files: func(_ *os.File, fi os.FileInfo) bool {
return fi.Name() != "skip.txt"
},
})
if err != nil {
t.Fatalf("CopyFolderContents (filter): %v", err)
}
if _, err := os.Stat(filepath.Join(dst, "keep.txt")); err != nil {
t.Error("keep.txt should be present")
}
if _, err := os.Stat(filepath.Join(dst, "skip.txt")); !os.IsNotExist(err) {
t.Error("skip.txt should have been filtered out")
}
}
// TestCopyFolderContents_CancelledContext verifies that cancellation is
// respected and does not leak file descriptors.
func TestCopyFolderContents_CancelledContext(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("FD leak check requires Linux /proc/self/fd")
}
tmp := t.TempDir()
src := filepath.Join(tmp, "src")
dst := filepath.Join(tmp, "dst")
os.MkdirAll(src, 0755)
os.MkdirAll(dst, 0755)
buildDeepTree(t, src)
srcDir := openTestDir(t, src)
dstDir := openTestDir(t, dst)
ctx, cancel := context.WithCancel(context.Background())
cancel() // pre-cancel
before := countOpenFDs()
_ = CopyFolderContents(ctx, srcDir, dstDir, CopyFolderOptions{
Disallow_hardlinks: true,
})
after := countOpenFDs()
if after > before {
t.Errorf("FD leak after cancelled copy: before=%d after=%d", before, after)
}
}
// TestCopyFolderContents_FDLeaks_Normal verifies that a complete, successful
// copy does not leak file descriptors.
func TestCopyFolderContents_FDLeaks_Normal(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("FD leak check requires Linux /proc/self/fd")
}
tmp := t.TempDir()
src := filepath.Join(tmp, "src")
dst := filepath.Join(tmp, "dst")
os.MkdirAll(src, 0755)
os.MkdirAll(dst, 0755)
buildDeepTree(t, src)
srcDir := openTestDir(t, src)
dstDir := openTestDir(t, dst)
before := countOpenFDs()
err := CopyFolderContents(context.Background(), srcDir, dstDir, CopyFolderOptions{
Disallow_hardlinks: true,
Follow_symlinks: false,
})
after := countOpenFDs()
if err != nil {
t.Fatalf("CopyFolderContents: %v", err)
}
if after > before {
t.Errorf("FD leak in normal copy: before=%d after=%d", before, after)
}
}
// TestCopyFolderContents_FDLeaks_FollowSymlinks_DirSymlink exercises the
// code path that was previously buggy: a symlink pointing to a directory when
// Follow_symlinks=true. Without the fix, the directory fd would be closed
// before next_dir processed the queue item. This test verifies both
// correctness (copy succeeds) and the absence of FD leaks.
func TestCopyFolderContents_FDLeaks_FollowSymlinks_DirSymlink(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("FD leak check requires Linux /proc/self/fd")
}
tmp := t.TempDir()
src := filepath.Join(tmp, "src")
dst := filepath.Join(tmp, "dst")
os.MkdirAll(src, 0755)
os.MkdirAll(dst, 0755)
subdir := filepath.Join(src, "subdir")
os.Mkdir(subdir, 0755)
os.WriteFile(filepath.Join(subdir, "deep.txt"), []byte("deep"), 0644)
// Symlink pointing to the subdirectory — the key bug scenario.
os.Symlink("subdir", filepath.Join(src, "link_to_subdir"))
srcDir := openTestDir(t, src)
dstDir := openTestDir(t, dst)
before := countOpenFDs()
err := CopyFolderContents(context.Background(), srcDir, dstDir, CopyFolderOptions{
Disallow_hardlinks: true,
Follow_symlinks: true,
})
after := countOpenFDs()
if err != nil {
t.Fatalf("CopyFolderContents (dir symlink): %v", err)
}
if after > before {
t.Errorf("FD leak with dir symlink: before=%d after=%d", before, after)
}
// The real subdir contents must appear in the destination.
if got := mustReadFile(t, filepath.Join(dst, "subdir", "deep.txt")); got != "deep" {
t.Errorf("subdir/deep.txt: got %q, want %q", got, "deep")
}
}
+50
View File
@@ -0,0 +1,50 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"errors"
"fmt"
"io/fs"
"os"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func lock(fd, op int, path string) (err error) {
for {
err = unix.Flock(fd, op)
if !errors.Is(err, unix.EINTR) {
break
}
}
if err != nil {
opname := "exclusive flock()"
switch op {
case unix.LOCK_UN:
opname = "unlock flock()"
case unix.LOCK_SH:
opname = "shared flock()"
}
return &fs.PathError{
Op: opname,
Path: path,
Err: err,
}
}
return nil
}
func LockFileShared(f *os.File) error {
return lock(int(f.Fd()), unix.LOCK_SH, f.Name())
}
func LockFileExclusive(f *os.File) error {
return lock(int(f.Fd()), unix.LOCK_EX, f.Name())
}
func UnlockFile(f *os.File) error {
return lock(int(f.Fd()), unix.LOCK_UN, f.Name())
}
+43
View File
@@ -0,0 +1,43 @@
// License: GPLv3 Copyright: 2024, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"os"
"os/exec"
"testing"
)
var _ = fmt.Print
func TestFileLock(t *testing.T) {
tdir := t.TempDir()
file_descriptor, err := os.Open(tdir)
if err != nil {
t.Fatalf("Initial open of %s failed with error: %s", tdir, err)
}
if err = LockFileExclusive(file_descriptor); err != nil {
file_descriptor.Close()
t.Fatalf("Initial lock of %s failed with error: %s", tdir, err)
}
defer func() {
_ = UnlockFile(file_descriptor)
file_descriptor.Close()
}()
cmd := exec.Command(KittyExe(), "+runpy", `
import sys, os, fcntl
fd = os.open(sys.argv[-1], os.O_RDONLY)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
sys.exit(0)
else:
print("Lock unexpectedly succeeded", flush=True)
sys.exit(1)
`, tdir)
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("Lock test process failed with error: %s and output:\n%s", err, string(output))
}
}
+21
View File
@@ -0,0 +1,21 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"os"
"sync"
)
var _ = fmt.Print
var hostname string = "*"
var Hostname = sync.OnceValue(func() string {
h, err := os.Hostname()
if err == nil {
return h
}
return ""
})
+104
View File
@@ -0,0 +1,104 @@
package humanize
import (
"fmt"
"math"
"strconv"
"strings"
"golang.org/x/exp/constraints"
)
// IEC Sizes.
// kibis of bits
const (
Byte = 1 << (iota * 10)
KiByte
MiByte
GiByte
TiByte
PiByte
EiByte
)
// SI Sizes.
const (
IByte = 1
KByte = IByte * 1000
MByte = KByte * 1000
GByte = MByte * 1000
TByte = GByte * 1000
PByte = TByte * 1000
EByte = PByte * 1000
)
func logn(n, b float64) float64 {
return math.Log(n) / math.Log(b)
}
func humanize_bytes(s uint64, base float64, sizes []string, sep string) string {
if s < 10 {
return fmt.Sprintf("%d%sB", s, sep)
}
e := math.Floor(logn(float64(s), base))
suffix := sizes[int(e)]
val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10
f := "%.0f%s%s"
if val < 10 {
f = "%.1f%s%s"
}
return fmt.Sprintf(f, val, sep, suffix)
}
// Bytes produces a human readable representation of an SI size.
// Bytes(82854982) -> 83 MB
func Bytes(s uint64) string {
return Size(s, SizeOptions{})
}
// IBytes produces a human readable representation of an IEC size.
// IBytes(82854982) -> 79 MiB
func IBytes(s uint64) string {
return Size(s, SizeOptions{Base: 1024})
}
type SizeOptions struct {
Separator string
Base int
}
func Size[T constraints.Integer | constraints.Float](s T, opts ...SizeOptions) string {
var o SizeOptions
prefix := ""
if len(opts) == 0 {
o = SizeOptions{}
} else {
o = opts[0]
}
if s < 0 {
prefix = "-"
}
if o.Separator == "" {
o.Separator = " "
}
if o.Base == 0 {
o.Base = 1000
}
var sizes []string
switch o.Base {
default:
sizes = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"}
case 1024:
sizes = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
}
return prefix + humanize_bytes(uint64(s), float64(o.Base), sizes, o.Separator)
}
func FormatNumber[T constraints.Float](n T, max_num_of_decimals ...int) string {
prec := 2
if len(max_num_of_decimals) > 0 {
prec = max_num_of_decimals[0]
}
ans := strconv.FormatFloat(float64(n), 'f', prec, 64)
return strings.TrimRight(strings.TrimRight(ans, "0"), ".")
}
+167
View File
@@ -0,0 +1,167 @@
package humanize
import (
"fmt"
"github.com/kovidgoyal/kitty/tools/wcswidth"
"math"
"sort"
"strings"
"time"
)
// Seconds-based time units
const (
Day = 24 * time.Hour
Week = 7 * Day
Month = 30 * Day
Year = 12 * Month
LongTime = 37 * Year
)
// Time formats a time into a relative string.
//
// Time(someT) -> "3 weeks ago"
func Time(then time.Time) string {
return RelTime(then, time.Now(), "ago", "from now")
}
// A RelTimeMagnitude struct contains a relative time point at which
// the relative format of time will switch to a new format string. A
// slice of these in ascending order by their "D" field is passed to
// CustomRelTime to format durations.
//
// The Format field is a string that may contain a "%s" which will be
// replaced with the appropriate signed label (e.g. "ago" or "from
// now") and a "%d" that will be replaced by the quantity.
//
// The DivBy field is the amount of time the time difference must be
// divided by in order to display correctly.
//
// e.g. if D is 2*time.Minute and you want to display "%d minutes %s"
// DivBy should be time.Minute so whatever the duration is will be
// expressed in minutes.
type RelTimeMagnitude struct {
D time.Duration
Format string
DivBy time.Duration
}
var defaultMagnitudes = []RelTimeMagnitude{
{time.Second, "now", time.Second},
{2 * time.Second, "1 second %s", 1},
{time.Minute, "%d seconds %s", time.Second},
{2 * time.Minute, "1 minute %s", 1},
{time.Hour, "%d minutes %s", time.Minute},
{2 * time.Hour, "1 hour %s", 1},
{Day, "%d hours %s", time.Hour},
{2 * Day, "1 day %s", 1},
{Week, "%d days %s", Day},
{2 * Week, "1 week %s", 1},
{Month, "%d weeks %s", Week},
{2 * Month, "1 month %s", 1},
{Year, "%d months %s", Month},
{18 * Month, "1 year %s", 1},
{2 * Year, "2 years %s", 1},
{LongTime, "%d years %s", Year},
{math.MaxInt64, "a long while %s", 1},
}
// RelTime formats a time into a relative string.
//
// It takes two times and two labels. In addition to the generic time
// delta string (e.g. 5 minutes), the labels are used applied so that
// the label corresponding to the smaller time is applied.
//
// RelTime(timeInPast, timeInFuture, "earlier", "later") -> "3 weeks earlier"
func RelTime(a, b time.Time, albl, blbl string) string {
return CustomRelTime(a, b, albl, blbl, defaultMagnitudes)
}
// CustomRelTime formats a time into a relative string.
//
// It takes two times two labels and a table of relative time formats.
// In addition to the generic time delta string (e.g. 5 minutes), the
// labels are used applied so that the label corresponding to the
// smaller time is applied.
func CustomRelTime(a, b time.Time, albl, blbl string, magnitudes []RelTimeMagnitude) string {
lbl := albl
diff := b.Sub(a)
if a.After(b) {
lbl = blbl
diff = a.Sub(b)
}
n := sort.Search(len(magnitudes), func(i int) bool {
return magnitudes[i].D > diff
})
if n >= len(magnitudes) {
n = len(magnitudes) - 1
}
mag := magnitudes[n]
args := []any{}
escaped := false
for _, ch := range mag.Format {
if escaped {
switch ch {
case 's':
args = append(args, lbl)
case 'd':
args = append(args, diff/mag.DivBy)
}
escaped = false
} else {
escaped = ch == '%'
}
}
return fmt.Sprintf(mag.Format, args...)
}
func optional_cut(x string, sep string) (string, string) {
a, b, found := strings.Cut(x, sep)
if found {
return a, b
}
return "00", a
}
func zero_pad(x string) string {
if len(x) < 2 {
x = strings.Repeat("0", 2-len(x)) + x
}
return x
}
// Render the duration in exactly 8 visual chars
func ShortDuration(val time.Duration) (ans string) {
if val >= time.Second {
if val > Day {
days := int(val.Hours() / 24)
if days > 99 {
ans = `∞`
} else {
if days == 1 {
ans = ">1 day"
} else {
ans = fmt.Sprintf(">%d days", int(days))
}
}
} else {
ans = val.String()
hr, rest := optional_cut(ans, `h`)
min, rest := optional_cut(rest, `m`)
secs, _, _ := strings.Cut(rest, ".")
secs = strings.Replace(secs, `s`, ``, 1)
ans = zero_pad(hr) + `:` + zero_pad(min) + `:` + zero_pad(secs)
}
} else {
ans = "<1 sec"
}
if w := wcswidth.Stringwidth(ans); w < 8 {
ans = strings.Repeat(" ", 8-w) + ans
} else if w > 8 {
ans = wcswidth.TruncateToVisualLength(ans, 8)
}
return
}
+35
View File
@@ -0,0 +1,35 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package humanize
import (
"fmt"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
func TestShortDuration(t *testing.T) {
q := func(i float64, e string) {
d := time.Duration(i * float64(time.Second))
if diff := cmp.Diff(e, ShortDuration(d)); diff != "" {
t.Fatalf("Failed for %f (%s): %s", i, d, diff)
}
}
q(0.1, " <1 sec")
q(1, `00:00:01`)
q(1.1234567, `00:00:01`)
q(60.1234567, `00:01:00`)
q(61.1234567, `00:01:01`)
q(3600, `01:00:00`)
q(3601.1234567, `01:00:01`)
day := 24. * 3600.
q(day, "24:00:00")
q(day+1, " >1 day")
q(day*2, " >2 days")
q(day*23, ">23 days")
q(day*999, " ∞")
}
+157
View File
@@ -0,0 +1,157 @@
package images
import (
"bytes"
"encoding/binary"
"fmt"
"image"
"io"
"os"
"slices"
"strconv"
"strings"
"github.com/kovidgoyal/imaging"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func encode_rgba(output io.Writer, img image.Image) (err error) {
var final_img *image.NRGBA
switch ti := img.(type) {
case *image.NRGBA:
final_img = ti
default:
b := img.Bounds()
final_img = image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
ctx := Context{}
ctx.PasteCenter(final_img, img, nil)
}
b := final_img.Bounds()
header := make([]byte, 8)
var width = utils.Abs(b.Dx())
var height = utils.Abs(b.Dy())
binary.LittleEndian.PutUint32(header, uint32(width))
binary.LittleEndian.PutUint32(header[4:], uint32(height))
readers := []io.Reader{bytes.NewReader(header)}
stride := 4 * width
if final_img.Stride == stride {
readers = append(readers, bytes.NewReader(final_img.Pix))
} else {
p := final_img.Pix
for y := 0; y < b.Dy(); y++ {
readers = append(readers, bytes.NewReader(p[:min(stride, len(p))]))
p = p[final_img.Stride:]
}
}
_, err = io.Copy(output, io.MultiReader(readers...))
return
}
func convert_image(input io.ReadSeeker, output io.Writer, format string) (err error) {
img, err := imaging.Decode(input)
if err != nil {
return err
}
q := strings.ToLower(format)
if q == "rgba" {
return encode_rgba(output, img)
}
mt := utils.GuessMimeType("file." + q)
if mt == "" {
return fmt.Errorf("Unknown image output format: %s", format)
}
return Encode(output, img, mt)
}
func images_equal(img, rimg *ImageData) (err error) {
for i := range img.Frames {
a, b := img.Frames[i], rimg.Frames[i]
if a.Img.Bounds() != b.Img.Bounds() {
return fmt.Errorf("bounds of frame %d not equal: %v != %v", i, a.Img.Bounds(), b.Img.Bounds())
}
for y := a.Img.Bounds().Min.Y; y < a.Img.Bounds().Max.Y; y++ {
for x := a.Img.Bounds().Min.X; x < a.Img.Bounds().Max.X; x++ {
or, og, ob, oa := a.Img.At(x, y).RGBA()
nr, ng, nb, na := b.Img.At(x, y).RGBA()
a, b := []uint32{or, og, ob, oa}, []uint32{nr, ng, nb, na}
if !slices.Equal(a, b) {
return fmt.Errorf("pixel at %dx%d differs: %v != %v", x, y, a, b)
}
}
}
}
return
}
func develop_serialize(input_data io.ReadSeeker) (err error) {
img, _, err := OpenImageFromReader(input_data)
if err != nil {
return err
}
m, b := img.Serialize()
rimg, err := ImageFromSerialized(m, b)
if err != nil {
return err
}
return images_equal(img, rimg)
}
func develop_resize(spec string, input_data io.ReadSeeker) (err error) {
ws, hs, _ := strings.Cut(spec, "x")
var w, h int
if w, err = strconv.Atoi(ws); err != nil {
return
}
if h, err = strconv.Atoi(hs); err != nil {
return
}
img, _, err := OpenImageFromReader(input_data)
if err != nil {
return err
}
aimg := img.Resize(float64(w)/float64(img.Width), float64(h)/float64(img.Height))
m, b := img.Serialize()
rimg, err := ImageFromSerialized(m, b)
if err != nil {
return err
}
if err = images_equal(img, rimg); err != nil {
return fmt.Errorf("roundtripped images not equal: %w", err)
}
bimg := rimg.Resize(float64(w)/float64(rimg.Width), float64(h)/float64(rimg.Height))
return images_equal(aimg, bimg)
}
func ConvertEntryPoint(root *cli.Command) {
root.AddSubCommand(&cli.Command{
Name: "__convert_image__",
Hidden: true,
OnlyArgsAllowed: true,
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
if len(args) != 1 {
return 1, fmt.Errorf("Usage: __convert_image__ OUTPUT_FORMAT")
}
format := args[0]
buf := bytes.NewBuffer(make([]byte, 0, 1024*1024))
if _, err = io.Copy(buf, os.Stdin); err != nil {
return 1, err
}
input_data := bytes.NewReader(buf.Bytes())
switch {
case format == "develop-serialize":
err = develop_serialize(input_data)
case strings.HasPrefix(format, "develop-resize-"):
err = develop_resize(format[len("develop-resize-"):], input_data)
default:
err = convert_image(input_data, os.Stdout, format)
}
rc = utils.IfElse(err == nil, 0, 1)
return
},
})
}
+49
View File
@@ -0,0 +1,49 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package images
import (
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"golang.org/x/image/bmp"
"golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
)
var _ = fmt.Print
var DecodableImageTypes = map[string]bool{
"image/jpeg": true, "image/png": true, "image/bmp": true, "image/tiff": true, "image/webp": true, "image/gif": true,
"image/x-portable-anymap": true,
"image/x-portable-bitmap": true,
"image/x-portable-graymap": true,
"image/x-portable-pixmap": true,
"image/x-portable-arbitrarymap": true,
}
var EncodableImageTypes = map[string]bool{
"image/jpeg": true, "image/png": true, "image/bmp": true, "image/tiff": true, "image/gif": true,
}
func Encode(output io.Writer, img image.Image, format_mime string) (err error) {
switch format_mime {
case "image/png":
return png.Encode(output, img)
case "image/jpeg":
return jpeg.Encode(output, img, nil)
case "image/bmp":
return bmp.Encode(output, img)
case "image/gif":
return gif.Encode(output, img, nil)
case "image/tiff":
return tiff.Encode(output, img, nil)
}
err = fmt.Errorf("Unsupported output image MIME type %s", format_mime)
return
}
+251
View File
@@ -0,0 +1,251 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package images
import (
"fmt"
"image"
"image/png"
"io"
"os"
"strings"
"github.com/kovidgoyal/go-parallel"
shm "github.com/kovidgoyal/go-shm/v2"
"github.com/kovidgoyal/imaging/nrgb"
"github.com/kovidgoyal/imaging"
)
var _ = fmt.Print
const TempTemplate = "kitty-tty-graphics-protocol-*"
func CreateTemp() (*os.File, error) {
return os.CreateTemp("", TempTemplate)
}
func CreateTempInRAM() (*os.File, error) {
if shm.SHM_DIR != "" {
f, err := os.CreateTemp(shm.SHM_DIR, TempTemplate)
if err == nil {
return f, err
}
}
return CreateTemp()
}
type ImageFrame struct {
Width, Height, Left, Top int
Number int // 1-based number
Compose_onto int // number of frame to compose onto
Delay_ms int32 // negative for gapless frame, zero ignored, positive is number of ms
Replace bool // do a replace rather than an alpha blend
Is_opaque bool
Img image.Image
}
type SerializableImageFrame struct {
Width, Height, Left, Top int
Number int // 1-based number
Compose_onto int // number of frame to compose onto
Delay_ms int // negative for gapless frame, zero ignored, positive is number of ms
Replace bool // do a replace rather than an alpha blend
Is_opaque bool
Size int // size in bytes of the serialized data
Number_of_channels int
Bits_per_channel int
Has_alpha_channel bool
}
func (s *ImageFrame) Serialize() SerializableImageFrame {
return SerializableImageFrame{
Width: s.Width, Height: s.Height, Left: s.Left, Top: s.Top,
Number: s.Number, Compose_onto: s.Compose_onto, Delay_ms: int(s.Delay_ms),
Is_opaque: s.Is_opaque, Replace: s.Replace,
}
}
func (self *ImageFrame) DataAsSHM(pattern string) (ans shm.MMap, err error) {
_, _, _, d := self.Data()
if ans, err = shm.CreateTemp(pattern, uint64(len(d))); err != nil {
return nil, err
}
copy(ans.Slice(), d)
return
}
func (self *ImageFrame) Data() (num_channels, bits_per_channel int, has_alpha_channel bool, ans []byte) {
if self.Is_opaque {
return 3, 8, false, imaging.AsRGBData8(self.Img)
}
return 4, 8, true, imaging.AsRGBAData8(self.Img)
}
func ImageFrameFromSerialized(s SerializableImageFrame, data []byte) (aa *ImageFrame, err error) {
ans := ImageFrame{
Width: s.Width, Height: s.Height, Left: s.Left, Top: s.Top,
Number: s.Number, Compose_onto: s.Compose_onto, Delay_ms: int32(s.Delay_ms),
Is_opaque: s.Is_opaque || !s.Has_alpha_channel, Replace: s.Replace,
}
bpc := s.Bits_per_channel
if bpc == 0 {
bpc = 8
}
if bpc != 8 {
return nil, fmt.Errorf("serialized image data has unsupported number of bits per channel: %d", bpc)
}
bytes_per_pixel := bpc * s.Number_of_channels / 8
if expected := bytes_per_pixel * s.Width * s.Height; len(data) != expected {
return nil, fmt.Errorf("serialized image data has size: %d != %d", len(data), expected)
}
switch s.Number_of_channels {
case 3, 0:
ans.Img, err = nrgb.NewNRGBWithContiguousRGBPixels(data, s.Left, s.Top, s.Width, s.Height)
case 4:
ans.Img, err = NewNRGBAWithContiguousRGBAPixels(data, s.Left, s.Top, s.Width, s.Height)
default:
return nil, fmt.Errorf("serialized image data has unsupported number of channels: %d", s.Number_of_channels)
}
return &ans, err
}
type ImageData struct {
Width, Height int
Format_uppercase string
Frames []*ImageFrame
}
type SerializableImageMetadata struct {
Version int
Width, Height int
Format_uppercase string
Frames []SerializableImageFrame
}
const SERIALIZE_VERSION = 1
func (self *ImageFrame) SaveAsUncompressedPNG(output io.Writer) error {
encoder := png.Encoder{CompressionLevel: png.NoCompression}
return encoder.Encode(output, self.Img)
}
func (self *ImageData) SerializeOnlyMetadata() SerializableImageMetadata {
f := make([]SerializableImageFrame, len(self.Frames))
for i, s := range self.Frames {
f[i] = s.Serialize()
}
return SerializableImageMetadata{Version: SERIALIZE_VERSION, Width: self.Width, Height: self.Height, Format_uppercase: self.Format_uppercase, Frames: f}
}
func (self *ImageData) Serialize() (SerializableImageMetadata, [][]byte) {
m := self.SerializeOnlyMetadata()
data := make([][]byte, len(self.Frames))
for i, f := range self.Frames {
df := &m.Frames[i]
df.Number_of_channels, df.Bits_per_channel, df.Has_alpha_channel, data[i] = f.Data()
df.Size = len(data[i])
if !df.Has_alpha_channel {
df.Is_opaque = true
}
}
return m, data
}
func ImageFromSerialized(m SerializableImageMetadata, data [][]byte) (*ImageData, error) {
if m.Version > SERIALIZE_VERSION {
return nil, fmt.Errorf("serialized image data has unsupported version: %d", m.Version)
}
if len(m.Frames) != len(data) {
return nil, fmt.Errorf("serialized image data has %d frames in metadata but have data for: %d", len(m.Frames), len(data))
}
ans := ImageData{
Width: m.Width, Height: m.Height, Format_uppercase: m.Format_uppercase,
}
for i, f := range m.Frames {
if ff, err := ImageFrameFromSerialized(f, data[i]); err != nil {
return nil, err
} else {
ans.Frames = append(ans.Frames, ff)
}
}
return &ans, nil
}
func (ans ImageFrame) Resize(x_frac, y_frac float64) *ImageFrame {
ans.Width = int(x_frac * float64(ans.Width))
ans.Height = int(y_frac * float64(ans.Height))
ans.Img = imaging.ResizeWithOpacity(ans.Img, ans.Width, ans.Height, imaging.Lanczos, ans.Is_opaque)
ans.Left = int(x_frac * float64(ans.Left))
ans.Top = int(y_frac * float64(ans.Top))
return &ans
}
func (self *ImageData) Resize(x_frac, y_frac float64) *ImageData {
ans := *self
ans.Frames = make([]*ImageFrame, len(self.Frames))
if err := parallel.Run_in_parallel_over_range(1, func(start, limit int) {
for i := start; i < limit; i++ {
ans.Frames[i] = self.Frames[i].Resize(x_frac, y_frac)
}
}, 0, len(ans.Frames)); err != nil {
panic(err)
}
if len(ans.Frames) > 0 {
ans.Width, ans.Height = ans.Frames[0].Width, ans.Frames[0].Height
}
return &ans
}
func MakeTempDir(template string) (ans string, err error) {
if template == "" {
template = "kitty-img-*"
}
if shm.SHM_DIR != "" {
ans, err = os.MkdirTemp(shm.SHM_DIR, template)
if err == nil {
return
}
}
return os.MkdirTemp("", template)
}
func NewImageData(ic *imaging.Image) (ans *ImageData) {
b := ic.Bounds()
ans = &ImageData{
Width: b.Dx(), Height: b.Dy(),
}
if ic.Metadata != nil {
ans.Format_uppercase = strings.ToUpper(ic.Metadata.Format.String())
}
for _, f := range ic.Frames {
fr := ImageFrame{
Img: f.Image, Left: f.TopLeft.X, Top: f.TopLeft.Y, Width: f.Image.Bounds().Dx(), Height: f.Image.Bounds().Dy(),
Compose_onto: int(f.ComposeOnto), Number: int(f.Number), Delay_ms: int32(f.Delay.Milliseconds()),
Replace: f.Replace, Is_opaque: imaging.IsOpaque(f.Image),
}
if fr.Delay_ms <= 0 {
fr.Delay_ms = -1 // -1 is gapless in graphics protocol
}
ans.Frames = append(ans.Frames, &fr)
}
return
}
func OpenImageFromPath(path string, opts ...imaging.DecodeOption) (ans *ImageData, err error) {
ic, err := imaging.OpenAll(path, opts...)
if err != nil {
return nil, err
}
return NewImageData(ic), nil
}
func OpenImageFromReader(r io.Reader, opts ...imaging.DecodeOption) (ans *ImageData, s io.Reader, err error) {
ic, s, err := imaging.DecodeAll(r, opts...)
if err != nil {
return nil, nil, err
}
return NewImageData(ic), s, nil
}
@@ -0,0 +1,8 @@
// Unicode data, built from the Unicode Standard 17.0.0
// Code generated by wcwidth.py, DO NOT EDIT.
package images
var NumberToDiacritic = [297]rune{
0x305, 0x30d, 0x30e, 0x310, 0x312, 0x33d, 0x33e, 0x33f, 0x346, 0x34a, 0x34b, 0x34c, 0x350, 0x351, 0x352, 0x357, 0x35b, 0x363, 0x364, 0x365, 0x366, 0x367, 0x368, 0x369, 0x36a, 0x36b, 0x36c, 0x36d, 0x36e, 0x36f, 0x483, 0x484, 0x485, 0x486, 0x487, 0x592, 0x593, 0x594, 0x595, 0x597, 0x598, 0x599, 0x59c, 0x59d, 0x59e, 0x59f, 0x5a0, 0x5a1, 0x5a8, 0x5a9, 0x5ab, 0x5ac, 0x5af, 0x5c4, 0x610, 0x611, 0x612, 0x613, 0x614, 0x615, 0x616, 0x617, 0x657, 0x658, 0x659, 0x65a, 0x65b, 0x65d, 0x65e, 0x6d6, 0x6d7, 0x6d8, 0x6d9, 0x6da, 0x6db, 0x6dc, 0x6df, 0x6e0, 0x6e1, 0x6e2, 0x6e4, 0x6e7, 0x6e8, 0x6eb, 0x6ec, 0x730, 0x732, 0x733, 0x735, 0x736, 0x73a, 0x73d, 0x73f, 0x740, 0x741, 0x743, 0x745, 0x747, 0x749, 0x74a, 0x7eb, 0x7ec, 0x7ed, 0x7ee, 0x7ef, 0x7f0, 0x7f1, 0x7f3, 0x816, 0x817, 0x818, 0x819, 0x81b, 0x81c, 0x81d, 0x81e, 0x81f, 0x820, 0x821, 0x822, 0x823, 0x825, 0x826, 0x827, 0x829, 0x82a, 0x82b, 0x82c, 0x82d, 0x951, 0x953, 0x954, 0xf82, 0xf83, 0xf86, 0xf87, 0x135d, 0x135e, 0x135f, 0x17dd, 0x193a, 0x1a17, 0x1a75, 0x1a76, 0x1a77, 0x1a78, 0x1a79, 0x1a7a, 0x1a7b, 0x1a7c, 0x1b6b, 0x1b6d, 0x1b6e, 0x1b6f, 0x1b70, 0x1b71, 0x1b72, 0x1b73, 0x1cd0, 0x1cd1, 0x1cd2, 0x1cda, 0x1cdb, 0x1ce0, 0x1dc0, 0x1dc1, 0x1dc3, 0x1dc4, 0x1dc5, 0x1dc6, 0x1dc7, 0x1dc8, 0x1dc9, 0x1dcb, 0x1dcc, 0x1dd1, 0x1dd2, 0x1dd3, 0x1dd4, 0x1dd5, 0x1dd6, 0x1dd7, 0x1dd8, 0x1dd9, 0x1dda, 0x1ddb, 0x1ddc, 0x1ddd, 0x1dde, 0x1ddf, 0x1de0, 0x1de1, 0x1de2, 0x1de3, 0x1de4, 0x1de5, 0x1de6, 0x1dfe, 0x20d0, 0x20d1, 0x20d4, 0x20d5, 0x20d6, 0x20d7, 0x20db, 0x20dc, 0x20e1, 0x20e7, 0x20e9, 0x20f0, 0x2cef, 0x2cf0, 0x2cf1, 0x2de0, 0x2de1, 0x2de2, 0x2de3, 0x2de4, 0x2de5, 0x2de6, 0x2de7, 0x2de8, 0x2de9, 0x2dea, 0x2deb, 0x2dec, 0x2ded, 0x2dee, 0x2def, 0x2df0, 0x2df1, 0x2df2, 0x2df3, 0x2df4, 0x2df5, 0x2df6, 0x2df7, 0x2df8, 0x2df9, 0x2dfa, 0x2dfb, 0x2dfc, 0x2dfd, 0x2dfe, 0x2dff, 0xa66f, 0xa67c, 0xa67d, 0xa6f0, 0xa6f1, 0xa8e0, 0xa8e1, 0xa8e2, 0xa8e3, 0xa8e4, 0xa8e5, 0xa8e6, 0xa8e7, 0xa8e8, 0xa8e9, 0xa8ea, 0xa8eb, 0xa8ec, 0xa8ed, 0xa8ee, 0xa8ef, 0xa8f0, 0xa8f1, 0xaab0, 0xaab2, 0xaab3, 0xaab7, 0xaab8, 0xaabe, 0xaabf, 0xaac1, 0xfe20, 0xfe21, 0xfe22, 0xfe23, 0xfe24, 0xfe25, 0xfe26, 0x10a0f, 0x10a38, 0x1d185, 0x1d186, 0x1d187, 0x1d188, 0x1d189, 0x1d1aa, 0x1d1ab, 0x1d1ac, 0x1d1ad, 0x1d242, 0x1d243, 0x1d244,
}
+31
View File
@@ -0,0 +1,31 @@
package images
import (
"bytes"
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/kovidgoyal/kitty"
)
var _ = fmt.Print
func TestImageSerialize(t *testing.T) {
img, _, err := OpenImageFromReader(bytes.NewReader(kitty.KittyLogoAsPNGData))
if err != nil {
t.Fatal(err)
}
m, data := img.Serialize()
img2, err := ImageFromSerialized(m, data)
if err != nil {
t.Fatal(err)
}
m2, data2 := img2.Serialize()
if diff := cmp.Diff(m, m2); diff != "" {
t.Fatalf("Image metadata failed to roundtrip:\n%s", diff)
}
if diff := cmp.Diff(data, data2); diff != "" {
t.Fatalf("Image data failed to roundtrip:\n%s", diff)
}
}
+23
View File
@@ -0,0 +1,23 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package images
import (
"fmt"
"image"
"github.com/kovidgoyal/imaging"
"github.com/kovidgoyal/imaging/nrgb"
)
var _ = fmt.Print
func (self *Context) paste_nrgb_onto_opaque(background *imaging.NRGB, img image.Image, pos image.Point, bgcol *imaging.NRGBColor) {
bg := imaging.NRGBColor{}
if bgcol != nil {
bg = *bgcol
}
src := nrgb.NewNRGBScanner(img, bg)
self.run_paste(src, background, pos, func(dst []byte) {})
}
+137
View File
@@ -0,0 +1,137 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package images
import (
"fmt"
"image"
"math"
"github.com/kovidgoyal/imaging"
"github.com/kovidgoyal/imaging/nrgba"
"github.com/kovidgoyal/kitty/tools/tty"
)
var _ = fmt.Print
var debugprintln = tty.DebugPrintln
var _ = debugprintln
func (self *Context) run_paste(src imaging.Scanner, background image.Image, pos image.Point, postprocess func([]byte)) {
pos = pos.Sub(background.Bounds().Min)
pasteRect := image.Rectangle{Min: pos, Max: pos.Add(src.Bounds().Size())}
interRect := pasteRect.Intersect(background.Bounds())
if interRect.Empty() {
return
}
bytes_per_pixel := src.Num_of_channels() * src.Bytes_per_channel()
var stride int
var pix []uint8
switch v := background.(type) {
case *image.NRGBA:
stride = v.Stride
pix = v.Pix
case *imaging.NRGB:
stride = v.Stride
pix = v.Pix
default:
panic(fmt.Sprintf("Unsupported image type: %v", v))
}
if len(pix) < background.Bounds().Dy()*stride {
panic(fmt.Sprintf("background image has insufficient pixel data. Bounds: %v Stride: %d Data len: %d", background.Bounds(), stride, len(pix)))
}
if err := self.SafeParallel(interRect.Min.Y, interRect.Max.Y, func(ys <-chan int) {
for y := range ys {
x1 := interRect.Min.X - pasteRect.Min.X
x2 := interRect.Max.X - pasteRect.Min.X
y1 := y - pasteRect.Min.Y
y2 := y1 + 1
i1 := y*stride + interRect.Min.X*bytes_per_pixel
i2 := i1 + interRect.Dx()*bytes_per_pixel
dst := pix[i1:i2]
src.Scan(x1, y1, x2, y2, dst)
postprocess(dst)
}
}); err != nil {
panic(err)
}
}
func (self *Context) paste_nrgba_onto_opaque(background *image.NRGBA, img image.Image, pos image.Point, bgcol *imaging.NRGBColor) {
src := nrgba.NewNRGBAScanner(img)
if bgcol == nil {
self.run_paste(src, background, pos, func([]byte) {})
return
}
bg := [3]float64{float64(bgcol.R), float64(bgcol.G), float64(bgcol.B)}
self.run_paste(src, background, pos, func(dst []byte) {
for len(dst) > 0 {
a := float64(dst[3]) / 255.0
for i := range dst[:3] {
// uint8() automatically converts floats greater than 255 but less than 256 to 255
dst[i] = uint8(float64(dst[i])*a + bg[i]*(1-a))
}
dst[3] = 255
dst = dst[4:]
}
})
}
// Paste pastes the img image to the background image at the specified position. Optionally composing onto the specified opaque color.
func (self *Context) Paste(background image.Image, img image.Image, pos image.Point, opaque_bg *imaging.NRGBColor) {
switch b := background.(type) {
case *image.NRGBA:
self.paste_nrgba_onto_opaque(b, img, pos, opaque_bg)
case *imaging.NRGB:
self.paste_nrgb_onto_opaque(b, img, pos, opaque_bg)
default:
panic("Unsupported background image type")
}
}
// PasteCenter pastes the img image to the center of the background image. Optionally composing onto the specified opaque color.
func (self *Context) PasteCenter(background image.Image, img image.Image, opaque_bg *imaging.NRGBColor) {
bgBounds := background.Bounds()
bgW := bgBounds.Dx()
bgH := bgBounds.Dy()
bgMinX := bgBounds.Min.X
bgMinY := bgBounds.Min.Y
centerX := bgMinX + bgW/2
centerY := bgMinY + bgH/2
x0 := centerX - img.Bounds().Dx()/2
y0 := centerY - img.Bounds().Dy()/2
self.Paste(background, img, image.Pt(x0, y0), opaque_bg)
}
func FitImage(width, height, pwidth, pheight int) (final_width int, final_height int) {
if height > pheight {
corrf := float64(pheight) / float64(height)
width, height = int(math.Floor(corrf*float64(width))), pheight
}
if width > pwidth {
corrf := float64(pwidth) / float64(width)
width, height = pwidth, int(math.Floor(corrf*float64(height)))
}
if height > pheight {
corrf := float64(pheight) / float64(height)
width, height = int(math.Floor(corrf*float64(width))), pheight
}
return width, height
}
func NewNRGBAWithContiguousRGBAPixels(p []byte, left, top, width, height int) (*image.NRGBA, error) {
const bpp = 4
if expected := bpp * width * height; expected != len(p) {
return nil, fmt.Errorf("the image width and height dont match the size of the specified pixel data: width=%d height=%d sz=%d != %d", width, height, len(p), expected)
}
return &image.NRGBA{
Pix: p,
Stride: bpp * width,
Rect: image.Rectangle{image.Point{left, top}, image.Point{left + width, top + height}},
}, nil
}
+67
View File
@@ -0,0 +1,67 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package images
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"github.com/kovidgoyal/go-parallel"
)
var _ = fmt.Print
type Context struct {
num_of_threads atomic.Int32
}
func (self *Context) SetNumberOfThreads(n int) {
self.num_of_threads.Store(int32(n))
}
func (self *Context) NumberOfThreads() int {
return int(self.num_of_threads.Load())
}
func (self *Context) EffectiveNumberOfThreads() int {
ans := int(self.num_of_threads.Load())
if ans <= 0 {
ans = max(1, runtime.NumCPU())
}
return ans
}
// parallel processes the data in separate goroutines. If any of them panics,
// returns an error. Note that if multiple goroutines panic, only one error is
// returned.
func (self *Context) SafeParallel(start, stop int, fn func(<-chan int)) (err error) {
count := stop - start
if count < 1 {
return
}
procs := min(self.EffectiveNumberOfThreads(), count)
c := make(chan int, count)
for i := start; i < stop; i++ {
c <- i
}
close(c)
var wg sync.WaitGroup
for range procs {
wg.Add(1)
go func() {
defer func() {
if r := recover(); r != nil {
err = parallel.Format_stacktrace_on_panic(r, 1)
}
wg.Done()
}()
fn(c)
}()
}
wg.Wait()
return
}
+7
View File
@@ -0,0 +1,7 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
const (
DEFAULT_IO_BUFFER_SIZE = 8192
)
+169
View File
@@ -0,0 +1,169 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"math"
"strconv"
"strings"
"time"
)
var _ = fmt.Print
func is_digit(x byte) bool {
return '0' <= x && x <= '9'
}
// The following is copied from the Go standard library to implement date range validation logic
// equivalent to the behaviour of Go's time.Parse.
func isLeap(year int) bool {
return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}
// daysInMonth is the number of days for non-leap years in each calendar month starting at 1
var daysInMonth = [13]int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
func daysIn(m time.Month, year int) int {
if m == time.February && isLeap(year) {
return 29
}
return daysInMonth[int(m)]
}
func ISO8601Parse(raw string) (time.Time, error) {
orig := raw
raw = strings.TrimSpace(raw)
required_number := func(num_digits int) (int, error) {
if len(raw) < num_digits {
return 0, fmt.Errorf("Insufficient digits")
}
text := raw[:num_digits]
raw = raw[num_digits:]
ans, err := strconv.ParseUint(text, 10, 32)
if err == nil && ans <= math.MaxInt {
return int(ans), nil
}
return math.MaxInt, err
}
optional_separator := func(x byte) bool {
if len(raw) > 0 && raw[0] == x {
raw = raw[1:]
}
return len(raw) > 0 && is_digit(raw[0])
}
errf := func(msg string) (time.Time, error) {
return time.Time{}, fmt.Errorf("Invalid ISO8601 timestamp: %#v. %s", orig, msg)
}
optional_separator('+')
year, err := required_number(4)
if err != nil {
return errf("timestamp does not start with a 4 digit year")
}
var month int = 1
var day int = 1
if optional_separator('-') {
month, err = required_number(2)
if err != nil {
return errf("timestamp does not have a valid 2 digit month")
}
if optional_separator('-') {
day, err = required_number(2)
if err != nil {
return errf("timestamp does not have a valid 2 digit day")
}
}
}
var hour, minute, second int
var nsec int64
if len(raw) > 0 && (raw[0] == 'T' || raw[0] == ' ') {
raw = raw[1:]
hour, err = required_number(2)
if err != nil {
return errf("timestamp does not have a valid 2 digit hour")
}
if optional_separator(':') {
minute, err = required_number(2)
if err != nil {
return errf("timestamp does not have a valid 2 digit minute")
}
if optional_separator(':') {
second, err = required_number(2)
if err != nil {
return errf("timestamp does not have a valid 2 digit second")
}
}
}
if len(raw) > 0 && (raw[0] == '.' || raw[0] == ',') {
raw = raw[1:]
num_digits := 0
for len(raw) > num_digits && is_digit(raw[num_digits]) {
num_digits++
}
text := raw[:num_digits]
raw = raw[num_digits:]
extra := 9 - len(text)
if extra < 0 {
text = text[:9]
}
if text != "" {
if nsec, err = strconv.ParseInt(text, 10, 0); err != nil {
return errf("timestamp does not have a valid nanosecond field")
}
for ; extra > 0; extra-- {
nsec *= 10
}
}
}
}
switch {
case month < 1 || month > 12:
return errf("timestamp has invalid month value")
case day < 1 || day > 31 || day > daysIn(time.Month(month), year):
return errf("timestamp has invalid day value")
case hour < 0 || hour > 23:
return errf("timestamp has invalid hour value")
case minute < 0 || minute > 59:
return errf("timestamp has invalid minute value")
case second < 0 || second > 59:
return errf("timestamp has invalid second value")
}
loc := time.UTC
tzsign, tzhour, tzminute := 0, 0, 0
if len(raw) > 0 {
switch raw[0] {
case '+':
tzsign = 1
case '-':
tzsign = -1
}
}
if tzsign != 0 {
raw = raw[1:]
tzhour, err = required_number(2)
if err != nil {
return errf("timestamp has invalid timezone hour")
}
optional_separator(':')
tzminute, err = required_number(2)
if err != nil {
tzminute = 0
}
seconds := tzhour*3600 + tzminute*60
loc = time.FixedZone("", tzsign*seconds)
}
return time.Date(year, time.Month(month), day, hour, minute, second, int(nsec), loc), err
}
func ISO8601Format(x time.Time) string {
return x.Format(time.RFC3339Nano)
}
+40
View File
@@ -0,0 +1,40 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
func TestISO8601(t *testing.T) {
now := time.Now()
tt := func(raw string, expected time.Time) {
actual, err := ISO8601Parse(raw)
if err != nil {
t.Fatalf("Parsing: %#v failed with error: %s", raw, err)
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("Parsing: %#v failed:\n%s", raw, diff)
}
}
tt(ISO8601Format(now), now)
tt("2023-02-08T07:24:09.551975+00:00", time.Date(2023, 2, 8, 7, 24, 9, 551975000, time.UTC))
tt("2023-02-08T07:24:09.551975Z", time.Date(2023, 2, 8, 7, 24, 9, 551975000, time.UTC))
tt("2023", time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC))
tt("2023-11-13", time.Date(2023, 11, 13, 0, 0, 0, 0, time.UTC))
tt("2023-11-13 07:23", time.Date(2023, 11, 13, 7, 23, 0, 0, time.UTC))
tt("2023-11-13 07:23:01", time.Date(2023, 11, 13, 7, 23, 1, 0, time.UTC))
tt("2023-11-13 07:23:01.", time.Date(2023, 11, 13, 7, 23, 1, 0, time.UTC))
tt("2023-11-13 07:23:01.0", time.Date(2023, 11, 13, 7, 23, 1, 0, time.UTC))
tt("2023-11-13 07:23:01.1", time.Date(2023, 11, 13, 7, 23, 1, 100000000, time.UTC))
tt("202311-13 07", time.Date(2023, 11, 13, 7, 0, 0, 0, time.UTC))
tt("20231113 0705", time.Date(2023, 11, 13, 7, 5, 0, 0, time.UTC))
}
+46
View File
@@ -0,0 +1,46 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"strings"
)
var _ = fmt.Print
// compares two strings and returns the Levenshtein distance between them.
func LevenshteinDistance(s, t string, ignore_case bool) int {
if ignore_case {
s = strings.ToLower(s)
t = strings.ToLower(t)
}
d := make([][]int, len(s)+1)
for i := range d {
d[i] = make([]int, len(t)+1)
}
for i := range d {
d[i][0] = i
}
for j := range d[0] {
d[0][j] = j
}
for j := 1; j <= len(t); j++ {
for i := 1; i <= len(s); i++ {
if s[i-1] == t[j-1] {
d[i][j] = d[i-1][j-1]
} else {
min := d[i-1][j]
if d[i][j-1] < min {
min = d[i][j-1]
}
if d[i-1][j-1] < min {
min = d[i-1][j-1]
}
d[i][j] = min + 1
}
}
}
return d[len(s)][len(t)]
}
+79
View File
@@ -0,0 +1,79 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"math"
)
var _ = fmt.Print
func slice_iter(strs []string) func() (string, bool) {
i := 0
limit := len(strs)
return func() (string, bool) {
if i < limit {
i++
return strs[i-1], false
}
return "", true
}
}
// Prefix returns the longest common prefix of the provided strings
func Prefix(strs []string) string {
return LongestCommon(slice_iter(strs), true)
}
// Suffix returns the longest common suffix of the provided strings
func Suffix(strs []string) string {
return LongestCommon(slice_iter(strs), false)
}
func min(a ...int) int {
ans := math.MaxInt
for _, x := range a {
if x < ans {
ans = x
}
}
return ans
}
func LongestCommon(next func() (string, bool), prefix bool) string {
xfix, done := next()
if xfix == "" || done {
return ""
}
for {
q, done := next()
if done {
break
}
q_len := len(q)
xfix_len := len(xfix)
max_len := min(q_len, xfix_len)
if max_len == 0 {
return ""
}
if prefix {
for i := range max_len {
if xfix[i] != q[i] {
xfix = xfix[:i]
break
}
}
} else {
for i := range max_len {
xi := xfix_len - i - 1
si := q_len - i - 1
if xfix[xi] != q[si] {
xfix = xfix[xi+1:]
break
}
}
}
}
return xfix
}
+21
View File
@@ -0,0 +1,21 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"testing"
)
var _ = fmt.Print
func TestLongestCommon(t *testing.T) {
p := func(expected string, items ...string) {
actual := Prefix(items)
if actual != expected {
t.Fatalf("Failed with %#v\nExpected: %#v\nActual: %#v", items, expected, actual)
}
}
p("abc", "abc", "abcd")
p("", "abc", "xy")
}
+10
View File
@@ -0,0 +1,10 @@
package machine_id
import (
"fmt"
"sync"
)
var _ = fmt.Print
var MachineId = sync.OnceValues(read_machine_id)
+15
View File
@@ -0,0 +1,15 @@
package machine_id
import (
"fmt"
"testing"
)
var _ = fmt.Print
func TestMachineId(t *testing.T) {
_, err := MachineId()
if err != nil {
t.Fatal(err)
}
}
+81
View File
@@ -0,0 +1,81 @@
//go:build darwin
package machine_id
import (
"fmt"
"strings"
"github.com/ebitengine/purego"
)
var _ = fmt.Print
func read_machine_id() (string, error) {
const kIOMainPortDefault uint32 = 0
const kCFStringEncodingUTF8 uint32 = 0x08000100
// 1. Load System Frameworks
iokit, err := purego.Dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", purego.RTLD_NOW)
if err != nil {
return "", err
}
defer purego.Dlclose(iokit)
corefoundation, err := purego.Dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", purego.RTLD_NOW)
if err != nil {
return "", err
}
defer purego.Dlclose(corefoundation)
// 2. Register CoreFoundation Functions
var cfStringCreateWithCString func(uintptr, *byte, uint32) uintptr
purego.RegisterLibFunc(&cfStringCreateWithCString, corefoundation, "CFStringCreateWithCString")
var cfStringGetCString func(uintptr, *byte, int64, uint32) bool
purego.RegisterLibFunc(&cfStringGetCString, corefoundation, "CFStringGetCString")
var cfRelease func(uintptr)
purego.RegisterLibFunc(&cfRelease, corefoundation, "CFRelease")
// 3. Register IOKit Functions
var ioServiceMatching func(*byte) uintptr
purego.RegisterLibFunc(&ioServiceMatching, iokit, "IOServiceMatching")
var ioServiceGetMatchingService func(uint32, uintptr) uint32
purego.RegisterLibFunc(&ioServiceGetMatchingService, iokit, "IOServiceGetMatchingService")
var ioRegistryEntryCreateCFProperty func(uint32, uintptr, uintptr, uint32) uintptr
purego.RegisterLibFunc(&ioRegistryEntryCreateCFProperty, iokit, "IORegistryEntryCreateCFProperty")
var ioObjectRelease func(uint32)
purego.RegisterLibFunc(&ioObjectRelease, iokit, "IOObjectRelease")
// 4. Retrieve the UUID
// Convert Go string to CFStringRef for the property key
keyName := "IOPlatformUUID\x00"
cfKey := cfStringCreateWithCString(0, &[]byte(keyName)[0], kCFStringEncodingUTF8)
defer cfRelease(cfKey)
// Look up the IOPlatformExpertDevice service
className := "IOPlatformExpertDevice\x00"
matchingDict := ioServiceMatching(&[]byte(className)[0])
service := ioServiceGetMatchingService(kIOMainPortDefault, matchingDict)
if service == 0 {
return "", fmt.Errorf("failed to find IOPlatformExpertDevice service")
}
defer ioObjectRelease(service)
// Get the property from the registry
cfValue := ioRegistryEntryCreateCFProperty(service, cfKey, 0, 0)
if cfValue == 0 {
return "", fmt.Errorf("failed to find IOPlatformUUID property")
}
defer cfRelease(cfValue)
// Convert the resulting CFString back to a Go string
buf := make([]byte, 128)
if cfStringGetCString(cfValue, &buf[0], 128, kCFStringEncodingUTF8) {
return strings.TrimRight(string(buf), "\x00"), nil
}
return "", fmt.Errorf("failed to extract string from CFProperty")
}
+23
View File
@@ -0,0 +1,23 @@
//go:build !darwin
package machine_id
import (
"fmt"
"os"
"strings"
"unicode"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func read_machine_id() (string, error) {
if data, err := os.ReadFile("/etc/machine-id"); err == nil {
ans := utils.UnsafeBytesToString(data)
return strings.TrimRightFunc(ans, unicode.IsSpace), nil
} else {
return "", err
}
}
+493
View File
@@ -0,0 +1,493 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"sync"
"golang.org/x/sys/unix"
)
// Fast lookup of MIME types for file names using the binary mime.cache files
// generated by update-mime-database from shared-mime-info. The lookup
// algorithm mirrors the one used by xdgmime (GLib/GIO). See
// https://specifications.freedesktop.org/shared-mime-info-spec/latest/ar01s02.html
const (
mime_cache_case_sensitive_flag = 0x100
mime_cache_weight_mask = 0xff
mime_cache_max_matches = 16
mime_cache_max_suffix_tree_depth = 256
mime_cache_header_size = 40
mime_cache_alias_list_offset_pos = 4
mime_cache_literal_list_offset_pos = 12
mime_cache_suffix_tree_offset_pos = 16
mime_cache_glob_list_offset_pos = 20
mime_cache_default_data_dirs = "/usr/local/share/:/usr/share/"
mime_cache_relative_path_in_datadir = "mime/mime.cache"
)
type mime_cache struct {
data []byte
}
type mime_cache_match struct {
mime string
weight uint32
}
type mime_cache_matches struct {
items []mime_cache_match
}
func (m *mime_cache_matches) full() bool { return len(m.items) >= mime_cache_max_matches }
func (c *mime_cache) u32(offset uint64) (uint32, bool) {
if offset > uint64(len(c.data)) || uint64(len(c.data))-offset < 4 {
return 0, false
}
return binary.BigEndian.Uint32(c.data[offset:]), true
}
func (c *mime_cache) entry(offset uint64) (a, b, weight uint32, ok bool) {
if a, ok = c.u32(offset); !ok {
return
}
if b, ok = c.u32(offset + 4); !ok {
return
}
weight, ok = c.u32(offset + 8)
return
}
// cstring returns the NUL terminated string at offset, without copying
func (c *mime_cache) cstring(offset uint32) ([]byte, bool) {
if uint64(offset) >= uint64(len(c.data)) {
return nil, false
}
data := c.data[offset:]
idx := bytes.IndexByte(data, 0)
if idx < 0 {
return nil, false
}
return data[:idx], true
}
func (c *mime_cache) add_match(ans *mime_cache_matches, mime_offset, weight uint32) bool {
if ans.full() {
return false
}
if mime, ok := c.cstring(mime_offset); ok {
ans.items = append(ans.items, mime_cache_match{string(mime), weight & mime_cache_weight_mask})
return true
}
return false
}
func (c *mime_cache) lookup_literal(name []byte, case_sensitive_check bool, ans *mime_cache_matches) bool {
list_offset, ok := c.u32(mime_cache_literal_list_offset_pos)
if !ok {
return false
}
n, ok := c.u32(uint64(list_offset))
if !ok {
return false
}
lo, hi := uint64(0), uint64(n)
for lo < hi {
mid := lo + (hi-lo)/2
literal_offset, mime_offset, weight, ok := c.entry(uint64(list_offset) + 4 + 12*mid)
if !ok {
return false
}
literal, ok := c.cstring(literal_offset)
if !ok {
return false
}
switch cmp := bytes.Compare(literal, name); {
case cmp < 0:
lo = mid + 1
case cmp > 0:
hi = mid
default:
if !case_sensitive_check && weight&mime_cache_case_sensitive_flag != 0 {
return false
}
return c.add_match(ans, mime_offset, weight)
}
}
return false
}
func (c *mime_cache) lookup_suffix_node(num_nodes, offset uint32, name []rune, case_sensitive_check bool, ans *mime_cache_matches, depth int) {
if len(name) == 0 || depth > mime_cache_max_suffix_tree_depth {
return
}
ch := uint32(name[len(name)-1])
lo, hi := uint64(0), uint64(num_nodes)
for lo < hi {
mid := lo + (hi-lo)/2
node_char, num_children, first_child_offset, ok := c.entry(uint64(offset) + 12*mid)
if !ok {
return
}
switch {
case ch < node_char:
hi = mid
case ch > node_char:
lo = mid + 1
default:
before := len(ans.items)
c.lookup_suffix_node(num_children, first_child_offset, name[:len(name)-1], case_sensitive_check, ans, depth+1)
if len(ans.items) == before {
// No longer suffix matched, use the leaf nodes of this node,
// which are sorted before all other children.
for i := range uint64(num_children) {
leaf_char, mime_offset, weight, ok := c.entry(uint64(first_child_offset) + 12*i)
if !ok || leaf_char != 0 {
break
}
if case_sensitive_check || weight&mime_cache_case_sensitive_flag == 0 {
c.add_match(ans, mime_offset, weight)
}
}
}
return
}
}
}
func (c *mime_cache) lookup_suffix(name []rune, case_sensitive_check bool, ans *mime_cache_matches) {
tree_offset, ok := c.u32(mime_cache_suffix_tree_offset_pos)
if !ok {
return
}
num_roots, ok := c.u32(uint64(tree_offset))
if !ok {
return
}
first_root_offset, ok := c.u32(uint64(tree_offset) + 4)
if !ok {
return
}
c.lookup_suffix_node(num_roots, first_root_offset, name, case_sensitive_check, ans, 0)
}
// fnmatch_to_go_pattern converts the fnmatch() negated bracket expression
// syntax [!...] to the [^...] syntax used by path.Match
func fnmatch_to_go_pattern(glob string) string {
if !strings.Contains(glob, "[!") {
return glob
}
return strings.ReplaceAll(glob, "[!", "[^")
}
func (c *mime_cache) lookup_glob(name string, case_sensitive_check bool, ans *mime_cache_matches) {
list_offset, ok := c.u32(mime_cache_glob_list_offset_pos)
if !ok {
return
}
n, ok := c.u32(uint64(list_offset))
if !ok {
return
}
for i := uint64(0); i < uint64(n) && !ans.full(); i++ {
glob_offset, mime_offset, weight, ok := c.entry(uint64(list_offset) + 4 + 12*i)
if !ok {
return
}
if !case_sensitive_check && weight&mime_cache_case_sensitive_flag != 0 {
continue
}
if glob, ok := c.cstring(glob_offset); ok {
if matched, err := path.Match(fnmatch_to_go_pattern(string(glob)), name); err == nil && matched {
c.add_match(ans, mime_offset, weight)
}
}
}
}
type mime_caches []*mime_cache
func (caches mime_caches) lookup(name string) string {
if name == "" || strings.IndexByte(name, 0) > -1 {
return ""
}
ans := mime_cache_matches{items: make([]mime_cache_match, 0, 4)}
bname := []byte(name)
for _, c := range caches {
if c.lookup_literal(bname, true, &ans) {
return ans.items[0].mime
}
}
lname := strings.ToLower(name)
for _, c := range caches {
if c.lookup_literal([]byte(lname), false, &ans) {
return ans.items[0].mime
}
}
lrunes := []rune(lname)
for _, c := range caches {
c.lookup_suffix(lrunes, false, &ans)
}
if len(ans.items) < 2 {
runes := []rune(name)
for _, c := range caches {
c.lookup_suffix(runes, true, &ans)
}
}
if len(ans.items) == 0 {
for _, c := range caches {
c.lookup_glob(name, true, &ans)
}
}
if len(ans.items) == 0 {
for _, c := range caches {
c.lookup_glob(lname, false, &ans)
}
}
if len(ans.items) == 0 {
return ""
}
// Highest weight wins, ties go to the earliest match, which means the
// longest suffix and the highest priority cache file.
best := ans.items[0]
for _, m := range ans.items[1:] {
if m.weight > best.weight {
best = m
}
}
return best.mime
}
func (c *mime_cache) alias_list() (list_offset, n uint32, ok bool) {
if list_offset, ok = c.u32(mime_cache_alias_list_offset_pos); ok {
n, ok = c.u32(uint64(list_offset))
}
return
}
func (c *mime_cache) alias_entry(list_offset uint32, idx uint64) (alias, mime []byte, ok bool) {
offset := uint64(list_offset) + 4 + 8*idx
alias_offset, ok := c.u32(offset)
if !ok {
return
}
mime_offset, ok := c.u32(offset + 4)
if !ok {
return
}
if alias, ok = c.cstring(alias_offset); ok {
mime, ok = c.cstring(mime_offset)
}
return
}
// canonical_mime_type returns the canonical MIME type for the specified alias
// or the empty string if mime is not an alias. The alias list is sorted by alias.
func (c *mime_cache) canonical_mime_type(mime []byte) string {
list_offset, n, ok := c.alias_list()
if !ok {
return ""
}
lo, hi := uint64(0), uint64(n)
for lo < hi {
mid := lo + (hi-lo)/2
alias, canonical, ok := c.alias_entry(list_offset, mid)
if !ok {
return ""
}
switch cmp := bytes.Compare(alias, mime); {
case cmp < 0:
lo = mid + 1
case cmp > 0:
hi = mid
default:
return string(canonical)
}
}
return ""
}
func (c *mime_cache) aliases_of(canonical []byte, add func(string)) {
list_offset, n, ok := c.alias_list()
if !ok {
return
}
for i := range uint64(n) {
alias, mime, ok := c.alias_entry(list_offset, i)
if !ok {
return
}
if bytes.Equal(mime, canonical) {
add(string(alias))
}
}
}
func (caches mime_caches) aliases(mime string) (ans []string) {
canonical := ""
for _, c := range caches {
if canonical = c.canonical_mime_type([]byte(mime)); canonical != "" {
break
}
}
if canonical == "" {
canonical = mime
}
seen := NewSet[string](8)
add := func(x string) {
if !seen.Has(x) {
seen.Add(x)
ans = append(ans, x)
}
}
add(canonical)
for _, c := range caches {
c.aliases_of([]byte(canonical), add)
}
add(mime)
return
}
func load_mime_cache(path string) (*mime_cache, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
if !st.Mode().IsRegular() {
return nil, fmt.Errorf("%s is not a regular file", path)
}
if st.Size() < mime_cache_header_size {
return nil, fmt.Errorf("the MIME cache file %s is too small", path)
}
// The mapping is never unmapped as it is used for the lifetime of the
// process. update-mime-database replaces the cache file atomically so the
// mapped data remains valid.
// Note for security reviews: if the file is truncated in place, accessing
// the mapped pages beyond the new end of file raises SIGBUS. This is
// deliberately not handled, as truncating the file in place requires write
// access to the XDG data directories and GLib (xdgmime) and Qt
// (QMimeBinaryProvider) mmap these files in exactly the same way, without
// handling SIGBUS. All reads from the mapped data are bounds checked, so
// corrupt or malicious cache file contents are safe.
data, err := unix.Mmap(int(f.Fd()), 0, int(st.Size()), unix.PROT_READ, unix.MAP_PRIVATE)
is_mmapped := err == nil
if !is_mmapped {
if data, err = os.ReadFile(path); err != nil {
return nil, err
}
if len(data) < mime_cache_header_size {
return nil, fmt.Errorf("the MIME cache file %s is too small", path)
}
}
major, minor := binary.BigEndian.Uint16(data), binary.BigEndian.Uint16(data[2:])
if major != 1 || minor < 1 {
if is_mmapped {
_ = unix.Munmap(data)
}
return nil, fmt.Errorf("the MIME cache file %s has unsupported version %d.%d", path, major, minor)
}
return &mime_cache{data: data}, nil
}
// mime_cache_paths returns the paths to mime.cache files in order of decreasing priority
func mime_cache_paths() (ans []string) {
seen := NewSet[string](4)
add := func(data_dir string) {
// relative paths are ignored as per the XDG spec
if filepath.IsAbs(data_dir) {
if p := filepath.Join(data_dir, mime_cache_relative_path_in_datadir); !seen.Has(p) {
seen.Add(p)
ans = append(ans, p)
}
}
}
if data_home := os.Getenv("XDG_DATA_HOME"); data_home != "" {
add(data_home)
} else if home := os.Getenv("HOME"); home != "" {
add(filepath.Join(home, ".local", "share"))
}
data_dirs := os.Getenv("XDG_DATA_DIRS")
if data_dirs == "" {
data_dirs = mime_cache_default_data_dirs
}
for _, x := range strings.Split(data_dirs, ":") {
add(x)
}
return
}
func load_mime_caches(paths []string) (ans mime_caches) {
for _, p := range paths {
c, err := load_mime_cache(p)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, unix.ENOTDIR) {
fmt.Fprintln(os.Stderr, "Failed to load MIME cache file with error:", err)
}
continue
}
ans = append(ans, c)
}
return
}
var system_mime_caches = sync.OnceValue(func() mime_caches {
if runtime.GOOS == "darwin" {
return nil
}
return load_mime_caches(mime_cache_paths())
})
// HaveMimeCache returns true if at least one shared-mime-info mime.cache file
// was successfully loaded
func HaveMimeCache() bool {
return len(system_mime_caches()) > 0
}
// MimeTypeFromCache returns the MIME type for the specified file name, as
// determined by the shared-mime-info mime.cache files. Returns the empty
// string if no match is found. Only the base name of the file is used.
func MimeTypeFromCache(filename string) string {
if caches := system_mime_caches(); len(caches) > 0 {
return caches.lookup(filepath.Base(filename))
}
return ""
}
// MimeTypeAliases returns all names for the specified MIME type as known to
// the shared-mime-info mime.cache files, starting with the canonical name,
// followed by all aliases. Always contains at least the specified MIME type.
// The returned slice must not be modified.
func MimeTypeAliases(mime string) []string {
mime_type_aliases_cache.RLock()
ans, found := mime_type_aliases_cache.m[mime]
mime_type_aliases_cache.RUnlock()
if !found {
ans = system_mime_caches().aliases(mime)
mime_type_aliases_cache.Lock()
mime_type_aliases_cache.m[mime] = ans
mime_type_aliases_cache.Unlock()
}
return ans
}
var mime_type_aliases_cache = struct {
sync.RWMutex
m map[string][]string
}{m: make(map[string][]string)}
+133
View File
@@ -0,0 +1,133 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// Keep in sync with kitty_tests/open_actions.py
const mime_cache_test_types = `
<mime-type type="text/x-kt-literal"><glob pattern="KittyLiteral"/></mime-type>
<mime-type type="text/x-kt-cs"><glob pattern="*.KCS" case-sensitive="true"/></mime-type>
<mime-type type="text/x-kt-ext"><glob pattern="*.kext"/><alias type="text/x-kt-old"/><alias type="application/x-kt-older"/></mime-type>
<mime-type type="text/x-kt-long"><glob pattern="*.long.kext"/></mime-type>
<mime-type type="text/x-kt-light"><glob pattern="*.kw" weight="40"/></mime-type>
<mime-type type="text/x-kt-heavy"><glob pattern="*.kw" weight="80"/></mime-type>
<mime-type type="text/x-kt-glob"><glob pattern="kglob[0-9].*"/></mime-type>
<mime-type type="text/x-kt-negated-glob"><glob pattern="kneg[!0-9].*"/></mime-type>
<mime-type type="text/x-kt-unicode"><glob pattern="*.kü"/></mime-type>
<mime-type type="application/json"><glob pattern="*.kjson"/><alias type="application/x-kt-json"/></mime-type>
<mime-type type="text/x-kt-make"><glob pattern="Makefile" case-sensitive="true"/></mime-type>
<mime-type type="text/x-kt-system"><glob pattern="*.kuser"/></mime-type>
`
func TestMimeCache(t *testing.T) {
if _, err := exec.LookPath("update-mime-database"); err != nil {
t.Skip("update-mime-database not available")
}
tdir := t.TempDir()
build_cache := func(data_dir, types string) {
pkgs := filepath.Join(data_dir, "mime", "packages")
if err := os.MkdirAll(pkgs, 0o755); err != nil {
t.Fatal(err)
}
xml := `<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">` + types + `</mime-info>`
if err := os.WriteFile(filepath.Join(pkgs, "kitty-test.xml"), []byte(xml), 0o644); err != nil {
t.Fatal(err)
}
cmd := exec.Command("update-mime-database", filepath.Join(data_dir, "mime"))
cmd.Env = append(os.Environ(), "PKGSYSTEM_ENABLE_FSYNC=0")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("update-mime-database failed with error: %s and output:\n%s", err, out)
}
}
user, system := filepath.Join(tdir, "user"), filepath.Join(tdir, "system")
build_cache(system, mime_cache_test_types)
build_cache(user, `<mime-type type="text/x-kt-user"><glob pattern="*.kuser"/><glob pattern="*.kext.override"/></mime-type><mime-type type="text/x-kt-ext"><alias type="text/x-kt-user-alias"/></mime-type>`)
build_cache(filepath.Join(tdir, "ignored"), `<mime-type type="text/x-kt-ignored"><glob pattern="*.kuser"/></mime-type>`)
t.Setenv("XDG_DATA_HOME", user)
t.Setenv("XDG_DATA_DIRS", strings.Join([]string{"relative/dir", system + "/", tdir + "/missing", tdir + "/ignored"}, ":"))
paths := mime_cache_paths()
expected_paths := []string{
filepath.Join(user, "mime", "mime.cache"), filepath.Join(system, "mime", "mime.cache"),
filepath.Join(tdir, "missing", "mime", "mime.cache"), filepath.Join(tdir, "ignored", "mime", "mime.cache")}
if strings.Join(paths, "\n") != strings.Join(expected_paths, "\n") {
t.Fatalf("Incorrect mime.cache paths: %#v != %#v", expected_paths, paths)
}
caches := load_mime_caches(paths)
if len(caches) != 3 {
t.Fatalf("Expected to load 3 caches, loaded: %d", len(caches))
}
for name, expected := range map[string]string{
"KittyLiteral": "text/x-kt-literal",
"kittyliteral": "text/x-kt-literal",
"KITTYLITERAL": "text/x-kt-literal",
"xKittyLiteral": "",
"a.KCS": "text/x-kt-cs",
"a.kcs": "",
"a.kext": "text/x-kt-ext",
"A.KEXT": "text/x-kt-ext",
"x.long.kext": "text/x-kt-long",
"x.LONG.KEXT": "text/x-kt-long",
"xlong.kext": "text/x-kt-ext",
"a.kw": "text/x-kt-heavy",
"kglob1.txt": "text/x-kt-glob",
"KGLOB1.TXT": "text/x-kt-glob",
"kglobx.txt": "",
"knegx.txt": "text/x-kt-negated-glob",
"kneg1.txt": "",
"a.kü": "text/x-kt-unicode",
"a.KÜ": "text/x-kt-unicode",
"a.kuser": "text/x-kt-user",
"a.kext.override": "text/x-kt-user",
"": "",
"a\x00.kext": "",
"notmatched": "",
} {
if actual := caches.lookup(name); actual != expected {
t.Errorf("Incorrect MIME type for %#v: %#v != %#v", name, expected, actual)
}
}
ext_names := []string{"text/x-kt-ext", "text/x-kt-user-alias", "application/x-kt-older", "text/x-kt-old"}
for q, expected := range map[string][]string{
"text/x-kt-ext": ext_names,
"text/x-kt-old": ext_names,
"application/json": {"application/json", "application/x-kt-json"},
"unknown/x-kt": {"unknown/x-kt"},
} {
if actual := caches.aliases(q); strings.Join(actual, " ") != strings.Join(expected, " ") {
t.Errorf("Incorrect aliases for %#v: %#v != %#v", q, expected, actual)
}
}
if actual := (mime_caches{}).aliases("text/x-kt-ext"); len(actual) != 1 || actual[0] != "text/x-kt-ext" {
t.Errorf("Incorrect aliases with no caches: %#v", actual)
}
if _, err := load_mime_cache(filepath.Join(tdir, "missing", "mime", "mime.cache")); err == nil {
t.Fatalf("Loading a non-existent cache did not fail")
}
bad := filepath.Join(tdir, "bad.cache")
if err := os.WriteFile(bad, []byte(strings.Repeat("\x00", mime_cache_header_size)), 0o644); err != nil {
t.Fatal(err)
}
if _, err := load_mime_cache(bad); err == nil {
t.Fatalf("Loading a cache with an invalid version did not fail")
}
truncated := filepath.Join(tdir, "truncated.cache")
if data, err := os.ReadFile(filepath.Join(system, "mime", "mime.cache")); err != nil {
t.Fatal(err)
} else if err := os.WriteFile(truncated, data[:mime_cache_header_size+8], 0o644); err != nil {
t.Fatal(err)
}
if c, err := load_mime_cache(truncated); err != nil {
t.Fatal(err)
} else if actual := (mime_caches{c}).lookup("a.kext"); actual != "" {
t.Fatalf("Lookup in truncated cache returned: %#v", actual)
}
}
+154
View File
@@ -0,0 +1,154 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"bufio"
"errors"
"fmt"
"io/fs"
"mime"
"os"
"path/filepath"
"strings"
"sync"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func load_mime_file(filename string, mime_map map[string]string) error {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) <= 1 || fields[0][0] == '#' {
continue
}
mime_type := fields[0]
for _, ext := range fields[1:] {
if ext[0] == '#' {
break
}
mime_map["."+ext] = mime_type
}
}
if err := scanner.Err(); err != nil {
return err
}
return nil
}
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
})
func is_special_file(path string) string {
name := filepath.Base(path)
lname := strings.ToLower(name)
if lname == "makefile" || strings.HasPrefix(lname, "makefile.") {
return "text/makefile"
}
if strings.HasSuffix(name, "rc") && !strings.Contains(name, ".") {
return "text/plain"
}
return ""
}
func GuessMimeType(filename string) string {
ext := filepath.Ext(filename)
mime_with_parameters := UserMimeMap()[ext]
if mime_with_parameters == "" {
mime_with_parameters = MimeTypeFromCache(filename)
}
// The stdlib database is loaded from the same shared-mime-info data as
// the cache, but slowly, by parsing text files, so avoid it if the cache
// is available.
if mime_with_parameters == "" && !HaveMimeCache() {
mime_with_parameters = mime.TypeByExtension(ext)
}
if mime_with_parameters == "" {
only_once.Do(set_builtins)
mime_with_parameters = builtin_types_map[ext]
if mime_with_parameters == "" {
lext := strings.ToLower(ext)
mime_with_parameters = builtin_types_map[lext]
if mime_with_parameters == "" {
mime_with_parameters = KnownExtensions[lext]
}
if mime_with_parameters == "" {
mime_with_parameters = is_special_file(filename)
}
if mime_with_parameters == "" {
return ""
}
}
}
ans, _, err := mime.ParseMediaType(mime_with_parameters)
if err != nil {
return ""
}
return ans
}
func GuessMimeTypeWithFileSystemAccess(filename string) string {
is_dir, is_exe := false, false
s, err := os.Stat(filename)
if err == nil {
is_dir = s.IsDir()
if !is_dir && s.Mode().Perm()&0o111 != 0 && unix.Access(filename, unix.X_OK) == nil {
is_exe = true
}
}
if is_dir {
return "inode/directory"
}
mt := GuessMimeType(filename)
if mt == "" {
if is_exe {
mt = "inode/executable"
}
}
return mt
}
func GuessFileExtensions(mime_type string) (ans []string) {
mime_type, _, err := mime.ParseMediaType(mime_type)
if err != nil {
return
}
seen := NewSet[string](8)
add := func(x string) {
if !seen.Has(x) {
seen.Add(x)
ans = append(ans, x)
}
}
for ext, q := range UserMimeMap() {
if ext != "" && q == mime_type {
add(ext)
}
}
// Go stdlib returns [".asc", ".text", ".txt"] for this
if mime_type == "text/plain" {
add(".txt")
}
if std, err := mime.ExtensionsByType(mime_type); err == nil {
for _, x := range std {
add(x)
}
}
return
}
+392
View File
@@ -0,0 +1,392 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"cmp"
"fmt"
"os"
"path/filepath"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"github.com/kovidgoyal/kitty/tools/simdstring"
"golang.org/x/exp/constraints"
"golang.org/x/text/language"
)
var _ = fmt.Print
func Reverse[T any](s []T) []T {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}
func Reversed[T any](s []T) []T {
ans := make([]T, len(s))
for i, x := range s {
ans[len(s)-1-i] = x
}
return ans
}
func Remove[T comparable](s []T, q T) []T {
idx := slices.Index(s, q)
if idx > -1 {
var zero T
s[idx] = zero // if pointer this allows garbage collection
return slices.Delete(s, idx, idx+1)
}
return s
}
func RemoveAll[T comparable](s []T, q T) []T {
ans := s
for {
idx := slices.Index(ans, q)
if idx < 0 {
break
}
ans = slices.Delete(ans, idx, idx+1)
}
return ans
}
func Filter[T any](s []T, f func(x T) bool) []T {
ans := make([]T, 0, len(s))
for _, x := range s {
if f(x) {
ans = append(ans, x)
}
}
return ans
}
func Map[T any, O any](f func(x T) O, s []T) []O {
ans := make([]O, 0, len(s))
for _, x := range s {
ans = append(ans, f(x))
}
return ans
}
func Repeat[T any](x T, n int) []T {
ans := make([]T, n)
for i := range n {
ans[i] = x
}
return ans
}
func Sort[T any](s []T, cmp func(a, b T) int) []T {
slices.SortFunc(s, cmp)
return s
}
func StableSort[T any](s []T, cmp func(a, b T) int) []T {
slices.SortStableFunc(s, cmp)
return s
}
func Uniq[T comparable](s []T) []T {
seen := NewSet[T](len(s))
ans := make([]T, 0, len(s))
for _, x := range s {
if !seen.Has(x) {
seen.Add(x)
ans = append(ans, x)
}
}
return ans
}
func sort_with_key[T any, C constraints.Ordered](stable bool, s []T, key func(a T) C) []T {
type t struct {
key C
val T
}
temp := make([]t, len(s))
for i, x := range s {
temp[i].val, temp[i].key = x, key(x)
}
key_cmp := func(a, b t) int {
return cmp.Compare(a.key, b.key)
}
if stable {
slices.SortStableFunc(temp, key_cmp)
} else {
slices.SortFunc(temp, key_cmp)
}
for i, x := range temp {
s[i] = x.val
}
return s
}
func SortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
return sort_with_key(false, s, key)
}
func StableSortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
return sort_with_key(true, s, key)
}
func Max[T constraints.Ordered](a T, items ...T) (ans T) {
ans = a
for _, q := range items {
if q > ans {
ans = q
}
}
return ans
}
func Min[T constraints.Ordered](a T, items ...T) (ans T) {
ans = a
for _, q := range items {
if q < ans {
ans = q
}
}
return ans
}
func Memset[T any](dest []T, pattern ...T) []T {
switch len(pattern) {
case 0:
var zero T
switch any(zero).(type) {
case byte: // special case this as the compiler can generate efficient code for memset of a byte slice to zero
bd := any(dest).([]byte)
for i := range bd {
bd[i] = 0
}
default:
for i := range dest {
dest[i] = zero
}
}
return dest
case 1:
val := pattern[0]
for i := range dest {
dest[i] = val
}
default:
bp := copy(dest, pattern)
for bp < len(dest) {
copy(dest[bp:], dest[:bp])
bp *= 2
}
}
return dest
}
type statable interface {
Stat() (os.FileInfo, error)
}
func Samefile(a, b any) bool {
var sta, stb os.FileInfo
var err error
switch v := a.(type) {
case string:
sta, err = os.Stat(v)
if err != nil {
return false
}
case statable:
sta, err = v.Stat()
if err != nil {
return false
}
case *os.FileInfo:
sta = *v
case os.FileInfo:
sta = v
default:
panic(fmt.Sprintf("a must be a string, os.FileInfo or a stat-able object not %T", v))
}
switch v := b.(type) {
case string:
stb, err = os.Stat(v)
if err != nil {
return false
}
case statable:
stb, err = v.Stat()
if err != nil {
return false
}
case *os.FileInfo:
stb = *v
case os.FileInfo:
stb = v
default:
panic(fmt.Sprintf("b must be a string, os.FileInfo or a stat-able object not %T", v))
}
return os.SameFile(sta, stb)
}
func Concat[T any](slices ...[]T) []T {
var total int
for _, s := range slices {
total += len(s)
}
result := make([]T, total)
var i int
for _, s := range slices {
i += copy(result[i:], s)
}
return result
}
func ShiftLeft[T any](s []T, amt int) []T {
leftover := len(s) - amt
if leftover > 0 {
copy(s, s[amt:])
}
return s[:leftover]
}
func SetStructDefaults(v reflect.Value) (err error) {
for _, field := range reflect.VisibleFields(v.Type()) {
if defval := field.Tag.Get("default"); defval != "" {
val := v.FieldByIndex(field.Index)
if val.CanSet() {
switch field.Type.Kind() {
case reflect.String:
if val.String() != "" {
val.SetString(defval)
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if d, err := strconv.ParseInt(defval, 10, 64); err == nil {
val.SetInt(d)
} else {
return fmt.Errorf("Could not parse default value for struct field: %#v with error: %s", field.Name, err)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if d, err := strconv.ParseUint(defval, 10, 64); err == nil {
val.SetUint(d)
} else {
return fmt.Errorf("Could not parse default value for struct field: %#v with error: %s", field.Name, err)
}
}
}
}
}
return
}
func IfElse[T any](condition bool, if_val T, else_val T) T {
if condition {
return if_val
}
return else_val
}
func SourceLine(skip_frames ...int) int {
s := 1
if len(skip_frames) > 0 {
s += skip_frames[0]
}
if _, _, ans, ok := runtime.Caller(s); ok {
return ans
}
return -1
}
func SourceLoc(skip_frames ...int) string {
s := 1
if len(skip_frames) > 0 {
s += skip_frames[0]
}
if _, file, line, ok := runtime.Caller(s); ok {
return filepath.Base(file) + ":" + strconv.Itoa(line)
}
return "unknown"
}
func FunctionName(a any) string {
if a == nil {
return "<nil>"
}
p := reflect.ValueOf(a).Pointer()
f := runtime.FuncForPC(p)
if f != nil {
return f.Name()
}
return ""
}
func Abs[T constraints.Integer](x T) T {
if x < 0 {
return -x
}
return x
}
var LanguageTag = sync.OnceValue(func() language.Tag {
// Check environment variables in order of precedence
var locale string
for _, v := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {
locale = os.Getenv(v)
if locale != "" {
break
}
}
if locale == "" {
return language.English // Default/fallback
}
// Remove encoding, e.g., ".UTF-8"
locale = strings.Split(locale, ".")[0]
// Replace underscore with hyphen to match BCP47 format (en_US -> en-US)
locale = strings.ReplaceAll(locale, "_", "-")
// Validate/normalize with golang.org/x/text/language
tag, err := language.Parse(locale)
if err != nil {
return language.English
}
return tag
})
// Replace control codes by unicode codepoints that describe the codes
// making the text safe to send to a terminal
func ReplaceControlCodes(text, replace_tab_by, replace_newline_by string) string {
buf := strings.Builder{}
for len(text) > 0 {
idx := simdstring.IndexC0String(text)
if idx < 0 {
if buf.Cap() == 0 {
return text
}
buf.WriteString(text)
break
}
if buf.Cap() == 0 {
buf.Grow(2 * len(text))
}
buf.WriteString(text[:idx])
switch text[idx] {
case '\n':
buf.WriteString(replace_newline_by)
case '\t':
buf.WriteString(replace_tab_by)
case 0x7f:
buf.WriteRune(0x2421)
default:
buf.WriteRune(0x2400 + rune(text[idx]))
}
text = text[idx+1:]
}
return buf.String()
}
+172
View File
@@ -0,0 +1,172 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"os"
"os/exec"
"os/user"
"runtime"
"strconv"
"strings"
"sync"
"howett.net/plist"
)
var _ = fmt.Print
type PasswdEntry struct {
Username, Pass, Uid, Gid, Gecos, Home, Shell string
}
func ParsePasswdLine(line string) (PasswdEntry, error) {
parts := strings.Split(line, ":")
if len(parts) == 7 {
return PasswdEntry{parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]}, nil
}
return PasswdEntry{}, fmt.Errorf("passwd line has %d colon delimited fields instead of 7", len(parts))
}
func ParsePasswdDatabase(raw string) (ans map[string]PasswdEntry) {
scanner := NewLineScanner(raw)
ans = make(map[string]PasswdEntry)
for scanner.Scan() {
line := scanner.Text()
if entry, e := ParsePasswdLine(line); e == nil {
ans[entry.Uid] = entry
}
}
return ans
}
func ParsePasswdFile(path string) (ans map[string]PasswdEntry, err error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return ParsePasswdDatabase(UnsafeBytesToString(raw)), nil
}
var passwd_err error
var passwd_database = sync.OnceValue(func() (ans map[string]PasswdEntry) {
ans, passwd_err = ParsePasswdFile("/etc/passwd")
return
})
func PwdEntryForUid(uid string) (ans PasswdEntry, err error) {
pwd := passwd_database()
if passwd_err != nil {
return ans, passwd_err
}
ans, found := pwd[uid]
if !found {
return ans, fmt.Errorf("No user matching the UID: %#v found", uid)
}
return ans, nil
}
func parse_dscl_data(raw []byte) (ans map[string]PasswdEntry, err error) {
var pd []any
_, err = plist.Unmarshal(raw, &pd)
if err != nil {
return
}
ans = make(map[string]PasswdEntry, 256)
for _, entry := range pd {
if e, ok := entry.(map[string]any); ok {
item := PasswdEntry{}
for key, a := range e {
array, ok := a.([]any)
if !ok || len(array) == 0 || !strings.HasPrefix(key, "dsAttrTypeNative:") {
continue
}
_, key, _ = strings.Cut(key, ":")
if val, ok := array[0].(string); ok {
switch key {
case "uid":
item.Uid = val
case "gid":
item.Gid = val
case "home":
item.Home = val
case "name":
item.Username = val
case "realname":
item.Gecos = val
case "shell":
item.Shell = val
}
}
}
ans[item.Uid] = item
}
}
return
}
var dscl_error error
var dscl_user_database = sync.OnceValue(func() map[string]PasswdEntry {
c := exec.Command("/usr/bin/dscl", "-plist", ".", "-readall", "/Users", "uid", "gid", "name", "realname", "home", "shell")
raw, err := c.Output()
if err != nil {
dscl_error = err
return nil
}
ans, err := parse_dscl_data(raw)
if err != nil {
dscl_error = err
return nil
}
return ans
})
func LoginShellForUser(u *user.User) (ans string, err error) {
var db map[string]PasswdEntry
switch runtime.GOOS {
case "darwin":
db = dscl_user_database()
err = dscl_error
default:
db = passwd_database()
err = passwd_err
}
if err != nil {
return
}
if rec, found := db[u.Uid]; found {
return rec.Shell, nil
}
return ans, fmt.Errorf("No user record available for user with UID: %#v", u.Uid)
}
func CurrentUser() (ans *user.User, err error) {
ans, err = user.Current()
if err != nil && runtime.GOOS == "darwin" {
uid := strconv.Itoa(os.Geteuid())
db := dscl_user_database()
if dscl_error != nil {
err = dscl_error
return
}
if rec, found := db[uid]; found {
u := user.User{Uid: uid, Gid: rec.Gid, Username: rec.Username, Name: rec.Gecos, HomeDir: rec.Home}
ans = &u
err = nil
} else {
err = fmt.Errorf("Could not find the current uid: %d in the DSCL user database", os.Geteuid())
}
}
return
}
func LoginShellForCurrentUser() (ans string, err error) {
u, err := CurrentUser()
if err != nil {
return ans, err
}
return LoginShellForUser(u)
}
File diff suppressed because it is too large. Load diff
+535
View File
@@ -0,0 +1,535 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"crypto/rand"
"encoding/base32"
"fmt"
"io/fs"
not_rand "math/rand/v2"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"unicode/utf8"
"github.com/shirou/gopsutil/v4/process"
"golang.org/x/sys/unix"
)
var Sep = string(os.PathSeparator)
func Expanduser(path string) string {
if !strings.HasPrefix(path, "~") {
return path
}
home, err := os.UserHomeDir()
if err != nil {
usr, err := user.Current()
if err == nil {
home = usr.HomeDir
}
}
if err != nil || home == "" {
return path
}
if path == "~" {
return home
}
path = strings.ReplaceAll(path, Sep, "/")
parts := strings.Split(path, "/")
if parts[0] == "~" {
parts[0] = home
} else {
uname := parts[0][1:]
if uname != "" {
u, err := user.Lookup(uname)
if err == nil && u.HomeDir != "" {
parts[0] = u.HomeDir
}
}
}
return strings.Join(parts, Sep)
}
func Abspath(path string) string {
q, err := filepath.Abs(path)
if err == nil {
return q
}
return path
}
var KittyExe = sync.OnceValue(func() string {
if kitty_pid := os.Getenv("KITTY_PID"); kitty_pid != "" {
if kp, err := strconv.ParseInt(kitty_pid, 10, 32); 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")
})
func ConfigDirForName(name string) (config_dir string) {
if kcd := os.Getenv("KITTY_CONFIG_DIRECTORY"); kcd != "" {
return Abspath(Expanduser(kcd))
}
var locations []string
seen := NewSet[string]()
add := func(x string) {
x = Abspath(Expanduser(x))
if !seen.Has(x) {
seen.Add(x)
locations = append(locations, x)
}
}
if xh := os.Getenv("XDG_CONFIG_HOME"); xh != "" {
add(xh)
}
if dirs := os.Getenv("XDG_CONFIG_DIRS"); dirs != "" {
for candidate := range strings.SplitSeq(dirs, ":") {
add(candidate)
}
}
add("~/.config")
if runtime.GOOS == "darwin" {
add("~/Library/Preferences")
}
for _, loc := range locations {
if loc != "" {
q := filepath.Join(loc, "kitty")
if _, err := os.Stat(filepath.Join(q, name)); err == nil {
if unix.Access(q, unix.W_OK) == nil {
config_dir = q
return
}
}
}
}
config_dir = os.Getenv("XDG_CONFIG_HOME")
if config_dir == "" {
config_dir = "~/.config"
}
config_dir = filepath.Join(Expanduser(config_dir), "kitty")
return
}
var ConfigDir = sync.OnceValue(func() (config_dir string) {
return ConfigDirForName("kitty.conf")
})
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
})
func macos_user_cache_dir() string {
// Sadly Go does not provide confstr() so we use this hack.
// Note that given a user generateduid and uid we can derive this by using
// the algorithm at https://github.com/ydkhatri/MacForensics/blob/master/darwin_path_generator.py
// but I cant find a good way to get the generateduid. Requires calling dscl in which case we might as well call getconf
// The data is in /var/db/dslocal/nodes/Default/users/<username>.plist but it needs root
// So instead we use various hacks to get it quickly, falling back to running /usr/bin/getconf
is_ok := func(m string) bool {
s, err := os.Stat(m)
if err != nil {
return false
}
stat, ok := s.Sys().(syscall.Stat_t)
return ok && s.IsDir() && int(stat.Uid) == os.Geteuid() && s.Mode().Perm() == 0o700 && unix.Access(m, unix.X_OK|unix.W_OK|unix.R_OK) == nil
}
if tdir := strings.TrimRight(os.Getenv("TMPDIR"), "/"); filepath.Base(tdir) == "T" {
if m := filepath.Join(filepath.Dir(tdir), "C"); is_ok(m) {
return m
}
}
matches, err := filepath.Glob("/private/var/folders/*/*/C")
if err == nil {
for _, m := range matches {
if is_ok(m) {
return m
}
}
}
out, err := exec.Command("/usr/bin/getconf", "DARWIN_USER_CACHE_DIR").Output()
if err == nil {
return strings.TrimRight(strings.TrimSpace(UnsafeBytesToString(out)), "/")
}
return ""
}
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
})
type Walk_callback func(path, abspath string, d fs.DirEntry, err error) error
func transform_symlink(path string) string {
if q, err := filepath.EvalSymlinks(path); err == nil {
return q
}
return path
}
func needs_symlink_recurse(path string, d fs.DirEntry) bool {
if d.Type()&os.ModeSymlink == os.ModeSymlink {
if s, serr := os.Stat(path); serr == nil && s.IsDir() {
return true
}
}
return false
}
type transformed_walker struct {
seen map[string]bool
real_callback Walk_callback
transform_func func(string) string
needs_recurse_func func(string, fs.DirEntry) bool
}
func (self *transformed_walker) walk(dirpath string) error {
resolved_path := self.transform_func(dirpath)
if self.seen[resolved_path] {
return nil
}
self.seen[resolved_path] = true
c := func(path string, d fs.DirEntry, err error) error {
if err != nil {
// Happens if ReadDir on d failed, skip it in that case
return fs.SkipDir
}
rpath, err := filepath.Rel(resolved_path, path)
if err != nil {
return err
}
// we cant use filepath.Join here as it calls Clean() which can alter dirpath if it contains .. or . etc.
path_based_on_original_dir := dirpath
if !strings.HasSuffix(dirpath, Sep) && dirpath != "" {
path_based_on_original_dir += Sep
}
path_based_on_original_dir += rpath
if self.needs_recurse_func(path, d) {
err = self.walk(path_based_on_original_dir)
} else {
err = self.real_callback(path_based_on_original_dir, path, d, err)
}
return err
}
return filepath.WalkDir(resolved_path, c)
}
// Walk, recursing into symlinks that point to directories. Ignores directories
// that could not be read.
func WalkWithSymlink(dirpath string, callback Walk_callback, transformers ...func(string) string) error {
transform := func(path string) string {
for _, t := range transformers {
path = t(path)
}
return transform_symlink(path)
}
sw := transformed_walker{
seen: make(map[string]bool), real_callback: callback, transform_func: transform, needs_recurse_func: needs_symlink_recurse}
return sw.walk(dirpath)
}
func RandomFilename() string {
b := []byte{0, 0, 0, 0, 0, 0, 0, 0}
_, err := rand.Read(b)
if err != nil {
return strconv.FormatUint(uint64(not_rand.Uint32()), 16)
}
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b)
}
func ResolveConfPath(path string) string {
cs := os.ExpandEnv(Expanduser(path))
if !filepath.IsAbs(cs) {
cs = filepath.Join(ConfigDir(), cs)
}
return cs
}
// Longest common path. Must be passed paths that have been cleaned by filepath.Clean
func Commonpath(paths ...string) (longest_prefix string) {
switch len(paths) {
case 0:
return
case 1:
return paths[0]
default:
sort.Strings(paths)
a, b := paths[0], paths[len(paths)-1]
sz := 0
for a != "" && b != "" {
ra, na := utf8.DecodeRuneInString(a)
rb, nb := utf8.DecodeRuneInString(b)
if ra != rb {
break
}
sz += na
a = a[na:]
b = b[nb:]
}
longest_prefix = paths[0][:sz]
}
return
}
// RelativeIfUnder returns the path to 'target' relative to 'base' if and only if
// target is inside base. It returns the relative path, a boolean indicating
// whether target is inside base, and an error.
//
// If resolveSymlinks is true, both base and target are run through filepath.EvalSymlinks
// before containment checks. If base == target the function returns "." and true.
//
// Notes:
// - This uses filepath.Rel and then checks for leading ".." components to determine
// whether the returned relative path escapes the base directory.
// - On Windows behaviour is consistent with filepath semantics.
func RelativeIfUnder(base, target string, resolveSymlinks bool) (rel string, inside bool, err error) {
// Optionally resolve symlinks first
if resolveSymlinks {
if base, err = filepath.EvalSymlinks(base); err != nil {
return "", false, fmt.Errorf("resolving base symlinks: %w", err)
}
if target, err = filepath.EvalSymlinks(target); err != nil {
return "", false, fmt.Errorf("resolving target symlinks: %w", err)
}
}
// Make absolute and clean
if base, err = filepath.Abs(base); err != nil {
return "", false, fmt.Errorf("abs base: %w", err)
}
if target, err = filepath.Abs(target); err != nil {
return "", false, fmt.Errorf("abs target: %w", err)
}
// On Windows the volume (drive letter) must match. If they don't, the path is not inside.
if runtime.GOOS == "windows" {
if !strings.EqualFold(filepath.VolumeName(base), filepath.VolumeName(target)) {
return "", false, nil
}
}
// Get the relative path from base to target
rel, err = filepath.Rel(base, target)
if err != nil {
return "", false, fmt.Errorf("computing relative path: %w", err)
}
// If rel begins with ".." (or is ".."), then target is outside base.
// Use os.PathSeparator to be portable.
up := ".." + string(os.PathSeparator)
if rel == ".." || strings.HasPrefix(rel, up) {
return "", false, nil
}
// If the returned rel is empty (shouldn't normally happen), normalize to "."
if rel == "" {
rel = "."
}
return rel, true, nil
}
func volnamelen(path string) int {
return len(filepath.VolumeName(path))
}
func EvalSymlinksThatExist(path string) (string, error) {
volLen := volnamelen(path)
pathSeparator := string(os.PathSeparator)
if volLen < len(path) && os.IsPathSeparator(path[volLen]) {
volLen++
}
vol := path[:volLen]
dest := vol
linksWalked := 0
for start, end := volLen, volLen; start < len(path); start = end {
for start < len(path) && os.IsPathSeparator(path[start]) {
start++
}
end = start
for end < len(path) && !os.IsPathSeparator(path[end]) {
end++
}
// On Windows, "." can be a symlink.
// We look it up, and use the value if it is absolute.
// If not, we just return ".".
isWindowsDot := runtime.GOOS == "windows" && path[volnamelen(path):] == "."
// The next path component is in path[start:end].
if end == start {
// No more path components.
break
} else if path[start:end] == "." && !isWindowsDot {
// Ignore path component ".".
continue
} else if path[start:end] == ".." {
// Back up to previous component if possible.
// Note that volLen includes any leading slash.
// Set r to the index of the last slash in dest,
// after the volume.
var r int
for r = len(dest) - 1; r >= volLen; r-- {
if os.IsPathSeparator(dest[r]) {
break
}
}
if r < volLen || dest[r+1:] == ".." {
// Either path has no slashes
// (it's empty or just "C:")
// or it ends in a ".." we had to keep.
// Either way, keep this "..".
if len(dest) > volLen {
dest += pathSeparator
}
dest += ".."
} else {
// Discard everything since the last slash.
dest = dest[:r]
}
continue
}
// Ordinary path component. Add it to result.
if len(dest) > volnamelen(dest) && !os.IsPathSeparator(dest[len(dest)-1]) {
dest += pathSeparator
}
dest += path[start:end]
// Resolve symlink.
fi, err := os.Lstat(dest)
if err != nil {
if os.IsNotExist(err) {
if end < len(path) {
dest += path[end:]
}
return filepath.Clean(dest), nil
}
return "", err
}
if fi.Mode()&fs.ModeSymlink == 0 {
if !fi.Mode().IsDir() && end < len(path) {
return "", fmt.Errorf("%s is not a directory while resolving symlinks in %s", dest, path)
}
continue
}
// Found symlink.
linksWalked++
if linksWalked > 255 {
return "", fmt.Errorf("EvalSymlinksThatExist: too many symlinks in %s", path)
}
link, err := os.Readlink(dest)
if err != nil {
return "", err
}
if isWindowsDot && !filepath.IsAbs(link) {
// On Windows, if "." is a relative symlink,
// just return ".".
break
}
path = link + path[end:]
v := volnamelen(link)
if v > 0 {
// Symlink to drive name is an absolute path.
if v < len(link) && os.IsPathSeparator(link[v]) {
v++
}
vol = link[:v]
dest = vol
end = len(vol)
} else if len(link) > 0 && os.IsPathSeparator(link[0]) {
// Symlink to absolute path.
dest = link[:1]
end = 1
vol = link[:1]
volLen = 1
} else {
// Symlink to relative path; replace last
// path component in dest.
var r int
for r = len(dest) - 1; r >= volLen; r-- {
if os.IsPathSeparator(dest[r]) {
break
}
}
if r < volLen {
dest = vol
} else {
dest = dest[:r]
}
end = 0
}
}
return filepath.Clean(dest), nil
}
+65
View File
@@ -0,0 +1,65 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package paths
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type Ctx struct {
home, cwd string
}
func (ctx *Ctx) SetHome(val string) {
ctx.home = val
}
func (ctx *Ctx) SetCwd(val string) {
ctx.cwd = val
}
func (ctx *Ctx) HomePath() (ans string) {
ans = ctx.home
if ans == "" {
ans = utils.Expanduser("~")
}
return
}
func (ctx *Ctx) CwdPath() (ans string) {
ans = ctx.cwd
if ans == "" {
var err error
ans, err = os.Getwd()
if err != nil {
ans = "."
}
}
return
}
func abspath(path, base string) (ans string) {
return filepath.Join(base, path)
}
func (ctx *Ctx) Abspath(path string) (ans string) {
return abspath(path, ctx.CwdPath())
}
func (ctx *Ctx) AbspathFromHome(path string) (ans string) {
return abspath(path, ctx.HomePath())
}
func (ctx *Ctx) ExpandHome(path string) (ans string) {
if strings.HasPrefix(path, "~/") {
return ctx.AbspathFromHome(path)
}
return path
}
+35
View File
@@ -0,0 +1,35 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package random
import (
"crypto/rand"
"fmt"
"math/big"
"golang.org/x/exp/constraints"
)
var _ = fmt.Print
// Return a random integer in the range [0, limit). limit must be > 0
func Int[T constraints.Integer](limit T) T {
b := big.NewInt(int64(limit))
n, err := rand.Int(rand.Reader, b)
if err != nil {
panic(err)
}
return T(n.Uint64())
}
// Return one of items randomnly
func Choice[T any](items ...T) T {
return items[Int(len(items))]
}
// Write randomn bytes into the provided slice
func Bytes(b []byte) {
if _, err := rand.Read(b); err != nil {
panic(err)
}
}
+53
View File
@@ -0,0 +1,53 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"regexp"
"strings"
)
var _ = fmt.Print
var pat_cache = NewLRUCache[string, *regexp.Regexp](128)
type SubMatch struct {
Text string
Start, End int
}
func Compile(pat string) (*regexp.Regexp, error) {
return pat_cache.GetOrCreate(pat, regexp.Compile)
}
func MustCompile(pat string) *regexp.Regexp {
return pat_cache.MustGetOrCreate(pat, regexp.MustCompile)
}
func ReplaceAll(cpat *regexp.Regexp, str string, repl func(full_match string, groupdict map[string]SubMatch) string) string {
result := strings.Builder{}
result.Grow(len(str) + 256)
last_index := 0
matches := cpat.FindAllStringSubmatchIndex(str, -1)
names := cpat.SubexpNames()
groupdict := make(map[string]SubMatch, len(names))
for _, v := range matches {
match_start, match_end := v[0], v[1]
full_match := str[match_start:match_end]
for k := range groupdict {
delete(groupdict, k)
}
for i, name := range names {
idx := 2 * i
if v[idx] > -1 && v[idx+1] > -1 {
groupdict[name] = SubMatch{Text: str[v[idx]:v[idx+1]], Start: v[idx], End: v[idx+1]}
}
}
result.WriteString(str[last_index:match_start])
result.WriteString(repl(full_match, groupdict))
last_index = match_end
}
result.WriteString(str[last_index:])
return result.String()
}
+123
View File
@@ -0,0 +1,123 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
)
var _ = fmt.Print
func rb_min(a, b uint64) uint64 {
if a < b {
return a
} else {
return b
}
}
type RingBuffer[T any] struct {
buffer []T
read_pos uint64
use_count uint64
}
func NewRingBuffer[T any](size uint64) *RingBuffer[T] {
return &RingBuffer[T]{
buffer: make([]T, size),
}
}
func (self *RingBuffer[T]) Len() uint64 {
return self.use_count
}
func (self *RingBuffer[T]) Capacity() uint64 {
return uint64(len(self.buffer))
}
func (self *RingBuffer[T]) Clear() {
self.read_pos = 0
self.use_count = 0
}
func (self *RingBuffer[T]) Grow(new_size uint64) {
if new_size <= self.Capacity() {
return
}
buf := make([]T, new_size)
if self.use_count > 0 {
self.ReadTillEmpty(buf)
}
self.buffer = buf
self.read_pos = 0
}
func (self *RingBuffer[T]) WriteTillFull(p ...T) uint64 {
ssz := self.Capacity()
available := ssz - self.use_count
sz := rb_min(uint64(len(p)), available)
if sz == 0 {
return 0
}
tail := (self.read_pos + self.use_count) % ssz
write_end := (self.read_pos + self.use_count + sz) % ssz
self.use_count += sz
p = p[:sz]
if tail <= write_end {
copy(self.buffer[tail:], p)
} else {
first_write := ssz - tail
copy(self.buffer[tail:], p[:first_write])
copy(self.buffer, p[first_write:])
}
return sz
}
func (self *RingBuffer[T]) WriteAllAndDiscardOld(p ...T) {
ssz := self.Capacity()
left := uint64(len(p))
if left >= ssz { // Fast path
extra := left - ssz
copy(self.buffer, p[extra:])
self.read_pos = 0
self.use_count = ssz
return
}
for {
written := self.WriteTillFull(p...)
p = p[written:]
left = uint64(len(p))
if left == 0 {
break
}
self.slices_to_read(left)
}
}
func (self *RingBuffer[T]) ReadTillEmpty(p []T) uint64 {
a, b := self.slices_to_read(uint64(len(p)))
copy(p, a)
copy(p[len(a):], b)
return uint64(len(a)) + uint64(len(b))
}
func (self *RingBuffer[T]) ReadAll() []T {
ans := make([]T, self.Len())
self.ReadTillEmpty(ans)
return ans
}
func (self *RingBuffer[T]) slices_to_read(sz uint64) ([]T, []T) {
ssz := self.Capacity()
sz = rb_min(sz, self.use_count)
head := self.read_pos
end_read := (head + sz) % ssz
self.use_count -= sz
self.read_pos = end_read
if end_read > head || sz == 0 {
return self.buffer[head:end_read], self.buffer[0:0]
}
first_read := ssz - head
return self.buffer[head : head+first_read], self.buffer[0 : sz-first_read]
}
+46
View File
@@ -0,0 +1,46 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"reflect"
"testing"
)
var _ = fmt.Print
func TestRingBuffer(t *testing.T) {
r := NewRingBuffer[int](8)
test_contents := func(expected ...int) {
actual := make([]int, len(expected))
num_read := r.ReadTillEmpty(actual)
if num_read != uint64(len(actual)) {
t.Fatalf("Did not read expected num of items: %d != %d", num_read, len(expected))
}
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("Did not read expected items:\n%#v != %#v", actual, expected)
}
if r.Len() != 0 {
t.Fatalf("Reading contents did not empty the buffer")
}
}
r.WriteTillFull(1, 2, 3, 4)
test_contents(1, 2, 3, 4)
r.WriteTillFull(1, 2, 3, 4)
test_contents(1, 2, 3, 4)
r.Clear()
r.WriteTillFull(1, 2, 3, 4)
r.ReadTillEmpty([]int{0, 1})
test_contents(3, 4)
r.WriteTillFull(1, 2, 3, 4, 5)
test_contents(1, 2, 3, 4, 5)
r.Clear()
r.WriteTillFull(1, 2, 3, 4)
r.WriteAllAndDiscardOld(5, 6, 7, 8, 9)
test_contents(2, 3, 4, 5, 6, 7, 8, 9)
}
+85
View File
@@ -0,0 +1,85 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package secrets
import (
"crypto/rand"
"encoding/hex"
"fmt"
"math/big"
"github.com/emmansun/base64"
)
var _ = fmt.Print
const DEFAULT_NUM_OF_BYTES_FOR_TOKEN = 32
func encode_bytes(input []byte, alphabet string) string {
if len(input) == 0 {
return ""
}
base := big.NewInt(int64(len(alphabet)))
num := new(big.Int).SetBytes(input)
mod := new(big.Int)
var result []byte
// Convert the large integer into the custom base system
for num.Sign() > 0 {
num.DivMod(num, base, mod)
result = append(result, alphabet[mod.Int64()])
}
// Preserve leading zeros from the original byte slice
for _, b := range input {
if b != 0x00 {
break
}
result = append(result, alphabet[0])
}
// Reverse the result slice since DivMod extracts digits backward
for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
result[i], result[j] = result[j], result[i]
}
return string(result)
}
func TokenBytes(nbytes ...int) ([]byte, error) {
if len(nbytes) == 0 {
nbytes = []int{DEFAULT_NUM_OF_BYTES_FOR_TOKEN}
}
buf := make([]byte, nbytes[0])
_, err := rand.Read(buf)
if err != nil {
return nil, err
}
return buf, nil
}
func TokenHex(nbytes ...int) (string, error) {
b, err := TokenBytes(nbytes...)
if err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func TokenBase64(nbytes ...int) (string, error) {
b, err := TokenBytes(nbytes...)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(b), nil
}
func TokenAlphabet(nbytes int, alphabet string) (string, error) {
b, err := TokenBytes(nbytes)
if err != nil {
return "", err
}
return encode_bytes(b, alphabet), nil
}
+103
View File
@@ -0,0 +1,103 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"time"
"golang.org/x/sys/unix"
)
type Selector struct {
read_set, write_set, err_set unix.FdSet
read_fds, write_fds, err_fds map[int]bool
}
func CreateSelect(expected_number_of_fds int) *Selector {
var ans Selector
ans.read_fds = make(map[int]bool, expected_number_of_fds)
ans.write_fds = make(map[int]bool, expected_number_of_fds)
ans.err_fds = make(map[int]bool, expected_number_of_fds)
return &ans
}
func (self *Selector) register(fd int, fdset *map[int]bool) {
(*fdset)[fd] = true
}
func (self *Selector) RegisterRead(fd int) {
self.register(fd, &self.read_fds)
}
func (self *Selector) RegisterWrite(fd int) {
self.register(fd, &self.write_fds)
}
func (self *Selector) RegisterError(fd int) {
self.register(fd, &self.err_fds)
}
func (self *Selector) unregister(fd int, fdset *map[int]bool) {
(*fdset)[fd] = false
}
func (self *Selector) UnRegisterRead(fd int) {
self.unregister(fd, &self.read_fds)
}
func (self *Selector) UnRegisterWrite(fd int) {
self.unregister(fd, &self.write_fds)
}
func (self *Selector) UnRegisterError(fd int) {
self.unregister(fd, &self.err_fds)
}
func (self *Selector) Wait(timeout time.Duration) (num_ready int, err error) {
max_fd_num := 0
init_set := func(s *unix.FdSet, m map[int]bool) {
s.Zero()
for fd, enabled := range m {
if fd > -1 && enabled {
if max_fd_num < fd {
max_fd_num = fd
}
s.Set(fd)
}
}
}
init_set(&self.read_set, self.read_fds)
init_set(&self.write_set, self.write_fds)
init_set(&self.err_set, self.err_fds)
num_ready, err = Select(max_fd_num+1, &self.read_set, &self.write_set, &self.err_set, timeout)
if err == unix.EINTR {
self.read_set.Zero()
self.write_set.Zero()
self.err_set.Zero()
return 0, err
}
return
}
func (self *Selector) WaitForever() (num_ready int, err error) {
return self.Wait(-1)
}
func (self *Selector) IsReadyToRead(fd int) bool {
return fd > -1 && self.read_set.IsSet(fd)
}
func (self *Selector) IsReadyToWrite(fd int) bool {
return fd > -1 && self.write_set.IsSet(fd)
}
func (self *Selector) IsErrored(fd int) bool {
return fd > -1 && self.err_set.IsSet(fd)
}
func (self *Selector) UnregisterAll() {
self.read_fds = make(map[int]bool)
self.write_fds = make(map[int]bool)
self.err_fds = make(map[int]bool)
}
+19
View File
@@ -0,0 +1,19 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
//go:build linux
package utils
import (
"time"
"golang.org/x/sys/unix"
)
func Select(nfd int, r *unix.FdSet, w *unix.FdSet, e *unix.FdSet, timeout time.Duration) (n int, err error) {
if timeout < 0 {
return unix.Pselect(nfd, r, w, e, nil, nil)
}
ts := unix.NsecToTimespec(int64(timeout))
return unix.Pselect(nfd, r, w, e, &ts, nil)
}
+21
View File
@@ -0,0 +1,21 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
//go:build !linux
package utils
import (
"time"
"golang.org/x/sys/unix"
)
// Go unix does not wrap pselect on darwin
func Select(nfd int, r *unix.FdSet, w *unix.FdSet, e *unix.FdSet, timeout time.Duration) (n int, err error) {
if timeout < 0 {
return unix.Select(nfd, r, w, e, nil)
}
ts := unix.NsecToTimeval(int64(timeout))
return unix.Select(nfd, r, w, e, &ts)
}
+160
View File
@@ -0,0 +1,160 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
)
var _ = fmt.Print
func Keys[M ~map[K]V, K comparable, V any](m M) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
func Values[M ~map[K]V, K comparable, V any](m M) []V {
r := make([]V, 0, len(m))
for _, k := range m {
r = append(r, k)
}
return r
}
type Set[T comparable] struct {
items map[T]struct{}
}
func (self *Set[T]) Add(val T) {
self.items[val] = struct{}{}
}
func (self *Set[T]) AddItems(val ...T) {
for _, x := range val {
self.items[x] = struct{}{}
}
}
func (self *Set[T]) String() string {
return fmt.Sprintf("%#v", Keys(self.items))
}
func (self *Set[T]) Remove(val T) {
delete(self.items, val)
}
func (self *Set[T]) Discard(val T) {
delete(self.items, val)
}
func (self *Set[T]) Has(val T) bool {
_, ok := self.items[val]
return ok
}
func (self *Set[T]) Clear() {
clear(self.items)
}
func (self *Set[T]) Len() int {
return len(self.items)
}
func (self *Set[T]) ForEach(f func(T)) {
for x := range self.items {
f(x)
}
}
func (self *Set[T]) Iterable() map[T]struct{} {
return self.items
}
func (self *Set[T]) Any() T {
for x := range self.items {
return x
}
panic("set is empty")
}
func (self *Set[T]) AsSlice() []T {
return Keys(self.items)
}
func (self *Set[T]) Intersect(other *Set[T]) (ans *Set[T]) {
if other == nil {
return NewSet[T]()
}
if self.Len() < other.Len() {
ans = NewSet[T](self.Len())
for x := range self.items {
if _, ok := other.items[x]; ok {
ans.items[x] = struct{}{}
}
}
} else {
ans = NewSet[T](other.Len())
for x := range other.items {
if _, ok := self.items[x]; ok {
ans.items[x] = struct{}{}
}
}
}
return
}
func (self *Set[T]) Subtract(other *Set[T]) (ans *Set[T]) {
ans = NewSet[T](self.Len())
for x := range self.items {
if other == nil || !other.Has(x) {
ans.items[x] = struct{}{}
}
}
return ans
}
func (self *Set[T]) IsSubsetOf(other *Set[T]) bool {
if other == nil {
return self.Len() == 0
}
for x := range self.items {
if !other.Has(x) {
return false
}
}
return true
}
func (self *Set[T]) Equal(other *Set[T]) bool {
l := self.Len()
if other == nil {
return l == 0
}
if l != other.Len() {
return false
}
for x := range self.items {
if !other.Has(x) {
return false
}
}
return true
}
func NewSet[T comparable](capacity ...int) (ans *Set[T]) {
if len(capacity) == 0 {
ans = &Set[T]{items: make(map[T]struct{}, 8)}
} else {
ans = &Set[T]{items: make(map[T]struct{}, capacity[0])}
}
return
}
func NewSetWithItems[T comparable](items ...T) (ans *Set[T]) {
ans = NewSet[T](len(items))
ans.AddItems(items...)
return ans
}
+40
View File
@@ -0,0 +1,40 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"strings"
)
var _ = fmt.Print
// Quotes arbitrary strings for bash, dash and zsh
func QuoteStringForSH(x string) string {
parts := strings.Split(x, "'")
for i, p := range parts {
parts[i] = "'" + p + "'"
}
return strings.Join(parts, "\"'\"")
}
// Quotes arbitrary strings for fish
func QuoteStringForFish(x string) string {
x = strings.ReplaceAll(x, "\\", "\\\\")
x = strings.ReplaceAll(x, "'", "\\'")
return "'" + x + "'"
}
// Escapes common shell meta characters
func EscapeSHMetaCharacters(x string) string {
ans := strings.Builder{}
ans.Grow(len(x) + 32)
for _, ch := range x {
switch ch {
case '\\', '|', '&', ';', '<', '>', '(', ')', '$', '\'', '"', ' ', '\n', '\t':
ans.WriteRune('\\')
}
ans.WriteRune(ch)
}
return ans.String()
}
+148
View File
@@ -0,0 +1,148 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package shlex
import (
"fmt"
"strconv"
"strings"
"unicode/utf8"
)
var _ = fmt.Print
type state int
const (
normal state = iota
control_char
backslash
hex_digit
oct_digit
)
type ansi_c struct {
state state
max_num_of_digits, digit_idx int
digits [16]rune
output strings.Builder
}
func is_hex_char(ch rune) bool {
return ('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
}
func is_oct_char(ch rune) bool {
return '0' <= ch && ch <= '7'
}
func (self *ansi_c) write_digits(base int) {
if self.digit_idx > 0 {
text := string(self.digits[:self.digit_idx])
if val, err := strconv.ParseUint(text, base, 32); err == nil && val <= utf8.MaxRune {
self.output.WriteRune(rune(val))
}
}
self.digit_idx = 0
self.state = normal
}
func (self *ansi_c) parse(ch rune) {
switch self.state {
case normal:
if ch == '\\' {
self.state = backslash
} else {
self.output.WriteRune(ch)
}
case control_char:
self.output.WriteRune(ch & 0x1f)
self.state = normal
case hex_digit:
if self.digit_idx < self.max_num_of_digits && is_hex_char(ch) {
self.digits[self.digit_idx] = ch
self.digit_idx++
} else {
self.write_digits(16)
self.parse(ch)
}
case oct_digit:
if self.digit_idx < self.max_num_of_digits && is_oct_char(ch) {
self.digits[self.digit_idx] = ch
self.digit_idx++
} else {
self.write_digits(8)
self.parse(ch)
}
case backslash:
self.state = normal
switch ch {
default:
self.output.WriteRune('\\')
self.output.WriteRune(ch)
case 'a':
self.output.WriteRune(7)
case 'b':
self.output.WriteRune(8)
case 'c':
self.state = control_char
case 'e', 'E':
self.output.WriteRune(27)
case 'f':
self.output.WriteRune(12)
case 'n':
self.output.WriteRune(10)
case 'r':
self.output.WriteRune(13)
case 't':
self.output.WriteRune(9)
case 'v':
self.output.WriteRune(11)
case 'x':
self.max_num_of_digits, self.digit_idx, self.state = 2, 0, hex_digit
case 'u':
self.max_num_of_digits, self.digit_idx, self.state = 4, 0, hex_digit
case 'U':
self.max_num_of_digits, self.digit_idx, self.state = 8, 0, hex_digit
case '0', '1', '2', '3', '4', '5', '6', '7':
self.max_num_of_digits, self.digit_idx, self.state = 3, 1, oct_digit
self.digits[0] = ch
case '\\':
self.output.WriteRune('\\')
case '?':
self.output.WriteRune('?')
case '"':
self.output.WriteRune('"')
case '\'':
self.output.WriteRune('\'')
}
}
}
func (self *ansi_c) finish() string {
switch self.state {
case hex_digit:
self.write_digits(16)
case oct_digit:
self.write_digits(8)
case backslash:
self.output.WriteRune('\\')
case control_char:
self.output.WriteString("\\c")
}
self.state = normal
self.digit_idx = 0
s := self.output.String()
self.output.Reset()
return s
}
func ExpandANSICEscapes(src string) string {
p := ansi_c{}
p.output.Grow(len(src))
for _, ch := range src {
p.parse(ch)
}
return p.finish()
}
+232
View File
@@ -0,0 +1,232 @@
/*
Package shlex implements a simple lexer which splits input in to tokens using
shell-style rules for quoting.
The basic use case uses the default ASCII lexer to split a string into sub-strings:
shlex.Split("one \"two three\" four") -> []string{"one", "two three", "four"}
To process a stream of strings:
l := NewLexer(os.Stdin)
for ; token, err := l.Next(); err != nil {
// process token
}
*/
package shlex
import (
"fmt"
"github.com/kovidgoyal/kitty/tools/utils"
"strings"
"unicode/utf8"
)
type Word struct {
Value string // The word, which can be empty if it was an empty quoted string
Pos int // The position in the input string of the word or the trailer, -1 if EOF is reached
Err error // Indicates an error (unterminated string or trailing unescaped backslash)
Trailer string // Extra trailing data such as an unterminated string or an unescaped backslash. Present only if Err != nil
}
type lexer_state int
// Lexer state machine states
const (
lex_normal lexer_state = iota
word
string_without_escapes
string_with_escapes
)
// Lexer turns an input stream into a sequence of tokens. Whitespace is skipped.
type Lexer struct {
state lexer_state
src string
src_sz, src_pos, word_start int
buf strings.Builder
allow_empty bool
}
// NewLexer creates a new lexer from an input string.
func NewLexer(x string) *Lexer {
return &Lexer{src: x, src_sz: len(x)}
}
func (self *Lexer) start_word() {
self.buf.Reset()
self.word_start = self.src_pos - 1
}
func (self *Lexer) get_word() Word {
self.allow_empty = false
return Word{Pos: self.word_start, Value: self.buf.String()}
}
func (self *Lexer) write_ch(ch byte) {
self.buf.WriteByte(ch)
}
func (self *Lexer) write_escaped_ch() bool {
ch, count := utf8.DecodeRuneInString(self.src[self.src_pos:])
if count > 0 {
self.src_pos += count
// Invalid UTF-8 always decodes as (RuneError, 1), so a larger size means a real U+FFFD.
if ch != utf8.RuneError || count > 1 {
self.buf.WriteRune(ch)
}
return true
}
return false
}
// Next returns the next word. At EOF Word.Pos will be -1
func (self *Lexer) Next() (ans Word) {
const string_with_escapes_delim = '"'
const string_without_escapes_delim = '\''
const escape_char = '\\'
for self.src_pos < self.src_sz {
ch := self.src[self.src_pos]
self.src_pos++
switch self.state {
case lex_normal:
switch ch {
case ' ', '\n', '\r', '\t':
case string_with_escapes_delim:
self.state = string_with_escapes
self.start_word()
case string_without_escapes_delim:
self.state = string_without_escapes
self.start_word()
case escape_char:
self.start_word()
if !self.write_escaped_ch() {
ans.Trailer = "\\"
ans.Err = fmt.Errorf("Extra backslash at end of input")
ans.Pos = self.word_start
return
}
self.state = word
default:
self.state = word
self.start_word()
self.write_ch(ch)
}
case word:
switch ch {
case ' ', '\n', '\r', '\t':
self.state = lex_normal
if self.buf.Len() > 0 || self.allow_empty {
return self.get_word()
}
case string_with_escapes_delim:
self.state = string_with_escapes
case string_without_escapes_delim:
self.state = string_without_escapes
case escape_char:
if !self.write_escaped_ch() {
ans.Pos = self.word_start
ans.Trailer = self.buf.String() + "\\"
ans.Err = fmt.Errorf("Extra backslash at end of input")
return
}
default:
self.write_ch(ch)
}
case string_without_escapes:
switch ch {
case string_without_escapes_delim:
self.state = word
self.allow_empty = true
default:
self.write_ch(ch)
}
case string_with_escapes:
switch ch {
case string_with_escapes_delim:
self.state = word
self.allow_empty = true
case escape_char:
self.write_escaped_ch()
default:
self.write_ch(ch)
}
}
}
switch self.state {
case word:
self.state = lex_normal
if self.buf.Len() > 0 || self.allow_empty {
return self.get_word()
}
case string_with_escapes, string_without_escapes:
self.state = lex_normal
ans.Trailer = self.buf.String()
ans.Pos = self.word_start
ans.Err = fmt.Errorf("Unterminated string at end of input")
return
case lex_normal:
}
ans.Pos = -1
return
}
// Split partitions a string into a slice of strings.
func Split(s string) (ans []string, err error) {
l := NewLexer(s)
var word Word
for {
word = l.Next()
if word.Err != nil {
return ans, word.Err
}
if word.Pos < 0 {
break
}
ans = append(ans, word.Value)
}
return
}
func Quote(s string) string {
if s == "" {
return s
}
if utils.MustCompile(`[^\w@%+=:,./-]`).MatchString(s) {
return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'"
}
return s
}
// SplitForCompletion partitions a string into a slice of strings. It differs from Split in being
// more relaxed about errors and also adding an empty string at the end if s ends with a Space.
func SplitForCompletion(s string) (argv []string, position_of_last_arg int) {
t := NewLexer(s)
argv = make([]string, 0, len(s)/4)
for {
word := t.Next()
if word.Pos < 0 || word.Err != nil {
if word.Trailer == "" {
trimmed := strings.TrimRight(s, " ")
if len(trimmed) < len(s) { // trailing spaces
pos := position_of_last_arg
if len(argv) > 0 {
pos += len(argv[len(argv)-1])
}
if pos < len(s) { // trailing whitespace
argv = append(argv, "")
position_of_last_arg = len(s)
}
}
} else {
argv = append(argv, word.Trailer)
position_of_last_arg = word.Pos
}
break
}
position_of_last_arg = word.Pos
argv = append(argv, word.Value)
}
return
}
+145
View File
@@ -0,0 +1,145 @@
package shlex
import (
"testing"
"github.com/google/go-cmp/cmp"
)
var (
// one two "three four" "five \"six\"" seven#eight # nine # ten
// eleven 'twelve\'
testString = "one two \"three four\" \"five \\\"six\\\"\" seven#eight # nine # ten eleven 'twelve\\' thirteen=13 fourteen/14"
)
func TestLexer(t *testing.T) {
testInput := testString
expectedStrings := []string{"one", "two", "three four", "five \"six\"", "seven#eight", "#", "nine", "#", "ten", "eleven", "twelve\\", "thirteen=13", "fourteen/14"}
lexer := NewLexer(testInput)
for i, want := range expectedStrings {
got := lexer.Next()
if got.Value != want {
t.Errorf("Lexer.Next()[%v] of %q -> %v. Want: %v", i, testString, got, want)
}
}
}
type Tok struct {
Pos int
Val string
}
func TestSplit(t *testing.T) {
want := []string{"one", "two", "three four", "five \"six\"", "seven#eight", "#", "nine", "#", "ten", "eleven", "twelve\\", "thirteen=13", "fourteen/14"}
got, err := Split(testString)
if err != nil {
t.Error(err)
}
if len(want) != len(got) {
t.Errorf("Split(%q) -> %v. Want: %v", testString, got, want)
}
for i := range got {
if got[i] != want[i] {
t.Errorf("Split(%q)[%v] -> %v. Want: %v", testString, i, got[i], want[i])
}
}
for _, x := range []string{
`abc\`, `\`, `'abc`, `'`, `"`, `asd\`,
} {
_, err := Split(x)
if err == nil {
t.Fatalf("Failed to get an error for: %#v", x)
}
}
s := func(q string) (ans []Tok) {
l := NewLexer(q)
for {
w := l.Next()
if w.Err != nil {
t.Fatal(w.Err)
}
if w.Pos < 0 {
break
}
ans = append(ans, Tok{w.Pos, w.Value})
}
return
}
for q, expected := range map[string][]Tok{
`a""`: {{0, "a"}},
`a""b`: {{0, "ab"}},
`-1 "" 2`: {{0, "-1"}, {3, ""}, {6, "2"}},
`-1 '' 2`: {{0, "-1"}, {3, ""}, {6, "2"}},
`a ""`: {{0, "a"}, {2, ""}},
`""`: {{0, ""}},
`"ab"`: {{0, "ab"}},
`x "ab"y \m`: {{0, `x`}, {2, `aby`}, {8, `m`}},
`x'y"\z'1`: {{0, `xy"\z1`}},
`\abc\ d`: {{0, `abc d`}},
``: nil,
` `: nil,
" \tabc\n\t\r ": {{2, "abc"}},
"a\\\xffb": {{0, "ab"}}, // an escaped invalid byte is still dropped
// An escaped U+FFFD is a real character, not a decoding failure, so it
// survives the escape the way it does unescaped or single quoted.
"a\\�b": {{0, "a�b"}},
"\"a\\�b\"": {{0, "a�b"}},
} {
if diff := cmp.Diff(expected, s(q)); diff != "" {
t.Fatalf("Failed for string: %#v\n%s", q, diff)
}
}
}
func TestSplitForCompletion(t *testing.T) {
test := func(cmdline string, last_arg_pos int, expected ...string) {
actual, actual_pos := SplitForCompletion(cmdline)
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("Failed to split: %s\n%s", cmdline, diff)
}
if last_arg_pos != actual_pos {
t.Fatalf("Failed to split: %#v\n Last arg pos: %d != %d", cmdline, last_arg_pos, actual_pos)
}
}
test("a b", 2, "a", "b")
test("a b ", 4, "a", "b", "")
test("a b ", 5, "a", "b", "")
test("ab cd ", 6, "ab", "cd", "")
test("launch --type ", 14, "launch", "--type", "")
test(`a "b c" `, 8, "a", "b c", "")
test(`a "b c"`, 2, "a", "b c")
test(`a "b c`, 2, "a", "b c")
test(`a "" b`, 5, "a", "", "b")
test(`a '' `, 5, "a", "", "")
}
func TestExpandANSICEscapes(t *testing.T) {
var m = map[string]string{
"abc": "abc",
`a\ab`: "a\ab",
`a\eb`: "a\x1bb",
`a\r\nb`: "a\r\nb",
`a\c b`: "a\000b",
`a\c`: "a\\c",
`a\x1bb`: "a\x1bb",
`a\x1b`: "a\x1b",
`a\x1`: "a\x01",
`a\x1\\`: "a\x01\\",
`a\x1g`: "a\x01g",
`a\z\"`: "a\\z\"",
`a\123b`: "a\123b",
`a\128b`: "a\0128b",
`a\u1234e`: "a\u1234e",
`a\U1f1eez`: "a\U0001f1eez",
}
for q, expected := range m {
actual := ExpandANSICEscapes(q)
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("Failed to process: %#v\n%s", q, diff)
}
}
}
+108
View File
@@ -0,0 +1,108 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"crypto/rand"
"math"
"math/big"
"github.com/ALTree/bigfloat"
"github.com/google/uuid"
)
const (
ESCAPE_CODE_SAFE_ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ "
HUMAN_ALPHABET = "23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func num_to_string(number *big.Int, alphabet []rune, alphabet_len *big.Int, pad_to_length int) string {
var zero, digit big.Int
if number.Sign() < 0 {
*number = zero
}
capacity := max(pad_to_length, 64)
ans := make([]rune, 0, capacity)
for number.Cmp(&zero) == 1 {
number.DivMod(number, alphabet_len, &digit)
ans = append(ans, alphabet[digit.Uint64()])
}
al := len(ans)
if pad_to_length > -1 && al < pad_to_length {
ans = ans[:pad_to_length]
for i := al; i < pad_to_length; i++ {
ans[i] = alphabet[0]
}
}
return string(ans)
}
func get_padding_length(alphabet_len int) int {
bi := big.NewInt(2)
bi = bi.Exp(bi, big.NewInt(128), nil)
bb := new(big.Float).SetPrec(256)
bb.SetInt(bi)
log_al := bigfloat.Log(big.NewFloat(float64(alphabet_len)).SetPrec(256))
log_b := bigfloat.Log(bb)
res := new(big.Float).SetPrec(256)
res = res.Quo(log_b, log_al)
val, _ := res.Float64()
return int(math.Ceil(val))
}
type ShortUUID struct {
alphabet []rune
alphabet_len big.Int
pad_to_length int
}
func CreateShortUUID(alphabet string) *ShortUUID {
if alphabet == "" {
alphabet = HUMAN_ALPHABET
}
var ans = ShortUUID{
alphabet: []rune(alphabet),
}
ans.pad_to_length = get_padding_length(len(ans.alphabet))
ans.alphabet_len.SetUint64(uint64(len(ans.alphabet)))
return &ans
}
func (self *ShortUUID) Random(num_bits int64) (string, error) {
max := big.NewInt(0).Exp(big.NewInt(2), big.NewInt(num_bits), nil)
bi, err := rand.Int(rand.Reader, max)
if err != nil {
return "", err
}
return num_to_string(bi, self.alphabet, &self.alphabet_len, self.pad_to_length), nil
}
func (self *ShortUUID) Uuid4() (string, error) {
b, err := uuid.NewRandom()
if err != nil {
return "", err
}
bb, err := b.MarshalBinary()
if err != nil {
return "", err
}
var bi big.Int
bi.SetBytes(bb)
return num_to_string(&bi, self.alphabet, &self.alphabet_len, self.pad_to_length), nil
}
var HumanUUID *ShortUUID
func HumanUUID4() (string, error) {
if HumanUUID == nil {
HumanUUID = CreateShortUUID(HUMAN_ALPHABET)
}
return HumanUUID.Uuid4()
}
func HumanRandomId(num_bits int64) (string, error) {
if HumanUUID == nil {
HumanUUID = CreateShortUUID(HUMAN_ALPHABET)
}
return HumanUUID.Random(num_bits)
}
+39
View File
@@ -0,0 +1,39 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"math/big"
"testing"
)
func TestShortUUID(t *testing.T) {
a, err := HumanRandomId(128)
if err != nil {
t.Fatal(err)
}
b, err := HumanRandomId(128)
if err != nil {
t.Fatal(err)
}
if a == b {
t.Fatalf("Two short uuid4's are unexpectedly equal")
}
if HumanUUID.pad_to_length != 22 {
t.Fatalf("pad length for human UUID is %d not %d", HumanUUID.pad_to_length, 22)
}
u, err := HumanUUID.Uuid4()
if err != nil {
t.Fatal(err)
}
if len(u) != 22 {
t.Fatalf("uuid4 %s has unexpected length: %d", u, len(u))
}
bi := big.NewInt(int64(1234567890123456789))
q := num_to_string(bi, HumanUUID.alphabet, &HumanUUID.alphabet_len, HumanUUID.pad_to_length)
const expected = "bzT6LtUjw4422222222222"
if q != expected {
t.Fatalf("unexpected short human serialization: %s != %s", q, expected)
}
}
+50
View File
@@ -0,0 +1,50 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"runtime"
"strconv"
"strings"
"github.com/seancfoley/ipaddress-go/ipaddr"
)
func ParseSocketAddress(spec string) (network string, addr string, err error) {
network, addr, found := strings.Cut(spec, ":")
if !found {
err = fmt.Errorf("Invalid socket address: %s must be prefix by a protocol such as unix:", spec)
return
}
if network == "unix" {
if strings.HasPrefix(addr, "@") && runtime.GOOS != "linux" {
err = fmt.Errorf("Abstract UNIX sockets are only supported on Linux. Cannot use: %s", spec)
}
return
}
if network == "tcp" || network == "tcp6" || network == "tcp4" {
host := ipaddr.NewHostName(addr)
if host.IsAddress() {
network = "ip"
}
return
}
if network == "ip" || network == "ip6" || network == "ip4" {
host := ipaddr.NewHostName(addr)
if !host.IsAddress() {
err = fmt.Errorf("Not a valid IP address: %#v. Cannot use: %s", addr, spec)
}
return
}
if network == "fd" {
fd := -1
if fd, err = strconv.Atoi(addr); err != nil || fd < 0 {
err = fmt.Errorf("Not a valid file descriptor number: %#v. Cannot use: %s", addr, spec)
}
return
}
err = fmt.Errorf("Unknown network type: %#v in socket address: %s", network, spec)
return
}
+59
View File
@@ -0,0 +1,59 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"runtime"
"testing"
)
func TestParseSocketAddress(t *testing.T) {
en := "unix"
ea := "/tmp/test"
var eerr error = nil
test := func(spec string) {
n, a, err := ParseSocketAddress(spec)
if err != eerr {
if eerr == nil {
t.Fatalf("Parsing of %s failed with unexpected error: %s", spec, err)
}
if err == nil {
t.Fatalf("Parsing of %s did not fail, unexpectedly", spec)
}
return
}
if a != ea {
t.Fatalf("actual != expected, %s != %s, when parsing %s", a, ea, spec)
}
if n != en {
t.Fatalf("actual != expected, %s != %s, when parsing %s", n, en, spec)
}
}
testf := func(spec string, netw string, addr string) {
eerr = nil
en = netw
ea = addr
test(spec)
}
teste := func(spec string, e string) {
eerr = fmt.Errorf("%s", e)
test(spec)
}
test("unix:/tmp/test")
if runtime.GOOS == "linux" {
ea = "@test"
} else {
eerr = fmt.Errorf("bad kitty")
}
test("unix:@test")
testf("tcp:localhost:123", "tcp", "localhost:123")
testf("tcp:1.1.1.1:123", "ip", "1.1.1.1:123")
testf("tcp:fe80::1", "ip", "fe80::1")
teste("xxx", "bad kitty")
teste("xxx:yyy", "bad kitty")
teste(":yyy", "bad kitty")
}
+124
View File
@@ -0,0 +1,124 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"errors"
"fmt"
"io"
)
var _ = fmt.Print
type StreamDecompressor = func(chunk []byte, is_last bool) error
type pipe_reader struct {
pr *io.PipeReader
}
func (self *pipe_reader) Read(b []byte) (n int, err error) {
// ensure the decompressor code never gets a zero byte read with no error
for len(b) > 0 {
n, err = self.pr.Read(b)
if err != nil || n > 0 {
return
}
}
return
}
// 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()
func NewStreamDecompressor(constructor func(io.Reader) (io.ReadCloser, error), output io.Writer) StreamDecompressor {
if constructor == nil { // identity decompressor
var err error
return func(chunk []byte, is_last bool) error {
if err != nil {
return err
}
if len(chunk) > 0 {
_, err = output.Write(chunk)
}
if is_last {
if err == nil {
err = io.EOF
return nil
}
}
return err
}
}
pipe_r, pipe_w := io.Pipe()
pr := pipe_reader{pr: pipe_r}
finished := make(chan error, 1)
finished_err := errors.New("finished")
go func() {
var err error
defer func() {
finished <- err
}()
var impl io.ReadCloser
impl, err = constructor(&pr)
if err != nil {
pipe_r.CloseWithError(err)
return
}
_, err = io.Copy(output, impl)
cerr := impl.Close()
if err == nil {
err = cerr
}
if err == nil {
err = finished_err
}
pipe_r.CloseWithError(err)
}()
var iter_err error
return func(chunk []byte, is_last bool) error {
if iter_err != nil {
if iter_err == finished_err {
iter_err = io.EOF
}
return iter_err
}
if len(chunk) > 0 {
var n int
n, iter_err = pipe_w.Write(chunk)
if iter_err != nil && iter_err != finished_err {
return iter_err
}
if n < len(chunk) {
iter_err = io.ErrShortWrite
return iter_err
}
// wait for output to finish
if iter_err == nil {
// after a zero byte read, pipe_reader.Read() calls pipe_r.Read() again so
// we know it is either blocked waiting for a write to pipe_w or has finished
_, iter_err = pipe_w.Write(nil)
if iter_err != nil && iter_err != finished_err {
return iter_err
}
}
}
if is_last {
pipe_w.CloseWithError(io.EOF)
err := <-finished
if err != nil && err != io.EOF && err != finished_err {
iter_err = err
return err
}
iter_err = io.EOF
return nil
}
return nil
}
}
+57
View File
@@ -0,0 +1,57 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"bytes"
"compress/zlib"
"crypto/rand"
"fmt"
"io"
"testing"
)
var _ = fmt.Print
func TestStreamDecompressor(t *testing.T) {
input := make([]byte, 9723)
io.ReadFull(rand.Reader, input)
b := bytes.Buffer{}
w := zlib.NewWriter(&b)
io.Copy(w, bytes.NewReader(input))
w.Close()
o := bytes.Buffer{}
sd := NewStreamDecompressor(zlib.NewReader, &o)
data := b.Bytes()
for len(data) > 0 {
chunk := data[:Min(117, len(data))]
data = data[len(chunk):]
if err := sd(chunk, len(data) == 0); err != nil {
t.Fatal(err)
}
}
if !bytes.Equal(o.Bytes(), input) {
t.Fatalf("Roundtripping via zlib failed output (%d) != input (%d)", len(o.Bytes()), len(input))
}
o.Reset()
sd = NewStreamDecompressor(zlib.NewReader, &o)
err := sd([]byte("abcd"), true)
if err == nil {
t.Fatalf("Did not get an invalid header error from zlib")
}
o.Reset()
sd = NewStreamDecompressor(zlib.NewReader, &o)
err = sd(b.Bytes(), false)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(o.Bytes(), input) {
t.Fatalf("Roundtripping via zlib failed output (%d) != input (%d)", len(o.Bytes()), len(input))
}
err = sd([]byte("extra trailing data"), true)
if err == nil {
t.Fatalf("Did not get an invalid header error from zlib")
}
}
+199
View File
@@ -0,0 +1,199 @@
package streaming_base64
import (
"fmt"
"iter"
"github.com/emmansun/base64"
)
var _ = fmt.Print
type CorruptInputError = base64.CorruptInputError
type StreamingBase64Decoder struct {
leftover [4]byte
num_leftover int
total_read int64
}
func wrap_error(err error, chunkOffset int64) error {
if e, ok := err.(CorruptInputError); ok {
// CorruptInputError is an int64 representing the relative byte offset
return CorruptInputError(int64(e) + chunkOffset)
}
return err
}
// The size of output buffer needed for the provided size of input
func (s *StreamingBase64Decoder) NeededOutputLen(input_len int) int {
return ((input_len + s.num_leftover) / 4) * 3
}
// Decode provided input, iterating in chunks. Each chunk is a slice from the
// provided output buffer, which must be at least s.NeededOutputLen() in size.
func (s *StreamingBase64Decoder) Decode(input []byte, output []byte) iter.Seq2[[]byte, error] {
// Base64 decoding: 4 input bytes -> 3 output bytes.
// We check if output is large enough for this chunk + any buffered data.
maxPossibleOutput := s.NeededOutputLen(len(input))
return func(yield func([]byte, error) bool) {
if len(output) < maxPossibleOutput {
yield(nil, fmt.Errorf("output slice too small: need at least %d, got %d", maxPossibleOutput, len(output)))
return
}
currIn := input
outOffset := 0
// 1. Handle leftover bytes from previous call
if s.num_leftover > 0 {
need := 4 - s.num_leftover
if len(currIn) >= need {
copy(s.leftover[s.num_leftover:], currIn[:need])
// Decode the bridge block
n, err := base64.StdEncoding.Decode(output[outOffset:], s.leftover[:4])
if err != nil {
yield(nil, wrap_error(err, s.total_read-int64(s.num_leftover)))
return
}
if !yield(output[outOffset:outOffset+n], nil) {
return
}
outOffset += n
currIn = currIn[need:]
s.total_read += int64(need)
s.num_leftover = 0
} else {
// Still not enough to complete a block
copy(s.leftover[s.num_leftover:], currIn)
s.num_leftover += len(currIn)
s.total_read += int64(len(currIn))
return
}
}
// 2. Decode the bulk of the current chunk
processableLen := (len(currIn) / 4) * 4
if processableLen > 0 {
if n, err := base64.StdEncoding.Decode(output[outOffset:], currIn[:processableLen]); err != nil {
yield(nil, wrap_error(err, s.total_read))
return
} else if n > 0 {
if !yield(output[outOffset:outOffset+n], nil) {
return
}
}
currIn = currIn[processableLen:]
s.total_read += int64(processableLen)
}
// 3. Buffer remaining bytes (1-3) for the next Decode call
if len(currIn) > 0 {
copy(s.leftover[:], currIn)
s.num_leftover = len(currIn)
s.total_read += int64(len(currIn))
}
}
}
// Finish decoding the stream. Resets the decoder. Returned slice can be nil
// if no leftover bytes are present.
func (s *StreamingBase64Decoder) Finish() ([]byte, error) {
defer func() {
s.num_leftover = 0
s.total_read = 0
}()
switch s.num_leftover {
case 0:
return nil, nil
case 1:
return nil, CorruptInputError(s.total_read - 1)
case 2:
s.leftover[2] = '='
s.leftover[3] = '='
case 3:
s.leftover[3] = '='
}
output := [3]byte{}
n, err := base64.StdEncoding.Decode(output[:3], s.leftover[:4])
return output[:n], wrap_error(err, s.total_read-int64(s.num_leftover))
}
type StreamingBase64Encoder struct {
leftover [3]byte
num_leftover int
}
// The size of output buffer needed to encode the provided number of input bytes.
func (s *StreamingBase64Encoder) NeededOutputLen(input_len int) int {
return ((input_len + s.num_leftover) / 3) * 4
}
// Encode provided input, iterating in chunks. Each chunk is a slice from the
// provided output buffer, which must be at least s.NeededOutputLen() in size.
// The only error returned is when the output slice is too small.
func (s *StreamingBase64Encoder) Encode(input []byte, output []byte) iter.Seq2[[]byte, error] {
maxPossibleOutput := s.NeededOutputLen(len(input))
return func(yield func([]byte, error) bool) {
if len(output) < maxPossibleOutput {
yield(nil, fmt.Errorf("output slice too small: need at least %d, got %d", maxPossibleOutput, len(output)))
return
}
currIn := input
outOffset := 0
// 1. Handle leftover bytes from previous call
if s.num_leftover > 0 {
need := 3 - s.num_leftover
if len(currIn) >= need {
copy(s.leftover[s.num_leftover:], currIn[:need])
// Encode the bridge block (3 bytes -> 4 chars)
base64.RawStdEncoding.Encode(output[outOffset:], s.leftover[:3])
if !yield(output[outOffset:outOffset+4], nil) {
return
}
outOffset += 4
currIn = currIn[need:]
s.num_leftover = 0
} else {
// Still not enough to complete a group of 3
copy(s.leftover[s.num_leftover:], currIn)
s.num_leftover += len(currIn)
return
}
}
// 2. Encode the bulk of the current chunk without copying
processableLen := (len(currIn) / 3) * 3
if processableLen > 0 {
encodedLen := (processableLen / 3) * 4
base64.RawStdEncoding.Encode(output[outOffset:], currIn[:processableLen])
if !yield(output[outOffset:outOffset+encodedLen], nil) {
return
}
outOffset += encodedLen
currIn = currIn[processableLen:]
}
// 3. Buffer remaining bytes (1-2) for the next Encode call
if len(currIn) > 0 {
copy(s.leftover[:], currIn)
s.num_leftover = len(currIn)
}
}
}
// Finish encoding the stream. Resets the encoder. Returned slice can be nil
// if no leftover bytes are present.
func (s *StreamingBase64Encoder) Finish() []byte {
if s.num_leftover == 0 {
return nil
}
encodedLen := base64.RawStdEncoding.EncodedLen(s.num_leftover)
output := [4]byte{}
base64.RawStdEncoding.Encode(output[:encodedLen], s.leftover[:s.num_leftover])
s.num_leftover = 0
return output[:encodedLen]
}
+689
View File
@@ -0,0 +1,689 @@
// License: GPLv3 Copyright: 2024, Kovid Goyal, <kovid at kovidgoyal.net>
package streaming_base64
import (
"bytes"
"fmt"
"testing"
"github.com/emmansun/base64"
)
var _ = fmt.Print
// collectDecode feeds input to the decoder in chunks of chunkSize bytes and
// accumulates all decoded output into a single slice. It uses a generously-
// sized output buffer so buffer-size issues never mask correctness bugs.
func collectDecode(t *testing.T, d *StreamingBase64Decoder, encoded []byte, chunkSize int) ([]byte, error) {
t.Helper()
var result []byte
for len(encoded) > 0 {
end := min(chunkSize, len(encoded))
chunk := encoded[:end]
encoded = encoded[end:]
// Output buffer: worst-case 3 bytes per 4 input bytes, plus the
// 3 bytes for a buffered leftover block.
outBuf := make([]byte, (len(chunk)+4)*3)
for decoded, err := range d.Decode(chunk, outBuf) {
if err != nil {
return nil, err
}
result = append(result, decoded...)
}
}
return result, nil
}
// roundtrip encodes plaintext with standard base64, then decodes it through
// the streaming decoder in chunkSize pieces and verifies the result.
func roundtrip(t *testing.T, plaintext []byte, chunkSize int) {
t.Helper()
encoded := []byte(base64.StdEncoding.EncodeToString(plaintext))
var d StreamingBase64Decoder
got, err := collectDecode(t, &d, encoded, chunkSize)
if err != nil {
t.Fatalf("chunkSize=%d: unexpected decode error: %v", chunkSize, err)
}
tail, err := d.Finish()
if err != nil {
t.Fatalf("chunkSize=%d: unexpected Finish error: %v", chunkSize, err)
}
got = append(got, tail...)
if !bytes.Equal(got, plaintext) {
t.Fatalf("chunkSize=%d: roundtrip mismatch:\n want %q\n got %q", chunkSize, plaintext, got)
}
}
// roundtripNoPadding is like roundtrip but strips the trailing '=' padding
// characters from the encoded string. The Finish method must add them back.
func roundtripNoPadding(t *testing.T, plaintext []byte, chunkSize int) {
t.Helper()
encoded := []byte(base64.RawStdEncoding.EncodeToString(plaintext)) // no padding
var d StreamingBase64Decoder
got, err := collectDecode(t, &d, encoded, chunkSize)
if err != nil {
t.Fatalf("noPad chunkSize=%d: unexpected decode error: %v", chunkSize, err)
}
tail, err := d.Finish()
if err != nil {
t.Fatalf("noPad chunkSize=%d: unexpected Finish error: %v", chunkSize, err)
}
got = append(got, tail...)
if !bytes.Equal(got, plaintext) {
t.Fatalf("noPad chunkSize=%d: roundtrip mismatch:\n want %q\n got %q", chunkSize, plaintext, got)
}
}
// TestRoundtripAllChunkSizes exercises every chunk size from 1 to 7 with
// plaintexts whose lengths produce all possible num_leftover values (0-3)
// after encoding: 0 mod 3 → 0 leftover, 1 mod 3 → 2 leftover, 2 mod 3 → 1
// leftover after decoding (but 2 base64 chars left when unpadded).
func TestRoundtripAllChunkSizes(t *testing.T) {
plaintexts := [][]byte{
{}, // 0 bytes → 0 encoded → num_leftover=0
[]byte("a"), // 1 byte → 4 encoded → no leftover (padded)
[]byte("ab"), // 2 bytes → 4 encoded → no leftover (padded)
[]byte("abc"), // 3 bytes → 4 encoded → no leftover
[]byte("abcd"), // 4 bytes → 8 encoded → no leftover
[]byte("abcde"), // 5 bytes → 8 encoded → no leftover (padded)
[]byte("abcdef"), // 6 bytes → 8 encoded → no leftover (padded)
[]byte("Hello, World!"), // 13 bytes → 20 encoded
[]byte("The quick brown fox jumps over the"), // 34 bytes → 48 encoded
bytes.Repeat([]byte{0x00, 0xff, 0x80}, 17), // binary data
}
for _, plain := range plaintexts {
for chunkSize := 1; chunkSize <= 7; chunkSize++ {
if len(plain) == 0 && chunkSize > 1 {
continue // only test once for empty input
}
roundtrip(t, plain, chunkSize)
}
}
}
// TestRoundtripNoPaddingAllChunkSizes tests decoding without trailing '='
// padding bytes for all relevant chunk sizes.
func TestRoundtripNoPaddingAllChunkSizes(t *testing.T) {
plaintexts := [][]byte{
[]byte("a"), // 1 byte → "YQ" (2 base64 chars, no pad)
[]byte("ab"), // 2 bytes → "YWI" (3 base64 chars, no pad)
[]byte("abc"), // 3 bytes → "YWJj" (4 chars, no leftover)
[]byte("abcd"), // 4 bytes → "YWJjZA" (6 chars)
[]byte("Hello, World!"), // mixed
bytes.Repeat([]byte{0xde}, 10), // binary, 1 mod 3 remainder
bytes.Repeat([]byte{0xbe}, 11), // binary, 2 mod 3 remainder
bytes.Repeat([]byte{0xef}, 12), // binary, 0 mod 3 remainder
}
for _, plain := range plaintexts {
for chunkSize := 1; chunkSize <= 7; chunkSize++ {
roundtripNoPadding(t, plain, chunkSize)
}
}
}
// TestNumLeftoverInDecode checks that the bridge-block path in Decode (the
// path that fires when num_leftover > 0 at the start of a new call) produces
// correct results. We achieve specific num_leftover values by feeding exactly
// that many bytes in the first call.
func TestNumLeftoverInDecode(t *testing.T) {
// plaintext whose encoding is long enough to exercise all leftover values
plain := []byte("abcdefghijklmnopqrstuvwxyz") // 26 bytes → 36 encoded chars
for firstCallLen := 1; firstCallLen <= 3; firstCallLen++ {
encoded := []byte(base64.StdEncoding.EncodeToString(plain))
var d StreamingBase64Decoder
outBuf := make([]byte, 64)
// Feed exactly firstCallLen bytes → num_leftover = firstCallLen % 4
var got []byte
for dec, err := range d.Decode(encoded[:firstCallLen], outBuf) {
if err != nil {
t.Fatalf("firstCallLen=%d first Decode error: %v", firstCallLen, err)
}
got = append(got, dec...)
}
// Feed the rest
rest, err := collectDecode(t, &d, encoded[firstCallLen:], 4)
if err != nil {
t.Fatalf("firstCallLen=%d rest Decode error: %v", firstCallLen, err)
}
got = append(got, rest...)
tail, err := d.Finish()
if err != nil {
t.Fatalf("firstCallLen=%d Finish error: %v", firstCallLen, err)
}
got = append(got, tail...)
if !bytes.Equal(got, plain) {
t.Fatalf("firstCallLen=%d mismatch:\n want %q\n got %q", firstCallLen, plain, got)
}
}
}
// TestFinishNumLeftover directly exercises all four branches of Finish.
//
// - num_leftover=0 → (nil, nil)
// - num_leftover=1 → error pointing to correct byte offset
// - num_leftover=2 → decode 1 byte, pad "=="
// - num_leftover=3 → decode 2 bytes, pad "="
func TestFinishNumLeftover(t *testing.T) {
// num_leftover=0: empty decoder, Finish must return (nil, nil).
t.Run("leftover=0", func(t *testing.T) {
var d StreamingBase64Decoder
out, err := d.Finish()
if err != nil || out != nil {
t.Fatalf("expected (nil,nil), got (%v,%v)", out, err)
}
})
// num_leftover=0 after a complete stream: also (nil, nil).
t.Run("leftover=0_after_stream", func(t *testing.T) {
// "abc" encodes to "YWJj" — exactly 4 chars, no leftover
var d StreamingBase64Decoder
outBuf := make([]byte, 16)
for _, err := range d.Decode([]byte("YWJj"), outBuf) {
if err != nil {
t.Fatal(err)
}
}
out, err := d.Finish()
if err != nil || out != nil {
t.Fatalf("expected (nil,nil), got (%v,%v)", out, err)
}
})
// num_leftover=1 → CorruptInputError pointing to total_read - 1.
t.Run("leftover=1", func(t *testing.T) {
// Feed 5 base64 chars: 4 will be consumed, 1 leftover.
encoded := []byte(base64.StdEncoding.EncodeToString([]byte("abc"))) // "YWJj" (4)
encoded = append(encoded, 'Y') // + 1 → total 5
var d StreamingBase64Decoder
outBuf := make([]byte, 16)
for _, err := range d.Decode(encoded, outBuf) {
if err != nil {
t.Fatalf("unexpected Decode error: %v", err)
}
}
// num_leftover should now be 1; total_read = 5
_, err := d.Finish()
if err == nil {
t.Fatal("expected error for leftover=1, got nil")
}
ce, ok := err.(base64.CorruptInputError)
if !ok {
t.Fatalf("expected base64.CorruptInputError, got %T: %v", err, err)
}
// total_read=5, num_leftover=1 → offset should be 4
if int64(ce) != 4 {
t.Fatalf("wrong error offset: want 4, got %d", int64(ce))
}
})
// num_leftover=2 → Finish pads "==" and decodes 1 byte.
t.Run("leftover=2", func(t *testing.T) {
// "a" encodes to "YQ==" with padding, or "YQ" without.
// Feed "YQ" (2 chars) so num_leftover=2.
var d StreamingBase64Decoder
outBuf := make([]byte, 16)
for _, err := range d.Decode([]byte("YQ"), outBuf) {
if err != nil {
t.Fatalf("unexpected Decode error: %v", err)
}
}
out, err := d.Finish()
if err != nil {
t.Fatalf("unexpected Finish error: %v", err)
}
if !bytes.Equal(out, []byte("a")) {
t.Fatalf("want %q, got %q", "a", out)
}
})
// num_leftover=3 → Finish pads "=" and decodes 2 bytes.
t.Run("leftover=3", func(t *testing.T) {
// "ab" encodes to "YWI=" with padding, or "YWI" without.
// Feed "YWI" (3 chars) so num_leftover=3.
var d StreamingBase64Decoder
outBuf := make([]byte, 16)
for _, err := range d.Decode([]byte("YWI"), outBuf) {
if err != nil {
t.Fatalf("unexpected Decode error: %v", err)
}
}
out, err := d.Finish()
if err != nil {
t.Fatalf("unexpected Finish error: %v", err)
}
if !bytes.Equal(out, []byte("ab")) {
t.Fatalf("want %q, got %q", "ab", out)
}
})
}
// TestErrorOffsetInDecode checks that when Decode encounters an invalid byte
// the returned error is a base64.CorruptInputError with the correct absolute
// byte offset within the full stream.
func TestErrorOffsetInDecode(t *testing.T) {
tests := []struct {
name string
chunks []string // successive calls to Decode
wantOffset int64
}{
{
// Error in the very first block (no leftovers involved).
name: "error_in_first_block",
chunks: []string{"YWJj", "YW!j"},
wantOffset: 4 + 2, // 4 bytes of good data, then offset 2 within chunk
},
{
// Error in the bridge block built from leftover + new bytes.
// Feed 3 chars (leftover=3), then 1 invalid char.
// The bridge block is "YWJ!" (positions 0–3 in the stream).
// base64 reports the '!' as relative byte 3 within "YWJ!";
// wrap_error adds chunk_offset = total_read - num_leftover = 3 - 3 = 0,
// so the absolute error offset is 3.
name: "error_in_bridge_block",
chunks: []string{"YWJ", "!"},
wantOffset: 3,
},
{
// Error well into the stream after multiple complete blocks.
// "YWJj" × 3 = 12 valid chars, then invalid at position 0 of next chunk.
name: "error_after_multiple_blocks",
chunks: []string{"YWJjYWJjYWJj", "!WJj"},
wantOffset: 12,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var d StreamingBase64Decoder
var gotErr error
outBuf := make([]byte, 64)
outer:
for _, chunk := range tc.chunks {
for _, err := range d.Decode([]byte(chunk), outBuf) {
if err != nil {
gotErr = err
break outer
}
}
}
if gotErr == nil {
t.Fatal("expected a decode error, got nil")
}
ce, ok := gotErr.(base64.CorruptInputError)
if !ok {
t.Fatalf("expected base64.CorruptInputError, got %T: %v", gotErr, gotErr)
}
if int64(ce) != tc.wantOffset {
t.Fatalf("wrong error offset: want %d, got %d", tc.wantOffset, int64(ce))
}
})
}
}
// TestOutputBufferTooSmall verifies that Decode returns an error (not a panic)
// when the supplied output buffer is too small.
func TestOutputBufferTooSmall(t *testing.T) {
var d StreamingBase64Decoder
tinyBuf := make([]byte, 0) // definitely too small for any decoded output
encoded := []byte("YWJj") // decodes to 3 bytes
var gotErr error
for _, err := range d.Decode(encoded, tinyBuf) {
if err != nil {
gotErr = err
break
}
}
if gotErr == nil {
t.Fatal("expected an error for too-small output buffer, got nil")
}
}
// TestEmptyInput verifies that decoding an empty input followed by Finish
// produces no output and no error.
func TestEmptyInput(t *testing.T) {
var d StreamingBase64Decoder
outBuf := make([]byte, 16)
for _, err := range d.Decode([]byte{}, outBuf) {
if err != nil {
t.Fatalf("unexpected error on empty input: %v", err)
}
}
out, err := d.Finish()
if err != nil || out != nil {
t.Fatalf("expected (nil,nil) for empty input, got (%v,%v)", out, err)
}
}
// TestLargeInput stress-tests the decoder with a large binary payload across
// every chunk size from 1 to 13 to catch off-by-one errors in the leftover
// accumulation logic.
func TestLargeInput(t *testing.T) {
plain := make([]byte, 1000)
for i := range plain {
plain[i] = byte(i * 7)
}
for chunkSize := 1; chunkSize <= 13; chunkSize++ {
roundtrip(t, plain, chunkSize)
roundtripNoPadding(t, plain, chunkSize)
}
}
// collectEncode feeds input to the encoder in chunks of chunkSize bytes and
// accumulates all encoded output into a single slice.
func collectEncode(t *testing.T, e *StreamingBase64Encoder, plain []byte, chunkSize int) ([]byte, error) {
t.Helper()
var result []byte
for len(plain) > 0 {
end := min(chunkSize, len(plain))
chunk := plain[:end]
plain = plain[end:]
outBuf := make([]byte, e.NeededOutputLen(len(chunk))+8)
for encoded, err := range e.Encode(chunk, outBuf) {
if err != nil {
return nil, err
}
result = append(result, encoded...)
}
}
return result, nil
}
// encodeRoundtrip encodes plaintext through the streaming encoder in chunkSize
// pieces, appends the Finish output, and verifies the result matches
// base64.RawStdEncoding.
func encodeRoundtrip(t *testing.T, plaintext []byte, chunkSize int) {
t.Helper()
var e StreamingBase64Encoder
got, err := collectEncode(t, &e, plaintext, chunkSize)
if err != nil {
t.Fatalf("chunkSize=%d: unexpected Encode error: %v", chunkSize, err)
}
tail := e.Finish()
got = append(got, tail...)
want := []byte(base64.RawStdEncoding.EncodeToString(plaintext))
if !bytes.Equal(got, want) {
t.Fatalf("chunkSize=%d: encode mismatch:\n want %q\n got %q", chunkSize, want, got)
}
}
// TestEncoderRoundtripAllChunkSizes exercises every chunk size from 1 to 7 with
// plaintexts whose lengths cover all possible num_leftover values (0, 1, 2).
func TestEncoderRoundtripAllChunkSizes(t *testing.T) {
plaintexts := [][]byte{
{}, // 0 bytes → 0 leftover
[]byte("a"), // 1 byte → 1 leftover
[]byte("ab"), // 2 bytes → 2 leftover
[]byte("abc"), // 3 bytes → 0 leftover
[]byte("abcd"), // 4 bytes → 1 leftover
[]byte("abcde"), // 5 bytes → 2 leftover
[]byte("abcdef"), // 6 bytes → 0 leftover
[]byte("Hello, World!"), // 13 bytes
[]byte("The quick brown fox jumps over the"), // 34 bytes
bytes.Repeat([]byte{0x00, 0xff, 0x80}, 17), // binary data
}
for _, plain := range plaintexts {
for chunkSize := 1; chunkSize <= 7; chunkSize++ {
if len(plain) == 0 && chunkSize > 1 {
continue
}
encodeRoundtrip(t, plain, chunkSize)
}
}
}
// TestEncoderFinishLeftover directly exercises all three branches of Finish.
func TestEncoderFinishLeftover(t *testing.T) {
// num_leftover=0: empty encoder, Finish must return (nil, nil).
t.Run("leftover=0", func(t *testing.T) {
var e StreamingBase64Encoder
out := e.Finish()
if out != nil {
t.Fatalf("expected (nil,nil), got (%v)", out)
}
})
// num_leftover=0 after a complete stream: also (nil, nil).
t.Run("leftover=0_after_stream", func(t *testing.T) {
// "abc" is 3 bytes, encodes with no leftover
var e StreamingBase64Encoder
outBuf := make([]byte, 16)
for _, err := range e.Encode([]byte("abc"), outBuf) {
if err != nil {
t.Fatal(err)
}
}
out := e.Finish()
if out != nil {
t.Fatalf("expected (nil,nil), got (%v)", out)
}
})
// num_leftover=1 → Finish encodes 1 byte → 2 chars.
t.Run("leftover=1", func(t *testing.T) {
// Feed 4 bytes: 3 processed, 1 leftover
var e StreamingBase64Encoder
outBuf := make([]byte, 16)
for _, err := range e.Encode([]byte("abcd"), outBuf) {
if err != nil {
t.Fatalf("unexpected Encode error: %v", err)
}
}
tail := e.Finish()
want := []byte(base64.RawStdEncoding.EncodeToString([]byte("d")))
if !bytes.Equal(tail, want) {
t.Fatalf("want %q, got %q", want, tail)
}
})
// num_leftover=2 → Finish encodes 2 bytes → 3 chars.
t.Run("leftover=2", func(t *testing.T) {
// Feed 5 bytes: 3 processed, 2 leftover
var e StreamingBase64Encoder
outBuf := make([]byte, 16)
for _, err := range e.Encode([]byte("abcde"), outBuf) {
if err != nil {
t.Fatalf("unexpected Encode error: %v", err)
}
}
tail := e.Finish()
want := []byte(base64.RawStdEncoding.EncodeToString([]byte("de")))
if !bytes.Equal(tail, want) {
t.Fatalf("want %q, got %q", want, tail)
}
})
}
// TestEncoderOutputBufferTooSmall verifies that Encode returns an error (not a
// panic) when the supplied output buffer is too small.
func TestEncoderOutputBufferTooSmall(t *testing.T) {
var e StreamingBase64Encoder
tinyBuf := make([]byte, 0) // too small for any output
input := []byte("abc") // 3 bytes → 4 chars needed
var gotErr error
for _, err := range e.Encode(input, tinyBuf) {
if err != nil {
gotErr = err
break
}
}
if gotErr == nil {
t.Fatal("expected an error for too-small output buffer, got nil")
}
}
// TestEncoderEmptyInput verifies that encoding an empty input followed by
// Finish produces no output and no error.
func TestEncoderEmptyInput(t *testing.T) {
var e StreamingBase64Encoder
outBuf := make([]byte, 16)
for _, err := range e.Encode([]byte{}, outBuf) {
if err != nil {
t.Fatalf("unexpected error on empty input: %v", err)
}
}
out := e.Finish()
if out != nil {
t.Fatalf("expected (nil,nil) for empty input, got (%v)", out)
}
}
// TestEncoderLargeInput stress-tests the encoder with a large binary payload
// across every chunk size from 1 to 13 to catch off-by-one errors.
func TestEncoderLargeInput(t *testing.T) {
plain := make([]byte, 1000)
for i := range plain {
plain[i] = byte(i * 7)
}
for chunkSize := 1; chunkSize <= 13; chunkSize++ {
encodeRoundtrip(t, plain, chunkSize)
}
}
// TestEncoderNumLeftoverInEncode checks that the bridge-block path in Encode
// (when num_leftover > 0 at the start of a new call) produces correct results.
func TestEncoderNumLeftoverInEncode(t *testing.T) {
plain := []byte("abcdefghijklmnopqrstuvwxyz") // 26 bytes
for firstCallLen := 1; firstCallLen <= 2; firstCallLen++ {
var e StreamingBase64Encoder
outBuf := make([]byte, 64)
var got []byte
for enc, err := range e.Encode(plain[:firstCallLen], outBuf) {
if err != nil {
t.Fatalf("firstCallLen=%d first Encode error: %v", firstCallLen, err)
}
got = append(got, enc...)
}
rest, err := collectEncode(t, &e, plain[firstCallLen:], 3)
if err != nil {
t.Fatalf("firstCallLen=%d rest Encode error: %v", firstCallLen, err)
}
got = append(got, rest...)
tail := e.Finish()
got = append(got, tail...)
want := []byte(base64.RawStdEncoding.EncodeToString(plain))
if !bytes.Equal(got, want) {
t.Fatalf("firstCallLen=%d mismatch:\n want %q\n got %q", firstCallLen, want, got)
}
}
}
// TestEncoderFinishResetsState verifies that calling Finish resets the encoder
// so it can be reused for a new stream.
func TestEncoderFinishResetsState(t *testing.T) {
var e StreamingBase64Encoder
outBuf := make([]byte, 64)
plain1 := []byte("hello")
var got1 []byte
for enc, err := range e.Encode(plain1, outBuf) {
if err != nil {
t.Fatal(err)
}
got1 = append(got1, enc...)
}
tail1 := e.Finish()
got1 = append(got1, tail1...)
want1 := []byte(base64.RawStdEncoding.EncodeToString(plain1))
if !bytes.Equal(got1, want1) {
t.Fatalf("first stream: want %q, got %q", want1, got1)
}
// Reuse encoder for a second stream
plain2 := []byte("world!")
var got2 []byte
for enc, err := range e.Encode(plain2, outBuf) {
if err != nil {
t.Fatal(err)
}
got2 = append(got2, enc...)
}
tail2 := e.Finish()
got2 = append(got2, tail2...)
want2 := []byte(base64.RawStdEncoding.EncodeToString(plain2))
if !bytes.Equal(got2, want2) {
t.Fatalf("second stream: want %q, got %q", want2, got2)
}
}
// TestEncoderNeededOutputLen verifies that NeededOutputLen returns the correct
// minimum buffer size for various input lengths and leftover states.
func TestEncoderNeededOutputLen(t *testing.T) {
tests := []struct {
leftover int
inputLen int
want int
}{
{0, 0, 0},
{0, 1, 0}, // 1 byte → leftover, no output yet
{0, 2, 0}, // 2 bytes → leftover, no output yet
{0, 3, 4}, // 3 bytes → 4 chars
{0, 4, 4}, // 4 bytes → 3+1, only 3 processed → 4 chars
{0, 6, 8}, // 6 bytes → 8 chars
{1, 2, 4}, // 1+2=3 bytes → 4 chars
{1, 3, 4}, // 1+3=4, floor(4/3)*4 = 4
{2, 1, 4}, // 2+1=3 bytes → 4 chars
{2, 4, 8}, // 2+4=6, floor(6/3)*4 = 8
}
for _, tt := range tests {
e := StreamingBase64Encoder{num_leftover: tt.leftover}
got := e.NeededOutputLen(tt.inputLen)
if got != tt.want {
t.Errorf("leftover=%d inputLen=%d: NeededOutputLen=%d, want %d", tt.leftover, tt.inputLen, got, tt.want)
}
}
}
// TestEncoderDecoderRoundtrip verifies that streaming-encode then
// streaming-decode recovers the original data for a variety of inputs and
// chunk sizes.
func TestEncoderDecoderRoundtrip(t *testing.T) {
plaintexts := [][]byte{
{},
[]byte("a"),
[]byte("ab"),
[]byte("abc"),
[]byte("Hello, World!"),
bytes.Repeat([]byte{0x00, 0xfe, 0x80}, 20),
}
for _, plain := range plaintexts {
for chunkSize := 1; chunkSize <= 7; chunkSize++ {
if len(plain) == 0 && chunkSize > 1 {
continue
}
// Encode
var e StreamingBase64Encoder
encoded, err := collectEncode(t, &e, plain, chunkSize)
if err != nil {
t.Fatalf("Encode error: %v", err)
}
tail := e.Finish()
encoded = append(encoded, tail...)
// Decode using RawStdEncoding (no padding)
var d StreamingBase64Decoder
decoded, err := collectDecode(t, &d, encoded, chunkSize)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
dtail, err := d.Finish()
if err != nil {
t.Fatalf("Decode Finish error: %v", err)
}
decoded = append(decoded, dtail...)
if !bytes.Equal(decoded, plain) {
t.Fatalf("chunkSize=%d roundtrip mismatch:\n want %q\n got %q", chunkSize, plain, decoded)
}
}
}
}
+171
View File
@@ -0,0 +1,171 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"strings"
"unicode/utf8"
)
var _ = fmt.Print
func Capitalize(x string) string {
if x == "" {
return x
}
s, sz := utf8.DecodeRuneInString(x)
cr := strings.ToUpper(string(s))
return cr + x[sz:]
}
type ScanLines struct {
entries []string
scanner *StringScanner
}
func NewScanLines(entries ...string) *ScanLines {
return &ScanLines{entries: entries}
}
func (self *ScanLines) Scan() bool {
if self.scanner == nil {
if len(self.entries) == 0 {
return false
}
self.scanner = NewLineScanner(self.entries[0])
self.entries = self.entries[1:]
return self.Scan()
} else {
if self.scanner.Scan() {
return true
}
self.scanner = nil
return self.Scan()
}
}
func (self *ScanLines) Text() string {
if self.scanner == nil {
return ""
}
return self.scanner.Text()
}
type StringScannerScanFunc = func(data string) (remaining_data, token string)
type StringScannerPostprocessFunc = func(token string) string
func ScanFuncForSeparator(sep string) StringScannerScanFunc {
if len(sep) == 1 {
sb := sep[0]
return func(data string) (remaining_data, token string) {
idx := strings.IndexByte(data, sb)
if idx < 0 {
return "", data
}
return data[idx+len(sep):], data[:idx]
}
}
return func(data string) (remaining_data, token string) {
before, after, ok := strings.Cut(data, sep)
if !ok {
return "", data
}
return after, before
}
}
// Faster, better designed, zero-allocation version of bufio.Scanner for strings
type StringScanner struct {
ScanFunc StringScannerScanFunc
PostProcessTokenFunc StringScannerPostprocessFunc
data string
token string
}
func (self *StringScanner) Scan() bool {
if self.data == "" {
self.token = ""
return false
}
self.data, self.token = self.ScanFunc(self.data)
if self.PostProcessTokenFunc != nil {
self.token = self.PostProcessTokenFunc(self.token)
}
return true
}
func (self *StringScanner) Err() error { return nil }
func (self *StringScanner) Text() string {
return self.token
}
func (self *StringScanner) Split(data string, expected_number ...int) (ans []string) {
if len(expected_number) != 0 {
ans = make([]string, 0, expected_number[0])
} else {
ans = []string{}
}
self.data = data
for self.Scan() {
ans = append(ans, self.Text())
}
return
}
func NewLineScanner(text string) *StringScanner {
return &StringScanner{
data: text, ScanFunc: ScanFuncForSeparator("\n"),
PostProcessTokenFunc: func(s string) string {
if len(s) > 0 && s[len(s)-1] == '\r' {
s = s[:len(s)-1]
}
return s
},
}
}
func NewSeparatorScanner(text, separator string) *StringScanner {
return &StringScanner{
data: text, ScanFunc: ScanFuncForSeparator(separator),
}
}
func Splitlines(x string, expected_number_of_lines ...int) (ans []string) {
return NewLineScanner("").Split(x, expected_number_of_lines...)
}
// 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 RuneOffsetsToByteOffsets(text string) func(int) int {
self := struct {
char_offset, byte_offset, last int
bytes []byte
}{bytes: UnsafeStringToBytes(text)}
return func(x int) (sz int) {
switch {
case x == self.last:
return self.byte_offset
case x < self.last:
return -1
}
self.last = x
x -= self.char_offset
for x > 0 {
_, d := utf8.DecodeRune(self.bytes)
sz += d
self.bytes = self.bytes[d:]
x--
self.char_offset++
}
self.byte_offset += sz
return self.byte_offset
}
}
func Repr(x any) string { return fmt.Sprintf("%#v", x) }
+50
View File
@@ -0,0 +1,50 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"bufio"
"fmt"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
func TestStringScanner(t *testing.T) {
for _, text := range []string{
"a\nb\nc",
"a\nb\nc\r",
"a\n\n\nb\nc",
"a\r\r\nb\r\nc\n",
"\n1",
"",
"\n",
} {
actual := Splitlines(text)
expected := make([]string, 0, len(actual))
s := bufio.NewScanner(strings.NewReader(text))
for s.Scan() {
expected = append(expected, s.Text())
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("Failed for: %#v\n%s", text, diff)
}
}
}
func TestReplaceControlCodes(t *testing.T) {
for text, expected := range map[string]string{
"none": "none",
"a\r\x01b\x03\x7f c\n\td": "a\u240d\u2401b\u2403\u2421 cX d",
"\x01": "\u2401",
"\x00\x0b": "\u2400\u240b",
} {
actual := ReplaceControlCodes(text, " ", "X")
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("Failed for text: %#v\n%s", text, diff)
}
}
}
+51
View File
@@ -0,0 +1,51 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package style
import (
"fmt"
"strings"
)
type Context struct {
AllowEscapeCodes bool
}
func (self *Context) SprintFunc(spec string) func(args ...any) string {
p := prefix_for_spec(spec)
s := suffix_for_spec(spec)
return func(args ...any) string {
body := fmt.Sprint(args...)
if !self.AllowEscapeCodes {
return body
}
b := strings.Builder{}
b.Grow(len(p) + len(body) + len(s))
b.WriteString(p)
b.WriteString(body)
b.WriteString(s)
return b.String()
}
}
func (self *Context) UrlFunc(spec string) func(string, string) string {
p := prefix_for_spec(spec)
s := suffix_for_spec(spec)
return func(url, text string) string {
if !self.AllowEscapeCodes {
return text
}
uc := url_code{url: url}
up, us := uc.prefix(), uc.suffix()
b := strings.Builder{}
b.Grow(len(p) + len(up) + len(text) + len(s) + len(us))
b.WriteString(p)
b.WriteString(up)
b.WriteString(text)
b.WriteString(us)
b.WriteString(s)
return b.String()
}
}
+342
View File
@@ -0,0 +1,342 @@
// License: GPLv3 Copyright: 2025, Kovid Goyal, <kovid at kovidgoyal.net>
package style
import (
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
var _ = fmt.Println
// Color space conversion functions for wide gamut color support
// Implements OKLCH, Display P3, and CIE LAB color formats with
// CSS Color Module Level 4 gamut mapping.
// srgbToLinear converts sRGB component (0-1) to linear light
func srgbToLinear(c float64) float64 {
if c <= 0.04045 {
return c / 12.92
}
return math.Pow((c+0.055)/1.055, 2.4)
}
// linearToSrgb converts linear light component (0-1) to sRGB
func linearToSrgb(c float64) float64 {
if c <= 0.0031308 {
return c * 12.92
}
return 1.055*math.Pow(c, 1.0/2.4) - 0.055
}
// oklabToLinearSrgb converts OKLab to linear sRGB
func oklabToLinearSrgb(l, a, b float64) (float64, float64, float64) {
l_ := l + 0.3963377774*a + 0.2158037573*b
m_ := l - 0.1055613458*a - 0.0638541728*b
s_ := l - 0.0894841775*a - 1.2914855480*b
l_cubed := l_ * l_ * l_
m_cubed := m_ * m_ * m_
s_cubed := s_ * s_ * s_
r := +4.0767416621*l_cubed - 3.3077115913*m_cubed + 0.2309699292*s_cubed
g := -1.2684380046*l_cubed + 2.6097574011*m_cubed - 0.3413193965*s_cubed
b_val := -0.0041960863*l_cubed - 0.7034186147*m_cubed + 1.7076147010*s_cubed
return r, g, b_val
}
// oklchToSrgb converts OKLCH to sRGB (without gamut mapping)
func oklchToSrgb(l, c, h float64) (float64, float64, float64) {
// Convert OKLCH to OKLab
hRad := h * math.Pi / 180.0
a := c * math.Cos(hRad)
b := c * math.Sin(hRad)
// Convert OKLab to linear sRGB
rLin, gLin, bLin := oklabToLinearSrgb(l, a, b)
// Apply sRGB transfer function
r := linearToSrgb(rLin)
g := linearToSrgb(gLin)
bVal := linearToSrgb(bLin)
return r, g, bVal
}
// srgbToOklab converts sRGB to OKLab (for deltaE calculations)
func srgbToOklab(r, g, b float64) (float64, float64, float64) {
rLin := srgbToLinear(r)
gLin := srgbToLinear(g)
bLin := srgbToLinear(b)
l_ := 0.4122214708*rLin + 0.5363325363*gLin + 0.0514459929*bLin
m_ := 0.2119034982*rLin + 0.6806995451*gLin + 0.1073969566*bLin
s_ := 0.0883024619*rLin + 0.2817188376*gLin + 0.6299787005*bLin
l_ = math.Cbrt(l_)
m_ = math.Cbrt(m_)
s_ = math.Cbrt(s_)
l := 0.2104542553*l_ + 0.7936177850*m_ - 0.0040720468*s_
a := 1.9779984951*l_ - 2.4285922050*m_ + 0.4505937099*s_
bVal := 0.0259040371*l_ + 0.7827717662*m_ - 0.8086757660*s_
return l, a, bVal
}
// deltaEOk calculates perceptual color difference in OKLab space
func deltaEOk(lab1, lab2 [3]float64) float64 {
dl := lab1[0] - lab2[0]
da := lab1[1] - lab2[1]
db := lab1[2] - lab2[2]
return math.Sqrt(dl*dl + da*da + db*db)
}
// oklchToSrgbGamutMap converts OKLCH to sRGB with CSS Color Module Level 4 gamut mapping
func oklchToSrgbGamutMap(l, c, h float64) (float64, float64, float64) {
// Constants from CSS Color Module Level 4
const jnd = 0.02 // Just Noticeable Difference threshold
const minConvergence = 0.0001 // Binary search precision
const epsilon = 0.00001 // Small value for floating point comparisons
// Edge cases: pure black or white
if l <= 0.0 {
return 0.0, 0.0, 0.0
}
if l >= 1.0 {
return 1.0, 1.0, 1.0
}
// If chroma is very small, color is achromatic
if c < epsilon {
gray := linearToSrgb(l)
return gray, gray, gray
}
// Try the original color first
r, g, b := oklchToSrgb(l, c, h)
// Check if already in gamut
if r >= 0.0 && r <= 1.0 && g >= 0.0 && g <= 1.0 && b >= 0.0 && b <= 1.0 {
return r, g, b
}
// Binary search for maximum in-gamut chroma
lowChroma := 0.0
highChroma := c
for (highChroma - lowChroma) > minConvergence {
midChroma := (highChroma + lowChroma) * 0.5
// Try this chroma value
rTest, gTest, bTest := oklchToSrgb(l, midChroma, h)
// Check if in gamut (before clipping)
inGamut := rTest >= 0.0 && rTest <= 1.0 &&
gTest >= 0.0 && gTest <= 1.0 &&
bTest >= 0.0 && bTest <= 1.0
if inGamut {
// In gamut - try higher chroma
lowChroma = midChroma
} else {
// Out of gamut - clip and check deltaE
rClipped := math.Max(0.0, math.Min(1.0, rTest))
gClipped := math.Max(0.0, math.Min(1.0, gTest))
bClipped := math.Max(0.0, math.Min(1.0, bTest))
// Convert both to OKLab for comparison
lTest, aTest, bTestLab := srgbToOklab(rTest, gTest, bTest)
testLab := [3]float64{lTest, aTest, bTestLab}
lClip, aClip, bClip := srgbToOklab(rClipped, gClipped, bClipped)
clippedLab := [3]float64{lClip, aClip, bClip}
// Calculate perceptual difference
de := deltaEOk(testLab, clippedLab)
if de < jnd {
// Difference is imperceptible - accept this chroma
lowChroma = midChroma
} else {
// Difference is noticeable - reduce chroma more
highChroma = midChroma
}
}
}
// Use the final chroma value and clip to ensure in-gamut
rFinal, gFinal, bFinal := oklchToSrgb(l, lowChroma, h)
return math.Max(0.0, math.Min(1.0, rFinal)),
math.Max(0.0, math.Min(1.0, gFinal)),
math.Max(0.0, math.Min(1.0, bFinal))
}
// labToOklch converts CIE LAB to OKLCH for gamut mapping
func labToOklch(l, a, b float64) (float64, float64, float64) {
// LAB to XYZ (using D65 illuminant)
y := (l + 16) / 116
x := a/500 + y
z := y - b/200
fInv := func(t float64) float64 {
delta := 6.0 / 29.0
if t > delta {
return t * t * t
}
return 3 * delta * delta * (t - 4.0/29.0)
}
// D65 white point
const xN = 0.95047
const yN = 1.00000
const zN = 1.08883
xVal := xN * fInv(x)
yVal := yN * fInv(y)
zVal := zN * fInv(z)
// XYZ to linear sRGB
rLin := +3.2404542*xVal - 1.5371385*yVal - 0.4985314*zVal
gLin := -0.9692660*xVal + 1.8760108*yVal + 0.0415560*zVal
bLin := +0.0556434*xVal - 0.2040259*yVal + 1.0572252*zVal
// Convert to OKLab
l_ := 0.4122214708*rLin + 0.5363325363*gLin + 0.0514459929*bLin
m_ := 0.2119034982*rLin + 0.6806995451*gLin + 0.1073969566*bLin
s_ := 0.0883024619*rLin + 0.2817188376*gLin + 0.6299787005*bLin
l_ = math.Cbrt(l_)
m_ = math.Cbrt(m_)
s_ = math.Cbrt(s_)
lOk := 0.2104542553*l_ + 0.7936177850*m_ - 0.0040720468*s_
aOk := 1.9779984951*l_ - 2.4285922050*m_ + 0.4505937099*s_
bOk := 0.0259040371*l_ + 0.7827717662*m_ - 0.8086757660*s_
// Convert OKLab to OKLCH
c := math.Sqrt(aOk*aOk + bOk*bOk)
h := math.Atan2(bOk, aOk) * 180.0 / math.Pi
if h < 0 {
h += 360
}
return lOk, c, h
}
// parseOklch parses OKLCH color: oklch(l c h) or oklch(l, c, h)
func parseOklch(spec string) (RGBA, error) {
spec = strings.TrimRight(spec, ")")
parts := splitColorComponents(spec)
if len(parts) != 3 {
return RGBA{}, errors.New("not enough parts")
}
l, err := parseFloatValue(parts[0])
if err != nil {
return RGBA{}, err
}
c, err := parseFloatValue(parts[1])
if err != nil {
return RGBA{}, err
}
h, err := parseFloatValue(parts[2])
if err != nil {
return RGBA{}, err
}
// Validate for NaN and infinity
if math.IsNaN(l) || math.IsInf(l, 0) ||
math.IsNaN(c) || math.IsInf(c, 0) ||
math.IsNaN(h) || math.IsInf(h, 0) {
return RGBA{}, errors.New("invalid float value")
}
// Handle percentages for L
if strings.Contains(parts[0], "%") {
l /= 100.0
}
// Clamp to reasonable ranges
l = max(0.0, min(l, 1.0))
c = max(0.0, c) // Chroma is unbounded
h = math.Mod(h, 360) // Wrap hue to 0-360
if h < 0 {
h += 360
}
// Convert OKLCH to sRGB with gamut mapping
r, g, b := oklchToSrgbGamutMap(l, c, h)
return RGBA{as8bit(r), as8bit(g), as8bit(b), 0}, nil
}
func as8bit(x float64) uint8 { return uint8(math.Round(x * 255)) }
// parseLab parses LAB color: lab(l a b) or lab(l, a, b)
func parseLab(spec string) (RGBA, error) {
spec = strings.TrimRight(spec, ")")
parts := splitColorComponents(spec)
if len(parts) != 3 {
return RGBA{}, errors.New("not enough parts")
}
l, err := parseFloatValue(parts[0])
if err != nil {
return RGBA{}, err
}
a, err := parseFloatValue(parts[1])
if err != nil {
return RGBA{}, err
}
b, err := parseFloatValue(parts[2])
if err != nil {
return RGBA{}, err
}
// Validate for NaN and infinity
if math.IsNaN(l) || math.IsInf(l, 0) ||
math.IsNaN(a) || math.IsInf(a, 0) ||
math.IsNaN(b) || math.IsInf(b, 0) {
return RGBA{}, errors.New("invalid float value")
}
// Clamp L to 0-100
l = max(0.0, min(l, 100.0))
// Convert LAB to OKLCH, then use gamut mapping to sRGB
lOk, c, h := labToOklch(l, a, b)
// Apply gamut mapping in OKLCH space
r, g, bVal := oklchToSrgbGamutMap(lOk, c, h)
return RGBA{as8bit(r), as8bit(g), as8bit(bVal), 0}, nil
}
// splitColorComponents splits color components by comma or whitespace
func splitColorComponents(spec string) []string {
re := regexp.MustCompile(`[,\s]+`)
parts := re.Split(spec, -1)
var result []string
for _, part := range parts {
part = strings.TrimSpace(part)
part = strings.TrimRight(part, "%,")
if part != "" {
result = append(result, part)
}
}
return result
}
// parseFloatValue parses a float value, handling percentages
func parseFloatValue(s string) (float64, error) {
s = strings.TrimSpace(s)
s = strings.TrimRight(s, "%,")
return strconv.ParseFloat(s, 64)
}
@@ -0,0 +1,79 @@
// License: GPLv3 Copyright: 2025, Kovid Goyal, <kovid at kovidgoyal.net>
package style
import (
"testing"
)
// Benchmark color parsing functions to demonstrate performance
func BenchmarkParseOklch(b *testing.B) {
for b.Loop() {
_, _ = parseOklch("0.5 0.1 180")
}
}
func BenchmarkParseLab(b *testing.B) {
for b.Loop() {
_, _ = parseLab("50 0 0")
}
}
func BenchmarkParseColorHex(b *testing.B) {
for b.Loop() {
_, _ = ParseColor("#ff0000")
}
}
func BenchmarkParseColorOklch(b *testing.B) {
for b.Loop() {
_, _ = ParseColor("oklch(0.5 0.1 180)")
}
}
func BenchmarkParseColorLab(b *testing.B) {
for b.Loop() {
_, _ = ParseColor("lab(50 0 0)")
}
}
func BenchmarkParseColorWithComment(b *testing.B) {
for b.Loop() {
_, _ = ParseColor("oklch(0.5 0.1 180) # vibrant color")
}
}
// Benchmark the gamut mapping algorithm specifically
func BenchmarkOklchToSrgbGamutMap(b *testing.B) {
for b.Loop() {
oklchToSrgbGamutMap(0.7, 0.4, 25) // Very saturated color requiring gamut mapping
}
}
func BenchmarkOklchToSrgbGamutMapInGamut(b *testing.B) {
for b.Loop() {
oklchToSrgbGamutMap(0.5, 0.05, 180) // Already in gamut
}
}
// Benchmark parsing many colors (simulating config file parsing)
func BenchmarkParseManyColors(b *testing.B) {
colors := []string{
"#ff0000",
"#00ff00",
"#0000ff",
"oklch(0.5 0.1 180)",
"lab(50 20 -30)",
"rgb:ff/00/00",
"red",
"blue",
"green",
}
for b.Loop() {
for _, color := range colors {
_, _ = ParseColor(color)
}
}
}
+43
View File
@@ -0,0 +1,43 @@
// License: GPLv3 Copyright: 2025, Kovid Goyal, <kovid at kovidgoyal.net>
package style
import (
"testing"
)
func TestParseColor(t *testing.T) {
type tr struct {
input string
expected RGBA
}
c := func(t string, r, g, b uint8) tr { return tr{t, RGBA{r, g, b, 0}} }
tests := []tr{
c(`#eee # comment`, 0xee, 0xee, 0xee),
c(`#234567`, 0x23, 0x45, 0x67),
c(`#abcabcdef`, 0xab, 0xab, 0xde),
c(`rgb:e/e/e # comment`, 0xee, 0xee, 0xee),
c(`rgb:23/45/67`, 0x23, 0x45, 0x67),
c(`rgb:abc/abc/def`, 0xab, 0xab, 0xde),
c(`red`, 0xff, 0, 0),
c(`alice blue # comment`, 240, 248, 255),
c(`oklch(1,0,0)`, 255, 255, 255),
c(`oklch(0,0,0)`, 0, 0, 0),
c(`oklch(0.5,0.1,180)`, 0, 117, 101),
c(`oklch(0.7 0.15 140) # comment`, 0x68, 0xb4, 0x57),
c(`oklch(0.9 0.05 265)`, 0xce, 0xde, 0xff),
c(`lab(70 50 -30)`, 0xea, 0x88, 0xe2),
c(`lab(50,0,0)`, 199, 199, 199),
c(`lab(100,0,0)`, 255, 255, 255),
c(`lab(0,0,0)`, 0, 0, 0),
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
actual, err := ParseColor(tt.input)
if actual != tt.expected {
t.Errorf("ParseColor(%#v) error = %v, got %v wanted %v", tt.input, err, actual, tt.expected)
}
})
}
}
+534
View File
@@ -0,0 +1,534 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package style
import (
"fmt"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
type sgr_color struct {
number int
color RGBA
}
func (self sgr_color) as_sgr(base int) string {
if self.number == 0 {
return ""
}
if self.number > 0 {
n := self.number - 1
if n <= 15 && (base == 30 || base == 40) {
if n <= 7 {
return strconv.Itoa(base + n)
}
return strconv.Itoa(base + 60 + n - 7)
}
return fmt.Sprintf("%d:5:%d", base+8, n)
}
return fmt.Sprintf("%d:2:%d:%d:%d", base+8, self.color.Red, self.color.Green, self.color.Blue)
}
func as_uint8(x int) uint8 {
return uint8(uint(x) & 0xff)
}
func (self *sgr_color) from_extended(nums []int) bool {
switch nums[0] {
case 5:
if len(nums) > 1 {
self.number = 1 + nums[1]
return true
}
case 2:
if len(nums) > 3 {
self.number = -1
self.color.Red = as_uint8(nums[1])
self.color.Green = as_uint8(nums[2])
self.color.Blue = as_uint8(nums[3])
return true
}
}
return false
}
type sgr_state struct {
italic, reverse, bold, dim, strikethrough bool
underline_style underline_style
fg, bg, uc sgr_color
}
func (self *sgr_state) reset() {
*self = sgr_state{}
}
func (self sgr_state) as_sgr(for_close bool) string {
ans := make([]byte, 0, 32)
if for_close {
if self.bold {
ans = append(ans, "221;"...)
}
if self.dim {
ans = append(ans, "222;"...)
}
if self.italic {
ans = append(ans, "23;"...)
}
if self.reverse {
ans = append(ans, "27;"...)
}
if self.strikethrough {
ans = append(ans, "29;"...)
}
if self.underline_style != no_underline && self.underline_style != nil_underline {
ans = append(ans, "4:0;"...)
}
if self.fg.number != 0 {
ans = append(ans, "39;"...)
}
if self.bg.number != 0 {
ans = append(ans, "49;"...)
}
if self.uc.number != 0 {
ans = append(ans, "59;"...)
}
} else {
if self.bold {
ans = append(ans, "1;"...)
}
if self.dim {
ans = append(ans, "2;"...)
}
if self.italic {
ans = append(ans, "3;"...)
}
if self.reverse {
ans = append(ans, "7;"...)
}
if self.strikethrough {
ans = append(ans, "9;"...)
}
if self.underline_style != no_underline && self.underline_style != nil_underline {
ans = append(ans, fmt.Sprintf("4:%d;", self.underline_style)...)
}
if q := self.fg.as_sgr(30); q != "" {
ans = append(ans, q...)
ans = append(ans, ';')
}
if q := self.bg.as_sgr(40); q != "" {
ans = append(ans, q...)
ans = append(ans, ';')
}
if q := self.uc.as_sgr(50); q != "" {
ans = append(ans, q...)
ans = append(ans, ';')
}
}
if len(ans) > 0 {
ans = ans[:len(ans)-1]
}
return utils.UnsafeBytesToString(ans)
}
func (self sgr_state) as_escape_codes(for_close bool) string {
q := self.as_sgr(for_close)
if q == "" {
return q
}
return fmt.Sprintf("\x1b[%sm", q)
}
func (self *sgr_state) apply_csi(raw string) {
if !strings.HasSuffix(raw, "m") {
return
}
raw = raw[:len(raw)-1]
if raw == "" {
raw = "0"
}
parts := strings.Split(raw, ";")
nums := make([]int, 0, 8)
for _, part := range parts {
subparts := strings.Split(part, ":")
nums = nums[:0]
for _, b := range subparts {
q, err := strconv.Atoi(b)
if err == nil {
nums = append(nums, q)
}
}
if len(nums) == 0 {
continue
}
switch nums[0] {
case 0:
self.reset()
case 1:
self.dim, self.bold = false, true
case 221:
self.bold = false
case 2:
self.dim, self.bold = true, false
case 222:
self.dim = false
case 22:
self.dim, self.bold = false, false
case 3:
self.italic = true
case 23:
self.italic = false
case 7:
self.reverse = true
case 27:
self.reverse = false
case 9:
self.strikethrough = true
case 29:
self.strikethrough = false
case 24:
self.underline_style = no_underline
case 4:
us := 1
if len(nums) > 1 {
us = nums[1]
}
switch us {
case 0:
self.underline_style = no_underline
case 1:
self.underline_style = straight_underline
case 2:
self.underline_style = double_underline
case 3:
self.underline_style = curly_underline
case 4:
self.underline_style = dotted_underline
case 5:
self.underline_style = dashed_underline
}
case 30, 31, 32, 33, 34, 35, 36, 37:
self.fg.number = nums[0] + 1 - 30
case 90, 91, 92, 93, 94, 95, 96, 97:
self.fg.number = nums[0] + 1 - 82
case 38:
self.fg.from_extended(nums[1:])
case 39:
self.fg.number = 0
case 40, 41, 42, 43, 44, 45, 46, 47:
self.bg.number = nums[0] + 1 - 40
case 100, 101, 102, 103, 104, 105, 106, 107:
self.bg.number = nums[0] + 1 - 92
case 48:
self.bg.from_extended(nums[1:])
case 49:
self.bg.number = 0
case 58:
self.uc.from_extended(nums[1:])
case 59:
self.uc.number = 0
}
}
}
type hyperlink_state struct {
id, url string
}
func (self *hyperlink_state) apply_osc(raw string) {
parts := strings.SplitN(raw, ";", 3)
if len(parts) != 3 || parts[0] != "8" {
return
}
self.id = parts[1]
self.url = parts[2]
}
func (self *hyperlink_state) reset() {
self.id = ""
self.url = ""
}
func (self hyperlink_state) as_escape_codes(for_close bool) string {
if self.id == "" && self.url == "" {
return ""
}
if for_close {
return "\x1b]8;;\x1b\\"
}
return fmt.Sprintf("\x1b]8;%s;%s\x1b\\", self.id, self.url)
}
type line_builder struct {
buf []byte
cursor_pos int
seen_non_space_chars bool
pos_of_trailing_whitespace int
}
func (self *line_builder) reset(trim_whitespace bool) string {
ans := string(self.buf)
if trim_whitespace && self.pos_of_trailing_whitespace > -1 {
prefix := ans[:self.pos_of_trailing_whitespace]
tp := strings.TrimRightFunc(prefix, is_space)
if len(tp) != len(prefix) {
ans = tp + ans[self.pos_of_trailing_whitespace:]
}
}
self.buf = self.buf[:0]
self.cursor_pos = 0
self.seen_non_space_chars = false
self.pos_of_trailing_whitespace = -1
return ans
}
func (self *line_builder) has_space_for_width(w, max_width int) bool {
return w+self.cursor_pos <= max_width
}
func (self *line_builder) add_space(ch rune, trim_whitespace bool) {
if !trim_whitespace || self.seen_non_space_chars {
self.buf = utf8.AppendRune(self.buf, ch)
self.pos_of_trailing_whitespace = len(self.buf)
self.cursor_pos += wcswidth.Runewidth(ch)
}
}
func (self *line_builder) add_word(word []byte, width int) {
self.seen_non_space_chars = true
self.pos_of_trailing_whitespace = -1
self.buf = append(self.buf, word...)
self.cursor_pos += width
}
func (self *line_builder) add_indent(word string, width int) {
if word != "" {
self.buf = append(self.buf, word...)
self.cursor_pos += width
}
}
func (self *line_builder) add_escape_code(code string) {
self.buf = append(self.buf, code...)
}
func (self *line_builder) add_escape_code2(prefix string, body []byte, suffix string) {
self.buf = append(self.buf, prefix...)
self.buf = append(self.buf, body...)
self.buf = append(self.buf, suffix...)
}
type escape_code_ struct {
prefix, body, suffix string
}
type word_builder struct {
buf []byte
escape_codes []escape_code_
text_start_position int
wcswidth *wcswidth.WCWidthIterator
}
func (self *word_builder) reset(copy_current_word func([]byte)) {
copy_current_word(self.buf)
self.buf = self.buf[:0]
self.escape_codes = self.escape_codes[:0]
self.text_start_position = 0
self.wcswidth.Reset()
}
func (self *word_builder) is_empty() bool {
return len(self.buf) == 0
}
func (self *word_builder) width() int {
return self.wcswidth.CurrentWidth()
}
func (self *word_builder) add_escape_code(prefix string, body []byte, suffix string) {
e := escape_code_{prefix: prefix, body: string(body), suffix: suffix}
self.escape_codes = append(self.escape_codes, e)
self.buf = append(self.buf, prefix...)
self.buf = append(self.buf, body...)
self.buf = append(self.buf, suffix...)
}
func (self *word_builder) has_text() bool { return self.text_start_position != 0 }
func (self *word_builder) recalculate_width() {
self.wcswidth.Reset()
self.wcswidth.Parse(self.buf)
}
func (self *word_builder) add_rune(ch rune) (num_bytes_written int) {
before := len(self.buf)
self.buf = utf8.AppendRune(self.buf, ch)
num_bytes_written = len(self.buf) - before
for _, b := range self.buf[before:] {
self.wcswidth.ParseByte(b)
}
if self.text_start_position == 0 {
self.text_start_position = len(self.buf)
}
return
}
func (self *word_builder) remove_trailing_bytes(n int) {
self.buf = self.buf[:len(self.buf)-n]
self.recalculate_width()
}
type wrapper struct {
ep wcswidth.EscapeCodeParser
indent string
width, indent_width int
trim_whitespace bool
sgr sgr_state
hyperlink hyperlink_state
current_word word_builder
current_line line_builder
lines []string
ignore_lines_containing []string
}
func (self *wrapper) newline_prefix() {
self.current_line.add_escape_code(self.sgr.as_escape_codes(true))
self.current_line.add_escape_code(self.hyperlink.as_escape_codes(true))
self.current_line.add_indent(self.indent, self.indent_width)
self.current_line.add_escape_code(self.sgr.as_escape_codes(false))
self.current_line.add_escape_code(self.hyperlink.as_escape_codes(false))
}
func (self *wrapper) append_line(line string) {
for _, q := range self.ignore_lines_containing {
if strings.Contains(line, q) {
return
}
}
self.lines = append(self.lines, line)
}
func (self *wrapper) end_current_line() {
line := self.current_line.reset(self.trim_whitespace)
if strings.HasSuffix(line, self.indent) && wcswidth.Stringwidth(line) == self.indent_width {
line = line[:len(line)-len(self.indent)]
}
self.append_line(line)
self.newline_prefix()
}
func (self *wrapper) print_word() {
w := self.current_word.width()
if !self.current_line.has_space_for_width(w, self.width) {
self.end_current_line()
w = self.current_word.width()
}
for _, e := range self.current_word.escape_codes {
if e.suffix != "" {
self.hyperlink.apply_osc(e.body)
} else {
self.sgr.apply_csi(e.body)
}
}
self.current_word.reset(func(word []byte) {
self.current_line.add_word(word, w)
})
}
func is_space(ch rune) bool {
return ch != 0xa0 && unicode.IsSpace(ch)
}
func (self *wrapper) handle_rune(ch rune) error {
if ch == '\n' {
self.print_word()
self.end_current_line()
} else if is_space(ch) {
if self.current_word.has_text() {
self.print_word()
}
if self.current_line.cursor_pos >= self.width {
self.end_current_line()
}
self.current_line.add_space(ch, self.trim_whitespace)
} else {
num_of_bytes_written := self.current_word.add_rune(ch)
if self.current_word.width() > self.width {
self.current_word.remove_trailing_bytes(num_of_bytes_written)
self.print_word()
return self.handle_rune(ch)
}
}
return nil
}
func (self *wrapper) handle_csi(raw []byte) error {
self.current_word.add_escape_code("\x1b[", raw, "")
return nil
}
func (self *wrapper) handle_osc(raw []byte) error {
self.current_word.add_escape_code("\x1b]", raw, "\x1b\\")
return nil
}
func (self *wrapper) wrap_text(text string) []string {
if text == "" {
return []string{""}
}
self.current_line.reset(self.trim_whitespace)
self.current_word.reset(func([]byte) {})
self.lines = self.lines[:0]
self.current_line.add_indent(self.indent, self.indent_width)
self.ep.ParseString(text)
if !self.current_word.is_empty() {
self.print_word()
}
self.end_current_line()
last_line := self.current_line.reset(self.trim_whitespace)
self.newline_prefix()
if last_line == self.current_line.reset(self.trim_whitespace) {
last_line = ""
}
if last_line != "" {
self.append_line(last_line)
}
return self.lines
}
func new_wrapper(opts WrapOptions, width int) *wrapper {
width = max(2, width)
ans := wrapper{indent: opts.Indent, width: width, trim_whitespace: opts.Trim_whitespace, indent_width: wcswidth.Stringwidth(opts.Indent)}
if opts.Ignore_lines_containing != "" {
ans.ignore_lines_containing = utils.Splitlines(opts.Ignore_lines_containing)
}
ans.ep.HandleRune = ans.handle_rune
ans.ep.HandleCSI = ans.handle_csi
ans.ep.HandleOSC = ans.handle_osc
ans.lines = make([]string, 0, 32)
ans.current_word.escape_codes = make([]escape_code_, 0, 8)
ans.current_word.wcswidth = wcswidth.CreateWCWidthIterator()
return &ans
}
type WrapOptions struct {
Ignore_lines_containing string
Trim_whitespace bool // trim whitespace at the start and end of lines (start is after indent).
Indent string // indent to add at the start of every line all formatting is cleared for the indent.
}
func WrapTextAsLines(text string, width int, opts WrapOptions) []string {
w := new_wrapper(opts, width)
return w.wrap_text(text)
}
func WrapText(text string, width int, opts WrapOptions) string {
return strings.Join(WrapTextAsLines(text, width, opts), "\n")
}
+69
View File
@@ -0,0 +1,69 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package style
import (
"encoding/json"
"strings"
"testing"
)
func TestFormatWithIndent(t *testing.T) {
screen_width := 0
opts := WrapOptions{}
tx := func(text string, expected ...string) {
q := opts.Indent + strings.Join(expected, "")
actual := WrapText(text, screen_width, opts)
if actual != q {
os, _ := json.Marshal(opts)
t.Fatalf("\nFailed for: %#v\nOptions: %s\nexpected: %#v\nactual: %#v", text, os, q, actual)
}
}
opts.Indent = ""
screen_width = 4
tx("one two", "one \ntwo")
tx("a b", "a b")
screen_width = 3
tx("one tw", "one\n tw")
screen_width = 4
opts.Trim_whitespace = true
opts.Indent = "X"
tx("one two", "one\nXtwo")
tx("\x1b[2mone \x1b[mtwo", "\x1b[2mone\n\x1b[222mX\x1b[2m\x1b[mtwo")
screen_width = 3
tx("on tw", "on\nXtw")
opts.Indent = ""
opts.Trim_whitespace = false
opts.Indent = "__"
screen_width = 11
tx("testing\n\ntwo", "testing\n\n__two")
tx("testing\n \ntwo", "testing\n__ \n__two")
a := strings.Repeat("a", screen_width-len(opts.Indent)-1)
tx(a+" b", a+" \n__b")
tx("123456 \x1b[31m789a", "123456 \n__\x1b[31m789a")
tx("12 \x1b[31m789 abcd", "12 \x1b[31m789 \n\x1b[39m__\x1b[31mabcd")
tx("bb \x1b]8;;http://xyz.com\x1b\\text\x1b]8;;\x1b\\ two", "bb \x1b]8;;http://xyz.com\x1b\\text\x1b]8;;\x1b\\ \n__two")
tx("\x1b[31maaaaaa \x1b[39mbbbbbb", "\x1b[31maaaaaa \n\x1b[39m__\x1b[31m\x1b[39mbbbbbb")
tx(
"\x1b[31;4:3m\x1b]8;;XXX\x1b\\combined using\x1b]8;;\x1b\\ operators",
"\x1b[31;4:3m\x1b]8;;XXX\x1b\\combined \n\x1b[4:0;39m\x1b]8;;\x1b\\__\x1b[4:3;31m\x1b]8;;XXX\x1b\\using\x1b]8;;\x1b\\ \n\x1b[4:0;39m__\x1b[4:3;31moperators")
opts.Indent = ""
screen_width = 3
tx("one", "one")
tx("four", "fou\nr")
tx("nl\n\n", "nl\n\n")
tx("four\n\n", "fou\nr\n\n")
screen_width = 8
tx(
"\x1b[1mbold\x1b[221m no more bold",
"\x1b[1mbold\x1b[221m no \nmore \nbold",
)
}
+482
View File
@@ -0,0 +1,482 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package style
import (
"fmt"
"strconv"
"strings"
"sync"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
)
type escape_code interface {
prefix() string
suffix() string
is_empty() bool
}
// bool values {{{
type bool_value struct {
is_set, val bool
}
func (self bool_value) as_sgr(start, end string, prefix, suffix []string) ([]string, []string) {
if self.is_set {
if !self.val {
start, end = end, start
}
prefix = append(prefix, start)
suffix = append(suffix, end)
}
return prefix, suffix
}
func (self *bool_value) set_val(val bool) {
self.is_set = true
self.val = val
}
func (self *bool_value) from_string(raw string) bool {
switch strings.ToLower(raw) {
case "y", "yes", "true", "1":
self.set_val(true)
return true
case "n", "no", "false", "0":
self.set_val(false)
return true
default:
return false
}
}
// }}}
// color values {{{
type RGBA struct {
Red, Green, Blue, Inverse_alpha uint8
}
func (self RGBA) AsRGBSharp() string {
return fmt.Sprintf("#%02x%02x%02x", self.Red, self.Green, self.Blue)
}
func (self *RGBA) parse_rgb_strings(r string, g string, b string) bool {
var rv, gv, bv uint64
var err error
if len(r) == 1 {
r += r
g += g
b += b
}
if rv, err = strconv.ParseUint(r[:min(len(r), 2)], 16, 8); err != nil {
return false
}
if gv, err = strconv.ParseUint(g[:min(len(r), 2)], 16, 8); err != nil {
return false
}
if bv, err = strconv.ParseUint(b[:min(len(r), 2)], 16, 8); err != nil {
return false
}
self.Red, self.Green, self.Blue = uint8(rv), uint8(gv), uint8(bv)
return true
}
func fas_uint8(x float64) uint8 {
x = max(0, min(x, 1))
return uint8(x * 255)
}
func (self *RGBA) parse_rgb_intensities(r string, g string, b string) bool {
var rv, gv, bv float64
var err error
if rv, err = strconv.ParseFloat(r, 64); err != nil {
return false
}
if gv, err = strconv.ParseFloat(g, 64); err != nil {
return false
}
if bv, err = strconv.ParseFloat(b, 64); err != nil {
return false
}
self.Red, self.Green, self.Blue = fas_uint8(rv), fas_uint8(gv), fas_uint8(bv)
return true
}
func (self *RGBA) AsRGB() uint32 {
return uint32(self.Blue) | (uint32(self.Green) << 8) | (uint32(self.Red) << 16)
}
func (self *RGBA) IsDark() bool {
return self.Red < 155 && self.Green < 155 && self.Blue < 155
}
func (self *RGBA) FromRGB(col uint32) {
self.Red = uint8((col >> 16) & 0xff)
self.Green = uint8((col >> 8) & 0xff)
self.Blue = uint8((col) & 0xff)
}
type color_type struct {
is_numbered bool
val RGBA
}
func (self color_type) as_sgr(number_base int, prefix, suffix []string) ([]string, []string) {
suffix = append(suffix, strconv.Itoa(number_base+9))
if self.is_numbered {
num := int(self.val.Red)
if num < 16 && number_base < 50 {
if num > 7 {
number_base += 60
num -= 8
}
prefix = append(prefix, strconv.Itoa(number_base+num))
} else {
prefix = append(prefix, fmt.Sprintf("%d:5:%d", number_base+8, num))
}
} else {
prefix = append(prefix, fmt.Sprintf("%d:2:%d:%d:%d", number_base+8, self.val.Red, self.val.Green, self.val.Blue))
}
return prefix, suffix
}
type color_value struct {
is_set bool
val color_type
}
func parse_sharp(color string) (ans RGBA, err error) {
if len(color)%3 != 0 {
return RGBA{}, fmt.Errorf("length not a multiple of 3")
}
part_size := len(color) / 3
r, g, b := color[:part_size], color[part_size:2*part_size], color[part_size*2:part_size*3]
if !ans.parse_rgb_strings(r, g, b) {
err = fmt.Errorf("invalid rgb numbers")
}
return
}
func parse_rgb(color string) (ans RGBA, err error) {
colors := strings.Split(color, "/")
if len(colors) != 3 {
return RGBA{}, fmt.Errorf("length not a multiple of 3")
}
if ans.parse_rgb_strings(colors[0], colors[1], colors[2]) {
return
}
err = fmt.Errorf("invalid rgb numbers")
return
}
func parse_rgbi(color string) (ans RGBA, err error) {
colors := strings.Split(color, "/")
if len(colors) != 3 {
return RGBA{}, fmt.Errorf("length not a multiple of 3")
}
if ans.parse_rgb_intensities(colors[0], colors[1], colors[2]) {
return
}
err = fmt.Errorf("invalid rgb numbers")
return
}
func ParseColor(color string) (ans RGBA, err error) {
// Strip inline comments (e.g., "oklch(...) # comment")
// For hex colors like "#ff0000", preserve the first #, but strip comments after spaces
color = strings.TrimSpace(color)
if strings.HasPrefix(color, "#") {
// For hex colors, only strip comments after whitespace
parts := strings.Fields(color)
if len(parts) > 0 {
color = parts[0] // Keep only the hex color part
}
} else {
// For non-hex colors, strip everything after #
if idx := strings.Index(color, "#"); idx >= 0 {
color = strings.TrimSpace(color[:idx])
}
}
raw := strings.TrimSpace(strings.ToLower(color))
if val, ok := ColorNames[raw]; ok {
return val, nil
}
if len(raw) < 4 {
return RGBA{}, fmt.Errorf("not a valid color name: %#v", color)
}
var parser func(string) (RGBA, error)
switch raw[0] {
case '#':
parser = parse_sharp
raw = raw[1:]
case 'o':
if strings.HasPrefix(raw, "oklch(") {
parser, raw = parseOklch, raw[6:]
}
case 'l':
if strings.HasPrefix(raw, "lab(") {
parser, raw = parseLab, raw[4:]
}
case 'r':
if len(raw) > 4 && strings.HasPrefix(raw, "rgb") {
raw = raw[3:]
switch raw[0] {
case ':':
parser, raw = parse_rgb, raw[1:]
case 'i':
if strings.HasPrefix(raw, "i:") {
parser, raw = parse_rgbi, raw[2:]
}
}
}
}
if parser == nil {
err = fmt.Errorf("not a valid color name: %#v", color)
} else {
if ans, err = parser(raw); err != nil {
err = fmt.Errorf("not a valid color name: %#v %w", color, err)
}
}
return
}
type NullableColor struct {
Color RGBA
IsSet bool
}
func ParseColorOrNone(color string) (NullableColor, error) {
raw := strings.TrimSpace(strings.ToLower(color))
if raw == "none" {
return NullableColor{}, nil
}
c, err := ParseColor(raw)
return NullableColor{Color: c, IsSet: err == nil}, err
}
var named_colors = map[string]uint8{
"black": 0, "red": 1, "green": 2, "yellow": 3, "blue": 4, "magenta": 5, "cyan": 6, "gray": 7, "white": 7,
"hi-black": 8, "hi-red": 9, "hi-green": 10, "hi-yellow": 11, "hi-blue": 12, "hi-magenta": 13, "hi-cyan": 14, "hi-gray": 15, "hi-white": 15,
"bright-black": 8, "bright-red": 9, "bright-green": 10, "bright-yellow": 11, "bright-blue": 12, "bright-magenta": 13, "bright-cyan": 14, "bright-gray": 15, "bright-white": 15,
"intense-black": 8, "intense-red": 9, "intense-green": 10, "intense-yellow": 11, "intense-blue": 12, "intense-magenta": 13, "intense-cyan": 14, "intense-gray": 15, "intense-white": 15,
}
func (self *color_value) from_string(raw string) bool {
if n, ok := named_colors[raw]; ok {
self.is_set = true
self.val = color_type{val: RGBA{Red: n}, is_numbered: true}
return true
}
a, err := strconv.Atoi(raw)
if err == nil && 0 <= a && a <= 255 {
self.is_set = true
self.val = color_type{val: RGBA{Red: uint8(a)}, is_numbered: true}
return true
}
c, err := ParseColor(raw)
if err != nil {
return false
}
self.is_set = true
self.val = color_type{val: c}
return true
}
func (self color_value) as_sgr(number_base int, prefix, suffix []string) ([]string, []string) {
if self.is_set {
prefix, suffix = self.val.as_sgr(number_base, prefix, suffix)
}
return prefix, suffix
}
// }}}
// underline values {{{
type underline_style uint8
const (
no_underline underline_style = 0
straight_underline underline_style = 1
double_underline underline_style = 2
curly_underline underline_style = 3
dotted_underline underline_style = 4
dashed_underline underline_style = 5
nil_underline underline_style = 255
)
type underline_value struct {
is_set bool
style underline_style
}
func (self *underline_value) from_string(val string) bool {
ans := nil_underline
switch val {
case "true", "yes", "y", "straight", "single":
ans = straight_underline
case "false", "no", "n", "none":
ans = no_underline
case "double":
ans = double_underline
case "curly":
ans = curly_underline
case "dotted":
ans = dotted_underline
case "dashed":
ans = dashed_underline
}
if ans == nil_underline {
return false
}
self.is_set = true
self.style = ans
return true
}
func (self underline_value) as_sgr(prefix, suffix []string) ([]string, []string) {
if self.is_set {
s, e := "4:0", "4:0"
if self.style != no_underline {
s = "4:" + strconv.Itoa(int(self.style))
}
prefix = append(prefix, s)
suffix = append(suffix, e)
}
return prefix, suffix
}
// }}}
type sgr_code struct {
bold, italic, reverse, dim, strikethrough bool_value
fg, bg, uc color_value
underline underline_value
_prefix, _suffix string
}
func (self sgr_code) prefix() string {
return self._prefix
}
func (self sgr_code) suffix() string {
return self._suffix
}
func (self sgr_code) is_empty() bool {
return self._prefix == ""
}
type url_code struct {
url string
}
func (self url_code) prefix() string {
return fmt.Sprintf("\x1b]8;;%s\x1b\\", self.url)
}
func (self url_code) suffix() string {
return "\x1b]8;;\x1b\\"
}
func (self url_code) is_empty() bool {
return self.url == ""
}
func (self *sgr_code) update() {
p := make([]string, 0, 1)
s := make([]string, 0, 1)
p, s = self.bold.as_sgr("1", "221", p, s)
p, s = self.dim.as_sgr("2", "222", p, s)
p, s = self.italic.as_sgr("3", "23", p, s)
p, s = self.reverse.as_sgr("7", "27", p, s)
p, s = self.strikethrough.as_sgr("9", "29", p, s)
p, s = self.underline.as_sgr(p, s)
p, s = self.fg.as_sgr(30, p, s)
p, s = self.bg.as_sgr(40, p, s)
p, s = self.uc.as_sgr(50, p, s)
if len(p) > 0 {
self._prefix = "\x1b[" + strings.Join(p, ";") + "m"
} else {
self._prefix = ""
}
if len(s) > 0 {
self._suffix = "\x1b[" + strings.Join(s, ";") + "m"
} else {
self._suffix = ""
}
}
func parse_spec(spec string) []escape_code {
ans := make([]escape_code, 0, 1)
sgr := sgr_code{}
sparts, _ := shlex.Split(spec)
for _, p := range sparts {
key, val, found := strings.Cut(p, "=")
if !found {
val = "true"
}
switch key {
case "fg":
sgr.fg.from_string(val)
case "bg":
sgr.bg.from_string(val)
case "bold", "b":
sgr.bold.from_string(val)
case "italic", "i":
sgr.italic.from_string(val)
case "reverse":
sgr.reverse.from_string(val)
case "dim", "faint":
sgr.dim.from_string(val)
case "underline", "u":
sgr.underline.from_string(val)
case "strikethrough", "s":
sgr.strikethrough.from_string(val)
case "ucol", "underline_color", "uc":
sgr.uc.from_string(val)
}
}
sgr.update()
if !sgr.is_empty() {
ans = append(ans, &sgr)
}
return ans
}
var parsed_spec_cache = make(map[string][]escape_code)
var parsed_spec_cache_mutex = sync.Mutex{}
func cached_parse_spec(spec string) []escape_code {
parsed_spec_cache_mutex.Lock()
defer parsed_spec_cache_mutex.Unlock()
if val, ok := parsed_spec_cache[spec]; ok {
return val
}
ans := parse_spec(spec)
parsed_spec_cache[spec] = ans
return ans
}
func prefix_for_spec(spec string) string {
sb := strings.Builder{}
for _, ec := range cached_parse_spec(spec) {
sb.WriteString(ec.prefix())
}
return sb.String()
}
func suffix_for_spec(spec string) string {
sb := strings.Builder{}
for _, ec := range cached_parse_spec(spec) {
sb.WriteString(ec.suffix())
}
return sb.String()
}
+52
View File
@@ -0,0 +1,52 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package style
import (
"fmt"
"testing"
)
var _ = fmt.Print
func TestANSIStyleContext(t *testing.T) {
var ctx = Context{AllowEscapeCodes: false}
sprint := ctx.SprintFunc("bold")
if sprint("test") != "test" {
t.Fatal("AllowEscapeCodes=false not respected")
}
ctx.AllowEscapeCodes = true
if sprint("test") == "test" {
t.Fatal("AllowEscapeCodes=true not respected")
}
}
func TestANSIStyleSprint(t *testing.T) {
var ctx = Context{AllowEscapeCodes: true}
test := func(spec string, prefix string, suffix string) {
actual := ctx.SprintFunc(spec)(" ")
expected := prefix + " " + suffix
if actual != expected {
t.Fatalf("Formatting with spec: %s failed expected != actual: %#v != %#v", spec, expected, actual)
}
}
test("", "", "")
test("bold", "\x1b[1m", "\x1b[221m")
test("bold fg=red u=curly", "\x1b[1;4:3;31m", "\x1b[221;4:0;39m")
test("fg=123", "\x1b[38:5:123m", "\x1b[39m")
test("fg=15", "\x1b[97m", "\x1b[39m")
test("bg=15", "\x1b[107m", "\x1b[49m")
test("fg=#123", "\x1b[38:2:17:34:51m", "\x1b[39m")
test("fg=rgb:1/2/3", "\x1b[38:2:17:34:51m", "\x1b[39m")
test("bg=123", "\x1b[48:5:123m", "\x1b[49m")
test("uc=123", "\x1b[58:5:123m", "\x1b[59m")
test("uc=1", "\x1b[58:5:1m", "\x1b[59m")
actual := ctx.UrlFunc("u=curly uc=cyan")("http://moo.com", "___")
expected := "\x1b[4:3;58:5:6m\x1b]8;;http://moo.com\x1b\\___\x1b]8;;\x1b\\\x1b[4:0;59m"
if actual != expected {
t.Fatalf("Formatting URL failed expected != actual: %#v != %#v", expected, actual)
}
}
+264
View File
@@ -0,0 +1,264 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"archive/tar"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
)
var _ = fmt.Print
type TarExtractOptions struct {
DontPreservePermissions bool
DontPreserveSuidAndSgid bool
}
// Resolve symlinks in all but the last component of path
func eval_symlinks_in_parent(path string) (string, error) {
parent, err := EvalSymlinksThatExist(filepath.Dir(path))
if err != nil {
return "", err
}
return filepath.Join(parent, filepath.Base(path)), nil
}
func is_symlink_path(path string) (bool, error) {
st, err := os.Lstat(path)
if err != nil {
return false, err
}
return st.Mode()&fs.ModeSymlink != 0, nil
}
func remove_existing_non_dir(path string) error {
st, err := os.Lstat(path)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
if st.IsDir() {
return fmt.Errorf("cannot replace the directory %s with a non-directory", path)
}
return os.Remove(path)
}
// Hardlink src to dest, falling back to copying if the hardlink cannot be
// created, for example, because the filesystem does not support hardlinks.
// If src is a symlink, dest becomes a copy of the symlink, since os.Link()
// follows symlinks on some platforms.
func link_or_copy(src, dest string) (is_symlink bool, err error) {
st, err := os.Lstat(src)
if err != nil {
return false, err
}
if st.Mode()&fs.ModeSymlink != 0 {
target, err := os.Readlink(src)
if err != nil {
return false, err
}
if !filepath.IsAbs(target) {
target = filepath.Join(filepath.Dir(src), target)
}
return true, os.Symlink(target, dest)
}
if !st.Mode().IsRegular() {
return false, fmt.Errorf("cannot hardlink %s to %s as it is not a regular file", dest, src)
}
link_err := os.Link(src, dest)
if link_err == nil {
return false, nil
}
s, err := os.Open(src)
if err != nil {
return false, errors.Join(link_err, err)
}
d, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_EXCL, st.Mode().Perm())
if err != nil {
s.Close()
return false, errors.Join(link_err, err)
}
if err = CopyFileAndClose(context.Background(), s, d); err != nil {
return false, errors.Join(link_err, err, os.Remove(dest))
}
return false, nil
}
func ExtractAllFromTar(tr *tar.Reader, dest_path string, optss ...TarExtractOptions) (count int, err error) {
opts := TarExtractOptions{}
if len(optss) > 0 {
opts = optss[0]
}
if !filepath.IsAbs(dest_path) {
if dest_path, err = filepath.Abs(dest_path); err != nil {
return
}
}
if dest_path, err = filepath.EvalSymlinks(dest_path); err != nil {
return
}
dest_path = filepath.Clean(dest_path)
mode := func(hdr int64) fs.FileMode {
// yes, we really want to preserve sticky bits and setuid/setgid bits
return fs.FileMode(hdr) & (fs.ModePerm | fs.ModeSetgid | fs.ModeSetuid | fs.ModeSticky)
}
set_metadata := func(chmod func(mode fs.FileMode) error, hdr_mode int64) (err error) {
if !opts.DontPreservePermissions && chmod != nil {
perms := mode(hdr_mode)
if opts.DontPreserveSuidAndSgid {
perms = perms &^ (os.ModeSetuid | os.ModeSetgid)
}
if err = chmod(perms); err != nil {
return err
}
}
count++
return
}
needed_prefix := dest_path + string(os.PathSeparator)
// Directory permissions are set after extraction as a read-only
// directory would prevent its contents from being created
var dir_chmods []func() error
for {
var hdr *tar.Header
hdr, err = tr.Next()
if errors.Is(err, io.EOF) {
err = nil
break
}
if err != nil {
return count, err
}
dest := hdr.Name
if !filepath.IsAbs(dest) {
dest = filepath.Join(dest_path, dest)
}
if hdr.Typeflag == tar.TypeDir {
dest, err = EvalSymlinksThatExist(dest)
} else {
// Only resolve symlinks in the parent directory so that an
// existing entry at this path is replaced rather than written
// through
dest, err = eval_symlinks_in_parent(dest)
}
if err != nil {
return count, err
}
if !strings.HasPrefix(dest, needed_prefix) {
continue
}
switch hdr.Typeflag {
case tar.TypeDir:
err = os.MkdirAll(dest, 0o700)
if err != nil {
return
}
if err = set_metadata(func(m fs.FileMode) error {
dir_chmods = append(dir_chmods, func() error { return os.Chmod(dest, m) })
return nil
}, hdr.Mode); err != nil {
return
}
case tar.TypeReg:
var d *os.File
if err = os.MkdirAll(filepath.Dir(dest), 0o700); err != nil {
return
}
// Remove rather than truncate any existing file as it may be
// hardlinked to another extracted file
if err = remove_existing_non_dir(dest); err != nil {
return
}
if d, err = os.Create(dest); err != nil {
return
}
err = set_metadata(d.Chmod, hdr.Mode)
if err == nil {
_, err = io.Copy(d, tr)
}
d.Close()
if err != nil {
return
}
case tar.TypeLink:
if err = os.MkdirAll(filepath.Dir(dest), 0o700); err != nil {
return
}
// Hardlink targets are relative to the archive root
link_target := hdr.Linkname
if !filepath.IsAbs(link_target) {
link_target = filepath.Join(dest_path, link_target)
}
// A hardlink to a symlink links to the symlink itself, not to
// what it points to
if link_target, err = eval_symlinks_in_parent(link_target); err != nil {
return
}
if !strings.HasPrefix(link_target, needed_prefix) {
return count, fmt.Errorf("the hardlink %s points to %s which is outside the destination directory", hdr.Name, hdr.Linkname)
}
var is_symlink bool
// GNU tar creates hardlinks to self when the same path is
// archived more than once
if link_target != dest {
if err = remove_existing_non_dir(dest); err != nil {
return
}
if is_symlink, err = link_or_copy(link_target, dest); err != nil {
return
}
} else if is_symlink, err = is_symlink_path(dest); err != nil {
return
}
chmod := func(m fs.FileMode) error { return os.Chmod(dest, m) }
if is_symlink {
// os.Chmod() follows symlinks
chmod = nil
}
if err = set_metadata(chmod, hdr.Mode); err != nil {
return
}
case tar.TypeSymlink:
if err = os.MkdirAll(filepath.Dir(dest), 0o700); err != nil {
return
}
if err = remove_existing_non_dir(dest); err != nil {
return
}
link_target := hdr.Linkname
if !filepath.IsAbs(link_target) {
link_target = filepath.Join(filepath.Dir(dest), link_target)
}
// We dont care about the link target being outside dest_path as
// we resolve symlinks in dest and never write through a
// symlink, so a symlink pointing outside dest_path cannot cause
// writes outside dest_path.
if err = os.Symlink(link_target, dest); err != nil {
return
}
if err = set_metadata(nil, hdr.Mode); err != nil {
return
}
}
}
// Apply in reverse so that children are processed before their parents,
// as a parent without search permission prevents chmod of its children
for i := len(dir_chmods) - 1; i >= 0; i-- {
if err = dir_chmods[i](); err != nil {
return
}
}
return
}
+311
View File
@@ -0,0 +1,311 @@
package utils
import (
"archive/tar"
"bytes"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
func TestTarExtract(t *testing.T) {
tdir := t.TempDir()
a, b := filepath.Join(tdir, "a"), filepath.Join(tdir, "b")
if err := os.Mkdir(a, 0700); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(b, 0700); err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
var files = []struct {
name, body string
}{
{"s/one.txt", "This archive contains some text files."},
{"b", b},
{"b/two.txt", "Get animal handling license."},
{"../b/three.txt", "Get animal handling license."},
{"nested/dir/", ""},
}
for _, file := range files {
hdr := &tar.Header{
Name: file.name,
Mode: 0600,
Size: int64(len(file.body)),
}
if file.name == "b" {
hdr.Linkname = file.body
hdr.Typeflag = tar.TypeSymlink
hdr.Size = 0
}
if err := tw.WriteHeader(hdr); err != nil {
t.Fatal(err)
}
if hdr.Typeflag != tar.TypeSymlink && len(file.body) > 0 {
if _, err := tw.Write([]byte(file.body)); err != nil {
t.Fatal(err)
}
}
}
if err := tw.Close(); err != nil {
t.Fatal(err)
}
tr := tar.NewReader(&buf)
count, err := ExtractAllFromTar(tr, a)
if err != nil {
t.Fatal(err)
}
if count != len(files)-2 {
t.Fatalf("Incorrect count of extracted files: %d != %d", count, len(files)-2)
}
entries := []string{}
if err = fs.WalkDir(os.DirFS(tdir), ".", func(path string, d fs.DirEntry, err error) error {
entries = append(entries, path)
return err
},
); err != nil {
t.Fatal(err)
}
if diff := cmp.Diff([]string{".", "a", "a/b", "a/nested", "a/nested/dir", "a/s", "a/s/one.txt", "b"}, entries); diff != "" {
t.Fatalf("Directory contents not as expected: %s", diff)
}
}
type tar_entry struct {
name, body, linkname string
typeflag byte
mode int64
}
func make_tar(t *testing.T, entries ...tar_entry) *tar.Reader {
t.Helper()
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
for _, e := range entries {
typeflag := e.typeflag
if typeflag == 0 {
typeflag = tar.TypeReg
}
mode := e.mode
if mode == 0 {
mode = 0600
}
hdr := tar.Header{Name: e.name, Mode: mode, Typeflag: typeflag, Linkname: e.linkname, Size: int64(len(e.body))}
if err := tw.WriteHeader(&hdr); err != nil {
t.Fatal(err)
}
if _, err := tw.Write([]byte(e.body)); err != nil {
t.Fatal(err)
}
}
if err := tw.Close(); err != nil {
t.Fatal(err)
}
return tar.NewReader(&buf)
}
func assert_same_file(t *testing.T, a, b string) {
t.Helper()
sa, err := os.Stat(a)
if err != nil {
t.Fatal(err)
}
sb, err := os.Stat(b)
if err != nil {
t.Fatal(err)
}
if !os.SameFile(sa, sb) {
t.Fatalf("%s and %s are not hardlinks", a, b)
}
}
func assert_file_contents(t *testing.T, path, expected string) {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if string(data) != expected {
t.Fatalf("Contents of %s not as expected: %#v != %#v", path, string(data), expected)
}
}
func TestTarExtractHardlinks(t *testing.T) {
for _, tc := range []struct {
name, target, link string
}{
{"root", "target.txt", "link.txt"},
{"same_directory", "dir/target.txt", "dir/link.txt"},
{"cross_directory", "one/target.txt", "two/link.txt"},
{"dot_slash_prefix", "./dir/target.txt", "./dir/link.txt"},
} {
t.Run(tc.name, func(t *testing.T) {
dest := t.TempDir()
count, err := ExtractAllFromTar(make_tar(t,
tar_entry{name: tc.target},
tar_entry{name: tc.link, typeflag: tar.TypeLink, linkname: tc.target},
), dest)
if err != nil {
t.Fatal(err)
}
if count != 2 {
t.Fatalf("Expected two extracted files, got %d", count)
}
assert_same_file(t, filepath.Join(dest, tc.target), filepath.Join(dest, tc.link))
})
}
t.Run("through_symlinked_directory", func(t *testing.T) {
dest := t.TempDir()
if _, err := ExtractAllFromTar(make_tar(t,
tar_entry{name: "real/target.txt"},
tar_entry{name: "alias", typeflag: tar.TypeSymlink, linkname: "real"},
tar_entry{name: "two/link.txt", typeflag: tar.TypeLink, linkname: "alias/target.txt"},
), dest); err != nil {
t.Fatal(err)
}
assert_same_file(t, filepath.Join(dest, "real/target.txt"), filepath.Join(dest, "two/link.txt"))
})
t.Run("to_symlink", func(t *testing.T) {
dest := t.TempDir()
if _, err := ExtractAllFromTar(make_tar(t,
tar_entry{name: "target.txt", body: "target"},
tar_entry{name: "sym", typeflag: tar.TypeSymlink, linkname: "target.txt"},
tar_entry{name: "dir/link", typeflag: tar.TypeLink, linkname: "sym"},
), dest); err != nil {
t.Fatal(err)
}
link := filepath.Join(dest, "dir/link")
st, err := os.Lstat(link)
if err != nil {
t.Fatal(err)
}
if st.Mode()&fs.ModeSymlink == 0 {
t.Fatalf("Hardlink to symlink is not a symlink: %v", st.Mode())
}
assert_file_contents(t, link, "target")
})
t.Run("duplicate_entries", func(t *testing.T) {
dest := t.TempDir()
if _, err := ExtractAllFromTar(make_tar(t,
tar_entry{name: "a", body: "one"},
tar_entry{name: "b", typeflag: tar.TypeLink, linkname: "a"},
tar_entry{name: "b", typeflag: tar.TypeLink, linkname: "a"},
tar_entry{name: "a", typeflag: tar.TypeLink, linkname: "a"},
tar_entry{name: "c", typeflag: tar.TypeLink, linkname: "a"},
tar_entry{name: "c", body: "two"},
tar_entry{name: "s", typeflag: tar.TypeSymlink, linkname: "a"},
tar_entry{name: "s", typeflag: tar.TypeSymlink, linkname: "c"},
), dest); err != nil {
t.Fatal(err)
}
assert_same_file(t, filepath.Join(dest, "a"), filepath.Join(dest, "b"))
// replacing a hardlinked file must not change the other links
assert_file_contents(t, filepath.Join(dest, "a"), "one")
assert_file_contents(t, filepath.Join(dest, "c"), "two")
assert_file_contents(t, filepath.Join(dest, "s"), "two")
})
outside := func(t *testing.T, entries ...tar_entry) {
parent := t.TempDir()
dest := filepath.Join(parent, "dest")
if err := os.Mkdir(dest, 0700); err != nil {
t.Fatal(err)
}
outside_file := filepath.Join(parent, "outside.txt")
if err := os.WriteFile(outside_file, []byte("outside"), 0600); err != nil {
t.Fatal(err)
}
for i := range entries {
entries[i].linkname = strings.ReplaceAll(entries[i].linkname, "PARENT", parent)
}
if _, err := ExtractAllFromTar(make_tar(t, entries...), dest); err == nil {
t.Fatal("Hardlink to file outside destination did not fail")
}
if _, err := os.Lstat(filepath.Join(dest, "link.txt")); !os.IsNotExist(err) {
t.Fatalf("Hardlink to file outside destination was created: %v", err)
}
st, err := os.Stat(outside_file)
if err != nil {
t.Fatal(err)
}
if st.Mode().Perm() != 0600 {
t.Fatalf("Permissions of file outside destination were changed: %v", st.Mode())
}
}
t.Run("outside_destination", func(t *testing.T) {
outside(t, tar_entry{name: "link.txt", typeflag: tar.TypeLink, linkname: "../outside.txt"})
})
t.Run("outside_destination_absolute", func(t *testing.T) {
outside(t, tar_entry{name: "link.txt", typeflag: tar.TypeLink, linkname: "PARENT/outside.txt"})
})
t.Run("outside_destination_via_symlink", func(t *testing.T) {
outside(t,
tar_entry{name: "s", typeflag: tar.TypeSymlink, linkname: "PARENT"},
tar_entry{name: "link.txt", typeflag: tar.TypeLink, linkname: "s/outside.txt"},
)
})
}
func TestTarExtractReadOnlyDirectory(t *testing.T) {
dest := t.TempDir()
ro := filepath.Join(dest, "ro")
t.Cleanup(func() { _ = os.Chmod(ro, 0700) })
if _, err := ExtractAllFromTar(make_tar(t,
tar_entry{name: "ro/", typeflag: tar.TypeDir, mode: 0555},
tar_entry{name: "ro/file.txt", body: "contents"},
), dest); err != nil {
t.Fatal(err)
}
assert_file_contents(t, filepath.Join(ro, "file.txt"), "contents")
st, err := os.Stat(ro)
if err != nil {
t.Fatal(err)
}
if st.Mode().Perm() != 0555 {
t.Fatalf("Permissions of read-only directory not preserved: %v", st.Mode())
}
}
func TestTarExtractUnsearchableParentDirectory(t *testing.T) {
dest := t.TempDir()
parent := filepath.Join(dest, "a")
t.Cleanup(func() {
_ = os.Chmod(parent, 0700)
_ = os.Chmod(filepath.Join(parent, "b"), 0700)
})
if _, err := ExtractAllFromTar(make_tar(t,
tar_entry{name: "a/", typeflag: tar.TypeDir, mode: 0600},
tar_entry{name: "a/b/", typeflag: tar.TypeDir, mode: 0555},
tar_entry{name: "a/b/file.txt", body: "contents"},
), dest); err != nil {
t.Fatal(err)
}
st, err := os.Stat(parent)
if err != nil {
t.Fatal(err)
}
if st.Mode().Perm() != 0600 {
t.Fatalf("Permissions of parent directory not preserved: %v", st.Mode())
}
if err = os.Chmod(parent, 0700); err != nil {
t.Fatal(err)
}
assert_file_contents(t, filepath.Join(parent, "b", "file.txt"), "contents")
if st, err = os.Stat(filepath.Join(parent, "b")); err != nil {
t.Fatal(err)
}
if st.Mode().Perm() != 0555 {
t.Fatalf("Permissions of child directory not preserved: %v", st.Mode())
}
}
+48
View File
@@ -0,0 +1,48 @@
//go:build linux
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"io/fs"
"os"
"strconv"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func CreateAnonymousTemp(dir string, perms ...fs.FileMode) (*os.File, error) {
if dir == "" {
dir = os.TempDir()
}
var perm fs.FileMode = unix.S_IREAD | unix.S_IWRITE
if len(perms) > 0 {
perm = perms[0]
}
fd, err := unix.Open(dir, unix.O_RDWR|unix.O_TMPFILE|unix.O_CLOEXEC, uint32(perm&fs.ModePerm))
if err == nil {
path := "/proc/self/fd/" + strconv.FormatUint(uint64(fd), 10)
return os.NewFile(uintptr(fd), path), nil
}
if err == unix.ENOENT {
return nil, &os.PathError{
Op: "open",
Path: dir,
Err: err,
}
}
f, err := os.CreateTemp(dir, "")
if err != nil {
return nil, err
}
err = os.Remove(f.Name())
if err != nil {
f.Close()
return nil, err
}
return f, err
}
+42
View File
@@ -0,0 +1,42 @@
//go:build !linux
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"io/fs"
"os"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func CreateAnonymousTemp(dir string, perms ...fs.FileMode) (*os.File, error) {
var perm fs.FileMode = unix.S_IREAD | unix.S_IWRITE
default_perm := perm
if len(perms) > 0 {
perm = perms[0]
}
f, err := os.CreateTemp(dir, "")
if err != nil {
return nil, err
}
if perm != default_perm {
err = f.Chmod(perm & fs.ModePerm)
if err != nil {
os.Remove(f.Name())
f.Close()
return nil, err
}
}
err = os.Remove(f.Name())
if err != nil {
f.Close()
return nil, err
}
return f, err
}
+26
View File
@@ -0,0 +1,26 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"runtime"
"strconv"
"testing"
)
var _ = fmt.Print
func TestCreateAnonymousTempfile(t *testing.T) {
f, err := CreateAnonymousTemp("")
if err != nil {
t.Fatal(err)
}
fd := int64(f.Fd())
f.Close()
if runtime.GOOS == "linux" {
if f.Name() != "/proc/self/fd/"+strconv.FormatInt(fd, 10) {
t.Fatalf("Anonymous tempfile was not created atomically")
}
}
}
+26
View File
@@ -0,0 +1,26 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
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 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"`
}
+24
View File
@@ -0,0 +1,24 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"unsafe"
)
var _ = fmt.Print
// 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 UnsafeStringToBytes(s string) (b []byte) {
return unsafe.Slice(unsafe.StringData(s), len(s))
}
// 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 UnsafeBytesToString(b []byte) (s string) {
return unsafe.String(unsafe.SliceData(b), len(b))
}
+70
View File
@@ -0,0 +1,70 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
// UTF-8 decode taken from: https://bjoern.hoehrmann.de/utf-8/decoder/dfa/
type UTF8State uint32
var utf8_data []uint8 = []uint8{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1f
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3f
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5f
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7f
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9f
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // a0..bf
8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // c0..df
0xa, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // e0..ef
0xb, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // f0..ff
0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2
1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // s7..s8
}
const (
UTF8_ACCEPT UTF8State = 0
UTF8_REJECT UTF8State = 1
)
func DecodeUtf8(state *UTF8State, codep *UTF8State, byte_ byte) UTF8State {
typ := UTF8State(utf8_data[byte_])
b := UTF8State(byte_)
if *state != UTF8_ACCEPT {
*codep = (b & 0x3f) | (*codep << 6)
} else {
*codep = (0xff >> typ) & (b)
}
idx := 256 + *state*16 + typ
*state = UTF8State(utf8_data[idx])
return *state
}
func EncodeUtf8(ch UTF8State, dest []byte) int {
if ch < 0x80 {
dest[0] = byte(ch)
return 1
}
if ch < 0x800 {
dest[0] = byte((ch >> 6) | 0xC0)
dest[1] = byte((ch & 0x3F) | 0x80)
return 2
}
if ch < 0x10000 {
dest[0] = byte((ch >> 12) | 0xE0)
dest[1] = byte(((ch >> 6) & 0x3F) | 0x80)
dest[2] = byte((ch & 0x3F) | 0x80)
return 3
}
if ch < 0x110000 {
dest[0] = byte((ch >> 18) | 0xF0)
dest[1] = byte(((ch >> 12) & 0x3F) | 0x80)
dest[2] = byte(((ch >> 6) & 0x3F) | 0x80)
dest[3] = byte((ch & 0x3F) | 0x80)
return 4
}
return 0
}
+62
View File
@@ -0,0 +1,62 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package utils
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
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
})
func Which(cmd string, paths ...string) string {
if strings.Contains(cmd, string(os.PathSeparator)) {
return ""
}
if len(paths) == 0 {
path := os.Getenv("PATH")
if path == "" {
return ""
}
paths = strings.Split(path, string(os.PathListSeparator))
}
for _, dir := range paths {
q := filepath.Join(dir, cmd)
if unix.Access(q, unix.X_OK) == nil {
s, err := os.Stat(q)
if err == nil && !s.IsDir() {
return q
}
}
}
return ""
}
func FindExe(name string) string {
ans := Which(name)
if ans != "" {
return ans
}
ans = Which(name, DefaultExeSearchPaths()...)
if ans == "" {
ans = name
}
return ans
}