Skip to content

Commit 5130663

Browse files
ikegami-tigaw
authored andcommitted
nvme-print-json: count json_show_init() and json_show_finish() calls
Add the json_init counter to create josn object exclusively. Also change json_output_key_value() to trim key string white spaces. Signed-off-by: Tokunori Ikegami <[email protected]>
1 parent c44bf20 commit 5130663

1 file changed

Lines changed: 36 additions & 2 deletions

File tree

nvme-print-json.c

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
static const uint8_t zero_uuid[16] = { 0 };
4747
static struct print_ops json_print_ops;
4848
static struct json_object *json_r;
49+
static int json_init;
4950

5051
static void json_feature_show_fields(enum nvme_features_id fid, unsigned int result,
5152
unsigned char *buf);
@@ -4921,27 +4922,60 @@ static void json_output_perror(const char *msg, va_list ap)
49214922
json_output_object(r);
49224923
}
49234924

4925+
static char *trim_white_space(char *str)
4926+
{
4927+
char *end;
4928+
4929+
if (!str)
4930+
return NULL;
4931+
4932+
/* Trim leading space */
4933+
while (isspace((unsigned char)*str))
4934+
str++;
4935+
4936+
/* All spaces */
4937+
if (!*str)
4938+
return str;
4939+
4940+
/* Trim trailing space */
4941+
end = str + strlen(str) - 1;
4942+
while (end > str && isspace((unsigned char)*end))
4943+
end--;
4944+
4945+
/* Write new null terminator character */
4946+
end[1] = '\0';
4947+
4948+
return str;
4949+
}
4950+
49244951
static void json_output_key_value(const char *key, const char *val, va_list ap)
49254952
{
49264953
struct json_object *r = json_r ? json_r : json_create_object();
49274954

49284955
_cleanup_free_ char *value = NULL;
4956+
_cleanup_free_ char *key_trim = trim_white_space(strdup(key));
49294957

49304958
if (vasprintf(&value, val, ap) < 0)
49314959
value = NULL;
49324960

4933-
obj_add_str(r, key, value ? value : "Could not allocate string");
4961+
obj_add_str(r, key_trim ? key_trim : key, value ? value : "Could not allocate string");
49344962

49354963
obj_print(r);
49364964
}
49374965

49384966
void json_show_init(void)
49394967
{
4940-
json_r = json_create_object();
4968+
json_init++;
4969+
4970+
if (!json_r)
4971+
json_r = json_create_object();
49414972
}
49424973

49434974
void json_show_finish(void)
49444975
{
4976+
if (--json_init)
4977+
return;
4978+
49454979
if (json_r)
49464980
json_output_object(json_r);
49474981

0 commit comments

Comments
 (0)