From 00e1c2fafde37904222740fb9c37bc401acf6940 Mon Sep 17 00:00:00 2001 From: zor-el <13865072+zor-el@users.noreply.github.com> Date: Wed, 18 Mar 2020 18:54:46 +0100 Subject: [PATCH] Add support for multiline content filters Side benefit: Much better run-time performance compared to multiple filters per rule. Closes #70 --- organize/filters/file_content.py | 2 +- tests/integration/test_file_content.py | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/organize/filters/file_content.py b/organize/filters/file_content.py index 63e9d96c..4f2cbb5f 100644 --- a/organize/filters/file_content.py +++ b/organize/filters/file_content.py @@ -43,7 +43,7 @@ class FileContent(Filter): """ def __init__(self, expr) -> None: - self.expr = re.compile(expr) + self.expr = re.compile(expr, re.MULTILINE | re.DOTALL) def matches(self, path: Path) -> Any: if path.suffix.lower() not in SUPPORTED_EXTENSIONS: diff --git a/tests/integration/test_file_content.py b/tests/integration/test_file_content.py index 40f251cf..273bb2e2 100644 --- a/tests/integration/test_file_content.py +++ b/tests/integration/test_file_content.py @@ -1,3 +1,5 @@ +import os + from conftest import create_filesystem, assertdir from organize.cli import main @@ -7,7 +9,7 @@ def test_file_content(tmp_path): create_filesystem( tmp_path, files=[ - ("Test1.txt", "Invoice 12345"), + ("Test1.txt", "Lorem MegaCorp Ltd. ipsum\nInvoice 12345\nMore text\nID: 98765"), ("Test2.txt", "Tests"), ("Test3.txt", "My Homework ...") ], @@ -15,9 +17,9 @@ def test_file_content(tmp_path): rules: - folders: files filters: - - filecontent: '.*Invoice (?P\w+).*' + - filecontent: 'MegaCorp Ltd.+^Invoice (?P\w+)$.+^ID: 98765$' actions: - - rename: "Invoice_{filecontent.number}.txt" + - rename: "MegaCorp_Invoice_{filecontent.number}.txt" - folders: files filters: - filecontent: '.*Homework.*' @@ -26,4 +28,4 @@ def test_file_content(tmp_path): """, ) main(["run", "--config-file=%s" % (tmp_path / "config.yaml")]) - assertdir(tmp_path, "Homework.txt", "Invoice_12345.txt", "Test2.txt") + assertdir(tmp_path, "Homework.txt", "MegaCorp_Invoice_12345.txt", "Test2.txt")