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