moveconfig.py 67 KB

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