Skip to content

Commit

Permalink
Add STDNIN placeholder
Browse files Browse the repository at this point in the history
In order to forward the original hook stdIn to other scripts the
Cap'n now provides a STDIN placeholder.
For example forwarding the stdIn to existing git-lfs hooks would
look like this

  {"action": "echo {$STDIN} | hooks/git-lfs/pre-push"}
  • Loading branch information
sebastianfeldmann committed Sep 9, 2024
1 parent e280012 commit f23a560
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
3 changes: 3 additions & 0 deletions hooks/placeholder/placeholder.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ var (
files, _ := aContext.Repository().StagedFiles()
return &FileList{name: "STAGED_FILES", context: aContext, files: files}
},
"STDIN": func(aContext *app.Context) Replacer {
return &StdIn{context: aContext}
},
}
)

Expand Down
18 changes: 18 additions & 0 deletions hooks/placeholder/stdin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package placeholder

import (
"github.com/captainhook-go/captainhook/hooks/app"
"github.com/captainhook-go/captainhook/io"
)

type StdIn struct {
context *app.Context
}

func (r *StdIn) Replacement(options map[string]string) string {
esc := "'"
if !io.AnswerToBool(io.MappedStringOrDefault(options, "escaped", "true")) {
esc = ""
}
return esc + r.context.IO().Option("input", "") + esc
}
49 changes: 49 additions & 0 deletions hooks/placeholder/stdin_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package placeholder

import (
"github.com/captainhook-go/captainhook/configuration"
"github.com/captainhook-go/captainhook/git"
"github.com/captainhook-go/captainhook/hooks/app"
"github.com/captainhook-go/captainhook/io"
"testing"
)

func TestStdin(t *testing.T) {
argMap := map[string]string{}
optMap := map[string]string{"input": "foo bar"}
expected := "'foo bar'"

config := configuration.NewConfiguration("foo", false)
repo, _ := git.NewRepository(".git")
ctx := app.NewContext(
io.NewDefaultIO(io.NORMAL, optMap, argMap),
config,
repo,
)
opts := map[string]string{}
placeholder := &StdIn{context: ctx}
result := placeholder.Replacement(opts)
if result != expected {
t.Errorf("Replacement didn't work, got: %s, want: %s.", result, expected)
}
}

func TestStdinUnescaped(t *testing.T) {
argMap := map[string]string{}
optMap := map[string]string{"input": "foo bar"}
expected := "foo bar"

config := configuration.NewConfiguration("foo", false)
repo, _ := git.NewRepository(".git")
ctx := app.NewContext(
io.NewDefaultIO(io.NORMAL, optMap, argMap),
config,
repo,
)
opts := map[string]string{"escaped": "false"}
placeholder := &StdIn{context: ctx}
result := placeholder.Replacement(opts)
if result != expected {
t.Errorf("Replacement didn't work, got: %s, want: %s.", result, expected)
}
}

0 comments on commit f23a560

Please sign in to comment.