from__future__importannotationsimportosimportsysfromcontextlibimportsuppressfromerrnoimportEACCESfrompathlibimportPathfromtypingimportcastfrom._apiimportBaseFileLockfrom._utilimportensure_directory_exists,raise_on_not_writable_fileifsys.platform=="win32":# pragma: win32 coverimportmsvcrtclassWindowsFileLock(BaseFileLock):"""Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems."""def_acquire(self)->None:raise_on_not_writable_file(self.lock_file)ensure_directory_exists(self.lock_file)flags=(os.O_RDWR# open for read and write|os.O_CREAT# create file if not exists|os.O_TRUNC# truncate file if not empty)try:fd=os.open(self.lock_file,flags,self._context.mode)exceptOSErrorasexception:ifexception.errno!=EACCES:# has no access to this lockraiseelse:try:msvcrt.locking(fd,msvcrt.LK_NBLCK,1)exceptOSErrorasexception:os.close(fd)# close file firstifexception.errno!=EACCES:# file is already lockedraiseelse:self._context.lock_file_fd=fddef_release(self)->None:fd=cast(int,self._context.lock_file_fd)self._context.lock_file_fd=Nonemsvcrt.locking(fd,msvcrt.LK_UNLCK,1)os.close(fd)withsuppress(OSError):# Probably another instance of the application hat acquired the file lock.Path(self.lock_file).unlink()else:# pragma: win32 no cover
[docs]classWindowsFileLock(BaseFileLock):"""Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems."""def_acquire(self)->None:raiseNotImplementedErrordef_release(self)->None:raiseNotImplementedError