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