1 /* Code to move a ccan module into the ccan_ namespace. */
10 #include <sys/types.h>
13 #include "ccan/string/string.h"
14 #include "ccan/talloc/talloc.h"
17 #define IDENT_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
18 "abcdefghijklmnopqrstuvwxyz" \
21 static bool verbose = false;
22 static int indent = 0;
23 #define verbose(args...) \
26 for (_i = 0; _i < indent; _i++) printf(" "); \
30 #define verbose_indent() (indent += 2)
31 #define verbose_unindent() (indent -= 2)
33 static int unlink_no_errno(const char *filename)
35 int ret = 0, serrno = errno;
36 if (unlink(filename) < 0)
42 static char **get_dir(const char *dir)
47 unsigned int size = 0;
53 while ((ent = readdir(d)) != NULL) {
54 names = talloc_realloc(dir, names, char *, size + 2);
56 = talloc_asprintf(names, "%s/%s", dir, ent->d_name);
69 static void __attribute__((noreturn)) usage(void)
72 "namespacize [--verbose] <dir>\n"
73 "namespacize [--verbose] --adjust <dir>...\n"
74 "The first form converts dir/ to insert 'ccan_' prefixes, and\n"
75 "then adjusts any other ccan directories at the same level which\n"
77 "--adjust does an adjustment for each directory, in case a\n"
78 "dependency has been namespacized\n");
81 static void add_replace(struct replace **repl, const char *str)
83 struct replace *new, *i;
85 /* Avoid duplicates. */
86 for (i = *repl; i; i = i->next)
87 if (streq(i->string, str))
90 new = talloc(*repl, struct replace);
92 new->string = talloc_strdup(new, str);
96 static void add_replace_tok(struct replace **repl, const char *s)
99 unsigned int len = strspn(s, IDENT_CHARS);
101 new = talloc(*repl, struct replace);
103 new->string = talloc_strndup(new, s, len);
107 static char *basename(const void *ctx, const char *dir)
109 char *p = strrchr(dir, '/');
113 return talloc_strdup(ctx, p+1);
116 static void look_for_macros(char *contents, struct replace **repl)
119 enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
121 /* Look for lines of form #define X */
122 for (p = contents; *p; p++) {
125 else if (!isspace(*p)) {
126 if (state == LINESTART && *p == '#')
128 else if (state==HASH && !strncmp(p, "define", 6)) {
131 } else if (state == DEFINE) {
134 len = strspn(p, IDENT_CHARS);
137 s = talloc_strndup(contents, p, len);
138 /* Don't wrap idempotent wrappers */
139 if (!strstarts(s, "CCAN_")) {
140 verbose("Found %s\n", s);
141 add_replace(repl, s);
151 /* Blank out preprocessor lines, and eliminate \ */
152 static void preprocess(char *p)
156 /* We assume backslashes are only used for macros. */
157 while ((s = strstr(p, "\\\n")) != NULL)
160 /* Now eliminate # lines. */
163 for (i = 0; p[i] != '\n'; i++)
166 while ((s = strstr(p, "\n#")) != NULL) {
168 for (i = 1; s[i] != '\n'; i++)
173 static char *get_statement(const void *ctx, char **p)
175 unsigned brackets = 0;
176 bool seen_brackets = false;
177 char *answer = talloc_strdup(ctx, "");
180 if ((*p)[0] == '/' && (*p)[1] == '/')
181 *p += strcspn(*p, "\n");
182 else if ((*p)[0] == '/' && (*p)[1] == '*')
183 *p = strstr(*p, "*/") + 1;
186 if (c == ';' && !brackets) {
190 /* Compress whitespace into a single ' ' */
193 while (isspace((*p)[1]))
195 } else if (c == '{' || c == '(' || c == '[') {
197 seen_brackets = true;
199 } else if (c == '}' || c == ')' || c == ']')
202 if (answer[0] != '\0' || c != ' ') {
203 answer = talloc_realloc(NULL, answer, char,
205 answer[strlen(answer)+1] = '\0';
206 answer[strlen(answer)] = c;
208 if (c == '}' && seen_brackets && brackets == 0) {
219 /* This hack should handle well-formatted code. */
220 static void look_for_definitions(char *contents, struct replace **repl)
222 char *stmt, *p = contents;
224 preprocess(contents);
226 while ((stmt = get_statement(contents, &p)) != NULL) {
229 /* Definition of struct/union? */
230 if ((strncmp(stmt, "struct", 5) == 0
231 || strncmp(stmt, "union", 5) == 0)
232 && strchr(stmt, '{') && stmt[7] != '{')
233 add_replace_tok(repl, stmt+7);
235 /* Definition of var or typedef? */
236 for (i = strlen(stmt)-1; i >= 0; i--)
237 if (strspn(stmt+i, IDENT_CHARS) == 0)
240 if (i != strlen(stmt)-1) {
241 add_replace_tok(repl, stmt+i+1);
245 /* function or array declaration? */
246 len = strspn(stmt, IDENT_CHARS "* ");
247 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
248 if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
249 for (i = len-1; i >= 0; i--)
250 if (strspn(stmt+i, IDENT_CHARS) == 0)
253 add_replace_tok(repl, stmt+i+1);
257 /* Pointer to function? */
259 len += strspn(stmt + len, " *");
260 i = strspn(stmt + len, IDENT_CHARS);
261 if (i > 0 && stmt[len + i] == ')')
262 add_replace_tok(repl, stmt+len);
268 /* FIXME: Only does main header, should chase local includes. */
269 static void analyze_headers(const char *dir, struct replace **repl)
271 char *hdr, *contents;
273 /* Get hold of header, assume that's it. */
274 hdr = talloc_asprintf(dir, "%s/%s.h", dir, basename(dir, dir));
275 contents = grab_file(dir, hdr);
277 err(1, "Reading %s", hdr);
279 verbose("Looking in %s for macros\n", hdr);
281 look_for_macros(contents, repl);
284 verbose("Looking in %s for symbols\n", hdr);
286 look_for_definitions(contents, repl);
290 static void write_replacement_file(const char *dir, struct replace **repl)
292 char *replname = talloc_asprintf(dir, "%s/.namespacize", dir);
296 fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
299 errx(1, "%s already exists: can't namespacize twice",
301 err(1, "Opening %s", replname);
304 for (r = *repl; r; r = r->next) {
305 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
306 || write(fd, "\n", 1) != 1) {
307 unlink_no_errno(replname);
309 errx(1, "Short write to %s: disk full?",
311 errx(1, "Writing to %s", replname);
318 static int unlink_destroy(char *name)
324 static char *find_word(char *f, const char *str)
328 while ((p = strstr(p, str)) != NULL) {
329 /* Check it's not in the middle of a word. */
330 if (p > f && (isalnum(p[-1]) || p[-1] == '_')) {
334 if (isalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
343 /* This is horribly inefficient but simple. */
344 static const char *rewrite_file(const char *filename,
345 const struct replace *repl)
347 char *newname, *file;
350 verbose("Rewriting %s\n", filename);
351 file = grab_file(filename, filename);
353 err(1, "Reading file %s", filename);
355 for (; repl; repl = repl->next) {
358 while ((p = find_word(file, repl->string)) != NULL) {
360 char *new = talloc_array(file, char, strlen(file)+6);
363 memcpy(new, file, off);
364 if (isupper(repl->string[0]))
365 memcpy(new + off, "CCAN_", 5);
367 memcpy(new + off, "ccan_", 5);
368 strcpy(new + off + 5, file + off);
373 /* If we exit for some reason, we want this erased. */
374 newname = talloc_asprintf(talloc_autofree_context(), "%s.tmp",
376 fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
378 err(1, "Creating %s", newname);
380 talloc_set_destructor(newname, unlink_destroy);
381 if (write(fd, file, strlen(file)) != strlen(file)) {
383 errx(1, "Short write to %s: disk full?", newname);
384 errx(1, "Writing to %s", newname);
392 struct adjusted *next;
397 static void setup_adjust_files(const char *dir,
398 const struct replace *repl,
399 struct adjusted **adj)
403 for (files = get_dir(dir); *files; files++) {
404 if (strends(*files, "/test"))
405 setup_adjust_files(*files, repl, adj);
406 else if (strends(*files, ".c") || strends(*files, ".h")) {
407 struct adjusted *a = talloc(dir, struct adjusted);
410 a->tmpfile = rewrite_file(a->file, repl);
416 /* This is the "commit" stage, so we hope it won't fail. */
417 static void rename_files(const struct adjusted *adj)
420 if (rename(adj->tmpfile, adj->file) != 0)
421 warn("Could not rename over '%s', we're in trouble",
427 static void convert_dir(const char *dir)
430 struct replace *replace = NULL;
431 struct adjusted *adj = NULL;
433 /* Remove any ugly trailing slashes. */
434 name = talloc_strdup(NULL, dir);
435 while (strends(name, "/"))
436 name[strlen(name)-1] = '\0';
438 analyze_headers(name, &replace);
439 write_replacement_file(name, &replace);
440 setup_adjust_files(name, replace, &adj);
443 talloc_free(replace);
446 static struct replace *read_replacement_file(const char *depdir)
448 struct replace *repl = NULL;
449 char *replname = talloc_asprintf(depdir, "%s/.namespacize", depdir);
452 file = grab_file(replname, replname);
455 err(1, "Opening %s", replname);
459 for (line = strsplit(file, file, "\n", NULL); *line; line++)
460 add_replace(&repl, *line);
464 static char *parent_dir(const void *ctx, const char *dir)
466 char *parent, *slash;
468 parent = talloc_strdup(ctx, dir);
469 slash = strrchr(parent, '/');
473 parent = talloc_strdup(ctx, ".");
477 static void adjust_dir(const char *dir)
479 char *parent = parent_dir(NULL, dir);
482 verbose("Adjusting %s\n", dir);
484 for (deps = get_deps(parent, dir); *deps; deps++) {
486 struct adjusted *adj = NULL;
487 struct replace *repl;
489 depdir = talloc_asprintf(parent, "%s/%s", parent, *deps);
490 repl = read_replacement_file(depdir);
492 verbose("%s has been namespacized\n", depdir);
493 setup_adjust_files(parent, repl, &adj);
496 verbose("%s has not been namespacized\n", depdir);
502 static void adjust_dependents(const char *dir)
504 char *parent = parent_dir(NULL, dir);
505 char *base = basename(parent, dir);
508 verbose("Looking for dependents in %s\n", parent);
510 for (file = get_dir(parent); *file; file++) {
514 if (basename(*file, *file)[0] == '.')
517 infoc = talloc_asprintf(*file, "%s/_info.c", *file);
518 if (access(infoc, R_OK) != 0)
521 for (deps = get_deps(*file, *file); *deps; deps++) {
522 if (streq(*deps, base))
528 verbose("%s is not dependent\n", *file);
533 int main(int argc, char *argv[])
535 if (argv[1] && streq(argv[1], "--verbose")) {
542 verbose("Namespacizing %s\n", argv[1]);
544 convert_dir(argv[1]);
545 adjust_dependents(argv[1]);
550 if (argc > 2 && streq(argv[1], "--adjust")) {
553 for (i = 2; i < argc; i++)