~charles/dotfiles

ref: f3d8c43ffc40a3ddf482a222c3399052aa6b2f4b dotfiles/fastabr/fastabr.c -rw-r--r-- 5.8 KiB
f3d8c43f — Charles Daniels gr ignore un-readable files 3 years ago
                                                                                
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#include "fastabr.h"

#ifdef __APPLE__
#ifdef __POWERPC__

/* old-school OSX does not define strnlen... probably not secure, but if you're
 * using PPC-era OSX, do you really care?
 *
 * https://stackoverflow.com/a/32468556 */
size_t strnlen(const char *str, size_t max) {
    const char *end = memchr (str, 0, max);
    return end ? (size_t)(end - str) : max;
}

#endif // __POWERPC__
#endif // __APPLE__

char* fastabr(char* path) {
	char* abr;
	char* ptr;
	char* ap;
	char* prev;
	char* prev_base;
	char* abr_base;
	char* result;

	if (((abr    = (char*) calloc(PATH_MAX, sizeof(char))) == NULL) ||
	    ((result = (char*) calloc(PATH_MAX, sizeof(char))) == NULL) ||
	    ((prev   = (char*) calloc(PATH_MAX, sizeof(char))) == NULL)   ) {
		err(1, "calloc()");
	}

	/* this allows us to free() later */
	prev_base = prev;
	abr_base = abr;

	memset(abr, '\0', PATH_MAX);
	memset(prev, '\0', PATH_MAX);

	/* we will advance ptr through the string abr - this is cleaner than
	 * using [] notation, since ptr is also guaranteed to be a valid string
	 * */
	ptr = abr;

	/* initialize abr to '/' - this prevents an edge case where '/'
	 * is abbreviated to '', in other cases it will simply be overwritten.
	 */
	abr[0] = '/';


	/* read until we're out of data in the input string */
	while((ap = strsep(&path, PATHSEP)) != NULL) {
		/* field is empty, ignore it */
		if (*ap == '\0') { continue; }

		/* insert separator */
		*ptr = PATHSEP[0]; ptr++;

		/*  copy at least the first character of the input, possibly
		 *  more (until we hit something not a . - this makes dot-dirs
		 *  look right, as opposed to just showing up as /./ */
		do { *ptr = *ap; ap++; ptr++; } while (*(ap-1) == '.');

		/* We want to keep a copy of the previous path element, since
		 * if we end on the next iteration, ap will be NULL */
		strlcpy(prev, ap, PATH_MAX);
	}

	/* copy the full text of the last (non-NULL) field */
	while (*prev != '\0') { *ptr = *prev ; prev++; ptr++; }

	/* handle case where output path is relative to ~ by stripping the
	 * leading separator */
	if (abr[1] == '~') { abr++;}

	/* this guarantees that the caller can free() result, since the above
	 * increment would mean that returning abr could result in freeing in
	 * the middle of an allocation. */
	strlcpy(result, abr, PATH_MAX-1);

	free(prev_base);
	free(abr_base);

	return result;
}

void set_home(char* path) {
	char* homedir;
	char* rcursor;
	char* wcursor;
	size_t homelen;


	if ((homedir = getenv("HOME")) == NULL) {
		homedir = getpwuid(getuid())->pw_dir;
	}
	homelen = strnlen(homedir, PATH_MAX);

	if (strnlen(path, PATH_MAX) < homelen) {
		return;
	}

	if (strncmp(path, homedir, homelen) != 0) {
		return;
	}

	/* path to user home is present, overwrite with ~ */

	/* shift everything in path over to account for ~ being shorter
	 * than homelen */
	wcursor = path;
	*wcursor = '~'; wcursor++;
	rcursor = path + homelen;

	while (*rcursor != '\0') {
		*wcursor = *rcursor;
		wcursor ++; rcursor++;
	}

	/* null terminate */
	*wcursor = '\0';

}

void display_usage(void) {
	printf("fastabr [-vHhn] [-p PATH]\n");
}

void display_help(void) {
	display_usage();
	printf("\n");
	printf("--disable-home, -h\n");
	printf("\tDon't replace $HOME with ~.\n");
	printf("--disable-normalize, -n\n");
	printf("\tDon't normalized paths with realpath () before abbreviating.\n");
	printf("--version, -v\n");
	printf("\tDisplay the version number and exit.\n");
	printf("--help, -H\n");
	printf("\tDisplay this help message.\n");
	printf("--path, -p\n");
	printf("\tProvide the path to abbreviate as an argument, rather than \n");
	printf("\tcalling getcwd().\n");

}

int main(int argc, char** argv) {
	char* path;
	char* abr;
	char* normalized;
	int c, option_index;
	int flag_disable_home, flag_disable_normalize, flag_version, flag_help;

	flag_disable_home = 0;
	flag_disable_normalize = 0;
	flag_version = 0;
	flag_help = 0;

	if (((path = (char*) calloc(PATH_MAX, sizeof(char))) == NULL)) {
		err(1, "calloc()");
	}
	memset(path, '\0', PATH_MAX);

	if (((normalized = (char*) calloc(PATH_MAX, sizeof(char))) == NULL)) {
		err(1, "calloc()");
	}

	while (1) {
		struct option long_options[] = {
			{"disable-home"      , no_argument       , &flag_disable_home      , 1  },
			{"disable-normalize" , no_argument       , &flag_disable_normalize , 1  },
			{"version"           , no_argument       , &flag_version           , 1  },
			{"help"              , no_argument       , &flag_help              , 1  },
			{"path"              , required_argument , 0                       , 'p'},
			{0, 0, 0, 0}
		};

		option_index = 0;

		c = getopt_long (argc, argv, "vhHnp:",
				long_options, &option_index);

		/* Detect the end of the options. */
		if (c == -1)
			break;

		switch (c) {
			case 0:
				/* If this option set a flag, do nothing else now. */
				if (long_options[option_index].flag != 0)
					break;
				break;

			case 'p':
				strlcpy(path, optarg, PATH_MAX);
				break;

			case 'h':
				flag_disable_home = 1;
				break;

			case 'n':
				flag_disable_normalize = 1;
				break;

			case 'v':
				flag_version = 1;
				break;

			case 'H':
				flag_help = 1;
				break;

			case '?':
				/* getopt_long already printed an error message. */
				break;

			default:
				abort ();
		}
	}

	if (flag_version == 1) {
		printf(FASTABR_VERSION);
		printf("\n");
		return 0;
	}

	if (flag_help == 1) {
		display_help();
		return 0;
	}

	/* path was not specified, use cwd */
	if (strlen(path) == 0) {
		getcwd(path, PATH_MAX);
	}

	/* normalize path */
	if (flag_disable_normalize != 1) {
		if (realpath(path, normalized) == NULL) {
			err(1, "realpath()");
		}
	} else {
		strlcpy(normalized, path, PATH_MAX);
	}

	/* strip home and replace with ~ */
	if (flag_disable_home != 1) {
		set_home(normalized);
	}

	abr = fastabr(normalized);
	printf("%s\n", abr);

	free(path);
	free(normalized);
	free(abr);

	return 0;

}