main.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. """Mypy type checker command line tool."""
  2. from __future__ import annotations
  3. import argparse
  4. import os
  5. import subprocess
  6. import sys
  7. import time
  8. from gettext import gettext
  9. from typing import IO, Any, Final, NoReturn, Sequence, TextIO
  10. from mypy import build, defaults, state, util
  11. from mypy.config_parser import get_config_module_names, parse_config_file, parse_version
  12. from mypy.errorcodes import error_codes
  13. from mypy.errors import CompileError
  14. from mypy.find_sources import InvalidSourceList, create_source_list
  15. from mypy.fscache import FileSystemCache
  16. from mypy.modulefinder import BuildSource, FindModuleCache, SearchPaths, get_search_dirs, mypy_path
  17. from mypy.options import INCOMPLETE_FEATURES, BuildType, Options
  18. from mypy.split_namespace import SplitNamespace
  19. from mypy.version import __version__
  20. orig_stat: Final = os.stat
  21. MEM_PROFILE: Final = False # If True, dump memory profile
  22. def stat_proxy(path: str) -> os.stat_result:
  23. try:
  24. st = orig_stat(path)
  25. except os.error as err:
  26. print(f"stat({path!r}) -> {err}")
  27. raise
  28. else:
  29. print(
  30. "stat(%r) -> (st_mode=%o, st_mtime=%d, st_size=%d)"
  31. % (path, st.st_mode, st.st_mtime, st.st_size)
  32. )
  33. return st
  34. def main(
  35. *,
  36. args: list[str] | None = None,
  37. stdout: TextIO = sys.stdout,
  38. stderr: TextIO = sys.stderr,
  39. clean_exit: bool = False,
  40. ) -> None:
  41. """Main entry point to the type checker.
  42. Args:
  43. args: Custom command-line arguments. If not given, sys.argv[1:] will
  44. be used.
  45. clean_exit: Don't hard kill the process on exit. This allows catching
  46. SystemExit.
  47. """
  48. util.check_python_version("mypy")
  49. t0 = time.time()
  50. # To log stat() calls: os.stat = stat_proxy
  51. sys.setrecursionlimit(2**14)
  52. if args is None:
  53. args = sys.argv[1:]
  54. fscache = FileSystemCache()
  55. sources, options = process_options(args, stdout=stdout, stderr=stderr, fscache=fscache)
  56. if clean_exit:
  57. options.fast_exit = False
  58. formatter = util.FancyFormatter(stdout, stderr, options.hide_error_codes)
  59. if options.install_types and (stdout is not sys.stdout or stderr is not sys.stderr):
  60. # Since --install-types performs user input, we want regular stdout and stderr.
  61. fail("error: --install-types not supported in this mode of running mypy", stderr, options)
  62. if options.non_interactive and not options.install_types:
  63. fail("error: --non-interactive is only supported with --install-types", stderr, options)
  64. if options.install_types and not options.incremental:
  65. fail(
  66. "error: --install-types not supported with incremental mode disabled", stderr, options
  67. )
  68. if options.install_types and options.python_executable is None:
  69. fail(
  70. "error: --install-types not supported without python executable or site packages",
  71. stderr,
  72. options,
  73. )
  74. if options.install_types and not sources:
  75. install_types(formatter, options, non_interactive=options.non_interactive)
  76. return
  77. res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)
  78. if options.non_interactive:
  79. missing_pkgs = read_types_packages_to_install(options.cache_dir, after_run=True)
  80. if missing_pkgs:
  81. # Install missing type packages and rerun build.
  82. install_types(formatter, options, after_run=True, non_interactive=True)
  83. fscache.flush()
  84. print()
  85. res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)
  86. show_messages(messages, stderr, formatter, options)
  87. if MEM_PROFILE:
  88. from mypy.memprofile import print_memory_profile
  89. print_memory_profile()
  90. code = 0
  91. n_errors, n_notes, n_files = util.count_stats(messages)
  92. if messages and n_notes < len(messages):
  93. code = 2 if blockers else 1
  94. if options.error_summary:
  95. if n_errors:
  96. summary = formatter.format_error(
  97. n_errors, n_files, len(sources), blockers=blockers, use_color=options.color_output
  98. )
  99. stdout.write(summary + "\n")
  100. # Only notes should also output success
  101. elif not messages or n_notes == len(messages):
  102. stdout.write(formatter.format_success(len(sources), options.color_output) + "\n")
  103. stdout.flush()
  104. if options.install_types and not options.non_interactive:
  105. result = install_types(formatter, options, after_run=True, non_interactive=False)
  106. if result:
  107. print()
  108. print("note: Run mypy again for up-to-date results with installed types")
  109. code = 2
  110. if options.fast_exit:
  111. # Exit without freeing objects -- it's faster.
  112. #
  113. # NOTE: We don't flush all open files on exit (or run other destructors)!
  114. util.hard_exit(code)
  115. elif code:
  116. sys.exit(code)
  117. # HACK: keep res alive so that mypyc won't free it before the hard_exit
  118. list([res])
  119. def run_build(
  120. sources: list[BuildSource],
  121. options: Options,
  122. fscache: FileSystemCache,
  123. t0: float,
  124. stdout: TextIO,
  125. stderr: TextIO,
  126. ) -> tuple[build.BuildResult | None, list[str], bool]:
  127. formatter = util.FancyFormatter(stdout, stderr, options.hide_error_codes)
  128. messages = []
  129. def flush_errors(new_messages: list[str], serious: bool) -> None:
  130. if options.pretty:
  131. new_messages = formatter.fit_in_terminal(new_messages)
  132. messages.extend(new_messages)
  133. if options.non_interactive:
  134. # Collect messages and possibly show them later.
  135. return
  136. f = stderr if serious else stdout
  137. show_messages(new_messages, f, formatter, options)
  138. serious = False
  139. blockers = False
  140. res = None
  141. try:
  142. # Keep a dummy reference (res) for memory profiling afterwards, as otherwise
  143. # the result could be freed.
  144. res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
  145. except CompileError as e:
  146. blockers = True
  147. if not e.use_stdout:
  148. serious = True
  149. if (
  150. options.warn_unused_configs
  151. and options.unused_configs
  152. and not options.incremental
  153. and not options.non_interactive
  154. ):
  155. print(
  156. "Warning: unused section(s) in %s: %s"
  157. % (
  158. options.config_file,
  159. get_config_module_names(
  160. options.config_file,
  161. [
  162. glob
  163. for glob in options.per_module_options.keys()
  164. if glob in options.unused_configs
  165. ],
  166. ),
  167. ),
  168. file=stderr,
  169. )
  170. maybe_write_junit_xml(time.time() - t0, serious, messages, options)
  171. return res, messages, blockers
  172. def show_messages(
  173. messages: list[str], f: TextIO, formatter: util.FancyFormatter, options: Options
  174. ) -> None:
  175. for msg in messages:
  176. if options.color_output:
  177. msg = formatter.colorize(msg)
  178. f.write(msg + "\n")
  179. f.flush()
  180. # Make the help output a little less jarring.
  181. class AugmentedHelpFormatter(argparse.RawDescriptionHelpFormatter):
  182. def __init__(self, prog: str) -> None:
  183. super().__init__(prog=prog, max_help_position=28)
  184. def _fill_text(self, text: str, width: int, indent: str) -> str:
  185. if "\n" in text:
  186. # Assume we want to manually format the text
  187. return super()._fill_text(text, width, indent)
  188. else:
  189. # Assume we want argparse to manage wrapping, indenting, and
  190. # formatting the text for us.
  191. return argparse.HelpFormatter._fill_text(self, text, width, indent)
  192. # Define pairs of flag prefixes with inverse meaning.
  193. flag_prefix_pairs: Final = [("allow", "disallow"), ("show", "hide")]
  194. flag_prefix_map: Final[dict[str, str]] = {}
  195. for a, b in flag_prefix_pairs:
  196. flag_prefix_map[a] = b
  197. flag_prefix_map[b] = a
  198. def invert_flag_name(flag: str) -> str:
  199. split = flag[2:].split("-", 1)
  200. if len(split) == 2:
  201. prefix, rest = split
  202. if prefix in flag_prefix_map:
  203. return f"--{flag_prefix_map[prefix]}-{rest}"
  204. elif prefix == "no":
  205. return f"--{rest}"
  206. return f"--no-{flag[2:]}"
  207. class PythonExecutableInferenceError(Exception):
  208. """Represents a failure to infer the version or executable while searching."""
  209. def python_executable_prefix(v: str) -> list[str]:
  210. if sys.platform == "win32":
  211. # on Windows, all Python executables are named `python`. To handle this, there
  212. # is the `py` launcher, which can be passed a version e.g. `py -3.8`, and it will
  213. # execute an installed Python 3.8 interpreter. See also:
  214. # https://docs.python.org/3/using/windows.html#python-launcher-for-windows
  215. return ["py", f"-{v}"]
  216. else:
  217. return [f"python{v}"]
  218. def _python_executable_from_version(python_version: tuple[int, int]) -> str:
  219. if sys.version_info[:2] == python_version:
  220. return sys.executable
  221. str_ver = ".".join(map(str, python_version))
  222. try:
  223. sys_exe = (
  224. subprocess.check_output(
  225. python_executable_prefix(str_ver) + ["-c", "import sys; print(sys.executable)"],
  226. stderr=subprocess.STDOUT,
  227. )
  228. .decode()
  229. .strip()
  230. )
  231. return sys_exe
  232. except (subprocess.CalledProcessError, FileNotFoundError) as e:
  233. raise PythonExecutableInferenceError(
  234. "failed to find a Python executable matching version {},"
  235. " perhaps try --python-executable, or --no-site-packages?".format(python_version)
  236. ) from e
  237. def infer_python_executable(options: Options, special_opts: argparse.Namespace) -> None:
  238. """Infer the Python executable from the given version.
  239. This function mutates options based on special_opts to infer the correct Python executable
  240. to use.
  241. """
  242. # TODO: (ethanhs) Look at folding these checks and the site packages subprocess calls into
  243. # one subprocess call for speed.
  244. # Use the command line specified executable, or fall back to one set in the
  245. # config file. If an executable is not specified, infer it from the version
  246. # (unless no_executable is set)
  247. python_executable = special_opts.python_executable or options.python_executable
  248. if python_executable is None:
  249. if not special_opts.no_executable and not options.no_site_packages:
  250. python_executable = _python_executable_from_version(options.python_version)
  251. options.python_executable = python_executable
  252. HEADER: Final = """%(prog)s [-h] [-v] [-V] [more options; see below]
  253. [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]"""
  254. DESCRIPTION: Final = """
  255. Mypy is a program that will type check your Python code.
  256. Pass in any files or folders you want to type check. Mypy will
  257. recursively traverse any provided folders to find .py files:
  258. $ mypy my_program.py my_src_folder
  259. For more information on getting started, see:
  260. - https://mypy.readthedocs.io/en/stable/getting_started.html
  261. For more details on both running mypy and using the flags below, see:
  262. - https://mypy.readthedocs.io/en/stable/running_mypy.html
  263. - https://mypy.readthedocs.io/en/stable/command_line.html
  264. You can also use a config file to configure mypy instead of using
  265. command line flags. For more details, see:
  266. - https://mypy.readthedocs.io/en/stable/config_file.html
  267. """
  268. FOOTER: Final = """Environment variables:
  269. Define MYPYPATH for additional module search path entries.
  270. Define MYPY_CACHE_DIR to override configuration cache_dir path."""
  271. class CapturableArgumentParser(argparse.ArgumentParser):
  272. """Override ArgumentParser methods that use sys.stdout/sys.stderr directly.
  273. This is needed because hijacking sys.std* is not thread-safe,
  274. yet output must be captured to properly support mypy.api.run.
  275. """
  276. def __init__(self, *args: Any, **kwargs: Any):
  277. self.stdout = kwargs.pop("stdout", sys.stdout)
  278. self.stderr = kwargs.pop("stderr", sys.stderr)
  279. super().__init__(*args, **kwargs)
  280. # =====================
  281. # Help-printing methods
  282. # =====================
  283. def print_usage(self, file: IO[str] | None = None) -> None:
  284. if file is None:
  285. file = self.stdout
  286. self._print_message(self.format_usage(), file)
  287. def print_help(self, file: IO[str] | None = None) -> None:
  288. if file is None:
  289. file = self.stdout
  290. self._print_message(self.format_help(), file)
  291. def _print_message(self, message: str, file: IO[str] | None = None) -> None:
  292. if message:
  293. if file is None:
  294. file = self.stderr
  295. file.write(message)
  296. # ===============
  297. # Exiting methods
  298. # ===============
  299. def exit(self, status: int = 0, message: str | None = None) -> NoReturn:
  300. if message:
  301. self._print_message(message, self.stderr)
  302. sys.exit(status)
  303. def error(self, message: str) -> NoReturn:
  304. """error(message: string)
  305. Prints a usage message incorporating the message to stderr and
  306. exits.
  307. If you override this in a subclass, it should not return -- it
  308. should either exit or raise an exception.
  309. """
  310. self.print_usage(self.stderr)
  311. args = {"prog": self.prog, "message": message}
  312. self.exit(2, gettext("%(prog)s: error: %(message)s\n") % args)
  313. class CapturableVersionAction(argparse.Action):
  314. """Supplement CapturableArgumentParser to handle --version.
  315. This is nearly identical to argparse._VersionAction except,
  316. like CapturableArgumentParser, it allows output to be captured.
  317. Another notable difference is that version is mandatory.
  318. This allows removing a line in __call__ that falls back to parser.version
  319. (which does not appear to exist).
  320. """
  321. def __init__(
  322. self,
  323. option_strings: Sequence[str],
  324. version: str,
  325. dest: str = argparse.SUPPRESS,
  326. default: str = argparse.SUPPRESS,
  327. help: str = "show program's version number and exit",
  328. stdout: IO[str] | None = None,
  329. ):
  330. super().__init__(
  331. option_strings=option_strings, dest=dest, default=default, nargs=0, help=help
  332. )
  333. self.version = version
  334. self.stdout = stdout or sys.stdout
  335. def __call__(
  336. self,
  337. parser: argparse.ArgumentParser,
  338. namespace: argparse.Namespace,
  339. values: str | Sequence[Any] | None,
  340. option_string: str | None = None,
  341. ) -> NoReturn:
  342. formatter = parser._get_formatter()
  343. formatter.add_text(self.version)
  344. parser._print_message(formatter.format_help(), self.stdout)
  345. parser.exit()
  346. def process_options(
  347. args: list[str],
  348. stdout: TextIO | None = None,
  349. stderr: TextIO | None = None,
  350. require_targets: bool = True,
  351. server_options: bool = False,
  352. fscache: FileSystemCache | None = None,
  353. program: str = "mypy",
  354. header: str = HEADER,
  355. ) -> tuple[list[BuildSource], Options]:
  356. """Parse command line arguments.
  357. If a FileSystemCache is passed in, and package_root options are given,
  358. call fscache.set_package_root() to set the cache's package root.
  359. """
  360. stdout = stdout or sys.stdout
  361. stderr = stderr or sys.stderr
  362. parser = CapturableArgumentParser(
  363. prog=program,
  364. usage=header,
  365. description=DESCRIPTION,
  366. epilog=FOOTER,
  367. fromfile_prefix_chars="@",
  368. formatter_class=AugmentedHelpFormatter,
  369. add_help=False,
  370. stdout=stdout,
  371. stderr=stderr,
  372. )
  373. strict_flag_names: list[str] = []
  374. strict_flag_assignments: list[tuple[str, bool]] = []
  375. def add_invertible_flag(
  376. flag: str,
  377. *,
  378. inverse: str | None = None,
  379. default: bool,
  380. dest: str | None = None,
  381. help: str,
  382. strict_flag: bool = False,
  383. group: argparse._ActionsContainer | None = None,
  384. ) -> None:
  385. if inverse is None:
  386. inverse = invert_flag_name(flag)
  387. if group is None:
  388. group = parser
  389. if help is not argparse.SUPPRESS:
  390. help += f" (inverse: {inverse})"
  391. arg = group.add_argument(
  392. flag, action="store_false" if default else "store_true", dest=dest, help=help
  393. )
  394. dest = arg.dest
  395. group.add_argument(
  396. inverse,
  397. action="store_true" if default else "store_false",
  398. dest=dest,
  399. help=argparse.SUPPRESS,
  400. )
  401. if strict_flag:
  402. assert dest is not None
  403. strict_flag_names.append(flag)
  404. strict_flag_assignments.append((dest, not default))
  405. # Unless otherwise specified, arguments will be parsed directly onto an
  406. # Options object. Options that require further processing should have
  407. # their `dest` prefixed with `special-opts:`, which will cause them to be
  408. # parsed into the separate special_opts namespace object.
  409. # Note: we have a style guide for formatting the mypy --help text. See
  410. # https://github.com/python/mypy/wiki/Documentation-Conventions
  411. general_group = parser.add_argument_group(title="Optional arguments")
  412. general_group.add_argument(
  413. "-h", "--help", action="help", help="Show this help message and exit"
  414. )
  415. general_group.add_argument(
  416. "-v", "--verbose", action="count", dest="verbosity", help="More verbose messages"
  417. )
  418. compilation_status = "no" if __file__.endswith(".py") else "yes"
  419. general_group.add_argument(
  420. "-V",
  421. "--version",
  422. action=CapturableVersionAction,
  423. version="%(prog)s " + __version__ + f" (compiled: {compilation_status})",
  424. help="Show program's version number and exit",
  425. stdout=stdout,
  426. )
  427. config_group = parser.add_argument_group(
  428. title="Config file",
  429. description="Use a config file instead of command line arguments. "
  430. "This is useful if you are using many flags or want "
  431. "to set different options per each module.",
  432. )
  433. config_group.add_argument(
  434. "--config-file",
  435. help="Configuration file, must have a [mypy] section "
  436. "(defaults to {})".format(", ".join(defaults.CONFIG_FILES)),
  437. )
  438. add_invertible_flag(
  439. "--warn-unused-configs",
  440. default=False,
  441. strict_flag=True,
  442. help="Warn about unused '[mypy-<pattern>]' or '[[tool.mypy.overrides]]' "
  443. "config sections",
  444. group=config_group,
  445. )
  446. imports_group = parser.add_argument_group(
  447. title="Import discovery", description="Configure how imports are discovered and followed."
  448. )
  449. add_invertible_flag(
  450. "--no-namespace-packages",
  451. dest="namespace_packages",
  452. default=True,
  453. help="Support namespace packages (PEP 420, __init__.py-less)",
  454. group=imports_group,
  455. )
  456. imports_group.add_argument(
  457. "--ignore-missing-imports",
  458. action="store_true",
  459. help="Silently ignore imports of missing modules",
  460. )
  461. imports_group.add_argument(
  462. "--follow-imports",
  463. choices=["normal", "silent", "skip", "error"],
  464. default="normal",
  465. help="How to treat imports (default normal)",
  466. )
  467. imports_group.add_argument(
  468. "--python-executable",
  469. action="store",
  470. metavar="EXECUTABLE",
  471. help="Python executable used for finding PEP 561 compliant installed"
  472. " packages and stubs",
  473. dest="special-opts:python_executable",
  474. )
  475. imports_group.add_argument(
  476. "--no-site-packages",
  477. action="store_true",
  478. dest="special-opts:no_executable",
  479. help="Do not search for installed PEP 561 compliant packages",
  480. )
  481. imports_group.add_argument(
  482. "--no-silence-site-packages",
  483. action="store_true",
  484. help="Do not silence errors in PEP 561 compliant installed packages",
  485. )
  486. platform_group = parser.add_argument_group(
  487. title="Platform configuration",
  488. description="Type check code assuming it will be run under certain "
  489. "runtime conditions. By default, mypy assumes your code "
  490. "will be run using the same operating system and Python "
  491. "version you are using to run mypy itself.",
  492. )
  493. platform_group.add_argument(
  494. "--python-version",
  495. type=parse_version,
  496. metavar="x.y",
  497. help="Type check code assuming it will be running on Python x.y",
  498. dest="special-opts:python_version",
  499. )
  500. platform_group.add_argument(
  501. "-2",
  502. "--py2",
  503. dest="special-opts:python_version",
  504. action="store_const",
  505. const=defaults.PYTHON2_VERSION,
  506. help="Use Python 2 mode (same as --python-version 2.7)",
  507. )
  508. platform_group.add_argument(
  509. "--platform",
  510. action="store",
  511. metavar="PLATFORM",
  512. help="Type check special-cased code for the given OS platform "
  513. "(defaults to sys.platform)",
  514. )
  515. platform_group.add_argument(
  516. "--always-true",
  517. metavar="NAME",
  518. action="append",
  519. default=[],
  520. help="Additional variable to be considered True (may be repeated)",
  521. )
  522. platform_group.add_argument(
  523. "--always-false",
  524. metavar="NAME",
  525. action="append",
  526. default=[],
  527. help="Additional variable to be considered False (may be repeated)",
  528. )
  529. disallow_any_group = parser.add_argument_group(
  530. title="Disallow dynamic typing",
  531. description="Disallow the use of the dynamic 'Any' type under certain conditions.",
  532. )
  533. disallow_any_group.add_argument(
  534. "--disallow-any-unimported",
  535. default=False,
  536. action="store_true",
  537. help="Disallow Any types resulting from unfollowed imports",
  538. )
  539. disallow_any_group.add_argument(
  540. "--disallow-any-expr",
  541. default=False,
  542. action="store_true",
  543. help="Disallow all expressions that have type Any",
  544. )
  545. disallow_any_group.add_argument(
  546. "--disallow-any-decorated",
  547. default=False,
  548. action="store_true",
  549. help="Disallow functions that have Any in their signature "
  550. "after decorator transformation",
  551. )
  552. disallow_any_group.add_argument(
  553. "--disallow-any-explicit",
  554. default=False,
  555. action="store_true",
  556. help="Disallow explicit Any in type positions",
  557. )
  558. add_invertible_flag(
  559. "--disallow-any-generics",
  560. default=False,
  561. strict_flag=True,
  562. help="Disallow usage of generic types that do not specify explicit type parameters",
  563. group=disallow_any_group,
  564. )
  565. add_invertible_flag(
  566. "--disallow-subclassing-any",
  567. default=False,
  568. strict_flag=True,
  569. help="Disallow subclassing values of type 'Any' when defining classes",
  570. group=disallow_any_group,
  571. )
  572. untyped_group = parser.add_argument_group(
  573. title="Untyped definitions and calls",
  574. description="Configure how untyped definitions and calls are handled. "
  575. "Note: by default, mypy ignores any untyped function definitions "
  576. "and assumes any calls to such functions have a return "
  577. "type of 'Any'.",
  578. )
  579. add_invertible_flag(
  580. "--disallow-untyped-calls",
  581. default=False,
  582. strict_flag=True,
  583. help="Disallow calling functions without type annotations"
  584. " from functions with type annotations",
  585. group=untyped_group,
  586. )
  587. add_invertible_flag(
  588. "--disallow-untyped-defs",
  589. default=False,
  590. strict_flag=True,
  591. help="Disallow defining functions without type annotations"
  592. " or with incomplete type annotations",
  593. group=untyped_group,
  594. )
  595. add_invertible_flag(
  596. "--disallow-incomplete-defs",
  597. default=False,
  598. strict_flag=True,
  599. help="Disallow defining functions with incomplete type annotations "
  600. "(while still allowing entirely unannotated definitions)",
  601. group=untyped_group,
  602. )
  603. add_invertible_flag(
  604. "--check-untyped-defs",
  605. default=False,
  606. strict_flag=True,
  607. help="Type check the interior of functions without type annotations",
  608. group=untyped_group,
  609. )
  610. add_invertible_flag(
  611. "--disallow-untyped-decorators",
  612. default=False,
  613. strict_flag=True,
  614. help="Disallow decorating typed functions with untyped decorators",
  615. group=untyped_group,
  616. )
  617. none_group = parser.add_argument_group(
  618. title="None and Optional handling",
  619. description="Adjust how values of type 'None' are handled. For more context on "
  620. "how mypy handles values of type 'None', see: "
  621. "https://mypy.readthedocs.io/en/stable/kinds_of_types.html#no-strict-optional",
  622. )
  623. add_invertible_flag(
  624. "--implicit-optional",
  625. default=False,
  626. help="Assume arguments with default values of None are Optional",
  627. group=none_group,
  628. )
  629. none_group.add_argument("--strict-optional", action="store_true", help=argparse.SUPPRESS)
  630. none_group.add_argument(
  631. "--no-strict-optional",
  632. action="store_false",
  633. dest="strict_optional",
  634. help="Disable strict Optional checks (inverse: --strict-optional)",
  635. )
  636. add_invertible_flag(
  637. "--force-uppercase-builtins", default=False, help=argparse.SUPPRESS, group=none_group
  638. )
  639. add_invertible_flag(
  640. "--force-union-syntax", default=False, help=argparse.SUPPRESS, group=none_group
  641. )
  642. lint_group = parser.add_argument_group(
  643. title="Configuring warnings",
  644. description="Detect code that is sound but redundant or problematic.",
  645. )
  646. add_invertible_flag(
  647. "--warn-redundant-casts",
  648. default=False,
  649. strict_flag=True,
  650. help="Warn about casting an expression to its inferred type",
  651. group=lint_group,
  652. )
  653. add_invertible_flag(
  654. "--warn-unused-ignores",
  655. default=False,
  656. strict_flag=True,
  657. help="Warn about unneeded '# type: ignore' comments",
  658. group=lint_group,
  659. )
  660. add_invertible_flag(
  661. "--no-warn-no-return",
  662. dest="warn_no_return",
  663. default=True,
  664. help="Do not warn about functions that end without returning",
  665. group=lint_group,
  666. )
  667. add_invertible_flag(
  668. "--warn-return-any",
  669. default=False,
  670. strict_flag=True,
  671. help="Warn about returning values of type Any from non-Any typed functions",
  672. group=lint_group,
  673. )
  674. add_invertible_flag(
  675. "--warn-unreachable",
  676. default=False,
  677. strict_flag=False,
  678. help="Warn about statements or expressions inferred to be unreachable",
  679. group=lint_group,
  680. )
  681. # Note: this group is intentionally added here even though we don't add
  682. # --strict to this group near the end.
  683. #
  684. # That way, this group will appear after the various strictness groups
  685. # but before the remaining flags.
  686. # We add `--strict` near the end so we don't accidentally miss any strictness
  687. # flags that are added after this group.
  688. strictness_group = parser.add_argument_group(title="Miscellaneous strictness flags")
  689. add_invertible_flag(
  690. "--allow-untyped-globals",
  691. default=False,
  692. strict_flag=False,
  693. help="Suppress toplevel errors caused by missing annotations",
  694. group=strictness_group,
  695. )
  696. add_invertible_flag(
  697. "--allow-redefinition",
  698. default=False,
  699. strict_flag=False,
  700. help="Allow unconditional variable redefinition with a new type",
  701. group=strictness_group,
  702. )
  703. add_invertible_flag(
  704. "--no-implicit-reexport",
  705. default=True,
  706. strict_flag=True,
  707. dest="implicit_reexport",
  708. help="Treat imports as private unless aliased",
  709. group=strictness_group,
  710. )
  711. add_invertible_flag(
  712. "--strict-equality",
  713. default=False,
  714. strict_flag=True,
  715. help="Prohibit equality, identity, and container checks for non-overlapping types",
  716. group=strictness_group,
  717. )
  718. add_invertible_flag(
  719. "--extra-checks",
  720. default=False,
  721. strict_flag=True,
  722. help="Enable additional checks that are technically correct but may be impractical "
  723. "in real code. For example, this prohibits partial overlap in TypedDict updates, "
  724. "and makes arguments prepended via Concatenate positional-only",
  725. group=strictness_group,
  726. )
  727. strict_help = "Strict mode; enables the following flags: {}".format(
  728. ", ".join(strict_flag_names)
  729. )
  730. strictness_group.add_argument(
  731. "--strict", action="store_true", dest="special-opts:strict", help=strict_help
  732. )
  733. strictness_group.add_argument(
  734. "--disable-error-code",
  735. metavar="NAME",
  736. action="append",
  737. default=[],
  738. help="Disable a specific error code",
  739. )
  740. strictness_group.add_argument(
  741. "--enable-error-code",
  742. metavar="NAME",
  743. action="append",
  744. default=[],
  745. help="Enable a specific error code",
  746. )
  747. error_group = parser.add_argument_group(
  748. title="Configuring error messages",
  749. description="Adjust the amount of detail shown in error messages.",
  750. )
  751. add_invertible_flag(
  752. "--show-error-context",
  753. default=False,
  754. dest="show_error_context",
  755. help='Precede errors with "note:" messages explaining context',
  756. group=error_group,
  757. )
  758. add_invertible_flag(
  759. "--show-column-numbers",
  760. default=False,
  761. help="Show column numbers in error messages",
  762. group=error_group,
  763. )
  764. add_invertible_flag(
  765. "--show-error-end",
  766. default=False,
  767. help="Show end line/end column numbers in error messages."
  768. " This implies --show-column-numbers",
  769. group=error_group,
  770. )
  771. add_invertible_flag(
  772. "--hide-error-codes",
  773. default=False,
  774. help="Hide error codes in error messages",
  775. group=error_group,
  776. )
  777. add_invertible_flag(
  778. "--show-error-code-links",
  779. default=False,
  780. help="Show links to error code documentation",
  781. group=error_group,
  782. )
  783. add_invertible_flag(
  784. "--pretty",
  785. default=False,
  786. help="Use visually nicer output in error messages:"
  787. " Use soft word wrap, show source code snippets,"
  788. " and show error location markers",
  789. group=error_group,
  790. )
  791. add_invertible_flag(
  792. "--no-color-output",
  793. dest="color_output",
  794. default=True,
  795. help="Do not colorize error messages",
  796. group=error_group,
  797. )
  798. add_invertible_flag(
  799. "--no-error-summary",
  800. dest="error_summary",
  801. default=True,
  802. help="Do not show error stats summary",
  803. group=error_group,
  804. )
  805. add_invertible_flag(
  806. "--show-absolute-path",
  807. default=False,
  808. help="Show absolute paths to files",
  809. group=error_group,
  810. )
  811. error_group.add_argument(
  812. "--soft-error-limit",
  813. default=defaults.MANY_ERRORS_THRESHOLD,
  814. type=int,
  815. dest="many_errors_threshold",
  816. help=argparse.SUPPRESS,
  817. )
  818. incremental_group = parser.add_argument_group(
  819. title="Incremental mode",
  820. description="Adjust how mypy incrementally type checks and caches modules. "
  821. "Mypy caches type information about modules into a cache to "
  822. "let you speed up future invocations of mypy. Also see "
  823. "mypy's daemon mode: "
  824. "mypy.readthedocs.io/en/stable/mypy_daemon.html#mypy-daemon",
  825. )
  826. incremental_group.add_argument(
  827. "-i", "--incremental", action="store_true", help=argparse.SUPPRESS
  828. )
  829. incremental_group.add_argument(
  830. "--no-incremental",
  831. action="store_false",
  832. dest="incremental",
  833. help="Disable module cache (inverse: --incremental)",
  834. )
  835. incremental_group.add_argument(
  836. "--cache-dir",
  837. action="store",
  838. metavar="DIR",
  839. help="Store module cache info in the given folder in incremental mode "
  840. "(defaults to '{}')".format(defaults.CACHE_DIR),
  841. )
  842. add_invertible_flag(
  843. "--sqlite-cache",
  844. default=False,
  845. help="Use a sqlite database to store the cache",
  846. group=incremental_group,
  847. )
  848. incremental_group.add_argument(
  849. "--cache-fine-grained",
  850. action="store_true",
  851. help="Include fine-grained dependency information in the cache for the mypy daemon",
  852. )
  853. incremental_group.add_argument(
  854. "--skip-version-check",
  855. action="store_true",
  856. help="Allow using cache written by older mypy version",
  857. )
  858. incremental_group.add_argument(
  859. "--skip-cache-mtime-checks",
  860. action="store_true",
  861. help="Skip cache internal consistency checks based on mtime",
  862. )
  863. internals_group = parser.add_argument_group(
  864. title="Advanced options", description="Debug and customize mypy internals."
  865. )
  866. internals_group.add_argument("--pdb", action="store_true", help="Invoke pdb on fatal error")
  867. internals_group.add_argument(
  868. "--show-traceback", "--tb", action="store_true", help="Show traceback on fatal error"
  869. )
  870. internals_group.add_argument(
  871. "--raise-exceptions", action="store_true", help="Raise exception on fatal error"
  872. )
  873. internals_group.add_argument(
  874. "--custom-typing-module",
  875. metavar="MODULE",
  876. dest="custom_typing_module",
  877. help="Use a custom typing module",
  878. )
  879. internals_group.add_argument(
  880. "--new-type-inference",
  881. action="store_true",
  882. help="Enable new experimental type inference algorithm",
  883. )
  884. internals_group.add_argument(
  885. "--disable-recursive-aliases",
  886. action="store_true",
  887. help="Disable experimental support for recursive type aliases",
  888. )
  889. # Deprecated reverse variant of the above.
  890. internals_group.add_argument(
  891. "--enable-recursive-aliases", action="store_true", help=argparse.SUPPRESS
  892. )
  893. parser.add_argument(
  894. "--enable-incomplete-feature",
  895. action="append",
  896. metavar="FEATURE",
  897. help="Enable support of incomplete/experimental features for early preview",
  898. )
  899. internals_group.add_argument(
  900. "--custom-typeshed-dir", metavar="DIR", help="Use the custom typeshed in DIR"
  901. )
  902. add_invertible_flag(
  903. "--warn-incomplete-stub",
  904. default=False,
  905. help="Warn if missing type annotation in typeshed, only relevant with"
  906. " --disallow-untyped-defs or --disallow-incomplete-defs enabled",
  907. group=internals_group,
  908. )
  909. internals_group.add_argument(
  910. "--shadow-file",
  911. nargs=2,
  912. metavar=("SOURCE_FILE", "SHADOW_FILE"),
  913. dest="shadow_file",
  914. action="append",
  915. help="When encountering SOURCE_FILE, read and type check "
  916. "the contents of SHADOW_FILE instead.",
  917. )
  918. internals_group.add_argument("--fast-exit", action="store_true", help=argparse.SUPPRESS)
  919. internals_group.add_argument(
  920. "--no-fast-exit", action="store_false", dest="fast_exit", help=argparse.SUPPRESS
  921. )
  922. # This flag is useful for mypy tests, where function bodies may be omitted. Plugin developers
  923. # may want to use this as well in their tests.
  924. add_invertible_flag(
  925. "--allow-empty-bodies", default=False, help=argparse.SUPPRESS, group=internals_group
  926. )
  927. # This undocumented feature exports limited line-level dependency information.
  928. internals_group.add_argument("--export-ref-info", action="store_true", help=argparse.SUPPRESS)
  929. report_group = parser.add_argument_group(
  930. title="Report generation", description="Generate a report in the specified format."
  931. )
  932. for report_type in sorted(defaults.REPORTER_NAMES):
  933. if report_type not in {"memory-xml"}:
  934. report_group.add_argument(
  935. f"--{report_type.replace('_', '-')}-report",
  936. metavar="DIR",
  937. dest=f"special-opts:{report_type}_report",
  938. )
  939. other_group = parser.add_argument_group(title="Miscellaneous")
  940. other_group.add_argument("--quickstart-file", help=argparse.SUPPRESS)
  941. other_group.add_argument("--junit-xml", help="Write junit.xml to the given file")
  942. other_group.add_argument(
  943. "--find-occurrences",
  944. metavar="CLASS.MEMBER",
  945. dest="special-opts:find_occurrences",
  946. help="Print out all usages of a class member (experimental)",
  947. )
  948. other_group.add_argument(
  949. "--scripts-are-modules",
  950. action="store_true",
  951. help="Script x becomes module x instead of __main__",
  952. )
  953. add_invertible_flag(
  954. "--install-types",
  955. default=False,
  956. strict_flag=False,
  957. help="Install detected missing library stub packages using pip",
  958. group=other_group,
  959. )
  960. add_invertible_flag(
  961. "--non-interactive",
  962. default=False,
  963. strict_flag=False,
  964. help=(
  965. "Install stubs without asking for confirmation and hide "
  966. + "errors, with --install-types"
  967. ),
  968. group=other_group,
  969. inverse="--interactive",
  970. )
  971. if server_options:
  972. # TODO: This flag is superfluous; remove after a short transition (2018-03-16)
  973. other_group.add_argument(
  974. "--experimental",
  975. action="store_true",
  976. dest="fine_grained_incremental",
  977. help="Enable fine-grained incremental mode",
  978. )
  979. other_group.add_argument(
  980. "--use-fine-grained-cache",
  981. action="store_true",
  982. help="Use the cache in fine-grained incremental mode",
  983. )
  984. # hidden options
  985. parser.add_argument(
  986. "--stats", action="store_true", dest="dump_type_stats", help=argparse.SUPPRESS
  987. )
  988. parser.add_argument(
  989. "--inferstats", action="store_true", dest="dump_inference_stats", help=argparse.SUPPRESS
  990. )
  991. parser.add_argument("--dump-build-stats", action="store_true", help=argparse.SUPPRESS)
  992. # Dump timing stats for each processed file into the given output file
  993. parser.add_argument("--timing-stats", dest="timing_stats", help=argparse.SUPPRESS)
  994. # Dump per line type checking timing stats for each processed file into the given
  995. # output file. Only total time spent in each top level expression will be shown.
  996. # Times are show in microseconds.
  997. parser.add_argument(
  998. "--line-checking-stats", dest="line_checking_stats", help=argparse.SUPPRESS
  999. )
  1000. # --debug-cache will disable any cache-related compressions/optimizations,
  1001. # which will make the cache writing process output pretty-printed JSON (which
  1002. # is easier to debug).
  1003. parser.add_argument("--debug-cache", action="store_true", help=argparse.SUPPRESS)
  1004. # --dump-deps will dump all fine-grained dependencies to stdout
  1005. parser.add_argument("--dump-deps", action="store_true", help=argparse.SUPPRESS)
  1006. # --dump-graph will dump the contents of the graph of SCCs and exit.
  1007. parser.add_argument("--dump-graph", action="store_true", help=argparse.SUPPRESS)
  1008. # --semantic-analysis-only does exactly that.
  1009. parser.add_argument("--semantic-analysis-only", action="store_true", help=argparse.SUPPRESS)
  1010. # --local-partial-types disallows partial types spanning module top level and a function
  1011. # (implicitly defined in fine-grained incremental mode)
  1012. parser.add_argument("--local-partial-types", action="store_true", help=argparse.SUPPRESS)
  1013. # --logical-deps adds some more dependencies that are not semantically needed, but
  1014. # may be helpful to determine relative importance of classes and functions for overall
  1015. # type precision in a code base. It also _removes_ some deps, so this flag should be never
  1016. # used except for generating code stats. This also automatically enables --cache-fine-grained.
  1017. # NOTE: This is an experimental option that may be modified or removed at any time.
  1018. parser.add_argument("--logical-deps", action="store_true", help=argparse.SUPPRESS)
  1019. # --bazel changes some behaviors for use with Bazel (https://bazel.build).
  1020. parser.add_argument("--bazel", action="store_true", help=argparse.SUPPRESS)
  1021. # --package-root adds a directory below which directories are considered
  1022. # packages even without __init__.py. May be repeated.
  1023. parser.add_argument(
  1024. "--package-root", metavar="ROOT", action="append", default=[], help=argparse.SUPPRESS
  1025. )
  1026. # --cache-map FILE ... gives a mapping from source files to cache files.
  1027. # Each triple of arguments is a source file, a cache meta file, and a cache data file.
  1028. # Modules not mentioned in the file will go through cache_dir.
  1029. # Must be followed by another flag or by '--' (and then only file args may follow).
  1030. parser.add_argument(
  1031. "--cache-map", nargs="+", dest="special-opts:cache_map", help=argparse.SUPPRESS
  1032. )
  1033. # --debug-serialize will run tree.serialize() even if cache generation is disabled.
  1034. # Useful for mypy_primer to detect serialize errors earlier.
  1035. parser.add_argument("--debug-serialize", action="store_true", help=argparse.SUPPRESS)
  1036. # This one is deprecated, but we will keep it for few releases.
  1037. parser.add_argument(
  1038. "--enable-incomplete-features", action="store_true", help=argparse.SUPPRESS
  1039. )
  1040. parser.add_argument(
  1041. "--disable-bytearray-promotion", action="store_true", help=argparse.SUPPRESS
  1042. )
  1043. parser.add_argument(
  1044. "--disable-memoryview-promotion", action="store_true", help=argparse.SUPPRESS
  1045. )
  1046. # This flag is deprecated, it has been moved to --extra-checks
  1047. parser.add_argument("--strict-concatenate", action="store_true", help=argparse.SUPPRESS)
  1048. # options specifying code to check
  1049. code_group = parser.add_argument_group(
  1050. title="Running code",
  1051. description="Specify the code you want to type check. For more details, see "
  1052. "mypy.readthedocs.io/en/stable/running_mypy.html#running-mypy",
  1053. )
  1054. add_invertible_flag(
  1055. "--explicit-package-bases",
  1056. default=False,
  1057. help="Use current directory and MYPYPATH to determine module names of files passed",
  1058. group=code_group,
  1059. )
  1060. add_invertible_flag(
  1061. "--fast-module-lookup", default=False, help=argparse.SUPPRESS, group=code_group
  1062. )
  1063. code_group.add_argument(
  1064. "--exclude",
  1065. action="append",
  1066. metavar="PATTERN",
  1067. default=[],
  1068. help=(
  1069. "Regular expression to match file names, directory names or paths which mypy should "
  1070. "ignore while recursively discovering files to check, e.g. --exclude '/setup\\.py$'. "
  1071. "May be specified more than once, eg. --exclude a --exclude b"
  1072. ),
  1073. )
  1074. code_group.add_argument(
  1075. "-m",
  1076. "--module",
  1077. action="append",
  1078. metavar="MODULE",
  1079. default=[],
  1080. dest="special-opts:modules",
  1081. help="Type-check module; can repeat for more modules",
  1082. )
  1083. code_group.add_argument(
  1084. "-p",
  1085. "--package",
  1086. action="append",
  1087. metavar="PACKAGE",
  1088. default=[],
  1089. dest="special-opts:packages",
  1090. help="Type-check package recursively; can be repeated",
  1091. )
  1092. code_group.add_argument(
  1093. "-c",
  1094. "--command",
  1095. action="append",
  1096. metavar="PROGRAM_TEXT",
  1097. dest="special-opts:command",
  1098. help="Type-check program passed in as string",
  1099. )
  1100. code_group.add_argument(
  1101. metavar="files",
  1102. nargs="*",
  1103. dest="special-opts:files",
  1104. help="Type-check given files or directories",
  1105. )
  1106. # Parse arguments once into a dummy namespace so we can get the
  1107. # filename for the config file and know if the user requested all strict options.
  1108. dummy = argparse.Namespace()
  1109. parser.parse_args(args, dummy)
  1110. config_file = dummy.config_file
  1111. # Don't explicitly test if "config_file is not None" for this check.
  1112. # This lets `--config-file=` (an empty string) be used to disable all config files.
  1113. if config_file and not os.path.exists(config_file):
  1114. parser.error(f"Cannot find config file '{config_file}'")
  1115. options = Options()
  1116. strict_option_set = False
  1117. def set_strict_flags() -> None:
  1118. nonlocal strict_option_set
  1119. strict_option_set = True
  1120. for dest, value in strict_flag_assignments:
  1121. setattr(options, dest, value)
  1122. # Parse config file first, so command line can override.
  1123. parse_config_file(options, set_strict_flags, config_file, stdout, stderr)
  1124. # Set strict flags before parsing (if strict mode enabled), so other command
  1125. # line options can override.
  1126. if getattr(dummy, "special-opts:strict"):
  1127. set_strict_flags()
  1128. # Override cache_dir if provided in the environment
  1129. environ_cache_dir = os.getenv("MYPY_CACHE_DIR", "")
  1130. if environ_cache_dir.strip():
  1131. options.cache_dir = environ_cache_dir
  1132. options.cache_dir = os.path.expanduser(options.cache_dir)
  1133. # Parse command line for real, using a split namespace.
  1134. special_opts = argparse.Namespace()
  1135. parser.parse_args(args, SplitNamespace(options, special_opts, "special-opts:"))
  1136. # The python_version is either the default, which can be overridden via a config file,
  1137. # or stored in special_opts and is passed via the command line.
  1138. options.python_version = special_opts.python_version or options.python_version
  1139. if options.python_version < (3,):
  1140. parser.error(
  1141. "Mypy no longer supports checking Python 2 code. "
  1142. "Consider pinning to mypy<0.980 if you need to check Python 2 code."
  1143. )
  1144. try:
  1145. infer_python_executable(options, special_opts)
  1146. except PythonExecutableInferenceError as e:
  1147. parser.error(str(e))
  1148. if special_opts.no_executable or options.no_site_packages:
  1149. options.python_executable = None
  1150. # Paths listed in the config file will be ignored if any paths, modules or packages
  1151. # are passed on the command line.
  1152. if not (special_opts.files or special_opts.packages or special_opts.modules):
  1153. if options.files:
  1154. special_opts.files = options.files
  1155. if options.packages:
  1156. special_opts.packages = options.packages
  1157. if options.modules:
  1158. special_opts.modules = options.modules
  1159. # Check for invalid argument combinations.
  1160. if require_targets:
  1161. code_methods = sum(
  1162. bool(c)
  1163. for c in [
  1164. special_opts.modules + special_opts.packages,
  1165. special_opts.command,
  1166. special_opts.files,
  1167. ]
  1168. )
  1169. if code_methods == 0 and not options.install_types:
  1170. parser.error("Missing target module, package, files, or command.")
  1171. elif code_methods > 1:
  1172. parser.error("May only specify one of: module/package, files, or command.")
  1173. if options.explicit_package_bases and not options.namespace_packages:
  1174. parser.error(
  1175. "Can only use --explicit-package-bases with --namespace-packages, since otherwise "
  1176. "examining __init__.py's is sufficient to determine module names for files"
  1177. )
  1178. # Check for overlapping `--always-true` and `--always-false` flags.
  1179. overlap = set(options.always_true) & set(options.always_false)
  1180. if overlap:
  1181. parser.error(
  1182. "You can't make a variable always true and always false (%s)"
  1183. % ", ".join(sorted(overlap))
  1184. )
  1185. # Process `--enable-error-code` and `--disable-error-code` flags
  1186. disabled_codes = set(options.disable_error_code)
  1187. enabled_codes = set(options.enable_error_code)
  1188. valid_error_codes = set(error_codes.keys())
  1189. invalid_codes = (enabled_codes | disabled_codes) - valid_error_codes
  1190. if invalid_codes:
  1191. parser.error(f"Invalid error code(s): {', '.join(sorted(invalid_codes))}")
  1192. options.disabled_error_codes |= {error_codes[code] for code in disabled_codes}
  1193. options.enabled_error_codes |= {error_codes[code] for code in enabled_codes}
  1194. # Enabling an error code always overrides disabling
  1195. options.disabled_error_codes -= options.enabled_error_codes
  1196. # Validate incomplete features.
  1197. for feature in options.enable_incomplete_feature:
  1198. if feature not in INCOMPLETE_FEATURES:
  1199. parser.error(f"Unknown incomplete feature: {feature}")
  1200. if options.enable_incomplete_features:
  1201. print(
  1202. "Warning: --enable-incomplete-features is deprecated, use"
  1203. " --enable-incomplete-feature=FEATURE instead"
  1204. )
  1205. options.enable_incomplete_feature = list(INCOMPLETE_FEATURES)
  1206. # Compute absolute path for custom typeshed (if present).
  1207. if options.custom_typeshed_dir is not None:
  1208. options.abs_custom_typeshed_dir = os.path.abspath(options.custom_typeshed_dir)
  1209. # Set build flags.
  1210. if special_opts.find_occurrences:
  1211. _find_occurrences = tuple(special_opts.find_occurrences.split("."))
  1212. if len(_find_occurrences) < 2:
  1213. parser.error("Can only find occurrences of class members.")
  1214. if len(_find_occurrences) != 2:
  1215. parser.error("Can only find occurrences of non-nested class members.")
  1216. state.find_occurrences = _find_occurrences # type: ignore[assignment]
  1217. # Set reports.
  1218. for flag, val in vars(special_opts).items():
  1219. if flag.endswith("_report") and val is not None:
  1220. report_type = flag[:-7].replace("_", "-")
  1221. report_dir = val
  1222. options.report_dirs[report_type] = report_dir
  1223. # Process --package-root.
  1224. if options.package_root:
  1225. process_package_roots(fscache, parser, options)
  1226. # Process --cache-map.
  1227. if special_opts.cache_map:
  1228. if options.sqlite_cache:
  1229. parser.error("--cache-map is incompatible with --sqlite-cache")
  1230. process_cache_map(parser, special_opts, options)
  1231. # An explicitly specified cache_fine_grained implies local_partial_types
  1232. # (because otherwise the cache is not compatible with dmypy)
  1233. if options.cache_fine_grained:
  1234. options.local_partial_types = True
  1235. # Implicitly show column numbers if error location end is shown
  1236. if options.show_error_end:
  1237. options.show_column_numbers = True
  1238. # Let logical_deps imply cache_fine_grained (otherwise the former is useless).
  1239. if options.logical_deps:
  1240. options.cache_fine_grained = True
  1241. if options.enable_recursive_aliases:
  1242. print(
  1243. "Warning: --enable-recursive-aliases is deprecated;"
  1244. " recursive types are enabled by default"
  1245. )
  1246. if options.strict_concatenate and not strict_option_set:
  1247. print("Warning: --strict-concatenate is deprecated; use --extra-checks instead")
  1248. # Set target.
  1249. if special_opts.modules + special_opts.packages:
  1250. options.build_type = BuildType.MODULE
  1251. sys_path, _ = get_search_dirs(options.python_executable)
  1252. search_paths = SearchPaths(
  1253. (os.getcwd(),), tuple(mypy_path() + options.mypy_path), tuple(sys_path), ()
  1254. )
  1255. targets = []
  1256. # TODO: use the same cache that the BuildManager will
  1257. cache = FindModuleCache(search_paths, fscache, options)
  1258. for p in special_opts.packages:
  1259. if os.sep in p or os.altsep and os.altsep in p:
  1260. fail(f"Package name '{p}' cannot have a slash in it.", stderr, options)
  1261. p_targets = cache.find_modules_recursive(p)
  1262. if not p_targets:
  1263. fail(f"Can't find package '{p}'", stderr, options)
  1264. targets.extend(p_targets)
  1265. for m in special_opts.modules:
  1266. targets.append(BuildSource(None, m, None))
  1267. return targets, options
  1268. elif special_opts.command:
  1269. options.build_type = BuildType.PROGRAM_TEXT
  1270. targets = [BuildSource(None, None, "\n".join(special_opts.command))]
  1271. return targets, options
  1272. else:
  1273. try:
  1274. targets = create_source_list(special_opts.files, options, fscache)
  1275. # Variable named e2 instead of e to work around mypyc bug #620
  1276. # which causes issues when using the same variable to catch
  1277. # exceptions of different types.
  1278. except InvalidSourceList as e2:
  1279. fail(str(e2), stderr, options)
  1280. return targets, options
  1281. def process_package_roots(
  1282. fscache: FileSystemCache | None, parser: argparse.ArgumentParser, options: Options
  1283. ) -> None:
  1284. """Validate and normalize package_root."""
  1285. if fscache is None:
  1286. parser.error("--package-root does not work here (no fscache)")
  1287. assert fscache is not None # Since mypy doesn't know parser.error() raises.
  1288. # Do some stuff with drive letters to make Windows happy (esp. tests).
  1289. current_drive, _ = os.path.splitdrive(os.getcwd())
  1290. dot = os.curdir
  1291. dotslash = os.curdir + os.sep
  1292. dotdotslash = os.pardir + os.sep
  1293. trivial_paths = {dot, dotslash}
  1294. package_root = []
  1295. for root in options.package_root:
  1296. if os.path.isabs(root):
  1297. parser.error(f"Package root cannot be absolute: {root!r}")
  1298. drive, root = os.path.splitdrive(root)
  1299. if drive and drive != current_drive:
  1300. parser.error(f"Package root must be on current drive: {drive + root!r}")
  1301. # Empty package root is always okay.
  1302. if root:
  1303. root = os.path.relpath(root) # Normalize the heck out of it.
  1304. if not root.endswith(os.sep):
  1305. root = root + os.sep
  1306. if root.startswith(dotdotslash):
  1307. parser.error(f"Package root cannot be above current directory: {root!r}")
  1308. if root in trivial_paths:
  1309. root = ""
  1310. package_root.append(root)
  1311. options.package_root = package_root
  1312. # Pass the package root on the the filesystem cache.
  1313. fscache.set_package_root(package_root)
  1314. def process_cache_map(
  1315. parser: argparse.ArgumentParser, special_opts: argparse.Namespace, options: Options
  1316. ) -> None:
  1317. """Validate cache_map and copy into options.cache_map."""
  1318. n = len(special_opts.cache_map)
  1319. if n % 3 != 0:
  1320. parser.error("--cache-map requires one or more triples (see source)")
  1321. for i in range(0, n, 3):
  1322. source, meta_file, data_file = special_opts.cache_map[i : i + 3]
  1323. if source in options.cache_map:
  1324. parser.error(f"Duplicate --cache-map source {source})")
  1325. if not source.endswith(".py") and not source.endswith(".pyi"):
  1326. parser.error(f"Invalid --cache-map source {source} (triple[0] must be *.py[i])")
  1327. if not meta_file.endswith(".meta.json"):
  1328. parser.error(
  1329. "Invalid --cache-map meta_file %s (triple[1] must be *.meta.json)" % meta_file
  1330. )
  1331. if not data_file.endswith(".data.json"):
  1332. parser.error(
  1333. "Invalid --cache-map data_file %s (triple[2] must be *.data.json)" % data_file
  1334. )
  1335. options.cache_map[source] = (meta_file, data_file)
  1336. def maybe_write_junit_xml(td: float, serious: bool, messages: list[str], options: Options) -> None:
  1337. if options.junit_xml:
  1338. py_version = f"{options.python_version[0]}_{options.python_version[1]}"
  1339. util.write_junit_xml(
  1340. td, serious, messages, options.junit_xml, py_version, options.platform
  1341. )
  1342. def fail(msg: str, stderr: TextIO, options: Options) -> NoReturn:
  1343. """Fail with a serious error."""
  1344. stderr.write(f"{msg}\n")
  1345. maybe_write_junit_xml(0.0, serious=True, messages=[msg], options=options)
  1346. sys.exit(2)
  1347. def read_types_packages_to_install(cache_dir: str, after_run: bool) -> list[str]:
  1348. if not os.path.isdir(cache_dir):
  1349. if not after_run:
  1350. sys.stderr.write(
  1351. "error: Can't determine which types to install with no files to check "
  1352. + "(and no cache from previous mypy run)\n"
  1353. )
  1354. else:
  1355. sys.stderr.write("error: --install-types failed (no mypy cache directory)\n")
  1356. sys.exit(2)
  1357. fnam = build.missing_stubs_file(cache_dir)
  1358. if not os.path.isfile(fnam):
  1359. # No missing stubs.
  1360. return []
  1361. with open(fnam) as f:
  1362. return [line.strip() for line in f]
  1363. def install_types(
  1364. formatter: util.FancyFormatter,
  1365. options: Options,
  1366. *,
  1367. after_run: bool = False,
  1368. non_interactive: bool = False,
  1369. ) -> bool:
  1370. """Install stub packages using pip if some missing stubs were detected."""
  1371. packages = read_types_packages_to_install(options.cache_dir, after_run)
  1372. if not packages:
  1373. # If there are no missing stubs, generate no output.
  1374. return False
  1375. if after_run and not non_interactive:
  1376. print()
  1377. print("Installing missing stub packages:")
  1378. assert options.python_executable, "Python executable required to install types"
  1379. cmd = [options.python_executable, "-m", "pip", "install"] + packages
  1380. print(formatter.style(" ".join(cmd), "none", bold=True))
  1381. print()
  1382. if not non_interactive:
  1383. x = input("Install? [yN] ")
  1384. if not x.strip() or not x.lower().startswith("y"):
  1385. print(formatter.style("mypy: Skipping installation", "red", bold=True))
  1386. sys.exit(2)
  1387. print()
  1388. subprocess.run(cmd)
  1389. return True