1 #include <tools/ccanlint/ccanlint.h>
2 #include <tools/tools.h>
3 #include <ccan/talloc/talloc.h>
4 #include <ccan/str/str.h>
17 /* Creates and adds an example file. */
18 static char *add_example(struct manifest *m, struct ccan_file *source,
20 struct doc_section *example)
27 name = talloc_asprintf(m, "%s/example-%s-%s.c",
32 /* example->function == 'struct foo' */
33 while (strchr(name, ' '))
34 *strchr(name, ' ') = '_';
36 name = maybe_temp_file(m, ".c", keep, 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 for (i = 0; i < example->num_lines; i++) {
47 if (write(fd, example->lines[i], strlen(example->lines[i]))
48 != strlen(example->lines[i])
49 || write(fd, "\n", 1) != 1) {
51 return "Failure writing to temporary file";
58 /* FIXME: We should have one example per function in header. */
60 bool info_example, header_example;
64 static void *extract_examples(struct manifest *m,
66 unsigned int *timeleft)
69 struct doc_section *d;
70 struct score *score = talloc(m, struct score);
72 score->info_example = score->header_example = false;
75 list_for_each(get_ccan_file_docs(m->info_file), d, list) {
76 if (streq(d->type, "example")) {
77 score->error = add_example(m, m->info_file, keep, d);
80 score->info_example = true;
84 /* Check main header. */
85 list_for_each(&m->h_files, f, list) {
86 if (!strstarts(f->name, m->basename)
87 || 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, keep, d);
95 score->header_example = true;
102 static unsigned int score_examples(struct manifest *m, void *check_result)
104 struct score *score = check_result;
109 total += score->info_example;
110 total += score->header_example;
114 static const char *describe_examples(struct manifest *m,
117 struct score *score = check_result;
118 char *descrip = NULL;
123 if (!score->info_example)
124 descrip = talloc_asprintf(score,
125 "Your _info file has no module example.\n\n"
126 "There should be an Example: section of the _info documentation\n"
127 "which provides a concise toy program which uses your module\n");
129 if (!score->header_example)
130 descrip = talloc_asprintf(score,
131 "%sMain header file file has no examples\n\n"
132 "There should be an Example: section for each public function\n"
133 "demonstrating its use\n", descrip ? descrip : "");
138 struct ccanlint has_examples = {
139 .key = "has-examples",
140 .name = "_info and header files have examples",
141 .score = score_examples,
142 .check = extract_examples,
143 .describe = describe_examples,
147 REGISTER_TEST(has_examples, &has_info, NULL);