mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-07-23 03:41:45 +00:00
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.
This commit is contained in:
parent
87e7f749a8
commit
de0f030bce
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user