1 /* Copyright (c) 2006-2013 Jonas Fonseca <jonas.fonseca@gmail.com>
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of the GNU General Public License as
5  * published by the Free Software Foundation; either version 2 of
6  * the License, or (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  */
13 
14 #ifdef HAVE_CONFIG_H
15 #include "config.h"
16 #endif
17 
18 #include "compat.h"
19 #include "stddef.h"
20 #include <stdlib.h>
21 #include <string.h>
22 #include <stdio.h>
23 
24 void
compat_wordfree(wordexp_t * pwordexp)25 compat_wordfree (wordexp_t *pwordexp)
26 {
27 	free(pwordexp->we_wordv[0]);
28 	free(pwordexp->we_wordv);
29 }
30 
31 int
compat_wordexp(const char * words,wordexp_t * pwordexp,int flags)32 compat_wordexp (const char *words, wordexp_t *pwordexp, int flags)
33 {
34 	char *expanded = NULL;
35 	const char *home = getenv("HOME");
36 
37 	if (home && words[0] == '~' && (words[1] == '/' || words[1] == 0)) {
38 		size_t len = strlen(home) + strlen(words + 1) + 1;
39 		if ((expanded = malloc(len)) && !snprintf(expanded, len, "%s%s", home, words + 1)) {
40 			free(expanded);
41 			return -1;
42 		}
43 	} else {
44 		expanded = strdup(words);
45 	}
46 
47 	if (!expanded)
48 		return -1;
49 
50 	pwordexp->we_wordv = calloc(2, sizeof(*pwordexp->we_wordv));
51 	if (!pwordexp->we_wordv) {
52 		free(expanded);
53 		return -1;
54 	}
55 	pwordexp->we_wordv[0] = expanded;
56 
57 	return 0;
58 }
59 
60 /* vim: set ts=8 sw=8 noexpandtab: */
61