1 /* Code to move a ccan module into the ccan_ namespace. */
12 #include "ccan/str/str.h"
13 #include "ccan/take/take.h"
14 #include "ccan/rbuf/rbuf.h"
15 #include "ccan/tal/path/path.h"
16 #include "ccan/err/err.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)
44 char **names = tal_arr(NULL, char *, 0), *n;
50 while ((ent = readdir(d)) != NULL) {
51 n = tal_fmt(names, "%s/%s", dir, ent->d_name);
52 tal_expand(&names, &n, 1);
55 tal_expand(&names, &n, 1);
66 static void __attribute__((noreturn)) usage(void)
69 "namespacize [--verbose] <dir>\n"
70 "namespacize [--verbose] --adjust <dir>...\n"
71 "The first form converts dir/ to insert 'ccan_' prefixes, and\n"
72 "then adjusts any other ccan directories at the same level which\n"
74 "--adjust does an adjustment for each directory, in case a\n"
75 "dependency has been namespacized\n");
78 static void add_replace(struct replace **repl, const char *str)
80 struct replace *new, *i;
82 /* Avoid duplicates. */
83 for (i = *repl; i; i = i->next)
84 if (streq(i->string, str))
87 new = tal(*repl, struct replace);
89 new->string = tal_strdup(new, str);
93 static void add_replace_tok(struct replace **repl, const char *s)
96 unsigned int len = strspn(s, IDENT_CHARS);
98 new = tal(*repl, struct replace);
100 new->string = tal_strndup(new, s, len);
104 static void look_for_macros(char *contents, struct replace **repl)
107 enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
109 /* Look for lines of form #define X */
110 for (p = contents; *p; p++) {
113 else if (!cisspace(*p)) {
114 if (state == LINESTART && *p == '#')
116 else if (state==HASH && !strncmp(p, "define", 6)) {
119 } else if (state == DEFINE) {
122 len = strspn(p, IDENT_CHARS);
125 s = tal_strndup(contents, p, len);
126 /* Don't wrap idempotent wrappers */
127 if (!strstarts(s, "CCAN_")) {
128 verbose("Found %s\n", s);
129 add_replace(repl, s);
139 /* Blank out preprocessor lines, and eliminate \ */
140 static void preprocess(char *p)
144 /* We assume backslashes are only used for macros. */
145 while ((s = strstr(p, "\\\n")) != NULL)
148 /* Now eliminate # lines. */
151 for (i = 0; p[i] != '\n'; i++)
154 while ((s = strstr(p, "\n#")) != NULL) {
156 for (i = 1; s[i] != '\n'; i++)
161 static char *get_statement(const void *ctx, char **p)
163 unsigned brackets = 0;
164 bool seen_brackets = false;
165 char *answer = tal_strdup(ctx, "");
168 if ((*p)[0] == '/' && (*p)[1] == '/')
169 *p += strcspn(*p, "\n");
170 else if ((*p)[0] == '/' && (*p)[1] == '*')
171 *p = strstr(*p, "*/") + 1;
174 if (c == ';' && !brackets) {
178 /* Compress whitespace into a single ' ' */
181 while (cisspace((*p)[1]))
183 } else if (c == '{' || c == '(' || c == '[') {
185 seen_brackets = true;
187 } else if (c == '}' || c == ')' || c == ']')
190 if (answer[0] != '\0' || c != ' ') {
191 tal_append_fmt(&answer, "%c", c);
193 if (c == '}' && seen_brackets && brackets == 0) {
204 /* This hack should handle well-formatted code. */
205 static void look_for_definitions(char *contents, struct replace **repl)
207 char *stmt, *p = contents;
209 preprocess(contents);
211 while ((stmt = get_statement(contents, &p)) != NULL) {
214 /* Definition of struct/union? */
215 if ((strncmp(stmt, "struct", 5) == 0
216 || strncmp(stmt, "union", 5) == 0)
217 && strchr(stmt, '{') && stmt[7] != '{')
218 add_replace_tok(repl, stmt+7);
220 /* Definition of var or typedef? */
221 for (i = strlen(stmt)-1; i >= 0; i--)
222 if (strspn(stmt+i, IDENT_CHARS) == 0)
225 if (i != strlen(stmt)-1) {
226 add_replace_tok(repl, stmt+i+1);
230 /* function or array declaration? */
231 len = strspn(stmt, IDENT_CHARS "* ");
232 if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
233 if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
234 for (i = len-1; i >= 0; i--)
235 if (strspn(stmt+i, IDENT_CHARS) == 0)
238 add_replace_tok(repl, stmt+i+1);
242 /* Pointer to function? */
244 len += strspn(stmt + len, " *");
245 i = strspn(stmt + len, IDENT_CHARS);
246 if (i > 0 && stmt[len + i] == ')')
247 add_replace_tok(repl, stmt+len);
253 /* FIXME: Only does main header, should chase local includes. */
254 static void analyze_headers(const char *dir, struct replace **repl)
256 char *hdr, *contents;
258 /* Get hold of header, assume that's it. */
259 hdr = tal_fmt(dir, "%s.h",
260 path_join(NULL, dir, take(path_basename(NULL, dir))));
262 contents = tal_grab_file(dir, hdr, NULL);
264 err(1, "Reading %s", hdr);
266 verbose("Looking in %s for macros\n", hdr);
268 look_for_macros(contents, repl);
271 verbose("Looking in %s for symbols\n", hdr);
273 look_for_definitions(contents, repl);
277 static void write_replacement_file(const char *dir, struct replace **repl)
279 char *replname = path_join(dir, dir, ".namespacize");
283 fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
286 errx(1, "%s already exists: can't namespacize twice",
288 err(1, "Opening %s", replname);
291 for (r = *repl; r; r = r->next) {
292 if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
293 || write(fd, "\n", 1) != 1) {
294 unlink_no_errno(replname);
296 errx(1, "Short write to %s: disk full?",
298 errx(1, "Writing to %s", replname);
305 static void unlink_destroy(char *name)
310 static char *find_word(char *f, const char *str)
314 while ((p = strstr(p, str)) != NULL) {
315 /* Check it's not in the middle of a word. */
316 if (p > f && (cisalnum(p[-1]) || p[-1] == '_')) {
320 if (cisalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
329 /* This is horribly inefficient but simple. */
330 static const char *rewrite_file(const char *filename,
331 const struct replace *repl)
333 char *newname, *file;
336 verbose("Rewriting %s\n", filename);
337 file = tal_grab_file(filename, filename, NULL);
339 err(1, "Reading file %s", filename);
341 for (; repl; repl = repl->next) {
344 while ((p = find_word(file, repl->string)) != NULL) {
346 char *new = tal_arr(file, char, strlen(file)+6);
349 memcpy(new, file, off);
350 if (cisupper(repl->string[0]))
351 memcpy(new + off, "CCAN_", 5);
353 memcpy(new + off, "ccan_", 5);
354 strcpy(new + off + 5, file + off);
359 /* If we exit for some reason, we want this erased. */
360 newname = tal_fmt(autofree(), "%s.tmp", filename);
361 fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
363 err(1, "Creating %s", newname);
365 tal_add_destructor(newname, unlink_destroy);
366 if (write(fd, file, strlen(file)) != strlen(file)) {
368 errx(1, "Short write to %s: disk full?", newname);
369 errx(1, "Writing to %s", newname);
377 struct adjusted *next;
382 static void setup_adjust_files(const char *dir,
383 const struct replace *repl,
384 struct adjusted **adj)
388 for (files = get_dir(dir); *files; files++) {
389 if (strends(*files, "/test"))
390 setup_adjust_files(*files, repl, adj);
391 else if (strends(*files, ".c") || strends(*files, ".h")) {
392 struct adjusted *a = tal(dir, struct adjusted);
395 a->tmpfile = rewrite_file(a->file, repl);
401 /* This is the "commit" stage, so we hope it won't fail. */
402 static void rename_files(const struct adjusted *adj)
405 if (!move_file(adj->tmpfile, adj->file))
406 warn("Could not rename over '%s', we're in trouble",
412 static void convert_dir(const char *dir)
415 struct replace *replace = NULL;
416 struct adjusted *adj = NULL;
418 /* Remove any ugly trailing slashes. */
419 name = path_canon(NULL, dir);
420 analyze_headers(name, &replace);
421 write_replacement_file(name, &replace);
422 setup_adjust_files(name, replace, &adj);
428 static struct replace *read_replacement_file(const char *depdir)
430 struct replace *repl = NULL;
431 char *replname = path_join(depdir, depdir, ".namespacize");
434 file = tal_grab_file(replname, replname, NULL);
437 err(1, "Opening %s", replname);
441 for (line = tal_strsplit(file, file, "\n", STR_EMPTY_OK); *line; line++)
442 add_replace(&repl, *line);
446 static void adjust_dir(const char *dir)
448 char *parent = path_dirname(autofree(), dir);
451 verbose("Adjusting %s\n", dir);
453 for (deps = get_deps(parent, dir, "depends", false, compile_info);
457 struct adjusted *adj = NULL;
458 struct replace *repl;
460 depdir = path_join(parent, parent, *deps);
461 repl = read_replacement_file(depdir);
463 verbose("%s has been namespacized\n", depdir);
464 setup_adjust_files(parent, repl, &adj);
467 verbose("%s has not been namespacized\n", depdir);
474 static void adjust_dependents(const char *dir)
476 char *parent = path_dirname(NULL, dir);
477 char *base = path_basename(parent, dir);
480 verbose("Looking for dependents in %s\n", parent);
482 for (file = get_dir(parent); *file; file++) {
486 if (path_basename(*file, *file)[0] == '.')
489 info = path_join(*file, *file, "_info");
490 if (access(info, R_OK) != 0)
493 for (deps = get_deps(*file, *file, "depends", false,
496 if (!strstarts(*deps, "ccan/"))
498 if (streq(*deps + strlen("ccan/"), base))
504 verbose("%s is not dependent\n", *file);
509 int main(int argc, char *argv[])
511 if (argv[1] && streq(argv[1], "--verbose")) {
518 verbose("Namespacizing %s\n", argv[1]);
520 convert_dir(argv[1]);
521 adjust_dependents(argv[1]);
526 if (argc > 2 && streq(argv[1], "--adjust")) {
529 for (i = 2; i < argc; i++)