File size: 1,966 Bytes
2847c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
"""
core.py
Application orchestration
"""

from __future__ import annotations

import tempfile
import zipfile
from pathlib import Path

from builder import (
    build_markdown,
    build_xml,
    split_output,
)
from reader import load_files
from scanner import (
    scan_files,
    build_tree_text,
)
from statistics import (
    build_statistics,
    statistics_markdown,
)


def extract_zip(zip_path: str) -> Path:
    """
    Extract uploaded ZIP into temp directory.
    """

    temp_dir = Path(tempfile.mkdtemp())

    with zipfile.ZipFile(zip_path, "r") as z:
        z.extractall(temp_dir)

    items = list(temp_dir.iterdir())

    if len(items) == 1 and items[0].is_dir():
        return items[0]

    return temp_dir


def build_context(
    zip_path: str,
    ignored_dirs: str,
    allowed_extensions: set[str] | None,
    max_size_mb: float,
    output_format: str,
    max_tokens: int,
    include_hash: bool,
):

    root = extract_zip(zip_path)

    ignore = {
        x.strip()
        for x in ignored_dirs.split(",")
        if x.strip()
    }

    files = scan_files(
        root=root,
        extra_ignore_dirs=ignore,
        max_size_mb=max_size_mb,
        allowed_extensions=allowed_extensions,
    )

    contents = load_files(files)

    stats = build_statistics(
        files,
        contents,
    )

    if output_format.lower() == "xml":
        text = build_xml(
            root,
            contents,
            include_hash,
        )
        ext = "xml"

    else:

        text = build_markdown(
            root,
            contents,
            include_hash,
        )

        ext = "md"

    chunks = split_output(
        text,
        max_tokens,
    )

    tree = build_tree_text(
        root,
        files,
    )

    preview = text[:3000]

    return {
        "statistics": statistics_markdown(stats),
        "tree": tree,
        "preview": preview,
        "chunks": chunks,
        "extension": ext,
    }