Skip to content

Commit

Permalink
Handle -1 option for first element #3
Browse files Browse the repository at this point in the history
  • Loading branch information
xonixx committed Jun 19, 2020
1 parent 279df56 commit 6c1e38f
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/main/java/com/github/jsqry/cli/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ public static void main(String[] args) {
help.setRequired(false);
options.addOption(help);

Option first = new Option("1", "first", false, "return first result element");
first.setRequired(false);
options.addOption(first);

CommandLineParser parser = new DefaultParser();
CommandLine cmd;

Expand Down Expand Up @@ -76,7 +80,8 @@ public static void main(String[] args) {
Value doWork = context.eval("js", "doWork");

String inputJsonStr = new String(System.in.readAllBytes(), StandardCharsets.UTF_8);
Value result = doWork.execute(inputJsonStr, query);

Value result = doWork.execute(inputJsonStr, query, cmd.hasOption(first.getLongOpt()));
if (!result.asBoolean()) {
System.exit(1);
}
Expand Down
4 changes: 2 additions & 2 deletions src/main/resources/app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function doWork(jsonStr, queryStr) {
function doWork(jsonStr, queryStr, useFirst) {
let json;
try {
json = JSON.parse(jsonStr);
Expand All @@ -8,7 +8,7 @@ function doWork(jsonStr, queryStr) {
}
let res;
try {
res = jsqry.query(json, queryStr);
res = (useFirst ? jsqry.first : jsqry.query)(json, queryStr);
} catch (e) {
console.error('error: ' + e);
return false;
Expand Down
1 change: 1 addition & 0 deletions test_app.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ CP=$(mvn -q exec:exec -Dexec.executable=echo -Dexec.args="%classpath")
echo $CP

echo '[{"a":1},{"a":2}]' | $JAVA -cp "$CP" com.github.jsqry.cli.App "a"
echo '[{"a":1},{"a":2}]' | $JAVA -cp "$CP" com.github.jsqry.cli.App -1 "a[1]"
echo 'wrong' | $JAVA -cp "$CP" com.github.jsqry.cli.App "a"
echo '[]' | $JAVA -cp "$CP" com.github.jsqry.cli.App "]"

0 comments on commit 6c1e38f

Please sign in to comment.