| 2143 | } |
| 2144 | |
| 2145 | static int jl_upsert_entry(const char *file_path, const char *const *object_path, size_t path_len, |
| 2146 | const char *entry_key, const char *entry_json, bool enforce_expected, |
| 2147 | const char *expected_content, size_t expected_length) { |
| 2148 | if (jl_validate_arguments(file_path, object_path, path_len, entry_key) != 0 || !entry_json) { |
| 2149 | return -1; |
| 2150 | } |
| 2151 | size_t entry_start = 0; |
| 2152 | size_t entry_length = 0; |
| 2153 | if (jl_validate_entry(entry_json, &entry_start, &entry_length) != 0) { |
| 2154 | return -1; |
| 2155 | } |
| 2156 | const char *entry_value = entry_json + entry_start; |
| 2157 | |
| 2158 | char *source = NULL; |
| 2159 | size_t source_length = 0; |
| 2160 | bool missing = false; |
| 2161 | jl_file_snapshot_t snapshot; |
| 2162 | if (jl_read_file(file_path, &source, &source_length, &missing, &snapshot) != 0) { |
| 2163 | return -1; |
| 2164 | } |
| 2165 | if (enforce_expected) { |
| 2166 | bool expected_missing = expected_content == NULL; |
| 2167 | bool content_matches = expected_missing |
| 2168 | ? missing |
| 2169 | : !missing && source_length == expected_length && |
| 2170 | (expected_length == 0U || |
| 2171 | memcmp(source, expected_content, expected_length) == 0); |
| 2172 | if (!content_matches) { |
| 2173 | free(source); |
| 2174 | return -1; |
| 2175 | } |
| 2176 | } |
| 2177 | if (missing || source_length == 0U) { |
| 2178 | char *fresh = NULL; |
| 2179 | size_t fresh_length = 0; |
| 2180 | int result = jl_build_fresh(object_path, path_len, entry_key, entry_value, entry_length, |
| 2181 | &fresh, &fresh_length); |
| 2182 | if (result == 0) { |
| 2183 | result = |
| 2184 | jl_write_document(file_path, fresh, fresh_length, source, source_length, &snapshot); |
| 2185 | } |
| 2186 | free(fresh); |
| 2187 | free(source); |
| 2188 | return result; |
| 2189 | } |
| 2190 | |
| 2191 | size_t object_start = 0; |
| 2192 | if (jl_validate_document(source, source_length, &object_start) != 0) { |
| 2193 | free(source); |
| 2194 | return -1; |
| 2195 | } |
| 2196 | for (size_t i = 0; i < path_len; i++) { |
| 2197 | jl_object_t object; |
| 2198 | if (jl_scan_object(source, source_length, object_start, object_path[i], &object) != 0 || |
| 2199 | object.match_count > 1U) { |
| 2200 | free(source); |
| 2201 | return -1; |
| 2202 | } |
no test coverage detected