My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

common-dependencies.py 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. #
  2. # common-dependencies.py
  3. # Convenience script to check dependencies and add libs and sources for Marlin Enabled Features
  4. #
  5. import subprocess
  6. import os
  7. import re
  8. try:
  9. import configparser
  10. except ImportError:
  11. import ConfigParser as configparser
  12. try:
  13. # PIO < 4.4
  14. from platformio.managers.package import PackageManager
  15. except ImportError:
  16. # PIO >= 4.4
  17. from platformio.package.meta import PackageSpec as PackageManager
  18. PIO_VERSION_MIN = (5, 0, 3)
  19. try:
  20. from platformio import VERSION as PIO_VERSION
  21. weights = (1000, 100, 1)
  22. version_min = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION_MIN)])
  23. version_cur = sum([x[0] * float(re.sub(r'[^0-9]', '.', str(x[1]))) for x in zip(weights, PIO_VERSION)])
  24. if version_cur < version_min:
  25. print()
  26. print("**************************************************")
  27. print("****** An update to PlatformIO is ******")
  28. print("****** required to build Marlin Firmware. ******")
  29. print("****** ******")
  30. print("****** Minimum version: ", PIO_VERSION_MIN, " ******")
  31. print("****** Current Version: ", PIO_VERSION, " ******")
  32. print("****** ******")
  33. print("****** Update PlatformIO and try again. ******")
  34. print("**************************************************")
  35. print()
  36. exit(1)
  37. except SystemExit:
  38. exit(1)
  39. except:
  40. print("Can't detect PlatformIO Version")
  41. Import("env")
  42. #print(env.Dump())
  43. try:
  44. verbose = int(env.GetProjectOption('custom_verbose'))
  45. except:
  46. verbose = 0
  47. def blab(str):
  48. if verbose:
  49. print(str)
  50. def parse_pkg_uri(spec):
  51. if PackageManager.__name__ == 'PackageSpec':
  52. return PackageManager(spec).name
  53. else:
  54. name, _, _ = PackageManager.parse_pkg_uri(spec)
  55. return name
  56. FEATURE_CONFIG = {}
  57. def add_to_feat_cnf(feature, flines):
  58. try:
  59. feat = FEATURE_CONFIG[feature]
  60. except:
  61. FEATURE_CONFIG[feature] = {}
  62. feat = FEATURE_CONFIG[feature]
  63. atoms = re.sub(',\\s*', '\n', flines).strip().split('\n')
  64. for dep in atoms:
  65. parts = dep.split('=')
  66. name = parts.pop(0)
  67. rest = '='.join(parts)
  68. if name in ['extra_scripts', 'src_filter', 'lib_ignore']:
  69. feat[name] = rest
  70. else:
  71. feat['lib_deps'] += [dep]
  72. def load_config():
  73. config = configparser.ConfigParser()
  74. config.read("platformio.ini")
  75. items = config.items('features')
  76. for key in items:
  77. feature = key[0].upper()
  78. if not feature in FEATURE_CONFIG:
  79. FEATURE_CONFIG[feature] = { 'lib_deps': [] }
  80. add_to_feat_cnf(feature, key[1])
  81. # Add options matching custom_marlin.MY_OPTION to the pile
  82. all_opts = env.GetProjectOptions()
  83. for n in all_opts:
  84. mat = re.match(r'custom_marlin\.(.+)', n[0])
  85. if mat:
  86. try:
  87. val = env.GetProjectOption(n[0])
  88. except:
  89. val = None
  90. if val:
  91. add_to_feat_cnf(mat.group(1).upper(), val)
  92. def get_all_known_libs():
  93. known_libs = []
  94. for feature in FEATURE_CONFIG:
  95. feat = FEATURE_CONFIG[feature]
  96. if not 'lib_deps' in feat:
  97. continue
  98. for dep in feat['lib_deps']:
  99. name = parse_pkg_uri(dep)
  100. known_libs.append(name)
  101. return known_libs
  102. def get_all_env_libs():
  103. env_libs = []
  104. lib_deps = env.GetProjectOption('lib_deps')
  105. for dep in lib_deps:
  106. name = parse_pkg_uri(dep)
  107. env_libs.append(name)
  108. return env_libs
  109. def set_env_field(field, value):
  110. proj = env.GetProjectConfig()
  111. proj.set("env:" + env['PIOENV'], field, value)
  112. # All unused libs should be ignored so that if a library
  113. # exists in .pio/lib_deps it will not break compilation.
  114. def force_ignore_unused_libs():
  115. env_libs = get_all_env_libs()
  116. known_libs = get_all_known_libs()
  117. diff = (list(set(known_libs) - set(env_libs)))
  118. lib_ignore = env.GetProjectOption('lib_ignore') + diff
  119. if verbose:
  120. print("Ignore libraries:", lib_ignore)
  121. set_env_field('lib_ignore', lib_ignore)
  122. def apply_features_config():
  123. load_config()
  124. for feature in FEATURE_CONFIG:
  125. if not env.MarlinFeatureIsEnabled(feature):
  126. continue
  127. feat = FEATURE_CONFIG[feature]
  128. if 'lib_deps' in feat and len(feat['lib_deps']):
  129. blab("Adding lib_deps for %s... " % feature)
  130. # feat to add
  131. deps_to_add = {}
  132. for dep in feat['lib_deps']:
  133. name = parse_pkg_uri(dep)
  134. deps_to_add[name] = dep
  135. # Does the env already have the dependency?
  136. deps = env.GetProjectOption('lib_deps')
  137. for dep in deps:
  138. name = parse_pkg_uri(dep)
  139. if name in deps_to_add:
  140. del deps_to_add[name]
  141. # Are there any libraries that should be ignored?
  142. lib_ignore = env.GetProjectOption('lib_ignore')
  143. for dep in deps:
  144. name = parse_pkg_uri(dep)
  145. if name in deps_to_add:
  146. del deps_to_add[name]
  147. # Is there anything left?
  148. if len(deps_to_add) > 0:
  149. # Only add the missing dependencies
  150. set_env_field('lib_deps', deps + list(deps_to_add.values()))
  151. if 'extra_scripts' in feat:
  152. blab("Running extra_scripts for %s... " % feature)
  153. env.SConscript(feat['extra_scripts'], exports="env")
  154. if 'src_filter' in feat:
  155. blab("Adding src_filter for %s... " % feature)
  156. src_filter = ' '.join(env.GetProjectOption('src_filter'))
  157. # first we need to remove the references to the same folder
  158. my_srcs = re.findall( r'[+-](<.*?>)', feat['src_filter'])
  159. cur_srcs = re.findall( r'[+-](<.*?>)', src_filter)
  160. for d in my_srcs:
  161. if d in cur_srcs:
  162. src_filter = re.sub(r'[+-]' + d, '', src_filter)
  163. src_filter = feat['src_filter'] + ' ' + src_filter
  164. set_env_field('src_filter', [src_filter])
  165. env.Replace(SRC_FILTER=src_filter)
  166. if 'lib_ignore' in feat:
  167. blab("Adding lib_ignore for %s... " % feature)
  168. lib_ignore = env.GetProjectOption('lib_ignore') + [feat['lib_ignore']]
  169. set_env_field('lib_ignore', lib_ignore)
  170. #
  171. # Find a compiler, considering the OS
  172. #
  173. ENV_BUILD_PATH = os.path.join(env.Dictionary('PROJECT_BUILD_DIR'), env['PIOENV'])
  174. GCC_PATH_CACHE = os.path.join(ENV_BUILD_PATH, ".gcc_path")
  175. def search_compiler():
  176. try:
  177. filepath = env.GetProjectOption('custom_gcc')
  178. blab('Getting compiler from env')
  179. return filepath
  180. except:
  181. pass
  182. if os.path.exists(GCC_PATH_CACHE):
  183. blab('Getting g++ path from cache')
  184. with open(GCC_PATH_CACHE, 'r') as f:
  185. return f.read()
  186. # Find the current platform compiler by searching the $PATH
  187. # which will be in a platformio toolchain bin folder
  188. path_regex = re.escape(env['PROJECT_PACKAGES_DIR'])
  189. gcc = "g++"
  190. if env['PLATFORM'] == 'win32':
  191. path_separator = ';'
  192. path_regex += r'.*\\bin'
  193. gcc += ".exe"
  194. else:
  195. path_separator = ':'
  196. path_regex += r'/.+/bin'
  197. # Search for the compiler
  198. for pathdir in env['ENV']['PATH'].split(path_separator):
  199. if not re.search(path_regex, pathdir, re.IGNORECASE):
  200. continue
  201. for filepath in os.listdir(pathdir):
  202. if not filepath.endswith(gcc):
  203. continue
  204. # Use entire path to not rely on env PATH
  205. filepath = os.path.sep.join([pathdir, filepath])
  206. # Cache the g++ path to no search always
  207. if os.path.exists(ENV_BUILD_PATH):
  208. blab('Caching g++ for current env')
  209. with open(GCC_PATH_CACHE, 'w+') as f:
  210. f.write(filepath)
  211. return filepath
  212. filepath = env.get('CXX')
  213. blab("Couldn't find a compiler! Fallback to %s" % filepath)
  214. return filepath
  215. #
  216. # Use the compiler to get a list of all enabled features
  217. #
  218. def load_marlin_features():
  219. if 'MARLIN_FEATURES' in env:
  220. return
  221. # Process defines
  222. build_flags = env.get('BUILD_FLAGS')
  223. build_flags = env.ParseFlagsExtended(build_flags)
  224. cxx = search_compiler()
  225. cmd = ['"' + cxx + '"']
  226. # Build flags from board.json
  227. #if 'BOARD' in env:
  228. # cmd += [env.BoardConfig().get("build.extra_flags")]
  229. for s in build_flags['CPPDEFINES']:
  230. if isinstance(s, tuple):
  231. cmd += ['-D' + s[0] + '=' + str(s[1])]
  232. else:
  233. cmd += ['-D' + s]
  234. cmd += ['-D__MARLIN_DEPS__ -w -dM -E -x c++ buildroot/share/PlatformIO/scripts/common-dependencies.h']
  235. cmd = ' '.join(cmd)
  236. blab(cmd)
  237. define_list = subprocess.check_output(cmd, shell=True).splitlines()
  238. marlin_features = {}
  239. for define in define_list:
  240. feature = define[8:].strip().decode().split(' ')
  241. feature, definition = feature[0], ' '.join(feature[1:])
  242. marlin_features[feature] = definition
  243. env['MARLIN_FEATURES'] = marlin_features
  244. #
  245. # Return True if a matching feature is enabled
  246. #
  247. def MarlinFeatureIsEnabled(env, feature):
  248. load_marlin_features()
  249. r = re.compile('^' + feature + '$')
  250. found = list(filter(r.match, env['MARLIN_FEATURES']))
  251. # Defines could still be 'false' or '0', so check
  252. some_on = False
  253. if len(found):
  254. for f in found:
  255. val = env['MARLIN_FEATURES'][f]
  256. if val in [ '', '1', 'true' ]:
  257. some_on = True
  258. elif val in env['MARLIN_FEATURES']:
  259. some_on = env.MarlinFeatureIsEnabled(val)
  260. return some_on
  261. #
  262. # Add a method for other PIO scripts to query enabled features
  263. #
  264. env.AddMethod(MarlinFeatureIsEnabled)
  265. #
  266. # Add dependencies for enabled Marlin features
  267. #
  268. apply_features_config()
  269. force_ignore_unused_libs()