path.con commit Merge branch 'sg/t5510-test-i18ngrep-fix' (8aa76ab)
   1/*
   2 * Utilities for paths and pathnames
   3 */
   4#include "cache.h"
   5#include "repository.h"
   6#include "strbuf.h"
   7#include "string-list.h"
   8#include "dir.h"
   9#include "worktree.h"
  10#include "submodule-config.h"
  11#include "path.h"
  12#include "packfile.h"
  13#include "object-store.h"
  14
  15static int get_st_mode_bits(const char *path, int *mode)
  16{
  17        struct stat st;
  18        if (lstat(path, &st) < 0)
  19                return -1;
  20        *mode = st.st_mode;
  21        return 0;
  22}
  23
  24static char bad_path[] = "/bad-path/";
  25
  26static struct strbuf *get_pathname(void)
  27{
  28        static struct strbuf pathname_array[4] = {
  29                STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
  30        };
  31        static int index;
  32        struct strbuf *sb = &pathname_array[index];
  33        index = (index + 1) % ARRAY_SIZE(pathname_array);
  34        strbuf_reset(sb);
  35        return sb;
  36}
  37
  38static const char *cleanup_path(const char *path)
  39{
  40        /* Clean it up */
  41        if (skip_prefix(path, "./", &path)) {
  42                while (*path == '/')
  43                        path++;
  44        }
  45        return path;
  46}
  47
  48static void strbuf_cleanup_path(struct strbuf *sb)
  49{
  50        const char *path = cleanup_path(sb->buf);
  51        if (path > sb->buf)
  52                strbuf_remove(sb, 0, path - sb->buf);
  53}
  54
  55char *mksnpath(char *buf, size_t n, const char *fmt, ...)
  56{
  57        va_list args;
  58        unsigned len;
  59
  60        va_start(args, fmt);
  61        len = vsnprintf(buf, n, fmt, args);
  62        va_end(args);
  63        if (len >= n) {
  64                strlcpy(buf, bad_path, n);
  65                return buf;
  66        }
  67        return (char *)cleanup_path(buf);
  68}
  69
  70static int dir_prefix(const char *buf, const char *dir)
  71{
  72        int len = strlen(dir);
  73        return !strncmp(buf, dir, len) &&
  74                (is_dir_sep(buf[len]) || buf[len] == '\0');
  75}
  76
  77/* $buf =~ m|$dir/+$file| but without regex */
  78static int is_dir_file(const char *buf, const char *dir, const char *file)
  79{
  80        int len = strlen(dir);
  81        if (strncmp(buf, dir, len) || !is_dir_sep(buf[len]))
  82                return 0;
  83        while (is_dir_sep(buf[len]))
  84                len++;
  85        return !strcmp(buf + len, file);
  86}
  87
  88static void replace_dir(struct strbuf *buf, int len, const char *newdir)
  89{
  90        int newlen = strlen(newdir);
  91        int need_sep = (buf->buf[len] && !is_dir_sep(buf->buf[len])) &&
  92                !is_dir_sep(newdir[newlen - 1]);
  93        if (need_sep)
  94                len--;   /* keep one char, to be replaced with '/'  */
  95        strbuf_splice(buf, 0, len, newdir, newlen);
  96        if (need_sep)
  97                buf->buf[newlen] = '/';
  98}
  99
 100struct common_dir {
 101        /* Not considered garbage for report_linked_checkout_garbage */
 102        unsigned ignore_garbage:1;
 103        unsigned is_dir:1;
 104        /* Not common even though its parent is */
 105        unsigned exclude:1;
 106        const char *dirname;
 107};
 108
 109static struct common_dir common_list[] = {
 110        { 0, 1, 0, "branches" },
 111        { 0, 1, 0, "common" },
 112        { 0, 1, 0, "hooks" },
 113        { 0, 1, 0, "info" },
 114        { 0, 0, 1, "info/sparse-checkout" },
 115        { 1, 1, 0, "logs" },
 116        { 1, 1, 1, "logs/HEAD" },
 117        { 0, 1, 1, "logs/refs/bisect" },
 118        { 0, 1, 1, "logs/refs/rewritten" },
 119        { 0, 1, 1, "logs/refs/worktree" },
 120        { 0, 1, 0, "lost-found" },
 121        { 0, 1, 0, "objects" },
 122        { 0, 1, 0, "refs" },
 123        { 0, 1, 1, "refs/bisect" },
 124        { 0, 1, 1, "refs/rewritten" },
 125        { 0, 1, 1, "refs/worktree" },
 126        { 0, 1, 0, "remotes" },
 127        { 0, 1, 0, "worktrees" },
 128        { 0, 1, 0, "rr-cache" },
 129        { 0, 1, 0, "svn" },
 130        { 0, 0, 0, "config" },
 131        { 1, 0, 0, "gc.pid" },
 132        { 0, 0, 0, "packed-refs" },
 133        { 0, 0, 0, "shallow" },
 134        { 0, 0, 0, NULL }
 135};
 136
 137/*
 138 * A compressed trie.  A trie node consists of zero or more characters that
 139 * are common to all elements with this prefix, optionally followed by some
 140 * children.  If value is not NULL, the trie node is a terminal node.
 141 *
 142 * For example, consider the following set of strings:
 143 * abc
 144 * def
 145 * definite
 146 * definition
 147 *
 148 * The trie would look like:
 149 * root: len = 0, children a and d non-NULL, value = NULL.
 150 *    a: len = 2, contents = bc, value = (data for "abc")
 151 *    d: len = 2, contents = ef, children i non-NULL, value = (data for "def")
 152 *       i: len = 3, contents = nit, children e and i non-NULL, value = NULL
 153 *           e: len = 0, children all NULL, value = (data for "definite")
 154 *           i: len = 2, contents = on, children all NULL,
 155 *              value = (data for "definition")
 156 */
 157struct trie {
 158        struct trie *children[256];
 159        int len;
 160        char *contents;
 161        void *value;
 162};
 163
 164static struct trie *make_trie_node(const char *key, void *value)
 165{
 166        struct trie *new_node = xcalloc(1, sizeof(*new_node));
 167        new_node->len = strlen(key);
 168        if (new_node->len) {
 169                new_node->contents = xmalloc(new_node->len);
 170                memcpy(new_node->contents, key, new_node->len);
 171        }
 172        new_node->value = value;
 173        return new_node;
 174}
 175
 176/*
 177 * Add a key/value pair to a trie.  The key is assumed to be \0-terminated.
 178 * If there was an existing value for this key, return it.
 179 */
 180static void *add_to_trie(struct trie *root, const char *key, void *value)
 181{
 182        struct trie *child;
 183        void *old;
 184        int i;
 185
 186        if (!*key) {
 187                /* we have reached the end of the key */
 188                old = root->value;
 189                root->value = value;
 190                return old;
 191        }
 192
 193        for (i = 0; i < root->len; i++) {
 194                if (root->contents[i] == key[i])
 195                        continue;
 196
 197                /*
 198                 * Split this node: child will contain this node's
 199                 * existing children.
 200                 */
 201                child = xmalloc(sizeof(*child));
 202                memcpy(child->children, root->children, sizeof(root->children));
 203
 204                child->len = root->len - i - 1;
 205                if (child->len) {
 206                        child->contents = xstrndup(root->contents + i + 1,
 207                                                   child->len);
 208                }
 209                child->value = root->value;
 210                root->value = NULL;
 211                root->len = i;
 212
 213                memset(root->children, 0, sizeof(root->children));
 214                root->children[(unsigned char)root->contents[i]] = child;
 215
 216                /* This is the newly-added child. */
 217                root->children[(unsigned char)key[i]] =
 218                        make_trie_node(key + i + 1, value);
 219                return NULL;
 220        }
 221
 222        /* We have matched the entire compressed section */
 223        if (key[i]) {
 224                child = root->children[(unsigned char)key[root->len]];
 225                if (child) {
 226                        return add_to_trie(child, key + root->len + 1, value);
 227                } else {
 228                        child = make_trie_node(key + root->len + 1, value);
 229                        root->children[(unsigned char)key[root->len]] = child;
 230                        return NULL;
 231                }
 232        }
 233
 234        old = root->value;
 235        root->value = value;
 236        return old;
 237}
 238
 239typedef int (*match_fn)(const char *unmatched, void *data, void *baton);
 240
 241/*
 242 * Search a trie for some key.  Find the longest /-or-\0-terminated
 243 * prefix of the key for which the trie contains a value.  Call fn
 244 * with the unmatched portion of the key and the found value, and
 245 * return its return value.  If there is no such prefix, return -1.
 246 *
 247 * The key is partially normalized: consecutive slashes are skipped.
 248 *
 249 * For example, consider the trie containing only [refs,
 250 * refs/worktree] (both with values).
 251 *
 252 * | key             | unmatched  | val from node | return value |
 253 * |-----------------|------------|---------------|--------------|
 254 * | a               | not called | n/a           | -1           |
 255 * | refs            | \0         | refs          | as per fn    |
 256 * | refs/           | /          | refs          | as per fn    |
 257 * | refs/w          | /w         | refs          | as per fn    |
 258 * | refs/worktree   | \0         | refs/worktree | as per fn    |
 259 * | refs/worktree/  | /          | refs/worktree | as per fn    |
 260 * | refs/worktree/a | /a         | refs/worktree | as per fn    |
 261 * |-----------------|------------|---------------|--------------|
 262 *
 263 */
 264static int trie_find(struct trie *root, const char *key, match_fn fn,
 265                     void *baton)
 266{
 267        int i;
 268        int result;
 269        struct trie *child;
 270
 271        if (!*key) {
 272                /* we have reached the end of the key */
 273                if (root->value && !root->len)
 274                        return fn(key, root->value, baton);
 275                else
 276                        return -1;
 277        }
 278
 279        for (i = 0; i < root->len; i++) {
 280                /* Partial path normalization: skip consecutive slashes. */
 281                if (key[i] == '/' && key[i+1] == '/') {
 282                        key++;
 283                        continue;
 284                }
 285                if (root->contents[i] != key[i])
 286                        return -1;
 287        }
 288
 289        /* Matched the entire compressed section */
 290        key += i;
 291        if (!*key)
 292                /* End of key */
 293                return fn(key, root->value, baton);
 294
 295        /* Partial path normalization: skip consecutive slashes */
 296        while (key[0] == '/' && key[1] == '/')
 297                key++;
 298
 299        child = root->children[(unsigned char)*key];
 300        if (child)
 301                result = trie_find(child, key + 1, fn, baton);
 302        else
 303                result = -1;
 304
 305        if (result >= 0 || (*key != '/' && *key != 0))
 306                return result;
 307        if (root->value)
 308                return fn(key, root->value, baton);
 309        else
 310                return -1;
 311}
 312
 313static struct trie common_trie;
 314static int common_trie_done_setup;
 315
 316static void init_common_trie(void)
 317{
 318        struct common_dir *p;
 319
 320        if (common_trie_done_setup)
 321                return;
 322
 323        for (p = common_list; p->dirname; p++)
 324                add_to_trie(&common_trie, p->dirname, p);
 325
 326        common_trie_done_setup = 1;
 327}
 328
 329/*
 330 * Helper function for update_common_dir: returns 1 if the dir
 331 * prefix is common.
 332 */
 333static int check_common(const char *unmatched, void *value, void *baton)
 334{
 335        struct common_dir *dir = value;
 336
 337        if (!dir)
 338                return 0;
 339
 340        if (dir->is_dir && (unmatched[0] == 0 || unmatched[0] == '/'))
 341                return !dir->exclude;
 342
 343        if (!dir->is_dir && unmatched[0] == 0)
 344                return !dir->exclude;
 345
 346        return 0;
 347}
 348
 349static void update_common_dir(struct strbuf *buf, int git_dir_len,
 350                              const char *common_dir)
 351{
 352        char *base = buf->buf + git_dir_len;
 353        init_common_trie();
 354        if (trie_find(&common_trie, base, check_common, NULL) > 0)
 355                replace_dir(buf, git_dir_len, common_dir);
 356}
 357
 358void report_linked_checkout_garbage(void)
 359{
 360        struct strbuf sb = STRBUF_INIT;
 361        const struct common_dir *p;
 362        int len;
 363
 364        if (!the_repository->different_commondir)
 365                return;
 366        strbuf_addf(&sb, "%s/", get_git_dir());
 367        len = sb.len;
 368        for (p = common_list; p->dirname; p++) {
 369                const char *path = p->dirname;
 370                if (p->ignore_garbage)
 371                        continue;
 372                strbuf_setlen(&sb, len);
 373                strbuf_addstr(&sb, path);
 374                if (file_exists(sb.buf))
 375                        report_garbage(PACKDIR_FILE_GARBAGE, sb.buf);
 376        }
 377        strbuf_release(&sb);
 378}
 379
 380static void adjust_git_path(const struct repository *repo,
 381                            struct strbuf *buf, int git_dir_len)
 382{
 383        const char *base = buf->buf + git_dir_len;
 384        if (is_dir_file(base, "info", "grafts"))
 385                strbuf_splice(buf, 0, buf->len,
 386                              repo->graft_file, strlen(repo->graft_file));
 387        else if (!strcmp(base, "index"))
 388                strbuf_splice(buf, 0, buf->len,
 389                              repo->index_file, strlen(repo->index_file));
 390        else if (dir_prefix(base, "objects"))
 391                replace_dir(buf, git_dir_len + 7, repo->objects->odb->path);
 392        else if (git_hooks_path && dir_prefix(base, "hooks"))
 393                replace_dir(buf, git_dir_len + 5, git_hooks_path);
 394        else if (repo->different_commondir)
 395                update_common_dir(buf, git_dir_len, repo->commondir);
 396}
 397
 398static void strbuf_worktree_gitdir(struct strbuf *buf,
 399                                   const struct repository *repo,
 400                                   const struct worktree *wt)
 401{
 402        if (!wt)
 403                strbuf_addstr(buf, repo->gitdir);
 404        else if (!wt->id)
 405                strbuf_addstr(buf, repo->commondir);
 406        else
 407                strbuf_git_common_path(buf, repo, "worktrees/%s", wt->id);
 408}
 409
 410static void do_git_path(const struct repository *repo,
 411                        const struct worktree *wt, struct strbuf *buf,
 412                        const char *fmt, va_list args)
 413{
 414        int gitdir_len;
 415        strbuf_worktree_gitdir(buf, repo, wt);
 416        if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
 417                strbuf_addch(buf, '/');
 418        gitdir_len = buf->len;
 419        strbuf_vaddf(buf, fmt, args);
 420        if (!wt)
 421                adjust_git_path(repo, buf, gitdir_len);
 422        strbuf_cleanup_path(buf);
 423}
 424
 425char *repo_git_path(const struct repository *repo,
 426                    const char *fmt, ...)
 427{
 428        struct strbuf path = STRBUF_INIT;
 429        va_list args;
 430        va_start(args, fmt);
 431        do_git_path(repo, NULL, &path, fmt, args);
 432        va_end(args);
 433        return strbuf_detach(&path, NULL);
 434}
 435
 436void strbuf_repo_git_path(struct strbuf *sb,
 437                          const struct repository *repo,
 438                          const char *fmt, ...)
 439{
 440        va_list args;
 441        va_start(args, fmt);
 442        do_git_path(repo, NULL, sb, fmt, args);
 443        va_end(args);
 444}
 445
 446char *git_path_buf(struct strbuf *buf, const char *fmt, ...)
 447{
 448        va_list args;
 449        strbuf_reset(buf);
 450        va_start(args, fmt);
 451        do_git_path(the_repository, NULL, buf, fmt, args);
 452        va_end(args);
 453        return buf->buf;
 454}
 455
 456void strbuf_git_path(struct strbuf *sb, const char *fmt, ...)
 457{
 458        va_list args;
 459        va_start(args, fmt);
 460        do_git_path(the_repository, NULL, sb, fmt, args);
 461        va_end(args);
 462}
 463
 464const char *git_path(const char *fmt, ...)
 465{
 466        struct strbuf *pathname = get_pathname();
 467        va_list args;
 468        va_start(args, fmt);
 469        do_git_path(the_repository, NULL, pathname, fmt, args);
 470        va_end(args);
 471        return pathname->buf;
 472}
 473
 474char *git_pathdup(const char *fmt, ...)
 475{
 476        struct strbuf path = STRBUF_INIT;
 477        va_list args;
 478        va_start(args, fmt);
 479        do_git_path(the_repository, NULL, &path, fmt, args);
 480        va_end(args);
 481        return strbuf_detach(&path, NULL);
 482}
 483
 484char *mkpathdup(const char *fmt, ...)
 485{
 486        struct strbuf sb = STRBUF_INIT;
 487        va_list args;
 488        va_start(args, fmt);
 489        strbuf_vaddf(&sb, fmt, args);
 490        va_end(args);
 491        strbuf_cleanup_path(&sb);
 492        return strbuf_detach(&sb, NULL);
 493}
 494
 495const char *mkpath(const char *fmt, ...)
 496{
 497        va_list args;
 498        struct strbuf *pathname = get_pathname();
 499        va_start(args, fmt);
 500        strbuf_vaddf(pathname, fmt, args);
 501        va_end(args);
 502        return cleanup_path(pathname->buf);
 503}
 504
 505const char *worktree_git_path(const struct worktree *wt, const char *fmt, ...)
 506{
 507        struct strbuf *pathname = get_pathname();
 508        va_list args;
 509        va_start(args, fmt);
 510        do_git_path(the_repository, wt, pathname, fmt, args);
 511        va_end(args);
 512        return pathname->buf;
 513}
 514
 515static void do_worktree_path(const struct repository *repo,
 516                             struct strbuf *buf,
 517                             const char *fmt, va_list args)
 518{
 519        strbuf_addstr(buf, repo->worktree);
 520        if(buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
 521                strbuf_addch(buf, '/');
 522
 523        strbuf_vaddf(buf, fmt, args);
 524        strbuf_cleanup_path(buf);
 525}
 526
 527char *repo_worktree_path(const struct repository *repo, const char *fmt, ...)
 528{
 529        struct strbuf path = STRBUF_INIT;
 530        va_list args;
 531
 532        if (!repo->worktree)
 533                return NULL;
 534
 535        va_start(args, fmt);
 536        do_worktree_path(repo, &path, fmt, args);
 537        va_end(args);
 538
 539        return strbuf_detach(&path, NULL);
 540}
 541
 542void strbuf_repo_worktree_path(struct strbuf *sb,
 543                               const struct repository *repo,
 544                               const char *fmt, ...)
 545{
 546        va_list args;
 547
 548        if (!repo->worktree)
 549                return;
 550
 551        va_start(args, fmt);
 552        do_worktree_path(repo, sb, fmt, args);
 553        va_end(args);
 554}
 555
 556/* Returns 0 on success, negative on failure. */
 557static int do_submodule_path(struct strbuf *buf, const char *path,
 558                             const char *fmt, va_list args)
 559{
 560        struct strbuf git_submodule_common_dir = STRBUF_INIT;
 561        struct strbuf git_submodule_dir = STRBUF_INIT;
 562        int ret;
 563
 564        ret = submodule_to_gitdir(&git_submodule_dir, path);
 565        if (ret)
 566                goto cleanup;
 567
 568        strbuf_complete(&git_submodule_dir, '/');
 569        strbuf_addbuf(buf, &git_submodule_dir);
 570        strbuf_vaddf(buf, fmt, args);
 571
 572        if (get_common_dir_noenv(&git_submodule_common_dir, git_submodule_dir.buf))
 573                update_common_dir(buf, git_submodule_dir.len, git_submodule_common_dir.buf);
 574
 575        strbuf_cleanup_path(buf);
 576
 577cleanup:
 578        strbuf_release(&git_submodule_dir);
 579        strbuf_release(&git_submodule_common_dir);
 580        return ret;
 581}
 582
 583char *git_pathdup_submodule(const char *path, const char *fmt, ...)
 584{
 585        int err;
 586        va_list args;
 587        struct strbuf buf = STRBUF_INIT;
 588        va_start(args, fmt);
 589        err = do_submodule_path(&buf, path, fmt, args);
 590        va_end(args);
 591        if (err) {
 592                strbuf_release(&buf);
 593                return NULL;
 594        }
 595        return strbuf_detach(&buf, NULL);
 596}
 597
 598int strbuf_git_path_submodule(struct strbuf *buf, const char *path,
 599                              const char *fmt, ...)
 600{
 601        int err;
 602        va_list args;
 603        va_start(args, fmt);
 604        err = do_submodule_path(buf, path, fmt, args);
 605        va_end(args);
 606
 607        return err;
 608}
 609
 610static void do_git_common_path(const struct repository *repo,
 611                               struct strbuf *buf,
 612                               const char *fmt,
 613                               va_list args)
 614{
 615        strbuf_addstr(buf, repo->commondir);
 616        if (buf->len && !is_dir_sep(buf->buf[buf->len - 1]))
 617                strbuf_addch(buf, '/');
 618        strbuf_vaddf(buf, fmt, args);
 619        strbuf_cleanup_path(buf);
 620}
 621
 622const char *git_common_path(const char *fmt, ...)
 623{
 624        struct strbuf *pathname = get_pathname();
 625        va_list args;
 626        va_start(args, fmt);
 627        do_git_common_path(the_repository, pathname, fmt, args);
 628        va_end(args);
 629        return pathname->buf;
 630}
 631
 632void strbuf_git_common_path(struct strbuf *sb,
 633                            const struct repository *repo,
 634                            const char *fmt, ...)
 635{
 636        va_list args;
 637        va_start(args, fmt);
 638        do_git_common_path(repo, sb, fmt, args);
 639        va_end(args);
 640}
 641
 642int validate_headref(const char *path)
 643{
 644        struct stat st;
 645        char buffer[256];
 646        const char *refname;
 647        struct object_id oid;
 648        int fd;
 649        ssize_t len;
 650
 651        if (lstat(path, &st) < 0)
 652                return -1;
 653
 654        /* Make sure it is a "refs/.." symlink */
 655        if (S_ISLNK(st.st_mode)) {
 656                len = readlink(path, buffer, sizeof(buffer)-1);
 657                if (len >= 5 && !memcmp("refs/", buffer, 5))
 658                        return 0;
 659                return -1;
 660        }
 661
 662        /*
 663         * Anything else, just open it and try to see if it is a symbolic ref.
 664         */
 665        fd = open(path, O_RDONLY);
 666        if (fd < 0)
 667                return -1;
 668        len = read_in_full(fd, buffer, sizeof(buffer)-1);
 669        close(fd);
 670
 671        if (len < 0)
 672                return -1;
 673        buffer[len] = '\0';
 674
 675        /*
 676         * Is it a symbolic ref?
 677         */
 678        if (skip_prefix(buffer, "ref:", &refname)) {
 679                while (isspace(*refname))
 680                        refname++;
 681                if (starts_with(refname, "refs/"))
 682                        return 0;
 683        }
 684
 685        /*
 686         * Is this a detached HEAD?
 687         */
 688        if (!get_oid_hex(buffer, &oid))
 689                return 0;
 690
 691        return -1;
 692}
 693
 694static struct passwd *getpw_str(const char *username, size_t len)
 695{
 696        struct passwd *pw;
 697        char *username_z = xmemdupz(username, len);
 698        pw = getpwnam(username_z);
 699        free(username_z);
 700        return pw;
 701}
 702
 703/*
 704 * Return a string with ~ and ~user expanded via getpw*.  If buf != NULL,
 705 * then it is a newly allocated string. Returns NULL on getpw failure or
 706 * if path is NULL.
 707 *
 708 * If real_home is true, real_path($HOME) is used in the expansion.
 709 */
 710char *expand_user_path(const char *path, int real_home)
 711{
 712        struct strbuf user_path = STRBUF_INIT;
 713        const char *to_copy = path;
 714
 715        if (path == NULL)
 716                goto return_null;
 717        if (path[0] == '~') {
 718                const char *first_slash = strchrnul(path, '/');
 719                const char *username = path + 1;
 720                size_t username_len = first_slash - username;
 721                if (username_len == 0) {
 722                        const char *home = getenv("HOME");
 723                        if (!home)
 724                                goto return_null;
 725                        if (real_home)
 726                                strbuf_add_real_path(&user_path, home);
 727                        else
 728                                strbuf_addstr(&user_path, home);
 729#ifdef GIT_WINDOWS_NATIVE
 730                        convert_slashes(user_path.buf);
 731#endif
 732                } else {
 733                        struct passwd *pw = getpw_str(username, username_len);
 734                        if (!pw)
 735                                goto return_null;
 736                        strbuf_addstr(&user_path, pw->pw_dir);
 737                }
 738                to_copy = first_slash;
 739        }
 740        strbuf_addstr(&user_path, to_copy);
 741        return strbuf_detach(&user_path, NULL);
 742return_null:
 743        strbuf_release(&user_path);
 744        return NULL;
 745}
 746
 747/*
 748 * First, one directory to try is determined by the following algorithm.
 749 *
 750 * (0) If "strict" is given, the path is used as given and no DWIM is
 751 *     done. Otherwise:
 752 * (1) "~/path" to mean path under the running user's home directory;
 753 * (2) "~user/path" to mean path under named user's home directory;
 754 * (3) "relative/path" to mean cwd relative directory; or
 755 * (4) "/absolute/path" to mean absolute directory.
 756 *
 757 * Unless "strict" is given, we check "%s/.git", "%s", "%s.git/.git", "%s.git"
 758 * in this order. We select the first one that is a valid git repository, and
 759 * chdir() to it. If none match, or we fail to chdir, we return NULL.
 760 *
 761 * If all goes well, we return the directory we used to chdir() (but
 762 * before ~user is expanded), avoiding getcwd() resolving symbolic
 763 * links.  User relative paths are also returned as they are given,
 764 * except DWIM suffixing.
 765 */
 766const char *enter_repo(const char *path, int strict)
 767{
 768        static struct strbuf validated_path = STRBUF_INIT;
 769        static struct strbuf used_path = STRBUF_INIT;
 770
 771        if (!path)
 772                return NULL;
 773
 774        if (!strict) {
 775                static const char *suffix[] = {
 776                        "/.git", "", ".git/.git", ".git", NULL,
 777                };
 778                const char *gitfile;
 779                int len = strlen(path);
 780                int i;
 781                while ((1 < len) && (path[len-1] == '/'))
 782                        len--;
 783
 784                /*
 785                 * We can handle arbitrary-sized buffers, but this remains as a
 786                 * sanity check on untrusted input.
 787                 */
 788                if (PATH_MAX <= len)
 789                        return NULL;
 790
 791                strbuf_reset(&used_path);
 792                strbuf_reset(&validated_path);
 793                strbuf_add(&used_path, path, len);
 794                strbuf_add(&validated_path, path, len);
 795
 796                if (used_path.buf[0] == '~') {
 797                        char *newpath = expand_user_path(used_path.buf, 0);
 798                        if (!newpath)
 799                                return NULL;
 800                        strbuf_attach(&used_path, newpath, strlen(newpath),
 801                                      strlen(newpath));
 802                }
 803                for (i = 0; suffix[i]; i++) {
 804                        struct stat st;
 805                        size_t baselen = used_path.len;
 806                        strbuf_addstr(&used_path, suffix[i]);
 807                        if (!stat(used_path.buf, &st) &&
 808                            (S_ISREG(st.st_mode) ||
 809                            (S_ISDIR(st.st_mode) && is_git_directory(used_path.buf)))) {
 810                                strbuf_addstr(&validated_path, suffix[i]);
 811                                break;
 812                        }
 813                        strbuf_setlen(&used_path, baselen);
 814                }
 815                if (!suffix[i])
 816                        return NULL;
 817                gitfile = read_gitfile(used_path.buf);
 818                if (gitfile) {
 819                        strbuf_reset(&used_path);
 820                        strbuf_addstr(&used_path, gitfile);
 821                }
 822                if (chdir(used_path.buf))
 823                        return NULL;
 824                path = validated_path.buf;
 825        }
 826        else {
 827                const char *gitfile = read_gitfile(path);
 828                if (gitfile)
 829                        path = gitfile;
 830                if (chdir(path))
 831                        return NULL;
 832        }
 833
 834        if (is_git_directory(".")) {
 835                set_git_dir(".");
 836                check_repository_format();
 837                return path;
 838        }
 839
 840        return NULL;
 841}
 842
 843static int calc_shared_perm(int mode)
 844{
 845        int tweak;
 846
 847        if (get_shared_repository() < 0)
 848                tweak = -get_shared_repository();
 849        else
 850                tweak = get_shared_repository();
 851
 852        if (!(mode & S_IWUSR))
 853                tweak &= ~0222;
 854        if (mode & S_IXUSR)
 855                /* Copy read bits to execute bits */
 856                tweak |= (tweak & 0444) >> 2;
 857        if (get_shared_repository() < 0)
 858                mode = (mode & ~0777) | tweak;
 859        else
 860                mode |= tweak;
 861
 862        return mode;
 863}
 864
 865
 866int adjust_shared_perm(const char *path)
 867{
 868        int old_mode, new_mode;
 869
 870        if (!get_shared_repository())
 871                return 0;
 872        if (get_st_mode_bits(path, &old_mode) < 0)
 873                return -1;
 874
 875        new_mode = calc_shared_perm(old_mode);
 876        if (S_ISDIR(old_mode)) {
 877                /* Copy read bits to execute bits */
 878                new_mode |= (new_mode & 0444) >> 2;
 879                new_mode |= FORCE_DIR_SET_GID;
 880        }
 881
 882        if (((old_mode ^ new_mode) & ~S_IFMT) &&
 883                        chmod(path, (new_mode & ~S_IFMT)) < 0)
 884                return -2;
 885        return 0;
 886}
 887
 888void safe_create_dir(const char *dir, int share)
 889{
 890        if (mkdir(dir, 0777) < 0) {
 891                if (errno != EEXIST) {
 892                        perror(dir);
 893                        exit(1);
 894                }
 895        }
 896        else if (share && adjust_shared_perm(dir))
 897                die(_("Could not make %s writable by group"), dir);
 898}
 899
 900static int have_same_root(const char *path1, const char *path2)
 901{
 902        int is_abs1, is_abs2;
 903
 904        is_abs1 = is_absolute_path(path1);
 905        is_abs2 = is_absolute_path(path2);
 906        return (is_abs1 && is_abs2 && tolower(path1[0]) == tolower(path2[0])) ||
 907               (!is_abs1 && !is_abs2);
 908}
 909
 910/*
 911 * Give path as relative to prefix.
 912 *
 913 * The strbuf may or may not be used, so do not assume it contains the
 914 * returned path.
 915 */
 916const char *relative_path(const char *in, const char *prefix,
 917                          struct strbuf *sb)
 918{
 919        int in_len = in ? strlen(in) : 0;
 920        int prefix_len = prefix ? strlen(prefix) : 0;
 921        int in_off = 0;
 922        int prefix_off = 0;
 923        int i = 0, j = 0;
 924
 925        if (!in_len)
 926                return "./";
 927        else if (!prefix_len)
 928                return in;
 929
 930        if (have_same_root(in, prefix))
 931                /* bypass dos_drive, for "c:" is identical to "C:" */
 932                i = j = has_dos_drive_prefix(in);
 933        else {
 934                return in;
 935        }
 936
 937        while (i < prefix_len && j < in_len && prefix[i] == in[j]) {
 938                if (is_dir_sep(prefix[i])) {
 939                        while (is_dir_sep(prefix[i]))
 940                                i++;
 941                        while (is_dir_sep(in[j]))
 942                                j++;
 943                        prefix_off = i;
 944                        in_off = j;
 945                } else {
 946                        i++;
 947                        j++;
 948                }
 949        }
 950
 951        if (
 952            /* "prefix" seems like prefix of "in" */
 953            i >= prefix_len &&
 954            /*
 955             * but "/foo" is not a prefix of "/foobar"
 956             * (i.e. prefix not end with '/')
 957             */
 958            prefix_off < prefix_len) {
 959                if (j >= in_len) {
 960                        /* in="/a/b", prefix="/a/b" */
 961                        in_off = in_len;
 962                } else if (is_dir_sep(in[j])) {
 963                        /* in="/a/b/c", prefix="/a/b" */
 964                        while (is_dir_sep(in[j]))
 965                                j++;
 966                        in_off = j;
 967                } else {
 968                        /* in="/a/bbb/c", prefix="/a/b" */
 969                        i = prefix_off;
 970                }
 971        } else if (
 972                   /* "in" is short than "prefix" */
 973                   j >= in_len &&
 974                   /* "in" not end with '/' */
 975                   in_off < in_len) {
 976                if (is_dir_sep(prefix[i])) {
 977                        /* in="/a/b", prefix="/a/b/c/" */
 978                        while (is_dir_sep(prefix[i]))
 979                                i++;
 980                        in_off = in_len;
 981                }
 982        }
 983        in += in_off;
 984        in_len -= in_off;
 985
 986        if (i >= prefix_len) {
 987                if (!in_len)
 988                        return "./";
 989                else
 990                        return in;
 991        }
 992
 993        strbuf_reset(sb);
 994        strbuf_grow(sb, in_len);
 995
 996        while (i < prefix_len) {
 997                if (is_dir_sep(prefix[i])) {
 998                        strbuf_addstr(sb, "../");
 999                        while (is_dir_sep(prefix[i]))
1000                                i++;
1001                        continue;
1002                }
1003                i++;
1004        }
1005        if (!is_dir_sep(prefix[prefix_len - 1]))
1006                strbuf_addstr(sb, "../");
1007
1008        strbuf_addstr(sb, in);
1009
1010        return sb->buf;
1011}
1012
1013/*
1014 * A simpler implementation of relative_path
1015 *
1016 * Get relative path by removing "prefix" from "in". This function
1017 * first appears in v1.5.6-1-g044bbbc, and makes git_dir shorter
1018 * to increase performance when traversing the path to work_tree.
1019 */
1020const char *remove_leading_path(const char *in, const char *prefix)
1021{
1022        static struct strbuf buf = STRBUF_INIT;
1023        int i = 0, j = 0;
1024
1025        if (!prefix || !prefix[0])
1026                return in;
1027        while (prefix[i]) {
1028                if (is_dir_sep(prefix[i])) {
1029                        if (!is_dir_sep(in[j]))
1030                                return in;
1031                        while (is_dir_sep(prefix[i]))
1032                                i++;
1033                        while (is_dir_sep(in[j]))
1034                                j++;
1035                        continue;
1036                } else if (in[j] != prefix[i]) {
1037                        return in;
1038                }
1039                i++;
1040                j++;
1041        }
1042        if (
1043            /* "/foo" is a prefix of "/foo" */
1044            in[j] &&
1045            /* "/foo" is not a prefix of "/foobar" */
1046            !is_dir_sep(prefix[i-1]) && !is_dir_sep(in[j])
1047           )
1048                return in;
1049        while (is_dir_sep(in[j]))
1050                j++;
1051
1052        strbuf_reset(&buf);
1053        if (!in[j])
1054                strbuf_addstr(&buf, ".");
1055        else
1056                strbuf_addstr(&buf, in + j);
1057        return buf.buf;
1058}
1059
1060/*
1061 * It is okay if dst == src, but they should not overlap otherwise.
1062 *
1063 * Performs the following normalizations on src, storing the result in dst:
1064 * - Ensures that components are separated by '/' (Windows only)
1065 * - Squashes sequences of '/' except "//server/share" on Windows
1066 * - Removes "." components.
1067 * - Removes ".." components, and the components the precede them.
1068 * Returns failure (non-zero) if a ".." component appears as first path
1069 * component anytime during the normalization. Otherwise, returns success (0).
1070 *
1071 * Note that this function is purely textual.  It does not follow symlinks,
1072 * verify the existence of the path, or make any system calls.
1073 *
1074 * prefix_len != NULL is for a specific case of prefix_pathspec():
1075 * assume that src == dst and src[0..prefix_len-1] is already
1076 * normalized, any time "../" eats up to the prefix_len part,
1077 * prefix_len is reduced. In the end prefix_len is the remaining
1078 * prefix that has not been overridden by user pathspec.
1079 *
1080 * NEEDSWORK: This function doesn't perform normalization w.r.t. trailing '/'.
1081 * For everything but the root folder itself, the normalized path should not
1082 * end with a '/', then the callers need to be fixed up accordingly.
1083 *
1084 */
1085int normalize_path_copy_len(char *dst, const char *src, int *prefix_len)
1086{
1087        char *dst0;
1088        const char *end;
1089
1090        /*
1091         * Copy initial part of absolute path: "/", "C:/", "//server/share/".
1092         */
1093        end = src + offset_1st_component(src);
1094        while (src < end) {
1095                char c = *src++;
1096                if (is_dir_sep(c))
1097                        c = '/';
1098                *dst++ = c;
1099        }
1100        dst0 = dst;
1101
1102        while (is_dir_sep(*src))
1103                src++;
1104
1105        for (;;) {
1106                char c = *src;
1107
1108                /*
1109                 * A path component that begins with . could be
1110                 * special:
1111                 * (1) "." and ends   -- ignore and terminate.
1112                 * (2) "./"           -- ignore them, eat slash and continue.
1113                 * (3) ".." and ends  -- strip one and terminate.
1114                 * (4) "../"          -- strip one, eat slash and continue.
1115                 */
1116                if (c == '.') {
1117                        if (!src[1]) {
1118                                /* (1) */
1119                                src++;
1120                        } else if (is_dir_sep(src[1])) {
1121                                /* (2) */
1122                                src += 2;
1123                                while (is_dir_sep(*src))
1124                                        src++;
1125                                continue;
1126                        } else if (src[1] == '.') {
1127                                if (!src[2]) {
1128                                        /* (3) */
1129                                        src += 2;
1130                                        goto up_one;
1131                                } else if (is_dir_sep(src[2])) {
1132                                        /* (4) */
1133                                        src += 3;
1134                                        while (is_dir_sep(*src))
1135                                                src++;
1136                                        goto up_one;
1137                                }
1138                        }
1139                }
1140
1141                /* copy up to the next '/', and eat all '/' */
1142                while ((c = *src++) != '\0' && !is_dir_sep(c))
1143                        *dst++ = c;
1144                if (is_dir_sep(c)) {
1145                        *dst++ = '/';
1146                        while (is_dir_sep(c))
1147                                c = *src++;
1148                        src--;
1149                } else if (!c)
1150                        break;
1151                continue;
1152
1153        up_one:
1154                /*
1155                 * dst0..dst is prefix portion, and dst[-1] is '/';
1156                 * go up one level.
1157                 */
1158                dst--;  /* go to trailing '/' */
1159                if (dst <= dst0)
1160                        return -1;
1161                /* Windows: dst[-1] cannot be backslash anymore */
1162                while (dst0 < dst && dst[-1] != '/')
1163                        dst--;
1164                if (prefix_len && *prefix_len > dst - dst0)
1165                        *prefix_len = dst - dst0;
1166        }
1167        *dst = '\0';
1168        return 0;
1169}
1170
1171int normalize_path_copy(char *dst, const char *src)
1172{
1173        return normalize_path_copy_len(dst, src, NULL);
1174}
1175
1176/*
1177 * path = Canonical absolute path
1178 * prefixes = string_list containing normalized, absolute paths without
1179 * trailing slashes (except for the root directory, which is denoted by "/").
1180 *
1181 * Determines, for each path in prefixes, whether the "prefix"
1182 * is an ancestor directory of path.  Returns the length of the longest
1183 * ancestor directory, excluding any trailing slashes, or -1 if no prefix
1184 * is an ancestor.  (Note that this means 0 is returned if prefixes is
1185 * ["/"].) "/foo" is not considered an ancestor of "/foobar".  Directories
1186 * are not considered to be their own ancestors.  path must be in a
1187 * canonical form: empty components, or "." or ".." components are not
1188 * allowed.
1189 */
1190int longest_ancestor_length(const char *path, struct string_list *prefixes)
1191{
1192        int i, max_len = -1;
1193
1194        if (!strcmp(path, "/"))
1195                return -1;
1196
1197        for (i = 0; i < prefixes->nr; i++) {
1198                const char *ceil = prefixes->items[i].string;
1199                int len = strlen(ceil);
1200
1201                if (len == 1 && ceil[0] == '/')
1202                        len = 0; /* root matches anything, with length 0 */
1203                else if (!strncmp(path, ceil, len) && path[len] == '/')
1204                        ; /* match of length len */
1205                else
1206                        continue; /* no match */
1207
1208                if (len > max_len)
1209                        max_len = len;
1210        }
1211
1212        return max_len;
1213}
1214
1215/* strip arbitrary amount of directory separators at end of path */
1216static inline int chomp_trailing_dir_sep(const char *path, int len)
1217{
1218        while (len && is_dir_sep(path[len - 1]))
1219                len--;
1220        return len;
1221}
1222
1223/*
1224 * If path ends with suffix (complete path components), returns the
1225 * part before suffix (sans trailing directory separators).
1226 * Otherwise returns NULL.
1227 */
1228char *strip_path_suffix(const char *path, const char *suffix)
1229{
1230        int path_len = strlen(path), suffix_len = strlen(suffix);
1231
1232        while (suffix_len) {
1233                if (!path_len)
1234                        return NULL;
1235
1236                if (is_dir_sep(path[path_len - 1])) {
1237                        if (!is_dir_sep(suffix[suffix_len - 1]))
1238                                return NULL;
1239                        path_len = chomp_trailing_dir_sep(path, path_len);
1240                        suffix_len = chomp_trailing_dir_sep(suffix, suffix_len);
1241                }
1242                else if (path[--path_len] != suffix[--suffix_len])
1243                        return NULL;
1244        }
1245
1246        if (path_len && !is_dir_sep(path[path_len - 1]))
1247                return NULL;
1248        return xstrndup(path, chomp_trailing_dir_sep(path, path_len));
1249}
1250
1251int daemon_avoid_alias(const char *p)
1252{
1253        int sl, ndot;
1254
1255        /*
1256         * This resurrects the belts and suspenders paranoia check by HPA
1257         * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
1258         * does not do getcwd() based path canonicalization.
1259         *
1260         * sl becomes true immediately after seeing '/' and continues to
1261         * be true as long as dots continue after that without intervening
1262         * non-dot character.
1263         */
1264        if (!p || (*p != '/' && *p != '~'))
1265                return -1;
1266        sl = 1; ndot = 0;
1267        p++;
1268
1269        while (1) {
1270                char ch = *p++;
1271                if (sl) {
1272                        if (ch == '.')
1273                                ndot++;
1274                        else if (ch == '/') {
1275                                if (ndot < 3)
1276                                        /* reject //, /./ and /../ */
1277                                        return -1;
1278                                ndot = 0;
1279                        }
1280                        else if (ch == 0) {
1281                                if (0 < ndot && ndot < 3)
1282                                        /* reject /.$ and /..$ */
1283                                        return -1;
1284                                return 0;
1285                        }
1286                        else
1287                                sl = ndot = 0;
1288                }
1289                else if (ch == 0)
1290                        return 0;
1291                else if (ch == '/') {
1292                        sl = 1;
1293                        ndot = 0;
1294                }
1295        }
1296}
1297
1298static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
1299{
1300        if (len < skip)
1301                return 0;
1302        len -= skip;
1303        path += skip;
1304        while (len-- > 0) {
1305                char c = *(path++);
1306                if (c != ' ' && c != '.')
1307                        return 0;
1308        }
1309        return 1;
1310}
1311
1312int is_ntfs_dotgit(const char *name)
1313{
1314        size_t len;
1315
1316        for (len = 0; ; len++)
1317                if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
1318                        if (only_spaces_and_periods(name, len, 4) &&
1319                                        !strncasecmp(name, ".git", 4))
1320                                return 1;
1321                        if (only_spaces_and_periods(name, len, 5) &&
1322                                        !strncasecmp(name, "git~1", 5))
1323                                return 1;
1324                        if (name[len] != '\\')
1325                                return 0;
1326                        name += len + 1;
1327                        len = -1;
1328                }
1329}
1330
1331static int is_ntfs_dot_generic(const char *name,
1332                               const char *dotgit_name,
1333                               size_t len,
1334                               const char *dotgit_ntfs_shortname_prefix)
1335{
1336        int saw_tilde;
1337        size_t i;
1338
1339        if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
1340                i = len + 1;
1341only_spaces_and_periods:
1342                for (;;) {
1343                        char c = name[i++];
1344                        if (!c)
1345                                return 1;
1346                        if (c != ' ' && c != '.')
1347                                return 0;
1348                }
1349        }
1350
1351        /*
1352         * Is it a regular NTFS short name, i.e. shortened to 6 characters,
1353         * followed by ~1, ... ~4?
1354         */
1355        if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
1356            name[7] >= '1' && name[7] <= '4') {
1357                i = 8;
1358                goto only_spaces_and_periods;
1359        }
1360
1361        /*
1362         * Is it a fall-back NTFS short name (for details, see
1363         * https://en.wikipedia.org/wiki/8.3_filename?
1364         */
1365        for (i = 0, saw_tilde = 0; i < 8; i++)
1366                if (name[i] == '\0')
1367                        return 0;
1368                else if (saw_tilde) {
1369                        if (name[i] < '0' || name[i] > '9')
1370                                return 0;
1371                } else if (name[i] == '~') {
1372                        if (name[++i] < '1' || name[i] > '9')
1373                                return 0;
1374                        saw_tilde = 1;
1375                } else if (i >= 6)
1376                        return 0;
1377                else if (name[i] & 0x80) {
1378                        /*
1379                         * We know our needles contain only ASCII, so we clamp
1380                         * here to make the results of tolower() sane.
1381                         */
1382                        return 0;
1383                } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
1384                        return 0;
1385
1386        goto only_spaces_and_periods;
1387}
1388
1389/*
1390 * Inline helper to make sure compiler resolves strlen() on literals at
1391 * compile time.
1392 */
1393static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
1394                                  const char *dotgit_ntfs_shortname_prefix)
1395{
1396        return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
1397                                   dotgit_ntfs_shortname_prefix);
1398}
1399
1400int is_ntfs_dotgitmodules(const char *name)
1401{
1402        return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
1403}
1404
1405int is_ntfs_dotgitignore(const char *name)
1406{
1407        return is_ntfs_dot_str(name, "gitignore", "gi250a");
1408}
1409
1410int is_ntfs_dotgitattributes(const char *name)
1411{
1412        return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
1413}
1414
1415int looks_like_command_line_option(const char *str)
1416{
1417        return str && str[0] == '-';
1418}
1419
1420char *xdg_config_home(const char *filename)
1421{
1422        const char *home, *config_home;
1423
1424        assert(filename);
1425        config_home = getenv("XDG_CONFIG_HOME");
1426        if (config_home && *config_home)
1427                return mkpathdup("%s/git/%s", config_home, filename);
1428
1429        home = getenv("HOME");
1430        if (home)
1431                return mkpathdup("%s/.config/git/%s", home, filename);
1432        return NULL;
1433}
1434
1435char *xdg_cache_home(const char *filename)
1436{
1437        const char *home, *cache_home;
1438
1439        assert(filename);
1440        cache_home = getenv("XDG_CACHE_HOME");
1441        if (cache_home && *cache_home)
1442                return mkpathdup("%s/git/%s", cache_home, filename);
1443
1444        home = getenv("HOME");
1445        if (home)
1446                return mkpathdup("%s/.cache/git/%s", home, filename);
1447        return NULL;
1448}
1449
1450REPO_GIT_PATH_FUNC(cherry_pick_head, "CHERRY_PICK_HEAD")
1451REPO_GIT_PATH_FUNC(revert_head, "REVERT_HEAD")
1452REPO_GIT_PATH_FUNC(squash_msg, "SQUASH_MSG")
1453REPO_GIT_PATH_FUNC(merge_msg, "MERGE_MSG")
1454REPO_GIT_PATH_FUNC(merge_rr, "MERGE_RR")
1455REPO_GIT_PATH_FUNC(merge_mode, "MERGE_MODE")
1456REPO_GIT_PATH_FUNC(merge_head, "MERGE_HEAD")
1457REPO_GIT_PATH_FUNC(fetch_head, "FETCH_HEAD")
1458REPO_GIT_PATH_FUNC(shallow, "shallow")