2 * Copyright 2004-2005 Timo Hirvonen
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 #include "tabexp_file.h"
27 #include <sys/types.h>
33 static char *get_home(const char *user
)
35 struct passwd
*passwd
;
40 passwd
= getpwuid(getuid());
42 passwd
= getpwnam(user
);
46 len
= strlen(passwd
->pw_dir
);
47 home
= xnew(char, len
+ 2);
48 memcpy(home
, passwd
->pw_dir
, len
);
54 static char *get_full_dir_name(const char *dir
)
60 } else if (dir
[0] == '~') {
61 char *first_slash
, *tmp
, *home
;
63 first_slash
= strchr(dir
, '/');
64 tmp
= xstrndup(dir
, first_slash
- dir
);
65 home
= get_home(tmp
+ 1);
69 full
= xstrjoin(home
, first_slash
);
78 * load all directory entries from directory 'dir' starting with 'start' and
79 * filtered with 'filter'
81 static void tabexp_load_dir(const char *dirname
, const char *start
,
82 int (*filter
)(const char *, const struct stat
*))
84 int start_len
= strlen(start
);
90 /* tabexp is reseted */
91 full_dir_name
= get_full_dir_name(dirname
);
95 if (dir_open(&dir
, full_dir_name
))
98 while ((name
= dir_read(&dir
))) {
105 if (strncmp(name
, start
, start_len
))
109 if (!filter(name
, &dir
.st
))
112 if (S_ISDIR(dir
.st
.st_mode
)) {
113 int len
= strlen(name
);
115 str
= xnew(char, len
+ 2);
116 memcpy(str
, name
, len
);
122 ptr_array_add(&array
, str
);
126 ptr_array_sort(&array
, strptrcmp
);
127 ptr_array_plug(&array
);
129 tabexp
.head
= xstrdup(dirname
);
130 tabexp
.tails
= array
.ptrs
;
136 void expand_files_and_dirs(const char *src
,
137 int (*filter
)(const char *name
, const struct stat
*s
))
141 /* split src to dir and file */
142 slash
= strrchr(src
, '/');
148 dir
= xstrndup(src
, slash
- src
+ 1);
150 /* get all dentries starting with file from dir */
151 tabexp_load_dir(dir
, file
, filter
);
155 char *home
= get_home(src
+ 1);
158 tabexp
.head
= xstrdup("");
159 tabexp
.tails
= xnew(char *, 2);
160 tabexp
.tails
[0] = home
;
161 tabexp
.tails
[1] = NULL
;
164 tabexp_load_dir("", src
, filter
);