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