| 4779 | } |
| 4780 | |
| 4781 | static int upsert_hooks_json(hooks_upsert_args_t args) { |
| 4782 | const char *settings_path = args.settings_path; |
| 4783 | const char *hook_event = args.hook_event; |
| 4784 | const char *matcher_str = args.matcher_str; |
| 4785 | const char *command_str = args.command_str; |
| 4786 | const char *const *old_matchers = args.old_matchers; |
| 4787 | if (!settings_path || !hook_event || !command_str) { |
| 4788 | return CLI_ERR; |
| 4789 | } |
| 4790 | |
| 4791 | char *expected_content = NULL; |
| 4792 | size_t expected_length = 0U; |
| 4793 | int read_result = |
| 4794 | cbm_json_like_read_document(settings_path, &expected_content, &expected_length); |
| 4795 | if (read_result < 0) { |
| 4796 | return CLI_ERR; |
| 4797 | } |
| 4798 | |
| 4799 | int rc = CLI_ERR; |
| 4800 | yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL); |
| 4801 | yyjson_doc *doc = NULL; |
| 4802 | yyjson_mut_val *root = NULL; |
| 4803 | if (!mdoc) { |
| 4804 | free(expected_content); |
| 4805 | return CLI_ERR; |
| 4806 | } |
| 4807 | if (read_result == 0) { |
| 4808 | yyjson_read_flag flags = YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS; |
| 4809 | doc = yyjson_read(expected_content, expected_length, flags); |
| 4810 | if (!doc || !yyjson_is_obj(yyjson_doc_get_root(doc))) { |
| 4811 | goto cleanup; |
| 4812 | } |
| 4813 | root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc)); |
| 4814 | } else { |
| 4815 | root = yyjson_mut_obj(mdoc); |
| 4816 | } |
| 4817 | if (!root) { |
| 4818 | goto cleanup; |
| 4819 | } |
| 4820 | yyjson_mut_doc_set_root(mdoc, root); |
| 4821 | |
| 4822 | /* Get or create hooks object in the temporary semantic copy. The actual |
| 4823 | * write below splices only this event array into the original JSON-like |
| 4824 | * file, retaining comments and unrelated formatting. */ |
| 4825 | yyjson_mut_val *hooks = yyjson_mut_obj_get(root, "hooks"); |
| 4826 | if (hooks && !yyjson_mut_is_obj(hooks)) { |
| 4827 | goto cleanup; |
| 4828 | } |
| 4829 | if (!hooks) { |
| 4830 | hooks = yyjson_mut_obj(mdoc); |
| 4831 | if (!hooks || !yyjson_mut_obj_add_val(mdoc, root, "hooks", hooks)) { |
| 4832 | goto cleanup; |
| 4833 | } |
| 4834 | } |
| 4835 | |
| 4836 | /* Get or create the hook event array (e.g. PreToolUse / BeforeTool) */ |
| 4837 | yyjson_mut_val *event_arr = yyjson_mut_obj_get(hooks, hook_event); |
| 4838 | if (event_arr && !yyjson_mut_is_arr(event_arr)) { |
no test coverage detected