-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiskscope.cpp
More file actions
399 lines (327 loc) · 12 KB
/
diskscope.cpp
File metadata and controls
399 lines (327 loc) · 12 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <cstdint>
#include <future>
#ifdef _WIN32
#include <windows.h>
#endif
namespace fs = std::filesystem;
// ============================================================================
// UTILITIES
// ============================================================================
std::string formatSize(std::uintmax_t bytes) {
const char* units[] = {"B", "KB", "MB", "GB", "TB"};
const int numUnits = 5;
int unitIndex = 0;
double size = static_cast<double>(bytes);
while (size >= 1024.0 && unitIndex < numUnits - 1) {
size /= 1024.0;
unitIndex++;
}
std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << size << " " << units[unitIndex];
return oss.str();
}
/**
* Clears the console screen
*/
void clearScreen() {
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
// ============================================================================
// SIZE CALCULATION
// ============================================================================
std::uintmax_t calculateFolderSize(const fs::path& folderPath) {
std::uintmax_t totalSize = 0;
std::error_code ec;
// Try to iterate the directory
auto dirIter = fs::directory_iterator(folderPath, ec);
if (ec) {
// Access denied or other error - return 0
return 0;
}
for (const auto& entry : dirIter) {
std::error_code entryEc;
// Skip symbolic links
if (entry.is_symlink(entryEc)) {
continue;
}
if (entry.is_directory(entryEc) && !entryEc) {
// Recurse into subdirectory
totalSize += calculateFolderSize(entry.path());
}
else if (entry.is_regular_file(entryEc) && !entryEc) {
// Add file size
auto fileSize = entry.file_size(entryEc);
if (!entryEc) {
totalSize += fileSize;
}
}
}
return totalSize;
}
// ============================================================================
// FOLDER INFO (for current level only)
// ============================================================================
struct FolderEntry {
std::string name;
fs::path path;
std::uintmax_t size;
bool accessDenied;
};
#include <map>
std::map<std::string, std::vector<FolderEntry>> globalCache;
std::vector<FolderEntry> getSubfolders(const fs::path& parentPath) {
std::vector<FolderEntry> folders;
std::error_code ec;
auto dirIter = fs::directory_iterator(parentPath, ec);
if (ec) {
return folders; // Empty if can't read
}
struct Task {
std::future<std::uintmax_t> future;
std::string name;
fs::path path;
};
std::vector<Task> tasks;
std::cout << " Scanning subfolders (Parallel Mode)... " << std::flush;
for (const auto& entry : dirIter) {
std::error_code entryEc;
// Only process directories
if (entry.is_directory(entryEc) && !entryEc && !entry.is_symlink(entryEc)) {
// Launch async task for each folder
tasks.push_back({
std::async(std::launch::async, calculateFolderSize, entry.path()),
entry.path().filename().string(),
entry.path()
});
}
}
// Collect results
for (auto& task : tasks) {
FolderEntry folder;
folder.name = task.name;
folder.path = task.path;
folder.accessDenied = false;
// .get() waits for the thread to finish
folder.size = task.future.get();
folders.push_back(folder);
}
// Sort by size descending (largest first)
std::sort(folders.begin(), folders.end(),
[](const FolderEntry& a, const FolderEntry& b) {
return a.size > b.size;
});
return folders;
}
// ============================================================================
// DISPLAY
// ============================================================================
void displayCurrentLevel(const fs::path& currentPath, const std::vector<FolderEntry>& folders) {
clearScreen();
std::cout << "============================================================\n";
std::cout << " DiskScope - Interactive Disk Explorer\n";
std::cout << "============================================================\n\n";
std::cout << "Current: " << currentPath.string() << "\n";
std::cout << "------------------------------------------------------------\n\n";
if (folders.empty()) {
std::cout << " (No subfolders found)\n";
} else {
// Find max name length for alignment
size_t maxNameLen = 0;
for (const auto& f : folders) {
maxNameLen = std::max(maxNameLen, f.name.length());
}
maxNameLen = std::min(maxNameLen, size_t(40)); // Cap at 40 chars
for (size_t i = 0; i < folders.size(); ++i) {
std::string displayName = folders[i].name;
if (displayName.length() > 40) {
displayName = displayName.substr(0, 37) + "...";
}
std::cout << " [" << std::setw(2) << i << "] "
<< std::left << std::setw(maxNameLen + 2) << displayName
<< std::right << std::setw(12) << formatSize(folders[i].size)
<< "\n";
}
}
std::cout << "\n------------------------------------------------------------\n";
std::cout << " [num] = enter | 'b' = back | 'r' = refresh\n";
std::cout << "------------------------------------------------------------\n";
std::cout << "> ";
}
// ============================================================================
// DRIVE DETECTION (Windows)
// ============================================================================
std::vector<fs::path> getAvailableDrives() {
std::vector<fs::path> drives;
#ifdef _WIN32
// Check drives
for (char letter = 'A'; letter <= 'Z'; ++letter) {
std::string drivePath = std::string(1, letter) + ":\\";
// Check if drive exists
UINT driveType = GetDriveTypeA(drivePath.c_str());
if (driveType != DRIVE_NO_ROOT_DIR && driveType != DRIVE_UNKNOWN) {
drives.push_back(fs::path(drivePath));
}
}
#else
drives.push_back(fs::path("/"));
#endif
return drives;
}
/**
* Shows drive selection menu and returns selected path
*/
fs::path selectDrive() {
std::vector<fs::path> drives = getAvailableDrives();
std::cout << "\n============================================================\n";
std::cout << " DiskScope - Interactive Disk Explorer\n";
std::cout << "============================================================\n\n";
std::cout << "Available drives:\n";
std::cout << "------------------------------------------------------------\n\n";
for (size_t i = 0; i < drives.size(); ++i) {
std::cout << " [" << i << "] " << drives[i].string() << "\n";
}
std::cout << "\n------------------------------------------------------------\n";
std::cout << "Select drive number or type a path: ";
std::string input;
std::getline(std::cin, input);
// Trim whitespace
while (!input.empty() && isspace(input.front())) input.erase(input.begin());
while (!input.empty() && isspace(input.back())) input.pop_back();
// Try to parse as number
try {
size_t index = std::stoul(input);
if (index < drives.size()) {
return drives[index];
}
} catch (...) {
// Not a number - treat as path
}
// If it looks like a path, use it directly
if (!input.empty()) {
return fs::path(input);
}
// Default to C:\
return drives.empty() ? fs::path("C:\\") : drives[0];
}
// ============================================================================
// MAIN - INTERACTIVE LOOP
// ============================================================================
void setupConsole() {
#ifdef _WIN32
SetConsoleOutputCP(CP_UTF8);
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hConsole, &mode);
SetConsoleMode(hConsole, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
#endif
}
int main(int argc, char* argv[]) {
setupConsole();
// Determine starting path
fs::path currentPath;
if (argc > 1) {
std::string arg = argv[1];
if (arg == "-h" || arg == "--help" || arg == "/?") {
std::cout << "\nDiskScope - Interactive Disk Explorer\n";
std::cout << "=====================================\n\n";
std::cout << "Usage: diskscope [path]\n\n";
std::cout << "Controls:\n";
std::cout << " [number] Navigate into folder\n";
std::cout << " b Go back to parent\n";
std::cout << " r Refresh current folder\n";
std::cout << " q Quit\n";
return 0;
}
currentPath = fs::absolute(arg);
// Validate provided path
if (!fs::exists(currentPath) || !fs::is_directory(currentPath)) {
std::cerr << "Error: Invalid directory: " << currentPath << "\n";
return 1;
}
} else {
// No argument - show drive selection
currentPath = selectDrive();
if (!fs::exists(currentPath) || !fs::is_directory(currentPath)) {
std::cerr << "Error: Invalid directory: " << currentPath << "\n";
return 1;
}
}
// Global cache for folder contents
std::map<std::string, std::vector<FolderEntry>> globalCache;
std::vector<fs::path> history;
// Main interaction loop
while (true) {
// 1. SCAN (if not cached)
bool needsScan = true;
std::vector<FolderEntry> folders;
std::string pathKey = currentPath.string();
if (globalCache.count(pathKey)) {
// Found in cache! Use it.
folders = globalCache[pathKey];
needsScan = false;
}
if (needsScan) {
std::cout << "\nScanning folders...\n";
folders = getSubfolders(currentPath);
// Save to cache
globalCache[pathKey] = folders;
}
// 2. DISPLAY
displayCurrentLevel(currentPath, folders);
// 3. INPUT
std::string input;
std::getline(std::cin, input);
// Trim
while (!input.empty() && isspace(input.front())) input.erase(input.begin());
while (!input.empty() && isspace(input.back())) input.pop_back();
if (input.empty()) continue;
// Process Input
if (input == "b" || input == "B") {
// BACK
if (!history.empty()) {
currentPath = history.back();
history.pop_back();
} else {
// Return to drive selection if at root history
currentPath = selectDrive();
}
}
else if (input == "r" || input == "R") {
// REFRESH (Clear cache for this folder)
globalCache.erase(pathKey);
}
else if (input == "q" || input == "Q") {
break;
}
else {
// TRY ENTER FOLDER
try {
size_t index = std::stoul(input);
if (index < folders.size()) {
// Push current to history
history.push_back(currentPath);
// Enter new
currentPath = folders[index].path;
} else {
std::cout << "Invalid selection. Press Enter to continue...";
std::cin.get();
}
} catch (...) {
std::cout << "Invalid input. Press Enter to continue...";
std::cin.get();
}
}
}
return 0;
}