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 7.5KB

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