log
[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 EC_LOG_TYPE_REGISTER(node_file);
49
50 struct ec_node_file {
51         struct ec_node gen;
52 };
53
54 static int
55 ec_node_file_parse(const struct ec_node *gen_node,
56                 struct ec_parsed *state,
57                 const struct ec_strvec *strvec)
58 {
59         (void)gen_node;
60         (void)state;
61
62         if (ec_strvec_len(strvec) == 0)
63                 return EC_PARSED_NOMATCH;
64
65         return 1;
66 }
67
68 /*
69  * Almost the same than dirname (3) and basename (3) except that:
70  * - it always returns a substring of the given path, which can
71  *   be empty.
72  * - the behavior is different when the path finishes with a '/'
73  * - the path argument is not modified
74  * - the outputs are allocated and must be freed with ec_free().
75  *
76  *   path       dirname   basename       split_path
77  *   /usr/lib   /usr      lib          /usr/     lib
78  *   /usr/      /         usr          /usr/
79  *   usr        .         usr                    usr
80  *   /          /         /            /
81  *   .          .         .                      .
82  *   ..         .         ..                     ..
83  */
84 static int split_path(const char *path, char **dname_p, char **bname_p)
85 {
86         char *last_slash;
87         size_t dirlen;
88         char *dname, *bname;
89
90         *dname_p = NULL;
91         *bname_p = NULL;
92
93         last_slash = strrchr(path, '/');
94         if (last_slash == NULL)
95                 dirlen = 0;
96         else
97                 dirlen = last_slash - path + 1;
98
99         dname = ec_strdup(path);
100         if (dname == NULL)
101                 return -ENOMEM;
102         dname[dirlen] = '\0';
103
104         bname = ec_strdup(path + dirlen);
105         if (bname == NULL) {
106                 ec_free(dname);
107                 return -ENOMEM;
108         }
109
110         *dname_p = dname;
111         *bname_p = bname;
112
113         return 0;
114 }
115
116 static int
117 ec_node_file_complete(const struct ec_node *gen_node,
118                 struct ec_completed *completed,
119                 struct ec_parsed *state,
120                 const struct ec_strvec *strvec)
121 {
122         struct ec_completed_item *item = NULL;
123         struct stat st;
124         const char *input;
125         size_t bname_len;
126         struct dirent *de = NULL;
127         DIR *dir = NULL;
128         char *dname = NULL, *bname = NULL, *effective_dir;
129         char *comp_str = NULL;
130         char *disp_str = NULL;
131         int ret;
132         int is_dir = 0;
133
134         /*
135          * Example with this file tree:
136          * /
137          * ├── dir1
138          * │   ├── file1
139          * │   ├── file2
140          * │   └── subdir
141          * │       └── file3
142          * ├── dir2
143          * │   └── file4
144          * └── file5
145          *
146          * Input     Output completions
147          *   /       [dir1/, dir2/, file5]
148          *   /d      [dir1/, dir2/]
149          *   /f      [file5]
150          *   /dir1/  [file1, file2, subdir/]
151          *
152          *
153          *
154          */
155
156         if (ec_strvec_len(strvec) != 1)
157                 goto out;
158
159         input = ec_strvec_val(strvec, 0);
160         ret = split_path(input, &dname, &bname);
161         if (ret < 0) {
162                 ec_completed_free(completed);
163                 completed = NULL;
164                 goto out;
165         }
166
167         if (strcmp(dname, "") == 0)
168                 effective_dir = ".";
169         else
170                 effective_dir = dname;
171
172         ret = lstat(effective_dir, &st);
173         if (ret != 0) {
174                 ret = -errno;
175                 goto out;
176         }
177         if (!S_ISDIR(st.st_mode))
178                 goto out;
179
180         dir = opendir(effective_dir);
181         if (dir == NULL)
182                 goto out;
183
184         bname_len = strlen(bname);
185         while (1) {
186                 de = readdir(dir);
187                 if (de == NULL)
188                         goto out;
189
190                 if (!ec_str_startswith(de->d_name, bname))
191                         continue;
192                 if (bname[0] != '.' && de->d_name[0] == '.')
193                         continue;
194
195                 /* add '/' if it's a dir */
196                 if (de->d_type == DT_DIR) {
197                         is_dir = 1;
198                 } else if (de->d_type == DT_UNKNOWN) { // XXX todo
199                 } else {
200                         is_dir = 0;
201                 }
202
203                 item = ec_completed_item(state, gen_node);
204                 if (item == NULL) {
205                         ret = -ENOMEM;
206                         goto out;
207                 }
208
209                 if (is_dir) {
210                         if (asprintf(&comp_str, "%s%s/", input,
211                                         &de->d_name[bname_len]) < 0) {
212                                 ret = -errno;
213                                 goto out;
214                         }
215                         if (asprintf(&disp_str, "%s/", de->d_name) < 0) {
216                                 ret = -errno;
217                                 goto out;
218                         }
219                         ret = ec_completed_item_set(item, EC_PARTIAL_MATCH,
220                                                 comp_str);
221                         if (ret < 0)
222                                 goto out;
223                 } else {
224                         if (asprintf(&comp_str, "%s%s", input,
225                                         &de->d_name[bname_len]) < 0) {
226                                 ret = -errno;
227                                 goto out;
228                         }
229                         if (asprintf(&disp_str, "%s", de->d_name) < 0) {
230                                 ret = -errno;
231                                 goto out;
232                         }
233                         ret = ec_completed_item_set(item, EC_MATCH,
234                                                 comp_str);
235                         if (ret < 0)
236                                 goto out;
237                 }
238                 ret = ec_completed_item_set_display(item, disp_str);
239                 if (ret < 0)
240                         goto out;
241                 ret = ec_completed_item_add(completed, item);
242                 if (ret < 0)
243                         goto out;
244
245                 item = NULL;
246                 free(comp_str);
247                 comp_str = NULL;
248                 free(disp_str);
249                 disp_str = NULL;
250         }
251         ret = 0;
252
253 out:
254         ec_completed_item_free(item);
255         free(comp_str);
256         free(disp_str);
257         ec_free(dname);
258         ec_free(bname);
259         if (dir != NULL)
260                 closedir(dir);
261
262         return ret;
263 }
264
265 static struct ec_node_type ec_node_file_type = {
266         .name = "file",
267         .parse = ec_node_file_parse,
268         .complete = ec_node_file_complete,
269         .size = sizeof(struct ec_node_file),
270 };
271
272 EC_NODE_TYPE_REGISTER(ec_node_file_type);
273
274 /* LCOV_EXCL_START */
275 static int ec_node_file_testcase(void)
276 {
277         struct ec_node *node;
278         int ret = 0;
279
280         node = ec_node("file", NULL);
281         if (node == NULL) {
282                 EC_LOG(EC_LOG_ERR, "cannot create node\n");
283                 return -1;
284         }
285         /* any string matches */
286         ret |= EC_TEST_CHECK_PARSE(node, 1, "foo");
287         ret |= EC_TEST_CHECK_PARSE(node, 1, "/tmp/bar");
288         ret |= EC_TEST_CHECK_PARSE(node, -1);
289
290         /* test completion */
291 #if 0 // XXX how to properly test file completion?
292         ret |= EC_TEST_CHECK_COMPLETE(node,
293                 EC_NODE_ENDLIST,
294                 EC_NODE_ENDLIST);
295         ret |= EC_TEST_CHECK_COMPLETE(node,
296                 "", EC_NODE_ENDLIST,
297                 EC_NODE_ENDLIST);
298         ret |= EC_TEST_CHECK_COMPLETE(node,
299                 "/", EC_NODE_ENDLIST,
300                 EC_NODE_ENDLIST);
301         ret |= EC_TEST_CHECK_COMPLETE(node,
302                 "/tmp", EC_NODE_ENDLIST,
303                 EC_NODE_ENDLIST);
304         ret |= EC_TEST_CHECK_COMPLETE(node,
305                 "/tmp/", EC_NODE_ENDLIST,
306                 EC_NODE_ENDLIST);
307         ret |= EC_TEST_CHECK_COMPLETE(node,
308                 "/tmp/.", EC_NODE_ENDLIST,
309                 EC_NODE_ENDLIST);
310 #endif
311         ec_node_free(node);
312
313         return ret;
314 }
315 /* LCOV_EXCL_STOP */
316
317 static struct ec_test ec_node_file_test = {
318         .name = "node_file",
319         .test = ec_node_file_testcase,
320 };
321
322 EC_TEST_REGISTER(ec_node_file_test);