Merge branch 'jt/test-protocol-version' into jt/fetch-no-update-shallow-in-proto-v2
[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
13 #ifndef DEFAULT_GIT_TEMPLATE_DIR
14 #define DEFAULT_GIT_TEMPLATE_DIR "/usr/share/git-core/templates"
15 #endif
16
17 #ifdef NO_TRUSTABLE_FILEMODE
18 #define TEST_FILEMODE 0
19 #else
20 #define TEST_FILEMODE 1
21 #endif
22
23 static int init_is_bare_repository = 0;
24 static int init_shared_repository = -1;
25 static const char *init_db_template_dir;
26
27 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
28                              DIR *dir)
29 {
30         size_t path_baselen = path->len;
31         size_t template_baselen = template_path->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_path, template_baselen);
48
49                 if (de->d_name[0] == '.')
50                         continue;
51                 strbuf_addstr(path, de->d_name);
52                 strbuf_addstr(template_path, 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_path->buf, &st_template))
61                         die_errno(_("cannot stat template '%s'"), template_path->buf);
62
63                 if (S_ISDIR(st_template.st_mode)) {
64                         DIR *subdir = opendir(template_path->buf);
65                         if (!subdir)
66                                 die_errno(_("cannot opendir '%s'"), template_path->buf);
67                         strbuf_addch(path, '/');
68                         strbuf_addch(template_path, '/');
69                         copy_templates_1(path, template_path, 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_path->buf,
77                                             st_template.st_size) < 0)
78                                 die_errno(_("cannot readlink '%s'"), template_path->buf);
79                         if (symlink(lnk.buf, path->buf))
80                                 die_errno(_("cannot symlink '%s' '%s'"),
81                                           lnk.buf, path->buf);
82                         strbuf_release(&lnk);
83                 }
84                 else if (S_ISREG(st_template.st_mode)) {
85                         if (copy_file(path->buf, template_path->buf, st_template.st_mode))
86                                 die_errno(_("cannot copy '%s' to '%s'"),
87                                           template_path->buf, path->buf);
88                 }
89                 else
90                         error(_("ignoring template %s"), template_path->buf);
91         }
92 }
93
94 static void copy_templates(const char *template_dir)
95 {
96         struct strbuf path = STRBUF_INIT;
97         struct strbuf template_path = STRBUF_INIT;
98         size_t template_len;
99         struct repository_format template_format = REPOSITORY_FORMAT_INIT;
100         struct strbuf err = STRBUF_INIT;
101         DIR *dir;
102         char *to_free = NULL;
103
104         if (!template_dir)
105                 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
106         if (!template_dir)
107                 template_dir = init_db_template_dir;
108         if (!template_dir)
109                 template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
110         if (!template_dir[0]) {
111                 free(to_free);
112                 return;
113         }
114
115         strbuf_addstr(&template_path, template_dir);
116         strbuf_complete(&template_path, '/');
117         template_len = template_path.len;
118
119         dir = opendir(template_path.buf);
120         if (!dir) {
121                 warning(_("templates not found in %s"), template_dir);
122                 goto free_return;
123         }
124
125         /* Make sure that template is from the correct vintage */
126         strbuf_addstr(&template_path, "config");
127         read_repository_format(&template_format, template_path.buf);
128         strbuf_setlen(&template_path, template_len);
129
130         /*
131          * No mention of version at all is OK, but anything else should be
132          * verified.
133          */
134         if (template_format.version >= 0 &&
135             verify_repository_format(&template_format, &err) < 0) {
136                 warning(_("not copying templates from '%s': %s"),
137                           template_dir, err.buf);
138                 strbuf_release(&err);
139                 goto close_free_return;
140         }
141
142         strbuf_addstr(&path, get_git_common_dir());
143         strbuf_complete(&path, '/');
144         copy_templates_1(&path, &template_path, dir);
145 close_free_return:
146         closedir(dir);
147 free_return:
148         free(to_free);
149         strbuf_release(&path);
150         strbuf_release(&template_path);
151         clear_repository_format(&template_format);
152 }
153
154 static int git_init_db_config(const char *k, const char *v, void *cb)
155 {
156         if (!strcmp(k, "init.templatedir"))
157                 return git_config_pathname(&init_db_template_dir, k, v);
158
159         return 0;
160 }
161
162 /*
163  * If the git_dir is not directly inside the working tree, then git will not
164  * find it by default, and we need to set the worktree explicitly.
165  */
166 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
167 {
168         if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
169                 return 0;
170         if (skip_prefix(git_dir, work_tree, &git_dir) &&
171             !strcmp(git_dir, "/.git"))
172                 return 0;
173         return 1;
174 }
175
176 static int create_default_files(const char *template_path,
177                                 const char *original_git_dir)
178 {
179         struct stat st1;
180         struct strbuf buf = STRBUF_INIT;
181         char *path;
182         char repo_version_string[10];
183         char junk[2];
184         int reinit;
185         int filemode;
186         struct strbuf err = STRBUF_INIT;
187
188         /* Just look for `init.templatedir` */
189         git_config(git_init_db_config, NULL);
190
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         /*
206          * We must make sure command-line options continue to override any
207          * values we might have just re-read from the config.
208          */
209         is_bare_repository_cfg = init_is_bare_repository;
210         if (init_shared_repository != -1)
211                 set_shared_repository(init_shared_repository);
212
213         /*
214          * We would have created the above under user's umask -- under
215          * shared-repository settings, we would need to fix them up.
216          */
217         if (get_shared_repository()) {
218                 adjust_shared_perm(get_git_dir());
219         }
220
221         /*
222          * We need to create a "refs" dir in any case so that older
223          * versions of git can tell that this is a repository.
224          */
225         safe_create_dir(git_path("refs"), 1);
226         adjust_shared_perm(git_path("refs"));
227
228         if (refs_init_db(&err))
229                 die("failed to set up refs db: %s", err.buf);
230
231         /*
232          * Create the default symlink from ".git/HEAD" to the "master"
233          * branch, if it does not exist yet.
234          */
235         path = git_path_buf(&buf, "HEAD");
236         reinit = (!access(path, R_OK)
237                   || readlink(path, junk, sizeof(junk)-1) != -1);
238         if (!reinit) {
239                 if (create_symref("HEAD", "refs/heads/master", NULL) < 0)
240                         exit(1);
241         }
242
243         /* This forces creation of new config file */
244         xsnprintf(repo_version_string, sizeof(repo_version_string),
245                   "%d", GIT_REPO_VERSION);
246         git_config_set("core.repositoryformatversion", repo_version_string);
247
248         /* Check filemode trustability */
249         path = git_path_buf(&buf, "config");
250         filemode = TEST_FILEMODE;
251         if (TEST_FILEMODE && !lstat(path, &st1)) {
252                 struct stat st2;
253                 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
254                                 !lstat(path, &st2) &&
255                                 st1.st_mode != st2.st_mode &&
256                                 !chmod(path, st1.st_mode));
257                 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
258                         filemode = 0;
259         }
260         git_config_set("core.filemode", filemode ? "true" : "false");
261
262         if (is_bare_repository())
263                 git_config_set("core.bare", "true");
264         else {
265                 const char *work_tree = get_git_work_tree();
266                 git_config_set("core.bare", "false");
267                 /* allow template config file to override the default */
268                 if (log_all_ref_updates == LOG_REFS_UNSET)
269                         git_config_set("core.logallrefupdates", "true");
270                 if (needs_work_tree_config(original_git_dir, work_tree))
271                         git_config_set("core.worktree", work_tree);
272         }
273
274         if (!reinit) {
275                 /* Check if symlink is supported in the work tree */
276                 path = git_path_buf(&buf, "tXXXXXX");
277                 if (!close(xmkstemp(path)) &&
278                     !unlink(path) &&
279                     !symlink("testing", path) &&
280                     !lstat(path, &st1) &&
281                     S_ISLNK(st1.st_mode))
282                         unlink(path); /* good */
283                 else
284                         git_config_set("core.symlinks", "false");
285
286                 /* Check if the filesystem is case-insensitive */
287                 path = git_path_buf(&buf, "CoNfIg");
288                 if (!access(path, F_OK))
289                         git_config_set("core.ignorecase", "true");
290                 probe_utf8_pathname_composition();
291         }
292
293         strbuf_release(&buf);
294         return reinit;
295 }
296
297 static void create_object_directory(void)
298 {
299         struct strbuf path = STRBUF_INIT;
300         size_t baselen;
301
302         strbuf_addstr(&path, get_object_directory());
303         baselen = path.len;
304
305         safe_create_dir(path.buf, 1);
306
307         strbuf_setlen(&path, baselen);
308         strbuf_addstr(&path, "/pack");
309         safe_create_dir(path.buf, 1);
310
311         strbuf_setlen(&path, baselen);
312         strbuf_addstr(&path, "/info");
313         safe_create_dir(path.buf, 1);
314
315         strbuf_release(&path);
316 }
317
318 static void separate_git_dir(const char *git_dir, const char *git_link)
319 {
320         struct stat st;
321
322         if (!stat(git_link, &st)) {
323                 const char *src;
324
325                 if (S_ISREG(st.st_mode))
326                         src = read_gitfile(git_link);
327                 else if (S_ISDIR(st.st_mode))
328                         src = git_link;
329                 else
330                         die(_("unable to handle file type %d"), (int)st.st_mode);
331
332                 if (rename(src, git_dir))
333                         die_errno(_("unable to move %s to %s"), src, git_dir);
334         }
335
336         write_file(git_link, "gitdir: %s", git_dir);
337 }
338
339 int init_db(const char *git_dir, const char *real_git_dir,
340             const char *template_dir, unsigned int flags)
341 {
342         int reinit;
343         int exist_ok = flags & INIT_DB_EXIST_OK;
344         char *original_git_dir = real_pathdup(git_dir, 1);
345
346         if (real_git_dir) {
347                 struct stat st;
348
349                 if (!exist_ok && !stat(git_dir, &st))
350                         die(_("%s already exists"), git_dir);
351
352                 if (!exist_ok && !stat(real_git_dir, &st))
353                         die(_("%s already exists"), real_git_dir);
354
355                 set_git_dir(real_path(real_git_dir));
356                 git_dir = get_git_dir();
357                 separate_git_dir(git_dir, original_git_dir);
358         }
359         else {
360                 set_git_dir(real_path(git_dir));
361                 git_dir = get_git_dir();
362         }
363         startup_info->have_repository = 1;
364
365         safe_create_dir(git_dir, 0);
366
367         init_is_bare_repository = is_bare_repository();
368
369         /* Check to see if the repository version is right.
370          * Note that a newly created repository does not have
371          * config file, so this will not fail.  What we are catching
372          * is an attempt to reinitialize new repository with an old tool.
373          */
374         check_repository_format();
375
376         reinit = create_default_files(template_dir, original_git_dir);
377
378         create_object_directory();
379
380         if (get_shared_repository()) {
381                 char buf[10];
382                 /* We do not spell "group" and such, so that
383                  * the configuration can be read by older version
384                  * of git. Note, we use octal numbers for new share modes,
385                  * and compatibility values for PERM_GROUP and
386                  * PERM_EVERYBODY.
387                  */
388                 if (get_shared_repository() < 0)
389                         /* force to the mode value */
390                         xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
391                 else if (get_shared_repository() == PERM_GROUP)
392                         xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
393                 else if (get_shared_repository() == PERM_EVERYBODY)
394                         xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
395                 else
396                         BUG("invalid value for shared_repository");
397                 git_config_set("core.sharedrepository", buf);
398                 git_config_set("receive.denyNonFastforwards", "true");
399         }
400
401         if (!(flags & INIT_DB_QUIET)) {
402                 int len = strlen(git_dir);
403
404                 if (reinit)
405                         printf(get_shared_repository()
406                                ? _("Reinitialized existing shared Git repository in %s%s\n")
407                                : _("Reinitialized existing Git repository in %s%s\n"),
408                                git_dir, len && git_dir[len-1] != '/' ? "/" : "");
409                 else
410                         printf(get_shared_repository()
411                                ? _("Initialized empty shared Git repository in %s%s\n")
412                                : _("Initialized empty Git repository in %s%s\n"),
413                                git_dir, len && git_dir[len-1] != '/' ? "/" : "");
414         }
415
416         free(original_git_dir);
417         return 0;
418 }
419
420 static int guess_repository_type(const char *git_dir)
421 {
422         const char *slash;
423         char *cwd;
424         int cwd_is_git_dir;
425
426         /*
427          * "GIT_DIR=. git init" is always bare.
428          * "GIT_DIR=`pwd` git init" too.
429          */
430         if (!strcmp(".", git_dir))
431                 return 1;
432         cwd = xgetcwd();
433         cwd_is_git_dir = !strcmp(git_dir, cwd);
434         free(cwd);
435         if (cwd_is_git_dir)
436                 return 1;
437         /*
438          * "GIT_DIR=.git or GIT_DIR=something/.git is usually not.
439          */
440         if (!strcmp(git_dir, ".git"))
441                 return 0;
442         slash = strrchr(git_dir, '/');
443         if (slash && !strcmp(slash, "/.git"))
444                 return 0;
445
446         /*
447          * Otherwise it is often bare.  At this point
448          * we are just guessing.
449          */
450         return 1;
451 }
452
453 static int shared_callback(const struct option *opt, const char *arg, int unset)
454 {
455         BUG_ON_OPT_NEG(unset);
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 = real_pathdup(real_git_dir, 1);
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 = xstrdup_or_null(getenv(GIT_DIR_ENVIRONMENT));
547         work_tree = xstrdup_or_null(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 = real_pathdup(rel, 1);
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         UNLEAK(real_git_dir);
586         UNLEAK(git_dir);
587         UNLEAK(work_tree);
588
589         flags |= INIT_DB_EXIST_OK;
590         return init_db(git_dir, real_git_dir, template_dir, flags);
591 }