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 if (write(fd, linemarker, strlen(linemarker)) != (int)strlen(linemarker)) {
50 return cast_const(char *, "Failure writing to temporary file");
53 for (i = 0; i < example->num_lines; i++) {
54 if (write(fd, example->lines[i], strlen(example->lines[i]))
55 != strlen(example->lines[i])
56 || write(fd, "\n", 1) != 1) {
58 return cast_const(char *,
59 "Failure writing to temporary file");
66 /* FIXME: We should have one example per function in header. */
67 static void extract_examples(struct manifest *m,
68 unsigned int *timeleft UNNEEDED,
71 struct ccan_file *f, *mainh = NULL; /* gcc complains uninitialized */
72 struct doc_section *d;
73 bool have_info_example = false, have_header_example = false;
76 list_for_each(get_ccan_file_docs(m->info_file), d, list) {
77 if (streq(d->type, "example")) {
78 score->error = add_example(m, m->info_file, d);
81 have_info_example = true;
85 /* Check all headers for examples. */
86 list_for_each(&m->h_files, f, list) {
87 if (strstarts(f->name, m->basename)
88 && strlen(f->name) == strlen(m->basename) + 2)
91 list_for_each(get_ccan_file_docs(f), d, list) {
92 if (streq(d->type, "example")) {
93 score->error = add_example(m, f, d);
96 have_header_example = true;
101 /* We don't fail ccanlint for this. */
103 if (have_info_example && have_header_example) {
104 score->score = score->total;
108 if (!have_info_example)
109 score_file_error(score, m->info_file, 0, "No Example: section");
110 if (!have_header_example)
111 score_file_error(score, mainh, 0, "No Example: section");
113 score->score = have_info_example + have_header_example;
116 struct ccanlint examples_exist = {
117 .key = "examples_exist",
118 .name = "_info and main header file have Example: sections",
119 .check = extract_examples,
120 .needs = "info_exists main_header_exists"
123 REGISTER_TEST(examples_exist);