moveconfig.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  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. Available options
  87. -----------------
  88. -c, --color
  89. Surround each portion of the log with escape sequences to display it
  90. in color on the terminal.
  91. -C, --commit
  92. Create a git commit with the changes when the operation is complete. A
  93. standard commit message is used which may need to be edited.
  94. -d, --defconfigs
  95. Specify a file containing a list of defconfigs to move. The defconfig
  96. files can be given with shell-style wildcards.
  97. -n, --dry-run
  98. Perform a trial run that does not make any changes. It is useful to
  99. see what is going to happen before one actually runs it.
  100. -e, --exit-on-error
  101. Exit immediately if Make exits with a non-zero status while processing
  102. a defconfig file.
  103. -s, --force-sync
  104. Do "make savedefconfig" forcibly for all the defconfig files.
  105. If not specified, "make savedefconfig" only occurs for cases
  106. where at least one CONFIG was moved.
  107. -S, --spl
  108. Look for moved config options in spl/include/autoconf.mk instead of
  109. include/autoconf.mk. This is useful for moving options for SPL build
  110. because SPL related options (mostly prefixed with CONFIG_SPL_) are
  111. sometimes blocked by CONFIG_SPL_BUILD ifdef conditionals.
  112. -H, --headers-only
  113. Only cleanup the headers; skip the defconfig processing
  114. -j, --jobs
  115. Specify the number of threads to run simultaneously. If not specified,
  116. the number of threads is the same as the number of CPU cores.
  117. -r, --git-ref
  118. Specify the git ref to clone for building the autoconf.mk. If unspecified
  119. use the CWD. This is useful for when changes to the Kconfig affect the
  120. default values and you want to capture the state of the defconfig from
  121. before that change was in effect. If in doubt, specify a ref pre-Kconfig
  122. changes (use HEAD if Kconfig changes are not committed). Worst case it will
  123. take a bit longer to run, but will always do the right thing.
  124. -v, --verbose
  125. Show any build errors as boards are built
  126. -y, --yes
  127. Instead of prompting, automatically go ahead with all operations. This
  128. includes cleaning up headers and CONFIG_SYS_EXTRA_OPTIONS.
  129. To see the complete list of supported options, run
  130. $ tools/moveconfig.py -h
  131. """
  132. import copy
  133. import difflib
  134. import filecmp
  135. import fnmatch
  136. import glob
  137. import multiprocessing
  138. import optparse
  139. import os
  140. import re
  141. import shutil
  142. import subprocess
  143. import sys
  144. import tempfile
  145. import time
  146. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  147. SLEEP_TIME=0.03
  148. # Here is the list of cross-tools I use.
  149. # Most of them are available at kernel.org
  150. # (https://www.kernel.org/pub/tools/crosstool/files/bin/), except the following:
  151. # arc: https://github.com/foss-for-synopsys-dwc-arc-processors/toolchain/releases
  152. # nds32: http://osdk.andestech.com/packages/nds32le-linux-glibc-v1.tgz
  153. # nios2: https://sourcery.mentor.com/GNUToolchain/subscription42545
  154. # sh: http://sourcery.mentor.com/public/gnu_toolchain/sh-linux-gnu
  155. CROSS_COMPILE = {
  156. 'arc': 'arc-linux-',
  157. 'aarch64': 'aarch64-linux-',
  158. 'arm': 'arm-unknown-linux-gnueabi-',
  159. 'm68k': 'm68k-linux-',
  160. 'microblaze': 'microblaze-linux-',
  161. 'mips': 'mips-linux-',
  162. 'nds32': 'nds32le-linux-',
  163. 'nios2': 'nios2-linux-gnu-',
  164. 'powerpc': 'powerpc-linux-',
  165. 'sh': 'sh-linux-gnu-',
  166. 'x86': 'i386-linux-',
  167. 'xtensa': 'xtensa-linux-'
  168. }
  169. STATE_IDLE = 0
  170. STATE_DEFCONFIG = 1
  171. STATE_AUTOCONF = 2
  172. STATE_SAVEDEFCONFIG = 3
  173. ACTION_MOVE = 0
  174. ACTION_NO_ENTRY = 1
  175. ACTION_NO_ENTRY_WARN = 2
  176. ACTION_NO_CHANGE = 3
  177. COLOR_BLACK = '0;30'
  178. COLOR_RED = '0;31'
  179. COLOR_GREEN = '0;32'
  180. COLOR_BROWN = '0;33'
  181. COLOR_BLUE = '0;34'
  182. COLOR_PURPLE = '0;35'
  183. COLOR_CYAN = '0;36'
  184. COLOR_LIGHT_GRAY = '0;37'
  185. COLOR_DARK_GRAY = '1;30'
  186. COLOR_LIGHT_RED = '1;31'
  187. COLOR_LIGHT_GREEN = '1;32'
  188. COLOR_YELLOW = '1;33'
  189. COLOR_LIGHT_BLUE = '1;34'
  190. COLOR_LIGHT_PURPLE = '1;35'
  191. COLOR_LIGHT_CYAN = '1;36'
  192. COLOR_WHITE = '1;37'
  193. ### helper functions ###
  194. def get_devnull():
  195. """Get the file object of '/dev/null' device."""
  196. try:
  197. devnull = subprocess.DEVNULL # py3k
  198. except AttributeError:
  199. devnull = open(os.devnull, 'wb')
  200. return devnull
  201. def check_top_directory():
  202. """Exit if we are not at the top of source directory."""
  203. for f in ('README', 'Licenses'):
  204. if not os.path.exists(f):
  205. sys.exit('Please run at the top of source directory.')
  206. def check_clean_directory():
  207. """Exit if the source tree is not clean."""
  208. for f in ('.config', 'include/config'):
  209. if os.path.exists(f):
  210. sys.exit("source tree is not clean, please run 'make mrproper'")
  211. def get_make_cmd():
  212. """Get the command name of GNU Make.
  213. U-Boot needs GNU Make for building, but the command name is not
  214. necessarily "make". (for example, "gmake" on FreeBSD).
  215. Returns the most appropriate command name on your system.
  216. """
  217. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  218. ret = process.communicate()
  219. if process.returncode:
  220. sys.exit('GNU Make not found')
  221. return ret[0].rstrip()
  222. def get_matched_defconfig(line):
  223. """Get the defconfig files that match a pattern
  224. Args:
  225. line: Path or filename to match, e.g. 'configs/snow_defconfig' or
  226. 'k2*_defconfig'. If no directory is provided, 'configs/' is
  227. prepended
  228. Returns:
  229. a list of matching defconfig files
  230. """
  231. dirname = os.path.dirname(line)
  232. if dirname:
  233. pattern = line
  234. else:
  235. pattern = os.path.join('configs', line)
  236. return glob.glob(pattern) + glob.glob(pattern + '_defconfig')
  237. def get_matched_defconfigs(defconfigs_file):
  238. """Get all the defconfig files that match the patterns in a file.
  239. Args:
  240. defconfigs_file: File containing a list of defconfigs to process, or
  241. '-' to read the list from stdin
  242. Returns:
  243. A list of paths to defconfig files, with no duplicates
  244. """
  245. defconfigs = []
  246. if defconfigs_file == '-':
  247. fd = sys.stdin
  248. defconfigs_file = 'stdin'
  249. else:
  250. fd = open(defconfigs_file)
  251. for i, line in enumerate(fd):
  252. line = line.strip()
  253. if not line:
  254. continue # skip blank lines silently
  255. matched = get_matched_defconfig(line)
  256. if not matched:
  257. print >> sys.stderr, "warning: %s:%d: no defconfig matched '%s'" % \
  258. (defconfigs_file, i + 1, line)
  259. defconfigs += matched
  260. # use set() to drop multiple matching
  261. return [ defconfig[len('configs') + 1:] for defconfig in set(defconfigs) ]
  262. def get_all_defconfigs():
  263. """Get all the defconfig files under the configs/ directory."""
  264. defconfigs = []
  265. for (dirpath, dirnames, filenames) in os.walk('configs'):
  266. dirpath = dirpath[len('configs') + 1:]
  267. for filename in fnmatch.filter(filenames, '*_defconfig'):
  268. defconfigs.append(os.path.join(dirpath, filename))
  269. return defconfigs
  270. def color_text(color_enabled, color, string):
  271. """Return colored string."""
  272. if color_enabled:
  273. # LF should not be surrounded by the escape sequence.
  274. # Otherwise, additional whitespace or line-feed might be printed.
  275. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
  276. for s in string.split('\n') ])
  277. else:
  278. return string
  279. def show_diff(a, b, file_path, color_enabled):
  280. """Show unidified diff.
  281. Arguments:
  282. a: A list of lines (before)
  283. b: A list of lines (after)
  284. file_path: Path to the file
  285. color_enabled: Display the diff in color
  286. """
  287. diff = difflib.unified_diff(a, b,
  288. fromfile=os.path.join('a', file_path),
  289. tofile=os.path.join('b', file_path))
  290. for line in diff:
  291. if line[0] == '-' and line[1] != '-':
  292. print color_text(color_enabled, COLOR_RED, line),
  293. elif line[0] == '+' and line[1] != '+':
  294. print color_text(color_enabled, COLOR_GREEN, line),
  295. else:
  296. print line,
  297. def update_cross_compile(color_enabled):
  298. """Update per-arch CROSS_COMPILE via environment variables
  299. The default CROSS_COMPILE values are available
  300. in the CROSS_COMPILE list above.
  301. You can override them via environment variables
  302. CROSS_COMPILE_{ARCH}.
  303. For example, if you want to override toolchain prefixes
  304. for ARM and PowerPC, you can do as follows in your shell:
  305. export CROSS_COMPILE_ARM=...
  306. export CROSS_COMPILE_POWERPC=...
  307. Then, this function checks if specified compilers really exist in your
  308. PATH environment.
  309. """
  310. archs = []
  311. for arch in os.listdir('arch'):
  312. if os.path.exists(os.path.join('arch', arch, 'Makefile')):
  313. archs.append(arch)
  314. # arm64 is a special case
  315. archs.append('aarch64')
  316. for arch in archs:
  317. env = 'CROSS_COMPILE_' + arch.upper()
  318. cross_compile = os.environ.get(env)
  319. if not cross_compile:
  320. cross_compile = CROSS_COMPILE.get(arch, '')
  321. for path in os.environ["PATH"].split(os.pathsep):
  322. gcc_path = os.path.join(path, cross_compile + 'gcc')
  323. if os.path.isfile(gcc_path) and os.access(gcc_path, os.X_OK):
  324. break
  325. else:
  326. print >> sys.stderr, color_text(color_enabled, COLOR_YELLOW,
  327. 'warning: %sgcc: not found in PATH. %s architecture boards will be skipped'
  328. % (cross_compile, arch))
  329. cross_compile = None
  330. CROSS_COMPILE[arch] = cross_compile
  331. def extend_matched_lines(lines, matched, pre_patterns, post_patterns, extend_pre,
  332. extend_post):
  333. """Extend matched lines if desired patterns are found before/after already
  334. matched lines.
  335. Arguments:
  336. lines: A list of lines handled.
  337. matched: A list of line numbers that have been already matched.
  338. (will be updated by this function)
  339. pre_patterns: A list of regular expression that should be matched as
  340. preamble.
  341. post_patterns: A list of regular expression that should be matched as
  342. postamble.
  343. extend_pre: Add the line number of matched preamble to the matched list.
  344. extend_post: Add the line number of matched postamble to the matched list.
  345. """
  346. extended_matched = []
  347. j = matched[0]
  348. for i in matched:
  349. if i == 0 or i < j:
  350. continue
  351. j = i
  352. while j in matched:
  353. j += 1
  354. if j >= len(lines):
  355. break
  356. for p in pre_patterns:
  357. if p.search(lines[i - 1]):
  358. break
  359. else:
  360. # not matched
  361. continue
  362. for p in post_patterns:
  363. if p.search(lines[j]):
  364. break
  365. else:
  366. # not matched
  367. continue
  368. if extend_pre:
  369. extended_matched.append(i - 1)
  370. if extend_post:
  371. extended_matched.append(j)
  372. matched += extended_matched
  373. matched.sort()
  374. def confirm(options, prompt):
  375. if not options.yes:
  376. while True:
  377. choice = raw_input('{} [y/n]: '.format(prompt))
  378. choice = choice.lower()
  379. print choice
  380. if choice == 'y' or choice == 'n':
  381. break
  382. if choice == 'n':
  383. return False
  384. return True
  385. def cleanup_one_header(header_path, patterns, options):
  386. """Clean regex-matched lines away from a file.
  387. Arguments:
  388. header_path: path to the cleaned file.
  389. patterns: list of regex patterns. Any lines matching to these
  390. patterns are deleted.
  391. options: option flags.
  392. """
  393. with open(header_path) as f:
  394. lines = f.readlines()
  395. matched = []
  396. for i, line in enumerate(lines):
  397. if i - 1 in matched and lines[i - 1][-2:] == '\\\n':
  398. matched.append(i)
  399. continue
  400. for pattern in patterns:
  401. if pattern.search(line):
  402. matched.append(i)
  403. break
  404. if not matched:
  405. return
  406. # remove empty #ifdef ... #endif, successive blank lines
  407. pattern_if = re.compile(r'#\s*if(def|ndef)?\W') # #if, #ifdef, #ifndef
  408. pattern_elif = re.compile(r'#\s*el(if|se)\W') # #elif, #else
  409. pattern_endif = re.compile(r'#\s*endif\W') # #endif
  410. pattern_blank = re.compile(r'^\s*$') # empty line
  411. while True:
  412. old_matched = copy.copy(matched)
  413. extend_matched_lines(lines, matched, [pattern_if],
  414. [pattern_endif], True, True)
  415. extend_matched_lines(lines, matched, [pattern_elif],
  416. [pattern_elif, pattern_endif], True, False)
  417. extend_matched_lines(lines, matched, [pattern_if, pattern_elif],
  418. [pattern_blank], False, True)
  419. extend_matched_lines(lines, matched, [pattern_blank],
  420. [pattern_elif, pattern_endif], True, False)
  421. extend_matched_lines(lines, matched, [pattern_blank],
  422. [pattern_blank], True, False)
  423. if matched == old_matched:
  424. break
  425. tolines = copy.copy(lines)
  426. for i in reversed(matched):
  427. tolines.pop(i)
  428. show_diff(lines, tolines, header_path, options.color)
  429. if options.dry_run:
  430. return
  431. with open(header_path, 'w') as f:
  432. for line in tolines:
  433. f.write(line)
  434. def cleanup_headers(configs, options):
  435. """Delete config defines from board headers.
  436. Arguments:
  437. configs: A list of CONFIGs to remove.
  438. options: option flags.
  439. """
  440. if not confirm(options, 'Clean up headers?'):
  441. return
  442. patterns = []
  443. for config in configs:
  444. patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
  445. patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
  446. for dir in 'include', 'arch', 'board':
  447. for (dirpath, dirnames, filenames) in os.walk(dir):
  448. if dirpath == os.path.join('include', 'generated'):
  449. continue
  450. for filename in filenames:
  451. if not fnmatch.fnmatch(filename, '*~'):
  452. cleanup_one_header(os.path.join(dirpath, filename),
  453. patterns, options)
  454. def cleanup_one_extra_option(defconfig_path, configs, options):
  455. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in one defconfig file.
  456. Arguments:
  457. defconfig_path: path to the cleaned defconfig file.
  458. configs: A list of CONFIGs to remove.
  459. options: option flags.
  460. """
  461. start = 'CONFIG_SYS_EXTRA_OPTIONS="'
  462. end = '"\n'
  463. with open(defconfig_path) as f:
  464. lines = f.readlines()
  465. for i, line in enumerate(lines):
  466. if line.startswith(start) and line.endswith(end):
  467. break
  468. else:
  469. # CONFIG_SYS_EXTRA_OPTIONS was not found in this defconfig
  470. return
  471. old_tokens = line[len(start):-len(end)].split(',')
  472. new_tokens = []
  473. for token in old_tokens:
  474. pos = token.find('=')
  475. if not (token[:pos] if pos >= 0 else token) in configs:
  476. new_tokens.append(token)
  477. if new_tokens == old_tokens:
  478. return
  479. tolines = copy.copy(lines)
  480. if new_tokens:
  481. tolines[i] = start + ','.join(new_tokens) + end
  482. else:
  483. tolines.pop(i)
  484. show_diff(lines, tolines, defconfig_path, options.color)
  485. if options.dry_run:
  486. return
  487. with open(defconfig_path, 'w') as f:
  488. for line in tolines:
  489. f.write(line)
  490. def cleanup_extra_options(configs, options):
  491. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in defconfig files.
  492. Arguments:
  493. configs: A list of CONFIGs to remove.
  494. options: option flags.
  495. """
  496. if not confirm(options, 'Clean up CONFIG_SYS_EXTRA_OPTIONS?'):
  497. return
  498. configs = [ config[len('CONFIG_'):] for config in configs ]
  499. defconfigs = get_all_defconfigs()
  500. for defconfig in defconfigs:
  501. cleanup_one_extra_option(os.path.join('configs', defconfig), configs,
  502. options)
  503. def cleanup_whitelist(configs, options):
  504. """Delete config whitelist entries
  505. Arguments:
  506. configs: A list of CONFIGs to remove.
  507. options: option flags.
  508. """
  509. if not confirm(options, 'Clean up whitelist entries?'):
  510. return
  511. with open(os.path.join('scripts', 'config_whitelist.txt')) as f:
  512. lines = f.readlines()
  513. lines = [x for x in lines if x.strip() not in configs]
  514. with open(os.path.join('scripts', 'config_whitelist.txt'), 'w') as f:
  515. f.write(''.join(lines))
  516. def find_matching(patterns, line):
  517. for pat in patterns:
  518. if pat.search(line):
  519. return True
  520. return False
  521. def cleanup_readme(configs, options):
  522. """Delete config description in README
  523. Arguments:
  524. configs: A list of CONFIGs to remove.
  525. options: option flags.
  526. """
  527. if not confirm(options, 'Clean up README?'):
  528. return
  529. patterns = []
  530. for config in configs:
  531. patterns.append(re.compile(r'^\s+%s' % config))
  532. with open('README') as f:
  533. lines = f.readlines()
  534. found = False
  535. newlines = []
  536. for line in lines:
  537. if not found:
  538. found = find_matching(patterns, line)
  539. if found:
  540. continue
  541. if found and re.search(r'^\s+CONFIG', line):
  542. found = False
  543. if not found:
  544. newlines.append(line)
  545. with open('README', 'w') as f:
  546. f.write(''.join(newlines))
  547. ### classes ###
  548. class Progress:
  549. """Progress Indicator"""
  550. def __init__(self, total):
  551. """Create a new progress indicator.
  552. Arguments:
  553. total: A number of defconfig files to process.
  554. """
  555. self.current = 0
  556. self.total = total
  557. def inc(self):
  558. """Increment the number of processed defconfig files."""
  559. self.current += 1
  560. def show(self):
  561. """Display the progress."""
  562. print ' %d defconfigs out of %d\r' % (self.current, self.total),
  563. sys.stdout.flush()
  564. class KconfigParser:
  565. """A parser of .config and include/autoconf.mk."""
  566. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  567. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  568. def __init__(self, configs, options, build_dir):
  569. """Create a new parser.
  570. Arguments:
  571. configs: A list of CONFIGs to move.
  572. options: option flags.
  573. build_dir: Build directory.
  574. """
  575. self.configs = configs
  576. self.options = options
  577. self.dotconfig = os.path.join(build_dir, '.config')
  578. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  579. self.spl_autoconf = os.path.join(build_dir, 'spl', 'include',
  580. 'autoconf.mk')
  581. self.config_autoconf = os.path.join(build_dir, 'include', 'config',
  582. 'auto.conf')
  583. self.defconfig = os.path.join(build_dir, 'defconfig')
  584. def get_cross_compile(self):
  585. """Parse .config file and return CROSS_COMPILE.
  586. Returns:
  587. A string storing the compiler prefix for the architecture.
  588. Return a NULL string for architectures that do not require
  589. compiler prefix (Sandbox and native build is the case).
  590. Return None if the specified compiler is missing in your PATH.
  591. Caller should distinguish '' and None.
  592. """
  593. arch = ''
  594. cpu = ''
  595. for line in open(self.dotconfig):
  596. m = self.re_arch.match(line)
  597. if m:
  598. arch = m.group(1)
  599. continue
  600. m = self.re_cpu.match(line)
  601. if m:
  602. cpu = m.group(1)
  603. if not arch:
  604. return None
  605. # fix-up for aarch64
  606. if arch == 'arm' and cpu == 'armv8':
  607. arch = 'aarch64'
  608. return CROSS_COMPILE.get(arch, None)
  609. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  610. """Parse .config, defconfig, include/autoconf.mk for one config.
  611. This function looks for the config options in the lines from
  612. defconfig, .config, and include/autoconf.mk in order to decide
  613. which action should be taken for this defconfig.
  614. Arguments:
  615. config: CONFIG name to parse.
  616. dotconfig_lines: lines from the .config file.
  617. autoconf_lines: lines from the include/autoconf.mk file.
  618. Returns:
  619. A tupple of the action for this defconfig and the line
  620. matched for the config.
  621. """
  622. not_set = '# %s is not set' % config
  623. for line in autoconf_lines:
  624. line = line.rstrip()
  625. if line.startswith(config + '='):
  626. new_val = line
  627. break
  628. else:
  629. new_val = not_set
  630. for line in dotconfig_lines:
  631. line = line.rstrip()
  632. if line.startswith(config + '=') or line == not_set:
  633. old_val = line
  634. break
  635. else:
  636. if new_val == not_set:
  637. return (ACTION_NO_ENTRY, config)
  638. else:
  639. return (ACTION_NO_ENTRY_WARN, config)
  640. # If this CONFIG is neither bool nor trisate
  641. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  642. # tools/scripts/define2mk.sed changes '1' to 'y'.
  643. # This is a problem if the CONFIG is int type.
  644. # Check the type in Kconfig and handle it correctly.
  645. if new_val[-2:] == '=y':
  646. new_val = new_val[:-1] + '1'
  647. return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
  648. new_val)
  649. def update_dotconfig(self):
  650. """Parse files for the config options and update the .config.
  651. This function parses the generated .config and include/autoconf.mk
  652. searching the target options.
  653. Move the config option(s) to the .config as needed.
  654. Arguments:
  655. defconfig: defconfig name.
  656. Returns:
  657. Return a tuple of (updated flag, log string).
  658. The "updated flag" is True if the .config was updated, False
  659. otherwise. The "log string" shows what happend to the .config.
  660. """
  661. results = []
  662. updated = False
  663. suspicious = False
  664. rm_files = [self.config_autoconf, self.autoconf]
  665. if self.options.spl:
  666. if os.path.exists(self.spl_autoconf):
  667. autoconf_path = self.spl_autoconf
  668. rm_files.append(self.spl_autoconf)
  669. else:
  670. for f in rm_files:
  671. os.remove(f)
  672. return (updated, suspicious,
  673. color_text(self.options.color, COLOR_BROWN,
  674. "SPL is not enabled. Skipped.") + '\n')
  675. else:
  676. autoconf_path = self.autoconf
  677. with open(self.dotconfig) as f:
  678. dotconfig_lines = f.readlines()
  679. with open(autoconf_path) as f:
  680. autoconf_lines = f.readlines()
  681. for config in self.configs:
  682. result = self.parse_one_config(config, dotconfig_lines,
  683. autoconf_lines)
  684. results.append(result)
  685. log = ''
  686. for (action, value) in results:
  687. if action == ACTION_MOVE:
  688. actlog = "Move '%s'" % value
  689. log_color = COLOR_LIGHT_GREEN
  690. elif action == ACTION_NO_ENTRY:
  691. actlog = "%s is not defined in Kconfig. Do nothing." % value
  692. log_color = COLOR_LIGHT_BLUE
  693. elif action == ACTION_NO_ENTRY_WARN:
  694. actlog = "%s is not defined in Kconfig (suspicious). Do nothing." % value
  695. log_color = COLOR_YELLOW
  696. suspicious = True
  697. elif action == ACTION_NO_CHANGE:
  698. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  699. % value
  700. log_color = COLOR_LIGHT_PURPLE
  701. elif action == ACTION_SPL_NOT_EXIST:
  702. actlog = "SPL is not enabled for this defconfig. Skip."
  703. log_color = COLOR_PURPLE
  704. else:
  705. sys.exit("Internal Error. This should not happen.")
  706. log += color_text(self.options.color, log_color, actlog) + '\n'
  707. with open(self.dotconfig, 'a') as f:
  708. for (action, value) in results:
  709. if action == ACTION_MOVE:
  710. f.write(value + '\n')
  711. updated = True
  712. self.results = results
  713. for f in rm_files:
  714. os.remove(f)
  715. return (updated, suspicious, log)
  716. def check_defconfig(self):
  717. """Check the defconfig after savedefconfig
  718. Returns:
  719. Return additional log if moved CONFIGs were removed again by
  720. 'make savedefconfig'.
  721. """
  722. log = ''
  723. with open(self.defconfig) as f:
  724. defconfig_lines = f.readlines()
  725. for (action, value) in self.results:
  726. if action != ACTION_MOVE:
  727. continue
  728. if not value + '\n' in defconfig_lines:
  729. log += color_text(self.options.color, COLOR_YELLOW,
  730. "'%s' was removed by savedefconfig.\n" %
  731. value)
  732. return log
  733. class Slot:
  734. """A slot to store a subprocess.
  735. Each instance of this class handles one subprocess.
  736. This class is useful to control multiple threads
  737. for faster processing.
  738. """
  739. def __init__(self, configs, options, progress, devnull, make_cmd, reference_src_dir):
  740. """Create a new process slot.
  741. Arguments:
  742. configs: A list of CONFIGs to move.
  743. options: option flags.
  744. progress: A progress indicator.
  745. devnull: A file object of '/dev/null'.
  746. make_cmd: command name of GNU Make.
  747. reference_src_dir: Determine the true starting config state from this
  748. source tree.
  749. """
  750. self.options = options
  751. self.progress = progress
  752. self.build_dir = tempfile.mkdtemp()
  753. self.devnull = devnull
  754. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  755. self.reference_src_dir = reference_src_dir
  756. self.parser = KconfigParser(configs, options, self.build_dir)
  757. self.state = STATE_IDLE
  758. self.failed_boards = set()
  759. self.suspicious_boards = set()
  760. def __del__(self):
  761. """Delete the working directory
  762. This function makes sure the temporary directory is cleaned away
  763. even if Python suddenly dies due to error. It should be done in here
  764. because it is guaranteed the destructor is always invoked when the
  765. instance of the class gets unreferenced.
  766. If the subprocess is still running, wait until it finishes.
  767. """
  768. if self.state != STATE_IDLE:
  769. while self.ps.poll() == None:
  770. pass
  771. shutil.rmtree(self.build_dir)
  772. def add(self, defconfig):
  773. """Assign a new subprocess for defconfig and add it to the slot.
  774. If the slot is vacant, create a new subprocess for processing the
  775. given defconfig and add it to the slot. Just returns False if
  776. the slot is occupied (i.e. the current subprocess is still running).
  777. Arguments:
  778. defconfig: defconfig name.
  779. Returns:
  780. Return True on success or False on failure
  781. """
  782. if self.state != STATE_IDLE:
  783. return False
  784. self.defconfig = defconfig
  785. self.log = ''
  786. self.current_src_dir = self.reference_src_dir
  787. self.do_defconfig()
  788. return True
  789. def poll(self):
  790. """Check the status of the subprocess and handle it as needed.
  791. Returns True if the slot is vacant (i.e. in idle state).
  792. If the configuration is successfully finished, assign a new
  793. subprocess to build include/autoconf.mk.
  794. If include/autoconf.mk is generated, invoke the parser to
  795. parse the .config and the include/autoconf.mk, moving
  796. config options to the .config as needed.
  797. If the .config was updated, run "make savedefconfig" to sync
  798. it, update the original defconfig, and then set the slot back
  799. to the idle state.
  800. Returns:
  801. Return True if the subprocess is terminated, False otherwise
  802. """
  803. if self.state == STATE_IDLE:
  804. return True
  805. if self.ps.poll() == None:
  806. return False
  807. if self.ps.poll() != 0:
  808. self.handle_error()
  809. elif self.state == STATE_DEFCONFIG:
  810. if self.reference_src_dir and not self.current_src_dir:
  811. self.do_savedefconfig()
  812. else:
  813. self.do_autoconf()
  814. elif self.state == STATE_AUTOCONF:
  815. if self.current_src_dir:
  816. self.current_src_dir = None
  817. self.do_defconfig()
  818. else:
  819. self.do_savedefconfig()
  820. elif self.state == STATE_SAVEDEFCONFIG:
  821. self.update_defconfig()
  822. else:
  823. sys.exit("Internal Error. This should not happen.")
  824. return True if self.state == STATE_IDLE else False
  825. def handle_error(self):
  826. """Handle error cases."""
  827. self.log += color_text(self.options.color, COLOR_LIGHT_RED,
  828. "Failed to process.\n")
  829. if self.options.verbose:
  830. self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
  831. self.ps.stderr.read())
  832. self.finish(False)
  833. def do_defconfig(self):
  834. """Run 'make <board>_defconfig' to create the .config file."""
  835. cmd = list(self.make_cmd)
  836. cmd.append(self.defconfig)
  837. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  838. stderr=subprocess.PIPE,
  839. cwd=self.current_src_dir)
  840. self.state = STATE_DEFCONFIG
  841. def do_autoconf(self):
  842. """Run 'make include/config/auto.conf'."""
  843. self.cross_compile = self.parser.get_cross_compile()
  844. if self.cross_compile is None:
  845. self.log += color_text(self.options.color, COLOR_YELLOW,
  846. "Compiler is missing. Do nothing.\n")
  847. self.finish(False)
  848. return
  849. cmd = list(self.make_cmd)
  850. if self.cross_compile:
  851. cmd.append('CROSS_COMPILE=%s' % self.cross_compile)
  852. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  853. cmd.append('include/config/auto.conf')
  854. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  855. stderr=subprocess.PIPE,
  856. cwd=self.current_src_dir)
  857. self.state = STATE_AUTOCONF
  858. def do_savedefconfig(self):
  859. """Update the .config and run 'make savedefconfig'."""
  860. (updated, suspicious, log) = self.parser.update_dotconfig()
  861. if suspicious:
  862. self.suspicious_boards.add(self.defconfig)
  863. self.log += log
  864. if not self.options.force_sync and not updated:
  865. self.finish(True)
  866. return
  867. if updated:
  868. self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
  869. "Syncing by savedefconfig...\n")
  870. else:
  871. self.log += "Syncing by savedefconfig (forced by option)...\n"
  872. cmd = list(self.make_cmd)
  873. cmd.append('savedefconfig')
  874. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  875. stderr=subprocess.PIPE)
  876. self.state = STATE_SAVEDEFCONFIG
  877. def update_defconfig(self):
  878. """Update the input defconfig and go back to the idle state."""
  879. log = self.parser.check_defconfig()
  880. if log:
  881. self.suspicious_boards.add(self.defconfig)
  882. self.log += log
  883. orig_defconfig = os.path.join('configs', self.defconfig)
  884. new_defconfig = os.path.join(self.build_dir, 'defconfig')
  885. updated = not filecmp.cmp(orig_defconfig, new_defconfig)
  886. if updated:
  887. self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
  888. "defconfig was updated.\n")
  889. if not self.options.dry_run and updated:
  890. shutil.move(new_defconfig, orig_defconfig)
  891. self.finish(True)
  892. def finish(self, success):
  893. """Display log along with progress and go to the idle state.
  894. Arguments:
  895. success: Should be True when the defconfig was processed
  896. successfully, or False when it fails.
  897. """
  898. # output at least 30 characters to hide the "* defconfigs out of *".
  899. log = self.defconfig.ljust(30) + '\n'
  900. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  901. # Some threads are running in parallel.
  902. # Print log atomically to not mix up logs from different threads.
  903. print >> (sys.stdout if success else sys.stderr), log
  904. if not success:
  905. if self.options.exit_on_error:
  906. sys.exit("Exit on error.")
  907. # If --exit-on-error flag is not set, skip this board and continue.
  908. # Record the failed board.
  909. self.failed_boards.add(self.defconfig)
  910. self.progress.inc()
  911. self.progress.show()
  912. self.state = STATE_IDLE
  913. def get_failed_boards(self):
  914. """Returns a set of failed boards (defconfigs) in this slot.
  915. """
  916. return self.failed_boards
  917. def get_suspicious_boards(self):
  918. """Returns a set of boards (defconfigs) with possible misconversion.
  919. """
  920. return self.suspicious_boards - self.failed_boards
  921. class Slots:
  922. """Controller of the array of subprocess slots."""
  923. def __init__(self, configs, options, progress, reference_src_dir):
  924. """Create a new slots controller.
  925. Arguments:
  926. configs: A list of CONFIGs to move.
  927. options: option flags.
  928. progress: A progress indicator.
  929. reference_src_dir: Determine the true starting config state from this
  930. source tree.
  931. """
  932. self.options = options
  933. self.slots = []
  934. devnull = get_devnull()
  935. make_cmd = get_make_cmd()
  936. for i in range(options.jobs):
  937. self.slots.append(Slot(configs, options, progress, devnull,
  938. make_cmd, reference_src_dir))
  939. def add(self, defconfig):
  940. """Add a new subprocess if a vacant slot is found.
  941. Arguments:
  942. defconfig: defconfig name to be put into.
  943. Returns:
  944. Return True on success or False on failure
  945. """
  946. for slot in self.slots:
  947. if slot.add(defconfig):
  948. return True
  949. return False
  950. def available(self):
  951. """Check if there is a vacant slot.
  952. Returns:
  953. Return True if at lease one vacant slot is found, False otherwise.
  954. """
  955. for slot in self.slots:
  956. if slot.poll():
  957. return True
  958. return False
  959. def empty(self):
  960. """Check if all slots are vacant.
  961. Returns:
  962. Return True if all the slots are vacant, False otherwise.
  963. """
  964. ret = True
  965. for slot in self.slots:
  966. if not slot.poll():
  967. ret = False
  968. return ret
  969. def show_failed_boards(self):
  970. """Display all of the failed boards (defconfigs)."""
  971. boards = set()
  972. output_file = 'moveconfig.failed'
  973. for slot in self.slots:
  974. boards |= slot.get_failed_boards()
  975. if boards:
  976. boards = '\n'.join(boards) + '\n'
  977. msg = "The following boards were not processed due to error:\n"
  978. msg += boards
  979. msg += "(the list has been saved in %s)\n" % output_file
  980. print >> sys.stderr, color_text(self.options.color, COLOR_LIGHT_RED,
  981. msg)
  982. with open(output_file, 'w') as f:
  983. f.write(boards)
  984. def show_suspicious_boards(self):
  985. """Display all boards (defconfigs) with possible misconversion."""
  986. boards = set()
  987. output_file = 'moveconfig.suspicious'
  988. for slot in self.slots:
  989. boards |= slot.get_suspicious_boards()
  990. if boards:
  991. boards = '\n'.join(boards) + '\n'
  992. msg = "The following boards might have been converted incorrectly.\n"
  993. msg += "It is highly recommended to check them manually:\n"
  994. msg += boards
  995. msg += "(the list has been saved in %s)\n" % output_file
  996. print >> sys.stderr, color_text(self.options.color, COLOR_YELLOW,
  997. msg)
  998. with open(output_file, 'w') as f:
  999. f.write(boards)
  1000. class ReferenceSource:
  1001. """Reference source against which original configs should be parsed."""
  1002. def __init__(self, commit):
  1003. """Create a reference source directory based on a specified commit.
  1004. Arguments:
  1005. commit: commit to git-clone
  1006. """
  1007. self.src_dir = tempfile.mkdtemp()
  1008. print "Cloning git repo to a separate work directory..."
  1009. subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
  1010. cwd=self.src_dir)
  1011. print "Checkout '%s' to build the original autoconf.mk." % \
  1012. subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip()
  1013. subprocess.check_output(['git', 'checkout', commit],
  1014. stderr=subprocess.STDOUT, cwd=self.src_dir)
  1015. def __del__(self):
  1016. """Delete the reference source directory
  1017. This function makes sure the temporary directory is cleaned away
  1018. even if Python suddenly dies due to error. It should be done in here
  1019. because it is guaranteed the destructor is always invoked when the
  1020. instance of the class gets unreferenced.
  1021. """
  1022. shutil.rmtree(self.src_dir)
  1023. def get_dir(self):
  1024. """Return the absolute path to the reference source directory."""
  1025. return self.src_dir
  1026. def move_config(configs, options):
  1027. """Move config options to defconfig files.
  1028. Arguments:
  1029. configs: A list of CONFIGs to move.
  1030. options: option flags
  1031. """
  1032. if len(configs) == 0:
  1033. if options.force_sync:
  1034. print 'No CONFIG is specified. You are probably syncing defconfigs.',
  1035. else:
  1036. print 'Neither CONFIG nor --force-sync is specified. Nothing will happen.',
  1037. else:
  1038. print 'Move ' + ', '.join(configs),
  1039. print '(jobs: %d)\n' % options.jobs
  1040. if options.git_ref:
  1041. reference_src = ReferenceSource(options.git_ref)
  1042. reference_src_dir = reference_src.get_dir()
  1043. else:
  1044. reference_src_dir = None
  1045. if options.defconfigs:
  1046. defconfigs = get_matched_defconfigs(options.defconfigs)
  1047. else:
  1048. defconfigs = get_all_defconfigs()
  1049. progress = Progress(len(defconfigs))
  1050. slots = Slots(configs, options, progress, reference_src_dir)
  1051. # Main loop to process defconfig files:
  1052. # Add a new subprocess into a vacant slot.
  1053. # Sleep if there is no available slot.
  1054. for defconfig in defconfigs:
  1055. while not slots.add(defconfig):
  1056. while not slots.available():
  1057. # No available slot: sleep for a while
  1058. time.sleep(SLEEP_TIME)
  1059. # wait until all the subprocesses finish
  1060. while not slots.empty():
  1061. time.sleep(SLEEP_TIME)
  1062. print ''
  1063. slots.show_failed_boards()
  1064. slots.show_suspicious_boards()
  1065. def main():
  1066. try:
  1067. cpu_count = multiprocessing.cpu_count()
  1068. except NotImplementedError:
  1069. cpu_count = 1
  1070. parser = optparse.OptionParser()
  1071. # Add options here
  1072. parser.add_option('-c', '--color', action='store_true', default=False,
  1073. help='display the log in color')
  1074. parser.add_option('-C', '--commit', action='store_true', default=False,
  1075. help='Create a git commit for the operation')
  1076. parser.add_option('-d', '--defconfigs', type='string',
  1077. help='a file containing a list of defconfigs to move, '
  1078. "one per line (for example 'snow_defconfig') "
  1079. "or '-' to read from stdin")
  1080. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  1081. help='perform a trial run (show log with no changes)')
  1082. parser.add_option('-e', '--exit-on-error', action='store_true',
  1083. default=False,
  1084. help='exit immediately on any error')
  1085. parser.add_option('-s', '--force-sync', action='store_true', default=False,
  1086. help='force sync by savedefconfig')
  1087. parser.add_option('-S', '--spl', action='store_true', default=False,
  1088. help='parse config options defined for SPL build')
  1089. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  1090. action='store_true', default=False,
  1091. help='only cleanup the headers')
  1092. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  1093. help='the number of jobs to run simultaneously')
  1094. parser.add_option('-r', '--git-ref', type='string',
  1095. help='the git ref to clone for building the autoconf.mk')
  1096. parser.add_option('-y', '--yes', action='store_true', default=False,
  1097. help="respond 'yes' to any prompts")
  1098. parser.add_option('-v', '--verbose', action='store_true', default=False,
  1099. help='show any build errors as boards are built')
  1100. parser.usage += ' CONFIG ...'
  1101. (options, configs) = parser.parse_args()
  1102. if len(configs) == 0 and not options.force_sync:
  1103. parser.print_usage()
  1104. sys.exit(1)
  1105. # prefix the option name with CONFIG_ if missing
  1106. configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
  1107. for config in configs ]
  1108. check_top_directory()
  1109. if not options.cleanup_headers_only:
  1110. check_clean_directory()
  1111. update_cross_compile(options.color)
  1112. move_config(configs, options)
  1113. if configs:
  1114. cleanup_headers(configs, options)
  1115. cleanup_extra_options(configs, options)
  1116. cleanup_whitelist(configs, options)
  1117. cleanup_readme(configs, options)
  1118. if options.commit:
  1119. subprocess.call(['git', 'add', '-u'])
  1120. if configs:
  1121. msg = 'Convert %s %sto Kconfig' % (configs[0],
  1122. 'et al ' if len(configs) > 1 else '')
  1123. msg += ('\n\nThis converts the following to Kconfig:\n %s\n' %
  1124. '\n '.join(configs))
  1125. else:
  1126. msg = 'configs: Resync with savedefconfig'
  1127. msg += '\n\nRsync all defconfig files using moveconfig.py'
  1128. subprocess.call(['git', 'commit', '-s', '-m', msg])
  1129. if __name__ == '__main__':
  1130. main()