glow/stash_cmd.go

83 lines
1.9 KiB
Go
Raw Normal View History

2020-04-23 22:05:38 +00:00
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"strings"
2020-04-23 22:05:38 +00:00
"github.com/charmbracelet/charm"
"github.com/charmbracelet/charm/ui/common"
"github.com/muesli/termenv"
2020-04-23 22:05:38 +00:00
"github.com/spf13/cobra"
)
var (
memo string
2020-08-24 12:53:55 +00:00
stashCmd = &cobra.Command{
Use: "stash [SOURCE]",
Hidden: false,
2020-08-27 22:08:39 +00:00
Short: "Stash a markdown",
Long: formatBlock(fmt.Sprintf("\nDo %s stuff. Run with no arguments to browse your stash or pass a path to a markdown file to stash it.", common.Keyword("stash"))),
Example: formatBlock("glow stash\nglow stash README.md\nglow stash -m \"secret notes\" path/to/notes.md"),
Args: cobra.MaximumNArgs(1),
2020-04-23 22:05:38 +00:00
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return runTUI(true)
}
filePath := args[0]
if memo == "" {
memo = strings.Replace(path.Base(filePath), path.Ext(filePath), "", 1)
}
2020-04-23 22:05:38 +00:00
cc := initCharmClient()
f, err := os.Open(filePath)
2020-04-23 22:05:38 +00:00
if err != nil {
return fmt.Errorf("bad filename")
}
2020-04-23 22:05:38 +00:00
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
return fmt.Errorf("error reading file")
}
_, err = cc.StashMarkdown(memo, string(b))
2020-04-23 22:05:38 +00:00
if err != nil {
return fmt.Errorf("error stashing markdown")
}
dot := termenv.String("•").Foreground(common.Green.Color()).String()
fmt.Println(dot + " Stashed!")
2020-04-23 22:05:38 +00:00
return nil
},
}
)
func getCharmConfig() *charm.Config {
cfg, err := charm.ConfigFromEnv()
if err != nil {
log.Fatal(err)
}
2020-08-24 12:53:55 +00:00
2020-04-23 22:05:38 +00:00
return cfg
}
func initCharmClient() *charm.Client {
cfg := getCharmConfig()
cc, err := charm.NewClient(cfg)
if err == charm.ErrMissingSSHAuth {
fmt.Println(formatBlock("We had some trouble authenticating via SSH. If this continues to happen the Charm tool may be able to help you. More info at https://github.com/charmbracelet/charm."))
os.Exit(1)
2020-04-23 22:05:38 +00:00
} else if err != nil {
fmt.Println(err)
os.Exit(1)
}
return cc
}