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 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 (!isspace(*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 = talloc_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 = talloc_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 (isspace((*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 answer = talloc_realloc(NULL, answer, char,
194 answer[strlen(answer)+1] = '\0';
195 answer[strlen(answer)] = c;
197 if (c == '}' && seen_brackets && brackets == 0) {
208 /* This hack should handle well-formatted code. */
209 static void look_for_definitions(char *contents, struct replace **repl)
211 char *stmt, *p = contents;
213 preprocess(contents);
215 while ((stmt = get_statement(contents, &p)) != NULL) {
218 /* Definition of struct/union? */
219 if ((strncmp(stmt, "struct", 5) == 0
220 || strncmp(stmt, "union", 5) == 0)
221 && strchr(stmt, '{') && stmt[7] != '{')
222 add_replace_tok(repl, stmt+7);
224 /* Definition of var or typedef? */
225 for (i = strlen(stmt)-1; i >= 0; i--)
226 if (strspn(stmt+i, IDENT_CHARS) == 0)
229 if (i != strlen(stmt)-1) {
230 add_replace_tok(repl, stmt+i+1);
234 /* function or array declaration? */
235 len = strspn(stmt, IDENT_CHARS "* ");
236 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
237 if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
238 for (i = len-1; i >= 0; i--)
239 if (strspn(stmt+i, IDENT_CHARS) == 0)
242 add_replace_tok(repl, stmt+i+1);
246 /* Pointer to function? */
248 len += strspn(stmt + len, " *");
249 i = strspn(stmt + len, IDENT_CHARS);
250 if (i > 0 && stmt[len + i] == ')')
251 add_replace_tok(repl, stmt+len);
257 /* FIXME: Only does main header, should chase local includes. */
258 static void analyze_headers(const char *dir, struct replace **repl)
260 char *hdr, *contents;
262 /* Get hold of header, assume that's it. */
263 hdr = talloc_asprintf(dir, "%s/%s.h", dir, talloc_basename(dir, dir));
264 contents = grab_file(dir, hdr, NULL);
266 err(1, "Reading %s", hdr);
268 verbose("Looking in %s for macros\n", hdr);
270 look_for_macros(contents, repl);
273 verbose("Looking in %s for symbols\n", hdr);
275 look_for_definitions(contents, repl);
279 static void write_replacement_file(const char *dir, struct replace **repl)
281 char *replname = talloc_asprintf(dir, "%s/.namespacize", dir);
285 fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
288 errx(1, "%s already exists: can't namespacize twice",
290 err(1, "Opening %s", replname);
293 for (r = *repl; r; r = r->next) {
294 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
295 || write(fd, "\n", 1) != 1) {
296 unlink_no_errno(replname);
298 errx(1, "Short write to %s: disk full?",
300 errx(1, "Writing to %s", replname);
307 static int unlink_destroy(char *name)
313 static char *find_word(char *f, const char *str)
317 while ((p = strstr(p, str)) != NULL) {
318 /* Check it's not in the middle of a word. */
319 if (p > f && (isalnum(p[-1]) || p[-1] == '_')) {
323 if (isalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
332 /* This is horribly inefficient but simple. */
333 static const char *rewrite_file(const char *filename,
334 const struct replace *repl)
336 char *newname, *file;
339 verbose("Rewriting %s\n", filename);
340 file = grab_file(filename, filename, NULL);
342 err(1, "Reading file %s", filename);
344 for (; repl; repl = repl->next) {
347 while ((p = find_word(file, repl->string)) != NULL) {
349 char *new = talloc_array(file, char, strlen(file)+6);
352 memcpy(new, file, off);
353 if (isupper(repl->string[0]))
354 memcpy(new + off, "CCAN_", 5);
356 memcpy(new + off, "ccan_", 5);
357 strcpy(new + off + 5, file + off);
362 /* If we exit for some reason, we want this erased. */
363 newname = talloc_asprintf(talloc_autofree_context(), "%s.tmp",
365 fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
367 err(1, "Creating %s", newname);
369 talloc_set_destructor(newname, unlink_destroy);
370 if (write(fd, file, strlen(file)) != strlen(file)) {
372 errx(1, "Short write to %s: disk full?", newname);
373 errx(1, "Writing to %s", newname);
381 struct adjusted *next;
386 static void setup_adjust_files(const char *dir,
387 const struct replace *repl,
388 struct adjusted **adj)
392 for (files = get_dir(dir); *files; files++) {
393 if (strends(*files, "/test"))
394 setup_adjust_files(*files, repl, adj);
395 else if (strends(*files, ".c") || strends(*files, ".h")) {
396 struct adjusted *a = talloc(dir, struct adjusted);
399 a->tmpfile = rewrite_file(a->file, repl);
405 /* This is the "commit" stage, so we hope it won't fail. */
406 static void rename_files(const struct adjusted *adj)
409 if (!move_file(adj->tmpfile, adj->file))
410 warn("Could not rename over '%s', we're in trouble",
416 static void convert_dir(const char *dir)
419 struct replace *replace = NULL;
420 struct adjusted *adj = NULL;
422 /* Remove any ugly trailing slashes. */
423 name = talloc_strdup(NULL, dir);
424 while (strends(name, "/"))
425 name[strlen(name)-1] = '\0';
427 analyze_headers(name, &replace);
428 write_replacement_file(name, &replace);
429 setup_adjust_files(name, replace, &adj);
432 talloc_free(replace);
435 static struct replace *read_replacement_file(const char *depdir)
437 struct replace *repl = NULL;
438 char *replname = talloc_asprintf(depdir, "%s/.namespacize", depdir);
441 file = grab_file(replname, replname, NULL);
444 err(1, "Opening %s", replname);
448 for (line = strsplit(file, file, "\n"); *line; line++)
449 add_replace(&repl, *line);
453 static void adjust_dir(const char *dir)
455 char *parent = talloc_dirname(talloc_autofree_context(), dir);
458 verbose("Adjusting %s\n", dir);
460 for (deps = get_deps(parent, dir, false, NULL); *deps; deps++) {
462 struct adjusted *adj = NULL;
463 struct replace *repl;
465 depdir = talloc_asprintf(parent, "%s/%s", parent, *deps);
466 repl = read_replacement_file(depdir);
468 verbose("%s has been namespacized\n", depdir);
469 setup_adjust_files(parent, repl, &adj);
472 verbose("%s has not been namespacized\n", depdir);
479 static void adjust_dependents(const char *dir)
481 char *parent = talloc_dirname(NULL, dir);
482 char *base = talloc_basename(parent, dir);
485 verbose("Looking for dependents in %s\n", parent);
487 for (file = get_dir(parent); *file; file++) {
491 if (talloc_basename(*file, *file)[0] == '.')
494 info = talloc_asprintf(*file, "%s/_info", *file);
495 if (access(info, R_OK) != 0)
498 for (deps = get_deps(*file, *file, false, NULL);
500 if (!strstarts(*deps, "ccan/"))
502 if (streq(*deps + strlen("ccan/"), base))
508 verbose("%s is not dependent\n", *file);
513 int main(int argc, char *argv[])
515 if (argv[1] && streq(argv[1], "--verbose")) {
522 verbose("Namespacizing %s\n", argv[1]);
524 convert_dir(argv[1]);
525 adjust_dependents(argv[1]);
530 if (argc > 2 && streq(argv[1], "--adjust")) {
533 for (i = 2; i < argc; i++)