Can shebang yq scripts! #1851

This commit is contained in:
Mike Farah 2024-02-16 10:47:50 +11:00
parent 047694546c
commit 86bb90f989
4 changed files with 39 additions and 1 deletions

26
acceptance_tests/shebang.sh Executable file
View File

@ -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

View File

@ -255,6 +255,16 @@ func processStdInArgs(args []string) []string {
func processArgs(originalArgs []string) (string, []string, error) { func processArgs(originalArgs []string) (string, []string, error) {
expression := forceExpression 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 != "" { if expressionFile != "" {
expressionBytes, err := os.ReadFile(expressionFile) expressionBytes, err := os.ReadFile(expressionFile)
if err != nil { if err != nil {
@ -264,7 +274,6 @@ func processArgs(originalArgs []string) (string, []string, error) {
expression = strings.ReplaceAll(string(expressionBytes), "\r\n", "\n") expression = strings.ReplaceAll(string(expressionBytes), "\r\n", "\n")
} }
args := processStdInArgs(originalArgs)
yqlib.GetLogger().Debugf("processed args: %v", args) yqlib.GetLogger().Debugf("processed args: %v", args)
if expression == "" && len(args) > 0 && args[0] != "-" && !maybeFile(args[0]) { if expression == "" && len(args) > 0 && args[0] != "-" && !maybeFile(args[0]) {
yqlib.GetLogger().Debug("assuming expression is '%v'", args[0]) yqlib.GetLogger().Debug("assuming expression is '%v'", args[0])

1
examples/environment.yq Normal file → Executable file
View File

@ -1,3 +1,4 @@
#!yq
.[] |( .[] |(
( select(kind == "scalar") | key + "='" + . + "'"), ( select(kind == "scalar") | key + "='" + . + "'"),
( select(kind == "seq") | key + "=(" + (map("'" + . + "'") | join(",")) + ")") ( select(kind == "seq") | key + "=(" + (map("'" + . + "'") | join(",")) + ")")

2
test.yq Executable file
View File

@ -0,0 +1,2 @@
#!./yq
.a.b