Skip to content

Commit efffba1

Browse files
committed
feat: add early eval option support
1 parent f188794 commit efffba1

3 files changed

Lines changed: 82 additions & 1 deletion

File tree

dialog/dynamic_options.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package dialog
2+
3+
import (
4+
"bytes"
5+
"fmt"
6+
"log"
7+
"os"
8+
"strings"
9+
10+
runner "github.com/knqyf263/pet/cmd/runner"
11+
)
12+
13+
// DynamicOptions run a command, split and returns an array of strings. It expect to
14+
// receive command substitions.
15+
//
16+
// Example:
17+
//
18+
// DynamicOptions("$(fd -tf --hidden --no-ignore --max-depth=1 .)")
19+
func DynamicOptions(what string) ([]string, error) {
20+
if what[:2] != "$(" || what[len(what)-1] != ')' {
21+
return nil, fmt.Errorf("no evaluated command found: %v", what)
22+
}
23+
24+
var w bytes.Buffer
25+
err := runner.Run(what[2:len(what)-1], os.Stdin, &w)
26+
if err != nil {
27+
log.Fatal(what)
28+
return nil, err
29+
}
30+
31+
return strings.Split(strings.TrimSpace(w.String()), "\n"), nil
32+
}

dialog/dynamic_options_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package dialog_test
2+
3+
import (
4+
"slices"
5+
"testing"
6+
7+
"github.com/knqyf263/pet/dialog"
8+
)
9+
10+
const nameOfThisFile = "eval_test.go"
11+
12+
func TestEvaluator(t *testing.T) {
13+
param := "$(ls)"
14+
15+
e, err := dialog.DynamicOptions(param)
16+
if err != nil {
17+
t.Log(err)
18+
t.FailNow()
19+
}
20+
21+
if len(e) == 0 {
22+
t.Log("Expected at least one result, but got none.")
23+
t.FailNow()
24+
}
25+
26+
if !slices.Contains(e, nameOfThisFile) {
27+
t.Log("it should have the current file in this path")
28+
t.FailNow()
29+
}
30+
}

dialog/view.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,26 @@ func GenerateParamsLayout(params [][2]string, command string) {
134134
r := regexp.MustCompile(parameterMultipleValueRegex)
135135
matches := r.FindAllStringSubmatch(parameterValue, -1)
136136

137-
if len(matches) > 0 {
137+
if len(matches) == 1 {
138+
// Extract the default values and generate multiple params view
139+
// using early evaluation context
140+
matchedGroup := matches[0][1]
141+
parameter := matchedGroup[2 : len(matchedGroup)-2]
142+
143+
options, err := DynamicOptions(parameter)
144+
if err != nil {
145+
// fallback to default evaluation (raw)
146+
options = []string{parameter}
147+
}
148+
149+
generateMultipleParameterView(
150+
g, parameterKey, options, []int{
151+
leftX,
152+
(maxY / 4) + (idx+1)*layoutStep,
153+
rightX,
154+
(maxY / 4) + 2 + (idx+1)*layoutStep},
155+
true)
156+
} else if len(matches) > 0 {
138157
// Extract the default values and generate multiple params view
139158
parameters := []string{}
140159
for _, p := range matches {

0 commit comments

Comments
 (0)