2016-10-29 01:20:20 +00:00
|
|
|
// Copyright © 2016 Zellyn Hunter <zellyn@gmail.com>
|
|
|
|
|
|
|
|
// Package helpers contains various routines used to help cobra
|
|
|
|
// commands stay succinct.
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
|
|
|
func WriteOutput(outfilename string, contents []byte, infilename string, force bool) error {
|
|
|
|
if outfilename == "" {
|
|
|
|
outfilename = infilename
|
|
|
|
}
|
|
|
|
if outfilename == "-" {
|
|
|
|
_, err := os.Stdout.Write(contents)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !force {
|
|
|
|
if _, err := os.Stat(outfilename); !errors.Is(err, fs.ErrNotExist) {
|
|
|
|
return fmt.Errorf("cannot overwrite file %q without --force (-f)", outfilename)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return os.WriteFile(outfilename, contents, 0666)
|
2016-10-29 01:20:20 +00:00
|
|
|
}
|