Skip to content

Commit

Permalink
feat: add 'pathwar cli @me'
Browse files Browse the repository at this point in the history
Signed-off-by: Manfred Touron <[email protected]>
  • Loading branch information
moul committed Jul 22, 2020
1 parent 225ddad commit 7fe1471
Show file tree
Hide file tree
Showing 3 changed files with 151 additions and 23 deletions.
117 changes: 117 additions & 0 deletions go/cmd/pathwar/cli.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package main

import (
"context"
"flag"
"fmt"
"os"

"github.com/dustin/go-humanize"
"github.com/olekukonko/tablewriter"
"github.com/peterbourgon/ff"
"github.com/peterbourgon/ff/ffcli"
"go.uber.org/zap"
"pathwar.land/pathwar/v2/go/pkg/pwapi"
"pathwar.land/pathwar/v2/go/pkg/pwdb"
)

func cliCommand() *ffcli.Command {
cliFlags := flag.NewFlagSet("cli", flag.ExitOnError)
cliFlags.StringVar(&httpAPIAddr, "http-api-addr", defaultHTTPApiAddr, "HTTP API address")
cliFlags.StringVar(&ssoOpts.ClientID, "sso-client-id", ssoOpts.ClientID, "SSO ClientID")
cliFlags.StringVar(&ssoOpts.ClientSecret, "sso-client-secret", ssoOpts.ClientSecret, "SSO ClientSecret")
cliFlags.StringVar(&ssoOpts.Realm, "sso-realm", ssoOpts.Realm, "SSO Realm")
cliFlags.StringVar(&ssoOpts.TokenFile, "sso-token-file", ssoOpts.TokenFile, "Token file")

return &ffcli.Command{
Name: "cli",
Usage: "pathwar [global flags] cli [cli flags] <cmd> [cmd flags]",
ShortHelp: "CLI replacement for the web portal",
FlagSet: cliFlags,
Options: []ff.Option{ff.WithEnvVarNoPrefix()},
Exec: func(args []string) error { return flag.ErrHelp },
Subcommands: []*ffcli.Command{
{
Name: "@me",
ShortHelp: "Get an overview of your account (good place to start)",
Exec: func(args []string) error {
if err := globalPreRun(); err != nil {
return err
}
ctx := context.Background()
client, err := httpClientFromEnv(ctx)
if err != nil {
return err
}
var ret pwapi.UserGetSession_Output
if err := client.RawProto(ctx, "GET", "/user/session", nil, &ret); err != nil {
return err
}

logger.Debug("GET /user/session", zap.Any("ret", ret))

// DB User
{
// fmt.Println(godev.PrettyJSON(ret.User))
fmt.Printf("Welcome %s! 👋\n", ret.User.Username)
createdAgo := humanize.Time(*ret.User.CreatedAt)
updatedAgo := humanize.Time(*ret.User.UpdatedAt)
fmt.Printf("Your account was created %s and updated %s.\n\n", createdAgo, updatedAgo)
}

// JWT Token
{
//fmt.Println(godev.PrettyJSON(ret.Claims))
tokenAgo := humanize.Time(*ret.Claims.ActionToken.AuthTime)
issuedAgo := humanize.Time(*ret.Claims.ActionToken.Iat)
expireIn := humanize.Time(*ret.Claims.ActionToken.Exp)
fmt.Printf("Your OAuth token was created %s, (re)issued %s and will expire in %s.\n\n", tokenAgo, issuedAgo, expireIn)
}

// Notifications
{
// FIXME: Todo
// fmt.Println(godev.PrettyJSON(ret.Notifications))
}

// sessions
{
//fmt.Println(godev.PrettyJSON(ret.Seasons))
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"SEASON", "STATUS", "TEAM"})
table.SetAlignment(tablewriter.ALIGN_CENTER)
table.SetBorder(false)
for _, entry := range ret.Seasons {
name := entry.Season.Name
// FIXME: use slug
if entry.Season.IsDefault {
name += " (default)"
}
status := ""
switch entry.Season.Status {
case pwdb.Season_Started:
status = "Started 🏁"
default:
status = entry.Season.Status.String()
}
status += " / "
switch entry.Season.Visibility {
case pwdb.Season_Public:
status += "Public 👐"
default:
status += entry.Season.Visibility.String()
}
team := "no team 👎"
if entry.Team != nil {
team = entry.Team.Organization.Name
}
table.Append([]string{name, status, team})
}
table.Render()
}
return nil
},
},
},
}
}
42 changes: 19 additions & 23 deletions go/cmd/pathwar/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,48 +22,44 @@ func main() {
}()

// setup flags
var (
globalFlags = flag.NewFlagSet("pathwar", flag.ExitOnError)
)
globalFlags := flag.NewFlagSet("pathwar", flag.ExitOnError)
globalFlags.SetOutput(flagOutput) // used in main_test.go
globalFlags.BoolVar(&globalDebug, "debug", false, "debug mode")
globalFlags.StringVar(&zipkinEndpoint, "zipkin-endpoint", "", "optional opentracing server")
globalFlags.StringVar(&bearerSecretKey, "bearer-secretkey", "", "bearer.sh secret key")
globalFlags.StringVar(&globalSentryDSN, "sentry-dsn", "", "Sentry DSN")

version := &ffcli.Command{
Name: "version",
Usage: "pathwar [global flags] version",
ShortHelp: "show version",
Exec: func(args []string) error {
fmt.Printf(
"version=%q\ncommit=%q\nbuilt-at=%q\nbuilt-by=%q\n",
pwversion.Version, pwversion.Commit, pwversion.Date, pwversion.BuiltBy,
)
return nil
},
}

root := &ffcli.Command{
Usage: "pathwar [global flags] <subcommand> [flags] [args...]",
FlagSet: globalFlags,
LongHelp: "More info here: https://github.com/pathwar/pathwar/wiki/CLI",
Options: []ff.Option{ff.WithEnvVarNoPrefix()},
Exec: func([]string) error { return flag.ErrHelp },
Subcommands: []*ffcli.Command{
rawclientCommand(),
cliCommand(),
apiCommand(),
composeCommand(),
agentCommand(),
miscCommand(),
adminCommand(),
version,
{
Name: "version",
Usage: "pathwar [global flags] version",
ShortHelp: "show version",
Exec: func(args []string) error {
fmt.Printf(
"version=%q\ncommit=%q\nbuilt-at=%q\nbuilt-by=%q\n",
pwversion.Version, pwversion.Commit, pwversion.Date, pwversion.BuiltBy,
)
return nil
},
},
},
Options: []ff.Option{ff.WithEnvVarNoPrefix()},
Exec: func([]string) error { return flag.ErrHelp },
}

if err := root.Run(os.Args[1:]); err != nil {
if !errors.Is(err, flag.ErrHelp) {
log.Fatalf("fatal: %+v", err)
}
err := root.Run(os.Args[1:])
if err != nil && !errors.Is(err, flag.ErrHelp) {
log.Fatalf("fatal: %+v", err)
}
}
15 changes: 15 additions & 0 deletions go/pkg/pwapi/httpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package pwapi
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
Expand Down Expand Up @@ -95,6 +96,20 @@ func (c HTTPClient) UserSetPreferences(ctx context.Context, input *UserSetPrefer
return result, err
}

func (c HTTPClient) RawProto(ctx context.Context, method string, path string, input, output proto.Message) error {
inputBytes, err := json.Marshal(input)
if err != nil {
return err
}

ret, err := c.Raw(ctx, method, path, inputBytes)
if err != nil {
return err
}

return jsonpb.UnmarshalString(string(ret), output)
}

func (c HTTPClient) Raw(ctx context.Context, method string, path string, input []byte) ([]byte, error) {
url := c.baseAPI + path
b := bytes.NewBuffer(input)
Expand Down

0 comments on commit 7fe1471

Please sign in to comment.