Metadata-Version: 2.4
Name: memowatch
Version: 0.1.9
Summary: A modern, high-performance filesystem monitoring library for Python with async support, event debouncing, file settling detection, and content-aware diffing.
Author-email: Yogesh Gokul <yogeshgokul372@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/yogesh12s/memowatch
Project-URL: Documentation, https://github.com/yogesh12s/memowatch#readme
Project-URL: Issues, https://github.com/yogesh12s/memowatch/issues
Keywords: filesystem,monitoring,watchdog,inotify,fsevents,async
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: System :: Filesystems
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"

<div align="center">

# 🔭 memowatch

[![Python Versions](https://img.shields.io/pypi/pyversions/memowatch.svg?style=for-the-badge&logo=python&logoColor=white)](#)
[![PyPI version](https://img.shields.io/pypi/v/memowatch.svg?style=for-the-badge&logo=pypi&logoColor=white)](https://pypi.org/project/memowatch/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](https://opensource.org/licenses/MIT)
[![Buy Me A Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-ffdd00?style=for-the-badge&logo=buy-me-a-coffee&logoColor=black)](https://www.buymeacoffee.com/yogeshgokuk)

**A modern, high-performance Python filesystem monitoring library.**

</div>

---

**`memowatch`** is a highly robust, cross-platform **filesystem event observer** for Python. At its core, it seamlessly tracks all standard directory activities (file creations, modifications, deletions, and moves) exactly like traditional tools. 

However, it goes far beyond standard file watchers by adding built-in event debouncing, file lock settling detection, native async support, and advanced AST-aware code diffing on top of its reliable observation engine.

## ✨ Key Features
- **Robust Filesystem Observer**: Reliably tracks `Created`, `Modified`, `Deleted`, and `Moved` events across Windows and Linux.
- **Built-in Debouncing & Settling**: Rapid saves are collapsed into single events, and large file copies wait until they are 100% complete before triggering.
- **Fluent BDD API**: Configure complex watchers using a highly readable, English-like builder pattern.
- **Async-First**: Native `async/await` iterators without blocking the event loop.
- **Zero-Dependency Core**: Uses pure `ctypes` for native OS filesystem APIs.
- **Advanced AST & Diffing**: Optional real-time parsing to trigger on actual code logic changes rather than just timestamps.

---

## 🤖 Unhinged Automation Ideas (Unleash the Chaos)

Because `memowatch` understands logic, diffs, and settling states, it unlocks **zero-touch wizardry** that regular file watchers simply cannot comprehend:

*   **Real-time RAG Vector Sync:** Watch your local knowledge base directory. When a new PDF is dropped, `FileSettledEvent` safely waits for the download to finish, then instantly triggers an OCR extraction pipeline to live-upsert embeddings into your vector database. 🧠
*   **Automated Data Extraction Pipeline:** Drop 500 messy receipts into a folder. `memowatch` intercepts the batch, funnels them through a local LLM extraction model, and silently blasts the structured JSON data straight into your database without you ever clicking a button. 🧾
*   **Self-Healing CI/CD Pipelines:** Listen for `FunctionAdded` events. If you forgot to write a test, auto-generate a boilerplate script using an LLM and commit it before your boss even notices. Pure witchcraft! 🧙‍♂️
*   **Zero-Overhead Hot Reloading:** Stop melting your CPU just to reload your app. Use `FileDiffEvent` to dynamically inject the exact lines of code into running memory like a ninja performing open-heart surgery. 🥷
*   **Clairvoyant Asset Compilation:** The AI realizes you're editing `styles.css` and starts pre-compiling Tailwind in the background before your finger even lifts off the `Ctrl+S` keys. It's basically a crystal ball for CSS. 🔮
*   **Bulletproof Video Processing:** Use `FileSettledEvent` on a drop-folder. Never again accidentally unleash `ffmpeg` on a half-downloaded, janky 40GB video file and spontaneously combust your server. 🔥

---

## 💎 The `memowatch` Difference: Rich File Events

While `memowatch` **majorly tracks standard file events** (creation, modification, deletion), it goes far beyond just telling you *"Hey, a file changed."* 

**`memowatch` is designed to truly understand the user's intent and pain points.** You get rich, context-aware `FileEvent` objects tailored to exactly what happened:

### Core File Events
*   **`FileCreatedEvent`**: A new file appeared in the directory.
*   **`FileModifiedEvent`**: A file's contents or metadata changed. (Automatically debounced so you don't get 5 events for one save!)
*   **`FileDeletedEvent`**: A file was removed.
*   **`FileMovedEvent`**: A file was renamed or moved (gives you both `src_path` and `dest_path`).

### Advanced Smart Events
*   **`FileSettledEvent`**: Ever tried to process a video or PDF while it's still downloading? Traditional watchers fire immediately, causing `PermissionError` or corrupted reads. `memowatch` actively monitors file locks and sizes, only firing a `FileSettledEvent` when the file is 100% finished writing to disk.
*   **`FileDiffEvent`**: Why run `git diff` when the watcher can just hand you the exact `added_lines` and `removed_lines` in real-time?
*   **`ASTCodeEvent`**: We parse Python's Abstract Syntax Tree on the fly. You'll receive events like `FunctionAdded`, `ClassDeleted`, or `LogicModified`, completely ignoring whitespace and formatting changes.

---

## 🚀 Quick Start & Snippets

### Installation
```bash
pip install memowatch
```

We've designed `memowatch` to be incredibly easy to use. Pick the API style that fits your project!

### 1. The "Reads-Like-English" Fluent API (Core File Events)
Track standard file events like creations, modifications, and deletions with zero boilerplate.
```python
import memowatch

watcher = (
    memowatch.observe(".")
    .using_gitignore()               # Auto-loads and parses .gitignore!
    .debounced(window_ms=200)        # Collapse rapid saves
    .specifically("modified", "created")
    .then_execute(lambda e: print(f"Saved: {e.src_path}"))
    .start_in_background()
)
```

### 2. Native Asyncio Watcher
No blocking the event loop. Pure `async/await`.
```python
import asyncio
import memowatch

async def main():
    async with memowatch.async_watch("./src", debounce_ms=300) as stream:
        async for event in stream:
            print(f"[{event.event_type}] {event.src_path}")

asyncio.run(main())
```

### 3. Classic Callbacks (Sync API)
The traditional way, but upgraded with the `FileSettledEvent` (fires only when a file finishes writing).
```python
import memowatch

class MyHandler(memowatch.FileSystemEventHandler):
    def on_settled(self, event):
        print(f"✨ Safe to process: {event.src_path}")

observer = memowatch.Observer(debounce_ms=300, settle_timeout_ms=1000)
observer.schedule(MyHandler(), path=".", recursive=True)
observer.start()
```

### 4. AST & Code Logic Tracking
Trigger only when the actual Python logic changes, ignoring formatting and blank lines.
```python
import memowatch

def on_code_change(event):
    print(f"Logic changed! Node: {event.node_name}")

watcher = (
    memowatch.observe("./src")
    .using_gitignore()
    .when_code_changes()
    .then_execute(on_code_change)
    .start_in_background()
)
```

### 5. Rich Text Diffing
Get the exact lines added and removed without calling `git status`.
```python
import memowatch

def handle_diff(event):
    for line in event.added_lines:
        print(f"  + {line.strip()}")
    for line in event.removed_lines:
        print(f"  - {line.strip()}")

watcher = (
    memowatch.observe(".")
    .when_code_changes()
    .specifically("diff")
    .then_execute(handle_diff)
    .start_in_background()
)
```

### 6. Email & WhatsApp Notifications
Instantly trigger webhooks or send bulk/digest emails when files change.
```python
import memowatch

watcher = (
    memowatch.observe(".")
    .when_code_changes()
    .then_notify_email(
        to="admin@company.com",
        smtp_host="smtp.gmail.com",
        smtp_user="bot@company.com",
        smtp_pass="password123",
        bulk_interval_seconds=60  # Buffer events and send 1 email every 60s
    )
    .then_notify_whatsapp(
        phone_number="+1234567890",
        api_url="https://graph.facebook.com/v17.0/...",
        token="YOUR_TOKEN"
    )
    .start_in_background()
)
```

---

## 🖥️ CLI Usage (Background Daemon)

---

<div align="center">
Built by <a href="https://github.com/yogesh12s">Yogesh Gokul</a>.<br><br>
<a href="https://buymeacoffee.com/yogeshgokuk" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 40px !important;width: 145px !important;" ></a>
</div>
