hupper-1.9.1/0000755€Déíè€bP^q0000000000013562615436016627 5ustar michaelDA\Domain Users00000000000000hupper-1.9.1/.coveragerc0000644€Déíè€bP^q0000000027413257220166020744 0ustar michaelDA\Domain Users00000000000000[run] parallel = true source = hupper tests omit = src/hupper/winapi.py [paths] source = src/hupper */site-packages/hupper [report] show_missing = true precision = 2 hupper-1.9.1/.flake80000644€Déíè€bP^q0000000056513465114453020003 0ustar michaelDA\Domain Users00000000000000[flake8] max-line-length = 79 ignore = # E203: whitespace before ':' (black fails to be PEP8 compliant) E203 # E731: do not assign a lambda expression, use a def E731 # W503: line break before binary operator (flake8 is not PEP8 compliant) W503 # W504: line break after binary operator (flake8 is not PEP8 compliant) W504 show-source = True hupper-1.9.1/.travis.yml0000644€Déíè€bP^q0000000115313441505433020727 0ustar michaelDA\Domain Users00000000000000sudo: false cache: directories: - $HOME/.cache/pip language: python matrix: include: - python: '3.7' env: TOXENV=py37 dist: xenial sudo: true - python: '3.6' env: TOXENV=py36 - python: '3.5' env: TOXENV=py35 - python: '3.4' env: TOXENV=py34 - python: '2.7' env: TOXENV=py27 - python: 'pypy3' env: TOXENV=pypy3 - python: 'pypy' env: TOXENV=pypy - python: '3.6' env: TOXENV=py27,py36,coverage - python: '3.6' env: TOXENV=docs - python: '3.6' env: TOXENV=lint install: pip install tox script: tox hupper-1.9.1/CHANGES.rst0000644€Déíè€bP^q0000002220213562615361020424 0ustar michaelDA\Domain Users000000000000001.9.1 (2019-11-12) ================== - Support some scenarios in which user code is symlinked ``site-packages``. These were previously being ignored by the file monitor but should now be tracked. See https://github.com/Pylons/hupper/pull/61 1.9 (2019-10-14) ================ - Support ``--shutdown-interval`` on the ``hupper`` CLI. See https://github.com/Pylons/hupper/pull/56 - Support ``--reload-interval`` on the ``hupper`` CLI. See https://github.com/Pylons/hupper/pull/59 - Do not choke when stdin is not a TTY while waiting for changes after a crash. For example, when running in Docker Compose. See https://github.com/Pylons/hupper/pull/58 1.8.1 (2019-06-12) ================== - Do not show the ``KeyboardInterrupt`` stacktrace when killing ``hupper`` while waiting for a reload. 1.8 (2019-06-11) ================ - If the worker process crashes, ``hupper`` can be forced to reload the worker by pressing the ``ENTER`` key in the terminal instead of waiting to change a file. See https://github.com/Pylons/hupper/pull/53 1.7 (2019-06-04) ================ - On Python 3.5+ support recursive glob syntax in ``reloader.watch_files``. See https://github.com/Pylons/hupper/pull/52 1.6.1 (2019-03-11) ================== - If the worker crashes immediately, sometimes ``hupper`` would go into a restart loop instead of waiting for a code change. See https://github.com/Pylons/hupper/pull/50 1.6 (2019-03-06) ================ - On systems that support ``SIGKILL`` and ``SIGTERM`` (not Windows), ``hupper`` will now send a ``SIGKILL`` to the worker process as a last resort. Normally, a ``SIGINT`` (Ctrl-C) or ``SIGTERM`` (on reload) will kill the worker. If, within ``shutdown_interval`` seconds, the worker doesn't exit, it will receive a ``SIGKILL``. See https://github.com/Pylons/hupper/pull/48 - Support a ``logger`` argument to ``hupper.start_reloader`` to override the default logger that outputs messages to ``sys.stderr``. See https://github.com/Pylons/hupper/pull/49 1.5 (2019-02-16) ================ - Add support for ignoring custom patterns via the new ``ignore_files`` option on ``hupper.start_reloader``. The ``hupper`` cli also supports ignoring files via the ``-x`` option. See https://github.com/Pylons/hupper/pull/46 1.4.2 (2018-11-26) ================== - Fix a bug prompting the "ignoring corrupted payload from watchman" message and placing the file monitor in an unrecoverable state when a change triggered a watchman message > 4096 bytes. See https://github.com/Pylons/hupper/pull/44 1.4.1 (2018-11-11) ================== - Stop ignoring a few paths that may not be system paths in cases where the virtualenv is the root of your project. See https://github.com/Pylons/hupper/pull/42 1.4 (2018-10-26) ================ - Ignore changes to any system / installed files. This includes mostly changes to any files in the stdlib and ``site-packages``. Anything that is installed in editable mode or not installed at all will still be monitored. This drastically reduces the number of files that ``hupper`` needs to monitor. See https://github.com/Pylons/hupper/pull/40 1.3.1 (2018-10-05) ================== - Support Python 3.7. - Avoid a restart-loop if the app is failing to restart on certain systems. There was a race where ``hupper`` failed to detect that the app was crashing and thus fell into its restart logic when the user manually triggers an immediate reload. See https://github.com/Pylons/hupper/pull/37 - Ignore corrupted packets coming from watchman that occur in semi-random scenarios. See https://github.com/Pylons/hupper/pull/38 1.3 (2018-05-21) ================ - Added watchman support via ``hupper.watchman.WatchmanFileMonitor``. This is the new preferred file monitor on systems supporting unix sockets. See https://github.com/Pylons/hupper/pull/32 - The ``hupper.watchdog.WatchdogFileMonitor`` will now output some info when it receives ulimit or other errors from ``watchdog``. See https://github.com/Pylons/hupper/pull/33 - Allow ``-q`` and ``-v`` cli options to control verbosity. See https://github.com/Pylons/hupper/pull/33 - Pass a ``logger`` value to the ``hupper.interfaces.IFileMonitorFactory``. This is an instance of ``hupper.interfaces.ILogger`` and can be used by file monitors to output errors and debug information. See https://github.com/Pylons/hupper/pull/33 1.2 (2018-05-01) ================ - Track only Python source files. Previously ``hupper`` would track all pyc and py files. Now, if a pyc file is found then the equivalent source file is searched and, if found, the pyc file is ignored. See https://github.com/Pylons/hupper/pull/31 - Allow overriding the default monitor lookup by specifying the ``HUPPER_DEFAULT_MONITOR`` environment variable as a Python dotted-path to a monitor factory. For example, ``HUPPER_DEFAULT_MONITOR=hupper.polling.PollingFileMonitor``. See https://github.com/Pylons/hupper/pull/29 - Backward-incompatible changes to the ``hupper.interfaces.IFileMonitorFactory`` API to pass arbitrary kwargs to the factory. See https://github.com/Pylons/hupper/pull/29 1.1 (2018-03-29) ================ - Support ``-w`` on the CLI to watch custom file paths. See https://github.com/Pylons/hupper/pull/28 1.0 (2017-05-18) ================ - Copy ``sys.path`` to the worker process and ensure ``hupper`` is on the ``PYTHONPATH`` so that the subprocess can import it to start the worker. This fixes an issue with how ``zc.buildout`` injects dependencies into a process which is done entirely by ``sys.path`` manipulation. See https://github.com/Pylons/hupper/pull/27 0.5 (2017-05-10) ================ - On non-windows systems ensure an exec occurs so that the worker does not share the same process space as the reloader causing certain code that is imported in both to not ever be reloaded. Under the hood this was a significant rewrite to use subprocess instead of multiprocessing. See https://github.com/Pylons/hupper/pull/23 0.4.4 (2017-03-10) ================== - Fix some versions of Windows which were failing to duplicate stdin to the subprocess and crashing. https://github.com/Pylons/hupper/pull/16 0.4.3 (2017-03-07) ================== - Fix pdb and other readline-based programs to operate properly. See https://github.com/Pylons/hupper/pull/15 0.4.2 (2017-01-24) ================== - Pause briefly after receiving a SIGINT to allow the worker to kill itself. If it does not die then it is terminated. See https://github.com/Pylons/hupper/issues/11 - Python 3.6 compatibility. 0.4.1 (2017-01-03) ================== - Handle errors that may occur when using watchdog to observe non-existent folders. 0.4.0 (2017-01-02) ================== - Support running any Python module via ``hupper -m ``. This is equivalent to ``python -m`` except will fully reload the process when files change. See https://github.com/Pylons/hupper/pull/8 0.3.6 (2016-12-18) ================== - Read the traceback for unknown files prior to crashing. If an import crashes due to a module-scope exception the file that caused the crash would not be tracked but this should help. 0.3.5 (2016-12-17) ================== - Attempt to send imported paths to the monitor process before crashing to avoid cases where the master is waiting for changes in files that it never started monitoring. 0.3.4 (2016-11-21) ================== - Add support for globbing using the stdlib ``glob`` module. On Python 3.5+ this allows recursive globs using ``**``. Prior to this, the globbing is more limited. 0.3.3 (2016-11-19) ================== - Fixed a runtime failure on Windows 32-bit systems. 0.3.2 (2016-11-15) ================== - Support triggering reloads via SIGHUP when hupper detected a crash and is waiting for a file to change. - Setup the reloader proxy prior to importing the worker's module. This should allow some work to be done at module-scope instead of in the callable. 0.3.1 (2016-11-06) ================== - Fix package long description on PyPI. - Ensure that the stdin file handle is inheritable incase the "spawn" variant of multiprocessing is enabled. 0.3 (2016-11-06) ================ - Disable bytecode compiling of files imported by the worker process. This should not be necessary when developing and it was causing the process to restart twice on Windows due to how it handles pyc timestamps. - Fix hupper's support for forwarding stdin to the worker processes on Python < 3.5 on Windows. - Fix some possible file descriptor leakage. - Simplify the ``hupper.interfaces.IFileMonitor`` interface by internalizing some of the hupper-specific integrations. They can now focus on just looking for changes. - Add the ``hupper.interfaces.IFileMonitorFactory`` interface to improve the documentation for the ``callback`` argument required by ``hupper.interfaces.IFileMonitor``. 0.2 (2016-10-26) ================ - Windows support! - Added support for `watchdog `_ if it's installed to do inotify-style file monitoring. This is an optional dependency and ``hupper`` will fallback to using polling if it's not available. 0.1 (2016-10-21) ================ - Initial release. hupper-1.9.1/CONTRIBUTING.rst0000644€Déíè€bP^q0000000574413257220166021273 0ustar michaelDA\Domain Users00000000000000.. highlight:: shell ============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/Pylons/hupper/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "feature" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ hupper could always use more documentation, whether as part of the official hupper docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/Pylons/hupper/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `hupper` for local development. 1. Fork the `hupper` repo on GitHub. 2. Clone your fork locally:: $ git clone git@github.com:your_name_here/hupper.git 3. Install your local copy into a virtualenv:: $ python3 -m venv env $ env/bin/pip install -e .[docs,testing] $ env/bin/pip install tox 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ env/bin/tox 6. Add your name to the ``CONTRIBUTORS.txt`` file in the root of the repository. 7. Commit your changes and push your branch to GitHub:: $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature 8. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 2.7, 3.4 and 3.5, and for PyPy. Check https://travis-ci.org/Pylons/hupper/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ env/bin/py.test tests.test_hupper hupper-1.9.1/CONTRIBUTORS.txt0000644€Déíè€bP^q0000001163013562615256021326 0ustar michaelDA\Domain Users00000000000000Pylons Project Contributor Agreement ==================================== The submitter agrees by adding his or her name within the section below named "Contributors" and submitting the resulting modified document to the canonical shared repository location for this software project (whether directly, as a user with "direct commit access", or via a "pull request"), he or she is signing a contract electronically. The submitter becomes a Contributor after a) he or she signs this document by adding their name beneath the "Contributors" section below, and b) the resulting document is accepted into the canonical version control repository. Treatment of Account -------------------- Contributor will not allow anyone other than the Contributor to use his or her username or source repository login to submit code to a Pylons Project source repository. Should Contributor become aware of any such use, Contributor will immediately notify Agendaless Consulting. Notification must be performed by sending an email to webmaster@agendaless.com. Until such notice is received, Contributor will be presumed to have taken all actions made through Contributor's account. If the Contributor has direct commit access, Agendaless Consulting will have complete control and discretion over capabilities assigned to Contributor's account, and may disable Contributor's account for any reason at any time. Legal Effect of Contribution ---------------------------- Upon submitting a change or new work to a Pylons Project source Repository (a "Contribution"), you agree to assign, and hereby do assign, a one-half interest of all right, title and interest in and to copyright and other intellectual property rights with respect to your new and original portions of the Contribution to Agendaless Consulting. You and Agendaless Consulting each agree that the other shall be free to exercise any and all exclusive rights in and to the Contribution, without accounting to one another, including without limitation, the right to license the Contribution to others under the MIT License. This agreement shall run with title to the Contribution. Agendaless Consulting does not convey to you any right, title or interest in or to the Program or such portions of the Contribution that were taken from the Program. Your transmission of a submission to the Pylons Project source Repository and marks of identification concerning the Contribution itself constitute your intent to contribute and your assignment of the work in accordance with the provisions of this Agreement. License Terms ------------- Code committed to the Pylons Project source repository (Committed Code) must be governed by the MIT License or another license acceptable to Agendaless Consulting. Until Agendaless Consulting declares in writing an acceptable license other than the MIT License, only the MIT License shall be used. A list of exceptions is detailed within the "Licensing Exceptions" section of this document, if one exists. Representations, Warranty, and Indemnification ---------------------------------------------- Contributor represents and warrants that the Committed Code does not violate the rights of any person or entity, and that the Contributor has legal authority to enter into this Agreement and legal authority over Contributed Code. Further, Contributor indemnifies Agendaless Consulting against violations. Cryptography ------------ Contributor understands that cryptographic code may be subject to government regulations with which Agendaless Consulting and/or entities using Committed Code must comply. Any code which contains any of the items listed below must not be checked-in until Agendaless Consulting staff has been notified and has approved such contribution in writing. - Cryptographic capabilities or features - Calls to cryptographic features - User interface elements which provide context relating to cryptography - Code which may, under casual inspection, appear to be cryptographic. Notices ------- Contributor confirms that any notices required will be included in any Committed Code. Licensing Exceptions ==================== Code committed within the ``docs/`` subdirectory of the hupper source control repository and "docstrings" which appear in the documentation generated by running "make" within this directory are licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License (http://creativecommons.org/licenses/by-nc-sa/3.0/us/). List of Contributors ==================== The below-signed are contributors to a code repository that is part of the project named "hupper". Each below-signed contributor has read, understand and agrees to the terms above in the section within this document entitled "Pylons Project Contributor Agreement" as of the date beside his or her name. Contributors ------------ - Michael Merickel (2016-10-21) - Bert JW Regeer (2017-05-17) - Jens Carl (2017-05-22) - Eric Atkin (2019-02-15) - Yeray Díaz Díaz (2019-10-03) hupper-1.9.1/LICENSE.txt0000644€Déíè€bP^q0000000204413104656445020447 0ustar michaelDA\Domain Users00000000000000Copyright (c) 2017 Michael Merickel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. hupper-1.9.1/MANIFEST.in0000644€Déíè€bP^q0000000050213441505433020351 0ustar michaelDA\Domain Users00000000000000graft src/hupper graft tests graft docs prune docs/_build include README.rst include CHANGES.rst include LICENSE.txt include CONTRIBUTING.rst include CONTRIBUTORS.txt include pyproject.toml setup.cfg include .coveragerc .flake8 include tox.ini appveyor.yml .travis.yml rtd.txt recursive-exclude * __pycache__ *.py[cod] hupper-1.9.1/PKG-INFO0000644€Déíè€bP^q0000003544513562615436017737 0ustar michaelDA\Domain Users00000000000000Metadata-Version: 2.1 Name: hupper Version: 1.9.1 Summary: Integrated process monitor for developing and reloading daemons. Home-page: https://github.com/Pylons/hupper Author: Michael Merickel Author-email: pylons-discuss@googlegroups.com License: MIT Description: ====== hupper ====== .. image:: https://img.shields.io/pypi/v/hupper.svg :target: https://pypi.python.org/pypi/hupper .. image:: https://img.shields.io/travis/Pylons/hupper/master.svg :target: https://travis-ci.org/Pylons/hupper .. image:: https://readthedocs.org/projects/hupper/badge/?version=latest :target: https://readthedocs.org/projects/hupper/?badge=latest :alt: Documentation Status ``hupper`` is an integrated process monitor that will track changes to any imported Python files in ``sys.modules`` as well as custom paths. When files are changed the process is restarted. Command-line Usage ================== Hupper can load any Python code similar to ``python -m `` by using the ``hupper -m `` program. .. code-block:: console $ hupper -m myapp Starting monitor for PID 23982. API Usage ========= Start by defining an entry point for your process. This must be an importable path in string format. For example, ``myapp.scripts.serve.main``. .. code-block:: python # myapp/scripts/serve.py import sys import hupper import waitress def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) yield b'hello' def main(args=sys.argv[1:]): if '--reload' in args: # start_reloader will only return in a monitored subprocess reloader = hupper.start_reloader('myapp.scripts.serve.main') # monitor an extra file reloader.watch_files(['foo.ini']) waitress.serve(wsgi_app) Acknowledgments =============== ``hupper`` is inspired by initial work done by Carl J Meyer and David Glick during a Pycon sprint and is built to be a more robust and generic version of Ian Bicking's excellent PasteScript ``paste serve --reload`` and Pyramid's ``pserve --reload``. 1.9.1 (2019-11-12) ================== - Support some scenarios in which user code is symlinked ``site-packages``. These were previously being ignored by the file monitor but should now be tracked. See https://github.com/Pylons/hupper/pull/61 1.9 (2019-10-14) ================ - Support ``--shutdown-interval`` on the ``hupper`` CLI. See https://github.com/Pylons/hupper/pull/56 - Support ``--reload-interval`` on the ``hupper`` CLI. See https://github.com/Pylons/hupper/pull/59 - Do not choke when stdin is not a TTY while waiting for changes after a crash. For example, when running in Docker Compose. See https://github.com/Pylons/hupper/pull/58 1.8.1 (2019-06-12) ================== - Do not show the ``KeyboardInterrupt`` stacktrace when killing ``hupper`` while waiting for a reload. 1.8 (2019-06-11) ================ - If the worker process crashes, ``hupper`` can be forced to reload the worker by pressing the ``ENTER`` key in the terminal instead of waiting to change a file. See https://github.com/Pylons/hupper/pull/53 1.7 (2019-06-04) ================ - On Python 3.5+ support recursive glob syntax in ``reloader.watch_files``. See https://github.com/Pylons/hupper/pull/52 1.6.1 (2019-03-11) ================== - If the worker crashes immediately, sometimes ``hupper`` would go into a restart loop instead of waiting for a code change. See https://github.com/Pylons/hupper/pull/50 1.6 (2019-03-06) ================ - On systems that support ``SIGKILL`` and ``SIGTERM`` (not Windows), ``hupper`` will now send a ``SIGKILL`` to the worker process as a last resort. Normally, a ``SIGINT`` (Ctrl-C) or ``SIGTERM`` (on reload) will kill the worker. If, within ``shutdown_interval`` seconds, the worker doesn't exit, it will receive a ``SIGKILL``. See https://github.com/Pylons/hupper/pull/48 - Support a ``logger`` argument to ``hupper.start_reloader`` to override the default logger that outputs messages to ``sys.stderr``. See https://github.com/Pylons/hupper/pull/49 1.5 (2019-02-16) ================ - Add support for ignoring custom patterns via the new ``ignore_files`` option on ``hupper.start_reloader``. The ``hupper`` cli also supports ignoring files via the ``-x`` option. See https://github.com/Pylons/hupper/pull/46 1.4.2 (2018-11-26) ================== - Fix a bug prompting the "ignoring corrupted payload from watchman" message and placing the file monitor in an unrecoverable state when a change triggered a watchman message > 4096 bytes. See https://github.com/Pylons/hupper/pull/44 1.4.1 (2018-11-11) ================== - Stop ignoring a few paths that may not be system paths in cases where the virtualenv is the root of your project. See https://github.com/Pylons/hupper/pull/42 1.4 (2018-10-26) ================ - Ignore changes to any system / installed files. This includes mostly changes to any files in the stdlib and ``site-packages``. Anything that is installed in editable mode or not installed at all will still be monitored. This drastically reduces the number of files that ``hupper`` needs to monitor. See https://github.com/Pylons/hupper/pull/40 1.3.1 (2018-10-05) ================== - Support Python 3.7. - Avoid a restart-loop if the app is failing to restart on certain systems. There was a race where ``hupper`` failed to detect that the app was crashing and thus fell into its restart logic when the user manually triggers an immediate reload. See https://github.com/Pylons/hupper/pull/37 - Ignore corrupted packets coming from watchman that occur in semi-random scenarios. See https://github.com/Pylons/hupper/pull/38 1.3 (2018-05-21) ================ - Added watchman support via ``hupper.watchman.WatchmanFileMonitor``. This is the new preferred file monitor on systems supporting unix sockets. See https://github.com/Pylons/hupper/pull/32 - The ``hupper.watchdog.WatchdogFileMonitor`` will now output some info when it receives ulimit or other errors from ``watchdog``. See https://github.com/Pylons/hupper/pull/33 - Allow ``-q`` and ``-v`` cli options to control verbosity. See https://github.com/Pylons/hupper/pull/33 - Pass a ``logger`` value to the ``hupper.interfaces.IFileMonitorFactory``. This is an instance of ``hupper.interfaces.ILogger`` and can be used by file monitors to output errors and debug information. See https://github.com/Pylons/hupper/pull/33 1.2 (2018-05-01) ================ - Track only Python source files. Previously ``hupper`` would track all pyc and py files. Now, if a pyc file is found then the equivalent source file is searched and, if found, the pyc file is ignored. See https://github.com/Pylons/hupper/pull/31 - Allow overriding the default monitor lookup by specifying the ``HUPPER_DEFAULT_MONITOR`` environment variable as a Python dotted-path to a monitor factory. For example, ``HUPPER_DEFAULT_MONITOR=hupper.polling.PollingFileMonitor``. See https://github.com/Pylons/hupper/pull/29 - Backward-incompatible changes to the ``hupper.interfaces.IFileMonitorFactory`` API to pass arbitrary kwargs to the factory. See https://github.com/Pylons/hupper/pull/29 1.1 (2018-03-29) ================ - Support ``-w`` on the CLI to watch custom file paths. See https://github.com/Pylons/hupper/pull/28 1.0 (2017-05-18) ================ - Copy ``sys.path`` to the worker process and ensure ``hupper`` is on the ``PYTHONPATH`` so that the subprocess can import it to start the worker. This fixes an issue with how ``zc.buildout`` injects dependencies into a process which is done entirely by ``sys.path`` manipulation. See https://github.com/Pylons/hupper/pull/27 0.5 (2017-05-10) ================ - On non-windows systems ensure an exec occurs so that the worker does not share the same process space as the reloader causing certain code that is imported in both to not ever be reloaded. Under the hood this was a significant rewrite to use subprocess instead of multiprocessing. See https://github.com/Pylons/hupper/pull/23 0.4.4 (2017-03-10) ================== - Fix some versions of Windows which were failing to duplicate stdin to the subprocess and crashing. https://github.com/Pylons/hupper/pull/16 0.4.3 (2017-03-07) ================== - Fix pdb and other readline-based programs to operate properly. See https://github.com/Pylons/hupper/pull/15 0.4.2 (2017-01-24) ================== - Pause briefly after receiving a SIGINT to allow the worker to kill itself. If it does not die then it is terminated. See https://github.com/Pylons/hupper/issues/11 - Python 3.6 compatibility. 0.4.1 (2017-01-03) ================== - Handle errors that may occur when using watchdog to observe non-existent folders. 0.4.0 (2017-01-02) ================== - Support running any Python module via ``hupper -m ``. This is equivalent to ``python -m`` except will fully reload the process when files change. See https://github.com/Pylons/hupper/pull/8 0.3.6 (2016-12-18) ================== - Read the traceback for unknown files prior to crashing. If an import crashes due to a module-scope exception the file that caused the crash would not be tracked but this should help. 0.3.5 (2016-12-17) ================== - Attempt to send imported paths to the monitor process before crashing to avoid cases where the master is waiting for changes in files that it never started monitoring. 0.3.4 (2016-11-21) ================== - Add support for globbing using the stdlib ``glob`` module. On Python 3.5+ this allows recursive globs using ``**``. Prior to this, the globbing is more limited. 0.3.3 (2016-11-19) ================== - Fixed a runtime failure on Windows 32-bit systems. 0.3.2 (2016-11-15) ================== - Support triggering reloads via SIGHUP when hupper detected a crash and is waiting for a file to change. - Setup the reloader proxy prior to importing the worker's module. This should allow some work to be done at module-scope instead of in the callable. 0.3.1 (2016-11-06) ================== - Fix package long description on PyPI. - Ensure that the stdin file handle is inheritable incase the "spawn" variant of multiprocessing is enabled. 0.3 (2016-11-06) ================ - Disable bytecode compiling of files imported by the worker process. This should not be necessary when developing and it was causing the process to restart twice on Windows due to how it handles pyc timestamps. - Fix hupper's support for forwarding stdin to the worker processes on Python < 3.5 on Windows. - Fix some possible file descriptor leakage. - Simplify the ``hupper.interfaces.IFileMonitor`` interface by internalizing some of the hupper-specific integrations. They can now focus on just looking for changes. - Add the ``hupper.interfaces.IFileMonitorFactory`` interface to improve the documentation for the ``callback`` argument required by ``hupper.interfaces.IFileMonitor``. 0.2 (2016-10-26) ================ - Windows support! - Added support for `watchdog `_ if it's installed to do inotify-style file monitoring. This is an optional dependency and ``hupper`` will fallback to using polling if it's not available. 0.1 (2016-10-21) ================ - Initial release. Keywords: server daemon autoreload reloader hup file watch process Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.* Provides-Extra: docs Provides-Extra: testing hupper-1.9.1/README.rst0000644€Déíè€bP^q0000000350013465114453020307 0ustar michaelDA\Domain Users00000000000000====== hupper ====== .. image:: https://img.shields.io/pypi/v/hupper.svg :target: https://pypi.python.org/pypi/hupper .. image:: https://img.shields.io/travis/Pylons/hupper/master.svg :target: https://travis-ci.org/Pylons/hupper .. image:: https://readthedocs.org/projects/hupper/badge/?version=latest :target: https://readthedocs.org/projects/hupper/?badge=latest :alt: Documentation Status ``hupper`` is an integrated process monitor that will track changes to any imported Python files in ``sys.modules`` as well as custom paths. When files are changed the process is restarted. Command-line Usage ================== Hupper can load any Python code similar to ``python -m `` by using the ``hupper -m `` program. .. code-block:: console $ hupper -m myapp Starting monitor for PID 23982. API Usage ========= Start by defining an entry point for your process. This must be an importable path in string format. For example, ``myapp.scripts.serve.main``. .. code-block:: python # myapp/scripts/serve.py import sys import hupper import waitress def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) yield b'hello' def main(args=sys.argv[1:]): if '--reload' in args: # start_reloader will only return in a monitored subprocess reloader = hupper.start_reloader('myapp.scripts.serve.main') # monitor an extra file reloader.watch_files(['foo.ini']) waitress.serve(wsgi_app) Acknowledgments =============== ``hupper`` is inspired by initial work done by Carl J Meyer and David Glick during a Pycon sprint and is built to be a more robust and generic version of Ian Bicking's excellent PasteScript ``paste serve --reload`` and Pyramid's ``pserve --reload``. hupper-1.9.1/appveyor.yml0000644€Déíè€bP^q0000000125713562615256021224 0ustar michaelDA\Domain Users00000000000000environment: matrix: - PYTHON: "C:\\Python37" TOXENV: "py37" - PYTHON: "C:\\Python36" TOXENV: "py36" - PYTHON: "C:\\Python35" TOXENV: "py35" - PYTHON: "C:\\Python27" TOXENV: "py27" - PYTHON: "C:\\Python37-x64" TOXENV: "py37" - PYTHON: "C:\\Python36-x64" TOXENV: "py36" - PYTHON: "C:\\Python35-x64" TOXENV: "py35" - PYTHON: "C:\\Python27-x64" TOXENV: "py27" cache: - '%LOCALAPPDATA%\pip\Cache' version: '{branch}.{build}' install: - "%PYTHON%\\python.exe -m pip install -U pip" - "%PYTHON%\\python.exe -m pip install -U tox virtualenv" build: off test_script: - "%PYTHON%\\Scripts\\tox.exe" hupper-1.9.1/docs/0000755€Déíè€bP^q0000000000013562615436017557 5ustar michaelDA\Domain Users00000000000000hupper-1.9.1/docs/Makefile0000644€Déíè€bP^q0000001515213002175122021201 0ustar michaelDA\Domain Users00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/hupper.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/hupper.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/hupper" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/hupper" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." hupper-1.9.1/docs/_static/0000755€Déíè€bP^q0000000000013562615436021205 5ustar michaelDA\Domain Users00000000000000hupper-1.9.1/docs/_static/.keep0000644€Déíè€bP^q0000000000013021336677022115 0ustar michaelDA\Domain Users00000000000000hupper-1.9.1/docs/api.rst0000644€Déíè€bP^q0000000153313441505433021053 0ustar michaelDA\Domain Users00000000000000================== :mod:`hupper` API ================== .. automodule:: hupper .. autofunction:: start_reloader .. autofunction:: is_active .. autofunction:: get_reloader .. autofunction:: is_watchdog_supported .. autofunction:: is_watchman_supported .. automodule:: hupper.reloader .. autoclass:: Reloader :members: .. automodule:: hupper.interfaces .. autoclass:: IReloaderProxy :members: :special-members: .. autoclass:: IFileMonitor :members: :special-members: .. autoclass:: IFileMonitorFactory :members: :special-members: .. autoclass:: ILogger :members: :special-members: .. automodule:: hupper.polling .. autoclass:: PollingFileMonitor .. automodule:: hupper.watchdog .. autoclass:: WatchdogFileMonitor .. automodule:: hupper.watchman .. autoclass:: WatchmanFileMonitor hupper-1.9.1/docs/changes.rst0000644€Déíè€bP^q0000000006513002175122021700 0ustar michaelDA\Domain Users00000000000000======= Changes ======= .. include:: ../CHANGES.rst hupper-1.9.1/docs/conf.py0000644€Déíè€bP^q0000002026313355727765021072 0ustar michaelDA\Domain Users00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # hupper documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import pkg_resources # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) # ensure the code is importable for use with autodoc import hupper # -- General configuration --------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'hupper' copyright = u'2017, Michael Merickel' # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. version = pkg_resources.get_distribution('hupper').version # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to # some non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built # documents. #keep_warnings = False # -- Options for HTML output ------------------------------------------- # Add and use Pylons theme sys.path.append(os.path.abspath('_themes')) import pylons_sphinx_themes html_theme_path = pylons_sphinx_themes.get_html_themes_path() html_theme = 'pylons' html_theme_options = { 'github_url': 'https://github.com/Pylons/hupper' } # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as # html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the # top of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon # of the docs. This file should be a Windows icon file (.ico) being # 16x16 or 32x32 pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) # here, relative to this directory. They are copied after the builtin # static files, so a file named "default.css" will overwrite the builtin # "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names # to template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. # Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. # Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages # will contain a tag referring to it. The value of this option # must be the base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'hupperdoc' # -- Options for LaTeX output ------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', 'hupper.tex', u'hupper Documentation', u'Michael Merickel', 'manual'), ] # The name of an image file (relative to this directory) to place at # the top of the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings # are parts, not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'hupper', u'hupper Documentation', [u'Michael Merickel'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ---------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'hupper', u'hupper Documentation', u'Michael Merickel', 'hupper', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False hupper-1.9.1/docs/contributing.rst0000644€Déíè€bP^q0000000004113002175122022771 0ustar michaelDA\Domain Users00000000000000.. include:: ../CONTRIBUTING.rst hupper-1.9.1/docs/index.rst0000644€Déíè€bP^q0000001164013441505433021411 0ustar michaelDA\Domain Users00000000000000====== hupper ====== ``hupper`` is monitor for your Python process. When files change, the process will be restarted. It can be extended to watch arbitrary files. Reloads can also be triggered manually from code. Builtin file monitors (in order of preference): - :ref:`watchman_support` - :ref:`watchdog_support` - :ref:`polling_support` Installation ============ Stable release -------------- To install hupper, run this command in your terminal: .. code-block:: console $ pip install hupper If you don't have `pip`_ installed, this `Python installation guide`_ can guide you through the process. .. _pip: https://pip.pypa.io .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ From sources ------------ The sources for hupper can be downloaded from the `Github repo`_. .. code-block:: console $ git clone https://github.com/Pylons/hupper.git Once you have a copy of the source, you can install it with: .. code-block:: console $ pip install -e . .. _Github repo: https://github.com/Pylons/hupper Builtin File Monitors ===================== .. _watchman_support: Watchman -------- If the `watchman `_ daemon is running, it is the preferred mechanism for monitoring files. On MacOS it can be installed via: .. code-block:: console $ brew install watchman Implementation: :class:`hupper.watchman.WatchmanFileMonitor` .. _watchdog_support: Watchdog -------- If `watchdog `_ is installed, it will be used to more efficiently watch for changes to files. .. code-block:: console $ pip install watchdog This is an optional dependency and if it's not installed, then ``hupper`` will fallback to less efficient polling of the filesystem. Implementation: :class:`hupper.watchdog.WatchdogFileMonitor` .. _polling_support: Polling ------- The least efficient but most portable approach is to use basic file polling. The ``reload_interval`` parameter controls how often the filesystem is scanned and defaults to once per second. Implementation: :class:`hupper.polling.PollingFileMonitor` Command-line Usage ================== Hupper can load any Python code similar to ``python -m `` by using the ``hupper -m `` program. .. code-block:: console $ hupper -m myapp Starting monitor for PID 23982. API Usage ========= The reloading mechanism is implemented by forking worker processes from a parent monitor. Start by defining an entry point for your process. This must be an importable path in string format. For example, ``myapp.scripts.serve.main``: .. code-block:: python # myapp/scripts/serve.py import sys import hupper import waitress def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain']) yield [b'hello'] def main(args=sys.argv[1:]): if '--reload' in args: # start_reloader will only return in a monitored subprocess reloader = hupper.start_reloader('myapp.scripts.serve.main') # monitor an extra file reloader.watch_files(['foo.ini']) waitress.serve(wsgi_app) Many applications will tend to re-use the same startup code for both the monitor and the worker. As a convenience to support this use case, the :func:`hupper.start_reloader` function can be invoked both from the parent process as well as the worker. When called initially from the parent process, it will fork a new worker, then start the monitor and never return. When called from the worker process it will return a proxy object that can be used to communicate back to the monitor. Checking if the reloader is active ---------------------------------- :func:`hupper.is_active` will return ``True`` if the reloader is active and the current process may be reloaded. Controlling the monitor ----------------------- The worker processes may communicate back to the monitor and notify it of new files to watch. This can be done by acquiring a reference to the :class:`hupper.interfaces.IReloaderProxy` instance living in the worker process. The :func:`hupper.start_reloader` function will return the instance or :func:`hupper.get_reloader` can be used as well. Overriding the default file monitor ----------------------------------- .. versionadded:: 1.2 By default, ``hupper`` will auto-select the best file monitor based on what is available. The preferred order is ``watchdog`` then ``polling``. If ``watchdog`` is installed but you do not want to use it for any reason, you may override the default by specifying the monitor you wish to use instead in the ``HUPPER_DEFAULT_MONITOR`` environment variable. For example: .. code:: bash $ HUPPER_DEFAULT_MONITOR=hupper.polling.PollingFileMonitor hupper -m foo More Information ================ .. toctree:: :maxdepth: 1 api contributing changes Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` hupper-1.9.1/docs/make.bat0000644€Déíè€bP^q0000001447313002175122021153 0ustar michaelDA\Domain Users00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\hupper.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\hupper.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end hupper-1.9.1/pyproject.toml0000644€Déíè€bP^q0000000107013562615256021541 0ustar michaelDA\Domain Users00000000000000[build-system] requires = ["setuptools>=41.0.1", "wheel"] build-backend = "setuptools.build_meta" [tool.black] line-length = 79 skip-string-normalization = true py36 = false exclude = ''' /( \.git | \.mypy_cache | \.tox | \.venv | \.pytest_cache | dist | build | docs )/ ''' # This next section only exists for people that have their editors # automatically call isort, black already sorts entries on its own when run. [tool.isort] multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 combine_as_imports = true line_length = 79 hupper-1.9.1/rtd.txt0000644€Déíè€bP^q0000000001013500236412020131 0ustar michaelDA\Domain Users00000000000000.[docs] hupper-1.9.1/setup.cfg0000644€Déíè€bP^q0000000043213562615436020447 0ustar michaelDA\Domain Users00000000000000[bdist_wheel] universal = 1 [metadata] license_file = LICENSE.txt [check-manifest] ignore = .gitignore PKG-INFO *.egg-info *.egg-info/* ignore-default-rules = true [tool:pytest] python_files = test_*.py testpaths = src/hupper tests [egg_info] tag_build = tag_date = 0 hupper-1.9.1/setup.py0000644€Déíè€bP^q0000000332413562615366020345 0ustar michaelDA\Domain Users00000000000000from setuptools import setup, find_packages def readfile(name): with open(name) as f: return f.read() readme = readfile('README.rst') changes = readfile('CHANGES.rst') docs_require = ['watchdog', 'Sphinx', 'pylons-sphinx-themes'] tests_require = ['watchdog', 'pytest', 'pytest-cov', 'mock'] setup( name='hupper', version='1.9.1', description=( 'Integrated process monitor for developing and reloading daemons.' ), long_description=readme + '\n\n' + changes, author='Michael Merickel', author_email='pylons-discuss@googlegroups.com', url='https://github.com/Pylons/hupper', license='MIT', packages=find_packages('src', exclude=['tests']), package_dir={'': 'src'}, include_package_data=True, python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*', extras_require={'docs': docs_require, 'testing': tests_require}, entry_points={"console_scripts": ["hupper = hupper.cli:main"]}, zip_safe=False, keywords='server daemon autoreload reloader hup file watch process', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], ) hupper-1.9.1/src/0000755€Déíè€bP^q0000000000013562615436017416 5ustar michaelDA\Domain Users00000000000000hupper-1.9.1/src/hupper/0000755€Déíè€bP^q0000000000013562615436020721 5ustar michaelDA\Domain Users00000000000000hupper-1.9.1/src/hupper/__init__.py0000644€Déíè€bP^q0000000030113441505433023013 0ustar michaelDA\Domain Users00000000000000# public api # flake8: noqa from .utils import is_watchdog_supported from .utils import is_watchman_supported from .reloader import start_reloader from .worker import is_active, get_reloader hupper-1.9.1/src/hupper/cli.py0000644€Déíè€bP^q0000000347513562615256022053 0ustar michaelDA\Domain Users00000000000000import argparse import runpy import sys from .logger import LogLevel from .reloader import start_reloader def interval_parser(string): """Parses the shutdown or reload interval into an int greater than 0.""" msg = "Interval must be an int greater than 0" try: value = int(string) if value <= 0: raise argparse.ArgumentTypeError(msg) return value except ValueError: raise argparse.ArgumentTypeError(msg) def main(): parser = argparse.ArgumentParser() parser.add_argument("-m", dest="module", required=True) parser.add_argument("-w", dest="watch", action="append") parser.add_argument("-x", dest="ignore", action="append") parser.add_argument("-v", dest="verbose", action='store_true') parser.add_argument("-q", dest="quiet", action='store_true') parser.add_argument("--shutdown-interval", type=interval_parser) parser.add_argument("--reload-interval", type=interval_parser) args, unknown_args = parser.parse_known_args() if args.quiet: level = LogLevel.ERROR elif args.verbose: level = LogLevel.DEBUG else: level = LogLevel.INFO # start_reloader has defaults for some values so we avoid passing # arguments if we don't have to reloader_kw = {} if args.reload_interval is not None: reloader_kw['reload_interval'] = args.reload_interval if args.shutdown_interval is not None: reloader_kw['shutdown_interval'] = args.shutdown_interval reloader = start_reloader( "hupper.cli.main", verbose=level, ignore_files=args.ignore, **reloader_kw ) sys.argv[1:] = unknown_args sys.path.insert(0, "") if args.watch: reloader.watch_files(args.watch) return runpy.run_module(args.module, alter_sys=True, run_name="__main__") hupper-1.9.1/src/hupper/compat.py0000644€Déíè€bP^q0000000424613500236412022545 0ustar michaelDA\Domain Users00000000000000# flake8: noqa import imp import importlib import site import subprocess import sys import time PY2 = sys.version_info[0] == 2 WIN = sys.platform == 'win32' try: import queue except ImportError: import Queue as queue try: from _thread import interrupt_main except ImportError: from thread import interrupt_main try: from importlib.util import source_from_cache as get_py_path except ImportError: if PY2: get_py_path = lambda path: path[:-1] # fallback on python < 3.5 else: get_py_path = imp.source_from_cache try: import cPickle as pickle except ImportError: import pickle if PY2 or sys.version_info[1] < 5: from glob import glob as gg def glob(pathname, recursive=False): return gg(pathname) else: from glob import glob def get_site_packages(): # pragma: no cover try: paths = site.getsitepackages() if site.ENABLE_USER_SITE: paths.append(site.getusersitepackages()) return paths # virtualenv does not ship with a getsitepackages impl so we fallback # to using distutils if we can # https://github.com/pypa/virtualenv/issues/355 except Exception: try: from distutils.sysconfig import get_python_lib return [get_python_lib()] # just incase, don't fail here, it's not worth it except Exception: return [] ################################################ # cross-compatible metaclass implementation # Copyright (c) 2010-2012 Benjamin Peterson def with_metaclass(meta, base=object): """Create a base class with a metaclass.""" return meta("%sBase" % meta.__name__, (base,), {}) if PY2: def subprocess_wait_with_timeout(process, timeout): max_time = time.time() + timeout while process.poll() is None: dt = max_time - time.time() if dt <= 0: break if dt > 0.5: dt = 0.5 time.sleep(dt) return process.poll() else: def subprocess_wait_with_timeout(process, timeout): try: return process.wait(timeout) except subprocess.TimeoutExpired: pass hupper-1.9.1/src/hupper/interfaces.py0000644€Déíè€bP^q0000000342013300635224023400 0ustar michaelDA\Domain Users00000000000000import abc from .compat import with_metaclass class IReloaderProxy(with_metaclass(abc.ABCMeta)): @abc.abstractmethod def watch_files(self, files): """ Signal to the monitor to track some custom paths.""" @abc.abstractmethod def trigger_reload(self): """ Signal the monitor to execute a reload.""" class IFileMonitorFactory(with_metaclass(abc.ABCMeta)): def __call__(self, callback, **kw): """ Return an :class:`.IFileMonitor` instance. ``callback`` is a callable to be invoked by the ``IFileMonitor`` when file changes are detected. It should accept the path of the changed file as its only parameter. Extra keyword-only arguments: ``interval`` is the value of ``reload_interval`` passed to the reloader and may be used to control behavior in the file monitor. ``logger`` is an :class:`.ILogger` instance used to record runtime output. """ class IFileMonitor(with_metaclass(abc.ABCMeta)): @abc.abstractmethod def add_path(self, path): """ Start monitoring a new path.""" @abc.abstractmethod def start(self): """ Start the monitor. This method should not block.""" @abc.abstractmethod def stop(self): """ Trigger the monitor to stop. This should be called before invoking ``join``. """ @abc.abstractmethod def join(self): """ Block until the monitor has stopped.""" class ILogger(with_metaclass(abc.ABCMeta)): @abc.abstractmethod def error(self, msg): """ Record an error message.""" @abc.abstractmethod def info(self, msg): """ Record an informational message.""" @abc.abstractmethod def debug(self, msg): """ Record a debug-only message.""" hupper-1.9.1/src/hupper/ipc.py0000644€Déíè€bP^q0000002144513562615256022054 0ustar michaelDA\Domain Users00000000000000import io import imp import os import struct import sys import subprocess import threading from .compat import WIN from .compat import pickle from .compat import queue from .compat import subprocess_wait_with_timeout from .utils import is_stream_interactive from .utils import resolve_spec if WIN: # pragma: no cover import msvcrt from . import winapi class ProcessGroup(object): def __init__(self): self.h_job = winapi.CreateJobObject(None, None) info = winapi.JOBOBJECT_BASIC_LIMIT_INFORMATION() info.LimitFlags = winapi.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE extended_info = winapi.JOBOBJECT_EXTENDED_LIMIT_INFORMATION() extended_info.BasicLimitInformation = info winapi.SetInformationJobObject( self.h_job, winapi.JobObjectExtendedLimitInformation, extended_info, ) def add_child(self, pid): hp = winapi.OpenProcess(winapi.PROCESS_ALL_ACCESS, False, pid) try: return winapi.AssignProcessToJobObject(self.h_job, hp) except OSError as ex: if getattr(ex, 'winerror') == 5: # skip ACCESS_DENIED_ERROR on windows < 8 which occurs when # the process is already attached to another job pass else: raise def snapshot_termios(stream): pass def restore_termios(stream, state): pass def get_handle(fd): return msvcrt.get_osfhandle(fd) def open_handle(handle, mode): flags = 0 if 'w' not in mode and '+' not in mode: flags |= os.O_RDONLY if 'b' not in mode: flags |= os.O_TEXT if 'a' in mode: flags |= os.O_APPEND return msvcrt.open_osfhandle(handle, flags) else: import fcntl import termios class ProcessGroup(object): def add_child(self, pid): # nothing to do on *nix pass def snapshot_termios(stream): if is_stream_interactive(stream): state = termios.tcgetattr(stream.fileno()) return state def restore_termios(stream, state): if state and is_stream_interactive(stream): fd = stream.fileno() termios.tcflush(fd, termios.TCIOFLUSH) termios.tcsetattr(fd, termios.TCSANOW, state) def get_handle(fd): return fd def open_handle(handle, mode): return handle def _pipe(): r, w = os.pipe() set_inheritable(r, False) set_inheritable(w, False) return r, w def Pipe(): c2pr_fd, c2pw_fd = _pipe() p2cr_fd, p2cw_fd = _pipe() c1 = Connection(c2pr_fd, p2cw_fd) c2 = Connection(p2cr_fd, c2pw_fd) return c1, c2 class Connection(object): """ A connection to a bi-directional pipe. """ _packet_len = struct.Struct('Q') def __init__(self, r_fd, w_fd): self.r_fd = r_fd self.w_fd = w_fd def __getstate__(self): return { 'r_handle': get_handle(self.r_fd), 'w_handle': get_handle(self.w_fd), } def __setstate__(self, state): self.r_fd = open_handle(state['r_handle'], 'rb') self.w_fd = open_handle(state['w_handle'], 'wb') def activate(self): self.send_lock = threading.Lock() self.reader_queue = queue.Queue() self.reader_thread = threading.Thread(target=self._read_loop) self.reader_thread.daemon = True self.reader_thread.start() def close(self): close_fd(self.r_fd) close_fd(self.w_fd) def _recv_packet(self): buf = io.BytesIO() chunk = os.read(self.r_fd, self._packet_len.size) if not chunk: return size = remaining = self._packet_len.unpack(chunk)[0] while remaining > 0: chunk = os.read(self.r_fd, remaining) n = len(chunk) if n == 0: if remaining == size: raise EOFError else: raise IOError('got end of file during message') buf.write(chunk) remaining -= n return pickle.loads(buf.getvalue()) def _read_loop(self): try: while True: packet = self._recv_packet() if packet is None: break self.reader_queue.put(packet) except EOFError: pass self.reader_queue.put(None) def _write_packet(self, data): while data: n = os.write(self.w_fd, data) data = data[n:] def send(self, value): data = pickle.dumps(value) with self.send_lock: self._write_packet(self._packet_len.pack(len(data))) self._write_packet(data) return len(data) + self._packet_len.size def recv(self, timeout=None): packet = self.reader_queue.get(block=True, timeout=timeout) return packet def set_inheritable(fd, inheritable): # On py34+ we can use os.set_inheritable but < py34 we must polyfill # with fcntl and SetHandleInformation if hasattr(os, 'get_inheritable'): if os.get_inheritable(fd) != inheritable: os.set_inheritable(fd, inheritable) elif WIN: h = get_handle(fd) flags = winapi.HANDLE_FLAG_INHERIT if inheritable else 0 winapi.SetHandleInformation(h, winapi.HANDLE_FLAG_INHERIT, flags) else: flags = fcntl.fcntl(fd, fcntl.F_GETFD) if inheritable: new_flags = flags & ~fcntl.FD_CLOEXEC else: new_flags = flags | fcntl.FD_CLOEXEC if new_flags != flags: fcntl.fcntl(fd, fcntl.F_SETFD, new_flags) def close_fd(fd, raises=True): if fd is not None: try: os.close(fd) except Exception: # pragma: no cover if raises: raise def args_from_interpreter_flags(): """ Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions. """ flag_opt_map = { 'debug': 'd', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet': 'q', 'optimize': 'O', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag, 0) if v > 0: args.append('-' + opt * v) for opt in sys.warnoptions: args.append('-W' + opt) return args def get_command_line(**kwds): prog = 'from hupper.ipc import spawn_main; spawn_main(%s)' prog %= ', '.join('%s=%r' % item for item in kwds.items()) opts = args_from_interpreter_flags() args = [sys.executable] + opts + ['-c', prog] # ensure hupper is on the PYTHONPATH in the worker process self_path = os.path.abspath(imp.find_module('hupper')[1]) extra_py_paths = [os.path.dirname(self_path)] env = os.environ.copy() env['PYTHONPATH'] = ( os.pathsep.join(extra_py_paths) + os.pathsep + env.get('PYTHONPATH', '') ) return args, env def get_preparation_data(): data = {} data['sys.argv'] = sys.argv # multiprocessing does some work here to replace '' in sys.path with # os.getcwd() but it is not valid to assume that os.getcwd() at the time # hupper is imported is the starting folder of the process so for now # we'll just assume that the user has not changed the CWD data['sys.path'] = list(sys.path) return data def prepare(data): if 'sys.argv' in data: sys.argv = data['sys.argv'] if 'sys.path' in data: sys.path = data['sys.path'] def spawn(spec, kwargs, pass_fds=()): """ Invoke a python function in a subprocess. """ r, w = os.pipe() for fd in [r] + list(pass_fds): set_inheritable(fd, True) preparation_data = get_preparation_data() r_handle = get_handle(r) args, env = get_command_line(pipe_handle=r_handle) process = subprocess.Popen(args, env=env, close_fds=False) to_child = os.fdopen(w, 'wb') to_child.write(pickle.dumps([preparation_data, spec, kwargs])) to_child.close() return process def spawn_main(pipe_handle): fd = open_handle(pipe_handle, 'rb') from_parent = os.fdopen(fd, 'rb') preparation_data, spec, kwargs = pickle.load(from_parent) from_parent.close() prepare(preparation_data) func = resolve_spec(spec) func(**kwargs) sys.exit(0) def wait(process, timeout=None): if timeout is None: return process.wait() if timeout == 0: return process.poll() return subprocess_wait_with_timeout(process, timeout) def kill(process, soft=False): if soft: return process.terminate() return process.kill() hupper-1.9.1/src/hupper/logger.py0000644€Déíè€bP^q0000000125213500236412022533 0ustar michaelDA\Domain Users00000000000000from __future__ import print_function import sys from .interfaces import ILogger class LogLevel: ERROR = 0 INFO = 1 DEBUG = 2 class DefaultLogger(ILogger): def __init__(self, level): self.level = level def _out(self, level, msg): if level <= self.level: print(msg, file=sys.stderr) def error(self, msg): self._out(LogLevel.ERROR, msg) def info(self, msg): self._out(LogLevel.INFO, msg) def debug(self, msg): self._out(LogLevel.DEBUG, msg) class SilentLogger(ILogger): def error(self, msg): pass def info(self, msg): pass def debug(self, msg): pass hupper-1.9.1/src/hupper/polling.py0000644€Déíè€bP^q0000000321613441505433022730 0ustar michaelDA\Domain Users00000000000000import os import threading import time from .interfaces import IFileMonitor class PollingFileMonitor(threading.Thread, IFileMonitor): """ An :class:`hupper.interfaces.IFileMonitor` that stats the files at periodic intervals. ``callback`` is a callable that accepts a path to a changed file. ``interval`` is a value in seconds between scans of the files on disk. Do not set this too low or it will eat your CPU and kill your drive. """ def __init__(self, callback, interval=1, **kw): super(PollingFileMonitor, self).__init__() self.callback = callback self.poll_interval = interval self.paths = set() self.mtimes = {} self.lock = threading.Lock() self.enabled = True def add_path(self, path): with self.lock: self.paths.add(path) def run(self): while self.enabled: with self.lock: paths = list(self.paths) self.check_reload(paths) time.sleep(self.poll_interval) def stop(self): self.enabled = False def check_reload(self, paths): changes = set() for path in paths: mtime = get_mtime(path) if path not in self.mtimes: self.mtimes[path] = mtime elif self.mtimes[path] < mtime: self.mtimes[path] = mtime changes.add(path) for path in sorted(changes): self.callback(path) def get_mtime(path): try: stat = os.stat(path) if stat: return stat.st_mtime except (OSError, IOError): # pragma: no cover pass return 0 hupper-1.9.1/src/hupper/reloader.py0000644€Déíè€bP^q0000002757213562615256023105 0ustar michaelDA\Domain Users00000000000000import fnmatch import os import re import signal import sys import threading import time from .compat import queue, glob from .ipc import ProcessGroup from .logger import DefaultLogger, SilentLogger from .utils import default from .utils import is_stream_interactive from .utils import is_watchdog_supported from .utils import is_watchman_supported from .utils import resolve_spec from .worker import Worker, is_active, get_reloader class FileMonitorProxy(object): """ Wrap an :class:`hupper.interfaces.IFileMonitor` into an object that exposes a thread-safe interface back to the reloader to detect when it should reload. """ monitor = None def __init__(self, logger, ignore_files=None): self.logger = logger self.change_event = threading.Event() self.changed_paths = set() self.ignore_files = [ re.compile(fnmatch.translate(x)) for x in set(ignore_files or []) ] def add_path(self, path): # if the glob does not match any files then go ahead and pass # the pattern to the monitor anyway incase it is just a file that # is currently missing for p in glob(path, recursive=True) or [path]: if not any(x.match(p) for x in self.ignore_files): self.monitor.add_path(p) def start(self): self.monitor.start() def stop(self): self.monitor.stop() self.monitor.join() def file_changed(self, path): if path not in self.changed_paths: self.changed_paths.add(path) self.logger.info('%s changed; reloading ...' % (path,)) self.set_changed() def is_changed(self): return self.change_event.is_set() def wait_for_change(self, timeout=None): return self.change_event.wait(timeout) def clear_changes(self): self.change_event.clear() self.changed_paths.clear() def set_changed(self): self.change_event.set() class WorkerResult: BROKEN_PIPE = 'broken_pipe' EXIT = 'exit' FILE_CHANGED = 'file_changed' RELOAD_REQUEST = 'reload_request' class Reloader(object): """ A wrapper class around a file monitor which will handle changes by restarting a new worker process. """ def __init__( self, worker_path, monitor_factory, logger, reload_interval=1, shutdown_interval=1, worker_args=None, worker_kwargs=None, ignore_files=None, ): self.worker_path = worker_path self.worker_args = worker_args self.worker_kwargs = worker_kwargs self.ignore_files = ignore_files self.monitor_factory = monitor_factory self.reload_interval = reload_interval self.shutdown_interval = shutdown_interval self.logger = logger self.monitor = None self.group = ProcessGroup() def run(self): """ Execute the reloader forever, blocking the current thread. This will invoke ``sys.exit(1)`` if interrupted. """ self._capture_signals() self._start_monitor() try: while True: result = self._run_worker() if result == WorkerResult.EXIT: result = self._wait_for_changes() if result != WorkerResult.RELOAD_REQUEST: time.sleep(self.reload_interval) except KeyboardInterrupt: pass finally: self._stop_monitor() self._restore_signals() sys.exit(1) def run_once(self): """ Execute the worker once. This method will return after a file change is detected. """ self._capture_signals() self._start_monitor() try: self._run_worker() except KeyboardInterrupt: return finally: self._stop_monitor() self._restore_signals() def _run_worker(self): worker = Worker( self.worker_path, args=self.worker_args, kwargs=self.worker_kwargs ) return _run_worker( worker, self.monitor, self.group, self.logger, self.reload_interval, self.shutdown_interval, ) def _wait_for_changes(self): worker = Worker(__name__ + '.wait_main') return _run_worker( worker, self.monitor, self.group, SilentLogger(), self.reload_interval, self.shutdown_interval, ) def _start_monitor(self): proxy = FileMonitorProxy(self.logger, self.ignore_files) proxy.monitor = self.monitor_factory( proxy.file_changed, interval=self.reload_interval, logger=self.logger, ) self.monitor = proxy self.monitor.start() def _stop_monitor(self): if self.monitor: self.monitor.stop() self.monitor = None def _capture_signals(self): # SIGHUP is not supported on windows if hasattr(signal, 'SIGHUP'): signal.signal(signal.SIGHUP, self._signal_sighup) def _signal_sighup(self, signum, frame): self.logger.info('Received SIGHUP, triggering a reload.') self.monitor.set_changed() def _restore_signals(self): if hasattr(signal, 'SIGHUP'): signal.signal(signal.SIGHUP, signal.SIG_DFL) def _run_worker( worker, monitor, process_group, logger, reload_interval, shutdown_interval ): worker.start() result = WorkerResult.EXIT try: # register the worker with the process group process_group.add_child(worker.pid) logger.info('Starting monitor for PID %s.' % worker.pid) monitor.clear_changes() while worker.is_alive(): if monitor.is_changed(): result = WorkerResult.FILE_CHANGED break try: cmd = worker.pipe.recv(timeout=0.5) except queue.Empty: continue if cmd is None: if worker.is_alive(): # the worker socket has died but the process is still # alive (somehow) so wait a brief period to see if it # dies on its own - if it does die then we want to # treat it as a crash and wait for changes before # reloading, if it doesn't die then we want to force # reload the app immediately because it probably # didn't die due to some file changes time.sleep(reload_interval) if worker.is_alive(): logger.info('Broken pipe to server, triggering a reload.') result = WorkerResult.BROKEN_PIPE else: logger.debug('Broken pipe to server, looks like a crash.') break if cmd[0] == 'reload': logger.debug('Server triggered a reload.') result = WorkerResult.RELOAD_REQUEST break if cmd[0] == 'watch': for path in cmd[1]: monitor.add_path(path) else: # pragma: no cover raise RuntimeError('received unknown command') if worker.is_alive() and shutdown_interval is not None: logger.info('Gracefully killing the server.') worker.kill(soft=True) worker.wait(shutdown_interval) except KeyboardInterrupt: if worker.is_alive(): logger.info('Received interrupt, waiting for server to exit ...') if shutdown_interval is not None: worker.wait(shutdown_interval) raise finally: if worker.is_alive(): logger.info('Server did not exit, forcefully killing.') worker.kill() worker.join() else: worker.join() logger.debug('Server exited with code %d.' % worker.exitcode) monitor.clear_changes() return result def wait_main(): try: reloader = get_reloader() if is_stream_interactive(sys.stdin): input('Press ENTER or change a file to reload.\n') reloader.trigger_reload() else: # just block while we wait for a file to change print('Waiting for a file to change before reload.') while True: time.sleep(10) except KeyboardInterrupt: pass def find_default_monitor_factory(logger): spec = os.getenv('HUPPER_DEFAULT_MONITOR') if spec: monitor_factory = resolve_spec(spec) logger.debug('File monitor backend: ' + spec) elif is_watchman_supported(): from .watchman import WatchmanFileMonitor as monitor_factory logger.debug('File monitor backend: watchman') elif is_watchdog_supported(): from .watchdog import WatchdogFileMonitor as monitor_factory logger.debug('File monitor backend: watchdog') else: from .polling import PollingFileMonitor as monitor_factory logger.debug('File monitor backend: polling') return monitor_factory def start_reloader( worker_path, reload_interval=1, shutdown_interval=default, verbose=1, logger=None, monitor_factory=None, worker_args=None, worker_kwargs=None, ignore_files=None, ): """ Start a monitor and then fork a worker process which starts by executing the importable function at ``worker_path``. If this function is called from a worker process that is already being monitored then it will return a reference to the current :class:`hupper.interfaces.IReloaderProxy` which can be used to communicate with the monitor. ``worker_path`` must be a dotted string pointing to a globally importable function that will be executed to start the worker. An example could be ``myapp.cli.main``. In most cases it will point at the same function that is invoking ``start_reloader`` in the first place. ``reload_interval`` is a value in seconds and will be used to throttle restarts. Default is ``1``. ``shutdown_interval`` is a value in seconds and will be used to trigger a graceful shutdown of the server. Set to ``None`` to disable the graceful shutdown. Default is the same as ``reload_interval``. ``verbose`` controls the output. Set to ``0`` to turn off any logging of activity and turn up to ``2`` for extra output. Default is ``1``. ``logger``, if supplied, supersedes ``verbose`` and should be an object implementing :class:`hupper.interfaces.ILogger`. ``monitor_factory`` is an instance of :class:`hupper.interfaces.IFileMonitorFactory`. If left unspecified, this will try to create a :class:`hupper.watchdog.WatchdogFileMonitor` if `watchdog `_ is installed and will fallback to the less efficient :class:`hupper.polling.PollingFileMonitor` otherwise. If ``monitor_factory`` is ``None`` it can be overridden by the ``HUPPER_DEFAULT_MONITOR`` environment variable. It should be a dotted python path pointing at an object implementing :class:`hupper.interfaces.IFileMonitorFactory`. ``ignore_files`` if provided must be an iterable of shell-style patterns to ignore. """ if is_active(): return get_reloader() if logger is None: logger = DefaultLogger(verbose) if monitor_factory is None: monitor_factory = find_default_monitor_factory(logger) if shutdown_interval is default: shutdown_interval = reload_interval reloader = Reloader( worker_path=worker_path, worker_args=worker_args, worker_kwargs=worker_kwargs, reload_interval=reload_interval, shutdown_interval=shutdown_interval, monitor_factory=monitor_factory, logger=logger, ignore_files=ignore_files, ) return reloader.run() hupper-1.9.1/src/hupper/utils.py0000644€Déíè€bP^q0000000250013562615256022430 0ustar michaelDA\Domain Users00000000000000import importlib import json import os import subprocess from .compat import WIN class Sentinel(object): def __init__(self, name): self.name = name def __repr__(self): return '<{0}>'.format(self.name) default = Sentinel('default') def resolve_spec(spec): modname, funcname = spec.rsplit('.', 1) module = importlib.import_module(modname) func = getattr(module, funcname) return func def is_watchdog_supported(): """ Return ``True`` if watchdog is available.""" try: import watchdog # noqa: F401 except ImportError: return False return True def is_watchman_supported(): """ Return ``True`` if watchman is available.""" if WIN: # for now we aren't bothering with windows sockets return False try: sockpath = get_watchman_sockpath() return bool(sockpath) except Exception: return False def get_watchman_sockpath(binpath='watchman'): """ Find the watchman socket or raise.""" path = os.getenv('WATCHMAN_SOCK') if path: return path cmd = [binpath, '--output-encoding=json', 'get-sockname'] result = subprocess.check_output(cmd) result = json.loads(result) return result['sockname'] def is_stream_interactive(stream): return stream is not None and stream.isatty() hupper-1.9.1/src/hupper/watchdog.py0000644€Déíè€bP^q0000000366513441505433023074 0ustar michaelDA\Domain Users00000000000000# check ``hupper.utils.is_watchdog_supported`` before using this module from __future__ import absolute_import import os.path import threading from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from .interfaces import IFileMonitor class WatchdogFileMonitor(FileSystemEventHandler, Observer, IFileMonitor): """ An :class:`hupper.interfaces.IFileMonitor` that uses ``watchdog`` to watch for file changes uses inotify. ``callback`` is a callable that accepts a path to a changed file. ``logger`` is an :class:`hupper.interfaces.ILogger` instance. """ def __init__(self, callback, logger, **kw): super(WatchdogFileMonitor, self).__init__() self.callback = callback self.logger = logger self.paths = set() self.dirpaths = set() self.lock = threading.Lock() def add_path(self, path): with self.lock: dirpath = os.path.dirname(path) if dirpath not in self.dirpaths: try: self.schedule(self, dirpath) except (OSError, IOError) as ex: # pragma: no cover # watchdog raises exceptions if folders are missing # or if the ulimit is passed self.logger.error('watchdog error: ' + str(ex)) else: self.dirpaths.add(dirpath) if path not in self.paths: self.paths.add(path) def _check(self, path): with self.lock: if path in self.paths: self.callback(path) def on_created(self, event): self._check(event.src_path) def on_modified(self, event): self._check(event.src_path) def on_moved(self, event): self._check(event.src_path) self._check(event.dest_path) self.add_path(event.dest_path) def on_deleted(self, event): self._check(event.src_path) hupper-1.9.1/src/hupper/watchman.py0000644€Déíè€bP^q0000001034213441505433023064 0ustar michaelDA\Domain Users00000000000000# check ``hupper.utils.is_watchman_supported`` before using this module import json import os import socket import threading import time from .compat import PY2 from .interfaces import IFileMonitor from .utils import get_watchman_sockpath class WatchmanFileMonitor(threading.Thread, IFileMonitor): """ An :class:`hupper.interfaces.IFileMonitor` that uses Facebook's ``watchman`` daemon to detect changes. ``callback`` is a callable that accepts a path to a changed file. """ def __init__( self, callback, logger, sockpath=None, binpath='watchman', timeout=1.0, **kw ): super(WatchmanFileMonitor, self).__init__() self.callback = callback self.logger = logger self.paths = set() self.dirpaths = set() self.lock = threading.Lock() self.enabled = True self.sockpath = sockpath self.binpath = binpath self.timeout = timeout def add_path(self, path): with self.lock: dirpath = os.path.dirname(path) if dirpath not in self.dirpaths: self._schedule(dirpath) self.dirpaths.add(dirpath) if path not in self.paths: self.paths.add(path) def start(self): sockpath = self._resolve_sockpath() sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.timeout) sock.connect(sockpath) self._sock = sock self._recvbufs = [] self._send(['version']) result = self._recv() self.logger.debug('Connected to watchman v' + result['version'] + '.') super(WatchmanFileMonitor, self).start() def join(self): try: return super(WatchmanFileMonitor, self).join() finally: self._sock.close() self._sock = None def run(self): while self.enabled: try: result = self._recv() if 'error' in result: self.logger.error('watchman error=' + result['error']) elif 'subscription' in result: root = result['root'] files = result['files'] with self.lock: for f in files: path = os.path.join(root, f) if path in self.paths: self.callback(path) except socket.timeout: pass def stop(self): self.enabled = False def _resolve_sockpath(self): if self.sockpath: return self.sockpath return get_watchman_sockpath(self.binpath) def _schedule(self, dirpath): self._send( [ 'subscribe', dirpath, dirpath, { # +1 second because we don't want any buffered changes # if the daemon is already watching the folder 'since': int(time.time() + 1), 'expression': ['type', 'f'], 'fields': ['name'], }, ] ) def _readline(self): # buffer may already have a line if len(self._recvbufs) == 1 and b'\n' in self._recvbufs[0]: line, b = self._recvbufs[0].split(b'\n', 1) self._recvbufs = [b] return line while True: b = self._sock.recv(4096) if not b: raise RuntimeError('lost connection to watchman') if b'\n' in b: result = b''.join(self._recvbufs) line, b = b.split(b'\n', 1) self._recvbufs = [b] return result + line self._recvbufs.append(b) def _recv(self): line = self._readline() if not PY2: line = line.decode('utf8') try: return json.loads(line) except Exception: # pragma: no cover self.logger.info('ignoring corrupted payload from watchman') return {} def _send(self, msg): cmd = json.dumps(msg) if not PY2: cmd = cmd.encode('ascii') self._sock.sendall(cmd + b'\n') hupper-1.9.1/src/hupper/winapi.py0000644€Déíè€bP^q0000001103713441505433022553 0ustar michaelDA\Domain Users00000000000000import ctypes from ctypes import wintypes kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) if ctypes.sizeof(ctypes.c_void_p) == 8: ULONG_PTR = ctypes.c_int64 else: ULONG_PTR = ctypes.c_ulong BOOL = wintypes.BOOL DWORD = wintypes.DWORD HANDLE = wintypes.HANDLE LARGE_INTEGER = wintypes.LARGE_INTEGER SIZE_T = ULONG_PTR ULONGLONG = ctypes.c_uint64 JobObjectAssociateCompletionPortInformation = 7 JobObjectBasicLimitInformation = 2 JobObjectBasicUIRestrictions = 4 JobObjectEndOfJobTimeInformation = 6 JobObjectExtendedLimitInformation = 9 JobObjectSecurityLimitInformation = 5 JobObjectGroupInformation = 11 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000 DELETE = 0x00010000 READ_CONTROL = 0x00020000 SYNCHRONIZE = 0x00100000 WRITE_DAC = 0x00040000 WRITE_OWNER = 0x00080000 STANDARD_RIGHTS_REQUIRED = DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER PROCESS_CREATE_PROCESS = 0x0080 PROCESS_CREATE_THREAD = 0x0002 PROCESS_DUP_HANDLE = 0x0040 PROCESS_QUERY_INFORMATION = 0x0400 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 PROCESS_SET_INFORMATION = 0x0200 PROCESS_SET_QUOTA = 0x0100 PROCESS_SUSPEND_RESUME = 0x0800 PROCESS_TERMINATE = 0x0001 PROCESS_VM_OPERATION = 0x0008 PROCESS_VM_READ = 0x0010 PROCESS_VM_WRITE = 0x0020 PROCESS_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF DUPLICATE_SAME_ACCESS = 0x0002 HANDLE_FLAG_INHERIT = 0x0001 HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x0002 class IO_COUNTERS(ctypes.Structure): _fields_ = [ ('ReadOperationCount', ULONGLONG), ('WriteOperationCount', ULONGLONG), ('OtherOperationCount', ULONGLONG), ('ReadTransferCount', ULONGLONG), ('WriteTransferCount', ULONGLONG), ('OtherTransferCount', ULONGLONG), ] class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure): _fields_ = [ ('PerProcessUserTimeLimit', LARGE_INTEGER), ('PerJobUserTimeLimit', LARGE_INTEGER), ('LimitFlags', DWORD), ('MinimumWorkingSetSize', SIZE_T), ('MaximumWorkingSetSize', SIZE_T), ('ActiveProcessLimit', DWORD), ('Affinity', ULONG_PTR), ('PriorityClass', DWORD), ('SchedulingClass', DWORD), ] class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure): _fields_ = [ ('BasicLimitInformation', JOBOBJECT_BASIC_LIMIT_INFORMATION), ('IoInfo', IO_COUNTERS), ('ProcessMemoryLimit', SIZE_T), ('JobMemoryLimit', SIZE_T), ('PeakProcessMemoryUsed', SIZE_T), ('PeakJobMemoryUsed', SIZE_T), ] class Handle(HANDLE): closed = False def Close(self): if not self.closed: self.closed = True CloseHandle(self) def Detach(self): if not self.closed: self.closed = True return self.value raise ValueError("already closed") def __repr__(self): return "%s(%d)" % (self.__class__.__name__, self.value) __del__ = Close __str__ = __repr__ def CloseHandle(h): kernel32.CloseHandle(h) def CheckError(result, msg): if not result: raise ctypes.WinError(ctypes.get_last_error(), msg) def DuplicateHandle( hSourceProcess, hSourceHandle, hTargetProcess, desiredAccess, inheritHandle, options, ): targetHandle = wintypes.HANDLE() ret = kernel32.DuplicateHandle( hSourceProcess, hSourceHandle, hTargetProcess, ctypes.byref(targetHandle), desiredAccess, inheritHandle, options, ) CheckError(ret, 'failed to duplicate handle') return Handle(targetHandle.value) def GetCurrentProcess(): hp = kernel32.GetCurrentProcess() return Handle(hp) def OpenProcess(desiredAccess, inherit, pid): hp = kernel32.OpenProcess(desiredAccess, inherit, pid) CheckError(hp, 'failed to open process') return Handle(hp) def CreateJobObject(jobAttributes, name): hp = kernel32.CreateJobObjectA(jobAttributes, name) CheckError(hp, 'failed to create job object') return Handle(hp) def SetInformationJobObject(hJob, infoType, jobObjectInfo): ret = kernel32.SetInformationJobObject( hJob, infoType, ctypes.byref(jobObjectInfo), ctypes.sizeof(jobObjectInfo), ) CheckError(ret, 'failed to set information job object') def AssignProcessToJobObject(hJob, hProcess): ret = kernel32.AssignProcessToJobObject(hJob, hProcess) CheckError(ret, 'failed to assign process to job object') def SetHandleInformation(h, dwMask, dwFlags): ret = kernel32.SetHandleInformation(h, dwMask, dwFlags) CheckError(ret, 'failed to set handle information') hupper-1.9.1/src/hupper/worker.py0000644€Déíè€bP^q0000001744013562615256022612 0ustar michaelDA\Domain Users00000000000000import os import signal import sys import sysconfig import threading import time import traceback from . import ipc from .compat import get_py_path from .compat import interrupt_main from .compat import get_site_packages from .interfaces import IReloaderProxy from .utils import resolve_spec class WatchSysModules(threading.Thread): """ Poll ``sys.modules`` for imported modules.""" poll_interval = 1 ignore_system_paths = True def __init__(self, callback): super(WatchSysModules, self).__init__() self.paths = set() self.callback = callback self.lock = threading.Lock() self.stopped = False self.system_paths = get_system_paths() def run(self): while not self.stopped: self.update_paths() time.sleep(self.poll_interval) def stop(self): self.stopped = True def update_paths(self): """ Check sys.modules for paths to add to our path set.""" new_paths = [] with self.lock: for path in expand_source_paths(iter_module_paths()): if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths) def search_traceback(self, tb): """ Inspect a traceback for new paths to add to our path set.""" new_paths = [] with self.lock: for filename, line, funcname, txt in traceback.extract_tb(tb): path = os.path.abspath(filename) if path not in self.paths: self.paths.add(path) new_paths.append(path) if new_paths: self.watch_paths(new_paths) def watch_paths(self, paths): if self.ignore_system_paths: paths = [path for path in paths if not self.in_system_paths(path)] if paths: self.callback(paths) def in_system_paths(self, path): for prefix in self.system_paths: # use realpath to only ignore files that live in a system path # versus a symlink which lives elsewhere if os.path.realpath(path).startswith(prefix): return True return False def get_system_paths(): paths = get_site_packages() for name in {'stdlib', 'platstdlib', 'platlib', 'purelib'}: path = sysconfig.get_path(name) if path is not None: paths.append(path) return paths def expand_source_paths(paths): """ Convert pyc files into their source equivalents.""" for src_path in paths: # only track the source path if we can find it to avoid double-reloads # when the source and the compiled path change because on some # platforms they are not changed at the same time if src_path.endswith(('.pyc', '.pyo')): py_path = get_py_path(src_path) if os.path.exists(py_path): src_path = py_path yield src_path def iter_module_paths(modules=None): """ Yield paths of all imported modules.""" modules = modules or list(sys.modules.values()) for module in modules: try: filename = module.__file__ except (AttributeError, ImportError): # pragma: no cover continue if filename is not None: abs_filename = os.path.abspath(filename) if os.path.isfile(abs_filename): yield abs_filename class WatchForParentShutdown(threading.Thread): """ Watch the pipe to ensure the parent is still alive.""" def __init__(self, pipe): super(WatchForParentShutdown, self).__init__() self.pipe = pipe def run(self): try: # wait until the pipe breaks while self.pipe.recv(): # pragma: no cover pass except EOFError: pass interrupt_main() class Worker(object): """ A helper object for managing a worker process lifecycle. """ def __init__(self, spec, args=None, kwargs=None): super(Worker, self).__init__() self.worker_spec = spec self.worker_args = args self.worker_kwargs = kwargs self.pipe, self._child_pipe = ipc.Pipe() self.pid = None self.process = None self.exitcode = None self.stdin_termios = None def start(self): self.stdin_termios = ipc.snapshot_termios(sys.stdin) kw = dict( spec=self.worker_spec, spec_args=self.worker_args, spec_kwargs=self.worker_kwargs, pipe=self._child_pipe, ) self.process = ipc.spawn( __name__ + '.worker_main', kwargs=kw, pass_fds=[self._child_pipe.r_fd, self._child_pipe.w_fd], ) self.pid = self.process.pid # activate the pipe after forking self.pipe.activate() # kill the child side of the pipe after forking as the child is now # responsible for it self._child_pipe.close() def is_alive(self): if self.exitcode is not None: return False if self.process: return ipc.wait(self.process, timeout=0) is None return False def kill(self, soft=False): return ipc.kill(self.process, soft=soft) def wait(self, timeout=None): return ipc.wait(self.process, timeout=timeout) def join(self): self.exitcode = self.wait() if self.stdin_termios: ipc.restore_termios(sys.stdin, self.stdin_termios) if self.pipe: try: self.pipe.close() except Exception: # pragma: no cover pass finally: self.pipe = None # set when the current process is being monitored _reloader_proxy = None def get_reloader(): """ Get a reference to the current :class:`hupper.interfaces.IReloaderProxy`. Raises a ``RuntimeError`` if the current process is not actively being monitored by a parent process. """ if _reloader_proxy is None: raise RuntimeError('process is not controlled by hupper') return _reloader_proxy def is_active(): """ Return ``True`` if the current process being monitored by a parent process. """ return _reloader_proxy is not None class ReloaderProxy(IReloaderProxy): def __init__(self, pipe): self.pipe = pipe def watch_files(self, files): files = [os.path.abspath(f) for f in files] self.pipe.send(('watch', files)) def trigger_reload(self): self.pipe.send(('reload',)) def worker_main(spec, pipe, spec_args=None, spec_kwargs=None): if spec_args is None: spec_args = [] if spec_kwargs is None: spec_kwargs = {} # activate the pipe after forking pipe.activate() # SIGHUP is not supported on windows if hasattr(signal, 'SIGHUP'): signal.signal(signal.SIGHUP, signal.SIG_IGN) # disable pyc files for project code because it can cause timestamp # issues in which files are reloaded twice sys.dont_write_bytecode = True global _reloader_proxy _reloader_proxy = ReloaderProxy(pipe) parent_watcher = WatchForParentShutdown(pipe) parent_watcher.daemon = True parent_watcher.start() poller = WatchSysModules(_reloader_proxy.watch_files) poller.daemon = True poller.start() # import the worker path before polling sys.modules func = resolve_spec(spec) # start the worker try: func(*spec_args, **spec_kwargs) except BaseException: # catch any error try: # attempt to send imported paths to the master prior to crashing poller.update_paths() poller.search_traceback(sys.exc_info()[2]) poller.stop() poller.join() except Exception: # pragma: no cover pass raise hupper-1.9.1/src/hupper.egg-info/0000755€Déíè€bP^q0000000000013562615436022413 5ustar michaelDA\Domain Users00000000000000hupper-1.9.1/src/hupper.egg-info/PKG-INFO0000644€Déíè€bP^q0000003544513562615436023523 0ustar michaelDA\Domain Users00000000000000Metadata-Version: 2.1 Name: hupper Version: 1.9.1 Summary: Integrated process monitor for developing and reloading daemons. Home-page: https://github.com/Pylons/hupper Author: Michael Merickel Author-email: pylons-discuss@googlegroups.com License: MIT Description: ====== hupper ====== .. image:: https://img.shields.io/pypi/v/hupper.svg :target: https://pypi.python.org/pypi/hupper .. image:: https://img.shields.io/travis/Pylons/hupper/master.svg :target: https://travis-ci.org/Pylons/hupper .. image:: https://readthedocs.org/projects/hupper/badge/?version=latest :target: https://readthedocs.org/projects/hupper/?badge=latest :alt: Documentation Status ``hupper`` is an integrated process monitor that will track changes to any imported Python files in ``sys.modules`` as well as custom paths. When files are changed the process is restarted. Command-line Usage ================== Hupper can load any Python code similar to ``python -m `` by using the ``hupper -m `` program. .. code-block:: console $ hupper -m myapp Starting monitor for PID 23982. API Usage ========= Start by defining an entry point for your process. This must be an importable path in string format. For example, ``myapp.scripts.serve.main``. .. code-block:: python # myapp/scripts/serve.py import sys import hupper import waitress def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) yield b'hello' def main(args=sys.argv[1:]): if '--reload' in args: # start_reloader will only return in a monitored subprocess reloader = hupper.start_reloader('myapp.scripts.serve.main') # monitor an extra file reloader.watch_files(['foo.ini']) waitress.serve(wsgi_app) Acknowledgments =============== ``hupper`` is inspired by initial work done by Carl J Meyer and David Glick during a Pycon sprint and is built to be a more robust and generic version of Ian Bicking's excellent PasteScript ``paste serve --reload`` and Pyramid's ``pserve --reload``. 1.9.1 (2019-11-12) ================== - Support some scenarios in which user code is symlinked ``site-packages``. These were previously being ignored by the file monitor but should now be tracked. See https://github.com/Pylons/hupper/pull/61 1.9 (2019-10-14) ================ - Support ``--shutdown-interval`` on the ``hupper`` CLI. See https://github.com/Pylons/hupper/pull/56 - Support ``--reload-interval`` on the ``hupper`` CLI. See https://github.com/Pylons/hupper/pull/59 - Do not choke when stdin is not a TTY while waiting for changes after a crash. For example, when running in Docker Compose. See https://github.com/Pylons/hupper/pull/58 1.8.1 (2019-06-12) ================== - Do not show the ``KeyboardInterrupt`` stacktrace when killing ``hupper`` while waiting for a reload. 1.8 (2019-06-11) ================ - If the worker process crashes, ``hupper`` can be forced to reload the worker by pressing the ``ENTER`` key in the terminal instead of waiting to change a file. See https://github.com/Pylons/hupper/pull/53 1.7 (2019-06-04) ================ - On Python 3.5+ support recursive glob syntax in ``reloader.watch_files``. See https://github.com/Pylons/hupper/pull/52 1.6.1 (2019-03-11) ================== - If the worker crashes immediately, sometimes ``hupper`` would go into a restart loop instead of waiting for a code change. See https://github.com/Pylons/hupper/pull/50 1.6 (2019-03-06) ================ - On systems that support ``SIGKILL`` and ``SIGTERM`` (not Windows), ``hupper`` will now send a ``SIGKILL`` to the worker process as a last resort. Normally, a ``SIGINT`` (Ctrl-C) or ``SIGTERM`` (on reload) will kill the worker. If, within ``shutdown_interval`` seconds, the worker doesn't exit, it will receive a ``SIGKILL``. See https://github.com/Pylons/hupper/pull/48 - Support a ``logger`` argument to ``hupper.start_reloader`` to override the default logger that outputs messages to ``sys.stderr``. See https://github.com/Pylons/hupper/pull/49 1.5 (2019-02-16) ================ - Add support for ignoring custom patterns via the new ``ignore_files`` option on ``hupper.start_reloader``. The ``hupper`` cli also supports ignoring files via the ``-x`` option. See https://github.com/Pylons/hupper/pull/46 1.4.2 (2018-11-26) ================== - Fix a bug prompting the "ignoring corrupted payload from watchman" message and placing the file monitor in an unrecoverable state when a change triggered a watchman message > 4096 bytes. See https://github.com/Pylons/hupper/pull/44 1.4.1 (2018-11-11) ================== - Stop ignoring a few paths that may not be system paths in cases where the virtualenv is the root of your project. See https://github.com/Pylons/hupper/pull/42 1.4 (2018-10-26) ================ - Ignore changes to any system / installed files. This includes mostly changes to any files in the stdlib and ``site-packages``. Anything that is installed in editable mode or not installed at all will still be monitored. This drastically reduces the number of files that ``hupper`` needs to monitor. See https://github.com/Pylons/hupper/pull/40 1.3.1 (2018-10-05) ================== - Support Python 3.7. - Avoid a restart-loop if the app is failing to restart on certain systems. There was a race where ``hupper`` failed to detect that the app was crashing and thus fell into its restart logic when the user manually triggers an immediate reload. See https://github.com/Pylons/hupper/pull/37 - Ignore corrupted packets coming from watchman that occur in semi-random scenarios. See https://github.com/Pylons/hupper/pull/38 1.3 (2018-05-21) ================ - Added watchman support via ``hupper.watchman.WatchmanFileMonitor``. This is the new preferred file monitor on systems supporting unix sockets. See https://github.com/Pylons/hupper/pull/32 - The ``hupper.watchdog.WatchdogFileMonitor`` will now output some info when it receives ulimit or other errors from ``watchdog``. See https://github.com/Pylons/hupper/pull/33 - Allow ``-q`` and ``-v`` cli options to control verbosity. See https://github.com/Pylons/hupper/pull/33 - Pass a ``logger`` value to the ``hupper.interfaces.IFileMonitorFactory``. This is an instance of ``hupper.interfaces.ILogger`` and can be used by file monitors to output errors and debug information. See https://github.com/Pylons/hupper/pull/33 1.2 (2018-05-01) ================ - Track only Python source files. Previously ``hupper`` would track all pyc and py files. Now, if a pyc file is found then the equivalent source file is searched and, if found, the pyc file is ignored. See https://github.com/Pylons/hupper/pull/31 - Allow overriding the default monitor lookup by specifying the ``HUPPER_DEFAULT_MONITOR`` environment variable as a Python dotted-path to a monitor factory. For example, ``HUPPER_DEFAULT_MONITOR=hupper.polling.PollingFileMonitor``. See https://github.com/Pylons/hupper/pull/29 - Backward-incompatible changes to the ``hupper.interfaces.IFileMonitorFactory`` API to pass arbitrary kwargs to the factory. See https://github.com/Pylons/hupper/pull/29 1.1 (2018-03-29) ================ - Support ``-w`` on the CLI to watch custom file paths. See https://github.com/Pylons/hupper/pull/28 1.0 (2017-05-18) ================ - Copy ``sys.path`` to the worker process and ensure ``hupper`` is on the ``PYTHONPATH`` so that the subprocess can import it to start the worker. This fixes an issue with how ``zc.buildout`` injects dependencies into a process which is done entirely by ``sys.path`` manipulation. See https://github.com/Pylons/hupper/pull/27 0.5 (2017-05-10) ================ - On non-windows systems ensure an exec occurs so that the worker does not share the same process space as the reloader causing certain code that is imported in both to not ever be reloaded. Under the hood this was a significant rewrite to use subprocess instead of multiprocessing. See https://github.com/Pylons/hupper/pull/23 0.4.4 (2017-03-10) ================== - Fix some versions of Windows which were failing to duplicate stdin to the subprocess and crashing. https://github.com/Pylons/hupper/pull/16 0.4.3 (2017-03-07) ================== - Fix pdb and other readline-based programs to operate properly. See https://github.com/Pylons/hupper/pull/15 0.4.2 (2017-01-24) ================== - Pause briefly after receiving a SIGINT to allow the worker to kill itself. If it does not die then it is terminated. See https://github.com/Pylons/hupper/issues/11 - Python 3.6 compatibility. 0.4.1 (2017-01-03) ================== - Handle errors that may occur when using watchdog to observe non-existent folders. 0.4.0 (2017-01-02) ================== - Support running any Python module via ``hupper -m ``. This is equivalent to ``python -m`` except will fully reload the process when files change. See https://github.com/Pylons/hupper/pull/8 0.3.6 (2016-12-18) ================== - Read the traceback for unknown files prior to crashing. If an import crashes due to a module-scope exception the file that caused the crash would not be tracked but this should help. 0.3.5 (2016-12-17) ================== - Attempt to send imported paths to the monitor process before crashing to avoid cases where the master is waiting for changes in files that it never started monitoring. 0.3.4 (2016-11-21) ================== - Add support for globbing using the stdlib ``glob`` module. On Python 3.5+ this allows recursive globs using ``**``. Prior to this, the globbing is more limited. 0.3.3 (2016-11-19) ================== - Fixed a runtime failure on Windows 32-bit systems. 0.3.2 (2016-11-15) ================== - Support triggering reloads via SIGHUP when hupper detected a crash and is waiting for a file to change. - Setup the reloader proxy prior to importing the worker's module. This should allow some work to be done at module-scope instead of in the callable. 0.3.1 (2016-11-06) ================== - Fix package long description on PyPI. - Ensure that the stdin file handle is inheritable incase the "spawn" variant of multiprocessing is enabled. 0.3 (2016-11-06) ================ - Disable bytecode compiling of files imported by the worker process. This should not be necessary when developing and it was causing the process to restart twice on Windows due to how it handles pyc timestamps. - Fix hupper's support for forwarding stdin to the worker processes on Python < 3.5 on Windows. - Fix some possible file descriptor leakage. - Simplify the ``hupper.interfaces.IFileMonitor`` interface by internalizing some of the hupper-specific integrations. They can now focus on just looking for changes. - Add the ``hupper.interfaces.IFileMonitorFactory`` interface to improve the documentation for the ``callback`` argument required by ``hupper.interfaces.IFileMonitor``. 0.2 (2016-10-26) ================ - Windows support! - Added support for `watchdog `_ if it's installed to do inotify-style file monitoring. This is an optional dependency and ``hupper`` will fallback to using polling if it's not available. 0.1 (2016-10-21) ================ - Initial release. Keywords: server daemon autoreload reloader hup file watch process Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Natural Language :: English Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Requires-Python: >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.* Provides-Extra: docs Provides-Extra: testing hupper-1.9.1/src/hupper.egg-info/SOURCES.txt0000644€Déíè€bP^q0000000176713562615436024312 0ustar michaelDA\Domain Users00000000000000.coveragerc .flake8 .travis.yml CHANGES.rst CONTRIBUTING.rst CONTRIBUTORS.txt LICENSE.txt MANIFEST.in README.rst appveyor.yml pyproject.toml rtd.txt setup.cfg setup.py tox.ini docs/Makefile docs/api.rst docs/changes.rst docs/conf.py docs/contributing.rst docs/index.rst docs/make.bat docs/_static/.keep src/hupper/__init__.py src/hupper/cli.py src/hupper/compat.py src/hupper/interfaces.py src/hupper/ipc.py src/hupper/logger.py src/hupper/polling.py src/hupper/reloader.py src/hupper/utils.py src/hupper/watchdog.py src/hupper/watchman.py src/hupper/winapi.py src/hupper/worker.py src/hupper.egg-info/PKG-INFO src/hupper.egg-info/SOURCES.txt src/hupper.egg-info/dependency_links.txt src/hupper.egg-info/entry_points.txt src/hupper.egg-info/not-zip-safe src/hupper.egg-info/requires.txt src/hupper.egg-info/top_level.txt tests/__init__.py tests/conftest.py tests/test_cli.py tests/test_it.py tests/test_reloader.py tests/util.py tests/myapp/__init__.py tests/myapp/__main__.py tests/myapp/cli.py tests/myapp/foo.inihupper-1.9.1/src/hupper.egg-info/dependency_links.txt0000644€Déíè€bP^q0000000000113562615436026461 0ustar michaelDA\Domain Users00000000000000 hupper-1.9.1/src/hupper.egg-info/entry_points.txt0000644€Déíè€bP^q0000000005413562615436025710 0ustar michaelDA\Domain Users00000000000000[console_scripts] hupper = hupper.cli:main hupper-1.9.1/src/hupper.egg-info/not-zip-safe0000644€Déíè€bP^q0000000000113021336742024627 0ustar michaelDA\Domain Users00000000000000 hupper-1.9.1/src/hupper.egg-info/requires.txt0000644€Déíè€bP^q0000000013013562615436025005 0ustar michaelDA\Domain Users00000000000000 [docs] watchdog Sphinx pylons-sphinx-themes [testing] watchdog pytest pytest-cov mock hupper-1.9.1/src/hupper.egg-info/top_level.txt0000644€Déíè€bP^q0000000000713562615436025142 0ustar michaelDA\Domain Users00000000000000hupper hupper-1.9.1/tests/0000755€Déíè€bP^q0000000000013562615436017771 5ustar michaelDA\Domain Users00000000000000hupper-1.9.1/tests/__init__.py0000644€Déíè€bP^q0000000000013002175122022046 0ustar michaelDA\Domain Users00000000000000hupper-1.9.1/tests/conftest.py0000644€Déíè€bP^q0000000277013441505433022165 0ustar michaelDA\Domain Users00000000000000from __future__ import print_function import pytest import sys from . import util def err(msg): # pragma: no cover print(msg, file=sys.stderr) @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): # execute all other hooks to obtain the report object outcome = yield rep = outcome.get_result() # set an report attribute for each phase of a call, which can # be "setup", "call", "teardown" setattr(item, "rep_" + rep.when, rep) @pytest.fixture def testapp(request): app = util.TestApp() try: yield app finally: app.stop() if ( request.node.rep_call.failed and app.exitcode is not None ): # pragma: no cover err( '-- test app failed --\nname=%s\nargs=%s\ncode=%s' % (app.name, app.args, app.exitcode) ) err('-- stdout --\n%s' % app.stdout) err('-- stderr --\n%s' % app.stderr) class DummyLogger: def __init__(self): self.messages = [] def reset(self): self.messages = [] def get_output(self, *levels): if not levels: levels = {'info', 'error', 'debug'} return '\n'.join(msg for lvl, msg in self.messages if lvl in levels) def info(self, msg): self.messages.append(('info', msg)) def error(self, msg): self.messages.append(('error', msg)) def debug(self, msg): self.messages.append(('debug', msg)) @pytest.fixture def logger(): return DummyLogger() hupper-1.9.1/tests/myapp/0000755€Déíè€bP^q0000000000013562615436021117 5ustar michaelDA\Domain Users00000000000000hupper-1.9.1/tests/myapp/__init__.py0000644€Déíè€bP^q0000000037313441505433023222 0ustar michaelDA\Domain Users00000000000000import pytest_cov.embed import signal import sys def cleanup(*args, **kwargs): # pragma: no cover # see https://github.com/pytest-dev/pytest-cov/issues/139 pytest_cov.embed.cleanup() sys.exit(1) signal.signal(signal.SIGTERM, cleanup) hupper-1.9.1/tests/myapp/__main__.py0000644€Déíè€bP^q0000000010413021336677023201 0ustar michaelDA\Domain Users00000000000000import sys from .cli import main sys.exit(main(sys.argv[1:]) or 0) hupper-1.9.1/tests/myapp/cli.py0000644€Déíè€bP^q0000000362413441505433022234 0ustar michaelDA\Domain Users00000000000000import argparse import hupper import os import sys import time here = os.path.dirname(__file__) def parse_options(args): parser = argparse.ArgumentParser() parser.add_argument('--reload', action='store_true') parser.add_argument('--callback-file') parser.add_argument( '--watch-file', action='append', dest='watch_files', default=[] ) parser.add_argument('--watchman', action='store_true') parser.add_argument('--watchdog', action='store_true') parser.add_argument('--poll', action='store_true') parser.add_argument('--poll-interval', type=int) parser.add_argument('--reload-interval', type=int) return parser.parse_args(args) def main(args=None): if args is None: args = sys.argv[1:] opts = parse_options(args) if opts.reload: kw = {} if opts.poll: from hupper.polling import PollingFileMonitor pkw = {} if opts.poll_interval: pkw['poll_interval'] = opts.poll_interval kw['monitor_factory'] = lambda cb: PollingFileMonitor(cb, **pkw) if opts.watchdog: from hupper.watchdog import WatchdogFileMonitor kw['monitor_factory'] = WatchdogFileMonitor if opts.watchman: from hupper.watchman import WatchmanFileMonitor kw['monitor_factory'] = WatchmanFileMonitor if opts.reload_interval: kw['reload_interval'] = opts.reload_interval hupper.start_reloader(__name__ + '.main', **kw) if hupper.is_active(): hupper.get_reloader().watch_files([os.path.join(here, 'foo.ini')]) hupper.get_reloader().watch_files(opts.watch_files) if opts.callback_file: with open(opts.callback_file, 'ab') as fp: fp.write('{:d}\n'.format(int(time.time())).encode('utf8')) try: while True: time.sleep(1) except KeyboardInterrupt: pass hupper-1.9.1/tests/myapp/foo.ini0000644€Déíè€bP^q0000000000013355727664022400 0ustar michaelDA\Domain Users00000000000000hupper-1.9.1/tests/test_cli.py0000644€Déíè€bP^q0000000046613562615256022157 0ustar michaelDA\Domain Users00000000000000import argparse import pytest from hupper.cli import interval_parser @pytest.mark.parametrize('value', ['0', "-1"]) def test_interval_parser_errors(value): with pytest.raises(argparse.ArgumentTypeError): interval_parser(value) def test_interval_parser(): assert interval_parser("5") == 5 hupper-1.9.1/tests/test_it.py0000644€Déíè€bP^q0000000134013300635224021777 0ustar michaelDA\Domain Users00000000000000import os.path import time from . import util here = os.path.abspath(os.path.dirname(__file__)) def test_myapp_reloads_when_touching_ini(testapp): testapp.start('myapp', ['--reload']) testapp.wait_for_response() time.sleep(2) util.touch(os.path.join(here, 'myapp/foo.ini')) testapp.wait_for_response() testapp.stop() assert len(testapp.response) == 2 assert testapp.stderr != '' def test_myapp_reloads_when_touching_pyfile(testapp): testapp.start('myapp', ['--reload']) testapp.wait_for_response() time.sleep(2) util.touch(os.path.join(here, 'myapp/cli.py')) testapp.wait_for_response() testapp.stop() assert len(testapp.response) == 2 assert testapp.stderr != '' hupper-1.9.1/tests/test_reloader.py0000644€Déíè€bP^q0000000553613441505433023177 0ustar michaelDA\Domain Users00000000000000import os here = os.path.abspath(os.path.dirname(__file__)) def make_proxy(monitor_factory, logger): from hupper.reloader import FileMonitorProxy proxy = FileMonitorProxy(logger) proxy.monitor = monitor_factory(proxy.file_changed) return proxy def test_proxy_proxies(logger): class DummyMonitor(object): started = stopped = joined = False def __call__(self, cb, **kw): self.cb = cb return self def start(self): self.started = True def stop(self): self.stopped = True def join(self): self.joined = True monitor = DummyMonitor() proxy = make_proxy(monitor, logger) assert monitor.cb assert not monitor.started and not monitor.stopped and not monitor.joined proxy.start() assert monitor.started and not monitor.stopped and not monitor.joined proxy.stop() assert monitor.stopped and monitor.joined def test_proxy_expands_paths(tmpdir, logger): class DummyMonitor(object): def __call__(self, cb, **kw): self.cb = cb self.paths = [] return self def add_path(self, path): self.paths.append(path) monitor = DummyMonitor() proxy = make_proxy(monitor, logger) proxy.add_path('foo') assert monitor.paths == ['foo'] tmpdir.join('foo.txt').ensure() tmpdir.join('bar.txt').ensure() rootdir = tmpdir.strpath monitor.paths = [] proxy.add_path(os.path.join(rootdir, '*.txt')) assert sorted(monitor.paths) == [ os.path.join(rootdir, 'bar.txt'), os.path.join(rootdir, 'foo.txt'), ] def test_proxy_tracks_changes(logger): class DummyMonitor(object): def __call__(self, cb, **kw): self.cb = cb return self monitor = DummyMonitor() proxy = make_proxy(monitor, logger) assert not proxy.is_changed() monitor.cb('foo.txt') assert proxy.is_changed() out = logger.get_output('info') assert out == 'foo.txt changed; reloading ...' logger.reset() monitor.cb('foo.txt') out = logger.get_output('info') assert out == '' logger.reset() proxy.clear_changes() assert not proxy.is_changed() monitor.cb('foo.txt') out = logger.get_output('info') assert out == 'foo.txt changed; reloading ...' logger.reset() def test_ignore_files(): class DummyMonitor(object): paths = set() def add_path(self, path): self.paths.add(path) from hupper.reloader import FileMonitorProxy proxy = FileMonitorProxy(None, {'/a/*'}) monitor = proxy.monitor = DummyMonitor() path = 'foo.txt' assert path not in monitor.paths proxy.add_path(path) assert path in monitor.paths path = '/a/foo.txt' assert path not in monitor.paths proxy.add_path(path) assert path not in monitor.paths hupper-1.9.1/tests/util.py0000644€Déíè€bP^q0000000531413441505433021312 0ustar michaelDA\Domain Users00000000000000import os import subprocess import sys import tempfile import threading import time here = os.path.abspath(os.path.dirname(__file__)) class TestApp(threading.Thread): name = None args = None stdin = None daemon = True def __init__(self): super(TestApp, self).__init__() self.exitcode = None self.process = None self.tmpfile = None self.tmpsize = 0 self.response = None self.stdout, self.stderr = b'', b'' def start(self, name, args): self.name = name self.args = args or [] fd, self.tmpfile = tempfile.mkstemp() os.close(fd) touch(self.tmpfile) self.tmpsize = os.path.getsize(self.tmpfile) self.response = readfile(self.tmpfile) super(TestApp, self).start() def run(self): cmd = [sys.executable, '-m', 'tests.' + self.name] if self.tmpfile: cmd += ['--callback-file', self.tmpfile] cmd += self.args env = os.environ.copy() env['PYTHONUNBUFFERED'] = '1' self.process = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, universal_newlines=True, ) try: self.stdout, self.stderr = self.process.communicate(self.stdin) finally: self.exitcode = self.process.wait() def is_alive(self): return self.process is not None and self.exitcode is None def stop(self): if self.is_alive(): self.process.terminate() self.join() if self.tmpfile: os.unlink(self.tmpfile) self.tmpfile = None def wait_for_response(self, timeout=5, interval=0.1): self.tmpsize = wait_for_change( self.tmpfile, last_size=self.tmpsize, timeout=timeout, interval=interval, ) self.response = readfile(self.tmpfile) def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) def readfile(path): with open(path, 'rb') as fp: return fp.readlines() def wait_for_change(path, last_size=0, timeout=5, interval=0.1): start = time.time() size = os.path.getsize(path) while size == last_size: duration = time.time() - start sleepfor = interval if timeout is not None: # pragma: no cover if duration >= timeout: raise RuntimeError( 'timeout waiting for change to file=%s' % (path,) ) sleepfor = min(timeout - duration, sleepfor) time.sleep(sleepfor) size = os.path.getsize(path) return size hupper-1.9.1/tox.ini0000644€Déíè€bP^q0000000250313562615256020142 0ustar michaelDA\Domain Users00000000000000[tox] envlist = lint, py27,py34,py35,py36,py37,pypy,pypy3, docs,coverage isolated_build = true requires = pip >= 19 [testenv] commands = py.test --cov --cov-report= {posargs:} setenv = COVERAGE_FILE=.coverage.{envname} extras = testing [testenv:coverage] skip_install = true commands = coverage combine coverage report deps = coverage setenv = COVERAGE_FILE=.coverage [testenv:docs] whitelist_externals = make commands = make -C docs html BUILDDIR={envdir} SPHINXOPTS="-W -E" extras = docs [testenv:lint] skip_install = true commands = flake8 src/hupper/ black --check --diff src/hupper tests setup.py python setup.py check -r -s -m check-manifest deps = black check-manifest flake8 readme_renderer [testenv:black] skip_install = true commands = black src/hupper tests setup.py deps = black [testenv:build] skip_install = true commands = # clean up build/ and dist/ folders python -c 'import shutil; shutil.rmtree("dist", ignore_errors=True)' python setup.py clean --all # build sdist python setup.py sdist --dist-dir {toxinidir}/dist # build wheel from sdist pip wheel -v --no-deps --no-index --no-build-isolation --wheel-dir {toxinidir}/dist --find-links {toxinidir}/dist hupper deps = setuptools wheel