Browse Source

Refactor the yarnc CLI and add support for -a/--post-as

pull/437/head
James Mills 3 weeks ago
parent
commit
7215664e2d
Signed by: prologic GPG Key ID: AC4C014F1440EBD6
  1. 4
      client/client.go
  2. 21
      cmd/yarnc/login.go
  3. 32
      cmd/yarnc/post.go
  4. 80
      cmd/yarnc/root.go
  5. 3
      cmd/yarnc/timeline.go

4
client/client.go

@ -121,8 +121,8 @@ func (c *Client) Login(username, password string) (res types.AuthResponse, err e
}
// Post ...
func (c *Client) Post(text string) (res types.AuthResponse, err error) {
req, err := c.newRequest("POST", "/post", types.PostRequest{Text: text})
func (c *Client) Post(text, as string) (res types.AuthResponse, err error) {
req, err := c.newRequest("POST", "/post", types.PostRequest{Text: text, PostAs: as})
if err != nil {
return types.AuthResponse{}, err
}

21
cmd/yarnc/login.go

@ -4,10 +4,8 @@ import (
"bufio"
"fmt"
"os"
"path/filepath"
"syscall"
"github.com/mitchellh/go-homedir"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
@ -20,9 +18,13 @@ import (
var loginCmd = &cobra.Command{
Use: "login [flags]",
Aliases: []string{"auth"},
Short: "Login and euthenticate to thw twt API",
Long: `...`,
Args: cobra.MaximumNArgs(0),
Short: "Login and euthenticate to a Yarn.social pod",
Long: `The login command allows you to login a user ot login to a
Yarn.social pod running yarnd. Once successfully authenticated with a valid
account a API token is generated on the account and a configuration file is
written to store the endpoint logged in to and the token for future used by
the command-line client.`,
Args: cobra.MaximumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
uri := viper.GetString("uri")
cli, err := client.NewClient(client.WithURI(uri))
@ -75,15 +77,8 @@ func login(cli *client.Client) {
log.Info("login successful")
// Find home directory.
home, err := homedir.Dir()
if err != nil {
log.WithError(err).Error("error finding home directory")
os.Exit(1)
}
cli.Config.Token = res.Token
if err := cli.Config.Save(filepath.Join(home, ".twt.yaml")); err != nil {
if err := cli.Config.Save(viper.ConfigFileUsed()); err != nil {
log.WithError(err).Error("error saving config")
os.Exit(1)
}

32
cmd/yarnc/post.go

@ -15,13 +15,16 @@ import (
// postCmd represents the pub command
var postCmd = &cobra.Command{
Use: "post [flags]",
Aliases: []string{"tweet", "twt", "new"},
Short: "Post a Twt to a Twtxt Pod",
Long: `...`,
Aliases: []string{"tweet", "twt", "new", "yarn"},
Short: "Post a new twt to a Yarn.social pod",
Long: `The post command makes a new post to a Yarn.social pod.
if the optional flag -a/--post-as is used the post is made from that specified
feed (persona) if the logged in user owned that feed.`,
//Args: cobra.NArgs(0),
Run: func(cmd *cobra.Command, args []string) {
uri := viper.GetString("uri")
token := viper.GetString("token")
cli, err := client.NewClient(
client.WithURI(uri),
client.WithToken(token),
@ -31,15 +34,26 @@ var postCmd = &cobra.Command{
os.Exit(1)
}
post(cli, args)
postAs, err := cmd.Flags().GetString("post-as")
if err != nil {
log.WithError(err).Error("error getting post-as flag")
os.Exit(1)
}
post(cli, postAs, args)
},
}
func init() {
RootCmd.AddCommand(postCmd)
postCmd.Flags().StringP(
"post-as", "a", "",
"Post as a different feed (default: primary account feed)",
)
}
func post(cli *client.Client, args []string) {
func post(cli *client.Client, postAs string, args []string) {
text := strings.Join(args, " ")
if text == "" {
@ -56,9 +70,13 @@ func post(cli *client.Client, args []string) {
os.Exit(1)
}
log.Info("posting twt...")
if postAs == "" {
log.Info("posting twt...")
} else {
log.Infof("posting twt as %s...", postAs)
}
_, err := cli.Post(text)
_, err := cli.Post(text, postAs)
if err != nil {
log.WithError(err).Error("error making post")
os.Exit(1)

80
cmd/yarnc/root.go

@ -3,6 +3,7 @@ package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/mitchellh/go-homedir"
@ -16,14 +17,33 @@ import (
"git.mills.io/yarnsocial/yarn/types/retwt"
)
var configFile string
const (
DefaultConfigFilename = ".yarnc.yml"
DefaultEnvPrefix = "YARNC"
)
var (
ConfigFile string
DefaultConfigFile string
)
func init() {
homeDir, err := homedir.Dir()
if err != nil {
log.WithError(err).Fatal("error finding user home directory")
}
DefaultConfigFile = filepath.Join(homeDir, DefaultConfigFilename)
}
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "yarn",
Use: "yarnc",
Version: yarn.FullVersion(),
Short: "Command-line client for twtxt",
Long: `...`,
Short: "Command-line client for yarnd",
Long: `This is the command-line client for Yarn.social pods running
yarnd. This tool allows a user to interact with a pod to view their timeline,
following feeds, make posts and managing their account.`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// set logging level
if viper.GetBool("debug") {
@ -47,9 +67,9 @@ func Execute() {
func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().StringVar(
&configFile, "config", "",
"config file (default: $HOME/.twt.yaml)",
RootCmd.PersistentFlags().StringVarP(
&ConfigFile, "config", "c", DefaultConfigFile,
"set a custom config file",
)
RootCmd.PersistentFlags().BoolP(
@ -58,25 +78,25 @@ func init() {
)
parser := RootCmd.PersistentFlags().StringP(
"parser", "P", "lextwt",
"parser", "p", "lextwt",
"Set active parse engine [lextwt, retwt]",
)
RootCmd.PersistentFlags().StringP(
"uri", "u", client.DefaultURI,
"twt API endpoint URI to connect to",
"yarnd API endpoint URI to connect to",
)
RootCmd.PersistentFlags().StringP(
"token", "t", "$TWT_TOKEN",
"twt API token to use to authenticate to endpoints",
"token", "t", fmt.Sprintf("$%s_TOKEN", DefaultEnvPrefix),
"yarnd API token to use to authenticate to endpoints",
)
viper.BindPFlag("uri", RootCmd.PersistentFlags().Lookup("uri"))
viper.SetDefault("uri", client.DefaultURI)
viper.BindPFlag("token", RootCmd.PersistentFlags().Lookup("token"))
viper.SetDefault("token", os.Getenv("TWT_TOKEN"))
viper.SetDefault("token", os.Getenv(fmt.Sprintf("%_TOKEN", DefaultEnvPrefix)))
viper.BindPFlag("debug", RootCmd.PersistentFlags().Lookup("debug"))
viper.SetDefault("debug", false)
@ -89,43 +109,23 @@ func init() {
case "retwt":
retwt.DefaultTwtManager()
default:
log.Errorf("unknown parse engine: %s", *parser)
os.Exit(1)
log.Fatalf("unknown parse engine: %s", *parser)
}
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if configFile != "" {
// Use config file from the flag.
viper.SetConfigFile(configFile)
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err != nil {
log.WithError(err).Errorf("error loading config file")
os.Exit(1)
}
log.Infof("Using config file: %s", viper.ConfigFileUsed())
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
viper.AddConfigPath(home)
viper.SetConfigName(".twt")
viper.SetConfigFile(ConfigFile)
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err != nil {
log.WithError(err).Warn("error loading config file")
}
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err != nil {
log.WithError(err).Warnf("error loading config file: %s", viper.ConfigFileUsed())
} else {
log.Debugf("Using config file: %s", viper.ConfigFileUsed())
}
// from the environment
viper.SetEnvPrefix("TWT")
viper.SetEnvPrefix(DefaultEnvPrefix)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv() // read in environment variables that match
}

3
cmd/yarnc/timeline.go

@ -18,7 +18,8 @@ var timelineCmd = &cobra.Command{
Use: "timeline [flags]",
Aliases: []string{"view", "show", "events"},
Short: "Display your timeline",
Long: `...`,
Long: `The timeline command retrieve the timeline from the logged in
Yarn.social account.`,
//Args: cobra.NArgs(0),
Run: func(cmd *cobra.Command, args []string) {
uri := viper.GetString("uri")

Loading…
Cancel
Save