Skip to content
Open
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ To help you start building real-world applications, we've created Kool Presets a
- **Node**: [NestJS](docs/03-Presets/NestJS.md), [AdonisJs](docs/03-Presets/AdonisJs.md), [Express.js](/docs/03-Presets/ExpressJS.md)
- **PHP**: [Laravel](docs/03-Presets/Laravel.md), [Laravel Octane](docs/03-Presets/Laravel+Octane.md), [Symfony](docs/03-Presets/Symfony.md), [CodeIgniter](docs/03-Presets/CodeIgniter.md)
- **Javascript**: [Next.js](docs/03-Presets/NextJS.md), [NuxtJS](docs/03-Presets/NuxtJS.md)
- **Java**: [Java with Gradle](docs/03-Presets/Java.md), [Spring Boot](docs/03-Presets/SpringBoot.md)
- **Others**: [Hugo](docs/03-Presets/Hugo.md), [WordPress](docs/03-Presets/WordPress.md)

#### Monorepo structures
Expand Down
26 changes: 26 additions & 0 deletions core/automate/actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const (
TypePrompt
TypeRecipe
TypeMerge
TypeInput
TypeAPI
)

// ActionSet represents a set of single actions or a question
Expand All @@ -34,8 +36,24 @@ type Action struct {
Scripts []string `yaml:"scripts"`
// prompt
Prompt string `yaml:"prompt"`
Input string `yaml:"input"`
Default string `yaml:"default"`
Options []*ActionSet `yaml:"options"`
// api
API string `yaml:"api"`
Prompts []*APIField `yaml:"prompts"`
}

// APIField describes a prompt backed by a field in an API response.
type APIField struct {
Path string `yaml:"path"`
Options string `yaml:"options"`
Value string `yaml:"value"`
Label string `yaml:"label"`
Default string `yaml:"default"`
Prompt string `yaml:"prompt"`
Ref string `yaml:"ref"`
Multiple bool `yaml:"multiple"`
}

// Type tells the actual implementation of this action
Expand All @@ -56,9 +74,17 @@ func (a *Action) Type() ActionType {
return TypePrompt
}

if a.Input != "" {
return TypeInput
}

if a.Merge != "" {
return TypeMerge
}

if a.API != "" {
return TypeAPI
}

return TypeUnknown
}
43 changes: 43 additions & 0 deletions core/automate/actions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,49 @@ func TestParseActionPrompt(t *testing.T) {
})
}

func TestParseActionInput(t *testing.T) {
a := parseAction("input: 'Project name'\nref: 'PROJECT_NAME'\ndefault: 'application'", t)

if a.Input != "Project name" || a.Ref != "PROJECT_NAME" || a.Default != "application" {
t.Errorf("failed parsing ActionInput: %v", a)
}
if a.Type() != TypeInput {
t.Errorf("failed parsing ActionInput type; got: %v", a.Type())
}
}

func TestParseActionAPI(t *testing.T) {
a := parseAction("api: 'https://example.test/options'\nprompts:\n - path: 'data'\n options: 'items'\n value: 'key'\n label: 'title'\n multiple: true", t)

if a.API == "" || len(a.Prompts) != 1 || a.Prompts[0].Options != "items" || !a.Prompts[0].Multiple {
t.Errorf("failed parsing ActionAPI: %v", a)
}
if a.Type() != TypeAPI {
t.Errorf("failed parsing ActionAPI type; got: %v", a.Type())
}
}

func TestAPIOptions(t *testing.T) {
data := map[string]any{
"data": map[string]any{
"default": "two",
"items": []any{
map[string]any{"key": "one", "title": "One"},
map[string]any{"key": "two", "title": "Two"},
},
},
}
options, defaultValue, err := apiOptions(data, &APIField{
Path: "data",
Options: "items",
Value: "key",
Label: "title",
})
if err != nil || len(options) != 2 || options[1].Value != "two" || defaultValue != "two" {
t.Errorf("unexpected API options: options=%v default=%q err=%v", options, defaultValue, err)
}
}

func TestParseActionMerge(t *testing.T) {
t.Run("Parse merge basic", func(t *testing.T) {
a := parseAction("merge: 'foo'", t)
Expand Down
208 changes: 208 additions & 0 deletions core/automate/executor.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package automate

import (
"encoding/json"
"fmt"
"io"
"kool-dev/kool/core/builder"
"kool-dev/kool/core/shell"
"kool-dev/kool/services/yamler"
"net/http"
"os"
"strings"
"time"

"github.com/spf13/afero"
Expand All @@ -21,6 +24,8 @@ type Executor struct {
getFromSource RetrieveSource
local afero.Fs
prompter shell.PromptSelect
multiPrompter shell.PromptMultiSelect
input shell.PromptInput

// promptState is a map of prompt answers
promptState map[string]string
Expand All @@ -32,6 +37,8 @@ func NewExecutor(sh shell.Shell, fn RetrieveSource) *Executor {
getFromSource: fn,
local: afero.NewOsFs(),
prompter: shell.NewPromptSelect(),
multiPrompter: shell.NewPromptMultiSelect(),
input: shell.NewPromptInput(),
promptState: make(map[string]string),
}
}
Expand Down Expand Up @@ -71,6 +78,14 @@ func (e *Executor) Do(steps []*ActionSet) (err error) {
if err = e.prompt(action); err != nil {
return
}
case TypeInput:
if err = e.inputValue(action); err != nil {
return
}
case TypeAPI:
if err = e.api(action); err != nil {
return
}
default:
err = fmt.Errorf("ops, something is wrong with this preset config (%d)", action.Type())
return
Expand Down Expand Up @@ -220,6 +235,199 @@ func (e *Executor) prompt(action *Action) (err error) {
return
}

func (e *Executor) inputValue(action *Action) (err error) {
value, err := e.input.Input(action.Input, action.Default)
if err != nil {
return
}
if action.Ref != "" {
e.promptState[action.Ref] = value
}

if action.Ref != "" {
err = os.Setenv(action.Ref, value)
}
return
}

func (e *Executor) api(action *Action) (err error) {
var (
response *http.Response
data map[string]any
)

client := &http.Client{Timeout: 15 * time.Second}
if response, err = client.Get(action.API); err != nil {
return
}
defer func() {
if closeErr := response.Body.Close(); err == nil {
err = closeErr
}
}()

if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
return fmt.Errorf("API request %s returned HTTP %d", action.API, response.StatusCode)
}
if err = json.NewDecoder(response.Body).Decode(&data); err != nil {
return fmt.Errorf("could not decode API response from %s: %w", action.API, err)
}

for _, field := range action.Prompts {
var (
values []apiOption
defaultValue string
)
if values, defaultValue, err = apiOptions(data, field); err != nil {
return fmt.Errorf("could not read API field %q: %w", field.Path, err)
}
if len(values) == 0 {
return fmt.Errorf("API field %q did not contain any options", field.Path)
}

options := make([]string, 0, len(values))
byLabel := make(map[string]string, len(values))
for _, option := range values {
options = append(options, option.Label)
byLabel[option.Label] = option.Value
}
if defaultValue != "" {
defaultLabel := ""
for _, option := range values {
if option.Value == defaultValue {
defaultLabel = option.Label
break
}
}
if defaultLabel != "" {
for i, option := range options {
if option == defaultLabel {
options = append([]string{defaultLabel}, append(options[:i], options[i+1:]...)...)
break
}
}
}
}

if field.Multiple {
var selected []string
if selected, err = e.multiPrompter.AskMany(field.Prompt, options); err != nil {
return
}
ids := make([]string, 0, len(selected))
for _, label := range selected {
if value, ok := byLabel[label]; ok {
ids = append(ids, value)
}
}
err = e.setAPIValue(field.Ref, strings.Join(ids, ","))
continue
}

var selected string
if selected, err = e.prompter.Ask(field.Prompt, options); err != nil {
return
}
err = e.setAPIValue(field.Ref, byLabel[selected])
}
return
}

type apiOption struct {
Label string
Value string
}

func apiOptions(data map[string]any, field *APIField) (options []apiOption, defaultValue string, err error) {
var current any
if current, err = apiPath(data, field.Path); err != nil {
return nil, "", err
}
if object, ok := current.(map[string]any); ok {
defaultValue, _ = object["default"].(string)
if field.Options != "" {
current, err = apiPath(object, field.Options)
} else {
current = object["values"]
}
} else if field.Options != "" {
return nil, "", fmt.Errorf("options path %q requires an object at path %q", field.Options, field.Path)
}
if field.Default != "" {
defaultValue = field.Default
}
if err != nil {
return nil, "", err
}
values, ok := current.([]any)
if !ok {
return nil, "", fmt.Errorf("path %q has no options", field.Path)
}
options, err = flattenAPIOptions(values, "", field.Value, field.Label)
return
}

func apiPath(root any, path string) (any, error) {
current := root
for _, part := range strings.Split(path, ".") {
if part == "" {
continue
}
value, ok := current.(map[string]any)
if !ok {
return nil, fmt.Errorf("options path %q is not an object", path)
}
current, ok = value[part]
if !ok {
return nil, fmt.Errorf("options path %q does not exist", path)
}
}
return current, nil
}

func flattenAPIOptions(values []any, group, valueKey, labelKey string) ([]apiOption, error) {
var options []apiOption
for _, raw := range values {
object, ok := raw.(map[string]any)
if !ok {
return nil, fmt.Errorf("option is not an object")
}
name, _ := object["name"].(string)
id, _ := object["id"].(string)
if nested, ok := object["values"].([]any); ok {
if nestedOptions, err := flattenAPIOptions(nested, name, valueKey, labelKey); err != nil {
return nil, err
} else {
options = append(options, nestedOptions...)
}
continue
}
if valueKey != "" {
id, _ = object[valueKey].(string)
}
if labelKey != "" {
name, _ = object[labelKey].(string)
}
if id == "" || name == "" {
continue
}
label := name
if group != "" {
label = group + ": " + name
}
options = append(options, apiOption{Label: label, Value: id})
}
return options, nil
}

func (e *Executor) setAPIValue(ref, value string) error {
if ref == "" {
return nil
}
e.promptState[ref] = value
return os.Setenv(ref, value)
}

func (e *Executor) recipe(action *Action) (err error) {
var (
set = new(ActionSet)
Expand Down
10 changes: 10 additions & 0 deletions core/shell/fake_prompt_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ func (f *FakePromptSelect) Ask(question string, options []string) (answer string
return
}

// AskMany mocked behavior for testing multiple option prompts.
func (f *FakePromptSelect) AskMany(question string, options []string) (answers []string, err error) {
f.CalledAsk = true
if answer := f.MockAnswer[question]; answer != "" {
answers = []string{answer}
}
err = f.MockError[question]
return
}

// Confirm mocked behavior for testing prompting a confirm question
func (f *FakePromptSelect) Confirm(question string, args ...any) (confirmed bool, err error) {
f.CalledConfirm = append(f.CalledConfirm, &struct {
Expand Down
Loading
Loading