init-db.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. /*
  2. * GIT - The information manager from hell
  3. *
  4. * Copyright (C) Linus Torvalds, 2005
  5. */
  6. #include "cache.h"
  7. #include "config.h"
  8. #include "refs.h"
  9. #include "builtin.h"
  10. #include "exec-cmd.h"
  11. #include "parse-options.h"
  12. #include "worktree.h"
  13. #ifndef DEFAULT_GIT_TEMPLATE_DIR
  14. #define DEFAULT_GIT_TEMPLATE_DIR "/usr/share/git-core/templates"
  15. #endif
  16. #ifdef NO_TRUSTABLE_FILEMODE
  17. #define TEST_FILEMODE 0
  18. #else
  19. #define TEST_FILEMODE 1
  20. #endif
  21. #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
  22. static int init_is_bare_repository = 0;
  23. static int init_shared_repository = -1;
  24. static const char *init_db_template_dir;
  25. static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
  26. DIR *dir)
  27. {
  28. size_t path_baselen = path->len;
  29. size_t template_baselen = template_path->len;
  30. struct dirent *de;
  31. /* Note: if ".git/hooks" file exists in the repository being
  32. * re-initialized, /etc/core-git/templates/hooks/update would
  33. * cause "git init" to fail here. I think this is sane but
  34. * it means that the set of templates we ship by default, along
  35. * with the way the namespace under .git/ is organized, should
  36. * be really carefully chosen.
  37. */
  38. safe_create_dir(path->buf, 1);
  39. while ((de = readdir(dir)) != NULL) {
  40. struct stat st_git, st_template;
  41. int exists = 0;
  42. strbuf_setlen(path, path_baselen);
  43. strbuf_setlen(template_path, template_baselen);
  44. if (de->d_name[0] == '.')
  45. continue;
  46. strbuf_addstr(path, de->d_name);
  47. strbuf_addstr(template_path, de->d_name);
  48. if (lstat(path->buf, &st_git)) {
  49. if (errno != ENOENT)
  50. die_errno(_("cannot stat '%s'"), path->buf);
  51. }
  52. else
  53. exists = 1;
  54. if (lstat(template_path->buf, &st_template))
  55. die_errno(_("cannot stat template '%s'"), template_path->buf);
  56. if (S_ISDIR(st_template.st_mode)) {
  57. DIR *subdir = opendir(template_path->buf);
  58. if (!subdir)
  59. die_errno(_("cannot opendir '%s'"), template_path->buf);
  60. strbuf_addch(path, '/');
  61. strbuf_addch(template_path, '/');
  62. copy_templates_1(path, template_path, subdir);
  63. closedir(subdir);
  64. }
  65. else if (exists)
  66. continue;
  67. else if (S_ISLNK(st_template.st_mode)) {
  68. struct strbuf lnk = STRBUF_INIT;
  69. if (strbuf_readlink(&lnk, template_path->buf,
  70. st_template.st_size) < 0)
  71. die_errno(_("cannot readlink '%s'"), template_path->buf);
  72. if (symlink(lnk.buf, path->buf))
  73. die_errno(_("cannot symlink '%s' '%s'"),
  74. lnk.buf, path->buf);
  75. strbuf_release(&lnk);
  76. }
  77. else if (S_ISREG(st_template.st_mode)) {
  78. if (copy_file(path->buf, template_path->buf, st_template.st_mode))
  79. die_errno(_("cannot copy '%s' to '%s'"),
  80. template_path->buf, path->buf);
  81. }
  82. else
  83. error(_("ignoring template %s"), template_path->buf);
  84. }
  85. }
  86. static void copy_templates(const char *template_dir)
  87. {
  88. struct strbuf path = STRBUF_INIT;
  89. struct strbuf template_path = STRBUF_INIT;
  90. size_t template_len;
  91. struct repository_format template_format = REPOSITORY_FORMAT_INIT;
  92. struct strbuf err = STRBUF_INIT;
  93. DIR *dir;
  94. char *to_free = NULL;
  95. if (!template_dir)
  96. template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
  97. if (!template_dir)
  98. template_dir = init_db_template_dir;
  99. if (!template_dir)
  100. template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
  101. if (!template_dir[0]) {
  102. free(to_free);
  103. return;
  104. }
  105. strbuf_addstr(&template_path, template_dir);
  106. strbuf_complete(&template_path, '/');
  107. template_len = template_path.len;
  108. dir = opendir(template_path.buf);
  109. if (!dir) {
  110. warning(_("templates not found in %s"), template_dir);
  111. goto free_return;
  112. }
  113. /* Make sure that template is from the correct vintage */
  114. strbuf_addstr(&template_path, "config");
  115. read_repository_format(&template_format, template_path.buf);
  116. strbuf_setlen(&template_path, template_len);
  117. /*
  118. * No mention of version at all is OK, but anything else should be
  119. * verified.
  120. */
  121. if (template_format.version >= 0 &&
  122. verify_repository_format(&template_format, &err) < 0) {
  123. warning(_("not copying templates from '%s': %s"),
  124. template_dir, err.buf);
  125. strbuf_release(&err);
  126. goto close_free_return;
  127. }
  128. strbuf_addstr(&path, get_git_common_dir());
  129. strbuf_complete(&path, '/');
  130. copy_templates_1(&path, &template_path, dir);
  131. close_free_return:
  132. closedir(dir);
  133. free_return:
  134. free(to_free);
  135. strbuf_release(&path);
  136. strbuf_release(&template_path);
  137. clear_repository_format(&template_format);
  138. }
  139. static int git_init_db_config(const char *k, const char *v, void *cb)
  140. {
  141. if (!strcmp(k, "init.templatedir"))
  142. return git_config_pathname(&init_db_template_dir, k, v);
  143. if (starts_with(k, "core."))
  144. return platform_core_config(k, v, cb);
  145. return 0;
  146. }
  147. /*
  148. * If the git_dir is not directly inside the working tree, then git will not
  149. * find it by default, and we need to set the worktree explicitly.
  150. */
  151. static int needs_work_tree_config(const char *git_dir, const char *work_tree)
  152. {
  153. if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
  154. return 0;
  155. if (skip_prefix(git_dir, work_tree, &git_dir) &&
  156. !strcmp(git_dir, "/.git"))
  157. return 0;
  158. return 1;
  159. }
  160. void initialize_repository_version(int hash_algo, int reinit)
  161. {
  162. char repo_version_string[10];
  163. int repo_version = GIT_REPO_VERSION;
  164. if (hash_algo != GIT_HASH_SHA1)
  165. repo_version = GIT_REPO_VERSION_READ;
  166. /* This forces creation of new config file */
  167. xsnprintf(repo_version_string, sizeof(repo_version_string),
  168. "%d", repo_version);
  169. git_config_set("core.repositoryformatversion", repo_version_string);
  170. if (hash_algo != GIT_HASH_SHA1)
  171. git_config_set("extensions.objectformat",
  172. hash_algos[hash_algo].name);
  173. else if (reinit)
  174. git_config_set_gently("extensions.objectformat", NULL);
  175. }
  176. static int create_default_files(const char *template_path,
  177. const char *original_git_dir,
  178. const char *initial_branch,
  179. const struct repository_format *fmt)
  180. {
  181. struct stat st1;
  182. struct strbuf buf = STRBUF_INIT;
  183. char *path;
  184. char junk[2];
  185. int reinit;
  186. int filemode;
  187. struct strbuf err = STRBUF_INIT;
  188. /* Just look for `init.templatedir` */
  189. init_db_template_dir = NULL; /* re-set in case it was set before */
  190. git_config(git_init_db_config, NULL);
  191. /*
  192. * First copy the templates -- we might have the default
  193. * config file there, in which case we would want to read
  194. * from it after installing.
  195. *
  196. * Before reading that config, we also need to clear out any cached
  197. * values (since we've just potentially changed what's available on
  198. * disk).
  199. */
  200. copy_templates(template_path);
  201. git_config_clear();
  202. reset_shared_repository();
  203. git_config(git_default_config, NULL);
  204. /*
  205. * We must make sure command-line options continue to override any
  206. * values we might have just re-read from the config.
  207. */
  208. is_bare_repository_cfg = init_is_bare_repository;
  209. if (init_shared_repository != -1)
  210. set_shared_repository(init_shared_repository);
  211. /*
  212. * We would have created the above under user's umask -- under
  213. * shared-repository settings, we would need to fix them up.
  214. */
  215. if (get_shared_repository()) {
  216. adjust_shared_perm(get_git_dir());
  217. }
  218. /*
  219. * We need to create a "refs" dir in any case so that older
  220. * versions of git can tell that this is a repository.
  221. */
  222. safe_create_dir(git_path("refs"), 1);
  223. adjust_shared_perm(git_path("refs"));
  224. if (refs_init_db(&err))
  225. die("failed to set up refs db: %s", err.buf);
  226. /*
  227. * Point the HEAD symref to the initial branch with if HEAD does
  228. * not yet exist.
  229. */
  230. path = git_path_buf(&buf, "HEAD");
  231. reinit = (!access(path, R_OK)
  232. || readlink(path, junk, sizeof(junk)-1) != -1);
  233. if (!reinit) {
  234. char *ref;
  235. if (!initial_branch)
  236. initial_branch = git_default_branch_name();
  237. ref = xstrfmt("refs/heads/%s", initial_branch);
  238. if (check_refname_format(ref, 0) < 0)
  239. die(_("invalid initial branch name: '%s'"),
  240. initial_branch);
  241. if (create_symref("HEAD", ref, NULL) < 0)
  242. exit(1);
  243. free(ref);
  244. }
  245. initialize_repository_version(fmt->hash_algo, 0);
  246. /* Check filemode trustability */
  247. path = git_path_buf(&buf, "config");
  248. filemode = TEST_FILEMODE;
  249. if (TEST_FILEMODE && !lstat(path, &st1)) {
  250. struct stat st2;
  251. filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
  252. !lstat(path, &st2) &&
  253. st1.st_mode != st2.st_mode &&
  254. !chmod(path, st1.st_mode));
  255. if (filemode && !reinit && (st1.st_mode & S_IXUSR))
  256. filemode = 0;
  257. }
  258. git_config_set("core.filemode", filemode ? "true" : "false");
  259. if (is_bare_repository())
  260. git_config_set("core.bare", "true");
  261. else {
  262. const char *work_tree = get_git_work_tree();
  263. git_config_set("core.bare", "false");
  264. /* allow template config file to override the default */
  265. if (log_all_ref_updates == LOG_REFS_UNSET)
  266. git_config_set("core.logallrefupdates", "true");
  267. if (needs_work_tree_config(original_git_dir, work_tree))
  268. git_config_set("core.worktree", work_tree);
  269. }
  270. if (!reinit) {
  271. /* Check if symlink is supported in the work tree */
  272. path = git_path_buf(&buf, "tXXXXXX");
  273. if (!close(xmkstemp(path)) &&
  274. !unlink(path) &&
  275. !symlink("testing", path) &&
  276. !lstat(path, &st1) &&
  277. S_ISLNK(st1.st_mode))
  278. unlink(path); /* good */
  279. else
  280. git_config_set("core.symlinks", "false");
  281. /* Check if the filesystem is case-insensitive */
  282. path = git_path_buf(&buf, "CoNfIg");
  283. if (!access(path, F_OK))
  284. git_config_set("core.ignorecase", "true");
  285. probe_utf8_pathname_composition();
  286. }
  287. strbuf_release(&buf);
  288. return reinit;
  289. }
  290. static void create_object_directory(void)
  291. {
  292. struct strbuf path = STRBUF_INIT;
  293. size_t baselen;
  294. strbuf_addstr(&path, get_object_directory());
  295. baselen = path.len;
  296. safe_create_dir(path.buf, 1);
  297. strbuf_setlen(&path, baselen);
  298. strbuf_addstr(&path, "/pack");
  299. safe_create_dir(path.buf, 1);
  300. strbuf_setlen(&path, baselen);
  301. strbuf_addstr(&path, "/info");
  302. safe_create_dir(path.buf, 1);
  303. strbuf_release(&path);
  304. }
  305. static void separate_git_dir(const char *git_dir, const char *git_link)
  306. {
  307. struct stat st;
  308. if (!stat(git_link, &st)) {
  309. const char *src;
  310. if (S_ISREG(st.st_mode))
  311. src = read_gitfile(git_link);
  312. else if (S_ISDIR(st.st_mode))
  313. src = git_link;
  314. else
  315. die(_("unable to handle file type %d"), (int)st.st_mode);
  316. if (rename(src, git_dir))
  317. die_errno(_("unable to move %s to %s"), src, git_dir);
  318. repair_worktrees(NULL, NULL);
  319. }
  320. write_file(git_link, "gitdir: %s", git_dir);
  321. }
  322. static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
  323. {
  324. const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
  325. /*
  326. * If we already have an initialized repo, don't allow the user to
  327. * specify a different algorithm, as that could cause corruption.
  328. * Otherwise, if the user has specified one on the command line, use it.
  329. */
  330. if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
  331. die(_("attempt to reinitialize repository with different hash"));
  332. else if (hash != GIT_HASH_UNKNOWN)
  333. repo_fmt->hash_algo = hash;
  334. else if (env) {
  335. int env_algo = hash_algo_by_name(env);
  336. if (env_algo == GIT_HASH_UNKNOWN)
  337. die(_("unknown hash algorithm '%s'"), env);
  338. repo_fmt->hash_algo = env_algo;
  339. }
  340. }
  341. int init_db(const char *git_dir, const char *real_git_dir,
  342. const char *template_dir, int hash, const char *initial_branch,
  343. unsigned int flags)
  344. {
  345. int reinit;
  346. int exist_ok = flags & INIT_DB_EXIST_OK;
  347. char *original_git_dir = real_pathdup(git_dir, 1);
  348. struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
  349. if (real_git_dir) {
  350. struct stat st;
  351. if (!exist_ok && !stat(git_dir, &st))
  352. die(_("%s already exists"), git_dir);
  353. if (!exist_ok && !stat(real_git_dir, &st))
  354. die(_("%s already exists"), real_git_dir);
  355. set_git_dir(real_git_dir, 1);
  356. git_dir = get_git_dir();
  357. separate_git_dir(git_dir, original_git_dir);
  358. }
  359. else {
  360. set_git_dir(git_dir, 1);
  361. git_dir = get_git_dir();
  362. }
  363. startup_info->have_repository = 1;
  364. /* Just look for `core.hidedotfiles` */
  365. git_config(git_init_db_config, NULL);
  366. safe_create_dir(git_dir, 0);
  367. init_is_bare_repository = is_bare_repository();
  368. /* Check to see if the repository version is right.
  369. * Note that a newly created repository does not have
  370. * config file, so this will not fail. What we are catching
  371. * is an attempt to reinitialize new repository with an old tool.
  372. */
  373. check_repository_format(&repo_fmt);
  374. validate_hash_algorithm(&repo_fmt, hash);
  375. reinit = create_default_files(template_dir, original_git_dir,
  376. initial_branch, &repo_fmt);
  377. if (reinit && initial_branch)
  378. warning(_("re-init: ignored --initial-branch=%s"),
  379. initial_branch);
  380. create_object_directory();
  381. if (get_shared_repository()) {
  382. char buf[10];
  383. /* We do not spell "group" and such, so that
  384. * the configuration can be read by older version
  385. * of git. Note, we use octal numbers for new share modes,
  386. * and compatibility values for PERM_GROUP and
  387. * PERM_EVERYBODY.
  388. */
  389. if (get_shared_repository() < 0)
  390. /* force to the mode value */
  391. xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
  392. else if (get_shared_repository() == PERM_GROUP)
  393. xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
  394. else if (get_shared_repository() == PERM_EVERYBODY)
  395. xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
  396. else
  397. BUG("invalid value for shared_repository");
  398. git_config_set("core.sharedrepository", buf);
  399. git_config_set("receive.denyNonFastforwards", "true");
  400. }
  401. if (!(flags & INIT_DB_QUIET)) {
  402. int len = strlen(git_dir);
  403. if (reinit)
  404. printf(get_shared_repository()
  405. ? _("Reinitialized existing shared Git repository in %s%s\n")
  406. : _("Reinitialized existing Git repository in %s%s\n"),
  407. git_dir, len && git_dir[len-1] != '/' ? "/" : "");
  408. else
  409. printf(get_shared_repository()
  410. ? _("Initialized empty shared Git repository in %s%s\n")
  411. : _("Initialized empty Git repository in %s%s\n"),
  412. git_dir, len && git_dir[len-1] != '/' ? "/" : "");
  413. }
  414. free(original_git_dir);
  415. return 0;
  416. }
  417. static int guess_repository_type(const char *git_dir)
  418. {
  419. const char *slash;
  420. char *cwd;
  421. int cwd_is_git_dir;
  422. /*
  423. * "GIT_DIR=. git init" is always bare.
  424. * "GIT_DIR=`pwd` git init" too.
  425. */
  426. if (!strcmp(".", git_dir))
  427. return 1;
  428. cwd = xgetcwd();
  429. cwd_is_git_dir = !strcmp(git_dir, cwd);
  430. free(cwd);
  431. if (cwd_is_git_dir)
  432. return 1;
  433. /*
  434. * "GIT_DIR=.git or GIT_DIR=something/.git is usually not.
  435. */
  436. if (!strcmp(git_dir, ".git"))
  437. return 0;
  438. slash = strrchr(git_dir, '/');
  439. if (slash && !strcmp(slash, "/.git"))
  440. return 0;
  441. /*
  442. * Otherwise it is often bare. At this point
  443. * we are just guessing.
  444. */
  445. return 1;
  446. }
  447. static int shared_callback(const struct option *opt, const char *arg, int unset)
  448. {
  449. BUG_ON_OPT_NEG(unset);
  450. *((int *) opt->value) = (arg) ? git_config_perm("arg", arg) : PERM_GROUP;
  451. return 0;
  452. }
  453. static const char *const init_db_usage[] = {
  454. N_("git init [-q | --quiet] [--bare] [--template=<template-directory>] [--shared[=<permissions>]] [<directory>]"),
  455. NULL
  456. };
  457. /*
  458. * If you want to, you can share the DB area with any number of branches.
  459. * That has advantages: you can save space by sharing all the SHA1 objects.
  460. * On the other hand, it might just make lookup slower and messier. You
  461. * be the judge. The default case is to have one DB per managed directory.
  462. */
  463. int cmd_init_db(int argc, const char **argv, const char *prefix)
  464. {
  465. const char *git_dir;
  466. const char *real_git_dir = NULL;
  467. const char *work_tree;
  468. const char *template_dir = NULL;
  469. unsigned int flags = 0;
  470. const char *object_format = NULL;
  471. const char *initial_branch = NULL;
  472. int hash_algo = GIT_HASH_UNKNOWN;
  473. const struct option init_db_options[] = {
  474. OPT_STRING(0, "template", &template_dir, N_("template-directory"),
  475. N_("directory from which templates will be used")),
  476. OPT_SET_INT(0, "bare", &is_bare_repository_cfg,
  477. N_("create a bare repository"), 1),
  478. { OPTION_CALLBACK, 0, "shared", &init_shared_repository,
  479. N_("permissions"),
  480. N_("specify that the git repository is to be shared amongst several users"),
  481. PARSE_OPT_OPTARG | PARSE_OPT_NONEG, shared_callback, 0},
  482. OPT_BIT('q', "quiet", &flags, N_("be quiet"), INIT_DB_QUIET),
  483. OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
  484. N_("separate git dir from working tree")),
  485. OPT_STRING('b', "initial-branch", &initial_branch, N_("name"),
  486. N_("override the name of the initial branch")),
  487. OPT_STRING(0, "object-format", &object_format, N_("hash"),
  488. N_("specify the hash algorithm to use")),
  489. OPT_END()
  490. };
  491. argc = parse_options(argc, argv, prefix, init_db_options, init_db_usage, 0);
  492. if (real_git_dir && is_bare_repository_cfg == 1)
  493. die(_("--separate-git-dir and --bare are mutually exclusive"));
  494. if (real_git_dir && !is_absolute_path(real_git_dir))
  495. real_git_dir = real_pathdup(real_git_dir, 1);
  496. if (template_dir && *template_dir && !is_absolute_path(template_dir))
  497. template_dir = absolute_pathdup(template_dir);
  498. if (argc == 1) {
  499. int mkdir_tried = 0;
  500. retry:
  501. if (chdir(argv[0]) < 0) {
  502. if (!mkdir_tried) {
  503. int saved;
  504. /*
  505. * At this point we haven't read any configuration,
  506. * and we know shared_repository should always be 0;
  507. * but just in case we play safe.
  508. */
  509. saved = get_shared_repository();
  510. set_shared_repository(0);
  511. switch (safe_create_leading_directories_const(argv[0])) {
  512. case SCLD_OK:
  513. case SCLD_PERMS:
  514. break;
  515. case SCLD_EXISTS:
  516. errno = EEXIST;
  517. /* fallthru */
  518. default:
  519. die_errno(_("cannot mkdir %s"), argv[0]);
  520. break;
  521. }
  522. set_shared_repository(saved);
  523. if (mkdir(argv[0], 0777) < 0)
  524. die_errno(_("cannot mkdir %s"), argv[0]);
  525. mkdir_tried = 1;
  526. goto retry;
  527. }
  528. die_errno(_("cannot chdir to %s"), argv[0]);
  529. }
  530. } else if (0 < argc) {
  531. usage(init_db_usage[0]);
  532. }
  533. if (is_bare_repository_cfg == 1) {
  534. char *cwd = xgetcwd();
  535. setenv(GIT_DIR_ENVIRONMENT, cwd, argc > 0);
  536. free(cwd);
  537. }
  538. if (object_format) {
  539. hash_algo = hash_algo_by_name(object_format);
  540. if (hash_algo == GIT_HASH_UNKNOWN)
  541. die(_("unknown hash algorithm '%s'"), object_format);
  542. }
  543. if (init_shared_repository != -1)
  544. set_shared_repository(init_shared_repository);
  545. /*
  546. * GIT_WORK_TREE makes sense only in conjunction with GIT_DIR
  547. * without --bare. Catch the error early.
  548. */
  549. git_dir = xstrdup_or_null(getenv(GIT_DIR_ENVIRONMENT));
  550. work_tree = xstrdup_or_null(getenv(GIT_WORK_TREE_ENVIRONMENT));
  551. if ((!git_dir || is_bare_repository_cfg == 1) && work_tree)
  552. die(_("%s (or --work-tree=<directory>) not allowed without "
  553. "specifying %s (or --git-dir=<directory>)"),
  554. GIT_WORK_TREE_ENVIRONMENT,
  555. GIT_DIR_ENVIRONMENT);
  556. /*
  557. * Set up the default .git directory contents
  558. */
  559. if (!git_dir)
  560. git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
  561. /*
  562. * When --separate-git-dir is used inside a linked worktree, take
  563. * care to ensure that the common .git/ directory is relocated, not
  564. * the worktree-specific .git/worktrees/<id>/ directory.
  565. */
  566. if (real_git_dir) {
  567. int err;
  568. const char *p;
  569. struct strbuf sb = STRBUF_INIT;
  570. p = read_gitfile_gently(git_dir, &err);
  571. if (p && get_common_dir(&sb, p)) {
  572. struct strbuf mainwt = STRBUF_INIT;
  573. strbuf_addbuf(&mainwt, &sb);
  574. strbuf_strip_suffix(&mainwt, "/.git");
  575. if (chdir(mainwt.buf) < 0)
  576. die_errno(_("cannot chdir to %s"), mainwt.buf);
  577. strbuf_release(&mainwt);
  578. git_dir = strbuf_detach(&sb, NULL);
  579. }
  580. strbuf_release(&sb);
  581. }
  582. if (is_bare_repository_cfg < 0)
  583. is_bare_repository_cfg = guess_repository_type(git_dir);
  584. if (!is_bare_repository_cfg) {
  585. const char *git_dir_parent = strrchr(git_dir, '/');
  586. if (git_dir_parent) {
  587. char *rel = xstrndup(git_dir, git_dir_parent - git_dir);
  588. git_work_tree_cfg = real_pathdup(rel, 1);
  589. free(rel);
  590. }
  591. if (!git_work_tree_cfg)
  592. git_work_tree_cfg = xgetcwd();
  593. if (work_tree)
  594. set_git_work_tree(work_tree);
  595. else
  596. set_git_work_tree(git_work_tree_cfg);
  597. if (access(get_git_work_tree(), X_OK))
  598. die_errno (_("Cannot access work tree '%s'"),
  599. get_git_work_tree());
  600. }
  601. else {
  602. if (real_git_dir)
  603. die(_("--separate-git-dir incompatible with bare repository"));
  604. if (work_tree)
  605. set_git_work_tree(work_tree);
  606. }
  607. UNLEAK(real_git_dir);
  608. UNLEAK(git_dir);
  609. UNLEAK(work_tree);
  610. flags |= INIT_DB_EXIST_OK;
  611. return init_db(git_dir, real_git_dir, template_dir, hash_algo,
  612. initial_branch, flags);
  613. }