ccanlint: add test to look for modules we use but don't list in _info.
[ccan] / tools / ccanlint / ccanlint.c
1 /*
2  * ccanlint: assorted checks and advice for a ccan package
3  * Copyright (C) 2008 Rusty Russell, Idris Soule
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the Free
7  * Software Foundation; either version 2 of the License, or (at your option)
8  * any later version.
9  *
10  *   This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 51
17  * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 #include "ccanlint.h"
20 #include "../tools.h"
21 #include <unistd.h>
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <err.h>
27 #include <ctype.h>
28 #include <ccan/btree/btree.h>
29 #include <ccan/str/str.h>
30 #include <ccan/str_talloc/str_talloc.h>
31 #include <ccan/talloc/talloc.h>
32 #include <ccan/opt/opt.h>
33
34 int verbose = 0;
35 static LIST_HEAD(compulsory_tests);
36 static LIST_HEAD(normal_tests);
37 static LIST_HEAD(finished_tests);
38 bool safe_mode = false;
39 static struct btree *cmdline_exclude;
40 static struct btree *info_exclude;
41 static unsigned int timeout;
42
43 #if 0
44 static void indent_print(const char *string)
45 {
46         while (*string) {
47                 unsigned int line = strcspn(string, "\n");
48                 printf("\t%.*s", line, string);
49                 if (string[line] == '\n') {
50                         printf("\n");
51                         line++;
52                 }
53                 string += line;
54         }
55 }
56 #endif
57
58 bool ask(const char *question)
59 {
60         char reply[2];
61
62         printf("%s ", question);
63         fflush(stdout);
64
65         return fgets(reply, sizeof(reply), stdin) != NULL
66                 && toupper(reply[0]) == 'Y';
67 }
68
69 static const char *should_skip(struct manifest *m, struct ccanlint *i)
70 {
71         if (btree_lookup(cmdline_exclude, i->key))
72                 return "excluded on command line";
73
74         if (btree_lookup(info_exclude, i->key))
75                 return "excluded in _info file";
76         
77         if (i->skip_fail)
78                 return "dependency failed";
79
80         if (i->skip)
81                 return "dependency was skipped";
82
83         if (i->can_run)
84                 return i->can_run(m);
85         return NULL;
86 }
87
88 static bool run_test(struct ccanlint *i,
89                      bool quiet,
90                      unsigned int *score,
91                      unsigned int *total_score,
92                      struct manifest *m)
93 {
94         void *result;
95         unsigned int this_score, max_score, timeleft;
96         const struct dependent *d;
97         const char *skip;
98         bool bad, good;
99
100         //one less test to run through
101         list_for_each(&i->dependencies, d, node)
102                 d->dependent->num_depends--;
103
104         skip = should_skip(m, i);
105
106         if (skip) {
107         skip:
108                 if (verbose)
109                         printf("  %s: skipped (%s)\n", i->name, skip);
110
111                 /* If we're skipping this because a prereq failed, we fail. */
112                 if (i->skip_fail)
113                         *total_score += i->total_score;
114                         
115                 list_del(&i->list);
116                 list_add_tail(&finished_tests, &i->list);
117                 list_for_each(&i->dependencies, d, node) {
118                         d->dependent->skip = true;
119                         d->dependent->skip_fail = i->skip_fail;
120                 }
121                 return true;
122         }
123
124         timeleft = timeout ? timeout : default_timeout_ms;
125         result = i->check(m, i->keep_results, &timeleft);
126         if (timeout && timeleft == 0) {
127                 skip = "timeout";
128                 goto skip;
129         }
130
131         max_score = i->total_score;
132         if (!max_score)
133                 max_score = 1;
134
135         if (!result)
136                 this_score = max_score;
137         else if (i->score)
138                 this_score = i->score(m, result);
139         else
140                 this_score = 0;
141
142         bad = (this_score == 0);
143         good = (this_score >= max_score);
144
145         if (verbose || (!good && !quiet)) {
146                 printf("  %s: %s", i->name,
147                        bad ? "FAIL" : good ? "PASS" : "PARTIAL");
148                 if (max_score > 1)
149                         printf(" (+%u/%u)", this_score, max_score);
150                 printf("\n");
151         }
152
153         if (!quiet && result) {
154                 const char *desc;
155                 if (i->describe && (desc = i->describe(m, result)) != NULL) 
156                         printf("    %s\n", desc);
157                 if (i->handle)
158                         i->handle(m, result);
159         }
160
161         if (i->total_score) {
162                 *score += this_score;
163                 *total_score += i->total_score;
164         }
165
166         list_del(&i->list);
167         list_add_tail(&finished_tests, &i->list);
168
169         if (bad) {
170                 /* Skip any tests which depend on this one. */
171                 list_for_each(&i->dependencies, d, node) {
172                         d->dependent->skip = true;
173                         d->dependent->skip_fail = true;
174                 }
175         }
176         return good;
177 }
178
179 static void register_test(struct list_head *h, struct ccanlint *test, ...)
180 {
181         va_list ap;
182         struct ccanlint *depends;
183         struct dependent *dchild;
184
185         list_add(h, &test->list);
186
187         va_start(ap, test);
188         /* Careful: we might have been initialized by a dependent. */
189         if (test->dependencies.n.next == NULL)
190                 list_head_init(&test->dependencies);
191
192         //dependent(s) args (if any), last one is NULL
193         while ((depends = va_arg(ap, struct ccanlint *)) != NULL) {
194                 dchild = malloc(sizeof(*dchild));
195                 dchild->dependent = test;
196                 /* The thing we depend on might not be initialized yet! */
197                 if (depends->dependencies.n.next == NULL)
198                         list_head_init(&depends->dependencies);
199                 list_add_tail(&depends->dependencies, &dchild->node);
200                 test->num_depends++;
201         }
202         va_end(ap);
203 }
204
205 /**
206  * get_next_test - retrieves the next test to be processed
207  **/
208 static inline struct ccanlint *get_next_test(struct list_head *test)
209 {
210         struct ccanlint *i;
211
212         if (list_empty(test))
213                 return NULL;
214
215         list_for_each(test, i, list) {
216                 if (i->num_depends == 0)
217                         return i;
218         }
219         errx(1, "Can't make process; test dependency cycle");
220 }
221
222 static void init_tests(void)
223 {
224         const struct ccanlint *i;
225         struct btree *keys, *names;
226
227 #undef REGISTER_TEST
228 #define REGISTER_TEST(name, ...) register_test(&normal_tests, &name, __VA_ARGS__, NULL)
229 #include "generated-normal-tests"
230 #undef REGISTER_TEST
231 #define REGISTER_TEST(name, ...) register_test(&compulsory_tests, &name, __VA_ARGS__, NULL)
232 #include "generated-compulsory-tests"
233
234         /* Self-consistency check: make sure no two tests
235            have the same key or name. */
236         keys = btree_new(btree_strcmp);
237         names = btree_new(btree_strcmp);
238         list_for_each(&compulsory_tests, i, list) {
239                 if (!btree_insert(keys, i->key))
240                         errx(1, "BUG: Duplicate test key '%s'", i->key);
241                 if (!btree_insert(keys, i->name))
242                         errx(1, "BUG: Duplicate test name '%s'", i->name);
243         }
244         list_for_each(&normal_tests, i, list) {
245                 if (!btree_insert(keys, i->key))
246                         errx(1, "BUG: Duplicate test key '%s'", i->key);
247                 if (!btree_insert(keys, i->name))
248                         errx(1, "BUG: Duplicate test name '%s'", i->name);
249         }
250         btree_delete(keys);
251         btree_delete(names);
252         
253         if (!verbose)
254                 return;
255
256         printf("\nCompulsory Tests\n");
257         list_for_each(&compulsory_tests, i, list) {
258                 printf("%s depends on %u others\n", i->name, i->num_depends);
259                 if (!list_empty(&i->dependencies)) {
260                         const struct dependent *d;
261                         printf("These depend on us:\n");
262                         list_for_each(&i->dependencies, d, node)
263                                 printf("\t%s\n", d->dependent->name);
264                 }
265         }
266
267         printf("\nNormal Tests\n");
268         list_for_each(&normal_tests, i, list) {
269                 printf("%s depends on %u others\n", i->name, i->num_depends);
270                 if (!list_empty(&i->dependencies)) {
271                         const struct dependent *d;
272                         printf("These depend on us:\n");
273                         list_for_each(&i->dependencies, d, node)
274                                 printf("\t%s\n", d->dependent->name);
275                 }
276         }
277 }
278
279 static struct ccanlint *find_test(const char *key)
280 {
281         struct ccanlint *i;
282
283         list_for_each(&compulsory_tests, i, list)
284                 if (streq(i->key, key))
285                         return i;
286
287         list_for_each(&normal_tests, i, list)
288                 if (streq(i->key, key))
289                         return i;
290
291         return NULL;
292 }
293
294 static char *keep_test(const char *testname, void *unused)
295 {
296         struct ccanlint *i = find_test(testname);
297         if (!i)
298                 errx(1, "No test %s to --keep", testname);
299         i->keep_results = true;
300         return NULL;
301 }
302
303 static char *skip_test(const char *testname, void *unused)
304 {
305         btree_insert(cmdline_exclude, optarg);
306         return NULL;
307 }
308
309 static void print_tests(struct list_head *tests, const char *type)
310 {
311         struct ccanlint *i;
312
313         printf("%s tests:\n", type);
314         /* This makes them print in topological order. */
315         while ((i = get_next_test(tests)) != NULL) {
316                 const struct dependent *d;
317                 printf("   %-25s %s\n", i->key, i->name);
318                 list_del(&i->list);
319                 list_for_each(&i->dependencies, d, node)
320                         d->dependent->num_depends--;
321         }
322 }
323
324 static char *list_tests(void *arg)
325 {
326         print_tests(&compulsory_tests, "Compulsory");
327         print_tests(&normal_tests, "Normal");
328         exit(0);
329 }
330
331 static char *strip(const void *ctx, const char *line)
332 {
333         line += strcspn(line, IDENT_CHARS "-");
334         return talloc_strndup(ctx, line, strspn(line, IDENT_CHARS "-"));
335 }
336
337 static void add_info_fails(struct ccan_file *info)
338 {
339         struct doc_section *d;
340         unsigned int i;
341
342         list_for_each(get_ccan_file_docs(info), d, list) {
343                 if (!streq(d->type, "fails"))
344                         continue;
345
346                 for (i = 0; i < d->num_lines; i++)
347                         btree_insert(info_exclude, strip(info, d->lines[i]));
348                 break;
349         }
350 }
351
352 int main(int argc, char *argv[])
353 {
354         bool summary = false;
355         unsigned int score = 0, total_score = 0;
356         struct manifest *m;
357         struct ccanlint *i;
358         const char *prefix = "";
359         char *dir = talloc_getcwd(NULL), *base_dir = dir;
360         
361         init_tests();
362
363         cmdline_exclude = btree_new(btree_strcmp);
364         info_exclude = btree_new(btree_strcmp);
365
366         opt_register_arg("--dir|-d", opt_set_charp, opt_show_charp, &dir,
367                          "use this directory");
368         opt_register_noarg("-n|--safe-mode", opt_set_bool, &safe_mode,
369                          "do not compile anything");
370         opt_register_noarg("-l|--list-tests", list_tests, NULL,
371                          "list tests ccanlint performs (and exit)");
372         opt_register_arg("-k|--keep <testname>", keep_test, NULL, NULL,
373                            "keep results of <testname> (can be used multiple times)");
374         opt_register_noarg("--summary|-s", opt_set_bool, &summary,
375                            "simply give one line summary");
376         opt_register_noarg("--verbose|-v", opt_inc_intval, &verbose,
377                            "verbose mode (can specify more than once)");
378         opt_register_arg("-x|--exclude <testname>", skip_test, NULL, NULL,
379                          "exclude <testname> (can be used multiple times)");
380         opt_register_arg("-t|--timeout <milleseconds>", opt_set_uintval,
381                          NULL, &timeout,
382                          "ignore (terminate) tests that are slower than this");
383         opt_register_noarg("-?|-h|--help", opt_usage_and_exit,
384                            "\nA program for checking and guiding development"
385                            " of CCAN modules.",
386                            "This usage message");
387
388         opt_parse(&argc, argv, opt_log_stderr_exit);
389
390         if (dir[0] != '/')
391                 dir = talloc_asprintf_append(NULL, "%s/%s", base_dir, dir);
392         if (dir != base_dir)
393                 prefix = talloc_append_string(talloc_basename(NULL, dir), ": ");
394         if (verbose >= 2)
395                 compile_verbose = true;
396         if (verbose >= 3)
397                 tools_verbose = true;
398
399         /* We move into temporary directory, so gcov dumps its files there. */
400         if (chdir(temp_dir(talloc_autofree_context())) != 0)
401                 err(1, "Error changing to %s temporary dir", temp_dir(NULL));
402
403         m = get_manifest(talloc_autofree_context(), dir);
404
405         /* Create a symlink from temp dir back to src dir's test directory. */
406         if (symlink(talloc_asprintf(m, "%s/test", dir),
407                     talloc_asprintf(m, "%s/test", temp_dir(NULL))) != 0)
408                 err(1, "Creating test symlink in %s", temp_dir(NULL));
409
410         /* If you don't pass the compulsory tests, you get a score of 0. */
411         if (verbose)
412                 printf("Compulsory tests:\n");
413
414         while ((i = get_next_test(&compulsory_tests)) != NULL) {
415                 if (!run_test(i, summary, &score, &total_score, m)) {
416                         printf("%sTotal score: 0/%u\n", prefix, total_score);
417                         errx(1, "%s%s failed", prefix, i->name);
418                 }
419         }
420
421         add_info_fails(m->info_file);
422
423         if (verbose)
424                 printf("\nNormal tests:\n");
425         while ((i = get_next_test(&normal_tests)) != NULL)
426                 run_test(i, summary, &score, &total_score, m);
427
428         printf("%sTotal score: %u/%u\n", prefix, score, total_score);
429         return 0;
430 }