setup.con commit commit: allow partial commits with relative paths (8894d53)
   1#include "cache.h"
   2#include "dir.h"
   3
   4static int inside_git_dir = -1;
   5static int inside_work_tree = -1;
   6
   7char *prefix_path(const char *prefix, int len, const char *path)
   8{
   9        const char *orig = path;
  10        char *sanitized;
  11        if (is_absolute_path(orig)) {
  12                const char *temp = real_path(path);
  13                sanitized = xmalloc(len + strlen(temp) + 1);
  14                strcpy(sanitized, temp);
  15        } else {
  16                sanitized = xmalloc(len + strlen(path) + 1);
  17                if (len)
  18                        memcpy(sanitized, prefix, len);
  19                strcpy(sanitized + len, path);
  20        }
  21        if (normalize_path_copy(sanitized, sanitized))
  22                goto error_out;
  23        if (is_absolute_path(orig)) {
  24                size_t root_len, len, total;
  25                const char *work_tree = get_git_work_tree();
  26                if (!work_tree)
  27                        goto error_out;
  28                len = strlen(work_tree);
  29                root_len = offset_1st_component(work_tree);
  30                total = strlen(sanitized) + 1;
  31                if (strncmp(sanitized, work_tree, len) ||
  32                    (len > root_len && sanitized[len] != '\0' && sanitized[len] != '/')) {
  33                error_out:
  34                        die("'%s' is outside repository", orig);
  35                }
  36                if (sanitized[len] == '/')
  37                        len++;
  38                memmove(sanitized, sanitized + len, total - len);
  39        }
  40        return sanitized;
  41}
  42
  43/*
  44 * Unlike prefix_path, this should be used if the named file does
  45 * not have to interact with index entry; i.e. name of a random file
  46 * on the filesystem.
  47 */
  48const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
  49{
  50        static char path[PATH_MAX];
  51#ifndef WIN32
  52        if (!pfx_len || is_absolute_path(arg))
  53                return arg;
  54        memcpy(path, pfx, pfx_len);
  55        strcpy(path + pfx_len, arg);
  56#else
  57        char *p;
  58        /* don't add prefix to absolute paths, but still replace '\' by '/' */
  59        if (is_absolute_path(arg))
  60                pfx_len = 0;
  61        else if (pfx_len)
  62                memcpy(path, pfx, pfx_len);
  63        strcpy(path + pfx_len, arg);
  64        for (p = path + pfx_len; *p; p++)
  65                if (*p == '\\')
  66                        *p = '/';
  67#endif
  68        return path;
  69}
  70
  71int check_filename(const char *prefix, const char *arg)
  72{
  73        const char *name;
  74        struct stat st;
  75
  76        name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
  77        if (!lstat(name, &st))
  78                return 1; /* file exists */
  79        if (errno == ENOENT || errno == ENOTDIR)
  80                return 0; /* file does not exist */
  81        die_errno("failed to stat '%s'", arg);
  82}
  83
  84static void NORETURN die_verify_filename(const char *prefix, const char *arg)
  85{
  86        unsigned char sha1[20];
  87        unsigned mode;
  88
  89        /*
  90         * Saying "'(icase)foo' does not exist in the index" when the
  91         * user gave us ":(icase)foo" is just stupid.  A magic pathspec
  92         * begins with a colon and is followed by a non-alnum; do not
  93         * let get_sha1_with_mode_1(only_to_die=1) to even trigger.
  94         */
  95        if (!(arg[0] == ':' && !isalnum(arg[1])))
  96                /* try a detailed diagnostic ... */
  97                get_sha1_with_mode_1(arg, sha1, &mode, 1, prefix);
  98
  99        /* ... or fall back the most general message. */
 100        die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
 101            "Use '--' to separate paths from revisions", arg);
 102
 103}
 104
 105/*
 106 * Verify a filename that we got as an argument for a pathspec
 107 * entry. Note that a filename that begins with "-" never verifies
 108 * as true, because even if such a filename were to exist, we want
 109 * it to be preceded by the "--" marker (or we want the user to
 110 * use a format like "./-filename")
 111 */
 112void verify_filename(const char *prefix, const char *arg)
 113{
 114        if (*arg == '-')
 115                die("bad flag '%s' used after filename", arg);
 116        if (check_filename(prefix, arg))
 117                return;
 118        die_verify_filename(prefix, arg);
 119}
 120
 121/*
 122 * Opposite of the above: the command line did not have -- marker
 123 * and we parsed the arg as a refname.  It should not be interpretable
 124 * as a filename.
 125 */
 126void verify_non_filename(const char *prefix, const char *arg)
 127{
 128        if (!is_inside_work_tree() || is_inside_git_dir())
 129                return;
 130        if (*arg == '-')
 131                return; /* flag */
 132        if (!check_filename(prefix, arg))
 133                return;
 134        die("ambiguous argument '%s': both revision and filename\n"
 135            "Use '--' to separate filenames from revisions", arg);
 136}
 137
 138/*
 139 * Magic pathspec
 140 *
 141 * NEEDSWORK: These need to be moved to dir.h or even to a new
 142 * pathspec.h when we restructure get_pathspec() users to use the
 143 * "struct pathspec" interface.
 144 *
 145 * Possible future magic semantics include stuff like:
 146 *
 147 *      { PATHSPEC_NOGLOB, '!', "noglob" },
 148 *      { PATHSPEC_ICASE, '\0', "icase" },
 149 *      { PATHSPEC_RECURSIVE, '*', "recursive" },
 150 *      { PATHSPEC_REGEXP, '\0', "regexp" },
 151 *
 152 */
 153#define PATHSPEC_FROMTOP    (1<<0)
 154
 155static struct pathspec_magic {
 156        unsigned bit;
 157        char mnemonic; /* this cannot be ':'! */
 158        const char *name;
 159} pathspec_magic[] = {
 160        { PATHSPEC_FROMTOP, '/', "top" },
 161};
 162
 163/*
 164 * Take an element of a pathspec and check for magic signatures.
 165 * Append the result to the prefix.
 166 *
 167 * For now, we only parse the syntax and throw out anything other than
 168 * "top" magic.
 169 *
 170 * NEEDSWORK: This needs to be rewritten when we start migrating
 171 * get_pathspec() users to use the "struct pathspec" interface.  For
 172 * example, a pathspec element may be marked as case-insensitive, but
 173 * the prefix part must always match literally, and a single stupid
 174 * string cannot express such a case.
 175 */
 176static const char *prefix_pathspec(const char *prefix, int prefixlen, const char *elt)
 177{
 178        unsigned magic = 0;
 179        const char *copyfrom = elt;
 180        int i;
 181
 182        if (elt[0] != ':') {
 183                ; /* nothing to do */
 184        } else if (elt[1] == '(') {
 185                /* longhand */
 186                const char *nextat;
 187                for (copyfrom = elt + 2;
 188                     *copyfrom && *copyfrom != ')';
 189                     copyfrom = nextat) {
 190                        size_t len = strcspn(copyfrom, ",)");
 191                        if (copyfrom[len] == ')')
 192                                nextat = copyfrom + len;
 193                        else
 194                                nextat = copyfrom + len + 1;
 195                        if (!len)
 196                                continue;
 197                        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
 198                                if (strlen(pathspec_magic[i].name) == len &&
 199                                    !strncmp(pathspec_magic[i].name, copyfrom, len)) {
 200                                        magic |= pathspec_magic[i].bit;
 201                                        break;
 202                                }
 203                        if (ARRAY_SIZE(pathspec_magic) <= i)
 204                                die("Invalid pathspec magic '%.*s' in '%s'",
 205                                    (int) len, copyfrom, elt);
 206                }
 207                if (*copyfrom == ')')
 208                        copyfrom++;
 209        } else {
 210                /* shorthand */
 211                for (copyfrom = elt + 1;
 212                     *copyfrom && *copyfrom != ':';
 213                     copyfrom++) {
 214                        char ch = *copyfrom;
 215
 216                        if (!is_pathspec_magic(ch))
 217                                break;
 218                        for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
 219                                if (pathspec_magic[i].mnemonic == ch) {
 220                                        magic |= pathspec_magic[i].bit;
 221                                        break;
 222                                }
 223                        if (ARRAY_SIZE(pathspec_magic) <= i)
 224                                die("Unimplemented pathspec magic '%c' in '%s'",
 225                                    ch, elt);
 226                }
 227                if (*copyfrom == ':')
 228                        copyfrom++;
 229        }
 230
 231        if (magic & PATHSPEC_FROMTOP)
 232                return xstrdup(copyfrom);
 233        else
 234                return prefix_path(prefix, prefixlen, copyfrom);
 235}
 236
 237const char **get_pathspec(const char *prefix, const char **pathspec)
 238{
 239        const char *entry = *pathspec;
 240        const char **src, **dst;
 241        int prefixlen;
 242
 243        if (!prefix && !entry)
 244                return NULL;
 245
 246        if (!entry) {
 247                static const char *spec[2];
 248                spec[0] = prefix;
 249                spec[1] = NULL;
 250                return spec;
 251        }
 252
 253        /* Otherwise we have to re-write the entries.. */
 254        src = pathspec;
 255        dst = pathspec;
 256        prefixlen = prefix ? strlen(prefix) : 0;
 257        while (*src) {
 258                *(dst++) = prefix_pathspec(prefix, prefixlen, *src);
 259                src++;
 260        }
 261        *dst = NULL;
 262        if (!*pathspec)
 263                return NULL;
 264        return pathspec;
 265}
 266
 267const char *pathspec_prefix(const char *prefix, const char **pathspec)
 268{
 269        const char **p, *n, *prev;
 270        unsigned long max;
 271
 272        if (!pathspec)
 273                return prefix ? xmemdupz(prefix, strlen(prefix)) : NULL;
 274
 275        prev = NULL;
 276        max = PATH_MAX;
 277        for (p = pathspec; (n = *p) != NULL; p++) {
 278                int i, len = 0;
 279                for (i = 0; i < max; i++) {
 280                        char c = n[i];
 281                        if (prev && prev[i] != c)
 282                                break;
 283                        if (!c || c == '*' || c == '?')
 284                                break;
 285                        if (c == '/')
 286                                len = i+1;
 287                }
 288                prev = n;
 289                if (len < max) {
 290                        max = len;
 291                        if (!max)
 292                                break;
 293                }
 294        }
 295
 296        return max ? xmemdupz(prev, max) : NULL;
 297}
 298
 299/*
 300 * Test if it looks like we're at a git directory.
 301 * We want to see:
 302 *
 303 *  - either an objects/ directory _or_ the proper
 304 *    GIT_OBJECT_DIRECTORY environment variable
 305 *  - a refs/ directory
 306 *  - either a HEAD symlink or a HEAD file that is formatted as
 307 *    a proper "ref:", or a regular file HEAD that has a properly
 308 *    formatted sha1 object name.
 309 */
 310static int is_git_directory(const char *suspect)
 311{
 312        char path[PATH_MAX];
 313        size_t len = strlen(suspect);
 314
 315        if (PATH_MAX <= len + strlen("/objects"))
 316                die("Too long path: %.*s", 60, suspect);
 317        strcpy(path, suspect);
 318        if (getenv(DB_ENVIRONMENT)) {
 319                if (access(getenv(DB_ENVIRONMENT), X_OK))
 320                        return 0;
 321        }
 322        else {
 323                strcpy(path + len, "/objects");
 324                if (access(path, X_OK))
 325                        return 0;
 326        }
 327
 328        strcpy(path + len, "/refs");
 329        if (access(path, X_OK))
 330                return 0;
 331
 332        strcpy(path + len, "/HEAD");
 333        if (validate_headref(path))
 334                return 0;
 335
 336        return 1;
 337}
 338
 339int is_inside_git_dir(void)
 340{
 341        if (inside_git_dir < 0)
 342                inside_git_dir = is_inside_dir(get_git_dir());
 343        return inside_git_dir;
 344}
 345
 346int is_inside_work_tree(void)
 347{
 348        if (inside_work_tree < 0)
 349                inside_work_tree = is_inside_dir(get_git_work_tree());
 350        return inside_work_tree;
 351}
 352
 353void setup_work_tree(void)
 354{
 355        const char *work_tree, *git_dir;
 356        static int initialized = 0;
 357
 358        if (initialized)
 359                return;
 360        work_tree = get_git_work_tree();
 361        git_dir = get_git_dir();
 362        if (!is_absolute_path(git_dir))
 363                git_dir = real_path(get_git_dir());
 364        if (!work_tree || chdir(work_tree))
 365                die("This operation must be run in a work tree");
 366
 367        /*
 368         * Make sure subsequent git processes find correct worktree
 369         * if $GIT_WORK_TREE is set relative
 370         */
 371        if (getenv(GIT_WORK_TREE_ENVIRONMENT))
 372                setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
 373
 374        set_git_dir(relative_path(git_dir, work_tree));
 375        initialized = 1;
 376}
 377
 378static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
 379{
 380        char repo_config[PATH_MAX+1];
 381
 382        /*
 383         * git_config() can't be used here because it calls git_pathdup()
 384         * to get $GIT_CONFIG/config. That call will make setup_git_env()
 385         * set git_dir to ".git".
 386         *
 387         * We are in gitdir setup, no git dir has been found useable yet.
 388         * Use a gentler version of git_config() to check if this repo
 389         * is a good one.
 390         */
 391        snprintf(repo_config, PATH_MAX, "%s/config", gitdir);
 392        git_config_early(check_repository_format_version, NULL, repo_config);
 393        if (GIT_REPO_VERSION < repository_format_version) {
 394                if (!nongit_ok)
 395                        die ("Expected git repo version <= %d, found %d",
 396                             GIT_REPO_VERSION, repository_format_version);
 397                warning("Expected git repo version <= %d, found %d",
 398                        GIT_REPO_VERSION, repository_format_version);
 399                warning("Please upgrade Git");
 400                *nongit_ok = -1;
 401                return -1;
 402        }
 403        return 0;
 404}
 405
 406/*
 407 * Try to read the location of the git directory from the .git file,
 408 * return path to git directory if found.
 409 */
 410const char *read_gitfile_gently(const char *path)
 411{
 412        char *buf;
 413        char *dir;
 414        const char *slash;
 415        struct stat st;
 416        int fd;
 417        ssize_t len;
 418
 419        if (stat(path, &st))
 420                return NULL;
 421        if (!S_ISREG(st.st_mode))
 422                return NULL;
 423        fd = open(path, O_RDONLY);
 424        if (fd < 0)
 425                die_errno("Error opening '%s'", path);
 426        buf = xmalloc(st.st_size + 1);
 427        len = read_in_full(fd, buf, st.st_size);
 428        close(fd);
 429        if (len != st.st_size)
 430                die("Error reading %s", path);
 431        buf[len] = '\0';
 432        if (prefixcmp(buf, "gitdir: "))
 433                die("Invalid gitfile format: %s", path);
 434        while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
 435                len--;
 436        if (len < 9)
 437                die("No path in gitfile: %s", path);
 438        buf[len] = '\0';
 439        dir = buf + 8;
 440
 441        if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
 442                size_t pathlen = slash+1 - path;
 443                size_t dirlen = pathlen + len - 8;
 444                dir = xmalloc(dirlen + 1);
 445                strncpy(dir, path, pathlen);
 446                strncpy(dir + pathlen, buf + 8, len - 8);
 447                dir[dirlen] = '\0';
 448                free(buf);
 449                buf = dir;
 450        }
 451
 452        if (!is_git_directory(dir))
 453                die("Not a git repository: %s", dir);
 454        path = real_path(dir);
 455
 456        free(buf);
 457        return path;
 458}
 459
 460static const char *setup_explicit_git_dir(const char *gitdirenv,
 461                                          char *cwd, int len,
 462                                          int *nongit_ok)
 463{
 464        const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
 465        const char *worktree;
 466        char *gitfile;
 467        int offset;
 468
 469        if (PATH_MAX - 40 < strlen(gitdirenv))
 470                die("'$%s' too big", GIT_DIR_ENVIRONMENT);
 471
 472        gitfile = (char*)read_gitfile_gently(gitdirenv);
 473        if (gitfile) {
 474                gitfile = xstrdup(gitfile);
 475                gitdirenv = gitfile;
 476        }
 477
 478        if (!is_git_directory(gitdirenv)) {
 479                if (nongit_ok) {
 480                        *nongit_ok = 1;
 481                        free(gitfile);
 482                        return NULL;
 483                }
 484                die("Not a git repository: '%s'", gitdirenv);
 485        }
 486
 487        if (check_repository_format_gently(gitdirenv, nongit_ok)) {
 488                free(gitfile);
 489                return NULL;
 490        }
 491
 492        /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
 493        if (work_tree_env)
 494                set_git_work_tree(work_tree_env);
 495        else if (is_bare_repository_cfg > 0) {
 496                if (git_work_tree_cfg) /* #22.2, #30 */
 497                        die("core.bare and core.worktree do not make sense");
 498
 499                /* #18, #26 */
 500                set_git_dir(gitdirenv);
 501                free(gitfile);
 502                return NULL;
 503        }
 504        else if (git_work_tree_cfg) { /* #6, #14 */
 505                if (is_absolute_path(git_work_tree_cfg))
 506                        set_git_work_tree(git_work_tree_cfg);
 507                else {
 508                        char core_worktree[PATH_MAX];
 509                        if (chdir(gitdirenv))
 510                                die_errno("Could not chdir to '%s'", gitdirenv);
 511                        if (chdir(git_work_tree_cfg))
 512                                die_errno("Could not chdir to '%s'", git_work_tree_cfg);
 513                        if (!getcwd(core_worktree, PATH_MAX))
 514                                die_errno("Could not get directory '%s'", git_work_tree_cfg);
 515                        if (chdir(cwd))
 516                                die_errno("Could not come back to cwd");
 517                        set_git_work_tree(core_worktree);
 518                }
 519        }
 520        else /* #2, #10 */
 521                set_git_work_tree(".");
 522
 523        /* set_git_work_tree() must have been called by now */
 524        worktree = get_git_work_tree();
 525
 526        /* both get_git_work_tree() and cwd are already normalized */
 527        if (!strcmp(cwd, worktree)) { /* cwd == worktree */
 528                set_git_dir(gitdirenv);
 529                free(gitfile);
 530                return NULL;
 531        }
 532
 533        offset = dir_inside_of(cwd, worktree);
 534        if (offset >= 0) {      /* cwd inside worktree? */
 535                set_git_dir(real_path(gitdirenv));
 536                if (chdir(worktree))
 537                        die_errno("Could not chdir to '%s'", worktree);
 538                cwd[len++] = '/';
 539                cwd[len] = '\0';
 540                free(gitfile);
 541                return cwd + offset;
 542        }
 543
 544        /* cwd outside worktree */
 545        set_git_dir(gitdirenv);
 546        free(gitfile);
 547        return NULL;
 548}
 549
 550static const char *setup_discovered_git_dir(const char *gitdir,
 551                                            char *cwd, int offset, int len,
 552                                            int *nongit_ok)
 553{
 554        if (check_repository_format_gently(gitdir, nongit_ok))
 555                return NULL;
 556
 557        /* --work-tree is set without --git-dir; use discovered one */
 558        if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
 559                if (offset != len && !is_absolute_path(gitdir))
 560                        gitdir = xstrdup(real_path(gitdir));
 561                if (chdir(cwd))
 562                        die_errno("Could not come back to cwd");
 563                return setup_explicit_git_dir(gitdir, cwd, len, nongit_ok);
 564        }
 565
 566        /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
 567        if (is_bare_repository_cfg > 0) {
 568                set_git_dir(offset == len ? gitdir : real_path(gitdir));
 569                if (chdir(cwd))
 570                        die_errno("Could not come back to cwd");
 571                return NULL;
 572        }
 573
 574        /* #0, #1, #5, #8, #9, #12, #13 */
 575        set_git_work_tree(".");
 576        if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
 577                set_git_dir(gitdir);
 578        inside_git_dir = 0;
 579        inside_work_tree = 1;
 580        if (offset == len)
 581                return NULL;
 582
 583        /* Make "offset" point to past the '/', and add a '/' at the end */
 584        offset++;
 585        cwd[len++] = '/';
 586        cwd[len] = 0;
 587        return cwd + offset;
 588}
 589
 590/* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
 591static const char *setup_bare_git_dir(char *cwd, int offset, int len, int *nongit_ok)
 592{
 593        int root_len;
 594
 595        if (check_repository_format_gently(".", nongit_ok))
 596                return NULL;
 597
 598        /* --work-tree is set without --git-dir; use discovered one */
 599        if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
 600                const char *gitdir;
 601
 602                gitdir = offset == len ? "." : xmemdupz(cwd, offset);
 603                if (chdir(cwd))
 604                        die_errno("Could not come back to cwd");
 605                return setup_explicit_git_dir(gitdir, cwd, len, nongit_ok);
 606        }
 607
 608        inside_git_dir = 1;
 609        inside_work_tree = 0;
 610        if (offset != len) {
 611                if (chdir(cwd))
 612                        die_errno("Cannot come back to cwd");
 613                root_len = offset_1st_component(cwd);
 614                cwd[offset > root_len ? offset : root_len] = '\0';
 615                set_git_dir(cwd);
 616        }
 617        else
 618                set_git_dir(".");
 619        return NULL;
 620}
 621
 622static const char *setup_nongit(const char *cwd, int *nongit_ok)
 623{
 624        if (!nongit_ok)
 625                die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
 626        if (chdir(cwd))
 627                die_errno("Cannot come back to cwd");
 628        *nongit_ok = 1;
 629        return NULL;
 630}
 631
 632static dev_t get_device_or_die(const char *path, const char *prefix)
 633{
 634        struct stat buf;
 635        if (stat(path, &buf))
 636                die_errno("failed to stat '%s%s%s'",
 637                                prefix ? prefix : "",
 638                                prefix ? "/" : "", path);
 639        return buf.st_dev;
 640}
 641
 642/*
 643 * We cannot decide in this function whether we are in the work tree or
 644 * not, since the config can only be read _after_ this function was called.
 645 */
 646static const char *setup_git_directory_gently_1(int *nongit_ok)
 647{
 648        const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
 649        static char cwd[PATH_MAX+1];
 650        const char *gitdirenv, *ret;
 651        char *gitfile;
 652        int len, offset, ceil_offset;
 653        dev_t current_device = 0;
 654        int one_filesystem = 1;
 655
 656        /*
 657         * Let's assume that we are in a git repository.
 658         * If it turns out later that we are somewhere else, the value will be
 659         * updated accordingly.
 660         */
 661        if (nongit_ok)
 662                *nongit_ok = 0;
 663
 664        if (!getcwd(cwd, sizeof(cwd)-1))
 665                die_errno("Unable to read current working directory");
 666        offset = len = strlen(cwd);
 667
 668        /*
 669         * If GIT_DIR is set explicitly, we're not going
 670         * to do any discovery, but we still do repository
 671         * validation.
 672         */
 673        gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
 674        if (gitdirenv)
 675                return setup_explicit_git_dir(gitdirenv, cwd, len, nongit_ok);
 676
 677        ceil_offset = longest_ancestor_length(cwd, env_ceiling_dirs);
 678        if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
 679                ceil_offset = 1;
 680
 681        /*
 682         * Test in the following order (relative to the cwd):
 683         * - .git (file containing "gitdir: <path>")
 684         * - .git/
 685         * - ./ (bare)
 686         * - ../.git
 687         * - ../.git/
 688         * - ../ (bare)
 689         * - ../../.git/
 690         *   etc.
 691         */
 692        one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
 693        if (one_filesystem)
 694                current_device = get_device_or_die(".", NULL);
 695        for (;;) {
 696                gitfile = (char*)read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
 697                if (gitfile)
 698                        gitdirenv = gitfile = xstrdup(gitfile);
 699                else {
 700                        if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
 701                                gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
 702                }
 703
 704                if (gitdirenv) {
 705                        ret = setup_discovered_git_dir(gitdirenv,
 706                                                       cwd, offset, len,
 707                                                       nongit_ok);
 708                        free(gitfile);
 709                        return ret;
 710                }
 711                free(gitfile);
 712
 713                if (is_git_directory("."))
 714                        return setup_bare_git_dir(cwd, offset, len, nongit_ok);
 715
 716                while (--offset > ceil_offset && cwd[offset] != '/');
 717                if (offset <= ceil_offset)
 718                        return setup_nongit(cwd, nongit_ok);
 719                if (one_filesystem) {
 720                        dev_t parent_device = get_device_or_die("..", cwd);
 721                        if (parent_device != current_device) {
 722                                if (nongit_ok) {
 723                                        if (chdir(cwd))
 724                                                die_errno("Cannot come back to cwd");
 725                                        *nongit_ok = 1;
 726                                        return NULL;
 727                                }
 728                                cwd[offset] = '\0';
 729                                die("Not a git repository (or any parent up to mount parent %s)\n"
 730                                "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).", cwd);
 731                        }
 732                }
 733                if (chdir("..")) {
 734                        cwd[offset] = '\0';
 735                        die_errno("Cannot change to '%s/..'", cwd);
 736                }
 737        }
 738}
 739
 740const char *setup_git_directory_gently(int *nongit_ok)
 741{
 742        const char *prefix;
 743
 744        prefix = setup_git_directory_gently_1(nongit_ok);
 745        if (startup_info) {
 746                startup_info->have_repository = !nongit_ok || !*nongit_ok;
 747                startup_info->prefix = prefix;
 748        }
 749        return prefix;
 750}
 751
 752int git_config_perm(const char *var, const char *value)
 753{
 754        int i;
 755        char *endptr;
 756
 757        if (value == NULL)
 758                return PERM_GROUP;
 759
 760        if (!strcmp(value, "umask"))
 761                return PERM_UMASK;
 762        if (!strcmp(value, "group"))
 763                return PERM_GROUP;
 764        if (!strcmp(value, "all") ||
 765            !strcmp(value, "world") ||
 766            !strcmp(value, "everybody"))
 767                return PERM_EVERYBODY;
 768
 769        /* Parse octal numbers */
 770        i = strtol(value, &endptr, 8);
 771
 772        /* If not an octal number, maybe true/false? */
 773        if (*endptr != 0)
 774                return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
 775
 776        /*
 777         * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
 778         * a chmod value to restrict to.
 779         */
 780        switch (i) {
 781        case PERM_UMASK:               /* 0 */
 782                return PERM_UMASK;
 783        case OLD_PERM_GROUP:           /* 1 */
 784                return PERM_GROUP;
 785        case OLD_PERM_EVERYBODY:       /* 2 */
 786                return PERM_EVERYBODY;
 787        }
 788
 789        /* A filemode value was given: 0xxx */
 790
 791        if ((i & 0600) != 0600)
 792                die("Problem with core.sharedRepository filemode value "
 793                    "(0%.3o).\nThe owner of files must always have "
 794                    "read and write permissions.", i);
 795
 796        /*
 797         * Mask filemode value. Others can not get write permission.
 798         * x flags for directories are handled separately.
 799         */
 800        return -(i & 0666);
 801}
 802
 803int check_repository_format_version(const char *var, const char *value, void *cb)
 804{
 805        if (strcmp(var, "core.repositoryformatversion") == 0)
 806                repository_format_version = git_config_int(var, value);
 807        else if (strcmp(var, "core.sharedrepository") == 0)
 808                shared_repository = git_config_perm(var, value);
 809        else if (strcmp(var, "core.bare") == 0) {
 810                is_bare_repository_cfg = git_config_bool(var, value);
 811                if (is_bare_repository_cfg == 1)
 812                        inside_work_tree = -1;
 813        } else if (strcmp(var, "core.worktree") == 0) {
 814                if (!value)
 815                        return config_error_nonbool(var);
 816                free(git_work_tree_cfg);
 817                git_work_tree_cfg = xstrdup(value);
 818                inside_work_tree = -1;
 819        }
 820        return 0;
 821}
 822
 823int check_repository_format(void)
 824{
 825        return check_repository_format_gently(get_git_dir(), NULL);
 826}
 827
 828/*
 829 * Returns the "prefix", a path to the current working directory
 830 * relative to the work tree root, or NULL, if the current working
 831 * directory is not a strict subdirectory of the work tree root. The
 832 * prefix always ends with a '/' character.
 833 */
 834const char *setup_git_directory(void)
 835{
 836        return setup_git_directory_gently(NULL);
 837}