watchmedo.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. """
  19. :module: watchdog.watchmedo
  20. :author: yesudeep@google.com (Yesudeep Mangalapilly)
  21. :synopsis: ``watchmedo`` shell script utility.
  22. """
  23. import os.path
  24. import sys
  25. import yaml
  26. import time
  27. import logging
  28. try:
  29. from cStringIO import StringIO
  30. except ImportError:
  31. try:
  32. from StringIO import StringIO
  33. except ImportError:
  34. from io import StringIO
  35. from argh import arg, aliases, ArghParser, expects_obj
  36. from watchdog.version import VERSION_STRING
  37. from watchdog.utils import load_class
  38. logging.basicConfig(level=logging.INFO)
  39. CONFIG_KEY_TRICKS = 'tricks'
  40. CONFIG_KEY_PYTHON_PATH = 'python-path'
  41. def path_split(pathname_spec, separator=os.pathsep):
  42. """
  43. Splits a pathname specification separated by an OS-dependent separator.
  44. :param pathname_spec:
  45. The pathname specification.
  46. :param separator:
  47. (OS Dependent) `:` on Unix and `;` on Windows or user-specified.
  48. """
  49. return list(pathname_spec.split(separator))
  50. def add_to_sys_path(pathnames, index=0):
  51. """
  52. Adds specified paths at specified index into the sys.path list.
  53. :param paths:
  54. A list of paths to add to the sys.path
  55. :param index:
  56. (Default 0) The index in the sys.path list where the paths will be
  57. added.
  58. """
  59. for pathname in pathnames[::-1]:
  60. sys.path.insert(index, pathname)
  61. def load_config(tricks_file_pathname):
  62. """
  63. Loads the YAML configuration from the specified file.
  64. :param tricks_file_path:
  65. The path to the tricks configuration file.
  66. :returns:
  67. A dictionary of configuration information.
  68. """
  69. with open(tricks_file_pathname, 'rb') as f:
  70. return yaml.safe_load(f.read())
  71. def parse_patterns(patterns_spec, ignore_patterns_spec, separator=';'):
  72. """
  73. Parses pattern argument specs and returns a two-tuple of
  74. (patterns, ignore_patterns).
  75. """
  76. patterns = patterns_spec.split(separator)
  77. ignore_patterns = ignore_patterns_spec.split(separator)
  78. if ignore_patterns == ['']:
  79. ignore_patterns = []
  80. return (patterns, ignore_patterns)
  81. def observe_with(observer, event_handler, pathnames, recursive):
  82. """
  83. Single observer thread with a scheduled path and event handler.
  84. :param observer:
  85. The observer thread.
  86. :param event_handler:
  87. Event handler which will be called in response to file system events.
  88. :param pathnames:
  89. A list of pathnames to monitor.
  90. :param recursive:
  91. ``True`` if recursive; ``False`` otherwise.
  92. """
  93. for pathname in set(pathnames):
  94. observer.schedule(event_handler, pathname, recursive)
  95. observer.start()
  96. try:
  97. while True:
  98. time.sleep(1)
  99. except KeyboardInterrupt:
  100. observer.stop()
  101. observer.join()
  102. def schedule_tricks(observer, tricks, pathname, recursive):
  103. """
  104. Schedules tricks with the specified observer and for the given watch
  105. path.
  106. :param observer:
  107. The observer thread into which to schedule the trick and watch.
  108. :param tricks:
  109. A list of tricks.
  110. :param pathname:
  111. A path name which should be watched.
  112. :param recursive:
  113. ``True`` if recursive; ``False`` otherwise.
  114. """
  115. for trick in tricks:
  116. for name, value in list(trick.items()):
  117. TrickClass = load_class(name)
  118. handler = TrickClass(**value)
  119. trick_pathname = getattr(handler, 'source_directory', None) or pathname
  120. observer.schedule(handler, trick_pathname, recursive)
  121. @aliases('tricks')
  122. @arg('files',
  123. nargs='*',
  124. help='perform tricks from given file')
  125. @arg('--python-path',
  126. default='.',
  127. help='paths separated by %s to add to the python path' % os.pathsep)
  128. @arg('--interval',
  129. '--timeout',
  130. dest='timeout',
  131. default=1.0,
  132. help='use this as the polling interval/blocking timeout (in seconds)')
  133. @arg('--recursive',
  134. default=True,
  135. help='recursively monitor paths')
  136. @expects_obj
  137. def tricks_from(args):
  138. """
  139. Subcommand to execute tricks from a tricks configuration file.
  140. :param args:
  141. Command line argument options.
  142. """
  143. from watchdog.observers import Observer
  144. add_to_sys_path(path_split(args.python_path))
  145. observers = []
  146. for tricks_file in args.files:
  147. observer = Observer(timeout=args.timeout)
  148. if not os.path.exists(tricks_file):
  149. raise IOError("cannot find tricks file: %s" % tricks_file)
  150. config = load_config(tricks_file)
  151. try:
  152. tricks = config[CONFIG_KEY_TRICKS]
  153. except KeyError:
  154. raise KeyError("No `%s' key specified in %s." % (
  155. CONFIG_KEY_TRICKS, tricks_file))
  156. if CONFIG_KEY_PYTHON_PATH in config:
  157. add_to_sys_path(config[CONFIG_KEY_PYTHON_PATH])
  158. dir_path = os.path.dirname(tricks_file)
  159. if not dir_path:
  160. dir_path = os.path.relpath(os.getcwd())
  161. schedule_tricks(observer, tricks, dir_path, args.recursive)
  162. observer.start()
  163. observers.append(observer)
  164. try:
  165. while True:
  166. time.sleep(1)
  167. except KeyboardInterrupt:
  168. for o in observers:
  169. o.unschedule_all()
  170. o.stop()
  171. for o in observers:
  172. o.join()
  173. @aliases('generate-tricks-yaml')
  174. @arg('trick_paths',
  175. nargs='*',
  176. help='Dotted paths for all the tricks you want to generate')
  177. @arg('--python-path',
  178. default='.',
  179. help='paths separated by %s to add to the python path' % os.pathsep)
  180. @arg('--append-to-file',
  181. default=None,
  182. help='appends the generated tricks YAML to a file; \
  183. if not specified, prints to standard output')
  184. @arg('-a',
  185. '--append-only',
  186. dest='append_only',
  187. default=False,
  188. help='if --append-to-file is not specified, produces output for \
  189. appending instead of a complete tricks yaml file.')
  190. @expects_obj
  191. def tricks_generate_yaml(args):
  192. """
  193. Subcommand to generate Yaml configuration for tricks named on the command
  194. line.
  195. :param args:
  196. Command line argument options.
  197. """
  198. python_paths = path_split(args.python_path)
  199. add_to_sys_path(python_paths)
  200. output = StringIO()
  201. for trick_path in args.trick_paths:
  202. TrickClass = load_class(trick_path)
  203. output.write(TrickClass.generate_yaml())
  204. content = output.getvalue()
  205. output.close()
  206. header = yaml.dump({CONFIG_KEY_PYTHON_PATH: python_paths})
  207. header += "%s:\n" % CONFIG_KEY_TRICKS
  208. if args.append_to_file is None:
  209. # Output to standard output.
  210. if not args.append_only:
  211. content = header + content
  212. sys.stdout.write(content)
  213. else:
  214. if not os.path.exists(args.append_to_file):
  215. content = header + content
  216. with open(args.append_to_file, 'ab') as output:
  217. output.write(content)
  218. @arg('directories',
  219. nargs='*',
  220. default='.',
  221. help='directories to watch.')
  222. @arg('-p',
  223. '--pattern',
  224. '--patterns',
  225. dest='patterns',
  226. default='*',
  227. help='matches event paths with these patterns (separated by ;).')
  228. @arg('-i',
  229. '--ignore-pattern',
  230. '--ignore-patterns',
  231. dest='ignore_patterns',
  232. default='',
  233. help='ignores event paths with these patterns (separated by ;).')
  234. @arg('-D',
  235. '--ignore-directories',
  236. dest='ignore_directories',
  237. default=False,
  238. help='ignores events for directories')
  239. @arg('-R',
  240. '--recursive',
  241. dest='recursive',
  242. default=False,
  243. help='monitors the directories recursively')
  244. @arg('--interval',
  245. '--timeout',
  246. dest='timeout',
  247. default=1.0,
  248. help='use this as the polling interval/blocking timeout')
  249. @arg('--trace',
  250. default=False,
  251. help='dumps complete dispatching trace')
  252. @arg('--debug-force-polling',
  253. default=False,
  254. help='[debug] forces polling')
  255. @arg('--debug-force-kqueue',
  256. default=False,
  257. help='[debug] forces BSD kqueue(2)')
  258. @arg('--debug-force-winapi',
  259. default=False,
  260. help='[debug] forces Windows API')
  261. @arg('--debug-force-winapi-async',
  262. default=False,
  263. help='[debug] forces Windows API + I/O completion')
  264. @arg('--debug-force-fsevents',
  265. default=False,
  266. help='[debug] forces Mac OS X FSEvents')
  267. @arg('--debug-force-inotify',
  268. default=False,
  269. help='[debug] forces Linux inotify(7)')
  270. @expects_obj
  271. def log(args):
  272. """
  273. Subcommand to log file system events to the console.
  274. :param args:
  275. Command line argument options.
  276. """
  277. from watchdog.utils import echo
  278. from watchdog.tricks import LoggerTrick
  279. if args.trace:
  280. echo.echo_class(LoggerTrick)
  281. patterns, ignore_patterns =\
  282. parse_patterns(args.patterns, args.ignore_patterns)
  283. handler = LoggerTrick(patterns=patterns,
  284. ignore_patterns=ignore_patterns,
  285. ignore_directories=args.ignore_directories)
  286. if args.debug_force_polling:
  287. from watchdog.observers.polling import PollingObserver as Observer
  288. elif args.debug_force_kqueue:
  289. from watchdog.observers.kqueue import KqueueObserver as Observer
  290. elif args.debug_force_winapi_async:
  291. from watchdog.observers.read_directory_changes_async import\
  292. WindowsApiAsyncObserver as Observer
  293. elif args.debug_force_winapi:
  294. from watchdog.observers.read_directory_changes import\
  295. WindowsApiObserver as Observer
  296. elif args.debug_force_inotify:
  297. from watchdog.observers.inotify import InotifyObserver as Observer
  298. elif args.debug_force_fsevents:
  299. from watchdog.observers.fsevents import FSEventsObserver as Observer
  300. else:
  301. # Automatically picks the most appropriate observer for the platform
  302. # on which it is running.
  303. from watchdog.observers import Observer
  304. observer = Observer(timeout=args.timeout)
  305. observe_with(observer, handler, args.directories, args.recursive)
  306. @arg('directories',
  307. nargs='*',
  308. default='.',
  309. help='directories to watch')
  310. @arg('-c',
  311. '--command',
  312. dest='command',
  313. default=None,
  314. help='''shell command executed in response to matching events.
  315. These interpolation variables are available to your command string::
  316. ${watch_src_path} - event source path;
  317. ${watch_dest_path} - event destination path (for moved events);
  318. ${watch_event_type} - event type;
  319. ${watch_object} - ``file`` or ``directory``
  320. Note::
  321. Please ensure you do not use double quotes (") to quote
  322. your command string. That will force your shell to
  323. interpolate before the command is processed by this
  324. subcommand.
  325. Example option usage::
  326. --command='echo "${watch_src_path}"'
  327. ''')
  328. @arg('-p',
  329. '--pattern',
  330. '--patterns',
  331. dest='patterns',
  332. default='*',
  333. help='matches event paths with these patterns (separated by ;).')
  334. @arg('-i',
  335. '--ignore-pattern',
  336. '--ignore-patterns',
  337. dest='ignore_patterns',
  338. default='',
  339. help='ignores event paths with these patterns (separated by ;).')
  340. @arg('-D',
  341. '--ignore-directories',
  342. dest='ignore_directories',
  343. default=False,
  344. help='ignores events for directories')
  345. @arg('-R',
  346. '--recursive',
  347. dest='recursive',
  348. default=False,
  349. help='monitors the directories recursively')
  350. @arg('--interval',
  351. '--timeout',
  352. dest='timeout',
  353. default=1.0,
  354. help='use this as the polling interval/blocking timeout')
  355. @arg('-w', '--wait',
  356. dest='wait_for_process',
  357. action='store_true',
  358. default=False,
  359. help="wait for process to finish to avoid multiple simultaneous instances")
  360. @arg('-W', '--drop',
  361. dest='drop_during_process',
  362. action='store_true',
  363. default=False,
  364. help="Ignore events that occur while command is still being executed "
  365. "to avoid multiple simultaneous instances")
  366. @arg('--debug-force-polling',
  367. default=False,
  368. help='[debug] forces polling')
  369. @expects_obj
  370. def shell_command(args):
  371. """
  372. Subcommand to execute shell commands in response to file system events.
  373. :param args:
  374. Command line argument options.
  375. """
  376. from watchdog.tricks import ShellCommandTrick
  377. if not args.command:
  378. args.command = None
  379. if args.debug_force_polling:
  380. from watchdog.observers.polling import PollingObserver as Observer
  381. else:
  382. from watchdog.observers import Observer
  383. patterns, ignore_patterns = parse_patterns(args.patterns,
  384. args.ignore_patterns)
  385. handler = ShellCommandTrick(shell_command=args.command,
  386. patterns=patterns,
  387. ignore_patterns=ignore_patterns,
  388. ignore_directories=args.ignore_directories,
  389. wait_for_process=args.wait_for_process,
  390. drop_during_process=args.drop_during_process)
  391. observer = Observer(timeout=args.timeout)
  392. observe_with(observer, handler, args.directories, args.recursive)
  393. @arg('command',
  394. help='''Long-running command to run in a subprocess.
  395. ''')
  396. @arg('command_args',
  397. metavar='arg',
  398. nargs='*',
  399. help='''Command arguments.
  400. Note: Use -- before the command arguments, otherwise watchmedo will
  401. try to interpret them.
  402. ''')
  403. @arg('-d',
  404. '--directory',
  405. dest='directories',
  406. metavar='directory',
  407. action='append',
  408. help='Directory to watch. Use another -d or --directory option '
  409. 'for each directory.')
  410. @arg('-p',
  411. '--pattern',
  412. '--patterns',
  413. dest='patterns',
  414. default='*',
  415. help='matches event paths with these patterns (separated by ;).')
  416. @arg('-i',
  417. '--ignore-pattern',
  418. '--ignore-patterns',
  419. dest='ignore_patterns',
  420. default='',
  421. help='ignores event paths with these patterns (separated by ;).')
  422. @arg('-D',
  423. '--ignore-directories',
  424. dest='ignore_directories',
  425. default=False,
  426. help='ignores events for directories')
  427. @arg('-R',
  428. '--recursive',
  429. dest='recursive',
  430. default=False,
  431. help='monitors the directories recursively')
  432. @arg('--interval',
  433. '--timeout',
  434. dest='timeout',
  435. default=1.0,
  436. help='use this as the polling interval/blocking timeout')
  437. @arg('--signal',
  438. dest='signal',
  439. default='SIGINT',
  440. help='stop the subprocess with this signal (default SIGINT)')
  441. @arg('--debug-force-polling',
  442. default=False,
  443. help='[debug] forces polling')
  444. @arg('--kill-after',
  445. dest='kill_after',
  446. default=10.0,
  447. help='when stopping, kill the subprocess after the specified timeout '
  448. '(default 10)')
  449. @expects_obj
  450. def auto_restart(args):
  451. """
  452. Subcommand to start a long-running subprocess and restart it
  453. on matched events.
  454. :param args:
  455. Command line argument options.
  456. """
  457. if args.debug_force_polling:
  458. from watchdog.observers.polling import PollingObserver as Observer
  459. else:
  460. from watchdog.observers import Observer
  461. from watchdog.tricks import AutoRestartTrick
  462. import signal
  463. if not args.directories:
  464. args.directories = ['.']
  465. # Allow either signal name or number.
  466. if args.signal.startswith("SIG"):
  467. stop_signal = getattr(signal, args.signal)
  468. else:
  469. stop_signal = int(args.signal)
  470. # Handle SIGTERM in the same manner as SIGINT so that
  471. # this program has a chance to stop the child process.
  472. def handle_sigterm(_signum, _frame):
  473. raise KeyboardInterrupt()
  474. signal.signal(signal.SIGTERM, handle_sigterm)
  475. patterns, ignore_patterns = parse_patterns(args.patterns,
  476. args.ignore_patterns)
  477. command = [args.command]
  478. command.extend(args.command_args)
  479. handler = AutoRestartTrick(command=command,
  480. patterns=patterns,
  481. ignore_patterns=ignore_patterns,
  482. ignore_directories=args.ignore_directories,
  483. stop_signal=stop_signal,
  484. kill_after=args.kill_after)
  485. handler.start()
  486. observer = Observer(timeout=args.timeout)
  487. observe_with(observer, handler, args.directories, args.recursive)
  488. handler.stop()
  489. epilog = """Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>.
  490. Copyright 2012 Google, Inc.
  491. Licensed under the terms of the Apache license, version 2.0. Please see
  492. LICENSE in the source code for more information."""
  493. parser = ArghParser(epilog=epilog)
  494. parser.add_commands([tricks_from,
  495. tricks_generate_yaml,
  496. log,
  497. shell_command,
  498. auto_restart])
  499. parser.add_argument('--version',
  500. action='version',
  501. version='%(prog)s ' + VERSION_STRING)
  502. def main():
  503. """Entry-point function."""
  504. parser.dispatch()
  505. if __name__ == '__main__':
  506. main()