Support standard input via shell redirection with `zk new` (#240)

pull/238/head^2
Mickaël Menu 2 years ago committed by GitHub
parent aaf6c42bd8
commit 53aabce1ed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -26,6 +26,7 @@ All notable changes to this project will be documented in this file.
### Fixed
* [#233](https://github.com/mickael-menu/zk/issues/233) Hide index progress in non-interactive shells.
* [#239](https://github.com/mickael-menu/zk/discussions/239) Support standard input via shell redirection with `zk new`.
## 0.10.1

@ -3,6 +3,7 @@ package cmd
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
@ -11,7 +12,6 @@ import (
"github.com/mickael-menu/zk/internal/core"
dateutil "github.com/mickael-menu/zk/internal/util/date"
"github.com/mickael-menu/zk/internal/util/opt"
osutil "github.com/mickael-menu/zk/internal/util/os"
)
// New adds a new note to the notebook.
@ -33,7 +33,7 @@ func (cmd *New) Run(container *cli.Container) error {
return err
}
content, err := osutil.ReadStdinPipe()
content, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
}
@ -48,7 +48,7 @@ func (cmd *New) Run(container *cli.Container) error {
note, err := notebook.NewNote(core.NewNoteOpts{
Title: opt.NewNotEmptyString(cmd.Title),
Content: content.Unwrap(),
Content: string(content),
Directory: opt.NewNotEmptyString(cmd.Directory),
Group: opt.NewNotEmptyString(cmd.Group),
Template: opt.NewNotEmptyString(cmd.Template),

@ -1,34 +1,12 @@
package os
import (
"bufio"
"io/ioutil"
"os"
"strings"
"github.com/mickael-menu/zk/internal/util/opt"
)
// ReadStdinPipe returns the content of any piped input.
func ReadStdinPipe() (opt.String, error) {
fi, err := os.Stdin.Stat()
if err != nil {
return opt.NullString, err
}
if fi.Mode()&os.ModeNamedPipe == 0 {
// Not a pipe
return opt.NullString, nil
}
reader := bufio.NewReader(os.Stdin)
bytes, err := ioutil.ReadAll(reader)
if err != nil {
return opt.NullString, err
}
return opt.NewNotEmptyString(string(bytes)), nil
}
// Getenv returns an optional String for the environment variable with given
// key.
func GetOptEnv(key string) opt.String {

@ -109,6 +109,14 @@ $ echo "Content of the note" | EDITOR=cat zk new --title "Piped note"
>Content of the note
>
# Redirect file to standard input when creating a new note.
$ echo "Content of the note" > input
$ EDITOR=cat zk new --title "Note from redirected input" < input
># Note from redirected input
>
>Content of the note
>
# Existing notes are not overwritten, but can be edited.
$ zk new --force-input n --title "Piped note"
>? piped-note.md already exists, do you want to edit this note instead? (y/N)

Loading…
Cancel
Save