mirror of
https://github.com/kovidgoyal/kitty.git
synced 2026-11-17 21:54:03 +00:00
Transfer kitten: Clearer errors when the destination is a directory
Refuse to replace an existing directory, or a symlink to a directory, with a file, reporting EISDIR before any data is transferred instead of a raw OSError (or silently replacing the symlink). Report failures to create parent directories with the actual errno and directory name. When a send fails, the kitten now prints hints for the common causes: a missing trailing slash on a directory destination and a ~ expanded by the shell on the remote machine. Fixes #8118 Closes #10710
This commit is contained in:
parent
d4d75646bd
commit
05d3ee35ff
4 changed files with 135 additions and 3 deletions
|
|
@ -1195,7 +1195,32 @@ func (self *SendHandler) on_interrupt() {
|
|||
self.abort_transfer()
|
||||
}
|
||||
|
||||
func send_loop(opts *Options, files []*File) (err error, rc int) {
|
||||
// failure_hints returns suggestions for common mistakes that can cause
|
||||
// transfers to fail, based on the command line arguments.
|
||||
func failure_hints(opts *Options, args []string, failed_files []*File) (ans []string) {
|
||||
if opts.Mode == "mirror" || len(args) < 2 || len(failed_files) == 0 {
|
||||
return
|
||||
}
|
||||
dest := filepath.ToSlash(args[len(args)-1])
|
||||
if len(args) == 2 && !strings.HasSuffix(dest, "/") {
|
||||
for _, f := range failed_files {
|
||||
if f.remote_path == dest && strings.HasPrefix(f.err_msg, "EISDIR:") {
|
||||
ans = append(ans, fmt.Sprintf("To transfer into the directory %s add a trailing slash, for example: %s/", dest, dest))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
home := filepath.ToSlash(strings.TrimRight(home_path(), string(filepath.Separator)))
|
||||
if home != "" && (dest == home || strings.HasPrefix(dest, home+"/")) {
|
||||
suggestion := "\\~" + strings.TrimPrefix(dest, home)
|
||||
ans = append(ans, fmt.Sprintf(
|
||||
"The destination %s is in the home directory of the computer this kitten is running on, probably because your shell expanded ~ before running the kitten. "+
|
||||
"To refer to the home directory of the computer kitty is running on, escape the ~, for example: %s", dest, suggestion))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func send_loop(opts *Options, args []string, files []*File) (err error, rc int) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors)
|
||||
if err != nil {
|
||||
return err, 1
|
||||
|
|
@ -1266,6 +1291,10 @@ func send_loop(opts *Options, files []*File) (err error, rc int) {
|
|||
fmt.Println(handler.ctx.BrightRed(f.display_name))
|
||||
fmt.Println(` `, f.err_msg)
|
||||
}
|
||||
for _, hint := range failure_hints(opts, args, handler.failed_files) {
|
||||
fmt.Println()
|
||||
fmt.Println(handler.ctx.Yellow("Hint:"), hint)
|
||||
}
|
||||
rc = 1
|
||||
}
|
||||
if lp.ExitCode() != 0 {
|
||||
|
|
@ -1282,7 +1311,7 @@ func send_main(opts *Options, args []string) (err error, rc int) {
|
|||
}
|
||||
fmt.Printf("Found %d files and directories, requesting transfer permission…", len(files))
|
||||
fmt.Println()
|
||||
err, rc = send_loop(opts, files)
|
||||
err, rc = send_loop(opts, args, files)
|
||||
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -100,3 +100,31 @@ func TestPathMappingSend(t *testing.T) {
|
|||
ae(f.file_type, FileType_link)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSendFailureHints(t *testing.T) {
|
||||
opts := &Options{}
|
||||
home := filepath.ToSlash(home_path())
|
||||
eisdir := func(remote_path string) *File {
|
||||
return &File{remote_path: remote_path, err_msg: "EISDIR:Cannot replace the existing directory x with a file"}
|
||||
}
|
||||
th := func(args []string, failed []*File, expected ...string) {
|
||||
t.Helper()
|
||||
actual := failure_hints(opts, args, failed)
|
||||
if len(actual) != len(expected) {
|
||||
t.Fatalf("Unexpected hints for %#v: %#v", args, actual)
|
||||
}
|
||||
for i, e := range expected {
|
||||
if !strings.Contains(actual[i], e) {
|
||||
t.Fatalf("Hint %#v does not contain %#v", actual[i], e)
|
||||
}
|
||||
}
|
||||
}
|
||||
th([]string{"a", "/x/d"}, nil)
|
||||
th([]string{"a", "/x/d"}, []*File{eisdir("/x/d")}, "trailing slash, for example: /x/d/")
|
||||
th([]string{"a", "/x/d/"}, []*File{eisdir("/x/d/a")})
|
||||
th([]string{"a", "b", "/x/d"}, []*File{eisdir("/x/d/a")})
|
||||
th([]string{"a", home + "/Downloads"}, []*File{{remote_path: home + "/Downloads", err_msg: "ENOTSUP:x"}}, `\~/Downloads`)
|
||||
th([]string{"a", home + "/Downloads"}, []*File{eisdir(home + "/Downloads")}, "trailing slash", `\~/Downloads`)
|
||||
opts.Mode = "mirror"
|
||||
th([]string{"a", "/x/d"}, []*File{eisdir("/x/d")})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -498,10 +498,28 @@ class DestFile:
|
|||
self.actual_file.close()
|
||||
self.actual_file = None
|
||||
|
||||
def check_destination(self) -> None:
|
||||
if self.ftype is FileType.directory or self.existing_stat is None:
|
||||
return
|
||||
is_dir = stat.S_ISDIR(self.existing_stat.st_mode)
|
||||
if not is_dir and self.ftype is FileType.regular and stat.S_ISLNK(self.existing_stat.st_mode):
|
||||
# Replacing a symlink to a directory with a regular file is almost
|
||||
# certainly not what the user intended, so refuse. Symlinks and
|
||||
# hard links are still allowed to replace such symlinks.
|
||||
with suppress(OSError):
|
||||
is_dir = stat.S_ISDIR(os.stat(self.name).st_mode)
|
||||
if is_dir:
|
||||
raise TransmissionError(code=ErrorCode.EISDIR, file_id=self.file_id, msg=f'Cannot replace the existing directory {self.name} with a file')
|
||||
|
||||
def make_parent_dirs(self) -> str:
|
||||
d = os.path.dirname(self.name)
|
||||
if d:
|
||||
os.makedirs(d, exist_ok=True)
|
||||
try:
|
||||
os.makedirs(d, exist_ok=True)
|
||||
except OSError as err:
|
||||
code = errno.errorcode.get(err.errno, 'EFAIL') if err.errno is not None else 'EFAIL'
|
||||
path = err.filename if isinstance(err.filename, str) else d
|
||||
raise TransmissionError(code=code, file_id=self.file_id, msg=f'Failed to create the directory {path}: {err.strerror or err}') from err
|
||||
return d
|
||||
|
||||
def apply_metadata(self, is_symlink: bool = False) -> None:
|
||||
|
|
@ -641,6 +659,13 @@ class ActiveReceive:
|
|||
file_id=ftc.file_id,
|
||||
)
|
||||
self.files[ftc.file_id] = df = DestFile(ftc)
|
||||
try:
|
||||
df.check_destination()
|
||||
except TransmissionError:
|
||||
# keep the file registered so that any data sent for it is discarded
|
||||
df.failed = True
|
||||
df.close()
|
||||
raise
|
||||
return df
|
||||
|
||||
def add_data(self, ftc: FileTransmissionCommand) -> DestFile:
|
||||
|
|
|
|||
|
|
@ -340,6 +340,56 @@ class TestFileTransmission(BaseTest):
|
|||
self.assertPathEqual(os.path.dirname(tf.name), base)
|
||||
os.remove(tf.name)
|
||||
|
||||
def test_file_put_existing_directory(self):
|
||||
def start_receiving():
|
||||
ft = FileTransmission()
|
||||
ft.handle_serialized_command(serialized_cmd(action='send'))
|
||||
ft.test_responses = []
|
||||
return ft
|
||||
|
||||
def statuses(ft):
|
||||
return [r['status'] for r in ft.test_responses if r.get('action') == 'status']
|
||||
|
||||
base = os.path.join(self.tdir, 'existing')
|
||||
dest_dir = os.path.join(base, 'dir')
|
||||
os.makedirs(os.path.join(dest_dir, 'child'))
|
||||
dir_link = os.path.join(base, 'dir_link')
|
||||
os.symlink(dest_dir, dir_link)
|
||||
|
||||
# a regular file must not replace an existing directory or a symlink
|
||||
# to one, and data sent for it must be silently discarded
|
||||
for dest in (dest_dir, dir_link):
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='f', name=dest, ftype='regular'))
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='f', data='xyz'))
|
||||
self.ae(statuses(ft), [f'EISDIR:Cannot replace the existing directory {dest} with a file'])
|
||||
self.assertTrue(os.path.isdir(dest))
|
||||
self.assertTrue(os.path.islink(dir_link))
|
||||
self.ae(set(names_in(dest_dir)), {'child'})
|
||||
|
||||
# a symlink must not replace an existing directory
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='s', name=dest_dir, ftype='symlink'))
|
||||
self.ae(statuses(ft), [f'EISDIR:Cannot replace the existing directory {dest_dir} with a file'])
|
||||
self.assertTrue(os.path.isdir(dest_dir))
|
||||
|
||||
# but it may replace a symlink to a directory
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='s', name=dir_link, ftype='symlink'))
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='s', data='path:elsewhere'))
|
||||
self.ae(statuses(ft)[-1], 'OK')
|
||||
self.ae(os.readlink(dir_link), 'elsewhere')
|
||||
|
||||
# failure to create parent directories gives a clear error
|
||||
blocker = os.path.join(base, 'blocker')
|
||||
with open(blocker, 'w'):
|
||||
pass
|
||||
dest = os.path.join(blocker, 'sub', 'f')
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='f', name=dest, ftype='regular'))
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='f', data='xyz'))
|
||||
self.ae(statuses(ft), ['STARTED', f'ENOTDIR:Failed to create the directory {os.path.dirname(dest)}: Not a directory'])
|
||||
|
||||
def test_file_get(self):
|
||||
# send refusal
|
||||
for quiet in (0, 1, 2):
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue