Git 1.6.6.3
[git.git] / setup.c
1 #include "cache.h"
2 #include "dir.h"
3
4 static int inside_git_dir = -1;
5 static int inside_work_tree = -1;
6
7 const char *prefix_path(const char *prefix, int len, const char *path)
8 {
9         const char *orig = path;
10         char *sanitized = xmalloc(len + strlen(path) + 1);
11         if (is_absolute_path(orig))
12                 strcpy(sanitized, path);
13         else {
14                 if (len)
15                         memcpy(sanitized, prefix, len);
16                 strcpy(sanitized + len, path);
17         }
18         if (normalize_path_copy(sanitized, sanitized))
19                 goto error_out;
20         if (is_absolute_path(orig)) {
21                 size_t len, total;
22                 const char *work_tree = get_git_work_tree();
23                 if (!work_tree)
24                         goto error_out;
25                 len = strlen(work_tree);
26                 total = strlen(sanitized) + 1;
27                 if (strncmp(sanitized, work_tree, len) ||
28                     (sanitized[len] != '\0' && sanitized[len] != '/')) {
29                 error_out:
30                         die("'%s' is outside repository", orig);
31                 }
32                 if (sanitized[len] == '/')
33                         len++;
34                 memmove(sanitized, sanitized + len, total - len);
35         }
36         return sanitized;
37 }
38
39 /*
40  * Unlike prefix_path, this should be used if the named file does
41  * not have to interact with index entry; i.e. name of a random file
42  * on the filesystem.
43  */
44 const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
45 {
46         static char path[PATH_MAX];
47 #ifndef WIN32
48         if (!pfx || !*pfx || is_absolute_path(arg))
49                 return arg;
50         memcpy(path, pfx, pfx_len);
51         strcpy(path + pfx_len, arg);
52 #else
53         char *p;
54         /* don't add prefix to absolute paths, but still replace '\' by '/' */
55         if (is_absolute_path(arg))
56                 pfx_len = 0;
57         else
58                 memcpy(path, pfx, pfx_len);
59         strcpy(path + pfx_len, arg);
60         for (p = path + pfx_len; *p; p++)
61                 if (*p == '\\')
62                         *p = '/';
63 #endif
64         return path;
65 }
66
67 int check_filename(const char *prefix, const char *arg)
68 {
69         const char *name;
70         struct stat st;
71
72         name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
73         if (!lstat(name, &st))
74                 return 1; /* file exists */
75         if (errno == ENOENT || errno == ENOTDIR)
76                 return 0; /* file does not exist */
77         die_errno("failed to stat '%s'", arg);
78 }
79
80 /*
81  * Verify a filename that we got as an argument for a pathspec
82  * entry. Note that a filename that begins with "-" never verifies
83  * as true, because even if such a filename were to exist, we want
84  * it to be preceded by the "--" marker (or we want the user to
85  * use a format like "./-filename")
86  */
87 void verify_filename(const char *prefix, const char *arg)
88 {
89         if (*arg == '-')
90                 die("bad flag '%s' used after filename", arg);
91         if (check_filename(prefix, arg))
92                 return;
93         die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
94             "Use '--' to separate paths from revisions", arg);
95 }
96
97 /*
98  * Opposite of the above: the command line did not have -- marker
99  * and we parsed the arg as a refname.  It should not be interpretable
100  * as a filename.
101  */
102 void verify_non_filename(const char *prefix, const char *arg)
103 {
104         if (!is_inside_work_tree() || is_inside_git_dir())
105                 return;
106         if (*arg == '-')
107                 return; /* flag */
108         if (!check_filename(prefix, arg))
109                 return;
110         die("ambiguous argument '%s': both revision and filename\n"
111             "Use '--' to separate filenames from revisions", arg);
112 }
113
114 const char **get_pathspec(const char *prefix, const char **pathspec)
115 {
116         const char *entry = *pathspec;
117         const char **src, **dst;
118         int prefixlen;
119
120         if (!prefix && !entry)
121                 return NULL;
122
123         if (!entry) {
124                 static const char *spec[2];
125                 spec[0] = prefix;
126                 spec[1] = NULL;
127                 return spec;
128         }
129
130         /* Otherwise we have to re-write the entries.. */
131         src = pathspec;
132         dst = pathspec;
133         prefixlen = prefix ? strlen(prefix) : 0;
134         while (*src) {
135                 const char *p = prefix_path(prefix, prefixlen, *src);
136                 *(dst++) = p;
137                 src++;
138         }
139         *dst = NULL;
140         if (!*pathspec)
141                 return NULL;
142         return pathspec;
143 }
144
145 /*
146  * Test if it looks like we're at a git directory.
147  * We want to see:
148  *
149  *  - either an objects/ directory _or_ the proper
150  *    GIT_OBJECT_DIRECTORY environment variable
151  *  - a refs/ directory
152  *  - either a HEAD symlink or a HEAD file that is formatted as
153  *    a proper "ref:", or a regular file HEAD that has a properly
154  *    formatted sha1 object name.
155  */
156 static int is_git_directory(const char *suspect)
157 {
158         char path[PATH_MAX];
159         size_t len = strlen(suspect);
160
161         if (PATH_MAX <= len + strlen("/objects"))
162                 die("Too long path: %.*s", 60, suspect);
163         strcpy(path, suspect);
164         if (getenv(DB_ENVIRONMENT)) {
165                 if (access(getenv(DB_ENVIRONMENT), X_OK))
166                         return 0;
167         }
168         else {
169                 strcpy(path + len, "/objects");
170                 if (access(path, X_OK))
171                         return 0;
172         }
173
174         strcpy(path + len, "/refs");
175         if (access(path, X_OK))
176                 return 0;
177
178         strcpy(path + len, "/HEAD");
179         if (validate_headref(path))
180                 return 0;
181
182         return 1;
183 }
184
185 int is_inside_git_dir(void)
186 {
187         if (inside_git_dir < 0)
188                 inside_git_dir = is_inside_dir(get_git_dir());
189         return inside_git_dir;
190 }
191
192 int is_inside_work_tree(void)
193 {
194         if (inside_work_tree < 0)
195                 inside_work_tree = is_inside_dir(get_git_work_tree());
196         return inside_work_tree;
197 }
198
199 /*
200  * set_work_tree() is only ever called if you set GIT_DIR explicitely.
201  * The old behaviour (which we retain here) is to set the work tree root
202  * to the cwd, unless overridden by the config, the command line, or
203  * GIT_WORK_TREE.
204  */
205 static const char *set_work_tree(const char *dir)
206 {
207         char buffer[PATH_MAX + 1];
208
209         if (!getcwd(buffer, sizeof(buffer)))
210                 die ("Could not get the current working directory");
211         git_work_tree_cfg = xstrdup(buffer);
212         inside_work_tree = 1;
213
214         return NULL;
215 }
216
217 void setup_work_tree(void)
218 {
219         const char *work_tree, *git_dir;
220         static int initialized = 0;
221
222         if (initialized)
223                 return;
224         work_tree = get_git_work_tree();
225         git_dir = get_git_dir();
226         if (!is_absolute_path(git_dir))
227                 git_dir = make_absolute_path(git_dir);
228         if (!work_tree || chdir(work_tree))
229                 die("This operation must be run in a work tree");
230         set_git_dir(make_relative_path(git_dir, work_tree));
231         initialized = 1;
232 }
233
234 static int check_repository_format_gently(int *nongit_ok)
235 {
236         git_config(check_repository_format_version, NULL);
237         if (GIT_REPO_VERSION < repository_format_version) {
238                 if (!nongit_ok)
239                         die ("Expected git repo version <= %d, found %d",
240                              GIT_REPO_VERSION, repository_format_version);
241                 warning("Expected git repo version <= %d, found %d",
242                         GIT_REPO_VERSION, repository_format_version);
243                 warning("Please upgrade Git");
244                 *nongit_ok = -1;
245                 return -1;
246         }
247         return 0;
248 }
249
250 /*
251  * Try to read the location of the git directory from the .git file,
252  * return path to git directory if found.
253  */
254 const char *read_gitfile_gently(const char *path)
255 {
256         char *buf;
257         struct stat st;
258         int fd;
259         size_t len;
260
261         if (stat(path, &st))
262                 return NULL;
263         if (!S_ISREG(st.st_mode))
264                 return NULL;
265         fd = open(path, O_RDONLY);
266         if (fd < 0)
267                 die_errno("Error opening '%s'", path);
268         buf = xmalloc(st.st_size + 1);
269         len = read_in_full(fd, buf, st.st_size);
270         close(fd);
271         if (len != st.st_size)
272                 die("Error reading %s", path);
273         buf[len] = '\0';
274         if (prefixcmp(buf, "gitdir: "))
275                 die("Invalid gitfile format: %s", path);
276         while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
277                 len--;
278         if (len < 9)
279                 die("No path in gitfile: %s", path);
280         buf[len] = '\0';
281         if (!is_git_directory(buf + 8))
282                 die("Not a git repository: %s", buf + 8);
283         path = make_absolute_path(buf + 8);
284         free(buf);
285         return path;
286 }
287
288 /*
289  * We cannot decide in this function whether we are in the work tree or
290  * not, since the config can only be read _after_ this function was called.
291  */
292 const char *setup_git_directory_gently(int *nongit_ok)
293 {
294         const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
295         const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
296         static char cwd[PATH_MAX+1];
297         const char *gitdirenv;
298         const char *gitfile_dir;
299         int len, offset, ceil_offset;
300
301         /*
302          * Let's assume that we are in a git repository.
303          * If it turns out later that we are somewhere else, the value will be
304          * updated accordingly.
305          */
306         if (nongit_ok)
307                 *nongit_ok = 0;
308
309         /*
310          * If GIT_DIR is set explicitly, we're not going
311          * to do any discovery, but we still do repository
312          * validation.
313          */
314         gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
315         if (gitdirenv) {
316                 if (PATH_MAX - 40 < strlen(gitdirenv))
317                         die("'$%s' too big", GIT_DIR_ENVIRONMENT);
318                 if (is_git_directory(gitdirenv)) {
319                         static char buffer[1024 + 1];
320                         const char *retval;
321
322                         if (!work_tree_env) {
323                                 retval = set_work_tree(gitdirenv);
324                                 /* config may override worktree */
325                                 if (check_repository_format_gently(nongit_ok))
326                                         return NULL;
327                                 return retval;
328                         }
329                         if (check_repository_format_gently(nongit_ok))
330                                 return NULL;
331                         retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
332                                         get_git_work_tree());
333                         if (!retval || !*retval)
334                                 return NULL;
335                         set_git_dir(make_absolute_path(gitdirenv));
336                         if (chdir(work_tree_env) < 0)
337                                 die_errno ("Could not chdir to '%s'", work_tree_env);
338                         strcat(buffer, "/");
339                         return retval;
340                 }
341                 if (nongit_ok) {
342                         *nongit_ok = 1;
343                         return NULL;
344                 }
345                 die("Not a git repository: '%s'", gitdirenv);
346         }
347
348         if (!getcwd(cwd, sizeof(cwd)-1))
349                 die_errno("Unable to read current working directory");
350
351         ceil_offset = longest_ancestor_length(cwd, env_ceiling_dirs);
352         if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
353                 ceil_offset = 1;
354
355         /*
356          * Test in the following order (relative to the cwd):
357          * - .git (file containing "gitdir: <path>")
358          * - .git/
359          * - ./ (bare)
360          * - ../.git
361          * - ../.git/
362          * - ../ (bare)
363          * - ../../.git/
364          *   etc.
365          */
366         offset = len = strlen(cwd);
367         for (;;) {
368                 gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
369                 if (gitfile_dir) {
370                         if (set_git_dir(gitfile_dir))
371                                 die("Repository setup failed");
372                         break;
373                 }
374                 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
375                         break;
376                 if (is_git_directory(".")) {
377                         inside_git_dir = 1;
378                         if (!work_tree_env)
379                                 inside_work_tree = 0;
380                         if (offset != len) {
381                                 cwd[offset] = '\0';
382                                 setenv(GIT_DIR_ENVIRONMENT, cwd, 1);
383                         } else
384                                 setenv(GIT_DIR_ENVIRONMENT, ".", 1);
385                         check_repository_format_gently(nongit_ok);
386                         return NULL;
387                 }
388                 while (--offset > ceil_offset && cwd[offset] != '/');
389                 if (offset <= ceil_offset) {
390                         if (nongit_ok) {
391                                 if (chdir(cwd))
392                                         die_errno("Cannot come back to cwd");
393                                 *nongit_ok = 1;
394                                 return NULL;
395                         }
396                         die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
397                 }
398                 if (chdir(".."))
399                         die_errno("Cannot change to '%s/..'", cwd);
400         }
401
402         inside_git_dir = 0;
403         if (!work_tree_env)
404                 inside_work_tree = 1;
405         git_work_tree_cfg = xstrndup(cwd, offset);
406         if (check_repository_format_gently(nongit_ok))
407                 return NULL;
408         if (offset == len)
409                 return NULL;
410
411         /* Make "offset" point to past the '/', and add a '/' at the end */
412         offset++;
413         cwd[len++] = '/';
414         cwd[len] = 0;
415         return cwd + offset;
416 }
417
418 int git_config_perm(const char *var, const char *value)
419 {
420         int i;
421         char *endptr;
422
423         if (value == NULL)
424                 return PERM_GROUP;
425
426         if (!strcmp(value, "umask"))
427                 return PERM_UMASK;
428         if (!strcmp(value, "group"))
429                 return PERM_GROUP;
430         if (!strcmp(value, "all") ||
431             !strcmp(value, "world") ||
432             !strcmp(value, "everybody"))
433                 return PERM_EVERYBODY;
434
435         /* Parse octal numbers */
436         i = strtol(value, &endptr, 8);
437
438         /* If not an octal number, maybe true/false? */
439         if (*endptr != 0)
440                 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
441
442         /*
443          * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
444          * a chmod value to restrict to.
445          */
446         switch (i) {
447         case PERM_UMASK:               /* 0 */
448                 return PERM_UMASK;
449         case OLD_PERM_GROUP:           /* 1 */
450                 return PERM_GROUP;
451         case OLD_PERM_EVERYBODY:       /* 2 */
452                 return PERM_EVERYBODY;
453         }
454
455         /* A filemode value was given: 0xxx */
456
457         if ((i & 0600) != 0600)
458                 die("Problem with core.sharedRepository filemode value "
459                     "(0%.3o).\nThe owner of files must always have "
460                     "read and write permissions.", i);
461
462         /*
463          * Mask filemode value. Others can not get write permission.
464          * x flags for directories are handled separately.
465          */
466         return -(i & 0666);
467 }
468
469 int check_repository_format_version(const char *var, const char *value, void *cb)
470 {
471         if (strcmp(var, "core.repositoryformatversion") == 0)
472                 repository_format_version = git_config_int(var, value);
473         else if (strcmp(var, "core.sharedrepository") == 0)
474                 shared_repository = git_config_perm(var, value);
475         else if (strcmp(var, "core.bare") == 0) {
476                 is_bare_repository_cfg = git_config_bool(var, value);
477                 if (is_bare_repository_cfg == 1)
478                         inside_work_tree = -1;
479         } else if (strcmp(var, "core.worktree") == 0) {
480                 if (!value)
481                         return config_error_nonbool(var);
482                 free(git_work_tree_cfg);
483                 git_work_tree_cfg = xstrdup(value);
484                 inside_work_tree = -1;
485         }
486         return 0;
487 }
488
489 int check_repository_format(void)
490 {
491         return check_repository_format_gently(NULL);
492 }
493
494 const char *setup_git_directory(void)
495 {
496         const char *retval = setup_git_directory_gently(NULL);
497
498         /* If the work tree is not the default one, recompute prefix */
499         if (inside_work_tree < 0) {
500                 static char buffer[PATH_MAX + 1];
501                 char *rel;
502                 if (retval && chdir(retval))
503                         die_errno ("Could not jump back into original cwd");
504                 rel = get_relative_cwd(buffer, PATH_MAX, get_git_work_tree());
505                 if (rel && *rel && chdir(get_git_work_tree()))
506                         die_errno ("Could not jump to working directory");
507                 return rel && *rel ? strcat(rel, "/") : NULL;
508         }
509
510         return retval;
511 }