exceptions.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. # Copyright (C) 2012 Anaconda, Inc
  2. # SPDX-License-Identifier: BSD-3-Clause
  3. from __future__ import annotations
  4. import json
  5. import os
  6. import sys
  7. from datetime import timedelta
  8. from json.decoder import JSONDecodeError
  9. from logging import getLogger
  10. from os.path import join
  11. from textwrap import dedent
  12. from traceback import format_exception, format_exception_only
  13. from conda.common.iterators import groupby_to_dict as groupby
  14. from . import CondaError, CondaExitZero, CondaMultiError
  15. from .auxlib.entity import EntityEncoder
  16. from .auxlib.ish import dals
  17. from .auxlib.logz import stringify
  18. from .base.constants import COMPATIBLE_SHELLS, PathConflict, SafetyChecks
  19. from .common.compat import on_win
  20. from .common.io import dashlist
  21. from .common.signals import get_signal_name
  22. from .common.url import join_url, maybe_unquote
  23. from .deprecations import DeprecatedError # noqa: 401
  24. from .exception_handler import ExceptionHandler, conda_exception_handler # noqa: 401
  25. from .models.channel import Channel
  26. log = getLogger(__name__)
  27. # TODO: for conda-build compatibility only
  28. # remove in conda 4.4
  29. class ResolvePackageNotFound(CondaError):
  30. def __init__(self, bad_deps):
  31. # bad_deps is a list of lists
  32. # bad_deps should really be named 'invalid_chains'
  33. self.bad_deps = tuple(dep for deps in bad_deps for dep in deps if dep)
  34. formatted_chains = tuple(
  35. " -> ".join(map(str, bad_chain)) for bad_chain in bad_deps
  36. )
  37. self._formatted_chains = formatted_chains
  38. message = "\n" + "\n".join(
  39. (" - %s" % bad_chain) for bad_chain in formatted_chains
  40. )
  41. super().__init__(message)
  42. NoPackagesFound = NoPackagesFoundError = ResolvePackageNotFound # NOQA
  43. class LockError(CondaError):
  44. def __init__(self, message):
  45. msg = "%s" % message
  46. super().__init__(msg)
  47. class ArgumentError(CondaError):
  48. return_code = 2
  49. def __init__(self, message, **kwargs):
  50. super().__init__(message, **kwargs)
  51. class Help(CondaError):
  52. pass
  53. class ActivateHelp(Help):
  54. def __init__(self):
  55. message = dals(
  56. """
  57. usage: conda activate [-h] [--[no-]stack] [env_name_or_prefix]
  58. Activate a conda environment.
  59. Options:
  60. positional arguments:
  61. env_name_or_prefix The environment name or prefix to activate. If the
  62. prefix is a relative path, it must start with './'
  63. (or '.\\' on Windows).
  64. optional arguments:
  65. -h, --help Show this help message and exit.
  66. --stack Stack the environment being activated on top of the
  67. previous active environment, rather replacing the
  68. current active environment with a new one. Currently,
  69. only the PATH environment variable is stacked. This
  70. may be enabled implicitly by the 'auto_stack'
  71. configuration variable.
  72. --no-stack Do not stack the environment. Overrides 'auto_stack'
  73. setting.
  74. """
  75. )
  76. super().__init__(message)
  77. class DeactivateHelp(Help):
  78. def __init__(self):
  79. message = dals(
  80. """
  81. usage: conda deactivate [-h]
  82. Deactivate the current active conda environment.
  83. Options:
  84. optional arguments:
  85. -h, --help Show this help message and exit.
  86. """
  87. )
  88. super().__init__(message)
  89. class GenericHelp(Help):
  90. def __init__(self, command):
  91. message = "help requested for %s" % command
  92. super().__init__(message)
  93. class CondaSignalInterrupt(CondaError):
  94. def __init__(self, signum):
  95. signal_name = get_signal_name(signum)
  96. super().__init__(
  97. "Signal interrupt %(signal_name)s", signal_name=signal_name, signum=signum
  98. )
  99. class TooManyArgumentsError(ArgumentError):
  100. def __init__(
  101. self, expected, received, offending_arguments, optional_message="", *args
  102. ):
  103. self.expected = expected
  104. self.received = received
  105. self.offending_arguments = offending_arguments
  106. self.optional_message = optional_message
  107. suffix = "s" if received - expected > 1 else ""
  108. msg = "{} Got {} argument{} ({}) but expected {}.".format(
  109. optional_message,
  110. received,
  111. suffix,
  112. ", ".join(offending_arguments),
  113. expected,
  114. )
  115. super().__init__(msg, *args)
  116. class ClobberError(CondaError):
  117. def __init__(self, message, path_conflict, **kwargs):
  118. self.path_conflict = path_conflict
  119. super().__init__(message, **kwargs)
  120. def __repr__(self):
  121. clz_name = (
  122. "ClobberWarning"
  123. if self.path_conflict == PathConflict.warn
  124. else "ClobberError"
  125. )
  126. return f"{clz_name}: {self}\n"
  127. class BasicClobberError(ClobberError):
  128. def __init__(self, source_path, target_path, context):
  129. message = dals(
  130. """
  131. Conda was asked to clobber an existing path.
  132. source path: %(source_path)s
  133. target path: %(target_path)s
  134. """
  135. )
  136. if context.path_conflict == PathConflict.prevent:
  137. message += (
  138. "Conda no longer clobbers existing paths without the use of the "
  139. "--clobber option\n."
  140. )
  141. super().__init__(
  142. message,
  143. context.path_conflict,
  144. target_path=target_path,
  145. source_path=source_path,
  146. )
  147. class KnownPackageClobberError(ClobberError):
  148. def __init__(
  149. self, target_path, colliding_dist_being_linked, colliding_linked_dist, context
  150. ):
  151. message = dals(
  152. """
  153. The package '%(colliding_dist_being_linked)s' cannot be installed due to a
  154. path collision for '%(target_path)s'.
  155. This path already exists in the target prefix, and it won't be removed by
  156. an uninstall action in this transaction. The path appears to be coming from
  157. the package '%(colliding_linked_dist)s', which is already installed in the prefix.
  158. """
  159. )
  160. if context.path_conflict == PathConflict.prevent:
  161. message += (
  162. "If you'd like to proceed anyway, re-run the command with "
  163. "the `--clobber` flag.\n."
  164. )
  165. super().__init__(
  166. message,
  167. context.path_conflict,
  168. target_path=target_path,
  169. colliding_dist_being_linked=colliding_dist_being_linked,
  170. colliding_linked_dist=colliding_linked_dist,
  171. )
  172. class UnknownPackageClobberError(ClobberError):
  173. def __init__(self, target_path, colliding_dist_being_linked, context):
  174. message = dals(
  175. """
  176. The package '%(colliding_dist_being_linked)s' cannot be installed due to a
  177. path collision for '%(target_path)s'.
  178. This path already exists in the target prefix, and it won't be removed
  179. by an uninstall action in this transaction. The path is one that conda
  180. doesn't recognize. It may have been created by another package manager.
  181. """
  182. )
  183. if context.path_conflict == PathConflict.prevent:
  184. message += (
  185. "If you'd like to proceed anyway, re-run the command with "
  186. "the `--clobber` flag.\n."
  187. )
  188. super().__init__(
  189. message,
  190. context.path_conflict,
  191. target_path=target_path,
  192. colliding_dist_being_linked=colliding_dist_being_linked,
  193. )
  194. class SharedLinkPathClobberError(ClobberError):
  195. def __init__(self, target_path, incompatible_package_dists, context):
  196. message = dals(
  197. """
  198. This transaction has incompatible packages due to a shared path.
  199. packages: %(incompatible_packages)s
  200. path: '%(target_path)s'
  201. """
  202. )
  203. if context.path_conflict == PathConflict.prevent:
  204. message += (
  205. "If you'd like to proceed anyway, re-run the command with "
  206. "the `--clobber` flag.\n."
  207. )
  208. super().__init__(
  209. message,
  210. context.path_conflict,
  211. target_path=target_path,
  212. incompatible_packages=", ".join(str(d) for d in incompatible_package_dists),
  213. )
  214. class CommandNotFoundError(CondaError):
  215. def __init__(self, command):
  216. activate_commands = {
  217. "activate",
  218. "deactivate",
  219. "run",
  220. }
  221. conda_commands = {
  222. "clean",
  223. "config",
  224. "create",
  225. "--help", # https://github.com/conda/conda/issues/11585
  226. "info",
  227. "install",
  228. "list",
  229. "package",
  230. "remove",
  231. "search",
  232. "uninstall",
  233. "update",
  234. "upgrade",
  235. }
  236. build_commands = {
  237. "build",
  238. "convert",
  239. "develop",
  240. "index",
  241. "inspect",
  242. "metapackage",
  243. "render",
  244. "skeleton",
  245. }
  246. from .base.context import context
  247. from .cli.main import init_loggers
  248. init_loggers(context)
  249. if command in activate_commands:
  250. # TODO: Point users to a page at conda-docs, which explains this context in more detail
  251. builder = [
  252. "Your shell has not been properly configured to use 'conda %(command)s'."
  253. ]
  254. if on_win:
  255. builder.append(
  256. dals(
  257. """
  258. If using 'conda %(command)s' from a batch script, change your
  259. invocation to 'CALL conda.bat %(command)s'.
  260. """
  261. )
  262. )
  263. builder.append(
  264. dals(
  265. """
  266. To initialize your shell, run
  267. $ conda init <SHELL_NAME>
  268. Currently supported shells are:%(supported_shells)s
  269. See 'conda init --help' for more information and options.
  270. IMPORTANT: You may need to close and restart your shell after running 'conda init'.
  271. """
  272. )
  273. % {
  274. "supported_shells": dashlist(COMPATIBLE_SHELLS),
  275. }
  276. )
  277. message = "\n".join(builder)
  278. elif command in build_commands:
  279. message = "To use 'conda %(command)s', install conda-build."
  280. else:
  281. from difflib import get_close_matches
  282. from .cli.find_commands import find_commands
  283. message = "No command 'conda %(command)s'."
  284. choices = (
  285. activate_commands
  286. | conda_commands
  287. | build_commands
  288. | set(find_commands())
  289. )
  290. close = get_close_matches(command, choices)
  291. if close:
  292. message += "\nDid you mean 'conda %s'?" % close[0]
  293. super().__init__(message, command=command)
  294. class PathNotFoundError(CondaError, OSError):
  295. def __init__(self, path):
  296. message = "%(path)s"
  297. super().__init__(message, path=path)
  298. class DirectoryNotFoundError(CondaError):
  299. def __init__(self, path):
  300. message = "%(path)s"
  301. super().__init__(message, path=path)
  302. class EnvironmentLocationNotFound(CondaError):
  303. def __init__(self, location):
  304. message = "Not a conda environment: %(location)s"
  305. super().__init__(message, location=location)
  306. class EnvironmentNameNotFound(CondaError):
  307. def __init__(self, environment_name):
  308. message = dals(
  309. """
  310. Could not find conda environment: %(environment_name)s
  311. You can list all discoverable environments with `conda info --envs`.
  312. """
  313. )
  314. super().__init__(message, environment_name=environment_name)
  315. class NoBaseEnvironmentError(CondaError):
  316. def __init__(self):
  317. message = dals(
  318. """
  319. This conda installation has no default base environment. Use
  320. 'conda create' to create new environments and 'conda activate' to
  321. activate environments.
  322. """
  323. )
  324. super().__init__(message)
  325. class DirectoryNotACondaEnvironmentError(CondaError):
  326. def __init__(self, target_directory):
  327. message = dals(
  328. """
  329. The target directory exists, but it is not a conda environment.
  330. Use 'conda create' to convert the directory to a conda environment.
  331. target directory: %(target_directory)s
  332. """
  333. )
  334. super().__init__(message, target_directory=target_directory)
  335. class CondaEnvironmentError(CondaError, EnvironmentError):
  336. def __init__(self, message, *args):
  337. msg = "%s" % message
  338. super().__init__(msg, *args)
  339. class DryRunExit(CondaExitZero):
  340. def __init__(self):
  341. msg = "Dry run. Exiting."
  342. super().__init__(msg)
  343. class CondaSystemExit(CondaExitZero, SystemExit):
  344. def __init__(self, *args):
  345. msg = " ".join(str(arg) for arg in self.args)
  346. super().__init__(msg)
  347. class PaddingError(CondaError):
  348. def __init__(self, dist, placeholder, placeholder_length):
  349. msg = (
  350. "Placeholder of length '%d' too short in package %s.\n"
  351. "The package must be rebuilt with conda-build > 2.0."
  352. % (placeholder_length, dist)
  353. )
  354. super().__init__(msg)
  355. class LinkError(CondaError):
  356. def __init__(self, message):
  357. super().__init__(message)
  358. class CondaOSError(CondaError, OSError):
  359. def __init__(self, message, **kwargs):
  360. msg = "%s" % message
  361. super().__init__(msg, **kwargs)
  362. class ProxyError(CondaError):
  363. def __init__(self):
  364. message = dals(
  365. """
  366. Conda cannot proceed due to an error in your proxy configuration.
  367. Check for typos and other configuration errors in any '.netrc' file in your home directory,
  368. any environment variables ending in '_PROXY', and any other system-wide proxy
  369. configuration settings.
  370. """
  371. )
  372. super().__init__(message)
  373. class CondaIOError(CondaError, IOError):
  374. def __init__(self, message, *args):
  375. msg = "%s" % message
  376. super().__init__(msg)
  377. class CondaFileIOError(CondaIOError):
  378. def __init__(self, filepath, message, *args):
  379. self.filepath = filepath
  380. msg = f"'{filepath}'. {message}"
  381. super().__init__(msg, *args)
  382. class CondaKeyError(CondaError, KeyError):
  383. def __init__(self, key, message, *args):
  384. self.key = key
  385. self.msg = f"'{key}': {message}"
  386. super().__init__(self.msg, *args)
  387. class ChannelError(CondaError):
  388. pass
  389. class ChannelNotAllowed(ChannelError):
  390. def __init__(self, channel):
  391. channel = Channel(channel)
  392. channel_name = channel.name
  393. channel_url = maybe_unquote(channel.base_url)
  394. message = dals(
  395. """
  396. Channel not included in allowlist:
  397. channel name: %(channel_name)s
  398. channel url: %(channel_url)s
  399. """
  400. )
  401. super().__init__(message, channel_url=channel_url, channel_name=channel_name)
  402. class UnavailableInvalidChannel(ChannelError):
  403. status_code: str | int
  404. def __init__(self, channel, status_code, response=None):
  405. # parse channel
  406. channel = Channel(channel)
  407. channel_name = channel.name
  408. channel_url = maybe_unquote(channel.base_url)
  409. # define hardcoded/default reason/message
  410. reason = getattr(response, "reason", None)
  411. message = dals(
  412. """
  413. The channel is not accessible or is invalid.
  414. You will need to adjust your conda configuration to proceed.
  415. Use `conda config --show channels` to view your configuration's current state,
  416. and use `conda config --show-sources` to view config file locations.
  417. """
  418. )
  419. if channel.scheme == "file":
  420. url = join_url(channel.location, channel.name)
  421. message += dedent(
  422. f"""
  423. As of conda 4.3, a valid channel must contain a `noarch/repodata.json` and
  424. associated `noarch/repodata.json.bz2` file, even if `noarch/repodata.json` is
  425. empty. Use `conda index {url}`, or create `noarch/repodata.json`
  426. and associated `noarch/repodata.json.bz2`.
  427. """
  428. )
  429. # if response includes a valid json body we prefer the reason/message defined there
  430. try:
  431. body = response.json()
  432. except (AttributeError, JSONDecodeError):
  433. body = {}
  434. else:
  435. reason = body.get("reason", None) or reason
  436. message = body.get("message", None) or message
  437. # standardize arguments
  438. status_code = status_code or "000"
  439. reason = reason or "UNAVAILABLE OR INVALID"
  440. if isinstance(reason, str):
  441. reason = reason.upper()
  442. self.status_code = status_code
  443. super().__init__(
  444. f"HTTP {status_code} {reason} for channel {channel_name} <{channel_url}>\n\n{message}",
  445. channel_name=channel_name,
  446. channel_url=channel_url,
  447. status_code=status_code,
  448. reason=reason,
  449. response_details=stringify(response, content_max_len=1024) or "",
  450. json=body,
  451. )
  452. class OperationNotAllowed(CondaError):
  453. def __init__(self, message):
  454. super().__init__(message)
  455. class CondaImportError(CondaError, ImportError):
  456. def __init__(self, message):
  457. msg = "%s" % message
  458. super().__init__(msg)
  459. class ParseError(CondaError):
  460. def __init__(self, message):
  461. msg = "%s" % message
  462. super().__init__(msg)
  463. class CouldntParseError(ParseError):
  464. def __init__(self, reason):
  465. self.reason = reason
  466. super().__init__(self.args[0])
  467. class ChecksumMismatchError(CondaError):
  468. def __init__(
  469. self, url, target_full_path, checksum_type, expected_checksum, actual_checksum
  470. ):
  471. message = dals(
  472. """
  473. Conda detected a mismatch between the expected content and downloaded content
  474. for url '%(url)s'.
  475. download saved to: %(target_full_path)s
  476. expected %(checksum_type)s: %(expected_checksum)s
  477. actual %(checksum_type)s: %(actual_checksum)s
  478. """
  479. )
  480. url = maybe_unquote(url)
  481. super().__init__(
  482. message,
  483. url=url,
  484. target_full_path=target_full_path,
  485. checksum_type=checksum_type,
  486. expected_checksum=expected_checksum,
  487. actual_checksum=actual_checksum,
  488. )
  489. class PackageNotInstalledError(CondaError):
  490. def __init__(self, prefix, package_name):
  491. message = dals(
  492. """
  493. Package is not installed in prefix.
  494. prefix: %(prefix)s
  495. package name: %(package_name)s
  496. """
  497. )
  498. super().__init__(message, prefix=prefix, package_name=package_name)
  499. class CondaHTTPError(CondaError):
  500. def __init__(
  501. self,
  502. message,
  503. url,
  504. status_code,
  505. reason,
  506. elapsed_time,
  507. response=None,
  508. caused_by=None,
  509. ):
  510. # if response includes a valid json body we prefer the reason/message defined there
  511. try:
  512. body = response.json()
  513. except (AttributeError, JSONDecodeError):
  514. body = {}
  515. else:
  516. reason = body.get("reason", None) or reason
  517. message = body.get("message", None) or message
  518. # standardize arguments
  519. url = maybe_unquote(url)
  520. status_code = status_code or "000"
  521. reason = reason or "CONNECTION FAILED"
  522. if isinstance(reason, str):
  523. reason = reason.upper()
  524. elapsed_time = elapsed_time or "-"
  525. if isinstance(elapsed_time, timedelta):
  526. elapsed_time = str(elapsed_time).split(":", 1)[-1]
  527. # extract CF-RAY
  528. try:
  529. cf_ray = response.headers["CF-RAY"]
  530. except (AttributeError, KeyError):
  531. cf_ray = ""
  532. else:
  533. cf_ray = f"CF-RAY: {cf_ray}\n"
  534. super().__init__(
  535. dals(
  536. f"""
  537. HTTP {status_code} {reason} for url <{url}>
  538. Elapsed: {elapsed_time}
  539. {cf_ray}
  540. """
  541. )
  542. # since message may include newlines don't include in f-string/dals above
  543. + message,
  544. url=url,
  545. status_code=status_code,
  546. reason=reason,
  547. elapsed_time=elapsed_time,
  548. response_details=stringify(response, content_max_len=1024) or "",
  549. json=body,
  550. caused_by=caused_by,
  551. )
  552. class CondaSSLError(CondaError):
  553. pass
  554. class AuthenticationError(CondaError):
  555. pass
  556. class PackagesNotFoundError(CondaError):
  557. def __init__(self, packages, channel_urls=()):
  558. format_list = lambda iterable: " - " + "\n - ".join(str(x) for x in iterable)
  559. if channel_urls:
  560. message = dals(
  561. """
  562. The following packages are not available from current channels:
  563. %(packages_formatted)s
  564. Current channels:
  565. %(channels_formatted)s
  566. To search for alternate channels that may provide the conda package you're
  567. looking for, navigate to
  568. https://anaconda.org
  569. and use the search bar at the top of the page.
  570. """
  571. )
  572. from .base.context import context
  573. if context.use_only_tar_bz2:
  574. message += dals(
  575. """
  576. Note: 'use_only_tar_bz2' is enabled. This might be omitting some
  577. packages from the index. Set this option to 'false' and retry.
  578. """
  579. )
  580. packages_formatted = format_list(packages)
  581. channels_formatted = format_list(channel_urls)
  582. else:
  583. message = dals(
  584. """
  585. The following packages are missing from the target environment:
  586. %(packages_formatted)s
  587. """
  588. )
  589. packages_formatted = format_list(packages)
  590. channels_formatted = ()
  591. super().__init__(
  592. message,
  593. packages=packages,
  594. packages_formatted=packages_formatted,
  595. channel_urls=channel_urls,
  596. channels_formatted=channels_formatted,
  597. )
  598. class UnsatisfiableError(CondaError):
  599. """An exception to report unsatisfiable dependencies.
  600. Args:
  601. bad_deps: a list of tuples of objects (likely MatchSpecs).
  602. chains: (optional) if True, the tuples are interpreted as chains
  603. of dependencies, from top level to bottom. If False, the tuples
  604. are interpreted as simple lists of conflicting specs.
  605. Returns:
  606. Raises an exception with a formatted message detailing the
  607. unsatisfiable specifications.
  608. """
  609. def _format_chain_str(self, bad_deps):
  610. chains = {}
  611. for dep in sorted(bad_deps, key=len, reverse=True):
  612. dep1 = [s.partition(" ") for s in dep[1:]]
  613. key = (dep[0],) + tuple(v[0] for v in dep1)
  614. vals = ("",) + tuple(v[2] for v in dep1)
  615. found = False
  616. for key2, csets in chains.items():
  617. if key2[: len(key)] == key:
  618. for cset, val in zip(csets, vals):
  619. cset.add(val)
  620. found = True
  621. if not found:
  622. chains[key] = [{val} for val in vals]
  623. for key, csets in chains.items():
  624. deps = []
  625. for name, cset in zip(key, csets):
  626. if "" not in cset:
  627. pass
  628. elif len(cset) == 1:
  629. cset.clear()
  630. else:
  631. cset.remove("")
  632. cset.add("*")
  633. if name[0] == "@":
  634. name = "feature:" + name[1:]
  635. deps.append(
  636. "{} {}".format(name, "|".join(sorted(cset))) if cset else name
  637. )
  638. chains[key] = " -> ".join(deps)
  639. return [chains[key] for key in sorted(chains.keys())]
  640. def __init__(self, bad_deps, chains=True, strict=False):
  641. from .models.match_spec import MatchSpec
  642. messages = {
  643. "python": dals(
  644. """
  645. The following specifications were found
  646. to be incompatible with the existing python installation in your environment:
  647. Specifications:\n{specs}
  648. Your python: {ref}
  649. If python is on the left-most side of the chain, that's the version you've asked for.
  650. When python appears to the right, that indicates that the thing on the left is somehow
  651. not available for the python version you are constrained to. Note that conda will not
  652. change your python version to a different minor version unless you explicitly specify
  653. that.
  654. """
  655. ),
  656. "request_conflict_with_history": dals(
  657. """
  658. The following specifications were found to be incompatible with a past
  659. explicit spec that is not an explicit spec in this operation ({ref}):\n{specs}
  660. """
  661. ),
  662. "direct": dals(
  663. """
  664. The following specifications were found to be incompatible with each other:
  665. """
  666. ),
  667. "virtual_package": dals(
  668. """
  669. The following specifications were found to be incompatible with your system:\n{specs}
  670. Your installed version is: {ref}
  671. """
  672. ),
  673. }
  674. msg = ""
  675. self.unsatisfiable = []
  676. if len(bad_deps) == 0:
  677. msg += """
  678. Did not find conflicting dependencies. If you would like to know which
  679. packages conflict ensure that you have enabled unsatisfiable hints.
  680. conda config --set unsatisfiable_hints True
  681. """
  682. else:
  683. for class_name, dep_class in bad_deps.items():
  684. if dep_class:
  685. _chains = []
  686. if class_name == "direct":
  687. msg += messages["direct"]
  688. last_dep_entry = {d[0][-1].name for d in dep_class}
  689. dep_constraint_map = {}
  690. for dep in dep_class:
  691. if dep[0][-1].name in last_dep_entry:
  692. if not dep_constraint_map.get(dep[0][-1].name):
  693. dep_constraint_map[dep[0][-1].name] = []
  694. dep_constraint_map[dep[0][-1].name].append(dep[0])
  695. msg += "\nOutput in format: Requested package -> Available versions"
  696. for dep, chain in dep_constraint_map.items():
  697. if len(chain) > 1:
  698. msg += "\n\nPackage %s conflicts for:\n" % dep
  699. msg += "\n".join(
  700. [" -> ".join([str(i) for i in c]) for c in chain]
  701. )
  702. self.unsatisfiable += [
  703. tuple(entries) for entries in chain
  704. ]
  705. else:
  706. for dep_chain, installed_blocker in dep_class:
  707. # Remove any target values from the MatchSpecs, convert to strings
  708. dep_chain = [
  709. str(MatchSpec(dep, target=None)) for dep in dep_chain
  710. ]
  711. _chains.append(dep_chain)
  712. if _chains:
  713. _chains = self._format_chain_str(_chains)
  714. else:
  715. _chains = [", ".join(c) for c in _chains]
  716. msg += messages[class_name].format(
  717. specs=dashlist(_chains), ref=installed_blocker
  718. )
  719. if strict:
  720. msg += (
  721. "\nNote that strict channel priority may have removed "
  722. "packages required for satisfiability."
  723. )
  724. super().__init__(msg)
  725. class RemoveError(CondaError):
  726. def __init__(self, message):
  727. msg = "%s" % message
  728. super().__init__(msg)
  729. class DisallowedPackageError(CondaError):
  730. def __init__(self, package_ref, **kwargs):
  731. from .models.records import PackageRecord
  732. package_ref = PackageRecord.from_objects(package_ref)
  733. message = (
  734. "The package '%(dist_str)s' is disallowed by configuration.\n"
  735. "See 'conda config --show disallowed_packages'."
  736. )
  737. super().__init__(
  738. message, package_ref=package_ref, dist_str=package_ref.dist_str(), **kwargs
  739. )
  740. class SpecsConfigurationConflictError(CondaError):
  741. def __init__(self, requested_specs, pinned_specs, prefix):
  742. message = dals(
  743. """
  744. Requested specs conflict with configured specs.
  745. requested specs: {requested_specs_formatted}
  746. pinned specs: {pinned_specs_formatted}
  747. Use 'conda config --show-sources' to look for 'pinned_specs' and 'track_features'
  748. configuration parameters. Pinned specs may also be defined in the file
  749. {pinned_specs_path}.
  750. """
  751. ).format(
  752. requested_specs_formatted=dashlist(requested_specs, 4),
  753. pinned_specs_formatted=dashlist(pinned_specs, 4),
  754. pinned_specs_path=join(prefix, "conda-meta", "pinned"),
  755. )
  756. super().__init__(
  757. message,
  758. requested_specs=requested_specs,
  759. pinned_specs=pinned_specs,
  760. prefix=prefix,
  761. )
  762. class CondaIndexError(CondaError, IndexError):
  763. def __init__(self, message):
  764. msg = "%s" % message
  765. super().__init__(msg)
  766. class CondaValueError(CondaError, ValueError):
  767. def __init__(self, message, *args, **kwargs):
  768. super().__init__(message, *args, **kwargs)
  769. class CyclicalDependencyError(CondaError, ValueError):
  770. def __init__(self, packages_with_cycles, **kwargs):
  771. from .models.records import PackageRecord
  772. packages_with_cycles = tuple(
  773. PackageRecord.from_objects(p) for p in packages_with_cycles
  774. )
  775. message = "Cyclic dependencies exist among these items: %s" % dashlist(
  776. p.dist_str() for p in packages_with_cycles
  777. )
  778. super().__init__(message, packages_with_cycles=packages_with_cycles, **kwargs)
  779. class CorruptedEnvironmentError(CondaError):
  780. def __init__(self, environment_location, corrupted_file, **kwargs):
  781. message = dals(
  782. """
  783. The target environment has been corrupted. Corrupted environments most commonly
  784. occur when the conda process is force-terminated while in an unlink-link
  785. transaction.
  786. environment location: %(environment_location)s
  787. corrupted file: %(corrupted_file)s
  788. """
  789. )
  790. super().__init__(
  791. message,
  792. environment_location=environment_location,
  793. corrupted_file=corrupted_file,
  794. **kwargs,
  795. )
  796. class CondaHistoryError(CondaError):
  797. def __init__(self, message):
  798. msg = "%s" % message
  799. super().__init__(msg)
  800. class CondaUpgradeError(CondaError):
  801. def __init__(self, message):
  802. msg = "%s" % message
  803. super().__init__(msg)
  804. class CondaVerificationError(CondaError):
  805. def __init__(self, message):
  806. super().__init__(message)
  807. class SafetyError(CondaError):
  808. def __init__(self, message):
  809. super().__init__(message)
  810. class CondaMemoryError(CondaError, MemoryError):
  811. def __init__(self, caused_by, **kwargs):
  812. message = "The conda process ran out of memory. Increase system memory and/or try again."
  813. super().__init__(message, caused_by=caused_by, **kwargs)
  814. class NotWritableError(CondaError, OSError):
  815. def __init__(self, path, errno, **kwargs):
  816. kwargs.update(
  817. {
  818. "path": path,
  819. "errno": errno,
  820. }
  821. )
  822. if on_win:
  823. message = dals(
  824. """
  825. The current user does not have write permissions to a required path.
  826. path: %(path)s
  827. """
  828. )
  829. else:
  830. message = dals(
  831. """
  832. The current user does not have write permissions to a required path.
  833. path: %(path)s
  834. uid: %(uid)s
  835. gid: %(gid)s
  836. If you feel that permissions on this path are set incorrectly, you can manually
  837. change them by executing
  838. $ sudo chown %(uid)s:%(gid)s %(path)s
  839. In general, it's not advisable to use 'sudo conda'.
  840. """
  841. )
  842. kwargs.update(
  843. {
  844. "uid": os.geteuid(),
  845. "gid": os.getegid(),
  846. }
  847. )
  848. super().__init__(message, **kwargs)
  849. self.errno = errno
  850. class NoWritableEnvsDirError(CondaError):
  851. def __init__(self, envs_dirs, **kwargs):
  852. message = "No writeable envs directories configured.%s" % dashlist(envs_dirs)
  853. super().__init__(message, envs_dirs=envs_dirs, **kwargs)
  854. class NoWritablePkgsDirError(CondaError):
  855. def __init__(self, pkgs_dirs, **kwargs):
  856. message = "No writeable pkgs directories configured.%s" % dashlist(pkgs_dirs)
  857. super().__init__(message, pkgs_dirs=pkgs_dirs, **kwargs)
  858. class EnvironmentNotWritableError(CondaError):
  859. def __init__(self, environment_location, **kwargs):
  860. kwargs.update(
  861. {
  862. "environment_location": environment_location,
  863. }
  864. )
  865. if on_win:
  866. message = dals(
  867. """
  868. The current user does not have write permissions to the target environment.
  869. environment location: %(environment_location)s
  870. """
  871. )
  872. else:
  873. message = dals(
  874. """
  875. The current user does not have write permissions to the target environment.
  876. environment location: %(environment_location)s
  877. uid: %(uid)s
  878. gid: %(gid)s
  879. """
  880. )
  881. kwargs.update(
  882. {
  883. "uid": os.geteuid(),
  884. "gid": os.getegid(),
  885. }
  886. )
  887. super().__init__(message, **kwargs)
  888. class CondaDependencyError(CondaError):
  889. def __init__(self, message):
  890. super().__init__(message)
  891. class BinaryPrefixReplacementError(CondaError):
  892. def __init__(
  893. self, path, placeholder, new_prefix, original_data_length, new_data_length
  894. ):
  895. message = dals(
  896. """
  897. Refusing to replace mismatched data length in binary file.
  898. path: %(path)s
  899. placeholder: %(placeholder)s
  900. new prefix: %(new_prefix)s
  901. original data Length: %(original_data_length)d
  902. new data length: %(new_data_length)d
  903. """
  904. )
  905. kwargs = {
  906. "path": path,
  907. "placeholder": placeholder,
  908. "new_prefix": new_prefix,
  909. "original_data_length": original_data_length,
  910. "new_data_length": new_data_length,
  911. }
  912. super().__init__(message, **kwargs)
  913. class InvalidSpec(CondaError, ValueError):
  914. def __init__(self, message, **kwargs):
  915. super().__init__(message, **kwargs)
  916. class InvalidVersionSpec(InvalidSpec):
  917. def __init__(self, invalid_spec, details):
  918. message = "Invalid version '%(invalid_spec)s': %(details)s"
  919. super().__init__(message, invalid_spec=invalid_spec, details=details)
  920. class InvalidMatchSpec(InvalidSpec):
  921. def __init__(self, invalid_spec, details):
  922. message = "Invalid spec '%(invalid_spec)s': %(details)s"
  923. super().__init__(message, invalid_spec=invalid_spec, details=details)
  924. class EncodingError(CondaError):
  925. def __init__(self, caused_by, **kwargs):
  926. message = (
  927. dals(
  928. """
  929. A unicode encoding or decoding error has occurred.
  930. Python 2 is the interpreter under which conda is running in your base environment.
  931. Replacing your base environment with one having Python 3 may help resolve this issue.
  932. If you still have a need for Python 2 environments, consider using 'conda create'
  933. and 'conda activate'. For example:
  934. $ conda create -n py2 python=2
  935. $ conda activate py2
  936. Error details: %r
  937. """
  938. )
  939. % caused_by
  940. )
  941. super().__init__(message, caused_by=caused_by, **kwargs)
  942. class NoSpaceLeftError(CondaError):
  943. def __init__(self, caused_by, **kwargs):
  944. message = "No space left on devices."
  945. super().__init__(message, caused_by=caused_by, **kwargs)
  946. class CondaEnvException(CondaError):
  947. def __init__(self, message, *args, **kwargs):
  948. msg = "%s" % message
  949. super().__init__(msg, *args, **kwargs)
  950. class EnvironmentFileNotFound(CondaEnvException):
  951. def __init__(self, filename, *args, **kwargs):
  952. msg = f"'{filename}' file not found"
  953. self.filename = filename
  954. super().__init__(msg, *args, **kwargs)
  955. class EnvironmentFileExtensionNotValid(CondaEnvException):
  956. def __init__(self, filename, *args, **kwargs):
  957. msg = f"'{filename}' file extension must be one of '.txt', '.yaml' or '.yml'"
  958. self.filename = filename
  959. super().__init__(msg, *args, **kwargs)
  960. class EnvironmentFileEmpty(CondaEnvException):
  961. def __init__(self, filename, *args, **kwargs):
  962. self.filename = filename
  963. msg = f"'{filename}' is empty"
  964. super().__init__(msg, *args, **kwargs)
  965. class EnvironmentFileNotDownloaded(CondaError):
  966. def __init__(self, username, packagename, *args, **kwargs):
  967. msg = f"{username}/{packagename} file not downloaded"
  968. self.username = username
  969. self.packagename = packagename
  970. super().__init__(msg, *args, **kwargs)
  971. class SpecNotFound(CondaError):
  972. def __init__(self, msg, *args, **kwargs):
  973. super().__init__(msg, *args, **kwargs)
  974. class PluginError(CondaError):
  975. pass
  976. def maybe_raise(error, context):
  977. if isinstance(error, CondaMultiError):
  978. groups = groupby(lambda e: isinstance(e, ClobberError), error.errors)
  979. clobber_errors = groups.get(True, ())
  980. groups = groupby(lambda e: isinstance(e, SafetyError), groups.get(False, ()))
  981. safety_errors = groups.get(True, ())
  982. other_errors = groups.get(False, ())
  983. if (
  984. (safety_errors and context.safety_checks == SafetyChecks.enabled)
  985. or (
  986. clobber_errors
  987. and context.path_conflict == PathConflict.prevent
  988. and not context.clobber
  989. )
  990. or other_errors
  991. ):
  992. raise error
  993. elif (safety_errors and context.safety_checks == SafetyChecks.warn) or (
  994. clobber_errors
  995. and context.path_conflict == PathConflict.warn
  996. and not context.clobber
  997. ):
  998. print_conda_exception(error)
  999. elif isinstance(error, ClobberError):
  1000. if context.path_conflict == PathConflict.prevent and not context.clobber:
  1001. raise error
  1002. elif context.path_conflict == PathConflict.warn and not context.clobber:
  1003. print_conda_exception(error)
  1004. elif isinstance(error, SafetyError):
  1005. if context.safety_checks == SafetyChecks.enabled:
  1006. raise error
  1007. elif context.safety_checks == SafetyChecks.warn:
  1008. print_conda_exception(error)
  1009. else:
  1010. raise error
  1011. def print_conda_exception(exc_val, exc_tb=None):
  1012. from .base.context import context
  1013. rc = getattr(exc_val, "return_code", None)
  1014. if (
  1015. context.debug
  1016. or context.verbosity > 2
  1017. or (not isinstance(exc_val, DryRunExit) and context.verbosity > 0)
  1018. ):
  1019. print(_format_exc(exc_val, exc_tb), file=sys.stderr)
  1020. elif context.json:
  1021. if isinstance(exc_val, DryRunExit):
  1022. return
  1023. logger = getLogger("conda.stdout" if rc else "conda.stderr")
  1024. exc_json = json.dumps(
  1025. exc_val.dump_map(), indent=2, sort_keys=True, cls=EntityEncoder
  1026. )
  1027. logger.info("%s\n" % exc_json)
  1028. else:
  1029. stderrlog = getLogger("conda.stderr")
  1030. stderrlog.error("\n%r\n", exc_val)
  1031. # An alternative which would allow us not to reload sys with newly setdefaultencoding()
  1032. # is to not use `%r`, e.g.:
  1033. # Still, not being able to use `%r` seems too great a price to pay.
  1034. # stderrlog.error("\n" + exc_val.__repr__() + \n")
  1035. def _format_exc(exc_val=None, exc_tb=None):
  1036. if exc_val is None:
  1037. exc_type, exc_val, exc_tb = sys.exc_info()
  1038. else:
  1039. exc_type = type(exc_val)
  1040. if exc_tb:
  1041. formatted_exception = format_exception(exc_type, exc_val, exc_tb)
  1042. else:
  1043. formatted_exception = format_exception_only(exc_type, exc_val)
  1044. return "".join(formatted_exception)