33668ed84c5ac3a3ccabe413e8dfb4298faa5dfd
[ccan] / tools / ccanlint / 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 int cleanup_testfile(char *testfile)
26 {
27         unlink(testfile);
28         return 0;
29 }
30
31 static void *check_includes_build(struct manifest *m)
32 {
33         char *contents;
34         char *tmpfile, *objfile;
35         int fd;
36
37         tmpfile = talloc_strdup(m, tempnam("/tmp", "ccanlint"));
38         talloc_set_destructor(tmpfile, cleanup_testfile);
39         objfile = talloc_strdup(m, tempnam("/tmp", "ccanlint"));
40         talloc_set_destructor(objfile, cleanup_testfile);
41
42         fd = open(tmpfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
43         if (fd < 0)
44                 return talloc_asprintf(m, "Creating temporary file: %s",
45                                        strerror(errno));
46
47         contents = talloc_asprintf(tmpfile, "#include <ccan/%s/%s.h>\n",
48                                    m->basename, m->basename);
49         if (write(fd, contents, strlen(contents)) != strlen(contents)) {
50                 close(fd);
51                 return "Failure writing to temporary file";
52         }
53         close(fd);
54
55         return run_command(m, "cc " CFLAGS " -o %s -c -x c %s",
56                            objfile, tmpfile);
57 }
58
59 static const char *describe_includes_build(struct manifest *m,
60                                            void *check_result)
61 {
62         return talloc_asprintf(check_result, 
63                                "#include of the main header file:\n"
64                                "%s", (char *)check_result);
65 }
66
67 struct ccanlint includes_build = {
68         .name = "Can compile against main header",
69         .total_score = 1,
70         .check = check_includes_build,
71         .describe = describe_includes_build,
72         .can_run = can_build,
73 };
74
75 REGISTER_TEST(includes_build, &depends_exist, NULL);