Skip to content

Commit

Permalink
Merge pull request #17 from maaslalani/stdin
Browse files Browse the repository at this point in the history
Read slides from stdin
  • Loading branch information
Maas Lalani authored Jun 9, 2021
2 parents f68b802 + 3da7238 commit 42c7a73
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 12 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand Down
66 changes: 54 additions & 12 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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

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")
if len(args) > 0 {
content, err = readFile(args[0])
} else {
content, err = readStdin()
}

b, err := ioutil.ReadFile(f)
if err != nil {
return errors.New("could not read file")
return err
}

content := string(b)
content = strings.ReplaceAll(content, altDelimiter, delimiter)
slides := strings.Split(content, delimiter)

Expand All @@ -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()
Expand All @@ -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
}

0 comments on commit 42c7a73

Please sign in to comment.