Skip to content

Commit 3447153

Browse files
committed
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 ef054b8 commit 3447153

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
@@ -44,6 +44,7 @@
4444
static const uint8_t zero_uuid[16] = { 0 };
4545
static struct print_ops json_print_ops;
4646
static struct json_object *json_r;
47+
static int json_init;
4748

4849
static void json_feature_show_fields(enum nvme_features_id fid, unsigned int result,
4950
unsigned char *buf);
@@ -4900,27 +4901,60 @@ static void json_output_perror(const char *msg, va_list ap)
49004901
json_output_object(r);
49014902
}
49024903

4904+
static char *trim_white_space(char *str)
4905+
{
4906+
char *end;
4907+
4908+
if (!str)
4909+
return NULL;
4910+
4911+
/* Trim leading space */
4912+
while (isspace((unsigned char)*str))
4913+
str++;
4914+
4915+
/* All spaces */
4916+
if (!*str)
4917+
return str;
4918+
4919+
/* Trim trailing space */
4920+
end = str + strlen(str) - 1;
4921+
while (end > str && isspace((unsigned char)*end))
4922+
end--;
4923+
4924+
/* Write new null terminator character */
4925+
end[1] = '\0';
4926+
4927+
return str;
4928+
}
4929+
49034930
static void json_output_key_value(const char *key, const char *val, va_list ap)
49044931
{
49054932
struct json_object *r = json_r ? json_r : json_create_object();
49064933

49074934
_cleanup_free_ char *value = NULL;
4935+
_cleanup_free_ char *key_trim = trim_white_space(strdup(key));
49084936

49094937
if (vasprintf(&value, val, ap) < 0)
49104938
value = NULL;
49114939

4912-
obj_add_str(r, key, value ? value : "Could not allocate string");
4940+
obj_add_str(r, key_trim ? key_trim : key, value ? value : "Could not allocate string");
49134941

49144942
obj_print(r);
49154943
}
49164944

49174945
void json_show_init(void)
49184946
{
4919-
json_r = json_create_object();
4947+
json_init++;
4948+
4949+
if (!json_r)
4950+
json_r = json_create_object();
49204951
}
49214952

49224953
void json_show_finish(void)
49234954
{
4955+
if (--json_init)
4956+
return;
4957+
49244958
if (json_r)
49254959
json_output_object(json_r);
49264960

0 commit comments

Comments
 (0)