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