Source Code

/ ssg / src / repository / tree.py

import re
from django.db.models import Q
from repository.models import File

def get_children_of(dir_path):
    """
    Return the children of a directory
    """
    if not dir_path:
        return File.objects.filter(~Q(path__contains="/"))

    prefix = f"{dir_path}/"
    return File.objects.filter(
        Q(path__startswith=prefix) &
        ~Q(path__regex=rf'^{re.escape(prefix)}[^/]*/')
    )

def get_render_context(dir_path=None, expanded_dirs=None, current_file=None):
    files = get_children_of(dir_path).order_by("-is_directory", "name")

    return {
        "files": files,
        "dir_path": dir_path or "",
        "expanded_dirs": expanded_dirs or [],
        "current_file": current_file,
        "should_expand": bool(dir_path and expanded_dirs and dir_path in expanded_dirs),
    }