__init__.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
  5. # Copyright 2012 Google, Inc.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import os
  19. import signal
  20. import subprocess
  21. import time
  22. from watchdog.utils import echo, has_attribute
  23. from watchdog.events import PatternMatchingEventHandler
  24. class Trick(PatternMatchingEventHandler):
  25. """Your tricks should subclass this class."""
  26. @classmethod
  27. def generate_yaml(cls):
  28. context = dict(module_name=cls.__module__,
  29. klass_name=cls.__name__)
  30. template_yaml = """- %(module_name)s.%(klass_name)s:
  31. args:
  32. - argument1
  33. - argument2
  34. kwargs:
  35. patterns:
  36. - "*.py"
  37. - "*.js"
  38. ignore_patterns:
  39. - "version.py"
  40. ignore_directories: false
  41. """
  42. return template_yaml % context
  43. class LoggerTrick(Trick):
  44. """A simple trick that does only logs events."""
  45. def on_any_event(self, event):
  46. pass
  47. @echo.echo
  48. def on_modified(self, event):
  49. pass
  50. @echo.echo
  51. def on_deleted(self, event):
  52. pass
  53. @echo.echo
  54. def on_created(self, event):
  55. pass
  56. @echo.echo
  57. def on_moved(self, event):
  58. pass
  59. class ShellCommandTrick(Trick):
  60. """Executes shell commands in response to matched events."""
  61. def __init__(self, shell_command=None, patterns=None, ignore_patterns=None,
  62. ignore_directories=False, wait_for_process=False,
  63. drop_during_process=False):
  64. super(ShellCommandTrick, self).__init__(patterns, ignore_patterns,
  65. ignore_directories)
  66. self.shell_command = shell_command
  67. self.wait_for_process = wait_for_process
  68. self.drop_during_process = drop_during_process
  69. self.process = None
  70. def on_any_event(self, event):
  71. from string import Template
  72. if self.drop_during_process and self.process and self.process.poll() is None:
  73. return
  74. if event.is_directory:
  75. object_type = 'directory'
  76. else:
  77. object_type = 'file'
  78. context = {
  79. 'watch_src_path': event.src_path,
  80. 'watch_dest_path': '',
  81. 'watch_event_type': event.event_type,
  82. 'watch_object': object_type,
  83. }
  84. if self.shell_command is None:
  85. if has_attribute(event, 'dest_path'):
  86. context.update({'dest_path': event.dest_path})
  87. command = 'echo "${watch_event_type} ${watch_object} from ${watch_src_path} to ${watch_dest_path}"'
  88. else:
  89. command = 'echo "${watch_event_type} ${watch_object} ${watch_src_path}"'
  90. else:
  91. if has_attribute(event, 'dest_path'):
  92. context.update({'watch_dest_path': event.dest_path})
  93. command = self.shell_command
  94. command = Template(command).safe_substitute(**context)
  95. self.process = subprocess.Popen(command, shell=True)
  96. if self.wait_for_process:
  97. self.process.wait()
  98. class AutoRestartTrick(Trick):
  99. """Starts a long-running subprocess and restarts it on matched events.
  100. The command parameter is a list of command arguments, such as
  101. ['bin/myserver', '-c', 'etc/myconfig.ini'].
  102. Call start() after creating the Trick. Call stop() when stopping
  103. the process.
  104. """
  105. def __init__(self, command, patterns=None, ignore_patterns=None,
  106. ignore_directories=False, stop_signal=signal.SIGINT,
  107. kill_after=10):
  108. super(AutoRestartTrick, self).__init__(
  109. patterns, ignore_patterns, ignore_directories)
  110. self.command = command
  111. self.stop_signal = stop_signal
  112. self.kill_after = kill_after
  113. self.process = None
  114. def start(self):
  115. self.process = subprocess.Popen(self.command, preexec_fn=os.setsid)
  116. def stop(self):
  117. if self.process is None:
  118. return
  119. try:
  120. os.killpg(os.getpgid(self.process.pid), self.stop_signal)
  121. except OSError:
  122. # Process is already gone
  123. pass
  124. else:
  125. kill_time = time.time() + self.kill_after
  126. while time.time() < kill_time:
  127. if self.process.poll() is not None:
  128. break
  129. time.sleep(0.25)
  130. else:
  131. try:
  132. os.killpg(os.getpgid(self.process.pid), 9)
  133. except OSError:
  134. # Process is already gone
  135. pass
  136. self.process = None
  137. @echo.echo
  138. def on_any_event(self, event):
  139. self.stop()
  140. self.start()