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.4KB

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