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