setup.con commit setup: split off get_device_or_die helper (60c98d1)
   1#include "cache.h"
   2#include "dir.h"
   3
   4static int inside_git_dir = -1;
   5static int inside_work_tree = -1;
   6
   7const char *prefix_path(const char *prefix, int len, const char *path)
   8{
   9        const char *orig = path;
  10        char *sanitized = xmalloc(len + strlen(path) + 1);
  11        if (is_absolute_path(orig))
  12                strcpy(sanitized, path);
  13        else {
  14                if (len)
  15                        memcpy(sanitized, prefix, len);
  16                strcpy(sanitized + len, path);
  17        }
  18        if (normalize_path_copy(sanitized, sanitized))
  19                goto error_out;
  20        if (is_absolute_path(orig)) {
  21                size_t root_len, len, total;
  22                const char *work_tree = get_git_work_tree();
  23                if (!work_tree)
  24                        goto error_out;
  25                len = strlen(work_tree);
  26                root_len = offset_1st_component(work_tree);
  27                total = strlen(sanitized) + 1;
  28                if (strncmp(sanitized, work_tree, len) ||
  29                    (len > root_len && sanitized[len] != '\0' && sanitized[len] != '/')) {
  30                error_out:
  31                        die("'%s' is outside repository", orig);
  32                }
  33                if (sanitized[len] == '/')
  34                        len++;
  35                memmove(sanitized, sanitized + len, total - len);
  36        }
  37        return sanitized;
  38}
  39
  40/*
  41 * Unlike prefix_path, this should be used if the named file does
  42 * not have to interact with index entry; i.e. name of a random file
  43 * on the filesystem.
  44 */
  45const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
  46{
  47        static char path[PATH_MAX];
  48#ifndef WIN32
  49        if (!pfx || !*pfx || is_absolute_path(arg))
  50                return arg;
  51        memcpy(path, pfx, pfx_len);
  52        strcpy(path + pfx_len, arg);
  53#else
  54        char *p;
  55        /* don't add prefix to absolute paths, but still replace '\' by '/' */
  56        if (is_absolute_path(arg))
  57                pfx_len = 0;
  58        else
  59                memcpy(path, pfx, pfx_len);
  60        strcpy(path + pfx_len, arg);
  61        for (p = path + pfx_len; *p; p++)
  62                if (*p == '\\')
  63                        *p = '/';
  64#endif
  65        return path;
  66}
  67
  68int check_filename(const char *prefix, const char *arg)
  69{
  70        const char *name;
  71        struct stat st;
  72
  73        name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
  74        if (!lstat(name, &st))
  75                return 1; /* file exists */
  76        if (errno == ENOENT || errno == ENOTDIR)
  77                return 0; /* file does not exist */
  78        die_errno("failed to stat '%s'", arg);
  79}
  80
  81static void NORETURN die_verify_filename(const char *prefix, const char *arg)
  82{
  83        unsigned char sha1[20];
  84        unsigned mode;
  85        /* try a detailed diagnostic ... */
  86        get_sha1_with_mode_1(arg, sha1, &mode, 0, prefix);
  87        /* ... or fall back the most general message. */
  88        die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
  89            "Use '--' to separate paths from revisions", arg);
  90
  91}
  92
  93/*
  94 * Verify a filename that we got as an argument for a pathspec
  95 * entry. Note that a filename that begins with "-" never verifies
  96 * as true, because even if such a filename were to exist, we want
  97 * it to be preceded by the "--" marker (or we want the user to
  98 * use a format like "./-filename")
  99 */
 100void verify_filename(const char *prefix, const char *arg)
 101{
 102        if (*arg == '-')
 103                die("bad flag '%s' used after filename", arg);
 104        if (check_filename(prefix, arg))
 105                return;
 106        die_verify_filename(prefix, arg);
 107}
 108
 109/*
 110 * Opposite of the above: the command line did not have -- marker
 111 * and we parsed the arg as a refname.  It should not be interpretable
 112 * as a filename.
 113 */
 114void verify_non_filename(const char *prefix, const char *arg)
 115{
 116        if (!is_inside_work_tree() || is_inside_git_dir())
 117                return;
 118        if (*arg == '-')
 119                return; /* flag */
 120        if (!check_filename(prefix, arg))
 121                return;
 122        die("ambiguous argument '%s': both revision and filename\n"
 123            "Use '--' to separate filenames from revisions", arg);
 124}
 125
 126const char **get_pathspec(const char *prefix, const char **pathspec)
 127{
 128        const char *entry = *pathspec;
 129        const char **src, **dst;
 130        int prefixlen;
 131
 132        if (!prefix && !entry)
 133                return NULL;
 134
 135        if (!entry) {
 136                static const char *spec[2];
 137                spec[0] = prefix;
 138                spec[1] = NULL;
 139                return spec;
 140        }
 141
 142        /* Otherwise we have to re-write the entries.. */
 143        src = pathspec;
 144        dst = pathspec;
 145        prefixlen = prefix ? strlen(prefix) : 0;
 146        while (*src) {
 147                const char *p = prefix_path(prefix, prefixlen, *src);
 148                *(dst++) = p;
 149                src++;
 150        }
 151        *dst = NULL;
 152        if (!*pathspec)
 153                return NULL;
 154        return pathspec;
 155}
 156
 157/*
 158 * Test if it looks like we're at a git directory.
 159 * We want to see:
 160 *
 161 *  - either an objects/ directory _or_ the proper
 162 *    GIT_OBJECT_DIRECTORY environment variable
 163 *  - a refs/ directory
 164 *  - either a HEAD symlink or a HEAD file that is formatted as
 165 *    a proper "ref:", or a regular file HEAD that has a properly
 166 *    formatted sha1 object name.
 167 */
 168static int is_git_directory(const char *suspect)
 169{
 170        char path[PATH_MAX];
 171        size_t len = strlen(suspect);
 172
 173        if (PATH_MAX <= len + strlen("/objects"))
 174                die("Too long path: %.*s", 60, suspect);
 175        strcpy(path, suspect);
 176        if (getenv(DB_ENVIRONMENT)) {
 177                if (access(getenv(DB_ENVIRONMENT), X_OK))
 178                        return 0;
 179        }
 180        else {
 181                strcpy(path + len, "/objects");
 182                if (access(path, X_OK))
 183                        return 0;
 184        }
 185
 186        strcpy(path + len, "/refs");
 187        if (access(path, X_OK))
 188                return 0;
 189
 190        strcpy(path + len, "/HEAD");
 191        if (validate_headref(path))
 192                return 0;
 193
 194        return 1;
 195}
 196
 197int is_inside_git_dir(void)
 198{
 199        if (inside_git_dir < 0)
 200                inside_git_dir = is_inside_dir(get_git_dir());
 201        return inside_git_dir;
 202}
 203
 204int is_inside_work_tree(void)
 205{
 206        if (inside_work_tree < 0)
 207                inside_work_tree = is_inside_dir(get_git_work_tree());
 208        return inside_work_tree;
 209}
 210
 211/*
 212 * set_work_tree() is only ever called if you set GIT_DIR explicitly.
 213 * The old behaviour (which we retain here) is to set the work tree root
 214 * to the cwd, unless overridden by the config, the command line, or
 215 * GIT_WORK_TREE.
 216 */
 217static const char *set_work_tree(const char *dir)
 218{
 219        char buffer[PATH_MAX + 1];
 220
 221        if (!getcwd(buffer, sizeof(buffer)))
 222                die ("Could not get the current working directory");
 223        git_work_tree_cfg = xstrdup(buffer);
 224        inside_work_tree = 1;
 225
 226        return NULL;
 227}
 228
 229void setup_work_tree(void)
 230{
 231        const char *work_tree, *git_dir;
 232        static int initialized = 0;
 233
 234        if (initialized)
 235                return;
 236        work_tree = get_git_work_tree();
 237        git_dir = get_git_dir();
 238        if (!is_absolute_path(git_dir))
 239                git_dir = make_absolute_path(git_dir);
 240        if (!work_tree || chdir(work_tree))
 241                die("This operation must be run in a work tree");
 242        set_git_dir(make_relative_path(git_dir, work_tree));
 243        initialized = 1;
 244}
 245
 246static int check_repository_format_gently(int *nongit_ok)
 247{
 248        git_config(check_repository_format_version, NULL);
 249        if (GIT_REPO_VERSION < repository_format_version) {
 250                if (!nongit_ok)
 251                        die ("Expected git repo version <= %d, found %d",
 252                             GIT_REPO_VERSION, repository_format_version);
 253                warning("Expected git repo version <= %d, found %d",
 254                        GIT_REPO_VERSION, repository_format_version);
 255                warning("Please upgrade Git");
 256                *nongit_ok = -1;
 257                return -1;
 258        }
 259        return 0;
 260}
 261
 262/*
 263 * Try to read the location of the git directory from the .git file,
 264 * return path to git directory if found.
 265 */
 266const char *read_gitfile_gently(const char *path)
 267{
 268        char *buf;
 269        char *dir;
 270        const char *slash;
 271        struct stat st;
 272        int fd;
 273        size_t len;
 274
 275        if (stat(path, &st))
 276                return NULL;
 277        if (!S_ISREG(st.st_mode))
 278                return NULL;
 279        fd = open(path, O_RDONLY);
 280        if (fd < 0)
 281                die_errno("Error opening '%s'", path);
 282        buf = xmalloc(st.st_size + 1);
 283        len = read_in_full(fd, buf, st.st_size);
 284        close(fd);
 285        if (len != st.st_size)
 286                die("Error reading %s", path);
 287        buf[len] = '\0';
 288        if (prefixcmp(buf, "gitdir: "))
 289                die("Invalid gitfile format: %s", path);
 290        while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
 291                len--;
 292        if (len < 9)
 293                die("No path in gitfile: %s", path);
 294        buf[len] = '\0';
 295        dir = buf + 8;
 296
 297        if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
 298                size_t pathlen = slash+1 - path;
 299                size_t dirlen = pathlen + len - 8;
 300                dir = xmalloc(dirlen + 1);
 301                strncpy(dir, path, pathlen);
 302                strncpy(dir + pathlen, buf + 8, len - 8);
 303                dir[dirlen] = '\0';
 304                free(buf);
 305                buf = dir;
 306        }
 307
 308        if (!is_git_directory(dir))
 309                die("Not a git repository: %s", dir);
 310        path = make_absolute_path(dir);
 311
 312        free(buf);
 313        return path;
 314}
 315
 316static const char *setup_explicit_git_dir(const char *gitdirenv,
 317                                const char *work_tree_env, int *nongit_ok)
 318{
 319        static char buffer[1024 + 1];
 320        const char *retval;
 321
 322        if (PATH_MAX - 40 < strlen(gitdirenv))
 323                die("'$%s' too big", GIT_DIR_ENVIRONMENT);
 324        if (!is_git_directory(gitdirenv)) {
 325                if (nongit_ok) {
 326                        *nongit_ok = 1;
 327                        return NULL;
 328                }
 329                die("Not a git repository: '%s'", gitdirenv);
 330        }
 331        if (!work_tree_env) {
 332                retval = set_work_tree(gitdirenv);
 333                /* config may override worktree */
 334                if (check_repository_format_gently(nongit_ok))
 335                        return NULL;
 336                return retval;
 337        }
 338        if (check_repository_format_gently(nongit_ok))
 339                return NULL;
 340        retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
 341                        get_git_work_tree());
 342        if (!retval || !*retval)
 343                return NULL;
 344        set_git_dir(make_absolute_path(gitdirenv));
 345        if (chdir(work_tree_env) < 0)
 346                die_errno ("Could not chdir to '%s'", work_tree_env);
 347        strcat(buffer, "/");
 348        return retval;
 349}
 350
 351static int cwd_contains_git_dir(const char **gitfile_dirp)
 352{
 353        const char *gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
 354        *gitfile_dirp = gitfile_dir;
 355        if (gitfile_dir) {
 356                if (set_git_dir(gitfile_dir))
 357                        die("Repository setup failed");
 358                return 1;
 359        }
 360        return is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT);
 361}
 362
 363static const char *setup_bare_git_dir(const char *work_tree_env,
 364                int offset, int len, char *cwd, int *nongit_ok)
 365{
 366        int root_len;
 367
 368        inside_git_dir = 1;
 369        if (!work_tree_env)
 370                inside_work_tree = 0;
 371        if (offset != len) {
 372                root_len = offset_1st_component(cwd);
 373                cwd[offset > root_len ? offset : root_len] = '\0';
 374                set_git_dir(cwd);
 375        } else
 376                set_git_dir(".");
 377        check_repository_format_gently(nongit_ok);
 378        return NULL;
 379}
 380
 381static const char *setup_nongit(const char *cwd, int *nongit_ok)
 382{
 383        if (!nongit_ok)
 384                die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
 385        if (chdir(cwd))
 386                die_errno("Cannot come back to cwd");
 387        *nongit_ok = 1;
 388        return NULL;
 389}
 390
 391static dev_t get_device_or_die(const char *path, const char *prefix)
 392{
 393        struct stat buf;
 394        if (stat(path, &buf))
 395                die_errno("failed to stat '%s%s%s'",
 396                                prefix ? prefix : "",
 397                                prefix ? "/" : "", path);
 398        return buf.st_dev;
 399}
 400
 401/*
 402 * We cannot decide in this function whether we are in the work tree or
 403 * not, since the config can only be read _after_ this function was called.
 404 */
 405const char *setup_git_directory_gently(int *nongit_ok)
 406{
 407        const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
 408        const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
 409        static char cwd[PATH_MAX+1];
 410        const char *gitdirenv;
 411        const char *gitfile_dir;
 412        int len, offset, ceil_offset, root_len;
 413        dev_t current_device = 0;
 414        int one_filesystem = 1;
 415
 416        /*
 417         * Let's assume that we are in a git repository.
 418         * If it turns out later that we are somewhere else, the value will be
 419         * updated accordingly.
 420         */
 421        if (nongit_ok)
 422                *nongit_ok = 0;
 423
 424        /*
 425         * If GIT_DIR is set explicitly, we're not going
 426         * to do any discovery, but we still do repository
 427         * validation.
 428         */
 429        gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
 430        if (gitdirenv)
 431                return setup_explicit_git_dir(gitdirenv, work_tree_env, nongit_ok);
 432
 433        if (!getcwd(cwd, sizeof(cwd)-1))
 434                die_errno("Unable to read current working directory");
 435
 436        ceil_offset = longest_ancestor_length(cwd, env_ceiling_dirs);
 437        if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
 438                ceil_offset = 1;
 439
 440        /*
 441         * Test in the following order (relative to the cwd):
 442         * - .git (file containing "gitdir: <path>")
 443         * - .git/
 444         * - ./ (bare)
 445         * - ../.git
 446         * - ../.git/
 447         * - ../ (bare)
 448         * - ../../.git/
 449         *   etc.
 450         */
 451        offset = len = strlen(cwd);
 452        one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
 453        if (one_filesystem)
 454                current_device = get_device_or_die(".", NULL);
 455        for (;;) {
 456                if (cwd_contains_git_dir(&gitfile_dir))
 457                        break;
 458                if (is_git_directory("."))
 459                        return setup_bare_git_dir(work_tree_env, offset,
 460                                                        len, cwd, nongit_ok);
 461                while (--offset > ceil_offset && cwd[offset] != '/');
 462                if (offset <= ceil_offset)
 463                        return setup_nongit(cwd, nongit_ok);
 464                if (one_filesystem) {
 465                        dev_t parent_device = get_device_or_die("..", cwd);
 466                        if (parent_device != current_device) {
 467                                if (nongit_ok) {
 468                                        if (chdir(cwd))
 469                                                die_errno("Cannot come back to cwd");
 470                                        *nongit_ok = 1;
 471                                        return NULL;
 472                                }
 473                                cwd[offset] = '\0';
 474                                die("Not a git repository (or any parent up to mount parent %s)\n"
 475                                "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).", cwd);
 476                        }
 477                }
 478                if (chdir("..")) {
 479                        cwd[offset] = '\0';
 480                        die_errno("Cannot change to '%s/..'", cwd);
 481                }
 482        }
 483
 484        inside_git_dir = 0;
 485        if (!work_tree_env)
 486                inside_work_tree = 1;
 487        root_len = offset_1st_component(cwd);
 488        git_work_tree_cfg = xstrndup(cwd, offset > root_len ? offset : root_len);
 489        if (check_repository_format_gently(nongit_ok))
 490                return NULL;
 491        if (offset == len)
 492                return NULL;
 493
 494        /* Make "offset" point to past the '/', and add a '/' at the end */
 495        offset++;
 496        cwd[len++] = '/';
 497        cwd[len] = 0;
 498        return cwd + offset;
 499}
 500
 501int git_config_perm(const char *var, const char *value)
 502{
 503        int i;
 504        char *endptr;
 505
 506        if (value == NULL)
 507                return PERM_GROUP;
 508
 509        if (!strcmp(value, "umask"))
 510                return PERM_UMASK;
 511        if (!strcmp(value, "group"))
 512                return PERM_GROUP;
 513        if (!strcmp(value, "all") ||
 514            !strcmp(value, "world") ||
 515            !strcmp(value, "everybody"))
 516                return PERM_EVERYBODY;
 517
 518        /* Parse octal numbers */
 519        i = strtol(value, &endptr, 8);
 520
 521        /* If not an octal number, maybe true/false? */
 522        if (*endptr != 0)
 523                return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
 524
 525        /*
 526         * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
 527         * a chmod value to restrict to.
 528         */
 529        switch (i) {
 530        case PERM_UMASK:               /* 0 */
 531                return PERM_UMASK;
 532        case OLD_PERM_GROUP:           /* 1 */
 533                return PERM_GROUP;
 534        case OLD_PERM_EVERYBODY:       /* 2 */
 535                return PERM_EVERYBODY;
 536        }
 537
 538        /* A filemode value was given: 0xxx */
 539
 540        if ((i & 0600) != 0600)
 541                die("Problem with core.sharedRepository filemode value "
 542                    "(0%.3o).\nThe owner of files must always have "
 543                    "read and write permissions.", i);
 544
 545        /*
 546         * Mask filemode value. Others can not get write permission.
 547         * x flags for directories are handled separately.
 548         */
 549        return -(i & 0666);
 550}
 551
 552int check_repository_format_version(const char *var, const char *value, void *cb)
 553{
 554        if (strcmp(var, "core.repositoryformatversion") == 0)
 555                repository_format_version = git_config_int(var, value);
 556        else if (strcmp(var, "core.sharedrepository") == 0)
 557                shared_repository = git_config_perm(var, value);
 558        else if (strcmp(var, "core.bare") == 0) {
 559                is_bare_repository_cfg = git_config_bool(var, value);
 560                if (is_bare_repository_cfg == 1)
 561                        inside_work_tree = -1;
 562        } else if (strcmp(var, "core.worktree") == 0) {
 563                if (!value)
 564                        return config_error_nonbool(var);
 565                free(git_work_tree_cfg);
 566                git_work_tree_cfg = xstrdup(value);
 567                inside_work_tree = -1;
 568        }
 569        return 0;
 570}
 571
 572int check_repository_format(void)
 573{
 574        return check_repository_format_gently(NULL);
 575}
 576
 577/*
 578 * Returns the "prefix", a path to the current working directory
 579 * relative to the work tree root, or NULL, if the current working
 580 * directory is not a strict subdirectory of the work tree root. The
 581 * prefix always ends with a '/' character.
 582 */
 583const char *setup_git_directory(void)
 584{
 585        const char *retval = setup_git_directory_gently(NULL);
 586
 587        /* If the work tree is not the default one, recompute prefix */
 588        if (inside_work_tree < 0) {
 589                static char buffer[PATH_MAX + 1];
 590                char *rel;
 591                if (retval && chdir(retval))
 592                        die_errno ("Could not jump back into original cwd");
 593                rel = get_relative_cwd(buffer, PATH_MAX, get_git_work_tree());
 594                if (rel && *rel && chdir(get_git_work_tree()))
 595                        die_errno ("Could not jump to working directory");
 596                return rel && *rel ? strcat(rel, "/") : NULL;
 597        }
 598
 599        return retval;
 600}