Merge pull request #85 from gethari/crawling-progress

#feat: Report progress of the crawling #64
This commit is contained in:
Zachary Huang
2025-05-05 11:32:42 -04:00
committed by GitHub
2 changed files with 63 additions and 58 deletions
+11
View File
@@ -61,12 +61,23 @@ class FetchRepo(Node):
) )
else: else:
print(f"Crawling directory: {prep_res['local_dir']}...") print(f"Crawling directory: {prep_res['local_dir']}...")
def progress_callback(processed, total):
percentage = (processed / total) * 100 if total > 0 else 0
rounded_percentage = int(percentage)
if rounded_percentage > progress_callback.last_reported:
progress_callback.last_reported = rounded_percentage
print(f"\033[92mProgress: {processed}/{total} files ({rounded_percentage}%)\033[0m")
progress_callback.last_reported = -1
result = crawl_local_files( result = crawl_local_files(
directory=prep_res["local_dir"], directory=prep_res["local_dir"],
include_patterns=prep_res["include_patterns"], include_patterns=prep_res["include_patterns"],
exclude_patterns=prep_res["exclude_patterns"], exclude_patterns=prep_res["exclude_patterns"],
max_file_size=prep_res["max_file_size"], max_file_size=prep_res["max_file_size"],
use_relative_paths=prep_res["use_relative_paths"], use_relative_paths=prep_res["use_relative_paths"],
progress_callback=progress_callback
) )
# Convert dict to list of tuples: [(path, content), ...] # Convert dict to list of tuples: [(path, content), ...]
+52 -58
View File
@@ -2,13 +2,13 @@ import os
import fnmatch import fnmatch
import pathspec import pathspec
def crawl_local_files( def crawl_local_files(
directory, directory,
include_patterns=None, include_patterns=None,
exclude_patterns=None, exclude_patterns=None,
max_file_size=None, max_file_size=None,
use_relative_paths=True, use_relative_paths=True,
progress_callback=None,
): ):
""" """
Crawl files in a local directory with similar interface as crawl_github_files. Crawl files in a local directory with similar interface as crawl_github_files.
@@ -18,6 +18,7 @@ def crawl_local_files(
exclude_patterns (set): File patterns to exclude (e.g. {"tests/*"}) exclude_patterns (set): File patterns to exclude (e.g. {"tests/*"})
max_file_size (int): Maximum file size in bytes max_file_size (int): Maximum file size in bytes
use_relative_paths (bool): Whether to use paths relative to directory use_relative_paths (bool): Whether to use paths relative to directory
progress_callback (callable): Function to report progress, takes (processed, total) as arguments
Returns: Returns:
dict: {"files": {filepath: content}} dict: {"files": {filepath: content}}
@@ -34,91 +35,84 @@ def crawl_local_files(
try: try:
with open(gitignore_path, "r", encoding="utf-8") as f: with open(gitignore_path, "r", encoding="utf-8") as f:
gitignore_patterns = f.readlines() gitignore_patterns = f.readlines()
gitignore_spec = pathspec.PathSpec.from_lines( gitignore_spec = pathspec.PathSpec.from_lines("gitwildmatch", gitignore_patterns)
"gitwildmatch", gitignore_patterns
)
print(f"Loaded .gitignore patterns from {gitignore_path}") print(f"Loaded .gitignore patterns from {gitignore_path}")
except Exception as e: except Exception as e:
print( print(f"Warning: Could not read or parse .gitignore file {gitignore_path}: {e}")
f"Warning: Could not read or parse .gitignore file {gitignore_path}: {e}"
)
# --- End Load .gitignore ---
all_files = []
for root, dirs, files in os.walk(directory): for root, dirs, files in os.walk(directory):
# Filter directories using .gitignore and exclude_patterns early to avoid descending # Filter directories using .gitignore and exclude_patterns early
# Need to process dirs list *in place* for os.walk to respect it
excluded_dirs = set() excluded_dirs = set()
for d in dirs: for d in dirs:
dirpath_rel = os.path.relpath(os.path.join(root, d), directory) dirpath_rel = os.path.relpath(os.path.join(root, d), directory)
# Check against .gitignore (important for directories)
if gitignore_spec and gitignore_spec.match_file(dirpath_rel): if gitignore_spec and gitignore_spec.match_file(dirpath_rel):
excluded_dirs.add(d) excluded_dirs.add(d)
continue # Skip further checks if gitignored continue
# Check against standard exclude_patterns
if exclude_patterns: if exclude_patterns:
for pattern in exclude_patterns: for pattern in exclude_patterns:
# Match pattern against full relative path or directory name itself if fnmatch.fnmatch(dirpath_rel, pattern) or fnmatch.fnmatch(d, pattern):
if fnmatch.fnmatch(dirpath_rel, pattern) or fnmatch.fnmatch(
d, pattern
):
excluded_dirs.add(d) excluded_dirs.add(d)
break break
# Modify dirs in-place: remove excluded ones
# Iterate over a copy (.copy()) because we are modifying the list during iteration
for d in dirs.copy(): for d in dirs.copy():
if d in excluded_dirs: if d in excluded_dirs:
dirs.remove(d) dirs.remove(d)
# Now process files in the non-excluded directories
for filename in files: for filename in files:
filepath = os.path.join(root, filename) filepath = os.path.join(root, filename)
all_files.append(filepath)
# Get path relative to directory if requested total_files = len(all_files)
if use_relative_paths: processed_files = 0
relpath = os.path.relpath(filepath, directory)
else:
relpath = filepath
# --- Exclusion check --- for filepath in all_files:
excluded = False relpath = os.path.relpath(filepath, directory) if use_relative_paths else filepath
# 1. Check .gitignore first
if gitignore_spec and gitignore_spec.match_file(relpath):
excluded = True
# 2. Check standard exclude_patterns if not already excluded by .gitignore # --- Exclusion check ---
if not excluded and exclude_patterns: excluded = False
for pattern in exclude_patterns: if gitignore_spec and gitignore_spec.match_file(relpath):
if fnmatch.fnmatch(relpath, pattern): excluded = True
excluded = True
break
included = False if not excluded and exclude_patterns:
if include_patterns: for pattern in exclude_patterns:
for pattern in include_patterns: if fnmatch.fnmatch(relpath, pattern):
if fnmatch.fnmatch(relpath, pattern): excluded = True
included = True break
break
else:
# If no include patterns, include everything *not excluded*
included = True
# Skip if not included or if excluded (by either method) included = False
if not included or excluded: if include_patterns:
continue for pattern in include_patterns:
if fnmatch.fnmatch(relpath, pattern):
included = True
break
else:
included = True
# Check file size if not included or excluded:
if max_file_size and os.path.getsize(filepath) > max_file_size: processed_files += 1
continue if progress_callback:
progress_callback(processed_files, total_files)
continue
try: if max_file_size and os.path.getsize(filepath) > max_file_size:
with open(filepath, "r", encoding="utf-8") as f: processed_files += 1
content = f.read() if progress_callback:
files_dict[relpath] = content progress_callback(processed_files, total_files)
except Exception as e: continue
print(f"Warning: Could not read file {filepath}: {e}")
try:
with open(filepath, "r", encoding="utf-8") as f:
content = f.read()
files_dict[relpath] = content
except Exception as e:
print(f"Warning: Could not read file {filepath}: {e}")
processed_files += 1
if progress_callback:
progress_callback(processed_files, total_files)
return {"files": files_dict} return {"files": files_dict}
@@ -138,4 +132,4 @@ if __name__ == "__main__":
) )
print(f"Found {len(files_data['files'])} files:") print(f"Found {len(files_data['files'])} files:")
for path in files_data["files"]: for path in files_data["files"]:
print(f" {path}") print(f" {path}")