Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add functionality to watch a directory and rebuild targets on file changes #24

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,4 @@ __pycache__/

*ipynb_checkpoints*
hello_looper-master*
venv/
3 changes: 2 additions & 1 deletion markmeld/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
__version__ = "0.2.1-dev"
__version__ = "0.3.0-dev"

25 changes: 25 additions & 0 deletions markmeld/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from .exceptions import *
from .melder import MarkdownMelder
from .watcher import MarkmeldWatchDog
from .utilities import load_config_file, get_file_open_cmd
from ._version import __version__

Expand Down Expand Up @@ -64,6 +65,14 @@ def build_argparser():
# position 1
parser.add_argument(dest="target", metavar="T", help="Target", nargs="?")

parser.add_argument(
"-w",
"--watch",
dest="watch",
help="Watch file for changes and autocompile",
action="store_true",
)

parser.add_argument(
"-l",
"--list",
Expand Down Expand Up @@ -168,6 +177,22 @@ def main(test_args=None):
_LOGGER.error(f" {k}: {v}")
sys.exit(0)

# meld it and watch
if args.watch:
watcher = MarkmeldWatchDog(
".", cfg, args.target, print_only=args.print, vardump=args.dump
)
watcher.start()
try:
while watcher.is_alive():
watcher.join(1)
except KeyboardInterrupt:
_LOGGER.info("Stopping...")
finally:
watcher.stop()
watcher.join()
return

_LOGGER.debug("Melding...") # Meld it!
mm = MarkdownMelder(cfg)

Expand Down
61 changes: 61 additions & 0 deletions markmeld/watcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import logging
from pathlib import Path
from typing import Union
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler, DirModifiedEvent, FileModifiedEvent

from .melder import Target
from .melder import MarkdownMelder

_LOGGER = logging.getLogger(__name__)


class MarkmeldWatchDog(Observer):
"""
Watchdog observer to watch for file changes.
"""

def __init__(
self,
path: str,
cfg: dict,
target: str,
print_only: bool = False,
vardump: bool = False,
):
super().__init__()
_LOGGER.info(f"Watching {path} for changes...")
self._mm = MarkdownMelder(cfg)
self.target = Target(cfg, target)
self.path = path
self.print_only = print_only
self.vardump = vardump

# init the ignore files list (just the output files)
if "output_file" in self.target.root_cfg["targets"][target]:
ignore_file_name = Path(
self.target.root_cfg["targets"][target]["output_file"]
).name
self.ignore_files = [ignore_file_name]
else:
self.ignore_files = []

self.event_handler = LoggingEventHandler()
self.event_handler.on_modified = self.on_modified
self.schedule(self.event_handler, path, recursive=True)

def on_modified(self, event: Union[DirModifiedEvent, FileModifiedEvent]):
"""
Check for file or directory modification and then rerun the melder.
"""
p = Path(event.src_path)

# dont rebuild if the modified file or directory is the output file
# otherwise this causes an infinite loop
if p.name in self.ignore_files:
return

_LOGGER.info(f"File modified: {event.src_path}")
self._mm.build_target(
self.target.target_name, print_only=self.print_only, vardump=self.vardump
)
1 change: 1 addition & 0 deletions requirements/requirements-all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ logmuse
pyyaml
requests
ubiquerg
watchdog