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