Skip to content

Commit

Permalink
fixup! Implement --json query format
Browse files Browse the repository at this point in the history
  • Loading branch information
pmatilai committed Feb 16, 2024
1 parent cb102a6 commit 34667b3
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 13 deletions.
72 changes: 61 additions & 11 deletions lib/formats.c
Original file line number Diff line number Diff line change
Expand Up @@ -339,27 +339,77 @@ static char * xmlFormat(rpmtd td, char **emsg)
return val;
}

static char * jsonFormat(rpmtd td, char **emsg)
static char *jsonEscape(const char *s)
{
char *es = NULL;
rstrcat(&es, "\"");
for (const char *c = s; *c != '\0'; c++) {
const char *ec = NULL;
switch (*c) {
case '\b':
ec = "\\b";
break;
case '\f':
ec = "\\f";
break;
case '\n':
ec = "\\n";
break;
case '\r':
ec = "\\t";
break;
case '\t':
ec = "\\t";
break;
case '"':
ec = "\\\"";
break;
case '\\':
ec = "\\\\";
break;
default:
break;
}

if (ec) {
rstrcat(&es, ec);
} else if (*c < 0x20) {
char *uc = NULL;
rasprintf(&uc, "\\\\u%04x", *c);
rstrcat(&es, uc);
free(uc);
} else {
char t[2] = " ";
*t = *c;
rstrcat(&es, t);
}
}
rstrcat(&es, "\"");
return es;
}

static char *jsonFormat(rpmtd td, char **emsg)
{
int isnum = 0;
char *s = NULL;
int escape = 1;
char *val = NULL;

switch (rpmtdClass(td)) {
case RPM_BINARY_CLASS:
/* json doesn't allow newlines, can't use base64Format() */
s = rpmBase64Encode(td->data, td->count, 0);
/* we don't want newlines in the binary output */
val = rpmBase64Encode(td->data, td->count, 0);
break;
case RPM_NUMERIC_CLASS:
isnum = 1;
escape = 0;
/* fallthrough */
default:
s = stringFormat(td, emsg);
val = stringFormat(td, emsg);
break;
}
char *val = NULL;
if (s) {
val = rstrscat(NULL, isnum ? "" : "\"", s, isnum ? "" : "\"", NULL);
free(s);

if (escape) {
char *s = jsonEscape(val);
free(val);
val = s;
}
return val;
}
Expand Down
6 changes: 4 additions & 2 deletions tests/rpmquery.at
Original file line number Diff line number Diff line change
Expand Up @@ -1185,8 +1185,10 @@ RPMTEST_CLEANUP
AT_SETUP([json format 2])
AT_KEYWORDS([query])
RPMDB_INIT
runroot rpmbuild --quiet -bb /data/SPECS/weirdnames.spec

RPMTEST_CHECK([
runroot rpm -q --json /data/RPMS/hlinktest-1.0-1.noarch.rpm
runroot rpm -q --json /build/RPMS/noarch/weirdnames-1.0-1.noarch.rpm
],
[0],
[stdout],
Expand All @@ -1197,7 +1199,7 @@ import json
s = open('stdout').read()
print(len(json.loads(s)))
],
[57
[58
],
[])
RPMTEST_CLEANUP
Expand Down

0 comments on commit 34667b3

Please # to comment.