| 1875 | * entry command to claim ownership */ |
| 1876 | } hooks_upsert_args_t; |
| 1877 | static int upsert_hooks_json(hooks_upsert_args_t args) { |
| 1878 | const char *settings_path = args.settings_path; |
| 1879 | const char *hook_event = args.hook_event; |
| 1880 | const char *matcher_str = args.matcher_str; |
| 1881 | const char *command_str = args.command_str; |
| 1882 | const char *const *old_matchers = args.old_matchers; |
| 1883 | if (!settings_path) { |
| 1884 | return CLI_ERR; |
| 1885 | } |
| 1886 | |
| 1887 | yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL); |
| 1888 | if (!mdoc) { |
| 1889 | return CLI_ERR; |
| 1890 | } |
| 1891 | |
| 1892 | yyjson_doc *doc = read_json_file(settings_path); |
| 1893 | yyjson_mut_val *root; |
| 1894 | if (doc) { |
| 1895 | root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc)); |
| 1896 | yyjson_doc_free(doc); |
| 1897 | } else { |
| 1898 | root = yyjson_mut_obj(mdoc); |
| 1899 | } |
| 1900 | if (!root) { |
| 1901 | yyjson_mut_doc_free(mdoc); |
| 1902 | return CLI_ERR; |
| 1903 | } |
| 1904 | yyjson_mut_doc_set_root(mdoc, root); |
| 1905 | |
| 1906 | /* Get or create hooks object */ |
| 1907 | yyjson_mut_val *hooks = yyjson_mut_obj_get(root, "hooks"); |
| 1908 | if (!hooks || !yyjson_mut_is_obj(hooks)) { |
| 1909 | hooks = yyjson_mut_obj(mdoc); |
| 1910 | yyjson_mut_obj_add_val(mdoc, root, "hooks", hooks); |
| 1911 | } |
| 1912 | |
| 1913 | /* Get or create the hook event array (e.g. PreToolUse / BeforeTool) */ |
| 1914 | yyjson_mut_val *event_arr = yyjson_mut_obj_get(hooks, hook_event); |
| 1915 | if (!event_arr || !yyjson_mut_is_arr(event_arr)) { |
| 1916 | event_arr = yyjson_mut_arr(mdoc); |
| 1917 | yyjson_mut_obj_add_val(mdoc, hooks, hook_event, event_arr); |
| 1918 | } |
| 1919 | |
| 1920 | /* Remove existing CMM entry if present */ |
| 1921 | size_t idx; |
| 1922 | size_t max; |
| 1923 | yyjson_mut_val *item; |
| 1924 | yyjson_mut_arr_foreach(event_arr, idx, max, item) { |
| 1925 | if (is_cmm_hook_entry(item, matcher_str, old_matchers, args.match_command_substr)) { |
| 1926 | yyjson_mut_arr_remove(event_arr, idx); |
| 1927 | break; |
| 1928 | } |
| 1929 | } |
| 1930 | |
| 1931 | /* Build our hook entry */ |
| 1932 | yyjson_mut_val *entry = yyjson_mut_obj(mdoc); |
| 1933 | yyjson_mut_obj_add_str(mdoc, entry, "matcher", matcher_str); |
| 1934 |
no test coverage detected