






"""simple docstring"""
import logging
import os
import threading
import time


try:
							import warnings
except ImportError:
							_lowerCAmelCase     :   Optional[Any]         =							None

try:
							import msvcrt
except ImportError:
							_lowerCAmelCase     :   Tuple         =							None

try:
							import fcntl
except ImportError:
							_lowerCAmelCase     :   Dict         =							None


# Backward compatibility
# ------------------------------------------------
try:
							TimeoutError
except NameError:
							_lowerCAmelCase     :   Union[str, Any]         =							OSError


# Data
# ------------------------------------------------
_lowerCAmelCase     :   List[Any]         =							[
    "Timeout",
    "BaseFileLock",
    "WindowsFileLock",
    "UnixFileLock",
    "SoftFileLock",
    "FileLock",
]

_lowerCAmelCase     :   int         =							"3.0.12"


_lowerCAmelCase     :   List[str]         =							None






def 			__UpperCamelCase	(		):
	global _logger
	A_		:						Dict	    =   _logger or logging.getLogger(__name__					)
	return _logger



class      SCREAMING_SNAKE_CASE  (				_SCREAMING_SNAKE_CASE						):





	"""simple docstring"""




	def __init__(self     ,     lowerCAmelCase_							):
		A_		:						Union[str, Any]	    =   lock_file
		return None





	def __str__(self							):
		A_		:						Optional[Any]	    =   f"""The file lock '{self.lock_file}' could not be acquired."""
		return temp






class      SCREAMING_SNAKE_CASE  :





	"""simple docstring"""




	def __init__(self     ,     lowerCAmelCase_							):
		A_		:						Optional[Any]	    =   lock
		return None





	def __enter__(self							):
		return self.lock





	def __exit__(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							):
		self.lock.release()
		return None






class      SCREAMING_SNAKE_CASE  :





	"""simple docstring"""




	def __init__(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_=-1     ,     lowerCAmelCase_=None							):
		A_		:						Tuple	    =   max_filename_length if max_filename_length is not None else 255
		# Hash the filename if it's too long
		A_		:						Tuple	    =   self.hash_filename_if_too_long(lowerCAmelCase_     ,     lowerCAmelCase_							)
		# The path to the lock file.
		A_		:						Optional[Any]	    =   lock_file

		# The file descriptor for the *_lock_file* as it is returned by the
		# os.open() function.
		# This file lock is only NOT None, if the object currently holds the
		# lock.
		A_		:						Any	    =   None

		# The default timeout value.
		A_		:						List[str]	    =   timeout

		# We use this lock primarily for the lock counter.
		A_		:						Tuple	    =   threading.Lock()

		# The lock counter is used for implementing the nested locking
		# mechanism. Whenever the lock is acquired, the counter is increased and
		# the lock is only released, when this value is 0 again.
		A_		:						Dict	    =   0
		return None





	@property
	def    lowerCamelCase(self							):
		return self._lock_file





	@property
	def    lowerCamelCase(self							):
		return self._timeout





	@timeout.setter
	def    lowerCamelCase(self     ,     lowerCAmelCase_							):
		A_		:						Tuple	    =   float(lowerCAmelCase_							)
		return None





	def    lowerCamelCase(self							):
		raise NotImplementedError()





	def    lowerCamelCase(self							):
		raise NotImplementedError()





	@property
	def    lowerCamelCase(self							):
		return self._lock_file_fd is not None





	def    lowerCamelCase(self     ,     lowerCAmelCase_=None     ,     lowerCAmelCase_=0.05							):
		# Use the default timeout, if no timeout is provided.
		if timeout is None:
			A_		:						List[str]	    =   self.timeout

		# Increment the number right at the beginning.
		# We can still undo it, if something fails.
		with self._thread_lock:
			self._lock_counter += 1

		A_		:						str	    =   id(self							)
		A_		:						Optional[int]	    =   self._lock_file
		A_		:						Dict	    =   time.time()
		try:
			while True:
				with self._thread_lock:
					if not self.is_locked:
						logger().debug(f"""Attempting to acquire lock {lock_id} on {lock_filename}"""							)
						self._acquire()

				if self.is_locked:
					logger().debug(f"""Lock {lock_id} acquired on {lock_filename}"""							)
					break
				elif timeout >= 0 and time.time() - start_time > timeout:
					logger().debug(f"""Timeout on acquiring lock {lock_id} on {lock_filename}"""							)
					raise Timeout(self._lock_file							)
				else:
					logger().debug(
					    f"""Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ..."""							)
					time.sleep(lowerCAmelCase_							)
		except:  # noqa
			# Something did go wrong, so decrement the counter.
			with self._thread_lock:
				A_		:						str	    =   max(0     ,     self._lock_counter - 1							)

			raise
		return _Acquire_ReturnProxy(lock=self							)





	def    lowerCamelCase(self     ,     lowerCAmelCase_=False							):
		with self._thread_lock:
			if self.is_locked:
				self._lock_counter -= 1

				if self._lock_counter == 0 or force:
					A_		:						Union[str, Any]	    =   id(self							)
					A_		:						List[Any]	    =   self._lock_file

					logger().debug(f"""Attempting to release lock {lock_id} on {lock_filename}"""							)
					self._release()
					A_		:						Any	    =   0
					logger().debug(f"""Lock {lock_id} released on {lock_filename}"""							)

		return None





	def __enter__(self							):
		self.acquire()
		return self





	def __exit__(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_     ,     lowerCAmelCase_							):
		self.release()
		return None





	def __del__(self							):
		self.release(force=lowerCAmelCase_							)
		return None





	def    lowerCamelCase(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_							):
		A_		:						Dict	    =   os.path.basename(lowerCAmelCase_							)
		if len(lowerCAmelCase_							) > max_length and max_length > 0:
			A_		:						str	    =   os.path.dirname(lowerCAmelCase_							)
			A_		:						List[str]	    =   str(hash(lowerCAmelCase_							)							)
			A_		:						List[Any]	    =   filename[: max_length - len(lowerCAmelCase_							) - 8] + """...""" + hashed_filename + """.lock"""
			return os.path.join(lowerCAmelCase_     ,     lowerCAmelCase_							)
		else:
			return path






class      SCREAMING_SNAKE_CASE  (				_SCREAMING_SNAKE_CASE						):





	"""simple docstring"""




	def __init__(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_=-1     ,     lowerCAmelCase_=None							):
		from .file_utils import relative_to_absolute_path

		super().__init__(lowerCAmelCase_     ,     timeout=lowerCAmelCase_     ,     max_filename_length=lowerCAmelCase_							)
		A_		:						Optional[Any]	    =   """\\\\?\\""" + relative_to_absolute_path(self.lock_file							)





	def    lowerCamelCase(self							):
		A_		:						Optional[int]	    =   os.O_RDWR | os.O_CREAT | os.O_TRUNC

		try:
			A_		:						Dict	    =   os.open(self._lock_file     ,     lowerCAmelCase_							)
		except OSError:
			pass
		else:
			try:
				msvcrt.locking(lowerCAmelCase_     ,     msvcrt.LK_NBLCK     ,     1							)
			except OSError:
				os.close(lowerCAmelCase_							)
			else:
				A_		:						Tuple	    =   fd
		return None





	def    lowerCamelCase(self							):
		A_		:						int	    =   self._lock_file_fd
		A_		:						Tuple	    =   None
		msvcrt.locking(lowerCAmelCase_     ,     msvcrt.LK_UNLCK     ,     1							)
		os.close(lowerCAmelCase_							)

		try:
			os.remove(self._lock_file							)
		# Probably another instance of the application
		# that acquired the file lock.
		except OSError:
			pass
		return None






class      SCREAMING_SNAKE_CASE  (				_SCREAMING_SNAKE_CASE						):





	"""simple docstring"""




	def __init__(self     ,     lowerCAmelCase_     ,     lowerCAmelCase_=-1     ,     lowerCAmelCase_=None							):
		A_		:						Tuple	    =   os.statvfs(os.path.dirname(lowerCAmelCase_							)							).f_namemax
		super().__init__(lowerCAmelCase_     ,     timeout=lowerCAmelCase_     ,     max_filename_length=lowerCAmelCase_							)





	def    lowerCamelCase(self							):
		A_		:						Optional[Any]	    =   os.O_RDWR | os.O_CREAT | os.O_TRUNC
		A_		:						int	    =   os.open(self._lock_file     ,     lowerCAmelCase_							)

		try:
			fcntl.flock(lowerCAmelCase_     ,     fcntl.LOCK_EX | fcntl.LOCK_NB							)
		except OSError:
			os.close(lowerCAmelCase_							)
		else:
			A_		:						Any	    =   fd
		return None





	def    lowerCamelCase(self							):
		# Do not remove the lockfile:
		#
		#   https://github.com/benediktschmitt/py-filelock/issues/31
		#   https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
		A_		:						List[str]	    =   self._lock_file_fd
		A_		:						int	    =   None
		fcntl.flock(lowerCAmelCase_     ,     fcntl.LOCK_UN							)
		os.close(lowerCAmelCase_							)
		return None






class      SCREAMING_SNAKE_CASE  (				_SCREAMING_SNAKE_CASE						):





	"""simple docstring"""




	def    lowerCamelCase(self							):
		A_		:						Union[str, Any]	    =   os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
		try:
			A_		:						Any	    =   os.open(self._lock_file     ,     lowerCAmelCase_							)
		except OSError:
			pass
		else:
			A_		:						List[str]	    =   fd
		return None





	def    lowerCamelCase(self							):
		os.close(self._lock_file_fd							)
		A_		:						List[str]	    =   None

		try:
			os.remove(self._lock_file							)
		# The file is already deleted and that's what we want.
		except OSError:
			pass
		return None






_lowerCAmelCase     :   Any         =							None

if msvcrt:
							_lowerCAmelCase     :   int         =							WindowsFileLock
elif fcntl:
							_lowerCAmelCase     :   Optional[Any]         =							UnixFileLock
else:
							_lowerCAmelCase     :   Any         =							SoftFileLock

							if warnings is not None:
														warnings.warn("only soft file lock is available")









"""simple docstring"""
import os


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_doctest_list.py
_lowerCAmelCase         =							"."


if __name__ == "__main__":
							_lowerCAmelCase         =							os.path.join(REPO_PATH, "utils/documentation_tests.txt")
							_lowerCAmelCase         =							[]
							_lowerCAmelCase         =							[]
							with open(doctest_file_path) as fp:
														for line in fp:
																					_lowerCAmelCase         =							line.strip()
																					_lowerCAmelCase         =							os.path.join(REPO_PATH, line)
																					if not (os.path.isfile(path) or os.path.isdir(path)):
																												non_existent_paths.append(line)
																					all_paths.append(path)
							if len(non_existent_paths) > 0:
														_lowerCAmelCase         =							"\n".join(non_existent_paths)
														raise ValueError(F'`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}')
							if all_paths != sorted(all_paths):
														raise ValueError("Files in `utils/documentation_tests.txt` are not in alphabetical order.")

