| 4258 | } |
| 4259 | |
| 4260 | static int upsert_hooks_json(hooks_upsert_args_t args) { |
| 4261 | const char *settings_path = args.settings_path; |
| 4262 | const char *hook_event = args.hook_event; |
| 4263 | const char *matcher_str = args.matcher_str; |
| 4264 | const char *command_str = args.command_str; |
| 4265 | const char *const *old_matchers = args.old_matchers; |
| 4266 | if (!settings_path || !hook_event || !command_str) { |
| 4267 | return CLI_ERR; |
| 4268 | } |
| 4269 | |
| 4270 | char *expected_content = NULL; |
| 4271 | size_t expected_length = 0U; |
| 4272 | int read_result = |
| 4273 | cbm_json_like_read_document(settings_path, &expected_content, &expected_length); |
| 4274 | if (read_result < 0) { |
| 4275 | return CLI_ERR; |
| 4276 | } |
| 4277 | |
| 4278 | int rc = CLI_ERR; |
| 4279 | yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL); |
| 4280 | yyjson_doc *doc = NULL; |
| 4281 | yyjson_mut_val *root = NULL; |
| 4282 | if (!mdoc) { |
| 4283 | free(expected_content); |
| 4284 | return CLI_ERR; |
| 4285 | } |
| 4286 | if (read_result == 0) { |
| 4287 | yyjson_read_flag flags = YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS; |
| 4288 | doc = yyjson_read(expected_content, expected_length, flags); |
| 4289 | if (!doc || !yyjson_is_obj(yyjson_doc_get_root(doc))) { |
| 4290 | goto cleanup; |
| 4291 | } |
| 4292 | root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc)); |
| 4293 | } else { |
| 4294 | root = yyjson_mut_obj(mdoc); |
| 4295 | } |
| 4296 | if (!root) { |
| 4297 | goto cleanup; |
| 4298 | } |
| 4299 | yyjson_mut_doc_set_root(mdoc, root); |
| 4300 | |
| 4301 | /* Get or create hooks object in the temporary semantic copy. The actual |
| 4302 | * write below splices only this event array into the original JSON-like |
| 4303 | * file, retaining comments and unrelated formatting. */ |
| 4304 | yyjson_mut_val *hooks = yyjson_mut_obj_get(root, "hooks"); |
| 4305 | if (hooks && !yyjson_mut_is_obj(hooks)) { |
| 4306 | goto cleanup; |
| 4307 | } |
| 4308 | if (!hooks) { |
| 4309 | hooks = yyjson_mut_obj(mdoc); |
| 4310 | if (!hooks || !yyjson_mut_obj_add_val(mdoc, root, "hooks", hooks)) { |
| 4311 | goto cleanup; |
| 4312 | } |
| 4313 | } |
| 4314 | |
| 4315 | /* Get or create the hook event array (e.g. PreToolUse / BeforeTool) */ |
| 4316 | yyjson_mut_val *event_arr = yyjson_mut_obj_get(hooks, hook_event); |
| 4317 | if (event_arr && !yyjson_mut_is_arr(event_arr)) { |
no test coverage detected