1 #include <tools/ccanlint/ccanlint.h>
2 #include <tools/tools.h>
3 #include <ccan/str/str.h>
4 #include <ccan/tal/path/path.h>
5 #include <ccan/take/take.h>
6 #include <ccan/cast/cast.h>
19 /* Creates and adds an example file. */
20 static char *add_example(struct manifest *m, struct ccan_file *source,
21 struct doc_section *example)
23 char *name, *linemarker;
28 name = tal_fmt(m, "example-%s-%s",
29 source->name, example->function);
30 /* example->function == 'struct foo' */
31 while (strchr(name, ' '))
32 *strchr(name, ' ') = '_';
34 name = temp_file(m, ".c", take(name));
35 f = new_ccan_file(m, take(path_dirname(m, name)),
36 take(path_basename(m, name)));
38 list_add_tail(&m->examples, &f->list);
40 fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
42 return tal_fmt(m, "Creating temporary file %s: %s",
43 f->fullname, strerror(errno));
45 /* Add #line to demark where we are from, so errors are correct! */
46 linemarker = tal_fmt(f, "#line %i \"%s\"\n",
47 example->srcline+2, source->fullname);
48 write(fd, linemarker, strlen(linemarker));
50 for (i = 0; i < example->num_lines; i++) {
51 if (write(fd, example->lines[i], strlen(example->lines[i]))
52 != strlen(example->lines[i])
53 || write(fd, "\n", 1) != 1) {
55 return cast_const(char *,
56 "Failure writing to temporary file");
63 /* FIXME: We should have one example per function in header. */
64 static void extract_examples(struct manifest *m,
65 unsigned int *timeleft,
68 struct ccan_file *f, *mainh = NULL; /* gcc complains uninitialized */
69 struct doc_section *d;
70 bool have_info_example = false, have_header_example = false;
73 list_for_each(get_ccan_file_docs(m->info_file), d, list) {
74 if (streq(d->type, "example")) {
75 score->error = add_example(m, m->info_file, d);
78 have_info_example = true;
82 /* Check all headers for examples. */
83 list_for_each(&m->h_files, f, list) {
84 if (strstarts(f->name, m->basename)
85 && strlen(f->name) == strlen(m->basename) + 2)
88 list_for_each(get_ccan_file_docs(f), d, list) {
89 if (streq(d->type, "example")) {
90 score->error = add_example(m, f, d);
93 have_header_example = true;
98 /* We don't fail ccanlint for this. */
100 if (have_info_example && have_header_example) {
101 score->score = score->total;
105 if (!have_info_example)
106 score_file_error(score, m->info_file, 0, "No Example: section");
107 if (!have_header_example)
108 score_file_error(score, mainh, 0, "No Example: section");
110 score->score = have_info_example + have_header_example;
113 struct ccanlint examples_exist = {
114 .key = "examples_exist",
115 .name = "_info and main header file have Example: sections",
116 .check = extract_examples,
117 .needs = "info_exists main_header_exists"
120 REGISTER_TEST(examples_exist);