d19ede6200e01ac2856c162f42c1c8f7c8936727
[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  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the Free
7  * Software Foundation; either version 2 of the License, or (at your option)
8  * any later version.
9  *
10  *   This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program; if not, write to the Free Software Foundation, Inc., 51
17  * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 #include "ccanlint.h"
20 #include "../tools.h"
21 #include <unistd.h>
22 #include <getopt.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <err.h>
28 #include <ctype.h>
29 #include <ccan/btree/btree.h>
30 #include <ccan/str/str.h>
31 #include <ccan/str_talloc/str_talloc.h>
32 #include <ccan/talloc/talloc.h>
33
34 unsigned int verbose = 0;
35 static LIST_HEAD(compulsory_tests);
36 static LIST_HEAD(normal_tests);
37 static LIST_HEAD(finished_tests);
38 bool safe_mode = false;
39 static struct btree *cmdline_exclude;
40 static struct btree *info_exclude;
41 static unsigned int timeout;
42
43 static void usage(const char *name)
44 {
45         fprintf(stderr, "Usage: %s [-s] [-n] [-v] [-t <ms>] [-d <dirname>] [-x <test>]* [-k <test>]*\n"
46                 "   -v: verbose mode (can specify more than once)\n"
47                 "   -s: simply give one line summary\n"
48                 "   -d: use this directory instead of the current one\n"
49                 "   -n: do not compile anything\n"
50                 "   -l: list tests ccanlint performs\n"
51                 "   -k: keep results of this test (can be used multiple times)\n"
52                 "   -x: exclude tests (can be used multiple times)\n"
53                 "   -t: ignore (terminate) tests that are slower than this\n",
54                 name);
55         exit(1);
56 }
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[2];
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 static const char *should_skip(struct manifest *m, struct ccanlint *i)
85 {
86         if (btree_lookup(cmdline_exclude, i->key))
87                 return "excluded on command line";
88
89         if (btree_lookup(info_exclude, i->key))
90                 return "excluded in _info file";
91         
92         if (i->skip_fail)
93                 return "dependency failed";
94
95         if (i->skip)
96                 return "dependency was skipped";
97
98         if (i->can_run)
99                 return i->can_run(m);
100         return NULL;
101 }
102
103 static bool run_test(struct ccanlint *i,
104                      bool quiet,
105                      unsigned int *score,
106                      unsigned int *total_score,
107                      struct manifest *m)
108 {
109         void *result;
110         unsigned int this_score, max_score, timeleft;
111         const struct dependent *d;
112         const char *skip;
113         bool bad, good;
114
115         //one less test to run through
116         list_for_each(&i->dependencies, d, node)
117                 d->dependent->num_depends--;
118
119         skip = should_skip(m, i);
120
121         if (skip) {
122         skip:
123                 if (verbose)
124                         printf("  %s: skipped (%s)\n", i->name, skip);
125
126                 /* If we're skipping this because a prereq failed, we fail. */
127                 if (i->skip_fail)
128                         *total_score += i->total_score;
129                         
130                 list_del(&i->list);
131                 list_add_tail(&finished_tests, &i->list);
132                 list_for_each(&i->dependencies, d, node) {
133                         d->dependent->skip = true;
134                         d->dependent->skip_fail = i->skip_fail;
135                 }
136                 return true;
137         }
138
139         timeleft = timeout ? timeout : default_timeout_ms;
140         result = i->check(m, i->keep_results, &timeleft);
141         if (timeout && timeleft == 0) {
142                 skip = "timeout";
143                 goto skip;
144         }
145
146         max_score = i->total_score;
147         if (!max_score)
148                 max_score = 1;
149
150         if (!result)
151                 this_score = max_score;
152         else if (i->score)
153                 this_score = i->score(m, result);
154         else
155                 this_score = 0;
156
157         bad = (this_score == 0);
158         good = (this_score >= max_score);
159
160         if (verbose || (!good && !quiet)) {
161                 printf("  %s: %s", i->name,
162                        bad ? "FAIL" : good ? "PASS" : "PARTIAL");
163                 if (max_score > 1)
164                         printf(" (+%u/%u)", this_score, max_score);
165                 printf("\n");
166         }
167
168         if (!quiet && result) {
169                 const char *desc;
170                 if (i->describe && (desc = i->describe(m, result)) != NULL) 
171                         printf("    %s\n", desc);
172                 if (i->handle)
173                         i->handle(m, result);
174         }
175
176         if (i->total_score) {
177                 *score += this_score;
178                 *total_score += i->total_score;
179         }
180
181         list_del(&i->list);
182         list_add_tail(&finished_tests, &i->list);
183
184         if (bad) {
185                 /* Skip any tests which depend on this one. */
186                 list_for_each(&i->dependencies, d, node) {
187                         d->dependent->skip = true;
188                         d->dependent->skip_fail = true;
189                 }
190         }
191         return good;
192 }
193
194 static void register_test(struct list_head *h, struct ccanlint *test, ...)
195 {
196         va_list ap;
197         struct ccanlint *depends;
198         struct dependent *dchild;
199
200         list_add(h, &test->list);
201
202         va_start(ap, test);
203         /* Careful: we might have been initialized by a dependent. */
204         if (test->dependencies.n.next == NULL)
205                 list_head_init(&test->dependencies);
206
207         //dependent(s) args (if any), last one is NULL
208         while ((depends = va_arg(ap, struct ccanlint *)) != NULL) {
209                 dchild = malloc(sizeof(*dchild));
210                 dchild->dependent = test;
211                 /* The thing we depend on might not be initialized yet! */
212                 if (depends->dependencies.n.next == NULL)
213                         list_head_init(&depends->dependencies);
214                 list_add_tail(&depends->dependencies, &dchild->node);
215                 test->num_depends++;
216         }
217         va_end(ap);
218 }
219
220 /**
221  * get_next_test - retrieves the next test to be processed
222  **/
223 static inline struct ccanlint *get_next_test(struct list_head *test)
224 {
225         struct ccanlint *i;
226
227         if (list_empty(test))
228                 return NULL;
229
230         list_for_each(test, i, list) {
231                 if (i->num_depends == 0)
232                         return i;
233         }
234         errx(1, "Can't make process; test dependency cycle");
235 }
236
237 static void init_tests(void)
238 {
239         const struct ccanlint *i;
240         struct btree *keys, *names;
241
242 #undef REGISTER_TEST
243 #define REGISTER_TEST(name, ...) register_test(&normal_tests, &name, __VA_ARGS__, NULL)
244 #include "generated-normal-tests"
245 #undef REGISTER_TEST
246 #define REGISTER_TEST(name, ...) register_test(&compulsory_tests, &name, __VA_ARGS__, NULL)
247 #include "generated-compulsory-tests"
248
249         /* Self-consistency check: make sure no two tests
250            have the same key or name. */
251         keys = btree_new(btree_strcmp);
252         names = btree_new(btree_strcmp);
253         list_for_each(&compulsory_tests, i, list) {
254                 if (!btree_insert(keys, i->key))
255                         errx(1, "BUG: Duplicate test key '%s'", i->key);
256                 if (!btree_insert(keys, i->name))
257                         errx(1, "BUG: Duplicate test name '%s'", i->name);
258         }
259         list_for_each(&normal_tests, i, list) {
260                 if (!btree_insert(keys, i->key))
261                         errx(1, "BUG: Duplicate test key '%s'", i->key);
262                 if (!btree_insert(keys, i->name))
263                         errx(1, "BUG: Duplicate test name '%s'", i->name);
264         }
265         btree_delete(keys);
266         btree_delete(names);
267         
268         if (!verbose)
269                 return;
270
271         printf("\nCompulsory Tests\n");
272         list_for_each(&compulsory_tests, i, list) {
273                 printf("%s depends on %u others\n", i->name, i->num_depends);
274                 if (!list_empty(&i->dependencies)) {
275                         const struct dependent *d;
276                         printf("These depend on us:\n");
277                         list_for_each(&i->dependencies, d, node)
278                                 printf("\t%s\n", d->dependent->name);
279                 }
280         }
281
282         printf("\nNormal Tests\n");
283         list_for_each(&normal_tests, i, list) {
284                 printf("%s depends on %u others\n", i->name, i->num_depends);
285                 if (!list_empty(&i->dependencies)) {
286                         const struct dependent *d;
287                         printf("These depend on us:\n");
288                         list_for_each(&i->dependencies, d, node)
289                                 printf("\t%s\n", d->dependent->name);
290                 }
291         }
292 }
293
294 static struct ccanlint *find_test(const char *key)
295 {
296         struct ccanlint *i;
297
298         list_for_each(&compulsory_tests, i, list)
299                 if (streq(i->key, key))
300                         return i;
301
302         list_for_each(&normal_tests, i, list)
303                 if (streq(i->key, key))
304                         return i;
305
306         return NULL;
307 }
308
309 static void keep_test(const char *testname)
310 {
311         struct ccanlint *i = find_test(testname);
312         if (!i)
313                 errx(1, "No test %s to --keep", testname);
314         i->keep_results = true;
315 }
316
317 static void print_tests(struct list_head *tests, const char *type)
318 {
319         struct ccanlint *i;
320
321         printf("%s tests:\n", type);
322         /* This makes them print in topological order. */
323         while ((i = get_next_test(tests)) != NULL) {
324                 const struct dependent *d;
325                 printf("   %-25s %s\n", i->key, i->name);
326                 list_del(&i->list);
327                 list_for_each(&i->dependencies, d, node)
328                         d->dependent->num_depends--;
329         }
330 }
331
332 static void list_tests(void)
333 {
334         print_tests(&compulsory_tests, "Compulsory");
335         print_tests(&normal_tests, "Normal");
336         exit(0);
337 }
338
339 static char *strip(const void *ctx, const char *line)
340 {
341         line += strcspn(line, IDENT_CHARS "-");
342         return talloc_strndup(ctx, line, strspn(line, IDENT_CHARS "-"));
343 }
344
345 static void add_info_fails(struct ccan_file *info)
346 {
347         struct doc_section *d;
348         unsigned int i;
349
350         list_for_each(get_ccan_file_docs(info), d, list) {
351                 if (!streq(d->type, "fails"))
352                         continue;
353
354                 for (i = 0; i < d->num_lines; i++)
355                         btree_insert(info_exclude, strip(info, d->lines[i]));
356                 break;
357         }
358 }
359
360 int main(int argc, char *argv[])
361 {
362         int c;
363         bool summary = false;
364         unsigned int score = 0, total_score = 0;
365         struct manifest *m;
366         struct ccanlint *i;
367         const char *prefix = "", *dir = talloc_getcwd(NULL);
368         
369         init_tests();
370
371         cmdline_exclude = btree_new(btree_strcmp);
372         info_exclude = btree_new(btree_strcmp);
373
374         /* I'd love to use long options, but that's not standard. */
375         /* FIXME: popt ccan package? */
376         while ((c = getopt(argc, argv, "sd:vnlx:t:k:")) != -1) {
377                 switch (c) {
378                 case 'd':
379                         if (optarg[0] != '/')
380                                 dir = talloc_asprintf_append(NULL, "%s/%s",
381                                                              dir, optarg);
382                         else
383                                 dir = optarg;
384                         prefix = talloc_append_string(talloc_basename(NULL,
385                                                                       optarg),
386                                                       ": ");
387                         break;
388                 case 'l':
389                         list_tests();
390                 case 's':
391                         summary = true;
392                         break;
393                 case 'v':
394                         verbose++;
395                         break;
396                 case 'n':
397                         safe_mode = true;
398                         break;
399                 case 'k':
400                         keep_test(optarg);
401                         break;
402                 case 'x':
403                         btree_insert(cmdline_exclude, optarg);
404                         break;
405                 case 't':
406                         timeout = atoi(optarg);
407                         if (!timeout)
408                                 errx(1, "Invalid timeout %s: 1 ms minumum",
409                                      optarg);
410                         break;
411                 default:
412                         usage(argv[0]);
413                 }
414         }
415
416         if (optind < argc)
417                 usage(argv[0]);
418
419         if (verbose >= 2)
420                 compile_verbose = true;
421         if (verbose >= 3)
422                 tools_verbose = true;
423
424         /* We move into temporary directory, so gcov dumps its files there. */
425         if (chdir(temp_dir(talloc_autofree_context())) != 0)
426                 err(1, "Error changing to %s temporary dir", temp_dir(NULL));
427
428         m = get_manifest(talloc_autofree_context(), dir);
429
430         /* Create a symlink from temp dir back to src dir's test directory. */
431         if (symlink(talloc_asprintf(m, "%s/test", dir),
432                     talloc_asprintf(m, "%s/test", temp_dir(NULL))) != 0)
433                 err(1, "Creating test symlink in %s", temp_dir(NULL));
434
435         /* If you don't pass the compulsory tests, you don't even get a score */
436         if (verbose)
437                 printf("Compulsory tests:\n");
438
439         while ((i = get_next_test(&compulsory_tests)) != NULL) {
440                 if (!run_test(i, summary, &score, &total_score, m)) {
441                         errx(1, "%s%s failed", prefix, i->name);
442                 }
443         }
444
445         add_info_fails(m->info_file);
446
447         if (verbose)
448                 printf("\nNormal tests:\n");
449         while ((i = get_next_test(&normal_tests)) != NULL)
450                 run_test(i, summary, &score, &total_score, m);
451
452         printf("%sTotal score: %u/%u\n", prefix, score, total_score);
453         return 0;
454 }