devtools: Refactoring, bug fix, new IDL
[src/app-framework-binder.git] / src / devtools / getref.c
1 /*
2  * Copyright (C) 2016, 2017, 2018 "IoT.bzh"
3  * Author José Bollo <jose.bollo@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 /*
18  * This simple program expands the object { "$ref": "#/path/to/a/target" }
19  *
20  * For example:
21  *
22  *  {
23  *    "type":{
24  *      "a": "int",
25  *      "b": { "$ref": "#/type/a" }
26  *    }
27  *  }
28  *
29  * will be exapanded to
30  *
31  *  {
32  *    "type":{
33  *      "a": "int",
34  *      "b": "int"
35  *    }
36  *  }
37  *
38  * Invocation:   program  [file|-]...
39  *
40  * without arguments, it reads the input.
41  */
42
43 #define _GNU_SOURCE
44 #include <stdio.h>
45 #include <string.h>
46
47 #include <json-c/json.h>
48
49 #include "getref.h"
50
51 /**
52  * Search for a reference of type "#/a/b/c" int the
53  * parsed JSON root object
54  */
55 int search$ref(struct json_object *root, const char *ref, struct json_object **result)
56 {
57         char *d;
58         struct json_object *i;
59
60         /* does it match #/ at the beginning? */
61         if (ref[0] != '#' || (ref[0] && ref[1] != '/')) {
62                 fprintf(stderr, "$ref invalid. Was: %s", ref);
63                 return 0;
64         }
65
66         /* search from root to target */
67         i = root;
68         d = strdupa(ref+2);
69         d = strtok(d, "/");
70         while(i && d) {
71                 if (!json_object_object_get_ex(i, d, &i))
72                         return 0;
73                 d = strtok(NULL, "/");
74         }
75         if (result)
76                 *result = i;
77         return 1;
78 }
79
80 struct json_object *get$ref(struct json_object *root, const char *ref)
81 {
82         struct json_object *result;
83         return search$ref(root, ref, &result) ? result : NULL;
84 }