+static json_content_t content_result;
+static int content_level;
+
+static int json_determine_content_deeper(void *ctx) {
+ content_level++;
+ return 1;
+}
+
+static int json_determine_content_shallower(void *ctx) {
+ content_level--;
+ return 1;
+}
+
+static int json_determine_content_string(void *ctx, const unsigned char *val, size_t len) {
+ if (strcasecmp(last_key, "type") != 0 || content_level > 1)
+ return 1;
+
+ DLOG("string = %.*s, last_key = %s\n", (int)len, val, last_key);
+ if (strncasecmp((const char *)val, "workspace", len) == 0)
+ content_result = JSON_CONTENT_WORKSPACE;
+ return 0;
+}
+
+/* Parses the given JSON file until it encounters the first “type” property to
+ * determine whether the file contains workspaces or regular containers, which
+ * is important to know when deciding where (and how) to append the contents.
+ * */
+json_content_t json_determine_content(const char *filename) {
+ FILE *f;
+ if ((f = fopen(filename, "r")) == NULL) {
+ ELOG("Cannot open file \"%s\"\n", filename);
+ return JSON_CONTENT_UNKNOWN;
+ }
+ struct stat stbuf;
+ if (fstat(fileno(f), &stbuf) != 0) {
+ ELOG("Cannot fstat() \"%s\"\n", filename);
+ fclose(f);
+ return JSON_CONTENT_UNKNOWN;
+ }
+ char *buf = smalloc(stbuf.st_size);
+ int n = fread(buf, 1, stbuf.st_size, f);
+ if (n != stbuf.st_size) {
+ ELOG("File \"%s\" could not be read entirely, not loading.\n", filename);
+ fclose(f);
+ return JSON_CONTENT_UNKNOWN;
+ }
+ DLOG("read %d bytes\n", n);
+ // We default to JSON_CONTENT_CON because it is legal to not include
+ // “"type": "con"” in the JSON files for better readability.
+ content_result = JSON_CONTENT_CON;
+ content_level = 0;
+ yajl_gen g;
+ yajl_handle hand;
+ static yajl_callbacks callbacks = {
+ .yajl_string = json_determine_content_string,
+ .yajl_map_key = json_key,
+ .yajl_start_array = json_determine_content_deeper,
+ .yajl_start_map = json_determine_content_deeper,
+ .yajl_end_map = json_determine_content_shallower,
+ .yajl_end_array = json_determine_content_shallower,
+ };
+ g = yajl_gen_alloc(NULL);
+ hand = yajl_alloc(&callbacks, NULL, (void *)g);
+ /* Allowing comments allows for more user-friendly layout files. */
+ yajl_config(hand, yajl_allow_comments, true);
+ /* Allow multiple values, i.e. multiple nodes to attach */
+ yajl_config(hand, yajl_allow_multiple_values, true);
+ yajl_status stat;
+ setlocale(LC_NUMERIC, "C");
+ stat = yajl_parse(hand, (const unsigned char *)buf, n);
+ if (stat != yajl_status_ok && stat != yajl_status_client_canceled) {
+ unsigned char *str = yajl_get_error(hand, 1, (const unsigned char *)buf, n);
+ ELOG("JSON parsing error: %s\n", str);
+ yajl_free_error(hand, str);
+ }
+
+ setlocale(LC_NUMERIC, "");
+ yajl_complete_parse(hand);
+
+ fclose(f);
+
+ return content_result;
+}
+
+void tree_append_json(Con *con, const char *filename, char **errormsg) {