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