2016-10-29 01:20:20 +00:00
|
|
|
// Copyright © 2016 Zellyn Hunter <zellyn@gmail.com>
|
|
|
|
|
2021-08-01 02:10:44 +00:00
|
|
|
// Package helpers contains helper routines for reading and writing files,
|
|
|
|
// allowing `-` to mean stdin/stdout.
|
2016-10-29 01:20:20 +00:00
|
|
|
package helpers
|
|
|
|
|
|
|
|
import (
|
2021-07-12 20:27:13 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/fs"
|
2016-10-29 01:20:20 +00:00
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2016-12-10 21:29:41 +00:00
|
|
|
// FileContentsOrStdIn returns the contents of a file, unless the file
|
|
|
|
// is "-", in which case it reads from stdin.
|
2016-10-29 01:20:20 +00:00
|
|
|
func FileContentsOrStdIn(s string) ([]byte, error) {
|
|
|
|
if s == "-" {
|
2021-07-12 20:27:13 +00:00
|
|
|
return io.ReadAll(os.Stdin)
|
2016-10-29 01:20:20 +00:00
|
|
|
}
|
2021-07-12 20:27:13 +00:00
|
|
|
return os.ReadFile(s)
|
|
|
|
}
|
|
|
|
|
2021-08-01 02:10:44 +00:00
|
|
|
func WriteOutput(filename string, contents []byte, force bool) error {
|
|
|
|
if filename == "-" {
|
2021-07-12 20:27:13 +00:00
|
|
|
_, err := os.Stdout.Write(contents)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !force {
|
2021-08-01 02:10:44 +00:00
|
|
|
if _, err := os.Stat(filename); !errors.Is(err, fs.ErrNotExist) {
|
|
|
|
return fmt.Errorf("cannot overwrite file %q without --force (-f)", filename)
|
2021-07-12 20:27:13 +00:00
|
|
|
}
|
|
|
|
}
|
2021-08-01 02:10:44 +00:00
|
|
|
return os.WriteFile(filename, contents, 0666)
|
2016-10-29 01:20:20 +00:00
|
|
|
}
|