← All ivy-nodes
IVYXSTUDIO · IVY NODE
T
Text Change Detect
ivy.node.text-change-detect · v0.1.0
ivyx✓
Compares a text with the one stored under the same key last time, stores the new one, and returns whether it changed with the lines added and removed. The first run stores the text and reports no change.
#monitor#diff#change#state
Inputs
| Field | Type | Description |
|---|---|---|
| keyrequired | string | What is being watched, such as the page's address. |
| textrequired | string | The current text. |
| state_dir | string | Where the last text of each key is kept. |
Outputs
| Field | Type | Description |
|---|---|---|
| changedrequired | boolean | True when the text differs from last time. |
| first_runrequired | boolean | True when nothing was stored for this key. |
| added_linesrequired | array | Lines that are new. |
| removed_linesrequired | array | Lines that are gone. |
| diffrequired | string | The added lines with '+ ' and the removed ones with '- '. |
Source
python
inp = __ivy_ctx__["nodes"][__ivy_node_id__]["input"]
import difflib, hashlib, os, re
key = inp["key"]
text = inp["text"]
state_dir = inp.get("state_dir", ".punica/ivy-state")
slug = re.sub(r"[^A-Za-z0-9._-]+", "-", key).strip("-")[:80] or "key"
path = os.path.join(state_dir, slug + "-" + hashlib.sha1(key.encode()).hexdigest()[:8] + ".txt")
previous = None
if os.path.exists(path):
with open(path, encoding="utf-8") as handle:
previous = handle.read()
os.makedirs(state_dir, exist_ok=True)
with open(path, "w", encoding="utf-8") as handle:
handle.write(text)
added, removed = [], []
if previous is not None:
for line in difflib.ndiff(previous.splitlines(), text.splitlines()):
if line.startswith("+ "):
added.append(line[2:])
elif line.startswith("- "):
removed.append(line[2:])
out = __ivy_ctx__["nodes"][__ivy_node_id__]["output"]
out["changed"] = previous is not None and previous != text
out["first_run"] = previous is None
out["added_lines"] = added
out["removed_lines"] = removed
out["diff"] = "\n".join(["+ " + l for l in added] + ["- " + l for l in removed])Tests
Requires: python:3.9
- first-run
Nothing stored yet: the text is kept and no change reported.
- changed
A changed line is reported as one removed and one added.