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

+264
View File
@@ -0,0 +1,264 @@
#!/bin/sh
#
# bootstrap-utils.sh
# Copyright (C) 2022 Kovid Goyal <kovid at kovidgoyal.net>
#
# Distributed under terms of the MIT license.
#
mv_files_and_dirs() {
cwd="$PWD"
cd "$1"
# Directories not present at the destination are moved intact, preserving
# their permissions, and pruned. Existing directories are merged, keeping
# their permissions, so make the source writable to allow moving out its
# contents. If a move fails fall back to creating the directory and merging.
command find . -type d ! -name . -exec sh -c '
if [ ! -d "$1/$2" ]; then
{ [ -L "$1/$2" ] || [ -e "$1/$2" ]; } && command rm -f -- "$1/$2"
command mv -- "$2" "$1/$2" 2> /dev/null && exit 0
[ -d "$1/$2" ] && exit 0
command mkdir -p -- "$1/$2"
fi
command chmod u+rwx "$2"
exit 1' sh "$2" "{}" ";" -prune
command find . -type l -exec sh -c 'tgt=$(command readlink -n "$2"); command ln -snf -- "$tgt" "$1/$2"; command rm -f -- "$2"' sh "$2" "{}" ";"
command find . -type f -exec mv "{}" "$2/{}" ";"
cd "$cwd"
}
compile_terminfo() {
tname=".terminfo"
# Ensure the 78 dir is present
if [ ! -f "$1/$tname/78/xterm-kitty" ]; then
command mkdir -p "$1/$tname/78"
command ln -sf "../x/xterm-kitty" "$1/$tname/78/xterm-kitty"
fi
if [ -e "/usr/share/misc/terminfo.cdb" ]; then
# NetBSD requires this file, see https://github.com/kovidgoyal/kitty/issues/4622
# Also compile terminfo using tic installed via pkgsrc,
# so that programs that depend on the new version of ncurses automatically fall back to this one.
if [ -x "/usr/pkg/bin/tic" ]; then
/usr/pkg/bin/tic -x -o "$1/$tname" "$1/.terminfo/kitty.terminfo" 2>/dev/null
fi
if [ ! -e "$1/$tname/x/xterm-kitty" ]; then
command ln -sf "../../.terminfo.cdb" "$1/$tname/x/xterm-kitty"
fi
tname=".terminfo.cdb"
fi
# export TERMINFO
export TERMINFO="$HOME/$tname"
# compile terminfo for this system
if [ -x "$(command -v tic)" ]; then
tic_out=$(command tic -x -o "$1/$tname" "$1/.terminfo/kitty.terminfo" 2>&1)
[ $? = 0 ] || die "Failed to compile terminfo with err: $tic_out"
fi
}
parse_passwd_record() {
printf "%s" "$(command grep -o '[^:]*$')"
}
login_shell_is_ok() {
[ -n "$1" ] && login_shell=$(echo $1 | parse_passwd_record)
[ -n "$login_shell" -a -x "$login_shell" ] && return 0
return 1
}
using_getent() {
cmd=$(command -v getent) && [ -n "$cmd" ] && output=$(command "$cmd" passwd "$USER" 2>/dev/null) \
&& login_shell_is_ok "$output"
}
using_id() {
cmd=$(command -v id) && [ -n "$cmd" ] && output=$(command "$cmd" -P "$USER" 2>/dev/null) \
&& login_shell_is_ok "$output"
}
using_python() {
detect_python && output=$(command "$python" -c "import pwd, os; print(pwd.getpwuid(os.geteuid()).pw_shell)" 2>/dev/null) \
&& login_shell="$output" && login_shell_is_ok
}
using_perl() {
detect_perl && output=$(command "$perl" -e 'my $shell = (getpwuid($<))[8]; print $shell' 2>/dev/null) \
&& login_shell="$output" && login_shell_is_ok
}
using_passwd() {
[ -f "/etc/passwd" -a -r "/etc/passwd" ] && output=$(command grep "^$USER:" /etc/passwd 2>/dev/null) \
&& login_shell_is_ok "$output"
}
using_shell_env() {
[ -n "$SHELL" ] && login_shell="$SHELL" && login_shell_is_ok
}
execute_with_python() {
if detect_python; then
exec "$python" "-c" 'import os, sys; os.execlp(sys.argv[1], "-" + sys.argv[2])' "$login_shell" "$shell_name"
fi
return 1
}
execute_with_perl() {
if detect_perl; then
exec "$perl" "-e" 'exec {$ARGV[0]} ("-" . $ARGV[1])' "$login_shell" "$shell_name"
fi
return 1
}
exec_zsh_with_integration() {
zdotdir="$ZDOTDIR"
if [ -z "$zdotdir" ]; then
zdotdir=~
else
export KITTY_ORIG_ZDOTDIR="$zdotdir"
fi
# dont prevent zsh-newuser-install from running
if [ -f "$zdotdir/.zshrc" -o -f "$zdotdir/.zshenv" -o -f "$zdotdir/.zprofile" -o -f "$zdotdir/.zlogin" ]; then
export ZDOTDIR="$shell_integration_dir/zsh"
exec "$login_shell" "-l"
fi
# ensure this is not propagated
unset KITTY_ORIG_ZDOTDIR
}
exec_fish_with_integration() {
if [ -z "$XDG_DATA_DIRS" ]; then
export XDG_DATA_DIRS="$shell_integration_dir"
else
export XDG_DATA_DIRS="$shell_integration_dir:$XDG_DATA_DIRS"
fi
export KITTY_FISH_XDG_DATA_DIR="$shell_integration_dir"
exec "$login_shell" "-l"
}
exec_bash_with_integration() {
export ENV="$shell_integration_dir/bash/kitty.bash"
export KITTY_BASH_INJECT="1"
if [ -z "$HISTFILE" ]; then
export HISTFILE="$HOME/.bash_history"
export KITTY_BASH_UNEXPORT_HISTFILE="1"
fi
exec "$login_shell" "--login" "--posix"
}
exec_with_shell_integration() {
[ -z "$shell_integration_dir" ] && return
case "$shell_name" in
"zsh")
exec_zsh_with_integration
;;
"fish")
exec_fish_with_integration
;;
"bash")
exec_bash_with_integration
;;
esac
}
execute_sh_with_posix_env() {
# only for sh as that is likely to be POSIX compliant
[ "$shell_name" = "sh" ] || return
# sh supports -l so use that
command "$login_shell" -l -c ":" > /dev/null 2> /dev/null && return
[ -z "$shell_integration_dir" ] && die "Could not read data over tty ssh kitten cannot function"
sh_dir="$shell_integration_dir/sh"
command mkdir -p "$sh_dir" || die "Creating directory $sh_dir failed"
sh_script="$sh_dir/login_shell_env.sh"
# Source /etc/profile, ~/.profile, and then check and source ENV
printf "%s" '
if [ -n "$KITTY_SH_INJECT" ]; then
unset ENV; unset KITTY_SH_INJECT
_ksi_safe_source() { [ -f "$1" -a -r "$1" ] || return 1; . "$1"; return 0; }
[ -n "$KITTY_SH_POSIX_ENV" ] && export ENV="$KITTY_SH_POSIX_ENV"
unset KITTY_SH_POSIX_ENV
_ksi_safe_source "/etc/profile"; _ksi_safe_source "${HOME-}/.profile"
[ -n "$ENV" ] && _ksi_safe_source "$ENV"
unset -f _ksi_safe_source
fi' > "$sh_script"
export KITTY_SH_INJECT="1"
[ -n "$ENV" ] && export KITTY_SH_POSIX_ENV="$ENV"
export ENV="$sh_script"
exec "$login_shell"
}
install_kitty_bootstrap() {
kitty_dir="$data_dir/kitty/bin"
export SSH_KITTEN_KITTY_DIR="$kitty_dir"
kitty_exists="n"
command -v kitty 2> /dev/null > /dev/null && kitty_exists="y"
if [ "$kitty_remote" = "yes" -o "$kitty_remote-$kitty_exists" = "if-needed-n" ]; then
if [ "$kitty_exists" = "y" ]; then
export PATH="$kitty_dir:$PATH"
else
export PATH="$PATH:$kitty_dir"
fi
fi
}
prepare_for_exec() {
if [ -n "$leading_data" ]; then
# clear current line as it might have things echoed on it from leading_data
# because we only turn off echo in this script whereas the leading bytes could
# have been sent before the script had a chance to run
printf "\r\033[K" > /dev/tty
fi
[ -f "$HOME/.terminfo/kitty.terminfo" ] || die "Incomplete extraction of ssh data"
install_kitty_bootstrap
[ -n "$login_shell" ] || using_getent || using_id || using_python || using_perl || using_passwd || using_shell_env || login_shell="sh"
case "$login_shell" in
/*) ;;
*)
if ! command -v "$login_shell" > /dev/null 2> /dev/null; then
for i in /opt/homebrew/bin /opt/homebrew/sbin /opt/local/bin /opt/local/sbin /usr/local/bin /usr/bin /bin /usr/sbin /sbin
do
if [ -x "$i/$login_shell" ]; then
login_shell="$i/$login_shell"
break
fi
done
fi
;;
esac
shell_name=$(command basename "$login_shell")
[ -n "$login_cwd" ] && cd "$login_cwd"
}
exec_login_shell() {
case "$KITTY_SHELL_INTEGRATION" in
("")
# only blanks or unset
unset KITTY_SHELL_INTEGRATION
;;
(*)
# not blank
printf "%s" "$KITTY_SHELL_INTEGRATION" | command grep -q '\bno-rc\b' || exec_with_shell_integration
# either no-rc or exec failed
unset KITTY_SHELL_INTEGRATION
;;
esac
# We need to pass the first argument to the executed program with a leading -
# to make sure the shell executes as a login shell. Note that not all shells
# support exec -a so we use the below to try to detect such shells
[ "$(exec -a echo echo OK 2> /dev/null)" = "OK" ] && exec -a "-$shell_name" "$login_shell"
execute_with_python
execute_with_perl
execute_sh_with_posix_env
exec "$login_shell" "-l"
if [ -e /dev/stderr ]; then
printf "%s\n" "Could not execute the shell $login_shell as a login shell" > /dev/stderr
elif [ -e /dev/fd/2 ]; then
printf "%s\n" "Could not execute the shell $login_shell as a login shell" > /dev/fd/2
else
printf "%s\n" "Could not execute the shell $login_shell as a login shell"
fi
exec "$login_shell"
}
+363
View File
@@ -0,0 +1,363 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
import base64
import contextlib
import errno
import io
import json
import os
import pwd
import shutil
import subprocess
import sys
import tarfile
import tempfile
import termios
tty_file_obj = None
echo_on = int('ECHO_ON')
data_dir = shell_integration_dir = ''
request_data = int('REQUEST_DATA')
leading_data = b''
login_shell = os.environ.get('SHELL') or '/bin/sh'
try:
login_shell = pwd.getpwuid(os.geteuid()).pw_shell
except KeyError:
pass
export_home_cmd = b'EXPORT_HOME_CMD'
if export_home_cmd:
HOME = base64.standard_b64decode(export_home_cmd).decode('utf-8')
os.chdir(HOME)
else:
HOME = os.path.expanduser('~')
def set_echo(fd, on=False):
if fd < 0:
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
if on:
new[3] |= termios.ECHO
else:
new[3] &= ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, new)
return fd, old
def cleanup():
global tty_file_obj
if tty_file_obj is not None:
if echo_on:
set_echo(tty_file_obj.fileno(), True)
tty_file_obj.close()
tty_file_obj = None
def write_all(fd, data):
if isinstance(data, str):
data = data.encode('utf-8')
data = memoryview(data)
while data:
try:
n = os.write(fd, data)
except BlockingIOError:
continue
if not n:
break
data = data[n:]
def dcs_to_kitty(payload, type='ssh'):
if isinstance(payload, str):
payload = payload.encode('utf-8')
payload = base64.standard_b64encode(payload)
return b'\033P@kitty-' + type.encode('ascii') + b'|' + payload + b'\033\\'
def send_data_request():
write_all(tty_file_obj.fileno(), dcs_to_kitty('id=REQUEST_ID:pwfile=PASSWORD_FILENAME:pw=DATA_PASSWORD'))
def debug(msg):
data = dcs_to_kitty('debug: {}'.format(msg), 'print')
if tty_file_obj is None:
with open(os.ctermid(), 'wb') as fl:
write_all(fl.fileno(), data)
else:
write_all(tty_file_obj.fileno(), data)
def apply_env_vars(raw):
global login_shell
def process_defn(defn):
parts = json.loads(defn)
if len(parts) == 1:
key, val = parts[0], ''
else:
key, val, literal_quote = parts
if not literal_quote:
val = os.path.expandvars(val)
os.environ[key] = val
for line in raw.splitlines():
val = line.split(' ', 1)[-1]
if line.startswith('export '):
process_defn(val)
elif line.startswith('unset '):
os.environ.pop(json.loads(val)[0], None)
login_shell = os.environ.pop('KITTY_LOGIN_SHELL', login_shell)
def move_dir(src, dest):
try:
os.rename(src, dest)
except OSError as e:
if e.errno != errno.EXDEV:
raise
# copytree preserves permissions, the source is removed with the
# temporary directory
shutil.copytree(src, dest, symlinks=True)
def make_deletable(top):
# copied directories can be read-only
for dirpath, dirnames, filenames in os.walk(top):
for x in dirnames:
path = os.path.join(dirpath, x)
if not os.path.islink(path):
os.chmod(path, 0o700)
def move(src, base_dest):
for x in os.listdir(src):
path = os.path.join(src, x)
dest = os.path.join(base_dest, x)
if os.path.islink(path):
try:
os.unlink(dest)
except EnvironmentError:
pass
os.symlink(os.readlink(path), dest)
elif os.path.isdir(path):
if os.path.isdir(dest):
# merge into the existing directory, keeping its permissions,
# the source may be read-only so make it writable
os.chmod(path, 0o700)
move(path, dest)
else:
# move the directory intact to preserve its permissions
if os.path.lexists(dest):
os.unlink(dest)
move_dir(path, dest)
else:
shutil.move(path, dest)
def compile_terminfo(base):
try:
tic = shutil.which('tic')
except AttributeError:
# python2
for x in os.environ.get('PATH', '').split(os.pathsep):
q = os.path.join(x, 'tic')
if os.access(q, os.X_OK) and os.path.isfile(q):
tic = q
break
else:
tic = ''
if not tic:
return
tname = '.terminfo'
q = os.path.join(base, tname, '78', 'xterm-kitty')
if not os.path.exists(q):
try:
os.makedirs(os.path.dirname(q))
except EnvironmentError as e:
if e.errno != errno.EEXIST:
raise
os.symlink('../x/xterm-kitty', q)
if os.path.exists('/usr/share/misc/terminfo.cdb'):
# NetBSD requires this
os.symlink('../../.terminfo.cdb', os.path.join(base, tname, 'x', 'xterm-kitty'))
tname += '.cdb'
os.environ['TERMINFO'] = os.path.join(HOME, tname)
p = subprocess.Popen(
[tic, '-x', '-o', os.path.join(base, tname), os.path.join(base, '.terminfo', 'kitty.terminfo')], stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
output = p.stdout.read()
rc = p.wait()
if rc != 0:
getattr(sys.stderr, 'buffer', sys.stderr).write(output)
raise SystemExit('Failed to compile the terminfo database')
def iter_base64_data(f):
global leading_data
started = 0
while True:
line = f.readline().rstrip()
if started == 0:
if line == b'KITTY_DATA_START':
started = 1
else:
leading_data += line
elif started == 1:
if line == b'OK':
started = 2
else:
raise SystemExit(line.decode('utf-8', 'replace').rstrip())
else:
if line == b'KITTY_DATA_END':
break
yield line
@contextlib.contextmanager
def temporary_directory(dir, prefix):
# tempfile.TemporaryDirectory not available in python2
tdir = tempfile.mkdtemp(dir=dir, prefix=prefix)
try:
yield tdir
finally:
make_deletable(tdir)
shutil.rmtree(tdir)
def get_data():
global data_dir, shell_integration_dir, leading_data
data = []
data = b''.join(iter_base64_data(tty_file_obj))
if leading_data:
# clear current line as it might have things echoed on it from leading_data
# because we only turn off echo in this script whereas the leading bytes could
# have been sent before the script had a chance to run
sys.stdout.write('\r\033[K')
data = base64.standard_b64decode(data)
with temporary_directory(dir=HOME, prefix='.kitty-ssh-kitten-untar-') as tdir, tarfile.open(fileobj=io.BytesIO(data)) as tf:
try:
# We have to use fully_trusted as otherwise it refuses to extract,
# for example, symlinks that point to absolute paths outside
# tdir.
tf.extractall(tdir, filter='fully_trusted')
except TypeError:
tf.extractall(tdir)
with open(tdir + '/data.sh') as f:
env_vars = f.read()
apply_env_vars(env_vars)
data_dir = os.environ.pop('KITTY_SSH_KITTEN_DATA_DIR')
if not os.path.isabs(data_dir):
data_dir = os.path.join(HOME, data_dir)
data_dir = os.path.abspath(data_dir)
shell_integration_dir = os.path.join(data_dir, 'shell-integration')
compile_terminfo(tdir + '/home')
move(tdir + '/home', HOME)
if os.path.exists(tdir + '/root'):
move(tdir + '/root', '/')
def exec_with_better_error(*a):
try:
os.execlp(*a)
except OSError as err:
if err.errno == errno.ENOENT:
raise SystemExit('The program: "' + a[0] + '" was not found')
raise
def exec_zsh_with_integration():
zdotdir = os.environ.get('ZDOTDIR') or ''
if not zdotdir:
zdotdir = HOME
os.environ.pop('KITTY_ORIG_ZDOTDIR', None) # ensure this is not propagated
else:
os.environ['KITTY_ORIG_ZDOTDIR'] = zdotdir
# dont prevent zsh-newuser-install from running
for q in ('.zshrc', '.zshenv', '.zprofile', '.zlogin'):
if os.path.exists(os.path.join(zdotdir, q)):
os.environ['ZDOTDIR'] = shell_integration_dir + '/zsh'
exec_with_better_error(login_shell, os.path.basename(login_shell), '-l')
os.environ.pop('KITTY_ORIG_ZDOTDIR', None) # ensure this is not propagated
def exec_fish_with_integration():
if not os.environ.get('XDG_DATA_DIRS'):
os.environ['XDG_DATA_DIRS'] = shell_integration_dir
else:
os.environ['XDG_DATA_DIRS'] = shell_integration_dir + ':' + os.environ['XDG_DATA_DIRS']
os.environ['KITTY_FISH_XDG_DATA_DIR'] = shell_integration_dir
exec_with_better_error(login_shell, os.path.basename(login_shell), '-l')
def exec_bash_with_integration():
os.environ['ENV'] = os.path.join(shell_integration_dir, 'bash', 'kitty.bash')
os.environ['KITTY_BASH_INJECT'] = '1'
if not os.environ.get('HISTFILE'):
os.environ['HISTFILE'] = os.path.join(HOME, '.bash_history')
os.environ['KITTY_BASH_UNEXPORT_HISTFILE'] = '1'
exec_with_better_error(login_shell, os.path.basename('login_shell'), '--posix')
def exec_with_shell_integration():
shell_name = os.path.basename(login_shell).lower()
if shell_name == 'zsh':
exec_zsh_with_integration()
if shell_name == 'fish':
exec_fish_with_integration()
if shell_name == 'bash':
exec_bash_with_integration()
def install_kitty_bootstrap():
kitty_remote = os.environ.pop('KITTY_REMOTE', '')
kitty_exists = shutil.which('kitty')
kitty_dir = os.path.join(data_dir, 'kitty', 'bin')
os.environ['SSH_KITTEN_KITTY_DIR'] = kitty_dir
if kitty_remote == 'yes' or (kitty_remote == 'if-needed' and not kitty_exists):
if kitty_exists:
os.environ['PATH'] = kitty_dir + os.pathsep + os.environ['PATH']
else:
os.environ['PATH'] = os.environ['PATH'] + os.pathsep + kitty_dir
def main():
global tty_file_obj, login_shell
# the value of O_CLOEXEC below is on macOS which is most likely to not have
# os.O_CLOEXEC being still stuck with python2
tty_file_obj = os.fdopen(os.open(os.ctermid(), os.O_RDWR | getattr(os, 'O_CLOEXEC', 16777216)), 'rb')
try:
if request_data:
set_echo(tty_file_obj.fileno(), on=False)
send_data_request()
get_data()
finally:
cleanup()
cwd = os.environ.pop('KITTY_LOGIN_CWD', '')
install_kitty_bootstrap()
if cwd:
try:
os.chdir(cwd)
except Exception as err:
print(f'Failed to change working directory to: {cwd} with error: {err}', file=sys.stderr)
ksi = frozenset(filter(None, os.environ.get('KITTY_SHELL_INTEGRATION', '').split()))
exec_cmd = b'EXEC_CMD'
if exec_cmd:
os.environ.pop('KITTY_SHELL_INTEGRATION', None)
cmd = base64.standard_b64decode(exec_cmd).decode('utf-8')
exec_with_better_error(login_shell, os.path.basename(login_shell), '-c', cmd)
remote_cmd = b'REMOTE_CMD'
if remote_cmd:
os.environ.pop('KITTY_SHELL_INTEGRATION', None)
cmd = base64.standard_b64decode(remote_cmd).decode('utf-8')
exec_with_better_error(login_shell, os.path.basename(login_shell), '-c', cmd)
TEST_SCRIPT # noqa
if ksi and 'no-rc' not in ksi:
exec_with_shell_integration()
os.environ.pop('KITTY_SHELL_INTEGRATION', None)
exec_with_better_error(login_shell, '-' + os.path.basename(login_shell))
main()
+172
View File
@@ -0,0 +1,172 @@
#!/bin/sh
# Copyright (C) 2022 Kovid Goyal <kovid at kovidgoyal.net>
# Distributed under terms of the GPLv3 license.
{ \unalias command; \unset -f command; } >/dev/null 2>&1
tdir=""
shell_integration_dir=""
echo_on="ECHO_ON"
remove_tdir() {
# copied directories can be read-only, make them deletable
command chmod -R u+rwx "$tdir" 2> /dev/null
command rm -rf "$tdir"
}
cleanup_on_bootstrap_exit() {
[ "$echo_on" = "1" ] && command stty "echo" 2> /dev/null < /dev/tty
echo_on="0"
[ -n "$tdir" ] && remove_tdir
tdir=""
}
die() {
if [ -e /dev/stderr ]; then
printf "\033[31m%s\033[m\n\r" "$*" > /dev/stderr;
elif [ -e /dev/fd/2 ]; then
printf "\033[31m%s\033[m\n\r" "$*" > /dev/fd/2;
else
printf "\033[31m%s\033[m\n\r" "$*";
fi
cleanup_on_bootstrap_exit;
exit 1;
}
python_detected="0"
detect_python() {
if [ python_detected = "1" ]; then
[ -n "$python" ] && return 0
return 1
fi
python_detected="1"
python=$(command -v python3)
[ -z "$python" ] && python=$(command -v python2)
[ -z "$python" ] && python=$(command -v python)
if [ -z "$python" -o ! -x "$python" ]; then python=""; return 1; fi
return 0
}
perl_detected="0"
detect_perl() {
if [ perl_detected = "1" ]; then
[ -n "$perl" ] && return 0
return 1
fi
perl_detected="1"
perl=$(command -v perl)
if [ -z "$perl" -o ! -x "$perl" ]; then perl=""; return 1; fi
return 0
}
if command -v base64 > /dev/null 2> /dev/null; then
base64_encode() { command base64 | command tr -d \\n\\r; }
base64_decode() { command base64 -d; }
elif command -v openssl > /dev/null 2> /dev/null; then
base64_encode() { command openssl enc -A -base64; }
base64_decode() { command openssl enc -A -d -base64; }
elif command -v b64encode > /dev/null 2> /dev/null; then
base64_encode() { command b64encode - | command sed '1d;$d' | command tr -d \\n\\r; }
base64_decode() { command fold -w 76 | command b64decode -r; }
elif detect_python; then
pybase64() { command "$python" -c "import sys, base64; getattr(sys.stdout, 'buffer', sys.stdout).write(base64.standard_b64$1(getattr(sys.stdin, 'buffer', sys.stdin).read()))"; }
base64_encode() { pybase64 "encode"; }
base64_decode() { pybase64 "decode"; }
elif detect_perl; then
base64_encode() { command "$perl" -MMIME::Base64 -0777 -ne 'print encode_base64($_)'; }
base64_decode() { command "$perl" -MMIME::Base64 -ne 'print decode_base64($_)'; }
else
die "base64 executable not present on remote host, ssh kitten cannot function."
fi
dcs_to_kitty() { printf "\033P@kitty-$1|%s\033\134" "$(printf "%s" "$2" | base64_encode)" > /dev/tty; }
debug() { dcs_to_kitty "print" "debug: $1"; }
# If $HOME is configured set it here
EXPORT_HOME_CMD
# ensure $HOME is set
[ -z "$HOME" ] && HOME=~
# ensure $USER is set
[ -z "$USER" ] && USER="$LOGNAME"
[ -z "$USER" ] && USER="$(command whoami 2> /dev/null)"
leading_data=""
login_shell=""
login_cwd=""
request_data="REQUEST_DATA"
trap "cleanup_on_bootstrap_exit" EXIT
[ "$request_data" = "1" ] && {
command stty "-echo" < /dev/tty
dcs_to_kitty "ssh" "id="REQUEST_ID":pwfile="PASSWORD_FILENAME":pw="DATA_PASSWORD""
}
read_base64_from_tty() {
while IFS= read -r line; do
[ "$line" = "KITTY_DATA_END" ] && return 0
printf "%s" "$line"
done
}
untar_and_read_env() {
# extract the tar file atomically, in the sense that any file from the
# tarfile is only put into place after it has been fully written to disk
command -v tar > /dev/null 2> /dev/null || die "tar is not available on this server. The ssh kitten requires tar."
tdir=$(command mktemp -d "$HOME/.kitty-ssh-kitten-untar-XXXXXXXXXXXX")
[ $? = 0 ] || die "Creating temp directory failed"
# suppress STDERR for tar as tar prints various warnings if for instance, timestamps are in the future
old_umask=$(umask)
umask 000
read_base64_from_tty | base64_decode | command tar "xpzf" "-" "-C" "$tdir" 2> /dev/null
umask "$old_umask"
. "$tdir/bootstrap-utils.sh"
. "$tdir/data.sh"
[ -z "$KITTY_SSH_KITTEN_DATA_DIR" ] && die "Failed to read SSH data from tty"
case "$KITTY_SSH_KITTEN_DATA_DIR" in
/*) data_dir="$KITTY_SSH_KITTEN_DATA_DIR" ;;
*) data_dir="$HOME/$KITTY_SSH_KITTEN_DATA_DIR"
esac
shell_integration_dir="$data_dir/shell-integration"
unset KITTY_SSH_KITTEN_DATA_DIR
login_shell="$KITTY_LOGIN_SHELL"
unset KITTY_LOGIN_SHELL
login_cwd="$KITTY_LOGIN_CWD"
unset KITTY_LOGIN_CWD
kitty_remote="$KITTY_REMOTE"
unset KITTY_REMOTE
compile_terminfo "$tdir/home"
mv_files_and_dirs "$tdir/home" "$HOME"
[ -e "$tdir/root" ] && mv_files_and_dirs "$tdir/root" ""
remove_tdir
tdir=""
}
get_data() {
started="n"
while IFS= read -r line; do
if [ "$started" = "y" ]; then
[ "$line" = "OK" ] && break
die "$line"
else
if [ "$line" = "KITTY_DATA_START" ]; then
started="y"
else
leading_data="$leading_data$line"
fi
fi
done
untar_and_read_env
}
# ask for the SSH data
get_data
cleanup_on_bootstrap_exit
prepare_for_exec
# If a command was passed to SSH execute it here
EXEC_CMD
REMOTE_CMD
# Used in the tests
TEST_SCRIPT
exec_login_shell
+99
View File
@@ -0,0 +1,99 @@
#!/bin/sh
# Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
#
# Distributed under terms of the GPLv3 license.
{ \unalias command; \unset -f command; } >/dev/null 2>&1
die() {
if [ -e /dev/stderr ]; then
printf "\033[31m%s\033[m\n\r" "$*" > /dev/stderr;
elif [ -e /dev/fd/2 ]; then
printf "\033[31m%s\033[m\n\r" "$*" > /dev/fd/2;
else
printf "\033[31m%s\033[m\n\r" "$*";
fi
exit 1;
}
exec_kitty() {
[ -n "$kitty_exe" ] && exec "$kitty_exe" "$@"
die "Failed to execute kitty"
}
script_path="$(command readlink -f "$0" 2> /dev/null)"
[ $? = 0 ] || script_path="$0"
script_dir="$(command dirname "$script_path")"
install_dir="$(command dirname "$script_dir")/install-tool"
remote_kitty_version_file="$script_dir/../version"
local_kitty_version_file="$install_dir/installed-kitten-version"
kitty_exe="$install_dir/kitten"
local_kitty_version=""
[ -f "$kitty_exe" -a -x "$kitty_exe" ] && exec_kitty "$@"
# Use kitten from the downloaded kitty installation, if available.
embed_exe="$(command dirname "$script_dir")/install/bin/kitten"
[ -f "$embed_exe" -a -x "$embed_exe" ] && {
kitty_exe="$embed_exe"
exec_kitty "$@"
}
# If called for shell completion with no binary available, do nothing to avoid
# downloading kitten and showing spurious output during tab completion.
[ "$1" = "__complete__" ] && exit 0
case "$(command uname)" in
'Linux') OS="linux";;
'Darwin') OS="darwin";;
'FreeBSD') OS="freebsd";;
'NetBSD') OS="netbsd";;
'OpenBSD') OS="openbsd";;
'DragonFlyBSD') OS="dragonfly";;
*) die "kitten pre-built binaries are not available for the $(command uname) operating system";;
esac
if command -v curl 2> /dev/null > /dev/null; then
fetch() {
command curl -fL "$1"
}
fetch_quiet() {
command curl -fsSL "$1"
}
elif command -v wget 2> /dev/null > /dev/null; then
fetch() {
command wget -O- "$1"
}
fetch_quiet() {
command wget --quiet -O- "$1"
}
else
die "Neither curl nor wget available, cannot download kitten"
fi
case "$(command uname -m)" in
amd64|x86_64) arch="amd64";;
aarch64*) arch="arm64";;
armv8*) arch="arm64";;
arm64) arch="arm64";;
arm|armv7l) arch="arm";;
i386) arch="386";;
i686) arch="386";;
*) die "Unknown CPU architecture $(command uname -m)";;
esac
url="https://github.com/kovidgoyal/kitty/releases/latest/download/kitten-$OS-$arch"
printf "\033[33mkitten needs to be installed\033[m\n\n"
command mkdir -p "$install_dir"
printf "Downloading kitten from: \033[32m%s\033[m\n\n" "$url"
download_dest="$(command mktemp "$kitty_exe.XXXXXXXXXX")"
fetch "$url" > "$download_dest" || {
command rm -f "$download_dest"
die "Failed to download kitten"
}
command chmod 755 "$download_dest"
command mv "$download_dest" "$kitty_exe"
command "$kitty_exe" --version | cut -d" " -f2 > "$local_kitty_version_file"
exec_kitty "$@"
+160
View File
@@ -0,0 +1,160 @@
#!/bin/sh
# Copyright (C) 2018 Kovid Goyal <kovid at kovidgoyal.net>
#
# Distributed under terms of the GPLv3 license.
{ \unalias command; \unset -f command; } >/dev/null 2>&1
die() { printf "\033[31m%s\033[m\n\r" "$*" > /dev/stderr; exit 1; }
delete_lock_dir() {
trap '' EXIT INT QUIT TERM
[ -n "$lock_dir" ] && {
command rm -rf "$lock_dir"
lock_dir=""
}
}
exec_kitty() {
delete_lock_dir
[ -n "$kitty_exe" ] && exec "$kitty_exe" "$@"
die "Failed to execute kitty"
}
has_diskutil_image() {
# hdiutil is deprecated in macOS 27
macos_major=$(command sw_vers -productVersion 2> /dev/null)
macos_major="${macos_major%%.*}"
case "$macos_major" in
''|*[!0-9]*) return 1;;
esac
[ "$macos_major" -ge 27 ]
}
mount_dmg() {
if has_diskutil_image; then
command diskutil image attach --readOnly --mountPoint "$2" "$1"
else
command hdiutil attach "$1" "-mountpoint" "$2"
fi
}
unmount_dmg() {
if has_diskutil_image; then
command diskutil eject "$1"
else
command hdiutil detach "$1"
fi
}
is_wrapped_kitten() {
wrapped_kittens="clipboard icat hyperlinked_grep ask hints unicode_input ssh themes diff show_key transfer query_terminal choose-files command-palette resize_window broadcast remote_file"
[ -n "$1" ] && {
case " $wrapped_kittens " in
*" $1 "*) printf "%s" "$1" ;;
esac
}
}
test "(" "$1" = "+kitten" -a -n "$(is_wrapped_kitten "$2")" ")" -o "(" "$1" = "+" -a "$2" = "kitten" -a "$(is_wrapped_kitten "$3")" ")" && {
if [ "$1" = "+kitten" ]; then shift "1"; else shift "2"; fi
exec kitten "$@"
}
lock_dir=""
script_path="$(command readlink -f "$0" 2> /dev/null)"
[ $? = 0 ] || script_path="$0"
script_dir="$(command dirname "$script_path")"
install_dir="$(command dirname "$script_dir")/install"
remote_kitty_version_file="$script_dir/../version"
local_kitty_version_file="$install_dir/installed-kitty-version"
kitty_exe="$install_dir/bin/kitty"
local_kitty_version=""
[ -f "$kitty_exe" -a -x "$kitty_exe" -a "$1" != "+update-kitty" ] && exec_kitty "$@"
case "$(command uname)" in
'Linux') OS="linux";;
'Darwin') OS="macos";;
*) die "kitty pre-built binaries are not available for the $(command uname) operating system";;
esac
if command -v curl 2> /dev/null > /dev/null; then
fetch() {
command curl -fL "$1"
}
fetch_quiet() {
command curl -fsSL "$1"
}
elif command -v wget 2> /dev/null > /dev/null; then
fetch() {
command wget -O- "$1"
}
fetch_quiet() {
command wget --quiet -O- "$1"
}
else
die "Neither curl nor wget available, cannot download kitty"
fi
if [ "$OS" = "linux" ]; then
case "$(command uname -m)" in
amd64|x86_64) arch="x86_64";;
aarch64*) arch="arm64";;
armv8*) arch="arm64";;
arm64) arch="arm64";;
i386) arch="i686";;
i686) arch="i686";;
*) die "Unknown CPU architecture $(command uname -m)";;
esac
fi
release_version=$(fetch_quiet "https://sw.kovidgoyal.net/kitty/current-version.txt")
[ $? -ne 0 -o -z "$release_version" ] && {
[ -n "$local_kitty_version" ] && exec_kitty "$@"
die "Could not get kitty latest release version"
}
if [ "$OS" = "linux" ]; then
url="https://github.com/kovidgoyal/kitty/releases/download/v$release_version/kitty-$release_version-$arch.txz"
else
url="https://github.com/kovidgoyal/kitty/releases/download/v$release_version/kitty-$release_version.dmg"
fi
lock_dir="$script_dir/kitty-install-lock"
if ! command mkdir "$lock_dir" 2> /dev/null; then
ed="$lock_dir"
lock_dir="";
die "Failed to create lock dir another instance of the kitty bootstrap script is running. If you are sure that is not the case delete: $ed";
fi
trap 'delete_lock_dir' EXIT INT QUIT TERM
printf "\033[33mkitty needs to be installed\033[m\n\n"
command rm -rf "$install_dir"
command mkdir -p "$install_dir"
printf "Downloading kitty from: \033[32m%s\033[m\n\n" "$url"
if [ "$OS" = "linux" ]; then
old_umask=$(umask)
umask 000
fetch "$url" | command tar -C "$install_dir" -xJof -
umask "$old_umask"
[ $? = 0 ] || die "Failed to download and install kitty"
else
tdir=$(command mktemp -d "$install_dir/tmp-for-dmg-XXXXXXXXXXXX")
[ $? = 0 ] || die "Creating temp directory failed"
fetch "$url" > "$tdir/kitty.dmg"
command mkdir "$tdir/mp"
mount_dmg "$tdir/kitty.dmg" "$tdir/mp" || die "Failed to mount kitty.dmg"
command ditto -v "$tdir/mp/kitty.app" "$install_dir/kitty.app"
rc="$?"
unmount_dmg "$tdir/mp"
command rm -rf "$tdir"
[ "$rc" != "0" ] && die "Failed to copy kitty.app from mounted dmg"
command mkdir "$install_dir/bin"
command ln -sf "$install_dir/kitty.app/Contents/MacOS/kitty" "$install_dir/bin/kitty"
fi
command "$kitty_exe" +runpy "from kitty.constants import str_version; print(end=str_version)" > "$local_kitty_version_file"
exec_kitty "$@"