ceph-csi/vendor/k8s.io/utils/temp/dir.go

71 lines
1.8 KiB
Go
Raw Normal View History

2018-01-09 18:57:14 +00:00
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package temp
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
// Directory is an interface to a temporary directory, in which you can
// create new files.
type Directory interface {
// NewFile creates a new file in that directory. Calling NewFile
// with the same filename twice will result in an error.
NewFile(name string) (io.WriteCloser, error)
// Delete removes the directory and its content.
Delete() error
}
2018-11-26 18:23:56 +00:00
// Dir is wrapping an temporary directory on disk.
type Dir struct {
2018-01-09 18:57:14 +00:00
// Name is the name (full path) of the created directory.
Name string
}
2018-11-26 18:23:56 +00:00
var _ Directory = &Dir{}
2018-01-09 18:57:14 +00:00
// CreateTempDir returns a new Directory wrapping a temporary directory
// on disk.
2018-11-26 18:23:56 +00:00
func CreateTempDir(prefix string) (*Dir, error) {
2018-01-09 18:57:14 +00:00
name, err := ioutil.TempDir("", fmt.Sprintf("%s-", prefix))
if err != nil {
return nil, err
}
2018-11-26 18:23:56 +00:00
return &Dir{
2018-01-09 18:57:14 +00:00
Name: name,
}, nil
}
// NewFile creates a new file in the specified directory.
2018-11-26 18:23:56 +00:00
func (d *Dir) NewFile(name string) (io.WriteCloser, error) {
2018-01-09 18:57:14 +00:00
return os.OpenFile(
filepath.Join(d.Name, name),
os.O_WRONLY|os.O_CREATE|os.O_TRUNC|os.O_EXCL,
0700,
)
}
// Delete the underlying directory, and all of its content.
2018-11-26 18:23:56 +00:00
func (d *Dir) Delete() error {
2018-01-09 18:57:14 +00:00
return os.RemoveAll(d.Name)
}