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:
commit
7e7d249099
1134 files changed
+433629
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,216 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package remote_file
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
)
|
||||
|
||||
type ControlMaster struct {
|
||||
conn *SSHConnectionData
|
||||
remote_path string
|
||||
tdir string
|
||||
keep_local_copy bool
|
||||
Dest string
|
||||
LastErrorLog string
|
||||
}
|
||||
|
||||
func new_control_master(conn *SSHConnectionData, remote_path, dest string) *ControlMaster {
|
||||
return &ControlMaster{conn: conn, remote_path: remote_path, Dest: dest}
|
||||
}
|
||||
|
||||
func (m *ControlMaster) check_call(argv []string) error {
|
||||
cmd := exec.Command(argv[0], argv[1:]...)
|
||||
cmd.Stdin = nil
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("the ssh command: %s failed: %w with output: %s", strings.Join(argv, " "), err, string(out))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ControlMaster) Start() (err error) {
|
||||
if !m.conn.IsSSHKitten {
|
||||
if err = m.check_call(append(m.conn.cmd_prefix(), "-o", "ControlMaster=auto", "-fN", m.conn.Hostname)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = m.check_call(append(m.conn.batch_cmd_prefix(), "-O", "check", m.conn.Hostname)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if m.Dest == "" {
|
||||
if m.tdir, err = os.MkdirTemp("", "kitty-remote-file"); err != nil {
|
||||
return err
|
||||
}
|
||||
m.Dest = filepath.Join(m.tdir, filepath.Base(m.remote_path))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ControlMaster) Close() {
|
||||
if !m.conn.IsSSHKitten {
|
||||
argv := append(m.conn.batch_cmd_prefix(), "-O", "exit", m.conn.Hostname)
|
||||
cmd := exec.Command(argv[0], argv[1:]...)
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = nil, nil, nil
|
||||
_ = cmd.Run()
|
||||
}
|
||||
if m.tdir != "" && !m.keep_local_copy {
|
||||
_ = os.RemoveAll(m.tdir)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ControlMaster) IsAlive() bool {
|
||||
if m.conn.IsSSHKitten {
|
||||
return true
|
||||
}
|
||||
argv := append(m.conn.batch_cmd_prefix(), "-O", "check", m.conn.Hostname)
|
||||
return exec.Command(argv[0], argv[1:]...).Run() == nil
|
||||
}
|
||||
|
||||
func (m *ControlMaster) Download() error {
|
||||
argv := append(m.conn.batch_cmd_prefix(), m.conn.Hostname, "cat", shlex.Quote(m.remote_path))
|
||||
f, err := os.Create(m.Dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
cmd := exec.Command(argv[0], argv[1:]...)
|
||||
cmd.Stdout = f
|
||||
var stderr strings.Builder
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
m.LastErrorLog = fmt.Sprintf("The command: %s failed\n%s", strings.Join(argv, " "), stderr.String())
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *ControlMaster) Upload(suppress_output bool) error {
|
||||
prefix := m.conn.cmd_prefix()
|
||||
if !suppress_output {
|
||||
prefix = m.conn.batch_cmd_prefix()
|
||||
}
|
||||
argv := append(prefix, m.conn.Hostname, "cat", ">", shlex.Quote(m.remote_path))
|
||||
if !suppress_output {
|
||||
fmt.Println(strings.Join(argv, " "))
|
||||
}
|
||||
f, err := os.Open(m.Dest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
cmd := exec.Command(argv[0], argv[1:]...)
|
||||
cmd.Stdin = f
|
||||
if suppress_output {
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
m.LastErrorLog = fmt.Sprintf("The command: %s failed\n%s", strings.Join(argv, " "), string(out))
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
// remote_hostname returns the remote machine's `hostname -f` output, or "" on failure.
|
||||
// Mirrors Python's check_hostname_matches: strip the combined output, split on
|
||||
// lines, drop empty lines, and take the last non-empty line.
|
||||
func (m *ControlMaster) remote_hostname() string {
|
||||
if m.conn.IsSSHKitten {
|
||||
return ""
|
||||
}
|
||||
argv := append(m.conn.batch_cmd_prefix(), m.conn.Hostname, "hostname", "-f")
|
||||
out, err := exec.Command(argv[0], argv[1:]...).Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
last := ""
|
||||
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line != "" {
|
||||
last = line
|
||||
}
|
||||
}
|
||||
return last
|
||||
}
|
||||
|
||||
// get_editor mirrors kitty/utils.py:get_editor_from_env_vars: check $VISUAL then
|
||||
// $EDITOR (shlex-split), then fall back to the first available editor from the
|
||||
// exact candidate list used there, defaulting to "vim" if none are found on PATH.
|
||||
func get_editor() []string {
|
||||
for _, env := range []string{"VISUAL", "EDITOR"} {
|
||||
if v := os.Getenv(env); v != "" {
|
||||
if parts, err := shlex.Split(v); err == nil && len(parts) > 0 {
|
||||
return parts
|
||||
}
|
||||
}
|
||||
}
|
||||
// Exact candidate list from kitty/utils.py get_editor_from_env_vars.
|
||||
for _, e := range []string{"vim", "nvim", "vi", "emacs", "hx", "kak", "micro", "nano", "vis"} {
|
||||
if p, err := exec.LookPath(e); err == nil {
|
||||
return []string{p}
|
||||
}
|
||||
}
|
||||
return []string{"vim"}
|
||||
}
|
||||
|
||||
// edit_and_upload runs the edit loop and, if the final upload fails after the
|
||||
// editor was started, keeps the local copy so the user's edits are not lost.
|
||||
func edit_and_upload(master *ControlMaster, editor []string) error {
|
||||
editor_started, err := edit_loop(master, editor)
|
||||
if err != nil && editor_started {
|
||||
master.keep_local_copy = true
|
||||
return fmt.Errorf("%w\nYour edited file is saved at: %s", err, master.Dest)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// edit_loop returns whether the editor was started, so callers can tell
|
||||
// failures before editing from failures to upload the edits.
|
||||
func edit_loop(master *ControlMaster, editor []string) (editor_started bool, err error) {
|
||||
st, err := os.Stat(master.Dest)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
mtime := st.ModTime()
|
||||
// Mirrors main.py handle_action's edit branch: reset the terminal (clear
|
||||
// whatever the ask-menu/hostname-prompt phases drew) right before handing
|
||||
// the screen to the user's $EDITOR, and again once it exits.
|
||||
reset_terminal()
|
||||
argv := append(append([]string{}, editor...), master.Dest)
|
||||
cmd := exec.Command(argv[0], argv[1:]...)
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
if err := cmd.Start(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
reset_terminal()
|
||||
if master.IsAlive() {
|
||||
if err := master.Upload(false); err != nil {
|
||||
return true, fmt.Errorf("failed to upload %s: %w", master.remote_path, err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
return true, fmt.Errorf("failed to upload %s, SSH master process died", master.remote_path)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
if st, err := os.Stat(master.Dest); err == nil && st.ModTime().After(mtime) {
|
||||
mtime = st.ModTime()
|
||||
if master.IsAlive() {
|
||||
_ = master.Upload(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package remote_file
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/kittens/choose_files"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/readline"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
// reset_terminal performs a full terminal reset (RIS), exactly mirroring
|
||||
// kittens/tui/operations.py:reset_terminal()'s escape sequence
|
||||
// ('\033]\033\\\033c'). Python's remote_file calls this between UI phases
|
||||
// (after the ask menu, around hostname-mismatch prompts, around the
|
||||
// overwrite-prompt, and around the $EDITOR invocation) to clear whatever was
|
||||
// drawn by the previous phase/loop before drawing the next; we mirror those
|
||||
// call sites exactly so the two implementations look the same on screen.
|
||||
// It is a no-op when stdout is not a terminal, for example when output is
|
||||
// piped or captured by tests.
|
||||
func reset_terminal() {
|
||||
if tty.IsTerminal(os.Stdout.Fd()) {
|
||||
fmt.Print("\x1b]\x1b\\\x1bc")
|
||||
}
|
||||
}
|
||||
|
||||
// get_key_press shows `draw` and waits for one of the runes in allowed.
|
||||
// Returns deflt on Esc/Ctrl+C. Mirrors kittens/tui/utils.py:get_key_press.
|
||||
func get_key_press(draw func(lp *loop.Loop, ctx *markup.Context), allowed, deflt string) (ans string, err error) {
|
||||
lp, err := loop.NewForSimpleInteraction()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ctx := markup.New(true)
|
||||
ans = deflt
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
draw(lp, ctx)
|
||||
return "", nil
|
||||
}
|
||||
lp.OnText = func(text string, from_key_event, in_bracketed_paste bool) error {
|
||||
text = strings.ToLower(text)
|
||||
if allowed != "" && strings.Contains(allowed, text) {
|
||||
ans = text
|
||||
lp.Quit(0)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
lp.OnKeyEvent = func(e *loop.KeyEvent) error {
|
||||
if e.MatchesPressOrRepeat("esc") || e.MatchesPressOrRepeat("ctrl+c") {
|
||||
e.Handled = true
|
||||
lp.Quit(1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err = lp.Run()
|
||||
lp.KillIfSignalled()
|
||||
return ans, err
|
||||
}
|
||||
|
||||
// wait_for_any_key blocks until the user presses any single key. Unlike
|
||||
// get_key_press it does not filter by an allowed set, matching Python's
|
||||
// show_error which breaks on the first byte read regardless of its value.
|
||||
func wait_for_any_key() error {
|
||||
lp, err := loop.NewForSimpleInteraction()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
return "", nil
|
||||
}
|
||||
lp.OnText = func(text string, from_key_event, in_bracketed_paste bool) error {
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
lp.OnKeyEvent = func(e *loop.KeyEvent) error {
|
||||
e.Handled = true
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
err = lp.Run()
|
||||
lp.KillIfSignalled()
|
||||
return err
|
||||
}
|
||||
|
||||
func show_error(msg string) {
|
||||
ctx := markup.New(true)
|
||||
fmt.Fprintln(os.Stderr, ctx.Err(msg))
|
||||
fmt.Println()
|
||||
fmt.Println("Press any key to quit")
|
||||
_ = wait_for_any_key()
|
||||
}
|
||||
|
||||
func ask_action(opts *Options) (string, error) {
|
||||
draw := func(lp *loop.Loop, ctx *markup.Context) {
|
||||
hostname := opts.Hostname
|
||||
if hostname == "" {
|
||||
hostname = "unknown"
|
||||
}
|
||||
lp.Println("What would you like to do with the remote file on " + ctx.Magenta(hostname) + ":")
|
||||
lp.Println(ctx.Yellow(opts.Path))
|
||||
lp.Println()
|
||||
lp.Println(ctx.Green("E") + "dit the file")
|
||||
lp.Println(lp.SprintStyled("dim", "The file will be downloaded and opened in an editor. Any changes you save will be automatically sent back to the remote machine"))
|
||||
lp.Println()
|
||||
lp.Println(ctx.Green("O") + "pen the file")
|
||||
lp.Println(lp.SprintStyled("dim", "The file will be downloaded and opened by the default open program"))
|
||||
lp.Println()
|
||||
lp.Println(ctx.Green("S") + "ave the file")
|
||||
lp.Println(lp.SprintStyled("dim", "The file will be downloaded to a destination you select"))
|
||||
lp.Println()
|
||||
lp.Println(ctx.Green("C") + "ancel")
|
||||
}
|
||||
response, err := get_key_press(draw, "ceos", "c")
|
||||
if err != nil {
|
||||
return "cancel", err
|
||||
}
|
||||
return map[string]string{"e": "edit", "o": "open", "s": "save"}[response], nil
|
||||
}
|
||||
|
||||
// check_hostname_matches prompts the user when the remote hostname does not
|
||||
// match the hyperlink hostname; mirrors main.py ControlMaster.check_hostname_matches.
|
||||
func check_hostname_matches(master *ControlMaster, cli_hostname string) (bool, error) {
|
||||
if master.conn.IsSSHKitten {
|
||||
return true, nil
|
||||
}
|
||||
q := master.remote_hostname()
|
||||
if q == "" || hostname_matches(cli_hostname, q) {
|
||||
return true, nil
|
||||
}
|
||||
reset_terminal()
|
||||
draw := func(lp *loop.Loop, ctx *markup.Context) {
|
||||
lp.Println("The remote hostname " + ctx.Green(q) + " does not match the")
|
||||
lp.Println("hostname in the hyperlink " + ctx.Err(cli_hostname))
|
||||
lp.Println("This indicates that kitty has not connected to the correct remote machine.")
|
||||
lp.Println("This can happen, for example, when using nested SSH sessions.")
|
||||
lp.Printf("The hostname kitty used to connect was: %s", ctx.Yellow(master.conn.Hostname))
|
||||
if master.conn.Port > 0 {
|
||||
lp.Printf(" with port: %d", master.conn.Port)
|
||||
}
|
||||
lp.Println()
|
||||
lp.Println()
|
||||
lp.Println("Do you want to continue anyway?")
|
||||
lp.Println(ctx.Green("Y") + "es\t" + ctx.Err("N") + "o")
|
||||
}
|
||||
response, err := get_key_press(draw, "yn", "n")
|
||||
reset_terminal()
|
||||
return response == "y", err
|
||||
}
|
||||
|
||||
// get_save_path reads a single line of input for the destination path,
|
||||
// with filename tab-completion, mirroring kittens/tui/path_completer.py's
|
||||
// PathCompleter/get_path. aborted is true on Ctrl+C/EOF, matching Python's
|
||||
// catch of KeyboardInterrupt/EOFError in save_as.
|
||||
func get_save_path(prompt string) (result string, aborted bool, err error) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
rl := readline.New(lp, readline.RlInit{Prompt: prompt, Completer: choose_files.FilePromptCompleter(nil)})
|
||||
lp.OnInitialize = func() (string, error) { rl.Start(); return "", nil }
|
||||
lp.OnFinalize = func() string { rl.End(); return "" }
|
||||
lp.OnResumeFromStop = func() error { rl.Start(); return nil }
|
||||
lp.OnResize = rl.OnResize
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") {
|
||||
aborted = true
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
kerr := rl.OnKeyEvent(event)
|
||||
if kerr != nil {
|
||||
if kerr == io.EOF {
|
||||
aborted = true
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
if kerr == readline.ErrAcceptInput {
|
||||
result = rl.AllText()
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
return kerr
|
||||
}
|
||||
if event.Handled {
|
||||
rl.Redraw()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
lp.OnText = func(text string, from_key_event, in_bracketed_paste bool) error {
|
||||
terr := rl.OnText(text, from_key_event, in_bracketed_paste)
|
||||
if terr == nil {
|
||||
rl.Redraw()
|
||||
}
|
||||
return terr
|
||||
}
|
||||
err = lp.Run()
|
||||
rl.Shutdown()
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if ds := lp.DeathSignalName(); ds != "" {
|
||||
return "", false, fmt.Errorf("killed by signal: %s", ds)
|
||||
}
|
||||
return result, aborted, nil
|
||||
}
|
||||
|
||||
func master_show_error(m *ControlMaster, msg string) {
|
||||
if m.LastErrorLog != "" {
|
||||
fmt.Fprintln(os.Stderr, m.LastErrorLog)
|
||||
m.LastErrorLog = ""
|
||||
}
|
||||
show_error(msg)
|
||||
}
|
||||
|
||||
// save_as mirrors main.py:save_as. hostname is the CLI --hostname value used
|
||||
// by check_hostname_matches.
|
||||
func save_as(conn *SSHConnectionData, remote_path, hostname string) error {
|
||||
ddir := utils.CacheDir()
|
||||
if err := os.MkdirAll(ddir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
last_used_store := filepath.Join(ddir, "remote-file-last-used.txt")
|
||||
last_used_path := os.TempDir()
|
||||
if b, err := os.ReadFile(last_used_store); err == nil {
|
||||
last_used_path = string(b)
|
||||
}
|
||||
last_used_file := filepath.Join(last_used_path, filepath.Base(remote_path))
|
||||
ctx := markup.New(true)
|
||||
fmt.Println("Where do you want to save the file? Leaving it blank will save it as:", ctx.Yellow(last_used_file))
|
||||
cwd, _ := os.Getwd()
|
||||
fmt.Println("Relative paths will be resolved from:", ctx.Bold(cwd))
|
||||
fmt.Println()
|
||||
|
||||
dest, aborted, err := get_save_path("> ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if aborted {
|
||||
return nil
|
||||
}
|
||||
if dest != "" {
|
||||
dest = utils.Expanduser(os.ExpandEnv(dest))
|
||||
if st, err := os.Stat(dest); err == nil && st.IsDir() {
|
||||
dest = filepath.Join(dest, filepath.Base(remote_path))
|
||||
}
|
||||
if abs, err := filepath.Abs(dest); err == nil {
|
||||
_ = os.WriteFile(last_used_store, []byte(filepath.Dir(abs)), 0o644)
|
||||
dest = abs
|
||||
}
|
||||
} else {
|
||||
dest = last_used_file
|
||||
}
|
||||
if _, err := os.Stat(dest); err == nil {
|
||||
reset_terminal()
|
||||
draw := func(lp *loop.Loop, mctx *markup.Context) {
|
||||
lp.Println("The file " + mctx.Yellow(dest) + " already exists. What would you like to do?")
|
||||
lp.Println(mctx.Green("O") + "verwrite " + mctx.Green("A") + "bort Auto " + mctx.Green("R") + "ename " + mctx.Green("N") + "ew name")
|
||||
}
|
||||
response, err := get_key_press(draw, "anor", "a")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch response {
|
||||
case "a":
|
||||
return nil
|
||||
case "n":
|
||||
reset_terminal()
|
||||
return save_as(conn, remote_path, hostname)
|
||||
case "r":
|
||||
dest = auto_rename_dest(dest, func(p string) bool { _, err := os.Stat(p); return err == nil })
|
||||
}
|
||||
}
|
||||
if d := filepath.Dir(dest); d != "" {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
master := new_control_master(conn, remote_path, dest)
|
||||
if err := master.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer master.Close()
|
||||
ok, err := check_hostname_matches(master, hostname)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if err := master.Download(); err != nil {
|
||||
master_show_error(master, "Failed to copy file from remote machine")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// handle_action returns the path to open locally (for the "open" action) or "".
|
||||
func handle_action(action string, opts *Options) (result string, err error) {
|
||||
conn, err := parse_conn_data(opts.SshConnectionData)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
remote_path := opts.Path
|
||||
switch action {
|
||||
case "open":
|
||||
fmt.Println("Opening", opts.Path, "from", opts.Hostname)
|
||||
tdir, err := os.MkdirTemp("", "kitty-remote-file")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dest := filepath.Join(tdir, filepath.Base(remote_path))
|
||||
master := new_control_master(conn, remote_path, dest)
|
||||
if err := master.Start(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer master.Close()
|
||||
ok, err := check_hostname_matches(master, opts.Hostname)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !ok {
|
||||
return "", nil
|
||||
}
|
||||
if err := master.Download(); err != nil {
|
||||
master_show_error(master, "Failed to copy file from remote machine")
|
||||
return "", nil
|
||||
}
|
||||
return dest, nil
|
||||
case "edit":
|
||||
fmt.Println("Editing", opts.Path, "from", opts.Hostname)
|
||||
master := new_control_master(conn, remote_path, "")
|
||||
if err := master.Start(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer master.Close()
|
||||
ok, err := check_hostname_matches(master, opts.Hostname)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !ok {
|
||||
return "", nil
|
||||
}
|
||||
if err := master.Download(); err != nil {
|
||||
master_show_error(master, "Failed to download "+remote_path)
|
||||
return "", nil
|
||||
}
|
||||
if err := edit_and_upload(master, get_editor()); err != nil {
|
||||
master_show_error(master, err.Error())
|
||||
}
|
||||
case "save":
|
||||
fmt.Println("Saving", opts.Path, "from", opts.Hostname)
|
||||
if err := save_as(conn, remote_path, opts.Hostname); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
action := opts.Mode
|
||||
if action == "ask" {
|
||||
action, err = ask_action(opts)
|
||||
reset_terminal()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
}
|
||||
if action == "" || action == "cancel" {
|
||||
return 0, nil
|
||||
}
|
||||
result, err := handle_action(action, opts)
|
||||
if err != nil {
|
||||
reset_terminal()
|
||||
show_error(err.Error())
|
||||
return 1, nil
|
||||
}
|
||||
if result != "" {
|
||||
serialized, err := tui.KittenOutputSerializer()(result)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
os.Stdout.WriteString(serialized)
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, main)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
from kitty.typing_compat import BossType
|
||||
from kitty.utils import command_for_open, open_cmd
|
||||
|
||||
from ..tui.handler import result_handler
|
||||
|
||||
# Must match kittens/remote_file/ssh.go is_ssh_kitten_sentinel. Kept importable
|
||||
# here because kitty/window.py:handle_remote_file imports it directly.
|
||||
is_ssh_kitten_sentinel = '!#*&$#($ssh-kitten)(##$'
|
||||
|
||||
|
||||
def option_text() -> str:
|
||||
# The -h short alias was intentionally dropped from --hostname below:
|
||||
# Go's cli reserves -h for --help, and the only caller (internal to
|
||||
# kitty) uses the long --hostname form.
|
||||
return """\
|
||||
--mode -m
|
||||
choices=ask,edit
|
||||
default=ask
|
||||
Which mode to operate in.
|
||||
|
||||
|
||||
--path -p
|
||||
Path to the remote file.
|
||||
|
||||
|
||||
--hostname
|
||||
Hostname of the remote host.
|
||||
|
||||
|
||||
--ssh-connection-data
|
||||
The data used to connect over ssh.
|
||||
"""
|
||||
|
||||
|
||||
def main(args: list[str]) -> None:
|
||||
raise SystemExit('This should be run as kitten remote_file')
|
||||
|
||||
|
||||
@result_handler()
|
||||
def handle_result(args: list[str], data: str | None, target_window_id: int, boss: BossType) -> None:
|
||||
if data:
|
||||
from kitty.fast_data_types import get_options
|
||||
|
||||
cmd = command_for_open(get_options().open_url_with)
|
||||
open_cmd(cmd, data)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
elif __name__ == '__doc__':
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = ''
|
||||
cd['options'] = option_text
|
||||
cd['help_text'] = 'Ask the user what to do with the remote file. For internal use by kitty, do not run it directly.'
|
||||
cd['short_desc'] = 'Handle remote files'
|
||||
@@ -0,0 +1,149 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package remote_file
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Must match kittens/remote_file/main.py is_ssh_kitten_sentinel
|
||||
const is_ssh_kitten_sentinel = `!#*&$#($ssh-kitten)(##$`
|
||||
|
||||
type SSHConnectionData struct {
|
||||
Binary string
|
||||
Hostname string
|
||||
Port int
|
||||
IdentityFile string
|
||||
IsSSHKitten bool
|
||||
SSHKittenCmdline []string
|
||||
}
|
||||
|
||||
func parse_conn_data(raw string) (*SSHConnectionData, error) {
|
||||
var items []any
|
||||
if err := json.Unmarshal([]byte(raw), &items); err != nil {
|
||||
return nil, fmt.Errorf("invalid --ssh-connection-data: %w", err)
|
||||
}
|
||||
if len(items) < 2 {
|
||||
return nil, fmt.Errorf("invalid --ssh-connection-data: need at least binary and hostname")
|
||||
}
|
||||
first, _ := items[0].(string)
|
||||
ans := &SSHConnectionData{}
|
||||
if first == is_ssh_kitten_sentinel {
|
||||
// Python: SSHConnectionData(sentinel, cli_data[-1], -1, identity_file=json.dumps(cli_data[1:]))
|
||||
// with the cmdline stripped of -t flags and its last two items.
|
||||
ans.IsSSHKitten = true
|
||||
ans.Hostname, _ = items[len(items)-1].(string)
|
||||
cmdline := make([]string, 0, len(items)-1)
|
||||
for _, x := range items[1:] {
|
||||
s, _ := x.(string)
|
||||
if s != "-t" {
|
||||
cmdline = append(cmdline, s)
|
||||
}
|
||||
}
|
||||
// Python: sk_cmdline[:-2] always removes last 2, or returns empty if fewer items
|
||||
if len(cmdline) >= 2 {
|
||||
cmdline = cmdline[:len(cmdline)-2]
|
||||
} else {
|
||||
cmdline = cmdline[:0]
|
||||
}
|
||||
ans.SSHKittenCmdline = cmdline
|
||||
return ans, nil
|
||||
}
|
||||
ans.Binary = first
|
||||
ans.Hostname, _ = items[1].(string)
|
||||
if len(items) > 2 {
|
||||
if p, ok := items[2].(float64); ok {
|
||||
ans.Port = int(p)
|
||||
}
|
||||
}
|
||||
if len(items) > 3 {
|
||||
ans.IdentityFile, _ = items[3].(string)
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
func (c *SSHConnectionData) cmd_prefix() []string {
|
||||
if c.IsSSHKitten {
|
||||
return append([]string{}, c.SSHKittenCmdline...)
|
||||
}
|
||||
ans := []string{
|
||||
c.Binary, "-o", fmt.Sprintf("ControlPath=~/.ssh/kitty-rf-%d-%%C", os.Getpid()),
|
||||
"-o", "TCPKeepAlive=yes", "-o", "ControlPersist=yes",
|
||||
}
|
||||
if c.Port > 0 {
|
||||
ans = append(ans, "-p", fmt.Sprint(c.Port))
|
||||
}
|
||||
if c.IdentityFile != "" {
|
||||
ans = append(ans, "-i", c.IdentityFile)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (c *SSHConnectionData) batch_cmd_prefix() []string {
|
||||
if c.IsSSHKitten {
|
||||
return c.cmd_prefix()
|
||||
}
|
||||
return append(c.cmd_prefix(), "-o", "BatchMode=yes")
|
||||
}
|
||||
|
||||
func hostname_matches(from_hyperlink, actual string) bool {
|
||||
if from_hyperlink == actual {
|
||||
return true
|
||||
}
|
||||
fl, _, _ := strings.Cut(from_hyperlink, ".")
|
||||
al, _, _ := strings.Cut(actual, ".")
|
||||
return fl == al
|
||||
}
|
||||
|
||||
// pythonSplitExt mirrors Python's os.path.splitext behavior exactly.
|
||||
// Algorithm: skip all leading dots in basename; find last dot in remainder;
|
||||
// if found, split at that dot; otherwise no extension.
|
||||
// Examples:
|
||||
//
|
||||
// "/x/.bashrc" → ("/x/.bashrc", "") [1 leading dot, no dot in remainder]
|
||||
// "/x/.bashrc.bak" → ("/x/.bashrc", ".bak") [1 leading dot, 1 dot in remainder]
|
||||
// "/x/a.b.c" → ("/x/a.b", ".c") [0 leading dots, last dot at position 3]
|
||||
// "....txt" → ("....txt", "") [4 leading dots, no dot in remainder]
|
||||
func pythonSplitExt(path string) (string, string) {
|
||||
basename := filepath.Base(path)
|
||||
dir := filepath.Dir(path)
|
||||
|
||||
// Skip all leading dots in basename
|
||||
i := 0
|
||||
for i < len(basename) && basename[i] == '.' {
|
||||
i++
|
||||
}
|
||||
|
||||
// Find the last dot in the remainder (after leading dots)
|
||||
remainder := basename[i:]
|
||||
idx := strings.LastIndex(remainder, ".")
|
||||
|
||||
if idx == -1 {
|
||||
// No extension found
|
||||
return path, ""
|
||||
}
|
||||
|
||||
// Extension starts at position i + idx in the original basename
|
||||
extStart := i + idx
|
||||
baseName := basename[:extStart]
|
||||
ext := basename[extStart:]
|
||||
|
||||
// Reconstruct the full path
|
||||
if dir == "." {
|
||||
return baseName, ext
|
||||
}
|
||||
return filepath.Join(dir, baseName), ext
|
||||
}
|
||||
|
||||
func auto_rename_dest(dest string, exists func(string) bool) string {
|
||||
q := dest
|
||||
base, ext := pythonSplitExt(dest)
|
||||
for c := 1; exists(q); c++ {
|
||||
q = fmt.Sprintf("%s-%d%s", base, c, ext)
|
||||
}
|
||||
return q
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package remote_file
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseConnData(t *testing.T) {
|
||||
c, err := parse_conn_data(`["ssh", "myhost", 2222, "/id/file"]`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Binary != "ssh" || c.Hostname != "myhost" || c.Port != 2222 || c.IdentityFile != "/id/file" || c.IsSSHKitten {
|
||||
t.Fatalf("bad conn data: %+v", c)
|
||||
}
|
||||
|
||||
c, err = parse_conn_data(`["ssh", "shorthost"]`)
|
||||
if err != nil || c.Port != 0 || c.IdentityFile != "" {
|
||||
t.Fatalf("optional fields: %+v err=%v", c, err)
|
||||
}
|
||||
|
||||
raw := fmt.Sprintf(`["%s", "kitten", "ssh", "-t", "somehost", "cmd"]`, is_ssh_kitten_sentinel)
|
||||
c, err = parse_conn_data(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !c.IsSSHKitten || c.Hostname != "cmd" || !slices.Equal(c.SSHKittenCmdline, []string{"kitten", "ssh"}) {
|
||||
t.Fatalf("ssh kitten form: %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCmdPrefixes(t *testing.T) {
|
||||
c := &SSHConnectionData{Binary: "ssh", Hostname: "h", Port: 2222, IdentityFile: "/id"}
|
||||
p := c.cmd_prefix()
|
||||
want := []string{
|
||||
"ssh", "-o", fmt.Sprintf("ControlPath=~/.ssh/kitty-rf-%d-%%C", os.Getpid()),
|
||||
"-o", "TCPKeepAlive=yes", "-o", "ControlPersist=yes", "-p", "2222", "-i", "/id",
|
||||
}
|
||||
if !slices.Equal(p, want) {
|
||||
t.Fatalf("cmd_prefix:\n got %q\nwant %q", p, want)
|
||||
}
|
||||
b := c.batch_cmd_prefix()
|
||||
if !slices.Equal(b, append(slices.Clone(want), "-o", "BatchMode=yes")) {
|
||||
t.Fatalf("batch_cmd_prefix: %q", b)
|
||||
}
|
||||
sk := &SSHConnectionData{IsSSHKitten: true, SSHKittenCmdline: []string{"kitten", "ssh"}}
|
||||
if !slices.Equal(sk.batch_cmd_prefix(), []string{"kitten", "ssh"}) {
|
||||
t.Fatalf("ssh-kitten batch prefix must not add BatchMode: %q", sk.batch_cmd_prefix())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostnameMatches(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
a, b string
|
||||
want bool
|
||||
}{
|
||||
{"foo", "foo", true},
|
||||
{"foo.example.com", "foo.local", true},
|
||||
{"foo", "bar", false},
|
||||
} {
|
||||
if hostname_matches(tc.a, tc.b) != tc.want {
|
||||
t.Fatalf("hostname_matches(%q, %q) != %v", tc.a, tc.b, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoRenameDest(t *testing.T) {
|
||||
taken := map[string]bool{"/x/a.txt": true, "/x/a-1.txt": true}
|
||||
got := auto_rename_dest("/x/a.txt", func(p string) bool { return taken[p] })
|
||||
if got != "/x/a-2.txt" {
|
||||
t.Fatalf("auto_rename_dest: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoRenameDotfile(t *testing.T) {
|
||||
taken := map[string]bool{"/x/.bashrc": true}
|
||||
got := auto_rename_dest("/x/.bashrc", func(p string) bool { return taken[p] })
|
||||
if got != "/x/.bashrc-1" {
|
||||
t.Fatalf("auto_rename_dest dotfile: got %q, want /x/.bashrc-1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConnDataSSHKittenEdge(t *testing.T) {
|
||||
// ssh-kitten with exactly 1 cmdline item after sentinel should result in empty SSHKittenCmdline
|
||||
raw := fmt.Sprintf(`["%s", "onlyitem"]`, is_ssh_kitten_sentinel)
|
||||
c, err := parse_conn_data(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !c.IsSSHKitten || c.Hostname != "onlyitem" || len(c.SSHKittenCmdline) != 0 {
|
||||
t.Fatalf("ssh kitten edge case (single item): %+v, SSHKittenCmdline=%v", c, c.SSHKittenCmdline)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPythonSplitExt(t *testing.T) {
|
||||
// Table-driven test for pythonSplitExt matching os.path.splitext semantics.
|
||||
// Expected values from Python 3: python3 -c "import os; print(os.path.splitext(f))" for each.
|
||||
// Reference run: 2026-08-12
|
||||
for _, tc := range []struct {
|
||||
input string
|
||||
wantBase string
|
||||
wantExt string
|
||||
}{
|
||||
// Dotfiles with no extension in remainder (leading dots only)
|
||||
{".bashrc", ".bashrc", ""},
|
||||
{"..bashrc", "..bashrc", ""},
|
||||
{"...", "...", ""},
|
||||
{"..", "..", ""},
|
||||
{"....txt", "....txt", ""}, // 4 leading dots, then "txt" with no dot
|
||||
|
||||
// Dotfiles with extension in remainder
|
||||
{".bashrc.bak", ".bashrc", ".bak"},
|
||||
|
||||
// Normal files
|
||||
{"a.b.c", "a.b", ".c"},
|
||||
{"a.txt", "a", ".txt"},
|
||||
{"plain", "plain", ""},
|
||||
} {
|
||||
base, ext := pythonSplitExt(tc.input)
|
||||
if base != tc.wantBase || ext != tc.wantExt {
|
||||
t.Fatalf("pythonSplitExt(%q):\n got (%q, %q)\n want (%q, %q)",
|
||||
tc.input, base, ext, tc.wantBase, tc.wantExt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteEditFinalUpload(t *testing.T) {
|
||||
const ssh_script = `#!/bin/sh
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-fN) exit 0 ;;
|
||||
check)
|
||||
if [ "$KITTY_TEST_SSH_MODE" = master-died ] && [ -f "$KITTY_TEST_EDITED_PATH" ]; then exit 255; fi
|
||||
exit 0 ;;
|
||||
exit) touch "$KITTY_TEST_SSH_CLOSED"; exit 0 ;;
|
||||
hostname) printf 'test-host\n'; exit 0 ;;
|
||||
'>')
|
||||
if [ "$KITTY_TEST_SSH_MODE" != success ]; then cat >/dev/null; exit 255; fi
|
||||
cat > "$KITTY_TEST_REMOTE_FILE"; exit $? ;;
|
||||
esac
|
||||
done
|
||||
cat "$KITTY_TEST_REMOTE_FILE"
|
||||
`
|
||||
const editor_script = `#!/bin/sh
|
||||
printf 'edited content\n' > "$1"
|
||||
printf '%s' "$1" > "$KITTY_TEST_EDITED_PATH"
|
||||
`
|
||||
for _, tc := range []struct {
|
||||
name, mode string
|
||||
ssh_kitten, editor_missing bool
|
||||
want_error, want_copy bool
|
||||
}{
|
||||
{name: "uploaded", mode: "success"},
|
||||
{name: "upload_failed", mode: "upload-failed", want_error: true, want_copy: true},
|
||||
{name: "master_died", mode: "master-died", want_error: true, want_copy: true},
|
||||
{name: "editor_start_failed", mode: "success", editor_missing: true, want_error: true},
|
||||
{name: "ssh_kitten_uploaded", mode: "success", ssh_kitten: true},
|
||||
{name: "ssh_kitten_upload_failed", mode: "upload-failed", ssh_kitten: true, want_error: true, want_copy: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
remote := filepath.Join(directory, "remote.txt")
|
||||
ssh := filepath.Join(directory, "ssh")
|
||||
editor := filepath.Join(directory, "editor")
|
||||
closed := filepath.Join(directory, "closed")
|
||||
t.Setenv("KITTY_TEST_REMOTE_FILE", remote)
|
||||
t.Setenv("KITTY_TEST_EDITED_PATH", filepath.Join(directory, "edited-path"))
|
||||
t.Setenv("KITTY_TEST_SSH_CLOSED", closed)
|
||||
t.Setenv("KITTY_TEST_SSH_MODE", tc.mode)
|
||||
for path, data := range map[string]string{remote: "original content\n", ssh: ssh_script, editor: editor_script} {
|
||||
if err := os.WriteFile(path, []byte(data), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
conn := &SSHConnectionData{Binary: ssh, Hostname: "test-host", IsSSHKitten: tc.ssh_kitten, SSHKittenCmdline: []string{ssh}}
|
||||
master := new_control_master(conn, "/remote/note with spaces.txt", "")
|
||||
if err := master.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
master.Close()
|
||||
_ = os.RemoveAll(master.tdir)
|
||||
})
|
||||
if err := master.Download(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.editor_missing {
|
||||
editor = filepath.Join(directory, "missing-editor")
|
||||
}
|
||||
err := func() error {
|
||||
defer master.Close()
|
||||
return edit_and_upload(master, []string{editor})
|
||||
}()
|
||||
if (err != nil) != tc.want_error {
|
||||
t.Fatalf("edit_loop error: %v, want error: %v", err, tc.want_error)
|
||||
}
|
||||
data, read_err := os.ReadFile(master.Dest)
|
||||
if tc.want_copy {
|
||||
if read_err != nil || string(data) != "edited content\n" {
|
||||
t.Errorf("edited copy was not retained after cleanup: %q, %v", data, read_err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), master.Dest) {
|
||||
t.Errorf("upload error does not identify the recovery path: %v", err)
|
||||
}
|
||||
} else if !os.IsNotExist(read_err) {
|
||||
t.Errorf("temporary copy was not cleaned up: %v", read_err)
|
||||
}
|
||||
data, read_err = os.ReadFile(remote)
|
||||
want := "original content\n"
|
||||
if !tc.want_error {
|
||||
want = "edited content\n"
|
||||
}
|
||||
if read_err != nil || string(data) != want {
|
||||
t.Errorf("remote contents: %q, %v, want %q", data, read_err, want)
|
||||
}
|
||||
_, close_err := os.Stat(closed)
|
||||
if !tc.ssh_kitten && close_err != nil {
|
||||
t.Error("SSH control connection was not closed:", close_err)
|
||||
} else if tc.ssh_kitten && !os.IsNotExist(close_err) {
|
||||
t.Error("borrowed ssh kitten connection was closed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user