Repository navigation
Expand file tree
/
Copy pathallocsight.cpp
More file actions
291 lines (265 loc) · 12.2 KB
/
Copy pathallocsight.cpp
File metadata and controls
291 lines (265 loc) · 12.2 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
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#define INITGUID
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <propidl.h>
#include <portabledevice.h>
#include <portabledeviceapi.h>
#include <portabledevicetypes.h>
#include "alloc_types.hpp"
#include "alloc_scanner.hpp"
#include "alloc_wpd.hpp"
#include "alloc_filter.hpp"
#include "alloc_views.hpp"
#include <chrono>
#include <fstream>
using namespace allocsight;
static int64_t parseSizeOption(const std::string& raw) {
std::string low = asciiLower(trimWhitespace(raw));
if (low.empty()) return 0;
size_t i = 0;
while (i < low.size() && ((low[i] >= '0' && low[i] <= '9') || low[i] == '.')) ++i;
if (i == 0) return 0;
double val = std::stod(low.substr(0, i));
std::string unit = trimWhitespace(low.substr(i));
int64_t mult = 1;
if (unit == "k" || unit == "kb" || unit == "kib") mult = 1024LL;
else if (unit == "m" || unit == "mb" || unit == "mib") mult = 1024LL * 1024LL;
else if (unit == "g" || unit == "gb" || unit == "gib") mult = 1024LL * 1024LL * 1024LL;
else if (unit == "t" || unit == "tb" || unit == "tib") mult = 1024LL * 1024LL * 1024LL * 1024LL;
return static_cast<int64_t>(val * static_cast<double>(mult));
}
static void printBannerHelp() {
std::cout <<
R"(================================================================================
AllocSight v1.1.2 - High-Concurrency Disk Allocation & AI Space Cleanup CLI
License: MIT (Zero-Dependency Native Win32 C++17 Implementation)
================================================================================
USAGE:
allocsight drives List all logical volumes & capacity
allocsight tree <path> [options] Hierarchical cluster-allocation tree
allocsight top <path> [options] Top-N largest files & directories
allocsight categories <path> [options] Breakdown by AI/dev categories & exts
allocsight analyze <path> [options] Smart cleanup & redundancy diagnostic
allocsight report <path> [options] Generate clickable Markdown report
OPTIONS:
-f, --filter "<expr>" Filter expression (e.g. "*.whl;>100mb;dir:node_modules")
-d, --depth <N> Max directory tree depth to display (default: 2)
-n, --top <N> Max items per level or list (default: 20)
-m, --min-size <size> Minimum allocated size to display (e.g. 50mb, 1gb)
-t, --threads <N> Worker threads for parallel Win32 scan (default: auto)
-o, --output <file> Write output (e.g. Markdown report or JSON) to file
--files Include only regular files in top/tree
--folders Include only directories in top/tree
--ads Inspect NTFS Alternate Data Streams (FindFirstStreamW)
--hardlinks Deduplicate NTFS hard links (prevents WinSxS double counting)
--logical Rank/display by logical size instead of cluster size
--unlocaldisk Enable scanning non-local / portable devices (MTP smartphones, WPD)
-j, --json Emit structured JSON (with file:/// URIs) for AI agents
-q, --quiet Suppress stderr scan telemetry summary
FILTER SYNTAX EXAMPLES:
- File globs : *.gguf;*.safetensors !*.log (prefix '!' or '-' to exclude)
- Folder globs : dir:node_modules;dir:.venv !dir:windows (or trailing '/')
- Size bounds : >100mb <4kb allocated>1gb logical>500mb
- Time / Age : >6months <7days created>30days modified>1year
- Categories : category:AI Models category:Archives category:Virtual
- Attributes : attr:hidden+system attr:compressed attr:sparse+ads
================================================================================
)";
}
int wmain(int argc, wchar_t* argv[]) {
SetConsoleOutputCP(CP_UTF8);
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
if (argc <= 1) {
printBannerHelp();
return 0;
}
std::vector<std::wstring> args;
for (int i = 1; i < argc; ++i) {
args.emplace_back(argv[i]);
}
std::string cmd = asciiLower(wideToUtf8(args[0]));
if (cmd == "help" || cmd == "-h" || cmd == "--help" || cmd == "/?") {
printBannerHelp();
return 0;
}
if (cmd == "version" || cmd == "-v" || cmd == "--version") {
std::cout << "AllocSight v1.1.2 (MIT License)\n";
return 0;
}
cmd = "tree";
size_t cmdArgIdx = static_cast<size_t>(-1);
for (size_t i = 0; i < args.size(); ++i) {
std::string s = asciiLower(wideToUtf8(args[i]));
if (s == "drives" || s == "tree" || s == "top" ||
s == "categories" || s == "analyze" || s == "report" || s == "scan") {
cmd = s;
cmdArgIdx = i;
break;
}
}
ScanConfig scanCfg{};
RenderOptions renderOpts{};
std::string filterExpr;
std::wstring outputPath;
std::vector<std::wstring> positional;
bool unlocalDisk = false;
for (size_t idx = 0; idx < args.size(); ++idx) {
if (idx == cmdArgIdx) continue;
std::string a = wideToUtf8(args[idx]);
if ((a == "-f" || a == "--filter") && idx + 1 < args.size()) {
filterExpr = wideToUtf8(args[++idx]);
} else if ((a == "-d" || a == "--depth") && idx + 1 < args.size()) {
renderOpts.maxDepth = std::stoi(wideToUtf8(args[++idx]));
scanCfg.maxScanDepth = renderOpts.maxDepth;
} else if ((a == "-n" || a == "--top") && idx + 1 < args.size()) {
renderOpts.topLimit = std::stoi(wideToUtf8(args[++idx]));
} else if ((a == "-m" || a == "--min-size") && idx + 1 < args.size()) {
renderOpts.minBytes = parseSizeOption(wideToUtf8(args[++idx]));
} else if ((a == "-t" || a == "--threads") && idx + 1 < args.size()) {
scanCfg.workerThreads = std::stoi(wideToUtf8(args[++idx]));
} else if ((a == "-o" || a == "--output") && idx + 1 < args.size()) {
outputPath = args[++idx];
} else if (a == "--files") {
renderOpts.filesOnly = true;
} else if (a == "--folders" || a == "--dirs") {
renderOpts.dirsOnly = true;
} else if (a == "--ads") {
scanCfg.includeAltStreams = true;
} else if (a == "--hardlinks") {
scanCfg.detectHardLinks = true;
} else if (a == "--logical") {
renderOpts.useLogical = true;
} else if (a == "--unlocaldisk" || a == "--unlocal") {
unlocalDisk = true;
} else if (a == "-j" || a == "--json") {
renderOpts.jsonOutput = true;
} else if (a == "-q" || a == "--quiet") {
scanCfg.quietMode = true;
} else {
positional.push_back(args[idx]);
}
}
std::ofstream fileOut;
std::ostream* outStream = &std::cout;
if (!outputPath.empty()) {
fileOut.open(outputPath.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
if (!fileOut) {
std::cerr << "[ERROR] Cannot open output file: " << wideToUtf8(outputPath) << "\n";
return 1;
}
outStream = &fileOut;
}
if (cmd == "drives") {
ReportEngine::renderDrives(renderOpts.jsonOutput, *outStream, unlocalDisk);
return 0;
}
if (positional.empty()) {
if (unlocalDisk) {
auto wpdDevices = WpdManager::enumerateDevices();
if (wpdDevices.empty()) {
std::cerr << "[ERROR] No portable (WPD/MTP) devices detected.\n"
<< "Please connect your mobile device via USB and ensure it is set to 'File Transfer / MTP' mode.\n"
<< "Run 'allocsight drives --unlocaldisk' to check status.\n";
return 1;
} else if (wpdDevices.size() == 1) {
std::cerr << "[INFO] Sole portable device detected: [0] " << wideToUtf8(wpdDevices[0].friendlyName) << "\n"
<< "Please specify target, for example:\n"
<< " allocsight " << cmd << " \"wpd:0\" --unlocaldisk\n";
return 0;
} else {
std::cerr << "[INFO] Multiple portable devices detected (" << wpdDevices.size() << " devices):\n";
for (size_t di = 0; di < wpdDevices.size(); ++di) {
std::cerr << " [" << di << "] " << wideToUtf8(wpdDevices[di].friendlyName);
if (!wpdDevices[di].storages.empty()) {
std::cerr << " (" << wideToUtf8(wpdDevices[di].storages[0].name) << ")";
}
std::cerr << "\n";
}
std::cerr << "Please specify the target device or folder, for example:\n"
<< " allocsight " << cmd << " \"wpd:0\" --unlocaldisk\n"
<< " allocsight " << cmd << " \"wpd:0\\DCIM\" --unlocaldisk\n";
return 0;
}
}
std::cerr << "[ERROR] Missing target directory or volume path.\n";
printBannerHelp();
return 1;
}
bool isWpd = isWpdTarget(positional[0]);
if (isWpd && !unlocalDisk) {
std::cerr << "[ERROR] Portable (WPD/MTP) device target detected ('" << wideToUtf8(positional[0]) << "').\n"
<< "Scanning non-local or portable devices requires the '--unlocaldisk' flag.\n\n"
<< "Example:\n"
<< " allocsight " << cmd << " \"" << wideToUtf8(positional[0]) << "\" --unlocaldisk\n";
return 1;
}
auto tStart = std::chrono::steady_clock::now();
ScanTelemetry telemetry{};
VolumeMetrics volInfo{};
std::unique_ptr<FsNode> root;
if (isWpd) {
root = WpdScanner::scan(positional[0], scanCfg, telemetry, &volInfo);
} else {
root = ParallelScanner::scan(positional[0], scanCfg, telemetry, &volInfo);
}
auto tEnd = std::chrono::steady_clock::now();
double secs = std::chrono::duration<double>(tEnd - tStart).count();
if (!root) {
std::cerr << "[ERROR] Target produced an empty or inaccessible tree.\n";
return 1;
}
if (!renderOpts.jsonOutput && !scanCfg.quietMode) {
if (isWpd) {
std::cerr << "[AllocSight scanned portable device in " << std::fixed << std::setprecision(2) << secs << "s | "
<< telemetry.dirsCount.load() << " dirs, "
<< telemetry.filesCount.load() << " files | "
<< "Data=" << humanBytes(telemetry.logicalTotal.load()) << "]\n";
} else {
std::cerr << "[AllocSight scanned in " << std::fixed << std::setprecision(2) << secs << "s | "
<< telemetry.dirsCount.load() << " dirs, "
<< telemetry.filesCount.load() << " files";
if (telemetry.hardLinksCount.load() > 0) {
std::cerr << ", " << telemetry.hardLinksCount.load() << " hardlinks deduped ("
<< humanBytes(telemetry.hardLinksBytesSaved.load()) << " saved)";
}
std::cerr << " | Threads=" << telemetry.threadsUsed << ", "
<< "Cluster=" << volInfo.clusterBytes << "B, "
<< "BackupPriv=" << (telemetry.backupPrivilegeEnabled ? "ON" : "OFF") << "]\n";
}
}
if (!filterExpr.empty()) {
QueryFilter qf(filterExpr);
for (const auto& w : qf.warnings()) {
std::cerr << "[Filter Warning] " << w << "\n";
}
if (!qf.isEmpty()) {
root = qf.applyToTree(root.get());
}
}
if (!root) {
std::cerr << "[ERROR] Filter matched 0 items, tree is empty.\n";
return 0;
}
if (cmd == "top") {
ReportEngine::renderTop(root.get(), renderOpts, *outStream);
} else if (cmd == "categories") {
QueryFilter qf(filterExpr);
ReportEngine::renderCategories(root.get(), qf, renderOpts, *outStream);
} else if (cmd == "analyze") {
ReportEngine::renderAnalyze(root.get(), renderOpts, *outStream);
} else if (cmd == "report") {
ReportEngine::renderMarkdownReport(root.get(), renderOpts, *outStream);
if (!outputPath.empty() && !scanCfg.quietMode) {
std::cerr << "[Report written to " << wideToUtf8(outputPath) << "]\n";
}
} else {
ReportEngine::renderTree(root.get(), renderOpts, *outStream);
}
return 0;
}