INITIAL COMMIT
This commit is contained in:
46
utils.py
Normal file
46
utils.py
Normal file
@ -0,0 +1,46 @@
|
||||
from collections import defaultdict
|
||||
import os
|
||||
|
||||
from typing import DefaultDict, Dict, List
|
||||
|
||||
|
||||
def tree() -> DefaultDict:
|
||||
return defaultdict(tree)
|
||||
|
||||
|
||||
def get_last_segment(path: str) -> str:
|
||||
if path[-1] == '/':
|
||||
path = path[:-1]
|
||||
return path.split(os.sep)[-1]
|
||||
|
||||
|
||||
FILES_KEY = '_i_files'
|
||||
|
||||
|
||||
def build_file_tree(root_dir: str) -> DefaultDict:
|
||||
file_tree = tree()
|
||||
root_dir = os.path.normpath(root_dir) # Normalize the path
|
||||
|
||||
for dirpath, dirnames, files in os.walk(root_dir):
|
||||
# Get the subdirectory path relative to the root directory
|
||||
subdir = os.path.relpath(dirpath, root_dir)
|
||||
|
||||
# Split the path into components to navigate the nested dictionary
|
||||
path_components = subdir.split(os.sep)
|
||||
|
||||
# Navigate to the current subdirectory in the file tree
|
||||
current_subdir = file_tree
|
||||
for component in path_components:
|
||||
current_subdir = current_subdir[component]
|
||||
|
||||
# Add files to the current subdirectory in the file tree
|
||||
current_subdir[FILES_KEY] = files
|
||||
|
||||
return file_tree
|
||||
|
||||
|
||||
# Function to convert defaultdict to dict (for readability)
|
||||
def defaultdict_to_dict(d: defaultdict) -> dict:
|
||||
if isinstance(d, defaultdict):
|
||||
d = {k: defaultdict_to_dict(v) for k, v in d.items()}
|
||||
return d
|
Reference in New Issue
Block a user