stop.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # -*- encoding: utf-8 -*-
  2. #
  3. # Copyright 2016–2021 Julien Danjou
  4. # Copyright 2016 Joshua Harlow
  5. # Copyright 2013-2014 Ray Holder
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import abc
  19. from pip._vendor import six
  20. @six.add_metaclass(abc.ABCMeta)
  21. class stop_base(object):
  22. """Abstract base class for stop strategies."""
  23. @abc.abstractmethod
  24. def __call__(self, retry_state):
  25. pass
  26. def __and__(self, other):
  27. return stop_all(self, other)
  28. def __or__(self, other):
  29. return stop_any(self, other)
  30. class stop_any(stop_base):
  31. """Stop if any of the stop condition is valid."""
  32. def __init__(self, *stops):
  33. self.stops = stops
  34. def __call__(self, retry_state):
  35. return any(x(retry_state) for x in self.stops)
  36. class stop_all(stop_base):
  37. """Stop if all the stop conditions are valid."""
  38. def __init__(self, *stops):
  39. self.stops = stops
  40. def __call__(self, retry_state):
  41. return all(x(retry_state) for x in self.stops)
  42. class _stop_never(stop_base):
  43. """Never stop."""
  44. def __call__(self, retry_state):
  45. return False
  46. stop_never = _stop_never()
  47. class stop_when_event_set(stop_base):
  48. """Stop when the given event is set."""
  49. def __init__(self, event):
  50. self.event = event
  51. def __call__(self, retry_state):
  52. return self.event.is_set()
  53. class stop_after_attempt(stop_base):
  54. """Stop when the previous attempt >= max_attempt."""
  55. def __init__(self, max_attempt_number):
  56. self.max_attempt_number = max_attempt_number
  57. def __call__(self, retry_state):
  58. return retry_state.attempt_number >= self.max_attempt_number
  59. class stop_after_delay(stop_base):
  60. """Stop when the time from the first attempt >= limit."""
  61. def __init__(self, max_delay):
  62. self.max_delay = max_delay
  63. def __call__(self, retry_state):
  64. return retry_state.seconds_since_start >= self.max_delay