Local filesystem connector
Walk local directories with path-matcher filtering, watch for changes in live mode via watchdog, and write outputs with declare_file() and declare_dir_target() — with memo-stable FilePath across project moves.
The localfs connector provides utilities for reading files from and writing files to the local file system.
from cocoindex.connectors import localfsStable memoization with FilePath
A key feature of the localfs connector is stable memoization through FilePath. When you move your entire project directory, memoization keys remain stable as long as you use the same ContextKey key string for the base directory.
Using ContextKey for stable base directories
Define a ContextKey[pathlib.Path] with a stable string identifier. Provide the actual path in your app’s lifespan, then pass the key directly to walk_dir(), declare_dir_target(), and related functions.
import pathlib
import cocoindex as coco
from cocoindex.connectors import localfs
# Define a stable key (the string "source_dir" is the stable memo identifier)
SOURCE_DIR = coco.ContextKey[pathlib.Path]("source_dir")
@coco.fn
async def app_main() -> None:
async for file in localfs.walk_dir(SOURCE_DIR, recursive=True):
# file.file_path has a stable memo key based on "source_dir"
await process(file)
# In your lifespan, provide the actual path:
async def lifespan(builder: coco.EnvironmentBuilder) -> None:
builder.provide(SOURCE_DIR, pathlib.Path("./data"))When you move your project to a different location, just update the path in builder.provide() — memoization keys remain the same because they’re based on the stable key string ("source_dir"), not the filesystem path.
Target files are keyed the same way, by the key name and the relative path. Because the base directory isn’t part of the key, CocoIndex can’t tell when two keys reach the same file. See One file, one declaration.
FilePath
FilePath combines an optional base directory key and a relative path. Passing a ContextKey[Path] directly to any localfs function is equivalent to constructing FilePath(base_dir=key).
FilePath supports all pathlib.PurePath operations:
SOURCE_DIR = coco.ContextKey[pathlib.Path]("source_dir")
source = localfs.FilePath(base_dir=SOURCE_DIR)
# Create paths using the / operator
config_path = source / "config" / "settings.json"
# Access path properties
print(config_path.name) # "settings.json"
print(config_path.suffix) # ".json"
print(config_path.parent) # FilePath pointing to "config/"
# Resolve to absolute path (requires active component context)
abs_path = config_path.resolve() # pathlib.PathSee FilePath in Resource Types for full details.
As source
Use walk_dir() to iterate over files in a directory. It returns a DirWalker that supports both synchronous and asynchronous iteration.
def walk_dir(
path: FilePath | Path | ContextKey[Path],
*,
live: bool = False,
recursive: bool = False,
path_matcher: FilePathMatcher | None = None,
rescan_interval: datetime.timedelta | None = datetime.timedelta(hours=1),
) -> DirWalkerParameters:
path— The root directory path to walk through. Can be aFilePath, apathlib.Path, or aContextKey[Path](equivalent toFilePath(base_dir=path)).live— IfTrue,items()returns aLiveMapViewthat supports live file watching viamount_each().recursive— IfTrue, recursively walk subdirectories.path_matcher— Optional filter for files and directories. See PatternFilePathMatcher.rescan_interval— Whenlive=True, the interval between periodic full rescans, which recreate the OS-level file watcher and walk the whole directory, as a safety net against events the platform dropped (for example macOS FSEvents silently stopping). Defaults to one hour;Nonedisables it. Ignored whenlive=False.
Returns: A DirWalker that supports async iteration via async for.
Symlinked directories are followed, except into a directory that is already an ancestor (a cycle); a symlink to a file is a file. A directory the process can’t read, and an entry that vanishes or can’t be stat-ed during the walk, are skipped.
Iterating files
walk_dir() returns a DirWalker that supports async iteration, yielding File objects (implementing the FileLike base class):
async for file in localfs.walk_dir("/path/to/documents", recursive=True):
text = await file.read_text()
...File I/O runs in a thread pool, keeping the event loop responsive.
Keyed iteration with items()
DirWalker.items() yields keyed (str, File) pairs, useful for associating each file with a stable string key (its relative path):
async for key, file in localfs.walk_dir("/path/to/dir", recursive=True).items():
content = await file.read()mount_each() reads only the selected keys from items(): it checks those files instead of walking the directory, and applies the same recursive and path_matcher rules as the walk.
Filtering files
Use PatternFilePathMatcher to filter which files and directories are included:
from cocoindex.connectors import localfs
from cocoindex.resources.file import PatternFilePathMatcher
# Include only .py and .md files, exclude hidden directories and test files
matcher = PatternFilePathMatcher(
included_patterns=["**/*.py", "**/*.md"],
excluded_patterns=["**/.*", "**/test_*", "**/__pycache__"],
)
async for file in localfs.walk_dir("/path/to/project", recursive=True, path_matcher=matcher):
await process(file)Live file watching
When live=True, items() returns a LiveMapView instead of a plain AsyncIterable. Combined with mount_each(), this enables automatic incremental file watching — new, modified, and deleted files are processed without a full rescan:
files = localfs.walk_dir(
sourcedir, recursive=True,
path_matcher=PatternFilePathMatcher(included_patterns=["**/*.md"]),
live=True,
)
await coco.mount_each(process_file, files.items(), target)See Live Mode for how this works and how to enable it on the app.
Example
import pathlib
import cocoindex as coco
from cocoindex.connectors import localfs
from cocoindex.resources.file import FileLike, PatternFilePathMatcher
SOURCE_DIR = coco.ContextKey[pathlib.Path]("source_dir")
@coco.fn
async def app_main() -> None:
matcher = PatternFilePathMatcher(included_patterns=["**/*.md"])
async for file in localfs.walk_dir(SOURCE_DIR, recursive=True, path_matcher=matcher):
await coco.mount(
coco.component_subpath("file", str(file.file_path.path)),
process_file,
file,
)
@coco.fn(memo=True)
async def process_file(file: FileLike) -> None:
text = await file.read_text()
# ... process the file content ...As target
The localfs connector provides target state APIs for writing files. CocoIndex tracks what files should exist and automatically handles creation, updates, and deletion.
declare_file
Declare a single file target. This is the simplest way to write a file.
@coco.fn
def declare_file(
path: FilePath | Path | ContextKey[Path],
content: bytes | str,
*,
create_parent_dirs: bool = False,
) -> NoneParameters:
path— The filesystem path for the file. Can be aFilePath, apathlib.Path, or aContextKey[Path].content— The file content (bytes or str).create_parent_dirs— IfTrue, create parent directories if they don’t exist.
Example:
OUTPUT_DIR = coco.ContextKey[pathlib.Path]("output_dir")
@coco.fn
def app_main() -> None:
coco.mount(
localfs.declare_file,
localfs.FilePath("readme.txt", base_dir=OUTPUT_DIR),
content="Hello, world!",
create_parent_dirs=True,
)declare_dir_target
Declare a directory target for writing multiple files. Returns a DirTarget for declaring files within.
@coco.fn
def declare_dir_target(
path: FilePath | Path | ContextKey[Path],
*,
create_parent_dirs: bool = True,
) -> DirTarget[coco.PendingS]Parameters:
path— The filesystem path for the directory. Can be aFilePath, apathlib.Path, or aContextKey[Path].create_parent_dirs— IfTrue, create parent directories if they don’t exist. Defaults toTrue.
Returns: A pending DirTarget. Use await coco.mount_target(...) or the convenience wrapper await localfs.mount_dir_target(path) to resolve.
DirTarget.declare_file
Declares a file to be written within the directory.
def declare_file(
self,
filename: str | PurePath,
content: bytes | str,
*,
create_parent_dirs: bool = False,
) -> NoneParameters:
filename— The name of the file (can include subdirectory path)..and..segments are normalized, so./a.txtanda.txtare one file. A name that is absolute or leaves the directory (such as../a.txt) raisesValueError.content— The file content (bytes or str).create_parent_dirs— IfTrue, create parent directories within the target directory.
DirTarget.declare_dir_target
Declares a subdirectory target within the directory.
def declare_dir_target(
self,
path: str | PurePath,
*,
create_parent_dirs: bool = False,
) -> DirTarget[coco.PendingS]Parameters:
path— The path of the subdirectory (relative to this directory). It’s normalized and checked likefilenameabove.create_parent_dirs— IfTrue, create parent directories.
Returns: A DirTarget for the subdirectory.
Target example
import pathlib
import cocoindex as coco
from cocoindex.connectors import localfs
from cocoindex.resources.file import FileLike, PatternFilePathMatcher
SOURCE_DIR = coco.ContextKey[pathlib.Path]("source_dir")
OUTPUT_DIR = coco.ContextKey[pathlib.Path]("output_dir")
@coco.fn
async def app_main() -> None:
# Declare output directory target using context key
target = await localfs.mount_dir_target(OUTPUT_DIR)
# Process files and write outputs
await coco.mount_each(process_file, localfs.walk_dir(SOURCE_DIR, recursive=True).items(), target)
@coco.fn(memo=True)
async def process_file(file: FileLike, target: localfs.DirTarget) -> None:
# Transform the file
content = (await file.read_text()).upper()
# Write to output with same relative path
target.declare_file(
filename=file.file_path.path,
content=content,
create_parent_dirs=True,
)One file, one declaration
CocoIndex identifies each target file by its key: the ContextKey name (none for a path relative to the current directory) and the path under it. The base directory isn’t part of the key, which is what lets you move it. The cost is that CocoIndex can’t tell when two keys reach the same file on disk. Declare each physical file through exactly one key.
Two keys can reach one file in these ways:
- Overlapping roots. Two root directory targets are the same directory, or one is inside the other: under two
ContextKeys, aContextKeyand a plain path, or two paths that reach one directory through a symlink. CocoIndex logs a warning when it applies two such targets. TwoContextKeys that point at one base directory are fine if their roots are disjoint, such asFilePath("foo", base_dir=A)andFilePath("bar", base_dir=B). - One file named two ways. Names are normalized, so
./a.txt,x/../a.txtanda.txtare one key. A flat path and a nested directory target are not:target.declare_file("sub/a.txt")andtarget.declare_dir_target("sub")withdeclare_file("a.txt")are two keys for one file. - Names that differ only in case on a case-insensitive file system (the default on macOS and Windows). There,
A.txtanda.txtare one file. - A file declared through a path into a directory target. If
subis a directory target and its parent also declaressub/a.txt, removing thesubdirectory target removessub/a.txttoo. Removing a directory target removes the whole directory.
You can switch a file from one key to another in one update if the processing component that declares the file stays the same. Examples are a case-only rename, or a flat path sub/a.txt moved to a nested sub directory target. CocoIndex writes the file under the new key and skips the delete under the old key. After a case-only rename on a case-insensitive file system, the file keeps its old spelling on disk.
The opposite switch, from a nested directory target to flat paths, takes two updates. A nested directory target is resolved in its own processing component, so CocoIndex removes it after it writes the flat files, and that removal deletes them. Remove the directory target and run an update first. Then declare the flat files and run a second update.
A relative path, such as pathlib.Path("out"), uses the current directory as its base, and the key holds only the relative path. If you run the app from another directory, the same keys reach other files: CocoIndex doesn’t write unchanged files to the new place, and the old files stay. Run the app from one directory, or use a ContextKey.