github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/libkb/tmpfile.go (about) 1 // Copyright 2015 Keybase, Inc. All rights reserved. Use of 2 // this source code is governed by the included BSD license. 3 4 package libkb 5 6 import ( 7 "fmt" 8 "os" 9 "path/filepath" 10 ) 11 12 // OpenTempFile creates an opened termporary file. Use mode=0 for default 13 // permissions. 14 // 15 // OpenTempFile("foo", ".zip", 0755) => "foo.RCG2KUSCGYOO3PCKNWQHBOXBKACOPIKL.zip" 16 // OpenTempFile(path.Join(os.TempDir(), "foo"), "", 0) => "/tmp/foo.RCG2KUSCGYOO3PCKNWQHBOXBKACOPIKL" 17 func OpenTempFile(prefix string, suffix string, mode os.FileMode) (string, *os.File, error) { 18 if prefix == "" { 19 return "", nil, fmt.Errorf("Prefix was an empty string") 20 } 21 filename, err := RandString(fmt.Sprintf("%s.", prefix), 20) 22 if err != nil { 23 return "", nil, err 24 } 25 if suffix != "" { 26 filename += suffix 27 } 28 flags := os.O_WRONLY | os.O_CREATE | os.O_EXCL 29 if mode == 0 { 30 mode = PermFile 31 } 32 file, err := os.OpenFile(filename, flags, mode) 33 return filename, file, err 34 } 35 36 // TempFileName returns a temporary random filename 37 func TempFileName(prefix string) (tmp string, err error) { 38 tmp, err = RandString(prefix, 20) 39 return 40 } 41 42 // TempFile returns a random path name in os.TempDir() 43 func TempFile(prefix string) (string, error) { 44 tmp, err := TempFileName(prefix) 45 if err != nil { 46 return "", err 47 } 48 return filepath.Join(os.TempDir(), tmp), nil 49 }