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