ccanlint: parse --verbose before anything else.
[ccan] / tools / ccanlint / ccanlint.c
1 /*
2  * ccanlint: assorted checks and advice for a ccan package
3  * Copyright (C) 2008 Rusty Russell, Idris Soule
4  * Copyright (C) 2010 Rusty Russell, Idris Soule
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the Free
8  * Software Foundation; either version 2 of the License, or (at your option)
9  * any later version.
10  *
11  *   This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program; if not, write to the Free Software Foundation, Inc., 51
18  * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20 #include "ccanlint.h"
21 #include "../tools.h"
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <err.h>
27 #include <ctype.h>
28 #include <ccan/btree/btree.h>
29 #include <ccan/str/str.h>
30 #include <ccan/str_talloc/str_talloc.h>
31 #include <ccan/talloc/talloc.h>
32 #include <ccan/opt/opt.h>
33 #include <ccan/foreach/foreach.h>
34 #include <ccan/grab_file/grab_file.h>
35 #include <ccan/cast/cast.h>
36 #include <ccan/tlist/tlist.h>
37
38 /* Defines struct tlist_ccanlint. */
39 TLIST_TYPE(ccanlint, struct ccanlint);
40
41 int verbose = 0;
42 static struct tlist_ccanlint tests = TLIST_INIT(tests);
43 bool safe_mode = false;
44 static struct btree *cmdline_exclude;
45 static struct btree *info_exclude;
46 static unsigned int timeout;
47
48 /* These are overridden at runtime if we can find config.h */
49 const char *compiler = NULL;
50 const char *cflags = NULL;
51
52 const char *config_header;
53
54 #if 0
55 static void indent_print(const char *string)
56 {
57         while (*string) {
58                 unsigned int line = strcspn(string, "\n");
59                 printf("\t%.*s", line, string);
60                 if (string[line] == '\n') {
61                         printf("\n");
62                         line++;
63                 }
64                 string += line;
65         }
66 }
67 #endif
68
69 bool ask(const char *question)
70 {
71         char reply[80];
72
73         printf("%s ", question);
74         fflush(stdout);
75
76         return fgets(reply, sizeof(reply), stdin) != NULL
77                 && toupper(reply[0]) == 'Y';
78 }
79
80 static const char *should_skip(struct manifest *m, struct ccanlint *i)
81 {
82         if (btree_lookup(cmdline_exclude, i->key))
83                 return "excluded on command line";
84
85         if (btree_lookup(info_exclude, i->key))
86                 return "excluded in _info file";
87         
88         if (i->skip)
89                 return i->skip;
90
91         if (i->skip_fail)
92                 return "dependency failed";
93
94         if (i->can_run)
95                 return i->can_run(m);
96         return NULL;
97 }
98
99 static bool run_test(struct ccanlint *i,
100                      bool quiet,
101                      unsigned int *running_score,
102                      unsigned int *running_total,
103                      struct manifest *m,
104                      const char *prefix)
105 {
106         unsigned int timeleft;
107         const struct dependent *d;
108         const char *skip;
109         struct score *score;
110
111         //one less test to run through
112         list_for_each(&i->dependencies, d, node)
113                 d->dependent->num_depends--;
114
115         score = talloc(m, struct score);
116         list_head_init(&score->per_file_errors);
117         score->error = NULL;
118         score->pass = false;
119         score->score = 0;
120         score->total = 1;
121
122         skip = should_skip(m, i);
123
124         if (skip) {
125         skip:
126                 if (verbose && !streq(skip, "not relevant to target"))
127                         printf("%s%s: skipped (%s)\n", prefix, i->name, skip);
128
129                 /* If we're skipping this because a prereq failed, we fail:
130                  * count it as a score of 1. */
131                 if (i->skip_fail)
132                         (*running_total)++;
133                         
134                 list_del(&i->list);
135                 list_for_each(&i->dependencies, d, node) {
136                         if (d->dependent->skip)
137                                 continue;
138                         d->dependent->skip = "dependency was skipped";
139                         d->dependent->skip_fail = i->skip_fail;
140                 }
141                 return i->skip_fail ? false : true;
142         }
143
144         timeleft = timeout ? timeout : default_timeout_ms;
145         i->check(m, i->keep_results, &timeleft, score);
146         if (timeout && timeleft == 0) {
147                 skip = "timeout";
148                 goto skip;
149         }
150
151         assert(score->score <= score->total);
152         if ((!score->pass && !quiet)
153             || (score->score < score->total && verbose)
154             || verbose > 1) {
155                 printf("%s%s (%s): %s",
156                        prefix, i->name, i->key, score->pass ? "PASS" : "FAIL");
157                 if (score->total > 1)
158                         printf(" (+%u/%u)", score->score, score->total);
159                 printf("\n");
160         }
161
162         if ((!quiet && !score->pass) || verbose) {
163                 if (score->error) {
164                         printf("%s%s", score->error,
165                                strends(score->error, "\n") ? "" : "\n");
166                 }
167         }
168         if (!quiet && score->score < score->total && i->handle)
169                 i->handle(m, score);
170
171         *running_score += score->score;
172         *running_total += score->total;
173
174         list_del(&i->list);
175
176         if (!score->pass) {
177                 /* Skip any tests which depend on this one. */
178                 list_for_each(&i->dependencies, d, node) {
179                         if (d->dependent->skip)
180                                 continue;
181                         d->dependent->skip = "dependency failed";
182                         d->dependent->skip_fail = true;
183                 }
184         }
185         return score->pass;
186 }
187
188 static void register_test(struct ccanlint *test)
189 {
190         tlist_add(&tests, test, list);
191         test->options = talloc_array(NULL, char *, 1);
192         test->options[0] = NULL;
193         test->skip = NULL;
194         test->skip_fail = false;
195 }
196
197 /**
198  * get_next_test - retrieves the next test to be processed
199  **/
200 static inline struct ccanlint *get_next_test(void)
201 {
202         struct ccanlint *i;
203
204         if (tlist_empty(&tests))
205                 return NULL;
206
207         tlist_for_each(&tests, i, list) {
208                 if (i->num_depends == 0)
209                         return i;
210         }
211         errx(1, "Can't make process; test dependency cycle");
212 }
213
214 static struct ccanlint *find_test(const char *key)
215 {
216         struct ccanlint *i;
217
218         tlist_for_each(&tests, i, list)
219                 if (streq(i->key, key))
220                         return i;
221
222         return NULL;
223 }
224
225 bool is_excluded(const char *name)
226 {
227         return btree_lookup(cmdline_exclude, name) != NULL
228                 || btree_lookup(info_exclude, name) != NULL
229                 || find_test(name)->skip != NULL;
230 }
231
232 #undef REGISTER_TEST
233 #define REGISTER_TEST(name, ...) extern struct ccanlint name
234 #include "generated-testlist"
235
236 static void init_tests(void)
237 {
238         struct ccanlint *c;
239         struct btree *keys, *names;
240
241         tlist_init(&tests);
242
243 #undef REGISTER_TEST
244 #define REGISTER_TEST(name) register_test(&name)
245 #include "generated-testlist"
246
247         /* Initialize dependency lists. */
248         tlist_for_each(&tests, c, list) {
249                 list_head_init(&c->dependencies);
250                 c->num_depends = 0;
251         }
252
253         /* Resolve dependencies. */
254         tlist_for_each(&tests, c, list) {
255                 char **deps = strsplit(NULL, c->needs, " ");
256                 unsigned int i;
257
258                 for (i = 0; deps[i]; i++) {
259                         struct ccanlint *dep;
260                         struct dependent *dchild;
261
262                         dep = find_test(deps[i]);
263                         if (!dep)
264                                 errx(1, "BUG: unknown dep '%s' for %s",
265                                      deps[i], c->key);
266                         dchild = talloc(NULL, struct dependent);
267                         dchild->dependent = c;
268                         list_add_tail(&dep->dependencies, &dchild->node);
269                         c->num_depends++;
270                 }
271                 talloc_free(deps);
272         }
273
274         /* Self-consistency check: make sure no two tests
275            have the same key or name. */
276         keys = btree_new(btree_strcmp);
277         names = btree_new(btree_strcmp);
278         tlist_for_each(&tests, c, list) {
279                 if (!btree_insert(keys, c->key))
280                         errx(1, "BUG: Duplicate test key '%s'",
281                              c->key);
282                 if (!btree_insert(names, c->name))
283                         errx(1, "BUG: Duplicate test name '%s'",
284                              c->name);
285         }
286
287         btree_delete(keys);
288         btree_delete(names);
289 }
290
291 static void print_test_depends(void)
292 {
293         struct ccanlint *c;
294         printf("Tests:\n");
295
296         tlist_for_each(&tests, c, list) {
297                 if (!list_empty(&c->dependencies)) {
298                         const struct dependent *d;
299                         printf("These depend on %s:\n", c->key);
300                         list_for_each(&c->dependencies, d, node)
301                                 printf("\t%s\n", d->dependent->key);
302                 }
303         }
304 }
305
306 static int show_tmpdir(const char *dir)
307 {
308         printf("You can find ccanlint working files in '%s'\n", dir);
309         return 0;
310 }
311
312 static char *keep_test(const char *testname, void *unused)
313 {
314         struct ccanlint *i;
315
316         init_tests();
317         if (streq(testname, "all")) {
318                 tlist_for_each(&tests, i, list)
319                         i->keep_results = true;
320         } else {
321                 i = find_test(testname);
322                 if (!i)
323                         errx(1, "No test %s to --keep", testname);
324                 i->keep_results = true;
325         }
326
327         /* Don't automatically destroy temporary dir. */
328         talloc_set_destructor(temp_dir(NULL), show_tmpdir);
329         return NULL;
330 }
331
332 static char *skip_test(const char *testname, void *unused)
333 {
334         btree_insert(cmdline_exclude, testname);
335         return NULL;
336 }
337
338 static char *list_tests(void *arg)
339 {
340         struct ccanlint *i;
341
342         init_tests();
343
344         printf("Tests:\n");
345         /* This makes them print in topological order. */
346         while ((i = get_next_test()) != NULL) {
347                 const struct dependent *d;
348                 printf("   %-25s %s\n", i->key, i->name);
349                 list_del(&i->list);
350                 list_for_each(&i->dependencies, d, node)
351                         d->dependent->num_depends--;
352         }
353         exit(0);
354 }
355
356 static void test_dgraph_vertices(const char *style)
357 {
358         const struct ccanlint *i;
359
360         tlist_for_each(&tests, i, list) {
361                 /*
362                  * todo: escape labels in case ccanlint test keys have
363                  *       characters interpreted as GraphViz syntax.
364                  */
365                 printf("\t\"%p\" [label=\"%s\"%s]\n", i, i->key, style);
366         }
367 }
368
369 static void test_dgraph_edges(void)
370 {
371         const struct ccanlint *i;
372         const struct dependent *d;
373
374         tlist_for_each(&tests, i, list)
375                 list_for_each(&i->dependencies, d, node)
376                         printf("\t\"%p\" -> \"%p\"\n", d->dependent, i);
377 }
378
379 static char *test_dependency_graph(void *arg)
380 {
381         init_tests();
382         puts("digraph G {");
383
384         test_dgraph_vertices("");
385         test_dgraph_edges();
386
387         puts("}");
388
389         exit(0);
390 }
391
392 /* Remove empty lines. */
393 static char **collapse(char **lines, unsigned int *nump)
394 {
395         unsigned int i, j;
396         for (i = j = 0; lines[i]; i++) {
397                 if (lines[i][0])
398                         lines[j++] = lines[i];
399         }
400         lines[j] = NULL;
401         if (nump)
402                 *nump = j;
403         return lines;
404 }
405
406
407 static void add_options(struct ccanlint *test, char **options,
408                         unsigned int num_options)
409 {
410         unsigned int num;
411
412         if (!test->options)
413                 num = 0;
414         else
415                 /* -1, because last one is NULL. */
416                 num = talloc_array_length(test->options) - 1;
417
418         test->options = talloc_realloc(NULL, test->options,
419                                        char *,
420                                        num + num_options + 1);
421         memcpy(&test->options[num], options, (num_options + 1)*sizeof(char *));
422 }
423
424 static void add_info_options(struct ccan_file *info, bool mark_fails)
425 {
426         struct doc_section *d;
427         unsigned int i;
428         struct ccanlint *test;
429
430         list_for_each(get_ccan_file_docs(info), d, list) {
431                 if (!streq(d->type, "ccanlint"))
432                         continue;
433
434                 for (i = 0; i < d->num_lines; i++) {
435                         unsigned int num_words;
436                         char **words = collapse(strsplit(d, d->lines[i], " \t"),
437                                                 &num_words);
438                         if (num_words == 0)
439                                 continue;
440
441                         if (strncmp(words[0], "//", 2) == 0)
442                                 continue;
443
444                         test = find_test(words[0]);
445                         if (!test) {
446                                 warnx("%s: unknown ccanlint test '%s'",
447                                       info->fullname, words[0]);
448                                 continue;
449                         }
450
451                         if (!words[1]) {
452                                 warnx("%s: no argument to test '%s'",
453                                       info->fullname, words[0]);
454                                 continue;
455                         }
456
457                         /* Known failure? */
458                         if (strcasecmp(words[1], "FAIL") == 0) {
459                                 if (mark_fails)
460                                         btree_insert(info_exclude, words[0]);
461                         } else {
462                                 if (!test->takes_options)
463                                         warnx("%s: %s doesn't take options",
464                                               info->fullname, words[0]);
465                                 add_options(test, words+1, num_words-1);
466                         }
467                 }
468         }
469 }
470
471 /* If options are of form "filename:<option>" they only apply to that file */
472 char **per_file_options(const struct ccanlint *test, struct ccan_file *f)
473 {
474         char **ret;
475         unsigned int i, j = 0;
476
477         /* Fast path. */
478         if (!test->options[0])
479                 return test->options;
480
481         ret = talloc_array(f, char *, talloc_array_length(test->options));
482         for (i = 0; test->options[i]; i++) {
483                 char *optname;
484
485                 if (!test->options[i] || !strchr(test->options[i], ':')) {
486                         optname = test->options[i];
487                 } else if (strstarts(test->options[i], f->name)
488                            && test->options[i][strlen(f->name)] == ':') {
489                         optname = test->options[i] + strlen(f->name) + 1;
490                 } else
491                         continue;
492
493                 /* FAIL overrides anything else. */
494                 if (streq(optname, "FAIL")) {
495                         ret = talloc_array(f, char *, 2);
496                         ret[0] = (char *)"FAIL";
497                         ret[1] = NULL;
498                         return ret;
499                 }
500                 ret[j++] = optname;
501         }
502         ret[j] = NULL;
503
504         /* Shrink it to size so talloc_array_length() works as expected. */
505         return talloc_realloc(NULL, ret, char *, j + 1);
506 }
507
508 static bool depends_on(struct ccanlint *i, struct ccanlint *target)
509 {
510         const struct dependent *d;
511
512         if (i == target)
513                 return true;
514
515         list_for_each(&i->dependencies, d, node) {
516                 if (depends_on(d->dependent, target))
517                         return true;
518         }
519         return false;
520 }
521
522 /* O(N^2), who cares? */
523 static void skip_unrelated_tests(struct ccanlint *target)
524 {
525         struct ccanlint *i;
526
527         tlist_for_each(&tests, i, list)
528                 if (!depends_on(i, target))
529                         i->skip = "not relevant to target";
530 }
531
532 static char *demangle_string(char *string)
533 {
534         unsigned int i;
535         const char mapfrom[] = "abfnrtv";
536         const char mapto[] = "\a\b\f\n\r\t\v";
537
538         if (!strchr(string, '"'))
539                 return NULL;
540         string = strchr(string, '"') + 1;
541         if (!strrchr(string, '"'))
542                 return NULL;
543         *strrchr(string, '"') = '\0';
544
545         for (i = 0; i < strlen(string); i++) {
546                 if (string[i] == '\\') {
547                         char repl;
548                         unsigned len = 0;
549                         const char *p = strchr(mapfrom, string[i+1]);
550                         if (p) {
551                                 repl = mapto[p - mapfrom];
552                                 len = 1;
553                         } else if (strlen(string+i+1) >= 3) {
554                                 if (string[i+1] == 'x') {
555                                         repl = (string[i+2]-'0')*16
556                                                 + string[i+3]-'0';
557                                         len = 3;
558                                 } else if (cisdigit(string[i+1])) {
559                                         repl = (string[i+2]-'0')*8*8
560                                                 + (string[i+3]-'0')*8
561                                                 + (string[i+4]-'0');
562                                         len = 3;
563                                 }
564                         }
565                         if (len == 0) {
566                                 repl = string[i+1];
567                                 len = 1;
568                         }
569
570                         string[i] = repl;
571                         memmove(string + i + 1, string + i + len + 1,
572                                 strlen(string + i + len + 1) + 1);
573                 }
574         }
575
576         return string;
577 }
578
579
580 static void read_config_header(void)
581 {
582         char *fname = talloc_asprintf(NULL, "%s/config.h", ccan_dir);
583         char **lines;
584         unsigned int i;
585
586         config_header = grab_file(NULL, fname, NULL);
587         if (!config_header) {
588                 talloc_free(fname);
589                 return;
590         }
591
592         lines = strsplit(config_header, config_header, "\n");
593         for (i = 0; i < talloc_array_length(lines) - 1; i++) {
594                 char *sym;
595                 const char **line = (const char **)&lines[i];
596
597                 if (!get_token(line, "#"))
598                         continue;
599                 if (!get_token(line, "define"))
600                         continue;
601                 sym = get_symbol_token(lines, line);
602                 if (streq(sym, "CCAN_COMPILER") && !compiler) {
603                         compiler = demangle_string(lines[i]);
604                         if (!compiler)
605                                 errx(1, "%s:%u:could not parse CCAN_COMPILER",
606                                      fname, i+1);
607                         if (verbose > 1)
608                                 printf("%s: compiler set to '%s'\n",
609                                        fname, compiler);
610                 } else if (streq(sym, "CCAN_CFLAGS") && !cflags) {
611                         cflags = demangle_string(lines[i]);
612                         if (!cflags)
613                                 errx(1, "%s:%u:could not parse CCAN_CFLAGS",
614                                      fname, i+1);
615                         if (verbose > 1)
616                                 printf("%s: compiler flags set to '%s'\n",
617                                        fname, cflags);
618                 }
619         }
620         if (!compiler)
621                 compiler = CCAN_COMPILER;
622         if (!cflags)
623                 compiler = CCAN_CFLAGS;
624 }
625
626 static char *opt_set_const_charp(const char *arg, const char **p)
627 {
628         return opt_set_charp(arg, cast_const2(char **, p));
629 }
630
631 int main(int argc, char *argv[])
632 {
633         bool summary = false, pass = true;
634         unsigned int i;
635         struct manifest *m;
636         struct ccanlint *t;
637         const char *prefix = "";
638         char *dir = talloc_getcwd(NULL), *base_dir = dir, *target = NULL,
639                 *testlink;
640         
641         cmdline_exclude = btree_new(btree_strcmp);
642         info_exclude = btree_new(btree_strcmp);
643
644         opt_register_early_noarg("--verbose|-v", opt_inc_intval, &verbose,
645                                  "verbose mode (up to -vvvv)");
646         opt_register_noarg("-n|--safe-mode", opt_set_bool, &safe_mode,
647                          "do not compile anything");
648         opt_register_noarg("-l|--list-tests", list_tests, NULL,
649                          "list tests ccanlint performs (and exit)");
650         opt_register_noarg("--test-dep-graph", test_dependency_graph, NULL,
651                          "print dependency graph of tests in Graphviz .dot format");
652         opt_register_arg("-k|--keep <testname>", keep_test, NULL, NULL,
653                          "keep results of <testname>"
654                          " (can be used multiple times, or 'all')");
655         opt_register_noarg("--summary|-s", opt_set_bool, &summary,
656                            "simply give one line summary");
657         opt_register_arg("-x|--exclude <testname>", skip_test, NULL, NULL,
658                          "exclude <testname> (can be used multiple times)");
659         opt_register_arg("-t|--timeout <milleseconds>", opt_set_uintval,
660                          NULL, &timeout,
661                          "ignore (terminate) tests that are slower than this");
662         opt_register_arg("--target <testname>", opt_set_charp,
663                          NULL, &target,
664                          "only run one test (and its prerequisites)");
665         opt_register_arg("--compiler <compiler>", opt_set_const_charp,
666                          NULL, &compiler, "set the compiler");
667         opt_register_arg("--cflags <flags>", opt_set_const_charp,
668                          NULL, &cflags, "set the compiler flags");
669         opt_register_noarg("-?|-h|--help", opt_usage_and_exit,
670                            "\nA program for checking and guiding development"
671                            " of CCAN modules.",
672                            "This usage message");
673
674         /* Do verbose before anything else... */
675         opt_early_parse(argc, argv, opt_log_stderr_exit);
676
677         /* We move into temporary directory, so gcov dumps its files there. */
678         if (chdir(temp_dir(talloc_autofree_context())) != 0)
679                 err(1, "Error changing to %s temporary dir", temp_dir(NULL));
680
681         opt_parse(&argc, argv, opt_log_stderr_exit);
682
683         if (verbose >= 3) {
684                 compile_verbose = true;
685                 print_test_depends();
686         }
687         if (verbose >= 4)
688                 tools_verbose = true;
689
690         /* This links back to the module's test dir. */
691         testlink = talloc_asprintf(NULL, "%s/test", temp_dir(NULL));
692
693         /* Defaults to pwd. */
694         if (argc == 1) {
695                 i = 1;
696                 goto got_dir;
697         }
698
699         for (i = 1; i < argc; i++) {
700                 unsigned int score, total_score;
701                 bool added_info_options = false;
702
703                 dir = argv[i];
704
705                 if (dir[0] != '/')
706                         dir = talloc_asprintf_append(NULL, "%s/%s",
707                                                      base_dir, dir);
708                 while (strends(dir, "/"))
709                         dir[strlen(dir)-1] = '\0';
710
711         got_dir:
712                 if (dir != base_dir)
713                         prefix = talloc_append_string(talloc_basename(NULL,dir),
714                                                       ": ");
715
716                 init_tests();
717
718                 if (target) {
719                         struct ccanlint *test;
720
721                         test = find_test(target);
722                         if (!test)
723                                 errx(1, "Unknown test to run '%s'", target);
724                         skip_unrelated_tests(test);
725                 }
726
727                 m = get_manifest(talloc_autofree_context(), dir);
728
729                 /* FIXME: This has to come after we've got manifest. */
730                 if (i == 1)
731                         read_config_header();
732
733                 /* Create a symlink from temp dir back to src dir's
734                  * test directory. */
735                 unlink(testlink);
736                 if (symlink(talloc_asprintf(m, "%s/test", dir), testlink) != 0)
737                         err(1, "Creating test symlink in %s", temp_dir(NULL));
738
739                 score = total_score = 0;
740                 while ((t = get_next_test()) != NULL) {
741                         if (!run_test(t, summary, &score, &total_score, m,
742                                       prefix)) {
743                                 pass = false;
744                                 if (t->compulsory) {
745                                         warnx("%s%s failed", prefix, t->name);
746                                         printf("%sTotal score: 0/%u\n",
747                                                prefix, total_score);
748                                         goto next;
749                                 }
750                         }
751
752                         /* --target overrides known FAIL from _info */
753                         if (!added_info_options && m->info_file) {
754                                 add_info_options(m->info_file, !target);
755                                 added_info_options = true;
756                         }
757                 }
758
759                 printf("%sTotal score: %u/%u\n", prefix, score, total_score);
760         next: ;
761         }
762         return pass ? 0 : 1;
763 }