Skip to content

Commit

Permalink
server/run: replace params with their values
Browse files Browse the repository at this point in the history
  • Loading branch information
joshi4 committed Jun 14, 2024
1 parent c8de3f7 commit 7ca6ebf
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 2 deletions.
2 changes: 1 addition & 1 deletion cmd/internal/current.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var currentCmd = &cobra.Command{
return
}

fmt.Printf("%s", state.Command)
fmt.Printf("%s", state.CommandWithSetParams())
},
}

Expand Down
11 changes: 10 additions & 1 deletion server/run/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"log/slog"
"net"
"os"
"strings"
"sync/atomic"

savvy_client "github.com/getsavvyinc/savvy-cli/client"
Expand Down Expand Up @@ -40,7 +41,15 @@ type State struct {
}

func (s *State) CommandWithSetParams() string {
return s.Command
if s.Params == nil || len(s.Params) == 0 {
return s.Command
}

cmd := s.Command
for k, v := range s.Params {
cmd = strings.ReplaceAll(cmd, k, v)
}
return cmd
}

const DefaultRunSocketPath = "/tmp/savvy-run.sock"
Expand Down
60 changes: 60 additions & 0 deletions server/run/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,63 @@ func newTestServerWithClient(t *testing.T, rb *savvy_client.Runbook) (*RunServer
go srv.ListenAndServe()
return srv, cl, srv.Close
}

func TestCommandWithSetParams(t *testing.T) {
testCases := []struct {
name string
state *State
expected string
}{
{
name: "no params",
state: &State{
Command: "echo hello",
Index: 0,
Params: nil,
},
expected: "echo hello",
},
{
name: "no params in command",
state: &State{
Command: "echo hello",
Index: 0,
Params: map[string]string{"<param>": "world"},
},
expected: "echo hello",
},
{
name: "single param",
state: &State{
Command: "echo <param>",
Index: 0,
Params: map[string]string{"<param>": "world"},
},
expected: "echo world",
},
{
name: "multiple instance of same param",
state: &State{
Command: "echo <param> <param>",
Index: 0,
Params: map[string]string{"<param>": "world"},
},
expected: "echo world world",
},
{
name: "multiple params",
state: &State{
Command: "echo <param1> <param2>",
Index: 0,
Params: map[string]string{"<param1>": "hello", "<param2>": "world"},
},
expected: "echo hello world",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.expected, tc.state.CommandWithSetParams())
})
}
}

0 comments on commit 7ca6ebf

Please sign in to comment.