moveconfig.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952
  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 filename.endswith(('~', '.dts', '.dtsi')):
  532. header_path = os.path.join(dirpath, filename)
  533. # This file contains UTF-16 data and no CONFIG symbols
  534. if header_path == 'include/video_font_data.h':
  535. continue
  536. cleanup_one_header(header_path, patterns, options)
  537. cleanup_empty_blocks(header_path, options)
  538. def cleanup_one_extra_option(defconfig_path, configs, options):
  539. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in one defconfig file.
  540. Arguments:
  541. defconfig_path: path to the cleaned defconfig file.
  542. configs: A list of CONFIGs to remove.
  543. options: option flags.
  544. """
  545. start = 'CONFIG_SYS_EXTRA_OPTIONS="'
  546. end = '"\n'
  547. with open(defconfig_path) as f:
  548. lines = f.readlines()
  549. for i, line in enumerate(lines):
  550. if line.startswith(start) and line.endswith(end):
  551. break
  552. else:
  553. # CONFIG_SYS_EXTRA_OPTIONS was not found in this defconfig
  554. return
  555. old_tokens = line[len(start):-len(end)].split(',')
  556. new_tokens = []
  557. for token in old_tokens:
  558. pos = token.find('=')
  559. if not (token[:pos] if pos >= 0 else token) in configs:
  560. new_tokens.append(token)
  561. if new_tokens == old_tokens:
  562. return
  563. tolines = copy.copy(lines)
  564. if new_tokens:
  565. tolines[i] = start + ','.join(new_tokens) + end
  566. else:
  567. tolines.pop(i)
  568. show_diff(lines, tolines, defconfig_path, options.color)
  569. if options.dry_run:
  570. return
  571. with open(defconfig_path, 'w') as f:
  572. for line in tolines:
  573. f.write(line)
  574. def cleanup_extra_options(configs, options):
  575. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in defconfig files.
  576. Arguments:
  577. configs: A list of CONFIGs to remove.
  578. options: option flags.
  579. """
  580. if not confirm(options, 'Clean up CONFIG_SYS_EXTRA_OPTIONS?'):
  581. return
  582. configs = [ config[len('CONFIG_'):] for config in configs ]
  583. defconfigs = get_all_defconfigs()
  584. for defconfig in defconfigs:
  585. cleanup_one_extra_option(os.path.join('configs', defconfig), configs,
  586. options)
  587. def cleanup_whitelist(configs, options):
  588. """Delete config whitelist entries
  589. Arguments:
  590. configs: A list of CONFIGs to remove.
  591. options: option flags.
  592. """
  593. if not confirm(options, 'Clean up whitelist entries?'):
  594. return
  595. with open(os.path.join('scripts', 'config_whitelist.txt')) as f:
  596. lines = f.readlines()
  597. lines = [x for x in lines if x.strip() not in configs]
  598. with open(os.path.join('scripts', 'config_whitelist.txt'), 'w') as f:
  599. f.write(''.join(lines))
  600. def find_matching(patterns, line):
  601. for pat in patterns:
  602. if pat.search(line):
  603. return True
  604. return False
  605. def cleanup_readme(configs, options):
  606. """Delete config description in README
  607. Arguments:
  608. configs: A list of CONFIGs to remove.
  609. options: option flags.
  610. """
  611. if not confirm(options, 'Clean up README?'):
  612. return
  613. patterns = []
  614. for config in configs:
  615. patterns.append(re.compile(r'^\s+%s' % config))
  616. with open('README') as f:
  617. lines = f.readlines()
  618. found = False
  619. newlines = []
  620. for line in lines:
  621. if not found:
  622. found = find_matching(patterns, line)
  623. if found:
  624. continue
  625. if found and re.search(r'^\s+CONFIG', line):
  626. found = False
  627. if not found:
  628. newlines.append(line)
  629. with open('README', 'w') as f:
  630. f.write(''.join(newlines))
  631. def try_expand(line):
  632. """If value looks like an expression, try expanding it
  633. Otherwise just return the existing value
  634. """
  635. if line.find('=') == -1:
  636. return line
  637. try:
  638. cfg, val = re.split("=", line)
  639. val= val.strip('\"')
  640. if re.search("[*+-/]|<<|SZ_+|\(([^\)]+)\)", val):
  641. newval = hex(eval(val, SIZES))
  642. print("\tExpanded expression %s to %s" % (val, newval))
  643. return cfg+'='+newval
  644. except:
  645. print("\tFailed to expand expression in %s" % line)
  646. return line
  647. ### classes ###
  648. class Progress:
  649. """Progress Indicator"""
  650. def __init__(self, total):
  651. """Create a new progress indicator.
  652. Arguments:
  653. total: A number of defconfig files to process.
  654. """
  655. self.current = 0
  656. self.total = total
  657. def inc(self):
  658. """Increment the number of processed defconfig files."""
  659. self.current += 1
  660. def show(self):
  661. """Display the progress."""
  662. print(' %d defconfigs out of %d\r' % (self.current, self.total), end=' ')
  663. sys.stdout.flush()
  664. class KconfigScanner:
  665. """Kconfig scanner."""
  666. def __init__(self):
  667. """Scan all the Kconfig files and create a Config object."""
  668. # Define environment variables referenced from Kconfig
  669. os.environ['srctree'] = os.getcwd()
  670. os.environ['UBOOTVERSION'] = 'dummy'
  671. os.environ['KCONFIG_OBJDIR'] = ''
  672. self.conf = kconfiglib.Kconfig()
  673. class KconfigParser:
  674. """A parser of .config and include/autoconf.mk."""
  675. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  676. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  677. def __init__(self, configs, options, build_dir):
  678. """Create a new parser.
  679. Arguments:
  680. configs: A list of CONFIGs to move.
  681. options: option flags.
  682. build_dir: Build directory.
  683. """
  684. self.configs = configs
  685. self.options = options
  686. self.dotconfig = os.path.join(build_dir, '.config')
  687. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  688. self.spl_autoconf = os.path.join(build_dir, 'spl', 'include',
  689. 'autoconf.mk')
  690. self.config_autoconf = os.path.join(build_dir, AUTO_CONF_PATH)
  691. self.defconfig = os.path.join(build_dir, 'defconfig')
  692. def get_arch(self):
  693. """Parse .config file and return the architecture.
  694. Returns:
  695. Architecture name (e.g. 'arm').
  696. """
  697. arch = ''
  698. cpu = ''
  699. for line in open(self.dotconfig):
  700. m = self.re_arch.match(line)
  701. if m:
  702. arch = m.group(1)
  703. continue
  704. m = self.re_cpu.match(line)
  705. if m:
  706. cpu = m.group(1)
  707. if not arch:
  708. return None
  709. # fix-up for aarch64
  710. if arch == 'arm' and cpu == 'armv8':
  711. arch = 'aarch64'
  712. return arch
  713. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  714. """Parse .config, defconfig, include/autoconf.mk for one config.
  715. This function looks for the config options in the lines from
  716. defconfig, .config, and include/autoconf.mk in order to decide
  717. which action should be taken for this defconfig.
  718. Arguments:
  719. config: CONFIG name to parse.
  720. dotconfig_lines: lines from the .config file.
  721. autoconf_lines: lines from the include/autoconf.mk file.
  722. Returns:
  723. A tupple of the action for this defconfig and the line
  724. matched for the config.
  725. """
  726. not_set = '# %s is not set' % config
  727. for line in autoconf_lines:
  728. line = line.rstrip()
  729. if line.startswith(config + '='):
  730. new_val = line
  731. break
  732. else:
  733. new_val = not_set
  734. new_val = try_expand(new_val)
  735. for line in dotconfig_lines:
  736. line = line.rstrip()
  737. if line.startswith(config + '=') or line == not_set:
  738. old_val = line
  739. break
  740. else:
  741. if new_val == not_set:
  742. return (ACTION_NO_ENTRY, config)
  743. else:
  744. return (ACTION_NO_ENTRY_WARN, config)
  745. # If this CONFIG is neither bool nor trisate
  746. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  747. # tools/scripts/define2mk.sed changes '1' to 'y'.
  748. # This is a problem if the CONFIG is int type.
  749. # Check the type in Kconfig and handle it correctly.
  750. if new_val[-2:] == '=y':
  751. new_val = new_val[:-1] + '1'
  752. return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
  753. new_val)
  754. def update_dotconfig(self):
  755. """Parse files for the config options and update the .config.
  756. This function parses the generated .config and include/autoconf.mk
  757. searching the target options.
  758. Move the config option(s) to the .config as needed.
  759. Arguments:
  760. defconfig: defconfig name.
  761. Returns:
  762. Return a tuple of (updated flag, log string).
  763. The "updated flag" is True if the .config was updated, False
  764. otherwise. The "log string" shows what happend to the .config.
  765. """
  766. results = []
  767. updated = False
  768. suspicious = False
  769. rm_files = [self.config_autoconf, self.autoconf]
  770. if self.options.spl:
  771. if os.path.exists(self.spl_autoconf):
  772. autoconf_path = self.spl_autoconf
  773. rm_files.append(self.spl_autoconf)
  774. else:
  775. for f in rm_files:
  776. os.remove(f)
  777. return (updated, suspicious,
  778. color_text(self.options.color, COLOR_BROWN,
  779. "SPL is not enabled. Skipped.") + '\n')
  780. else:
  781. autoconf_path = self.autoconf
  782. with open(self.dotconfig) as f:
  783. dotconfig_lines = f.readlines()
  784. with open(autoconf_path) as f:
  785. autoconf_lines = f.readlines()
  786. for config in self.configs:
  787. result = self.parse_one_config(config, dotconfig_lines,
  788. autoconf_lines)
  789. results.append(result)
  790. log = ''
  791. for (action, value) in results:
  792. if action == ACTION_MOVE:
  793. actlog = "Move '%s'" % value
  794. log_color = COLOR_LIGHT_GREEN
  795. elif action == ACTION_NO_ENTRY:
  796. actlog = "%s is not defined in Kconfig. Do nothing." % value
  797. log_color = COLOR_LIGHT_BLUE
  798. elif action == ACTION_NO_ENTRY_WARN:
  799. actlog = "%s is not defined in Kconfig (suspicious). Do nothing." % value
  800. log_color = COLOR_YELLOW
  801. suspicious = True
  802. elif action == ACTION_NO_CHANGE:
  803. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  804. % value
  805. log_color = COLOR_LIGHT_PURPLE
  806. elif action == ACTION_SPL_NOT_EXIST:
  807. actlog = "SPL is not enabled for this defconfig. Skip."
  808. log_color = COLOR_PURPLE
  809. else:
  810. sys.exit("Internal Error. This should not happen.")
  811. log += color_text(self.options.color, log_color, actlog) + '\n'
  812. with open(self.dotconfig, 'a') as f:
  813. for (action, value) in results:
  814. if action == ACTION_MOVE:
  815. f.write(value + '\n')
  816. updated = True
  817. self.results = results
  818. for f in rm_files:
  819. os.remove(f)
  820. return (updated, suspicious, log)
  821. def check_defconfig(self):
  822. """Check the defconfig after savedefconfig
  823. Returns:
  824. Return additional log if moved CONFIGs were removed again by
  825. 'make savedefconfig'.
  826. """
  827. log = ''
  828. with open(self.defconfig) as f:
  829. defconfig_lines = f.readlines()
  830. for (action, value) in self.results:
  831. if action != ACTION_MOVE:
  832. continue
  833. if not value + '\n' in defconfig_lines:
  834. log += color_text(self.options.color, COLOR_YELLOW,
  835. "'%s' was removed by savedefconfig.\n" %
  836. value)
  837. return log
  838. class DatabaseThread(threading.Thread):
  839. """This thread processes results from Slot threads.
  840. It collects the data in the master config directary. There is only one
  841. result thread, and this helps to serialise the build output.
  842. """
  843. def __init__(self, config_db, db_queue):
  844. """Set up a new result thread
  845. Args:
  846. builder: Builder which will be sent each result
  847. """
  848. threading.Thread.__init__(self)
  849. self.config_db = config_db
  850. self.db_queue= db_queue
  851. def run(self):
  852. """Called to start up the result thread.
  853. We collect the next result job and pass it on to the build.
  854. """
  855. while True:
  856. defconfig, configs = self.db_queue.get()
  857. self.config_db[defconfig] = configs
  858. self.db_queue.task_done()
  859. class Slot:
  860. """A slot to store a subprocess.
  861. Each instance of this class handles one subprocess.
  862. This class is useful to control multiple threads
  863. for faster processing.
  864. """
  865. def __init__(self, toolchains, configs, options, progress, devnull,
  866. make_cmd, reference_src_dir, db_queue):
  867. """Create a new process slot.
  868. Arguments:
  869. toolchains: Toolchains object containing toolchains.
  870. configs: A list of CONFIGs to move.
  871. options: option flags.
  872. progress: A progress indicator.
  873. devnull: A file object of '/dev/null'.
  874. make_cmd: command name of GNU Make.
  875. reference_src_dir: Determine the true starting config state from this
  876. source tree.
  877. db_queue: output queue to write config info for the database
  878. """
  879. self.toolchains = toolchains
  880. self.options = options
  881. self.progress = progress
  882. self.build_dir = tempfile.mkdtemp()
  883. self.devnull = devnull
  884. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  885. self.reference_src_dir = reference_src_dir
  886. self.db_queue = db_queue
  887. self.parser = KconfigParser(configs, options, self.build_dir)
  888. self.state = STATE_IDLE
  889. self.failed_boards = set()
  890. self.suspicious_boards = set()
  891. def __del__(self):
  892. """Delete the working directory
  893. This function makes sure the temporary directory is cleaned away
  894. even if Python suddenly dies due to error. It should be done in here
  895. because it is guaranteed the destructor is always invoked when the
  896. instance of the class gets unreferenced.
  897. If the subprocess is still running, wait until it finishes.
  898. """
  899. if self.state != STATE_IDLE:
  900. while self.ps.poll() == None:
  901. pass
  902. shutil.rmtree(self.build_dir)
  903. def add(self, defconfig):
  904. """Assign a new subprocess for defconfig and add it to the slot.
  905. If the slot is vacant, create a new subprocess for processing the
  906. given defconfig and add it to the slot. Just returns False if
  907. the slot is occupied (i.e. the current subprocess is still running).
  908. Arguments:
  909. defconfig: defconfig name.
  910. Returns:
  911. Return True on success or False on failure
  912. """
  913. if self.state != STATE_IDLE:
  914. return False
  915. self.defconfig = defconfig
  916. self.log = ''
  917. self.current_src_dir = self.reference_src_dir
  918. self.do_defconfig()
  919. return True
  920. def poll(self):
  921. """Check the status of the subprocess and handle it as needed.
  922. Returns True if the slot is vacant (i.e. in idle state).
  923. If the configuration is successfully finished, assign a new
  924. subprocess to build include/autoconf.mk.
  925. If include/autoconf.mk is generated, invoke the parser to
  926. parse the .config and the include/autoconf.mk, moving
  927. config options to the .config as needed.
  928. If the .config was updated, run "make savedefconfig" to sync
  929. it, update the original defconfig, and then set the slot back
  930. to the idle state.
  931. Returns:
  932. Return True if the subprocess is terminated, False otherwise
  933. """
  934. if self.state == STATE_IDLE:
  935. return True
  936. if self.ps.poll() == None:
  937. return False
  938. if self.ps.poll() != 0:
  939. self.handle_error()
  940. elif self.state == STATE_DEFCONFIG:
  941. if self.reference_src_dir and not self.current_src_dir:
  942. self.do_savedefconfig()
  943. else:
  944. self.do_autoconf()
  945. elif self.state == STATE_AUTOCONF:
  946. if self.current_src_dir:
  947. self.current_src_dir = None
  948. self.do_defconfig()
  949. elif self.options.build_db:
  950. self.do_build_db()
  951. else:
  952. self.do_savedefconfig()
  953. elif self.state == STATE_SAVEDEFCONFIG:
  954. self.update_defconfig()
  955. else:
  956. sys.exit("Internal Error. This should not happen.")
  957. return True if self.state == STATE_IDLE else False
  958. def handle_error(self):
  959. """Handle error cases."""
  960. self.log += color_text(self.options.color, COLOR_LIGHT_RED,
  961. "Failed to process.\n")
  962. if self.options.verbose:
  963. self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
  964. self.ps.stderr.read())
  965. self.finish(False)
  966. def do_defconfig(self):
  967. """Run 'make <board>_defconfig' to create the .config file."""
  968. cmd = list(self.make_cmd)
  969. cmd.append(self.defconfig)
  970. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  971. stderr=subprocess.PIPE,
  972. cwd=self.current_src_dir)
  973. self.state = STATE_DEFCONFIG
  974. def do_autoconf(self):
  975. """Run 'make AUTO_CONF_PATH'."""
  976. arch = self.parser.get_arch()
  977. try:
  978. toolchain = self.toolchains.Select(arch)
  979. except ValueError:
  980. self.log += color_text(self.options.color, COLOR_YELLOW,
  981. "Tool chain for '%s' is missing. Do nothing.\n" % arch)
  982. self.finish(False)
  983. return
  984. env = toolchain.MakeEnvironment(False)
  985. cmd = list(self.make_cmd)
  986. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  987. cmd.append(AUTO_CONF_PATH)
  988. self.ps = subprocess.Popen(cmd, stdout=self.devnull, env=env,
  989. stderr=subprocess.PIPE,
  990. cwd=self.current_src_dir)
  991. self.state = STATE_AUTOCONF
  992. def do_build_db(self):
  993. """Add the board to the database"""
  994. configs = {}
  995. with open(os.path.join(self.build_dir, AUTO_CONF_PATH)) as fd:
  996. for line in fd.readlines():
  997. if line.startswith('CONFIG'):
  998. config, value = line.split('=', 1)
  999. configs[config] = value.rstrip()
  1000. self.db_queue.put([self.defconfig, configs])
  1001. self.finish(True)
  1002. def do_savedefconfig(self):
  1003. """Update the .config and run 'make savedefconfig'."""
  1004. (updated, suspicious, log) = self.parser.update_dotconfig()
  1005. if suspicious:
  1006. self.suspicious_boards.add(self.defconfig)
  1007. self.log += log
  1008. if not self.options.force_sync and not updated:
  1009. self.finish(True)
  1010. return
  1011. if updated:
  1012. self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
  1013. "Syncing by savedefconfig...\n")
  1014. else:
  1015. self.log += "Syncing by savedefconfig (forced by option)...\n"
  1016. cmd = list(self.make_cmd)
  1017. cmd.append('savedefconfig')
  1018. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  1019. stderr=subprocess.PIPE)
  1020. self.state = STATE_SAVEDEFCONFIG
  1021. def update_defconfig(self):
  1022. """Update the input defconfig and go back to the idle state."""
  1023. log = self.parser.check_defconfig()
  1024. if log:
  1025. self.suspicious_boards.add(self.defconfig)
  1026. self.log += log
  1027. orig_defconfig = os.path.join('configs', self.defconfig)
  1028. new_defconfig = os.path.join(self.build_dir, 'defconfig')
  1029. updated = not filecmp.cmp(orig_defconfig, new_defconfig)
  1030. if updated:
  1031. self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
  1032. "defconfig was updated.\n")
  1033. if not self.options.dry_run and updated:
  1034. shutil.move(new_defconfig, orig_defconfig)
  1035. self.finish(True)
  1036. def finish(self, success):
  1037. """Display log along with progress and go to the idle state.
  1038. Arguments:
  1039. success: Should be True when the defconfig was processed
  1040. successfully, or False when it fails.
  1041. """
  1042. # output at least 30 characters to hide the "* defconfigs out of *".
  1043. log = self.defconfig.ljust(30) + '\n'
  1044. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  1045. # Some threads are running in parallel.
  1046. # Print log atomically to not mix up logs from different threads.
  1047. print(log, file=(sys.stdout if success else sys.stderr))
  1048. if not success:
  1049. if self.options.exit_on_error:
  1050. sys.exit("Exit on error.")
  1051. # If --exit-on-error flag is not set, skip this board and continue.
  1052. # Record the failed board.
  1053. self.failed_boards.add(self.defconfig)
  1054. self.progress.inc()
  1055. self.progress.show()
  1056. self.state = STATE_IDLE
  1057. def get_failed_boards(self):
  1058. """Returns a set of failed boards (defconfigs) in this slot.
  1059. """
  1060. return self.failed_boards
  1061. def get_suspicious_boards(self):
  1062. """Returns a set of boards (defconfigs) with possible misconversion.
  1063. """
  1064. return self.suspicious_boards - self.failed_boards
  1065. class Slots:
  1066. """Controller of the array of subprocess slots."""
  1067. def __init__(self, toolchains, configs, options, progress,
  1068. reference_src_dir, db_queue):
  1069. """Create a new slots controller.
  1070. Arguments:
  1071. toolchains: Toolchains object containing toolchains.
  1072. configs: A list of CONFIGs to move.
  1073. options: option flags.
  1074. progress: A progress indicator.
  1075. reference_src_dir: Determine the true starting config state from this
  1076. source tree.
  1077. db_queue: output queue to write config info for the database
  1078. """
  1079. self.options = options
  1080. self.slots = []
  1081. devnull = get_devnull()
  1082. make_cmd = get_make_cmd()
  1083. for i in range(options.jobs):
  1084. self.slots.append(Slot(toolchains, configs, options, progress,
  1085. devnull, make_cmd, reference_src_dir,
  1086. db_queue))
  1087. def add(self, defconfig):
  1088. """Add a new subprocess if a vacant slot is found.
  1089. Arguments:
  1090. defconfig: defconfig name to be put into.
  1091. Returns:
  1092. Return True on success or False on failure
  1093. """
  1094. for slot in self.slots:
  1095. if slot.add(defconfig):
  1096. return True
  1097. return False
  1098. def available(self):
  1099. """Check if there is a vacant slot.
  1100. Returns:
  1101. Return True if at lease one vacant slot is found, False otherwise.
  1102. """
  1103. for slot in self.slots:
  1104. if slot.poll():
  1105. return True
  1106. return False
  1107. def empty(self):
  1108. """Check if all slots are vacant.
  1109. Returns:
  1110. Return True if all the slots are vacant, False otherwise.
  1111. """
  1112. ret = True
  1113. for slot in self.slots:
  1114. if not slot.poll():
  1115. ret = False
  1116. return ret
  1117. def show_failed_boards(self):
  1118. """Display all of the failed boards (defconfigs)."""
  1119. boards = set()
  1120. output_file = 'moveconfig.failed'
  1121. for slot in self.slots:
  1122. boards |= slot.get_failed_boards()
  1123. if boards:
  1124. boards = '\n'.join(boards) + '\n'
  1125. msg = "The following boards were not processed due to error:\n"
  1126. msg += boards
  1127. msg += "(the list has been saved in %s)\n" % output_file
  1128. print(color_text(self.options.color, COLOR_LIGHT_RED,
  1129. msg), file=sys.stderr)
  1130. with open(output_file, 'w') as f:
  1131. f.write(boards)
  1132. def show_suspicious_boards(self):
  1133. """Display all boards (defconfigs) with possible misconversion."""
  1134. boards = set()
  1135. output_file = 'moveconfig.suspicious'
  1136. for slot in self.slots:
  1137. boards |= slot.get_suspicious_boards()
  1138. if boards:
  1139. boards = '\n'.join(boards) + '\n'
  1140. msg = "The following boards might have been converted incorrectly.\n"
  1141. msg += "It is highly recommended to check them manually:\n"
  1142. msg += boards
  1143. msg += "(the list has been saved in %s)\n" % output_file
  1144. print(color_text(self.options.color, COLOR_YELLOW,
  1145. msg), file=sys.stderr)
  1146. with open(output_file, 'w') as f:
  1147. f.write(boards)
  1148. class ReferenceSource:
  1149. """Reference source against which original configs should be parsed."""
  1150. def __init__(self, commit):
  1151. """Create a reference source directory based on a specified commit.
  1152. Arguments:
  1153. commit: commit to git-clone
  1154. """
  1155. self.src_dir = tempfile.mkdtemp()
  1156. print("Cloning git repo to a separate work directory...")
  1157. subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
  1158. cwd=self.src_dir)
  1159. print("Checkout '%s' to build the original autoconf.mk." % \
  1160. subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip())
  1161. subprocess.check_output(['git', 'checkout', commit],
  1162. stderr=subprocess.STDOUT, cwd=self.src_dir)
  1163. def __del__(self):
  1164. """Delete the reference source directory
  1165. This function makes sure the temporary directory is cleaned away
  1166. even if Python suddenly dies due to error. It should be done in here
  1167. because it is guaranteed the destructor is always invoked when the
  1168. instance of the class gets unreferenced.
  1169. """
  1170. shutil.rmtree(self.src_dir)
  1171. def get_dir(self):
  1172. """Return the absolute path to the reference source directory."""
  1173. return self.src_dir
  1174. def move_config(toolchains, configs, options, db_queue):
  1175. """Move config options to defconfig files.
  1176. Arguments:
  1177. configs: A list of CONFIGs to move.
  1178. options: option flags
  1179. """
  1180. if len(configs) == 0:
  1181. if options.force_sync:
  1182. print('No CONFIG is specified. You are probably syncing defconfigs.', end=' ')
  1183. elif options.build_db:
  1184. print('Building %s database' % CONFIG_DATABASE)
  1185. else:
  1186. print('Neither CONFIG nor --force-sync is specified. Nothing will happen.', end=' ')
  1187. else:
  1188. print('Move ' + ', '.join(configs), end=' ')
  1189. print('(jobs: %d)\n' % options.jobs)
  1190. if options.git_ref:
  1191. reference_src = ReferenceSource(options.git_ref)
  1192. reference_src_dir = reference_src.get_dir()
  1193. else:
  1194. reference_src_dir = None
  1195. if options.defconfigs:
  1196. defconfigs = get_matched_defconfigs(options.defconfigs)
  1197. else:
  1198. defconfigs = get_all_defconfigs()
  1199. progress = Progress(len(defconfigs))
  1200. slots = Slots(toolchains, configs, options, progress, reference_src_dir,
  1201. db_queue)
  1202. # Main loop to process defconfig files:
  1203. # Add a new subprocess into a vacant slot.
  1204. # Sleep if there is no available slot.
  1205. for defconfig in defconfigs:
  1206. while not slots.add(defconfig):
  1207. while not slots.available():
  1208. # No available slot: sleep for a while
  1209. time.sleep(SLEEP_TIME)
  1210. # wait until all the subprocesses finish
  1211. while not slots.empty():
  1212. time.sleep(SLEEP_TIME)
  1213. print('')
  1214. slots.show_failed_boards()
  1215. slots.show_suspicious_boards()
  1216. def find_kconfig_rules(kconf, config, imply_config):
  1217. """Check whether a config has a 'select' or 'imply' keyword
  1218. Args:
  1219. kconf: Kconfiglib.Kconfig object
  1220. config: Name of config to check (without CONFIG_ prefix)
  1221. imply_config: Implying config (without CONFIG_ prefix) which may or
  1222. may not have an 'imply' for 'config')
  1223. Returns:
  1224. Symbol object for 'config' if found, else None
  1225. """
  1226. sym = kconf.syms.get(imply_config)
  1227. if sym:
  1228. for sel in sym.get_selected_symbols() | sym.get_implied_symbols():
  1229. if sel.get_name() == config:
  1230. return sym
  1231. return None
  1232. def check_imply_rule(kconf, config, imply_config):
  1233. """Check if we can add an 'imply' option
  1234. This finds imply_config in the Kconfig and looks to see if it is possible
  1235. to add an 'imply' for 'config' to that part of the Kconfig.
  1236. Args:
  1237. kconf: Kconfiglib.Kconfig object
  1238. config: Name of config to check (without CONFIG_ prefix)
  1239. imply_config: Implying config (without CONFIG_ prefix) which may or
  1240. may not have an 'imply' for 'config')
  1241. Returns:
  1242. tuple:
  1243. filename of Kconfig file containing imply_config, or None if none
  1244. line number within the Kconfig file, or 0 if none
  1245. message indicating the result
  1246. """
  1247. sym = kconf.syms.get(imply_config)
  1248. if not sym:
  1249. return 'cannot find sym'
  1250. locs = sym.get_def_locations()
  1251. if len(locs) != 1:
  1252. return '%d locations' % len(locs)
  1253. fname, linenum = locs[0]
  1254. cwd = os.getcwd()
  1255. if cwd and fname.startswith(cwd):
  1256. fname = fname[len(cwd) + 1:]
  1257. file_line = ' at %s:%d' % (fname, linenum)
  1258. with open(fname) as fd:
  1259. data = fd.read().splitlines()
  1260. if data[linenum - 1] != 'config %s' % imply_config:
  1261. return None, 0, 'bad sym format %s%s' % (data[linenum], file_line)
  1262. return fname, linenum, 'adding%s' % file_line
  1263. def add_imply_rule(config, fname, linenum):
  1264. """Add a new 'imply' option to a Kconfig
  1265. Args:
  1266. config: config option to add an imply for (without CONFIG_ prefix)
  1267. fname: Kconfig filename to update
  1268. linenum: Line number to place the 'imply' before
  1269. Returns:
  1270. Message indicating the result
  1271. """
  1272. file_line = ' at %s:%d' % (fname, linenum)
  1273. data = open(fname).read().splitlines()
  1274. linenum -= 1
  1275. for offset, line in enumerate(data[linenum:]):
  1276. if line.strip().startswith('help') or not line:
  1277. data.insert(linenum + offset, '\timply %s' % config)
  1278. with open(fname, 'w') as fd:
  1279. fd.write('\n'.join(data) + '\n')
  1280. return 'added%s' % file_line
  1281. return 'could not insert%s'
  1282. (IMPLY_MIN_2, IMPLY_TARGET, IMPLY_CMD, IMPLY_NON_ARCH_BOARD) = (
  1283. 1, 2, 4, 8)
  1284. IMPLY_FLAGS = {
  1285. 'min2': [IMPLY_MIN_2, 'Show options which imply >2 boards (normally >5)'],
  1286. 'target': [IMPLY_TARGET, 'Allow CONFIG_TARGET_... options to imply'],
  1287. 'cmd': [IMPLY_CMD, 'Allow CONFIG_CMD_... to imply'],
  1288. 'non-arch-board': [
  1289. IMPLY_NON_ARCH_BOARD,
  1290. 'Allow Kconfig options outside arch/ and /board/ to imply'],
  1291. };
  1292. def do_imply_config(config_list, add_imply, imply_flags, skip_added,
  1293. check_kconfig=True, find_superset=False):
  1294. """Find CONFIG options which imply those in the list
  1295. Some CONFIG options can be implied by others and this can help to reduce
  1296. the size of the defconfig files. For example, CONFIG_X86 implies
  1297. CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
  1298. all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
  1299. each of the x86 defconfig files.
  1300. This function uses the moveconfig database to find such options. It
  1301. displays a list of things that could possibly imply those in the list.
  1302. The algorithm ignores any that start with CONFIG_TARGET since these
  1303. typically refer to only a few defconfigs (often one). It also does not
  1304. display a config with less than 5 defconfigs.
  1305. The algorithm works using sets. For each target config in config_list:
  1306. - Get the set 'defconfigs' which use that target config
  1307. - For each config (from a list of all configs):
  1308. - Get the set 'imply_defconfig' of defconfigs which use that config
  1309. -
  1310. - If imply_defconfigs contains anything not in defconfigs then
  1311. this config does not imply the target config
  1312. Params:
  1313. config_list: List of CONFIG options to check (each a string)
  1314. add_imply: Automatically add an 'imply' for each config.
  1315. imply_flags: Flags which control which implying configs are allowed
  1316. (IMPLY_...)
  1317. skip_added: Don't show options which already have an imply added.
  1318. check_kconfig: Check if implied symbols already have an 'imply' or
  1319. 'select' for the target config, and show this information if so.
  1320. find_superset: True to look for configs which are a superset of those
  1321. already found. So for example if CONFIG_EXYNOS5 implies an option,
  1322. but CONFIG_EXYNOS covers a larger set of defconfigs and also
  1323. implies that option, this will drop the former in favour of the
  1324. latter. In practice this option has not proved very used.
  1325. Note the terminoloy:
  1326. config - a CONFIG_XXX options (a string, e.g. 'CONFIG_CMD_EEPROM')
  1327. defconfig - a defconfig file (a string, e.g. 'configs/snow_defconfig')
  1328. """
  1329. kconf = KconfigScanner().conf if check_kconfig else None
  1330. if add_imply and add_imply != 'all':
  1331. add_imply = add_imply.split()
  1332. # key is defconfig name, value is dict of (CONFIG_xxx, value)
  1333. config_db = {}
  1334. # Holds a dict containing the set of defconfigs that contain each config
  1335. # key is config, value is set of defconfigs using that config
  1336. defconfig_db = collections.defaultdict(set)
  1337. # Set of all config options we have seen
  1338. all_configs = set()
  1339. # Set of all defconfigs we have seen
  1340. all_defconfigs = set()
  1341. # Read in the database
  1342. configs = {}
  1343. with open(CONFIG_DATABASE) as fd:
  1344. for line in fd.readlines():
  1345. line = line.rstrip()
  1346. if not line: # Separator between defconfigs
  1347. config_db[defconfig] = configs
  1348. all_defconfigs.add(defconfig)
  1349. configs = {}
  1350. elif line[0] == ' ': # CONFIG line
  1351. config, value = line.strip().split('=', 1)
  1352. configs[config] = value
  1353. defconfig_db[config].add(defconfig)
  1354. all_configs.add(config)
  1355. else: # New defconfig
  1356. defconfig = line
  1357. # Work through each target config option in tern, independently
  1358. for config in config_list:
  1359. defconfigs = defconfig_db.get(config)
  1360. if not defconfigs:
  1361. print('%s not found in any defconfig' % config)
  1362. continue
  1363. # Get the set of defconfigs without this one (since a config cannot
  1364. # imply itself)
  1365. non_defconfigs = all_defconfigs - defconfigs
  1366. num_defconfigs = len(defconfigs)
  1367. print('%s found in %d/%d defconfigs' % (config, num_defconfigs,
  1368. len(all_configs)))
  1369. # This will hold the results: key=config, value=defconfigs containing it
  1370. imply_configs = {}
  1371. rest_configs = all_configs - set([config])
  1372. # Look at every possible config, except the target one
  1373. for imply_config in rest_configs:
  1374. if 'ERRATUM' in imply_config:
  1375. continue
  1376. if not (imply_flags & IMPLY_CMD):
  1377. if 'CONFIG_CMD' in imply_config:
  1378. continue
  1379. if not (imply_flags & IMPLY_TARGET):
  1380. if 'CONFIG_TARGET' in imply_config:
  1381. continue
  1382. # Find set of defconfigs that have this config
  1383. imply_defconfig = defconfig_db[imply_config]
  1384. # Get the intersection of this with defconfigs containing the
  1385. # target config
  1386. common_defconfigs = imply_defconfig & defconfigs
  1387. # Get the set of defconfigs containing this config which DO NOT
  1388. # also contain the taret config. If this set is non-empty it means
  1389. # that this config affects other defconfigs as well as (possibly)
  1390. # the ones affected by the target config. This means it implies
  1391. # things we don't want to imply.
  1392. not_common_defconfigs = imply_defconfig & non_defconfigs
  1393. if not_common_defconfigs:
  1394. continue
  1395. # If there are common defconfigs, imply_config may be useful
  1396. if common_defconfigs:
  1397. skip = False
  1398. if find_superset:
  1399. for prev in list(imply_configs.keys()):
  1400. prev_count = len(imply_configs[prev])
  1401. count = len(common_defconfigs)
  1402. if (prev_count > count and
  1403. (imply_configs[prev] & common_defconfigs ==
  1404. common_defconfigs)):
  1405. # skip imply_config because prev is a superset
  1406. skip = True
  1407. break
  1408. elif count > prev_count:
  1409. # delete prev because imply_config is a superset
  1410. del imply_configs[prev]
  1411. if not skip:
  1412. imply_configs[imply_config] = common_defconfigs
  1413. # Now we have a dict imply_configs of configs which imply each config
  1414. # The value of each dict item is the set of defconfigs containing that
  1415. # config. Rank them so that we print the configs that imply the largest
  1416. # number of defconfigs first.
  1417. ranked_iconfigs = sorted(imply_configs,
  1418. key=lambda k: len(imply_configs[k]), reverse=True)
  1419. kconfig_info = ''
  1420. cwd = os.getcwd()
  1421. add_list = collections.defaultdict(list)
  1422. for iconfig in ranked_iconfigs:
  1423. num_common = len(imply_configs[iconfig])
  1424. # Don't bother if there are less than 5 defconfigs affected.
  1425. if num_common < (2 if imply_flags & IMPLY_MIN_2 else 5):
  1426. continue
  1427. missing = defconfigs - imply_configs[iconfig]
  1428. missing_str = ', '.join(missing) if missing else 'all'
  1429. missing_str = ''
  1430. show = True
  1431. if kconf:
  1432. sym = find_kconfig_rules(kconf, config[CONFIG_LEN:],
  1433. iconfig[CONFIG_LEN:])
  1434. kconfig_info = ''
  1435. if sym:
  1436. locs = sym.get_def_locations()
  1437. if len(locs) == 1:
  1438. fname, linenum = locs[0]
  1439. if cwd and fname.startswith(cwd):
  1440. fname = fname[len(cwd) + 1:]
  1441. kconfig_info = '%s:%d' % (fname, linenum)
  1442. if skip_added:
  1443. show = False
  1444. else:
  1445. sym = kconf.syms.get(iconfig[CONFIG_LEN:])
  1446. fname = ''
  1447. if sym:
  1448. locs = sym.get_def_locations()
  1449. if len(locs) == 1:
  1450. fname, linenum = locs[0]
  1451. if cwd and fname.startswith(cwd):
  1452. fname = fname[len(cwd) + 1:]
  1453. in_arch_board = not sym or (fname.startswith('arch') or
  1454. fname.startswith('board'))
  1455. if (not in_arch_board and
  1456. not (imply_flags & IMPLY_NON_ARCH_BOARD)):
  1457. continue
  1458. if add_imply and (add_imply == 'all' or
  1459. iconfig in add_imply):
  1460. fname, linenum, kconfig_info = (check_imply_rule(kconf,
  1461. config[CONFIG_LEN:], iconfig[CONFIG_LEN:]))
  1462. if fname:
  1463. add_list[fname].append(linenum)
  1464. if show and kconfig_info != 'skip':
  1465. print('%5d : %-30s%-25s %s' % (num_common, iconfig.ljust(30),
  1466. kconfig_info, missing_str))
  1467. # Having collected a list of things to add, now we add them. We process
  1468. # each file from the largest line number to the smallest so that
  1469. # earlier additions do not affect our line numbers. E.g. if we added an
  1470. # imply at line 20 it would change the position of each line after
  1471. # that.
  1472. for fname, linenums in add_list.items():
  1473. for linenum in sorted(linenums, reverse=True):
  1474. add_imply_rule(config[CONFIG_LEN:], fname, linenum)
  1475. def main():
  1476. try:
  1477. cpu_count = multiprocessing.cpu_count()
  1478. except NotImplementedError:
  1479. cpu_count = 1
  1480. parser = optparse.OptionParser()
  1481. # Add options here
  1482. parser.add_option('-a', '--add-imply', type='string', default='',
  1483. help='comma-separated list of CONFIG options to add '
  1484. "an 'imply' statement to for the CONFIG in -i")
  1485. parser.add_option('-A', '--skip-added', action='store_true', default=False,
  1486. help="don't show options which are already marked as "
  1487. 'implying others')
  1488. parser.add_option('-b', '--build-db', action='store_true', default=False,
  1489. help='build a CONFIG database')
  1490. parser.add_option('-c', '--color', action='store_true', default=False,
  1491. help='display the log in color')
  1492. parser.add_option('-C', '--commit', action='store_true', default=False,
  1493. help='Create a git commit for the operation')
  1494. parser.add_option('-d', '--defconfigs', type='string',
  1495. help='a file containing a list of defconfigs to move, '
  1496. "one per line (for example 'snow_defconfig') "
  1497. "or '-' to read from stdin")
  1498. parser.add_option('-i', '--imply', action='store_true', default=False,
  1499. help='find options which imply others')
  1500. parser.add_option('-I', '--imply-flags', type='string', default='',
  1501. help="control the -i option ('help' for help")
  1502. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  1503. help='perform a trial run (show log with no changes)')
  1504. parser.add_option('-e', '--exit-on-error', action='store_true',
  1505. default=False,
  1506. help='exit immediately on any error')
  1507. parser.add_option('-s', '--force-sync', action='store_true', default=False,
  1508. help='force sync by savedefconfig')
  1509. parser.add_option('-S', '--spl', action='store_true', default=False,
  1510. help='parse config options defined for SPL build')
  1511. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  1512. action='store_true', default=False,
  1513. help='only cleanup the headers')
  1514. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  1515. help='the number of jobs to run simultaneously')
  1516. parser.add_option('-r', '--git-ref', type='string',
  1517. help='the git ref to clone for building the autoconf.mk')
  1518. parser.add_option('-y', '--yes', action='store_true', default=False,
  1519. help="respond 'yes' to any prompts")
  1520. parser.add_option('-v', '--verbose', action='store_true', default=False,
  1521. help='show any build errors as boards are built')
  1522. parser.usage += ' CONFIG ...'
  1523. (options, configs) = parser.parse_args()
  1524. if len(configs) == 0 and not any((options.force_sync, options.build_db,
  1525. options.imply)):
  1526. parser.print_usage()
  1527. sys.exit(1)
  1528. # prefix the option name with CONFIG_ if missing
  1529. configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
  1530. for config in configs ]
  1531. check_top_directory()
  1532. if options.imply:
  1533. imply_flags = 0
  1534. if options.imply_flags == 'all':
  1535. imply_flags = -1
  1536. elif options.imply_flags:
  1537. for flag in options.imply_flags.split(','):
  1538. bad = flag not in IMPLY_FLAGS
  1539. if bad:
  1540. print("Invalid flag '%s'" % flag)
  1541. if flag == 'help' or bad:
  1542. print("Imply flags: (separate with ',')")
  1543. for name, info in IMPLY_FLAGS.items():
  1544. print(' %-15s: %s' % (name, info[1]))
  1545. parser.print_usage()
  1546. sys.exit(1)
  1547. imply_flags |= IMPLY_FLAGS[flag][0]
  1548. do_imply_config(configs, options.add_imply, imply_flags,
  1549. options.skip_added)
  1550. return
  1551. config_db = {}
  1552. db_queue = queue.Queue()
  1553. t = DatabaseThread(config_db, db_queue)
  1554. t.setDaemon(True)
  1555. t.start()
  1556. if not options.cleanup_headers_only:
  1557. check_clean_directory()
  1558. bsettings.Setup('')
  1559. toolchains = toolchain.Toolchains()
  1560. toolchains.GetSettings()
  1561. toolchains.Scan(verbose=False)
  1562. move_config(toolchains, configs, options, db_queue)
  1563. db_queue.join()
  1564. if configs:
  1565. cleanup_headers(configs, options)
  1566. cleanup_extra_options(configs, options)
  1567. cleanup_whitelist(configs, options)
  1568. cleanup_readme(configs, options)
  1569. if options.commit:
  1570. subprocess.call(['git', 'add', '-u'])
  1571. if configs:
  1572. msg = 'Convert %s %sto Kconfig' % (configs[0],
  1573. 'et al ' if len(configs) > 1 else '')
  1574. msg += ('\n\nThis converts the following to Kconfig:\n %s\n' %
  1575. '\n '.join(configs))
  1576. else:
  1577. msg = 'configs: Resync with savedefconfig'
  1578. msg += '\n\nRsync all defconfig files using moveconfig.py'
  1579. subprocess.call(['git', 'commit', '-s', '-m', msg])
  1580. if options.build_db:
  1581. with open(CONFIG_DATABASE, 'w') as fd:
  1582. for defconfig, configs in config_db.items():
  1583. fd.write('%s\n' % defconfig)
  1584. for config in sorted(configs.keys()):
  1585. fd.write(' %s=%s\n' % (config, configs[config]))
  1586. fd.write('\n')
  1587. if __name__ == '__main__':
  1588. main()