git fetch-pack: do not complain about "no common commits" in an empty repo
[git/debian.git] / abspath.c
blob4f95a954d5e20e2d42549141ac23794f681559e1
1 #include "cache.h"
3 /* We allow "recursive" symbolic links. Only within reason, though. */
4 #define MAXDEPTH 5
6 const char *make_absolute_path(const char *path)
8 static char bufs[2][PATH_MAX + 1], *buf = bufs[0], *next_buf = bufs[1];
9 char cwd[1024] = "";
10 int buf_index = 1, len;
12 int depth = MAXDEPTH;
13 char *last_elem = NULL;
14 struct stat st;
16 if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
17 die ("Too long path: %.*s", 60, path);
19 while (depth--) {
20 if (stat(buf, &st) || !S_ISDIR(st.st_mode)) {
21 char *last_slash = strrchr(buf, '/');
22 if (last_slash) {
23 *last_slash = '\0';
24 last_elem = xstrdup(last_slash + 1);
25 } else {
26 last_elem = xstrdup(buf);
27 *buf = '\0';
31 if (*buf) {
32 if (!*cwd && !getcwd(cwd, sizeof(cwd)))
33 die ("Could not get current working directory");
35 if (chdir(buf))
36 die ("Could not switch to '%s'", buf);
38 if (!getcwd(buf, PATH_MAX))
39 die ("Could not get current working directory");
41 if (last_elem) {
42 int len = strlen(buf);
43 if (len + strlen(last_elem) + 2 > PATH_MAX)
44 die ("Too long path name: '%s/%s'",
45 buf, last_elem);
46 buf[len] = '/';
47 strcpy(buf + len + 1, last_elem);
48 free(last_elem);
49 last_elem = NULL;
52 if (!lstat(buf, &st) && S_ISLNK(st.st_mode)) {
53 len = readlink(buf, next_buf, PATH_MAX);
54 if (len < 0)
55 die ("Invalid symlink: %s", buf);
56 next_buf[len] = '\0';
57 buf = next_buf;
58 buf_index = 1 - buf_index;
59 next_buf = bufs[buf_index];
60 } else
61 break;
64 if (*cwd && chdir(cwd))
65 die ("Could not change back to '%s'", cwd);
67 return buf;