fb3e4d140fe378108f23b4d0042f5ec41a6fd645
[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 <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 #include <ccan/opt/opt.h>
34 #include <ccan/foreach/foreach.h>
35
36 int verbose = 0;
37 static LIST_HEAD(compulsory_tests);
38 static LIST_HEAD(normal_tests);
39 static LIST_HEAD(finished_tests);
40 bool safe_mode = false;
41 static struct btree *cmdline_exclude;
42 static struct btree *info_exclude;
43 static unsigned int timeout;
44
45 #if 0
46 static void indent_print(const char *string)
47 {
48         while (*string) {
49                 unsigned int line = strcspn(string, "\n");
50                 printf("\t%.*s", line, string);
51                 if (string[line] == '\n') {
52                         printf("\n");
53                         line++;
54                 }
55                 string += line;
56         }
57 }
58 #endif
59
60 bool ask(const char *question)
61 {
62         char reply[2];
63
64         printf("%s ", question);
65         fflush(stdout);
66
67         return fgets(reply, sizeof(reply), stdin) != NULL
68                 && toupper(reply[0]) == 'Y';
69 }
70
71 static const char *should_skip(struct manifest *m, struct ccanlint *i)
72 {
73         if (btree_lookup(cmdline_exclude, i->key))
74                 return "excluded on command line";
75
76         if (btree_lookup(info_exclude, i->key))
77                 return "excluded in _info file";
78         
79         if (i->skip)
80                 return i->skip;
81
82         if (i->skip_fail)
83                 return "dependency failed";
84
85         if (i->can_run)
86                 return i->can_run(m);
87         return NULL;
88 }
89
90 static bool run_test(struct ccanlint *i,
91                      bool quiet,
92                      unsigned int *running_score,
93                      unsigned int *running_total,
94                      struct manifest *m)
95 {
96         unsigned int timeleft;
97         const struct dependent *d;
98         const char *skip;
99         struct score *score;
100
101         //one less test to run through
102         list_for_each(&i->dependencies, d, node)
103                 d->dependent->num_depends--;
104
105         score = talloc(m, struct score);
106         list_head_init(&score->per_file_errors);
107         score->error = NULL;
108         score->pass = false;
109         score->score = 0;
110         score->total = 1;
111
112         skip = should_skip(m, i);
113
114         if (skip) {
115         skip:
116                 if (verbose && !streq(skip, "not relevant to target"))
117                         printf("%s: skipped (%s)\n", i->name, skip);
118
119                 /* If we're skipping this because a prereq failed, we fail:
120                  * count it as a score of 1. */
121                 if (i->skip_fail)
122                         (*running_total)++;
123                         
124                 list_del(&i->list);
125                 list_add_tail(&finished_tests, &i->list);
126                 list_for_each(&i->dependencies, d, node) {
127                         if (d->dependent->skip)
128                                 continue;
129                         d->dependent->skip = "dependency was skipped";
130                         d->dependent->skip_fail = i->skip_fail;
131                 }
132                 return i->skip_fail ? false : true;
133         }
134
135         timeleft = timeout ? timeout : default_timeout_ms;
136         i->check(m, i->keep_results, &timeleft, score);
137         if (timeout && timeleft == 0) {
138                 skip = "timeout";
139                 goto skip;
140         }
141
142         assert(score->score <= score->total);
143         if ((!score->pass && !quiet)
144             || (score->score < score->total && verbose)
145             || verbose > 1) {
146                 printf("%s: %s", i->name, score->pass ? "PASS" : "FAIL");
147                 if (score->total > 1)
148                         printf(" (+%u/%u)", score->score, score->total);
149                 printf("\n");
150         }
151
152         if (!quiet && !score->pass) {
153                 struct file_error *f;
154
155                 if (score->error)
156                         printf("%s:\n", score->error);
157
158                 list_for_each(&score->per_file_errors, f, list) {
159                         if (f->line)
160                                 printf("%s:%u:%s\n",
161                                        f->file->fullname, f->line, f->error);
162                         else if (f->file)
163                                 printf("%s:%s\n", f->file->fullname, f->error);
164                         else
165                                 printf("%s\n", f->error);
166                 }
167                 if (i->handle)
168                         i->handle(m, score);
169         }
170
171         *running_score += score->score;
172         *running_total += score->total;
173
174         list_del(&i->list);
175         list_add_tail(&finished_tests, &i->list);
176
177         if (!score->pass) {
178                 /* Skip any tests which depend on this one. */
179                 list_for_each(&i->dependencies, d, node) {
180                         if (d->dependent->skip)
181                                 continue;
182                         d->dependent->skip = "dependency failed";
183                         d->dependent->skip_fail = true;
184                 }
185         }
186         return score->pass;
187 }
188
189 static void register_test(struct list_head *h, struct ccanlint *test, ...)
190 {
191         va_list ap;
192         struct ccanlint *depends;
193         struct dependent *dchild;
194
195         list_add(h, &test->list);
196
197         va_start(ap, test);
198         /* Careful: we might have been initialized by a dependent. */
199         if (test->dependencies.n.next == NULL)
200                 list_head_init(&test->dependencies);
201
202         //dependent(s) args (if any), last one is NULL
203         while ((depends = va_arg(ap, struct ccanlint *)) != NULL) {
204                 dchild = malloc(sizeof(*dchild));
205                 dchild->dependent = test;
206                 /* The thing we depend on might not be initialized yet! */
207                 if (depends->dependencies.n.next == NULL)
208                         list_head_init(&depends->dependencies);
209                 list_add_tail(&depends->dependencies, &dchild->node);
210                 test->num_depends++;
211         }
212         va_end(ap);
213 }
214
215 /**
216  * get_next_test - retrieves the next test to be processed
217  **/
218 static inline struct ccanlint *get_next_test(struct list_head *test)
219 {
220         struct ccanlint *i;
221
222         if (list_empty(test))
223                 return NULL;
224
225         list_for_each(test, i, list) {
226                 if (i->num_depends == 0)
227                         return i;
228         }
229         errx(1, "Can't make process; test dependency cycle");
230 }
231
232 static void init_tests(void)
233 {
234         const struct ccanlint *i;
235         struct btree *keys, *names;
236
237 #undef REGISTER_TEST
238 #define REGISTER_TEST(name, ...) register_test(&normal_tests, &name, __VA_ARGS__, NULL)
239 #include "generated-normal-tests"
240 #undef REGISTER_TEST
241 #define REGISTER_TEST(name, ...) register_test(&compulsory_tests, &name, __VA_ARGS__, NULL)
242 #include "generated-compulsory-tests"
243
244         /* Self-consistency check: make sure no two tests
245            have the same key or name. */
246         keys = btree_new(btree_strcmp);
247         names = btree_new(btree_strcmp);
248         list_for_each(&compulsory_tests, i, list) {
249                 if (!btree_insert(keys, i->key))
250                         errx(1, "BUG: Duplicate test key '%s'", i->key);
251                 if (!btree_insert(keys, i->name))
252                         errx(1, "BUG: Duplicate test name '%s'", i->name);
253         }
254         list_for_each(&normal_tests, i, list) {
255                 if (!btree_insert(keys, i->key))
256                         errx(1, "BUG: Duplicate test key '%s'", i->key);
257                 if (!btree_insert(keys, i->name))
258                         errx(1, "BUG: Duplicate test name '%s'", i->name);
259         }
260         btree_delete(keys);
261         btree_delete(names);
262         
263         if (!verbose)
264                 return;
265
266         printf("\nCompulsory Tests\n");
267         list_for_each(&compulsory_tests, i, list) {
268                 printf("%s depends on %u others\n", i->name, i->num_depends);
269                 if (!list_empty(&i->dependencies)) {
270                         const struct dependent *d;
271                         printf("These depend on us:\n");
272                         list_for_each(&i->dependencies, d, node)
273                                 printf("\t%s\n", d->dependent->name);
274                 }
275         }
276
277         printf("\nNormal Tests\n");
278         list_for_each(&normal_tests, i, list) {
279                 printf("%s depends on %u others\n", i->name, i->num_depends);
280                 if (!list_empty(&i->dependencies)) {
281                         const struct dependent *d;
282                         printf("These depend on us:\n");
283                         list_for_each(&i->dependencies, d, node)
284                                 printf("\t%s\n", d->dependent->name);
285                 }
286         }
287 }
288
289 static struct ccanlint *find_test(const char *key)
290 {
291         struct ccanlint *i;
292
293         list_for_each(&compulsory_tests, i, list)
294                 if (streq(i->key, key))
295                         return i;
296
297         list_for_each(&normal_tests, i, list)
298                 if (streq(i->key, key))
299                         return i;
300
301         return NULL;
302 }
303
304 static char *keep_test(const char *testname, void *unused)
305 {
306         struct ccanlint *i = find_test(testname);
307         if (!i)
308                 errx(1, "No test %s to --keep", testname);
309         i->keep_results = true;
310         return NULL;
311 }
312
313 static char *skip_test(const char *testname, void *unused)
314 {
315         btree_insert(cmdline_exclude, optarg);
316         return NULL;
317 }
318
319 static void print_tests(struct list_head *tests, const char *type)
320 {
321         struct ccanlint *i;
322
323         printf("%s tests:\n", type);
324         /* This makes them print in topological order. */
325         while ((i = get_next_test(tests)) != NULL) {
326                 const struct dependent *d;
327                 printf("   %-25s %s\n", i->key, i->name);
328                 list_del(&i->list);
329                 list_for_each(&i->dependencies, d, node)
330                         d->dependent->num_depends--;
331         }
332 }
333
334 static char *list_tests(void *arg)
335 {
336         print_tests(&compulsory_tests, "Compulsory");
337         print_tests(&normal_tests, "Normal");
338         exit(0);
339 }
340
341 static char *strip(const void *ctx, const char *line)
342 {
343         line += strcspn(line, IDENT_CHARS "-");
344         return talloc_strndup(ctx, line, strspn(line, IDENT_CHARS "-"));
345 }
346
347 static void add_info_fails(struct ccan_file *info)
348 {
349         struct doc_section *d;
350         unsigned int i;
351
352         list_for_each(get_ccan_file_docs(info), d, list) {
353                 if (!streq(d->type, "fails"))
354                         continue;
355
356                 for (i = 0; i < d->num_lines; i++)
357                         btree_insert(info_exclude, strip(info, d->lines[i]));
358                 break;
359         }
360 }
361
362 static bool depends_on(struct ccanlint *i, struct ccanlint *target)
363 {
364         const struct dependent *d;
365
366         if (i == target)
367                 return true;
368
369         list_for_each(&i->dependencies, d, node) {
370                 if (depends_on(d->dependent, target))
371                         return true;
372         }
373         return false;
374 }
375
376 /* O(N^2), who cares? */
377 static void skip_unrelated_tests(struct ccanlint *target)
378 {
379         struct ccanlint *i;
380         struct list_head *list;
381
382         foreach_ptr(list, &compulsory_tests, &normal_tests)
383                 list_for_each(list, i, list)
384                         if (!depends_on(i, target))
385                                 i->skip = "not relevant to target";
386 }
387
388 int main(int argc, char *argv[])
389 {
390         bool summary = false;
391         unsigned int score = 0, total_score = 0;
392         struct manifest *m;
393         struct ccanlint *i;
394         const char *prefix = "";
395         char *dir = talloc_getcwd(NULL), *base_dir = dir, *target = NULL;
396         
397         init_tests();
398
399         cmdline_exclude = btree_new(btree_strcmp);
400         info_exclude = btree_new(btree_strcmp);
401
402         opt_register_arg("--dir|-d", opt_set_charp, opt_show_charp, &dir,
403                          "use this directory");
404         opt_register_noarg("-n|--safe-mode", opt_set_bool, &safe_mode,
405                          "do not compile anything");
406         opt_register_noarg("-l|--list-tests", list_tests, NULL,
407                          "list tests ccanlint performs (and exit)");
408         opt_register_arg("-k|--keep <testname>", keep_test, NULL, NULL,
409                            "keep results of <testname> (can be used multiple times)");
410         opt_register_noarg("--summary|-s", opt_set_bool, &summary,
411                            "simply give one line summary");
412         opt_register_noarg("--verbose|-v", opt_inc_intval, &verbose,
413                            "verbose mode (up to -vvvv)");
414         opt_register_arg("-x|--exclude <testname>", skip_test, NULL, NULL,
415                          "exclude <testname> (can be used multiple times)");
416         opt_register_arg("-t|--timeout <milleseconds>", opt_set_uintval,
417                          NULL, &timeout,
418                          "ignore (terminate) tests that are slower than this");
419         opt_register_arg("--target <testname>", opt_set_charp,
420                          NULL, &target,
421                          "only run one test (and its prerequisites)");
422         opt_register_noarg("-?|-h|--help", opt_usage_and_exit,
423                            "\nA program for checking and guiding development"
424                            " of CCAN modules.",
425                            "This usage message");
426
427         opt_parse(&argc, argv, opt_log_stderr_exit);
428
429         if (dir[0] != '/')
430                 dir = talloc_asprintf_append(NULL, "%s/%s", base_dir, dir);
431         if (dir != base_dir)
432                 prefix = talloc_append_string(talloc_basename(NULL, dir), ": ");
433         if (verbose >= 3)
434                 compile_verbose = true;
435         if (verbose >= 4)
436                 tools_verbose = true;
437
438         /* We move into temporary directory, so gcov dumps its files there. */
439         if (chdir(temp_dir(talloc_autofree_context())) != 0)
440                 err(1, "Error changing to %s temporary dir", temp_dir(NULL));
441
442         m = get_manifest(talloc_autofree_context(), dir);
443
444         /* Create a symlink from temp dir back to src dir's test directory. */
445         if (symlink(talloc_asprintf(m, "%s/test", dir),
446                     talloc_asprintf(m, "%s/test", temp_dir(NULL))) != 0)
447                 err(1, "Creating test symlink in %s", temp_dir(NULL));
448
449         if (target) {
450                 struct ccanlint *test;
451
452                 test = find_test(target);
453                 if (!test)
454                         err(1, "Unknown test to run '%s'", target);
455                 skip_unrelated_tests(test);
456         }
457
458         /* If you don't pass the compulsory tests, you get a score of 0. */
459         while ((i = get_next_test(&compulsory_tests)) != NULL) {
460                 if (!run_test(i, summary, &score, &total_score, m)) {
461                         printf("%sTotal score: 0/%u\n", prefix, total_score);
462                         errx(1, "%s%s failed", prefix, i->name);
463                 }
464         }
465
466         add_info_fails(m->info_file);
467         while ((i = get_next_test(&normal_tests)) != NULL)
468                 run_test(i, summary, &score, &total_score, m);
469
470         printf("%sTotal score: %u/%u\n", prefix, score, total_score);
471         return 0;
472 }