1 /* Code to move a ccan module into the ccan_ namespace. */
10 #include <sys/types.h>
13 #include "string/string.h"
14 #include "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 #define strstarts(str,prefix) (strncmp((str),(prefix),strlen(prefix)) == 0)
35 static inline bool strends(const char *str, const char *postfix)
37 if (strlen(str) < strlen(postfix))
40 return streq(str + strlen(str) - strlen(postfix), postfix);
43 static int unlink_no_errno(const char *filename)
45 int ret = 0, serrno = errno;
46 if (unlink(filename) < 0)
52 static char **get_dir(const char *dir)
57 unsigned int size = 0;
63 while ((ent = readdir(d)) != NULL) {
64 names = talloc_realloc(dir, names, char *, size + 2);
66 = talloc_asprintf(names, "%s/%s", dir, ent->d_name);
79 static void __attribute__((noreturn)) usage(void)
82 "namespacize [--verbose] <dir>\n"
83 "namespacize [--verbose] --adjust <dir>...\n"
84 "The first form converts dir/ to insert 'ccan_' prefixes, and\n"
85 "then adjusts any other ccan directories at the same level which\n"
87 "--adjust does an adjustment for each directory, in case a\n"
88 "dependency has been namespacized\n");
91 static void add_replace(struct replace **repl, const char *str)
93 struct replace *new, *i;
95 /* Avoid duplicates. */
96 for (i = *repl; i; i = i->next)
97 if (streq(i->string, str))
100 new = talloc(*repl, struct replace);
102 new->string = talloc_strdup(new, str);
106 static void add_replace_tok(struct replace **repl, const char *s)
109 unsigned int len = strspn(s, IDENT_CHARS);
111 new = talloc(*repl, struct replace);
113 new->string = talloc_strndup(new, s, len);
117 static char *basename(const void *ctx, const char *dir)
119 char *p = strrchr(dir, '/');
123 return talloc_strdup(ctx, p+1);
126 static void look_for_macros(char *contents, struct replace **repl)
129 enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
131 /* Look for lines of form #define X */
132 for (p = contents; *p; p++) {
135 else if (!isspace(*p)) {
136 if (state == LINESTART && *p == '#')
138 else if (state==HASH && !strncmp(p, "define", 6)) {
141 } else if (state == DEFINE) {
144 len = strspn(p, IDENT_CHARS);
147 s = talloc_strndup(contents, p, len);
148 /* Don't wrap idempotent wrappers */
149 if (!strstarts(s, "CCAN_")) {
150 verbose("Found %s\n", s);
151 add_replace(repl, s);
161 /* Blank out preprocessor lines, and eliminate \ */
162 static void preprocess(char *p)
166 /* We assume backslashes are only used for macros. */
167 while ((s = strstr(p, "\\\n")) != NULL)
170 /* Now eliminate # lines. */
173 for (i = 0; p[i] != '\n'; i++)
176 while ((s = strstr(p, "\n#")) != NULL) {
178 for (i = 1; s[i] != '\n'; i++)
183 static char *get_statement(const void *ctx, char **p)
185 unsigned brackets = 0;
186 bool seen_brackets = false;
187 char *answer = talloc_strdup(ctx, "");
190 if ((*p)[0] == '/' && (*p)[1] == '/')
191 *p += strcspn(*p, "\n");
192 else if ((*p)[0] == '/' && (*p)[1] == '*')
193 *p = strstr(*p, "*/") + 1;
196 if (c == ';' && !brackets) {
200 /* Compress whitespace into a single ' ' */
203 while (isspace((*p)[1]))
205 } else if (c == '{' || c == '(' || c == '[') {
207 seen_brackets = true;
209 } else if (c == '}' || c == ')' || c == ']')
212 if (answer[0] != '\0' || c != ' ') {
213 answer = talloc_realloc(NULL, answer, char,
215 answer[strlen(answer)+1] = '\0';
216 answer[strlen(answer)] = c;
218 if (c == '}' && seen_brackets && brackets == 0) {
229 /* This hack should handle well-formatted code. */
230 static void look_for_definitions(char *contents, struct replace **repl)
232 char *stmt, *p = contents;
234 preprocess(contents);
236 while ((stmt = get_statement(contents, &p)) != NULL) {
239 /* Definition of struct/union? */
240 if ((strncmp(stmt, "struct", 5) == 0
241 || strncmp(stmt, "union", 5) == 0)
242 && strchr(stmt, '{') && stmt[7] != '{')
243 add_replace_tok(repl, stmt+7);
245 /* Definition of var or typedef? */
246 for (i = strlen(stmt)-1; i >= 0; i--)
247 if (strspn(stmt+i, IDENT_CHARS) == 0)
250 if (i != strlen(stmt)-1) {
251 add_replace_tok(repl, stmt+i+1);
255 /* function or array declaration? */
256 len = strspn(stmt, IDENT_CHARS "* ");
257 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
258 if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
259 for (i = len-1; i >= 0; i--)
260 if (strspn(stmt+i, IDENT_CHARS) == 0)
263 add_replace_tok(repl, stmt+i+1);
267 /* Pointer to function? */
269 len += strspn(stmt + len, " *");
270 i = strspn(stmt + len, IDENT_CHARS);
271 if (i > 0 && stmt[len + i] == ')')
272 add_replace_tok(repl, stmt+len);
278 /* FIXME: Only does main header, should chase local includes. */
279 static void analyze_headers(const char *dir, struct replace **repl)
281 char *hdr, *contents;
283 /* Get hold of header, assume that's it. */
284 hdr = talloc_asprintf(dir, "%s/%s.h", dir, basename(dir, dir));
285 contents = grab_file(dir, hdr);
287 err(1, "Reading %s", hdr);
289 verbose("Looking in %s for macros\n", hdr);
291 look_for_macros(contents, repl);
294 verbose("Looking in %s for symbols\n", hdr);
296 look_for_definitions(contents, repl);
300 static void write_replacement_file(const char *dir, struct replace **repl)
302 char *replname = talloc_asprintf(dir, "%s/.namespacize", dir);
306 fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
309 errx(1, "%s already exists: can't namespacize twice",
311 err(1, "Opening %s", replname);
314 for (r = *repl; r; r = r->next) {
315 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
316 || write(fd, "\n", 1) != 1) {
317 unlink_no_errno(replname);
319 errx(1, "Short write to %s: disk full?",
321 errx(1, "Writing to %s", replname);
328 static int unlink_destroy(char *name)
334 static char *find_word(char *f, const char *str)
338 while ((p = strstr(p, str)) != NULL) {
339 /* Check it's not in the middle of a word. */
340 if (p > f && (isalnum(p[-1]) || p[-1] == '_')) {
344 if (isalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
353 /* This is horribly inefficient but simple. */
354 static const char *rewrite_file(const char *filename,
355 const struct replace *repl)
357 char *newname, *file;
360 verbose("Rewriting %s\n", filename);
361 file = grab_file(filename, filename);
363 err(1, "Reading file %s", filename);
365 for (; repl; repl = repl->next) {
368 while ((p = find_word(file, repl->string)) != NULL) {
370 char *new = talloc_array(file, char, strlen(file)+6);
373 memcpy(new, file, off);
374 if (isupper(repl->string[0]))
375 memcpy(new + off, "CCAN_", 5);
377 memcpy(new + off, "ccan_", 5);
378 strcpy(new + off + 5, file + off);
383 /* If we exit for some reason, we want this erased. */
384 newname = talloc_asprintf(talloc_autofree_context(), "%s.tmp",
386 fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
388 err(1, "Creating %s", newname);
390 talloc_set_destructor(newname, unlink_destroy);
391 if (write(fd, file, strlen(file)) != strlen(file)) {
393 errx(1, "Short write to %s: disk full?", newname);
394 errx(1, "Writing to %s", newname);
402 struct adjusted *next;
407 static void setup_adjust_files(const char *dir,
408 const struct replace *repl,
409 struct adjusted **adj)
413 for (files = get_dir(dir); *files; files++) {
414 if (strends(*files, "/test"))
415 setup_adjust_files(*files, repl, adj);
416 else if (strends(*files, ".c") || strends(*files, ".h")) {
417 struct adjusted *a = talloc(dir, struct adjusted);
420 a->tmpfile = rewrite_file(a->file, repl);
426 /* This is the "commit" stage, so we hope it won't fail. */
427 static void rename_files(const struct adjusted *adj)
430 if (rename(adj->tmpfile, adj->file) != 0)
431 warn("Could not rename over '%s', we're in trouble",
437 static void convert_dir(const char *dir)
440 struct replace *replace = NULL;
441 struct adjusted *adj = NULL;
443 /* Remove any ugly trailing slashes. */
444 name = talloc_strdup(NULL, dir);
445 while (strends(name, "/"))
446 name[strlen(name)-1] = '\0';
448 analyze_headers(name, &replace);
449 write_replacement_file(name, &replace);
450 setup_adjust_files(name, replace, &adj);
453 talloc_free(replace);
456 static struct replace *read_replacement_file(const char *depdir)
458 struct replace *repl = NULL;
459 char *replname = talloc_asprintf(depdir, "%s/.namespacize", depdir);
462 file = grab_file(replname, replname);
465 err(1, "Opening %s", replname);
469 for (line = split(file, file, "\n", NULL); *line; line++)
470 add_replace(&repl, *line);
474 static char *parent_dir(const void *ctx, const char *dir)
476 char *parent, *slash;
478 parent = talloc_strdup(ctx, dir);
479 slash = strrchr(parent, '/');
483 parent = talloc_strdup(ctx, ".");
487 static void adjust_dir(const char *dir)
489 char *parent = parent_dir(NULL, dir);
492 verbose("Adjusting %s\n", dir);
494 for (deps = get_deps(parent, dir); *deps; deps++) {
496 struct adjusted *adj = NULL;
497 struct replace *repl;
499 depdir = talloc_asprintf(parent, "%s/%s", parent, *deps);
500 repl = read_replacement_file(depdir);
502 verbose("%s has been namespacized\n", depdir);
503 setup_adjust_files(parent, repl, &adj);
506 verbose("%s has not been namespacized\n", depdir);
512 static void adjust_dependents(const char *dir)
514 char *parent = parent_dir(NULL, dir);
515 char *base = basename(parent, dir);
518 verbose("Looking for dependents in %s\n", parent);
520 for (file = get_dir(parent); *file; file++) {
524 if (basename(*file, *file)[0] == '.')
527 infoc = talloc_asprintf(*file, "%s/_info.c", *file);
528 if (access(infoc, R_OK) != 0)
531 for (deps = get_deps(*file, *file); *deps; deps++) {
532 if (streq(*deps, base))
538 verbose("%s is not dependent\n", *file);
543 int main(int argc, char *argv[])
545 if (argv[1] && streq(argv[1], "--verbose")) {
552 verbose("Namespacizing %s\n", argv[1]);
554 convert_dir(argv[1]);
555 adjust_dependents(argv[1]);
560 if (argc > 2 && streq(argv[1], "--adjust")) {
563 for (i = 2; i < argc; i++)