
    Sܐg[                    8   S r  " S S\5      r " S S\5      rSSKr\R
                  S:  a  \" \R                  5      eSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SS	KJrJr  SSKrSSKrSSKrSSKrSSKrSSKr SS
KJr   SSKrSSKr SSK r Sr!Sr"Sq# " S S\5      r$ " S S5      r% " S S\%5      r& " S S\%5      r'S r(\(" 5       r) " S S5      r*S H  r+\*" \+5      \," 5       \+'   M      " S S5      r-0 \-l.        0 \-l/        \-R`                  Rc                  5        H^  u  r2r3\4" \-\2\35        \-R\                  Rk                  \35        \3Rc                  5        H  u  r6r7\7\," 5       \6'   \6\-R^                  \7'   M!     M`     \" S \-Rp                  Rs                  5       5      r:\:\-R\                  S'   S\-R^                  \:'    " S S5      r; " S  S!\;5      r< " S" S#\;5      r= " S$ S%\5      r> " S& S'5      r? " S( S)\?5      r@ " S* S+\?5      rA " S, S-\A5      rB " S. S/\A5      rC " S0 S1\A5      rD " S2 S3\5      rE " S4 S55      rF " S6 S7\R                  \F5      rH " S8 S9\R                  \F5      rJ " S: S;\F5      rK " S< S=\F5      rL " S> S?5      rM " S@ SA5      rN " SB SC\5      rO " SD SE5      rP " SF SG5      rQ\Q" 5       qR " SH SI\Q5      rSSJ rTSK rU\VSL:X  a  \U" 5         gg! \ a     GNff = f! \ a    Sr GNlf = f! \ a    Sr  GNvf = f)MzW
pyinotify

@author: Sebastien Martini
@license: MIT License
@contact: seb@dbzteam.org
c                       \ rS rSrSrSrg)PyinotifyError   z1Indicates exceptions raised by a Pyinotify class. N)__name__
__module____qualname____firstlineno____doc____static_attributes__r       +/usr/lib/python3/dist-packages/pyinotify.pyr   r      s    ;r   r   c                       \ rS rSrSrS rSrg)UnsupportedPythonVersionError$   z(
Raised on unsupported Python versions.
c                 6    [         R                  U SU-  5        g)z>
@param version: Current Python version
@type version: string
z6Python %s is unsupported, requires at least Python 3.0Nr   __init__)selfversions     r   r   &UnsupportedPythonVersionError.__init__(   s#    
 	"7:A!B	Cr   r   Nr   r   r   r	   r
   r   r   r   r   r   r   r   $   s    Cr   r       N)   r   )deque)datetime	timedelta)reducez#seb@dbzteam.org (Sebastien Martini)z0.9.6Fc                       \ rS rSrSrS rSrg)InotifyBindingNotFoundErrorh   z3
Raised when no inotify support couldn't be found.
c                 2    Sn[         R                  X5        g )Nz!Couldn't find any inotify bindingr   r   errs     r   r   $InotifyBindingNotFoundError.__init__l   s    1*r   r   Nr   r   r   r   r   r   h   s    +r   r   c                   F    \ rS rSrSr\S 5       rS rS rS r	S r
S rS	rg
)INotifyWrapperq   zS
Abstract class wrapping access to inotify's functions. This is an
internal class.
c                      [         (       a!  [        5       n U R                  5       (       a  U $ [        (       a"  [	        5       n U R                  5       (       a  U $ gg)z?
Factory method instanciating and returning the right wrapper.
N)ctypes_CtypesLibcINotifyWrapperinitinotify_syscalls_INotifySyscallsWrapper)inotifys    r   createINotifyWrapper.createv   sI     6/1G||~~-/G||~~  r   c                 "    U R                  5       $ )z,
Return None is no errno code is available.
)
_get_errnor   s    r   	get_errnoINotifyWrapper.get_errno   s       r   c                     U R                  5       nUc  gS[        R                  " U5      < S[        R                  U   < S3$ )NzErrno: no errno supportzErrno=z ())r4   osstrerrorerrno	errorcode)r   codes     r   	str_errnoINotifyWrapper.str_errno   s8    ~~<, "$++d"3U__T5JKKr   c                 "    U R                  5       $ N)_inotify_initr3   s    r   inotify_initINotifyWrapper.inotify_init   s    !!##r   c                 T    [        U[        5      (       d   eU R                  XU5      $ r@   )
isinstancestr_inotify_add_watchr   fdpathnamemasks       r   inotify_add_watch INotifyWrapper.inotify_add_watch   s*     (C((((&&rT::r   c                 $    U R                  X5      $ r@   )_inotify_rm_watchr   rI   wds      r   inotify_rm_watchINotifyWrapper.inotify_rm_watch   s    %%b--r   r   N)r   r   r   r	   r
   staticmethodr/   r4   r=   rB   rL   rR   r   r   r   r   r&   r&   q   s5      !L$;.r   r&   c                   8    \ rS rSrS rS rS rS rS rS r	Sr
g	)
r-      c                     S U l         g r@   _last_errnor3   s    r   r    _INotifySyscallsWrapper.__init__   s
    r   c                     [         (       d   eg)NT)r,   r3   s    r   r+   _INotifySyscallsWrapper.init   s    r   c                     U R                   $ r@   rX   r3   s    r   r2   "_INotifySyscallsWrapper._get_errno   s    r   c                      [         R                  " 5       nU$ ! [         a  nUR                  U l         S nAgS nAff = fN)r,   rB   IOErrorr:   rY   )r   rI   r#   s      r   rA   %_INotifySyscallsWrapper._inotify_init   s=    	!..0B 	  	"yyD	s    
>9>c                      [         R                  " XU5      nU$ ! [         a  nUR                  U l         S nAgS nAff = fr`   )r,   rL   rb   r:   rY   )r   rI   rJ   rK   rQ   r#   s         r   rG   *_INotifySyscallsWrapper._inotify_add_watch   sA    	!33B$GB 	  	"yyD	s    
A ;A c                      [         R                  " X5      nU$ ! [         a  nUR                  U l         S nAgS nAff = fr`   )r,   rR   rb   r:   rY   )r   rI   rQ   retr#   s        r   rO   )_INotifySyscallsWrapper._inotify_rm_watch   s?    	"33B;C 
  	"yyD	s    
?:?rX   Nr   r   r   r	   r   r+   r2   rA   rG   rO   r   r   r   r   r-   r-      s       r   r-   c                   8    \ rS rSrS rS rS rS rS rS r	Sr
g	)
r*      c                      S U l         S U l        g r@   )_libc_get_errno_funcr3   s    r   r   "_CtypesLibcINotifyWrapper.__init__   s    
#r   c                    [         (       d   eSn[        R                  R                  S5      (       a  SnS n [         R                  R                  U5      n[         R                  " USS9U l	        [         R                  U l        [        U R                  S5      (       a6  [        U R                  S5      (       a  [        U R                  S5      (       d  g	/ U R                  R                  l        [         R                  U R                  R                  l        [         R                  [         R"                  [         R$                  /U R                  R&                  l        [         R                  U R                  R&                  l        [         R                  [         R                  /U R                  R(                  l        [         R                  U R                  R(                  l        g! [        [        4 a     GNf = f)
Ncfreebsdr.   T)	use_errnorB   rL   rR   F)r)   sysplatform
startswithutilfind_libraryOSErrorrb   CDLLrm   r4   rn   hasattrrB   argtypesc_intrestypec_char_pc_uint32rL   rR   )r   try_libc_name	libc_names      r   r+   _CtypesLibcINotifyWrapper.init   s\   vv<<""9--%M		00?I [[d;
%// 

N33

$788

$677+-

(*0,,

'17v171B

$$-/5||

$$,06fll/K

##,.4ll

##+' ! 		s   G1 1HHc                 H    U R                   (       d   eU R                  5       $ r@   )rn   r3   s    r   r2   $_CtypesLibcINotifyWrapper._get_errno   s     ######%%r   c                 T    U R                   c   eU R                   R                  5       $ r@   )rm   rB   r3   s    r   rA   '_CtypesLibcINotifyWrapper._inotify_init   s%    zz%%%zz&&((r   c                     U R                   c   eUR                  [        R                  " 5       5      n[        R
                  " U5      nU R                   R                  XU5      $ r@   )rm   encodert   getfilesystemencodingr)   create_string_bufferrL   rH   s       r   rG   ,_CtypesLibcINotifyWrapper._inotify_add_watch   sR    zz%%%
 ??3#<#<#>?..x8zz++B$??r   c                 V    U R                   c   eU R                   R                  X5      $ r@   )rm   rR   rP   s      r   rO   +_CtypesLibcINotifyWrapper._inotify_rm_watch   s'    zz%%%zz**222r   )rn   rm   Nri   r   r   r   r*   r*      s!    $>&)@3r   r*   c                      [         R                  " S5      n [         R                  " 5       nUR                  [         R                  " S5      5        U R                  U5        U R                  S5        U $ )zInitialize logger instance.	pyinotifyz0[%(asctime)s %(name)s %(levelname)s] %(message)s   )logging	getLoggerStreamHandlersetFormatter	Formatter
addHandlersetLevel)logconsole_handlers     r   logger_initr      s[    


K
(C++-O  LMONN?#LLJr   c                   B    \ rS rSrSrS rS rS r\" \\5      r	S r
Srg)	ProcINotifyi  a  
Access (read, write) inotify's variables through /proc/sys/. Note that
usually it requires administrator rights to update them.

Examples:
  - Read max_queued_events attribute: myvar = max_queued_events.value
  - Update max_queued_events attribute: max_queued_events.value = 42
c                     SU l         Xl        g )Nz/proc/sys/fs/inotify)_base_attr)r   attrs     r   r   ProcINotify.__init__  s    +

r   c                     [        [        R                  R                  U R                  U R
                  5      S5       n[        UR                  5       5      sSSS5        $ ! , (       d  f       g= f)z
Gets attribute's value.

@return: stored value.
@rtype: int
@raise IOError: if corresponding file in /proc/sys cannot be read.
rN)openr8   pathjoinr   r   intreadline)r   file_objs     r   get_valProcINotify.get_val  sD     "'',,tzz4::6<x((*+ =<<s   A""
A0c                     [        [        R                  R                  U R                  U R
                  5      S5       nUR                  [        U5      S-   5        SSS5        g! , (       d  f       g= f)z
Sets new attribute's value.

@param nval: replaces current value by nval.
@type nval: int
@raise IOError: if corresponding file in /proc/sys cannot be written.
w
N)r   r8   r   r   r   r   writerF   )r   nvalr   s      r   set_valProcINotify.set_val&  sH     "'',,tzz4::6<NN3t9t+, =<<s   A&&
A4c                 @    SU R                   U R                  5       4-  $ )Nz<%s=%d>)r   r   r3   s    r   __repr__ProcINotify.__repr__3  s    DJJ777r   )r   r   N)r   r   r   r	   r
   r   r   r   propertyvaluer   r   r   r   r   r   r     s)    	,	- Wg&E8r   r   )max_queued_eventsmax_user_instancesmax_user_watchesc                   j    \ rS rSrSrSSSSSSS	S
SSSSS.SSSS.SSSSSSS.S.rS r\" \5      rSrg)EventsCodesiD  a	  
Set of codes corresponding to each kind of events.
Some of these flags are used to communicate with inotify, whereas
the others are sent to userspace by inotify notifying some events.

@cvar IN_ACCESS: File was accessed.
@type IN_ACCESS: int
@cvar IN_MODIFY: File was modified.
@type IN_MODIFY: int
@cvar IN_ATTRIB: Metadata changed.
@type IN_ATTRIB: int
@cvar IN_CLOSE_WRITE: Writtable file was closed.
@type IN_CLOSE_WRITE: int
@cvar IN_CLOSE_NOWRITE: Unwrittable file closed.
@type IN_CLOSE_NOWRITE: int
@cvar IN_OPEN: File was opened.
@type IN_OPEN: int
@cvar IN_MOVED_FROM: File was moved from X.
@type IN_MOVED_FROM: int
@cvar IN_MOVED_TO: File was moved to Y.
@type IN_MOVED_TO: int
@cvar IN_CREATE: Subfile was created.
@type IN_CREATE: int
@cvar IN_DELETE: Subfile was deleted.
@type IN_DELETE: int
@cvar IN_DELETE_SELF: Self (watched item itself) was deleted.
@type IN_DELETE_SELF: int
@cvar IN_MOVE_SELF: Self (watched item itself) was moved.
@type IN_MOVE_SELF: int
@cvar IN_UNMOUNT: Backing fs was unmounted.
@type IN_UNMOUNT: int
@cvar IN_Q_OVERFLOW: Event queued overflowed.
@type IN_Q_OVERFLOW: int
@cvar IN_IGNORED: File was ignored.
@type IN_IGNORED: int
@cvar IN_ONLYDIR: only watch the path if it is a directory (new
                  in kernel 2.6.15).
@type IN_ONLYDIR: int
@cvar IN_DONT_FOLLOW: don't follow a symlink (new in kernel 2.6.15).
                      IN_ONLYDIR we can make sure that we don't watch
                      the target of symlinks.
@type IN_DONT_FOLLOW: int
@cvar IN_EXCL_UNLINK: Events are not generated for children after they
                      have been unlinked from the watched directory.
                      (new in kernel 2.6.36).
@type IN_EXCL_UNLINK: int
@cvar IN_MASK_ADD: add to the mask of an already existing watch (new
                   in kernel 2.6.14).
@type IN_MASK_ADD: int
@cvar IN_ISDIR: Event occurred against dir.
@type IN_ISDIR: int
@cvar IN_ONESHOT: Only send event once.
@type IN_ONESHOT: int
@cvar ALL_EVENTS: Alias for considering all of the events.
@type ALL_EVENTS: int
                   @         i   i   i   )	IN_ACCESS	IN_MODIFY	IN_ATTRIBIN_CLOSE_WRITEIN_CLOSE_NOWRITEIN_OPENIN_MOVED_FROMIN_MOVED_TO	IN_CREATE	IN_DELETEIN_DELETE_SELFIN_MOVE_SELFi    i @  i   )
IN_UNMOUNTIN_Q_OVERFLOW
IN_IGNOREDi   i   i   i    i   @l        )
IN_ONLYDIRIN_DONT_FOLLOWIN_EXCL_UNLINKIN_MASK_ADDIN_ISDIR
IN_ONESHOT)OP_FLAGSEVENT_FLAGSSPECIAL_FLAGSc                 h    U nSnU [         -  (       a  U [         -
  nSnU[        R                  U   -  $ )z
Returns the event name associated to mask. IN_ISDIR is appended to
the result when appropriate. Note: only one event is returned, because
only one event can be raised at a given time.

@param mask: mask.
@type mask: int
@return: event name.
@rtype: str
z%sz%s|IN_ISDIR)r   r   
ALL_VALUES)rK   msnames      r   masknameEventsCodes.maskname  s9     (?B Dk,,R000r   r   N)	r   r   r   r	   r
   FLAG_COLLECTIONSr   rT   r   r   r   r   r   r   D  sv    7z ('''''''''''%
  (''(
 ('''''	*
)@1$ H%Hr   r   c                 
    X-  $ r@   r   )xys     r   <lambda>r     s    r   
ALL_EVENTSc                   *    \ rS rSrSrS rS rS rSrg)_Eventi  zk
Event structure, represent events raised by the system. This
is the base class and should be subclassed.

c                 J    UR                  5        H  n[        U /UQ76   M     g)zk
Attach attributes (contained in dict_) to self.

@param dict_: Set of attributes.
@type dict_: dictionary
N)itemssetattr)r   dict_tpls      r   r   _Event.__init__  s!     ;;=CD3 !r   c                 L   Sn[        U R                  R                  5       S S9 H  u  p#UR                  S5      (       a  M  US:X  a  [	        [        X5      5      nO[        U[        5      (       a	  U(       d  SnUS[        R                  U5      < [        R                  S5      < [        R                  U5      < 3-  nM     [        R                  S	5      < [        R                  U R                  R                  5      < U< S[        R                  S
5      < 3nU$ )z;
@return: Generic event string representation.
@rtype: str
 c                     U S   $ Nr   r   r   s    r   r   !_Event.__repr__.<locals>.<lambda>  s    qtr   key_rK   z'' =<>)sorted__dict__r   rv   hexgetattrrE   rF   output_format
field_namepunctuationfield_value
class_name	__class__r   )r   sr   r   s       r   r   _Event.__repr__  s    
 !$--"5"5"7^LKDs##v~GD/0E3''m66t<+77<+77>@ @A M )44S9(33DNN4K4KL(44S9; r   c                     [        U 5      $ r@   )reprr3   s    r   __str___Event.__str__  s    Dzr   r   N)	r   r   r   r	   r
   r   r   r  r   r   r   r   r   r     s    
 .r   r   c                   $    \ rS rSrSrS rS rSrg)	_RawEventi  za
Raw event, it contains only the informations provided by the system.
It doesn't infer anything.
c                     SU l         UUUUR                  S5      S.n[        R                  X5        [        R                  [        U 5      5        g)a  
@param wd: Watch Descriptor.
@type wd: int
@param mask: Bitmask of events.
@type mask: int
@param cookie: Cookie.
@type cookie: int
@param name: Basename of the file or directory against which the
             event was raised in case where the watched directory
             is the parent directory. None if the event was raised
             on the watched item itself.
@type name: string or None
N )rQ   rK   cookier   )_strrstripr   r   r   debugrF   )r   rQ   rK   r  r   ds         r   r   _RawEvent.__init__  sE      	[[&( 	 		#d)r   c                 h    U R                   c  [        R                  U 5      U l         U R                   $ r@   )r  r   r  r3   s    r   r  _RawEvent.__str__  s&    99t,DIyyr   )r  N)r   r   r   r	   r
   r   r  r   r   r   r   r  r    s    2r   r  c                       \ rS rSrSrS rSrg)Eventi  a  
This class contains all the useful informations about the observed
event. However, the presence of each field is not guaranteed and
depends on the type of event. In effect, some fields are irrelevant
for some kind of event (for example 'cookie' is meaningless for
IN_CREATE whereas it is mandatory for IN_MOVE_TO).

The possible fields are:
  - wd (int): Watch Descriptor.
  - mask (int): Mask.
  - maskname (str): Readable event name.
  - path (str): path of the file or directory being watched.
  - name (str): Basename of the file or directory against which the
          event was raised in case where the watched directory
          is the parent directory. None if the event was raised
          on the watched item itself. This field is always provided
          even if the string is ''.
  - pathname (str): Concatenation of 'path' and 'name'.
  - src_pathname (str): Only present for IN_MOVED_TO events and only in
          the case where IN_MOVED_FROM events are watched too. Holds the
          source pathname from where pathname was moved from.
  - cookie (int): Cookie.
  - dir (bool): True if the event was raised against a directory.

c                 4   [         R                  X5        [        R                  U R                  5      U l        [
        (       a  U R                  U l         U R                  (       aW  [        R                  R                  [        R                  R                  U R                  U R                  5      5      U l        g[        R                  R                  U R                  5      U l        g! [         a  n[        R                  U5         SnAgSnAff = f)z8
Concretely, this is the raw event plus inferred infos.
N)r   r   r   r   rK   COMPATIBILITY_MODE
event_namer   r8   r   abspathr   rJ   AttributeErrorr   r  )r   rawr#   s      r   r   Event.__init__7  s     	"#,,TYY7"mmDO		yy "TYY=AYY1H !I !#		 : 	 IIcNN	s   A'C. ?.C. .
D8DD)r   r   rJ   Nr   r   r   r   r  r    s    2r   r  c                       \ rS rSrSrS rSrg)ProcessEventErroriK  z<
ProcessEventError Exception. Raised on ProcessEvent error.
c                 .    [         R                  X5        g)z<
@param err: Exception error description.
@type err: string
Nr   r"   s     r   r   ProcessEventError.__init__O      
 	*r   r   Nr   r   r   r   r&  r&  K  s    +r   r&  c                   $    \ rS rSrSrS rS rSrg)_ProcessEventiW  z"
Abstract processing event class.
c                 T   UR                   UR                   [        -  -
  n[        R                  R	                  U5      nUc  [        SU-  5      e[        U SU-   S5      nUb  U" U5      $ [        U SUR                  S5      S   -   S5      nUb  U" U5      $ U R                  U5      $ )a  
To behave like a functor the object must be callable.
This method is a dispatch method. Its lookup order is:
  1. process_MASKNAME method
  2. process_FAMILY_NAME method
  3. otherwise calls process_default

@param event: Event to be processed.
@type event: Event object
@return: By convention when used from the ProcessEvent class:
         - Returning False or None (default value) means keep on
         executing next chained functors (see chain.py example).
         - Returning True instead means do not execute next
           processing functions.
@rtype: bool
@raise ProcessEventError: Event object undispatchable,
                          unknown event.
NzUnknown mask 0x%08xprocess_process_IN_r   r   )	rK   r   r   r   getr&  r  splitprocess_default)r   eventstripped_maskr   meths        r   __call___ProcessEvent.__call__[  s    & 

ejj8&;<))--m<#$9M$IJJ tZ(2D9;t]X^^C-@-CCTJ;##E**r   c                 4    SU R                   R                  -  $ )Nz<%s>)r	  r   r3   s    r   r   _ProcessEvent.__repr__~  s    ////r   r   N)r   r   r   r	   r
   r5  r   r   r   r   r   r+  r+  W  s    !+F0r   r+  c                   R    \ rS rSrSrS rS rS rS rS r	S r
S	 rS
 rSS jrSrg)_SysProcessEventi  a  
There is three kind of processing according to each event:

  1. special handling (deletion from internal container, bug, ...).
  2. default treatment: which is applied to the majority of events.
  3. IN_ISDIR is never sent alone, he is piggybacked with a standard
     event, he is not processed as the others events, instead, its
     value is captured and appropriately aggregated to dst event.
c                 8    Xl         X l        0 U l        0 U l        g)zy

@param wm: Watch Manager.
@type wm: WatchManager instance
@param notifier: Notifier.
@type notifier: Notifier instance
N)_watch_manager	_notifier
_mv_cookie_mv)r   wmnotifiers      r   r   _SysProcessEvent.__init__  s     !!r   c                    [         R                  " 5       nU R                  U R                  4 HW  n[	        UR                  5       5       H7  nXU   S   -
  [        SS9:  d  M  [        R                  SX#   S   5        X#	 M9     MY     g)zP
Cleanup (delete) old (>1mn) records contained in self._mv_cookie
and self._mv.
r   )minuteszCleanup: deleting entry %sr   N)	r   nowr>  r?  listkeysr   r   r  )r   	date_cur_seqks       r   cleanup_SysProcessEvent.cleanup  sm    
 LLN	OOTXX.C#((*%Aq	)Yq-AAII:CF1IF & /r   c           	         UR                   [        -  (       Ga  U R                  R                  UR                  5      n[
        R                  R                  UR                  UR                  5      nUR                  (       Ga  UR                  U5      (       Gdj  U R                  R                  nU" X2R                   UR                  SUR                  UR                  S9nUR                  U5      nUGb  US:  Ga  [
        R                  R                  U5      (       a   [
        R                  " U5       H  n[
        R                  R                  X75      nU R                  R!                  U5      b  M@  [
        R                  R#                  U5      (       a  [$        n	O4[
        R                  R                  U5      (       a  [$        [        -  n	OM  ['        XiSU5      n
U R(                  R+                  U
5        M     U R5                  U5      $ ! [,         a-  nSn[.        R1                  U[3        U5      -  5         SnANCSnAff = f)z
If the event affects a directory and the auto_add flag of the
targetted watch is set to True, a new watch is added on this
new directory, with the same attribute values than those of
this watch.
Fproc_funrecauto_addexclude_filterNr   z(process_IN_CREATE, invalid directory: %s)rK   r   r<  	get_watchrQ   r8   r   r   r   rQ  rR  	add_watchrO  r/  isdirlistdirget_wdisfiler   r  r=  append_eventry   r   r  rF   r1  )r   	raw_eventwatch_created_diraddwaddw_retcreated_dir_wdr   innerflagsraweventr#   msgs                r   process_IN_CREATE"_SysProcessEvent.process_IN_CREATE  s    >>H$$((229<<@F'',,v{{INNCKv'<'<['I'I**44  [[)/$)FOO/5/D/DF "*k!:#/nq6HGGMM+..2$&JJ{$;D$&GGLL$CE#2299%@L (  "ww~~e44(1!#u!5!5(1H(< !)'04'PH NN77A %<& ##I.. # 2H		#C.112s   %C!H 
I!#I		Ic                    U R                   R                  UR                  5      nUR                  n[        R                  R                  [        R                  R                  X1R                  5      5      nU[        R                  " 5       4U R                  UR                  '   U R                  USUR                  05      $ )z<
Map the cookie with the source path (+ date for cleaning).
r  )r<  rS  rQ   r   r8   normpathr   r   r   rE  r>  r  r1  )r   rZ  r[  path_src_paths        r   process_IN_MOVED_FROM&_SysProcessEvent.process_IN_MOVED_FROM  s     $$..y||<77##BGGLL$GH-5x||~,F	(()##I):J:J/KLLr   c           	         U R                   R                  UR                  5      nUR                  n[        R                  R                  [        R                  R                  X1R                  5      5      nU R                  R                  UR                  5      nSUR                  0nUb0  U[        R                  " 5       4U R                  US   '   US   US'   OzUR                  [        -  (       ab  UR                   (       aQ  UR#                  U5      (       d;  U R                   R%                  XBR                  UR&                  SSUR"                  S9  U R)                  X5      $ )zF
Map the source path with the destination path (+ date for
cleaning).
r  r   src_pathnameTrN  )r<  rS  rQ   r   r8   rg  r   r   r>  r/  r  r   rE  r?  rK   r   rQ  rR  rT  rO  r1  )r   rZ  r[  rh  dst_pathmv_	to_appends          r   process_IN_MOVED_TO$_SysProcessEvent.process_IN_MOVED_TO  s   
 $$..y||<77##BGGLL$GHoo!!)"2"23y//0	? ((,,.9DHHSV ),AIn%nnx'FOO''11
 ))(KK39??.2T9?9N9N * P ##I99r   c                    U R                   R                  UR                  5      nUR                  nU R                  R                  U5      nU(       a  US   nXRl        U[        R                  R                  -  n[        U5      nU R                   R                  R                  5        HV  nUR                  R                  U5      (       d  M%  [        R                  R                  XWR                  US 5      Ul        MX     O[        R                  SUR                  U[        R                  R                  [        R                  R                  UR                  [        R                  R                   5      5      5        UR                  R#                  S5      (       d  U=R                  S-  sl        U R%                  U5      $ )a  
STATUS: the following bug has been fixed in recent kernels (FIXME:
which version ?). Now it raises IN_DELETE_SELF instead.

Old kernels were bugged, this event raised when the watched item
were moved, so we had to update its path, but under some circumstances
it was impossible: if its parent directory and its destination
directory wasn't watched. The kernel (see include/linux/fsnotify.h)
doesn't bring us enough informations like the destination path of
moved items.
r   NzThe pathname '%s' of this watch %s has probably changed and couldn't be updated, so it cannot be trusted anymore. To fix this error move directories/files only between watched parents directories, in this case e.g. put a watch on '%s'.z-unknown-path)r<  rS  rQ   r   r?  r/  r8   seplenwatchesvaluesrv   r   r   errorrg  pardirendswithr1  )r   rZ  r[  ri  ro  	dest_pathsrc_path_lenr   s           r   process_IN_MOVE_SELF%_SysProcessEvent.process_IN_MOVE_SELF  sE    $$..y||<;;hhll8$AI#K #Hx=L ((0077966$$X..WW\\)VVLM5JKAF :
 II -
 kk6gg&&rww||FKK46GGNN(D EF ;;''88.##I..r   c                 0    [        SUR                  05      $ )zc
Only signal an overflow, most of the common flags are irrelevant
for this event (path, wd, name).
rK   )r  rK   )r   rZ  s     r   process_IN_Q_OVERFLOW&_SysProcessEvent.process_IN_Q_OVERFLOW'  s    
 finn-..r   c                 r    U R                  U5      nU R                  R                  UR                  5        U$ )z
The watch descriptor raised by this event is now ignored (forever),
it can be safely deleted from the watch manager dictionary.
After this event we can be sure that neither the event queue nor
the system will raise an event associated to this wd again.
)r1  r<  	del_watchrQ   )r   rZ  event_s      r   process_IN_IGNORED#_SysProcessEvent.process_IN_IGNORED.  s1     %%i0%%ill3r   Nc                    U R                   R                  UR                  5      nUR                  [        [
        -  -  (       a  UR                  nO[        UR                  [        -  5      nUR                  UR                  UR                  UR                  US.n[        (       a  XES'   Ub  UR                  U5        [        U5      $ )z
Commons handling for the followings events:

IN_ACCESS, IN_MODIFY, IN_ATTRIB, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE,
IN_OPEN, IN_DELETE, IN_DELETE_SELF, IN_UNMOUNT.
)rQ   rK   r   r   diris_dir)r<  rS  rQ   rK   r   r   r  boolr   r   r   r  updater  )r   rZ  rp  r[  dir_r   s         r   r1   _SysProcessEvent.process_default9  s     $$..y||<>>^l:;::D	12D ||""	
 "(O LL#U|r   )r?  r>  r=  r<  r@   )r   r   r   r	   r
   r   rK  rd  rj  rq  r}  r  r  r1  r   r   r   r   r:  r:    s7    
./`M:<(/T/	r   r:  c                   D    \ rS rSrSrSrSS jrS rS rS r	S r
S	 rS
rg)ProcessEventiR  a  
Process events objects, can be specialized via subclassing, thus its
behavior can be overriden:

Note: you should not override __init__ in your subclass instead define
a my_init() method, this method will be called automatically from the
constructor of this class with its optionals parameters.

  1. Provide specialized individual methods, e.g. process_IN_DELETE for
     processing a precise type of event (e.g. IN_DELETE in this case).
  2. Or/and provide methods for processing events by 'family', e.g.
     process_IN_CLOSE method will process both IN_CLOSE_WRITE and
     IN_CLOSE_NOWRITE events (if process_IN_CLOSE_WRITE and
     process_IN_CLOSE_NOWRITE aren't defined though).
  3. Or/and override process_default for catching and processing all
     the remaining types of events.
Nc                 4    Xl         U R                  " S0 UD6  g)ae  
Enable chaining of ProcessEvent instances.

@param pevent: Optional callable object, will be called on event
               processing (before self).
@type pevent: callable
@param kargs: This constructor is implemented as a template method
              delegating its optionals keyworded arguments to the
              method my_init().
@type kargs: dict
Nr   )peventmy_init)r   r  kargss      r   r   ProcessEvent.__init__f  s     ur   c                     g)a  
This method is called from ProcessEvent.__init__(). This method is
empty here and must be redefined to be useful. In effect, if you
need to specifically initialize your subclass' instance then you
just have to override this method in your subclass. Then all the
keyworded arguments passed to ProcessEvent.__init__() will be
transmitted as parameters to this method. Beware you MUST pass
keyword arguments though.

@param kargs: optional delegated arguments from __init__().
@type kargs: dict
Nr   )r   r  s     r   r  ProcessEvent.my_initu  s     	r   c                 |    SnU R                   b  U R                  U5      nU(       d  [        R                  X5      $ g NF)r  r+  r5  )r   r2  stop_chainings      r   r5  ProcessEvent.__call__  s:    ;;" !KK.M ))$66 r   c                     U R                   $ r@   r  r3   s    r   nested_peventProcessEvent.nested_pevent  s    {{r   c                 .    [         R                  S5        g)a>  
By default this method only reports warning messages, you can overredide
it by subclassing ProcessEvent and implement your own
process_IN_Q_OVERFLOW method. The actions you can take on receiving this
event is either to update the variable max_queued_events in order to
handle more simultaneous events or to modify your code in order to
accomplish a better filtering diminishing the number of raised events.
Because this method is defined, IN_Q_OVERFLOW will never get
transmitted as arguments to process_default calls.

@param event: IN_Q_OVERFLOW event.
@type event: dict
zEvent queue overflowed.N)r   warningr   r2  s     r   r  "ProcessEvent.process_IN_Q_OVERFLOW  s     	-.r   c                     g)a5  
Default processing event method. By default does nothing. Subclass
ProcessEvent and redefine this method in order to modify its behavior.

@param event: Event to be processed. Can be of any type of events but
              IN_Q_OVERFLOW events (see method process_IN_Q_OVERFLOW).
@type event: Event instance
Nr   r  s     r   r1  ProcessEvent.process_default  s     	r   r  r@   )r   r   r   r	   r
   r  r   r  r5  r  r  r1  r   r   r   r   r  r  R  s,    " F
7/ 	r   r  c                   (    \ rS rSrSrSS jrS rSrg)PrintAllEventsi  z
Dummy class used to print events strings representations. For instance this
class is used from command line to print all received events to stdout.
Nc                 6    Uc  [         R                  nXl        g)zf
@param out: Where events will be written.
@type out: Object providing a valid file object interface.
N)rt   stdout_out)r   outs     r   r  PrintAllEvents.my_init  s    
 ;**C	r   c                     U R                   R                  [        U5      5        U R                   R                  S5        U R                   R                  5         g)z
Writes event string representation to file object provided to
my_init().

@param event: Event to be processed. Can be of any type of events but
              IN_Q_OVERFLOW events (see method process_IN_Q_OVERFLOW).
@type event: Event instance
r   N)r  r   rF   flushr  s     r   r1  PrintAllEvents.process_default  s6     			E
#				r   )r  r@   r   r   r   r	   r
   r  r1  r   r   r   r   r  r    s    r   r  c                   $    \ rS rSrSrS rS rSrg)ChainIfTruei  zW
Makes conditional chaining depending on the result of the nested
processing instance.
c                     Xl         gz:
Method automatically called from base class constructor.
N_func)r   funcs     r   r  ChainIfTrue.my_init  s	     
r   c                 .    U R                  U5      (       + $ r@   r  r  s     r   r1  ChainIfTrue.process_default  s    ::e$$$r   r  Nr  r   r   r   r  r    s    %r   r  c                   @    \ rS rSrSrS rS rS rS rS r	SS jr
S	rg
)Statsi  z@
Compute and display trivial statistics about processed events.
c                 z    [         R                   " 5       U l        0 U l        [        R                  " 5       U l        gr  )time_start_time_stats	threadingLock_stats_lockr3   s    r   r  Stats.my_init  s(      99;$>>+r   c                 P   U R                   R                  5          UR                  R                  S5      nU H1  nU R                  R                  US5      nUS-   U R                  U'   M3     U R                   R                  5         g! U R                   R                  5         f = f)z
Processes |event|.
|r   r   N)r  acquirer   r0  r  r/  release)r   r2  eventsr   counts        r   r1  Stats.process_default  s     	  "	'^^))#.F$

A6*/!)J' % $$&D$$&s   AB	 	B%c                     U R                   R                  5          U R                  R                  5       U R                   R	                  5         $ ! U R                   R	                  5         f = fr@   )r  r  r  copyr  r3   s    r   _stats_copyStats._stats_copy  sN      "	';;##%$$&D$$&s   A A,c           	         U R                  5       n[        [        R                  " 5       U R                  -
  5      nSnUS:  a  [	        U5      S-   nOUSUs=::  a  S:  a  O  OSUS-  US-  4-  nO7SUs=::  a  S:  a  O  OSUS-  US-  S-  4-  nOUS:  a  SUS-  US-  S-  4-  nX1S	'   / n[        UR                  5       S
 S9 HD  u  pVUR                  S[        R                  U5      < S[        R                  U5      < 35        MF     S[        R                  U R                  R                  5      < SR                  U5      < S3nU$ )Nr   <   seci  z	%dmn%dseciQ z%dh%dmnz%dd%dhElapsedTimec                     U S   $ r   r   r   s    r   r    Stats.__repr__.<locals>.<lambda>
  s    QqTr   r   r   r   r   z >)r  r   r  r  rF   r   r   appendr  r  r  r  r	  r   r   )r   statselapsedelapsed_strlevr   r
  s           r   r   Stats.__repr__  s<     "diikD$4$445R<g,.K7!T!%2w|(DDKW$u$#w~$"7L&MMK"go%47O%PPK*m>BIBHH!9!9"!=!.!:!:5!AC D C '11$..2I2IJ%r   c                 h   [         R                  [         R                  -  [         R                  -  [         R                  -  n[         R
                  " XS5      n[         R                  " U[        U R                  5       [        R                  " 5       5      5        [         R                  " U5        g)z
Dumps statistics.

@param filename: filename where stats will be dumped, filename is
                 created and must not exist prior to this call.
@type filename: string
  N)r8   O_WRONLYO_CREAT
O_NOFOLLOWO_EXCLr   r   bytesr  localegetpreferredencodingclose)r   filenamera  rI   s       r   dump
Stats.dump  sg     BJJ&r}}4RYY>WWXf-
U4<<>6+F+F+HIJ
r   c           
      4  ^^ U R                  5       nU(       d  g[        UR                  5       5      nX-  mS[        [        R                  SU-  5      5      S-   -  mUU4S jnSR                  [        U[        UR                  5       S S95      5      nU$ )	Nr   z%%-26s%%-%ds%%s@r   c           	         > T[         R                  U S   5      [         R                  S[        U S   T-  5      -  5      [         R	                  SU S   -  S5      4-  $ )Nr   r  r   z%dyellow)r  r  r  r   simple)r   fmtunitys    r   r  Stats.__str__.<locals>.func'  sa    -221Q48'33C#adUl:K4KL'..tad{HEG G Gr   r   c                     U S   $ r   r   r   s    r   r   Stats.__str__.<locals>.<lambda>+  s    AaDr   r   )
r  maxrw  ru  r  r  r   mapr   r   )r   scaler  mr  r
  r  r  s         @@r   r  Stats.__str__  s      "	3}'@'@u'M#N%&$' (	G IIc$u{{}. IJKr   )r  r  r  N)-   )r   r   r   r	   r
   r  r1  r  r   r  r  r   r   r   r   r  r    s%    ,''.r   r  c                       \ rS rSrSrS rSrg)NotifierErrori/  z0
Notifier Exception. Raised on Notifier error.

c                 .    [         R                  X5        g)z?
@param err: Exception string's description.
@type err: string
Nr   r"   s     r   r   NotifierError.__init__4  r)  r   r   Nr   r   r   r   r  r  /  s    +r   r  c                       \ rS rSrSr  SS jrS rS rSS jrSS jr	S	 r
S
 rS\R                  \R                  \R                  4S jrS rSS jrS rSrg)Notifieri<  z&
Read notifications, process events.

Nc                    Xl         U R                   R                  5       U l        [        R                  " 5       U l        U R
                  R                  U R                  [        R                  5        SU l        [        5       U l
        [        U R                   U 5      U l        X l        Uc  [        5       U l        X0l        X@l        XPl        SU l        ['        5       U l        g)as  
Initialization. read_freq, threshold and timeout parameters are used
when looping.

@param watch_manager: Watch Manager.
@type watch_manager: WatchManager instance
@param default_proc_fun: Default processing method. If None, a new
                         instance of PrintAllEvents will be assigned.
@type default_proc_fun: instance of ProcessEvent
@param read_freq: if read_freq == 0, events are read asap,
                  if read_freq is > 0, this thread sleeps
                  max(0, read_freq - (timeout / 1000)) seconds. But if
                  timeout is None it may be different because
                  poll is blocking waiting for something to read.
@type read_freq: int
@param threshold: File descriptor will be read only if the accumulated
                  size to read becomes >= threshold. If != 0, you likely
                  want to use it in combination with an appropriate
                  value for read_freq because without that you would
                  keep looping without really reading anything and that
                  until the amount of events to read is >= threshold.
                  At least with read_freq set you might sleep.
@type threshold: int
@param timeout: see read_freq above. If provided, it must be set in
                milliseconds. See
                https://docs.python.org/3/library/select.html#select.poll.poll
@type timeout: int
)ra   ra   NF)r<  get_fd_fdselectpoll_pollobjregisterPOLLIN_piper   _eventqr:  _sys_proc_fun_default_proc_funr  
_read_freq
_threshold_timeout	_coalesceset	_eventsetr   watch_managerdefault_proc_fun	read_freq	thresholdtimeouts         r   r   Notifier.__init__A  s    > ,&&--/txx7
w-d.A.A4H!1#%3%5D"##r   c                 :    U R                   R                  U5        g)zb
Append a raw event to the event queue.

@param event: An event.
@type event: _RawEvent instance.
N)r  r  r  s     r   rY  Notifier.append_eventy  s     	E"r   c                     U R                   $ r@   )r
  r3   s    r   rO  Notifier.proc_fun  s    %%%r   c                 T    Xl         U(       d  U R                  R                  5         gg)a  
Coalescing events. Events are usually processed by batchs, their size
depend on various factors. Thus, before processing them, events received
from inotify are aggregated in a fifo queue. If this coalescing
option is enabled events are filtered based on their unicity, only
unique events are enqueued, doublons are discarded. An event is unique
when the combination of its fields (wd, mask, cookie, name) is unique
among events of a same batch. After a batch of events is processed any
events is accepted again. By default this option is disabled, you have
to explictly call this function to turn it on.

@param coalesce: Optional new coalescing value. True by default.
@type coalesce: Bool
N)r  r  clear)r   coalesces     r   coalesce_eventsNotifier.coalesce_events  s!     "NN  " r   c                 X     Uc  U R                   nU R                  R                  U5      n U(       a  U R                  S   US   S   :X  a  gUS   S   [        R                  -  $ ! [        R                   a-  nUR
                  S   [        R                  :X  a   SnAM  e SnAff = f)a/  
Check for new events available to read, blocks up to timeout
milliseconds.

@param timeout: If specified it overrides the corresponding instance
                attribute _timeout. timeout must be sepcified in
                milliseconds.
@type timeout: int

@return: New events to read.
@rtype: bool
Nr   Fr   )
r  r  r  r  rx  argsr:   EINTRr  r  )r   r  rg   r#   s       r   check_eventsNotifier.check_events  s     ?"mmGmm((1 tzz!}Aq	11vay6==(( << 88A;%++-	s   *A( (B)<!B$#B$$B)c                    [         R                   " SS/5      n[        R                  " U R                  [        R
                  US5      S:X  a  gUS   nX R                  :  a-  [        R                  SU R                  UU R                  5        g [        R                  " U R                  U5      n[        R                  SU5        SnXR:  a  Sn[        R                  " S	X5XV-    5      u  pxp[        R                  " S
U
-  X5U-   XV-   U
-    5      u  nUR                  5       n[!        XxX5      nU R"                  (       aQ  [%        U5      nXR&                  ;  a6  U R&                  R)                  U5        U R*                  R-                  U5        OU R*                  R-                  U5        XVU
-   -  nXR:  a  M  gg! [         a  n[        U5      eSnAff = f)z>
Read events from device, build _RawEvents, and enqueue them.
ir   r   ra   NzF(fd: %d) %d bytes available to read but threshold is fixed to %d byteszEvent queue size: %dr   iIIIz%ds)arrayfcntlioctlr  termiosFIONREADr  r   r  r8   read	Exceptionr  structunpackdecoder  r  rF   r  addr  r  )r   buf_
queue_sizer   rc  rsums_sizerQ   rK   r  	fname_lenbnameunamerb  raweventstrs                  r   read_eventsNotifier.read_events  s    {{3$;;txx!1!14;rA!W
'II *+/88Zoo' 	%*-A 			(*5F*0--89t{8K+M'Bf ]]59#4#$F]4=93L#MOFE LLNE 69H~~!(mnn4NN&&{3LL''1##H-Y&&D' 	  	%$$	%s   !F> >
GGGc                    U R                   (       Ga1  U R                   R                  5       nU R                  R                  (       a#  [        R                  S[        U5      -  5        Mj  U R                  R                  UR                  5      nUcQ  UR                  [        -  (       d9  UR                  [        -  (       d  [        R                  S[        U5      5        M  U R                  U5      nU(       a#  UR                  (       a  UR                  U5        OU R                  U5        U R                   (       a  GM1  U R                  R!                  5         U R"                  (       a  U R$                  R'                  5         gg)z
Routine for processing events from queue by calling their
associated proccessing method (an instance of ProcessEvent).
It also does internal processings, to keep the system updated.
zEvent ignored: %sNz0Unable to retrieve Watch object associated to %s)r  popleftr<  ignore_eventsr   r  r  rS  rQ   rK   r   r   r  r	  rO  r
  rK  r  r  r  )r   rZ  r[  revents       r   process_eventsNotifier.process_events  s    lll,,.I""00		-Y?@((229<<@F-)G!3 KK R $Y1''	2F&//'&&v.% lll& 	""$>>NN  " r   c           	      (  ^^^^ Tc]  Sn[         R                  R                  [        R                  S   5      =(       d    Sn[         R                  R                  XVS-   5      mTS:w  a4  [         R                  R                  T5      (       a  ST-  n[        U5      eUUU4S jnU" 5         TS:w  a  [         R                  [         R                  -  [         R                  -  [         R                  -  n	[         R                  " TU	S	5      n
[         R                  " U
[        [        [         R                   " 5       5      S
-   ["        R$                  " 5       5      5        [         R&                  " U
5        [(        R*                  " U4S j5        gg)z
pid_file: file where the pid will be written. If pid_file=None the pid
          is written to /var/run/<sys.argv[0]|pyinotify>.pid, if
          pid_file=False no pid_file is written.
stdin, stdout, stderr: files associated to common streams.
Nz	/var/run/r   r   z.pidFz-Cannot daemonize: pid file %s already exists.c                     > [         R                  " 5       n U S:X  at  [         R                  " 5         [         R                  " 5       n U S:X  a-  [         R                  " S5        [         R                  " S5        O-[         R
                  " S5        O[         R
                  " S5        [         R                  " T[         R                  5      n[         R                  " US5        [         R                  " T[         R                  [         R                  -  S5      n[         R                  " US5        [         R                  " T[         R                  [         R                  -  S5      n[         R                  " US5        g )Nr   /   r  r   r   )r8   forksetsidchdirumask_exitr   O_RDONLYdup2r  r  )pidfd_inpfd_outfd_errstderrstdinr  s       r   fork_daemon)Notifier.__daemonize.<locals>.fork_daemon  s     '')Cq		ggi1HHHSMHHUO HHQK WWUBKK0FGGFAWWVR[[%;VDFGGFAWWVR[[%;VDFGGFAr   r  r   c                  0   > [         R                  " T 5      $ r@   )r8   unlink)pid_files   r   r   &Notifier.__daemonize.<locals>.<lambda>6  s    RYYx%8r   )r8   r   basenamert   argvr   lexistsr  r  r  r  r  r   r   r  rF   getpidr  r  r  atexitr  )r   rY  rT  r  rS  dirnamer[  r#   rU  ra  fd_pids    ````      r   __daemonizeNotifier.__daemonize   s    !Gww''4CHww||G->?Hu!:!:AHLC$$	6 	 uKK

*2==8BEWWXuf5FHHVeC		$4t$;$*$?$?$AC DHHVOO89 r   c                     U R                   S:  aZ  [        R                  " 5       nU R                   X!-
  -
  nUS:  a-  [        R                  SU5        [        R                  " U5        g g g )Nr   zNow sleeping %d seconds)r  r  r   r  sleep)r   ref_timecur_timesleep_amounts       r   _sleepNotifier._sleep8  sW    ??Qyy{H??h.ABLa		3\B

<(   r   c                 ~   U(       a  U R                   " S0 UD6    U R                  5         Ub  U" U 5      SL a  OM[        R                  " 5       nU R                  5       (       a!  U R	                  U5        U R                  5         Mm  U R                  5         g! [         a    [        R                  S5         M3  f = f)a  
Events are read only one time every min(read_freq, timeout)
seconds at best and only if the size to read is >= threshold.
After this method returns it must not be called again for the same
instance.

@param callback: Functor called after each event processing iteration.
                 Expects to receive the notifier object (self) as first
                 parameter. If this function returns True the loop is
                 immediately terminated otherwise the loop method keeps
                 looping.
@type callback: callable object or function
@param daemonize: This thread is daemonized if set to True.
@type daemonize: boolean
@param args: Optional and relevant only if daemonize is True. Remaining
             keyworded arguments are directly passed to daemonize see
             __daemonize() method. If pid_file=None or is set to a
             pathname the caller must ensure the file does not exist
             before this method is called otherwise an exception
             pyinotify.NotifierError will be raised. If pid_file=False
             it is still daemonized but the pid is not written in any
             file.
@type args: various
NTzPyinotify stops monitoring.r   )
_Notifier__daemonizerB  r  r$  ri  r<  KeyboardInterruptr   r  stop)r   callback	daemonizer"  rf  s        r   loopNotifier.loopA  s    2 $t$ ##%(x~/E99;$$&&KK)$$&  			 % 		78s   B AB B<;B<c                     U R                   bL  U R                  R                  U R                   5        [        R                  " U R                   5        SU l         SU l        g)z
Close inotify's instance (close its file descriptor).
It destroys all existing watches, pending events,...
This method is automatically called at the end of loop().
Afterward it is invalid to access this instance.
N)r  r  
unregisterr8   r  r	  r3   s    r   rn  Notifier.stopo  sC     88MM$$TXX.HHTXXDH!r   )r  r
  r  r  r  r  r  r  r	  r  r  r<  Nr   r   N)Tr@   r  )r   r   r   r	   r
   r   rY  rO  r  r$  r<  rB  r8   devnullrl  ri  rq  rn  r   r   r   r   r  r  <  se     HI&*6p#&#&)@)'V#: $(rzz"**::6:p),\"r   r  c                   8    \ rS rSrSr  S	S jrS rS rS rSr	g)
ThreadedNotifieri}  a^  
This notifier inherits from threading.Thread for instanciating a separate
thread, and also inherits from Notifier, because it is a threaded notifier.

Note that every functionality provided by this class is also provided
through Notifier class. Moreover Notifier should be considered first because
it is not threaded and could be easily daemonized.
Nc                 F   [         R                  R                  U 5        [         R                  " 5       U l        [
        R                  XX#XE5        [        R                  " 5       U l        U R                  R                  U R                  S   [        R                  5        g)a  
Initialization, initialize base classes. read_freq, threshold and
timeout parameters are used when looping.

@param watch_manager: Watch Manager.
@type watch_manager: WatchManager instance
@param default_proc_fun: Default processing method. See base class.
@type default_proc_fun: instance of ProcessEvent
@param read_freq: if read_freq == 0, events are read asap,
                  if read_freq is > 0, this thread sleeps
                  max(0, read_freq - (timeout / 1000)) seconds.
@type read_freq: int
@param threshold: File descriptor will be read only if the accumulated
                  size to read becomes >= threshold. If != 0, you likely
                  want to use it in combination with an appropriate
                  value set for read_freq because without that you would
                  keep looping without really reading anything and that
                  until the amount of events to read is >= threshold. At
                  least with read_freq you might sleep.
@type threshold: int
@param timeout: see read_freq above. If provided, it must be set in
                milliseconds. See
                https://docs.python.org/3/library/select.html#select.poll.poll
@type timeout: int
r   N)r  Threadr   r  _stop_eventr  r8   piper  r  r  r  r  r  s         r   r   ThreadedNotifier.__init__  sl    8 	!!$'$??,$/?#	. WWY
tzz!}fmm<r   c                    U R                   R                  5         [        R                  " U R                  S   S5        [
        R                  R                  U 5        [        R                  U 5        U R                  R                  U R                  S   5        [        R                  " U R                  S   5        [        R                  " U R                  S   5        g)z;
Stop notifier's loop. Stop notification. Join the thread.
r   s   stopr   N)r|  r  r8   r   r  r  r{  r   r  rn  r  rt  r  r3   s    r   rn  ThreadedNotifier.stop  s     	
A(d#d  A/
A
Ar   c                 <   U R                   R                  5       (       d}  U R                  5         [        R                  " 5       nU R	                  5       (       a!  U R                  U5        U R                  5         U R                   R                  5       (       d  M|  gg)z
Thread's main loop. Don't meant to be called by user directly.
Call inherited start() method instead.

Events are read only once time every min(read_freq, timeout)
seconds at best and only if the size of events to read is >= threshold.
N)r|  isSetrB  r  r$  ri  r<  )r   rf  s     r   rq  ThreadedNotifier.loop  sn     ""((**!yy{H  ""H%  " ""((**r   c                 $    U R                  5         g)z
Start thread's loop: read and process events until the method
stop() is called.
Never call this method directly, instead call the start() method
inherited from threading.Thread, which then will call run() in
its turn.
N)rq  r3   s    r   runThreadedNotifier.run  s     			r   )r  r|  rv  )
r   r   r   r	   r
   r   rn  rq  r  r   r   r   r   ry  ry  }  s&     HI&*$=L
 #&r   ry  c                   ,    \ rS rSrSr  SS jrS rSrg)AsyncNotifieri  z
This notifier inherits from asyncore.file_dispatcher in order to be able to
use pyinotify along with the asyncore framework.

Nc                     [         R                  XX#XE5        [        R                  R                  X R                  U5        g)z
Initializes the async notifier. The only additional parameter is
'channel_map' which is the optional asyncore private map. See
Notifier class for the meaning of the others parameters.

N)r  r   asyncorefile_dispatcherr  )r   r  r  r  r  r  channel_maps          r   r   AsyncNotifier.__init__  s4     	$/?#	.  ))$+Fr   c                 D    U R                  5         U R                  5         g)z
When asyncore tells us we can read from the fd, we proceed processing
events. This method can be overridden for handling a notification
differently.

N)r<  rB  r3   s    r   handle_readAsyncNotifier.handle_read  s     	r   r   )Nr   r   NN)r   r   r   r	   r
   r   r  r   r   r   r   r  r    s    
 HI8<
Gr   r  c                   4    \ rS rSrSr   SS jrS rS rSrg)	TornadoAsyncNotifieri  z
Tornado ioloop adapter.

Nc	                     X l         X0l        [        R                  XXEXg5        UR	                  U R
                  U R                  UR                  5        g)a  
Note that if later you must call ioloop.close() be sure to let the
default parameter to all_fds=False.

See example tornado_notifier.py for an example using this notifier.

@param ioloop: Tornado's IO loop.
@type ioloop: tornado.ioloop.IOLoop instance.
@param callback: Functor called at the end of each call to handle_read
                 (IOLoop's read handler). Expects to receive the
                 notifier object (self) as single parameter.
@type callback: callable object or function
N)io_loophandle_read_callbackr  r   add_handlerr  r  READ)	r   r  ioloopro  r  r  r  r  r  s	            r   r   TornadoAsyncNotifier.__init__  sE      $,!$/?#	.488T%5%5v{{Cr   c                 x    U R                   R                  U R                  5        [        R	                  U 5        g r@   )r  remove_handlerr  r  rn  r3   s    r   rn  TornadoAsyncNotifier.stop  s$    ##DHH-dr   c                     U R                  5         U R                  5         U R                  b  U R                  U 5        gg)z 
See comment in AsyncNotifier.

Nr<  rB  r  r   r"  kwargss      r   r   TornadoAsyncNotifier.handle_read  s;    
 	$$0%%d+ 1r   )r  r  )NNr   r   NN	r   r   r   r	   r
   r   rn  r  r   r   r   r   r  r    s"     8<JN!D,,r   r  c                   2    \ rS rSrSr  SS jrS rS rSrg)	AsyncioNotifieri  z(

asyncio/trollius event loop adapter.

Nc                     X l         X0l        [        R                  XXEXg5        UR	                  U R
                  U R                  5        g)a  

See examples/asyncio_notifier.py for an example usage.

@param loop: asyncio or trollius event loop instance.
@type loop: asyncio.BaseEventLoop or trollius.BaseEventLoop instance.
@param callback: Functor called at the end of each call to handle_read.
                 Expects to receive the notifier object (self) as
                 single parameter.
@type callback: callable object or function

N)rq  r  r  r   
add_readerr  r  )r   r  rq  ro  r  r  r  r  s           r   r   AsyncioNotifier.__init__#  s=     	$,!$/?#	.$"2"23r   c                 x    U R                   R                  U R                  5        [        R	                  U 5        g r@   )rq  remove_readerr  r  rn  r3   s    r   rn  AsyncioNotifier.stop7  s$    		)dr   c                     U R                  5         U R                  5         U R                  b  U R                  U 5        g g r@   r  r  s      r   r  AsyncioNotifier.handle_read;  s9    $$0%%d+ 1r   )r  rq  )NNr   r   Nr  r   r   r   r  r    s    
 6:JN4(,r   r  c                   (    \ rS rSrSrSrS rS rSrg)WatchiB  z=
Represent a watch, i.e. a file or directory being watched.

)rQ   r   rK   rO  rQ  rR  r  c                     Xl         X l        X0l        X@l        XPl        X`l        [        R                  R                  U R                  5      U l        g)a  
Initializations.

@param wd: Watch descriptor.
@type wd: int
@param path: Path of the file or directory being watched.
@type path: str
@param mask: Mask.
@type mask: int
@param proc_fun: Processing callable object.
@type proc_fun:
@param auto_add: Automatically add watches on new directories.
@type auto_add: bool
@param exclude_filter: Boolean function, used to exclude new
                       directories from being automatically watched.
                       See WatchManager.__init__
@type exclude_filter: callable object
N)	rQ   r   rK   rO  rQ  rR  r8   rU  r  )r   rQ   r   rK   rO  rQ  rR  s          r   r   Watch.__init__J  s;    & 		  ,77==+r   c                    SR                  U R                   Vs/ s Hh  oR                  S5      (       a  M  [        R	                  U5      < [        R                  S5      < [        R                  [        U U5      5      < 3PMj     sn5      n[        R                  S5      < [        R                  U R                  R                  5      < SU< S[        R                  S5      < 3nU$ s  snf )z-
@return: String representation.
@rtype: str
r   r   r   r   r   )r   	__slots__rv   r  r  r  r  r  r  r	  r   )r   r   r
  s      r   r   Watch.__repr__e  s    
 HH #'..	N #1$8L	L-":":4"@"/";";C"@"/";";GDDH=J #KL #1	N O *55c:)44T^^5L5LM)55c:< Ns   C/AC/)rQ  r  rR  rK   r   rO  rQ   N)	r   r   r   r	   r
   r  r   r   r   r   r   r   r  r  B  s    *I,6r   r  c                   0    \ rS rSrSrS rS rS rS rSr	g)	ExcludeFilteriw  z'
ExcludeFilter is an exclusion filter.
c                 *   [        U[        5      (       a  U R                  U5      nO[        U[        5      (       a  UnO[        e/ U l        U HA  nU R
                  R                  [        R                  " U[        R                  5      5        MC     g)a  
Examples:
  ef1 = ExcludeFilter(["/etc/rc.*", "/etc/hostname"])
  ef2 = ExcludeFilter("/my/path/exclude.lst")
  Where exclude.lst contains:
  /etc/rc.*
  /etc/hostname

Note: it is not possible to exclude a file if its encapsulating
      directory is itself watched. See this issue for more details
      https://github.com/seb-m/pyinotify/issues/31

@param arg_lst: is either a list of patterns or a filename from which
                patterns will be loaded.
@type arg_lst: list of str or str
N)
rE   rF   _load_patterns_from_filerF  	TypeError_lregexr  recompileUNICODE)r   arg_lstlstregexs       r   r   ExcludeFilter.__init__{  sj    " gs##//8C&&COELL

5"** => r   c                    / n[        US5       nUR                  5        HC  nUR                  5       nU(       a  UR                  S5      (       a  M2  UR	                  U5        ME     S S S 5        U$ ! , (       d  f       U$ = f)Nr   #)r   	readlinesstriprv   r  )r   r  r  r   linepatterns         r   r  &ExcludeFilter._load_patterns_from_file  so    (C H **,**,'"4"4S"9"9

7# - ! 
 !  
s   AA11
B c                 (    UR                  U5      S L$ r@   )match)r   r  r   s      r   _matchExcludeFilter._match  s    {{4 ,,r   c                 Z    U R                    H  nU R                  X!5      (       d  M    g   g)z
@param path: Path to match against provided regexps.
@type path: str
@return: Return True if path has been matched and should
         be excluded, False otherwise.
@rtype: bool
TF)r  r  )r   r   r  s      r   r5  ExcludeFilter.__call__  s)     \\E{{5'' " r   )r  N)
r   r   r   r	   r
   r   r  r  r5  r   r   r   r   r  r  w  s    ?8	-r   r  c                       \ rS rSrSrS rSrg)WatchManagerErrori  zL
WatchManager Exception. Raised on error encountered on watches
operations.
c                 :    X l         [        R                  X5        g)z
@param msg: Exception string's description.
@type msg: string
@param wmd: This dictionary contains the wd assigned to paths of the
            same call for which watches were successfully added.
@type wmd: dict
N)wmdr/  r   )r   rc  r  s      r   r   WatchManagerError.__init__  s     4%r   )r  Nr   r   r   r   r  r    s    	&r   r  c                       \ rS rSrSrS 4S jrS rS rS rS r	\
S	 5       rS
 rS rS r   SS jrS r  SS jrS rS rS rS rSS jrS rS rS r\
" \\S5      rSrg)WatchManageri  z
Provide operations for watching files and directories. Its internal
dictionary is used to reference watched items. When used inside
threaded code, one must instanciate as many WatchManager instances as
there are ThreadedNotifier instances.

c                     gr  r   r   s    r   r   WatchManager.<lambda>  s    5r   c                 8   SU l         Xl        0 U l        [        R	                  5       U l        U R
                  c
  [        5       eU R
                  R                  5       U l        U R                  S:  a'  Sn[        X R
                  R                  5       -  5      eg)a  
Initialization: init inotify, init watch manager dictionary.
Raise OSError if initialization fails, raise InotifyBindingNotFoundError
if no inotify binding was found (through ctypes or from direct access to
syscalls).

@param exclude_filter: boolean function, returns True if current
                       path must be excluded from being watched.
                       Convenient for providing a common exclusion
                       filter for every call to add_watch.
@type exclude_filter: callable object
FNr   z-Cannot initialize new instance of inotify, %s)_ignore_events_exclude_filter_wmdr&   r/   _inotify_wrapperr   rB   r  ry   r=   )r   rR  r#   s      r   r   WatchManager.__init__  s     $-	 . 5 5 7  (-//((55788a<AC# 5 5 ? ? AABB r   c                 D    [         R                  " U R                  5        g)a  
Close inotify's file descriptor, this action will also automatically
remove (i.e. stop watching) all its associated watch descriptors.
After a call to this method the WatchManager's instance become useless
and cannot be reused, a new instance must then be instanciated. It
makes sense to call this method in few situations for instance if
several independant WatchManager must be instanciated or if all watches
must be removed and no other watches need to be added.
N)r8   r  r  r3   s    r   r  WatchManager.close  s     	r   c                     U R                   $ )zS
Return assigned inotify's file descriptor.

@return: File descriptor.
@rtype: int
)r  r3   s    r   r   WatchManager.get_fd  s     xxr   c                 8    U R                   R                  U5      $ )zZ
Get watch from provided watch descriptor wd.

@param wd: Watch descriptor.
@type wd: int
)r  r/  )r   rQ   s     r   rS  WatchManager.get_watch  s     yy}}R  r   c                      U R                   U	 g! [         a+  n[        R                  S[	        U5      -  5         SnAgSnAff = f)zc
Remove watch entry associated to watch descriptor wd.

@param wd: Watch descriptor.
@type wd: int
z)Cannot delete unknown watch descriptor %sN)r  KeyErrorr   rx  rF   )r   rQ   r#   s      r   r  WatchManager.del_watch  s>    	N		" 	NIIACHLMM	Ns    
A!A  Ac                     U R                   $ )zu
Get a reference on the internal watch manager dictionary.

@return: Internal watch manager dictionary.
@rtype: dict
)r  r3   s    r   rv  WatchManager.watches  s     yyr   c                 @    [         R                  R                  U5      $ )zG
Format path to its internal (stored in watch manager) representation.
)r8   r   rg  )r   r   s     r   __format_pathWatchManager.__format_path  s    
 ww%%r   c           	         U R                  U5      nU(       a  U[        -  (       d	  U[        -  nU R                  R                  U R                  X5      nUS:  a  U$ [        XaX#XES9nXpR                  U'   [        R                  SU5        U$ )zo
Add a watch on path, build a Watch object and insert it in the
watch manager dictionary. Return the wd value.
r   )rQ   r   rK   rO  rQ  rR  zNew %s)	_WatchManager__format_pathr   r  rL   r  r  r  r   r  )r   r   rK   rO  rQ  rR  rQ   watchs           r   __add_watchWatchManager.__add_watch!  s    
 !!$'D9,ID""44TXXtJ6IT'H 		"		(E"	r   c                 B    U(       a  [         R                  " U5      $ U/$ r@   )globiglob)r   r   do_globs      r   __globWatchManager.__glob3  s    ::d##6Mr   Nc	           
         0 n	Uc  U R                   nU R                  U5       H  n
[        U
[        5      (       d  SX'   M  U R	                  X5       H  nU R                  X5       H|  nU" U5      (       dh  U R                  XUUU5      =oU'   US:  aH  SXU R                  R                  5       4-  nU(       a  [        R                  U5        Mk  [        X5      eMx  SX'   M~     M     M     U	$ )a  
Add watch(s) on the provided |path|(s) with associated |mask| flag
value and optionally with a processing |proc_fun| function and
recursive flag |rec| set to True.
All |path| components _must_ be str (i.e. unicode) objects.
If |path| is already watched it is ignored, but if it is called with
option rec=True a watch is put on each one of its not-watched
subdirectory.

@param path: Path to watch, the path can either be a file or a
             directory. Also accepts a sequence (list) of paths.
@type path: string or list of strings
@param mask: Bitmask of events.
@type mask: int
@param proc_fun: Processing object.
@type proc_fun: function or ProcessEvent instance or instance of
                one of its subclasses or callable object.
@param rec: Recursively add watches from path on all its
            subdirectories, set to False by default (doesn't
            follows symlinks in any case).
@type rec: bool
@param auto_add: Automatically add watches on newly created
                 directories in watched parent |path| directory.
                 If |auto_add| is True, IN_CREATE is ored with |mask|
                 when the watch is added.
@type auto_add: bool
@param do_glob: Do globbing on pathname (see standard globbing
                module for more informations).
@type do_glob: bool
@param quiet: if False raises a WatchManagerError exception on
              error. See example not_quiet.py.
@type quiet: bool
@param exclude_filter: predicate (boolean function), which returns
                       True if the current path must be excluded
                       from being watched. This argument has
                       precedence over exclude_filter passed to
                       the class' constructor.
@type exclude_filter: callable object
@return: dict of paths associated to watch descriptors. A wd value
         is positive if the watch was added sucessfully, otherwise
         the value is negative. If the path was invalid or was already
         watched it is not included into this returned dictionary.
@rtype: dict of {str: int}
r   z$add_watch: cannot watch %s WD=%d, %s)r  _WatchManager__format_paramrE   rF   _WatchManager__glob_WatchManager__walk_rec_WatchManager__add_watchr  r=   r   rx  r  )r   r   rK   rO  rP  rQ  r  quietrR  ret_npathapathrpathrQ   r#   s                  r   rT  WatchManager.add_watch9  s   ^ !!11N ((.EeS))
 U4!__U8E)%00+/+;+;E<D<D<J,L L%[ 6#I(-(,(=(=(G(G(I(K$KC  % #		#&7&B B " ')# 9 5 /6 r   c              #   V  #    U GH  nU R                  U5      nUb  Uv   OM  [        R                  R                  U5      (       d  ME  [        R                  R	                  U5      n[        U5      nU R                  R                  5        H  nUS   R                  n[        R                  R                  X6/5      nU[        R                  :X  d:  [        U5      U:X  d  MW  [        U5      U:  d  Mh  Xd   [        R                  :X  d  M  US   R                  v   M     GM!     g7f)z
Get every wd from self._wmd if its path is under the path of
one (at least) of those in lpath. Doesn't follow symlinks.

@param lpath: list of watch descriptor
@type lpath: list of int
@return: list of watch descriptor
@rtype: list of int
Nr   )get_pathr8   r   rU  rg  ru  r  r   commonprefixrt  rQ   )r   lpathr  rootlendiwdcurprefs           r   __get_sub_recWatchManager.__get_sub_rec  s      A==#D  77==&& 77##D)Dt9Dyy(!fkkww++TK8266>c$i4&7&)#ho&)i266&9a&))O )# s   CD)%D)6D)D)c                    U R                  U5      nU(       a  U R                  U5      n0 nU GH7  n	U R                  U	5      n
U
(       a  U	S:  a.  SU	-  nU(       a  [        R	                  U5        ME  [        X5      eU(       a  U R                  R                  U R                  U
U5      nUS:  aL  SX'   SXU R                  R                  5       4-  nU(       a  [        R	                  U5        M  [        X5      eX:X  d   eU(       d  U(       a  U R                  U	   nU(       a  UWl        U(       a  UWl        SX'   [        R                  SU R                  U	   5        GM:     U$ )a  
Update existing watch descriptors |wd|. The |mask| value, the
processing object |proc_fun|, the recursive param |rec| and the
|auto_add| and |quiet| flags can all be updated.

@param wd: Watch Descriptor to update. Also accepts a list of
           watch descriptors.
@type wd: int or list of int
@param mask: Optional new bitmask of events.
@type mask: int
@param proc_fun: Optional new processing function.
@type proc_fun: function or ProcessEvent instance or instance of
                one of its subclasses or callable object.
@param rec: Optionally adds watches recursively on all
            subdirectories contained into |wd| directory.
@type rec: bool
@param auto_add: Automatically adds watches on newly created
                 directories in the watch's path corresponding to |wd|.
                 If |auto_add| is True, IN_CREATE is ored with |mask|
                 when the watch is updated.
@type auto_add: bool
@param quiet: If False raises a WatchManagerError exception on
              error. See example not_quiet.py
@type quiet: bool
@return: dict of watch descriptors associated to booleans values.
         True if the corresponding wd has been successfully
         updated, False otherwise.
@rtype: dict of {int: bool}
r   zupdate_watch: invalid WD=%dFz(update_watch: cannot update %s WD=%d, %sTzUpdated watch - %s)r  _WatchManager__get_sub_recr  r   rx  r  r  rL   r  r=   r  rO  rQ  r  )r   rQ   rK   rO  rP  rQ  r  lwdr  awdr  r#   wd_r[  s                 r   update_watchWatchManager.update_watch  s;   > !!"%$$S)CCMM#&EC!G3c9IIcN'22++==dhh>BD7 %DIE %D,A,A,K,K,MNOC		# +C66z"z83"*"*DIII*DIIcN;C D r   c              #   Z   #    [        U[        5      (       a  U H  nUv   M	     gUv   g7f)zf
@param param: Parameter.
@type param: string or int
@return: wrap param.
@rtype: list of type(param)
N)rE   rF  )r   paramp_s      r   __format_paramWatchManager.__format_param  s*      eT""  Ks   )+c                     U R                  U5      nU R                  R                  5        H  nUS   R                  U:X  d  M  US   s  $    g)a  
Returns the watch descriptor associated to path. This method
presents a prohibitive cost, always prefer to keep the WD
returned by add_watch(). If the path is unknown it returns None.

@param path: Path.
@type path: str
@return: WD or None.
@rtype: int or None
r   r   N)r  r  r   r   )r   r   r
  s      r   rW  WatchManager.get_wd  sB     !!$'99??$C1v{{d"1v %r   c                 X    U R                   R                  U5      nUb  UR                  $ g)z
Returns the path associated to WD, if WD is unknown it returns None.

@param wd: Watch descriptor.
@type wd: int
@return: Path or None.
@rtype: string or None
N)r  r/  r   )r   rQ   r[  s      r   r  WatchManager.get_path  s+     r";; r   c              #      #    U(       aH  [         R                  R                  U5      (       d$  [         R                  R                  U5      (       d  Uv   g[         R                  " U5       H
  u  p4nUv   M     g7f)z
Yields each subdirectories of top, doesn't follow symlinks.
If rec is false, only yield top.

@param top: root directory.
@type top: string
@param rec: recursive flag.
@type rec: bool
@return: path of one subdirectory.
@rtype: string
N)r8   r   islinkrU  walk)r   toprP  r  dirsfiless         r   
__walk_recWatchManager.__walk_rec   sO      bggnnS))s1C1CI%'WWS\!E
 &2s   A:A<c                    U R                  U5      nU(       a  U R                  U5      n0 nU H  nU R                  R                  U R                  U5      nUS:  aK  SXV'   SX`R                  R                  5       4-  nU(       a  [        R                  U5        Mo  [        X5      eX`R                  ;   a  U R                  U	 SXV'   [        R                  SX`R                  U5      5        M     U$ )aP  
Removes watch(s).

@param wd: Watch Descriptor of the file or directory to unwatch.
           Also accepts a list of WDs.
@type wd: int or list of int.
@param rec: Recursively removes watches on every already watched
            subdirectories and subfiles.
@type rec: bool
@param quiet: If False raises a WatchManagerError exception on
              error. See example not_quiet.py
@type quiet: bool
@return: dict of watch descriptors associated to booleans values.
         True if the corresponding wd has been successfully
         removed, False otherwise.
@rtype: dict of {int: bool}
r   Fz!rm_watch: cannot remove WD=%d, %sTzWatch WD=%d (%s) removed)r  r  r  rR   r  r=   r   rx  r  r  r  r  )	r   rQ   rP  r  r  r  r  r  r#   s	            r   rm_watchWatchManager.rm_watch2  s    $ !!"%$$S)CC''883GCQw!	:!6!6!@!@!BCDIIcN'22 iiIIcNDIII0#}}S7IJ! " r   c           
         ^ [         R                  R                  U5      nUS:X  a  0 $ [         R                  R                  U5      mU[        [
        -  -  nU4S jnU R                  XBU" [        US95      SSSS S9$ )a  
Watch a transient file, which will be created and deleted frequently
over time (e.g. pid file).

@attention: Currently under the call to this function it is not
possible to correctly watch the events triggered into the same
base directory than the directory where is located this watched
transient file. For instance it would be wrong to make these
two successive calls: wm.watch_transient_file('/var/run/foo.pid', ...)
and wm.add_watch('/var/run/', ...)

@param filename: Filename.
@type filename: string
@param mask: Bitmask of events, should contain IN_CREATE and IN_DELETE.
@type mask: int
@param proc_class: ProcessEvent (or of one of its subclass), beware of
                   accepting a ProcessEvent's instance as argument into
                   __init__, see transient_file.py example for more
                   details.
@type proc_class: ProcessEvent's instance or of one of its subclasses.
@return: Same as add_watch().
@rtype: Same as add_watch().
r   c                 >   > [        U S5      c  gTU R                  :H  $ )Nr   F)r  r   )r2  r[  s    r   cmp_name3WatchManager.watch_transient_file.<locals>.cmp_name|  s"    uf%-uzz))r   )r  Fc                     gr  r   r  s    r   r   3WatchManager.watch_transient_file.<locals>.<lambda>  s    %r   )rO  rP  rQ  r  rR  )r8   r   r`  r[  r   r   rT  r  )r   r  rK   
proc_classr`  r,  r[  s         @r   watch_transient_file!WatchManager.watch_transient_file]  s    0 ''//(+b=I77##H-	I%%	* ~~g'1+82L'M"'',e-?	  A 	Ar   c                     U R                   $ r@   r  r3   s    r   get_ignore_eventsWatchManager.get_ignore_events  s    """r   c                     Xl         g r@   r4  )r   r   s     r   set_ignore_eventsWatchManager.set_ignore_events  s    "r   z'Make watch manager ignoring new events.)r  r  r  r  r  )NFFFTN)NNFFT)FT)r   r   r   r	   r
   r   r  r   rS  r  r   rv  r  r  r  rT  r  r  r  rW  r  r  r(  r1  r5  r8  r@  r   r   r   r   r  r    s     '9 C4
!
N  &$ 8=7;!%Pd!$F >C+/FP $(V'AR## .0AFHMr   r  c                   @    \ rS rSrSrSS jrS rS rS rS r	S	 r
S
rg)RawOutputFormati  z 
Format string representations.
Nc                 $    U=(       d    0 U l         g r@   format)r   r>  s     r   r   RawOutputFormat.__init__  s    lr   c                     [        U[        5      (       d  [        U5      nU R                  R                  US5      U-   U R                  R                  SS5      -   $ )Nr   normal)rE   rF   r>  r/  )r   r
  	attributes      r   r  RawOutputFormat.simple  sK    !S!!AA	2.2"-. 	/r   c                 &    U R                  US5      $ )zPunctuation color.rA  r  r   r
  s     r   r  RawOutputFormat.punctuation      {{1h''r   c                 &    U R                  US5      $ )zField value color.purplerE  rF  s     r   r  RawOutputFormat.field_value  rH  r   c                 &    U R                  US5      $ )zField name color.bluerE  rF  s     r   r  RawOutputFormat.field_name  s    {{1f%%r   c                 `    U R                   R                  SS5      U R                  US5      -   $ )zClass name color.redr   bold)r>  r/  r  rF  s     r   r  RawOutputFormat.class_name  s'    {{ub)DKK6,BBBr   r=  r@   )r   r   r   r	   r
   r   r  r  r  r  r  r   r   r   r   r;  r;    s&    #/((&Cr   r;  c                       \ rS rSrSrS rSrg)ColoredOutputFormati  z(
Format colored string representations.
c                 L    SSSSSSSSS	S
SSS.n[         R                  X5        g )Nz[0mz[30mz[31mz[32mz[33mz[34mz[35mz[36mz[1mz[4mz[5mz[7m)rA  blackrP  greenr  rM  rJ  cyanrQ  ulineblinkinvert)r;  r   )r   fs     r   r   ColoredOutputFormat.__init__  s=       !! " 	  )r   r   Nr   r   r   r   rT  rT    s    *r   rT  c                      [        [        S[        5        [        5        H7  n U R	                  S5      (       d  M  [        [        U [        5       U    5        M9     Sqg)a  
Use this function to turn on the compatibility mode. The compatibility
mode is used to improve compatibility with Pyinotify 0.7.1 (or older)
programs. The compatibility mode provides additional variables 'is_dir',
'event_name', 'EventsCodes.IN_*' and 'EventsCodes.ALL_EVENTS' as
Pyinotify 0.7.1 provided. Do not call this function from new programs!!
Especially if there are developped for Pyinotify >= 0.8.x.
r   IN_TN)r   r   r   globalsrv   r  )evnames    r   compatibility_moderb    sH     Kz2)U##K6):;  r   c                    ^ SSK Jn   SnU " US9nUR                  SSSSS	S
9  UR                  SSSSSS
9  UR                  SSSSSS
9  UR                  SSSSSS
9  UR                  SSSSSS9  UR                  SSSSS S
9  UR                  S!S"SS#S$S
9  UR                  S%S&SS'S(S
9  UR                  S)S*S+S,S-S
9  UR                  5       u  mnTR                  (       a  [
        R                  S.5        TR                  (       a  [        [        5        TR                  (       d
  [        5       q[        U5      S/:  a  S0nOUn[        5       nTR                  (       a  [!        U[#        5       S1S29nO[!        U[%        5       S39nSnTR&                  (       af  TR&                  R)                  S45      nU HD  n	[*        R,                  R/                  U	S5      n
U
(       a  Xz-  nM0  UR1                  S5U	-  5        MF     O[2        nS6nTR                  (       a  S7 nUnTR4                  (       a  U4S8 jnUn[
        R7                  S9U-  5        UR9                  XGTR:                  TR<                  TR>                  S:9  URA                  US;9  g6)<z
By default the watched path is '/tmp' and all types of events are
monitored. Events monitoring serves forever, type c^c to stop it.
r   )OptionParserz.usage: %prog [options] [path1] [path2] [pathn])usagez-vz	--verbose
store_trueverbosezVerbose mode)actiondesthelpz-rz--recursive	recursivez Add watches recursively on pathsz-az
--auto_addrQ  z,Automatically add watches on new directoriesz-gz--globr  zTreat paths as globsz-ez--events-listzEVENT[,...]events_listzpA comma-separated list of events to watch for - see the documentation for valid options (defaults to everything))metavarri  rj  z-sz--statsr  zDisplay dummy statisticsz-Vz	--versionr   zPyinotify versionz-fz--raw-format
raw_formatzDisable enhanced output format.z-cz	--commandstorecommandzShell command to run upon event
   r   z/tmp   )r  r  )r  ,z4The event '%s' specified with option -e is not validNc                    [         R                  R                  [        U R	                  5       5      5        [         R                  R                  S5        [         R                  R                  [        U R	                  5       5      5        [         R                  R                  S5        [         R                  R                  5         g )Nr   )rt   r  r   r  rO  rF   r  )r
  s    r   cbcommand_line.<locals>.cb$	  sp    JJT!**,/0JJT"JJS./JJT"JJr   c                 D   > [         R                  " TR                  SS9  g )NT)shell)
subprocessPopenrp  )r
  optionss    r   ru  rv  .	  s    W__D9r   z2Start monitoring %s, (press c^c to halt pyinotify))rP  rQ  r  )ro  )!optparserd  
add_option
parse_argsrg  r   r   r   print__version__rn  rT  r  ru  r  r  r  r  r  rl  r0  r   	ALL_FLAGSr/  rx  r   rp  r  rT  rk  rQ  r  rq  )rd  re  parserr"  r   r@  rA  rK   rl  r  evcodecb_funru  r{  s                @r   command_liner    s   
 &<E&F
dK$>  ;
dM,&=  ? dL%I  K dH\!1  3 dO](-  /
 dIl"5  7 dK$,?  A
dN<'<  > dK$<  > '')OWdRk+-
4y1} 
B}}BAFB1AB D))//4B **..r15F -/12 3   F}}	  	:IIBTIJLL!2!2W=M=MW^WcWcLdMM6M"r   __main__)Wr
   r/  r   r   rt   version_infor   r  r8   r  r0  r*  r:   r,  r)  r   r_  collectionsr   r   r   r  r  r  r  r  ry  	functoolsr   ImportErrorr)   ctypes.utilr,   
__author__r  r  r   r&   r-   r*   r   r   r   attrnamer`  r   r  r   r   r   flagcvalcr   r  r   valr   rw  r   r   r  r  r&  r+  r:  r  r  r  r  r  r  r{  ry  r  r  r  r  r  r  r  r  r;  r  rT  rb  r  r   r   r   r   <module>r     sx  .	Y 	
CN C f
'
44  	          (  	    	 
 3
  +. ++. +.\"n "J83 83x m&8 &8d PH%h/GIh Po& o&f   //557KE4 K%   & ZZ\	c	$&*s# " 8  &(<(<(C(C(EF
&0  l #%1  z "( (V! !H+F +\	+ 	+(0 (0VM} M`Z= Zz\ 8%, %RL Rj
+N 
+~" ~"B
Vy'' VrH,,h :',8 ',T",h ",J2 2j9 9x&	 &"IH IHXC C:  !*/ *("b#J zN WG  		  F
  s6   K1 K> L 1K;:K;>L
	L
LL