1 #include <tools/ccanlint/ccanlint.h>
2 #include <tools/tools.h>
3 #include <ccan/talloc/talloc.h>
4 #include <ccan/str/str.h>
5 #include <ccan/cast/cast.h>
18 /* Creates and adds an example file. */
19 static char *add_example(struct manifest *m, struct ccan_file *source,
20 struct doc_section *example)
22 char *name, *linemarker;
27 name = talloc_asprintf(m, "%s/example-%s-%s.c",
32 /* example->function == 'struct foo' */
33 while (strchr(name, ' '))
34 *strchr(name, ' ') = '_';
36 name = temp_file(m, ".c", name);
37 f = new_ccan_file(m, talloc_dirname(m, name), talloc_basename(m, name));
38 talloc_steal(f, name);
39 list_add_tail(&m->examples, &f->list);
41 fd = open(f->fullname, O_WRONLY | O_CREAT | O_EXCL, 0600);
43 return talloc_asprintf(m, "Creating temporary file %s: %s",
44 f->fullname, strerror(errno));
46 /* Add #line to demark where we are from, so errors are correct! */
47 linemarker = talloc_asprintf(f, "#line %i \"%s\"\n",
48 example->srcline+2, source->fullname);
49 write(fd, linemarker, strlen(linemarker));
51 for (i = 0; i < example->num_lines; i++) {
52 if (write(fd, example->lines[i], strlen(example->lines[i]))
53 != strlen(example->lines[i])
54 || write(fd, "\n", 1) != 1) {
56 return cast_const(char *,
57 "Failure writing to temporary file");
64 /* FIXME: We should have one example per function in header. */
65 static void extract_examples(struct manifest *m,
66 unsigned int *timeleft,
69 struct ccan_file *f, *mainh = NULL; /* gcc complains uninitialized */
70 struct doc_section *d;
71 bool have_info_example = false, have_header_example = false;
74 list_for_each(get_ccan_file_docs(m->info_file), d, list) {
75 if (streq(d->type, "example")) {
76 score->error = add_example(m, m->info_file, d);
79 have_info_example = true;
83 /* Check main header. */
84 list_for_each(&m->h_files, f, list) {
85 if (!strstarts(f->name, m->basename)
86 || strlen(f->name) != strlen(m->basename) + 2)
90 list_for_each(get_ccan_file_docs(f), d, list) {
91 if (streq(d->type, "example")) {
92 score->error = add_example(m, f, d);
95 have_header_example = true;
100 /* We don't fail ccanlint for this. */
102 if (have_info_example && have_header_example) {
103 score->score = score->total;
107 if (!have_info_example)
108 score_file_error(score, m->info_file, 0, "No Example: section");
109 if (!have_header_example)
110 score_file_error(score, mainh, 0, "No Example: section");
112 score->score = have_info_example + have_header_example;
115 struct ccanlint examples_exist = {
116 .key = "examples_exist",
117 .name = "_info and main header file have Example: sections",
118 .check = extract_examples,
119 .needs = "info_exists"
122 REGISTER_TEST(examples_exist);