| 4038 | } |
| 4039 | |
| 4040 | static int upsert_hooks_json(hooks_upsert_args_t args) { |
| 4041 | const char *settings_path = args.settings_path; |
| 4042 | const char *hook_event = args.hook_event; |
| 4043 | const char *matcher_str = args.matcher_str; |
| 4044 | const char *command_str = args.command_str; |
| 4045 | const char *const *old_matchers = args.old_matchers; |
| 4046 | if (!settings_path || !hook_event || !command_str) { |
| 4047 | return CLI_ERR; |
| 4048 | } |
| 4049 | |
| 4050 | char *expected_content = NULL; |
| 4051 | size_t expected_length = 0U; |
| 4052 | int read_result = |
| 4053 | cbm_json_like_read_document(settings_path, &expected_content, &expected_length); |
| 4054 | if (read_result < 0) { |
| 4055 | return CLI_ERR; |
| 4056 | } |
| 4057 | |
| 4058 | int rc = CLI_ERR; |
| 4059 | yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL); |
| 4060 | yyjson_doc *doc = NULL; |
| 4061 | yyjson_mut_val *root = NULL; |
| 4062 | if (!mdoc) { |
| 4063 | free(expected_content); |
| 4064 | return CLI_ERR; |
| 4065 | } |
| 4066 | if (read_result == 0) { |
| 4067 | yyjson_read_flag flags = YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS; |
| 4068 | doc = yyjson_read(expected_content, expected_length, flags); |
| 4069 | if (!doc || !yyjson_is_obj(yyjson_doc_get_root(doc))) { |
| 4070 | goto cleanup; |
| 4071 | } |
| 4072 | root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc)); |
| 4073 | } else { |
| 4074 | root = yyjson_mut_obj(mdoc); |
| 4075 | } |
| 4076 | if (!root) { |
| 4077 | goto cleanup; |
| 4078 | } |
| 4079 | yyjson_mut_doc_set_root(mdoc, root); |
| 4080 | |
| 4081 | /* Get or create hooks object in the temporary semantic copy. The actual |
| 4082 | * write below splices only this event array into the original JSON-like |
| 4083 | * file, retaining comments and unrelated formatting. */ |
| 4084 | yyjson_mut_val *hooks = yyjson_mut_obj_get(root, "hooks"); |
| 4085 | if (hooks && !yyjson_mut_is_obj(hooks)) { |
| 4086 | goto cleanup; |
| 4087 | } |
| 4088 | if (!hooks) { |
| 4089 | hooks = yyjson_mut_obj(mdoc); |
| 4090 | if (!hooks || !yyjson_mut_obj_add_val(mdoc, root, "hooks", hooks)) { |
| 4091 | goto cleanup; |
| 4092 | } |
| 4093 | } |
| 4094 | |
| 4095 | /* Get or create the hook event array (e.g. PreToolUse / BeforeTool) */ |
| 4096 | yyjson_mut_val *event_arr = yyjson_mut_obj_get(hooks, hook_event); |
| 4097 | if (event_arr && !yyjson_mut_is_arr(event_arr)) { |
no test coverage detected