1 /* Code to move a ccan module into the ccan_ namespace. */
10 #include <sys/types.h>
13 #include "ccan/str/str.h"
14 #include "ccan/str_talloc/str_talloc.h"
15 #include "ccan/grab_file/grab_file.h"
16 #include "ccan/talloc/talloc.h"
19 static bool verbose = false;
20 static int indent = 0;
21 #define verbose(args...) \
24 for (_i = 0; _i < indent; _i++) printf(" "); \
28 #define verbose_indent() (indent += 2)
29 #define verbose_unindent() (indent -= 2)
31 static int unlink_no_errno(const char *filename)
33 int ret = 0, serrno = errno;
34 if (unlink(filename) < 0)
40 static char **get_dir(const char *dir)
45 unsigned int size = 0;
51 while ((ent = readdir(d)) != NULL) {
52 names = talloc_realloc(dir, names, char *, size + 2);
54 = talloc_asprintf(names, "%s/%s", dir, ent->d_name);
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 = talloc(*repl, struct replace);
90 new->string = talloc_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 = talloc(*repl, struct replace);
101 new->string = talloc_strndup(new, s, len);
105 static char *basename(const void *ctx, const char *dir)
107 char *p = strrchr(dir, '/');
111 return talloc_strdup(ctx, p+1);
114 static void look_for_macros(char *contents, struct replace **repl)
117 enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
119 /* Look for lines of form #define X */
120 for (p = contents; *p; p++) {
123 else if (!isspace(*p)) {
124 if (state == LINESTART && *p == '#')
126 else if (state==HASH && !strncmp(p, "define", 6)) {
129 } else if (state == DEFINE) {
132 len = strspn(p, IDENT_CHARS);
135 s = talloc_strndup(contents, p, len);
136 /* Don't wrap idempotent wrappers */
137 if (!strstarts(s, "CCAN_")) {
138 verbose("Found %s\n", s);
139 add_replace(repl, s);
149 /* Blank out preprocessor lines, and eliminate \ */
150 static void preprocess(char *p)
154 /* We assume backslashes are only used for macros. */
155 while ((s = strstr(p, "\\\n")) != NULL)
158 /* Now eliminate # lines. */
161 for (i = 0; p[i] != '\n'; i++)
164 while ((s = strstr(p, "\n#")) != NULL) {
166 for (i = 1; s[i] != '\n'; i++)
171 static char *get_statement(const void *ctx, char **p)
173 unsigned brackets = 0;
174 bool seen_brackets = false;
175 char *answer = talloc_strdup(ctx, "");
178 if ((*p)[0] == '/' && (*p)[1] == '/')
179 *p += strcspn(*p, "\n");
180 else if ((*p)[0] == '/' && (*p)[1] == '*')
181 *p = strstr(*p, "*/") + 1;
184 if (c == ';' && !brackets) {
188 /* Compress whitespace into a single ' ' */
191 while (isspace((*p)[1]))
193 } else if (c == '{' || c == '(' || c == '[') {
195 seen_brackets = true;
197 } else if (c == '}' || c == ')' || c == ']')
200 if (answer[0] != '\0' || c != ' ') {
201 answer = talloc_realloc(NULL, answer, char,
203 answer[strlen(answer)+1] = '\0';
204 answer[strlen(answer)] = c;
206 if (c == '}' && seen_brackets && brackets == 0) {
217 /* This hack should handle well-formatted code. */
218 static void look_for_definitions(char *contents, struct replace **repl)
220 char *stmt, *p = contents;
222 preprocess(contents);
224 while ((stmt = get_statement(contents, &p)) != NULL) {
227 /* Definition of struct/union? */
228 if ((strncmp(stmt, "struct", 5) == 0
229 || strncmp(stmt, "union", 5) == 0)
230 && strchr(stmt, '{') && stmt[7] != '{')
231 add_replace_tok(repl, stmt+7);
233 /* Definition of var or typedef? */
234 for (i = strlen(stmt)-1; i >= 0; i--)
235 if (strspn(stmt+i, IDENT_CHARS) == 0)
238 if (i != strlen(stmt)-1) {
239 add_replace_tok(repl, stmt+i+1);
243 /* function or array declaration? */
244 len = strspn(stmt, IDENT_CHARS "* ");
245 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
246 if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
247 for (i = len-1; i >= 0; i--)
248 if (strspn(stmt+i, IDENT_CHARS) == 0)
251 add_replace_tok(repl, stmt+i+1);
255 /* Pointer to function? */
257 len += strspn(stmt + len, " *");
258 i = strspn(stmt + len, IDENT_CHARS);
259 if (i > 0 && stmt[len + i] == ')')
260 add_replace_tok(repl, stmt+len);
266 /* FIXME: Only does main header, should chase local includes. */
267 static void analyze_headers(const char *dir, struct replace **repl)
269 char *hdr, *contents;
271 /* Get hold of header, assume that's it. */
272 hdr = talloc_asprintf(dir, "%s/%s.h", dir, basename(dir, dir));
273 contents = grab_file(dir, hdr, NULL);
275 err(1, "Reading %s", hdr);
277 verbose("Looking in %s for macros\n", hdr);
279 look_for_macros(contents, repl);
282 verbose("Looking in %s for symbols\n", hdr);
284 look_for_definitions(contents, repl);
288 static void write_replacement_file(const char *dir, struct replace **repl)
290 char *replname = talloc_asprintf(dir, "%s/.namespacize", dir);
294 fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
297 errx(1, "%s already exists: can't namespacize twice",
299 err(1, "Opening %s", replname);
302 for (r = *repl; r; r = r->next) {
303 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
304 || write(fd, "\n", 1) != 1) {
305 unlink_no_errno(replname);
307 errx(1, "Short write to %s: disk full?",
309 errx(1, "Writing to %s", replname);
316 static int unlink_destroy(char *name)
322 static char *find_word(char *f, const char *str)
326 while ((p = strstr(p, str)) != NULL) {
327 /* Check it's not in the middle of a word. */
328 if (p > f && (isalnum(p[-1]) || p[-1] == '_')) {
332 if (isalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
341 /* This is horribly inefficient but simple. */
342 static const char *rewrite_file(const char *filename,
343 const struct replace *repl)
345 char *newname, *file;
348 verbose("Rewriting %s\n", filename);
349 file = grab_file(filename, filename, NULL);
351 err(1, "Reading file %s", filename);
353 for (; repl; repl = repl->next) {
356 while ((p = find_word(file, repl->string)) != NULL) {
358 char *new = talloc_array(file, char, strlen(file)+6);
361 memcpy(new, file, off);
362 if (isupper(repl->string[0]))
363 memcpy(new + off, "CCAN_", 5);
365 memcpy(new + off, "ccan_", 5);
366 strcpy(new + off + 5, file + off);
371 /* If we exit for some reason, we want this erased. */
372 newname = talloc_asprintf(talloc_autofree_context(), "%s.tmp",
374 fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
376 err(1, "Creating %s", newname);
378 talloc_set_destructor(newname, unlink_destroy);
379 if (write(fd, file, strlen(file)) != strlen(file)) {
381 errx(1, "Short write to %s: disk full?", newname);
382 errx(1, "Writing to %s", newname);
390 struct adjusted *next;
395 static void setup_adjust_files(const char *dir,
396 const struct replace *repl,
397 struct adjusted **adj)
401 for (files = get_dir(dir); *files; files++) {
402 if (strends(*files, "/test"))
403 setup_adjust_files(*files, repl, adj);
404 else if (strends(*files, ".c") || strends(*files, ".h")) {
405 struct adjusted *a = talloc(dir, struct adjusted);
408 a->tmpfile = rewrite_file(a->file, repl);
414 /* This is the "commit" stage, so we hope it won't fail. */
415 static void rename_files(const struct adjusted *adj)
418 if (rename(adj->tmpfile, adj->file) != 0)
419 warn("Could not rename over '%s', we're in trouble",
425 static void convert_dir(const char *dir)
428 struct replace *replace = NULL;
429 struct adjusted *adj = NULL;
431 /* Remove any ugly trailing slashes. */
432 name = talloc_strdup(NULL, dir);
433 while (strends(name, "/"))
434 name[strlen(name)-1] = '\0';
436 analyze_headers(name, &replace);
437 write_replacement_file(name, &replace);
438 setup_adjust_files(name, replace, &adj);
441 talloc_free(replace);
444 static struct replace *read_replacement_file(const char *depdir)
446 struct replace *repl = NULL;
447 char *replname = talloc_asprintf(depdir, "%s/.namespacize", depdir);
450 file = grab_file(replname, replname, NULL);
453 err(1, "Opening %s", replname);
457 for (line = strsplit(file, file, "\n", NULL); *line; line++)
458 add_replace(&repl, *line);
462 static char *parent_dir(const void *ctx, const char *dir)
464 char *parent, *slash;
466 parent = talloc_strdup(ctx, dir);
467 slash = strrchr(parent, '/');
471 parent = talloc_strdup(ctx, ".");
475 static void adjust_dir(const char *dir)
477 char *parent = parent_dir(talloc_autofree_context(), dir);
480 verbose("Adjusting %s\n", dir);
482 for (deps = get_deps(parent, dir, false); *deps; deps++) {
484 struct adjusted *adj = NULL;
485 struct replace *repl;
487 depdir = talloc_asprintf(parent, "%s/%s", parent, *deps);
488 repl = read_replacement_file(depdir);
490 verbose("%s has been namespacized\n", depdir);
491 setup_adjust_files(parent, repl, &adj);
494 verbose("%s has not been namespacized\n", depdir);
501 static void adjust_dependents(const char *dir)
503 char *parent = parent_dir(NULL, dir);
504 char *base = basename(parent, dir);
507 verbose("Looking for dependents in %s\n", parent);
509 for (file = get_dir(parent); *file; file++) {
513 if (basename(*file, *file)[0] == '.')
516 info = talloc_asprintf(*file, "%s/_info", *file);
517 if (access(info, R_OK) != 0)
520 for (deps = get_deps(*file, *file, false); *deps; deps++) {
521 if (streq(*deps, base))
527 verbose("%s is not dependent\n", *file);
532 int main(int argc, char *argv[])
534 if (argv[1] && streq(argv[1], "--verbose")) {
541 verbose("Namespacizing %s\n", argv[1]);
543 convert_dir(argv[1]);
544 adjust_dependents(argv[1]);
549 if (argc > 2 && streq(argv[1], "--adjust")) {
552 for (i = 2; i < argc; i++)