auto-dep.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #!/usr/bin/env python3
  2. # coding: utf-8
  3. import os
  4. import sys
  5. import subprocess
  6. cflags = "-O3 -g -std=gnu99 -I. -Iapps -pipe -mmmx -msse -msse2 -fplan9-extensions -Wall -Wextra -Wno-unused-parameter"
  7. class Classifier(object):
  8. dependency_hints = {
  9. # Toaru Standard Library
  10. '<toaru/kbd.h>': (None, '-ltoaru_kbd', []),
  11. '<toaru/list.h>': (None, '-ltoaru_list', []),
  12. '<toaru/hashmap.h>': (None, '-ltoaru_hashmap', ['<toaru/list.h>']),
  13. '<toaru/tree.h>': (None, '-ltoaru_tree', ['<toaru/list.h>']),
  14. '<toaru/pex.h>': (None, '-ltoaru_pex', []),
  15. '<toaru/auth.h>': (None, '-ltoaru_auth', []),
  16. '<toaru/graphics.h>': (None, '-ltoaru_graphics', []),
  17. '<toaru/drawstring.h>': (None, '-ltoaru_drawstring', ['<toaru/graphics.h>']),
  18. '<toaru/jpeg.h>': (None, '-ltoaru_jpeg', ['<toaru/graphics.h>']),
  19. '<toaru/rline.h>': (None, '-ltoaru_rline', ['<toaru/kbd.h>']),
  20. '<toaru/rline_exp.h>': (None, '-ltoaru_rline_exp', ['<toaru/rline.h>']),
  21. '<toaru/confreader.h>': (None, '-ltoaru_confreader', ['<toaru/hashmap.h>']),
  22. '<toaru/markup.h>': (None, '-ltoaru_markup', ['<toaru/hashmap.h>']),
  23. '<toaru/yutani.h>': (None, '-ltoaru_yutani', ['<toaru/kbd.h>', '<toaru/list.h>', '<toaru/pex.h>', '<toaru/graphics.h>', '<toaru/hashmap.h>']),
  24. '<toaru/decorations.h>': (None, '-ltoaru_decorations', ['<toaru/menu.h>', '<toaru/sdf.h>', '<toaru/graphics.h>', '<toaru/yutani.h>']),
  25. '<toaru/termemu.h>': (None, '-ltoaru_termemu', ['<toaru/graphics.h>']),
  26. '<toaru/sdf.h>': (None, '-ltoaru_sdf', ['<toaru/graphics.h>', '<toaru/hashmap.h>']),
  27. '<toaru/icon_cache.h>': (None, '-ltoaru_icon_cache', ['<toaru/graphics.h>', '<toaru/hashmap.h>']),
  28. '<toaru/menu.h>': (None, '-ltoaru_menu', ['<toaru/sdf.h>', '<toaru/yutani.h>', '<toaru/icon_cache.h>', '<toaru/graphics.h>', '<toaru/hashmap.h>']),
  29. '<toaru/textregion.h>': (None, '-ltoaru_textregion', ['<toaru/sdf.h>', '<toaru/yutani.h>','<toaru/graphics.h>', '<toaru/hashmap.h>']),
  30. '<toaru/button.h>': (None, '-ltoaru_button', ['<toaru/graphics.h>','<toaru/sdf.h>', '<toaru/icon_cache.h>']),
  31. # OPTIONAL third-party libraries, for extensions / ports
  32. '<ft2build.h>': ('freetype2', '-lfreetype', []),
  33. '<pixman.h>': ('pixman-1', '-lpixman-1', []),
  34. '<cairo.h>': ('cairo', '-lcairo', ['<ft2build.h>', '<pixman.h>']),
  35. }
  36. def __init__(self, filename):
  37. self.export_dynamic_hint = False
  38. self.filename = filename
  39. self.includes, self.libs = self._depends()
  40. def _calculate(self, depends, new):
  41. """Calculate all dependencies for the given set of new elements."""
  42. for k in new:
  43. if not k in depends:
  44. depends.append(k)
  45. _, _, other = self.dependency_hints[k]
  46. depends = self._calculate(depends, other)
  47. return depends
  48. def _sort(self, depends):
  49. """Sort the list of dependencies so that elements appearing first depend on elements following."""
  50. satisfied = []
  51. a = depends[:]
  52. while set(satisfied) != set(depends):
  53. b = []
  54. for k in a:
  55. if all([x in satisfied for x in self.dependency_hints[k][2]]):
  56. satisfied.append(k)
  57. else:
  58. b.append(k)
  59. a = b[:]
  60. return satisfied[::-1]
  61. def _depends(self):
  62. """Calculate include and library dependencies."""
  63. lines = []
  64. depends = []
  65. with open(self.filename,'r') as f:
  66. lines = f.readlines()
  67. for l in lines:
  68. if l.startswith('#include'):
  69. depends.extend([k for k in list(self.dependency_hints.keys()) if l.startswith('#include ' + k)])
  70. elif l.startswith('/* auto-dep: export-dynamic */'):
  71. self.export_dynamic_hint = True
  72. depends = self._calculate([], depends)
  73. depends = self._sort(depends)
  74. includes = []
  75. libraries = []
  76. for k in depends:
  77. dep = self.dependency_hints[k]
  78. if dep[0]:
  79. includes.append('-I' + 'base/usr/include/' + dep[0])
  80. if dep[1]:
  81. libraries.append(dep[1])
  82. return includes, libraries
  83. def todep(name):
  84. """Convert a library name to an archive path or object file name."""
  85. if name.startswith("-l"):
  86. name = name.replace("-l","",1)
  87. if name.startswith('toaru'):
  88. return (True, "%s/lib%s.so" % ('base/lib', name))
  89. else:
  90. return (True, "%s/lib%s.so" % ('base/usr/lib', name))
  91. else:
  92. return (False, name)
  93. def toheader(name):
  94. if name.startswith('-ltoaru_'):
  95. return name.replace('-ltoaru_','base/usr/include/toaru/') + '.h'
  96. else:
  97. return ''
  98. if __name__ == "__main__":
  99. if len(sys.argv) < 3:
  100. print("usage: util/auto-dep.py command filename")
  101. exit(1)
  102. command = sys.argv[1]
  103. filename = sys.argv[2]
  104. c = Classifier(filename)
  105. if command == "--cflags":
  106. print(" ".join([x for x in c.includes]))
  107. elif command == "--libs":
  108. print(" ".join([x for x in c.libs]))
  109. elif command == "--deps":
  110. results = [todep(x) for x in c.libs]
  111. normal = [x[1] for x in results if not x[0]]
  112. order_only = [x[1] for x in results if x[0]]
  113. print(" ".join(normal) + " | " + " ".join(order_only))
  114. elif command == "--build":
  115. subprocess.run("gcc {cflags} {extra} {includes} -o {app} {source} {libraries}".format(
  116. cflags=cflags,
  117. app=os.path.basename(filename).replace(".c",""),
  118. source=filename,
  119. headers=" ".join([toheader(x) for x in c.libs]),
  120. libraries=" ".join([x for x in c.libs]),
  121. includes=" ".join([x for x in c.includes if x is not None]),
  122. extra="-Wl,--export-dynamic" if c.export_dynamic_hint else "",
  123. ), shell=True)
  124. elif command == "--buildlib":
  125. libname = os.path.basename(filename).replace(".c","")
  126. _libs = [x for x in c.libs if not x.startswith('-ltoaru_') or x.replace("-ltoaru_","") != libname]
  127. subprocess.run("gcc {cflags} {includes} -shared -fPIC -olibtoaru_{lib}.so {source} {libraries}".format(
  128. cflags=cflags,
  129. lib=libname,
  130. source=filename,
  131. headers=" ".join([toheader(x) for x in c.libs]),
  132. libraryfiles=" ".join([todep(x)[1] for x in _libs]),
  133. libraries=" ".join([x for x in _libs]),
  134. includes=" ".join([x for x in c.includes if x is not None])
  135. ),shell=True)
  136. elif command == "--make":
  137. print("base/bin/{app}: {source} {headers} util/auto-dep.py | {libraryfiles} $(LC)\n\t$(CC) $(CFLAGS) {extra} {includes} -o $@ $< {libraries}".format(
  138. app=os.path.basename(filename).replace(".c",""),
  139. source=filename,
  140. headers=" ".join([toheader(x) for x in c.libs]),
  141. libraryfiles=" ".join([todep(x)[1] for x in c.libs]),
  142. libraries=" ".join([x for x in c.libs]),
  143. includes=" ".join([x for x in c.includes if x is not None]),
  144. extra="-Wl,--export-dynamic" if c.export_dynamic_hint else "",
  145. ))
  146. elif command == "--makelib":
  147. libname = os.path.basename(filename).replace(".c","")
  148. _libs = [x for x in c.libs if not x.startswith('-ltoaru_') or x.replace("-ltoaru_","") != libname]
  149. print("base/lib/libtoaru_{lib}.so: {source} {headers} util/auto-dep.py | {libraryfiles} $(LC)\n\t$(CC) $(CFLAGS) {includes} -shared -fPIC -o $@ $< {libraries}".format(
  150. lib=libname,
  151. source=filename,
  152. headers=" ".join([toheader(x) for x in c.libs]),
  153. libraryfiles=" ".join([todep(x)[1] for x in _libs]),
  154. libraries=" ".join([x for x in _libs]),
  155. includes=" ".join([x for x in c.includes if x is not None])
  156. ))