Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tui: selection mode #42

Merged
merged 21 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions cli/any.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package cli

import (
"fmt"

"github.com/charmbracelet/lipgloss"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/wrapperspb"
)

var (
anyTypeStyle = lipgloss.NewStyle().Foreground(grayColor)
anyNilStyle = lipgloss.NewStyle().Foreground(grayColor)
)

func anyString(any *anypb.Any) string {
if any == nil {
return anyNilStyle.Render("nil")
}
switch any.TypeUrl {
case "type.googleapis.com/google.protobuf.BytesValue":
if s, err := anyBytesString(any); err == nil && s != "" {
return s
}
// Suppress the error; render the type only.
}
return anyTypeStyle.Render(fmt.Sprintf("<%s>", any.TypeUrl))

}

func anyBytesString(any *anypb.Any) (string, error) {
m, err := anypb.UnmarshalNew(any, proto.UnmarshalOptions{})
if err != nil {
return "", err
}
bv, ok := m.(*wrapperspb.BytesValue)
if !ok {
return "", fmt.Errorf("invalid bytes value: %T", m)
}
b := bv.Value

// TODO: support unpacking other types of serialized values
return pythonPickleString(b)
}
2 changes: 1 addition & 1 deletion cli/color.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ var (

// See https://www.hackitu.de/termcolor256/
grayColor = lipgloss.ANSIColor(102)
redColor = lipgloss.ANSIColor(124)
redColor = lipgloss.ANSIColor(160)
greenColor = lipgloss.ANSIColor(34)
yellowColor = lipgloss.ANSIColor(142)
magentaColor = lipgloss.ANSIColor(127)
Expand Down
224 changes: 224 additions & 0 deletions cli/python.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
package cli

import (
"bytes"
"fmt"
"strings"

"github.com/charmbracelet/lipgloss"
"github.com/nlpodyssey/gopickle/pickle"
"github.com/nlpodyssey/gopickle/types"
)

var (
kwargStyle = lipgloss.NewStyle().Foreground(grayColor)
)

func pythonPickleString(b []byte) (string, error) {
u := pickle.NewUnpickler(bytes.NewReader(b))
u.FindClass = findPythonClass

value, err := u.Load()
if err != nil {
return "", err
}
return pythonValueString(value)
}

func pythonValueString(value interface{}) (string, error) {
switch v := value.(type) {
case nil:
return "None", nil
case bool:
if v {
return "True", nil
}
return "False", nil
case string:
return fmt.Sprintf("%q", v), nil
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, float32, float64:
return fmt.Sprintf("%v", v), nil
case *types.List:
return pythonListString(v)
case *types.Tuple:
return pythonTupleString(v)
case *types.Dict:
return pythonDictString(v)
case *types.Set:
return pythonSetString(v)
case *pythonArgumentsObject:
return pythonArgumentsString(v)
case *types.GenericClass:
return fmt.Sprintf("%s.%s", v.Module, v.Name), nil
case *types.GenericObject:
s, _ := pythonValueString(v.Class)
return fmt.Sprintf("%s(?)", s), nil
default:
return "", fmt.Errorf("unsupported Python value: %T", value)
}
}

func pythonListString(list *types.List) (string, error) {
var b strings.Builder
b.WriteByte('[')
for i, entry := range *list {
if i > 0 {
b.WriteString(", ")
}
s, err := pythonValueString(entry)
if err != nil {
return "", err
}
b.WriteString(s)
}
b.WriteByte(']')
return b.String(), nil
}

func pythonTupleString(tuple *types.Tuple) (string, error) {
var b strings.Builder
b.WriteByte('(')
for i, entry := range *tuple {
if i > 0 {
b.WriteString(", ")
}
s, err := pythonValueString(entry)
if err != nil {
return "", err
}
b.WriteString(s)
}
b.WriteByte(')')
return b.String(), nil
}

func pythonDictString(dict *types.Dict) (string, error) {
var b strings.Builder
b.WriteByte('{')
for i, entry := range *dict {
if i > 0 {
b.WriteString(", ")
}
keyStr, err := pythonValueString(entry.Key)
if err != nil {
return "", err
}
b.WriteString(keyStr)
b.WriteString(": ")

valueStr, err := pythonValueString(entry.Value)
if err != nil {
return "", err
}
b.WriteString(valueStr)
}
b.WriteByte('}')
return b.String(), nil
}

func pythonSetString(set *types.Set) (string, error) {
var b strings.Builder
b.WriteByte('{')
var i int
for entry := range *set {
if i > 0 {
b.WriteString(", ")
}
s, err := pythonValueString(entry)
if err != nil {
return "", err
}
b.WriteString(s)
i++
}
b.WriteByte('}')
return b.String(), nil
}

func pythonArgumentsString(a *pythonArgumentsObject) (string, error) {
var b strings.Builder
b.WriteByte('(')

var argsLen int
if a.args != nil {
argsLen = a.args.Len()
for i := 0; i < argsLen; i++ {
if i > 0 {
b.WriteString(", ")
}
arg := a.args.Get(i)
s, err := pythonValueString(arg)
if err != nil {
return "", err
}
b.WriteString(s)
}
}

if a.kwargs != nil {
for i, entry := range *a.kwargs {
if i > 0 || argsLen > 0 {
b.WriteString(", ")
}
var keyStr string
if s, ok := entry.Key.(string); ok {
keyStr = s
} else {
var err error
keyStr, err = pythonValueString(entry.Key)
if err != nil {
return "", err
}
}
b.WriteString(kwargStyle.Render(keyStr + "="))

valueStr, err := pythonValueString(entry.Value)
if err != nil {
return "", err
}
b.WriteString(valueStr)
}
}

b.WriteByte(')')
return b.String(), nil

}

func findPythonClass(module, name string) (interface{}, error) {
// https://github.com/dispatchrun/dispatch-py/blob/0a482491/src/dispatch/proto.py#L175
if module == "dispatch.proto" && name == "Arguments" {
return &pythonArgumentsClass{}, nil
}
return types.NewGenericClass(module, name), nil
}

type pythonArgumentsClass struct{}

func (a *pythonArgumentsClass) PyNew(args ...interface{}) (interface{}, error) {
return &pythonArgumentsObject{}, nil
}

type pythonArgumentsObject struct {
args *types.Tuple
kwargs *types.Dict
}

var _ types.PyDictSettable = (*pythonArgumentsObject)(nil)

func (a *pythonArgumentsObject) PyDictSet(key, value interface{}) error {
var ok bool
switch key {
case "args":
if a.args, ok = value.(*types.Tuple); !ok {
return fmt.Errorf("invalid Arguments.args: %T", value)
}
case "kwargs":
if a.kwargs, ok = value.(*types.Dict); !ok {
return fmt.Errorf("invalid Arguments.kwargs: %T", value)
}
default:
return fmt.Errorf("unexpected key: %v", key)
}
return nil
}
17 changes: 9 additions & 8 deletions cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ func poll(ctx context.Context, client *http.Client, url string) (string, *http.R
type FunctionCallObserver interface {
// ObserveRequest observes a RunRequest as it passes from the API through
// the CLI to the local application.
ObserveRequest(*sdkv1.RunRequest)
ObserveRequest(time.Time, *sdkv1.RunRequest)

// ObserveResponse observes a response to the RunRequest.
//
Expand All @@ -383,7 +383,7 @@ type FunctionCallObserver interface {
//
// ObserveResponse always comes after a call to ObserveRequest for any given
// RunRequest.
ObserveResponse(*sdkv1.RunRequest, error, *http.Response, *sdkv1.RunResponse)
ObserveResponse(time.Time, *sdkv1.RunRequest, error, *http.Response, *sdkv1.RunResponse)
}

func invoke(ctx context.Context, client *http.Client, url, requestID string, bridgeGetRes *http.Response, observer FunctionCallObserver) error {
Expand Down Expand Up @@ -430,7 +430,7 @@ func invoke(ctx context.Context, client *http.Client, url, requestID string, bri
logger.Info("resuming function", "function", runRequest.Function)
}
if observer != nil {
observer.ObserveRequest(&runRequest)
observer.ObserveRequest(time.Now(), &runRequest)
}

// The RequestURI field must be cleared for client.Do() to
Expand All @@ -442,9 +442,10 @@ func invoke(ctx context.Context, client *http.Client, url, requestID string, bri
endpointReq.URL.Scheme = "http"
endpointReq.URL.Host = LocalEndpoint
endpointRes, err := client.Do(endpointReq)
now := time.Now()
if err != nil {
if observer != nil {
observer.ObserveResponse(&runRequest, err, nil, nil)
observer.ObserveResponse(now, &runRequest, err, nil, nil)
}
return fmt.Errorf("failed to contact local application endpoint (%s): %v. Please check that -e,--endpoint is correct.", LocalEndpoint, err)
}
Expand All @@ -458,7 +459,7 @@ func invoke(ctx context.Context, client *http.Client, url, requestID string, bri
endpointRes.Body.Close()
if err != nil {
if observer != nil {
observer.ObserveResponse(&runRequest, err, endpointRes, nil)
observer.ObserveResponse(now, &runRequest, err, endpointRes, nil)
}
return fmt.Errorf("failed to read response from local application endpoint (%s): %v", LocalEndpoint, err)
}
Expand All @@ -470,7 +471,7 @@ func invoke(ctx context.Context, client *http.Client, url, requestID string, bri
var runResponse sdkv1.RunResponse
if err := proto.Unmarshal(endpointResBody.Bytes(), &runResponse); err != nil {
if observer != nil {
observer.ObserveResponse(&runRequest, err, endpointRes, nil)
observer.ObserveResponse(now, &runRequest, err, endpointRes, nil)
}
return fmt.Errorf("invalid response from local application endpoint (%s): %v", LocalEndpoint, err)
}
Expand All @@ -491,13 +492,13 @@ func invoke(ctx context.Context, client *http.Client, url, requestID string, bri
logger.Warn("function call failed", "function", runRequest.Function, "status", statusString(runResponse.Status), "error_type", err.GetType(), "error_message", err.GetMessage())
}
if observer != nil {
observer.ObserveResponse(&runRequest, nil, endpointRes, &runResponse)
observer.ObserveResponse(now, &runRequest, nil, endpointRes, &runResponse)
}
} else {
// The response might indicate some other issue, e.g. it could be a 404 if the function can't be found
logger.Warn("function call failed", "function", runRequest.Function, "http_status", endpointRes.StatusCode)
if observer != nil {
observer.ObserveResponse(&runRequest, nil, endpointRes, nil)
observer.ObserveResponse(now, &runRequest, nil, endpointRes, nil)
}
}

Expand Down
9 changes: 2 additions & 7 deletions cli/style.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ import (
)

var (
green = lipgloss.Color("#00FF00")
red = lipgloss.Color("#FF0000")

dialogBoxStyle = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("#874BFD")).
Expand All @@ -22,11 +19,9 @@ var (
BorderRight(true).
BorderBottom(true)

successStyle = lipgloss.NewStyle().
Foreground(green)
successStyle = lipgloss.NewStyle().Foreground(greenColor)

failureStyle = lipgloss.NewStyle().
Foreground(red)
failureStyle = lipgloss.NewStyle().Foreground(redColor)
)

type errMsg struct{ error }
Expand Down
Loading
Loading