1#include"cache.h" 2#include"repository.h" 3#include"config.h" 4#include"dir.h" 5#include"string-list.h" 6#include"chdir-notify.h" 7 8static int inside_git_dir = -1; 9static int inside_work_tree = -1; 10static int work_tree_config_is_bogus; 11 12static struct startup_info the_startup_info; 13struct startup_info *startup_info = &the_startup_info; 14 15/* 16 * The input parameter must contain an absolute path, and it must already be 17 * normalized. 18 * 19 * Find the part of an absolute path that lies inside the work tree by 20 * dereferencing symlinks outside the work tree, for example: 21 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file 22 * /dir/file (work tree is /) -> dir/file 23 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2 24 * /dir/repolink/file (repolink points to /dir/repo) -> file 25 * /dir/repo (exactly equal to work tree) -> (empty string) 26 */ 27static intabspath_part_inside_repo(char*path) 28{ 29size_t len; 30size_t wtlen; 31char*path0; 32int off; 33const char*work_tree =get_git_work_tree(); 34 35if(!work_tree) 36return-1; 37 wtlen =strlen(work_tree); 38 len =strlen(path); 39 off =offset_1st_component(path); 40 41/* check if work tree is already the prefix */ 42if(wtlen <= len && !fspathncmp(path, work_tree, wtlen)) { 43if(path[wtlen] =='/') { 44memmove(path, path + wtlen +1, len - wtlen); 45return0; 46}else if(path[wtlen -1] =='/'|| path[wtlen] =='\0') { 47/* work tree is the root, or the whole path */ 48memmove(path, path + wtlen, len - wtlen +1); 49return0; 50} 51/* work tree might match beginning of a symlink to work tree */ 52 off = wtlen; 53} 54 path0 = path; 55 path += off; 56 57/* check each '/'-terminated level */ 58while(*path) { 59 path++; 60if(*path =='/') { 61*path ='\0'; 62if(fspathcmp(real_path(path0), work_tree) ==0) { 63memmove(path0, path +1, len - (path - path0)); 64return0; 65} 66*path ='/'; 67} 68} 69 70/* check whole path */ 71if(fspathcmp(real_path(path0), work_tree) ==0) { 72*path0 ='\0'; 73return0; 74} 75 76return-1; 77} 78 79/* 80 * Normalize "path", prepending the "prefix" for relative paths. If 81 * remaining_prefix is not NULL, return the actual prefix still 82 * remains in the path. For example, prefix = sub1/sub2/ and path is 83 * 84 * foo -> sub1/sub2/foo (full prefix) 85 * ../foo -> sub1/foo (remaining prefix is sub1/) 86 * ../../bar -> bar (no remaining prefix) 87 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix) 88 * `pwd`/../bar -> sub1/bar (no remaining prefix) 89 */ 90char*prefix_path_gently(const char*prefix,int len, 91int*remaining_prefix,const char*path) 92{ 93const char*orig = path; 94char*sanitized; 95if(is_absolute_path(orig)) { 96 sanitized =xmallocz(strlen(path)); 97if(remaining_prefix) 98*remaining_prefix =0; 99if(normalize_path_copy_len(sanitized, path, remaining_prefix)) { 100free(sanitized); 101return NULL; 102} 103if(abspath_part_inside_repo(sanitized)) { 104free(sanitized); 105return NULL; 106} 107}else{ 108 sanitized =xstrfmt("%.*s%s", len, len ? prefix :"", path); 109if(remaining_prefix) 110*remaining_prefix = len; 111if(normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) { 112free(sanitized); 113return NULL; 114} 115} 116return sanitized; 117} 118 119char*prefix_path(const char*prefix,int len,const char*path) 120{ 121char*r =prefix_path_gently(prefix, len, NULL, path); 122if(!r) 123die(_("'%s' is outside repository"), path); 124return r; 125} 126 127intpath_inside_repo(const char*prefix,const char*path) 128{ 129int len = prefix ?strlen(prefix) :0; 130char*r =prefix_path_gently(prefix, len, NULL, path); 131if(r) { 132free(r); 133return1; 134} 135return0; 136} 137 138intcheck_filename(const char*prefix,const char*arg) 139{ 140char*to_free = NULL; 141struct stat st; 142 143if(skip_prefix(arg,":/", &arg)) { 144if(!*arg)/* ":/" is root dir, always exists */ 145return1; 146 prefix = NULL; 147}else if(skip_prefix(arg,":!", &arg) || 148skip_prefix(arg,":^", &arg)) { 149if(!*arg)/* excluding everything is silly, but allowed */ 150return1; 151} 152 153if(prefix) 154 arg = to_free =prefix_filename(prefix, arg); 155 156if(!lstat(arg, &st)) { 157free(to_free); 158return1;/* file exists */ 159} 160if(is_missing_file_error(errno)) { 161free(to_free); 162return0;/* file does not exist */ 163} 164die_errno(_("failed to stat '%s'"), arg); 165} 166 167static void NORETURN die_verify_filename(struct repository *r, 168const char*prefix, 169const char*arg, 170int diagnose_misspelt_rev) 171{ 172if(!diagnose_misspelt_rev) 173die(_("%s: no such path in the working tree.\n" 174"Use 'git <command> -- <path>...' to specify paths that do not exist locally."), 175 arg); 176/* 177 * Saying "'(icase)foo' does not exist in the index" when the 178 * user gave us ":(icase)foo" is just stupid. A magic pathspec 179 * begins with a colon and is followed by a non-alnum; do not 180 * let maybe_die_on_misspelt_object_name() even trigger. 181 */ 182if(!(arg[0] ==':'&& !isalnum(arg[1]))) 183maybe_die_on_misspelt_object_name(r, arg, prefix); 184 185/* ... or fall back the most general message. */ 186die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n" 187"Use '--' to separate paths from revisions, like this:\n" 188"'git <command> [<revision>...] -- [<file>...]'"), arg); 189 190} 191 192/* 193 * Check for arguments that don't resolve as actual files, 194 * but which look sufficiently like pathspecs that we'll consider 195 * them such for the purposes of rev/pathspec DWIM parsing. 196 */ 197static intlooks_like_pathspec(const char*arg) 198{ 199/* anything with a wildcard character */ 200if(!no_wildcard(arg)) 201return1; 202 203/* long-form pathspec magic */ 204if(starts_with(arg,":(")) 205return1; 206 207return0; 208} 209 210/* 211 * Verify a filename that we got as an argument for a pathspec 212 * entry. Note that a filename that begins with "-" never verifies 213 * as true, because even if such a filename were to exist, we want 214 * it to be preceded by the "--" marker (or we want the user to 215 * use a format like "./-filename") 216 * 217 * The "diagnose_misspelt_rev" is used to provide a user-friendly 218 * diagnosis when dying upon finding that "name" is not a pathname. 219 * If set to 1, the diagnosis will try to diagnose "name" as an 220 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis 221 * will only complain about an inexisting file. 222 * 223 * This function is typically called to check that a "file or rev" 224 * argument is unambiguous. In this case, the caller will want 225 * diagnose_misspelt_rev == 1 when verifying the first non-rev 226 * argument (which could have been a revision), and 227 * diagnose_misspelt_rev == 0 for the next ones (because we already 228 * saw a filename, there's not ambiguity anymore). 229 */ 230voidverify_filename(const char*prefix, 231const char*arg, 232int diagnose_misspelt_rev) 233{ 234if(*arg =='-') 235die(_("option '%s' must come before non-option arguments"), arg); 236if(looks_like_pathspec(arg) ||check_filename(prefix, arg)) 237return; 238die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev); 239} 240 241/* 242 * Opposite of the above: the command line did not have -- marker 243 * and we parsed the arg as a refname. It should not be interpretable 244 * as a filename. 245 */ 246voidverify_non_filename(const char*prefix,const char*arg) 247{ 248if(!is_inside_work_tree() ||is_inside_git_dir()) 249return; 250if(*arg =='-') 251return;/* flag */ 252if(!check_filename(prefix, arg)) 253return; 254die(_("ambiguous argument '%s': both revision and filename\n" 255"Use '--' to separate paths from revisions, like this:\n" 256"'git <command> [<revision>...] -- [<file>...]'"), arg); 257} 258 259intget_common_dir(struct strbuf *sb,const char*gitdir) 260{ 261const char*git_env_common_dir =getenv(GIT_COMMON_DIR_ENVIRONMENT); 262if(git_env_common_dir) { 263strbuf_addstr(sb, git_env_common_dir); 264return1; 265}else{ 266returnget_common_dir_noenv(sb, gitdir); 267} 268} 269 270intget_common_dir_noenv(struct strbuf *sb,const char*gitdir) 271{ 272struct strbuf data = STRBUF_INIT; 273struct strbuf path = STRBUF_INIT; 274int ret =0; 275 276strbuf_addf(&path,"%s/commondir", gitdir); 277if(file_exists(path.buf)) { 278if(strbuf_read_file(&data, path.buf,0) <=0) 279die_errno(_("failed to read%s"), path.buf); 280while(data.len && (data.buf[data.len -1] =='\n'|| 281 data.buf[data.len -1] =='\r')) 282 data.len--; 283 data.buf[data.len] ='\0'; 284strbuf_reset(&path); 285if(!is_absolute_path(data.buf)) 286strbuf_addf(&path,"%s/", gitdir); 287strbuf_addbuf(&path, &data); 288strbuf_add_real_path(sb, path.buf); 289 ret =1; 290}else{ 291strbuf_addstr(sb, gitdir); 292} 293 294strbuf_release(&data); 295strbuf_release(&path); 296return ret; 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 */ 310intis_git_directory(const char*suspect) 311{ 312struct strbuf path = STRBUF_INIT; 313int ret =0; 314size_t len; 315 316/* Check worktree-related signatures */ 317strbuf_addstr(&path, suspect); 318strbuf_complete(&path,'/'); 319strbuf_addstr(&path,"HEAD"); 320if(validate_headref(path.buf)) 321goto done; 322 323strbuf_reset(&path); 324get_common_dir(&path, suspect); 325 len = path.len; 326 327/* Check non-worktree-related signatures */ 328if(getenv(DB_ENVIRONMENT)) { 329if(access(getenv(DB_ENVIRONMENT), X_OK)) 330goto done; 331} 332else{ 333strbuf_setlen(&path, len); 334strbuf_addstr(&path,"/objects"); 335if(access(path.buf, X_OK)) 336goto done; 337} 338 339strbuf_setlen(&path, len); 340strbuf_addstr(&path,"/refs"); 341if(access(path.buf, X_OK)) 342goto done; 343 344 ret =1; 345done: 346strbuf_release(&path); 347return ret; 348} 349 350intis_nonbare_repository_dir(struct strbuf *path) 351{ 352int ret =0; 353int gitfile_error; 354size_t orig_path_len = path->len; 355assert(orig_path_len !=0); 356strbuf_complete(path,'/'); 357strbuf_addstr(path,".git"); 358if(read_gitfile_gently(path->buf, &gitfile_error) ||is_git_directory(path->buf)) 359 ret =1; 360if(gitfile_error == READ_GITFILE_ERR_OPEN_FAILED || 361 gitfile_error == READ_GITFILE_ERR_READ_FAILED) 362 ret =1; 363strbuf_setlen(path, orig_path_len); 364return ret; 365} 366 367intis_inside_git_dir(void) 368{ 369if(inside_git_dir <0) 370 inside_git_dir =is_inside_dir(get_git_dir()); 371return inside_git_dir; 372} 373 374intis_inside_work_tree(void) 375{ 376if(inside_work_tree <0) 377 inside_work_tree =is_inside_dir(get_git_work_tree()); 378return inside_work_tree; 379} 380 381voidsetup_work_tree(void) 382{ 383const char*work_tree; 384static int initialized =0; 385 386if(initialized) 387return; 388 389if(work_tree_config_is_bogus) 390die(_("unable to set up work tree using invalid config")); 391 392 work_tree =get_git_work_tree(); 393if(!work_tree ||chdir_notify(work_tree)) 394die(_("this operation must be run in a work tree")); 395 396/* 397 * Make sure subsequent git processes find correct worktree 398 * if $GIT_WORK_TREE is set relative 399 */ 400if(getenv(GIT_WORK_TREE_ENVIRONMENT)) 401setenv(GIT_WORK_TREE_ENVIRONMENT,".",1); 402 403 initialized =1; 404} 405 406static intread_worktree_config(const char*var,const char*value,void*vdata) 407{ 408struct repository_format *data = vdata; 409 410if(strcmp(var,"core.bare") ==0) { 411 data->is_bare =git_config_bool(var, value); 412}else if(strcmp(var,"core.worktree") ==0) { 413if(!value) 414returnconfig_error_nonbool(var); 415free(data->work_tree); 416 data->work_tree =xstrdup(value); 417} 418return0; 419} 420 421static intcheck_repo_format(const char*var,const char*value,void*vdata) 422{ 423struct repository_format *data = vdata; 424const char*ext; 425 426if(strcmp(var,"core.repositoryformatversion") ==0) 427 data->version =git_config_int(var, value); 428else if(skip_prefix(var,"extensions.", &ext)) { 429/* 430 * record any known extensions here; otherwise, 431 * we fall through to recording it as unknown, and 432 * check_repository_format will complain 433 */ 434if(!strcmp(ext,"noop")) 435; 436else if(!strcmp(ext,"preciousobjects")) 437 data->precious_objects =git_config_bool(var, value); 438else if(!strcmp(ext,"partialclone")) { 439if(!value) 440returnconfig_error_nonbool(var); 441 data->partial_clone =xstrdup(value); 442}else if(!strcmp(ext,"worktreeconfig")) 443 data->worktree_config =git_config_bool(var, value); 444else 445string_list_append(&data->unknown_extensions, ext); 446} 447 448returnread_worktree_config(var, value, vdata); 449} 450 451static intcheck_repository_format_gently(const char*gitdir,struct repository_format *candidate,int*nongit_ok) 452{ 453struct strbuf sb = STRBUF_INIT; 454struct strbuf err = STRBUF_INIT; 455int has_common; 456 457 has_common =get_common_dir(&sb, gitdir); 458strbuf_addstr(&sb,"/config"); 459read_repository_format(candidate, sb.buf); 460strbuf_release(&sb); 461 462/* 463 * For historical use of check_repository_format() in git-init, 464 * we treat a missing config as a silent "ok", even when nongit_ok 465 * is unset. 466 */ 467if(candidate->version <0) 468return0; 469 470if(verify_repository_format(candidate, &err) <0) { 471if(nongit_ok) { 472warning("%s", err.buf); 473strbuf_release(&err); 474*nongit_ok = -1; 475return-1; 476} 477die("%s", err.buf); 478} 479 480 repository_format_precious_objects = candidate->precious_objects; 481 repository_format_partial_clone =xstrdup_or_null(candidate->partial_clone); 482 repository_format_worktree_config = candidate->worktree_config; 483string_list_clear(&candidate->unknown_extensions,0); 484 485if(repository_format_worktree_config) { 486/* 487 * pick up core.bare and core.worktree from per-worktree 488 * config if present 489 */ 490strbuf_addf(&sb,"%s/config.worktree", gitdir); 491git_config_from_file(read_worktree_config, sb.buf, candidate); 492strbuf_release(&sb); 493 has_common =0; 494} 495 496if(!has_common) { 497if(candidate->is_bare != -1) { 498 is_bare_repository_cfg = candidate->is_bare; 499if(is_bare_repository_cfg ==1) 500 inside_work_tree = -1; 501} 502if(candidate->work_tree) { 503free(git_work_tree_cfg); 504 git_work_tree_cfg =xstrdup(candidate->work_tree); 505 inside_work_tree = -1; 506} 507} 508 509return0; 510} 511 512static voidinit_repository_format(struct repository_format *format) 513{ 514const struct repository_format fresh = REPOSITORY_FORMAT_INIT; 515 516memcpy(format, &fresh,sizeof(fresh)); 517} 518 519intread_repository_format(struct repository_format *format,const char*path) 520{ 521clear_repository_format(format); 522git_config_from_file(check_repo_format, path, format); 523if(format->version == -1) 524clear_repository_format(format); 525return format->version; 526} 527 528voidclear_repository_format(struct repository_format *format) 529{ 530string_list_clear(&format->unknown_extensions,0); 531free(format->work_tree); 532free(format->partial_clone); 533init_repository_format(format); 534} 535 536intverify_repository_format(const struct repository_format *format, 537struct strbuf *err) 538{ 539if(GIT_REPO_VERSION_READ < format->version) { 540strbuf_addf(err,_("Expected git repo version <=%d, found%d"), 541 GIT_REPO_VERSION_READ, format->version); 542return-1; 543} 544 545if(format->version >=1&& format->unknown_extensions.nr) { 546int i; 547 548strbuf_addstr(err,_("unknown repository extensions found:")); 549 550for(i =0; i < format->unknown_extensions.nr; i++) 551strbuf_addf(err,"\n\t%s", 552 format->unknown_extensions.items[i].string); 553return-1; 554} 555 556return0; 557} 558 559voidread_gitfile_error_die(int error_code,const char*path,const char*dir) 560{ 561switch(error_code) { 562case READ_GITFILE_ERR_STAT_FAILED: 563case READ_GITFILE_ERR_NOT_A_FILE: 564/* non-fatal; follow return path */ 565break; 566case READ_GITFILE_ERR_OPEN_FAILED: 567die_errno(_("error opening '%s'"), path); 568case READ_GITFILE_ERR_TOO_LARGE: 569die(_("too large to be a .git file: '%s'"), path); 570case READ_GITFILE_ERR_READ_FAILED: 571die(_("error reading%s"), path); 572case READ_GITFILE_ERR_INVALID_FORMAT: 573die(_("invalid gitfile format:%s"), path); 574case READ_GITFILE_ERR_NO_PATH: 575die(_("no path in gitfile:%s"), path); 576case READ_GITFILE_ERR_NOT_A_REPO: 577die(_("not a git repository:%s"), dir); 578default: 579BUG("unknown error code"); 580} 581} 582 583/* 584 * Try to read the location of the git directory from the .git file, 585 * return path to git directory if found. The return value comes from 586 * a shared buffer. 587 * 588 * On failure, if return_error_code is not NULL, return_error_code 589 * will be set to an error code and NULL will be returned. If 590 * return_error_code is NULL the function will die instead (for most 591 * cases). 592 */ 593const char*read_gitfile_gently(const char*path,int*return_error_code) 594{ 595const int max_file_size =1<<20;/* 1MB */ 596int error_code =0; 597char*buf = NULL; 598char*dir = NULL; 599const char*slash; 600struct stat st; 601int fd; 602 ssize_t len; 603 604if(stat(path, &st)) { 605/* NEEDSWORK: discern between ENOENT vs other errors */ 606 error_code = READ_GITFILE_ERR_STAT_FAILED; 607goto cleanup_return; 608} 609if(!S_ISREG(st.st_mode)) { 610 error_code = READ_GITFILE_ERR_NOT_A_FILE; 611goto cleanup_return; 612} 613if(st.st_size > max_file_size) { 614 error_code = READ_GITFILE_ERR_TOO_LARGE; 615goto cleanup_return; 616} 617 fd =open(path, O_RDONLY); 618if(fd <0) { 619 error_code = READ_GITFILE_ERR_OPEN_FAILED; 620goto cleanup_return; 621} 622 buf =xmallocz(st.st_size); 623 len =read_in_full(fd, buf, st.st_size); 624close(fd); 625if(len != st.st_size) { 626 error_code = READ_GITFILE_ERR_READ_FAILED; 627goto cleanup_return; 628} 629if(!starts_with(buf,"gitdir: ")) { 630 error_code = READ_GITFILE_ERR_INVALID_FORMAT; 631goto cleanup_return; 632} 633while(buf[len -1] =='\n'|| buf[len -1] =='\r') 634 len--; 635if(len <9) { 636 error_code = READ_GITFILE_ERR_NO_PATH; 637goto cleanup_return; 638} 639 buf[len] ='\0'; 640 dir = buf +8; 641 642if(!is_absolute_path(dir) && (slash =strrchr(path,'/'))) { 643size_t pathlen = slash+1- path; 644 dir =xstrfmt("%.*s%.*s", (int)pathlen, path, 645(int)(len -8), buf +8); 646free(buf); 647 buf = dir; 648} 649if(!is_git_directory(dir)) { 650 error_code = READ_GITFILE_ERR_NOT_A_REPO; 651goto cleanup_return; 652} 653 path =real_path(dir); 654 655cleanup_return: 656if(return_error_code) 657*return_error_code = error_code; 658else if(error_code) 659read_gitfile_error_die(error_code, path, dir); 660 661free(buf); 662return error_code ? NULL : path; 663} 664 665static const char*setup_explicit_git_dir(const char*gitdirenv, 666struct strbuf *cwd, 667struct repository_format *repo_fmt, 668int*nongit_ok) 669{ 670const char*work_tree_env =getenv(GIT_WORK_TREE_ENVIRONMENT); 671const char*worktree; 672char*gitfile; 673int offset; 674 675if(PATH_MAX -40<strlen(gitdirenv)) 676die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT); 677 678 gitfile = (char*)read_gitfile(gitdirenv); 679if(gitfile) { 680 gitfile =xstrdup(gitfile); 681 gitdirenv = gitfile; 682} 683 684if(!is_git_directory(gitdirenv)) { 685if(nongit_ok) { 686*nongit_ok =1; 687free(gitfile); 688return NULL; 689} 690die(_("not a git repository: '%s'"), gitdirenv); 691} 692 693if(check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) { 694free(gitfile); 695return NULL; 696} 697 698/* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */ 699if(work_tree_env) 700set_git_work_tree(work_tree_env); 701else if(is_bare_repository_cfg >0) { 702if(git_work_tree_cfg) { 703/* #22.2, #30 */ 704warning("core.bare and core.worktree do not make sense"); 705 work_tree_config_is_bogus =1; 706} 707 708/* #18, #26 */ 709set_git_dir(gitdirenv); 710free(gitfile); 711return NULL; 712} 713else if(git_work_tree_cfg) {/* #6, #14 */ 714if(is_absolute_path(git_work_tree_cfg)) 715set_git_work_tree(git_work_tree_cfg); 716else{ 717char*core_worktree; 718if(chdir(gitdirenv)) 719die_errno(_("cannot chdir to '%s'"), gitdirenv); 720if(chdir(git_work_tree_cfg)) 721die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg); 722 core_worktree =xgetcwd(); 723if(chdir(cwd->buf)) 724die_errno(_("cannot come back to cwd")); 725set_git_work_tree(core_worktree); 726free(core_worktree); 727} 728} 729else if(!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT,1)) { 730/* #16d */ 731set_git_dir(gitdirenv); 732free(gitfile); 733return NULL; 734} 735else/* #2, #10 */ 736set_git_work_tree("."); 737 738/* set_git_work_tree() must have been called by now */ 739 worktree =get_git_work_tree(); 740 741/* both get_git_work_tree() and cwd are already normalized */ 742if(!strcmp(cwd->buf, worktree)) {/* cwd == worktree */ 743set_git_dir(gitdirenv); 744free(gitfile); 745return NULL; 746} 747 748 offset =dir_inside_of(cwd->buf, worktree); 749if(offset >=0) {/* cwd inside worktree? */ 750set_git_dir(real_path(gitdirenv)); 751if(chdir(worktree)) 752die_errno(_("cannot chdir to '%s'"), worktree); 753strbuf_addch(cwd,'/'); 754free(gitfile); 755return cwd->buf + offset; 756} 757 758/* cwd outside worktree */ 759set_git_dir(gitdirenv); 760free(gitfile); 761return NULL; 762} 763 764static const char*setup_discovered_git_dir(const char*gitdir, 765struct strbuf *cwd,int offset, 766struct repository_format *repo_fmt, 767int*nongit_ok) 768{ 769if(check_repository_format_gently(gitdir, repo_fmt, nongit_ok)) 770return NULL; 771 772/* --work-tree is set without --git-dir; use discovered one */ 773if(getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) { 774char*to_free = NULL; 775const char*ret; 776 777if(offset != cwd->len && !is_absolute_path(gitdir)) 778 gitdir = to_free =real_pathdup(gitdir,1); 779if(chdir(cwd->buf)) 780die_errno(_("cannot come back to cwd")); 781 ret =setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok); 782free(to_free); 783return ret; 784} 785 786/* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */ 787if(is_bare_repository_cfg >0) { 788set_git_dir(offset == cwd->len ? gitdir :real_path(gitdir)); 789if(chdir(cwd->buf)) 790die_errno(_("cannot come back to cwd")); 791return NULL; 792} 793 794/* #0, #1, #5, #8, #9, #12, #13 */ 795set_git_work_tree("."); 796if(strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT)) 797set_git_dir(gitdir); 798 inside_git_dir =0; 799 inside_work_tree =1; 800if(offset == cwd->len) 801return NULL; 802 803/* Make "offset" point past the '/' (already the case for root dirs) */ 804if(offset !=offset_1st_component(cwd->buf)) 805 offset++; 806/* Add a '/' at the end */ 807strbuf_addch(cwd,'/'); 808return cwd->buf + offset; 809} 810 811/* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */ 812static const char*setup_bare_git_dir(struct strbuf *cwd,int offset, 813struct repository_format *repo_fmt, 814int*nongit_ok) 815{ 816int root_len; 817 818if(check_repository_format_gently(".", repo_fmt, nongit_ok)) 819return NULL; 820 821setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT,"0",1); 822 823/* --work-tree is set without --git-dir; use discovered one */ 824if(getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) { 825static const char*gitdir; 826 827 gitdir = offset == cwd->len ?".":xmemdupz(cwd->buf, offset); 828if(chdir(cwd->buf)) 829die_errno(_("cannot come back to cwd")); 830returnsetup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok); 831} 832 833 inside_git_dir =1; 834 inside_work_tree =0; 835if(offset != cwd->len) { 836if(chdir(cwd->buf)) 837die_errno(_("cannot come back to cwd")); 838 root_len =offset_1st_component(cwd->buf); 839strbuf_setlen(cwd, offset > root_len ? offset : root_len); 840set_git_dir(cwd->buf); 841} 842else 843set_git_dir("."); 844return NULL; 845} 846 847static dev_t get_device_or_die(const char*path,const char*prefix,int prefix_len) 848{ 849struct stat buf; 850if(stat(path, &buf)) { 851die_errno(_("failed to stat '%*s%s%s'"), 852 prefix_len, 853 prefix ? prefix :"", 854 prefix ?"/":"", path); 855} 856return buf.st_dev; 857} 858 859/* 860 * A "string_list_each_func_t" function that canonicalizes an entry 861 * from GIT_CEILING_DIRECTORIES using real_path_if_valid(), or 862 * discards it if unusable. The presence of an empty entry in 863 * GIT_CEILING_DIRECTORIES turns off canonicalization for all 864 * subsequent entries. 865 */ 866static intcanonicalize_ceiling_entry(struct string_list_item *item, 867void*cb_data) 868{ 869int*empty_entry_found = cb_data; 870char*ceil = item->string; 871 872if(!*ceil) { 873*empty_entry_found =1; 874return0; 875}else if(!is_absolute_path(ceil)) { 876return0; 877}else if(*empty_entry_found) { 878/* Keep entry but do not canonicalize it */ 879return1; 880}else{ 881char*real_path =real_pathdup(ceil,0); 882if(!real_path) { 883return0; 884} 885free(item->string); 886 item->string = real_path; 887return1; 888} 889} 890 891enum discovery_result { 892 GIT_DIR_NONE =0, 893 GIT_DIR_EXPLICIT, 894 GIT_DIR_DISCOVERED, 895 GIT_DIR_BARE, 896/* these are errors */ 897 GIT_DIR_HIT_CEILING = -1, 898 GIT_DIR_HIT_MOUNT_POINT = -2, 899 GIT_DIR_INVALID_GITFILE = -3 900}; 901 902/* 903 * We cannot decide in this function whether we are in the work tree or 904 * not, since the config can only be read _after_ this function was called. 905 * 906 * Also, we avoid changing any global state (such as the current working 907 * directory) to allow early callers. 908 * 909 * The directory where the search should start needs to be passed in via the 910 * `dir` parameter; upon return, the `dir` buffer will contain the path of 911 * the directory where the search ended, and `gitdir` will contain the path of 912 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it 913 * is relative to `dir` (i.e. *not* necessarily the cwd). 914 */ 915static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir, 916struct strbuf *gitdir, 917int die_on_error) 918{ 919const char*env_ceiling_dirs =getenv(CEILING_DIRECTORIES_ENVIRONMENT); 920struct string_list ceiling_dirs = STRING_LIST_INIT_DUP; 921const char*gitdirenv; 922int ceil_offset = -1, min_offset =has_dos_drive_prefix(dir->buf) ?3:1; 923 dev_t current_device =0; 924int one_filesystem =1; 925 926/* 927 * If GIT_DIR is set explicitly, we're not going 928 * to do any discovery, but we still do repository 929 * validation. 930 */ 931 gitdirenv =getenv(GIT_DIR_ENVIRONMENT); 932if(gitdirenv) { 933strbuf_addstr(gitdir, gitdirenv); 934return GIT_DIR_EXPLICIT; 935} 936 937if(env_ceiling_dirs) { 938int empty_entry_found =0; 939 940string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1); 941filter_string_list(&ceiling_dirs,0, 942 canonicalize_ceiling_entry, &empty_entry_found); 943 ceil_offset =longest_ancestor_length(dir->buf, &ceiling_dirs); 944string_list_clear(&ceiling_dirs,0); 945} 946 947if(ceil_offset <0) 948 ceil_offset = min_offset -2; 949 950/* 951 * Test in the following order (relative to the dir): 952 * - .git (file containing "gitdir: <path>") 953 * - .git/ 954 * - ./ (bare) 955 * - ../.git 956 * - ../.git/ 957 * - ../ (bare) 958 * - ../../.git 959 * etc. 960 */ 961 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM",0); 962if(one_filesystem) 963 current_device =get_device_or_die(dir->buf, NULL,0); 964for(;;) { 965int offset = dir->len, error_code =0; 966 967if(offset > min_offset) 968strbuf_addch(dir,'/'); 969strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT); 970 gitdirenv =read_gitfile_gently(dir->buf, die_on_error ? 971 NULL : &error_code); 972if(!gitdirenv) { 973if(die_on_error || 974 error_code == READ_GITFILE_ERR_NOT_A_FILE) { 975/* NEEDSWORK: fail if .git is not file nor dir */ 976if(is_git_directory(dir->buf)) 977 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT; 978}else if(error_code != READ_GITFILE_ERR_STAT_FAILED) 979return GIT_DIR_INVALID_GITFILE; 980} 981strbuf_setlen(dir, offset); 982if(gitdirenv) { 983strbuf_addstr(gitdir, gitdirenv); 984return GIT_DIR_DISCOVERED; 985} 986 987if(is_git_directory(dir->buf)) { 988strbuf_addstr(gitdir,"."); 989return GIT_DIR_BARE; 990} 991 992if(offset <= min_offset) 993return GIT_DIR_HIT_CEILING; 994 995while(--offset > ceil_offset && !is_dir_sep(dir->buf[offset])) 996;/* continue */ 997if(offset <= ceil_offset) 998return GIT_DIR_HIT_CEILING; 9991000strbuf_setlen(dir, offset > min_offset ? offset : min_offset);1001if(one_filesystem &&1002 current_device !=get_device_or_die(dir->buf, NULL, offset))1003return GIT_DIR_HIT_MOUNT_POINT;1004}1005}10061007intdiscover_git_directory(struct strbuf *commondir,1008struct strbuf *gitdir)1009{1010struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;1011size_t gitdir_offset = gitdir->len, cwd_len;1012size_t commondir_offset = commondir->len;1013struct repository_format candidate = REPOSITORY_FORMAT_INIT;10141015if(strbuf_getcwd(&dir))1016return-1;10171018 cwd_len = dir.len;1019if(setup_git_directory_gently_1(&dir, gitdir,0) <=0) {1020strbuf_release(&dir);1021return-1;1022}10231024/*1025 * The returned gitdir is relative to dir, and if dir does not reflect1026 * the current working directory, we simply make the gitdir absolute.1027 */1028if(dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {1029/* Avoid a trailing "/." */1030if(!strcmp(".", gitdir->buf + gitdir_offset))1031strbuf_setlen(gitdir, gitdir_offset);1032else1033strbuf_addch(&dir,'/');1034strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);1035}10361037get_common_dir(commondir, gitdir->buf + gitdir_offset);10381039strbuf_reset(&dir);1040strbuf_addf(&dir,"%s/config", commondir->buf + commondir_offset);1041read_repository_format(&candidate, dir.buf);1042strbuf_release(&dir);10431044if(verify_repository_format(&candidate, &err) <0) {1045warning("ignoring git dir '%s':%s",1046 gitdir->buf + gitdir_offset, err.buf);1047strbuf_release(&err);1048strbuf_setlen(commondir, commondir_offset);1049strbuf_setlen(gitdir, gitdir_offset);1050clear_repository_format(&candidate);1051return-1;1052}10531054clear_repository_format(&candidate);1055return0;1056}10571058const char*setup_git_directory_gently(int*nongit_ok)1059{1060static struct strbuf cwd = STRBUF_INIT;1061struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT;1062const char*prefix = NULL;1063struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;10641065/*1066 * We may have read an incomplete configuration before1067 * setting-up the git directory. If so, clear the cache so1068 * that the next queries to the configuration reload complete1069 * configuration (including the per-repo config file that we1070 * ignored previously).1071 */1072git_config_clear();10731074/*1075 * Let's assume that we are in a git repository.1076 * If it turns out later that we are somewhere else, the value will be1077 * updated accordingly.1078 */1079if(nongit_ok)1080*nongit_ok =0;10811082if(strbuf_getcwd(&cwd))1083die_errno(_("Unable to read current working directory"));1084strbuf_addbuf(&dir, &cwd);10851086switch(setup_git_directory_gently_1(&dir, &gitdir,1)) {1087case GIT_DIR_EXPLICIT:1088 prefix =setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);1089break;1090case GIT_DIR_DISCOVERED:1091if(dir.len < cwd.len &&chdir(dir.buf))1092die(_("cannot change to '%s'"), dir.buf);1093 prefix =setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,1094&repo_fmt, nongit_ok);1095break;1096case GIT_DIR_BARE:1097if(dir.len < cwd.len &&chdir(dir.buf))1098die(_("cannot change to '%s'"), dir.buf);1099 prefix =setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);1100break;1101case GIT_DIR_HIT_CEILING:1102if(!nongit_ok)1103die(_("not a git repository (or any of the parent directories):%s"),1104 DEFAULT_GIT_DIR_ENVIRONMENT);1105*nongit_ok =1;1106break;1107case GIT_DIR_HIT_MOUNT_POINT:1108if(!nongit_ok)1109die(_("not a git repository (or any parent up to mount point%s)\n"1110"Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),1111 dir.buf);1112*nongit_ok =1;1113break;1114case GIT_DIR_NONE:1115/*1116 * As a safeguard against setup_git_directory_gently_1 returning1117 * this value, fallthrough to BUG. Otherwise it is possible to1118 * set startup_info->have_repository to 1 when we did nothing to1119 * find a repository.1120 */1121default:1122BUG("unhandled setup_git_directory_1() result");1123}11241125/*1126 * At this point, nongit_ok is stable. If it is non-NULL and points1127 * to a non-zero value, then this means that we haven't found a1128 * repository and that the caller expects startup_info to reflect1129 * this.1130 *1131 * Regardless of the state of nongit_ok, startup_info->prefix and1132 * the GIT_PREFIX environment variable must always match. For details1133 * see Documentation/config/alias.txt.1134 */1135if(nongit_ok && *nongit_ok) {1136 startup_info->have_repository =0;1137 startup_info->prefix = NULL;1138setenv(GIT_PREFIX_ENVIRONMENT,"",1);1139}else{1140 startup_info->have_repository =1;1141 startup_info->prefix = prefix;1142if(prefix)1143setenv(GIT_PREFIX_ENVIRONMENT, prefix,1);1144else1145setenv(GIT_PREFIX_ENVIRONMENT,"",1);1146}11471148/*1149 * Not all paths through the setup code will call 'set_git_dir()' (which1150 * directly sets up the environment) so in order to guarantee that the1151 * environment is in a consistent state after setup, explicitly setup1152 * the environment if we have a repository.1153 *1154 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some1155 * code paths so we also need to explicitly setup the environment if1156 * the user has set GIT_DIR. It may be beneficial to disallow bogus1157 * GIT_DIR values at some point in the future.1158 */1159if(/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */1160 startup_info->have_repository ||1161/* GIT_DIR_EXPLICIT */1162getenv(GIT_DIR_ENVIRONMENT)) {1163if(!the_repository->gitdir) {1164const char*gitdir =getenv(GIT_DIR_ENVIRONMENT);1165if(!gitdir)1166 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;1167setup_git_env(gitdir);1168}1169if(startup_info->have_repository)1170repo_set_hash_algo(the_repository, repo_fmt.hash_algo);1171}11721173strbuf_release(&dir);1174strbuf_release(&gitdir);1175clear_repository_format(&repo_fmt);11761177return prefix;1178}11791180intgit_config_perm(const char*var,const char*value)1181{1182int i;1183char*endptr;11841185if(value == NULL)1186return PERM_GROUP;11871188if(!strcmp(value,"umask"))1189return PERM_UMASK;1190if(!strcmp(value,"group"))1191return PERM_GROUP;1192if(!strcmp(value,"all") ||1193!strcmp(value,"world") ||1194!strcmp(value,"everybody"))1195return PERM_EVERYBODY;11961197/* Parse octal numbers */1198 i =strtol(value, &endptr,8);11991200/* If not an octal number, maybe true/false? */1201if(*endptr !=0)1202returngit_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;12031204/*1205 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is1206 * a chmod value to restrict to.1207 */1208switch(i) {1209case PERM_UMASK:/* 0 */1210return PERM_UMASK;1211case OLD_PERM_GROUP:/* 1 */1212return PERM_GROUP;1213case OLD_PERM_EVERYBODY:/* 2 */1214return PERM_EVERYBODY;1215}12161217/* A filemode value was given: 0xxx */12181219if((i &0600) !=0600)1220die(_("problem with core.sharedRepository filemode value "1221"(0%.3o).\nThe owner of files must always have "1222"read and write permissions."), i);12231224/*1225 * Mask filemode value. Others can not get write permission.1226 * x flags for directories are handled separately.1227 */1228return-(i &0666);1229}12301231voidcheck_repository_format(void)1232{1233struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;1234check_repository_format_gently(get_git_dir(), &repo_fmt, NULL);1235 startup_info->have_repository =1;1236clear_repository_format(&repo_fmt);1237}12381239/*1240 * Returns the "prefix", a path to the current working directory1241 * relative to the work tree root, or NULL, if the current working1242 * directory is not a strict subdirectory of the work tree root. The1243 * prefix always ends with a '/' character.1244 */1245const char*setup_git_directory(void)1246{1247returnsetup_git_directory_gently(NULL);1248}12491250const char*resolve_gitdir_gently(const char*suspect,int*return_error_code)1251{1252if(is_git_directory(suspect))1253return suspect;1254returnread_gitfile_gently(suspect, return_error_code);1255}12561257/* if any standard file descriptor is missing open it to /dev/null */1258voidsanitize_stdfds(void)1259{1260int fd =open("/dev/null", O_RDWR,0);1261while(fd != -1&& fd <2)1262 fd =dup(fd);1263if(fd == -1)1264die_errno(_("open /dev/null or dup failed"));1265if(fd >2)1266close(fd);1267}12681269intdaemonize(void)1270{1271#ifdef NO_POSIX_GOODIES1272 errno = ENOSYS;1273return-1;1274#else1275switch(fork()) {1276case0:1277break;1278case-1:1279die_errno(_("fork failed"));1280default:1281exit(0);1282}1283if(setsid() == -1)1284die_errno(_("setsid failed"));1285close(0);1286close(1);1287close(2);1288sanitize_stdfds();1289return0;1290#endif1291}