moveconfig.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953
  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 asteval
  220. import collections
  221. import copy
  222. import difflib
  223. import filecmp
  224. import fnmatch
  225. import glob
  226. import multiprocessing
  227. import optparse
  228. import os
  229. import queue
  230. import re
  231. import shutil
  232. import subprocess
  233. import sys
  234. import tempfile
  235. import threading
  236. import time
  237. from buildman import bsettings
  238. from buildman import kconfiglib
  239. from buildman import toolchain
  240. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  241. SLEEP_TIME=0.03
  242. STATE_IDLE = 0
  243. STATE_DEFCONFIG = 1
  244. STATE_AUTOCONF = 2
  245. STATE_SAVEDEFCONFIG = 3
  246. ACTION_MOVE = 0
  247. ACTION_NO_ENTRY = 1
  248. ACTION_NO_ENTRY_WARN = 2
  249. ACTION_NO_CHANGE = 3
  250. COLOR_BLACK = '0;30'
  251. COLOR_RED = '0;31'
  252. COLOR_GREEN = '0;32'
  253. COLOR_BROWN = '0;33'
  254. COLOR_BLUE = '0;34'
  255. COLOR_PURPLE = '0;35'
  256. COLOR_CYAN = '0;36'
  257. COLOR_LIGHT_GRAY = '0;37'
  258. COLOR_DARK_GRAY = '1;30'
  259. COLOR_LIGHT_RED = '1;31'
  260. COLOR_LIGHT_GREEN = '1;32'
  261. COLOR_YELLOW = '1;33'
  262. COLOR_LIGHT_BLUE = '1;34'
  263. COLOR_LIGHT_PURPLE = '1;35'
  264. COLOR_LIGHT_CYAN = '1;36'
  265. COLOR_WHITE = '1;37'
  266. AUTO_CONF_PATH = 'include/config/auto.conf'
  267. CONFIG_DATABASE = 'moveconfig.db'
  268. CONFIG_LEN = len('CONFIG_')
  269. SIZES = {
  270. "SZ_1": 0x00000001, "SZ_2": 0x00000002,
  271. "SZ_4": 0x00000004, "SZ_8": 0x00000008,
  272. "SZ_16": 0x00000010, "SZ_32": 0x00000020,
  273. "SZ_64": 0x00000040, "SZ_128": 0x00000080,
  274. "SZ_256": 0x00000100, "SZ_512": 0x00000200,
  275. "SZ_1K": 0x00000400, "SZ_2K": 0x00000800,
  276. "SZ_4K": 0x00001000, "SZ_8K": 0x00002000,
  277. "SZ_16K": 0x00004000, "SZ_32K": 0x00008000,
  278. "SZ_64K": 0x00010000, "SZ_128K": 0x00020000,
  279. "SZ_256K": 0x00040000, "SZ_512K": 0x00080000,
  280. "SZ_1M": 0x00100000, "SZ_2M": 0x00200000,
  281. "SZ_4M": 0x00400000, "SZ_8M": 0x00800000,
  282. "SZ_16M": 0x01000000, "SZ_32M": 0x02000000,
  283. "SZ_64M": 0x04000000, "SZ_128M": 0x08000000,
  284. "SZ_256M": 0x10000000, "SZ_512M": 0x20000000,
  285. "SZ_1G": 0x40000000, "SZ_2G": 0x80000000,
  286. "SZ_4G": 0x100000000
  287. }
  288. ### helper functions ###
  289. def get_devnull():
  290. """Get the file object of '/dev/null' device."""
  291. try:
  292. devnull = subprocess.DEVNULL # py3k
  293. except AttributeError:
  294. devnull = open(os.devnull, 'wb')
  295. return devnull
  296. def check_top_directory():
  297. """Exit if we are not at the top of source directory."""
  298. for f in ('README', 'Licenses'):
  299. if not os.path.exists(f):
  300. sys.exit('Please run at the top of source directory.')
  301. def check_clean_directory():
  302. """Exit if the source tree is not clean."""
  303. for f in ('.config', 'include/config'):
  304. if os.path.exists(f):
  305. sys.exit("source tree is not clean, please run 'make mrproper'")
  306. def get_make_cmd():
  307. """Get the command name of GNU Make.
  308. U-Boot needs GNU Make for building, but the command name is not
  309. necessarily "make". (for example, "gmake" on FreeBSD).
  310. Returns the most appropriate command name on your system.
  311. """
  312. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  313. ret = process.communicate()
  314. if process.returncode:
  315. sys.exit('GNU Make not found')
  316. return ret[0].rstrip()
  317. def get_matched_defconfig(line):
  318. """Get the defconfig files that match a pattern
  319. Args:
  320. line: Path or filename to match, e.g. 'configs/snow_defconfig' or
  321. 'k2*_defconfig'. If no directory is provided, 'configs/' is
  322. prepended
  323. Returns:
  324. a list of matching defconfig files
  325. """
  326. dirname = os.path.dirname(line)
  327. if dirname:
  328. pattern = line
  329. else:
  330. pattern = os.path.join('configs', line)
  331. return glob.glob(pattern) + glob.glob(pattern + '_defconfig')
  332. def get_matched_defconfigs(defconfigs_file):
  333. """Get all the defconfig files that match the patterns in a file.
  334. Args:
  335. defconfigs_file: File containing a list of defconfigs to process, or
  336. '-' to read the list from stdin
  337. Returns:
  338. A list of paths to defconfig files, with no duplicates
  339. """
  340. defconfigs = []
  341. if defconfigs_file == '-':
  342. fd = sys.stdin
  343. defconfigs_file = 'stdin'
  344. else:
  345. fd = open(defconfigs_file)
  346. for i, line in enumerate(fd):
  347. line = line.strip()
  348. if not line:
  349. continue # skip blank lines silently
  350. if ' ' in line:
  351. line = line.split(' ')[0] # handle 'git log' input
  352. matched = get_matched_defconfig(line)
  353. if not matched:
  354. print("warning: %s:%d: no defconfig matched '%s'" % \
  355. (defconfigs_file, i + 1, line), file=sys.stderr)
  356. defconfigs += matched
  357. # use set() to drop multiple matching
  358. return [ defconfig[len('configs') + 1:] for defconfig in set(defconfigs) ]
  359. def get_all_defconfigs():
  360. """Get all the defconfig files under the configs/ directory."""
  361. defconfigs = []
  362. for (dirpath, dirnames, filenames) in os.walk('configs'):
  363. dirpath = dirpath[len('configs') + 1:]
  364. for filename in fnmatch.filter(filenames, '*_defconfig'):
  365. defconfigs.append(os.path.join(dirpath, filename))
  366. return defconfigs
  367. def color_text(color_enabled, color, string):
  368. """Return colored string."""
  369. if color_enabled:
  370. # LF should not be surrounded by the escape sequence.
  371. # Otherwise, additional whitespace or line-feed might be printed.
  372. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
  373. for s in string.split('\n') ])
  374. else:
  375. return string
  376. def show_diff(a, b, file_path, color_enabled):
  377. """Show unidified diff.
  378. Arguments:
  379. a: A list of lines (before)
  380. b: A list of lines (after)
  381. file_path: Path to the file
  382. color_enabled: Display the diff in color
  383. """
  384. diff = difflib.unified_diff(a, b,
  385. fromfile=os.path.join('a', file_path),
  386. tofile=os.path.join('b', file_path))
  387. for line in diff:
  388. if line[0] == '-' and line[1] != '-':
  389. print(color_text(color_enabled, COLOR_RED, line), end=' ')
  390. elif line[0] == '+' and line[1] != '+':
  391. print(color_text(color_enabled, COLOR_GREEN, line), end=' ')
  392. else:
  393. print(line, end=' ')
  394. def extend_matched_lines(lines, matched, pre_patterns, post_patterns, extend_pre,
  395. extend_post):
  396. """Extend matched lines if desired patterns are found before/after already
  397. matched lines.
  398. Arguments:
  399. lines: A list of lines handled.
  400. matched: A list of line numbers that have been already matched.
  401. (will be updated by this function)
  402. pre_patterns: A list of regular expression that should be matched as
  403. preamble.
  404. post_patterns: A list of regular expression that should be matched as
  405. postamble.
  406. extend_pre: Add the line number of matched preamble to the matched list.
  407. extend_post: Add the line number of matched postamble to the matched list.
  408. """
  409. extended_matched = []
  410. j = matched[0]
  411. for i in matched:
  412. if i == 0 or i < j:
  413. continue
  414. j = i
  415. while j in matched:
  416. j += 1
  417. if j >= len(lines):
  418. break
  419. for p in pre_patterns:
  420. if p.search(lines[i - 1]):
  421. break
  422. else:
  423. # not matched
  424. continue
  425. for p in post_patterns:
  426. if p.search(lines[j]):
  427. break
  428. else:
  429. # not matched
  430. continue
  431. if extend_pre:
  432. extended_matched.append(i - 1)
  433. if extend_post:
  434. extended_matched.append(j)
  435. matched += extended_matched
  436. matched.sort()
  437. def confirm(options, prompt):
  438. if not options.yes:
  439. while True:
  440. choice = input('{} [y/n]: '.format(prompt))
  441. choice = choice.lower()
  442. print(choice)
  443. if choice == 'y' or choice == 'n':
  444. break
  445. if choice == 'n':
  446. return False
  447. return True
  448. def cleanup_empty_blocks(header_path, options):
  449. """Clean up empty conditional blocks
  450. Arguments:
  451. header_path: path to the cleaned file.
  452. options: option flags.
  453. """
  454. pattern = re.compile(r'^\s*#\s*if.*$\n^\s*#\s*endif.*$\n*', flags=re.M)
  455. with open(header_path) as f:
  456. data = f.read()
  457. new_data = pattern.sub('\n', data)
  458. show_diff(data.splitlines(True), new_data.splitlines(True), header_path,
  459. options.color)
  460. if options.dry_run:
  461. return
  462. with open(header_path, 'w') as f:
  463. f.write(new_data)
  464. def cleanup_one_header(header_path, patterns, options):
  465. """Clean regex-matched lines away from a file.
  466. Arguments:
  467. header_path: path to the cleaned file.
  468. patterns: list of regex patterns. Any lines matching to these
  469. patterns are deleted.
  470. options: option flags.
  471. """
  472. with open(header_path) as f:
  473. lines = f.readlines()
  474. matched = []
  475. for i, line in enumerate(lines):
  476. if i - 1 in matched and lines[i - 1][-2:] == '\\\n':
  477. matched.append(i)
  478. continue
  479. for pattern in patterns:
  480. if pattern.search(line):
  481. matched.append(i)
  482. break
  483. if not matched:
  484. return
  485. # remove empty #ifdef ... #endif, successive blank lines
  486. pattern_if = re.compile(r'#\s*if(def|ndef)?\W') # #if, #ifdef, #ifndef
  487. pattern_elif = re.compile(r'#\s*el(if|se)\W') # #elif, #else
  488. pattern_endif = re.compile(r'#\s*endif\W') # #endif
  489. pattern_blank = re.compile(r'^\s*$') # empty line
  490. while True:
  491. old_matched = copy.copy(matched)
  492. extend_matched_lines(lines, matched, [pattern_if],
  493. [pattern_endif], True, True)
  494. extend_matched_lines(lines, matched, [pattern_elif],
  495. [pattern_elif, pattern_endif], True, False)
  496. extend_matched_lines(lines, matched, [pattern_if, pattern_elif],
  497. [pattern_blank], False, True)
  498. extend_matched_lines(lines, matched, [pattern_blank],
  499. [pattern_elif, pattern_endif], True, False)
  500. extend_matched_lines(lines, matched, [pattern_blank],
  501. [pattern_blank], True, False)
  502. if matched == old_matched:
  503. break
  504. tolines = copy.copy(lines)
  505. for i in reversed(matched):
  506. tolines.pop(i)
  507. show_diff(lines, tolines, header_path, options.color)
  508. if options.dry_run:
  509. return
  510. with open(header_path, 'w') as f:
  511. for line in tolines:
  512. f.write(line)
  513. def cleanup_headers(configs, options):
  514. """Delete config defines from board headers.
  515. Arguments:
  516. configs: A list of CONFIGs to remove.
  517. options: option flags.
  518. """
  519. if not confirm(options, 'Clean up headers?'):
  520. return
  521. patterns = []
  522. for config in configs:
  523. patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
  524. patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
  525. for dir in 'include', 'arch', 'board':
  526. for (dirpath, dirnames, filenames) in os.walk(dir):
  527. if dirpath == os.path.join('include', 'generated'):
  528. continue
  529. for filename in filenames:
  530. if not filename.endswith(('~', '.dts', '.dtsi', '.bin',
  531. '.elf')):
  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. aeval = asteval.Interpreter( usersyms=SIZES, minimal=True )
  639. cfg, val = re.split("=", line)
  640. val= val.strip('\"')
  641. if re.search("[*+-/]|<<|SZ_+|\(([^\)]+)\)", val):
  642. newval = hex(aeval(val))
  643. print("\tExpanded expression %s to %s" % (val, newval))
  644. return cfg+'='+newval
  645. except:
  646. print("\tFailed to expand expression in %s" % line)
  647. return line
  648. ### classes ###
  649. class Progress:
  650. """Progress Indicator"""
  651. def __init__(self, total):
  652. """Create a new progress indicator.
  653. Arguments:
  654. total: A number of defconfig files to process.
  655. """
  656. self.current = 0
  657. self.total = total
  658. def inc(self):
  659. """Increment the number of processed defconfig files."""
  660. self.current += 1
  661. def show(self):
  662. """Display the progress."""
  663. print(' %d defconfigs out of %d\r' % (self.current, self.total), end=' ')
  664. sys.stdout.flush()
  665. class KconfigScanner:
  666. """Kconfig scanner."""
  667. def __init__(self):
  668. """Scan all the Kconfig files and create a Config object."""
  669. # Define environment variables referenced from Kconfig
  670. os.environ['srctree'] = os.getcwd()
  671. os.environ['UBOOTVERSION'] = 'dummy'
  672. os.environ['KCONFIG_OBJDIR'] = ''
  673. self.conf = kconfiglib.Kconfig()
  674. class KconfigParser:
  675. """A parser of .config and include/autoconf.mk."""
  676. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  677. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  678. def __init__(self, configs, options, build_dir):
  679. """Create a new parser.
  680. Arguments:
  681. configs: A list of CONFIGs to move.
  682. options: option flags.
  683. build_dir: Build directory.
  684. """
  685. self.configs = configs
  686. self.options = options
  687. self.dotconfig = os.path.join(build_dir, '.config')
  688. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  689. self.spl_autoconf = os.path.join(build_dir, 'spl', 'include',
  690. 'autoconf.mk')
  691. self.config_autoconf = os.path.join(build_dir, AUTO_CONF_PATH)
  692. self.defconfig = os.path.join(build_dir, 'defconfig')
  693. def get_arch(self):
  694. """Parse .config file and return the architecture.
  695. Returns:
  696. Architecture name (e.g. 'arm').
  697. """
  698. arch = ''
  699. cpu = ''
  700. for line in open(self.dotconfig):
  701. m = self.re_arch.match(line)
  702. if m:
  703. arch = m.group(1)
  704. continue
  705. m = self.re_cpu.match(line)
  706. if m:
  707. cpu = m.group(1)
  708. if not arch:
  709. return None
  710. # fix-up for aarch64
  711. if arch == 'arm' and cpu == 'armv8':
  712. arch = 'aarch64'
  713. return arch
  714. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  715. """Parse .config, defconfig, include/autoconf.mk for one config.
  716. This function looks for the config options in the lines from
  717. defconfig, .config, and include/autoconf.mk in order to decide
  718. which action should be taken for this defconfig.
  719. Arguments:
  720. config: CONFIG name to parse.
  721. dotconfig_lines: lines from the .config file.
  722. autoconf_lines: lines from the include/autoconf.mk file.
  723. Returns:
  724. A tupple of the action for this defconfig and the line
  725. matched for the config.
  726. """
  727. not_set = '# %s is not set' % config
  728. for line in autoconf_lines:
  729. line = line.rstrip()
  730. if line.startswith(config + '='):
  731. new_val = line
  732. break
  733. else:
  734. new_val = not_set
  735. new_val = try_expand(new_val)
  736. for line in dotconfig_lines:
  737. line = line.rstrip()
  738. if line.startswith(config + '=') or line == not_set:
  739. old_val = line
  740. break
  741. else:
  742. if new_val == not_set:
  743. return (ACTION_NO_ENTRY, config)
  744. else:
  745. return (ACTION_NO_ENTRY_WARN, config)
  746. # If this CONFIG is neither bool nor trisate
  747. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  748. # tools/scripts/define2mk.sed changes '1' to 'y'.
  749. # This is a problem if the CONFIG is int type.
  750. # Check the type in Kconfig and handle it correctly.
  751. if new_val[-2:] == '=y':
  752. new_val = new_val[:-1] + '1'
  753. return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
  754. new_val)
  755. def update_dotconfig(self):
  756. """Parse files for the config options and update the .config.
  757. This function parses the generated .config and include/autoconf.mk
  758. searching the target options.
  759. Move the config option(s) to the .config as needed.
  760. Arguments:
  761. defconfig: defconfig name.
  762. Returns:
  763. Return a tuple of (updated flag, log string).
  764. The "updated flag" is True if the .config was updated, False
  765. otherwise. The "log string" shows what happend to the .config.
  766. """
  767. results = []
  768. updated = False
  769. suspicious = False
  770. rm_files = [self.config_autoconf, self.autoconf]
  771. if self.options.spl:
  772. if os.path.exists(self.spl_autoconf):
  773. autoconf_path = self.spl_autoconf
  774. rm_files.append(self.spl_autoconf)
  775. else:
  776. for f in rm_files:
  777. os.remove(f)
  778. return (updated, suspicious,
  779. color_text(self.options.color, COLOR_BROWN,
  780. "SPL is not enabled. Skipped.") + '\n')
  781. else:
  782. autoconf_path = self.autoconf
  783. with open(self.dotconfig) as f:
  784. dotconfig_lines = f.readlines()
  785. with open(autoconf_path) as f:
  786. autoconf_lines = f.readlines()
  787. for config in self.configs:
  788. result = self.parse_one_config(config, dotconfig_lines,
  789. autoconf_lines)
  790. results.append(result)
  791. log = ''
  792. for (action, value) in results:
  793. if action == ACTION_MOVE:
  794. actlog = "Move '%s'" % value
  795. log_color = COLOR_LIGHT_GREEN
  796. elif action == ACTION_NO_ENTRY:
  797. actlog = "%s is not defined in Kconfig. Do nothing." % value
  798. log_color = COLOR_LIGHT_BLUE
  799. elif action == ACTION_NO_ENTRY_WARN:
  800. actlog = "%s is not defined in Kconfig (suspicious). Do nothing." % value
  801. log_color = COLOR_YELLOW
  802. suspicious = True
  803. elif action == ACTION_NO_CHANGE:
  804. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  805. % value
  806. log_color = COLOR_LIGHT_PURPLE
  807. elif action == ACTION_SPL_NOT_EXIST:
  808. actlog = "SPL is not enabled for this defconfig. Skip."
  809. log_color = COLOR_PURPLE
  810. else:
  811. sys.exit("Internal Error. This should not happen.")
  812. log += color_text(self.options.color, log_color, actlog) + '\n'
  813. with open(self.dotconfig, 'a') as f:
  814. for (action, value) in results:
  815. if action == ACTION_MOVE:
  816. f.write(value + '\n')
  817. updated = True
  818. self.results = results
  819. for f in rm_files:
  820. os.remove(f)
  821. return (updated, suspicious, log)
  822. def check_defconfig(self):
  823. """Check the defconfig after savedefconfig
  824. Returns:
  825. Return additional log if moved CONFIGs were removed again by
  826. 'make savedefconfig'.
  827. """
  828. log = ''
  829. with open(self.defconfig) as f:
  830. defconfig_lines = f.readlines()
  831. for (action, value) in self.results:
  832. if action != ACTION_MOVE:
  833. continue
  834. if not value + '\n' in defconfig_lines:
  835. log += color_text(self.options.color, COLOR_YELLOW,
  836. "'%s' was removed by savedefconfig.\n" %
  837. value)
  838. return log
  839. class DatabaseThread(threading.Thread):
  840. """This thread processes results from Slot threads.
  841. It collects the data in the master config directary. There is only one
  842. result thread, and this helps to serialise the build output.
  843. """
  844. def __init__(self, config_db, db_queue):
  845. """Set up a new result thread
  846. Args:
  847. builder: Builder which will be sent each result
  848. """
  849. threading.Thread.__init__(self)
  850. self.config_db = config_db
  851. self.db_queue= db_queue
  852. def run(self):
  853. """Called to start up the result thread.
  854. We collect the next result job and pass it on to the build.
  855. """
  856. while True:
  857. defconfig, configs = self.db_queue.get()
  858. self.config_db[defconfig] = configs
  859. self.db_queue.task_done()
  860. class Slot:
  861. """A slot to store a subprocess.
  862. Each instance of this class handles one subprocess.
  863. This class is useful to control multiple threads
  864. for faster processing.
  865. """
  866. def __init__(self, toolchains, configs, options, progress, devnull,
  867. make_cmd, reference_src_dir, db_queue):
  868. """Create a new process slot.
  869. Arguments:
  870. toolchains: Toolchains object containing toolchains.
  871. configs: A list of CONFIGs to move.
  872. options: option flags.
  873. progress: A progress indicator.
  874. devnull: A file object of '/dev/null'.
  875. make_cmd: command name of GNU Make.
  876. reference_src_dir: Determine the true starting config state from this
  877. source tree.
  878. db_queue: output queue to write config info for the database
  879. """
  880. self.toolchains = toolchains
  881. self.options = options
  882. self.progress = progress
  883. self.build_dir = tempfile.mkdtemp()
  884. self.devnull = devnull
  885. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  886. self.reference_src_dir = reference_src_dir
  887. self.db_queue = db_queue
  888. self.parser = KconfigParser(configs, options, self.build_dir)
  889. self.state = STATE_IDLE
  890. self.failed_boards = set()
  891. self.suspicious_boards = set()
  892. def __del__(self):
  893. """Delete the working directory
  894. This function makes sure the temporary directory is cleaned away
  895. even if Python suddenly dies due to error. It should be done in here
  896. because it is guaranteed the destructor is always invoked when the
  897. instance of the class gets unreferenced.
  898. If the subprocess is still running, wait until it finishes.
  899. """
  900. if self.state != STATE_IDLE:
  901. while self.ps.poll() == None:
  902. pass
  903. shutil.rmtree(self.build_dir)
  904. def add(self, defconfig):
  905. """Assign a new subprocess for defconfig and add it to the slot.
  906. If the slot is vacant, create a new subprocess for processing the
  907. given defconfig and add it to the slot. Just returns False if
  908. the slot is occupied (i.e. the current subprocess is still running).
  909. Arguments:
  910. defconfig: defconfig name.
  911. Returns:
  912. Return True on success or False on failure
  913. """
  914. if self.state != STATE_IDLE:
  915. return False
  916. self.defconfig = defconfig
  917. self.log = ''
  918. self.current_src_dir = self.reference_src_dir
  919. self.do_defconfig()
  920. return True
  921. def poll(self):
  922. """Check the status of the subprocess and handle it as needed.
  923. Returns True if the slot is vacant (i.e. in idle state).
  924. If the configuration is successfully finished, assign a new
  925. subprocess to build include/autoconf.mk.
  926. If include/autoconf.mk is generated, invoke the parser to
  927. parse the .config and the include/autoconf.mk, moving
  928. config options to the .config as needed.
  929. If the .config was updated, run "make savedefconfig" to sync
  930. it, update the original defconfig, and then set the slot back
  931. to the idle state.
  932. Returns:
  933. Return True if the subprocess is terminated, False otherwise
  934. """
  935. if self.state == STATE_IDLE:
  936. return True
  937. if self.ps.poll() == None:
  938. return False
  939. if self.ps.poll() != 0:
  940. self.handle_error()
  941. elif self.state == STATE_DEFCONFIG:
  942. if self.reference_src_dir and not self.current_src_dir:
  943. self.do_savedefconfig()
  944. else:
  945. self.do_autoconf()
  946. elif self.state == STATE_AUTOCONF:
  947. if self.current_src_dir:
  948. self.current_src_dir = None
  949. self.do_defconfig()
  950. elif self.options.build_db:
  951. self.do_build_db()
  952. else:
  953. self.do_savedefconfig()
  954. elif self.state == STATE_SAVEDEFCONFIG:
  955. self.update_defconfig()
  956. else:
  957. sys.exit("Internal Error. This should not happen.")
  958. return True if self.state == STATE_IDLE else False
  959. def handle_error(self):
  960. """Handle error cases."""
  961. self.log += color_text(self.options.color, COLOR_LIGHT_RED,
  962. "Failed to process.\n")
  963. if self.options.verbose:
  964. self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
  965. self.ps.stderr.read().decode())
  966. self.finish(False)
  967. def do_defconfig(self):
  968. """Run 'make <board>_defconfig' to create the .config file."""
  969. cmd = list(self.make_cmd)
  970. cmd.append(self.defconfig)
  971. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  972. stderr=subprocess.PIPE,
  973. cwd=self.current_src_dir)
  974. self.state = STATE_DEFCONFIG
  975. def do_autoconf(self):
  976. """Run 'make AUTO_CONF_PATH'."""
  977. arch = self.parser.get_arch()
  978. try:
  979. toolchain = self.toolchains.Select(arch)
  980. except ValueError:
  981. self.log += color_text(self.options.color, COLOR_YELLOW,
  982. "Tool chain for '%s' is missing. Do nothing.\n" % arch)
  983. self.finish(False)
  984. return
  985. env = toolchain.MakeEnvironment(False)
  986. cmd = list(self.make_cmd)
  987. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  988. cmd.append(AUTO_CONF_PATH)
  989. self.ps = subprocess.Popen(cmd, stdout=self.devnull, env=env,
  990. stderr=subprocess.PIPE,
  991. cwd=self.current_src_dir)
  992. self.state = STATE_AUTOCONF
  993. def do_build_db(self):
  994. """Add the board to the database"""
  995. configs = {}
  996. with open(os.path.join(self.build_dir, AUTO_CONF_PATH)) as fd:
  997. for line in fd.readlines():
  998. if line.startswith('CONFIG'):
  999. config, value = line.split('=', 1)
  1000. configs[config] = value.rstrip()
  1001. self.db_queue.put([self.defconfig, configs])
  1002. self.finish(True)
  1003. def do_savedefconfig(self):
  1004. """Update the .config and run 'make savedefconfig'."""
  1005. (updated, suspicious, log) = self.parser.update_dotconfig()
  1006. if suspicious:
  1007. self.suspicious_boards.add(self.defconfig)
  1008. self.log += log
  1009. if not self.options.force_sync and not updated:
  1010. self.finish(True)
  1011. return
  1012. if updated:
  1013. self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
  1014. "Syncing by savedefconfig...\n")
  1015. else:
  1016. self.log += "Syncing by savedefconfig (forced by option)...\n"
  1017. cmd = list(self.make_cmd)
  1018. cmd.append('savedefconfig')
  1019. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  1020. stderr=subprocess.PIPE)
  1021. self.state = STATE_SAVEDEFCONFIG
  1022. def update_defconfig(self):
  1023. """Update the input defconfig and go back to the idle state."""
  1024. log = self.parser.check_defconfig()
  1025. if log:
  1026. self.suspicious_boards.add(self.defconfig)
  1027. self.log += log
  1028. orig_defconfig = os.path.join('configs', self.defconfig)
  1029. new_defconfig = os.path.join(self.build_dir, 'defconfig')
  1030. updated = not filecmp.cmp(orig_defconfig, new_defconfig)
  1031. if updated:
  1032. self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
  1033. "defconfig was updated.\n")
  1034. if not self.options.dry_run and updated:
  1035. shutil.move(new_defconfig, orig_defconfig)
  1036. self.finish(True)
  1037. def finish(self, success):
  1038. """Display log along with progress and go to the idle state.
  1039. Arguments:
  1040. success: Should be True when the defconfig was processed
  1041. successfully, or False when it fails.
  1042. """
  1043. # output at least 30 characters to hide the "* defconfigs out of *".
  1044. log = self.defconfig.ljust(30) + '\n'
  1045. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  1046. # Some threads are running in parallel.
  1047. # Print log atomically to not mix up logs from different threads.
  1048. print(log, file=(sys.stdout if success else sys.stderr))
  1049. if not success:
  1050. if self.options.exit_on_error:
  1051. sys.exit("Exit on error.")
  1052. # If --exit-on-error flag is not set, skip this board and continue.
  1053. # Record the failed board.
  1054. self.failed_boards.add(self.defconfig)
  1055. self.progress.inc()
  1056. self.progress.show()
  1057. self.state = STATE_IDLE
  1058. def get_failed_boards(self):
  1059. """Returns a set of failed boards (defconfigs) in this slot.
  1060. """
  1061. return self.failed_boards
  1062. def get_suspicious_boards(self):
  1063. """Returns a set of boards (defconfigs) with possible misconversion.
  1064. """
  1065. return self.suspicious_boards - self.failed_boards
  1066. class Slots:
  1067. """Controller of the array of subprocess slots."""
  1068. def __init__(self, toolchains, configs, options, progress,
  1069. reference_src_dir, db_queue):
  1070. """Create a new slots controller.
  1071. Arguments:
  1072. toolchains: Toolchains object containing toolchains.
  1073. configs: A list of CONFIGs to move.
  1074. options: option flags.
  1075. progress: A progress indicator.
  1076. reference_src_dir: Determine the true starting config state from this
  1077. source tree.
  1078. db_queue: output queue to write config info for the database
  1079. """
  1080. self.options = options
  1081. self.slots = []
  1082. devnull = get_devnull()
  1083. make_cmd = get_make_cmd()
  1084. for i in range(options.jobs):
  1085. self.slots.append(Slot(toolchains, configs, options, progress,
  1086. devnull, make_cmd, reference_src_dir,
  1087. db_queue))
  1088. def add(self, defconfig):
  1089. """Add a new subprocess if a vacant slot is found.
  1090. Arguments:
  1091. defconfig: defconfig name to be put into.
  1092. Returns:
  1093. Return True on success or False on failure
  1094. """
  1095. for slot in self.slots:
  1096. if slot.add(defconfig):
  1097. return True
  1098. return False
  1099. def available(self):
  1100. """Check if there is a vacant slot.
  1101. Returns:
  1102. Return True if at lease one vacant slot is found, False otherwise.
  1103. """
  1104. for slot in self.slots:
  1105. if slot.poll():
  1106. return True
  1107. return False
  1108. def empty(self):
  1109. """Check if all slots are vacant.
  1110. Returns:
  1111. Return True if all the slots are vacant, False otherwise.
  1112. """
  1113. ret = True
  1114. for slot in self.slots:
  1115. if not slot.poll():
  1116. ret = False
  1117. return ret
  1118. def show_failed_boards(self):
  1119. """Display all of the failed boards (defconfigs)."""
  1120. boards = set()
  1121. output_file = 'moveconfig.failed'
  1122. for slot in self.slots:
  1123. boards |= slot.get_failed_boards()
  1124. if boards:
  1125. boards = '\n'.join(boards) + '\n'
  1126. msg = "The following boards were not processed due to error:\n"
  1127. msg += boards
  1128. msg += "(the list has been saved in %s)\n" % output_file
  1129. print(color_text(self.options.color, COLOR_LIGHT_RED,
  1130. msg), file=sys.stderr)
  1131. with open(output_file, 'w') as f:
  1132. f.write(boards)
  1133. def show_suspicious_boards(self):
  1134. """Display all boards (defconfigs) with possible misconversion."""
  1135. boards = set()
  1136. output_file = 'moveconfig.suspicious'
  1137. for slot in self.slots:
  1138. boards |= slot.get_suspicious_boards()
  1139. if boards:
  1140. boards = '\n'.join(boards) + '\n'
  1141. msg = "The following boards might have been converted incorrectly.\n"
  1142. msg += "It is highly recommended to check them manually:\n"
  1143. msg += boards
  1144. msg += "(the list has been saved in %s)\n" % output_file
  1145. print(color_text(self.options.color, COLOR_YELLOW,
  1146. msg), file=sys.stderr)
  1147. with open(output_file, 'w') as f:
  1148. f.write(boards)
  1149. class ReferenceSource:
  1150. """Reference source against which original configs should be parsed."""
  1151. def __init__(self, commit):
  1152. """Create a reference source directory based on a specified commit.
  1153. Arguments:
  1154. commit: commit to git-clone
  1155. """
  1156. self.src_dir = tempfile.mkdtemp()
  1157. print("Cloning git repo to a separate work directory...")
  1158. subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
  1159. cwd=self.src_dir)
  1160. print("Checkout '%s' to build the original autoconf.mk." % \
  1161. subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip())
  1162. subprocess.check_output(['git', 'checkout', commit],
  1163. stderr=subprocess.STDOUT, cwd=self.src_dir)
  1164. def __del__(self):
  1165. """Delete the reference source directory
  1166. This function makes sure the temporary directory is cleaned away
  1167. even if Python suddenly dies due to error. It should be done in here
  1168. because it is guaranteed the destructor is always invoked when the
  1169. instance of the class gets unreferenced.
  1170. """
  1171. shutil.rmtree(self.src_dir)
  1172. def get_dir(self):
  1173. """Return the absolute path to the reference source directory."""
  1174. return self.src_dir
  1175. def move_config(toolchains, configs, options, db_queue):
  1176. """Move config options to defconfig files.
  1177. Arguments:
  1178. configs: A list of CONFIGs to move.
  1179. options: option flags
  1180. """
  1181. if len(configs) == 0:
  1182. if options.force_sync:
  1183. print('No CONFIG is specified. You are probably syncing defconfigs.', end=' ')
  1184. elif options.build_db:
  1185. print('Building %s database' % CONFIG_DATABASE)
  1186. else:
  1187. print('Neither CONFIG nor --force-sync is specified. Nothing will happen.', end=' ')
  1188. else:
  1189. print('Move ' + ', '.join(configs), end=' ')
  1190. print('(jobs: %d)\n' % options.jobs)
  1191. if options.git_ref:
  1192. reference_src = ReferenceSource(options.git_ref)
  1193. reference_src_dir = reference_src.get_dir()
  1194. else:
  1195. reference_src_dir = None
  1196. if options.defconfigs:
  1197. defconfigs = get_matched_defconfigs(options.defconfigs)
  1198. else:
  1199. defconfigs = get_all_defconfigs()
  1200. progress = Progress(len(defconfigs))
  1201. slots = Slots(toolchains, configs, options, progress, reference_src_dir,
  1202. db_queue)
  1203. # Main loop to process defconfig files:
  1204. # Add a new subprocess into a vacant slot.
  1205. # Sleep if there is no available slot.
  1206. for defconfig in defconfigs:
  1207. while not slots.add(defconfig):
  1208. while not slots.available():
  1209. # No available slot: sleep for a while
  1210. time.sleep(SLEEP_TIME)
  1211. # wait until all the subprocesses finish
  1212. while not slots.empty():
  1213. time.sleep(SLEEP_TIME)
  1214. print('')
  1215. slots.show_failed_boards()
  1216. slots.show_suspicious_boards()
  1217. def find_kconfig_rules(kconf, config, imply_config):
  1218. """Check whether a config has a 'select' or 'imply' keyword
  1219. Args:
  1220. kconf: Kconfiglib.Kconfig object
  1221. config: Name of config to check (without CONFIG_ prefix)
  1222. imply_config: Implying config (without CONFIG_ prefix) which may or
  1223. may not have an 'imply' for 'config')
  1224. Returns:
  1225. Symbol object for 'config' if found, else None
  1226. """
  1227. sym = kconf.syms.get(imply_config)
  1228. if sym:
  1229. for sel in sym.get_selected_symbols() | sym.get_implied_symbols():
  1230. if sel.get_name() == config:
  1231. return sym
  1232. return None
  1233. def check_imply_rule(kconf, config, imply_config):
  1234. """Check if we can add an 'imply' option
  1235. This finds imply_config in the Kconfig and looks to see if it is possible
  1236. to add an 'imply' for 'config' to that part of the Kconfig.
  1237. Args:
  1238. kconf: Kconfiglib.Kconfig object
  1239. config: Name of config to check (without CONFIG_ prefix)
  1240. imply_config: Implying config (without CONFIG_ prefix) which may or
  1241. may not have an 'imply' for 'config')
  1242. Returns:
  1243. tuple:
  1244. filename of Kconfig file containing imply_config, or None if none
  1245. line number within the Kconfig file, or 0 if none
  1246. message indicating the result
  1247. """
  1248. sym = kconf.syms.get(imply_config)
  1249. if not sym:
  1250. return 'cannot find sym'
  1251. locs = sym.get_def_locations()
  1252. if len(locs) != 1:
  1253. return '%d locations' % len(locs)
  1254. fname, linenum = locs[0]
  1255. cwd = os.getcwd()
  1256. if cwd and fname.startswith(cwd):
  1257. fname = fname[len(cwd) + 1:]
  1258. file_line = ' at %s:%d' % (fname, linenum)
  1259. with open(fname) as fd:
  1260. data = fd.read().splitlines()
  1261. if data[linenum - 1] != 'config %s' % imply_config:
  1262. return None, 0, 'bad sym format %s%s' % (data[linenum], file_line)
  1263. return fname, linenum, 'adding%s' % file_line
  1264. def add_imply_rule(config, fname, linenum):
  1265. """Add a new 'imply' option to a Kconfig
  1266. Args:
  1267. config: config option to add an imply for (without CONFIG_ prefix)
  1268. fname: Kconfig filename to update
  1269. linenum: Line number to place the 'imply' before
  1270. Returns:
  1271. Message indicating the result
  1272. """
  1273. file_line = ' at %s:%d' % (fname, linenum)
  1274. data = open(fname).read().splitlines()
  1275. linenum -= 1
  1276. for offset, line in enumerate(data[linenum:]):
  1277. if line.strip().startswith('help') or not line:
  1278. data.insert(linenum + offset, '\timply %s' % config)
  1279. with open(fname, 'w') as fd:
  1280. fd.write('\n'.join(data) + '\n')
  1281. return 'added%s' % file_line
  1282. return 'could not insert%s'
  1283. (IMPLY_MIN_2, IMPLY_TARGET, IMPLY_CMD, IMPLY_NON_ARCH_BOARD) = (
  1284. 1, 2, 4, 8)
  1285. IMPLY_FLAGS = {
  1286. 'min2': [IMPLY_MIN_2, 'Show options which imply >2 boards (normally >5)'],
  1287. 'target': [IMPLY_TARGET, 'Allow CONFIG_TARGET_... options to imply'],
  1288. 'cmd': [IMPLY_CMD, 'Allow CONFIG_CMD_... to imply'],
  1289. 'non-arch-board': [
  1290. IMPLY_NON_ARCH_BOARD,
  1291. 'Allow Kconfig options outside arch/ and /board/ to imply'],
  1292. };
  1293. def do_imply_config(config_list, add_imply, imply_flags, skip_added,
  1294. check_kconfig=True, find_superset=False):
  1295. """Find CONFIG options which imply those in the list
  1296. Some CONFIG options can be implied by others and this can help to reduce
  1297. the size of the defconfig files. For example, CONFIG_X86 implies
  1298. CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
  1299. all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
  1300. each of the x86 defconfig files.
  1301. This function uses the moveconfig database to find such options. It
  1302. displays a list of things that could possibly imply those in the list.
  1303. The algorithm ignores any that start with CONFIG_TARGET since these
  1304. typically refer to only a few defconfigs (often one). It also does not
  1305. display a config with less than 5 defconfigs.
  1306. The algorithm works using sets. For each target config in config_list:
  1307. - Get the set 'defconfigs' which use that target config
  1308. - For each config (from a list of all configs):
  1309. - Get the set 'imply_defconfig' of defconfigs which use that config
  1310. -
  1311. - If imply_defconfigs contains anything not in defconfigs then
  1312. this config does not imply the target config
  1313. Params:
  1314. config_list: List of CONFIG options to check (each a string)
  1315. add_imply: Automatically add an 'imply' for each config.
  1316. imply_flags: Flags which control which implying configs are allowed
  1317. (IMPLY_...)
  1318. skip_added: Don't show options which already have an imply added.
  1319. check_kconfig: Check if implied symbols already have an 'imply' or
  1320. 'select' for the target config, and show this information if so.
  1321. find_superset: True to look for configs which are a superset of those
  1322. already found. So for example if CONFIG_EXYNOS5 implies an option,
  1323. but CONFIG_EXYNOS covers a larger set of defconfigs and also
  1324. implies that option, this will drop the former in favour of the
  1325. latter. In practice this option has not proved very used.
  1326. Note the terminoloy:
  1327. config - a CONFIG_XXX options (a string, e.g. 'CONFIG_CMD_EEPROM')
  1328. defconfig - a defconfig file (a string, e.g. 'configs/snow_defconfig')
  1329. """
  1330. kconf = KconfigScanner().conf if check_kconfig else None
  1331. if add_imply and add_imply != 'all':
  1332. add_imply = add_imply.split()
  1333. # key is defconfig name, value is dict of (CONFIG_xxx, value)
  1334. config_db = {}
  1335. # Holds a dict containing the set of defconfigs that contain each config
  1336. # key is config, value is set of defconfigs using that config
  1337. defconfig_db = collections.defaultdict(set)
  1338. # Set of all config options we have seen
  1339. all_configs = set()
  1340. # Set of all defconfigs we have seen
  1341. all_defconfigs = set()
  1342. # Read in the database
  1343. configs = {}
  1344. with open(CONFIG_DATABASE) as fd:
  1345. for line in fd.readlines():
  1346. line = line.rstrip()
  1347. if not line: # Separator between defconfigs
  1348. config_db[defconfig] = configs
  1349. all_defconfigs.add(defconfig)
  1350. configs = {}
  1351. elif line[0] == ' ': # CONFIG line
  1352. config, value = line.strip().split('=', 1)
  1353. configs[config] = value
  1354. defconfig_db[config].add(defconfig)
  1355. all_configs.add(config)
  1356. else: # New defconfig
  1357. defconfig = line
  1358. # Work through each target config option in tern, independently
  1359. for config in config_list:
  1360. defconfigs = defconfig_db.get(config)
  1361. if not defconfigs:
  1362. print('%s not found in any defconfig' % config)
  1363. continue
  1364. # Get the set of defconfigs without this one (since a config cannot
  1365. # imply itself)
  1366. non_defconfigs = all_defconfigs - defconfigs
  1367. num_defconfigs = len(defconfigs)
  1368. print('%s found in %d/%d defconfigs' % (config, num_defconfigs,
  1369. len(all_configs)))
  1370. # This will hold the results: key=config, value=defconfigs containing it
  1371. imply_configs = {}
  1372. rest_configs = all_configs - set([config])
  1373. # Look at every possible config, except the target one
  1374. for imply_config in rest_configs:
  1375. if 'ERRATUM' in imply_config:
  1376. continue
  1377. if not (imply_flags & IMPLY_CMD):
  1378. if 'CONFIG_CMD' in imply_config:
  1379. continue
  1380. if not (imply_flags & IMPLY_TARGET):
  1381. if 'CONFIG_TARGET' in imply_config:
  1382. continue
  1383. # Find set of defconfigs that have this config
  1384. imply_defconfig = defconfig_db[imply_config]
  1385. # Get the intersection of this with defconfigs containing the
  1386. # target config
  1387. common_defconfigs = imply_defconfig & defconfigs
  1388. # Get the set of defconfigs containing this config which DO NOT
  1389. # also contain the taret config. If this set is non-empty it means
  1390. # that this config affects other defconfigs as well as (possibly)
  1391. # the ones affected by the target config. This means it implies
  1392. # things we don't want to imply.
  1393. not_common_defconfigs = imply_defconfig & non_defconfigs
  1394. if not_common_defconfigs:
  1395. continue
  1396. # If there are common defconfigs, imply_config may be useful
  1397. if common_defconfigs:
  1398. skip = False
  1399. if find_superset:
  1400. for prev in list(imply_configs.keys()):
  1401. prev_count = len(imply_configs[prev])
  1402. count = len(common_defconfigs)
  1403. if (prev_count > count and
  1404. (imply_configs[prev] & common_defconfigs ==
  1405. common_defconfigs)):
  1406. # skip imply_config because prev is a superset
  1407. skip = True
  1408. break
  1409. elif count > prev_count:
  1410. # delete prev because imply_config is a superset
  1411. del imply_configs[prev]
  1412. if not skip:
  1413. imply_configs[imply_config] = common_defconfigs
  1414. # Now we have a dict imply_configs of configs which imply each config
  1415. # The value of each dict item is the set of defconfigs containing that
  1416. # config. Rank them so that we print the configs that imply the largest
  1417. # number of defconfigs first.
  1418. ranked_iconfigs = sorted(imply_configs,
  1419. key=lambda k: len(imply_configs[k]), reverse=True)
  1420. kconfig_info = ''
  1421. cwd = os.getcwd()
  1422. add_list = collections.defaultdict(list)
  1423. for iconfig in ranked_iconfigs:
  1424. num_common = len(imply_configs[iconfig])
  1425. # Don't bother if there are less than 5 defconfigs affected.
  1426. if num_common < (2 if imply_flags & IMPLY_MIN_2 else 5):
  1427. continue
  1428. missing = defconfigs - imply_configs[iconfig]
  1429. missing_str = ', '.join(missing) if missing else 'all'
  1430. missing_str = ''
  1431. show = True
  1432. if kconf:
  1433. sym = find_kconfig_rules(kconf, config[CONFIG_LEN:],
  1434. iconfig[CONFIG_LEN:])
  1435. kconfig_info = ''
  1436. if sym:
  1437. locs = sym.get_def_locations()
  1438. if len(locs) == 1:
  1439. fname, linenum = locs[0]
  1440. if cwd and fname.startswith(cwd):
  1441. fname = fname[len(cwd) + 1:]
  1442. kconfig_info = '%s:%d' % (fname, linenum)
  1443. if skip_added:
  1444. show = False
  1445. else:
  1446. sym = kconf.syms.get(iconfig[CONFIG_LEN:])
  1447. fname = ''
  1448. if sym:
  1449. locs = sym.get_def_locations()
  1450. if len(locs) == 1:
  1451. fname, linenum = locs[0]
  1452. if cwd and fname.startswith(cwd):
  1453. fname = fname[len(cwd) + 1:]
  1454. in_arch_board = not sym or (fname.startswith('arch') or
  1455. fname.startswith('board'))
  1456. if (not in_arch_board and
  1457. not (imply_flags & IMPLY_NON_ARCH_BOARD)):
  1458. continue
  1459. if add_imply and (add_imply == 'all' or
  1460. iconfig in add_imply):
  1461. fname, linenum, kconfig_info = (check_imply_rule(kconf,
  1462. config[CONFIG_LEN:], iconfig[CONFIG_LEN:]))
  1463. if fname:
  1464. add_list[fname].append(linenum)
  1465. if show and kconfig_info != 'skip':
  1466. print('%5d : %-30s%-25s %s' % (num_common, iconfig.ljust(30),
  1467. kconfig_info, missing_str))
  1468. # Having collected a list of things to add, now we add them. We process
  1469. # each file from the largest line number to the smallest so that
  1470. # earlier additions do not affect our line numbers. E.g. if we added an
  1471. # imply at line 20 it would change the position of each line after
  1472. # that.
  1473. for fname, linenums in add_list.items():
  1474. for linenum in sorted(linenums, reverse=True):
  1475. add_imply_rule(config[CONFIG_LEN:], fname, linenum)
  1476. def main():
  1477. try:
  1478. cpu_count = multiprocessing.cpu_count()
  1479. except NotImplementedError:
  1480. cpu_count = 1
  1481. parser = optparse.OptionParser()
  1482. # Add options here
  1483. parser.add_option('-a', '--add-imply', type='string', default='',
  1484. help='comma-separated list of CONFIG options to add '
  1485. "an 'imply' statement to for the CONFIG in -i")
  1486. parser.add_option('-A', '--skip-added', action='store_true', default=False,
  1487. help="don't show options which are already marked as "
  1488. 'implying others')
  1489. parser.add_option('-b', '--build-db', action='store_true', default=False,
  1490. help='build a CONFIG database')
  1491. parser.add_option('-c', '--color', action='store_true', default=False,
  1492. help='display the log in color')
  1493. parser.add_option('-C', '--commit', action='store_true', default=False,
  1494. help='Create a git commit for the operation')
  1495. parser.add_option('-d', '--defconfigs', type='string',
  1496. help='a file containing a list of defconfigs to move, '
  1497. "one per line (for example 'snow_defconfig') "
  1498. "or '-' to read from stdin")
  1499. parser.add_option('-i', '--imply', action='store_true', default=False,
  1500. help='find options which imply others')
  1501. parser.add_option('-I', '--imply-flags', type='string', default='',
  1502. help="control the -i option ('help' for help")
  1503. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  1504. help='perform a trial run (show log with no changes)')
  1505. parser.add_option('-e', '--exit-on-error', action='store_true',
  1506. default=False,
  1507. help='exit immediately on any error')
  1508. parser.add_option('-s', '--force-sync', action='store_true', default=False,
  1509. help='force sync by savedefconfig')
  1510. parser.add_option('-S', '--spl', action='store_true', default=False,
  1511. help='parse config options defined for SPL build')
  1512. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  1513. action='store_true', default=False,
  1514. help='only cleanup the headers')
  1515. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  1516. help='the number of jobs to run simultaneously')
  1517. parser.add_option('-r', '--git-ref', type='string',
  1518. help='the git ref to clone for building the autoconf.mk')
  1519. parser.add_option('-y', '--yes', action='store_true', default=False,
  1520. help="respond 'yes' to any prompts")
  1521. parser.add_option('-v', '--verbose', action='store_true', default=False,
  1522. help='show any build errors as boards are built')
  1523. parser.usage += ' CONFIG ...'
  1524. (options, configs) = parser.parse_args()
  1525. if len(configs) == 0 and not any((options.force_sync, options.build_db,
  1526. options.imply)):
  1527. parser.print_usage()
  1528. sys.exit(1)
  1529. # prefix the option name with CONFIG_ if missing
  1530. configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
  1531. for config in configs ]
  1532. check_top_directory()
  1533. if options.imply:
  1534. imply_flags = 0
  1535. if options.imply_flags == 'all':
  1536. imply_flags = -1
  1537. elif options.imply_flags:
  1538. for flag in options.imply_flags.split(','):
  1539. bad = flag not in IMPLY_FLAGS
  1540. if bad:
  1541. print("Invalid flag '%s'" % flag)
  1542. if flag == 'help' or bad:
  1543. print("Imply flags: (separate with ',')")
  1544. for name, info in IMPLY_FLAGS.items():
  1545. print(' %-15s: %s' % (name, info[1]))
  1546. parser.print_usage()
  1547. sys.exit(1)
  1548. imply_flags |= IMPLY_FLAGS[flag][0]
  1549. do_imply_config(configs, options.add_imply, imply_flags,
  1550. options.skip_added)
  1551. return
  1552. config_db = {}
  1553. db_queue = queue.Queue()
  1554. t = DatabaseThread(config_db, db_queue)
  1555. t.setDaemon(True)
  1556. t.start()
  1557. if not options.cleanup_headers_only:
  1558. check_clean_directory()
  1559. bsettings.Setup('')
  1560. toolchains = toolchain.Toolchains()
  1561. toolchains.GetSettings()
  1562. toolchains.Scan(verbose=False)
  1563. move_config(toolchains, configs, options, db_queue)
  1564. db_queue.join()
  1565. if configs:
  1566. cleanup_headers(configs, options)
  1567. cleanup_extra_options(configs, options)
  1568. cleanup_whitelist(configs, options)
  1569. cleanup_readme(configs, options)
  1570. if options.commit:
  1571. subprocess.call(['git', 'add', '-u'])
  1572. if configs:
  1573. msg = 'Convert %s %sto Kconfig' % (configs[0],
  1574. 'et al ' if len(configs) > 1 else '')
  1575. msg += ('\n\nThis converts the following to Kconfig:\n %s\n' %
  1576. '\n '.join(configs))
  1577. else:
  1578. msg = 'configs: Resync with savedefconfig'
  1579. msg += '\n\nRsync all defconfig files using moveconfig.py'
  1580. subprocess.call(['git', 'commit', '-s', '-m', msg])
  1581. if options.build_db:
  1582. with open(CONFIG_DATABASE, 'w') as fd:
  1583. for defconfig, configs in config_db.items():
  1584. fd.write('%s\n' % defconfig)
  1585. for config in sorted(configs.keys()):
  1586. fd.write(' %s=%s\n' % (config, configs[config]))
  1587. fd.write('\n')
  1588. if __name__ == '__main__':
  1589. main()