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

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