Skip to content

Commit

Permalink
acat: add -nonempty flag
Browse files Browse the repository at this point in the history
Skip replacing the output if the input is empty, when set.
  • Loading branch information
creachadair committed May 5, 2022
1 parent 5bc5301 commit 42c8711
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions cmd/acat/acat.go
Expand Up @@ -4,6 +4,7 @@ package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
Expand All @@ -12,7 +13,10 @@ import (
"github.com/creachadair/atomicfile"
)

var fileMode = flag.String("mode", "0600", "Output file mode")
var (
fileMode = flag.String("mode", "0600", "Output file mode")
nonEmpty = flag.Bool("nonempty", false, "Only write if the input is nonempty")
)

func init() {
flag.Usage = func() {
Expand All @@ -38,7 +42,18 @@ func main() {
if err != nil {
log.Fatalf("Invalid mode %q: %v", *fileMode, err)
}
if _, err := atomicfile.WriteAll(flag.Arg(0), os.Stdin, os.FileMode(mode)); err != nil {
log.Fatalf("Error: %v", err)
f, err := atomicfile.New(flag.Arg(0), os.FileMode(mode))
if err != nil {
log.Fatalf("New: %v", err)
}
defer f.Cancel()
nw, err := io.Copy(f, os.Stdin)
if err != nil {
f.Cancel()
log.Fatalf("Copy: %v", err)
} else if nw == 0 && *nonEmpty {
return
} else if err := f.Close(); err != nil {
log.Fatalf("Close: %v", err)
}
}

0 comments on commit 42c8711

Please sign in to comment.