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