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.

Kubernetes-commit: de0f030bcec55944dcbf81a9eec4f4d87f76567f
This commit is contained in:
Hong Xu 2021-04-08 16:00:25 -07:00 committed by Kubernetes Publisher
parent 76fce851e0
commit e8a9ba311e
1 changed files with 1 additions and 26 deletions

View File

@ -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