diff --git a/internal/pkg/file.go b/internal/pkg/file.go new file mode 100644 index 0000000..42ec7d2 --- /dev/null +++ b/internal/pkg/file.go @@ -0,0 +1,51 @@ +package pkg + +import ( + "crypto/rand" + "os" + "path/filepath" + "time" +) + +type File struct { + filepath string + file *os.File + + isMoved bool +} + +func CreateRandomTmpFile(dir string) (*File, error) { + if err := os.MkdirAll(dir, 0750); err != nil { + return nil, err + } + tmpFile := filepath.Join(dir, time.Now().Format(time.RFC3339)+"_"+rand.Text()+".tmp") + file, err := os.Create(tmpFile) + if err != nil { + return nil, err + } + + return &File{ + filepath: tmpFile, + file: file, + }, nil +} + +func (f *File) Write(p []byte) (n int, err error) { + return f.file.Write(p) +} + +func (f *File) Path() string { + return f.filepath +} + +func (f *File) Remove() error { + if f.isMoved { + return nil + } + + return os.Remove(f.filepath) +} + +func (f *File) Move(path string) error { + return os.Rename(f.filepath, path) +}