From aa373084bf55917eea564363f7d83096286bd849 Mon Sep 17 00:00:00 2001 From: Bilal Amarni Date: Wed, 22 Apr 2020 11:09:41 +0200 Subject: [PATCH] [kubectl] Fail when local source file doesn't exist When trying to upload an unexisting file to a pod, kubectl currently doesn't print any error message and terminates with a zero exit code. This adds a check and fails explicitly in such cases. Kubernetes-commit: 3fa5b504423f169723b911547cd22ae85da168e0 --- pkg/cmd/cp/cp.go | 8 ++++---- pkg/cmd/cp/cp_test.go | 11 ++++++++++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/pkg/cmd/cp/cp.go b/pkg/cmd/cp/cp.go index 605f36dda..7790db531 100644 --- a/pkg/cmd/cp/cp.go +++ b/pkg/cmd/cp/cp.go @@ -203,10 +203,7 @@ func (o *CopyOptions) Run(args []string) error { } if len(srcSpec.PodName) != 0 && len(destSpec.PodName) != 0 { - if _, err := os.Stat(args[0]); err == nil { - return o.copyToPod(fileSpec{File: args[0]}, destSpec, &exec.ExecOptions{}) - } - return fmt.Errorf("src doesn't exist in local filesystem") + return fmt.Errorf("one of src or dest must be a local file specification") } if len(srcSpec.PodName) != 0 { @@ -245,6 +242,9 @@ func (o *CopyOptions) copyToPod(src, dest fileSpec, options *exec.ExecOptions) e if len(src.File) == 0 || len(dest.File) == 0 { return errFileCannotBeEmpty } + if _, err := os.Stat(src.File); err != nil { + return fmt.Errorf("%s doesn't exist in local filesystem", src.File) + } reader, writer := io.Pipe() // strip trailing slash (if any) diff --git a/pkg/cmd/cp/cp_test.go b/pkg/cmd/cp/cp_test.go index e7ada179b..9af5c92e7 100644 --- a/pkg/cmd/cp/cp_test.go +++ b/pkg/cmd/cp/cp_test.go @@ -576,27 +576,36 @@ func TestCopyToPod(t *testing.T) { defer os.RemoveAll(srcFile) tests := map[string]struct { + src string dest string expectedErr bool }{ "copy to directory": { + src: srcFile, dest: "/tmp/", expectedErr: false, }, "copy to root": { + src: srcFile, dest: "/", expectedErr: false, }, "copy to empty file name": { + src: srcFile, dest: "", expectedErr: true, }, + "copy unexisting file": { + src: path.Join(srcFile, "nope"), + dest: "/tmp", + expectedErr: true, + }, } for name, test := range tests { opts := NewCopyOptions(ioStreams) src := fileSpec{ - File: srcFile, + File: test.src, } dest := fileSpec{ PodNamespace: "pod-ns",