coma

create simple config files from JSON input
git clone git://git.hanetzok.net/coma
Log | Files | Refs | README

coma.c (1868B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 #include <cjson/cJSON.h>
      5 
      6 #define SEPARATOR "="
      7 
      8 #define BUFFSIZE 2048
      9 
     10 #define VERSION    "0.1"
     11 #define OK         0
     12 #define INVALIDUSE 1
     13 #define TOOLONG    2
     14 #define PARSEFAIL  3
     15 
     16 typedef struct JSONProperty {
     17   char *key;
     18   char *value;
     19 } jprop;
     20 
     21 void die(char *msg, int rc) {
     22   printf("%s\n", msg);
     23   exit(rc);
     24 }
     25 
     26 void stradd(char *output, char *key, char *value) {
     27   strcat(output, key);
     28   strcat(output, SEPARATOR);
     29   strcat(output, value);
     30   strcat(output, "\n");
     31 }
     32 
     33 int main (int argc, char *argv[]) {
     34   int i;
     35   for (i = 1; i < argc; i++) {
     36     if (!strcmp(argv[i], "-v"))
     37       die("coma-"VERSION, OK);
     38     if (!strcmp(argv[i], "-h"))
     39       die("usage: coma [-hv]", INVALIDUSE);
     40   }
     41 
     42   char *input = malloc(sizeof(char) * BUFFSIZE);
     43   size_t inputsize = fread(input, sizeof(char), BUFFSIZE, stdin);
     44   cJSON *json = cJSON_Parse(input);
     45   if (json == NULL) {
     46     const char *error_ptr = cJSON_GetErrorPtr();
     47     cJSON_Delete(json);
     48     if (error_ptr != NULL)
     49       printf("%s\n", error_ptr);
     50     die("Thou shall not parse\n", PARSEFAIL);
     51   }
     52   free(input);
     53 
     54   cJSON *node;
     55   char *output = malloc(sizeof(char) * inputsize);
     56   for (node = json->child; node != NULL; node = node->next) {
     57     char *key = node->string;
     58     cJSON *item = cJSON_GetObjectItemCaseSensitive(json, key);
     59     if (cJSON_IsString(item) && (item->valuestring != NULL)) {
     60       stradd(output, key, item->valuestring);
     61     }
     62     if (cJSON_IsNumber(item) && (item->valuedouble != 0)) {
     63       char numstr[64];
     64       snprintf(numstr, 64, "%f", item->valuedouble);
     65       stradd(output, key, numstr);
     66     }
     67     if (cJSON_IsTrue(item)) {
     68       stradd(output, key, "true");
     69     }
     70     if (cJSON_IsFalse(item)) {
     71       stradd(output, key, "false");
     72     }
     73   }
     74 
     75   cJSON_Delete(json);
     76   printf("%s\n", output);
     77   free(output);
     78 
     79   return OK;
     80 }
     81