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