github.com/stevenmatthewt/agent@v3.5.4+incompatible/bootstrap/shell/tempfile.go (about) 1 package shell 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 "strings" 9 ) 10 11 // TempFileWithExtension creates a temporary file that copies the extension of the provided filename 12 func TempFileWithExtension(filename string) (*os.File, error) { 13 extension := filepath.Ext(filename) 14 basename := strings.TrimSuffix(filename, extension) 15 16 // Create the file 17 tempFile, err := ioutil.TempFile("", basename+"-") 18 if err != nil { 19 return nil, fmt.Errorf("Failed to create temporary file \"%s\" (%s)", filename, err) 20 } 21 22 // Do we need to rename the file? 23 if extension != "" { 24 // Close the currently open tempfile 25 tempFile.Close() 26 27 // Rename it 28 newTempFileName := tempFile.Name() + extension 29 err = os.Rename(tempFile.Name(), newTempFileName) 30 if err != nil { 31 return nil, fmt.Errorf("Failed to rename \"%s\" to \"%s\" (%s)", tempFile.Name(), newTempFileName, err) 32 } 33 34 // Open it again 35 tempFile, err = os.OpenFile(newTempFileName, os.O_RDWR|os.O_EXCL, 0600) 36 if err != nil { 37 return nil, fmt.Errorf("Failed to open temporary file \"%s\" (%s)", newTempFileName, err) 38 } 39 } 40 41 return tempFile, nil 42 }