4 * Do not use this for inspecting *tracked* content. When path is a
5 * symlink to a directory, we do not want to say it is a directory when
6 * dealing with tracked content in the working tree.
8 int is_directory(const char *path
)
11 return (!stat(path
, &st
) && S_ISDIR(st
.st_mode
));
14 /* We allow "recursive" symbolic links. Only within reason, though. */
18 * Use this to get the real path, i.e. resolve links. If you want an
19 * absolute path but don't mind links, use absolute_path.
21 * If path is our buffer, then return path, as it's already what the
24 const char *real_path(const char *path
)
26 static char bufs
[2][PATH_MAX
+ 1], *buf
= bufs
[0], *next_buf
= bufs
[1];
31 char *last_elem
= NULL
;
34 /* We've already done it */
35 if (path
== buf
|| path
== next_buf
)
38 if (strlcpy(buf
, path
, PATH_MAX
) >= PATH_MAX
)
39 die ("Too long path: %.*s", 60, path
);
42 if (!is_directory(buf
)) {
43 char *last_slash
= strrchr(buf
, '/');
46 last_elem
= xstrdup(last_slash
+ 1);
48 last_elem
= xstrdup(buf
);
54 if (!*cwd
&& !getcwd(cwd
, sizeof(cwd
)))
55 die_errno ("Could not get current working directory");
58 die_errno ("Could not switch to '%s'", buf
);
60 if (!getcwd(buf
, PATH_MAX
))
61 die_errno ("Could not get current working directory");
64 size_t len
= strlen(buf
);
65 if (len
+ strlen(last_elem
) + 2 > PATH_MAX
)
66 die ("Too long path name: '%s/%s'",
68 if (len
&& buf
[len
-1] != '/')
70 strcpy(buf
+ len
, last_elem
);
75 if (!lstat(buf
, &st
) && S_ISLNK(st
.st_mode
)) {
76 ssize_t len
= readlink(buf
, next_buf
, PATH_MAX
);
78 die_errno ("Invalid symlink '%s'", buf
);
80 die("symbolic link too long: %s", buf
);
83 buf_index
= 1 - buf_index
;
84 next_buf
= bufs
[buf_index
];
89 if (*cwd
&& chdir(cwd
))
90 die_errno ("Could not change back to '%s'", cwd
);
95 static const char *get_pwd_cwd(void)
97 static char cwd
[PATH_MAX
+ 1];
99 struct stat cwd_stat
, pwd_stat
;
100 if (getcwd(cwd
, PATH_MAX
) == NULL
)
103 if (pwd
&& strcmp(pwd
, cwd
)) {
104 stat(cwd
, &cwd_stat
);
105 if ((cwd_stat
.st_dev
|| cwd_stat
.st_ino
) &&
106 !stat(pwd
, &pwd_stat
) &&
107 pwd_stat
.st_dev
== cwd_stat
.st_dev
&&
108 pwd_stat
.st_ino
== cwd_stat
.st_ino
) {
109 strlcpy(cwd
, pwd
, PATH_MAX
);
116 * Use this to get an absolute path from a relative one. If you want
117 * to resolve links, you should use real_path.
119 * If the path is already absolute, then return path. As the user is
120 * never meant to free the return value, we're safe.
122 const char *absolute_path(const char *path
)
124 static char buf
[PATH_MAX
+ 1];
126 if (is_absolute_path(path
)) {
127 if (strlcpy(buf
, path
, PATH_MAX
) >= PATH_MAX
)
128 die("Too long path: %.*s", 60, path
);
132 const char *cwd
= get_pwd_cwd();
134 die_errno("Cannot determine the current working directory");
136 fmt
= (len
> 0 && is_dir_sep(cwd
[len
-1])) ? "%s%s" : "%s/%s";
137 if (snprintf(buf
, PATH_MAX
, fmt
, cwd
, path
) >= PATH_MAX
)
138 die("Too long path: %.*s", 60, path
);