-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
expandpath.c
123 lines (106 loc) · 3.03 KB
/
expandpath.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#define _POSIX_C_SOURCE 200809L
#include <pwd.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <xph/io.h>
#include <xph/stdlib.h>
#define DIE(...) \
{ \
fputs("expandpath: ", stderr); \
fprintf(stderr, __VA_ARGS__); \
fputc('\n', stderr); \
exit(EXIT_FAILURE); \
}
char delim = '\n';
char *home;
char *expand(const char *path, char *buf, size_t bufsize)
{
size_t i, j, len;
bool dupe = false;
struct passwd *pw = NULL;
len = strlen(path);
buf = areallocfit(buf, bufsize, (len + 1) * sizeof(char));
for (i = 0, j = 0; i < len; i++) {
if (path[i] == '/') {
if (!dupe)
buf[j++] = '/';
dupe = true;
} else {
buf[j++] = path[i];
dupe = false;
}
}
buf[len = j] = '\0';
if (buf[0] != '~') {
fputs(buf, stdout);
} else {
if (len == 1)
fputs(home, stdout);
else if (buf[1] == '/') {
fputs(home, stdout);
fputs(buf + 1, stdout);
} else {
for (i = 0, j = 0; i < len; i++) {
if (buf[i] == '/') {
buf[j = i] = '\0';
break;
}
}
if ((pw = getpwnam(buf + 1))) {
fputs(pw->pw_dir, stdout);
if (j) {
buf[j] = '/';
fputs(buf + j, stdout);
}
} else {
if (j)
buf[j] = '/';
fputs(buf, stdout);
}
}
}
putchar(delim);
return buf;
}
int main(int argc, char *argv[])
{
int i;
char *line = NULL, *buf = NULL;
size_t bufsize = 0;
while ((i = getopt(argc, argv, "hz0")) != -1) {
switch (i) {
case 'h':
puts("Usage: expandpath [OPTION]... [PATH]...\n"
"Like `wordexp`, but only expands tildes.\n"
"\n"
"With no PATH, read standard input.\n"
"\n"
" -h display this help and exit\n"
" -z line delimiter is NUL, not newline\n"
" -0 line delimiter is NUL, not newline");
exit(EXIT_SUCCESS);
break;
case 'z':
case '0':
delim = '\0';
break;
default:
fputs("Try 'expandpath -h' for more information.\n", stderr);
exit(EXIT_FAILURE);
break;
}
}
argc -= optind;
argv += optind;
if (!(home = getenv("HOME")) && !(home = getpwuid(getuid())->pw_dir))
DIE("could not determine home directory");
while ((line = getstr(argc, argv, delim)))
buf = expand(line, buf, bufsize);
free(line);
free(buf);
return 0;
}