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/tal/path/path.h"
16 #include "ccan/tal/grab_file/grab_file.h"
17 #include "ccan/err/err.h"
20 static bool verbose = false;
21 static int indent = 0;
22 #define verbose(args...) \
25 for (_i = 0; _i < indent; _i++) printf(" "); \
29 #define verbose_indent() (indent += 2)
30 #define verbose_unindent() (indent -= 2)
32 static int unlink_no_errno(const char *filename)
34 int ret = 0, serrno = errno;
35 if (unlink(filename) < 0)
41 static char **get_dir(const char *dir)
45 char **names = tal_arr(NULL, char *, 0), *n;
51 while ((ent = readdir(d)) != NULL) {
52 n = tal_fmt(names, "%s/%s", dir, ent->d_name);
53 tal_expand(&names, &n, 1);
56 tal_expand(&names, &n, 1);
67 static void __attribute__((noreturn)) usage(void)
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"
75 "--adjust does an adjustment for each directory, in case a\n"
76 "dependency has been namespacized\n");
79 static void add_replace(struct replace **repl, const char *str)
81 struct replace *new, *i;
83 /* Avoid duplicates. */
84 for (i = *repl; i; i = i->next)
85 if (streq(i->string, str))
88 new = tal(*repl, struct replace);
90 new->string = tal_strdup(new, str);
94 static void add_replace_tok(struct replace **repl, const char *s)
97 unsigned int len = strspn(s, IDENT_CHARS);
99 new = tal(*repl, struct replace);
101 new->string = tal_strndup(new, s, len);
105 static void look_for_macros(char *contents, struct replace **repl)
108 enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
110 /* Look for lines of form #define X */
111 for (p = contents; *p; p++) {
114 else if (!cisspace(*p)) {
115 if (state == LINESTART && *p == '#')
117 else if (state==HASH && !strncmp(p, "define", 6)) {
120 } else if (state == DEFINE) {
123 len = strspn(p, IDENT_CHARS);
126 s = tal_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);
140 /* Blank out preprocessor lines, and eliminate \ */
141 static void preprocess(char *p)
145 /* We assume backslashes are only used for macros. */
146 while ((s = strstr(p, "\\\n")) != NULL)
149 /* Now eliminate # lines. */
152 for (i = 0; p[i] != '\n'; i++)
155 while ((s = strstr(p, "\n#")) != NULL) {
157 for (i = 1; s[i] != '\n'; i++)
162 static char *get_statement(const void *ctx, char **p)
164 unsigned brackets = 0;
165 bool seen_brackets = false;
166 char *answer = tal_strdup(ctx, "");
169 if ((*p)[0] == '/' && (*p)[1] == '/')
170 *p += strcspn(*p, "\n");
171 else if ((*p)[0] == '/' && (*p)[1] == '*')
172 *p = strstr(*p, "*/") + 1;
175 if (c == ';' && !brackets) {
179 /* Compress whitespace into a single ' ' */
182 while (cisspace((*p)[1]))
184 } else if (c == '{' || c == '(' || c == '[') {
186 seen_brackets = true;
188 } else if (c == '}' || c == ')' || c == ']')
191 if (answer[0] != '\0' || c != ' ') {
192 tal_append_fmt(&answer, "%c", c);
194 if (c == '}' && seen_brackets && brackets == 0) {
205 /* This hack should handle well-formatted code. */
206 static void look_for_definitions(char *contents, struct replace **repl)
208 char *stmt, *p = contents;
210 preprocess(contents);
212 while ((stmt = get_statement(contents, &p)) != NULL) {
215 /* Definition of struct/union? */
216 if ((strncmp(stmt, "struct", 5) == 0
217 || strncmp(stmt, "union", 5) == 0)
218 && strchr(stmt, '{') && stmt[7] != '{')
219 add_replace_tok(repl, stmt+7);
221 /* Definition of var or typedef? */
222 for (i = strlen(stmt)-1; i >= 0; i--)
223 if (strspn(stmt+i, IDENT_CHARS) == 0)
226 if (i != strlen(stmt)-1) {
227 add_replace_tok(repl, stmt+i+1);
231 /* function or array declaration? */
232 len = strspn(stmt, IDENT_CHARS "* ");
233 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
234 if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
235 for (i = len-1; i >= 0; i--)
236 if (strspn(stmt+i, IDENT_CHARS) == 0)
239 add_replace_tok(repl, stmt+i+1);
243 /* Pointer to function? */
245 len += strspn(stmt + len, " *");
246 i = strspn(stmt + len, IDENT_CHARS);
247 if (i > 0 && stmt[len + i] == ')')
248 add_replace_tok(repl, stmt+len);
254 /* FIXME: Only does main header, should chase local includes. */
255 static void analyze_headers(const char *dir, struct replace **repl)
257 char *hdr, *contents;
259 /* Get hold of header, assume that's it. */
260 hdr = tal_fmt(dir, "%s.h",
261 path_join(NULL, dir, take(path_basename(NULL, dir))));
263 contents = grab_file(dir, hdr);
265 err(1, "Reading %s", hdr);
267 verbose("Looking in %s for macros\n", hdr);
269 look_for_macros(contents, repl);
272 verbose("Looking in %s for symbols\n", hdr);
274 look_for_definitions(contents, repl);
278 static void write_replacement_file(const char *dir, struct replace **repl)
280 char *replname = path_join(dir, dir, ".namespacize");
284 fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
287 errx(1, "%s already exists: can't namespacize twice",
289 err(1, "Opening %s", replname);
292 for (r = *repl; r; r = r->next) {
293 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
294 || write(fd, "\n", 1) != 1) {
295 unlink_no_errno(replname);
297 errx(1, "Short write to %s: disk full?",
299 errx(1, "Writing to %s", replname);
306 static void unlink_destroy(char *name)
311 static char *find_word(char *f, const char *str)
315 while ((p = strstr(p, str)) != NULL) {
316 /* Check it's not in the middle of a word. */
317 if (p > f && (cisalnum(p[-1]) || p[-1] == '_')) {
321 if (cisalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
330 /* This is horribly inefficient but simple. */
331 static const char *rewrite_file(const char *filename,
332 const struct replace *repl)
334 char *newname, *file;
337 verbose("Rewriting %s\n", filename);
338 file = grab_file(filename, filename);
340 err(1, "Reading file %s", filename);
342 for (; repl; repl = repl->next) {
345 while ((p = find_word(file, repl->string)) != NULL) {
347 char *new = tal_arr(file, char, strlen(file)+6);
350 memcpy(new, file, off);
351 if (cisupper(repl->string[0]))
352 memcpy(new + off, "CCAN_", 5);
354 memcpy(new + off, "ccan_", 5);
355 strcpy(new + off + 5, file + off);
360 /* If we exit for some reason, we want this erased. */
361 newname = tal_fmt(autofree(), "%s.tmp", filename);
362 fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
364 err(1, "Creating %s", newname);
366 tal_add_destructor(newname, unlink_destroy);
367 if (write(fd, file, strlen(file)) != strlen(file)) {
369 errx(1, "Short write to %s: disk full?", newname);
370 errx(1, "Writing to %s", newname);
378 struct adjusted *next;
383 static void setup_adjust_files(const char *dir,
384 const struct replace *repl,
385 struct adjusted **adj)
389 for (files = get_dir(dir); *files; files++) {
390 if (strends(*files, "/test"))
391 setup_adjust_files(*files, repl, adj);
392 else if (strends(*files, ".c") || strends(*files, ".h")) {
393 struct adjusted *a = tal(dir, struct adjusted);
396 a->tmpfile = rewrite_file(a->file, repl);
402 /* This is the "commit" stage, so we hope it won't fail. */
403 static void rename_files(const struct adjusted *adj)
406 if (!move_file(adj->tmpfile, adj->file))
407 warn("Could not rename over '%s', we're in trouble",
413 static void convert_dir(const char *dir)
416 struct replace *replace = NULL;
417 struct adjusted *adj = NULL;
419 /* Remove any ugly trailing slashes. */
420 name = path_canon(NULL, dir);
421 analyze_headers(name, &replace);
422 write_replacement_file(name, &replace);
423 setup_adjust_files(name, replace, &adj);
429 static struct replace *read_replacement_file(const char *depdir)
431 struct replace *repl = NULL;
432 char *replname = path_join(depdir, depdir, ".namespacize");
435 file = grab_file(replname, replname);
438 err(1, "Opening %s", replname);
442 for (line = tal_strsplit(file, file, "\n", STR_EMPTY_OK); *line; line++)
443 add_replace(&repl, *line);
447 static void adjust_dir(const char *dir)
449 char *parent = path_dirname(autofree(), dir);
452 verbose("Adjusting %s\n", dir);
454 for (deps = get_deps(parent, dir, "depends", false, compile_info);
458 struct adjusted *adj = NULL;
459 struct replace *repl;
461 depdir = path_join(parent, parent, *deps);
462 repl = read_replacement_file(depdir);
464 verbose("%s has been namespacized\n", depdir);
465 setup_adjust_files(parent, repl, &adj);
468 verbose("%s has not been namespacized\n", depdir);
475 static void adjust_dependents(const char *dir)
477 char *parent = path_dirname(NULL, dir);
478 char *base = path_basename(parent, dir);
481 verbose("Looking for dependents in %s\n", parent);
483 for (file = get_dir(parent); *file; file++) {
487 if (path_basename(*file, *file)[0] == '.')
490 info = path_join(*file, *file, "_info");
491 if (access(info, R_OK) != 0)
494 for (deps = get_deps(*file, *file, "depends", false,
497 if (!strstarts(*deps, "ccan/"))
499 if (streq(*deps + strlen("ccan/"), base))
505 verbose("%s is not dependent\n", *file);
510 int main(int argc, char *argv[])
512 if (argv[1] && streq(argv[1], "--verbose")) {
519 verbose("Namespacizing %s\n", argv[1]);
521 convert_dir(argv[1]);
522 adjust_dependents(argv[1]);
527 if (argc > 2 && streq(argv[1], "--adjust")) {
530 for (i = 2; i < argc; i++)