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
22static int init_is_bare_repository = 0;
23static int init_shared_repository = -1;
24static const char *init_db_template_dir;
25
26static void copy_templates_1(struct strbuf *path, struct strbuf *template,
27 DIR *dir)
28{
29 size_t path_baselen = path->len;
30 size_t template_baselen = template->len;
31 struct dirent *de;
32
33 /* Note: if ".git/hooks" file exists in the repository being
34 * re-initialized, /etc/core-git/templates/hooks/update would
35 * cause "git init" to fail here. I think this is sane but
36 * it means that the set of templates we ship by default, along
37 * with the way the namespace under .git/ is organized, should
38 * be really carefully chosen.
39 */
40 safe_create_dir(path->buf, 1);
41 while ((de = readdir(dir)) != NULL) {
42 struct stat st_git, st_template;
43 int exists = 0;
44
45 strbuf_setlen(path, path_baselen);
46 strbuf_setlen(template, template_baselen);
47
48 if (de->d_name[0] == '.')
49 continue;
50 strbuf_addstr(path, de->d_name);
51 strbuf_addstr(template, de->d_name);
52 if (lstat(path->buf, &st_git)) {
53 if (errno != ENOENT)
54 die_errno(_("cannot stat '%s'"), path->buf);
55 }
56 else
57 exists = 1;
58
59 if (lstat(template->buf, &st_template))
60 die_errno(_("cannot stat template '%s'"), template->buf);
61
62 if (S_ISDIR(st_template.st_mode)) {
63 DIR *subdir = opendir(template->buf);
64 if (!subdir)
65 die_errno(_("cannot opendir '%s'"), template->buf);
66 strbuf_addch(path, '/');
67 strbuf_addch(template, '/');
68 copy_templates_1(path, template, subdir);
69 closedir(subdir);
70 }
71 else if (exists)
72 continue;
73 else if (S_ISLNK(st_template.st_mode)) {
74 struct strbuf lnk = STRBUF_INIT;
75 if (strbuf_readlink(&lnk, template->buf, 0) < 0)
76 die_errno(_("cannot readlink '%s'"), template->buf);
77 if (symlink(lnk.buf, path->buf))
78 die_errno(_("cannot symlink '%s' '%s'"),
79 lnk.buf, path->buf);
80 strbuf_release(&lnk);
81 }
82 else if (S_ISREG(st_template.st_mode)) {
83 if (copy_file(path->buf, template->buf, st_template.st_mode))
84 die_errno(_("cannot copy '%s' to '%s'"),
85 template->buf, path->buf);
86 }
87 else
88 error(_("ignoring template %s"), template->buf);
89 }
90}
91
92static void copy_templates(const char *template_dir)
93{
94 struct strbuf path = STRBUF_INIT;
95 struct strbuf template_path = STRBUF_INIT;
96 size_t template_len;
97 struct repository_format template_format;
98 struct strbuf err = STRBUF_INIT;
99 DIR *dir;
100 char *to_free = NULL;
101
102 if (!template_dir)
103 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
104 if (!template_dir)
105 template_dir = init_db_template_dir;
106 if (!template_dir)
107 template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
108 if (!template_dir[0]) {
109 free(to_free);
110 return;
111 }
112
113 strbuf_addstr(&template_path, template_dir);
114 strbuf_complete(&template_path, '/');
115 template_len = template_path.len;
116
117 dir = opendir(template_path.buf);
118 if (!dir) {
119 warning(_("templates not found %s"), template_dir);
120 goto free_return;
121 }
122
123 /* Make sure that template is from the correct vintage */
124 strbuf_addstr(&template_path, "config");
125 read_repository_format(&template_format, template_path.buf);
126 strbuf_setlen(&template_path, template_len);
127
128 /*
129 * No mention of version at all is OK, but anything else should be
130 * verified.
131 */
132 if (template_format.version >= 0 &&
133 verify_repository_format(&template_format, &err) < 0) {
134 warning(_("not copying templates from '%s': %s"),
135 template_dir, err.buf);
136 strbuf_release(&err);
137 goto close_free_return;
138 }
139
140 strbuf_addstr(&path, get_git_common_dir());
141 strbuf_complete(&path, '/');
142 copy_templates_1(&path, &template_path, dir);
143close_free_return:
144 closedir(dir);
145free_return:
146 free(to_free);
147 strbuf_release(&path);
148 strbuf_release(&template_path);
149}
150
151static int git_init_db_config(const char *k, const char *v, void *cb)
152{
153 if (!strcmp(k, "init.templatedir"))
154 return git_config_pathname(&init_db_template_dir, k, v);
155
156 return 0;
157}
158
159/*
160 * If the git_dir is not directly inside the working tree, then git will not
161 * find it by default, and we need to set the worktree explicitly.
162 */
163static int needs_work_tree_config(const char *git_dir, const char *work_tree)
164{
165 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
166 return 0;
167 if (skip_prefix(git_dir, work_tree, &git_dir) &&
168 !strcmp(git_dir, "/.git"))
169 return 0;
170 return 1;
171}
172
173static int create_default_files(const char *template_path,
174 const char *original_git_dir)
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(original_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
293static 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
314static void separate_git_dir(const char *git_dir, const char *git_link)
315{
316 struct stat st;
317
318 if (!stat(git_link, &st)) {
319 const char *src;
320
321 if (S_ISREG(st.st_mode))
322 src = read_gitfile(git_link);
323 else if (S_ISDIR(st.st_mode))
324 src = git_link;
325 else
326 die(_("unable to handle file type %d"), (int)st.st_mode);
327
328 if (rename(src, git_dir))
329 die_errno(_("unable to move %s to %s"), src, git_dir);
330 }
331
332 write_file(git_link, "gitdir: %s", git_dir);
333}
334
335int init_db(const char *git_dir, const char *real_git_dir,
336 const char *template_dir, unsigned int flags)
337{
338 int reinit;
339 int exist_ok = flags & INIT_DB_EXIST_OK;
340 char *original_git_dir = xstrdup(real_path(git_dir));
341
342 if (real_git_dir) {
343 struct stat st;
344
345 if (!exist_ok && !stat(git_dir, &st))
346 die(_("%s already exists"), git_dir);
347
348 if (!exist_ok && !stat(real_git_dir, &st))
349 die(_("%s already exists"), real_git_dir);
350
351 set_git_dir(real_path(real_git_dir));
352 git_dir = get_git_dir();
353 separate_git_dir(git_dir, original_git_dir);
354 }
355 else {
356 set_git_dir(real_path(git_dir));
357 git_dir = get_git_dir();
358 }
359 startup_info->have_repository = 1;
360
361 safe_create_dir(git_dir, 0);
362
363 init_is_bare_repository = is_bare_repository();
364
365 /* Check to see if the repository version is right.
366 * Note that a newly created repository does not have
367 * config file, so this will not fail. What we are catching
368 * is an attempt to reinitialize new repository with an old tool.
369 */
370 check_repository_format();
371
372 reinit = create_default_files(template_dir, original_git_dir);
373
374 create_object_directory();
375
376 if (get_shared_repository()) {
377 char buf[10];
378 /* We do not spell "group" and such, so that
379 * the configuration can be read by older version
380 * of git. Note, we use octal numbers for new share modes,
381 * and compatibility values for PERM_GROUP and
382 * PERM_EVERYBODY.
383 */
384 if (get_shared_repository() < 0)
385 /* force to the mode value */
386 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
387 else if (get_shared_repository() == PERM_GROUP)
388 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
389 else if (get_shared_repository() == PERM_EVERYBODY)
390 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
391 else
392 die("BUG: invalid value for shared_repository");
393 git_config_set("core.sharedrepository", buf);
394 git_config_set("receive.denyNonFastforwards", "true");
395 }
396
397 if (!(flags & INIT_DB_QUIET)) {
398 int len = strlen(git_dir);
399
400 /* TRANSLATORS: The first '%s' is either "Reinitialized
401 existing" or "Initialized empty", the second " shared" or
402 "", and the last '%s%s' is the verbatim directory name. */
403 printf(_("%s%s Git repository in %s%s\n"),
404 reinit ? _("Reinitialized existing") : _("Initialized empty"),
405 get_shared_repository() ? _(" shared") : "",
406 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
407 }
408
409 free(original_git_dir);
410 return 0;
411}
412
413static int guess_repository_type(const char *git_dir)
414{
415 const char *slash;
416 char *cwd;
417 int cwd_is_git_dir;
418
419 /*
420 * "GIT_DIR=. git init" is always bare.
421 * "GIT_DIR=`pwd` git init" too.
422 */
423 if (!strcmp(".", git_dir))
424 return 1;
425 cwd = xgetcwd();
426 cwd_is_git_dir = !strcmp(git_dir, cwd);
427 free(cwd);
428 if (cwd_is_git_dir)
429 return 1;
430 /*
431 * "GIT_DIR=.git or GIT_DIR=something/.git is usually not.
432 */
433 if (!strcmp(git_dir, ".git"))
434 return 0;
435 slash = strrchr(git_dir, '/');
436 if (slash && !strcmp(slash, "/.git"))
437 return 0;
438
439 /*
440 * Otherwise it is often bare. At this point
441 * we are just guessing.
442 */
443 return 1;
444}
445
446static int shared_callback(const struct option *opt, const char *arg, int unset)
447{
448 *((int *) opt->value) = (arg) ? git_config_perm("arg", arg) : PERM_GROUP;
449 return 0;
450}
451
452static const char *const init_db_usage[] = {
453 N_("git init [-q | --quiet] [--bare] [--template=<template-directory>] [--shared[=<permissions>]] [<directory>]"),
454 NULL
455};
456
457/*
458 * If you want to, you can share the DB area with any number of branches.
459 * That has advantages: you can save space by sharing all the SHA1 objects.
460 * On the other hand, it might just make lookup slower and messier. You
461 * be the judge. The default case is to have one DB per managed directory.
462 */
463int cmd_init_db(int argc, const char **argv, const char *prefix)
464{
465 const char *git_dir;
466 const char *real_git_dir = NULL;
467 const char *work_tree;
468 const char *template_dir = NULL;
469 unsigned int flags = 0;
470 const struct option init_db_options[] = {
471 OPT_STRING(0, "template", &template_dir, N_("template-directory"),
472 N_("directory from which templates will be used")),
473 OPT_SET_INT(0, "bare", &is_bare_repository_cfg,
474 N_("create a bare repository"), 1),
475 { OPTION_CALLBACK, 0, "shared", &init_shared_repository,
476 N_("permissions"),
477 N_("specify that the git repository is to be shared amongst several users"),
478 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, shared_callback, 0},
479 OPT_BIT('q', "quiet", &flags, N_("be quiet"), INIT_DB_QUIET),
480 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
481 N_("separate git dir from working tree")),
482 OPT_END()
483 };
484
485 argc = parse_options(argc, argv, prefix, init_db_options, init_db_usage, 0);
486
487 if (real_git_dir && !is_absolute_path(real_git_dir))
488 real_git_dir = xstrdup(real_path(real_git_dir));
489
490 if (argc == 1) {
491 int mkdir_tried = 0;
492 retry:
493 if (chdir(argv[0]) < 0) {
494 if (!mkdir_tried) {
495 int saved;
496 /*
497 * At this point we haven't read any configuration,
498 * and we know shared_repository should always be 0;
499 * but just in case we play safe.
500 */
501 saved = get_shared_repository();
502 set_shared_repository(0);
503 switch (safe_create_leading_directories_const(argv[0])) {
504 case SCLD_OK:
505 case SCLD_PERMS:
506 break;
507 case SCLD_EXISTS:
508 errno = EEXIST;
509 /* fallthru */
510 default:
511 die_errno(_("cannot mkdir %s"), argv[0]);
512 break;
513 }
514 set_shared_repository(saved);
515 if (mkdir(argv[0], 0777) < 0)
516 die_errno(_("cannot mkdir %s"), argv[0]);
517 mkdir_tried = 1;
518 goto retry;
519 }
520 die_errno(_("cannot chdir to %s"), argv[0]);
521 }
522 } else if (0 < argc) {
523 usage(init_db_usage[0]);
524 }
525 if (is_bare_repository_cfg == 1) {
526 char *cwd = xgetcwd();
527 setenv(GIT_DIR_ENVIRONMENT, cwd, argc > 0);
528 free(cwd);
529 }
530
531 if (init_shared_repository != -1)
532 set_shared_repository(init_shared_repository);
533
534 /*
535 * GIT_WORK_TREE makes sense only in conjunction with GIT_DIR
536 * without --bare. Catch the error early.
537 */
538 git_dir = getenv(GIT_DIR_ENVIRONMENT);
539 work_tree = getenv(GIT_WORK_TREE_ENVIRONMENT);
540 if ((!git_dir || is_bare_repository_cfg == 1) && work_tree)
541 die(_("%s (or --work-tree=<directory>) not allowed without "
542 "specifying %s (or --git-dir=<directory>)"),
543 GIT_WORK_TREE_ENVIRONMENT,
544 GIT_DIR_ENVIRONMENT);
545
546 /*
547 * Set up the default .git directory contents
548 */
549 if (!git_dir)
550 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
551
552 if (is_bare_repository_cfg < 0)
553 is_bare_repository_cfg = guess_repository_type(git_dir);
554
555 if (!is_bare_repository_cfg) {
556 const char *git_dir_parent = strrchr(git_dir, '/');
557 if (git_dir_parent) {
558 char *rel = xstrndup(git_dir, git_dir_parent - git_dir);
559 git_work_tree_cfg = xstrdup(real_path(rel));
560 free(rel);
561 }
562 if (!git_work_tree_cfg)
563 git_work_tree_cfg = xgetcwd();
564 if (work_tree)
565 set_git_work_tree(work_tree);
566 else
567 set_git_work_tree(git_work_tree_cfg);
568 if (access(get_git_work_tree(), X_OK))
569 die_errno (_("Cannot access work tree '%s'"),
570 get_git_work_tree());
571 }
572 else {
573 if (work_tree)
574 set_git_work_tree(work_tree);
575 }
576
577 flags |= INIT_DB_EXIST_OK;
578 return init_db(git_dir, real_git_dir, template_dir, flags);
579}