├── tests ├── __init__.py ├── test_logger.py ├── test_cli.py ├── test_config.py └── test_monitor.py ├── pymon ├── __init__.py ├── logger.py ├── main.py └── monitor.py ├── pytest.ini ├── CHANGELOG.md ├── .github └── workflows │ └── tests.yml ├── LICENSE ├── setup.py ├── README.md └── .gitignore /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pymon/__init__.py: -------------------------------------------------------------------------------- 1 | from .logger import * 2 | 3 | __version__ = "2.2.0" 4 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | testpaths = tests 3 | python_files = test_*.py 4 | python_classes = Test* 5 | python_functions = test_* 6 | addopts = -v --tb=short 7 | 8 | -------------------------------------------------------------------------------- /pymon/logger.py: -------------------------------------------------------------------------------- 1 | from colorama import Fore, Style 2 | 3 | 4 | class Color: 5 | GREEN = Fore.GREEN 6 | YELLOW = Fore.YELLOW + Style.BRIGHT 7 | RED = Fore.RED 8 | CYAN = Fore.CYAN 9 | 10 | 11 | def log(colour, message): 12 | print(f"{colour}[pymon] {message}{Style.RESET_ALL}") 13 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 2.2.0 4 | - Added `--version` / `-V` to print the installed version. 5 | - Added config file support (`.pymonrc`, `pymon.json`). 6 | - Added GitHub Actions CI to run tests on push/PR. 7 | - Expanded docs: config file usage, test instructions. 8 | 9 | ## 2.1.0 10 | - Refreshed codebase and options (watch/ignore/exec/debug/clean). 11 | - Added colored logging and command input helpers (`rs`, `stop`). 12 | 13 | ## 2.0.x and earlier 14 | - Initial rewrite with auto-reload for Python scripts and shell commands. 15 | 16 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - "**" 7 | pull_request: 8 | branches: 9 | - "**" 10 | 11 | jobs: 12 | tests: 13 | runs-on: ubuntu-latest 14 | strategy: 15 | matrix: 16 | python-version: ["3.10", "3.11", "3.12"] 17 | 18 | steps: 19 | - name: Checkout repository 20 | uses: actions/checkout@v4 21 | 22 | - name: Set up Python 23 | uses: actions/setup-python@v5 24 | with: 25 | python-version: ${{ matrix.python-version }} 26 | 27 | - name: Install dependencies 28 | run: | 29 | python -m pip install --upgrade pip 30 | python -m pip install -e ".[dev]" 31 | 32 | - name: Run tests 33 | run: pytest 34 | 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2026 Kevin Thomas 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="py-mon", 8 | version="2.2.0", 9 | author="kevinjosethomas", 10 | author_email="kevin.jt2007@gmail.com", 11 | description="🔁 Automatically restart application when file changes are detected; made for development", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/kevinjosethomas/py-mon", 15 | keywords="development, testing, monitor", 16 | packages=setuptools.find_packages(), 17 | include_package_data=True, 18 | classifiers=[ 19 | "Programming Language :: Python :: 3", 20 | "License :: OSI Approved :: MIT License", 21 | "Operating System :: OS Independent", 22 | ], 23 | python_requires=">=3.6", 24 | entry_points={"console_scripts": ["pymon=pymon.main:main"]}, 25 | install_requires=[ 26 | "colorama", 27 | "watchdog", 28 | ], 29 | extras_require={ 30 | "dev": [ 31 | "pytest>=7.0.0", 32 | ], 33 | }, 34 | ) 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # py-mon [![](https://img.shields.io/pypi/v/py-mon?color=3776AB&logo=python&style=for-the-badge)](https://pypi.org/project/py-mon/) [![](https://img.shields.io/pypi/dm/py-mon?color=3776AB&logo=python&style=for-the-badge)](https://pypi.org/project/py-mon/) 2 | A modern, easy-to-use package to automatically restart a Python application when file changes are detected! 3 | 4 | ## Quickstart (10s) 5 | ```bash 6 | pip install -U py-mon 7 | pymon app.py 8 | ``` 9 | Zero-config reloads for Python files by default. 10 | 11 | ### Why py-mon? 12 | - Works for Python files or any shell command (`-x "npm run dev"`). 13 | - Simple patterns for watch/ignore; sane defaults. 14 | - Clean/quiet mode available when you don’t want prompts. 15 | 16 | ### Core flags 17 | - `-w / --watch `: what to watch (default `*.py`). 18 | - `-i / --ignore `: what to ignore. 19 | - `-x / --exec`: run a shell command instead of `python `. 20 | - `-d / --debug`: print changed paths. 21 | - `-c / --clean`: no logs, no stdin commands. 22 | 23 | ### Command Input 24 | When running pymon, you can use these commands: 25 | - Type `rs` to manually restart the process 26 | - Type `stop` to terminate pymon 27 | 28 | ### Optional Config File 29 | Put a `.pymonrc` or `pymon.json` in your project root to keep team settings consistent: 30 | 31 | ```json 32 | { 33 | "watch": ["*.py", "config/*.yaml"], 34 | "ignore": ["*__pycache__*", "*.log"], 35 | "debug": false, 36 | "clean": false, 37 | "exec": false, 38 | "delay": 250 39 | } 40 | ``` 41 | 42 | Command line arguments will always override config file settings. 43 | 44 | Anyway that's basically it! Thanks for everything, I would appreciate it if you could leave a follow or star this repository ❣️ If you have any feature requests, read below! 45 | 46 | ## Contributing 47 | This package is open source so anyone with adequate Python experience can contribute to this project! 48 | 49 | ### Report Issues 50 | If you find any issues with the package or in the code, please [create an issue and report it here](https://github.com/kevinjosethomas/py-mon/issues)! 51 | 52 | ### Fix/Edit Content 53 | If you want to contribute to this package, fork the repository, clone it, make your changes and then [proceed to create a pull request here](https://github.com/kevinjosethomas/py-mon/pulls) 54 | 55 | ### Tests 56 | Run the test suite locally with pytest: 57 | ``` 58 | pip install -e ".[dev]" 59 | pytest 60 | ``` -------------------------------------------------------------------------------- /tests/test_logger.py: -------------------------------------------------------------------------------- 1 | """Tests for the logger module.""" 2 | 3 | import pytest 4 | from unittest.mock import patch 5 | from colorama import Fore, Style 6 | 7 | from pymon.logger import log, Color 8 | 9 | 10 | class TestColor: 11 | """Tests for Color class constants.""" 12 | 13 | def test_green_color(self): 14 | """Should have green color defined.""" 15 | assert Color.GREEN == Fore.GREEN 16 | 17 | def test_yellow_color(self): 18 | """Should have yellow bright color defined.""" 19 | assert Color.YELLOW == Fore.YELLOW + Style.BRIGHT 20 | 21 | def test_red_color(self): 22 | """Should have red color defined.""" 23 | assert Color.RED == Fore.RED 24 | 25 | def test_cyan_color(self): 26 | """Should have cyan color defined.""" 27 | assert Color.CYAN == Fore.CYAN 28 | 29 | 30 | class TestLog: 31 | """Tests for the log function.""" 32 | 33 | def test_log_formats_message(self, capsys): 34 | """Should format message with pymon prefix.""" 35 | log(Color.GREEN, "test message") 36 | 37 | captured = capsys.readouterr() 38 | assert "[pymon]" in captured.out 39 | assert "test message" in captured.out 40 | 41 | def test_log_includes_color(self, capsys): 42 | """Should include color codes in output.""" 43 | log(Color.GREEN, "test") 44 | 45 | captured = capsys.readouterr() 46 | assert Fore.GREEN in captured.out 47 | 48 | def test_log_resets_style(self, capsys): 49 | """Should reset style after message.""" 50 | log(Color.RED, "test") 51 | 52 | captured = capsys.readouterr() 53 | assert Style.RESET_ALL in captured.out 54 | 55 | def test_log_different_colors(self, capsys): 56 | """Should work with different colors.""" 57 | log(Color.GREEN, "green") 58 | log(Color.YELLOW, "yellow") 59 | log(Color.RED, "red") 60 | log(Color.CYAN, "cyan") 61 | 62 | captured = capsys.readouterr() 63 | assert "green" in captured.out 64 | assert "yellow" in captured.out 65 | assert "red" in captured.out 66 | assert "cyan" in captured.out 67 | 68 | def test_log_empty_message(self, capsys): 69 | """Should handle empty message.""" 70 | log(Color.GREEN, "") 71 | 72 | captured = capsys.readouterr() 73 | assert "[pymon]" in captured.out 74 | 75 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | .vscode/ 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | pip-wheel-metadata/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | .python-version 87 | 88 | # virtualenv 89 | Scripts 90 | pyvenv.cfg 91 | 92 | # pipenv 93 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 94 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 95 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 96 | # install all needed dependencies. 97 | #Pipfile.lock 98 | 99 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 100 | __pypackages__/ 101 | 102 | # Celery stuff 103 | celerybeat-schedule 104 | celerybeat.pid 105 | 106 | # SageMath parsed files 107 | *.sage.py 108 | 109 | # Environments 110 | .env 111 | .venv 112 | env/ 113 | venv/ 114 | ENV/ 115 | env.bak/ 116 | venv.bak/ 117 | 118 | # Spyder project settings 119 | .spyderproject 120 | .spyproject 121 | 122 | # Rope project settings 123 | .ropeproject 124 | 125 | # mkdocs documentation 126 | /site 127 | 128 | # mypy 129 | .mypy_cache/ 130 | .dmypy.json 131 | dmypy.json 132 | 133 | # Pyre type checker 134 | .pyre/ 135 | -------------------------------------------------------------------------------- /pymon/main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import time 3 | import argparse 4 | import colorama 5 | from pathlib import Path 6 | 7 | from .monitor import Monitor 8 | from .logger import log, Color 9 | from . import __version__ 10 | 11 | CONFIG_FILES = [".pymonrc", "pymon.json"] 12 | 13 | 14 | def load_config(): 15 | """Load configuration from .pymonrc or pymon.json if present.""" 16 | for config_name in CONFIG_FILES: 17 | config_path = Path(config_name) 18 | if config_path.exists(): 19 | try: 20 | with open(config_path, "r") as f: 21 | config = json.load(f) 22 | return config, config_name 23 | except json.JSONDecodeError as e: 24 | log(Color.RED, f"Error parsing {config_name}: {e}") 25 | return {}, None 26 | except OSError as e: 27 | log(Color.RED, f"Error reading {config_name}: {e}") 28 | return {}, None 29 | return {}, None 30 | 31 | 32 | def merge_config(args, config): 33 | """Merge config file settings with command line arguments. CLI takes precedence.""" 34 | 35 | if args.watch is None: 36 | args.watch = config.get("watch", ["*.py"]) 37 | 38 | if not args.ignore: 39 | args.ignore = config.get("ignore", []) 40 | 41 | if not args.debug: 42 | args.debug = config.get("debug", False) 43 | 44 | if not args.clean: 45 | args.clean = config.get("clean", False) 46 | 47 | if not args.exec: 48 | args.exec = config.get("exec", False) 49 | 50 | return args 51 | 52 | 53 | parser = argparse.ArgumentParser( 54 | prog="pymon", 55 | ) 56 | 57 | parser.add_argument( 58 | "-V", 59 | "--version", 60 | action="version", 61 | version=f"%(prog)s {__version__}", 62 | help="show the py-mon version and exit", 63 | ) 64 | 65 | parser.add_argument( 66 | "command", 67 | type=str, 68 | help="the file to be executed or command to run with pymon", 69 | metavar="command", 70 | ) 71 | 72 | parser.add_argument( 73 | "-w", 74 | "--watch", 75 | type=str, 76 | help="paths/patterns to watch (e.g., 'src/*.py', 'data/**/*.json'). use once for each path/pattern. default is '*.py'", 77 | action="append", 78 | default=None, 79 | metavar="path_pattern", 80 | ) 81 | 82 | parser.add_argument( 83 | "-d", 84 | "--debug", 85 | help="logs detected file changes to the terminal", 86 | action="store_true", 87 | ) 88 | 89 | parser.add_argument( 90 | "-c", 91 | "--clean", 92 | help="runs pymon in clean mode (no logs, no commands)", 93 | action="store_true", 94 | ) 95 | 96 | parser.add_argument( 97 | "-i", 98 | "--ignore", 99 | type=str, 100 | help="patterns of files/paths to ignore. use once for each pattern.", 101 | action="append", 102 | default=[], 103 | metavar="patterns", 104 | ) 105 | 106 | parser.add_argument( 107 | "-x", 108 | "--exec", 109 | help="execute a shell command instead of running a Python file", 110 | action="store_true", 111 | default=False, 112 | ) 113 | 114 | 115 | def main(): 116 | colorama.init() 117 | arguments = parser.parse_args() 118 | 119 | config, config_name = load_config() 120 | if config and not arguments.clean: 121 | log(Color.CYAN, f"using config from {config_name}") 122 | arguments = merge_config(arguments, config) 123 | 124 | monitor = Monitor(arguments) 125 | monitor.start() 126 | 127 | try: 128 | while True: 129 | if not arguments.clean: 130 | cmd = input() 131 | if cmd == "rs": 132 | monitor.restart_process() 133 | elif cmd == "stop": 134 | monitor.stop() 135 | break 136 | else: 137 | time.sleep(1) 138 | except KeyboardInterrupt: 139 | monitor.stop() 140 | 141 | return 142 | 143 | 144 | if __name__ == "__main__": 145 | main() 146 | -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | """Tests for CLI argument parsing.""" 2 | 3 | import pytest 4 | from pymon.main import parser 5 | from pymon import __version__ 6 | 7 | 8 | class TestCLIArguments: 9 | """Tests for command line argument parsing.""" 10 | 11 | def test_command_required(self): 12 | """Should require command argument.""" 13 | with pytest.raises(SystemExit): 14 | parser.parse_args([]) 15 | 16 | def test_command_parsed(self): 17 | """Should parse command argument.""" 18 | args = parser.parse_args(["app.py"]) 19 | assert args.command == "app.py" 20 | 21 | def test_watch_default_none(self): 22 | """Should have None as default watch (merged later).""" 23 | args = parser.parse_args(["app.py"]) 24 | assert args.watch is None 25 | 26 | def test_watch_single(self): 27 | """Should parse single watch pattern.""" 28 | args = parser.parse_args(["app.py", "-w", "*.json"]) 29 | assert args.watch == ["*.json"] 30 | 31 | def test_watch_multiple(self): 32 | """Should parse multiple watch patterns.""" 33 | args = parser.parse_args(["app.py", "-w", "*.py", "-w", "*.json"]) 34 | assert args.watch == ["*.py", "*.json"] 35 | 36 | def test_watch_long_form(self): 37 | """Should parse --watch long form.""" 38 | args = parser.parse_args(["app.py", "--watch", "src/*.py"]) 39 | assert args.watch == ["src/*.py"] 40 | 41 | def test_ignore_default_empty(self): 42 | """Should have empty list as default ignore.""" 43 | args = parser.parse_args(["app.py"]) 44 | assert args.ignore == [] 45 | 46 | def test_ignore_single(self): 47 | """Should parse single ignore pattern.""" 48 | args = parser.parse_args(["app.py", "-i", "*.log"]) 49 | assert args.ignore == ["*.log"] 50 | 51 | def test_ignore_multiple(self): 52 | """Should parse multiple ignore patterns.""" 53 | args = parser.parse_args(["app.py", "-i", "*.log", "-i", "*__pycache__*"]) 54 | assert args.ignore == ["*.log", "*__pycache__*"] 55 | 56 | def test_debug_default_false(self): 57 | """Should have False as default debug.""" 58 | args = parser.parse_args(["app.py"]) 59 | assert args.debug is False 60 | 61 | def test_debug_flag(self): 62 | """Should set debug to True with -d flag.""" 63 | args = parser.parse_args(["app.py", "-d"]) 64 | assert args.debug is True 65 | 66 | def test_debug_long_form(self): 67 | """Should set debug with --debug.""" 68 | args = parser.parse_args(["app.py", "--debug"]) 69 | assert args.debug is True 70 | 71 | def test_clean_default_false(self): 72 | """Should have False as default clean.""" 73 | args = parser.parse_args(["app.py"]) 74 | assert args.clean is False 75 | 76 | def test_clean_flag(self): 77 | """Should set clean to True with -c flag.""" 78 | args = parser.parse_args(["app.py", "-c"]) 79 | assert args.clean is True 80 | 81 | def test_exec_default_false(self): 82 | """Should have False as default exec.""" 83 | args = parser.parse_args(["app.py"]) 84 | assert args.exec is False 85 | 86 | def test_exec_flag(self): 87 | """Should set exec to True with -x flag.""" 88 | args = parser.parse_args(["app.py", "-x"]) 89 | assert args.exec is True 90 | 91 | def test_combined_flags(self): 92 | """Should parse multiple flags together.""" 93 | args = parser.parse_args([ 94 | "npm run dev", 95 | "-x", 96 | "-d", 97 | "-w", "*.js", 98 | "-w", "*.jsx", 99 | "-i", "node_modules", 100 | ]) 101 | 102 | assert args.command == "npm run dev" 103 | assert args.exec is True 104 | assert args.debug is True 105 | assert args.watch == ["*.js", "*.jsx"] 106 | assert args.ignore == ["node_modules"] 107 | 108 | def test_shell_command_with_exec(self): 109 | """Should accept shell commands with exec mode.""" 110 | args = parser.parse_args(["python -m http.server", "-x"]) 111 | assert args.command == "python -m http.server" 112 | assert args.exec is True 113 | 114 | def test_version_flag(self, capsys): 115 | """Should print version and exit.""" 116 | with pytest.raises(SystemExit) as excinfo: 117 | parser.parse_args(["--version"]) 118 | 119 | assert excinfo.value.code == 0 120 | out = capsys.readouterr().out 121 | assert __version__ in out 122 | 123 | def test_version_short_flag(self, capsys): 124 | """Should print version with short flag and exit.""" 125 | with pytest.raises(SystemExit) as excinfo: 126 | parser.parse_args(["-V"]) 127 | 128 | assert excinfo.value.code == 0 129 | out = capsys.readouterr().out 130 | assert __version__ in out 131 | 132 | -------------------------------------------------------------------------------- /pymon/monitor.py: -------------------------------------------------------------------------------- 1 | import fnmatch 2 | import argparse 3 | import subprocess 4 | from .logger import * 5 | from sys import executable 6 | from pathlib import Path 7 | from watchdog.observers import Observer 8 | from watchdog.events import PatternMatchingEventHandler, FileSystemEvent 9 | 10 | 11 | 12 | class Monitor: 13 | def _handle_event(self, event: FileSystemEvent): 14 | """ 15 | Handle the event when a file is modified, created, deleted, or moved. 16 | """ 17 | 18 | for ignore_pattern in self.ignore_patterns: 19 | if self._matches_pattern(event.src_path, ignore_pattern): 20 | if self.debug: 21 | log(Color.CYAN, f"Ignoring change in {event.src_path}") 22 | return 23 | 24 | if not self.clean: 25 | log(Color.YELLOW, "restarting due to changes detected...") 26 | 27 | if self.debug: 28 | log(Color.CYAN, f"{event.event_type} {event.src_path}") 29 | 30 | self.restart_process() 31 | 32 | def _matches_pattern(self, path: str, pattern: str) -> bool: 33 | """ 34 | Check if the given path matches the pattern. 35 | """ 36 | 37 | return fnmatch.fnmatch(path, pattern) 38 | 39 | def _parse_watch_path(self, path_pattern: str) -> tuple[str, str]: 40 | """ 41 | Parse a path pattern like 'src/*.py' to extract directory and pattern. 42 | Returns (directory_to_watch, file_pattern) 43 | """ 44 | 45 | path = Path(path_pattern) 46 | 47 | if any(char in str(path) for char in '*?[]'): 48 | parts = path.parts 49 | pattern_index = 0 50 | 51 | for i, part in enumerate(parts): 52 | if any(char in part for char in '*?[]'): 53 | pattern_index = i 54 | break 55 | 56 | if pattern_index > 0: 57 | directory = str(Path(*parts[:pattern_index])) 58 | pattern = str(Path(*parts[pattern_index:])) 59 | else: 60 | directory = '.' 61 | pattern = path_pattern 62 | 63 | if not directory: 64 | directory = '.' 65 | 66 | return directory, pattern 67 | else: 68 | return path_pattern, '*' 69 | 70 | def __init__(self, arguments: argparse.Namespace): 71 | self.command = arguments.command 72 | self.debug = arguments.debug 73 | self.clean = arguments.clean 74 | self.exec_mode = arguments.exec 75 | self.ignore_patterns = arguments.ignore 76 | 77 | self.watch_items = [] 78 | self.patterns = [] 79 | 80 | for path_pattern in arguments.watch: 81 | directory, pattern = self._parse_watch_path(path_pattern) 82 | self.patterns.append(pattern) 83 | self.watch_items.append((directory, pattern)) 84 | 85 | self.process = None 86 | 87 | self.event_handler = PatternMatchingEventHandler( 88 | patterns=self.patterns, 89 | ignore_patterns=self.ignore_patterns 90 | ) 91 | 92 | self.event_handler.on_modified = self._handle_event 93 | self.event_handler.on_created = self._handle_event 94 | self.event_handler.on_deleted = self._handle_event 95 | self.event_handler.on_moved = self._handle_event 96 | 97 | self.observers = [] 98 | for directory, _ in self.watch_items: 99 | observer = Observer() 100 | observer.schedule(self.event_handler, directory, recursive=True) 101 | self.observers.append(observer) 102 | 103 | def start(self): 104 | """ 105 | Start the monitor and observers. 106 | """ 107 | 108 | if not self.clean: 109 | for directory, pattern in self.watch_items: 110 | log(Color.YELLOW, f"watching {pattern} in {directory}") 111 | 112 | if self.ignore_patterns: 113 | log(Color.YELLOW, f"ignoring patterns: {', '.join(self.ignore_patterns)}") 114 | 115 | log(Color.YELLOW, "enter 'rs' to restart or 'stop' to terminate") 116 | 117 | for observer in self.observers: 118 | observer.start() 119 | 120 | self.start_process() 121 | 122 | def stop(self): 123 | """ 124 | Stop the monitor and observers. 125 | """ 126 | 127 | self.stop_process() 128 | 129 | for observer in self.observers: 130 | observer.stop() 131 | observer.join() 132 | 133 | if not self.clean: 134 | log(Color.RED, "terminated process") 135 | 136 | def restart_process(self): 137 | """ 138 | Restart the process. 139 | """ 140 | 141 | self.stop_process() 142 | self.start_process() 143 | 144 | def start_process(self): 145 | if not self.clean: 146 | log(Color.GREEN, f"starting {self.command}") 147 | 148 | if self.exec_mode: 149 | if not self.clean: 150 | log(Color.GREEN, f"executing: {self.command}") 151 | self.process = subprocess.Popen(self.command, shell=True) 152 | else: 153 | py_command = self.command + (".py" if not self.command.endswith(".py") else "") 154 | self.process = subprocess.Popen([executable, py_command]) 155 | 156 | def stop_process(self): 157 | """ 158 | Stop the process. 159 | """ 160 | 161 | if self.process: 162 | self.process.terminate() 163 | self.process = None 164 | -------------------------------------------------------------------------------- /tests/test_config.py: -------------------------------------------------------------------------------- 1 | """Tests for config file loading and merging.""" 2 | 3 | import json 4 | import pytest 5 | from argparse import Namespace 6 | from pathlib import Path 7 | from unittest.mock import patch, mock_open 8 | 9 | from pymon.main import load_config, merge_config 10 | 11 | 12 | class TestLoadConfig: 13 | """Tests for the load_config function.""" 14 | 15 | def test_load_pymonrc(self, tmp_path, monkeypatch): 16 | """Should load config from .pymonrc file.""" 17 | monkeypatch.chdir(tmp_path) 18 | 19 | config_data = {"watch": ["*.py", "*.json"], "debug": True} 20 | config_file = tmp_path / ".pymonrc" 21 | config_file.write_text(json.dumps(config_data)) 22 | 23 | config, name = load_config() 24 | 25 | assert name == ".pymonrc" 26 | assert config == config_data 27 | 28 | def test_load_pymon_json(self, tmp_path, monkeypatch): 29 | """Should load config from pymon.json file.""" 30 | monkeypatch.chdir(tmp_path) 31 | 32 | config_data = {"watch": ["src/*.py"], "ignore": ["*.log"]} 33 | config_file = tmp_path / "pymon.json" 34 | config_file.write_text(json.dumps(config_data)) 35 | 36 | config, name = load_config() 37 | 38 | assert name == "pymon.json" 39 | assert config == config_data 40 | 41 | def test_pymonrc_takes_priority(self, tmp_path, monkeypatch): 42 | """Should prefer .pymonrc over pymon.json when both exist.""" 43 | monkeypatch.chdir(tmp_path) 44 | 45 | pymonrc_data = {"watch": ["from_pymonrc"]} 46 | pymon_json_data = {"watch": ["from_pymon_json"]} 47 | 48 | (tmp_path / ".pymonrc").write_text(json.dumps(pymonrc_data)) 49 | (tmp_path / "pymon.json").write_text(json.dumps(pymon_json_data)) 50 | 51 | config, name = load_config() 52 | 53 | assert name == ".pymonrc" 54 | assert config["watch"] == ["from_pymonrc"] 55 | 56 | def test_no_config_file(self, tmp_path, monkeypatch): 57 | """Should return empty config when no config file exists.""" 58 | monkeypatch.chdir(tmp_path) 59 | 60 | config, name = load_config() 61 | 62 | assert config == {} 63 | assert name is None 64 | 65 | def test_unreadable_config_file(self, tmp_path, monkeypatch): 66 | """Should handle unreadable config file gracefully.""" 67 | monkeypatch.chdir(tmp_path) 68 | 69 | config_file = tmp_path / ".pymonrc" 70 | config_file.write_text("{}") 71 | 72 | with patch("builtins.open", side_effect=PermissionError("denied")): 73 | config, name = load_config() 74 | 75 | assert config == {} 76 | assert name is None 77 | 78 | def test_invalid_json(self, tmp_path, monkeypatch, capsys): 79 | """Should handle invalid JSON gracefully.""" 80 | monkeypatch.chdir(tmp_path) 81 | 82 | config_file = tmp_path / ".pymonrc" 83 | config_file.write_text("{ invalid json }") 84 | 85 | config, name = load_config() 86 | 87 | assert config == {} 88 | assert name is None 89 | 90 | def test_empty_config_file(self, tmp_path, monkeypatch): 91 | """Should handle empty config object.""" 92 | monkeypatch.chdir(tmp_path) 93 | 94 | config_file = tmp_path / ".pymonrc" 95 | config_file.write_text("{}") 96 | 97 | config, name = load_config() 98 | 99 | assert config == {} 100 | assert name == ".pymonrc" 101 | 102 | 103 | class TestMergeConfig: 104 | """Tests for the merge_config function.""" 105 | 106 | def create_args(self, **kwargs): 107 | """Helper to create a Namespace with default values.""" 108 | defaults = { 109 | "command": "app.py", 110 | "watch": None, 111 | "ignore": [], 112 | "debug": False, 113 | "clean": False, 114 | "exec": False, 115 | } 116 | defaults.update(kwargs) 117 | return Namespace(**defaults) 118 | 119 | def test_config_sets_watch(self): 120 | """Config should set watch patterns when CLI doesn't specify.""" 121 | args = self.create_args(watch=None) 122 | config = {"watch": ["src/*.py", "*.json"]} 123 | 124 | result = merge_config(args, config) 125 | 126 | assert result.watch == ["src/*.py", "*.json"] 127 | 128 | def test_cli_watch_overrides_config(self): 129 | """CLI watch should override config watch.""" 130 | args = self.create_args(watch=["cli/*.py"]) 131 | config = {"watch": ["config/*.py"]} 132 | 133 | result = merge_config(args, config) 134 | 135 | assert result.watch == ["cli/*.py"] 136 | 137 | def test_default_watch_when_no_config(self): 138 | """Should use default *.py when no CLI or config watch.""" 139 | args = self.create_args(watch=None) 140 | config = {} 141 | 142 | result = merge_config(args, config) 143 | 144 | assert result.watch == ["*.py"] 145 | 146 | def test_config_sets_ignore(self): 147 | """Config should set ignore patterns when CLI doesn't specify.""" 148 | args = self.create_args(ignore=[]) 149 | config = {"ignore": ["*.log", "*__pycache__*"]} 150 | 151 | result = merge_config(args, config) 152 | 153 | assert result.ignore == ["*.log", "*__pycache__*"] 154 | 155 | def test_cli_ignore_overrides_config(self): 156 | """CLI ignore should override config ignore.""" 157 | args = self.create_args(ignore=["cli_ignore"]) 158 | config = {"ignore": ["config_ignore"]} 159 | 160 | result = merge_config(args, config) 161 | 162 | assert result.ignore == ["cli_ignore"] 163 | 164 | def test_config_sets_debug(self): 165 | """Config should set debug when CLI doesn't specify.""" 166 | args = self.create_args(debug=False) 167 | config = {"debug": True} 168 | 169 | result = merge_config(args, config) 170 | 171 | assert result.debug is True 172 | 173 | def test_cli_debug_overrides_config(self): 174 | """CLI debug should override config debug.""" 175 | args = self.create_args(debug=True) 176 | config = {"debug": False} 177 | 178 | result = merge_config(args, config) 179 | 180 | assert result.debug is True 181 | 182 | def test_config_sets_clean(self): 183 | """Config should set clean when CLI doesn't specify.""" 184 | args = self.create_args(clean=False) 185 | config = {"clean": True} 186 | 187 | result = merge_config(args, config) 188 | 189 | assert result.clean is True 190 | 191 | def test_config_sets_exec(self): 192 | """Config should set exec when CLI doesn't specify.""" 193 | args = self.create_args(exec=False) 194 | config = {"exec": True} 195 | 196 | result = merge_config(args, config) 197 | 198 | assert result.exec is True 199 | 200 | def test_empty_config_uses_defaults(self): 201 | """Empty config should result in default values.""" 202 | args = self.create_args() 203 | config = {} 204 | 205 | result = merge_config(args, config) 206 | 207 | assert result.watch == ["*.py"] 208 | assert result.ignore == [] 209 | assert result.debug is False 210 | assert result.clean is False 211 | assert result.exec is False 212 | 213 | def test_partial_config(self): 214 | """Should handle partial config with some fields.""" 215 | args = self.create_args() 216 | config = {"watch": ["*.py", "*.json"], "debug": True} 217 | 218 | result = merge_config(args, config) 219 | 220 | assert result.watch == ["*.py", "*.json"] 221 | assert result.debug is True 222 | assert result.ignore == [] 223 | assert result.clean is False 224 | assert result.exec is False 225 | -------------------------------------------------------------------------------- /tests/test_monitor.py: -------------------------------------------------------------------------------- 1 | """Tests for the Monitor class.""" 2 | 3 | import pytest 4 | from argparse import Namespace 5 | from unittest.mock import Mock, patch, MagicMock 6 | 7 | from pymon.monitor import Monitor 8 | 9 | 10 | class TestMonitorPathParsing: 11 | """Tests for path pattern parsing in Monitor.""" 12 | 13 | def create_monitor(self, **kwargs): 14 | """Helper to create a Monitor with default args.""" 15 | defaults = { 16 | "command": "app.py", 17 | "watch": ["*.py"], 18 | "ignore": [], 19 | "debug": False, 20 | "clean": False, 21 | "exec": False, 22 | } 23 | defaults.update(kwargs) 24 | args = Namespace(**defaults) 25 | 26 | with patch.object(Monitor, '__init__', lambda self, args: None): 27 | monitor = Monitor.__new__(Monitor) 28 | monitor.command = args.command 29 | monitor.debug = args.debug 30 | monitor.clean = args.clean 31 | monitor.exec_mode = args.exec 32 | monitor.ignore_patterns = args.ignore 33 | 34 | return monitor, args 35 | 36 | def test_parse_simple_pattern(self): 37 | """Should parse simple glob pattern.""" 38 | monitor, _ = self.create_monitor() 39 | 40 | directory, pattern = monitor._parse_watch_path("*.py") 41 | 42 | assert directory == "." 43 | assert pattern == "*.py" 44 | 45 | def test_parse_directory_pattern(self): 46 | """Should parse pattern with directory.""" 47 | monitor, _ = self.create_monitor() 48 | 49 | directory, pattern = monitor._parse_watch_path("src/*.py") 50 | 51 | assert directory == "src" 52 | assert pattern == "*.py" 53 | 54 | def test_parse_nested_directory_pattern(self): 55 | """Should parse pattern with nested directories.""" 56 | monitor, _ = self.create_monitor() 57 | 58 | directory, pattern = monitor._parse_watch_path("src/lib/*.py") 59 | 60 | assert directory == "src/lib" 61 | assert pattern == "*.py" 62 | 63 | def test_parse_recursive_pattern(self): 64 | """Should parse recursive glob pattern.""" 65 | monitor, _ = self.create_monitor() 66 | 67 | directory, pattern = monitor._parse_watch_path("src/**/*.py") 68 | 69 | assert directory == "src" 70 | assert pattern == "**/*.py" 71 | 72 | def test_parse_plain_directory(self): 73 | """Should handle plain directory without glob.""" 74 | monitor, _ = self.create_monitor() 75 | 76 | directory, pattern = monitor._parse_watch_path("src") 77 | 78 | assert directory == "src" 79 | assert pattern == "*" 80 | 81 | def test_parse_question_mark_glob(self): 82 | """Should handle ? glob character.""" 83 | monitor, _ = self.create_monitor() 84 | 85 | directory, pattern = monitor._parse_watch_path("src/file?.py") 86 | 87 | assert directory == "src" 88 | assert pattern == "file?.py" 89 | 90 | def test_parse_bracket_glob(self): 91 | """Should handle [] glob characters.""" 92 | monitor, _ = self.create_monitor() 93 | 94 | directory, pattern = monitor._parse_watch_path("src/file[0-9].py") 95 | 96 | assert directory == "src" 97 | assert pattern == "file[0-9].py" 98 | 99 | 100 | class TestMonitorPatternMatching: 101 | """Tests for pattern matching in Monitor.""" 102 | 103 | def create_monitor(self): 104 | """Helper to create a Monitor instance.""" 105 | with patch.object(Monitor, '__init__', lambda self, args: None): 106 | monitor = Monitor.__new__(Monitor) 107 | return monitor 108 | 109 | def test_matches_simple_pattern(self): 110 | """Should match simple glob pattern.""" 111 | monitor = self.create_monitor() 112 | 113 | assert monitor._matches_pattern("test.py", "*.py") is True 114 | assert monitor._matches_pattern("test.js", "*.py") is False 115 | 116 | def test_matches_directory_pattern(self): 117 | """Should match pattern with directory.""" 118 | monitor = self.create_monitor() 119 | 120 | assert monitor._matches_pattern("src/test.py", "src/*.py") is True 121 | assert monitor._matches_pattern("lib/test.py", "src/*.py") is False 122 | 123 | def test_matches_pycache_pattern(self): 124 | """Should match __pycache__ pattern.""" 125 | monitor = self.create_monitor() 126 | 127 | assert monitor._matches_pattern("src/__pycache__/test.pyc", "*__pycache__*") is True 128 | assert monitor._matches_pattern("src/test.py", "*__pycache__*") is False 129 | 130 | def test_matches_log_pattern(self): 131 | """Should match log file pattern.""" 132 | monitor = self.create_monitor() 133 | 134 | assert monitor._matches_pattern("debug.log", "*.log") is True 135 | assert monitor._matches_pattern("app.py", "*.log") is False 136 | 137 | 138 | class TestMonitorInitialization: 139 | """Tests for Monitor initialization.""" 140 | 141 | def test_init_with_single_watch(self): 142 | """Should initialize with a single watch pattern.""" 143 | args = Namespace( 144 | command="app.py", 145 | watch=["*.py"], 146 | ignore=[], 147 | debug=False, 148 | clean=False, 149 | exec=False, 150 | ) 151 | 152 | monitor = Monitor(args) 153 | 154 | assert monitor.command == "app.py" 155 | assert (".", "*.py") in monitor.watch_items 156 | assert monitor.debug is False 157 | assert monitor.clean is False 158 | assert monitor.exec_mode is False 159 | 160 | def test_init_with_multiple_watch(self): 161 | """Should initialize with multiple watch patterns.""" 162 | args = Namespace( 163 | command="app.py", 164 | watch=["*.py", "config/*.json"], 165 | ignore=[], 166 | debug=False, 167 | clean=False, 168 | exec=False, 169 | ) 170 | 171 | monitor = Monitor(args) 172 | 173 | assert len(monitor.watch_items) == 2 174 | assert (".", "*.py") in monitor.watch_items 175 | assert ("config", "*.json") in monitor.watch_items 176 | 177 | def test_init_with_ignore_patterns(self): 178 | """Should initialize with ignore patterns.""" 179 | args = Namespace( 180 | command="app.py", 181 | watch=["*.py"], 182 | ignore=["*.log", "*__pycache__*"], 183 | debug=False, 184 | clean=False, 185 | exec=False, 186 | ) 187 | 188 | monitor = Monitor(args) 189 | 190 | assert monitor.ignore_patterns == ["*.log", "*__pycache__*"] 191 | 192 | def test_init_exec_mode(self): 193 | """Should initialize in exec mode.""" 194 | args = Namespace( 195 | command="npm run dev", 196 | watch=["*.js"], 197 | ignore=[], 198 | debug=False, 199 | clean=False, 200 | exec=True, 201 | ) 202 | 203 | monitor = Monitor(args) 204 | 205 | assert monitor.exec_mode is True 206 | assert monitor.command == "npm run dev" 207 | 208 | 209 | class TestMonitorProcessManagement: 210 | """Tests for process start/stop/restart.""" 211 | 212 | def create_args(self, **kwargs): 213 | """Helper to create args namespace.""" 214 | defaults = { 215 | "command": "app.py", 216 | "watch": ["*.py"], 217 | "ignore": [], 218 | "debug": False, 219 | "clean": True, # Use clean mode to suppress output 220 | "exec": False, 221 | } 222 | defaults.update(kwargs) 223 | return Namespace(**defaults) 224 | 225 | @patch("pymon.monitor.subprocess.Popen") 226 | def test_start_process_python_file(self, mock_popen): 227 | """Should start Python file with python executable.""" 228 | args = self.create_args(command="app.py") 229 | monitor = Monitor(args) 230 | 231 | monitor.start_process() 232 | 233 | mock_popen.assert_called_once() 234 | call_args = mock_popen.call_args 235 | assert "app.py" in call_args[0][0][1] 236 | 237 | @patch("pymon.monitor.subprocess.Popen") 238 | def test_start_process_adds_py_extension(self, mock_popen): 239 | """Should add .py extension if missing.""" 240 | args = self.create_args(command="app") 241 | monitor = Monitor(args) 242 | 243 | monitor.start_process() 244 | 245 | call_args = mock_popen.call_args 246 | assert "app.py" in call_args[0][0][1] 247 | 248 | @patch("pymon.monitor.subprocess.Popen") 249 | def test_start_process_exec_mode(self, mock_popen): 250 | """Should run shell command in exec mode.""" 251 | args = self.create_args(command="npm run dev", exec=True) 252 | monitor = Monitor(args) 253 | 254 | monitor.start_process() 255 | 256 | mock_popen.assert_called_once_with("npm run dev", shell=True) 257 | 258 | @patch("pymon.monitor.subprocess.Popen") 259 | def test_stop_process(self, mock_popen): 260 | """Should terminate running process.""" 261 | mock_process = Mock() 262 | mock_popen.return_value = mock_process 263 | 264 | args = self.create_args() 265 | monitor = Monitor(args) 266 | monitor.start_process() 267 | monitor.stop_process() 268 | 269 | mock_process.terminate.assert_called_once() 270 | assert monitor.process is None 271 | 272 | @patch("pymon.monitor.subprocess.Popen") 273 | def test_stop_process_when_none(self, mock_popen): 274 | """Should handle stop when no process is running.""" 275 | args = self.create_args() 276 | monitor = Monitor(args) 277 | 278 | # Should not raise 279 | monitor.stop_process() 280 | 281 | assert monitor.process is None 282 | 283 | @patch("pymon.monitor.subprocess.Popen") 284 | def test_restart_process(self, mock_popen): 285 | """Should stop and start process on restart.""" 286 | mock_process = Mock() 287 | mock_popen.return_value = mock_process 288 | 289 | args = self.create_args() 290 | monitor = Monitor(args) 291 | monitor.start_process() 292 | monitor.restart_process() 293 | 294 | mock_process.terminate.assert_called_once() 295 | assert mock_popen.call_count == 2 296 | 297 | --------------------------------------------------------------------------------