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);
56 /* FIXME: if the loop doesn't run at least once, we'll segfault here */
68 static void __attribute__((noreturn)) usage(void)
71 "namespacize [--verbose] <dir>\n"
72 "namespacize [--verbose] --adjust <dir>...\n"
73 "The first form converts dir/ to insert 'ccan_' prefixes, and\n"
74 "then adjusts any other ccan directories at the same level which\n"
76 "--adjust does an adjustment for each directory, in case a\n"
77 "dependency has been namespacized\n");
80 static void add_replace(struct replace **repl, const char *str)
82 struct replace *new, *i;
84 /* Avoid duplicates. */
85 for (i = *repl; i; i = i->next)
86 if (streq(i->string, str))
89 new = talloc(*repl, struct replace);
91 new->string = talloc_strdup(new, str);
95 static void add_replace_tok(struct replace **repl, const char *s)
98 unsigned int len = strspn(s, IDENT_CHARS);
100 new = talloc(*repl, struct replace);
102 new->string = talloc_strndup(new, s, len);
106 static void look_for_macros(char *contents, struct replace **repl)
109 enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
111 /* Look for lines of form #define X */
112 for (p = contents; *p; p++) {
115 else if (!cisspace(*p)) {
116 if (state == LINESTART && *p == '#')
118 else if (state==HASH && !strncmp(p, "define", 6)) {
121 } else if (state == DEFINE) {
124 len = strspn(p, IDENT_CHARS);
127 s = talloc_strndup(contents, p, len);
128 /* Don't wrap idempotent wrappers */
129 if (!strstarts(s, "CCAN_")) {
130 verbose("Found %s\n", s);
131 add_replace(repl, s);
141 /* Blank out preprocessor lines, and eliminate \ */
142 static void preprocess(char *p)
146 /* We assume backslashes are only used for macros. */
147 while ((s = strstr(p, "\\\n")) != NULL)
150 /* Now eliminate # lines. */
153 for (i = 0; p[i] != '\n'; i++)
156 while ((s = strstr(p, "\n#")) != NULL) {
158 for (i = 1; s[i] != '\n'; i++)
163 static char *get_statement(const void *ctx, char **p)
165 unsigned brackets = 0;
166 bool seen_brackets = false;
167 char *answer = talloc_strdup(ctx, "");
170 if ((*p)[0] == '/' && (*p)[1] == '/')
171 *p += strcspn(*p, "\n");
172 else if ((*p)[0] == '/' && (*p)[1] == '*')
173 *p = strstr(*p, "*/") + 1;
176 if (c == ';' && !brackets) {
180 /* Compress whitespace into a single ' ' */
183 while (cisspace((*p)[1]))
185 } else if (c == '{' || c == '(' || c == '[') {
187 seen_brackets = true;
189 } else if (c == '}' || c == ')' || c == ']')
192 if (answer[0] != '\0' || c != ' ') {
193 answer = talloc_realloc(NULL, answer, char,
195 answer[strlen(answer)+1] = '\0';
196 answer[strlen(answer)] = c;
198 if (c == '}' && seen_brackets && brackets == 0) {
209 /* This hack should handle well-formatted code. */
210 static void look_for_definitions(char *contents, struct replace **repl)
212 char *stmt, *p = contents;
214 preprocess(contents);
216 while ((stmt = get_statement(contents, &p)) != NULL) {
219 /* Definition of struct/union? */
220 if ((strncmp(stmt, "struct", 5) == 0
221 || strncmp(stmt, "union", 5) == 0)
222 && strchr(stmt, '{') && stmt[7] != '{')
223 add_replace_tok(repl, stmt+7);
225 /* Definition of var or typedef? */
226 for (i = strlen(stmt)-1; i >= 0; i--)
227 if (strspn(stmt+i, IDENT_CHARS) == 0)
230 if (i != strlen(stmt)-1) {
231 add_replace_tok(repl, stmt+i+1);
235 /* function or array declaration? */
236 len = strspn(stmt, IDENT_CHARS "* ");
237 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
238 if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
239 for (i = len-1; i >= 0; i--)
240 if (strspn(stmt+i, IDENT_CHARS) == 0)
243 add_replace_tok(repl, stmt+i+1);
247 /* Pointer to function? */
249 len += strspn(stmt + len, " *");
250 i = strspn(stmt + len, IDENT_CHARS);
251 if (i > 0 && stmt[len + i] == ')')
252 add_replace_tok(repl, stmt+len);
258 /* FIXME: Only does main header, should chase local includes. */
259 static void analyze_headers(const char *dir, struct replace **repl)
261 char *hdr, *contents;
263 /* Get hold of header, assume that's it. */
264 hdr = talloc_asprintf(dir, "%s/%s.h", dir, talloc_basename(dir, dir));
265 contents = grab_file(dir, hdr, NULL);
267 err(1, "Reading %s", hdr);
269 verbose("Looking in %s for macros\n", hdr);
271 look_for_macros(contents, repl);
274 verbose("Looking in %s for symbols\n", hdr);
276 look_for_definitions(contents, repl);
280 static void write_replacement_file(const char *dir, struct replace **repl)
282 char *replname = talloc_asprintf(dir, "%s/.namespacize", dir);
286 fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
289 errx(1, "%s already exists: can't namespacize twice",
291 err(1, "Opening %s", replname);
294 for (r = *repl; r; r = r->next) {
295 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
296 || write(fd, "\n", 1) != 1) {
297 unlink_no_errno(replname);
299 errx(1, "Short write to %s: disk full?",
301 errx(1, "Writing to %s", replname);
308 static int unlink_destroy(char *name)
314 static char *find_word(char *f, const char *str)
318 while ((p = strstr(p, str)) != NULL) {
319 /* Check it's not in the middle of a word. */
320 if (p > f && (cisalnum(p[-1]) || p[-1] == '_')) {
324 if (cisalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
333 /* This is horribly inefficient but simple. */
334 static const char *rewrite_file(const char *filename,
335 const struct replace *repl)
337 char *newname, *file;
340 verbose("Rewriting %s\n", filename);
341 file = grab_file(filename, filename, NULL);
343 err(1, "Reading file %s", filename);
345 for (; repl; repl = repl->next) {
348 while ((p = find_word(file, repl->string)) != NULL) {
350 char *new = talloc_array(file, char, strlen(file)+6);
353 memcpy(new, file, off);
354 if (cisupper(repl->string[0]))
355 memcpy(new + off, "CCAN_", 5);
357 memcpy(new + off, "ccan_", 5);
358 strcpy(new + off + 5, file + off);
363 /* If we exit for some reason, we want this erased. */
364 newname = talloc_asprintf(talloc_autofree_context(), "%s.tmp",
366 fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
368 err(1, "Creating %s", newname);
370 talloc_set_destructor(newname, unlink_destroy);
371 if (write(fd, file, strlen(file)) != strlen(file)) {
373 errx(1, "Short write to %s: disk full?", newname);
374 errx(1, "Writing to %s", newname);
382 struct adjusted *next;
387 static void setup_adjust_files(const char *dir,
388 const struct replace *repl,
389 struct adjusted **adj)
393 for (files = get_dir(dir); *files; files++) {
394 if (strends(*files, "/test"))
395 setup_adjust_files(*files, repl, adj);
396 else if (strends(*files, ".c") || strends(*files, ".h")) {
397 struct adjusted *a = talloc(dir, struct adjusted);
400 a->tmpfile = rewrite_file(a->file, repl);
406 /* This is the "commit" stage, so we hope it won't fail. */
407 static void rename_files(const struct adjusted *adj)
410 if (!move_file(adj->tmpfile, adj->file))
411 warn("Could not rename over '%s', we're in trouble",
417 static void convert_dir(const char *dir)
420 struct replace *replace = NULL;
421 struct adjusted *adj = NULL;
423 /* Remove any ugly trailing slashes. */
424 name = talloc_strdup(NULL, dir);
425 while (strends(name, "/"))
426 name[strlen(name)-1] = '\0';
428 analyze_headers(name, &replace);
429 write_replacement_file(name, &replace);
430 setup_adjust_files(name, replace, &adj);
433 talloc_free(replace);
436 static struct replace *read_replacement_file(const char *depdir)
438 struct replace *repl = NULL;
439 char *replname = talloc_asprintf(depdir, "%s/.namespacize", depdir);
442 file = grab_file(replname, replname, NULL);
445 err(1, "Opening %s", replname);
449 for (line = strsplit(file, file, "\n"); *line; line++)
450 add_replace(&repl, *line);
454 static void adjust_dir(const char *dir)
456 char *parent = talloc_dirname(talloc_autofree_context(), dir);
459 verbose("Adjusting %s\n", dir);
461 for (deps = get_deps(parent, dir, false, NULL); *deps; deps++) {
463 struct adjusted *adj = NULL;
464 struct replace *repl;
466 depdir = talloc_asprintf(parent, "%s/%s", parent, *deps);
467 repl = read_replacement_file(depdir);
469 verbose("%s has been namespacized\n", depdir);
470 setup_adjust_files(parent, repl, &adj);
473 verbose("%s has not been namespacized\n", depdir);
480 static void adjust_dependents(const char *dir)
482 char *parent = talloc_dirname(NULL, dir);
483 char *base = talloc_basename(parent, dir);
486 verbose("Looking for dependents in %s\n", parent);
488 for (file = get_dir(parent); *file; file++) {
492 if (talloc_basename(*file, *file)[0] == '.')
495 info = talloc_asprintf(*file, "%s/_info", *file);
496 if (access(info, R_OK) != 0)
499 for (deps = get_deps(*file, *file, false, NULL);
501 if (!strstarts(*deps, "ccan/"))
503 if (streq(*deps + strlen("ccan/"), base))
509 verbose("%s is not dependent\n", *file);
514 int main(int argc, char *argv[])
516 if (argv[1] && streq(argv[1], "--verbose")) {
523 verbose("Namespacizing %s\n", argv[1]);
525 convert_dir(argv[1]);
526 adjust_dependents(argv[1]);
531 if (argc > 2 && streq(argv[1], "--adjust")) {
534 for (i = 2; i < argc; i++)