| 1 |
/* |
| 2 |
Copyright 2017 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package temp |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"io" |
| 22 |
"io/ioutil" |
| 23 |
"os" |
| 24 |
"path/filepath" |
| 25 |
) |
| 26 |
|
| 27 |
// Directory is an interface to a temporary directory, in which you can |
| 28 |
// create new files. |
| 29 |
type Directory interface { |
| 30 |
// NewFile creates a new file in that directory. Calling NewFile |
| 31 |
// with the same filename twice will result in an error. |
| 32 |
NewFile(name string) (io.WriteCloser, error) |
| 33 |
// Delete removes the directory and its content. |
| 34 |
Delete() error |
| 35 |
} |
| 36 |
|
| 37 |
// Dir is wrapping an temporary directory on disk. |
| 38 |
type Dir struct { |
| 39 |
// Name is the name (full path) of the created directory. |
| 40 |
Name string |
| 41 |
} |
| 42 |
|
| 43 |
var _ Directory = &Dir{} |
| 44 |
|
| 45 |
// CreateTempDir returns a new Directory wrapping a temporary directory |
| 46 |
// on disk. |
| 47 |
func CreateTempDir(prefix string) (*Dir, error) { |
| 48 |
name, err := ioutil.TempDir("", fmt.Sprintf("%s-", prefix)) |
| 49 |
if err != nil { |
| 50 |
return nil, err |
| 51 |
} |
| 52 |
|
| 53 |
return &Dir{ |
| 54 |
Name: name, |
| 55 |
}, nil |
| 56 |
} |
| 57 |
|
| 58 |
// NewFile creates a new file in the specified directory. |
| 59 |
func (d *Dir) NewFile(name string) (io.WriteCloser, error) { |
| 60 |
return os.OpenFile( |
| 61 |
filepath.Join(d.Name, name), |
| 62 |
os.O_WRONLY|os.O_CREATE|os.O_TRUNC|os.O_EXCL, |
| 63 |
0700, |
| 64 |
) |
| 65 |
} |
| 66 |
|
| 67 |
// Delete the underlying directory, and all of its content. |
| 68 |
func (d *Dir) Delete() error { |
| 69 |
return os.RemoveAll(d.Name) |
| 70 |
} |