save
[protos/libecoli.git] / lib / ecoli_node_file.c
1 /*
2  * Copyright (c) 2016, Olivier MATZ <zer0@droids-corp.org>
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  *     * Redistributions of source code must retain the above copyright
8  *       notice, this list of conditions and the following disclaimer.
9  *     * Redistributions in binary form must reproduce the above copyright
10  *       notice, this list of conditions and the following disclaimer in the
11  *       documentation and/or other materials provided with the distribution.
12  *     * Neither the name of the University of California, Berkeley nor the
13  *       names of its contributors may be used to endorse or promote products
14  *       derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
20  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #define _GNU_SOURCE /* for asprintf */
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <unistd.h>
36 #include <dirent.h>
37
38 #include <ecoli_log.h>
39 #include <ecoli_malloc.h>
40 #include <ecoli_test.h>
41 #include <ecoli_strvec.h>
42 #include <ecoli_string.h>
43 #include <ecoli_node.h>
44 #include <ecoli_parsed.h>
45 #include <ecoli_completed.h>
46 #include <ecoli_node_file.h>
47
48 struct ec_node_file {
49         struct ec_node gen;
50 };
51
52 static int
53 ec_node_file_parse(const struct ec_node *gen_node,
54                 struct ec_parsed *state,
55                 const struct ec_strvec *strvec)
56 {
57         (void)gen_node;
58         (void)state;
59
60         if (ec_strvec_len(strvec) == 0)
61                 return EC_PARSED_NOMATCH;
62
63         return 1;
64 }
65
66 /*
67  * Almost the same than dirname (3) and basename (3) except that:
68  * - it always returns a substring of the given path, which can
69  *   be empty.
70  * - the behavior is different when the path finishes with a '/'
71  * - the path argument is not modified
72  * - the outputs are allocated and must be freed with ec_free().
73  *
74  *   path       dirname   basename       split_path
75  *   /usr/lib   /usr      lib          /usr/     lib
76  *   /usr/      /         usr          /usr/
77  *   usr        .         usr                    usr
78  *   /          /         /            /
79  *   .          .         .                      .
80  *   ..         .         ..                     ..
81  */
82 static int split_path(const char *path, char **dname_p, char **bname_p)
83 {
84         char *last_slash;
85         size_t dirlen;
86         char *dname, *bname;
87
88         *dname_p = NULL;
89         *bname_p = NULL;
90
91         last_slash = strrchr(path, '/');
92         if (last_slash == NULL)
93                 dirlen = 0;
94         else
95                 dirlen = last_slash - path + 1;
96
97         dname = ec_strdup(path);
98         if (dname == NULL)
99                 return -ENOMEM;
100         dname[dirlen] = '\0';
101
102         bname = ec_strdup(path + dirlen);
103         if (bname == NULL) {
104                 ec_free(dname);
105                 return -ENOMEM;
106         }
107
108         *dname_p = dname;
109         *bname_p = bname;
110
111         return 0;
112 }
113
114 static int
115 ec_node_file_complete(const struct ec_node *gen_node,
116                 struct ec_completed *completed,
117                 struct ec_parsed *state,
118                 const struct ec_strvec *strvec)
119 {
120         struct ec_completed_item *item = NULL;
121         struct stat st;
122         const char *input;
123         size_t bname_len;
124         struct dirent *de = NULL;
125         DIR *dir = NULL;
126         char *dname = NULL, *bname = NULL, *effective_dir;
127         char *comp_str = NULL;
128         char *disp_str = NULL;
129         int ret;
130         int is_dir = 0;
131
132         /*
133          * Example with this file tree:
134          * /
135          * ├── dir1
136          * │   ├── file1
137          * │   ├── file2
138          * │   └── subdir
139          * │       └── file3
140          * ├── dir2
141          * │   └── file4
142          * └── file5
143          *
144          * Input     Output completions
145          *   /       [dir1/, dir2/, file5]
146          *   /d      [dir1/, dir2/]
147          *   /f      [file5]
148          *   /dir1/  [file1, file2, subdir/]
149          *
150          *
151          *
152          */
153
154         if (ec_strvec_len(strvec) != 1)
155                 goto out;
156
157         input = ec_strvec_val(strvec, 0);
158         ret = split_path(input, &dname, &bname);
159         if (ret < 0) {
160                 ec_completed_free(completed);
161                 completed = NULL;
162                 goto out;
163         }
164
165         if (strcmp(dname, "") == 0)
166                 effective_dir = ".";
167         else
168                 effective_dir = dname;
169
170         ret = lstat(effective_dir, &st);
171         if (ret != 0) {
172                 ret = -errno;
173                 goto out;
174         }
175         if (!S_ISDIR(st.st_mode))
176                 goto out;
177
178         dir = opendir(effective_dir);
179         if (dir == NULL)
180                 goto out;
181
182         bname_len = strlen(bname);
183         while (1) {
184                 de = readdir(dir);
185                 if (de == NULL)
186                         goto out;
187
188                 if (!ec_str_startswith(de->d_name, bname))
189                         continue;
190                 if (bname[0] != '.' && de->d_name[0] == '.')
191                         continue;
192
193                 /* add '/' if it's a dir */
194                 if (de->d_type == DT_DIR) {
195                         is_dir = 1;
196                 } else if (de->d_type == DT_UNKNOWN) { // XXX todo
197                 } else {
198                         is_dir = 0;
199                 }
200
201                 item = ec_completed_item(state, gen_node);
202                 if (item == NULL) {
203                         ret = -ENOMEM;
204                         goto out;
205                 }
206
207                 if (is_dir) {
208                         if (asprintf(&comp_str, "%s%s/", input,
209                                         &de->d_name[bname_len]) < 0) {
210                                 ret = -errno;
211                                 goto out;
212                         }
213                         if (asprintf(&disp_str, "%s/", de->d_name) < 0) {
214                                 ret = -errno;
215                                 goto out;
216                         }
217                         ret = ec_completed_item_set(item, EC_PARTIAL_MATCH,
218                                                 comp_str);
219                         if (ret < 0)
220                                 goto out;
221                 } else {
222                         if (asprintf(&comp_str, "%s%s", input,
223                                         &de->d_name[bname_len]) < 0) {
224                                 ret = -errno;
225                                 goto out;
226                         }
227                         if (asprintf(&disp_str, "%s", de->d_name) < 0) {
228                                 ret = -errno;
229                                 goto out;
230                         }
231                         ret = ec_completed_item_set(item, EC_MATCH,
232                                                 comp_str);
233                         if (ret < 0)
234                                 goto out;
235                 }
236                 ret = ec_completed_item_set_display(item, disp_str);
237                 if (ret < 0)
238                         goto out;
239                 ret = ec_completed_item_add(completed, item);
240                 if (ret < 0)
241                         goto out;
242
243                 item = NULL;
244                 free(comp_str);
245                 comp_str = NULL;
246                 free(disp_str);
247                 disp_str = NULL;
248         }
249         ret = 0;
250
251 out:
252         ec_completed_item_free(item);
253         free(comp_str);
254         free(disp_str);
255         ec_free(dname);
256         ec_free(bname);
257         if (dir != NULL)
258                 closedir(dir);
259
260         return ret;
261 }
262
263 static struct ec_node_type ec_node_file_type = {
264         .name = "file",
265         .parse = ec_node_file_parse,
266         .complete = ec_node_file_complete,
267         .size = sizeof(struct ec_node_file),
268 };
269
270 EC_NODE_TYPE_REGISTER(ec_node_file_type);
271
272 /* LCOV_EXCL_START */
273 static int ec_node_file_testcase(void)
274 {
275         struct ec_node *node;
276         int ret = 0;
277
278         node = ec_node("file", NULL);
279         if (node == NULL) {
280                 ec_log(EC_LOG_ERR, "cannot create node\n");
281                 return -1;
282         }
283         /* any string matches */
284         ret |= EC_TEST_CHECK_PARSE(node, 1, "foo");
285         ret |= EC_TEST_CHECK_PARSE(node, 1, "/tmp/bar");
286         ret |= EC_TEST_CHECK_PARSE(node, -1);
287
288         /* test completion */
289 #if 0 // XXX how to properly test file completion?
290         ret |= EC_TEST_CHECK_COMPLETE(node,
291                 EC_NODE_ENDLIST,
292                 EC_NODE_ENDLIST);
293         ret |= EC_TEST_CHECK_COMPLETE(node,
294                 "", EC_NODE_ENDLIST,
295                 EC_NODE_ENDLIST);
296         ret |= EC_TEST_CHECK_COMPLETE(node,
297                 "/", EC_NODE_ENDLIST,
298                 EC_NODE_ENDLIST);
299         ret |= EC_TEST_CHECK_COMPLETE(node,
300                 "/tmp", EC_NODE_ENDLIST,
301                 EC_NODE_ENDLIST);
302         ret |= EC_TEST_CHECK_COMPLETE(node,
303                 "/tmp/", EC_NODE_ENDLIST,
304                 EC_NODE_ENDLIST);
305         ret |= EC_TEST_CHECK_COMPLETE(node,
306                 "/tmp/.", EC_NODE_ENDLIST,
307                 EC_NODE_ENDLIST);
308 #endif
309         ec_node_free(node);
310
311         return ret;
312 }
313 /* LCOV_EXCL_STOP */
314
315 static struct ec_test ec_node_file_test = {
316         .name = "node_file",
317         .test = ec_node_file_testcase,
318 };
319
320 EC_TEST_REGISTER(ec_node_file_test);