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