build-singleheader.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. const fs = require('fs')
  2. function read_file(name) {
  3. return fs
  4. .readFileSync(name)
  5. .toString('utf-8')
  6. .trim()
  7. }
  8. function include_enet(src) {
  9. return src
  10. .split('\n')
  11. .map(line => {
  12. if (line.indexOf('#include "enet/') !== -1) {
  13. return read_file('include/' + line.slice(10, -1))
  14. }
  15. return line
  16. })
  17. .join('\n')
  18. }
  19. function filter_libs(src, unqiue_lib_list) {
  20. return src
  21. .split('\n')
  22. .map((line, i) => {
  23. if (line.indexOf('#include "enet/') !== -1) {
  24. return ''
  25. }
  26. if (line.indexOf('#include <') !== -1) {
  27. if (!unqiue_lib_list[line.slice(10, -1)]) {
  28. unqiue_lib_list[line.slice(10, -1)] = 1;
  29. return line
  30. } else {
  31. unqiue_lib_list[line.slice(10, -1)]++
  32. return ''
  33. }
  34. }
  35. return line.replace(/\s*$/, '')
  36. })
  37. .join('\n')
  38. }
  39. function attach_src(src, unqiue_lib_list, sources_list, scr_template) {
  40. let files = sources_list
  41. .map(file => {
  42. return '\n// @from_file: ' + file + '\n' +
  43. filter_libs(read_file(file), unqiue_lib_list)
  44. })
  45. .join('\n')
  46. // add 4 spaces in front
  47. files = files
  48. .split('\n')
  49. .map(line => line !== '' ? " " + line : line)
  50. .join('\n')
  51. src = src.replace('#endif /* __ENET_ENET_H__ */', '')
  52. src = src + scr_template[0] + files + scr_template[1]
  53. return src
  54. }
  55. let sources = [
  56. 'callbacks.c',
  57. 'compress.c',
  58. 'host.c',
  59. 'list.c',
  60. 'packet.c',
  61. 'peer.c',
  62. 'protocol.c',
  63. 'unix.c',
  64. 'win32.c',
  65. ]
  66. let scr_template = [
  67. `
  68. #if defined(ENET_IMPLEMENTATION) && !defined(ENET_IMPLEMENTATION_DONE)
  69. #define ENET_IMPLEMENTATION_DONE
  70. #define ENET_BUILDING_LIB 1
  71. #ifdef __cplusplus
  72. extern "C"
  73. {
  74. #endif
  75. `,
  76. // code there
  77. `
  78. #ifdef __cplusplus
  79. }
  80. #endif
  81. #endif
  82. #endif /* __ENET_ENET_H__ */
  83. `];
  84. let prefix =
  85. `/**
  86. * include/enet.h - a Single-Header auto-generated variant of enet.h library.
  87. *
  88. * Usage:
  89. * #define ENET_IMPLEMENTATION exactly in ONE source file right BEFORE including the library, like:
  90. *
  91. * #define ENET_IMPLEMENTATION
  92. * #include <enet.h>
  93. *
  94. */
  95. `;
  96. (function main() {
  97. let list = {};
  98. let src = read_file('include/enet/enet.h')
  99. src = include_enet(src)
  100. src = filter_libs(src, list)
  101. src = attach_src(src, list, sources, scr_template)
  102. fs.writeFileSync('include/enet.h', prefix + src)
  103. })();