Skip to content

Commit 88fbb7c

Browse files
authored
g.list: Print empty list for JSON (OSGeo#6302)
If nothing is found, still print an empty JSON list with format=json (but still nothing with other formats). Additionally, sort only with list with two or more items. While calling qsort on zero items should work, there is no reason to call it on zero items or one item.
1 parent de4f00d commit 88fbb7c

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

general/g.list/list.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ void print_list(FILE *fp, struct elist *el, int count, const char *separator,
8080
JSON_Object *map_object = NULL;
8181
JSON_Value *map_value = NULL;
8282

83-
if (!count)
83+
if (!count && format != JSON)
8484
return;
8585

8686
if (format == JSON) {
@@ -91,7 +91,8 @@ void print_list(FILE *fp, struct elist *el, int count, const char *separator,
9191
root_array = G_json_array(root_value);
9292
}
9393

94-
qsort(el, count, sizeof(struct elist), compare_elist);
94+
if (count > 1)
95+
qsort(el, count, sizeof(struct elist), compare_elist);
9596

9697
for (i = 0; i < count; i++) {
9798
int need_mapset = 0;

general/g.list/tests/g_list_test.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1-
import grass.script as gs
2-
import pytest
31
import sys
42

3+
import pytest
4+
5+
import grass.script as gs
6+
from grass.tools import Tools
7+
58

69
def test_default_output(simple_dataset):
710
"""Test default output of g.list."""
@@ -290,3 +293,15 @@ def test_json_output(simple_dataset):
290293
},
291294
]
292295
assert actual == expected
296+
297+
298+
def test_no_json_output(simple_dataset):
299+
"""Test g.list returning an empty JSON list"""
300+
tools = Tools(env=simple_dataset.env)
301+
result = tools.g_list(
302+
type="raster",
303+
pattern="does_not_exist",
304+
format="json",
305+
)
306+
assert not result
307+
assert list(result) == []

0 commit comments

Comments
 (0)