t1007: factor out repeated setup
[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         struct repository_format template_format;
99         struct strbuf err = STRBUF_INIT;
100         DIR *dir;
101         char *to_free = NULL;
102
103         if (!template_dir)
104                 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
105         if (!template_dir)
106                 template_dir = init_db_template_dir;
107         if (!template_dir)
108                 template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
109         if (!template_dir[0]) {
110                 free(to_free);
111                 return;
112         }
113
114         strbuf_addstr(&template_path, template_dir);
115         strbuf_complete(&template_path, '/');
116         template_len = template_path.len;
117
118         dir = opendir(template_path.buf);
119         if (!dir) {
120                 warning(_("templates not found %s"), template_dir);
121                 goto free_return;
122         }
123
124         /* Make sure that template is from the correct vintage */
125         strbuf_addstr(&template_path, "config");
126         read_repository_format(&template_format, template_path.buf);
127         strbuf_setlen(&template_path, template_len);
128
129         /*
130          * No mention of version at all is OK, but anything else should be
131          * verified.
132          */
133         if (template_format.version >= 0 &&
134             verify_repository_format(&template_format, &err) < 0) {
135                 warning(_("not copying templates from '%s': %s"),
136                           template_dir, err.buf);
137                 strbuf_release(&err);
138                 goto close_free_return;
139         }
140
141         strbuf_addstr(&path, get_git_dir());
142         strbuf_complete(&path, '/');
143         copy_templates_1(&path, &template_path, dir);
144 close_free_return:
145         closedir(dir);
146 free_return:
147         free(to_free);
148         strbuf_release(&path);
149         strbuf_release(&template_path);
150 }
151
152 static int git_init_db_config(const char *k, const char *v, void *cb)
153 {
154         if (!strcmp(k, "init.templatedir"))
155                 return git_config_pathname(&init_db_template_dir, k, v);
156
157         return 0;
158 }
159
160 /*
161  * If the git_dir is not directly inside the working tree, then git will not
162  * find it by default, and we need to set the worktree explicitly.
163  */
164 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
165 {
166         if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
167                 return 0;
168         if (skip_prefix(git_dir, work_tree, &git_dir) &&
169             !strcmp(git_dir, "/.git"))
170                 return 0;
171         return 1;
172 }
173
174 static int create_default_files(const char *template_path)
175 {
176         struct stat st1;
177         struct strbuf buf = STRBUF_INIT;
178         char *path;
179         char repo_version_string[10];
180         char junk[2];
181         int reinit;
182         int filemode;
183
184         /*
185          * Create .git/refs/{heads,tags}
186          */
187         safe_create_dir(git_path_buf(&buf, "refs"), 1);
188         safe_create_dir(git_path_buf(&buf, "refs/heads"), 1);
189         safe_create_dir(git_path_buf(&buf, "refs/tags"), 1);
190
191         /* Just look for `init.templatedir` */
192         git_config(git_init_db_config, NULL);
193
194         /*
195          * First copy the templates -- we might have the default
196          * config file there, in which case we would want to read
197          * from it after installing.
198          *
199          * Before reading that config, we also need to clear out any cached
200          * values (since we've just potentially changed what's available on
201          * disk).
202          */
203         copy_templates(template_path);
204         git_config_clear();
205         reset_shared_repository();
206         git_config(git_default_config, NULL);
207
208         /*
209          * We must make sure command-line options continue to override any
210          * values we might have just re-read from the config.
211          */
212         is_bare_repository_cfg = init_is_bare_repository;
213         if (init_shared_repository != -1)
214                 set_shared_repository(init_shared_repository);
215
216         /*
217          * We would have created the above under user's umask -- under
218          * shared-repository settings, we would need to fix them up.
219          */
220         if (get_shared_repository()) {
221                 adjust_shared_perm(get_git_dir());
222                 adjust_shared_perm(git_path_buf(&buf, "refs"));
223                 adjust_shared_perm(git_path_buf(&buf, "refs/heads"));
224                 adjust_shared_perm(git_path_buf(&buf, "refs/tags"));
225         }
226
227         /*
228          * Create the default symlink from ".git/HEAD" to the "master"
229          * branch, if it does not exist yet.
230          */
231         path = git_path_buf(&buf, "HEAD");
232         reinit = (!access(path, R_OK)
233                   || readlink(path, junk, sizeof(junk)-1) != -1);
234         if (!reinit) {
235                 if (create_symref("HEAD", "refs/heads/master", NULL) < 0)
236                         exit(1);
237         }
238
239         /* This forces creation of new config file */
240         xsnprintf(repo_version_string, sizeof(repo_version_string),
241                   "%d", GIT_REPO_VERSION);
242         git_config_set("core.repositoryformatversion", repo_version_string);
243
244         /* Check filemode trustability */
245         path = git_path_buf(&buf, "config");
246         filemode = TEST_FILEMODE;
247         if (TEST_FILEMODE && !lstat(path, &st1)) {
248                 struct stat st2;
249                 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
250                                 !lstat(path, &st2) &&
251                                 st1.st_mode != st2.st_mode &&
252                                 !chmod(path, st1.st_mode));
253                 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
254                         filemode = 0;
255         }
256         git_config_set("core.filemode", filemode ? "true" : "false");
257
258         if (is_bare_repository())
259                 git_config_set("core.bare", "true");
260         else {
261                 const char *work_tree = get_git_work_tree();
262                 git_config_set("core.bare", "false");
263                 /* allow template config file to override the default */
264                 if (log_all_ref_updates == -1)
265                         git_config_set("core.logallrefupdates", "true");
266                 if (needs_work_tree_config(get_git_dir(), work_tree))
267                         git_config_set("core.worktree", work_tree);
268         }
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
282                 /* Check if the filesystem is case-insensitive */
283                 path = git_path_buf(&buf, "CoNfIg");
284                 if (!access(path, F_OK))
285                         git_config_set("core.ignorecase", "true");
286                 probe_utf8_pathname_composition();
287         }
288
289         strbuf_release(&buf);
290         return reinit;
291 }
292
293 static void create_object_directory(void)
294 {
295         struct strbuf path = STRBUF_INIT;
296         size_t baselen;
297
298         strbuf_addstr(&path, get_object_directory());
299         baselen = path.len;
300
301         safe_create_dir(path.buf, 1);
302
303         strbuf_setlen(&path, baselen);
304         strbuf_addstr(&path, "/pack");
305         safe_create_dir(path.buf, 1);
306
307         strbuf_setlen(&path, baselen);
308         strbuf_addstr(&path, "/info");
309         safe_create_dir(path.buf, 1);
310
311         strbuf_release(&path);
312 }
313
314 int set_git_dir_init(const char *git_dir, const char *real_git_dir,
315                      int exist_ok)
316 {
317         if (real_git_dir) {
318                 struct stat st;
319
320                 if (!exist_ok && !stat(git_dir, &st))
321                         die(_("%s already exists"), git_dir);
322
323                 if (!exist_ok && !stat(real_git_dir, &st))
324                         die(_("%s already exists"), real_git_dir);
325
326                 /*
327                  * make sure symlinks are resolved because we'll be
328                  * moving the target repo later on in separate_git_dir()
329                  */
330                 git_link = xstrdup(real_path(git_dir));
331                 set_git_dir(real_path(real_git_dir));
332         }
333         else {
334                 set_git_dir(real_path(git_dir));
335                 git_link = NULL;
336         }
337         startup_info->have_repository = 1;
338         return 0;
339 }
340
341 static void separate_git_dir(const char *git_dir)
342 {
343         struct stat st;
344
345         if (!stat(git_link, &st)) {
346                 const char *src;
347
348                 if (S_ISREG(st.st_mode))
349                         src = read_gitfile(git_link);
350                 else if (S_ISDIR(st.st_mode))
351                         src = git_link;
352                 else
353                         die(_("unable to handle file type %d"), (int)st.st_mode);
354
355                 if (rename(src, git_dir))
356                         die_errno(_("unable to move %s to %s"), src, git_dir);
357         }
358
359         write_file(git_link, "gitdir: %s", git_dir);
360 }
361
362 int init_db(const char *template_dir, unsigned int flags)
363 {
364         int reinit;
365         const char *git_dir = get_git_dir();
366
367         if (git_link)
368                 separate_git_dir(git_dir);
369
370         safe_create_dir(git_dir, 0);
371
372         init_is_bare_repository = is_bare_repository();
373
374         /* Check to see if the repository version is right.
375          * Note that a newly created repository does not have
376          * config file, so this will not fail.  What we are catching
377          * is an attempt to reinitialize new repository with an old tool.
378          */
379         check_repository_format();
380
381         reinit = create_default_files(template_dir);
382
383         create_object_directory();
384
385         if (get_shared_repository()) {
386                 char buf[10];
387                 /* We do not spell "group" and such, so that
388                  * the configuration can be read by older version
389                  * of git. Note, we use octal numbers for new share modes,
390                  * and compatibility values for PERM_GROUP and
391                  * PERM_EVERYBODY.
392                  */
393                 if (get_shared_repository() < 0)
394                         /* force to the mode value */
395                         xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
396                 else if (get_shared_repository() == PERM_GROUP)
397                         xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
398                 else if (get_shared_repository() == PERM_EVERYBODY)
399                         xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
400                 else
401                         die("BUG: invalid value for shared_repository");
402                 git_config_set("core.sharedrepository", buf);
403                 git_config_set("receive.denyNonFastforwards", "true");
404         }
405
406         if (!(flags & INIT_DB_QUIET)) {
407                 int len = strlen(git_dir);
408
409                 /* TRANSLATORS: The first '%s' is either "Reinitialized
410                    existing" or "Initialized empty", the second " shared" or
411                    "", and the last '%s%s' is the verbatim directory name. */
412                 printf(_("%s%s Git repository in %s%s\n"),
413                        reinit ? _("Reinitialized existing") : _("Initialized empty"),
414                        get_shared_repository() ? _(" shared") : "",
415                        git_dir, len && git_dir[len-1] != '/' ? "/" : "");
416         }
417
418         return 0;
419 }
420
421 static int guess_repository_type(const char *git_dir)
422 {
423         const char *slash;
424         char *cwd;
425         int cwd_is_git_dir;
426
427         /*
428          * "GIT_DIR=. git init" is always bare.
429          * "GIT_DIR=`pwd` git init" too.
430          */
431         if (!strcmp(".", git_dir))
432                 return 1;
433         cwd = xgetcwd();
434         cwd_is_git_dir = !strcmp(git_dir, cwd);
435         free(cwd);
436         if (cwd_is_git_dir)
437                 return 1;
438         /*
439          * "GIT_DIR=.git or GIT_DIR=something/.git is usually not.
440          */
441         if (!strcmp(git_dir, ".git"))
442                 return 0;
443         slash = strrchr(git_dir, '/');
444         if (slash && !strcmp(slash, "/.git"))
445                 return 0;
446
447         /*
448          * Otherwise it is often bare.  At this point
449          * we are just guessing.
450          */
451         return 1;
452 }
453
454 static int shared_callback(const struct option *opt, const char *arg, int unset)
455 {
456         *((int *) opt->value) = (arg) ? git_config_perm("arg", arg) : PERM_GROUP;
457         return 0;
458 }
459
460 static const char *const init_db_usage[] = {
461         N_("git init [-q | --quiet] [--bare] [--template=<template-directory>] [--shared[=<permissions>]] [<directory>]"),
462         NULL
463 };
464
465 /*
466  * If you want to, you can share the DB area with any number of branches.
467  * That has advantages: you can save space by sharing all the SHA1 objects.
468  * On the other hand, it might just make lookup slower and messier. You
469  * be the judge.  The default case is to have one DB per managed directory.
470  */
471 int cmd_init_db(int argc, const char **argv, const char *prefix)
472 {
473         const char *git_dir;
474         const char *real_git_dir = NULL;
475         const char *work_tree;
476         const char *template_dir = NULL;
477         unsigned int flags = 0;
478         const struct option init_db_options[] = {
479                 OPT_STRING(0, "template", &template_dir, N_("template-directory"),
480                                 N_("directory from which templates will be used")),
481                 OPT_SET_INT(0, "bare", &is_bare_repository_cfg,
482                                 N_("create a bare repository"), 1),
483                 { OPTION_CALLBACK, 0, "shared", &init_shared_repository,
484                         N_("permissions"),
485                         N_("specify that the git repository is to be shared amongst several users"),
486                         PARSE_OPT_OPTARG | PARSE_OPT_NONEG, shared_callback, 0},
487                 OPT_BIT('q', "quiet", &flags, N_("be quiet"), INIT_DB_QUIET),
488                 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
489                            N_("separate git dir from working tree")),
490                 OPT_END()
491         };
492
493         argc = parse_options(argc, argv, prefix, init_db_options, init_db_usage, 0);
494
495         if (real_git_dir && !is_absolute_path(real_git_dir))
496                 real_git_dir = xstrdup(real_path(real_git_dir));
497
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
539         if (init_shared_repository != -1)
540                 set_shared_repository(init_shared_repository);
541
542         /*
543          * GIT_WORK_TREE makes sense only in conjunction with GIT_DIR
544          * without --bare.  Catch the error early.
545          */
546         git_dir = getenv(GIT_DIR_ENVIRONMENT);
547         work_tree = getenv(GIT_WORK_TREE_ENVIRONMENT);
548         if ((!git_dir || is_bare_repository_cfg == 1) && work_tree)
549                 die(_("%s (or --work-tree=<directory>) not allowed without "
550                           "specifying %s (or --git-dir=<directory>)"),
551                     GIT_WORK_TREE_ENVIRONMENT,
552                     GIT_DIR_ENVIRONMENT);
553
554         /*
555          * Set up the default .git directory contents
556          */
557         if (!git_dir)
558                 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
559
560         if (is_bare_repository_cfg < 0)
561                 is_bare_repository_cfg = guess_repository_type(git_dir);
562
563         if (!is_bare_repository_cfg) {
564                 const char *git_dir_parent = strrchr(git_dir, '/');
565                 if (git_dir_parent) {
566                         char *rel = xstrndup(git_dir, git_dir_parent - git_dir);
567                         git_work_tree_cfg = xstrdup(real_path(rel));
568                         free(rel);
569                 }
570                 if (!git_work_tree_cfg)
571                         git_work_tree_cfg = xgetcwd();
572                 if (work_tree)
573                         set_git_work_tree(work_tree);
574                 else
575                         set_git_work_tree(git_work_tree_cfg);
576                 if (access(get_git_work_tree(), X_OK))
577                         die_errno (_("Cannot access work tree '%s'"),
578                                    get_git_work_tree());
579         }
580         else {
581                 if (work_tree)
582                         set_git_work_tree(work_tree);
583         }
584
585         set_git_dir_init(git_dir, real_git_dir, 1);
586
587         return init_db(template_dir, flags);
588 }