File size: 6,337 Bytes
6237959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215

from pathlib import Path
from datetime import datetime
import os

# ==========================================
# KONFIGURACJA
# ==========================================

DEFAULT_FOLDER = r"C:\Users\Mateusz\Desktop\ORCASat"
OUTPUT_NAME = "structure_tree_output.txt"


def format_size(size):
    return f"{size:,}".replace(",", " ") + " B"


def get_extension(path):
    extensions = "".join(path.suffixes)
    return extensions if extensions else "(brak rozszerzenia)"


def get_date(timestamp):
    return datetime.fromtimestamp(timestamp).strftime(
        "%Y-%m-%d %H:%M:%S"
    )


def generate_report(folder_path):
    root = Path(folder_path).expanduser().absolute()

    if not root.is_dir():
        print(f"BLAD: Folder nie istnieje: {root}")
        return

    output_file = root / OUTPUT_NAME

    tree = [f"{root.name}/"]
    details = []
    errors = []

    stats = {
        "directories": 0,
        "files": 0,
        "links": 0,
        "other": 0,
        "total_bytes": 0
    }

    def sort_key(path):
        try:
            is_directory = path.is_dir() and not path.is_symlink()
        except OSError:
            is_directory = False

        return (not is_directory, path.name.casefold())

    def scan_directory(current, prefix=""):
        try:
            entries = sorted(
                [
                    p for p in current.iterdir()
                    if p != output_file
                ],
                key=sort_key
            )
        except OSError as exc:
            message = f"Nie mozna odczytac: {current} ({exc})"
            errors.append(message)
            tree.append(prefix + "[BLAD ODCZYTU]")
            return

        for index, entry in enumerate(entries):
            is_last = index == len(entries) - 1

            connector = "└── " if is_last else "├── "
            next_prefix = prefix + (
                "    " if is_last else "│   "
            )

            try:
                metadata = entry.lstat()
                is_link = entry.is_symlink()
                is_directory = (
                    entry.is_dir() and not is_link
                )
                is_file = (
                    entry.is_file() and not is_link
                )

                relative = entry.relative_to(root)
                full_path = entry.absolute()
                size = metadata.st_size
                modified = get_date(metadata.st_mtime)

                if is_directory:
                    element_type = "KATALOG"
                    extension = "(nie dotyczy)"
                    description = "[KATALOG]"
                    stats["directories"] += 1

                elif is_file:
                    element_type = "PLIK"
                    extension = get_extension(entry)
                    description = (
                        f"[PLIK | {extension} | "
                        f"{format_size(size)}]"
                    )
                    stats["files"] += 1
                    stats["total_bytes"] += size

                elif is_link:
                    element_type = "DOWIAZANIE"
                    extension = get_extension(entry)
                    description = "[DOWIAZANIE]"
                    stats["links"] += 1

                else:
                    element_type = "INNY"
                    extension = get_extension(entry)
                    description = "[INNY]"
                    stats["other"] += 1

                tree.append(
                    f"{prefix}{connector}"
                    f"{entry.name} {description}"
                )

                record = [
                    "=" * 75,
                    f"Nazwa:           {entry.name}",
                    f"Typ:             {element_type}",
                    f"Rozszerzenie:    {extension}",
                    f"Sciezka pelna:   {full_path}",
                    f"Sciezka wzgledna:{relative}",
                    f"Ostatnia zmiana: {modified}"
                ]

                if is_file:
                    record.append(
                        f"Rozmiar:         {format_size(size)}"
                    )

                if is_link:
                    record.append(
                        f"Cel dowiazania: {os.readlink(entry)}"
                    )

                details.extend(record)
                details.append("")

                if is_directory:
                    scan_directory(entry, next_prefix)

            except OSError as exc:
                message = f"{entry}: {exc}"
                errors.append(message)
                tree.append(
                    f"{prefix}{connector}"
                    f"{entry.name} [BLAD]"
                )

    print("Analizowanie struktury folderu...")
    scan_directory(root)

    report = [
        "RAPORT STRUKTURY KATALOGU",
        "=" * 75,
        f"Folder glowny: {root}",
        f"Data raportu: {datetime.now():%Y-%m-%d %H:%M:%S}",
        "",
        "PODSUMOWANIE",
        "-" * 75,
        f"Liczba katalogow: {stats['directories']}",
        f"Liczba plikow:    {stats['files']}",
        f"Liczba dowiazan:  {stats['links']}",
        f"Inne elementy:   {stats['other']}",
        f"Laczny rozmiar:  {format_size(stats['total_bytes'])}",
        "",
        "DRZEWO KATALOGOW",
        "=" * 75,
        *tree,
        "",
        "SZCZEGOLOWY WYKAZ ELEMENTOW",
        "=" * 75,
        *details,
        "",
        "BLEDY ODCZYTU",
        "=" * 75,
        *(errors if errors else ["Brak bledow."]),
        ""
    ]

    # Zapis w trybie nadpisywania.
    # UTF-8 BOM zapewnia poprawne otwieranie w Notatniku.
    with output_file.open("w", encoding="utf-8-sig") as file:
        file.write("\n".join(report))

    print("\nZAKONCZONO")
    print(f"Zapisano: {output_file}")
    print(f"Katalogi: {stats['directories']}")
    print(f"Pliki: {stats['files']}")
    print(f"Bledy: {len(errors)}")


if __name__ == "__main__":
    folder = input(
        f"Podaj sciezke folderu [{DEFAULT_FOLDER}]: "
    ).strip().strip('"')

    if not folder:
        folder = DEFAULT_FOLDER

    generate_report(folder)