60 lines
1.5 KiB
Go
Executable File
60 lines
1.5 KiB
Go
Executable File
// Package os provides utility functions for file operations.
|
|
package os
|
|
|
|
import (
|
|
"io"
|
|
std "os"
|
|
"path/filepath"
|
|
|
|
"git.sdf.org/jchenry/x"
|
|
)
|
|
|
|
// FileOrStdin returns the given file if not nil, otherwise returns os.Stdin.
|
|
func FileOrStdin(f *std.File) (fileReader io.ReadCloser) {
|
|
if f == nil {
|
|
return std.Stdin
|
|
}
|
|
|
|
return f
|
|
}
|
|
|
|
// CopyToNewFile creates a new file at the given path and copies data from the reader to it.
|
|
// Returns an error if file creation or copying fails.
|
|
func CopyToNewFile(path string, r io.Reader) error {
|
|
out, err := std.Create(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer out.Close()
|
|
return CopyToFile(out, r)
|
|
}
|
|
|
|
// CopyToFile copies data from the reader to the given file.
|
|
// Returns an error if the copy operation fails.
|
|
func CopyToFile(f *std.File, r io.Reader) error {
|
|
if _, err := io.Copy(f, r); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// FileExists checks if a file exists at the given path.
|
|
// Returns true if the file exists and can be accessed, false otherwise.
|
|
func FileExists(filePath string) bool {
|
|
_, err := std.Stat(filePath)
|
|
if std.IsNotExist(err) {
|
|
return false
|
|
}
|
|
return err == nil
|
|
}
|
|
|
|
// Mkdir creates a directory (and any necessary parent directories) from the given path segments.
|
|
// At least one path segment must be provided or this function will panic.
|
|
// Returns an error if directory creation fails.
|
|
func Mkdir(p ...string) error {
|
|
x.Assert(len(p) > 0, "Mkdir: p <= 0")
|
|
newpath := filepath.Join(p...)
|
|
return std.MkdirAll(newpath, 0711)
|
|
}
|