moveconfig.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # Author: Masahiro Yamada <yamada.masahiro@socionext.com>
  5. #
  6. """
  7. Move config options from headers to defconfig files.
  8. Since Kconfig was introduced to U-Boot, we have worked on moving
  9. config options from headers to Kconfig (defconfig).
  10. This tool intends to help this tremendous work.
  11. Usage
  12. -----
  13. First, you must edit the Kconfig to add the menu entries for the configs
  14. you are moving.
  15. And then run this tool giving CONFIG names you want to move.
  16. For example, if you want to move CONFIG_CMD_USB and CONFIG_SYS_TEXT_BASE,
  17. simply type as follows:
  18. $ tools/moveconfig.py CONFIG_CMD_USB CONFIG_SYS_TEXT_BASE
  19. The tool walks through all the defconfig files and move the given CONFIGs.
  20. The log is also displayed on the terminal.
  21. The log is printed for each defconfig as follows:
  22. <defconfig_name>
  23. <action1>
  24. <action2>
  25. <action3>
  26. ...
  27. <defconfig_name> is the name of the defconfig.
  28. <action*> shows what the tool did for that defconfig.
  29. It looks like one of the following:
  30. - Move 'CONFIG_... '
  31. This config option was moved to the defconfig
  32. - CONFIG_... is not defined in Kconfig. Do nothing.
  33. The entry for this CONFIG was not found in Kconfig. The option is not
  34. defined in the config header, either. So, this case can be just skipped.
  35. - CONFIG_... is not defined in Kconfig (suspicious). Do nothing.
  36. This option is defined in the config header, but its entry was not found
  37. in Kconfig.
  38. There are two common cases:
  39. - You forgot to create an entry for the CONFIG before running
  40. this tool, or made a typo in a CONFIG passed to this tool.
  41. - The entry was hidden due to unmet 'depends on'.
  42. The tool does not know if the result is reasonable, so please check it
  43. manually.
  44. - 'CONFIG_...' is the same as the define in Kconfig. Do nothing.
  45. The define in the config header matched the one in Kconfig.
  46. We do not need to touch it.
  47. - Compiler is missing. Do nothing.
  48. The compiler specified for this architecture was not found
  49. in your PATH environment.
  50. (If -e option is passed, the tool exits immediately.)
  51. - Failed to process.
  52. An error occurred during processing this defconfig. Skipped.
  53. (If -e option is passed, the tool exits immediately on error.)
  54. Finally, you will be asked, Clean up headers? [y/n]:
  55. If you say 'y' here, the unnecessary config defines are removed
  56. from the config headers (include/configs/*.h).
  57. It just uses the regex method, so you should not rely on it.
  58. Just in case, please do 'git diff' to see what happened.
  59. How does it work?
  60. -----------------
  61. This tool runs configuration and builds include/autoconf.mk for every
  62. defconfig. The config options defined in Kconfig appear in the .config
  63. file (unless they are hidden because of unmet dependency.)
  64. On the other hand, the config options defined by board headers are seen
  65. in include/autoconf.mk. The tool looks for the specified options in both
  66. of them to decide the appropriate action for the options. If the given
  67. config option is found in the .config, but its value does not match the
  68. one from the board header, the config option in the .config is replaced
  69. with the define in the board header. Then, the .config is synced by
  70. "make savedefconfig" and the defconfig is updated with it.
  71. For faster processing, this tool handles multi-threading. It creates
  72. separate build directories where the out-of-tree build is run. The
  73. temporary build directories are automatically created and deleted as
  74. needed. The number of threads are chosen based on the number of the CPU
  75. cores of your system although you can change it via -j (--jobs) option.
  76. Toolchains
  77. ----------
  78. Appropriate toolchain are necessary to generate include/autoconf.mk
  79. for all the architectures supported by U-Boot. Most of them are available
  80. at the kernel.org site, some are not provided by kernel.org. This tool uses
  81. the same tools as buildman, so see that tool for setup (e.g. --fetch-arch).
  82. Tips and trips
  83. --------------
  84. To sync only X86 defconfigs:
  85. ./tools/moveconfig.py -s -d <(grep -l X86 configs/*)
  86. or:
  87. grep -l X86 configs/* | ./tools/moveconfig.py -s -d -
  88. To process CONFIG_CMD_FPGAD only for a subset of configs based on path match:
  89. ls configs/{hrcon*,iocon*,strider*} | \
  90. ./tools/moveconfig.py -Cy CONFIG_CMD_FPGAD -d -
  91. Finding implied CONFIGs
  92. -----------------------
  93. Some CONFIG options can be implied by others and this can help to reduce
  94. the size of the defconfig files. For example, CONFIG_X86 implies
  95. CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
  96. all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
  97. each of the x86 defconfig files.
  98. This tool can help find such configs. To use it, first build a database:
  99. ./tools/moveconfig.py -b
  100. Then try to query it:
  101. ./tools/moveconfig.py -i CONFIG_CMD_IRQ
  102. CONFIG_CMD_IRQ found in 311/2384 defconfigs
  103. 44 : CONFIG_SYS_FSL_ERRATUM_IFC_A002769
  104. 41 : CONFIG_SYS_FSL_ERRATUM_A007075
  105. 31 : CONFIG_SYS_FSL_DDR_VER_44
  106. 28 : CONFIG_ARCH_P1010
  107. 28 : CONFIG_SYS_FSL_ERRATUM_P1010_A003549
  108. 28 : CONFIG_SYS_FSL_ERRATUM_SEC_A003571
  109. 28 : CONFIG_SYS_FSL_ERRATUM_IFC_A003399
  110. 25 : CONFIG_SYS_FSL_ERRATUM_A008044
  111. 22 : CONFIG_ARCH_P1020
  112. 21 : CONFIG_SYS_FSL_DDR_VER_46
  113. 20 : CONFIG_MAX_PIRQ_LINKS
  114. 20 : CONFIG_HPET_ADDRESS
  115. 20 : CONFIG_X86
  116. 20 : CONFIG_PCIE_ECAM_SIZE
  117. 20 : CONFIG_IRQ_SLOT_COUNT
  118. 20 : CONFIG_I8259_PIC
  119. 20 : CONFIG_CPU_ADDR_BITS
  120. 20 : CONFIG_RAMBASE
  121. 20 : CONFIG_SYS_FSL_ERRATUM_A005871
  122. 20 : CONFIG_PCIE_ECAM_BASE
  123. 20 : CONFIG_X86_TSC_TIMER
  124. 20 : CONFIG_I8254_TIMER
  125. 20 : CONFIG_CMD_GETTIME
  126. 19 : CONFIG_SYS_FSL_ERRATUM_A005812
  127. 18 : CONFIG_X86_RUN_32BIT
  128. 17 : CONFIG_CMD_CHIP_CONFIG
  129. ...
  130. This shows a list of config options which might imply CONFIG_CMD_EEPROM along
  131. with how many defconfigs they cover. From this you can see that CONFIG_X86
  132. implies CONFIG_CMD_EEPROM. Therefore, instead of adding CONFIG_CMD_EEPROM to
  133. the defconfig of every x86 board, you could add a single imply line to the
  134. Kconfig file:
  135. config X86
  136. bool "x86 architecture"
  137. ...
  138. imply CMD_EEPROM
  139. That will cover 20 defconfigs. Many of the options listed are not suitable as
  140. they are not related. E.g. it would be odd for CONFIG_CMD_GETTIME to imply
  141. CMD_EEPROM.
  142. Using this search you can reduce the size of moveconfig patches.
  143. You can automatically add 'imply' statements in the Kconfig with the -a
  144. option:
  145. ./tools/moveconfig.py -s -i CONFIG_SCSI \
  146. -a CONFIG_ARCH_LS1021A,CONFIG_ARCH_LS1043A
  147. This will add 'imply SCSI' to the two CONFIG options mentioned, assuming that
  148. the database indicates that they do actually imply CONFIG_SCSI and do not
  149. already have an 'imply SCSI'.
  150. The output shows where the imply is added:
  151. 18 : CONFIG_ARCH_LS1021A arch/arm/cpu/armv7/ls102xa/Kconfig:1
  152. 13 : CONFIG_ARCH_LS1043A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:11
  153. 12 : CONFIG_ARCH_LS1046A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:31
  154. The first number is the number of boards which can avoid having a special
  155. CONFIG_SCSI option in their defconfig file if this 'imply' is added.
  156. The location at the right is the Kconfig file and line number where the config
  157. appears. For example, adding 'imply CONFIG_SCSI' to the 'config ARCH_LS1021A'
  158. in arch/arm/cpu/armv7/ls102xa/Kconfig at line 1 will help 18 boards to reduce
  159. the size of their defconfig files.
  160. If you want to add an 'imply' to every imply config in the list, you can use
  161. ./tools/moveconfig.py -s -i CONFIG_SCSI -a all
  162. To control which ones are displayed, use -I <list> where list is a list of
  163. options (use '-I help' to see possible options and their meaning).
  164. To skip showing you options that already have an 'imply' attached, use -A.
  165. When you have finished adding 'imply' options you can regenerate the
  166. defconfig files for affected boards with something like:
  167. git show --stat | ./tools/moveconfig.py -s -d -
  168. This will regenerate only those defconfigs changed in the current commit.
  169. If you start with (say) 100 defconfigs being changed in the commit, and add
  170. a few 'imply' options as above, then regenerate, hopefully you can reduce the
  171. number of defconfigs changed in the commit.
  172. Available options
  173. -----------------
  174. -c, --color
  175. Surround each portion of the log with escape sequences to display it
  176. in color on the terminal.
  177. -C, --commit
  178. Create a git commit with the changes when the operation is complete. A
  179. standard commit message is used which may need to be edited.
  180. -d, --defconfigs
  181. Specify a file containing a list of defconfigs to move. The defconfig
  182. files can be given with shell-style wildcards. Use '-' to read from stdin.
  183. -n, --dry-run
  184. Perform a trial run that does not make any changes. It is useful to
  185. see what is going to happen before one actually runs it.
  186. -e, --exit-on-error
  187. Exit immediately if Make exits with a non-zero status while processing
  188. a defconfig file.
  189. -s, --force-sync
  190. Do "make savedefconfig" forcibly for all the defconfig files.
  191. If not specified, "make savedefconfig" only occurs for cases
  192. where at least one CONFIG was moved.
  193. -S, --spl
  194. Look for moved config options in spl/include/autoconf.mk instead of
  195. include/autoconf.mk. This is useful for moving options for SPL build
  196. because SPL related options (mostly prefixed with CONFIG_SPL_) are
  197. sometimes blocked by CONFIG_SPL_BUILD ifdef conditionals.
  198. -H, --headers-only
  199. Only cleanup the headers; skip the defconfig processing
  200. -j, --jobs
  201. Specify the number of threads to run simultaneously. If not specified,
  202. the number of threads is the same as the number of CPU cores.
  203. -r, --git-ref
  204. Specify the git ref to clone for building the autoconf.mk. If unspecified
  205. use the CWD. This is useful for when changes to the Kconfig affect the
  206. default values and you want to capture the state of the defconfig from
  207. before that change was in effect. If in doubt, specify a ref pre-Kconfig
  208. changes (use HEAD if Kconfig changes are not committed). Worst case it will
  209. take a bit longer to run, but will always do the right thing.
  210. -v, --verbose
  211. Show any build errors as boards are built
  212. -y, --yes
  213. Instead of prompting, automatically go ahead with all operations. This
  214. includes cleaning up headers, CONFIG_SYS_EXTRA_OPTIONS, the config whitelist
  215. and the README.
  216. To see the complete list of supported options, run
  217. $ tools/moveconfig.py -h
  218. """
  219. import collections
  220. import copy
  221. import difflib
  222. import filecmp
  223. import fnmatch
  224. import glob
  225. import multiprocessing
  226. import optparse
  227. import os
  228. import queue
  229. import re
  230. import shutil
  231. import subprocess
  232. import sys
  233. import tempfile
  234. import threading
  235. import time
  236. sys.path.append(os.path.join(os.path.dirname(__file__), 'buildman'))
  237. sys.path.append(os.path.join(os.path.dirname(__file__), 'patman'))
  238. import bsettings
  239. import kconfiglib
  240. import toolchain
  241. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  242. SLEEP_TIME=0.03
  243. STATE_IDLE = 0
  244. STATE_DEFCONFIG = 1
  245. STATE_AUTOCONF = 2
  246. STATE_SAVEDEFCONFIG = 3
  247. ACTION_MOVE = 0
  248. ACTION_NO_ENTRY = 1
  249. ACTION_NO_ENTRY_WARN = 2
  250. ACTION_NO_CHANGE = 3
  251. COLOR_BLACK = '0;30'
  252. COLOR_RED = '0;31'
  253. COLOR_GREEN = '0;32'
  254. COLOR_BROWN = '0;33'
  255. COLOR_BLUE = '0;34'
  256. COLOR_PURPLE = '0;35'
  257. COLOR_CYAN = '0;36'
  258. COLOR_LIGHT_GRAY = '0;37'
  259. COLOR_DARK_GRAY = '1;30'
  260. COLOR_LIGHT_RED = '1;31'
  261. COLOR_LIGHT_GREEN = '1;32'
  262. COLOR_YELLOW = '1;33'
  263. COLOR_LIGHT_BLUE = '1;34'
  264. COLOR_LIGHT_PURPLE = '1;35'
  265. COLOR_LIGHT_CYAN = '1;36'
  266. COLOR_WHITE = '1;37'
  267. AUTO_CONF_PATH = 'include/config/auto.conf'
  268. CONFIG_DATABASE = 'moveconfig.db'
  269. CONFIG_LEN = len('CONFIG_')
  270. SIZES = {
  271. "SZ_1": 0x00000001, "SZ_2": 0x00000002,
  272. "SZ_4": 0x00000004, "SZ_8": 0x00000008,
  273. "SZ_16": 0x00000010, "SZ_32": 0x00000020,
  274. "SZ_64": 0x00000040, "SZ_128": 0x00000080,
  275. "SZ_256": 0x00000100, "SZ_512": 0x00000200,
  276. "SZ_1K": 0x00000400, "SZ_2K": 0x00000800,
  277. "SZ_4K": 0x00001000, "SZ_8K": 0x00002000,
  278. "SZ_16K": 0x00004000, "SZ_32K": 0x00008000,
  279. "SZ_64K": 0x00010000, "SZ_128K": 0x00020000,
  280. "SZ_256K": 0x00040000, "SZ_512K": 0x00080000,
  281. "SZ_1M": 0x00100000, "SZ_2M": 0x00200000,
  282. "SZ_4M": 0x00400000, "SZ_8M": 0x00800000,
  283. "SZ_16M": 0x01000000, "SZ_32M": 0x02000000,
  284. "SZ_64M": 0x04000000, "SZ_128M": 0x08000000,
  285. "SZ_256M": 0x10000000, "SZ_512M": 0x20000000,
  286. "SZ_1G": 0x40000000, "SZ_2G": 0x80000000,
  287. "SZ_4G": 0x100000000
  288. }
  289. ### helper functions ###
  290. def get_devnull():
  291. """Get the file object of '/dev/null' device."""
  292. try:
  293. devnull = subprocess.DEVNULL # py3k
  294. except AttributeError:
  295. devnull = open(os.devnull, 'wb')
  296. return devnull
  297. def check_top_directory():
  298. """Exit if we are not at the top of source directory."""
  299. for f in ('README', 'Licenses'):
  300. if not os.path.exists(f):
  301. sys.exit('Please run at the top of source directory.')
  302. def check_clean_directory():
  303. """Exit if the source tree is not clean."""
  304. for f in ('.config', 'include/config'):
  305. if os.path.exists(f):
  306. sys.exit("source tree is not clean, please run 'make mrproper'")
  307. def get_make_cmd():
  308. """Get the command name of GNU Make.
  309. U-Boot needs GNU Make for building, but the command name is not
  310. necessarily "make". (for example, "gmake" on FreeBSD).
  311. Returns the most appropriate command name on your system.
  312. """
  313. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  314. ret = process.communicate()
  315. if process.returncode:
  316. sys.exit('GNU Make not found')
  317. return ret[0].rstrip()
  318. def get_matched_defconfig(line):
  319. """Get the defconfig files that match a pattern
  320. Args:
  321. line: Path or filename to match, e.g. 'configs/snow_defconfig' or
  322. 'k2*_defconfig'. If no directory is provided, 'configs/' is
  323. prepended
  324. Returns:
  325. a list of matching defconfig files
  326. """
  327. dirname = os.path.dirname(line)
  328. if dirname:
  329. pattern = line
  330. else:
  331. pattern = os.path.join('configs', line)
  332. return glob.glob(pattern) + glob.glob(pattern + '_defconfig')
  333. def get_matched_defconfigs(defconfigs_file):
  334. """Get all the defconfig files that match the patterns in a file.
  335. Args:
  336. defconfigs_file: File containing a list of defconfigs to process, or
  337. '-' to read the list from stdin
  338. Returns:
  339. A list of paths to defconfig files, with no duplicates
  340. """
  341. defconfigs = []
  342. if defconfigs_file == '-':
  343. fd = sys.stdin
  344. defconfigs_file = 'stdin'
  345. else:
  346. fd = open(defconfigs_file)
  347. for i, line in enumerate(fd):
  348. line = line.strip()
  349. if not line:
  350. continue # skip blank lines silently
  351. if ' ' in line:
  352. line = line.split(' ')[0] # handle 'git log' input
  353. matched = get_matched_defconfig(line)
  354. if not matched:
  355. print("warning: %s:%d: no defconfig matched '%s'" % \
  356. (defconfigs_file, i + 1, line), file=sys.stderr)
  357. defconfigs += matched
  358. # use set() to drop multiple matching
  359. return [ defconfig[len('configs') + 1:] for defconfig in set(defconfigs) ]
  360. def get_all_defconfigs():
  361. """Get all the defconfig files under the configs/ directory."""
  362. defconfigs = []
  363. for (dirpath, dirnames, filenames) in os.walk('configs'):
  364. dirpath = dirpath[len('configs') + 1:]
  365. for filename in fnmatch.filter(filenames, '*_defconfig'):
  366. defconfigs.append(os.path.join(dirpath, filename))
  367. return defconfigs
  368. def color_text(color_enabled, color, string):
  369. """Return colored string."""
  370. if color_enabled:
  371. # LF should not be surrounded by the escape sequence.
  372. # Otherwise, additional whitespace or line-feed might be printed.
  373. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
  374. for s in string.split('\n') ])
  375. else:
  376. return string
  377. def show_diff(a, b, file_path, color_enabled):
  378. """Show unidified diff.
  379. Arguments:
  380. a: A list of lines (before)
  381. b: A list of lines (after)
  382. file_path: Path to the file
  383. color_enabled: Display the diff in color
  384. """
  385. diff = difflib.unified_diff(a, b,
  386. fromfile=os.path.join('a', file_path),
  387. tofile=os.path.join('b', file_path))
  388. for line in diff:
  389. if line[0] == '-' and line[1] != '-':
  390. print(color_text(color_enabled, COLOR_RED, line), end=' ')
  391. elif line[0] == '+' and line[1] != '+':
  392. print(color_text(color_enabled, COLOR_GREEN, line), end=' ')
  393. else:
  394. print(line, end=' ')
  395. def extend_matched_lines(lines, matched, pre_patterns, post_patterns, extend_pre,
  396. extend_post):
  397. """Extend matched lines if desired patterns are found before/after already
  398. matched lines.
  399. Arguments:
  400. lines: A list of lines handled.
  401. matched: A list of line numbers that have been already matched.
  402. (will be updated by this function)
  403. pre_patterns: A list of regular expression that should be matched as
  404. preamble.
  405. post_patterns: A list of regular expression that should be matched as
  406. postamble.
  407. extend_pre: Add the line number of matched preamble to the matched list.
  408. extend_post: Add the line number of matched postamble to the matched list.
  409. """
  410. extended_matched = []
  411. j = matched[0]
  412. for i in matched:
  413. if i == 0 or i < j:
  414. continue
  415. j = i
  416. while j in matched:
  417. j += 1
  418. if j >= len(lines):
  419. break
  420. for p in pre_patterns:
  421. if p.search(lines[i - 1]):
  422. break
  423. else:
  424. # not matched
  425. continue
  426. for p in post_patterns:
  427. if p.search(lines[j]):
  428. break
  429. else:
  430. # not matched
  431. continue
  432. if extend_pre:
  433. extended_matched.append(i - 1)
  434. if extend_post:
  435. extended_matched.append(j)
  436. matched += extended_matched
  437. matched.sort()
  438. def confirm(options, prompt):
  439. if not options.yes:
  440. while True:
  441. choice = input('{} [y/n]: '.format(prompt))
  442. choice = choice.lower()
  443. print(choice)
  444. if choice == 'y' or choice == 'n':
  445. break
  446. if choice == 'n':
  447. return False
  448. return True
  449. def cleanup_empty_blocks(header_path, options):
  450. """Clean up empty conditional blocks
  451. Arguments:
  452. header_path: path to the cleaned file.
  453. options: option flags.
  454. """
  455. pattern = re.compile(r'^\s*#\s*if.*$\n^\s*#\s*endif.*$\n*', flags=re.M)
  456. with open(header_path) as f:
  457. data = f.read()
  458. new_data = pattern.sub('\n', data)
  459. show_diff(data.splitlines(True), new_data.splitlines(True), header_path,
  460. options.color)
  461. if options.dry_run:
  462. return
  463. with open(header_path, 'w') as f:
  464. f.write(new_data)
  465. def cleanup_one_header(header_path, patterns, options):
  466. """Clean regex-matched lines away from a file.
  467. Arguments:
  468. header_path: path to the cleaned file.
  469. patterns: list of regex patterns. Any lines matching to these
  470. patterns are deleted.
  471. options: option flags.
  472. """
  473. with open(header_path) as f:
  474. lines = f.readlines()
  475. matched = []
  476. for i, line in enumerate(lines):
  477. if i - 1 in matched and lines[i - 1][-2:] == '\\\n':
  478. matched.append(i)
  479. continue
  480. for pattern in patterns:
  481. if pattern.search(line):
  482. matched.append(i)
  483. break
  484. if not matched:
  485. return
  486. # remove empty #ifdef ... #endif, successive blank lines
  487. pattern_if = re.compile(r'#\s*if(def|ndef)?\W') # #if, #ifdef, #ifndef
  488. pattern_elif = re.compile(r'#\s*el(if|se)\W') # #elif, #else
  489. pattern_endif = re.compile(r'#\s*endif\W') # #endif
  490. pattern_blank = re.compile(r'^\s*$') # empty line
  491. while True:
  492. old_matched = copy.copy(matched)
  493. extend_matched_lines(lines, matched, [pattern_if],
  494. [pattern_endif], True, True)
  495. extend_matched_lines(lines, matched, [pattern_elif],
  496. [pattern_elif, pattern_endif], True, False)
  497. extend_matched_lines(lines, matched, [pattern_if, pattern_elif],
  498. [pattern_blank], False, True)
  499. extend_matched_lines(lines, matched, [pattern_blank],
  500. [pattern_elif, pattern_endif], True, False)
  501. extend_matched_lines(lines, matched, [pattern_blank],
  502. [pattern_blank], True, False)
  503. if matched == old_matched:
  504. break
  505. tolines = copy.copy(lines)
  506. for i in reversed(matched):
  507. tolines.pop(i)
  508. show_diff(lines, tolines, header_path, options.color)
  509. if options.dry_run:
  510. return
  511. with open(header_path, 'w') as f:
  512. for line in tolines:
  513. f.write(line)
  514. def cleanup_headers(configs, options):
  515. """Delete config defines from board headers.
  516. Arguments:
  517. configs: A list of CONFIGs to remove.
  518. options: option flags.
  519. """
  520. if not confirm(options, 'Clean up headers?'):
  521. return
  522. patterns = []
  523. for config in configs:
  524. patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
  525. patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
  526. for dir in 'include', 'arch', 'board':
  527. for (dirpath, dirnames, filenames) in os.walk(dir):
  528. if dirpath == os.path.join('include', 'generated'):
  529. continue
  530. for filename in filenames:
  531. if not fnmatch.fnmatch(filename, '*~'):
  532. header_path = os.path.join(dirpath, filename)
  533. cleanup_one_header(header_path, patterns, options)
  534. cleanup_empty_blocks(header_path, options)
  535. def cleanup_one_extra_option(defconfig_path, configs, options):
  536. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in one defconfig file.
  537. Arguments:
  538. defconfig_path: path to the cleaned defconfig file.
  539. configs: A list of CONFIGs to remove.
  540. options: option flags.
  541. """
  542. start = 'CONFIG_SYS_EXTRA_OPTIONS="'
  543. end = '"\n'
  544. with open(defconfig_path) as f:
  545. lines = f.readlines()
  546. for i, line in enumerate(lines):
  547. if line.startswith(start) and line.endswith(end):
  548. break
  549. else:
  550. # CONFIG_SYS_EXTRA_OPTIONS was not found in this defconfig
  551. return
  552. old_tokens = line[len(start):-len(end)].split(',')
  553. new_tokens = []
  554. for token in old_tokens:
  555. pos = token.find('=')
  556. if not (token[:pos] if pos >= 0 else token) in configs:
  557. new_tokens.append(token)
  558. if new_tokens == old_tokens:
  559. return
  560. tolines = copy.copy(lines)
  561. if new_tokens:
  562. tolines[i] = start + ','.join(new_tokens) + end
  563. else:
  564. tolines.pop(i)
  565. show_diff(lines, tolines, defconfig_path, options.color)
  566. if options.dry_run:
  567. return
  568. with open(defconfig_path, 'w') as f:
  569. for line in tolines:
  570. f.write(line)
  571. def cleanup_extra_options(configs, options):
  572. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in defconfig files.
  573. Arguments:
  574. configs: A list of CONFIGs to remove.
  575. options: option flags.
  576. """
  577. if not confirm(options, 'Clean up CONFIG_SYS_EXTRA_OPTIONS?'):
  578. return
  579. configs = [ config[len('CONFIG_'):] for config in configs ]
  580. defconfigs = get_all_defconfigs()
  581. for defconfig in defconfigs:
  582. cleanup_one_extra_option(os.path.join('configs', defconfig), configs,
  583. options)
  584. def cleanup_whitelist(configs, options):
  585. """Delete config whitelist entries
  586. Arguments:
  587. configs: A list of CONFIGs to remove.
  588. options: option flags.
  589. """
  590. if not confirm(options, 'Clean up whitelist entries?'):
  591. return
  592. with open(os.path.join('scripts', 'config_whitelist.txt')) as f:
  593. lines = f.readlines()
  594. lines = [x for x in lines if x.strip() not in configs]
  595. with open(os.path.join('scripts', 'config_whitelist.txt'), 'w') as f:
  596. f.write(''.join(lines))
  597. def find_matching(patterns, line):
  598. for pat in patterns:
  599. if pat.search(line):
  600. return True
  601. return False
  602. def cleanup_readme(configs, options):
  603. """Delete config description in README
  604. Arguments:
  605. configs: A list of CONFIGs to remove.
  606. options: option flags.
  607. """
  608. if not confirm(options, 'Clean up README?'):
  609. return
  610. patterns = []
  611. for config in configs:
  612. patterns.append(re.compile(r'^\s+%s' % config))
  613. with open('README') as f:
  614. lines = f.readlines()
  615. found = False
  616. newlines = []
  617. for line in lines:
  618. if not found:
  619. found = find_matching(patterns, line)
  620. if found:
  621. continue
  622. if found and re.search(r'^\s+CONFIG', line):
  623. found = False
  624. if not found:
  625. newlines.append(line)
  626. with open('README', 'w') as f:
  627. f.write(''.join(newlines))
  628. def try_expand(line):
  629. """If value looks like an expression, try expanding it
  630. Otherwise just return the existing value
  631. """
  632. if line.find('=') == -1:
  633. return line
  634. try:
  635. cfg, val = re.split("=", line)
  636. val= val.strip('\"')
  637. if re.search("[*+-/]|<<|SZ_+|\(([^\)]+)\)", val):
  638. newval = hex(eval(val, SIZES))
  639. print("\tExpanded expression %s to %s" % (val, newval))
  640. return cfg+'='+newval
  641. except:
  642. print("\tFailed to expand expression in %s" % line)
  643. return line
  644. ### classes ###
  645. class Progress:
  646. """Progress Indicator"""
  647. def __init__(self, total):
  648. """Create a new progress indicator.
  649. Arguments:
  650. total: A number of defconfig files to process.
  651. """
  652. self.current = 0
  653. self.total = total
  654. def inc(self):
  655. """Increment the number of processed defconfig files."""
  656. self.current += 1
  657. def show(self):
  658. """Display the progress."""
  659. print(' %d defconfigs out of %d\r' % (self.current, self.total), end=' ')
  660. sys.stdout.flush()
  661. class KconfigScanner:
  662. """Kconfig scanner."""
  663. def __init__(self):
  664. """Scan all the Kconfig files and create a Config object."""
  665. # Define environment variables referenced from Kconfig
  666. os.environ['srctree'] = os.getcwd()
  667. os.environ['UBOOTVERSION'] = 'dummy'
  668. os.environ['KCONFIG_OBJDIR'] = ''
  669. self.conf = kconfiglib.Kconfig()
  670. class KconfigParser:
  671. """A parser of .config and include/autoconf.mk."""
  672. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  673. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  674. def __init__(self, configs, options, build_dir):
  675. """Create a new parser.
  676. Arguments:
  677. configs: A list of CONFIGs to move.
  678. options: option flags.
  679. build_dir: Build directory.
  680. """
  681. self.configs = configs
  682. self.options = options
  683. self.dotconfig = os.path.join(build_dir, '.config')
  684. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  685. self.spl_autoconf = os.path.join(build_dir, 'spl', 'include',
  686. 'autoconf.mk')
  687. self.config_autoconf = os.path.join(build_dir, AUTO_CONF_PATH)
  688. self.defconfig = os.path.join(build_dir, 'defconfig')
  689. def get_arch(self):
  690. """Parse .config file and return the architecture.
  691. Returns:
  692. Architecture name (e.g. 'arm').
  693. """
  694. arch = ''
  695. cpu = ''
  696. for line in open(self.dotconfig):
  697. m = self.re_arch.match(line)
  698. if m:
  699. arch = m.group(1)
  700. continue
  701. m = self.re_cpu.match(line)
  702. if m:
  703. cpu = m.group(1)
  704. if not arch:
  705. return None
  706. # fix-up for aarch64
  707. if arch == 'arm' and cpu == 'armv8':
  708. arch = 'aarch64'
  709. return arch
  710. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  711. """Parse .config, defconfig, include/autoconf.mk for one config.
  712. This function looks for the config options in the lines from
  713. defconfig, .config, and include/autoconf.mk in order to decide
  714. which action should be taken for this defconfig.
  715. Arguments:
  716. config: CONFIG name to parse.
  717. dotconfig_lines: lines from the .config file.
  718. autoconf_lines: lines from the include/autoconf.mk file.
  719. Returns:
  720. A tupple of the action for this defconfig and the line
  721. matched for the config.
  722. """
  723. not_set = '# %s is not set' % config
  724. for line in autoconf_lines:
  725. line = line.rstrip()
  726. if line.startswith(config + '='):
  727. new_val = line
  728. break
  729. else:
  730. new_val = not_set
  731. new_val = try_expand(new_val)
  732. for line in dotconfig_lines:
  733. line = line.rstrip()
  734. if line.startswith(config + '=') or line == not_set:
  735. old_val = line
  736. break
  737. else:
  738. if new_val == not_set:
  739. return (ACTION_NO_ENTRY, config)
  740. else:
  741. return (ACTION_NO_ENTRY_WARN, config)
  742. # If this CONFIG is neither bool nor trisate
  743. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  744. # tools/scripts/define2mk.sed changes '1' to 'y'.
  745. # This is a problem if the CONFIG is int type.
  746. # Check the type in Kconfig and handle it correctly.
  747. if new_val[-2:] == '=y':
  748. new_val = new_val[:-1] + '1'
  749. return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
  750. new_val)
  751. def update_dotconfig(self):
  752. """Parse files for the config options and update the .config.
  753. This function parses the generated .config and include/autoconf.mk
  754. searching the target options.
  755. Move the config option(s) to the .config as needed.
  756. Arguments:
  757. defconfig: defconfig name.
  758. Returns:
  759. Return a tuple of (updated flag, log string).
  760. The "updated flag" is True if the .config was updated, False
  761. otherwise. The "log string" shows what happend to the .config.
  762. """
  763. results = []
  764. updated = False
  765. suspicious = False
  766. rm_files = [self.config_autoconf, self.autoconf]
  767. if self.options.spl:
  768. if os.path.exists(self.spl_autoconf):
  769. autoconf_path = self.spl_autoconf
  770. rm_files.append(self.spl_autoconf)
  771. else:
  772. for f in rm_files:
  773. os.remove(f)
  774. return (updated, suspicious,
  775. color_text(self.options.color, COLOR_BROWN,
  776. "SPL is not enabled. Skipped.") + '\n')
  777. else:
  778. autoconf_path = self.autoconf
  779. with open(self.dotconfig) as f:
  780. dotconfig_lines = f.readlines()
  781. with open(autoconf_path) as f:
  782. autoconf_lines = f.readlines()
  783. for config in self.configs:
  784. result = self.parse_one_config(config, dotconfig_lines,
  785. autoconf_lines)
  786. results.append(result)
  787. log = ''
  788. for (action, value) in results:
  789. if action == ACTION_MOVE:
  790. actlog = "Move '%s'" % value
  791. log_color = COLOR_LIGHT_GREEN
  792. elif action == ACTION_NO_ENTRY:
  793. actlog = "%s is not defined in Kconfig. Do nothing." % value
  794. log_color = COLOR_LIGHT_BLUE
  795. elif action == ACTION_NO_ENTRY_WARN:
  796. actlog = "%s is not defined in Kconfig (suspicious). Do nothing." % value
  797. log_color = COLOR_YELLOW
  798. suspicious = True
  799. elif action == ACTION_NO_CHANGE:
  800. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  801. % value
  802. log_color = COLOR_LIGHT_PURPLE
  803. elif action == ACTION_SPL_NOT_EXIST:
  804. actlog = "SPL is not enabled for this defconfig. Skip."
  805. log_color = COLOR_PURPLE
  806. else:
  807. sys.exit("Internal Error. This should not happen.")
  808. log += color_text(self.options.color, log_color, actlog) + '\n'
  809. with open(self.dotconfig, 'a') as f:
  810. for (action, value) in results:
  811. if action == ACTION_MOVE:
  812. f.write(value + '\n')
  813. updated = True
  814. self.results = results
  815. for f in rm_files:
  816. os.remove(f)
  817. return (updated, suspicious, log)
  818. def check_defconfig(self):
  819. """Check the defconfig after savedefconfig
  820. Returns:
  821. Return additional log if moved CONFIGs were removed again by
  822. 'make savedefconfig'.
  823. """
  824. log = ''
  825. with open(self.defconfig) as f:
  826. defconfig_lines = f.readlines()
  827. for (action, value) in self.results:
  828. if action != ACTION_MOVE:
  829. continue
  830. if not value + '\n' in defconfig_lines:
  831. log += color_text(self.options.color, COLOR_YELLOW,
  832. "'%s' was removed by savedefconfig.\n" %
  833. value)
  834. return log
  835. class DatabaseThread(threading.Thread):
  836. """This thread processes results from Slot threads.
  837. It collects the data in the master config directary. There is only one
  838. result thread, and this helps to serialise the build output.
  839. """
  840. def __init__(self, config_db, db_queue):
  841. """Set up a new result thread
  842. Args:
  843. builder: Builder which will be sent each result
  844. """
  845. threading.Thread.__init__(self)
  846. self.config_db = config_db
  847. self.db_queue= db_queue
  848. def run(self):
  849. """Called to start up the result thread.
  850. We collect the next result job and pass it on to the build.
  851. """
  852. while True:
  853. defconfig, configs = self.db_queue.get()
  854. self.config_db[defconfig] = configs
  855. self.db_queue.task_done()
  856. class Slot:
  857. """A slot to store a subprocess.
  858. Each instance of this class handles one subprocess.
  859. This class is useful to control multiple threads
  860. for faster processing.
  861. """
  862. def __init__(self, toolchains, configs, options, progress, devnull,
  863. make_cmd, reference_src_dir, db_queue):
  864. """Create a new process slot.
  865. Arguments:
  866. toolchains: Toolchains object containing toolchains.
  867. configs: A list of CONFIGs to move.
  868. options: option flags.
  869. progress: A progress indicator.
  870. devnull: A file object of '/dev/null'.
  871. make_cmd: command name of GNU Make.
  872. reference_src_dir: Determine the true starting config state from this
  873. source tree.
  874. db_queue: output queue to write config info for the database
  875. """
  876. self.toolchains = toolchains
  877. self.options = options
  878. self.progress = progress
  879. self.build_dir = tempfile.mkdtemp()
  880. self.devnull = devnull
  881. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  882. self.reference_src_dir = reference_src_dir
  883. self.db_queue = db_queue
  884. self.parser = KconfigParser(configs, options, self.build_dir)
  885. self.state = STATE_IDLE
  886. self.failed_boards = set()
  887. self.suspicious_boards = set()
  888. def __del__(self):
  889. """Delete the working directory
  890. This function makes sure the temporary directory is cleaned away
  891. even if Python suddenly dies due to error. It should be done in here
  892. because it is guaranteed the destructor is always invoked when the
  893. instance of the class gets unreferenced.
  894. If the subprocess is still running, wait until it finishes.
  895. """
  896. if self.state != STATE_IDLE:
  897. while self.ps.poll() == None:
  898. pass
  899. shutil.rmtree(self.build_dir)
  900. def add(self, defconfig):
  901. """Assign a new subprocess for defconfig and add it to the slot.
  902. If the slot is vacant, create a new subprocess for processing the
  903. given defconfig and add it to the slot. Just returns False if
  904. the slot is occupied (i.e. the current subprocess is still running).
  905. Arguments:
  906. defconfig: defconfig name.
  907. Returns:
  908. Return True on success or False on failure
  909. """
  910. if self.state != STATE_IDLE:
  911. return False
  912. self.defconfig = defconfig
  913. self.log = ''
  914. self.current_src_dir = self.reference_src_dir
  915. self.do_defconfig()
  916. return True
  917. def poll(self):
  918. """Check the status of the subprocess and handle it as needed.
  919. Returns True if the slot is vacant (i.e. in idle state).
  920. If the configuration is successfully finished, assign a new
  921. subprocess to build include/autoconf.mk.
  922. If include/autoconf.mk is generated, invoke the parser to
  923. parse the .config and the include/autoconf.mk, moving
  924. config options to the .config as needed.
  925. If the .config was updated, run "make savedefconfig" to sync
  926. it, update the original defconfig, and then set the slot back
  927. to the idle state.
  928. Returns:
  929. Return True if the subprocess is terminated, False otherwise
  930. """
  931. if self.state == STATE_IDLE:
  932. return True
  933. if self.ps.poll() == None:
  934. return False
  935. if self.ps.poll() != 0:
  936. self.handle_error()
  937. elif self.state == STATE_DEFCONFIG:
  938. if self.reference_src_dir and not self.current_src_dir:
  939. self.do_savedefconfig()
  940. else:
  941. self.do_autoconf()
  942. elif self.state == STATE_AUTOCONF:
  943. if self.current_src_dir:
  944. self.current_src_dir = None
  945. self.do_defconfig()
  946. elif self.options.build_db:
  947. self.do_build_db()
  948. else:
  949. self.do_savedefconfig()
  950. elif self.state == STATE_SAVEDEFCONFIG:
  951. self.update_defconfig()
  952. else:
  953. sys.exit("Internal Error. This should not happen.")
  954. return True if self.state == STATE_IDLE else False
  955. def handle_error(self):
  956. """Handle error cases."""
  957. self.log += color_text(self.options.color, COLOR_LIGHT_RED,
  958. "Failed to process.\n")
  959. if self.options.verbose:
  960. self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
  961. self.ps.stderr.read())
  962. self.finish(False)
  963. def do_defconfig(self):
  964. """Run 'make <board>_defconfig' to create the .config file."""
  965. cmd = list(self.make_cmd)
  966. cmd.append(self.defconfig)
  967. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  968. stderr=subprocess.PIPE,
  969. cwd=self.current_src_dir)
  970. self.state = STATE_DEFCONFIG
  971. def do_autoconf(self):
  972. """Run 'make AUTO_CONF_PATH'."""
  973. arch = self.parser.get_arch()
  974. try:
  975. toolchain = self.toolchains.Select(arch)
  976. except ValueError:
  977. self.log += color_text(self.options.color, COLOR_YELLOW,
  978. "Tool chain for '%s' is missing. Do nothing.\n" % arch)
  979. self.finish(False)
  980. return
  981. env = toolchain.MakeEnvironment(False)
  982. cmd = list(self.make_cmd)
  983. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  984. cmd.append(AUTO_CONF_PATH)
  985. self.ps = subprocess.Popen(cmd, stdout=self.devnull, env=env,
  986. stderr=subprocess.PIPE,
  987. cwd=self.current_src_dir)
  988. self.state = STATE_AUTOCONF
  989. def do_build_db(self):
  990. """Add the board to the database"""
  991. configs = {}
  992. with open(os.path.join(self.build_dir, AUTO_CONF_PATH)) as fd:
  993. for line in fd.readlines():
  994. if line.startswith('CONFIG'):
  995. config, value = line.split('=', 1)
  996. configs[config] = value.rstrip()
  997. self.db_queue.put([self.defconfig, configs])
  998. self.finish(True)
  999. def do_savedefconfig(self):
  1000. """Update the .config and run 'make savedefconfig'."""
  1001. (updated, suspicious, log) = self.parser.update_dotconfig()
  1002. if suspicious:
  1003. self.suspicious_boards.add(self.defconfig)
  1004. self.log += log
  1005. if not self.options.force_sync and not updated:
  1006. self.finish(True)
  1007. return
  1008. if updated:
  1009. self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
  1010. "Syncing by savedefconfig...\n")
  1011. else:
  1012. self.log += "Syncing by savedefconfig (forced by option)...\n"
  1013. cmd = list(self.make_cmd)
  1014. cmd.append('savedefconfig')
  1015. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  1016. stderr=subprocess.PIPE)
  1017. self.state = STATE_SAVEDEFCONFIG
  1018. def update_defconfig(self):
  1019. """Update the input defconfig and go back to the idle state."""
  1020. log = self.parser.check_defconfig()
  1021. if log:
  1022. self.suspicious_boards.add(self.defconfig)
  1023. self.log += log
  1024. orig_defconfig = os.path.join('configs', self.defconfig)
  1025. new_defconfig = os.path.join(self.build_dir, 'defconfig')
  1026. updated = not filecmp.cmp(orig_defconfig, new_defconfig)
  1027. if updated:
  1028. self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
  1029. "defconfig was updated.\n")
  1030. if not self.options.dry_run and updated:
  1031. shutil.move(new_defconfig, orig_defconfig)
  1032. self.finish(True)
  1033. def finish(self, success):
  1034. """Display log along with progress and go to the idle state.
  1035. Arguments:
  1036. success: Should be True when the defconfig was processed
  1037. successfully, or False when it fails.
  1038. """
  1039. # output at least 30 characters to hide the "* defconfigs out of *".
  1040. log = self.defconfig.ljust(30) + '\n'
  1041. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  1042. # Some threads are running in parallel.
  1043. # Print log atomically to not mix up logs from different threads.
  1044. print(log, file=(sys.stdout if success else sys.stderr))
  1045. if not success:
  1046. if self.options.exit_on_error:
  1047. sys.exit("Exit on error.")
  1048. # If --exit-on-error flag is not set, skip this board and continue.
  1049. # Record the failed board.
  1050. self.failed_boards.add(self.defconfig)
  1051. self.progress.inc()
  1052. self.progress.show()
  1053. self.state = STATE_IDLE
  1054. def get_failed_boards(self):
  1055. """Returns a set of failed boards (defconfigs) in this slot.
  1056. """
  1057. return self.failed_boards
  1058. def get_suspicious_boards(self):
  1059. """Returns a set of boards (defconfigs) with possible misconversion.
  1060. """
  1061. return self.suspicious_boards - self.failed_boards
  1062. class Slots:
  1063. """Controller of the array of subprocess slots."""
  1064. def __init__(self, toolchains, configs, options, progress,
  1065. reference_src_dir, db_queue):
  1066. """Create a new slots controller.
  1067. Arguments:
  1068. toolchains: Toolchains object containing toolchains.
  1069. configs: A list of CONFIGs to move.
  1070. options: option flags.
  1071. progress: A progress indicator.
  1072. reference_src_dir: Determine the true starting config state from this
  1073. source tree.
  1074. db_queue: output queue to write config info for the database
  1075. """
  1076. self.options = options
  1077. self.slots = []
  1078. devnull = get_devnull()
  1079. make_cmd = get_make_cmd()
  1080. for i in range(options.jobs):
  1081. self.slots.append(Slot(toolchains, configs, options, progress,
  1082. devnull, make_cmd, reference_src_dir,
  1083. db_queue))
  1084. def add(self, defconfig):
  1085. """Add a new subprocess if a vacant slot is found.
  1086. Arguments:
  1087. defconfig: defconfig name to be put into.
  1088. Returns:
  1089. Return True on success or False on failure
  1090. """
  1091. for slot in self.slots:
  1092. if slot.add(defconfig):
  1093. return True
  1094. return False
  1095. def available(self):
  1096. """Check if there is a vacant slot.
  1097. Returns:
  1098. Return True if at lease one vacant slot is found, False otherwise.
  1099. """
  1100. for slot in self.slots:
  1101. if slot.poll():
  1102. return True
  1103. return False
  1104. def empty(self):
  1105. """Check if all slots are vacant.
  1106. Returns:
  1107. Return True if all the slots are vacant, False otherwise.
  1108. """
  1109. ret = True
  1110. for slot in self.slots:
  1111. if not slot.poll():
  1112. ret = False
  1113. return ret
  1114. def show_failed_boards(self):
  1115. """Display all of the failed boards (defconfigs)."""
  1116. boards = set()
  1117. output_file = 'moveconfig.failed'
  1118. for slot in self.slots:
  1119. boards |= slot.get_failed_boards()
  1120. if boards:
  1121. boards = '\n'.join(boards) + '\n'
  1122. msg = "The following boards were not processed due to error:\n"
  1123. msg += boards
  1124. msg += "(the list has been saved in %s)\n" % output_file
  1125. print(color_text(self.options.color, COLOR_LIGHT_RED,
  1126. msg), file=sys.stderr)
  1127. with open(output_file, 'w') as f:
  1128. f.write(boards)
  1129. def show_suspicious_boards(self):
  1130. """Display all boards (defconfigs) with possible misconversion."""
  1131. boards = set()
  1132. output_file = 'moveconfig.suspicious'
  1133. for slot in self.slots:
  1134. boards |= slot.get_suspicious_boards()
  1135. if boards:
  1136. boards = '\n'.join(boards) + '\n'
  1137. msg = "The following boards might have been converted incorrectly.\n"
  1138. msg += "It is highly recommended to check them manually:\n"
  1139. msg += boards
  1140. msg += "(the list has been saved in %s)\n" % output_file
  1141. print(color_text(self.options.color, COLOR_YELLOW,
  1142. msg), file=sys.stderr)
  1143. with open(output_file, 'w') as f:
  1144. f.write(boards)
  1145. class ReferenceSource:
  1146. """Reference source against which original configs should be parsed."""
  1147. def __init__(self, commit):
  1148. """Create a reference source directory based on a specified commit.
  1149. Arguments:
  1150. commit: commit to git-clone
  1151. """
  1152. self.src_dir = tempfile.mkdtemp()
  1153. print("Cloning git repo to a separate work directory...")
  1154. subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
  1155. cwd=self.src_dir)
  1156. print("Checkout '%s' to build the original autoconf.mk." % \
  1157. subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip())
  1158. subprocess.check_output(['git', 'checkout', commit],
  1159. stderr=subprocess.STDOUT, cwd=self.src_dir)
  1160. def __del__(self):
  1161. """Delete the reference source directory
  1162. This function makes sure the temporary directory is cleaned away
  1163. even if Python suddenly dies due to error. It should be done in here
  1164. because it is guaranteed the destructor is always invoked when the
  1165. instance of the class gets unreferenced.
  1166. """
  1167. shutil.rmtree(self.src_dir)
  1168. def get_dir(self):
  1169. """Return the absolute path to the reference source directory."""
  1170. return self.src_dir
  1171. def move_config(toolchains, configs, options, db_queue):
  1172. """Move config options to defconfig files.
  1173. Arguments:
  1174. configs: A list of CONFIGs to move.
  1175. options: option flags
  1176. """
  1177. if len(configs) == 0:
  1178. if options.force_sync:
  1179. print('No CONFIG is specified. You are probably syncing defconfigs.', end=' ')
  1180. elif options.build_db:
  1181. print('Building %s database' % CONFIG_DATABASE)
  1182. else:
  1183. print('Neither CONFIG nor --force-sync is specified. Nothing will happen.', end=' ')
  1184. else:
  1185. print('Move ' + ', '.join(configs), end=' ')
  1186. print('(jobs: %d)\n' % options.jobs)
  1187. if options.git_ref:
  1188. reference_src = ReferenceSource(options.git_ref)
  1189. reference_src_dir = reference_src.get_dir()
  1190. else:
  1191. reference_src_dir = None
  1192. if options.defconfigs:
  1193. defconfigs = get_matched_defconfigs(options.defconfigs)
  1194. else:
  1195. defconfigs = get_all_defconfigs()
  1196. progress = Progress(len(defconfigs))
  1197. slots = Slots(toolchains, configs, options, progress, reference_src_dir,
  1198. db_queue)
  1199. # Main loop to process defconfig files:
  1200. # Add a new subprocess into a vacant slot.
  1201. # Sleep if there is no available slot.
  1202. for defconfig in defconfigs:
  1203. while not slots.add(defconfig):
  1204. while not slots.available():
  1205. # No available slot: sleep for a while
  1206. time.sleep(SLEEP_TIME)
  1207. # wait until all the subprocesses finish
  1208. while not slots.empty():
  1209. time.sleep(SLEEP_TIME)
  1210. print('')
  1211. slots.show_failed_boards()
  1212. slots.show_suspicious_boards()
  1213. def find_kconfig_rules(kconf, config, imply_config):
  1214. """Check whether a config has a 'select' or 'imply' keyword
  1215. Args:
  1216. kconf: Kconfiglib.Kconfig object
  1217. config: Name of config to check (without CONFIG_ prefix)
  1218. imply_config: Implying config (without CONFIG_ prefix) which may or
  1219. may not have an 'imply' for 'config')
  1220. Returns:
  1221. Symbol object for 'config' if found, else None
  1222. """
  1223. sym = kconf.syms.get(imply_config)
  1224. if sym:
  1225. for sel in sym.get_selected_symbols() | sym.get_implied_symbols():
  1226. if sel.get_name() == config:
  1227. return sym
  1228. return None
  1229. def check_imply_rule(kconf, config, imply_config):
  1230. """Check if we can add an 'imply' option
  1231. This finds imply_config in the Kconfig and looks to see if it is possible
  1232. to add an 'imply' for 'config' to that part of the Kconfig.
  1233. Args:
  1234. kconf: Kconfiglib.Kconfig object
  1235. config: Name of config to check (without CONFIG_ prefix)
  1236. imply_config: Implying config (without CONFIG_ prefix) which may or
  1237. may not have an 'imply' for 'config')
  1238. Returns:
  1239. tuple:
  1240. filename of Kconfig file containing imply_config, or None if none
  1241. line number within the Kconfig file, or 0 if none
  1242. message indicating the result
  1243. """
  1244. sym = kconf.syms.get(imply_config)
  1245. if not sym:
  1246. return 'cannot find sym'
  1247. locs = sym.get_def_locations()
  1248. if len(locs) != 1:
  1249. return '%d locations' % len(locs)
  1250. fname, linenum = locs[0]
  1251. cwd = os.getcwd()
  1252. if cwd and fname.startswith(cwd):
  1253. fname = fname[len(cwd) + 1:]
  1254. file_line = ' at %s:%d' % (fname, linenum)
  1255. with open(fname) as fd:
  1256. data = fd.read().splitlines()
  1257. if data[linenum - 1] != 'config %s' % imply_config:
  1258. return None, 0, 'bad sym format %s%s' % (data[linenum], file_line)
  1259. return fname, linenum, 'adding%s' % file_line
  1260. def add_imply_rule(config, fname, linenum):
  1261. """Add a new 'imply' option to a Kconfig
  1262. Args:
  1263. config: config option to add an imply for (without CONFIG_ prefix)
  1264. fname: Kconfig filename to update
  1265. linenum: Line number to place the 'imply' before
  1266. Returns:
  1267. Message indicating the result
  1268. """
  1269. file_line = ' at %s:%d' % (fname, linenum)
  1270. data = open(fname).read().splitlines()
  1271. linenum -= 1
  1272. for offset, line in enumerate(data[linenum:]):
  1273. if line.strip().startswith('help') or not line:
  1274. data.insert(linenum + offset, '\timply %s' % config)
  1275. with open(fname, 'w') as fd:
  1276. fd.write('\n'.join(data) + '\n')
  1277. return 'added%s' % file_line
  1278. return 'could not insert%s'
  1279. (IMPLY_MIN_2, IMPLY_TARGET, IMPLY_CMD, IMPLY_NON_ARCH_BOARD) = (
  1280. 1, 2, 4, 8)
  1281. IMPLY_FLAGS = {
  1282. 'min2': [IMPLY_MIN_2, 'Show options which imply >2 boards (normally >5)'],
  1283. 'target': [IMPLY_TARGET, 'Allow CONFIG_TARGET_... options to imply'],
  1284. 'cmd': [IMPLY_CMD, 'Allow CONFIG_CMD_... to imply'],
  1285. 'non-arch-board': [
  1286. IMPLY_NON_ARCH_BOARD,
  1287. 'Allow Kconfig options outside arch/ and /board/ to imply'],
  1288. };
  1289. def do_imply_config(config_list, add_imply, imply_flags, skip_added,
  1290. check_kconfig=True, find_superset=False):
  1291. """Find CONFIG options which imply those in the list
  1292. Some CONFIG options can be implied by others and this can help to reduce
  1293. the size of the defconfig files. For example, CONFIG_X86 implies
  1294. CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
  1295. all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
  1296. each of the x86 defconfig files.
  1297. This function uses the moveconfig database to find such options. It
  1298. displays a list of things that could possibly imply those in the list.
  1299. The algorithm ignores any that start with CONFIG_TARGET since these
  1300. typically refer to only a few defconfigs (often one). It also does not
  1301. display a config with less than 5 defconfigs.
  1302. The algorithm works using sets. For each target config in config_list:
  1303. - Get the set 'defconfigs' which use that target config
  1304. - For each config (from a list of all configs):
  1305. - Get the set 'imply_defconfig' of defconfigs which use that config
  1306. -
  1307. - If imply_defconfigs contains anything not in defconfigs then
  1308. this config does not imply the target config
  1309. Params:
  1310. config_list: List of CONFIG options to check (each a string)
  1311. add_imply: Automatically add an 'imply' for each config.
  1312. imply_flags: Flags which control which implying configs are allowed
  1313. (IMPLY_...)
  1314. skip_added: Don't show options which already have an imply added.
  1315. check_kconfig: Check if implied symbols already have an 'imply' or
  1316. 'select' for the target config, and show this information if so.
  1317. find_superset: True to look for configs which are a superset of those
  1318. already found. So for example if CONFIG_EXYNOS5 implies an option,
  1319. but CONFIG_EXYNOS covers a larger set of defconfigs and also
  1320. implies that option, this will drop the former in favour of the
  1321. latter. In practice this option has not proved very used.
  1322. Note the terminoloy:
  1323. config - a CONFIG_XXX options (a string, e.g. 'CONFIG_CMD_EEPROM')
  1324. defconfig - a defconfig file (a string, e.g. 'configs/snow_defconfig')
  1325. """
  1326. kconf = KconfigScanner().conf if check_kconfig else None
  1327. if add_imply and add_imply != 'all':
  1328. add_imply = add_imply.split()
  1329. # key is defconfig name, value is dict of (CONFIG_xxx, value)
  1330. config_db = {}
  1331. # Holds a dict containing the set of defconfigs that contain each config
  1332. # key is config, value is set of defconfigs using that config
  1333. defconfig_db = collections.defaultdict(set)
  1334. # Set of all config options we have seen
  1335. all_configs = set()
  1336. # Set of all defconfigs we have seen
  1337. all_defconfigs = set()
  1338. # Read in the database
  1339. configs = {}
  1340. with open(CONFIG_DATABASE) as fd:
  1341. for line in fd.readlines():
  1342. line = line.rstrip()
  1343. if not line: # Separator between defconfigs
  1344. config_db[defconfig] = configs
  1345. all_defconfigs.add(defconfig)
  1346. configs = {}
  1347. elif line[0] == ' ': # CONFIG line
  1348. config, value = line.strip().split('=', 1)
  1349. configs[config] = value
  1350. defconfig_db[config].add(defconfig)
  1351. all_configs.add(config)
  1352. else: # New defconfig
  1353. defconfig = line
  1354. # Work through each target config option in tern, independently
  1355. for config in config_list:
  1356. defconfigs = defconfig_db.get(config)
  1357. if not defconfigs:
  1358. print('%s not found in any defconfig' % config)
  1359. continue
  1360. # Get the set of defconfigs without this one (since a config cannot
  1361. # imply itself)
  1362. non_defconfigs = all_defconfigs - defconfigs
  1363. num_defconfigs = len(defconfigs)
  1364. print('%s found in %d/%d defconfigs' % (config, num_defconfigs,
  1365. len(all_configs)))
  1366. # This will hold the results: key=config, value=defconfigs containing it
  1367. imply_configs = {}
  1368. rest_configs = all_configs - set([config])
  1369. # Look at every possible config, except the target one
  1370. for imply_config in rest_configs:
  1371. if 'ERRATUM' in imply_config:
  1372. continue
  1373. if not (imply_flags & IMPLY_CMD):
  1374. if 'CONFIG_CMD' in imply_config:
  1375. continue
  1376. if not (imply_flags & IMPLY_TARGET):
  1377. if 'CONFIG_TARGET' in imply_config:
  1378. continue
  1379. # Find set of defconfigs that have this config
  1380. imply_defconfig = defconfig_db[imply_config]
  1381. # Get the intersection of this with defconfigs containing the
  1382. # target config
  1383. common_defconfigs = imply_defconfig & defconfigs
  1384. # Get the set of defconfigs containing this config which DO NOT
  1385. # also contain the taret config. If this set is non-empty it means
  1386. # that this config affects other defconfigs as well as (possibly)
  1387. # the ones affected by the target config. This means it implies
  1388. # things we don't want to imply.
  1389. not_common_defconfigs = imply_defconfig & non_defconfigs
  1390. if not_common_defconfigs:
  1391. continue
  1392. # If there are common defconfigs, imply_config may be useful
  1393. if common_defconfigs:
  1394. skip = False
  1395. if find_superset:
  1396. for prev in list(imply_configs.keys()):
  1397. prev_count = len(imply_configs[prev])
  1398. count = len(common_defconfigs)
  1399. if (prev_count > count and
  1400. (imply_configs[prev] & common_defconfigs ==
  1401. common_defconfigs)):
  1402. # skip imply_config because prev is a superset
  1403. skip = True
  1404. break
  1405. elif count > prev_count:
  1406. # delete prev because imply_config is a superset
  1407. del imply_configs[prev]
  1408. if not skip:
  1409. imply_configs[imply_config] = common_defconfigs
  1410. # Now we have a dict imply_configs of configs which imply each config
  1411. # The value of each dict item is the set of defconfigs containing that
  1412. # config. Rank them so that we print the configs that imply the largest
  1413. # number of defconfigs first.
  1414. ranked_iconfigs = sorted(imply_configs,
  1415. key=lambda k: len(imply_configs[k]), reverse=True)
  1416. kconfig_info = ''
  1417. cwd = os.getcwd()
  1418. add_list = collections.defaultdict(list)
  1419. for iconfig in ranked_iconfigs:
  1420. num_common = len(imply_configs[iconfig])
  1421. # Don't bother if there are less than 5 defconfigs affected.
  1422. if num_common < (2 if imply_flags & IMPLY_MIN_2 else 5):
  1423. continue
  1424. missing = defconfigs - imply_configs[iconfig]
  1425. missing_str = ', '.join(missing) if missing else 'all'
  1426. missing_str = ''
  1427. show = True
  1428. if kconf:
  1429. sym = find_kconfig_rules(kconf, config[CONFIG_LEN:],
  1430. iconfig[CONFIG_LEN:])
  1431. kconfig_info = ''
  1432. if sym:
  1433. locs = sym.get_def_locations()
  1434. if len(locs) == 1:
  1435. fname, linenum = locs[0]
  1436. if cwd and fname.startswith(cwd):
  1437. fname = fname[len(cwd) + 1:]
  1438. kconfig_info = '%s:%d' % (fname, linenum)
  1439. if skip_added:
  1440. show = False
  1441. else:
  1442. sym = kconf.syms.get(iconfig[CONFIG_LEN:])
  1443. fname = ''
  1444. if sym:
  1445. locs = sym.get_def_locations()
  1446. if len(locs) == 1:
  1447. fname, linenum = locs[0]
  1448. if cwd and fname.startswith(cwd):
  1449. fname = fname[len(cwd) + 1:]
  1450. in_arch_board = not sym or (fname.startswith('arch') or
  1451. fname.startswith('board'))
  1452. if (not in_arch_board and
  1453. not (imply_flags & IMPLY_NON_ARCH_BOARD)):
  1454. continue
  1455. if add_imply and (add_imply == 'all' or
  1456. iconfig in add_imply):
  1457. fname, linenum, kconfig_info = (check_imply_rule(kconf,
  1458. config[CONFIG_LEN:], iconfig[CONFIG_LEN:]))
  1459. if fname:
  1460. add_list[fname].append(linenum)
  1461. if show and kconfig_info != 'skip':
  1462. print('%5d : %-30s%-25s %s' % (num_common, iconfig.ljust(30),
  1463. kconfig_info, missing_str))
  1464. # Having collected a list of things to add, now we add them. We process
  1465. # each file from the largest line number to the smallest so that
  1466. # earlier additions do not affect our line numbers. E.g. if we added an
  1467. # imply at line 20 it would change the position of each line after
  1468. # that.
  1469. for fname, linenums in add_list.items():
  1470. for linenum in sorted(linenums, reverse=True):
  1471. add_imply_rule(config[CONFIG_LEN:], fname, linenum)
  1472. def main():
  1473. try:
  1474. cpu_count = multiprocessing.cpu_count()
  1475. except NotImplementedError:
  1476. cpu_count = 1
  1477. parser = optparse.OptionParser()
  1478. # Add options here
  1479. parser.add_option('-a', '--add-imply', type='string', default='',
  1480. help='comma-separated list of CONFIG options to add '
  1481. "an 'imply' statement to for the CONFIG in -i")
  1482. parser.add_option('-A', '--skip-added', action='store_true', default=False,
  1483. help="don't show options which are already marked as "
  1484. 'implying others')
  1485. parser.add_option('-b', '--build-db', action='store_true', default=False,
  1486. help='build a CONFIG database')
  1487. parser.add_option('-c', '--color', action='store_true', default=False,
  1488. help='display the log in color')
  1489. parser.add_option('-C', '--commit', action='store_true', default=False,
  1490. help='Create a git commit for the operation')
  1491. parser.add_option('-d', '--defconfigs', type='string',
  1492. help='a file containing a list of defconfigs to move, '
  1493. "one per line (for example 'snow_defconfig') "
  1494. "or '-' to read from stdin")
  1495. parser.add_option('-i', '--imply', action='store_true', default=False,
  1496. help='find options which imply others')
  1497. parser.add_option('-I', '--imply-flags', type='string', default='',
  1498. help="control the -i option ('help' for help")
  1499. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  1500. help='perform a trial run (show log with no changes)')
  1501. parser.add_option('-e', '--exit-on-error', action='store_true',
  1502. default=False,
  1503. help='exit immediately on any error')
  1504. parser.add_option('-s', '--force-sync', action='store_true', default=False,
  1505. help='force sync by savedefconfig')
  1506. parser.add_option('-S', '--spl', action='store_true', default=False,
  1507. help='parse config options defined for SPL build')
  1508. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  1509. action='store_true', default=False,
  1510. help='only cleanup the headers')
  1511. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  1512. help='the number of jobs to run simultaneously')
  1513. parser.add_option('-r', '--git-ref', type='string',
  1514. help='the git ref to clone for building the autoconf.mk')
  1515. parser.add_option('-y', '--yes', action='store_true', default=False,
  1516. help="respond 'yes' to any prompts")
  1517. parser.add_option('-v', '--verbose', action='store_true', default=False,
  1518. help='show any build errors as boards are built')
  1519. parser.usage += ' CONFIG ...'
  1520. (options, configs) = parser.parse_args()
  1521. if len(configs) == 0 and not any((options.force_sync, options.build_db,
  1522. options.imply)):
  1523. parser.print_usage()
  1524. sys.exit(1)
  1525. # prefix the option name with CONFIG_ if missing
  1526. configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
  1527. for config in configs ]
  1528. check_top_directory()
  1529. if options.imply:
  1530. imply_flags = 0
  1531. if options.imply_flags == 'all':
  1532. imply_flags = -1
  1533. elif options.imply_flags:
  1534. for flag in options.imply_flags.split(','):
  1535. bad = flag not in IMPLY_FLAGS
  1536. if bad:
  1537. print("Invalid flag '%s'" % flag)
  1538. if flag == 'help' or bad:
  1539. print("Imply flags: (separate with ',')")
  1540. for name, info in IMPLY_FLAGS.items():
  1541. print(' %-15s: %s' % (name, info[1]))
  1542. parser.print_usage()
  1543. sys.exit(1)
  1544. imply_flags |= IMPLY_FLAGS[flag][0]
  1545. do_imply_config(configs, options.add_imply, imply_flags,
  1546. options.skip_added)
  1547. return
  1548. config_db = {}
  1549. db_queue = queue.Queue()
  1550. t = DatabaseThread(config_db, db_queue)
  1551. t.setDaemon(True)
  1552. t.start()
  1553. if not options.cleanup_headers_only:
  1554. check_clean_directory()
  1555. bsettings.Setup('')
  1556. toolchains = toolchain.Toolchains()
  1557. toolchains.GetSettings()
  1558. toolchains.Scan(verbose=False)
  1559. move_config(toolchains, configs, options, db_queue)
  1560. db_queue.join()
  1561. if configs:
  1562. cleanup_headers(configs, options)
  1563. cleanup_extra_options(configs, options)
  1564. cleanup_whitelist(configs, options)
  1565. cleanup_readme(configs, options)
  1566. if options.commit:
  1567. subprocess.call(['git', 'add', '-u'])
  1568. if configs:
  1569. msg = 'Convert %s %sto Kconfig' % (configs[0],
  1570. 'et al ' if len(configs) > 1 else '')
  1571. msg += ('\n\nThis converts the following to Kconfig:\n %s\n' %
  1572. '\n '.join(configs))
  1573. else:
  1574. msg = 'configs: Resync with savedefconfig'
  1575. msg += '\n\nRsync all defconfig files using moveconfig.py'
  1576. subprocess.call(['git', 'commit', '-s', '-m', msg])
  1577. if options.build_db:
  1578. with open(CONFIG_DATABASE, 'w') as fd:
  1579. for defconfig, configs in config_db.items():
  1580. fd.write('%s\n' % defconfig)
  1581. for config in sorted(configs.keys()):
  1582. fd.write(' %s=%s\n' % (config, configs[config]))
  1583. fd.write('\n')
  1584. if __name__ == '__main__':
  1585. main()