| 654 | }; |
| 655 | |
| 656 | static void print_path(const char *path, const char *prefix, enum format_type format, enum default_type def) |
| 657 | { |
| 658 | char *cwd = NULL; |
| 659 | /* |
| 660 | * We don't ever produce a relative path if prefix is NULL, so set the |
| 661 | * prefix to the current directory so that we can produce a relative |
| 662 | * path whenever possible. If we're using RELATIVE_IF_SHARED mode, then |
| 663 | * we want an absolute path unless the two share a common prefix, so don't |
| 664 | * set it in that case, since doing so causes a relative path to always |
| 665 | * be produced if possible. |
| 666 | */ |
| 667 | if (!prefix && (format != FORMAT_DEFAULT || def != DEFAULT_RELATIVE_IF_SHARED)) |
| 668 | prefix = cwd = xgetcwd(); |
| 669 | if (format == FORMAT_DEFAULT && def == DEFAULT_UNMODIFIED) { |
| 670 | puts(path); |
| 671 | } else if (format == FORMAT_RELATIVE || |
| 672 | (format == FORMAT_DEFAULT && def == DEFAULT_RELATIVE)) { |
| 673 | /* |
| 674 | * In order for relative_path to work as expected, we need to |
| 675 | * make sure that both paths are absolute paths. If we don't, |
| 676 | * we can end up with an unexpected absolute path that the user |
| 677 | * didn't want. |
| 678 | */ |
| 679 | struct strbuf buf = STRBUF_INIT, realbuf = STRBUF_INIT, prefixbuf = STRBUF_INIT; |
| 680 | if (!is_absolute_path(path)) { |
| 681 | strbuf_realpath_forgiving(&realbuf, path, 1); |
| 682 | path = realbuf.buf; |
| 683 | } |
| 684 | if (!is_absolute_path(prefix)) { |
| 685 | strbuf_realpath_forgiving(&prefixbuf, prefix, 1); |
| 686 | prefix = prefixbuf.buf; |
| 687 | } |
| 688 | puts(relative_path(path, prefix, &buf)); |
| 689 | strbuf_release(&buf); |
| 690 | strbuf_release(&realbuf); |
| 691 | strbuf_release(&prefixbuf); |
| 692 | } else if (format == FORMAT_DEFAULT && def == DEFAULT_RELATIVE_IF_SHARED) { |
| 693 | struct strbuf buf = STRBUF_INIT; |
| 694 | puts(relative_path(path, prefix, &buf)); |
| 695 | strbuf_release(&buf); |
| 696 | } else { |
| 697 | struct strbuf buf = STRBUF_INIT; |
| 698 | strbuf_realpath_forgiving(&buf, path, 1); |
| 699 | puts(buf.buf); |
| 700 | strbuf_release(&buf); |
| 701 | } |
| 702 | free(cwd); |
| 703 | } |
| 704 | |
| 705 | int cmd_rev_parse(int argc, |
| 706 | const char **argv, |
no test coverage detected