ccanlint: Alter meaning of --summary option
[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 "../read_config_header.h"
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <err.h>
28 #include <ctype.h>
29 #include <ccan/str/str.h>
30 #include <ccan/take/take.h>
31 #include <ccan/opt/opt.h>
32 #include <ccan/foreach/foreach.h>
33 #include <ccan/cast/cast.h>
34 #include <ccan/tlist/tlist.h>
35 #include <ccan/tal/path/path.h>
36 #include <ccan/strmap/strmap.h>
37
38 typedef STRMAP(struct ccanlint *) ccanlint_map_t;
39
40 int verbose = 0;
41 static ccanlint_map_t tests;
42 bool safe_mode = false;
43 bool keep_results = false;
44 bool non_ccan_deps = false;
45 bool build_failed = false;
46 static bool targeting = false;
47 static unsigned int timeout;
48
49 const char *config_header;
50
51 const char *ccan_dir;
52
53 #if 0
54 static void indent_print(const char *string)
55 {
56         while (*string) {
57                 unsigned int line = strcspn(string, "\n");
58                 printf("\t%.*s", line, string);
59                 if (string[line] == '\n') {
60                         printf("\n");
61                         line++;
62                 }
63                 string += line;
64         }
65 }
66 #endif
67
68 bool ask(const char *question)
69 {
70         char reply[80];
71
72         printf("%s ", question);
73         fflush(stdout);
74
75         return fgets(reply, sizeof(reply), stdin) != NULL
76                 && toupper(reply[0]) == 'Y';
77 }
78
79 /* Skip, but don't remove. */
80 static bool skip_test(struct dgraph_node *node, const char *why)
81 {
82         struct ccanlint *c = container_of(node, struct ccanlint, node);
83         c->skip = why;
84         return true;
85 }
86
87 static const char *dep_failed(struct manifest *m UNNEEDED)
88 {
89         return "dependency couldn't run";
90 }
91
92 static bool cannot_run(struct dgraph_node *node, void *all UNNEEDED)
93 {
94         struct ccanlint *c = container_of(node, struct ccanlint, node);
95         c->can_run = dep_failed;
96
97         return true;
98 }
99
100 struct run_info {
101         bool noninteractive;
102         unsigned int score, total;
103         struct manifest *m;
104         const char *prefix;
105         bool pass;
106 };
107
108 static bool run_test(struct dgraph_node *n, struct run_info *run)
109 {
110         struct ccanlint *i = container_of(n, struct ccanlint, node);
111         unsigned int timeleft;
112         struct score *score;
113
114         if (i->done)
115                 return true;
116
117         score = tal(run->m, struct score);
118         list_head_init(&score->per_file_errors);
119         score->error = NULL;
120         score->pass = false;
121         score->score = 0;
122         score->total = 1;
123
124         /* We can see skipped things in two cases:
125          * (1) _info excluded them (presumably because they fail).
126          * (2) A prerequisite failed.
127          */
128         if (i->skip) {
129                 if (verbose)
130                         printf("%s%s: skipped (%s)\n",
131                                run->prefix, i->name, i->skip);
132                 /* Pass us up to the test which failed, not us. */
133                 score->pass = true;
134                 goto out;
135         }
136
137         if (i->can_run) {
138                 i->skip = i->can_run(run->m);
139                 if (i->skip) {
140                         /* Test doesn't apply, or can't run?  That's OK. */
141                         if (verbose > 1)
142                                 printf("%s%s: skipped (%s)\n",
143                                        run->prefix, i->name, i->skip);
144                         /* Mark our dependencies to skip. */
145                         dgraph_traverse_from(&i->node, cannot_run, NULL);
146                         score->pass = true;
147                         score->total = 0;
148                         goto out;
149                 }
150         }
151
152         timeleft = timeout ? timeout : default_timeout_ms;
153         i->check(run->m, &timeleft, score);
154         if (timeout && timeleft == 0) {
155                 i->skip = "timeout";
156                 if (verbose)
157                         printf("%s%s: skipped (%s)\n",
158                                run->prefix, i->name, i->skip);
159                 /* Mark our dependencies to skip. */
160                 dgraph_traverse_from(&i->node, skip_test,
161                                      "dependency timed out");
162                 score->pass = true;
163                 score->total = 0;
164                 goto out;
165         }
166
167         assert(score->score <= score->total);
168         if (!score->pass
169             || (score->score < score->total && verbose)
170             || verbose > 1) {
171                 printf("%s%s (%s): %s",
172                        run->prefix, i->name, i->key,
173                        score->pass ? "PASS" : "FAIL");
174                 if (score->total > 1)
175                         printf(" (+%u/%u)", score->score, score->total);
176                 printf("\n");
177         }
178
179         if (!score->pass || verbose) {
180                 if (score->error) {
181                         printf("%s%s", score->error,
182                                strends(score->error, "\n") ? "" : "\n");
183                 }
184         }
185         if (!run->noninteractive && score->score < score->total && i->handle)
186                 i->handle(run->m, score);
187
188         if (!score->pass) {
189                 /* Skip any tests which depend on this one. */
190                 dgraph_traverse_from(&i->node, skip_test, "dependency failed");
191         }
192
193 out:
194         run->score += score->score;
195         run->total += score->total;
196
197         /* FIXME: Free score. */
198         run->pass &= score->pass;
199         i->done = true;
200
201         if (!score->pass && i->compulsory) {
202                 warnx("%s%s failed", run->prefix, i->name);
203                 run->score = 0;
204                 return false;
205         }
206         return true;
207 }
208
209 static void register_test(struct ccanlint *test)
210 {
211         if (!strmap_add(&tests, test->key, test))
212                 err(1, "Adding test %s", test->key);
213         test->options = tal_arr(NULL, char *, 1);
214         test->options[0] = NULL;
215         dgraph_init_node(&test->node);
216 }
217
218 static bool get_test(const char *member UNNEEDED, struct ccanlint *i,
219                      struct ccanlint **ret)
220 {
221         if (tlist_empty(&i->node.edge[DGRAPH_TO])) {
222                 *ret = i;
223                 return false;
224         }
225         return true;
226 }
227
228 /**
229  * get_next_test - retrieves the next test to be processed
230  **/
231 static inline struct ccanlint *get_next_test(void)
232 {
233         struct ccanlint *i = NULL;
234
235         strmap_iterate(&tests, get_test, &i);
236         if (i)
237                 return i;
238
239         if (strmap_empty(&tests))
240                 return NULL;
241
242         errx(1, "Can't make process; test dependency cycle");
243 }
244
245 static struct ccanlint *find_test(const char *key)
246 {
247         return strmap_get(&tests, key);
248 }
249
250 bool is_excluded(const char *name)
251 {
252         return find_test(name)->skip != NULL;
253 }
254
255 static bool init_deps(const char *member UNNEEDED,
256                       struct ccanlint *c, void *unused UNNEEDED)
257 {
258         char **deps = tal_strsplit(NULL, c->needs, " ", STR_EMPTY_OK);
259         unsigned int i;
260
261         for (i = 0; deps[i]; i++) {
262                 struct ccanlint *dep;
263
264                 dep = find_test(deps[i]);
265                 if (!dep)
266                         errx(1, "BUG: unknown dep '%s' for %s",
267                              deps[i], c->key);
268                 dgraph_add_edge(&dep->node, &c->node);
269         }
270         tal_free(deps);
271         return true;
272 }
273
274 static bool check_names(const char *member UNNEEDED, struct ccanlint *c,
275                         ccanlint_map_t *names)
276 {
277         if (!strmap_add(names, c->name, c))
278                 err(1, "Duplicate name %s", c->name);
279         return true;
280 }
281
282 static void init_tests(void)
283 {
284         ccanlint_map_t names;
285         struct ccanlint **table;
286         size_t i, num;
287
288         strmap_init(&tests);
289
290         table = autodata_get(ccanlint_tests, &num);
291         for (i = 0; i < num; i++)
292                 register_test(table[i]);
293         autodata_free(table);
294
295         strmap_iterate(&tests, init_deps, NULL);
296
297         /* Check for duplicate names. */
298         strmap_init(&names);
299         strmap_iterate(&tests, check_names, &names);
300         strmap_clear(&names);
301 }
302
303 static bool reset_test(struct dgraph_node *node, void *unused UNNEEDED)
304 {
305         struct ccanlint *c = container_of(node, struct ccanlint, node);
306         c->skip = NULL;
307         c->done = false;
308         return true;
309 }
310
311 static void reset_tests(struct dgraph_node *all)
312 {
313         dgraph_traverse_to(all, reset_test, NULL);
314 }
315
316 static bool print_deps(const char *member UNNEEDED,
317                        struct ccanlint *c, void *unused UNNEEDED)
318 {
319         if (!tlist_empty(&c->node.edge[DGRAPH_FROM])) {
320                 struct dgraph_edge *e;
321
322                 printf("These depend on %s:\n", c->key);
323                 dgraph_for_each_edge(&c->node, e, DGRAPH_FROM) {
324                         struct ccanlint *to = container_of(e->n[DGRAPH_TO],
325                                                            struct ccanlint,
326                                                            node);
327                         printf("\t%s\n", to->key);
328                 }
329         }
330         return true;
331 }
332
333 static void print_test_depends(void)
334 {
335         printf("Tests:\n");
336
337         strmap_iterate(&tests, print_deps, NULL);
338 }
339
340
341 static void show_tmpdir(const char *dir)
342 {
343         printf("You can find ccanlint working files in '%s'\n", dir);
344 }
345
346 static char *keep_tests(void *unused UNNEEDED)
347 {
348         keep_results = true;
349
350         /* Don't automatically destroy temporary dir. */
351         keep_temp_dir();
352         tal_add_destructor(temp_dir(), show_tmpdir);
353         return NULL;
354 }
355
356 static bool remove_test(struct dgraph_node *node, const char *why)
357 {
358         struct ccanlint *c = container_of(node, struct ccanlint, node);
359         c->skip = why;
360         dgraph_clear_node(node);
361         return true;
362 }
363
364 static char *exclude_test(const char *testname, void *unused UNNEEDED)
365 {
366         struct ccanlint *i = find_test(testname);
367         if (!i)
368                 return tal_fmt(NULL, "No test %s to --exclude", testname);
369
370         /* Remove this, and everything which depends on it. */
371         dgraph_traverse_from(&i->node, remove_test, "excluded on command line");
372         remove_test(&i->node, "excluded on command line");
373         return NULL;
374 }
375
376 static void skip_test_and_deps(struct ccanlint *c, const char *why)
377 {
378         /* Skip this, and everything which depends on us. */
379         dgraph_traverse_from(&c->node, skip_test, why);
380         skip_test(&c->node, why);
381 }
382
383 static char *list_tests(void *arg UNNEEDED)
384 {
385         struct ccanlint *i;
386
387         printf("Tests:\n");
388         /* This makes them print in topological order. */
389         while ((i = get_next_test()) != NULL) {
390                 printf("   %-25s %s\n", i->key, i->name);
391                 dgraph_clear_node(&i->node);
392                 strmap_del(&tests, i->key, NULL);
393         }
394         exit(0);
395 }
396
397 static bool draw_test(const char *member UNNEEDED,
398                       struct ccanlint *c, const char *style)
399 {
400         /*
401          * todo: escape labels in case ccanlint test keys have
402          *       characters interpreted as GraphViz syntax.
403          */
404         printf("\t\"%p\" [label=\"%s\"%s]\n", c, c->key, style);
405         return true;
406 }
407
408 static void test_dgraph_vertices(const char *style)
409 {
410         strmap_iterate(&tests, draw_test, style);
411 }
412
413 static bool draw_edges(const char *member UNNEEDED,
414                        struct ccanlint *c, void *unused UNNEEDED)
415 {
416         struct dgraph_edge *e;
417
418         dgraph_for_each_edge(&c->node, e, DGRAPH_FROM) {
419                 struct ccanlint *to = container_of(e->n[DGRAPH_TO],
420                                                    struct ccanlint,
421                                                    node);
422                 printf("\t\"%p\" -> \"%p\"\n", c->name, to->name);
423         }
424         return true;
425 }
426
427 static void test_dgraph_edges(void)
428 {
429         strmap_iterate(&tests, draw_edges, NULL);
430 }
431
432 static char *test_dependency_graph(void *arg UNNEEDED)
433 {
434         puts("digraph G {");
435
436         test_dgraph_vertices("");
437         test_dgraph_edges();
438
439         puts("}");
440
441         exit(0);
442 }
443
444 static void add_options(struct ccanlint *test, char **options,
445                         unsigned int num_options)
446 {
447         unsigned int num;
448
449         if (!test->options)
450                 num = 0;
451         else
452                 /* -1, because last one is NULL. */
453                 num = tal_count(test->options) - 1;
454
455         tal_resize(&test->options, num + num_options + 1);
456         memcpy(&test->options[num], options, (num_options + 1)*sizeof(char *));
457 }
458
459 void add_info_options(struct ccan_file *info)
460 {
461         struct doc_section *d;
462         unsigned int i;
463         struct ccanlint *test;
464
465         list_for_each(get_ccan_file_docs(info), d, list) {
466                 if (!streq(d->type, "ccanlint"))
467                         continue;
468
469                 for (i = 0; i < d->num_lines; i++) {
470                         char **words = tal_strsplit(d, d->lines[i], " \t",
471                                                     STR_NO_EMPTY);
472                         if (!words[0])
473                                 continue;
474
475                         if (strncmp(words[0], "//", 2) == 0)
476                                 continue;
477
478                         test = find_test(words[0]);
479                         if (!test) {
480                                 warnx("%s: unknown ccanlint test '%s'",
481                                       info->fullname, words[0]);
482                                 continue;
483                         }
484
485                         if (!words[1]) {
486                                 warnx("%s: no argument to test '%s'",
487                                       info->fullname, words[0]);
488                                 continue;
489                         }
490
491                         /* Known failure? */
492                         if (strcasecmp(words[1], "FAIL") == 0) {
493                                 if (!targeting)
494                                         skip_test_and_deps(test,
495                                                            "excluded in _info"
496                                                            " file");
497                         } else {
498                                 if (!test->takes_options)
499                                         warnx("%s: %s doesn't take options",
500                                               info->fullname, words[0]);
501                                 add_options(test, words+1, tal_count(words)-1);
502                         }
503                 }
504         }
505 }
506
507 /* If options are of form "filename:<option>" they only apply to that file */
508 char **per_file_options(const struct ccanlint *test, struct ccan_file *f)
509 {
510         char **ret;
511         unsigned int i, j = 0;
512
513         /* Fast path. */
514         if (!test->options[0])
515                 return test->options;
516
517         ret = tal_arr(f, char *, tal_count(test->options));
518         for (i = 0; test->options[i]; i++) {
519                 char *optname;
520
521                 if (!test->options[i] || !strchr(test->options[i], ':')) {
522                         optname = test->options[i];
523                 } else if (strstarts(test->options[i], f->name)
524                            && test->options[i][strlen(f->name)] == ':') {
525                         optname = test->options[i] + strlen(f->name) + 1;
526                 } else
527                         continue;
528
529                 /* FAIL overrides anything else. */
530                 if (streq(optname, "FAIL")) {
531                         ret = tal_arr(f, char *, 2);
532                         ret[0] = (char *)"FAIL";
533                         ret[1] = NULL;
534                         return ret;
535                 }
536                 ret[j++] = optname;
537         }
538         ret[j] = NULL;
539
540         /* Shrink it to size so tal_array_length() works as expected. */
541         tal_resize(&ret, j + 1);
542         return ret;
543 }
544
545 static char *opt_set_const_charp(const char *arg, const char **p)
546 {
547         return opt_set_charp(arg, cast_const2(char **, p));
548 }
549
550 static char *opt_set_target(const char *arg, struct dgraph_node *all)
551 {
552         struct ccanlint *t = find_test(arg);
553         if (!t)
554                 return tal_fmt(NULL, "unknown --target %s", arg);
555
556         targeting = true;
557         dgraph_add_edge(&t->node, all);
558         return NULL;
559 }
560
561 static bool run_tests(struct dgraph_node *all,
562                       bool summary,
563                       bool deps_fail_ignore,
564                       struct manifest *m,
565                       const char *prefix)
566 {
567         struct run_info run;
568         const char *comment = "";
569
570         run.noninteractive = summary;
571         run.m = m;
572         run.prefix = prefix;
573         run.score = run.total = 0;
574         run.pass = true;
575
576         non_ccan_deps = build_failed = false;
577
578         dgraph_traverse_to(all, run_test, &run);
579
580         /* We can completely fail if we're missing external stuff: ignore */
581         if (deps_fail_ignore && non_ccan_deps && build_failed) {
582                 comment = " (missing non-ccan dependencies?)";
583                 run.pass = true;
584         } else if (!run.pass) {
585                 comment = " FAIL!";
586         }
587         printf("%sTotal score: %u/%u%s\n",
588                prefix, run.score, run.total, comment);
589
590         return run.pass;
591 }
592
593 static bool add_to_all(const char *member UNNEEDED, struct ccanlint *c,
594                        struct dgraph_node *all)
595 {
596         /* If we're excluded on cmdline, don't add. */
597         if (!c->skip)
598                 dgraph_add_edge(&c->node, all);
599         return true;
600 }
601
602 static bool test_module(struct dgraph_node *all,
603                         const char *dir, const char *prefix, bool summary,
604                         bool deps_fail_ignore)
605 {
606         struct manifest *m = get_manifest(autofree(), dir);
607         char *testlink = path_join(NULL, temp_dir(), "test");
608
609         /* Create a symlink from temp dir back to src dir's
610          * test directory. */
611         unlink(testlink);
612         if (symlink(path_join(m, dir, "test"), testlink) != 0)
613                 err(1, "Creating test symlink in %s", temp_dir());
614
615         return run_tests(all, summary, deps_fail_ignore, m, prefix);
616 }
617
618 int main(int argc, char *argv[])
619 {
620         bool summary = false, pass = true, deps_fail_ignore = false;
621         int i;
622         const char *prefix = "";
623         char *cwd = path_cwd(NULL), *dir;
624         struct ccanlint top;  /* cannot_run may try to set ->can_run */
625         const char *override_compiler = NULL, *override_cflags = NULL;
626         
627         /* Empty graph node to which we attach everything else. */
628         dgraph_init_node(&top.node);
629
630         opt_register_early_noarg("--verbose|-v", opt_inc_intval, &verbose,
631                                  "verbose mode (up to -vvvv)");
632         opt_register_noarg("-n|--safe-mode", opt_set_bool, &safe_mode,
633                          "do not compile anything");
634         opt_register_noarg("-l|--list-tests", list_tests, NULL,
635                          "list tests ccanlint performs (and exit)");
636         opt_register_noarg("--test-dep-graph", test_dependency_graph, NULL,
637                          "print dependency graph of tests in Graphviz .dot format");
638         opt_register_noarg("-k|--keep", keep_tests, NULL,
639                          "do not delete ccanlint working files");
640         opt_register_noarg("--summary|-s", opt_set_bool, &summary,
641                            "give results only, no interactive correction");
642         opt_register_arg("-x|--exclude <testname>", exclude_test, NULL, NULL,
643                          "exclude <testname> (can be used multiple times)");
644         opt_register_arg("--timeout <milleseconds>", opt_set_uintval,
645                          NULL, &timeout,
646                          "ignore (terminate) tests that are slower than this");
647         opt_register_arg("-t|--target <testname>", opt_set_target, NULL,
648                          &top.node,
649                          "only run one test (and its prerequisites)");
650         opt_register_arg("--compiler <compiler>", opt_set_const_charp,
651                          NULL, &override_compiler, "set the compiler");
652         opt_register_arg("--cflags <flags>", opt_set_const_charp,
653                          NULL, &override_cflags, "set the compiler flags");
654         opt_register_noarg("--deps-fail-ignore", opt_set_bool,
655                            &deps_fail_ignore,
656                            "don't fail if external dependencies are missing");
657         opt_register_noarg("-?|-h|--help", opt_usage_and_exit,
658                            "\nA program for checking and guiding development"
659                            " of CCAN modules.",
660                            "This usage message");
661
662         /* Do verbose before anything else... */
663         opt_early_parse(argc, argv, opt_log_stderr_exit);
664
665         /* We move into temporary directory, so gcov dumps its files there. */
666         if (chdir(temp_dir()) != 0)
667                 err(1, "Error changing to %s temporary dir", temp_dir());
668
669         init_tests();
670
671         if (verbose >= 3) {
672                 compile_verbose = true;
673                 print_test_depends();
674         }
675         if (verbose >= 4)
676                 tools_verbose = true;
677
678         opt_parse(&argc, argv, opt_log_stderr_exit);
679
680         if (!targeting)
681                 strmap_iterate(&tests, add_to_all, &top.node);
682
683         if (argc == 1)
684                 dir = cwd;
685         else
686                 dir = path_simplify(NULL, take(path_join(NULL, cwd, argv[1])));
687
688         ccan_dir = find_ccan_dir(dir);
689         if (!ccan_dir)
690                 errx(1, "Cannot find ccan/ base directory in %s", dir);
691         config_header = read_config_header(ccan_dir, verbose > 1);
692
693         /* We do this after read_config_header has set compiler & cflags */
694         if (override_cflags)
695                 cflags = override_cflags;
696         if (override_compiler)
697                 compiler = override_compiler;
698
699         if (argc == 1)
700                 pass = test_module(&top.node, cwd, "",
701                                    summary, deps_fail_ignore);
702         else {
703                 for (i = 1; i < argc; i++) {
704                         dir = path_canon(NULL,
705                                          take(path_join(NULL, cwd, argv[i])));
706                         if (!dir)
707                                 err(1, "Cannot get canonical name of '%s'",
708                                     argv[i]);
709
710                         prefix = path_join(NULL, ccan_dir, "ccan");
711                         prefix = path_rel(NULL, take(prefix), dir);
712                         prefix = tal_strcat(NULL, take(prefix), ": ");
713
714                         pass &= test_module(&top.node, dir, prefix, summary,
715                                             deps_fail_ignore);
716                         reset_tests(&top.node);
717                 }
718         }
719         return pass ? 0 : 1;
720 }