]> git.ozlabs.org Git - ccan/blob - tools/namespacize.c
update include to match header name conforming to CCAN standard
[ccan] / tools / namespacize.c
1 /* Code to move a ccan module into the ccan_ namespace. */
2 #include <err.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <stdbool.h>
6 #include <ctype.h>
7 #include <sys/types.h>
8 #include <dirent.h>
9 #include <unistd.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 #include "ccan/str/str.h"
14 #include "ccan/str_talloc/str_talloc.h"
15 #include "ccan/grab_file/grab_file.h"
16 #include "ccan/talloc/talloc.h"
17 #include "tools.h"
18
19 static bool verbose = false;
20 static int indent = 0;
21 #define verbose(args...)                                                \
22         do { if (verbose) {                                             \
23                         unsigned int _i;                                \
24                         for (_i = 0; _i < indent; _i++) printf(" ");    \
25                         printf(args);                                   \
26                 }                                                       \
27         } while(0)
28 #define verbose_indent() (indent += 2)
29 #define verbose_unindent() (indent -= 2)
30
31 static int unlink_no_errno(const char *filename)
32 {
33         int ret = 0, serrno = errno;
34         if (unlink(filename) < 0)
35                 ret = errno;
36         errno = serrno;
37         return ret;
38 }
39
40 static char **get_dir(const char *dir)
41 {
42         DIR *d;
43         struct dirent *ent;
44         char **names = NULL;
45         unsigned int size = 0;
46
47         d = opendir(dir);
48         if (!d)
49                 return NULL;
50
51         while ((ent = readdir(d)) != NULL) {
52                 names = talloc_realloc(dir, names, char *, size + 2);
53                 names[size++]
54                         = talloc_asprintf(names, "%s/%s", dir, ent->d_name);
55         }
56         names[size++] = NULL;
57         closedir(d);
58         return names;
59 }
60
61 struct replace
62 {
63         struct replace *next;
64         char *string;
65 };
66
67 static void __attribute__((noreturn)) usage(void)
68 {
69         errx(1, "Usage:\n"
70              "namespacize [--verbose] <dir>\n"
71              "namespacize [--verbose] --adjust <dir>...\n"
72              "The first form converts dir/ to insert 'ccan_' prefixes, and\n"
73              "then adjusts any other ccan directories at the same level which\n"
74              "are effected.\n"
75              "--adjust does an adjustment for each directory, in case a\n"
76              "dependency has been namespacized\n");
77 }
78
79 static void add_replace(struct replace **repl, const char *str)
80 {
81         struct replace *new, *i;
82
83         /* Avoid duplicates. */
84         for (i = *repl; i; i = i->next)
85                 if (streq(i->string, str))
86                         return;
87
88         new = talloc(*repl, struct replace);
89         new->next = *repl;
90         new->string = talloc_strdup(new, str);
91         *repl = new;
92 }
93
94 static void add_replace_tok(struct replace **repl, const char *s)
95 {
96         struct replace *new;
97         unsigned int len = strspn(s, IDENT_CHARS);
98
99         new = talloc(*repl, struct replace);
100         new->next = *repl;
101         new->string = talloc_strndup(new, s, len);
102         *repl = new;
103 }
104
105 static void look_for_macros(char *contents, struct replace **repl)
106 {
107         char *p;
108         enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
109
110         /* Look for lines of form #define X */
111         for (p = contents; *p; p++) {
112                 if (*p == '\n')
113                         state = LINESTART;
114                 else if (!isspace(*p)) {
115                         if (state == LINESTART && *p == '#')
116                                 state = HASH;
117                         else if (state==HASH && !strncmp(p, "define", 6)) {
118                                 state = DEFINE;
119                                 p += 5;
120                         } else if (state == DEFINE) {
121                                 unsigned int len;
122
123                                 len = strspn(p, IDENT_CHARS);
124                                 if (len) {
125                                         char *s;
126                                         s = talloc_strndup(contents, p, len);
127                                         /* Don't wrap idempotent wrappers */
128                                         if (!strstarts(s, "CCAN_")) {
129                                                 verbose("Found %s\n", s);
130                                                 add_replace(repl, s);
131                                         }
132                                 }
133                                 state = NONE;
134                         } else
135                                 state = NONE;
136                 }
137         }
138 }
139
140 /* Blank out preprocessor lines, and eliminate \ */
141 static void preprocess(char *p)
142 {
143         char *s;
144
145         /* We assume backslashes are only used for macros. */
146         while ((s = strstr(p, "\\\n")) != NULL)
147                 s[0] = s[1] = ' ';
148
149         /* Now eliminate # lines. */
150         if (p[0] == '#') {
151                 unsigned int i;
152                 for (i = 0; p[i] != '\n'; i++)
153                         p[i] = ' ';
154         }
155         while ((s = strstr(p, "\n#")) != NULL) {
156                 unsigned int i;
157                 for (i = 1; s[i] != '\n'; i++)
158                         s[i] = ' ';
159         }
160 }
161
162 static char *get_statement(const void *ctx, char **p)
163 {
164         unsigned brackets = 0;
165         bool seen_brackets = false;
166         char *answer = talloc_strdup(ctx, "");
167
168         for (;;) {
169                 if ((*p)[0] == '/' && (*p)[1] == '/')
170                         *p += strcspn(*p, "\n");
171                 else if ((*p)[0] == '/' && (*p)[1] == '*')
172                         *p = strstr(*p, "*/") + 1;
173                 else {
174                         char c = **p;
175                         if (c == ';' && !brackets) {
176                                 (*p)++;
177                                 return answer;
178                         }
179                         /* Compress whitespace into a single ' ' */
180                         if (isspace(c)) {
181                                 c = ' ';
182                                 while (isspace((*p)[1]))
183                                         (*p)++;
184                         } else if (c == '{' || c == '(' || c == '[') {
185                                 if (c == '(')
186                                         seen_brackets = true;
187                                 brackets++;
188                         } else if (c == '}' || c == ')' || c == ']')
189                                 brackets--;
190
191                         if (answer[0] != '\0' || c != ' ') {
192                                 answer = talloc_realloc(NULL, answer, char,
193                                                         strlen(answer) + 2);
194                                 answer[strlen(answer)+1] = '\0';
195                                 answer[strlen(answer)] = c;
196                         }
197                         if (c == '}' && seen_brackets && brackets == 0) {
198                                 (*p)++;
199                                 return answer;
200                         }
201                 }
202                 (*p)++;
203                 if (**p == '\0')
204                         return NULL;
205         }
206 }
207
208 /* This hack should handle well-formatted code. */
209 static void look_for_definitions(char *contents, struct replace **repl)
210 {
211         char *stmt, *p = contents;
212
213         preprocess(contents);
214
215         while ((stmt = get_statement(contents, &p)) != NULL) {
216                 int i, len;
217
218                 /* Definition of struct/union? */
219                 if ((strncmp(stmt, "struct", 5) == 0
220                      || strncmp(stmt, "union", 5) == 0)
221                     && strchr(stmt, '{') && stmt[7] != '{')
222                         add_replace_tok(repl, stmt+7);
223
224                 /* Definition of var or typedef? */
225                 for (i = strlen(stmt)-1; i >= 0; i--)
226                         if (strspn(stmt+i, IDENT_CHARS) == 0)
227                                 break;
228
229                 if (i != strlen(stmt)-1) {
230                         add_replace_tok(repl, stmt+i+1);
231                         continue;
232                 }
233
234                 /* function or array declaration? */
235                 len = strspn(stmt, IDENT_CHARS "* ");
236                 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
237                         if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
238                                 for (i = len-1; i >= 0; i--)
239                                         if (strspn(stmt+i, IDENT_CHARS) == 0)
240                                                 break;
241                                 if (i != len-1) {
242                                         add_replace_tok(repl, stmt+i+1);
243                                         continue;
244                                 }
245                         } else {
246                                 /* Pointer to function? */
247                                 len++;
248                                 len += strspn(stmt + len, " *");
249                                 i = strspn(stmt + len, IDENT_CHARS);
250                                 if (i > 0 && stmt[len + i] == ')')
251                                         add_replace_tok(repl, stmt+len);
252                         }
253                 }
254         }
255 }
256
257 /* FIXME: Only does main header, should chase local includes. */ 
258 static void analyze_headers(const char *dir, struct replace **repl)
259 {
260         char *hdr, *contents;
261
262         /* Get hold of header, assume that's it. */
263         hdr = talloc_asprintf(dir, "%s/%s.h", dir, talloc_basename(dir, dir));
264         contents = grab_file(dir, hdr, NULL);
265         if (!contents)
266                 err(1, "Reading %s", hdr);
267
268         verbose("Looking in %s for macros\n", hdr);
269         verbose_indent();
270         look_for_macros(contents, repl);
271         verbose_unindent();
272
273         verbose("Looking in %s for symbols\n", hdr);
274         verbose_indent();
275         look_for_definitions(contents, repl);
276         verbose_unindent();
277 }
278
279 static void write_replacement_file(const char *dir, struct replace **repl)
280 {
281         char *replname = talloc_asprintf(dir, "%s/.namespacize", dir);
282         int fd;
283         struct replace *r;
284
285         fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
286         if (fd < 0) {
287                 if (errno == EEXIST)
288                         errx(1, "%s already exists: can't namespacize twice",
289                              replname);
290                 err(1, "Opening %s", replname);
291         }
292
293         for (r = *repl; r; r = r->next) {
294                 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
295                     || write(fd, "\n", 1) != 1) {
296                         unlink_no_errno(replname);
297                         if (errno == 0)
298                                 errx(1, "Short write to %s: disk full?",
299                                      replname);
300                         errx(1, "Writing to %s", replname);
301                 }
302         }
303
304         close(fd);
305 }
306
307 static int unlink_destroy(char *name)
308 {
309         unlink(name);
310         return 0;
311 }
312
313 static char *find_word(char *f, const char *str)
314 {
315         char *p = f;
316
317         while ((p = strstr(p, str)) != NULL) {
318                 /* Check it's not in the middle of a word. */
319                 if (p > f && (isalnum(p[-1]) || p[-1] == '_')) {
320                         p++;
321                         continue;
322                 }
323                 if (isalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
324                         p++;
325                         continue;
326                 }
327                 return p;
328         }
329         return NULL;
330 }
331
332 /* This is horribly inefficient but simple. */
333 static const char *rewrite_file(const char *filename,
334                                 const struct replace *repl)
335 {
336         char *newname, *file;
337         int fd;
338
339         verbose("Rewriting %s\n", filename);
340         file = grab_file(filename, filename, NULL);
341         if (!file)
342                 err(1, "Reading file %s", filename);
343
344         for (; repl; repl = repl->next) {
345                 char *p;
346
347                 while ((p = find_word(file, repl->string)) != NULL) {
348                         unsigned int off;
349                         char *new = talloc_array(file, char, strlen(file)+6);
350
351                         off = p - file;
352                         memcpy(new, file, off);
353                         if (isupper(repl->string[0]))
354                                 memcpy(new + off, "CCAN_", 5);
355                         else
356                                 memcpy(new + off, "ccan_", 5);
357                         strcpy(new + off + 5, file + off);
358                         file = new;
359                 }
360         }
361
362         /* If we exit for some reason, we want this erased. */
363         newname = talloc_asprintf(talloc_autofree_context(), "%s.tmp",
364                                   filename);
365         fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
366         if (fd < 0)
367                 err(1, "Creating %s", newname);
368
369         talloc_set_destructor(newname, unlink_destroy);
370         if (write(fd, file, strlen(file)) != strlen(file)) {
371                 if (errno == 0)
372                         errx(1, "Short write to %s: disk full?", newname);
373                 errx(1, "Writing to %s", newname);
374         }
375         close(fd);
376         return newname;
377 }
378
379 struct adjusted
380 {
381         struct adjusted *next;
382         const char *file;
383         const char *tmpfile;
384 };
385
386 static void setup_adjust_files(const char *dir,
387                                const struct replace *repl,
388                                struct adjusted **adj)
389 {
390         char **files;
391
392         for (files = get_dir(dir); *files; files++) {
393                 if (strends(*files, "/test"))
394                         setup_adjust_files(*files, repl, adj);
395                 else if (strends(*files, ".c") || strends(*files, ".h")) {
396                         struct adjusted *a = talloc(dir, struct adjusted);
397                         a->next = *adj;
398                         a->file = *files;
399                         a->tmpfile = rewrite_file(a->file, repl);
400                         *adj = a;
401                 }
402         }
403 }
404
405 /* This is the "commit" stage, so we hope it won't fail. */
406 static void rename_files(const struct adjusted *adj)
407 {
408         while (adj) {
409                 if (!move_file(adj->tmpfile, adj->file))
410                         warn("Could not rename over '%s', we're in trouble",
411                              adj->file);
412                 adj = adj->next;
413         }
414 }
415
416 static void convert_dir(const char *dir)
417 {
418         char *name;
419         struct replace *replace = NULL;
420         struct adjusted *adj = NULL;
421
422         /* Remove any ugly trailing slashes. */
423         name = talloc_strdup(NULL, dir);
424         while (strends(name, "/"))
425                 name[strlen(name)-1] = '\0';
426
427         analyze_headers(name, &replace);
428         write_replacement_file(name, &replace);
429         setup_adjust_files(name, replace, &adj);
430         rename_files(adj);
431         talloc_free(name);
432         talloc_free(replace);
433 }
434
435 static struct replace *read_replacement_file(const char *depdir)
436 {
437         struct replace *repl = NULL;
438         char *replname = talloc_asprintf(depdir, "%s/.namespacize", depdir);
439         char *file, **line;
440
441         file = grab_file(replname, replname, NULL);
442         if (!file) {
443                 if (errno != ENOENT)
444                         err(1, "Opening %s", replname);
445                 return NULL;
446         }
447
448         for (line = strsplit(file, file, "\n"); *line; line++)
449                 add_replace(&repl, *line);
450         return repl;
451 }
452
453 static void adjust_dir(const char *dir)
454 {
455         char *parent = talloc_dirname(talloc_autofree_context(), dir);
456         char **deps;
457
458         verbose("Adjusting %s\n", dir);
459         verbose_indent();
460         for (deps = get_deps(parent, dir, false, NULL); *deps; deps++) {
461                 char *depdir;
462                 struct adjusted *adj = NULL;
463                 struct replace *repl;
464
465                 depdir = talloc_asprintf(parent, "%s/%s", parent, *deps);
466                 repl = read_replacement_file(depdir);
467                 if (repl) {
468                         verbose("%s has been namespacized\n", depdir);
469                         setup_adjust_files(parent, repl, &adj);
470                         rename_files(adj);
471                 } else
472                         verbose("%s has not been namespacized\n", depdir);
473                 talloc_free(depdir);
474         }
475         verbose_unindent();
476         talloc_free(parent);
477 }
478
479 static void adjust_dependents(const char *dir)
480 {
481         char *parent = talloc_dirname(NULL, dir);
482         char *base = talloc_basename(parent, dir);
483         char **file;
484
485         verbose("Looking for dependents in %s\n", parent);
486         verbose_indent();
487         for (file = get_dir(parent); *file; file++) {
488                 char *info, **deps;
489                 bool isdep = false;
490
491                 if (talloc_basename(*file, *file)[0] == '.')
492                         continue;
493
494                 info = talloc_asprintf(*file, "%s/_info", *file);
495                 if (access(info, R_OK) != 0)
496                         continue;
497
498                 for (deps = get_deps(*file, *file, false, NULL);
499                      *deps; deps++) {
500                         if (!strstarts(*deps, "ccan/"))
501                                 continue;
502                         if (streq(*deps + strlen("ccan/"), base))
503                                 isdep = true;
504                 }
505                 if (isdep)
506                         adjust_dir(*file);
507                 else
508                         verbose("%s is not dependent\n", *file);
509         }
510         verbose_unindent();
511 }
512
513 int main(int argc, char *argv[])
514 {
515         if (argv[1] && streq(argv[1], "--verbose")) {
516                 verbose = true;
517                 argv++;
518                 argc--;
519         }
520
521         if (argc == 2) {
522                 verbose("Namespacizing %s\n", argv[1]);
523                 verbose_indent();
524                 convert_dir(argv[1]);
525                 adjust_dependents(argv[1]);
526                 verbose_unindent();
527                 return 0;
528         }
529
530         if (argc > 2 && streq(argv[1], "--adjust")) {
531                 unsigned int i;
532
533                 for (i = 2; i < argc; i++)
534                         adjust_dir(argv[i]);
535                 return 0;
536         }
537         usage();
538 }