ccanlint: Add -k option to keep results.
[ccan] / tools / ccanlint / compulsory_tests / check_includes_build.c
1 #include <tools/ccanlint/ccanlint.h>
2 #include <tools/tools.h>
3 #include <ccan/talloc/talloc.h>
4 #include <ccan/grab_file/grab_file.h>
5 #include <ccan/str/str.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <limits.h>
11 #include <errno.h>
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <err.h>
15 #include <string.h>
16 #include <ctype.h>
17
18 static const char *can_build(struct manifest *m)
19 {
20         if (safe_mode)
21                 return "Safe mode enabled";
22         return NULL;
23 }
24
25 static struct ccan_file *main_header(struct manifest *m)
26 {
27         struct ccan_file *f;
28
29         list_for_each(&m->h_files, f, list) {
30                 if (strstarts(f->name, m->basename)
31                     && strlen(f->name) == strlen(m->basename) + 2)
32                         return f;
33         }
34         /* Should not happen: we depend on has_main_header */
35         return NULL;
36 }
37
38 static void *check_includes_build(struct manifest *m,
39                                   bool keep,
40                                   unsigned int *timeleft)
41 {
42         char *contents;
43         char *tmpsrc, *tmpobj;
44         int fd;
45         struct ccan_file *mainh = main_header(m);
46
47         tmpsrc = maybe_temp_file(m, "-included.c", keep, mainh->fullname);
48         tmpobj = maybe_temp_file(m, ".o", keep, tmpsrc);
49
50         fd = open(tmpsrc, O_WRONLY | O_CREAT | O_EXCL, 0600);
51         if (fd < 0)
52                 return talloc_asprintf(m, "Creating temporary file %s: %s",
53                                        tmpsrc, strerror(errno));
54
55         contents = talloc_asprintf(tmpsrc, "#include <ccan/%s/%s.h>\n",
56                                    m->basename, m->basename);
57         if (write(fd, contents, strlen(contents)) != strlen(contents)) {
58                 close(fd);
59                 return "Failure writing to temporary file";
60         }
61         close(fd);
62
63         return compile_object(m, tmpsrc, ccan_dir, tmpobj);
64 }
65
66 static const char *describe_includes_build(struct manifest *m,
67                                            void *check_result)
68 {
69         return talloc_asprintf(check_result, 
70                                "#include of the main header file:\n"
71                                "%s", (char *)check_result);
72 }
73
74 struct ccanlint includes_build = {
75         .key = "include-main",
76         .name = "Modules main header compiles",
77         .total_score = 1,
78         .check = check_includes_build,
79         .describe = describe_includes_build,
80         .can_run = can_build,
81 };
82
83 REGISTER_TEST(includes_build, &depends_exist, &has_main_header, NULL);