namespacize.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /* Code to move a ccan module into the ccan_ namespace. */
  2. #include <errno.h>
  3. #include <string.h>
  4. #include <stdbool.h>
  5. #include <ctype.h>
  6. #include <sys/types.h>
  7. #include <dirent.h>
  8. #include <unistd.h>
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. #include <fcntl.h>
  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"
  17. #include "tools.h"
  18. static bool verbose = false;
  19. static int indent = 0;
  20. #define verbose(args...) \
  21. do { if (verbose) { \
  22. unsigned int _i; \
  23. for (_i = 0; _i < indent; _i++) printf(" "); \
  24. printf(args); \
  25. } \
  26. } while(0)
  27. #define verbose_indent() (indent += 2)
  28. #define verbose_unindent() (indent -= 2)
  29. static int unlink_no_errno(const char *filename)
  30. {
  31. int ret = 0, serrno = errno;
  32. if (unlink(filename) < 0)
  33. ret = errno;
  34. errno = serrno;
  35. return ret;
  36. }
  37. static char **get_dir(const char *dir)
  38. {
  39. DIR *d;
  40. struct dirent *ent;
  41. char **names = tal_arr(NULL, char *, 0), *n;
  42. d = opendir(dir);
  43. if (!d)
  44. return NULL;
  45. while ((ent = readdir(d)) != NULL) {
  46. n = tal_fmt(names, "%s/%s", dir, ent->d_name);
  47. tal_expand(&names, &n, 1);
  48. }
  49. n = NULL;
  50. tal_expand(&names, &n, 1);
  51. closedir(d);
  52. return names;
  53. }
  54. struct replace
  55. {
  56. struct replace *next;
  57. char *string;
  58. };
  59. static void __attribute__((noreturn)) usage(void)
  60. {
  61. errx(1, "Usage:\n"
  62. "namespacize [--verbose] <dir>\n"
  63. "namespacize [--verbose] --adjust <dir>...\n"
  64. "The first form converts dir/ to insert 'ccan_' prefixes, and\n"
  65. "then adjusts any other ccan directories at the same level which\n"
  66. "are effected.\n"
  67. "--adjust does an adjustment for each directory, in case a\n"
  68. "dependency has been namespacized\n");
  69. }
  70. static void add_replace(struct replace **repl, const char *str)
  71. {
  72. struct replace *new, *i;
  73. /* Avoid duplicates. */
  74. for (i = *repl; i; i = i->next)
  75. if (streq(i->string, str))
  76. return;
  77. new = tal(*repl, struct replace);
  78. new->next = *repl;
  79. new->string = tal_strdup(new, str);
  80. *repl = new;
  81. }
  82. static void add_replace_tok(struct replace **repl, const char *s)
  83. {
  84. struct replace *new;
  85. unsigned int len = strspn(s, IDENT_CHARS);
  86. new = tal(*repl, struct replace);
  87. new->next = *repl;
  88. new->string = tal_strndup(new, s, len);
  89. *repl = new;
  90. }
  91. static void look_for_macros(char *contents, struct replace **repl)
  92. {
  93. char *p;
  94. enum { LINESTART, HASH, DEFINE, NONE } state = LINESTART;
  95. /* Look for lines of form #define X */
  96. for (p = contents; *p; p++) {
  97. if (*p == '\n')
  98. state = LINESTART;
  99. else if (!cisspace(*p)) {
  100. if (state == LINESTART && *p == '#')
  101. state = HASH;
  102. else if (state==HASH && !strncmp(p, "define", 6)) {
  103. state = DEFINE;
  104. p += 5;
  105. } else if (state == DEFINE) {
  106. unsigned int len;
  107. len = strspn(p, IDENT_CHARS);
  108. if (len) {
  109. char *s;
  110. s = tal_strndup(contents, p, len);
  111. /* Don't wrap idempotent wrappers */
  112. if (!strstarts(s, "CCAN_")) {
  113. verbose("Found %s\n", s);
  114. add_replace(repl, s);
  115. }
  116. }
  117. state = NONE;
  118. } else
  119. state = NONE;
  120. }
  121. }
  122. }
  123. /* Blank out preprocessor lines, and eliminate \ */
  124. static void preprocess(char *p)
  125. {
  126. char *s;
  127. /* We assume backslashes are only used for macros. */
  128. while ((s = strstr(p, "\\\n")) != NULL)
  129. s[0] = s[1] = ' ';
  130. /* Now eliminate # lines. */
  131. if (p[0] == '#') {
  132. unsigned int i;
  133. for (i = 0; p[i] != '\n'; i++)
  134. p[i] = ' ';
  135. }
  136. while ((s = strstr(p, "\n#")) != NULL) {
  137. unsigned int i;
  138. for (i = 1; s[i] != '\n'; i++)
  139. s[i] = ' ';
  140. }
  141. }
  142. static char *get_statement(const void *ctx, char **p)
  143. {
  144. unsigned brackets = 0;
  145. bool seen_brackets = false;
  146. char *answer = tal_strdup(ctx, "");
  147. for (;;) {
  148. if ((*p)[0] == '/' && (*p)[1] == '/')
  149. *p += strcspn(*p, "\n");
  150. else if ((*p)[0] == '/' && (*p)[1] == '*')
  151. *p = strstr(*p, "*/") + 1;
  152. else {
  153. char c = **p;
  154. if (c == ';' && !brackets) {
  155. (*p)++;
  156. return answer;
  157. }
  158. /* Compress whitespace into a single ' ' */
  159. if (cisspace(c)) {
  160. c = ' ';
  161. while (cisspace((*p)[1]))
  162. (*p)++;
  163. } else if (c == '{' || c == '(' || c == '[') {
  164. if (c == '(')
  165. seen_brackets = true;
  166. brackets++;
  167. } else if (c == '}' || c == ')' || c == ']')
  168. brackets--;
  169. if (answer[0] != '\0' || c != ' ') {
  170. tal_append_fmt(&answer, "%c", c);
  171. }
  172. if (c == '}' && seen_brackets && brackets == 0) {
  173. (*p)++;
  174. return answer;
  175. }
  176. }
  177. (*p)++;
  178. if (**p == '\0')
  179. return NULL;
  180. }
  181. }
  182. /* This hack should handle well-formatted code. */
  183. static void look_for_definitions(char *contents, struct replace **repl)
  184. {
  185. char *stmt, *p = contents;
  186. preprocess(contents);
  187. while ((stmt = get_statement(contents, &p)) != NULL) {
  188. int i, len;
  189. /* Definition of struct/union? */
  190. if ((strncmp(stmt, "struct", 5) == 0
  191. || strncmp(stmt, "union", 5) == 0)
  192. && strchr(stmt, '{') && stmt[7] != '{')
  193. add_replace_tok(repl, stmt+7);
  194. /* Definition of var or typedef? */
  195. for (i = strlen(stmt)-1; i >= 0; i--)
  196. if (strspn(stmt+i, IDENT_CHARS) == 0)
  197. break;
  198. if (i != strlen(stmt)-1) {
  199. add_replace_tok(repl, stmt+i+1);
  200. continue;
  201. }
  202. /* function or array declaration? */
  203. len = strspn(stmt, IDENT_CHARS "* ");
  204. if (len > 0 && (stmt[len] == '(' || stmt[len] == '[')) {
  205. if (strspn(stmt + len + 1, IDENT_CHARS) != 0) {
  206. for (i = len-1; i >= 0; i--)
  207. if (strspn(stmt+i, IDENT_CHARS) == 0)
  208. break;
  209. if (i != len-1) {
  210. add_replace_tok(repl, stmt+i+1);
  211. continue;
  212. }
  213. } else {
  214. /* Pointer to function? */
  215. len++;
  216. len += strspn(stmt + len, " *");
  217. i = strspn(stmt + len, IDENT_CHARS);
  218. if (i > 0 && stmt[len + i] == ')')
  219. add_replace_tok(repl, stmt+len);
  220. }
  221. }
  222. }
  223. }
  224. /* FIXME: Only does main header, should chase local includes. */
  225. static void analyze_headers(const char *dir, struct replace **repl)
  226. {
  227. char *hdr, *contents;
  228. /* Get hold of header, assume that's it. */
  229. hdr = tal_fmt(dir, "%s/%s.h", dir, path_basename(dir, dir));
  230. contents = tal_grab_file(dir, hdr, NULL);
  231. if (!contents)
  232. err(1, "Reading %s", hdr);
  233. verbose("Looking in %s for macros\n", hdr);
  234. verbose_indent();
  235. look_for_macros(contents, repl);
  236. verbose_unindent();
  237. verbose("Looking in %s for symbols\n", hdr);
  238. verbose_indent();
  239. look_for_definitions(contents, repl);
  240. verbose_unindent();
  241. }
  242. static void write_replacement_file(const char *dir, struct replace **repl)
  243. {
  244. char *replname = tal_fmt(dir, "%s/.namespacize", dir);
  245. int fd;
  246. struct replace *r;
  247. fd = open(replname, O_WRONLY|O_CREAT|O_EXCL, 0644);
  248. if (fd < 0) {
  249. if (errno == EEXIST)
  250. errx(1, "%s already exists: can't namespacize twice",
  251. replname);
  252. err(1, "Opening %s", replname);
  253. }
  254. for (r = *repl; r; r = r->next) {
  255. if (write(fd,r->string,strlen(r->string)) != strlen(r->string)
  256. || write(fd, "\n", 1) != 1) {
  257. unlink_no_errno(replname);
  258. if (errno == 0)
  259. errx(1, "Short write to %s: disk full?",
  260. replname);
  261. errx(1, "Writing to %s", replname);
  262. }
  263. }
  264. close(fd);
  265. }
  266. static void unlink_destroy(char *name)
  267. {
  268. unlink(name);
  269. }
  270. static char *find_word(char *f, const char *str)
  271. {
  272. char *p = f;
  273. while ((p = strstr(p, str)) != NULL) {
  274. /* Check it's not in the middle of a word. */
  275. if (p > f && (cisalnum(p[-1]) || p[-1] == '_')) {
  276. p++;
  277. continue;
  278. }
  279. if (cisalnum(p[strlen(str)]) || p[strlen(str)] == '_') {
  280. p++;
  281. continue;
  282. }
  283. return p;
  284. }
  285. return NULL;
  286. }
  287. /* This is horribly inefficient but simple. */
  288. static const char *rewrite_file(const char *filename,
  289. const struct replace *repl)
  290. {
  291. char *newname, *file;
  292. int fd;
  293. verbose("Rewriting %s\n", filename);
  294. file = tal_grab_file(filename, filename, NULL);
  295. if (!file)
  296. err(1, "Reading file %s", filename);
  297. for (; repl; repl = repl->next) {
  298. char *p;
  299. while ((p = find_word(file, repl->string)) != NULL) {
  300. unsigned int off;
  301. char *new = tal_arr(file, char, strlen(file)+6);
  302. off = p - file;
  303. memcpy(new, file, off);
  304. if (cisupper(repl->string[0]))
  305. memcpy(new + off, "CCAN_", 5);
  306. else
  307. memcpy(new + off, "ccan_", 5);
  308. strcpy(new + off + 5, file + off);
  309. file = new;
  310. }
  311. }
  312. /* If we exit for some reason, we want this erased. */
  313. newname = tal_fmt(autofree(), "%s.tmp", filename);
  314. fd = open(newname, O_WRONLY|O_CREAT|O_EXCL, 0644);
  315. if (fd < 0)
  316. err(1, "Creating %s", newname);
  317. tal_add_destructor(newname, unlink_destroy);
  318. if (write(fd, file, strlen(file)) != strlen(file)) {
  319. if (errno == 0)
  320. errx(1, "Short write to %s: disk full?", newname);
  321. errx(1, "Writing to %s", newname);
  322. }
  323. close(fd);
  324. return newname;
  325. }
  326. struct adjusted
  327. {
  328. struct adjusted *next;
  329. const char *file;
  330. const char *tmpfile;
  331. };
  332. static void setup_adjust_files(const char *dir,
  333. const struct replace *repl,
  334. struct adjusted **adj)
  335. {
  336. char **files;
  337. for (files = get_dir(dir); *files; files++) {
  338. if (strends(*files, "/test"))
  339. setup_adjust_files(*files, repl, adj);
  340. else if (strends(*files, ".c") || strends(*files, ".h")) {
  341. struct adjusted *a = tal(dir, struct adjusted);
  342. a->next = *adj;
  343. a->file = *files;
  344. a->tmpfile = rewrite_file(a->file, repl);
  345. *adj = a;
  346. }
  347. }
  348. }
  349. /* This is the "commit" stage, so we hope it won't fail. */
  350. static void rename_files(const struct adjusted *adj)
  351. {
  352. while (adj) {
  353. if (!move_file(adj->tmpfile, adj->file))
  354. warn("Could not rename over '%s', we're in trouble",
  355. adj->file);
  356. adj = adj->next;
  357. }
  358. }
  359. static void convert_dir(const char *dir)
  360. {
  361. char *name;
  362. struct replace *replace = NULL;
  363. struct adjusted *adj = NULL;
  364. /* Remove any ugly trailing slashes. */
  365. name = tal_strdup(NULL, dir);
  366. while (strends(name, "/"))
  367. name[strlen(name)-1] = '\0';
  368. analyze_headers(name, &replace);
  369. write_replacement_file(name, &replace);
  370. setup_adjust_files(name, replace, &adj);
  371. rename_files(adj);
  372. tal_free(name);
  373. tal_free(replace);
  374. }
  375. static struct replace *read_replacement_file(const char *depdir)
  376. {
  377. struct replace *repl = NULL;
  378. char *replname = tal_fmt(depdir, "%s/.namespacize", depdir);
  379. char *file, **line;
  380. file = tal_grab_file(replname, replname, NULL);
  381. if (!file) {
  382. if (errno != ENOENT)
  383. err(1, "Opening %s", replname);
  384. return NULL;
  385. }
  386. for (line = tal_strsplit(file, file, "\n", STR_EMPTY_OK); *line; line++)
  387. add_replace(&repl, *line);
  388. return repl;
  389. }
  390. static void adjust_dir(const char *dir)
  391. {
  392. char *parent = path_dirname(autofree(), dir);
  393. char **deps;
  394. verbose("Adjusting %s\n", dir);
  395. verbose_indent();
  396. for (deps = get_deps(parent, dir, "depends", false, compile_info);
  397. *deps;
  398. deps++) {
  399. char *depdir;
  400. struct adjusted *adj = NULL;
  401. struct replace *repl;
  402. depdir = tal_fmt(parent, "%s/%s", parent, *deps);
  403. repl = read_replacement_file(depdir);
  404. if (repl) {
  405. verbose("%s has been namespacized\n", depdir);
  406. setup_adjust_files(parent, repl, &adj);
  407. rename_files(adj);
  408. } else
  409. verbose("%s has not been namespacized\n", depdir);
  410. tal_free(depdir);
  411. }
  412. verbose_unindent();
  413. tal_free(parent);
  414. }
  415. static void adjust_dependents(const char *dir)
  416. {
  417. char *parent = path_dirname(NULL, dir);
  418. char *base = path_basename(parent, dir);
  419. char **file;
  420. verbose("Looking for dependents in %s\n", parent);
  421. verbose_indent();
  422. for (file = get_dir(parent); *file; file++) {
  423. char *info, **deps;
  424. bool isdep = false;
  425. if (path_basename(*file, *file)[0] == '.')
  426. continue;
  427. info = tal_fmt(*file, "%s/_info", *file);
  428. if (access(info, R_OK) != 0)
  429. continue;
  430. for (deps = get_deps(*file, *file, "depends", false,
  431. compile_info);
  432. *deps; deps++) {
  433. if (!strstarts(*deps, "ccan/"))
  434. continue;
  435. if (streq(*deps + strlen("ccan/"), base))
  436. isdep = true;
  437. }
  438. if (isdep)
  439. adjust_dir(*file);
  440. else
  441. verbose("%s is not dependent\n", *file);
  442. }
  443. verbose_unindent();
  444. }
  445. int main(int argc, char *argv[])
  446. {
  447. if (argv[1] && streq(argv[1], "--verbose")) {
  448. verbose = true;
  449. argv++;
  450. argc--;
  451. }
  452. if (argc == 2) {
  453. verbose("Namespacizing %s\n", argv[1]);
  454. verbose_indent();
  455. convert_dir(argv[1]);
  456. adjust_dependents(argv[1]);
  457. verbose_unindent();
  458. return 0;
  459. }
  460. if (argc > 2 && streq(argv[1], "--adjust")) {
  461. unsigned int i;
  462. for (i = 2; i < argc; i++)
  463. adjust_dir(argv[i]);
  464. return 0;
  465. }
  466. usage();
  467. }