1 /* Code to move a ccan module into the ccan_ namespace. */
12 #include "ccan/str/str.h"
13 #include "ccan/take/take.h"
14 #include "ccan/rbuf/rbuf.h"
15 #include "ccan/err/err.h"
18 static bool verbose = false;
19 static int indent = 0;
20 #define verbose(args...) \
23 for (_i = 0; _i < indent; _i++) printf(" "); \
27 #define verbose_indent() (indent += 2)
28 #define verbose_unindent() (indent -= 2)
30 static int unlink_no_errno(const char *filename)
32 int ret = 0, serrno = errno;
33 if (unlink(filename) < 0)
39 static char **get_dir(const char *dir)
43 char **names = tal_arr(NULL, char *, 0), *n;
49 while ((ent = readdir(d)) != NULL) {
50 n = tal_fmt(names, "%s/%s", dir, ent->d_name);
51 tal_expand(&names, &n, 1);
54 tal_expand(&names, &n, 1);
65 static void __attribute__((noreturn)) usage(void)
68 "namespacize [--verbose] <dir>\n"
69 "namespacize [--verbose] --adjust <dir>...\n"
70 "The first form converts dir/ to insert 'ccan_' prefixes, and\n"
71 "then adjusts any other ccan directories at the same level which\n"
73 "--adjust does an adjustment for each directory, in case a\n"
74 "dependency has been namespacized\n");
77 static void add_replace(struct replace **repl, const char *str)
79 struct replace *new, *i;
81 /* Avoid duplicates. */
82 for (i = *repl; i; i = i->next)
83 if (streq(i->string, str))
86 new = tal(*repl, struct replace);
88 new->string = tal_strdup(new, str);
92 static void add_replace_tok(struct replace **repl, const char *s)
95 unsigned int len = strspn(s, IDENT_CHARS);
97 new = tal(*repl, struct replace);
99 new->string = tal_strndup(new, s, len);
103 static void look_for_macros(char *contents, struct replace **repl)
106 enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
108 /* Look for lines of form #define X */
109 for (p = contents; *p; p++) {
112 else if (!cisspace(*p)) {
113 if (state == LINESTART && *p == '#')
115 else if (state==HASH && !strncmp(p, "define", 6)) {
118 } else if (state == DEFINE) {
121 len = strspn(p, IDENT_CHARS);
124 s = tal_strndup(contents, p, len);
125 /* Don't wrap idempotent wrappers */
126 if (!strstarts(s, "CCAN_")) {
127 verbose("Found %s\n", s);
128 add_replace(repl, s);
138 /* Blank out preprocessor lines, and eliminate \ */
139 static void preprocess(char *p)
143 /* We assume backslashes are only used for macros. */
144 while ((s = strstr(p, "\\\n")) != NULL)
147 /* Now eliminate # lines. */
150 for (i = 0; p[i] != '\n'; i++)
153 while ((s = strstr(p, "\n#")) != NULL) {
155 for (i = 1; s[i] != '\n'; i++)
160 static char *get_statement(const void *ctx, char **p)
162 unsigned brackets = 0;
163 bool seen_brackets = false;
164 char *answer = tal_strdup(ctx, "");
167 if ((*p)[0] == '/' && (*p)[1] == '/')
168 *p += strcspn(*p, "\n");
169 else if ((*p)[0] == '/' && (*p)[1] == '*')
170 *p = strstr(*p, "*/") + 1;
173 if (c == ';' && !brackets) {
177 /* Compress whitespace into a single ' ' */
180 while (cisspace((*p)[1]))
182 } else if (c == '{' || c == '(' || c == '[') {
184 seen_brackets = true;
186 } else if (c == '}' || c == ')' || c == ']')
189 if (answer[0] != '\0' || c != ' ') {
190 tal_append_fmt(&answer, "%c", c);
192 if (c == '}' && seen_brackets && brackets == 0) {
203 /* This hack should handle well-formatted code. */
204 static void look_for_definitions(char *contents, struct replace **repl)
206 char *stmt, *p = contents;
208 preprocess(contents);
210 while ((stmt = get_statement(contents, &p)) != NULL) {
213 /* Definition of struct/union? */
214 if ((strncmp(stmt, "struct", 5) == 0
215 || strncmp(stmt, "union", 5) == 0)
216 && strchr(stmt, '{') && stmt[7] != '{')
217 add_replace_tok(repl, stmt+7);
219 /* Definition of var or typedef? */
220 for (i = strlen(stmt)-1; i >= 0; i--)
221 if (strspn(stmt+i, IDENT_CHARS) == 0)
224 if (i != strlen(stmt)-1) {
225 add_replace_tok(repl, stmt+i+1);
229 /* function or array declaration? */
230 len = strspn(stmt, IDENT_CHARS "* ");
231 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
232 if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
233 for (i = len-1; i >= 0; i--)
234 if (strspn(stmt+i, IDENT_CHARS) == 0)
237 add_replace_tok(repl, stmt+i+1);
241 /* Pointer to function? */
243 len += strspn(stmt + len, " *");
244 i = strspn(stmt + len, IDENT_CHARS);
245 if (i > 0 && stmt[len + i] == ')')
246 add_replace_tok(repl, stmt+len);
252 /* FIXME: Only does main header, should chase local includes. */
253 static void analyze_headers(const char *dir, struct replace **repl)
255 char *hdr, *contents;
257 /* Get hold of header, assume that's it. */
258 hdr = tal_fmt(dir, "%s/%s.h", dir, tal_basename(dir, dir));
259 contents = tal_grab_file(dir, hdr, NULL);
261 err(1, "Reading %s", hdr);
263 verbose("Looking in %s for macros\n", hdr);
265 look_for_macros(contents, repl);
268 verbose("Looking in %s for symbols\n", hdr);
270 look_for_definitions(contents, repl);
274 static void write_replacement_file(const char *dir, struct replace **repl)
276 char *replname = tal_fmt(dir, "%s/.namespacize", dir);
280 fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
283 errx(1, "%s already exists: can't namespacize twice",
285 err(1, "Opening %s", replname);
288 for (r = *repl; r; r = r->next) {
289 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
290 || write(fd, "\n", 1) != 1) {
291 unlink_no_errno(replname);
293 errx(1, "Short write to %s: disk full?",
295 errx(1, "Writing to %s", replname);
302 static void unlink_destroy(char *name)
307 static char *find_word(char *f, const char *str)
311 while ((p = strstr(p, str)) != NULL) {
312 /* Check it's not in the middle of a word. */
313 if (p > f && (cisalnum(p[-1]) || p[-1] == '_')) {
317 if (cisalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
326 /* This is horribly inefficient but simple. */
327 static const char *rewrite_file(const char *filename,
328 const struct replace *repl)
330 char *newname, *file;
333 verbose("Rewriting %s\n", filename);
334 file = tal_grab_file(filename, filename, NULL);
336 err(1, "Reading file %s", filename);
338 for (; repl; repl = repl->next) {
341 while ((p = find_word(file, repl->string)) != NULL) {
343 char *new = tal_arr(file, char, strlen(file)+6);
346 memcpy(new, file, off);
347 if (cisupper(repl->string[0]))
348 memcpy(new + off, "CCAN_", 5);
350 memcpy(new + off, "ccan_", 5);
351 strcpy(new + off + 5, file + off);
356 /* If we exit for some reason, we want this erased. */
357 newname = tal_fmt(autofree(), "%s.tmp", filename);
358 fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
360 err(1, "Creating %s", newname);
362 tal_add_destructor(newname, unlink_destroy);
363 if (write(fd, file, strlen(file)) != strlen(file)) {
365 errx(1, "Short write to %s: disk full?", newname);
366 errx(1, "Writing to %s", newname);
374 struct adjusted *next;
379 static void setup_adjust_files(const char *dir,
380 const struct replace *repl,
381 struct adjusted **adj)
385 for (files = get_dir(dir); *files; files++) {
386 if (strends(*files, "/test"))
387 setup_adjust_files(*files, repl, adj);
388 else if (strends(*files, ".c") || strends(*files, ".h")) {
389 struct adjusted *a = tal(dir, struct adjusted);
392 a->tmpfile = rewrite_file(a->file, repl);
398 /* This is the "commit" stage, so we hope it won't fail. */
399 static void rename_files(const struct adjusted *adj)
402 if (!move_file(adj->tmpfile, adj->file))
403 warn("Could not rename over '%s', we're in trouble",
409 static void convert_dir(const char *dir)
412 struct replace *replace = NULL;
413 struct adjusted *adj = NULL;
415 /* Remove any ugly trailing slashes. */
416 name = tal_strdup(NULL, dir);
417 while (strends(name, "/"))
418 name[strlen(name)-1] = '\0';
420 analyze_headers(name, &replace);
421 write_replacement_file(name, &replace);
422 setup_adjust_files(name, replace, &adj);
428 static struct replace *read_replacement_file(const char *depdir)
430 struct replace *repl = NULL;
431 char *replname = tal_fmt(depdir, "%s/.namespacize", depdir);
434 file = tal_grab_file(replname, replname, NULL);
437 err(1, "Opening %s", replname);
441 for (line = tal_strsplit(file, file, "\n", STR_EMPTY_OK); *line; line++)
442 add_replace(&repl, *line);
446 static void adjust_dir(const char *dir)
448 char *parent = tal_dirname(autofree(), dir);
451 verbose("Adjusting %s\n", dir);
453 for (deps = get_deps(parent, dir, "depends", false, compile_info);
457 struct adjusted *adj = NULL;
458 struct replace *repl;
460 depdir = tal_fmt(parent, "%s/%s", parent, *deps);
461 repl = read_replacement_file(depdir);
463 verbose("%s has been namespacized\n", depdir);
464 setup_adjust_files(parent, repl, &adj);
467 verbose("%s has not been namespacized\n", depdir);
474 static void adjust_dependents(const char *dir)
476 char *parent = tal_dirname(NULL, dir);
477 char *base = tal_basename(parent, dir);
480 verbose("Looking for dependents in %s\n", parent);
482 for (file = get_dir(parent); *file; file++) {
486 if (tal_basename(*file, *file)[0] == '.')
489 info = tal_fmt(*file, "%s/_info", *file);
490 if (access(info, R_OK) != 0)
493 for (deps = get_deps(*file, *file, "depends", false,
496 if (!strstarts(*deps, "ccan/"))
498 if (streq(*deps + strlen("ccan/"), base))
504 verbose("%s is not dependent\n", *file);
509 int main(int argc, char *argv[])
511 if (argv[1] && streq(argv[1], "--verbose")) {
518 verbose("Namespacizing %s\n", argv[1]);
520 convert_dir(argv[1]);
521 adjust_dependents(argv[1]);
526 if (argc > 2 && streq(argv[1], "--adjust")) {
529 for (i = 2; i < argc; i++)