Skip to content

Commit

Permalink
feat: add early eval option support
Browse files Browse the repository at this point in the history
  • Loading branch information
ppcamp committed Sep 21, 2024
1 parent f188794 commit efffba1
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 1 deletion.
32 changes: 32 additions & 0 deletions dialog/dynamic_options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package dialog

import (
"bytes"
"fmt"
"log"
"os"
"strings"

runner "github.com/knqyf263/pet/cmd/runner"
)

// DynamicOptions run a command, split and returns an array of strings. It expect to
// receive command substitions.
//
// Example:
//
// DynamicOptions("$(fd -tf --hidden --no-ignore --max-depth=1 .)")
func DynamicOptions(what string) ([]string, error) {
if what[:2] != "$(" || what[len(what)-1] != ')' {
return nil, fmt.Errorf("no evaluated command found: %v", what)
}

var w bytes.Buffer
err := runner.Run(what[2:len(what)-1], os.Stdin, &w)
if err != nil {
log.Fatal(what)
return nil, err
}

return strings.Split(strings.TrimSpace(w.String()), "\n"), nil
}
30 changes: 30 additions & 0 deletions dialog/dynamic_options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package dialog_test

import (
"slices"
"testing"

"github.com/knqyf263/pet/dialog"
)

const nameOfThisFile = "eval_test.go"

func TestEvaluator(t *testing.T) {
param := "$(ls)"

e, err := dialog.DynamicOptions(param)
if err != nil {
t.Log(err)
t.FailNow()
}

if len(e) == 0 {
t.Log("Expected at least one result, but got none.")
t.FailNow()
}

if !slices.Contains(e, nameOfThisFile) {
t.Log("it should have the current file in this path")
t.FailNow()
}
}
21 changes: 20 additions & 1 deletion dialog/view.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,26 @@ func GenerateParamsLayout(params [][2]string, command string) {
r := regexp.MustCompile(parameterMultipleValueRegex)
matches := r.FindAllStringSubmatch(parameterValue, -1)

if len(matches) > 0 {
if len(matches) == 1 {
// Extract the default values and generate multiple params view
// using early evaluation context
matchedGroup := matches[0][1]
parameter := matchedGroup[2 : len(matchedGroup)-2]

options, err := DynamicOptions(parameter)
if err != nil {
// fallback to default evaluation (raw)
options = []string{parameter}
}

generateMultipleParameterView(
g, parameterKey, options, []int{
leftX,
(maxY / 4) + (idx+1)*layoutStep,
rightX,
(maxY / 4) + 2 + (idx+1)*layoutStep},
true)
} else if len(matches) > 0 {
// Extract the default values and generate multiple params view
parameters := []string{}
for _, p := range matches {
Expand Down

0 comments on commit efffba1

Please sign in to comment.