| 492 | } |
| 493 | |
| 494 | char *path_dirname(const tal_t *ctx, const char *path) |
| 495 | { |
| 496 | const char *sep; |
| 497 | |
| 498 | if (unlikely(!path) && taken(path)) |
| 499 | return NULL; |
| 500 | |
| 501 | sep = strrchr(path, PATH_SEP); |
| 502 | if (!sep) |
| 503 | return fixed_string(ctx, ".", path); |
| 504 | |
| 505 | /* Trailing slashes need to be trimmed. */ |
| 506 | if (!sep[1]) { |
| 507 | const char *end; |
| 508 | |
| 509 | for (end = sep; end != path; end--) |
| 510 | if (*end != PATH_SEP) |
| 511 | break; |
| 512 | |
| 513 | /* Find *previous* / */ |
| 514 | for (sep = end; sep > path && *sep != PATH_SEP; sep--); |
| 515 | } |
| 516 | |
| 517 | /* In case there are multiple / in a row. */ |
| 518 | while (sep > path && sep[-1] == PATH_SEP) |
| 519 | sep--; |
| 520 | |
| 521 | if (sep == path) { |
| 522 | if (path_is_abs(path)) |
| 523 | return tal_strndup(ctx, path, 1); |
| 524 | else |
| 525 | return fixed_string(ctx, ".", path); |
| 526 | } |
| 527 | return tal_strndup(ctx, path, sep - path); |
| 528 | } |
| 529 | |
| 530 | bool path_is_abs(const char *path) |
| 531 | { |