From de0f030bcec55944dcbf81a9eec4f4d87f76567f Mon Sep 17 00:00:00 2001 From: Hong Xu Date: Thu, 8 Apr 2021 16:00:25 -0700 Subject: [PATCH] Use os.CreateTemp in kubectl editor (#99921) os.CreateTemp seems to perform the exactly same task here, and its implementation seems having considered many more edge cases than the implementation here. This patch uses os.CreateTemp here to avoid reinventing the wheel. --- .../kubectl/pkg/cmd/util/editor/editor.go | 27 +------------------ 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go b/staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go index cee99e1a670..1a31d68148d 100644 --- a/staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go +++ b/staging/src/k8s.io/kubectl/pkg/cmd/util/editor/editor.go @@ -20,7 +20,6 @@ import ( "fmt" "io" "io/ioutil" - "math/rand" "os" "os/exec" "path/filepath" @@ -142,7 +141,7 @@ func (e Editor) Launch(path string) error { // the contents of the file after launch, any errors that occur, and the path of the // temporary file so the caller can clean it up as needed. func (e Editor) LaunchTempFile(prefix, suffix string, r io.Reader) ([]byte, string, error) { - f, err := tempFile(prefix, suffix) + f, err := os.CreateTemp("", prefix+"*"+suffix) if err != nil { return nil, "", err } @@ -161,30 +160,6 @@ func (e Editor) LaunchTempFile(prefix, suffix string, r io.Reader) ([]byte, stri return bytes, path, err } -func tempFile(prefix, suffix string) (f *os.File, err error) { - dir := os.TempDir() - - for i := 0; i < 10000; i++ { - name := filepath.Join(dir, prefix+randSeq(5)+suffix) - f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if os.IsExist(err) { - continue - } - break - } - return -} - -var letters = []rune("abcdefghijklmnopqrstuvwxyz0123456789") - -func randSeq(n int) string { - b := make([]rune, n) - for i := range b { - b[i] = letters[rand.Intn(len(letters))] - } - return string(b) -} - func platformize(linux, windows string) string { if runtime.GOOS == "windows" { return windows