1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
# ----------------------------------------------------------------------------- |
3
|
|
|
# Copyright (c) 2015 Yann Lanthony |
4
|
|
|
# Copyright (c) 2017-2018 Spyder Project Contributors |
5
|
|
|
# |
6
|
|
|
# Licensed under the terms of the MIT License |
7
|
|
|
# (See LICENSE.txt for details) |
8
|
|
|
# ----------------------------------------------------------------------------- |
9
|
|
|
"""Source files event handler.""" |
10
|
|
|
|
11
|
|
|
# Standard library imports |
12
|
|
|
import os |
13
|
|
|
import time |
14
|
|
|
|
15
|
|
|
# Third party imports |
16
|
|
|
from watchdog.events import FileSystemEventHandler |
17
|
|
|
|
18
|
|
|
|
19
|
|
|
# py2 has no FileNotFoundError |
20
|
|
|
try: |
21
|
|
|
FileNotFoundError |
22
|
|
|
except NameError: |
23
|
|
|
FileNotFoundError = IOError |
|
|
|
|
24
|
|
|
|
25
|
|
|
|
26
|
|
|
class SourceModificationEventHandler(FileSystemEventHandler): |
|
|
|
|
27
|
|
|
|
28
|
|
|
def __init__(self, input_file, dest_file, watched_dir, compiler): |
29
|
|
|
super(SourceModificationEventHandler, self).__init__() |
30
|
|
|
self._input_file = input_file |
31
|
|
|
self._dest_file = dest_file |
32
|
|
|
self._compiler = compiler |
33
|
|
|
self._watched_dir = watched_dir |
34
|
|
|
self._watched_extension = os.path.splitext(self._input_file)[1] |
35
|
|
|
|
36
|
|
|
def _recompile(self): |
37
|
|
|
i = 0 |
38
|
|
|
success = False |
39
|
|
|
while i < 10 and not success: |
40
|
|
|
try: |
41
|
|
|
time.sleep(0.2) |
42
|
|
|
self._compiler(self._input_file, self._dest_file) |
43
|
|
|
success = True |
44
|
|
|
except FileNotFoundError: |
45
|
|
|
i += 1 |
46
|
|
|
|
47
|
|
|
def on_modified(self, event): |
48
|
|
|
# On Mac, event will always be a directory. |
49
|
|
|
# On Windows, only recompile if event's file |
50
|
|
|
# has the same extension as the input file |
51
|
|
|
we_should_recompile = ( |
|
|
|
|
52
|
|
|
event.is_directory and |
53
|
|
|
os.path.samefile(event.src_path, self._watched_dir) or |
54
|
|
|
os.path.splitext(event.src_path)[1] == self._watched_extension |
55
|
|
|
) |
56
|
|
|
if we_should_recompile: |
57
|
|
|
self._recompile() |
58
|
|
|
|
59
|
|
|
def on_created(self, event): |
60
|
|
|
if os.path.splitext(event.src_path)[1] == self._watched_extension: |
61
|
|
|
self._recompile() |
62
|
|
|
|
It is generally discouraged to redefine built-ins as this makes code very hard to read.