watchdog icon indicating copy to clipboard operation
watchdog copied to clipboard

Custom tricks cannot inspect their target directories

Open brianthelion opened this issue 2 years ago • 2 comments

It would be very helpful if pathname was passed to the TrickClass constructor by watchmedo: https://github.com/gorakhargosh/watchdog/blob/21e9f4c6466b884f87ab39d704101fb4b8b9f3c6/src/watchdog/watchmedo.py#L206

Without this, a Trick subclass cannot do directory inspection prior to the .dispatch(...) loop kicking off, eg, to set its internal state on restart or similar.

brianthelion avatar Nov 07 '22 15:11 brianthelion

A useful workaround is to overload the main() entrypoint of watchmedo:

# mywatchmedo.py
import watchdog.watchmedo as watchmedo

def schedule_tricks(observer, tricks, pathname, recursive):
    """
    Overload original 'schedule_tricks' function.

    :param observer:
        The observer thread into which to schedule the trick and watch.
    :param tricks:
        A list of tricks.
    :param pathname:
        A path name which should be watched.
    :param recursive:
        ``True`` if recursive; ``False`` otherwise.
    """
    for trick in tricks:
        for name, value in list(trick.items()):
            TrickClass = watchmedo.load_class(name)
            handler = TrickClass(path=pathname, recursive=recursive, **value)
            trick_pathname = getattr(handler, 'source_directory', None) or pathname
            observer.schedule(handler, trick_pathname, recursive)

watchmedo.schedule_tricks = schedule_tricks

def main():
    watchmedo.main()

if __name__ == '__main__':
    main()

and then call python mywatchmedo.py ... instead of watchmedo ....

brianthelion avatar Nov 07 '22 16:11 brianthelion

I am open for patches if you would like to contriutte. :)

BoboTiG avatar Nov 08 '22 06:11 BoboTiG