| 265 | } |
| 266 | |
| 267 | int cbm_git_context_resolve(const char *path, cbm_git_context_t *out) { |
| 268 | if (!out) { |
| 269 | return CBM_NOT_FOUND; |
| 270 | } |
| 271 | |
| 272 | memset(out, 0, sizeof(*out)); |
| 273 | if (!path || !path[0]) { |
| 274 | return CBM_NOT_FOUND; |
| 275 | } |
| 276 | |
| 277 | out->input_path = git_strdup(path); |
| 278 | if (!out->input_path) { |
| 279 | return CBM_NOT_FOUND; |
| 280 | } |
| 281 | |
| 282 | out->root_exists = cbm_is_dir(path); |
| 283 | if (!out->root_exists) { |
| 284 | return 0; |
| 285 | } |
| 286 | |
| 287 | if (git_capture(path, "rev-parse --show-toplevel", &out->worktree_root) != 0) { |
| 288 | out->is_git = false; |
| 289 | return 0; |
| 290 | } |
| 291 | out->is_git = true; |
| 292 | |
| 293 | if (git_capture(path, "rev-parse --git-dir", &out->git_dir) != 0) { |
| 294 | out->git_dir = git_strdup(""); |
| 295 | } |
| 296 | if (git_capture(path, "rev-parse --git-common-dir", &out->git_common_dir) != 0) { |
| 297 | out->git_common_dir = git_strdup(""); |
| 298 | } |
| 299 | if (git_capture(path, "rev-parse --verify HEAD", &out->head_sha) != 0) { |
| 300 | out->head_sha = git_strdup(""); |
| 301 | } |
| 302 | |
| 303 | if (git_capture(path, "symbolic-ref --quiet --short HEAD", &out->branch) != 0) { |
| 304 | out->branch = git_strdup("DETACHED"); |
| 305 | out->is_detached = true; |
| 306 | } |
| 307 | |
| 308 | out->is_worktree = |
| 309 | out->git_dir && out->git_common_dir && strcmp(out->git_dir, out->git_common_dir) != 0; |
| 310 | /* git 2.31+ canonical absolute common-dir (best-effort; NULL on older git, |
| 311 | * where derive_canonical_root falls back to the relative common-dir). */ |
| 312 | char *abs_common_dir = NULL; |
| 313 | (void)git_capture(path, "rev-parse --path-format=absolute --git-common-dir", &abs_common_dir); |
| 314 | out->canonical_root = |
| 315 | derive_canonical_root(path, out->worktree_root, out->git_common_dir, abs_common_dir); |
| 316 | free(abs_common_dir); |
| 317 | out->branch_slug = slug_from_branch(out->branch, out->is_detached); |
| 318 | if (git_capture(path, "merge-base HEAD @{upstream}", &out->base_sha) != 0) { |
| 319 | out->base_sha = git_strdup(""); |
| 320 | } |
| 321 | |
| 322 | if (!out->git_dir || !out->git_common_dir || !out->head_sha || !out->branch || |
| 323 | !out->canonical_root || !out->branch_slug || !out->base_sha) { |
| 324 | cbm_git_context_free(out); |