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. */
17 const char *make_absolute_path(const char *path
)
19 static char bufs
[2][PATH_MAX
+ 1], *buf
= bufs
[0], *next_buf
= bufs
[1];
24 char *last_elem
= NULL
;
27 /* We've already done it */
28 if (path
== buf
|| path
== next_buf
)
31 if (strlcpy(buf
, path
, PATH_MAX
) >= PATH_MAX
)
32 die ("Too long path: %.*s", 60, path
);
35 if (!is_directory(buf
)) {
36 char *last_slash
= strrchr(buf
, '/');
39 last_elem
= xstrdup(last_slash
+ 1);
41 last_elem
= xstrdup(buf
);
47 if (!*cwd
&& !getcwd(cwd
, sizeof(cwd
)))
48 die_errno ("Could not get current working directory");
51 die_errno ("Could not switch to '%s'", buf
);
53 if (!getcwd(buf
, PATH_MAX
))
54 die_errno ("Could not get current working directory");
57 size_t len
= strlen(buf
);
58 if (len
+ strlen(last_elem
) + 2 > PATH_MAX
)
59 die ("Too long path name: '%s/%s'",
61 if (len
&& buf
[len
-1] != '/')
63 strcpy(buf
+ len
, last_elem
);
68 if (!lstat(buf
, &st
) && S_ISLNK(st
.st_mode
)) {
69 ssize_t len
= readlink(buf
, next_buf
, PATH_MAX
);
71 die_errno ("Invalid symlink '%s'", buf
);
73 die("symbolic link too long: %s", buf
);
76 buf_index
= 1 - buf_index
;
77 next_buf
= bufs
[buf_index
];
82 if (*cwd
&& chdir(cwd
))
83 die_errno ("Could not change back to '%s'", cwd
);
88 static const char *get_pwd_cwd(void)
90 static char cwd
[PATH_MAX
+ 1];
92 struct stat cwd_stat
, pwd_stat
;
93 if (getcwd(cwd
, PATH_MAX
) == NULL
)
96 if (pwd
&& strcmp(pwd
, cwd
)) {
98 if (!stat(pwd
, &pwd_stat
) &&
99 pwd_stat
.st_dev
== cwd_stat
.st_dev
&&
100 pwd_stat
.st_ino
== cwd_stat
.st_ino
) {
101 strlcpy(cwd
, pwd
, PATH_MAX
);
107 const char *make_nonrelative_path(const char *path
)
109 static char buf
[PATH_MAX
+ 1];
111 if (is_absolute_path(path
)) {
112 if (strlcpy(buf
, path
, PATH_MAX
) >= PATH_MAX
)
113 die("Too long path: %.*s", 60, path
);
117 const char *cwd
= get_pwd_cwd();
119 die_errno("Cannot determine the current working directory");
121 fmt
= (len
> 0 && is_dir_sep(cwd
[len
-1])) ? "%s%s" : "%s/%s";
122 if (snprintf(buf
, PATH_MAX
, fmt
, cwd
, path
) >= PATH_MAX
)
123 die("Too long path: %.*s", 60, path
);