1 /* Code to move a ccan module into the ccan_ namespace. */
10 #include <sys/types.h>
13 #include "talloc/talloc.h"
16 #define IDENT_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
17 "abcdefghijklmnopqrstuvwxyz" \
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 #define strstarts(str,prefix) (strncmp((str),(prefix),strlen(prefix)) == 0)
34 static inline bool strends(const char *str, const char *postfix)
36 if (strlen(str) < strlen(postfix))
39 return streq(str + strlen(str) - strlen(postfix), postfix);
42 static int unlink_no_errno(const char *filename)
44 int ret = 0, serrno = errno;
45 if (unlink(filename) < 0)
51 static char **get_dir(const char *dir)
56 unsigned int size = 0;
62 while ((ent = readdir(d)) != NULL) {
63 names = talloc_realloc(dir, names, char *, size + 2);
65 = talloc_asprintf(names, "%s/%s", dir, ent->d_name);
78 static void __attribute__((noreturn)) usage(void)
81 "namespacize [--verbose] <dir>\n"
82 "namespacize [--verbose] --adjust <dir>...\n"
83 "The first form converts dir/ to insert 'ccan_' prefixes, and\n"
84 "then adjusts any other ccan directories at the same level which\n"
86 "--adjust does an adjustment for each directory, in case a\n"
87 "dependency has been namespacized\n");
90 static void add_replace(struct replace **repl, const char *str)
92 struct replace *new, *i;
94 /* Avoid duplicates. */
95 for (i = *repl; i; i = i->next)
96 if (streq(i->string, str))
99 new = talloc(*repl, struct replace);
101 new->string = talloc_strdup(new, str);
105 static void add_replace_tok(struct replace **repl, const char *s)
108 unsigned int len = strspn(s, IDENT_CHARS);
110 new = talloc(*repl, struct replace);
112 new->string = talloc_strndup(new, s, len);
116 static char *basename(const void *ctx, const char *dir)
118 char *p = strrchr(dir, '/');
122 return talloc_strdup(ctx, p+1);
125 static void look_for_macros(char *contents, struct replace **repl)
128 enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
130 /* Look for lines of form #define X */
131 for (p = contents; *p; p++) {
134 else if (!isspace(*p)) {
135 if (state == LINESTART && *p == '#')
137 else if (state==HASH && !strncmp(p, "define", 6)) {
140 } else if (state == DEFINE) {
143 len = strspn(p, IDENT_CHARS);
146 s = talloc_strndup(contents, p, len);
147 /* Don't wrap idempotent wrappers */
148 if (!strstarts(s, "CCAN_")) {
149 verbose("Found %s\n", s);
150 add_replace(repl, s);
160 /* Blank out preprocessor lines, and eliminate \ */
161 static void preprocess(char *p)
165 /* We assume backslashes are only used for macros. */
166 while ((s = strstr(p, "\\\n")) != NULL)
169 /* Now eliminate # lines. */
172 for (i = 0; p[i] != '\n'; i++)
175 while ((s = strstr(p, "\n#")) != NULL) {
177 for (i = 1; s[i] != '\n'; i++)
182 static char *get_statement(const void *ctx, char **p)
184 unsigned brackets = 0;
185 bool seen_brackets = false;
186 char *answer = talloc_strdup(ctx, "");
189 if ((*p)[0] == '/' && (*p)[1] == '/')
190 *p += strcspn(*p, "\n");
191 else if ((*p)[0] == '/' && (*p)[1] == '*')
192 *p = strstr(*p, "*/") + 1;
195 if (c == ';' && !brackets) {
199 /* Compress whitespace into a single ' ' */
202 while (isspace((*p)[1]))
204 } else if (c == '{' || c == '(' || c == '[') {
206 seen_brackets = true;
208 } else if (c == '}' || c == ')' || c == ']')
211 if (answer[0] != '\0' || c != ' ') {
212 answer = talloc_realloc(NULL, answer, char,
214 answer[strlen(answer)+1] = '\0';
215 answer[strlen(answer)] = c;
217 if (c == '}' && seen_brackets && brackets == 0) {
228 /* This hack should handle well-formatted code. */
229 static void look_for_definitions(char *contents, struct replace **repl)
231 char *stmt, *p = contents;
233 preprocess(contents);
235 while ((stmt = get_statement(contents, &p)) != NULL) {
238 /* Definition of struct/union? */
239 if ((strncmp(stmt, "struct", 5) == 0
240 || strncmp(stmt, "union", 5) == 0)
241 && strchr(stmt, '{') && stmt[7] != '{')
242 add_replace_tok(repl, stmt+7);
244 /* Definition of var or typedef? */
245 for (i = strlen(stmt)-1; i >= 0; i--)
246 if (strspn(stmt+i, IDENT_CHARS) == 0)
249 if (i != strlen(stmt)-1) {
250 add_replace_tok(repl, stmt+i+1);
254 /* function or array declaration? */
255 len = strspn(stmt, IDENT_CHARS "* ");
256 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
257 if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
258 for (i = len-1; i >= 0; i--)
259 if (strspn(stmt+i, IDENT_CHARS) == 0)
262 add_replace_tok(repl, stmt+i+1);
266 /* Pointer to function? */
268 len += strspn(stmt + len, " *");
269 i = strspn(stmt + len, IDENT_CHARS);
270 if (i > 0 && stmt[len + i] == ')')
271 add_replace_tok(repl, stmt+len);
277 /* FIXME: Only does main header, should chase local includes. */
278 static void analyze_headers(const char *dir, struct replace **repl)
280 char *hdr, *contents;
282 /* Get hold of header, assume that's it. */
283 hdr = talloc_asprintf(dir, "%s/%s.h", dir, basename(dir, dir));
284 contents = grab_file(dir, hdr);
286 err(1, "Reading %s", hdr);
288 verbose("Looking in %s for macros\n", hdr);
290 look_for_macros(contents, repl);
293 verbose("Looking in %s for symbols\n", hdr);
295 look_for_definitions(contents, repl);
299 static void write_replacement_file(const char *dir, struct replace **repl)
301 char *replname = talloc_asprintf(dir, "%s/.namespacize", dir);
305 fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
308 errx(1, "%s already exists: can't namespacize twice",
310 err(1, "Opening %s", replname);
313 for (r = *repl; r; r = r->next) {
314 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
315 || write(fd, "\n", 1) != 1) {
316 unlink_no_errno(replname);
318 errx(1, "Short write to %s: disk full?",
320 errx(1, "Writing to %s", replname);
327 static int unlink_destroy(char *name)
333 static char *find_word(char *f, const char *str)
337 while ((p = strstr(p, str)) != NULL) {
338 /* Check it's not in the middle of a word. */
339 if (p > f && (isalnum(p[-1]) || p[-1] == '_')) {
343 if (isalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
352 /* This is horribly inefficient but simple. */
353 static const char *rewrite_file(const char *filename,
354 const struct replace *repl)
356 char *newname, *file;
359 verbose("Rewriting %s\n", filename);
360 file = grab_file(filename, filename);
362 err(1, "Reading file %s", filename);
364 for (; repl; repl = repl->next) {
367 while ((p = find_word(file, repl->string)) != NULL) {
369 char *new = talloc_array(file, char, strlen(file)+6);
372 memcpy(new, file, off);
373 if (isupper(repl->string[0]))
374 memcpy(new + off, "CCAN_", 5);
376 memcpy(new + off, "ccan_", 5);
377 strcpy(new + off + 5, file + off);
382 /* If we exit for some reason, we want this erased. */
383 newname = talloc_asprintf(talloc_autofree_context(), "%s.tmp",
385 fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
387 err(1, "Creating %s", newname);
389 talloc_set_destructor(newname, unlink_destroy);
390 if (write(fd, file, strlen(file)) != strlen(file)) {
392 errx(1, "Short write to %s: disk full?", newname);
393 errx(1, "Writing to %s", newname);
401 struct adjusted *next;
406 static void setup_adjust_files(const char *dir,
407 const struct replace *repl,
408 struct adjusted **adj)
412 for (files = get_dir(dir); *files; files++) {
413 if (strends(*files, "/test"))
414 setup_adjust_files(*files, repl, adj);
415 else if (strends(*files, ".c") || strends(*files, ".h")) {
416 struct adjusted *a = talloc(dir, struct adjusted);
419 a->tmpfile = rewrite_file(a->file, repl);
425 /* This is the "commit" stage, so we hope it won't fail. */
426 static void rename_files(const struct adjusted *adj)
429 if (rename(adj->tmpfile, adj->file) != 0)
430 warn("Could not rename over '%s', we're in trouble",
436 static void convert_dir(const char *dir)
439 struct replace *replace = NULL;
440 struct adjusted *adj = NULL;
442 /* Remove any ugly trailing slashes. */
443 name = talloc_strdup(NULL, dir);
444 while (strends(name, "/"))
445 name[strlen(name)-1] = '\0';
447 analyze_headers(name, &replace);
448 write_replacement_file(name, &replace);
449 setup_adjust_files(name, replace, &adj);
452 talloc_free(replace);
455 static struct replace *read_replacement_file(const char *depdir)
457 struct replace *repl = NULL;
458 char *replname = talloc_asprintf(depdir, "%s/.namespacize", depdir);
461 file = grab_file(replname, replname);
464 err(1, "Opening %s", replname);
468 for (line = split(file, file, "\n", NULL); *line; line++)
469 add_replace(&repl, *line);
473 static char *parent_dir(const void *ctx, const char *dir)
475 char *parent, *slash;
477 parent = talloc_strdup(ctx, dir);
478 slash = strrchr(parent, '/');
482 parent = talloc_strdup(ctx, ".");
486 static void adjust_dir(const char *dir)
488 char *parent = parent_dir(NULL, dir);
491 verbose("Adjusting %s\n", dir);
493 for (deps = get_deps(parent, dir); *deps; deps++) {
495 struct adjusted *adj = NULL;
496 struct replace *repl;
498 depdir = talloc_asprintf(parent, "%s/%s", parent, *deps);
499 repl = read_replacement_file(depdir);
501 verbose("%s has been namespacized\n", depdir);
502 setup_adjust_files(parent, repl, &adj);
505 verbose("%s has not been namespacized\n", depdir);
511 static void adjust_dependents(const char *dir)
513 char *parent = parent_dir(NULL, dir);
514 char *base = basename(parent, dir);
517 verbose("Looking for dependents in %s\n", parent);
519 for (file = get_dir(parent); *file; file++) {
523 if (basename(*file, *file)[0] == '.')
526 infoc = talloc_asprintf(*file, "%s/_info.c", *file);
527 if (access(infoc, R_OK) != 0)
530 for (deps = get_deps(*file, *file); *deps; deps++) {
531 if (streq(*deps, base))
537 verbose("%s is not dependent\n", *file);
542 int main(int argc, char *argv[])
544 if (argv[1] && streq(argv[1], "--verbose")) {
551 verbose("Namespacizing %s\n", argv[1]);
553 convert_dir(argv[1]);
554 adjust_dependents(argv[1]);
559 if (argc > 2 && streq(argv[1], "--adjust")) {
562 for (i = 2; i < argc; i++)