cli has dry mode and install script
This commit is contained in:
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"local/pt-todo-server/pttodo"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
@@ -28,16 +29,17 @@ func _main() error {
|
||||
}
|
||||
filepath := flag.String("f", defaultFilepath, "($PTTODO_FILE) path to yaml file")
|
||||
e := flag.Bool("e", false, "edit file")
|
||||
dry := flag.Bool("dry", false, "dry run")
|
||||
flag.Parse()
|
||||
if *e {
|
||||
if err := edit(*filepath); err != nil {
|
||||
if err := edit(*dry, *filepath); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return dump(os.Stdout, *filepath)
|
||||
return dump(*dry, os.Stdout, *filepath)
|
||||
}
|
||||
|
||||
func edit(filepath string) error {
|
||||
func edit(dry bool, filepath string) error {
|
||||
var tempFile string
|
||||
cp := func() error {
|
||||
f, err := ioutil.TempFile(os.TempDir(), path.Base(filepath))
|
||||
@@ -90,15 +92,19 @@ func edit(filepath string) error {
|
||||
return nil
|
||||
}
|
||||
verify := func() error {
|
||||
return dump(io.Discard, tempFile)
|
||||
return dump(true, io.Discard, tempFile)
|
||||
}
|
||||
save := func() error {
|
||||
if dry {
|
||||
log.Printf("would've saved %s as %s", tempFile, filepath)
|
||||
return nil
|
||||
}
|
||||
return os.Rename(tempFile, filepath)
|
||||
}
|
||||
|
||||
for _, foo := range []func() error{cp, vi, verify, save} {
|
||||
if err := foo(); err != nil {
|
||||
if tempFile != "" {
|
||||
if tempFile != "" && !dry {
|
||||
os.Remove(tempFile)
|
||||
}
|
||||
return err
|
||||
@@ -108,7 +114,7 @@ func edit(filepath string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func dump(writer io.Writer, filepath string) error {
|
||||
func dump(dry bool, writer io.Writer, filepath string) error {
|
||||
var reader io.Reader
|
||||
if filepath == "-" {
|
||||
reader = os.Stdin
|
||||
@@ -136,5 +142,10 @@ func dump(writer io.Writer, filepath string) error {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(writer, "%s\n", b2)
|
||||
return nil
|
||||
|
||||
if dry {
|
||||
return nil
|
||||
}
|
||||
|
||||
return os.WriteFile(filepath, b2, os.ModePerm)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user