]> git.ipfire.org Git - thirdparty/git.git/blob - setup.c
setup: adopt shared init-db & clone code
[thirdparty/git.git] / setup.c
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "copy.h"
4 #include "environment.h"
5 #include "exec-cmd.h"
6 #include "gettext.h"
7 #include "object-name.h"
8 #include "refs.h"
9 #include "repository.h"
10 #include "config.h"
11 #include "dir.h"
12 #include "setup.h"
13 #include "string-list.h"
14 #include "chdir-notify.h"
15 #include "promisor-remote.h"
16 #include "quote.h"
17 #include "trace2.h"
18 #include "worktree.h"
19 #include "wrapper.h"
20
21 static int inside_git_dir = -1;
22 static int inside_work_tree = -1;
23 static int work_tree_config_is_bogus;
24 enum allowed_bare_repo {
25 ALLOWED_BARE_REPO_EXPLICIT = 0,
26 ALLOWED_BARE_REPO_ALL,
27 };
28
29 static struct startup_info the_startup_info;
30 struct startup_info *startup_info = &the_startup_info;
31 const char *tmp_original_cwd;
32
33 /*
34 * The input parameter must contain an absolute path, and it must already be
35 * normalized.
36 *
37 * Find the part of an absolute path that lies inside the work tree by
38 * dereferencing symlinks outside the work tree, for example:
39 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
40 * /dir/file (work tree is /) -> dir/file
41 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
42 * /dir/repolink/file (repolink points to /dir/repo) -> file
43 * /dir/repo (exactly equal to work tree) -> (empty string)
44 */
45 static int abspath_part_inside_repo(char *path)
46 {
47 size_t len;
48 size_t wtlen;
49 char *path0;
50 int off;
51 const char *work_tree = get_git_work_tree();
52 struct strbuf realpath = STRBUF_INIT;
53
54 if (!work_tree)
55 return -1;
56 wtlen = strlen(work_tree);
57 len = strlen(path);
58 off = offset_1st_component(path);
59
60 /* check if work tree is already the prefix */
61 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
62 if (path[wtlen] == '/') {
63 memmove(path, path + wtlen + 1, len - wtlen);
64 return 0;
65 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
66 /* work tree is the root, or the whole path */
67 memmove(path, path + wtlen, len - wtlen + 1);
68 return 0;
69 }
70 /* work tree might match beginning of a symlink to work tree */
71 off = wtlen;
72 }
73 path0 = path;
74 path += off;
75
76 /* check each '/'-terminated level */
77 while (*path) {
78 path++;
79 if (*path == '/') {
80 *path = '\0';
81 strbuf_realpath(&realpath, path0, 1);
82 if (fspathcmp(realpath.buf, work_tree) == 0) {
83 memmove(path0, path + 1, len - (path - path0));
84 strbuf_release(&realpath);
85 return 0;
86 }
87 *path = '/';
88 }
89 }
90
91 /* check whole path */
92 strbuf_realpath(&realpath, path0, 1);
93 if (fspathcmp(realpath.buf, work_tree) == 0) {
94 *path0 = '\0';
95 strbuf_release(&realpath);
96 return 0;
97 }
98
99 strbuf_release(&realpath);
100 return -1;
101 }
102
103 /*
104 * Normalize "path", prepending the "prefix" for relative paths. If
105 * remaining_prefix is not NULL, return the actual prefix still
106 * remains in the path. For example, prefix = sub1/sub2/ and path is
107 *
108 * foo -> sub1/sub2/foo (full prefix)
109 * ../foo -> sub1/foo (remaining prefix is sub1/)
110 * ../../bar -> bar (no remaining prefix)
111 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
112 * `pwd`/../bar -> sub1/bar (no remaining prefix)
113 */
114 char *prefix_path_gently(const char *prefix, int len,
115 int *remaining_prefix, const char *path)
116 {
117 const char *orig = path;
118 char *sanitized;
119 if (is_absolute_path(orig)) {
120 sanitized = xmallocz(strlen(path));
121 if (remaining_prefix)
122 *remaining_prefix = 0;
123 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
124 free(sanitized);
125 return NULL;
126 }
127 if (abspath_part_inside_repo(sanitized)) {
128 free(sanitized);
129 return NULL;
130 }
131 } else {
132 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
133 if (remaining_prefix)
134 *remaining_prefix = len;
135 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
136 free(sanitized);
137 return NULL;
138 }
139 }
140 return sanitized;
141 }
142
143 char *prefix_path(const char *prefix, int len, const char *path)
144 {
145 char *r = prefix_path_gently(prefix, len, NULL, path);
146 if (!r) {
147 const char *hint_path = get_git_work_tree();
148 if (!hint_path)
149 hint_path = get_git_dir();
150 die(_("'%s' is outside repository at '%s'"), path,
151 absolute_path(hint_path));
152 }
153 return r;
154 }
155
156 int path_inside_repo(const char *prefix, const char *path)
157 {
158 int len = prefix ? strlen(prefix) : 0;
159 char *r = prefix_path_gently(prefix, len, NULL, path);
160 if (r) {
161 free(r);
162 return 1;
163 }
164 return 0;
165 }
166
167 int check_filename(const char *prefix, const char *arg)
168 {
169 char *to_free = NULL;
170 struct stat st;
171
172 if (skip_prefix(arg, ":/", &arg)) {
173 if (!*arg) /* ":/" is root dir, always exists */
174 return 1;
175 prefix = NULL;
176 } else if (skip_prefix(arg, ":!", &arg) ||
177 skip_prefix(arg, ":^", &arg)) {
178 if (!*arg) /* excluding everything is silly, but allowed */
179 return 1;
180 }
181
182 if (prefix)
183 arg = to_free = prefix_filename(prefix, arg);
184
185 if (!lstat(arg, &st)) {
186 free(to_free);
187 return 1; /* file exists */
188 }
189 if (is_missing_file_error(errno)) {
190 free(to_free);
191 return 0; /* file does not exist */
192 }
193 die_errno(_("failed to stat '%s'"), arg);
194 }
195
196 static void NORETURN die_verify_filename(struct repository *r,
197 const char *prefix,
198 const char *arg,
199 int diagnose_misspelt_rev)
200 {
201 if (!diagnose_misspelt_rev)
202 die(_("%s: no such path in the working tree.\n"
203 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
204 arg);
205 /*
206 * Saying "'(icase)foo' does not exist in the index" when the
207 * user gave us ":(icase)foo" is just stupid. A magic pathspec
208 * begins with a colon and is followed by a non-alnum; do not
209 * let maybe_die_on_misspelt_object_name() even trigger.
210 */
211 if (!(arg[0] == ':' && !isalnum(arg[1])))
212 maybe_die_on_misspelt_object_name(r, arg, prefix);
213
214 /* ... or fall back the most general message. */
215 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
216 "Use '--' to separate paths from revisions, like this:\n"
217 "'git <command> [<revision>...] -- [<file>...]'"), arg);
218
219 }
220
221 /*
222 * Check for arguments that don't resolve as actual files,
223 * but which look sufficiently like pathspecs that we'll consider
224 * them such for the purposes of rev/pathspec DWIM parsing.
225 */
226 static int looks_like_pathspec(const char *arg)
227 {
228 const char *p;
229 int escaped = 0;
230
231 /*
232 * Wildcard characters imply the user is looking to match pathspecs
233 * that aren't in the filesystem. Note that this doesn't include
234 * backslash even though it's a glob special; by itself it doesn't
235 * cause any increase in the match. Likewise ignore backslash-escaped
236 * wildcard characters.
237 */
238 for (p = arg; *p; p++) {
239 if (escaped) {
240 escaped = 0;
241 } else if (is_glob_special(*p)) {
242 if (*p == '\\')
243 escaped = 1;
244 else
245 return 1;
246 }
247 }
248
249 /* long-form pathspec magic */
250 if (starts_with(arg, ":("))
251 return 1;
252
253 return 0;
254 }
255
256 /*
257 * Verify a filename that we got as an argument for a pathspec
258 * entry. Note that a filename that begins with "-" never verifies
259 * as true, because even if such a filename were to exist, we want
260 * it to be preceded by the "--" marker (or we want the user to
261 * use a format like "./-filename")
262 *
263 * The "diagnose_misspelt_rev" is used to provide a user-friendly
264 * diagnosis when dying upon finding that "name" is not a pathname.
265 * If set to 1, the diagnosis will try to diagnose "name" as an
266 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
267 * will only complain about an inexisting file.
268 *
269 * This function is typically called to check that a "file or rev"
270 * argument is unambiguous. In this case, the caller will want
271 * diagnose_misspelt_rev == 1 when verifying the first non-rev
272 * argument (which could have been a revision), and
273 * diagnose_misspelt_rev == 0 for the next ones (because we already
274 * saw a filename, there's not ambiguity anymore).
275 */
276 void verify_filename(const char *prefix,
277 const char *arg,
278 int diagnose_misspelt_rev)
279 {
280 if (*arg == '-')
281 die(_("option '%s' must come before non-option arguments"), arg);
282 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
283 return;
284 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
285 }
286
287 /*
288 * Opposite of the above: the command line did not have -- marker
289 * and we parsed the arg as a refname. It should not be interpretable
290 * as a filename.
291 */
292 void verify_non_filename(const char *prefix, const char *arg)
293 {
294 if (!is_inside_work_tree() || is_inside_git_dir())
295 return;
296 if (*arg == '-')
297 return; /* flag */
298 if (!check_filename(prefix, arg))
299 return;
300 die(_("ambiguous argument '%s': both revision and filename\n"
301 "Use '--' to separate paths from revisions, like this:\n"
302 "'git <command> [<revision>...] -- [<file>...]'"), arg);
303 }
304
305 int get_common_dir(struct strbuf *sb, const char *gitdir)
306 {
307 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
308 if (git_env_common_dir) {
309 strbuf_addstr(sb, git_env_common_dir);
310 return 1;
311 } else {
312 return get_common_dir_noenv(sb, gitdir);
313 }
314 }
315
316 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
317 {
318 struct strbuf data = STRBUF_INIT;
319 struct strbuf path = STRBUF_INIT;
320 int ret = 0;
321
322 strbuf_addf(&path, "%s/commondir", gitdir);
323 if (file_exists(path.buf)) {
324 if (strbuf_read_file(&data, path.buf, 0) <= 0)
325 die_errno(_("failed to read %s"), path.buf);
326 while (data.len && (data.buf[data.len - 1] == '\n' ||
327 data.buf[data.len - 1] == '\r'))
328 data.len--;
329 data.buf[data.len] = '\0';
330 strbuf_reset(&path);
331 if (!is_absolute_path(data.buf))
332 strbuf_addf(&path, "%s/", gitdir);
333 strbuf_addbuf(&path, &data);
334 strbuf_add_real_path(sb, path.buf);
335 ret = 1;
336 } else {
337 strbuf_addstr(sb, gitdir);
338 }
339
340 strbuf_release(&data);
341 strbuf_release(&path);
342 return ret;
343 }
344
345 /*
346 * Test if it looks like we're at a git directory.
347 * We want to see:
348 *
349 * - either an objects/ directory _or_ the proper
350 * GIT_OBJECT_DIRECTORY environment variable
351 * - a refs/ directory
352 * - either a HEAD symlink or a HEAD file that is formatted as
353 * a proper "ref:", or a regular file HEAD that has a properly
354 * formatted sha1 object name.
355 */
356 int is_git_directory(const char *suspect)
357 {
358 struct strbuf path = STRBUF_INIT;
359 int ret = 0;
360 size_t len;
361
362 /* Check worktree-related signatures */
363 strbuf_addstr(&path, suspect);
364 strbuf_complete(&path, '/');
365 strbuf_addstr(&path, "HEAD");
366 if (validate_headref(path.buf))
367 goto done;
368
369 strbuf_reset(&path);
370 get_common_dir(&path, suspect);
371 len = path.len;
372
373 /* Check non-worktree-related signatures */
374 if (getenv(DB_ENVIRONMENT)) {
375 if (access(getenv(DB_ENVIRONMENT), X_OK))
376 goto done;
377 }
378 else {
379 strbuf_setlen(&path, len);
380 strbuf_addstr(&path, "/objects");
381 if (access(path.buf, X_OK))
382 goto done;
383 }
384
385 strbuf_setlen(&path, len);
386 strbuf_addstr(&path, "/refs");
387 if (access(path.buf, X_OK))
388 goto done;
389
390 ret = 1;
391 done:
392 strbuf_release(&path);
393 return ret;
394 }
395
396 int is_nonbare_repository_dir(struct strbuf *path)
397 {
398 int ret = 0;
399 int gitfile_error;
400 size_t orig_path_len = path->len;
401 assert(orig_path_len != 0);
402 strbuf_complete(path, '/');
403 strbuf_addstr(path, ".git");
404 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
405 ret = 1;
406 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
407 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
408 ret = 1;
409 strbuf_setlen(path, orig_path_len);
410 return ret;
411 }
412
413 int is_inside_git_dir(void)
414 {
415 if (inside_git_dir < 0)
416 inside_git_dir = is_inside_dir(get_git_dir());
417 return inside_git_dir;
418 }
419
420 int is_inside_work_tree(void)
421 {
422 if (inside_work_tree < 0)
423 inside_work_tree = is_inside_dir(get_git_work_tree());
424 return inside_work_tree;
425 }
426
427 void setup_work_tree(void)
428 {
429 const char *work_tree;
430 static int initialized = 0;
431
432 if (initialized)
433 return;
434
435 if (work_tree_config_is_bogus)
436 die(_("unable to set up work tree using invalid config"));
437
438 work_tree = get_git_work_tree();
439 if (!work_tree || chdir_notify(work_tree))
440 die(_("this operation must be run in a work tree"));
441
442 /*
443 * Make sure subsequent git processes find correct worktree
444 * if $GIT_WORK_TREE is set relative
445 */
446 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
447 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
448
449 initialized = 1;
450 }
451
452 static void setup_original_cwd(void)
453 {
454 struct strbuf tmp = STRBUF_INIT;
455 const char *worktree = NULL;
456 int offset = -1;
457
458 if (!tmp_original_cwd)
459 return;
460
461 /*
462 * startup_info->original_cwd points to the current working
463 * directory we inherited from our parent process, which is a
464 * directory we want to avoid removing.
465 *
466 * For convience, we would like to have the path relative to the
467 * worktree instead of an absolute path.
468 *
469 * Yes, startup_info->original_cwd is usually the same as 'prefix',
470 * but differs in two ways:
471 * - prefix has a trailing '/'
472 * - if the user passes '-C' to git, that modifies the prefix but
473 * not startup_info->original_cwd.
474 */
475
476 /* Normalize the directory */
477 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
478 trace2_data_string("setup", the_repository,
479 "realpath-path", tmp_original_cwd);
480 trace2_data_string("setup", the_repository,
481 "realpath-failure", strerror(errno));
482 free((char*)tmp_original_cwd);
483 tmp_original_cwd = NULL;
484 return;
485 }
486
487 free((char*)tmp_original_cwd);
488 tmp_original_cwd = NULL;
489 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
490
491 /*
492 * Get our worktree; we only protect the current working directory
493 * if it's in the worktree.
494 */
495 worktree = get_git_work_tree();
496 if (!worktree)
497 goto no_prevention_needed;
498
499 offset = dir_inside_of(startup_info->original_cwd, worktree);
500 if (offset >= 0) {
501 /*
502 * If startup_info->original_cwd == worktree, that is already
503 * protected and we don't need original_cwd as a secondary
504 * protection measure.
505 */
506 if (!*(startup_info->original_cwd + offset))
507 goto no_prevention_needed;
508
509 /*
510 * original_cwd was inside worktree; precompose it just as
511 * we do prefix so that built up paths will match
512 */
513 startup_info->original_cwd = \
514 precompose_string_if_needed(startup_info->original_cwd
515 + offset);
516 return;
517 }
518
519 no_prevention_needed:
520 free((char*)startup_info->original_cwd);
521 startup_info->original_cwd = NULL;
522 }
523
524 static int read_worktree_config(const char *var, const char *value, void *vdata)
525 {
526 struct repository_format *data = vdata;
527
528 if (strcmp(var, "core.bare") == 0) {
529 data->is_bare = git_config_bool(var, value);
530 } else if (strcmp(var, "core.worktree") == 0) {
531 if (!value)
532 return config_error_nonbool(var);
533 free(data->work_tree);
534 data->work_tree = xstrdup(value);
535 }
536 return 0;
537 }
538
539 enum extension_result {
540 EXTENSION_ERROR = -1, /* compatible with error(), etc */
541 EXTENSION_UNKNOWN = 0,
542 EXTENSION_OK = 1
543 };
544
545 /*
546 * Do not add new extensions to this function. It handles extensions which are
547 * respected even in v0-format repositories for historical compatibility.
548 */
549 static enum extension_result handle_extension_v0(const char *var,
550 const char *value,
551 const char *ext,
552 struct repository_format *data)
553 {
554 if (!strcmp(ext, "noop")) {
555 return EXTENSION_OK;
556 } else if (!strcmp(ext, "preciousobjects")) {
557 data->precious_objects = git_config_bool(var, value);
558 return EXTENSION_OK;
559 } else if (!strcmp(ext, "partialclone")) {
560 data->partial_clone = xstrdup(value);
561 return EXTENSION_OK;
562 } else if (!strcmp(ext, "worktreeconfig")) {
563 data->worktree_config = git_config_bool(var, value);
564 return EXTENSION_OK;
565 }
566
567 return EXTENSION_UNKNOWN;
568 }
569
570 /*
571 * Record any new extensions in this function.
572 */
573 static enum extension_result handle_extension(const char *var,
574 const char *value,
575 const char *ext,
576 struct repository_format *data)
577 {
578 if (!strcmp(ext, "noop-v1")) {
579 return EXTENSION_OK;
580 } else if (!strcmp(ext, "objectformat")) {
581 int format;
582
583 if (!value)
584 return config_error_nonbool(var);
585 format = hash_algo_by_name(value);
586 if (format == GIT_HASH_UNKNOWN)
587 return error(_("invalid value for '%s': '%s'"),
588 "extensions.objectformat", value);
589 data->hash_algo = format;
590 return EXTENSION_OK;
591 }
592 return EXTENSION_UNKNOWN;
593 }
594
595 static int check_repo_format(const char *var, const char *value, void *vdata)
596 {
597 struct repository_format *data = vdata;
598 const char *ext;
599
600 if (strcmp(var, "core.repositoryformatversion") == 0)
601 data->version = git_config_int(var, value);
602 else if (skip_prefix(var, "extensions.", &ext)) {
603 switch (handle_extension_v0(var, value, ext, data)) {
604 case EXTENSION_ERROR:
605 return -1;
606 case EXTENSION_OK:
607 return 0;
608 case EXTENSION_UNKNOWN:
609 break;
610 }
611
612 switch (handle_extension(var, value, ext, data)) {
613 case EXTENSION_ERROR:
614 return -1;
615 case EXTENSION_OK:
616 string_list_append(&data->v1_only_extensions, ext);
617 return 0;
618 case EXTENSION_UNKNOWN:
619 string_list_append(&data->unknown_extensions, ext);
620 return 0;
621 }
622 }
623
624 return read_worktree_config(var, value, vdata);
625 }
626
627 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
628 {
629 struct strbuf sb = STRBUF_INIT;
630 struct strbuf err = STRBUF_INIT;
631 int has_common;
632
633 has_common = get_common_dir(&sb, gitdir);
634 strbuf_addstr(&sb, "/config");
635 read_repository_format(candidate, sb.buf);
636 strbuf_release(&sb);
637
638 /*
639 * For historical use of check_repository_format() in git-init,
640 * we treat a missing config as a silent "ok", even when nongit_ok
641 * is unset.
642 */
643 if (candidate->version < 0)
644 return 0;
645
646 if (verify_repository_format(candidate, &err) < 0) {
647 if (nongit_ok) {
648 warning("%s", err.buf);
649 strbuf_release(&err);
650 *nongit_ok = -1;
651 return -1;
652 }
653 die("%s", err.buf);
654 }
655
656 repository_format_precious_objects = candidate->precious_objects;
657 string_list_clear(&candidate->unknown_extensions, 0);
658 string_list_clear(&candidate->v1_only_extensions, 0);
659
660 if (candidate->worktree_config) {
661 /*
662 * pick up core.bare and core.worktree from per-worktree
663 * config if present
664 */
665 strbuf_addf(&sb, "%s/config.worktree", gitdir);
666 git_config_from_file(read_worktree_config, sb.buf, candidate);
667 strbuf_release(&sb);
668 has_common = 0;
669 }
670
671 if (!has_common) {
672 if (candidate->is_bare != -1) {
673 is_bare_repository_cfg = candidate->is_bare;
674 if (is_bare_repository_cfg == 1)
675 inside_work_tree = -1;
676 }
677 if (candidate->work_tree) {
678 free(git_work_tree_cfg);
679 git_work_tree_cfg = xstrdup(candidate->work_tree);
680 inside_work_tree = -1;
681 }
682 }
683
684 return 0;
685 }
686
687 int upgrade_repository_format(int target_version)
688 {
689 struct strbuf sb = STRBUF_INIT;
690 struct strbuf err = STRBUF_INIT;
691 struct strbuf repo_version = STRBUF_INIT;
692 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
693
694 strbuf_git_common_path(&sb, the_repository, "config");
695 read_repository_format(&repo_fmt, sb.buf);
696 strbuf_release(&sb);
697
698 if (repo_fmt.version >= target_version)
699 return 0;
700
701 if (verify_repository_format(&repo_fmt, &err) < 0) {
702 error("cannot upgrade repository format from %d to %d: %s",
703 repo_fmt.version, target_version, err.buf);
704 strbuf_release(&err);
705 return -1;
706 }
707 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr)
708 return error("cannot upgrade repository format: "
709 "unknown extension %s",
710 repo_fmt.unknown_extensions.items[0].string);
711
712 strbuf_addf(&repo_version, "%d", target_version);
713 git_config_set("core.repositoryformatversion", repo_version.buf);
714 strbuf_release(&repo_version);
715 return 1;
716 }
717
718 static void init_repository_format(struct repository_format *format)
719 {
720 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
721
722 memcpy(format, &fresh, sizeof(fresh));
723 }
724
725 int read_repository_format(struct repository_format *format, const char *path)
726 {
727 clear_repository_format(format);
728 git_config_from_file(check_repo_format, path, format);
729 if (format->version == -1)
730 clear_repository_format(format);
731 return format->version;
732 }
733
734 void clear_repository_format(struct repository_format *format)
735 {
736 string_list_clear(&format->unknown_extensions, 0);
737 string_list_clear(&format->v1_only_extensions, 0);
738 free(format->work_tree);
739 free(format->partial_clone);
740 init_repository_format(format);
741 }
742
743 int verify_repository_format(const struct repository_format *format,
744 struct strbuf *err)
745 {
746 if (GIT_REPO_VERSION_READ < format->version) {
747 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
748 GIT_REPO_VERSION_READ, format->version);
749 return -1;
750 }
751
752 if (format->version >= 1 && format->unknown_extensions.nr) {
753 int i;
754
755 strbuf_addstr(err, Q_("unknown repository extension found:",
756 "unknown repository extensions found:",
757 format->unknown_extensions.nr));
758
759 for (i = 0; i < format->unknown_extensions.nr; i++)
760 strbuf_addf(err, "\n\t%s",
761 format->unknown_extensions.items[i].string);
762 return -1;
763 }
764
765 if (format->version == 0 && format->v1_only_extensions.nr) {
766 int i;
767
768 strbuf_addstr(err,
769 Q_("repo version is 0, but v1-only extension found:",
770 "repo version is 0, but v1-only extensions found:",
771 format->v1_only_extensions.nr));
772
773 for (i = 0; i < format->v1_only_extensions.nr; i++)
774 strbuf_addf(err, "\n\t%s",
775 format->v1_only_extensions.items[i].string);
776 return -1;
777 }
778
779 return 0;
780 }
781
782 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
783 {
784 switch (error_code) {
785 case READ_GITFILE_ERR_STAT_FAILED:
786 case READ_GITFILE_ERR_NOT_A_FILE:
787 /* non-fatal; follow return path */
788 break;
789 case READ_GITFILE_ERR_OPEN_FAILED:
790 die_errno(_("error opening '%s'"), path);
791 case READ_GITFILE_ERR_TOO_LARGE:
792 die(_("too large to be a .git file: '%s'"), path);
793 case READ_GITFILE_ERR_READ_FAILED:
794 die(_("error reading %s"), path);
795 case READ_GITFILE_ERR_INVALID_FORMAT:
796 die(_("invalid gitfile format: %s"), path);
797 case READ_GITFILE_ERR_NO_PATH:
798 die(_("no path in gitfile: %s"), path);
799 case READ_GITFILE_ERR_NOT_A_REPO:
800 die(_("not a git repository: %s"), dir);
801 default:
802 BUG("unknown error code");
803 }
804 }
805
806 /*
807 * Try to read the location of the git directory from the .git file,
808 * return path to git directory if found. The return value comes from
809 * a shared buffer.
810 *
811 * On failure, if return_error_code is not NULL, return_error_code
812 * will be set to an error code and NULL will be returned. If
813 * return_error_code is NULL the function will die instead (for most
814 * cases).
815 */
816 const char *read_gitfile_gently(const char *path, int *return_error_code)
817 {
818 const int max_file_size = 1 << 20; /* 1MB */
819 int error_code = 0;
820 char *buf = NULL;
821 char *dir = NULL;
822 const char *slash;
823 struct stat st;
824 int fd;
825 ssize_t len;
826 static struct strbuf realpath = STRBUF_INIT;
827
828 if (stat(path, &st)) {
829 /* NEEDSWORK: discern between ENOENT vs other errors */
830 error_code = READ_GITFILE_ERR_STAT_FAILED;
831 goto cleanup_return;
832 }
833 if (!S_ISREG(st.st_mode)) {
834 error_code = READ_GITFILE_ERR_NOT_A_FILE;
835 goto cleanup_return;
836 }
837 if (st.st_size > max_file_size) {
838 error_code = READ_GITFILE_ERR_TOO_LARGE;
839 goto cleanup_return;
840 }
841 fd = open(path, O_RDONLY);
842 if (fd < 0) {
843 error_code = READ_GITFILE_ERR_OPEN_FAILED;
844 goto cleanup_return;
845 }
846 buf = xmallocz(st.st_size);
847 len = read_in_full(fd, buf, st.st_size);
848 close(fd);
849 if (len != st.st_size) {
850 error_code = READ_GITFILE_ERR_READ_FAILED;
851 goto cleanup_return;
852 }
853 if (!starts_with(buf, "gitdir: ")) {
854 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
855 goto cleanup_return;
856 }
857 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
858 len--;
859 if (len < 9) {
860 error_code = READ_GITFILE_ERR_NO_PATH;
861 goto cleanup_return;
862 }
863 buf[len] = '\0';
864 dir = buf + 8;
865
866 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
867 size_t pathlen = slash+1 - path;
868 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
869 (int)(len - 8), buf + 8);
870 free(buf);
871 buf = dir;
872 }
873 if (!is_git_directory(dir)) {
874 error_code = READ_GITFILE_ERR_NOT_A_REPO;
875 goto cleanup_return;
876 }
877
878 strbuf_realpath(&realpath, dir, 1);
879 path = realpath.buf;
880
881 cleanup_return:
882 if (return_error_code)
883 *return_error_code = error_code;
884 else if (error_code)
885 read_gitfile_error_die(error_code, path, dir);
886
887 free(buf);
888 return error_code ? NULL : path;
889 }
890
891 static const char *setup_explicit_git_dir(const char *gitdirenv,
892 struct strbuf *cwd,
893 struct repository_format *repo_fmt,
894 int *nongit_ok)
895 {
896 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
897 const char *worktree;
898 char *gitfile;
899 int offset;
900
901 if (PATH_MAX - 40 < strlen(gitdirenv))
902 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
903
904 gitfile = (char*)read_gitfile(gitdirenv);
905 if (gitfile) {
906 gitfile = xstrdup(gitfile);
907 gitdirenv = gitfile;
908 }
909
910 if (!is_git_directory(gitdirenv)) {
911 if (nongit_ok) {
912 *nongit_ok = 1;
913 free(gitfile);
914 return NULL;
915 }
916 die(_("not a git repository: '%s'"), gitdirenv);
917 }
918
919 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
920 free(gitfile);
921 return NULL;
922 }
923
924 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
925 if (work_tree_env)
926 set_git_work_tree(work_tree_env);
927 else if (is_bare_repository_cfg > 0) {
928 if (git_work_tree_cfg) {
929 /* #22.2, #30 */
930 warning("core.bare and core.worktree do not make sense");
931 work_tree_config_is_bogus = 1;
932 }
933
934 /* #18, #26 */
935 set_git_dir(gitdirenv, 0);
936 free(gitfile);
937 return NULL;
938 }
939 else if (git_work_tree_cfg) { /* #6, #14 */
940 if (is_absolute_path(git_work_tree_cfg))
941 set_git_work_tree(git_work_tree_cfg);
942 else {
943 char *core_worktree;
944 if (chdir(gitdirenv))
945 die_errno(_("cannot chdir to '%s'"), gitdirenv);
946 if (chdir(git_work_tree_cfg))
947 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
948 core_worktree = xgetcwd();
949 if (chdir(cwd->buf))
950 die_errno(_("cannot come back to cwd"));
951 set_git_work_tree(core_worktree);
952 free(core_worktree);
953 }
954 }
955 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
956 /* #16d */
957 set_git_dir(gitdirenv, 0);
958 free(gitfile);
959 return NULL;
960 }
961 else /* #2, #10 */
962 set_git_work_tree(".");
963
964 /* set_git_work_tree() must have been called by now */
965 worktree = get_git_work_tree();
966
967 /* both get_git_work_tree() and cwd are already normalized */
968 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
969 set_git_dir(gitdirenv, 0);
970 free(gitfile);
971 return NULL;
972 }
973
974 offset = dir_inside_of(cwd->buf, worktree);
975 if (offset >= 0) { /* cwd inside worktree? */
976 set_git_dir(gitdirenv, 1);
977 if (chdir(worktree))
978 die_errno(_("cannot chdir to '%s'"), worktree);
979 strbuf_addch(cwd, '/');
980 free(gitfile);
981 return cwd->buf + offset;
982 }
983
984 /* cwd outside worktree */
985 set_git_dir(gitdirenv, 0);
986 free(gitfile);
987 return NULL;
988 }
989
990 static const char *setup_discovered_git_dir(const char *gitdir,
991 struct strbuf *cwd, int offset,
992 struct repository_format *repo_fmt,
993 int *nongit_ok)
994 {
995 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
996 return NULL;
997
998 /* --work-tree is set without --git-dir; use discovered one */
999 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1000 char *to_free = NULL;
1001 const char *ret;
1002
1003 if (offset != cwd->len && !is_absolute_path(gitdir))
1004 gitdir = to_free = real_pathdup(gitdir, 1);
1005 if (chdir(cwd->buf))
1006 die_errno(_("cannot come back to cwd"));
1007 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1008 free(to_free);
1009 return ret;
1010 }
1011
1012 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1013 if (is_bare_repository_cfg > 0) {
1014 set_git_dir(gitdir, (offset != cwd->len));
1015 if (chdir(cwd->buf))
1016 die_errno(_("cannot come back to cwd"));
1017 return NULL;
1018 }
1019
1020 /* #0, #1, #5, #8, #9, #12, #13 */
1021 set_git_work_tree(".");
1022 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1023 set_git_dir(gitdir, 0);
1024 inside_git_dir = 0;
1025 inside_work_tree = 1;
1026 if (offset >= cwd->len)
1027 return NULL;
1028
1029 /* Make "offset" point past the '/' (already the case for root dirs) */
1030 if (offset != offset_1st_component(cwd->buf))
1031 offset++;
1032 /* Add a '/' at the end */
1033 strbuf_addch(cwd, '/');
1034 return cwd->buf + offset;
1035 }
1036
1037 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1038 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1039 struct repository_format *repo_fmt,
1040 int *nongit_ok)
1041 {
1042 int root_len;
1043
1044 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1045 return NULL;
1046
1047 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1048
1049 /* --work-tree is set without --git-dir; use discovered one */
1050 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1051 static const char *gitdir;
1052
1053 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1054 if (chdir(cwd->buf))
1055 die_errno(_("cannot come back to cwd"));
1056 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1057 }
1058
1059 inside_git_dir = 1;
1060 inside_work_tree = 0;
1061 if (offset != cwd->len) {
1062 if (chdir(cwd->buf))
1063 die_errno(_("cannot come back to cwd"));
1064 root_len = offset_1st_component(cwd->buf);
1065 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1066 set_git_dir(cwd->buf, 0);
1067 }
1068 else
1069 set_git_dir(".", 0);
1070 return NULL;
1071 }
1072
1073 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1074 {
1075 struct stat buf;
1076 if (stat(path, &buf)) {
1077 die_errno(_("failed to stat '%*s%s%s'"),
1078 prefix_len,
1079 prefix ? prefix : "",
1080 prefix ? "/" : "", path);
1081 }
1082 return buf.st_dev;
1083 }
1084
1085 /*
1086 * A "string_list_each_func_t" function that canonicalizes an entry
1087 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1088 * discards it if unusable. The presence of an empty entry in
1089 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1090 * subsequent entries.
1091 */
1092 static int canonicalize_ceiling_entry(struct string_list_item *item,
1093 void *cb_data)
1094 {
1095 int *empty_entry_found = cb_data;
1096 char *ceil = item->string;
1097
1098 if (!*ceil) {
1099 *empty_entry_found = 1;
1100 return 0;
1101 } else if (!is_absolute_path(ceil)) {
1102 return 0;
1103 } else if (*empty_entry_found) {
1104 /* Keep entry but do not canonicalize it */
1105 return 1;
1106 } else {
1107 char *real_path = real_pathdup(ceil, 0);
1108 if (!real_path) {
1109 return 0;
1110 }
1111 free(item->string);
1112 item->string = real_path;
1113 return 1;
1114 }
1115 }
1116
1117 struct safe_directory_data {
1118 const char *path;
1119 int is_safe;
1120 };
1121
1122 static int safe_directory_cb(const char *key, const char *value, void *d)
1123 {
1124 struct safe_directory_data *data = d;
1125
1126 if (strcmp(key, "safe.directory"))
1127 return 0;
1128
1129 if (!value || !*value) {
1130 data->is_safe = 0;
1131 } else if (!strcmp(value, "*")) {
1132 data->is_safe = 1;
1133 } else {
1134 const char *interpolated = NULL;
1135
1136 if (!git_config_pathname(&interpolated, key, value) &&
1137 !fspathcmp(data->path, interpolated ? interpolated : value))
1138 data->is_safe = 1;
1139
1140 free((char *)interpolated);
1141 }
1142
1143 return 0;
1144 }
1145
1146 /*
1147 * Check if a repository is safe, by verifying the ownership of the
1148 * worktree (if any), the git directory, and the gitfile (if any).
1149 *
1150 * Exemptions for known-safe repositories can be added via `safe.directory`
1151 * config settings; for non-bare repositories, their worktree needs to be
1152 * added, for bare ones their git directory.
1153 */
1154 static int ensure_valid_ownership(const char *gitfile,
1155 const char *worktree, const char *gitdir,
1156 struct strbuf *report)
1157 {
1158 struct safe_directory_data data = {
1159 .path = worktree ? worktree : gitdir
1160 };
1161
1162 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1163 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1164 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1165 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1166 return 1;
1167
1168 /*
1169 * data.path is the "path" that identifies the repository and it is
1170 * constant regardless of what failed above. data.is_safe should be
1171 * initialized to false, and might be changed by the callback.
1172 */
1173 git_protected_config(safe_directory_cb, &data);
1174
1175 return data.is_safe;
1176 }
1177
1178 static int allowed_bare_repo_cb(const char *key, const char *value, void *d)
1179 {
1180 enum allowed_bare_repo *allowed_bare_repo = d;
1181
1182 if (strcasecmp(key, "safe.bareRepository"))
1183 return 0;
1184
1185 if (!strcmp(value, "explicit")) {
1186 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1187 return 0;
1188 }
1189 if (!strcmp(value, "all")) {
1190 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1191 return 0;
1192 }
1193 return -1;
1194 }
1195
1196 static enum allowed_bare_repo get_allowed_bare_repo(void)
1197 {
1198 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1199 git_protected_config(allowed_bare_repo_cb, &result);
1200 return result;
1201 }
1202
1203 static const char *allowed_bare_repo_to_string(
1204 enum allowed_bare_repo allowed_bare_repo)
1205 {
1206 switch (allowed_bare_repo) {
1207 case ALLOWED_BARE_REPO_EXPLICIT:
1208 return "explicit";
1209 case ALLOWED_BARE_REPO_ALL:
1210 return "all";
1211 default:
1212 BUG("invalid allowed_bare_repo %d",
1213 allowed_bare_repo);
1214 }
1215 return NULL;
1216 }
1217
1218 enum discovery_result {
1219 GIT_DIR_NONE = 0,
1220 GIT_DIR_EXPLICIT,
1221 GIT_DIR_DISCOVERED,
1222 GIT_DIR_BARE,
1223 /* these are errors */
1224 GIT_DIR_HIT_CEILING = -1,
1225 GIT_DIR_HIT_MOUNT_POINT = -2,
1226 GIT_DIR_INVALID_GITFILE = -3,
1227 GIT_DIR_INVALID_OWNERSHIP = -4,
1228 GIT_DIR_DISALLOWED_BARE = -5,
1229 };
1230
1231 /*
1232 * We cannot decide in this function whether we are in the work tree or
1233 * not, since the config can only be read _after_ this function was called.
1234 *
1235 * Also, we avoid changing any global state (such as the current working
1236 * directory) to allow early callers.
1237 *
1238 * The directory where the search should start needs to be passed in via the
1239 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1240 * the directory where the search ended, and `gitdir` will contain the path of
1241 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1242 * is relative to `dir` (i.e. *not* necessarily the cwd).
1243 */
1244 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1245 struct strbuf *gitdir,
1246 struct strbuf *report,
1247 int die_on_error)
1248 {
1249 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1250 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1251 const char *gitdirenv;
1252 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1253 dev_t current_device = 0;
1254 int one_filesystem = 1;
1255
1256 /*
1257 * If GIT_DIR is set explicitly, we're not going
1258 * to do any discovery, but we still do repository
1259 * validation.
1260 */
1261 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1262 if (gitdirenv) {
1263 strbuf_addstr(gitdir, gitdirenv);
1264 return GIT_DIR_EXPLICIT;
1265 }
1266
1267 if (env_ceiling_dirs) {
1268 int empty_entry_found = 0;
1269
1270 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1271 filter_string_list(&ceiling_dirs, 0,
1272 canonicalize_ceiling_entry, &empty_entry_found);
1273 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1274 string_list_clear(&ceiling_dirs, 0);
1275 }
1276
1277 if (ceil_offset < 0)
1278 ceil_offset = min_offset - 2;
1279
1280 if (min_offset && min_offset == dir->len &&
1281 !is_dir_sep(dir->buf[min_offset - 1])) {
1282 strbuf_addch(dir, '/');
1283 min_offset++;
1284 }
1285
1286 /*
1287 * Test in the following order (relative to the dir):
1288 * - .git (file containing "gitdir: <path>")
1289 * - .git/
1290 * - ./ (bare)
1291 * - ../.git
1292 * - ../.git/
1293 * - ../ (bare)
1294 * - ../../.git
1295 * etc.
1296 */
1297 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1298 if (one_filesystem)
1299 current_device = get_device_or_die(dir->buf, NULL, 0);
1300 for (;;) {
1301 int offset = dir->len, error_code = 0;
1302 char *gitdir_path = NULL;
1303 char *gitfile = NULL;
1304
1305 if (offset > min_offset)
1306 strbuf_addch(dir, '/');
1307 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1308 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1309 NULL : &error_code);
1310 if (!gitdirenv) {
1311 if (die_on_error ||
1312 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1313 /* NEEDSWORK: fail if .git is not file nor dir */
1314 if (is_git_directory(dir->buf)) {
1315 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1316 gitdir_path = xstrdup(dir->buf);
1317 }
1318 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1319 return GIT_DIR_INVALID_GITFILE;
1320 } else
1321 gitfile = xstrdup(dir->buf);
1322 /*
1323 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1324 * to check that directory for a repository.
1325 * Now trim that tentative addition away, because we want to
1326 * focus on the real directory we are in.
1327 */
1328 strbuf_setlen(dir, offset);
1329 if (gitdirenv) {
1330 enum discovery_result ret;
1331 const char *gitdir_candidate =
1332 gitdir_path ? gitdir_path : gitdirenv;
1333
1334 if (ensure_valid_ownership(gitfile, dir->buf,
1335 gitdir_candidate, report)) {
1336 strbuf_addstr(gitdir, gitdirenv);
1337 ret = GIT_DIR_DISCOVERED;
1338 } else
1339 ret = GIT_DIR_INVALID_OWNERSHIP;
1340
1341 /*
1342 * Earlier, during discovery, we might have allocated
1343 * string copies for gitdir_path or gitfile so make
1344 * sure we don't leak by freeing them now, before
1345 * leaving the loop and function.
1346 *
1347 * Note: gitdirenv will be non-NULL whenever these are
1348 * allocated, therefore we need not take care of releasing
1349 * them outside of this conditional block.
1350 */
1351 free(gitdir_path);
1352 free(gitfile);
1353
1354 return ret;
1355 }
1356
1357 if (is_git_directory(dir->buf)) {
1358 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1359 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT)
1360 return GIT_DIR_DISALLOWED_BARE;
1361 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1362 return GIT_DIR_INVALID_OWNERSHIP;
1363 strbuf_addstr(gitdir, ".");
1364 return GIT_DIR_BARE;
1365 }
1366
1367 if (offset <= min_offset)
1368 return GIT_DIR_HIT_CEILING;
1369
1370 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1371 ; /* continue */
1372 if (offset <= ceil_offset)
1373 return GIT_DIR_HIT_CEILING;
1374
1375 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1376 if (one_filesystem &&
1377 current_device != get_device_or_die(dir->buf, NULL, offset))
1378 return GIT_DIR_HIT_MOUNT_POINT;
1379 }
1380 }
1381
1382 int discover_git_directory(struct strbuf *commondir,
1383 struct strbuf *gitdir)
1384 {
1385 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1386 size_t gitdir_offset = gitdir->len, cwd_len;
1387 size_t commondir_offset = commondir->len;
1388 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1389
1390 if (strbuf_getcwd(&dir))
1391 return -1;
1392
1393 cwd_len = dir.len;
1394 if (setup_git_directory_gently_1(&dir, gitdir, NULL, 0) <= 0) {
1395 strbuf_release(&dir);
1396 return -1;
1397 }
1398
1399 /*
1400 * The returned gitdir is relative to dir, and if dir does not reflect
1401 * the current working directory, we simply make the gitdir absolute.
1402 */
1403 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1404 /* Avoid a trailing "/." */
1405 if (!strcmp(".", gitdir->buf + gitdir_offset))
1406 strbuf_setlen(gitdir, gitdir_offset);
1407 else
1408 strbuf_addch(&dir, '/');
1409 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1410 }
1411
1412 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1413
1414 strbuf_reset(&dir);
1415 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1416 read_repository_format(&candidate, dir.buf);
1417 strbuf_release(&dir);
1418
1419 if (verify_repository_format(&candidate, &err) < 0) {
1420 warning("ignoring git dir '%s': %s",
1421 gitdir->buf + gitdir_offset, err.buf);
1422 strbuf_release(&err);
1423 strbuf_setlen(commondir, commondir_offset);
1424 strbuf_setlen(gitdir, gitdir_offset);
1425 clear_repository_format(&candidate);
1426 return -1;
1427 }
1428
1429 the_repository->repository_format_worktree_config =
1430 candidate.worktree_config;
1431
1432 /* take ownership of candidate.partial_clone */
1433 the_repository->repository_format_partial_clone =
1434 candidate.partial_clone;
1435 candidate.partial_clone = NULL;
1436
1437 clear_repository_format(&candidate);
1438 return 0;
1439 }
1440
1441 const char *setup_git_directory_gently(int *nongit_ok)
1442 {
1443 static struct strbuf cwd = STRBUF_INIT;
1444 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1445 const char *prefix = NULL;
1446 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1447
1448 /*
1449 * We may have read an incomplete configuration before
1450 * setting-up the git directory. If so, clear the cache so
1451 * that the next queries to the configuration reload complete
1452 * configuration (including the per-repo config file that we
1453 * ignored previously).
1454 */
1455 git_config_clear();
1456
1457 /*
1458 * Let's assume that we are in a git repository.
1459 * If it turns out later that we are somewhere else, the value will be
1460 * updated accordingly.
1461 */
1462 if (nongit_ok)
1463 *nongit_ok = 0;
1464
1465 if (strbuf_getcwd(&cwd))
1466 die_errno(_("Unable to read current working directory"));
1467 strbuf_addbuf(&dir, &cwd);
1468
1469 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1470 case GIT_DIR_EXPLICIT:
1471 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1472 break;
1473 case GIT_DIR_DISCOVERED:
1474 if (dir.len < cwd.len && chdir(dir.buf))
1475 die(_("cannot change to '%s'"), dir.buf);
1476 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1477 &repo_fmt, nongit_ok);
1478 break;
1479 case GIT_DIR_BARE:
1480 if (dir.len < cwd.len && chdir(dir.buf))
1481 die(_("cannot change to '%s'"), dir.buf);
1482 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1483 break;
1484 case GIT_DIR_HIT_CEILING:
1485 if (!nongit_ok)
1486 die(_("not a git repository (or any of the parent directories): %s"),
1487 DEFAULT_GIT_DIR_ENVIRONMENT);
1488 *nongit_ok = 1;
1489 break;
1490 case GIT_DIR_HIT_MOUNT_POINT:
1491 if (!nongit_ok)
1492 die(_("not a git repository (or any parent up to mount point %s)\n"
1493 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1494 dir.buf);
1495 *nongit_ok = 1;
1496 break;
1497 case GIT_DIR_INVALID_OWNERSHIP:
1498 if (!nongit_ok) {
1499 struct strbuf quoted = STRBUF_INIT;
1500
1501 strbuf_complete(&report, '\n');
1502 sq_quote_buf_pretty(&quoted, dir.buf);
1503 die(_("detected dubious ownership in repository at '%s'\n"
1504 "%s"
1505 "To add an exception for this directory, call:\n"
1506 "\n"
1507 "\tgit config --global --add safe.directory %s"),
1508 dir.buf, report.buf, quoted.buf);
1509 }
1510 *nongit_ok = 1;
1511 break;
1512 case GIT_DIR_DISALLOWED_BARE:
1513 if (!nongit_ok) {
1514 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1515 dir.buf,
1516 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1517 }
1518 *nongit_ok = 1;
1519 break;
1520 case GIT_DIR_NONE:
1521 /*
1522 * As a safeguard against setup_git_directory_gently_1 returning
1523 * this value, fallthrough to BUG. Otherwise it is possible to
1524 * set startup_info->have_repository to 1 when we did nothing to
1525 * find a repository.
1526 */
1527 default:
1528 BUG("unhandled setup_git_directory_gently_1() result");
1529 }
1530
1531 /*
1532 * At this point, nongit_ok is stable. If it is non-NULL and points
1533 * to a non-zero value, then this means that we haven't found a
1534 * repository and that the caller expects startup_info to reflect
1535 * this.
1536 *
1537 * Regardless of the state of nongit_ok, startup_info->prefix and
1538 * the GIT_PREFIX environment variable must always match. For details
1539 * see Documentation/config/alias.txt.
1540 */
1541 if (nongit_ok && *nongit_ok)
1542 startup_info->have_repository = 0;
1543 else
1544 startup_info->have_repository = 1;
1545
1546 /*
1547 * Not all paths through the setup code will call 'set_git_dir()' (which
1548 * directly sets up the environment) so in order to guarantee that the
1549 * environment is in a consistent state after setup, explicitly setup
1550 * the environment if we have a repository.
1551 *
1552 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1553 * code paths so we also need to explicitly setup the environment if
1554 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1555 * GIT_DIR values at some point in the future.
1556 */
1557 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1558 startup_info->have_repository ||
1559 /* GIT_DIR_EXPLICIT */
1560 getenv(GIT_DIR_ENVIRONMENT)) {
1561 if (!the_repository->gitdir) {
1562 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1563 if (!gitdir)
1564 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1565 setup_git_env(gitdir);
1566 }
1567 if (startup_info->have_repository) {
1568 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1569 the_repository->repository_format_worktree_config =
1570 repo_fmt.worktree_config;
1571 /* take ownership of repo_fmt.partial_clone */
1572 the_repository->repository_format_partial_clone =
1573 repo_fmt.partial_clone;
1574 repo_fmt.partial_clone = NULL;
1575 }
1576 }
1577 /*
1578 * Since precompose_string_if_needed() needs to look at
1579 * the core.precomposeunicode configuration, this
1580 * has to happen after the above block that finds
1581 * out where the repository is, i.e. a preparation
1582 * for calling git_config_get_bool().
1583 */
1584 if (prefix) {
1585 prefix = precompose_string_if_needed(prefix);
1586 startup_info->prefix = prefix;
1587 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1588 } else {
1589 startup_info->prefix = NULL;
1590 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1591 }
1592
1593 setup_original_cwd();
1594
1595 strbuf_release(&dir);
1596 strbuf_release(&gitdir);
1597 strbuf_release(&report);
1598 clear_repository_format(&repo_fmt);
1599
1600 return prefix;
1601 }
1602
1603 int git_config_perm(const char *var, const char *value)
1604 {
1605 int i;
1606 char *endptr;
1607
1608 if (!value)
1609 return PERM_GROUP;
1610
1611 if (!strcmp(value, "umask"))
1612 return PERM_UMASK;
1613 if (!strcmp(value, "group"))
1614 return PERM_GROUP;
1615 if (!strcmp(value, "all") ||
1616 !strcmp(value, "world") ||
1617 !strcmp(value, "everybody"))
1618 return PERM_EVERYBODY;
1619
1620 /* Parse octal numbers */
1621 i = strtol(value, &endptr, 8);
1622
1623 /* If not an octal number, maybe true/false? */
1624 if (*endptr != 0)
1625 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1626
1627 /*
1628 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1629 * a chmod value to restrict to.
1630 */
1631 switch (i) {
1632 case PERM_UMASK: /* 0 */
1633 return PERM_UMASK;
1634 case OLD_PERM_GROUP: /* 1 */
1635 return PERM_GROUP;
1636 case OLD_PERM_EVERYBODY: /* 2 */
1637 return PERM_EVERYBODY;
1638 }
1639
1640 /* A filemode value was given: 0xxx */
1641
1642 if ((i & 0600) != 0600)
1643 die(_("problem with core.sharedRepository filemode value "
1644 "(0%.3o).\nThe owner of files must always have "
1645 "read and write permissions."), i);
1646
1647 /*
1648 * Mask filemode value. Others can not get write permission.
1649 * x flags for directories are handled separately.
1650 */
1651 return -(i & 0666);
1652 }
1653
1654 void check_repository_format(struct repository_format *fmt)
1655 {
1656 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1657 if (!fmt)
1658 fmt = &repo_fmt;
1659 check_repository_format_gently(get_git_dir(), fmt, NULL);
1660 startup_info->have_repository = 1;
1661 repo_set_hash_algo(the_repository, fmt->hash_algo);
1662 the_repository->repository_format_worktree_config =
1663 fmt->worktree_config;
1664 the_repository->repository_format_partial_clone =
1665 xstrdup_or_null(fmt->partial_clone);
1666 clear_repository_format(&repo_fmt);
1667 }
1668
1669 /*
1670 * Returns the "prefix", a path to the current working directory
1671 * relative to the work tree root, or NULL, if the current working
1672 * directory is not a strict subdirectory of the work tree root. The
1673 * prefix always ends with a '/' character.
1674 */
1675 const char *setup_git_directory(void)
1676 {
1677 return setup_git_directory_gently(NULL);
1678 }
1679
1680 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1681 {
1682 if (is_git_directory(suspect))
1683 return suspect;
1684 return read_gitfile_gently(suspect, return_error_code);
1685 }
1686
1687 /* if any standard file descriptor is missing open it to /dev/null */
1688 void sanitize_stdfds(void)
1689 {
1690 int fd = xopen("/dev/null", O_RDWR);
1691 while (fd < 2)
1692 fd = xdup(fd);
1693 if (fd > 2)
1694 close(fd);
1695 }
1696
1697 int daemonize(void)
1698 {
1699 #ifdef NO_POSIX_GOODIES
1700 errno = ENOSYS;
1701 return -1;
1702 #else
1703 switch (fork()) {
1704 case 0:
1705 break;
1706 case -1:
1707 die_errno(_("fork failed"));
1708 default:
1709 exit(0);
1710 }
1711 if (setsid() == -1)
1712 die_errno(_("setsid failed"));
1713 close(0);
1714 close(1);
1715 close(2);
1716 sanitize_stdfds();
1717 return 0;
1718 #endif
1719 }
1720
1721 #ifdef NO_TRUSTABLE_FILEMODE
1722 #define TEST_FILEMODE 0
1723 #else
1724 #define TEST_FILEMODE 1
1725 #endif
1726
1727 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1728
1729 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1730 DIR *dir)
1731 {
1732 size_t path_baselen = path->len;
1733 size_t template_baselen = template_path->len;
1734 struct dirent *de;
1735
1736 /* Note: if ".git/hooks" file exists in the repository being
1737 * re-initialized, /etc/core-git/templates/hooks/update would
1738 * cause "git init" to fail here. I think this is sane but
1739 * it means that the set of templates we ship by default, along
1740 * with the way the namespace under .git/ is organized, should
1741 * be really carefully chosen.
1742 */
1743 safe_create_dir(path->buf, 1);
1744 while ((de = readdir(dir)) != NULL) {
1745 struct stat st_git, st_template;
1746 int exists = 0;
1747
1748 strbuf_setlen(path, path_baselen);
1749 strbuf_setlen(template_path, template_baselen);
1750
1751 if (de->d_name[0] == '.')
1752 continue;
1753 strbuf_addstr(path, de->d_name);
1754 strbuf_addstr(template_path, de->d_name);
1755 if (lstat(path->buf, &st_git)) {
1756 if (errno != ENOENT)
1757 die_errno(_("cannot stat '%s'"), path->buf);
1758 }
1759 else
1760 exists = 1;
1761
1762 if (lstat(template_path->buf, &st_template))
1763 die_errno(_("cannot stat template '%s'"), template_path->buf);
1764
1765 if (S_ISDIR(st_template.st_mode)) {
1766 DIR *subdir = opendir(template_path->buf);
1767 if (!subdir)
1768 die_errno(_("cannot opendir '%s'"), template_path->buf);
1769 strbuf_addch(path, '/');
1770 strbuf_addch(template_path, '/');
1771 copy_templates_1(path, template_path, subdir);
1772 closedir(subdir);
1773 }
1774 else if (exists)
1775 continue;
1776 else if (S_ISLNK(st_template.st_mode)) {
1777 struct strbuf lnk = STRBUF_INIT;
1778 if (strbuf_readlink(&lnk, template_path->buf,
1779 st_template.st_size) < 0)
1780 die_errno(_("cannot readlink '%s'"), template_path->buf);
1781 if (symlink(lnk.buf, path->buf))
1782 die_errno(_("cannot symlink '%s' '%s'"),
1783 lnk.buf, path->buf);
1784 strbuf_release(&lnk);
1785 }
1786 else if (S_ISREG(st_template.st_mode)) {
1787 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1788 die_errno(_("cannot copy '%s' to '%s'"),
1789 template_path->buf, path->buf);
1790 }
1791 else
1792 error(_("ignoring template %s"), template_path->buf);
1793 }
1794 }
1795
1796 static void copy_templates(const char *template_dir, const char *init_template_dir)
1797 {
1798 struct strbuf path = STRBUF_INIT;
1799 struct strbuf template_path = STRBUF_INIT;
1800 size_t template_len;
1801 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
1802 struct strbuf err = STRBUF_INIT;
1803 DIR *dir;
1804 char *to_free = NULL;
1805
1806 if (!template_dir)
1807 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1808 if (!template_dir)
1809 template_dir = init_template_dir;
1810 if (!template_dir)
1811 template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1812 if (!template_dir[0]) {
1813 free(to_free);
1814 return;
1815 }
1816
1817 strbuf_addstr(&template_path, template_dir);
1818 strbuf_complete(&template_path, '/');
1819 template_len = template_path.len;
1820
1821 dir = opendir(template_path.buf);
1822 if (!dir) {
1823 warning(_("templates not found in %s"), template_dir);
1824 goto free_return;
1825 }
1826
1827 /* Make sure that template is from the correct vintage */
1828 strbuf_addstr(&template_path, "config");
1829 read_repository_format(&template_format, template_path.buf);
1830 strbuf_setlen(&template_path, template_len);
1831
1832 /*
1833 * No mention of version at all is OK, but anything else should be
1834 * verified.
1835 */
1836 if (template_format.version >= 0 &&
1837 verify_repository_format(&template_format, &err) < 0) {
1838 warning(_("not copying templates from '%s': %s"),
1839 template_dir, err.buf);
1840 strbuf_release(&err);
1841 goto close_free_return;
1842 }
1843
1844 strbuf_addstr(&path, get_git_common_dir());
1845 strbuf_complete(&path, '/');
1846 copy_templates_1(&path, &template_path, dir);
1847 close_free_return:
1848 closedir(dir);
1849 free_return:
1850 free(to_free);
1851 strbuf_release(&path);
1852 strbuf_release(&template_path);
1853 clear_repository_format(&template_format);
1854 }
1855
1856 /*
1857 * If the git_dir is not directly inside the working tree, then git will not
1858 * find it by default, and we need to set the worktree explicitly.
1859 */
1860 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
1861 {
1862 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
1863 return 0;
1864 if (skip_prefix(git_dir, work_tree, &git_dir) &&
1865 !strcmp(git_dir, "/.git"))
1866 return 0;
1867 return 1;
1868 }
1869
1870 void initialize_repository_version(int hash_algo, int reinit)
1871 {
1872 char repo_version_string[10];
1873 int repo_version = GIT_REPO_VERSION;
1874
1875 if (hash_algo != GIT_HASH_SHA1)
1876 repo_version = GIT_REPO_VERSION_READ;
1877
1878 /* This forces creation of new config file */
1879 xsnprintf(repo_version_string, sizeof(repo_version_string),
1880 "%d", repo_version);
1881 git_config_set("core.repositoryformatversion", repo_version_string);
1882
1883 if (hash_algo != GIT_HASH_SHA1)
1884 git_config_set("extensions.objectformat",
1885 hash_algos[hash_algo].name);
1886 else if (reinit)
1887 git_config_set_gently("extensions.objectformat", NULL);
1888 }
1889
1890 static int create_default_files(const char *template_path,
1891 const char *original_git_dir,
1892 const char *initial_branch,
1893 const struct repository_format *fmt,
1894 int prev_bare_repository,
1895 int init_shared_repository,
1896 int quiet)
1897 {
1898 struct stat st1;
1899 struct strbuf buf = STRBUF_INIT;
1900 char *path;
1901 char junk[2];
1902 int reinit;
1903 int filemode;
1904 struct strbuf err = STRBUF_INIT;
1905 const char *init_template_dir = NULL;
1906 const char *work_tree = get_git_work_tree();
1907
1908 /*
1909 * First copy the templates -- we might have the default
1910 * config file there, in which case we would want to read
1911 * from it after installing.
1912 *
1913 * Before reading that config, we also need to clear out any cached
1914 * values (since we've just potentially changed what's available on
1915 * disk).
1916 */
1917 git_config_get_pathname("init.templatedir", &init_template_dir);
1918 copy_templates(template_path, init_template_dir);
1919 free((char *)init_template_dir);
1920 git_config_clear();
1921 reset_shared_repository();
1922 git_config(git_default_config, NULL);
1923
1924 /*
1925 * We must make sure command-line options continue to override any
1926 * values we might have just re-read from the config.
1927 */
1928 if (init_shared_repository != -1)
1929 set_shared_repository(init_shared_repository);
1930 /*
1931 * TODO: heed core.bare from config file in templates if no
1932 * command-line override given
1933 */
1934 is_bare_repository_cfg = prev_bare_repository || !work_tree;
1935 /* TODO (continued):
1936 *
1937 * Unfortunately, the line above is equivalent to
1938 * is_bare_repository_cfg = !work_tree;
1939 * which ignores the config entirely even if no `--[no-]bare`
1940 * command line option was present.
1941 *
1942 * To see why, note that before this function, there was this call:
1943 * prev_bare_repository = is_bare_repository()
1944 * expanding the right hand side:
1945 * = is_bare_repository_cfg && !get_git_work_tree()
1946 * = is_bare_repository_cfg && !work_tree
1947 * note that the last simplification above is valid because nothing
1948 * calls repo_init() or set_git_work_tree() between any of the
1949 * relevant calls in the code, and thus the !get_git_work_tree()
1950 * calls will return the same result each time. So, what we are
1951 * interested in computing is the right hand side of the line of
1952 * code just above this comment:
1953 * prev_bare_repository || !work_tree
1954 * = is_bare_repository_cfg && !work_tree || !work_tree
1955 * = !work_tree
1956 * because "A && !B || !B == !B" for all boolean values of A & B.
1957 */
1958
1959 /*
1960 * We would have created the above under user's umask -- under
1961 * shared-repository settings, we would need to fix them up.
1962 */
1963 if (get_shared_repository()) {
1964 adjust_shared_perm(get_git_dir());
1965 }
1966
1967 /*
1968 * We need to create a "refs" dir in any case so that older
1969 * versions of git can tell that this is a repository.
1970 */
1971 safe_create_dir(git_path("refs"), 1);
1972 adjust_shared_perm(git_path("refs"));
1973
1974 if (refs_init_db(&err))
1975 die("failed to set up refs db: %s", err.buf);
1976
1977 /*
1978 * Point the HEAD symref to the initial branch with if HEAD does
1979 * not yet exist.
1980 */
1981 path = git_path_buf(&buf, "HEAD");
1982 reinit = (!access(path, R_OK)
1983 || readlink(path, junk, sizeof(junk)-1) != -1);
1984 if (!reinit) {
1985 char *ref;
1986
1987 if (!initial_branch)
1988 initial_branch = git_default_branch_name(quiet);
1989
1990 ref = xstrfmt("refs/heads/%s", initial_branch);
1991 if (check_refname_format(ref, 0) < 0)
1992 die(_("invalid initial branch name: '%s'"),
1993 initial_branch);
1994
1995 if (create_symref("HEAD", ref, NULL) < 0)
1996 exit(1);
1997 free(ref);
1998 }
1999
2000 initialize_repository_version(fmt->hash_algo, 0);
2001
2002 /* Check filemode trustability */
2003 path = git_path_buf(&buf, "config");
2004 filemode = TEST_FILEMODE;
2005 if (TEST_FILEMODE && !lstat(path, &st1)) {
2006 struct stat st2;
2007 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2008 !lstat(path, &st2) &&
2009 st1.st_mode != st2.st_mode &&
2010 !chmod(path, st1.st_mode));
2011 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2012 filemode = 0;
2013 }
2014 git_config_set("core.filemode", filemode ? "true" : "false");
2015
2016 if (is_bare_repository())
2017 git_config_set("core.bare", "true");
2018 else {
2019 git_config_set("core.bare", "false");
2020 /* allow template config file to override the default */
2021 if (log_all_ref_updates == LOG_REFS_UNSET)
2022 git_config_set("core.logallrefupdates", "true");
2023 if (needs_work_tree_config(original_git_dir, work_tree))
2024 git_config_set("core.worktree", work_tree);
2025 }
2026
2027 if (!reinit) {
2028 /* Check if symlink is supported in the work tree */
2029 path = git_path_buf(&buf, "tXXXXXX");
2030 if (!close(xmkstemp(path)) &&
2031 !unlink(path) &&
2032 !symlink("testing", path) &&
2033 !lstat(path, &st1) &&
2034 S_ISLNK(st1.st_mode))
2035 unlink(path); /* good */
2036 else
2037 git_config_set("core.symlinks", "false");
2038
2039 /* Check if the filesystem is case-insensitive */
2040 path = git_path_buf(&buf, "CoNfIg");
2041 if (!access(path, F_OK))
2042 git_config_set("core.ignorecase", "true");
2043 probe_utf8_pathname_composition();
2044 }
2045
2046 strbuf_release(&buf);
2047 return reinit;
2048 }
2049
2050 static void create_object_directory(void)
2051 {
2052 struct strbuf path = STRBUF_INIT;
2053 size_t baselen;
2054
2055 strbuf_addstr(&path, get_object_directory());
2056 baselen = path.len;
2057
2058 safe_create_dir(path.buf, 1);
2059
2060 strbuf_setlen(&path, baselen);
2061 strbuf_addstr(&path, "/pack");
2062 safe_create_dir(path.buf, 1);
2063
2064 strbuf_setlen(&path, baselen);
2065 strbuf_addstr(&path, "/info");
2066 safe_create_dir(path.buf, 1);
2067
2068 strbuf_release(&path);
2069 }
2070
2071 static void separate_git_dir(const char *git_dir, const char *git_link)
2072 {
2073 struct stat st;
2074
2075 if (!stat(git_link, &st)) {
2076 const char *src;
2077
2078 if (S_ISREG(st.st_mode))
2079 src = read_gitfile(git_link);
2080 else if (S_ISDIR(st.st_mode))
2081 src = git_link;
2082 else
2083 die(_("unable to handle file type %d"), (int)st.st_mode);
2084
2085 if (rename(src, git_dir))
2086 die_errno(_("unable to move %s to %s"), src, git_dir);
2087 repair_worktrees(NULL, NULL);
2088 }
2089
2090 write_file(git_link, "gitdir: %s", git_dir);
2091 }
2092
2093 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2094 {
2095 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2096 /*
2097 * If we already have an initialized repo, don't allow the user to
2098 * specify a different algorithm, as that could cause corruption.
2099 * Otherwise, if the user has specified one on the command line, use it.
2100 */
2101 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2102 die(_("attempt to reinitialize repository with different hash"));
2103 else if (hash != GIT_HASH_UNKNOWN)
2104 repo_fmt->hash_algo = hash;
2105 else if (env) {
2106 int env_algo = hash_algo_by_name(env);
2107 if (env_algo == GIT_HASH_UNKNOWN)
2108 die(_("unknown hash algorithm '%s'"), env);
2109 repo_fmt->hash_algo = env_algo;
2110 }
2111 }
2112
2113 int init_db(const char *git_dir, const char *real_git_dir,
2114 const char *template_dir, int hash, const char *initial_branch,
2115 int init_shared_repository, unsigned int flags)
2116 {
2117 int reinit;
2118 int exist_ok = flags & INIT_DB_EXIST_OK;
2119 char *original_git_dir = real_pathdup(git_dir, 1);
2120 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2121 int prev_bare_repository;
2122
2123 if (real_git_dir) {
2124 struct stat st;
2125
2126 if (!exist_ok && !stat(git_dir, &st))
2127 die(_("%s already exists"), git_dir);
2128
2129 if (!exist_ok && !stat(real_git_dir, &st))
2130 die(_("%s already exists"), real_git_dir);
2131
2132 set_git_dir(real_git_dir, 1);
2133 git_dir = get_git_dir();
2134 separate_git_dir(git_dir, original_git_dir);
2135 }
2136 else {
2137 set_git_dir(git_dir, 1);
2138 git_dir = get_git_dir();
2139 }
2140 startup_info->have_repository = 1;
2141
2142 /* Ensure `core.hidedotfiles` is processed */
2143 git_config(platform_core_config, NULL);
2144
2145 safe_create_dir(git_dir, 0);
2146
2147 prev_bare_repository = is_bare_repository();
2148
2149 /* Check to see if the repository version is right.
2150 * Note that a newly created repository does not have
2151 * config file, so this will not fail. What we are catching
2152 * is an attempt to reinitialize new repository with an old tool.
2153 */
2154 check_repository_format(&repo_fmt);
2155
2156 validate_hash_algorithm(&repo_fmt, hash);
2157
2158 reinit = create_default_files(template_dir, original_git_dir,
2159 initial_branch, &repo_fmt,
2160 prev_bare_repository,
2161 init_shared_repository,
2162 flags & INIT_DB_QUIET);
2163 if (reinit && initial_branch)
2164 warning(_("re-init: ignored --initial-branch=%s"),
2165 initial_branch);
2166
2167 create_object_directory();
2168
2169 if (get_shared_repository()) {
2170 char buf[10];
2171 /* We do not spell "group" and such, so that
2172 * the configuration can be read by older version
2173 * of git. Note, we use octal numbers for new share modes,
2174 * and compatibility values for PERM_GROUP and
2175 * PERM_EVERYBODY.
2176 */
2177 if (get_shared_repository() < 0)
2178 /* force to the mode value */
2179 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2180 else if (get_shared_repository() == PERM_GROUP)
2181 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2182 else if (get_shared_repository() == PERM_EVERYBODY)
2183 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2184 else
2185 BUG("invalid value for shared_repository");
2186 git_config_set("core.sharedrepository", buf);
2187 git_config_set("receive.denyNonFastforwards", "true");
2188 }
2189
2190 if (!(flags & INIT_DB_QUIET)) {
2191 int len = strlen(git_dir);
2192
2193 if (reinit)
2194 printf(get_shared_repository()
2195 ? _("Reinitialized existing shared Git repository in %s%s\n")
2196 : _("Reinitialized existing Git repository in %s%s\n"),
2197 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2198 else
2199 printf(get_shared_repository()
2200 ? _("Initialized empty shared Git repository in %s%s\n")
2201 : _("Initialized empty Git repository in %s%s\n"),
2202 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2203 }
2204
2205 free(original_git_dir);
2206 return 0;
2207 }