2020-04-23 22:05:38 +00:00
package main
import (
"fmt"
2022-10-25 14:40:51 +00:00
"io"
2020-04-23 22:05:38 +00:00
"log"
"os"
2020-08-27 18:26:38 +00:00
"path"
"strings"
2020-04-23 22:05:38 +00:00
"github.com/charmbracelet/charm"
2021-06-14 20:52:00 +00:00
"github.com/charmbracelet/lipgloss"
2020-04-23 22:05:38 +00:00
"github.com/spf13/cobra"
)
var (
2020-08-27 18:26:38 +00:00
memo string
2021-06-14 20:52:00 +00:00
dot = lipgloss . NewStyle ( ) . Foreground ( lipgloss . Color ( "#04B575" ) ) . Render ( "•" )
2020-08-27 18:26:38 +00:00
2020-08-24 12:53:55 +00:00
stashCmd = & cobra . Command {
2020-09-07 23:14:59 +00:00
Use : "stash [SOURCE]" ,
2020-08-27 22:07:22 +00:00
Hidden : false ,
2020-08-27 22:08:39 +00:00
Short : "Stash a markdown" ,
2021-06-14 20:52:00 +00:00
Long : paragraph ( fmt . Sprintf ( "\nDo %s stuff. Run with no arguments to browse your stash or pass a path to a markdown file to stash it." , keyword ( "stash" ) ) ) ,
Example : paragraph ( "glow stash\nglow stash README.md\nglow stash -m \"secret notes\" path/to/notes.md" ) ,
2020-09-07 23:14:59 +00:00
Args : cobra . MaximumNArgs ( 1 ) ,
2020-04-23 22:05:38 +00:00
RunE : func ( cmd * cobra . Command , args [ ] string ) error {
2020-10-26 19:21:38 +00:00
initConfig ( )
2020-09-07 23:14:59 +00:00
if len ( args ) == 0 {
2021-01-15 20:58:58 +00:00
return runTUI ( "" , true )
2020-09-07 23:14:59 +00:00
}
2020-08-27 18:26:38 +00:00
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 ( )
2020-08-27 18:26:38 +00:00
f , err := os . Open ( filePath )
2020-04-23 22:05:38 +00:00
if err != nil {
return fmt . Errorf ( "bad filename" )
}
2020-08-27 18:26:38 +00:00
2022-10-25 14:40:51 +00:00
defer f . Close ( ) //nolint:errcheck
b , err := io . ReadAll ( f )
2020-04-23 22:05:38 +00:00
if err != nil {
return fmt . Errorf ( "error reading file" )
}
2020-08-27 18:26:38 +00:00
2020-08-21 19:52:53 +00:00
_ , err = cc . StashMarkdown ( memo , string ( b ) )
2020-04-23 22:05:38 +00:00
if err != nil {
return fmt . Errorf ( "error stashing markdown" )
}
2020-08-27 18:26:38 +00:00
2020-07-21 21:38:37 +00:00
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 {
2021-06-14 20:52:00 +00:00
fmt . Println ( paragraph ( "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." ) )
2020-08-27 22:07:22 +00:00
os . Exit ( 1 )
2020-04-23 22:05:38 +00:00
} else if err != nil {
fmt . Println ( err )
os . Exit ( 1 )
}
return cc
}