moveconfig.py 68 KB

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