config.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. #!/usr/bin/env python3
  2. """Mbed TLS configuration file manipulation library and tool
  3. Basic usage, to read the Mbed TLS or Mbed Crypto configuration:
  4. config = ConfigFile()
  5. if 'MBEDTLS_RSA_C' in config: print('RSA is enabled')
  6. """
  7. # Note that as long as Mbed TLS 2.28 LTS is maintained, the version of
  8. # this script in the mbedtls-2.28 branch must remain compatible with
  9. # Python 3.4. The version in development may only use more recent features
  10. # in parts that are not backported to 2.28.
  11. ## Copyright The Mbed TLS Contributors
  12. ## SPDX-License-Identifier: Apache-2.0
  13. ##
  14. ## Licensed under the Apache License, Version 2.0 (the "License"); you may
  15. ## not use this file except in compliance with the License.
  16. ## You may obtain a copy of the License at
  17. ##
  18. ## http://www.apache.org/licenses/LICENSE-2.0
  19. ##
  20. ## Unless required by applicable law or agreed to in writing, software
  21. ## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  22. ## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. ## See the License for the specific language governing permissions and
  24. ## limitations under the License.
  25. import os
  26. import re
  27. class Setting:
  28. """Representation of one Mbed TLS mbedtls_config.h setting.
  29. Fields:
  30. * name: the symbol name ('MBEDTLS_xxx').
  31. * value: the value of the macro. The empty string for a plain #define
  32. with no value.
  33. * active: True if name is defined, False if a #define for name is
  34. present in mbedtls_config.h but commented out.
  35. * section: the name of the section that contains this symbol.
  36. """
  37. # pylint: disable=too-few-public-methods
  38. def __init__(self, active, name, value='', section=None):
  39. self.active = active
  40. self.name = name
  41. self.value = value
  42. self.section = section
  43. class Config:
  44. """Representation of the Mbed TLS configuration.
  45. In the documentation of this class, a symbol is said to be *active*
  46. if there is a #define for it that is not commented out, and *known*
  47. if there is a #define for it whether commented out or not.
  48. This class supports the following protocols:
  49. * `name in config` is `True` if the symbol `name` is active, `False`
  50. otherwise (whether `name` is inactive or not known).
  51. * `config[name]` is the value of the macro `name`. If `name` is inactive,
  52. raise `KeyError` (even if `name` is known).
  53. * `config[name] = value` sets the value associated to `name`. `name`
  54. must be known, but does not need to be set. This does not cause
  55. name to become set.
  56. """
  57. def __init__(self):
  58. self.settings = {}
  59. def __contains__(self, name):
  60. """True if the given symbol is active (i.e. set).
  61. False if the given symbol is not set, even if a definition
  62. is present but commented out.
  63. """
  64. return name in self.settings and self.settings[name].active
  65. def all(self, *names):
  66. """True if all the elements of names are active (i.e. set)."""
  67. return all(self.__contains__(name) for name in names)
  68. def any(self, *names):
  69. """True if at least one symbol in names are active (i.e. set)."""
  70. return any(self.__contains__(name) for name in names)
  71. def known(self, name):
  72. """True if a #define for name is present, whether it's commented out or not."""
  73. return name in self.settings
  74. def __getitem__(self, name):
  75. """Get the value of name, i.e. what the preprocessor symbol expands to.
  76. If name is not known, raise KeyError. name does not need to be active.
  77. """
  78. return self.settings[name].value
  79. def get(self, name, default=None):
  80. """Get the value of name. If name is inactive (not set), return default.
  81. If a #define for name is present and not commented out, return
  82. its expansion, even if this is the empty string.
  83. If a #define for name is present but commented out, return default.
  84. """
  85. if name in self.settings:
  86. return self.settings[name].value
  87. else:
  88. return default
  89. def __setitem__(self, name, value):
  90. """If name is known, set its value.
  91. If name is not known, raise KeyError.
  92. """
  93. self.settings[name].value = value
  94. def set(self, name, value=None):
  95. """Set name to the given value and make it active.
  96. If value is None and name is already known, don't change its value.
  97. If value is None and name is not known, set its value to the empty
  98. string.
  99. """
  100. if name in self.settings:
  101. if value is not None:
  102. self.settings[name].value = value
  103. self.settings[name].active = True
  104. else:
  105. self.settings[name] = Setting(True, name, value=value)
  106. def unset(self, name):
  107. """Make name unset (inactive).
  108. name remains known if it was known before.
  109. """
  110. if name not in self.settings:
  111. return
  112. self.settings[name].active = False
  113. def adapt(self, adapter):
  114. """Run adapter on each known symbol and (de)activate it accordingly.
  115. `adapter` must be a function that returns a boolean. It is called as
  116. `adapter(name, active, section)` for each setting, where `active` is
  117. `True` if `name` is set and `False` if `name` is known but unset,
  118. and `section` is the name of the section containing `name`. If
  119. `adapter` returns `True`, then set `name` (i.e. make it active),
  120. otherwise unset `name` (i.e. make it known but inactive).
  121. """
  122. for setting in self.settings.values():
  123. setting.active = adapter(setting.name, setting.active,
  124. setting.section)
  125. def change_matching(self, regexs, enable):
  126. """Change all symbols matching one of the regexs to the desired state."""
  127. if not regexs:
  128. return
  129. regex = re.compile('|'.join(regexs))
  130. for setting in self.settings.values():
  131. if regex.search(setting.name):
  132. setting.active = enable
  133. def is_full_section(section):
  134. """Is this section affected by "config.py full" and friends?"""
  135. return section.endswith('support') or section.endswith('modules')
  136. def realfull_adapter(_name, active, section):
  137. """Activate all symbols found in the global and boolean feature sections.
  138. This is intended for building the documentation, including the
  139. documentation of settings that are activated by defining an optional
  140. preprocessor macro.
  141. Do not activate definitions in the section containing symbols that are
  142. supposed to be defined and documented in their own module.
  143. """
  144. if section == 'Module configuration options':
  145. return active
  146. return True
  147. # The goal of the full configuration is to have everything that can be tested
  148. # together. This includes deprecated or insecure options. It excludes:
  149. # * Options that require additional build dependencies or unusual hardware.
  150. # * Options that make testing less effective.
  151. # * Options that are incompatible with other options, or more generally that
  152. # interact with other parts of the code in such a way that a bulk enabling
  153. # is not a good way to test them.
  154. # * Options that remove features.
  155. EXCLUDE_FROM_FULL = frozenset([
  156. #pylint: disable=line-too-long
  157. 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
  158. 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
  159. 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
  160. 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
  161. 'MBEDTLS_ECP_NO_FALLBACK', # removes internal ECP implementation
  162. 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
  163. 'MBEDTLS_HAVE_SSE2', # hardware dependency
  164. 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
  165. 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
  166. 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
  167. 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
  168. 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
  169. 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
  170. 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
  171. 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
  172. 'MBEDTLS_PSA_CRYPTO_CONFIG', # toggles old/new style PSA config
  173. 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
  174. 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
  175. 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
  176. 'MBEDTLS_PSA_INJECT_ENTROPY', # build dependency (hook functions)
  177. 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
  178. 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
  179. 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
  180. 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
  181. 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
  182. 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
  183. 'MBEDTLS_SSL_RECORD_SIZE_LIMIT', # in development, currently breaks other tests
  184. ])
  185. def is_seamless_alt(name):
  186. """Whether the xxx_ALT symbol should be included in the full configuration.
  187. Include alternative implementations of platform functions, which are
  188. configurable function pointers that default to the built-in function.
  189. This way we test that the function pointers exist and build correctly
  190. without changing the behavior, and tests can verify that the function
  191. pointers are used by modifying those pointers.
  192. Exclude alternative implementations of library functions since they require
  193. an implementation of the relevant functions and an xxx_alt.h header.
  194. """
  195. if name == 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT':
  196. # Similar to non-platform xxx_ALT, requires platform_alt.h
  197. return False
  198. return name.startswith('MBEDTLS_PLATFORM_')
  199. def include_in_full(name):
  200. """Rules for symbols in the "full" configuration."""
  201. if name in EXCLUDE_FROM_FULL:
  202. return False
  203. if name.endswith('_ALT'):
  204. return is_seamless_alt(name)
  205. return True
  206. def full_adapter(name, active, section):
  207. """Config adapter for "full"."""
  208. if not is_full_section(section):
  209. return active
  210. return include_in_full(name)
  211. # The baremetal configuration excludes options that require a library or
  212. # operating system feature that is typically not present on bare metal
  213. # systems. Features that are excluded from "full" won't be in "baremetal"
  214. # either (unless explicitly turned on in baremetal_adapter) so they don't
  215. # need to be repeated here.
  216. EXCLUDE_FROM_BAREMETAL = frozenset([
  217. #pylint: disable=line-too-long
  218. 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
  219. 'MBEDTLS_FS_IO', # requires a filesystem
  220. 'MBEDTLS_HAVE_TIME', # requires a clock
  221. 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
  222. 'MBEDTLS_NET_C', # requires POSIX-like networking
  223. 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
  224. 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
  225. 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
  226. 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
  227. 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
  228. 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
  229. 'MBEDTLS_THREADING_C', # requires a threading interface
  230. 'MBEDTLS_THREADING_PTHREAD', # requires pthread
  231. 'MBEDTLS_TIMING_C', # requires a clock
  232. ])
  233. def keep_in_baremetal(name):
  234. """Rules for symbols in the "baremetal" configuration."""
  235. if name in EXCLUDE_FROM_BAREMETAL:
  236. return False
  237. return True
  238. def baremetal_adapter(name, active, section):
  239. """Config adapter for "baremetal"."""
  240. if not is_full_section(section):
  241. return active
  242. if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
  243. # No OS-provided entropy source
  244. return True
  245. return include_in_full(name) and keep_in_baremetal(name)
  246. # This set contains options that are mostly for debugging or test purposes,
  247. # and therefore should be excluded when doing code size measurements.
  248. # Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
  249. # and therefore will be included when doing code size measurements.
  250. EXCLUDE_FOR_SIZE = frozenset([
  251. 'MBEDTLS_DEBUG_C', # large code size increase in TLS
  252. 'MBEDTLS_SELF_TEST', # increases the size of many modules
  253. 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
  254. ])
  255. def baremetal_size_adapter(name, active, section):
  256. if name in EXCLUDE_FOR_SIZE:
  257. return False
  258. return baremetal_adapter(name, active, section)
  259. def include_in_crypto(name):
  260. """Rules for symbols in a crypto configuration."""
  261. if name.startswith('MBEDTLS_X509_') or \
  262. name.startswith('MBEDTLS_SSL_') or \
  263. name.startswith('MBEDTLS_KEY_EXCHANGE_'):
  264. return False
  265. if name in [
  266. 'MBEDTLS_DEBUG_C', # part of libmbedtls
  267. 'MBEDTLS_NET_C', # part of libmbedtls
  268. 'MBEDTLS_PKCS7_C', # part of libmbedx509
  269. ]:
  270. return False
  271. return True
  272. def crypto_adapter(adapter):
  273. """Modify an adapter to disable non-crypto symbols.
  274. ``crypto_adapter(adapter)(name, active, section)`` is like
  275. ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
  276. """
  277. def continuation(name, active, section):
  278. if not include_in_crypto(name):
  279. return False
  280. if adapter is None:
  281. return active
  282. return adapter(name, active, section)
  283. return continuation
  284. DEPRECATED = frozenset([
  285. 'MBEDTLS_PSA_CRYPTO_SE_C',
  286. ])
  287. def no_deprecated_adapter(adapter):
  288. """Modify an adapter to disable deprecated symbols.
  289. ``no_deprecated_adapter(adapter)(name, active, section)`` is like
  290. ``adapter(name, active, section)``, but unsets all deprecated symbols
  291. and sets ``MBEDTLS_DEPRECATED_REMOVED``.
  292. """
  293. def continuation(name, active, section):
  294. if name == 'MBEDTLS_DEPRECATED_REMOVED':
  295. return True
  296. if name in DEPRECATED:
  297. return False
  298. if adapter is None:
  299. return active
  300. return adapter(name, active, section)
  301. return continuation
  302. class ConfigFile(Config):
  303. """Representation of the Mbed TLS configuration read for a file.
  304. See the documentation of the `Config` class for methods to query
  305. and modify the configuration.
  306. """
  307. _path_in_tree = 'include/mbedtls/mbedtls_config.h'
  308. default_path = [_path_in_tree,
  309. os.path.join(os.path.dirname(__file__),
  310. os.pardir,
  311. _path_in_tree),
  312. os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
  313. _path_in_tree)]
  314. def __init__(self, filename=None):
  315. """Read the Mbed TLS configuration file."""
  316. if filename is None:
  317. for candidate in self.default_path:
  318. if os.path.lexists(candidate):
  319. filename = candidate
  320. break
  321. else:
  322. raise Exception('Mbed TLS configuration file not found',
  323. self.default_path)
  324. super().__init__()
  325. self.filename = filename
  326. self.current_section = 'header'
  327. with open(filename, 'r', encoding='utf-8') as file:
  328. self.templates = [self._parse_line(line) for line in file]
  329. self.current_section = None
  330. def set(self, name, value=None):
  331. if name not in self.settings:
  332. self.templates.append((name, '', '#define ' + name + ' '))
  333. super().set(name, value)
  334. _define_line_regexp = (r'(?P<indentation>\s*)' +
  335. r'(?P<commented_out>(//\s*)?)' +
  336. r'(?P<define>#\s*define\s+)' +
  337. r'(?P<name>\w+)' +
  338. r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
  339. r'(?P<separator>\s*)' +
  340. r'(?P<value>.*)')
  341. _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
  342. r'(?P<section>.*)[ */]*')
  343. _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
  344. _section_line_regexp]))
  345. def _parse_line(self, line):
  346. """Parse a line in mbedtls_config.h and return the corresponding template."""
  347. line = line.rstrip('\r\n')
  348. m = re.match(self._config_line_regexp, line)
  349. if m is None:
  350. return line
  351. elif m.group('section'):
  352. self.current_section = m.group('section')
  353. return line
  354. else:
  355. active = not m.group('commented_out')
  356. name = m.group('name')
  357. value = m.group('value')
  358. template = (name,
  359. m.group('indentation'),
  360. m.group('define') + name +
  361. m.group('arguments') + m.group('separator'))
  362. self.settings[name] = Setting(active, name, value,
  363. self.current_section)
  364. return template
  365. def _format_template(self, name, indent, middle):
  366. """Build a line for mbedtls_config.h for the given setting.
  367. The line has the form "<indent>#define <name> <value>"
  368. where <middle> is "#define <name> ".
  369. """
  370. setting = self.settings[name]
  371. value = setting.value
  372. if value is None:
  373. value = ''
  374. # Normally the whitespace to separate the symbol name from the
  375. # value is part of middle, and there's no whitespace for a symbol
  376. # with no value. But if a symbol has been changed from having a
  377. # value to not having one, the whitespace is wrong, so fix it.
  378. if value:
  379. if middle[-1] not in '\t ':
  380. middle += ' '
  381. else:
  382. middle = middle.rstrip()
  383. return ''.join([indent,
  384. '' if setting.active else '//',
  385. middle,
  386. value]).rstrip()
  387. def write_to_stream(self, output):
  388. """Write the whole configuration to output."""
  389. for template in self.templates:
  390. if isinstance(template, str):
  391. line = template
  392. else:
  393. line = self._format_template(*template)
  394. output.write(line + '\n')
  395. def write(self, filename=None):
  396. """Write the whole configuration to the file it was read from.
  397. If filename is specified, write to this file instead.
  398. """
  399. if filename is None:
  400. filename = self.filename
  401. with open(filename, 'w', encoding='utf-8') as output:
  402. self.write_to_stream(output)
  403. if __name__ == '__main__':
  404. def main():
  405. """Command line mbedtls_config.h manipulation tool."""
  406. parser = argparse.ArgumentParser(description="""
  407. Mbed TLS and Mbed Crypto configuration file manipulation tool.
  408. """)
  409. parser.add_argument('--file', '-f',
  410. help="""File to read (and modify if requested).
  411. Default: {}.
  412. """.format(ConfigFile.default_path))
  413. parser.add_argument('--force', '-o',
  414. action='store_true',
  415. help="""For the set command, if SYMBOL is not
  416. present, add a definition for it.""")
  417. parser.add_argument('--write', '-w', metavar='FILE',
  418. help="""File to write to instead of the input file.""")
  419. subparsers = parser.add_subparsers(dest='command',
  420. title='Commands')
  421. parser_get = subparsers.add_parser('get',
  422. help="""Find the value of SYMBOL
  423. and print it. Exit with
  424. status 0 if a #define for SYMBOL is
  425. found, 1 otherwise.
  426. """)
  427. parser_get.add_argument('symbol', metavar='SYMBOL')
  428. parser_set = subparsers.add_parser('set',
  429. help="""Set SYMBOL to VALUE.
  430. If VALUE is omitted, just uncomment
  431. the #define for SYMBOL.
  432. Error out of a line defining
  433. SYMBOL (commented or not) is not
  434. found, unless --force is passed.
  435. """)
  436. parser_set.add_argument('symbol', metavar='SYMBOL')
  437. parser_set.add_argument('value', metavar='VALUE', nargs='?',
  438. default='')
  439. parser_set_all = subparsers.add_parser('set-all',
  440. help="""Uncomment all #define
  441. whose name contains a match for
  442. REGEX.""")
  443. parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*')
  444. parser_unset = subparsers.add_parser('unset',
  445. help="""Comment out the #define
  446. for SYMBOL. Do nothing if none
  447. is present.""")
  448. parser_unset.add_argument('symbol', metavar='SYMBOL')
  449. parser_unset_all = subparsers.add_parser('unset-all',
  450. help="""Comment out all #define
  451. whose name contains a match for
  452. REGEX.""")
  453. parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*')
  454. def add_adapter(name, function, description):
  455. subparser = subparsers.add_parser(name, help=description)
  456. subparser.set_defaults(adapter=function)
  457. add_adapter('baremetal', baremetal_adapter,
  458. """Like full, but exclude features that require platform
  459. features such as file input-output.""")
  460. add_adapter('baremetal_size', baremetal_size_adapter,
  461. """Like baremetal, but exclude debugging features.
  462. Useful for code size measurements.""")
  463. add_adapter('full', full_adapter,
  464. """Uncomment most features.
  465. Exclude alternative implementations and platform support
  466. options, as well as some options that are awkward to test.
  467. """)
  468. add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
  469. """Uncomment most non-deprecated features.
  470. Like "full", but without deprecated features.
  471. """)
  472. add_adapter('realfull', realfull_adapter,
  473. """Uncomment all boolean #defines.
  474. Suitable for generating documentation, but not for building.""")
  475. add_adapter('crypto', crypto_adapter(None),
  476. """Only include crypto features. Exclude X.509 and TLS.""")
  477. add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
  478. """Like baremetal, but with only crypto features,
  479. excluding X.509 and TLS.""")
  480. add_adapter('crypto_full', crypto_adapter(full_adapter),
  481. """Like full, but with only crypto features,
  482. excluding X.509 and TLS.""")
  483. args = parser.parse_args()
  484. config = ConfigFile(args.file)
  485. if args.command is None:
  486. parser.print_help()
  487. return 1
  488. elif args.command == 'get':
  489. if args.symbol in config:
  490. value = config[args.symbol]
  491. if value:
  492. sys.stdout.write(value + '\n')
  493. return 0 if args.symbol in config else 1
  494. elif args.command == 'set':
  495. if not args.force and args.symbol not in config.settings:
  496. sys.stderr.write("A #define for the symbol {} "
  497. "was not found in {}\n"
  498. .format(args.symbol, config.filename))
  499. return 1
  500. config.set(args.symbol, value=args.value)
  501. elif args.command == 'set-all':
  502. config.change_matching(args.regexs, True)
  503. elif args.command == 'unset':
  504. config.unset(args.symbol)
  505. elif args.command == 'unset-all':
  506. config.change_matching(args.regexs, False)
  507. else:
  508. config.adapt(args.adapter)
  509. config.write(args.write)
  510. return 0
  511. # Import modules only used by main only if main is defined and called.
  512. # pylint: disable=wrong-import-position
  513. import argparse
  514. import sys
  515. sys.exit(main())