Skip to content

Commit

Permalink
Can shebang yq scripts! #1851
Browse files Browse the repository at this point in the history
  • Loading branch information
mikefarah committed Feb 15, 2024
1 parent 0476945 commit 86bb90f
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
26 changes: 26 additions & 0 deletions acceptance_tests/shebang.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/bin/bash

setUp() {
rm test*.yq || true
cat >test.yq <<EOL
#!./yq
.a.b
EOL
chmod +x test.yq

rm test*.yml || true
cat >test.yml <<EOL
a: {b: apple}
EOL
}

testCanExecYqFile() {
read -r -d '' expected << EOM
apple
EOM
X=$(./test.yq test.yml)
assertEquals "$expected" "$X"
}

source ./scripts/shunit2

11 changes: 10 additions & 1 deletion cmd/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,16 @@ func processStdInArgs(args []string) []string {

func processArgs(originalArgs []string) (string, []string, error) {
expression := forceExpression
args := processStdInArgs(originalArgs)
maybeFirstArgIsAFile := len(args) > 0 && maybeFile(args[0])

if expressionFile == "" && maybeFirstArgIsAFile && strings.HasSuffix(args[0], ".yq") {
// lets check if an expression file was given
yqlib.GetLogger().Debug("Assuming arg %v is an expression file", args[0])
expressionFile = args[0]
args = args[1:]
}

if expressionFile != "" {
expressionBytes, err := os.ReadFile(expressionFile)
if err != nil {
Expand All @@ -264,7 +274,6 @@ func processArgs(originalArgs []string) (string, []string, error) {
expression = strings.ReplaceAll(string(expressionBytes), "\r\n", "\n")
}

args := processStdInArgs(originalArgs)
yqlib.GetLogger().Debugf("processed args: %v", args)
if expression == "" && len(args) > 0 && args[0] != "-" && !maybeFile(args[0]) {
yqlib.GetLogger().Debug("assuming expression is '%v'", args[0])
Expand Down
1 change: 1 addition & 0 deletions examples/environment.yq
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!yq
.[] |(
( select(kind == "scalar") | key + "='" + . + "'"),
( select(kind == "seq") | key + "=(" + (map("'" + . + "'") | join(",")) + ")")
Expand Down
2 changes: 2 additions & 0 deletions test.yq
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!./yq
.a.b

0 comments on commit 86bb90f

Please sign in to comment.