Merge pull request #17 from maaslalani/stdin

Read slides from stdin
This commit is contained in:
Maas Lalani
2021-06-09 09:56:57 -04:00
committed by GitHub
2 changed files with 61 additions and 14 deletions

View File

@@ -40,6 +40,11 @@ Then, to present, run:
slides presentation.md
```
You are also able to pass in slides through `stdin`, this allows you to `curl` and present remote files:
```
curl https://example.com/slides.md | slides
```
Go to the next slide with any of the following keys:
* <kbd>space</kbd>
* <kbd>right</kbd>

View File

@@ -1,12 +1,15 @@
package cmd
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/user"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/maaslalani/slides/internal/model"
@@ -21,24 +24,21 @@ const (
var root = &cobra.Command{
Use: "slides <file.md>",
Short: "Slides is a terminal based presentation tool",
Args: cobra.ExactArgs(1),
Args: cobra.MaximumNArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
f := args[0]
var content string
var err error
if len(args) > 0 {
content, err = readFile(args[0])
} else {
content, err = readStdin()
}
s, err := os.Stat(f)
if err != nil {
return errors.New("could not read file")
}
if s.IsDir() {
return errors.New("must pass a file")
return err
}
b, err := ioutil.ReadFile(f)
if err != nil {
return errors.New("could not read file")
}
content := string(b)
content = strings.ReplaceAll(content, altDelimiter, delimiter)
slides := strings.Split(content, delimiter)
@@ -51,7 +51,7 @@ var root = &cobra.Command{
Slides: slides,
Page: 0,
Author: user.Name,
Date: s.ModTime().Format("2006-01-02"),
Date: time.Now().Format("2006-01-02"),
}, tea.WithAltScreen())
err = p.Start()
@@ -66,3 +66,45 @@ func Execute() {
os.Exit(1)
}
}
func readFile(path string) (string, error) {
s, err := os.Stat(path)
if err != nil {
return "", errors.New("could not read file")
}
if s.IsDir() {
return "", errors.New("can not read directory")
}
b, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return string(b), err
}
func readStdin() (string, error) {
stat, err := os.Stdin.Stat()
if err != nil {
return "", err
}
if stat.Mode()&os.ModeNamedPipe == 0 && stat.Size() == 0 {
return "", errors.New("no slides provided")
}
reader := bufio.NewReader(os.Stdin)
var b strings.Builder
for {
r, _, err := reader.ReadRune()
if err != nil && err == io.EOF {
break
}
_, err = b.WriteRune(r)
if err != nil {
return "", err
}
}
return b.String(), nil
}