
    gi_                       d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZmZmZmZ ddlm Z  dd	l!m"Z" erdd
l#m$Z$ ddlm%Z% ddlm&Z& ddlm'Z'm(Z( dZ)dZ* e jV                         re*nejX                  ejZ                  z  Z.ej^                  Z0ejb                  ejd                  z  ejf                  z  Z4ejj                  ejl                  z  ejn                  z  ejp                  z  ejr                  z  ejt                  z  ejv                  z  Z<ddZ=ddZ>ddZ?ddZ@ddZA G d d      ZB G d d      ZC G d de      ZD G d de      ZEy)u  :module: watchdog.observers.kqueue
:synopsis: ``kqueue(2)`` based emitter implementation.
:author: yesudeep@google.com (Yesudeep Mangalapilly)
:author: contact@tiger-222.fr (Mickaël Schoentgen)
:platforms: macOS and BSD with kqueue(2).

.. WARNING:: kqueue is a very heavyweight way to monitor file systems.
             Each kqueue-detected directory modification triggers
             a full directory scan. Traversing the entire directory tree
             and opening file descriptors for all files will create
             performance problems. We need to find a way to re-scan
             only those directories which report changes and do a diff
             between two sub-DirectorySnapshots perhaps.

.. ADMONITION:: About OS X performance guidelines

    Quote from the `macOS File System Performance Guidelines`_:

        "When you only want to track changes on a file or directory, be sure to
        open it using the ``O_EVTONLY`` flag. This flag prevents the file or
        directory from being marked as open or in use. This is important
        if you are tracking files on a removable volume and the user tries to
        unmount the volume. With this flag in place, the system knows it can
        dismiss the volume. If you had opened the files or directories without
        this flag, the volume would be marked as busy and would not be
        unmounted."

    ``O_EVTONLY`` is defined as ``0x8000`` in the OS X header files.
    More information here: http://www.mlsite.net/blog/?p=2312

Classes
-------
.. autoclass:: KqueueEmitter
   :members:
   :show-inheritance:

Collections and Utility Classes
-------------------------------
.. autoclass:: KeventDescriptor
   :members:
   :show-inheritance:

.. autoclass:: KeventDescriptorSet
   :members:
   :show-inheritance:

.. _macOS File System Performance Guidelines:
    http://developer.apple.com/library/ios/#documentation/Performance/Conceptual/FileSystem/Articles/TrackingChanges.html#//apple_ref/doc/uid/20001993-CJBJFIDD

    )annotationsN)S_ISDIR)TYPE_CHECKING)EVENT_TYPE_CREATEDEVENT_TYPE_DELETEDEVENT_TYPE_MOVEDDirCreatedEventDirDeletedEventDirModifiedEventDirMovedEventFileCreatedEventFileDeletedEventFileModifiedEventFileMovedEventgenerate_sub_moved_events)DEFAULT_EMITTER_TIMEOUTDEFAULT_OBSERVER_TIMEOUTBaseObserverEventEmitter)platform)DirectorySnapshot)	Generator)Callable)FileSystemEvent)
EventQueueObservedWatchi   i   c                z    t         j                  j                  t         j                  j                  |             S N)ospathabspathnormpath)r    s    N/var/www/openai/venv/lib/python3.12/site-packages/watchdog/observers/kqueue.pyabsolute_pathr$   s   s$    77??277++D122    c                B    | j                   t        j                  z  dkD  S )z8Determines whether the given kevent represents deletion.r   )fflagsselectKQ_NOTE_DELETEkevs    r#   
is_deletedr,   z       ::---11r%   c                v    | j                   }|t        j                  z  dkD  xs |t        j                  z  dkD  S )z<Determines whether the given kevent represents modification.r   )r'   r(   KQ_NOTE_EXTENDKQ_NOTE_WRITE)r+   r'   s     r#   is_modifiedr1      s7    ZZFV***Q.VFV=Q=Q4QTU4UVr%   c                B    | j                   t        j                  z  dkD  S )zFDetermines whether the given kevent represents attribute modification.r   )r'   r(   KQ_NOTE_ATTRIBr*   s    r#   is_attrib_modifiedr4      r-   r%   c                B    | j                   t        j                  z  dkD  S )z8Determines whether the given kevent represents movement.r   )r'   r(   KQ_NOTE_RENAMEr*   s    r#   
is_renamedr7      r-   r%   c                      e Zd ZdZddZedd       Zedd       ZddZddZ	ddZ
ddZdd	Zdd
ZddZddZddZddZy)KeventDescriptorSetz)Thread-safe kevent descriptor collection.c                ~    t               | _        i | _        i | _        g | _        t        j                         | _        y r   )set_descriptors_descriptor_for_path_descriptor_for_fd_kevents	threadingLock_lockselfs    r#   __init__zKeventDescriptorSet.__init__   s1    365IK!?A-/^^%
r%   c                ^    | j                   5  | j                  cddd       S # 1 sw Y   yxY w)zList of kevents monitored.N)rB   r?   rC   s    r#   keventszKeventDescriptorSet.kevents   s     ZZ== ZZs   #,c                    | j                   5  t        | j                  j                               cddd       S # 1 sw Y   yxY w)z2List of paths for which kevents have been created.N)rB   listr=   keysrC   s    r#   pathszKeventDescriptorSet.paths   s,     ZZ116689 ZZs	   #:Ac                d    | j                   5  | j                  |   cddd       S # 1 sw Y   yxY w)zGiven a file descriptor, returns the kevent descriptor object
        for it.

        :param fd:
            OS file descriptor.
        :type fd:
            ``int``
        :returns:
            A :class:`KeventDescriptor` object.
        N)rB   r>   )rD   fds     r#   
get_for_fdzKeventDescriptorSet.get_for_fd   s#     ZZ**2. ZZs   &/c                ~    | j                   5  t        |      }| j                  |      cddd       S # 1 sw Y   yxY w)zObtains a :class:`KeventDescriptor` object for the specified path.

        :param path:
            Path for which the descriptor will be obtained.
        N)rB   r$   _getrD   r    s     r#   getzKeventDescriptorSet.get   s*     ZZ &D99T? ZZ   3<c                ~    | j                   5  t        |      }| j                  |      cddd       S # 1 sw Y   yxY w)zDetermines whether a :class:`KeventDescriptor has been registered
        for the specified path.

        :param path:
            Path for which the descriptor will be obtained.
        N)rB   r$   	_has_pathrQ   s     r#   __contains__z KeventDescriptorSet.__contains__   s+     ZZ &D>>$' ZZrS   c                   | j                   5  t        |      }| j                  |      s| j                  t	        ||             ddd       y# 1 sw Y   yxY w)ae  Adds a :class:`KeventDescriptor` to the collection for the given
        path.

        :param path:
            The path for which a :class:`KeventDescriptor` object will be
            added.
        :param is_directory:
            ``True`` if the path refers to a directory; ``False`` otherwise.
        :type is_directory:
            ``bool``
        is_directoryN)rB   r$   rU   _add_descriptorKeventDescriptorrD   r    rY   s      r#   addzKeventDescriptorSet.add   sA     ZZ &D>>$'$$%5d%VW ZZs   9AAc                    | j                   5  t        |      }| j                  |      r | j                  | j	                  |             ddd       y# 1 sw Y   yxY w)zRemoves the :class:`KeventDescriptor` object for the given path
        if it already exists.

        :param path:
            Path for which the :class:`KeventDescriptor` object will be
            removed.
        N)rB   r$   rU   _remove_descriptorrP   rQ   s     r#   removezKeventDescriptorSet.remove   sA     ZZ &D~~d#''		$8 ZZs   =AAc                2   | j                   5  | j                  D ]  }|j                           | j                  j                          | j                  j                          | j
                  j                          g | _        ddd       y# 1 sw Y   yxY w)z6Clears the collection and closes all open descriptors.N)rB   r<   closeclearr>   r=   r?   rD   
descriptors     r#   rc   zKeventDescriptorSet.clear   sl    ZZ"//
  " 0##%##))+%%++-DM ZZs   A7BBc                     | j                   |   S )z-Returns a kevent descriptor for a given path.r=   rQ   s     r#   rP   zKeventDescriptorSet._get   s    ((..r%   c                    || j                   v S )zxDetermines whether a :class:`KeventDescriptor` for the specified
        path exists already in the collection.
        rg   rQ   s     r#   rU   zKeventDescriptorSet._has_path   s     t0000r%   c                    | j                   j                  |       | j                  j                  |j                         || j
                  |j                  <   || j                  |j                  <   y)zAdds a descriptor to the collection.

        :param descriptor:
            An instance of :class:`KeventDescriptor` to be added.
        N)	r<   r]   r?   appendkeventr=   r    r>   rM   rd   s     r#   rZ   z#KeventDescriptorSet._add_descriptor   sX     	j)Z../5?!!*//21;
.r%   c                    | j                   j                  |       | j                  |j                  = | j                  |j
                  = | j                  j                  |j                         |j                          y)zRemoves a descriptor from the collection.

        :param descriptor:
            An instance of :class:`KeventDescriptor` to be removed.
        N)	r<   r`   r>   rM   r=   r    r?   rk   rb   rd   s     r#   r_   z&KeventDescriptorSet._remove_descriptor  s`     	  ,##JMM2%%joo6Z../r%   NreturnNone)rn   list[select.kevent])rn   zlist[bytes | str])rM   intrn   r[   )r    bytes | strrn   r[   )r    rr   rn   boolr    rr   rY   rs   rn   ro   r    rr   rn   ro   )re   r[   rn   ro   )__name__
__module____qualname____doc__rE   propertyrG   rK   rN   rR   rV   r]   r`   rc   rP   rU   rZ   r_    r%   r#   r9   r9      se    3& ! !
 : :
/#	(X"9/1	<
r%   r9   c                      e Zd ZdZddZedd       Zedd       Zedd       Zedd       Z	ddZ
edd       Zdd	Zdd
ZddZddZy)r[   a{  A kevent descriptor convenience data structure to keep together:

        * kevent
        * directory status
        * path
        * file descriptor

    :param path:
        Path string for which a kevent descriptor will be created.
    :param is_directory:
        ``True`` if the path refers to a directory; ``False`` otherwise.
    :type is_directory:
        ``bool``
    c                   t        |      | _        || _        t        j                  |t
              | _        t        j                  | j                  t        t        t              | _        y )N)filterflagsr'   )r$   _path_is_directoryr   openWATCHDOG_OS_OPEN_FLAGS_fdr(   rk   WATCHDOG_KQ_FILTERWATCHDOG_KQ_EV_FLAGSWATCHDOG_KQ_FFLAGS_kevr\   s      r#   rE   zKeventDescriptor.__init__#  sI    "4(
)774!78MMHH%&%	
	r%   c                    | j                   S )z-OS file descriptor for the kevent descriptor.)r   rC   s    r#   rM   zKeventDescriptor.fd.  s     xxr%   c                    | j                   S )z/The path associated with the kevent descriptor.)r   rC   s    r#   r    zKeventDescriptor.path3  s     zzr%   c                    | j                   S )z8The kevent object associated with the kevent descriptor.)r   rC   s    r#   rk   zKeventDescriptor.kevent8  s     yyr%   c                    | j                   S )z}Determines whether the kevent descriptor refers to a directory.

        :returns:
            ``True`` or ``False``
        )r   rC   s    r#   rY   zKeventDescriptor.is_directory=  s     !!!r%   c                    t        j                  t              5  t        j                  | j
                         ddd       y# 1 sw Y   yxY w)z?Closes the file descriptor associated with a kevent descriptor.N)
contextlibsuppressOSErrorr   rb   rM   rC   s    r#   rb   zKeventDescriptor.closeF  s,      )HHTWW *))s    AAc                2    | j                   | j                  fS r   )r    rY   rC   s    r#   keyzKeventDescriptor.keyK  s    		4,,--r%   c                `    t        |t              st        S | j                  |j                  k(  S r   
isinstancer[   NotImplementedr   rd   s     r#   __eq__zKeventDescriptor.__eq__O  &    *&67!!xx:>>))r%   c                `    t        |t              st        S | j                  |j                  k7  S r   r   rd   s     r#   __ne__zKeventDescriptor.__ne__T  r   r%   c                ,    t        | j                        S r   )hashr   rC   s    r#   __hash__zKeventDescriptor.__hash__Y  s    DHH~r%   c                h    dt        |       j                   d| j                  d| j                   dS )N<z: path=z, is_directory=>)typerv   r    rY   rC   s    r#   __repr__zKeventDescriptor.__repr__\  s4    4:&&'wtyym?4K\K\J]]^__r%   Nrt   )rn   rq   )rn   rr   )rn   select.kevent)rn   rs   rm   )rn   ztuple[bytes | str, bool])re   objectrn   rs   )rn   str)rv   rw   rx   ry   rE   rz   rM   r    rk   rY   rb   r   r   r   r   r   r{   r%   r#   r[   r[     s    	
       " "
 . .*
*
`r%   r[   c                       e Zd ZdZedej                  d	 	 	 	 	 	 	 	 	 	 	 d fdZddZddZ	ddZ
	 	 	 	 	 	 	 	 ddZdd	Z	 	 	 	 	 	 	 	 	 	 dd
ZddZddZddZ xZS )KqueueEmittera}  kqueue(2)-based event emitter.

    .. ADMONITION:: About ``kqueue(2)`` behavior and this implementation

              ``kqueue(2)`` monitors file system events only for
              open descriptors, which means, this emitter does a lot of
              book-keeping behind the scenes to keep track of open
              descriptors for every entry in the monitored directory tree.

              This also means the number of maximum open file descriptors
              on your system must be increased **manually**.
              Usually, issuing a call to ``ulimit`` should suffice::

                  ulimit -n 1024

              Ensure that you pick a number that is larger than the
              number of files you expect to be monitored.

              ``kqueue(2)`` does not provide enough information about the
              following things:

              * The destination path of a file or directory that is renamed.
              * Creation of a file or directory within a directory; in this
                case, ``kqueue(2)`` only indicates a modified event on the
                parent directory.

              Therefore, this emitter takes a snapshot of the directory
              tree when ``kqueue(2)`` detects a change on the file system
              to be able to determine the above information.

    :param event_queue:
        The event queue to fill with events.
    :param watch:
        A watch object representing the directory to monitor.
    :type watch:
        :class:`watchdog.observers.api.ObservedWatch`
    :param timeout:
        Read events blocking timeout (in seconds).
    :type timeout:
        ``float``
    :param event_filter:
        Collection of event types to emit, or None for no filtering (default).
    :type event_filter:
        Iterable[:class:`watchdog.events.FileSystemEvent`] | None
    :param stat: stat function. See ``os.stat`` for details.
    N)timeoutevent_filterstatc                  t         |   ||||       t        j                         | _        t        j                         | _        t               | _	        | fdfd}t        |j                  |j                  |      | _        y )N)r   r   c                d     |       }|j                  | t        |j                               |S )NrX   )_register_keventr   st_mode)r    cls	stat_infor   s      r#   custom_statz+KqueueEmitter.__init__.<locals>.custom_stat  s0    T
I  GI<M<M4N Or%   )	recursiver   )r    r   r   r   rn   zos.stat_result)superrE   r(   kqueue_kqr@   RLockrB   r9   r<   r   r    is_recursive	_snapshot)rD   event_queuewatchr   r   r   r   	__class__s        ` r#   rE   zKqueueEmitter.__init__  sh     	eW<X==?__&
 018< 	
 +5::ASASZefr%   c                   	 | j                   j                  ||       y# t        $ rL}|j                  t        j                  k(  rn$|j                  t        j
                  k(  rn Y d}~yY d}~yd}~ww xY w)a+  Registers a kevent descriptor for the given path.

        :param path:
            Path for which a kevent descriptor will be created.
        :param is_directory:
            ``True`` if the path refers to a directory; ``False`` otherwise.
        :type is_directory:
            ``bool``
        rX   N)r<   r]   r   errnoENOENT
EOPNOTSUPP)rD   r    rY   es       r#   r   zKqueueEmitter._register_kevent  sk    	!!$\!B 	ww%,,& E,,,
    	s     	A5=A00A5c                :    | j                   j                  |       y)zConvenience function to close the kevent descriptor for a
        specified kqueue-monitored path.

        :param path:
            Path for which the kevent descriptor will be closed.
        N)r<   r`   rQ   s     r#   _unregister_keventz KqueueEmitter._unregister_kevent  s     	  &r%   c                   t        j                  | |       |j                  t        k(  r(| j	                  |j
                  |j                         y|j                  t        k(  rC| j                  |j
                         | j	                  |j                  |j                         y|j                  t        k(  r| j                  |j
                         yy)zHandles queueing a single event object.

        :param event:
            An instance of :class:`watchdog.events.FileSystemEvent`
            or a subclass.
        rX   N)r   queue_event
event_typer   r   src_pathrY   r   r   	dest_pathr   )rD   events     r#   r   zKqueueEmitter.queue_event  s     	  u-11!!%..u?Q?Q!R!11##ENN3!!%//@R@R!S!33##ENN3 4r%   c              #  j  K   | j                   j                  |j                        }|j                  }t	        |      r(| j                  ||||j                        E d{    yt        |      r(|j                  rt        |       yt        |       yt        |      rX|j                  r=| j                  j                  s| j                  j                  |k(  rt        |       yt        |       yyt        |      r(|j                  rt        |       yt        |       yy7 ϭw)a  Generate events from the kevent list returned from the call to
        :meth:`select.kqueue.control`.

        .. NOTE:: kqueue only tells us about deletions, file modifications,
                  attribute modifications. The other events, namely,
                  file creation, directory modification, file rename,
                  directory rename, directory creation, etc. are
                  determined by comparing directory snapshots.
        rX   N)r<   rN   identr    r7   _gen_renamed_eventsrY   r4   r   r   r1   r   r   r,   r
   r   )rD   r+   ref_snapshotnew_snapshotre   r   s         r#   _gen_kqueue_eventsz KqueueEmitter._gen_kqueue_events  s	     &&11#))<
??c? //'44	 0     $&&&x00'11&&::**djjoo.I
 +844'11 /J _&&%h//&x00	 +s   AD3!D1"CD3c                R    t        t        j                  j                  |            S )z@Helper to generate a DirModifiedEvent on the parent of src_path.)r   r   r    dirname)rD   r   s     r#   _parent_dir_modifiedz"KqueueEmitter._parent_dir_modified  s     9::r%   c             #  F  K   	 |j                  |      }|j                  |      }|t        |      }|rt        ||       nt        ||       | j                  |       | j                  |       |r,| j                  j                  rt        ||      E d{    yyy|rt        |       nt        |       | j                  |       y# t        $ r; |rt        |       t        |       Y yt	        |       t        |       Y yw xY w7 w)a  Compares information from two directory snapshots (one taken before
        the rename operation and another taken right after) to determine the
        destination path of the file system object renamed, and yields
        the appropriate events to be queued.
        N)inodeKeyErrorr	   r
   r   r   r    r$   r   r   r   r   r   r   )rD   r   r   r   rY   f_inoder   s          r#   r   z!KqueueEmitter._gen_renamed_events  s%    	"((2G !%%g.	 %i0I#Hi88$Xy99++H55++I66

 7 7 5XyIII !8| %h//&x00++H55M  	 %h//%h// 	 'x00&x00 	: Js@   D!C B
D!D 8D!%D=D!?DD!DD!c                l    | j                   j                  | j                  j                  t        |      S )zReads events from a call to the blocking
        :meth:`select.kqueue.control()` method.

        :param timeout:
            Blocking timeout for reading events.
        :type timeout:
            ``float`` (seconds)
        )r   controlr<   rG   
MAX_EVENTS)rD   r   s     r#   _read_eventszKqueueEmitter._read_eventsQ  s)     xx 1 1 9 9:wOOr%   c                   | j                   5  	 | j                  |      }|j                          t        | j                  j
                  | j                  j                        }| j                  }|| _        ||z
  }|j                  D ]  }| j                  t        |              |j                  D ]  }| j                  t        |              |j                  D ]  }| j                  t        |              |D ]+  }	| j                  |	||      D ]  }
| j                  |
        - 	 ddd       y# t         $ r(}|j"                  t"        j$                  k7  r Y d}~5d}~ww xY w# 1 sw Y   yxY w)zQueues events by reading them from a call to the blocking
        :meth:`select.kqueue.control()` method.

        :param timeout:
            Blocking timeout for reading events.
        :type timeout:
            ``float`` (seconds)
        )r   N)rB   r   reverser   r   r    r   r   dirs_createdr   r	   files_createdr   files_modifiedr   r   r   r   EBADF)rD   r   
event_listr   r   diff_eventsdirectory_createdfile_createdfile_modifiedr+   r   r   s               r#   queue_eventszKqueueEmitter.queue_events\  sD    ZZ!..w7
""$  1DJJLcLcd#~~!-*\9 *5)A)A%$$_5F%GH *B$/$=$=L$$%5l%CD %>%0%?%?M$$%6}%EF &@ &C!%!8!8lL!Y((/ "Z &+ Z2  77ekk) *3 Zs5   E,DD8.E,8	E)E$E,$E))E,,E5c                    | j                   5  | j                  j                          | j                  j	                          d d d        y # 1 sw Y   y xY wr   )rB   r<   rc   r   rb   rC   s    r#   on_thread_stopzKqueueEmitter.on_thread_stop  s3    ZZ##%HHNN ZZs   5AA)r   r   r   r   r   floatr   z"list[type[FileSystemEvent]] | Noner   zCallable[[str], os.stat_result]rn   ro   rt   ru   )r   r   rn   ro   )r+   r   r   r   r   r   rn   Generator[FileSystemEvent])r   rr   rn   r   )
r   rr   r   r   r   r   rY   rs   rn   r   )r   r   rn   rp   r   r   rn   ro   rm   )rv   rw   rx   ry   r   r   r   rE   r   r   r   r   r   r   r   r   r   __classcell__r   s   @r#   r   r   `  s    -h 1;?02gg g
 g 9g .g 
g0!F'4(,1 ,10A,1Qb,1	#,1\;5656 (56 (	56 56 
$56n	P$Lr%   r   c                  *     e Zd ZdZedd fdZ xZS )KqueueObserverzdObserver thread that schedules watching directories and dispatches
    calls to event handlers.
    r   c               0    t         |   t        |       y )Nr   )r   rE   r   )rD   r   r   s     r#   rE   zKqueueObserver.__init__  s    8r%   r   )rv   rw   rx   ry   r   rE   r   r   s   @r#   r   r     s     ,D 9 9r%   r   )r    rr   rn   rr   )r+   r   rn   rs   )Fry   
__future__r   r   r   r   os.pathr(   r@   r   r   typingr   watchdog.eventsr   r   r   r	   r
   r   r   r   r   r   r   r   watchdog.observers.apir   r   r   r   watchdog.utilsr   watchdog.utils.dirsnapshotr   collections.abcr   r   r   r   r   r   	O_EVTONLY	is_darwinO_RDONLY
O_NONBLOCKr   KQ_FILTER_VNODEr   	KQ_EV_ADDKQ_EV_ENABLEKQ_EV_CLEARr   r)   r0   r/   r3   KQ_NOTE_LINKr6   KQ_NOTE_REVOKEr   r$   r,   r1   r4   r7   r9   r[   r   r   r{   r%   r#   <module>r     su  1r #   	          q p # 8)/@ 
 	 '9h&8&8&:bmm@[ ++ ''&*=*==@R@RR 
  	
   32
W2
2
A AHJ` J`ZfL fR	9\ 9r%   