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