Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(directory-scan): add directory pre-scan validation module with f… (#102)

Eric Shaw0c312300b621
diff --git a/openviking/exceptions.py b/openviking/exceptions.py
index 3f3e15d3c..807d317e5 100644
--- a/openviking/exceptions.py
+++ b/openviking/exceptions.py
@@ -39,6 +39,14 @@ class InvalidURIError(InvalidArgumentError):
super().__init__(message, details={"uri": uri, "reason": reason})
+class UnsupportedDirectoryFilesError(InvalidArgumentError):
+ """Directory contains unsupported file types (used when strict=True)."""
+
+ def __init__(self, message: str, unsupported_files: list):
+ super().__init__(message, details={"unsupported_files": unsupported_files})
+ self.unsupported_files = unsupported_files
+
+
# ============= Resource Errors =============
@@ -47,7 +55,9 @@ class NotFoundError(OpenVikingError):
def __init__(self, resource: str, resource_type: str = "resource"):
message = f"{resource_type.capitalize()} not found: {resource}"
- super().__init__(message, code="NOT_FOUND", details={"resource": resource, "type": resource_type})
+ super().__init__(
+ message, code="NOT_FOUND", details={"resource": resource, "type": resource_type}
+ )
class AlreadyExistsError(OpenVikingError):
@@ -55,7 +65,9 @@ class AlreadyExistsError(OpenVikingError):
def __init__(self, resource: str, resource_type: str = "resource"):
message = f"{resource_type.capitalize()} already exists: {resource}"
- super().__init__(message, code="ALREADY_EXISTS", details={"resource": resource, "type": resource_type})
+ super().__init__(
+ message, code="ALREADY_EXISTS", details={"resource": resource, "type": resource_type}
+ )
# ============= Authentication Errors =============
@@ -86,7 +98,9 @@ class UnavailableError(OpenVikingError):
message = f"{service.capitalize()} unavailable"
if reason:
message += f": {reason}"
- super().__init__(message, code="UNAVAILABLE", details={"service": service, "reason": reason})
+ super().__init__(
+ message, code="UNAVAILABLE", details={"service": service, "reason": reason}
+ )
class InternalError(OpenVikingError):
@@ -104,7 +118,9 @@ class DeadlineExceededError(OpenVikingError):
message = f"{operation.capitalize()} timed out"
if timeout:
message += f" after {timeout}s"
- super().__init__(message, code="DEADLINE_EXCEEDED", details={"operation": operation, "timeout": timeout})
+ super().__init__(
+ message, code="DEADLINE_EXCEEDED", details={"operation": operation, "timeout": timeout}
+ )
# ============= Business Errors =============
diff --git a/openviking/parse/__init__.py b/openviking/parse/__init__.py
index 488d27e9f..344fa25a5 100644
--- a/openviking/parse/__init__.py
+++ b/openviking/parse/__init__.py
@@ -5,6 +5,13 @@
from openviking.parse.base import NodeType, ParseResult, ResourceNode, create_parse_result
from openviking.parse.converter import DocumentConverter
from openviking.parse.custom import CallbackParserWrapper, CustomParserProtocol, CustomParserWrapper
+from openviking.parse.directory_scan import (
+ CLASS_PROCESSABLE,
+ CLASS_UNSUPPORTED,
+ ClassifiedFile,
+ DirectoryScanResult,
+ scan_directory,
+)
from openviking.parse.parsers.base_parser import BaseParser
from openviking.parse.parsers.code import CodeRepositoryParser
from openviking.parse.parsers.html import HTMLParser
@@ -42,4 +49,10 @@ __all__ = [
"BuildingTree",
# VLM
"VLMProcessor",
+ # Directory scan (phase-one validation)
+ "CLASS_PROCESSABLE",
+ "CLASS_UNSUPPORTED",
+ "ClassifiedFile",
+ "DirectoryScanResult",
+ "scan_directory",
]
diff --git a/openviking/parse/directory_scan.py b/openviking/parse/directory_scan.py
new file mode 100644
index 000000000..9aa7de170
--- /dev/null
+++ b/openviking/parse/directory_scan.py
@@ -0,0 +1,283 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""
+Directory pre-scan validation module for OpenViking.
+
+Implements phase-one of directory import (RFC #83): traverse directory tree,
+classify files as processable / unsupported, validate format,
+and report errors or warnings with optional strict mode.
+"""
+
+import fnmatch
+import os
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import List, Optional, Set, Union
+
+from openviking.exceptions import UnsupportedDirectoryFilesError
+from openviking.parse.parsers.constants import IGNORE_DIRS
+from openviking.parse.parsers.upload_utils import is_text_file
+from openviking.parse.registry import ParserRegistry, get_registry
+from openviking.utils.logger import get_logger
+
+logger = get_logger(__name__)
+
+# File classification labels
+CLASS_PROCESSABLE = "processable"
+CLASS_UNSUPPORTED = "unsupported"
+
+
+@dataclass
+class ClassifiedFile:
+ """A single file with its classification and relative path."""
+
+ path: Path
+ rel_path: str
+ classification: str # CLASS_PROCESSABLE | CLASS_UNSUPPORTED
+
+
+@dataclass
+class DirectoryScanResult:
+ """Result of directory pre-scan: classified files and optional warnings."""
+
+ root: Path
+ processable: List[ClassifiedFile] = field(default_factory=list)
+ unsupported: List[ClassifiedFile] = field(default_factory=list)
+ skipped: List[str] = field(default_factory=list) # reason -> count or paths for debugging
+ warnings: List[str] = field(default_factory=list)
+
+ def all_processable_files(self) -> List[ClassifiedFile]:
+ """Return processable files in order (for phase-two routing)."""
+ return self.processable
+
+
+def _should_skip_file(file_path: Path) -> tuple[bool, str]:
+ """
+ Return (True, reason) if the file should be skipped (not counted as supported/unsupported).
+
+ Skip: dot files, symlinks, empty files (per RFC phase-one).
+ """
+ if file_path.name.startswith("."):
+ return True, "dot file"
+ if file_path.is_symlink():
+ return True, "symlink"
+ try:
+ if file_path.stat().st_size == 0:
+ return True, "empty file"
+ except OSError:
+ return True, "os error"
+ return False, ""
+
+
+def _should_skip_directory(
+ dir_path: Path,
+ root: Path,
+ ignore_dirs: Optional[Set[str]] = None,
+) -> tuple[bool, str]:
+ """
+ Return (True, reason) if the directory should be skipped (not counted as supported/unsupported).
+
+ Skip: dot directories, symlinks, IGNORE_DIRS, and any dir in ignore_dirs.
+ ignore_dirs: directory names, or relative paths (relative to root).
+ - Name only (no path sep): skip any dir with that name.
+ - Relative path (e.g. "parse/", "./storage/vectordb", "openviking/parse"): skip when dir's path matches.
+ """
+ if dir_path.name.startswith("."):
+ return True, "dot directory"
+ if dir_path.is_symlink():
+ return True, "symlink"
+ if dir_path.name in IGNORE_DIRS:
+ return True, "IGNORE_DIRS"
+ if not ignore_dirs:
+ return False, ""
+
+ try:
+ dir_rel = _normalize_rel_path(str(dir_path.relative_to(root)))
+ except ValueError:
+ dir_rel = _normalize_rel_path(str(dir_path))
+
+ for entry in ignore_dirs:
+ if not entry or not str(entry).strip():
+ continue
+ raw = str(entry).strip().replace("\\", "/")
+ if not raw:
+ continue
+
+ # Relative path (contains '/'): match by path relative to root
+ if "/" in raw:
+ prefix = raw.rstrip("/").lstrip("./")
+ if prefix and (dir_rel == prefix or dir_rel.startswith(prefix + "/")):
+ return True, "ignore_dirs"
+ continue
+
+ # Single segment: match by directory name
+ if dir_path.name == raw:
+ return True, "ignore_dirs"
+
+ return False, ""
+
+
+def _parse_patterns(value: Optional[str]) -> List[str]:
+ """Parse comma-separated include/exclude string into list of stripped patterns."""
+ if not value or not value.strip():
+ return []
+ return [p.strip() for p in value.split(",") if p.strip()]
+
+
+def _normalize_rel_path(rel_path: str) -> str:
+ """Use forward slashes for consistent matching across platforms."""
+ return rel_path.replace("\\", "/")
+
+
+def _matches_include(path_name: str, patterns: List[str]) -> bool:
+ """True if file is included: no patterns means include all; else match path name against any pattern."""
+ if not patterns:
+ return True
+ return any(fnmatch.fnmatch(path_name, p) for p in patterns)
+
+
+def _matches_exclude(rel_path_norm: str, path_name: str, patterns: List[str]) -> bool:
+ """
+ True if file is excluded.
+ - Pattern ending with '/' is a path prefix (e.g. 'drafts/' excludes paths under drafts/).
+ - Otherwise match path name as glob (e.g. '*.tmp').
+ """
+ if not patterns:
+ return False
+ for p in patterns:
+ if p.endswith("/"):
+ prefix = p.rstrip("/").replace("\\", "/")
+ if rel_path_norm == prefix or rel_path_norm.startswith(prefix + "/"):
+ return True
+ else:
+ if fnmatch.fnmatch(path_name, p):
+ return True
+ return False
+
+
+def _classify_file(
+ file_path: Path,
+ registry: ParserRegistry,
+) -> str:
+ """
+ Classify a single file as CLASS_PROCESSABLE or CLASS_UNSUPPORTED.
+
+ Processable: ParserRegistry has a parser, or is_text_file (code/config/docs).
+ """
+ if registry.get_parser_for_file(file_path) is not None:
+ return CLASS_PROCESSABLE
+ if is_text_file(file_path):
+ return CLASS_PROCESSABLE
+ return CLASS_UNSUPPORTED
+
+
+def scan_directory(
+ root: Union[str, Path],
+ registry: Optional[ParserRegistry] = None,
+ strict: bool = True,
+ ignore_dirs: Optional[Set[str]] = None,
+ include: Optional[str] = None,
+ exclude: Optional[str] = None,
+) -> DirectoryScanResult:
+ """
+ Traverse directory tree and classify every file (phase-one validation).
+
+ - Skips directories in IGNORE_DIRS (or ignore_dirs), and skips dot files,
+ symlinks, and empty files (they are not included in any list).
+ - If include is set, only files whose name matches one of the glob patterns are considered
+ (e.g. include="*.pdf,*.md"). If exclude is set, files matching any exclude pattern are
+ skipped (e.g. exclude="drafts/" for path prefix, or "*.tmp" for name glob).
+ - Classifies remaining files:
+ - processable: ParserRegistry has a parser, or is_text_file (code/docs/config)
+ - unsupported: everything else
+
+ Args:
+ root: Directory path to scan.
+ registry: Parser registry for processable detection. Defaults to get_registry().
+ strict: If True, raise UnsupportedDirectoryFilesError when any unsupported file exists.
+ If False, append warnings and continue (unsupported list still populated).
+ ignore_dirs: Directory names or relative paths (to root) to skip. E.g. "parse", "parse/", "./storage/".
+ include: Comma-separated glob patterns for file names; only matching files are included
+ (e.g. "*.pdf,*.md"). If not set, all files (subject to exclude) are considered.
+ exclude: Comma-separated patterns: trailing '/' = path prefix (e.g. "drafts/"),
+ else glob on file name (e.g. "*.tmp").
+
+ Returns:
+ DirectoryScanResult with processable, unsupported, warnings.
+
+ Raises:
+ UnsupportedDirectoryFilesError: When strict=True and there is at least one unsupported file.
+ FileNotFoundError: When root does not exist.
+ NotADirectoryError: When root is not a directory.
+ """
+ root = Path(root).resolve()
+ if not root.exists():
+ raise FileNotFoundError(f"Directory does not exist: {root}")
+ if not root.is_dir():
+ raise NotADirectoryError(f"Not a directory: {root}")
+
+ effective_registry = registry if registry is not None else get_registry()
+ include_patterns = _parse_patterns(include)
+ exclude_patterns = _parse_patterns(exclude)
+
+ result = DirectoryScanResult(root=root)
+ for dir_path_str, dir_names, file_names in os.walk(root, topdown=True):
+ dir_path = Path(dir_path_str)
+
+ # Prune subdirectories in-place so os.walk won't descend into them
+ kept = []
+ for d in dir_names:
+ sub = dir_path / d
+ skip, reason = _should_skip_directory(sub, root, ignore_dirs)
+ if skip:
+ result.skipped.append(f"{sub.relative_to(root)} ({reason})")
+ else:
+ kept.append(d)
+ dir_names[:] = kept
+
+ for name in file_names:
+ file_path = dir_path / name
+ try:
+ rel_path = str(file_path.relative_to(root))
+ except ValueError:
+ rel_path = str(file_path)
+ rel_path_norm = _normalize_rel_path(rel_path)
+
+ skip, reason = _should_skip_file(file_path)
+ if skip:
+ result.skipped.append(f"{rel_path} ({reason})")
+ continue
+
+ if include_patterns and not _matches_include(name, include_patterns):
+ result.skipped.append(f"{rel_path} (excluded by include filter)")
+ continue
+ if exclude_patterns and _matches_exclude(rel_path_norm, name, exclude_patterns):
+ result.skipped.append(f"{rel_path} (excluded by exclude filter)")
+ continue
+
+ classification = _classify_file(file_path, effective_registry)
+ classified = ClassifiedFile(
+ path=file_path, rel_path=rel_path, classification=classification
+ )
+ if classification == CLASS_PROCESSABLE:
+ result.processable.append(classified)
+ else:
+ result.unsupported.append(classified)
+
+ if result.unsupported:
+ unsupported_paths = [f.rel_path for f in result.unsupported]
+ msg = (
+ f"Directory contains {len(result.unsupported)} unsupported file(s). "
+ f"Unsupported: {unsupported_paths[:10]}{'...' if len(unsupported_paths) > 10 else ''}"
+ )
+ if strict:
+ raise UnsupportedDirectoryFilesError(msg, unsupported_paths)
+ result.warnings.append(msg)
+ for rel in unsupported_paths:
+ result.warnings.append(f" - {rel}")
+
+ result.processable.sort(key=lambda x: x.rel_path)
+ result.unsupported.sort(key=lambda x: x.rel_path)
+ result.skipped.sort()
+ result.warnings.sort()
+ return result
diff --git a/tests/parse/__init__.py b/tests/parse/__init__.py
new file mode 100644
index 000000000..d4ae00fa5
--- /dev/null
+++ b/tests/parse/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Directory scan test module"""
diff --git a/tests/parse/test_directory_scan.py b/tests/parse/test_directory_scan.py
new file mode 100644
index 000000000..52ddf72d8
--- /dev/null
+++ b/tests/parse/test_directory_scan.py
@@ -0,0 +1,396 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Unit tests for directory pre-scan validation module (RFC #83 T1)."""
+
+from pathlib import Path
+
+import pytest
+
+from openviking.exceptions import UnsupportedDirectoryFilesError
+from openviking.parse.directory_scan import (
+ CLASS_PROCESSABLE,
+ ClassifiedFile,
+ DirectoryScanResult,
+ scan_directory,
+)
+from openviking.parse.registry import ParserRegistry
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def tmp_tree(tmp_path: Path) -> Path:
+ """Create a directory tree with mixed file types for scan tests."""
+ # rich (parser exists): .md, .pdf, .html, .txt
+ (tmp_path / "readme.md").write_text("# README", encoding="utf-8")
+ (tmp_path / "doc.html").write_text("<html></html>", encoding="utf-8")
+ (tmp_path / "note.txt").write_text("plain text", encoding="utf-8")
+
+ # text (code/config, no dedicated parser or text parser only): .py, .yaml
+ (tmp_path / "main.py").write_text("print(1)", encoding="utf-8")
+ (tmp_path / "config.yaml").write_text("key: value", encoding="utf-8")
+
+ # unsupported: unknown extension
+ (tmp_path / "data.xyz").write_text("unknown", encoding="utf-8")
+ (tmp_path / "archive.rar").write_bytes(b"RAR\x00")
+
+ # skipped: dot file, empty, ignored dir
+ (tmp_path / ".hidden").write_text("secret", encoding="utf-8")
+ (tmp_path / "empty.txt").write_bytes(b"")
+ (tmp_path / ".git").mkdir()
+ (tmp_path / ".git" / "config").write_text("[core]", encoding="utf-8")
+ (tmp_path / "node_modules").mkdir()
+ (tmp_path / "node_modules" / "pkg").write_text("x", encoding="utf-8")
+
+ # subdir with mixed
+ sub = tmp_path / "src"
+ sub.mkdir()
+ (sub / "app.py").write_text("code", encoding="utf-8")
+ (sub / "custom.bin").write_bytes(b"\x00\x01")
+
+ return tmp_path
+
+
+def tmp_all_supported(tmp_path: Path) -> Path:
+ """Directory where every file is rich or text (no unsupported)."""
+ (tmp_path / "a.md").write_text("# A", encoding="utf-8")
+ (tmp_path / "b.py").write_text("pass", encoding="utf-8")
+ (tmp_path / "c.yaml").write_text("k: v", encoding="utf-8")
+ return tmp_path
+
+
+def tmp_with_drafts(tmp_path: Path) -> Path:
+ """Tree with drafts/ subdir and mixed extensions for include/exclude tests."""
+ (tmp_path / "readme.md").write_text("# README", encoding="utf-8")
+ (tmp_path / "doc.pdf").write_bytes(b"%PDF-1.0")
+ (tmp_path / "main.py").write_text("pass", encoding="utf-8")
+ (tmp_path / "drafts").mkdir()
+ (tmp_path / "drafts" / "draft.pdf").write_bytes(b"%PDF")
+ (tmp_path / "drafts" / "notes.md").write_text("notes", encoding="utf-8")
+ (tmp_path / "drafts" / "skip.py").write_text("x", encoding="utf-8")
+ return tmp_path
+
+
+def registry() -> ParserRegistry:
+ """Default parser registry (includes markdown, pdf, html, text, etc.)."""
+ return ParserRegistry(register_optional=False)
+
+
+# ---------------------------------------------------------------------------
+# Traversal and classification
+# ---------------------------------------------------------------------------
+
+
+class TestScanDirectoryTraversal:
+ """Test that scan_directory traverses the tree and respects IGNORE_DIRS."""
+
+ def test_traverses_all_non_ignored_dirs(self, tmp_tree: Path, registry: ParserRegistry) -> None:
+ result: DirectoryScanResult = scan_directory(tmp_tree, registry=registry, strict=False)
+ rel_paths = {f.rel_path for f in result.all_processable_files()}
+ assert "readme.md" in rel_paths
+ assert "main.py" in rel_paths
+ assert "src/app.py" in rel_paths
+ # Ignored dirs must not appear
+ assert not any(".git" in p for p in rel_paths)
+ assert not any("node_modules" in p for p in rel_paths)
+
+ def test_skips_dot_files_and_empty(self, tmp_tree: Path, registry: ParserRegistry) -> None:
+ result: DirectoryScanResult = scan_directory(tmp_tree, registry=registry, strict=False)
+ all_rel = [f.rel_path for f in result.processable + result.unsupported]
+ assert ".hidden" not in all_rel
+ assert "empty.txt" not in all_rel
+ assert any("empty" in s or "dot" in s for s in result.skipped)
+
+
+class TestScanDirectoryClassification:
+ """Test processable / unsupported classification."""
+
+ def test_processable_includes_parser_files(
+ self, tmp_tree: Path, registry: ParserRegistry
+ ) -> None:
+ result: DirectoryScanResult = scan_directory(tmp_tree, registry=registry, strict=False)
+ processable_rel = [f.rel_path for f in result.processable]
+ assert "readme.md" in processable_rel
+ assert "doc.html" in processable_rel
+ assert "note.txt" in processable_rel
+
+ def test_processable_includes_code_or_config(
+ self, tmp_tree: Path, registry: ParserRegistry
+ ) -> None:
+ result: DirectoryScanResult = scan_directory(tmp_tree, registry=registry, strict=False)
+ processable_rel = [f.rel_path for f in result.processable]
+ assert "main.py" in processable_rel
+ assert "config.yaml" in processable_rel
+ assert "src/app.py" in processable_rel
+
+ def test_unsupported_unknown_ext(self, tmp_tree: Path, registry: ParserRegistry) -> None:
+ result: DirectoryScanResult = scan_directory(tmp_tree, registry=registry, strict=False)
+ unsup_rel = [f.rel_path for f in result.unsupported]
+ assert "data.xyz" in unsup_rel
+ assert "archive.rar" in unsup_rel
+ assert "src/custom.bin" in unsup_rel
+
+
+# ---------------------------------------------------------------------------
+# Strict vs non-strict (unsupported handling)
+# ---------------------------------------------------------------------------
+
+
+class TestStrictParameter:
+ """Test strict=True raises; strict=False adds warnings."""
+
+ def test_strict_raises_when_unsupported(self, tmp_tree: Path, registry: ParserRegistry) -> None:
+ with pytest.raises(UnsupportedDirectoryFilesError) as exc_info:
+ scan_directory(tmp_tree, registry=registry, strict=True)
+ err = exc_info.value
+ assert err.unsupported_files
+ assert "data.xyz" in err.unsupported_files or any("xyz" in p for p in err.unsupported_files)
+
+ def test_non_strict_returns_warnings(self, tmp_tree: Path, registry: ParserRegistry) -> None:
+ result: DirectoryScanResult = scan_directory(tmp_tree, registry=registry, strict=False)
+ assert result.unsupported
+ assert result.warnings
+ assert any("unsupported" in w.lower() for w in result.warnings)
+
+ def test_strict_passes_when_no_unsupported(
+ self, tmp_all_supported: Path, registry: ParserRegistry
+ ) -> None:
+ result: DirectoryScanResult = scan_directory(
+ tmp_all_supported, registry=registry, strict=True
+ )
+ assert not result.unsupported
+ assert not result.warnings
+
+
+# ---------------------------------------------------------------------------
+# Exception reporting
+# ---------------------------------------------------------------------------
+
+
+class TestExceptionReporting:
+ """Test that UnsupportedDirectoryFilesError carries full unsupported list."""
+
+ def test_error_contains_all_unsupported_paths(
+ self, tmp_tree: Path, registry: ParserRegistry
+ ) -> None:
+ with pytest.raises(UnsupportedDirectoryFilesError) as exc_info:
+ scan_directory(tmp_tree, registry=registry, strict=True)
+ paths = exc_info.value.unsupported_files
+ assert len(paths) >= 3 # data.xyz, archive.rar, src/custom.bin
+ assert "data.xyz" in paths
+ assert "archive.rar" in paths
+ assert "src/custom.bin" in paths
+
+
+# ---------------------------------------------------------------------------
+# Edge cases and API
+# ---------------------------------------------------------------------------
+
+
+class TestScanDirectoryEdgeCases:
+ """Edge cases: missing dir, not a dir, custom ignore_dirs."""
+
+ def test_raises_on_nonexistent(self, registry: ParserRegistry) -> None:
+ with pytest.raises(FileNotFoundError):
+ scan_directory("/nonexistent/path/12345", registry=registry)
+
+ def test_raises_on_file_not_dir(self, tmp_tree: Path, registry: ParserRegistry) -> None:
+ with pytest.raises(NotADirectoryError):
+ scan_directory(tmp_tree / "readme.md", registry=registry)
+
+ def test_custom_ignore_dirs(self, tmp_tree: Path, registry: ParserRegistry) -> None:
+ """Custom ignore_dirs supports directory names and relative paths."""
+
+ # 1) Ignore by directory name ("src")
+ result_name: DirectoryScanResult = scan_directory(
+ tmp_tree,
+ registry=registry,
+ strict=False,
+ ignore_dirs={".git", "node_modules", "src"},
+ )
+ all_rel_name = [f.rel_path for f in result_name.processable + result_name.unsupported]
+ assert not any(p.startswith("src/") for p in all_rel_name)
+
+ # 2) Ignore by relative path with trailing slash ("src/")
+ result_rel_slash: DirectoryScanResult = scan_directory(
+ tmp_tree,
+ registry=registry,
+ strict=False,
+ ignore_dirs=["src/"],
+ )
+ all_rel_slash = [
+ f.rel_path for f in result_rel_slash.processable + result_rel_slash.unsupported
+ ]
+ assert not any(p.startswith("src/") for p in all_rel_slash)
+
+ # 3) Ignore by relative path with ./ prefix ("./src")
+ result_rel_dot: DirectoryScanResult = scan_directory(
+ tmp_tree,
+ registry=registry,
+ strict=False,
+ ignore_dirs=["./src"],
+ )
+ all_rel_dot = [f.rel_path for f in result_rel_dot.processable + result_rel_dot.unsupported]
+ assert not any(p.startswith("src/") for p in all_rel_dot)
+
+ def test_result_all_processable(
+ self, tmp_all_supported: Path, registry: ParserRegistry
+ ) -> None:
+ result: DirectoryScanResult = scan_directory(
+ tmp_all_supported, registry=registry, strict=True
+ )
+ all_p = result.all_processable_files()
+ assert len(all_p) == len(result.processable)
+ for cf in all_p:
+ assert cf.classification == CLASS_PROCESSABLE
+
+
+# ---------------------------------------------------------------------------
+# Include / exclude filters
+# ---------------------------------------------------------------------------
+
+
+class TestIncludeExclude:
+ """Test include and exclude parameters for user-defined file filtering."""
+
+ def test_include_only_matching_files(
+ self, tmp_with_drafts: Path, registry: ParserRegistry
+ ) -> None:
+ result: DirectoryScanResult = scan_directory(
+ tmp_with_drafts,
+ registry=registry,
+ strict=False,
+ include="*.pdf,*.md",
+ )
+ rel_paths = [f.rel_path for f in result.processable + result.unsupported]
+ assert "readme.md" in rel_paths
+ assert "doc.pdf" in rel_paths
+ assert "drafts/draft.pdf" in rel_paths
+ assert "drafts/notes.md" in rel_paths
+ assert "main.py" not in rel_paths
+ assert "drafts/skip.py" not in rel_paths
+ skipped_reasons = " ".join(result.skipped)
+ assert "excluded by include" in skipped_reasons
+
+ def test_exclude_path_prefix(self, tmp_with_drafts: Path, registry: ParserRegistry) -> None:
+ result: DirectoryScanResult = scan_directory(
+ tmp_with_drafts,
+ registry=registry,
+ strict=False,
+ exclude="drafts/",
+ )
+ rel_paths = [f.rel_path for f in result.processable + result.unsupported]
+ assert "readme.md" in rel_paths
+ assert "doc.pdf" in rel_paths
+ assert "main.py" in rel_paths
+ assert "drafts/draft.pdf" not in rel_paths
+ assert "drafts/notes.md" not in rel_paths
+ assert "drafts/skip.py" not in rel_paths
+ skipped_reasons = " ".join(result.skipped)
+ assert "excluded by exclude" in skipped_reasons
+
+ def test_include_and_exclude_combined(
+ self, tmp_with_drafts: Path, registry: ParserRegistry
+ ) -> None:
+ result: DirectoryScanResult = scan_directory(
+ tmp_with_drafts,
+ registry=registry,
+ strict=False,
+ include="*.pdf,*.md",
+ exclude="drafts/",
+ )
+ rel_paths = [f.rel_path for f in result.processable + result.unsupported]
+ assert "readme.md" in rel_paths
+ assert "doc.pdf" in rel_paths
+ assert "drafts/draft.pdf" not in rel_paths
+ assert "drafts/notes.md" not in rel_paths
+ assert "main.py" not in rel_paths
+
+ def test_exclude_name_glob(self, tmp_tree: Path, registry: ParserRegistry) -> None:
+ result: DirectoryScanResult = scan_directory(
+ tmp_tree,
+ registry=registry,
+ strict=False,
+ exclude="*.rar,*.xyz",
+ )
+ unsup_rel = [f.rel_path for f in result.unsupported]
+ assert "data.xyz" not in unsup_rel
+ assert "archive.rar" not in unsup_rel
+ assert "src/custom.bin" in unsup_rel
+
+ def test_no_include_means_all_files(
+ self, tmp_with_drafts: Path, registry: ParserRegistry
+ ) -> None:
+ result: DirectoryScanResult = scan_directory(
+ tmp_with_drafts, registry=registry, strict=False
+ )
+ rel_paths = [f.rel_path for f in result.processable + result.unsupported]
+ assert "readme.md" in rel_paths
+ assert "doc.pdf" in rel_paths
+ assert "main.py" in rel_paths
+ assert "drafts/draft.pdf" in rel_paths
+ assert "drafts/notes.md" in rel_paths
+ assert "drafts/skip.py" in rel_paths
+
+ def test_empty_include_exclude_unchanged(
+ self, tmp_tree: Path, registry: ParserRegistry
+ ) -> None:
+ r1 = scan_directory(tmp_tree, registry=registry, strict=False)
+ r2 = scan_directory(tmp_tree, registry=registry, strict=False, include="", exclude="")
+ paths1 = {f.rel_path for f in r1.processable + r1.unsupported}
+ paths2 = {f.rel_path for f in r2.processable + r2.unsupported}
+ assert paths1 == paths2
+
+ def test_ignore_dirs_with_include_and_exclude(
+ self, tmp_with_drafts: Path, registry: ParserRegistry
+ ) -> None:
+ """Combined ignore_dirs + include + exclude should work together."""
+
+ result: DirectoryScanResult = scan_directory(
+ tmp_with_drafts,
+ registry=registry,
+ strict=False,
+ ignore_dirs={"drafts"},
+ include="*.md,*.py",
+ exclude="main.py",
+ )
+
+ rel_paths = [f.rel_path for f in result.processable + result.unsupported]
+
+ # ignore_dirs: drafts/ 整个目录被跳过
+ assert not any(p.startswith("drafts/") for p in rel_paths)
+ # include: .md 仍然被保留
+ assert "readme.md" in rel_paths
+ # exclude: main.py 被排除
+ assert "main.py" not in rel_paths
+
+ skipped_reasons = " ".join(result.skipped)
+ assert "ignore_dirs" in skipped_reasons
+ assert "excluded by include" in skipped_reasons or "excluded by exclude" in skipped_reasons
+
+
+class TestClassifiedFileAndResult:
+ """Test ClassifiedFile and DirectoryScanResult types."""
+
+ def test_classified_file_has_rel_path_and_classification(self) -> None:
+ p = Path("/tmp/foo/bar.txt")
+ cf = ClassifiedFile(path=p, rel_path="bar.txt", classification=CLASS_PROCESSABLE)
+ assert cf.rel_path == "bar.txt"
+ assert cf.classification == CLASS_PROCESSABLE
+
+ def test_scan_result_root_and_lists(
+ self, tmp_all_supported: Path, registry: ParserRegistry
+ ) -> None:
+ result: DirectoryScanResult = scan_directory(
+ tmp_all_supported, registry=registry, strict=True
+ )
+ assert result.root == tmp_all_supported.resolve()
+ assert isinstance(result.processable, list)
+ assert isinstance(result.unsupported, list)
+ assert isinstance(result.warnings, list)
+ assert isinstance(result.skipped, list)