common-dependencies.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #
  2. # common-dependencies.py
  3. # Convenience script to check dependencies and add libs and sources for Marlin Enabled Features
  4. #
  5. import pioutil
  6. if pioutil.is_pio_build():
  7. import os, re, fnmatch, glob
  8. srcfilepattern = re.compile(r".*[.](cpp|c)$")
  9. marlinbasedir = os.path.join(os.getcwd(), "Marlin/")
  10. env = pioutil.env
  11. from platformio.package.meta import PackageSpec
  12. from platformio.project.config import ProjectConfig
  13. verbose = 0
  14. FEATURE_CONFIG = {}
  15. def validate_pio():
  16. PIO_VERSION_MIN = (6, 0, 1)
  17. try:
  18. from platformio import VERSION as PIO_VERSION
  19. weights = (1000, 100, 1)
  20. version_min = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION_MIN)])
  21. version_cur = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION)])
  22. if version_cur < version_min:
  23. print()
  24. print("**************************************************")
  25. print("****** An update to PlatformIO is ******")
  26. print("****** required to build Marlin Firmware. ******")
  27. print("****** ******")
  28. print("****** Minimum version: ", PIO_VERSION_MIN, " ******")
  29. print("****** Current Version: ", PIO_VERSION, " ******")
  30. print("****** ******")
  31. print("****** Update PlatformIO and try again. ******")
  32. print("**************************************************")
  33. print()
  34. exit(1)
  35. except SystemExit:
  36. exit(1)
  37. except:
  38. print("Can't detect PlatformIO Version")
  39. def blab(str,level=1):
  40. if verbose >= level:
  41. print("[deps] %s" % str)
  42. def add_to_feat_cnf(feature, flines):
  43. try:
  44. feat = FEATURE_CONFIG[feature]
  45. except:
  46. FEATURE_CONFIG[feature] = {}
  47. # Get a reference to the FEATURE_CONFIG under construction
  48. feat = FEATURE_CONFIG[feature]
  49. # Split up passed lines on commas or newlines and iterate.
  50. # Take care to convert Windows '\' paths to Unix-style '/'.
  51. # Add common options to the features config under construction.
  52. # For lib_deps replace a previous instance of the same library.
  53. atoms = re.sub(r',\s*', '\n', flines.replace('\\', '/')).strip().split('\n')
  54. for line in atoms:
  55. parts = line.split('=')
  56. name = parts.pop(0)
  57. if name in ['build_flags', 'extra_scripts', 'build_src_filter', 'lib_ignore']:
  58. feat[name] = '='.join(parts)
  59. blab("[%s] %s=%s" % (feature, name, feat[name]), 3)
  60. else:
  61. for dep in re.split(r',\s*', line):
  62. lib_name = re.sub(r'@([~^]|[<>]=?)?[\d.]+', '', dep.strip()).split('=').pop(0)
  63. lib_re = re.compile('(?!^' + lib_name + '\\b)')
  64. if not 'lib_deps' in feat: feat['lib_deps'] = {}
  65. feat['lib_deps'] = list(filter(lib_re.match, feat['lib_deps'])) + [dep]
  66. blab("[%s] lib_deps = %s" % (feature, dep), 3)
  67. def load_features():
  68. blab("========== Gather [features] entries...")
  69. for key in ProjectConfig().items('features'):
  70. feature = key[0].upper()
  71. if not feature in FEATURE_CONFIG:
  72. FEATURE_CONFIG[feature] = { 'lib_deps': [] }
  73. add_to_feat_cnf(feature, key[1])
  74. # Add options matching custom_marlin.MY_OPTION to the pile
  75. blab("========== Gather custom_marlin entries...")
  76. for n in env.GetProjectOptions():
  77. key = n[0]
  78. mat = re.match(r'custom_marlin\.(.+)', key)
  79. if mat:
  80. try:
  81. val = env.GetProjectOption(key)
  82. except:
  83. val = None
  84. if val:
  85. opt = mat[1].upper()
  86. blab("%s.custom_marlin.%s = '%s'" % ( env['PIOENV'], opt, val ), 2)
  87. add_to_feat_cnf(opt, val)
  88. def get_all_known_libs():
  89. known_libs = []
  90. for feature in FEATURE_CONFIG:
  91. feat = FEATURE_CONFIG[feature]
  92. if not 'lib_deps' in feat:
  93. continue
  94. for dep in feat['lib_deps']:
  95. known_libs.append(PackageSpec(dep).name)
  96. return known_libs
  97. def get_all_env_libs():
  98. env_libs = []
  99. lib_deps = env.GetProjectOption('lib_deps')
  100. for dep in lib_deps:
  101. env_libs.append(PackageSpec(dep).name)
  102. return env_libs
  103. def set_env_field(field, value):
  104. proj = env.GetProjectConfig()
  105. proj.set("env:" + env['PIOENV'], field, value)
  106. # All unused libs should be ignored so that if a library
  107. # exists in .pio/lib_deps it will not break compilation.
  108. def force_ignore_unused_libs():
  109. env_libs = get_all_env_libs()
  110. known_libs = get_all_known_libs()
  111. diff = (list(set(known_libs) - set(env_libs)))
  112. lib_ignore = env.GetProjectOption('lib_ignore') + diff
  113. blab("Ignore libraries: %s" % lib_ignore)
  114. set_env_field('lib_ignore', lib_ignore)
  115. def apply_features_config():
  116. load_features()
  117. blab("========== Apply enabled features...")
  118. build_filters = ' '.join(env.GetProjectOption('build_src_filter'))
  119. for feature in FEATURE_CONFIG:
  120. if not env.MarlinHas(feature):
  121. continue
  122. feat = FEATURE_CONFIG[feature]
  123. if 'lib_deps' in feat and len(feat['lib_deps']):
  124. blab("========== Adding lib_deps for %s... " % feature, 2)
  125. # feat to add
  126. deps_to_add = {}
  127. for dep in feat['lib_deps']:
  128. deps_to_add[PackageSpec(dep).name] = dep
  129. blab("==================== %s... " % dep, 2)
  130. # Does the env already have the dependency?
  131. deps = env.GetProjectOption('lib_deps')
  132. for dep in deps:
  133. name = PackageSpec(dep).name
  134. if name in deps_to_add:
  135. del deps_to_add[name]
  136. # Are there any libraries that should be ignored?
  137. lib_ignore = env.GetProjectOption('lib_ignore')
  138. for dep in deps:
  139. name = PackageSpec(dep).name
  140. if name in deps_to_add:
  141. del deps_to_add[name]
  142. # Is there anything left?
  143. if len(deps_to_add) > 0:
  144. # Only add the missing dependencies
  145. set_env_field('lib_deps', deps + list(deps_to_add.values()))
  146. if 'build_flags' in feat:
  147. f = feat['build_flags']
  148. blab("========== Adding build_flags for %s: %s" % (feature, f), 2)
  149. new_flags = env.GetProjectOption('build_flags') + [ f ]
  150. env.Replace(BUILD_FLAGS=new_flags)
  151. if 'extra_scripts' in feat:
  152. blab("Running extra_scripts for %s... " % feature, 2)
  153. env.SConscript(feat['extra_scripts'], exports="env")
  154. if 'build_src_filter' in feat:
  155. blab("========== Adding build_src_filter for %s... " % feature, 2)
  156. build_filters = build_filters + ' ' + feat['build_src_filter']
  157. # Just append the filter in the order that the build environment specifies.
  158. # Important here is the order of entries in the "features.ini" file.
  159. if 'lib_ignore' in feat:
  160. blab("========== Adding lib_ignore for %s... " % feature, 2)
  161. lib_ignore = env.GetProjectOption('lib_ignore') + [feat['lib_ignore']]
  162. set_env_field('lib_ignore', lib_ignore)
  163. build_src_filter = ""
  164. # Build the actual equivalent build_src_filter list based on the inclusions by the features.
  165. # PlatformIO doesn't do it this way, but maybe in the future....
  166. cur_srcs = set()
  167. # Remove the references to the same folder
  168. my_srcs = re.findall(r'([+-]<.*?>)', build_filters)
  169. for d in my_srcs:
  170. # Assume normalized relative paths
  171. plain = d[2:-1]
  172. if d[0] == '+':
  173. def addentry(fullpath, info=None):
  174. relp = os.path.relpath(fullpath, marlinbasedir)
  175. if srcfilepattern.match(relp):
  176. if info:
  177. blab("Added src file %s (%s)" % (relp, str(info)), 3)
  178. else:
  179. blab("Added src file %s " % relp, 3)
  180. cur_srcs.add(relp)
  181. # Special rule: If a direct folder is specified add all files within.
  182. fullplain = os.path.join(marlinbasedir, plain)
  183. if os.path.isdir(fullplain):
  184. blab("Directory content addition for %s " % plain, 3)
  185. gpattern = os.path.join(fullplain, "**")
  186. for fname in glob.glob(gpattern, recursive=True):
  187. addentry(fname, "dca")
  188. else:
  189. # Add all the things from the pattern by GLOB.
  190. def srepl(matchi):
  191. g0 = matchi.group(0)
  192. return r"**" + g0[1:]
  193. gpattern = re.sub(r'[*]($|[^*])', srepl, plain)
  194. gpattern = os.path.join(marlinbasedir, gpattern)
  195. for fname in glob.glob(gpattern, recursive=True):
  196. addentry(fname)
  197. else:
  198. # Special rule: If a direct folder is specified then remove all files within.
  199. def onremove(relp, info=None):
  200. if info:
  201. blab("Removed src file %s (%s)" % (relp, str(info)), 3)
  202. else:
  203. blab("Removed src file %s " % relp, 3)
  204. fullplain = os.path.join(marlinbasedir, plain)
  205. if os.path.isdir(fullplain):
  206. blab("Directory content removal for %s " % plain, 2)
  207. def filt(x):
  208. common = os.path.commonpath([plain, x])
  209. if not common == os.path.normpath(plain): return True
  210. onremove(x, "dcr")
  211. return False
  212. cur_srcs = set(filter(filt, cur_srcs))
  213. else:
  214. # Remove matching source entries.
  215. def filt(x):
  216. if not fnmatch.fnmatch(x, plain): return True
  217. onremove(x)
  218. return False
  219. cur_srcs = set(filter(filt, cur_srcs))
  220. # Transform the resulting set into a string.
  221. for x in cur_srcs:
  222. if build_src_filter != "": build_src_filter += ' '
  223. build_src_filter += "+<" + x + ">"
  224. # Update in PlatformIO
  225. set_env_field('build_src_filter', [build_src_filter])
  226. env.Replace(SRC_FILTER=build_src_filter)
  227. #blab("Final build_src_filter: " + build_src_filter, 3)
  228. #
  229. # Use the compiler to get a list of all enabled features
  230. #
  231. def load_marlin_features():
  232. if 'MARLIN_FEATURES' in env:
  233. return
  234. # Process defines
  235. from preprocessor import run_preprocessor
  236. define_list = run_preprocessor(env)
  237. marlin_features = {}
  238. for define in define_list:
  239. feature = define[8:].strip().decode().split(' ')
  240. feature, definition = feature[0], ' '.join(feature[1:])
  241. marlin_features[feature] = definition
  242. env['MARLIN_FEATURES'] = marlin_features
  243. #
  244. # Return True if a matching feature is enabled
  245. #
  246. def MarlinHas(env, feature):
  247. load_marlin_features()
  248. r = re.compile('^' + feature + '$', re.IGNORECASE)
  249. found = list(filter(r.match, env['MARLIN_FEATURES']))
  250. # Defines could still be 'false' or '0', so check
  251. some_on = False
  252. if len(found):
  253. for f in found:
  254. val = env['MARLIN_FEATURES'][f]
  255. if val in [ '', '1', 'true' ]:
  256. some_on = True
  257. elif val in env['MARLIN_FEATURES']:
  258. some_on = env.MarlinHas(val)
  259. #blab("%s is %s" % (feature, str(some_on)), 2)
  260. return some_on
  261. validate_pio()
  262. try:
  263. verbose = int(env.GetProjectOption('custom_verbose'))
  264. except:
  265. pass
  266. #
  267. # Add a method for other PIO scripts to query enabled features
  268. #
  269. env.AddMethod(MarlinHas)
  270. #
  271. # Add dependencies for enabled Marlin features
  272. #
  273. apply_features_config()
  274. force_ignore_unused_libs()
  275. #print(env.Dump())
  276. from signature import compute_build_signature
  277. compute_build_signature(env)