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