hfcontext7 / repo2txt.py
abdullahmeda's picture
finalize hfcontext7 v2
0955e72
"""
A fork of github.com/donoceidon/repo2txt/blob/main/src/repo2txt/repo2txt.py
This version only includes the functionality to document the structure of a repository containing .md and .mdx files.
"""
import os
def should_ignore(item_path):
"""
Determine if a given item should be ignored.
Only includes .md and .mdx files, ignores hidden files and directories.
Args:
item_path (str): The path of the item (file or directory) to check.
Returns:
bool: True if the item should be ignored, False otherwise.
"""
item_name = os.path.basename(item_path)
# Ignore hidden files and directories
if item_name.startswith('.'):
return True
# If it's a file, only include .md and .mdx files
if os.path.isfile(item_path):
file_ext = os.path.splitext(item_name)[1].lower()
return file_ext not in ['.md', '.mdx']
# Include directories (they will be traversed)
return False
def make_tree(dir_path, prefix="", is_root=True):
"""
Recursively generate the directory tree as a string.
Args:
dir_path (str): The path of the directory to document.
prefix (str): Prefix string for line indentation and structure.
is_root (bool): Flag to indicate if the current directory is the root.
Returns:
str: The tree structure as a string.
"""
tree_string = ""
if is_root:
tree_string += "└── ./\n"
# Add the actual directory name as a child of ./
actual_dir_name = os.path.basename(dir_path)
if actual_dir_name:
tree_string += f" └── {actual_dir_name}\n"
prefix = " "
else:
prefix = " "
is_root = False
try:
items = os.listdir(dir_path)
except PermissionError:
return tree_string
items.sort()
# Filter out items that should be ignored
filtered_items = []
for item in items:
item_path = os.path.join(dir_path, item)
if not should_ignore(item_path):
filtered_items.append(item)
num_items = len(filtered_items)
for index, item in enumerate(filtered_items):
item_path = os.path.join(dir_path, item)
is_last_item = (index == num_items - 1)
new_prefix = "└── " if is_last_item else "β”œβ”€β”€ "
child_prefix = " " if is_last_item else "β”‚ "
tree_string += f"{prefix}{new_prefix}{item}\n"
if os.path.isdir(item_path):
next_prefix = prefix + child_prefix
tree_string += make_tree(item_path, next_prefix, is_root=False)
return tree_string