Skip to content

Commit

Permalink
Added option to read from prompt
Browse files Browse the repository at this point in the history
  • Loading branch information
aosasona committed Sep 4, 2024
1 parent 2eb3d64 commit 731b374
Showing 1 changed file with 44 additions and 16 deletions.
60 changes: 44 additions & 16 deletions cmd/bore/app/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ package app

import (
"bufio"
"bytes"
"fmt"
"strings"
"os"

"github.com/urfave/cli/v2"
"go.trulyao.dev/bore/pkg/handler"
Expand Down Expand Up @@ -34,38 +35,65 @@ func (a *App) PasteCommand() *cli.Command {
}

func (a *App) Copy(ctx *cli.Context) error {
if strings.TrimSpace(ctx.String("file")) != "" {
return a.CopyFromFile(ctx)
fi, _ := os.Stdin.Stat()
isPipe := (fi.Mode() & os.ModeCharDevice) == 0

if isPipe {
return a.CopyFromStdin(ctx)
}

return a.CopyFromStdin(ctx)
return a.CopyFromPrompt(ctx)
}

// CopyFromStdin copies the content from the STDIN to the database
// TODO: implement collections and artifact types
func (a *App) CopyFromStdin(ctx *cli.Context) error {
content := bufio.NewReader(ctx.App.Reader)
id, err := a.Handler().Copy(content, handler.CopyOpts{})
// CopyFromPrompt reads the content from the terminal prompt
func (a *App) CopyFromPrompt(ctx *cli.Context) error {
content := []byte{}

reader := bufio.NewReader(ctx.App.Reader)
fmt.Print("Enter content to copy (press esc + enter to finish):\n")

for {
b, err := reader.ReadByte()
if err != nil {
return err
}

if b == 27 {
break
}

content = append(content, b)
}

contentReader := bytes.NewReader(content)
id, err := a.Handler().Copy(contentReader, handler.CopyOpts{})
if err != nil {
return err
}

if a.config.ShowIdOnCopy {
fmt.Fprintln(ctx.App.Writer, fmt.Sprintf("Copied content with ID: %s\n", id))
fmt.Fprintln(ctx.App.Writer, fmt.Sprintf("Copied content with ID: %s", id))
}

return nil
}

func (a *App) CopyFromFile(ctx *cli.Context) error {
return fmt.Errorf("not implemented")
}

func (a *App) Paste(ctx *cli.Context) error {
err := a.Handler().PasteLastCopied(ctx.App.Writer)
// CopyFromStdin copies the content from the STDIN
func (a *App) CopyFromStdin(ctx *cli.Context) error {
content := bufio.NewReader(ctx.App.Reader)
id, err := a.Handler().Copy(content, handler.CopyOpts{})
if err != nil {
return err
}

if a.config.ShowIdOnCopy {
fmt.Fprintln(ctx.App.Writer, fmt.Sprintf("Copied content with ID: %s", id))
}

return nil
}

func (a *App) Paste(ctx *cli.Context) error {
err := a.Handler().PasteLastCopied(ctx.App.Writer)
return err
}

0 comments on commit 731b374

Please sign in to comment.