configuration.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #
  2. # configuration.py
  3. # Apply options from config.ini to the existing Configuration headers
  4. #
  5. import re, shutil, configparser
  6. from pathlib import Path
  7. verbose = 0
  8. def blab(str,level=1):
  9. if verbose >= level: print(f"[config] {str}")
  10. def config_path(cpath):
  11. return Path("Marlin", cpath, encoding='utf-8')
  12. # Apply a single name = on/off ; name = value ; etc.
  13. # TODO: Limit to the given (optional) configuration
  14. def apply_opt(name, val, conf=None):
  15. if name == "lcd": name, val = val, "on"
  16. # Create a regex to match the option and capture parts of the line
  17. # 1: Indentation
  18. # 2: Comment
  19. # 3: #define and whitespace
  20. # 4: Option name
  21. # 5: First space after name
  22. # 6: Remaining spaces between name and value
  23. # 7: Option value
  24. # 8: Whitespace after value
  25. # 9: End comment
  26. regex = re.compile(rf'^(\s*)(//\s*)?(#define\s+)({name}\b)(\s?)(\s*)(.*?)(\s*)(//.*)?$', re.IGNORECASE)
  27. # Find and enable and/or update all matches
  28. for file in ("Configuration.h", "Configuration_adv.h"):
  29. fullpath = config_path(file)
  30. lines = fullpath.read_text(encoding='utf-8').split('\n')
  31. found = False
  32. for i in range(len(lines)):
  33. line = lines[i]
  34. match = regex.match(line)
  35. if match and match[4].upper() == name.upper():
  36. found = True
  37. # For boolean options un/comment the define
  38. if val in ("on", "", None):
  39. newline = re.sub(r'^(\s*)//+\s*(#define)(\s{1,3})?(\s*)', r'\1\2 \4', line)
  40. elif val == "off":
  41. newline = re.sub(r'^(\s*)(#define)(\s{1,3})?(\s*)', r'\1//\2 \4', line)
  42. else:
  43. # For options with values, enable and set the value
  44. addsp = '' if match[5] else ' '
  45. newline = match[1] + match[3] + match[4] + match[5] + addsp + val + match[6]
  46. if match[9]:
  47. sp = match[8] if match[8] else ' '
  48. newline += sp + match[9]
  49. lines[i] = newline
  50. blab(f"Set {name} to {val}")
  51. # If the option was found, write the modified lines
  52. if found:
  53. fullpath.write_text('\n'.join(lines), encoding='utf-8')
  54. break
  55. # If the option didn't appear in either config file, add it
  56. if not found:
  57. # OFF options are added as disabled items so they appear
  58. # in config dumps. Useful for custom settings.
  59. prefix = ""
  60. if val == "off":
  61. prefix, val = "//", "" # Item doesn't appear in config dump
  62. #val = "false" # Item appears in config dump
  63. # Uppercase the option unless already mixed/uppercase
  64. added = name.upper() if name.islower() else name
  65. # Add the provided value after the name
  66. if val != "on" and val != "" and val is not None:
  67. added += " " + val
  68. # Prepend the new option after the first set of #define lines
  69. fullpath = config_path("Configuration.h")
  70. with fullpath.open(encoding='utf-8') as f:
  71. lines = f.readlines()
  72. linenum = 0
  73. gotdef = False
  74. for line in lines:
  75. isdef = line.startswith("#define")
  76. if not gotdef:
  77. gotdef = isdef
  78. elif not isdef:
  79. break
  80. linenum += 1
  81. lines.insert(linenum, f"{prefix}#define {added:30} // Added by config.ini\n")
  82. fullpath.write_text(''.join(lines), encoding='utf-8')
  83. # Fetch configuration files from GitHub given the path.
  84. # Return True if any files were fetched.
  85. def fetch_example(url):
  86. if url.endswith("/"): url = url[:-1]
  87. if not url.startswith('http'):
  88. brch = "bugfix-2.1.x"
  89. if '@' in url: url, brch = map(str.strip, url.split('@'))
  90. if url == 'examples/default': url = 'default'
  91. url = f"https://raw.githubusercontent.com/MarlinFirmware/Configurations/{brch}/config/{url}"
  92. url = url.replace("%", "%25").replace(" ", "%20")
  93. # Find a suitable fetch command
  94. if shutil.which("curl") is not None:
  95. fetch = "curl -L -s -S -f -o"
  96. elif shutil.which("wget") is not None:
  97. fetch = "wget -q -O"
  98. else:
  99. blab("Couldn't find curl or wget", -1)
  100. return False
  101. import os
  102. # Reset configurations to default
  103. os.system("git checkout HEAD Marlin/*.h")
  104. # Try to fetch the remote files
  105. gotfile = False
  106. for fn in ("Configuration.h", "Configuration_adv.h", "_Bootscreen.h", "_Statusscreen.h"):
  107. if os.system(f"{fetch} wgot {url}/{fn} >/dev/null 2>&1") == 0:
  108. shutil.move('wgot', config_path(fn))
  109. gotfile = True
  110. if Path('wgot').exists(): shutil.rmtree('wgot')
  111. return gotfile
  112. def section_items(cp, sectkey):
  113. return cp.items(sectkey) if sectkey in cp.sections() else []
  114. # Apply all items from a config section
  115. def apply_ini_by_name(cp, sect):
  116. iniok = True
  117. if sect in ('config:base', 'config:root'):
  118. iniok = False
  119. items = section_items(cp, 'config:base') + section_items(cp, 'config:root')
  120. else:
  121. items = section_items(cp, sect)
  122. for item in items:
  123. if iniok or not item[0].startswith('ini_'):
  124. apply_opt(item[0], item[1])
  125. # Apply all config sections from a parsed file
  126. def apply_all_sections(cp):
  127. for sect in cp.sections():
  128. if sect.startswith('config:'):
  129. apply_ini_by_name(cp, sect)
  130. # Apply certain config sections from a parsed file
  131. def apply_sections(cp, ckey='all'):
  132. blab(f"Apply section key: {ckey}")
  133. if ckey == 'all':
  134. apply_all_sections(cp)
  135. else:
  136. # Apply the base/root config.ini settings after external files are done
  137. if ckey in ('base', 'root'):
  138. apply_ini_by_name(cp, 'config:base')
  139. # Apply historically 'Configuration.h' settings everywhere
  140. if ckey == 'basic':
  141. apply_ini_by_name(cp, 'config:basic')
  142. # Apply historically Configuration_adv.h settings everywhere
  143. # (Some of which rely on defines in 'Conditionals_LCD.h')
  144. elif ckey in ('adv', 'advanced'):
  145. apply_ini_by_name(cp, 'config:advanced')
  146. # Apply a specific config:<name> section directly
  147. elif ckey.startswith('config:'):
  148. apply_ini_by_name(cp, ckey)
  149. # Apply settings from a top level config.ini
  150. def apply_config_ini(cp):
  151. blab("=" * 20 + " Gather 'config.ini' entries...")
  152. # Pre-scan for ini_use_config to get config_keys
  153. base_items = section_items(cp, 'config:base') + section_items(cp, 'config:root')
  154. config_keys = ['base']
  155. for ikey, ival in base_items:
  156. if ikey == 'ini_use_config':
  157. config_keys = map(str.strip, ival.split(','))
  158. # For each ini_use_config item perform an action
  159. for ckey in config_keys:
  160. addbase = False
  161. # For a key ending in .ini load and parse another .ini file
  162. if ckey.endswith('.ini'):
  163. sect = 'base'
  164. if '@' in ckey: sect, ckey = map(str.strip, ckey.split('@'))
  165. cp2 = configparser.ConfigParser()
  166. cp2.read(config_path(ckey))
  167. apply_sections(cp2, sect)
  168. ckey = 'base';
  169. # (Allow 'example/' as a shortcut for 'examples/')
  170. elif ckey.startswith('example/'):
  171. ckey = 'examples' + ckey[7:]
  172. # For 'examples/<path>' fetch an example set from GitHub.
  173. # For https?:// do a direct fetch of the URL.
  174. if ckey.startswith('examples/') or ckey.startswith('http'):
  175. fetch_example(ckey)
  176. ckey = 'base'
  177. if ckey == 'all':
  178. apply_sections(cp)
  179. else:
  180. # Apply keyed sections after external files are done
  181. apply_sections(cp, 'config:' + ckey)
  182. if __name__ == "__main__":
  183. #
  184. # From command line use the given file name
  185. #
  186. import sys
  187. args = sys.argv[1:]
  188. if len(args) > 0:
  189. if args[0].endswith('.ini'):
  190. ini_file = args[0]
  191. else:
  192. print("Usage: %s <.ini file>" % sys.argv[0])
  193. else:
  194. ini_file = config_path('config.ini')
  195. if ini_file:
  196. user_ini = configparser.ConfigParser()
  197. user_ini.read(ini_file)
  198. apply_config_ini(user_ini)
  199. else:
  200. #
  201. # From within PlatformIO use the loaded INI file
  202. #
  203. import pioutil
  204. if pioutil.is_pio_build():
  205. Import("env")
  206. try:
  207. verbose = int(env.GetProjectOption('custom_verbose'))
  208. except:
  209. pass
  210. from platformio.project.config import ProjectConfig
  211. apply_config_ini(ProjectConfig())