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