myspace-cli 1.4.0__py3-none-any.whl → 1.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {myspace_cli-1.4.0.dist-info → myspace_cli-1.5.0.dist-info}/METADATA +1 -2
- myspace_cli-1.5.0.dist-info/RECORD +6 -0
- space_cli.py +134 -1045
- myspace_cli-1.4.0.dist-info/RECORD +0 -6
- {myspace_cli-1.4.0.dist-info → myspace_cli-1.5.0.dist-info}/WHEEL +0 -0
- {myspace_cli-1.4.0.dist-info → myspace_cli-1.5.0.dist-info}/entry_points.txt +0 -0
- {myspace_cli-1.4.0.dist-info → myspace_cli-1.5.0.dist-info}/top_level.txt +0 -0
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: myspace-cli
|
3
|
-
Version: 1.
|
3
|
+
Version: 1.5.0
|
4
4
|
Summary: A macOS disk space analysis CLI: health, index, app usage, big files.
|
5
5
|
Author-email: Your Name <you@example.com>
|
6
6
|
License: MIT
|
@@ -38,7 +38,6 @@ space-cli是一个开源的macOS命令行小工具,用于分析磁盘空间健
|
|
38
38
|
- 🗑️ **一键删除应用** - 在应用分析列表中输入序号即可一键删除所选应用及其缓存(含二次确认)
|
39
39
|
- 🏠 **用户目录深度分析** - 针对 `~/Library`、`~/Downloads`、`~/Documents` 分别下探并展示Top N目录
|
40
40
|
- 🗄️ **大文件分析** - 扫描并列出指定路径下最大的文件,支持数量和最小体积阈值
|
41
|
-
- 🔄 **返回上一级** - 在下探分析中支持选择0返回上一级目录
|
42
41
|
- ⏱️ **支持MCP调用** - 支持你自己的AI Agent无缝调用磁盘空间信息
|
43
42
|
|
44
43
|
## 安装
|
@@ -0,0 +1,6 @@
|
|
1
|
+
space_cli.py,sha256=smLtarqGtTKHcIMi7usckw8M9IcM2hlQDXXY8zvM3x4,9487
|
2
|
+
myspace_cli-1.5.0.dist-info/METADATA,sha256=QCG4_N2rvebz_sC2ui4RFCG6hRhY1I9j_AvKd38lVLc,12665
|
3
|
+
myspace_cli-1.5.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
4
|
+
myspace_cli-1.5.0.dist-info/entry_points.txt,sha256=sIVEmPf6W8aNa7KiqOwAI6JrsgHlQciO5xH2G29tKPQ,45
|
5
|
+
myspace_cli-1.5.0.dist-info/top_level.txt,sha256=lnUfbQX9h-9ZjecMVCOWucS2kx69FwTndlrb48S20Sc,10
|
6
|
+
myspace_cli-1.5.0.dist-info/RECORD,,
|
space_cli.py
CHANGED
@@ -1,956 +1,19 @@
|
|
1
1
|
#!/usr/bin/env python3
|
2
2
|
# -*- coding: utf-8 -*-
|
3
3
|
"""
|
4
|
-
SpaceCli -
|
5
|
-
|
4
|
+
SpaceCli - macOS 磁盘空间分析工具
|
5
|
+
模块化版本的主入口文件
|
6
6
|
"""
|
7
7
|
|
8
8
|
import os
|
9
9
|
import sys
|
10
10
|
import argparse
|
11
|
-
import subprocess
|
12
|
-
import shutil
|
13
11
|
from pathlib import Path
|
14
|
-
from typing import List, Tuple, Dict
|
15
|
-
import json
|
16
|
-
import time
|
17
|
-
from datetime import datetime, timedelta
|
18
|
-
import heapq
|
19
12
|
|
13
|
+
# 添加 src 目录到 Python 路径
|
14
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
|
20
15
|
|
21
|
-
|
22
|
-
"""简单的目录大小索引缓存管理器"""
|
23
|
-
|
24
|
-
def __init__(self, index_file: str = None):
|
25
|
-
home = str(Path.home())
|
26
|
-
cache_dir = os.path.join(home, ".spacecli")
|
27
|
-
os.makedirs(cache_dir, exist_ok=True)
|
28
|
-
self.index_file = index_file or os.path.join(cache_dir, "index.json")
|
29
|
-
self._data: Dict = {}
|
30
|
-
self._loaded = False
|
31
|
-
|
32
|
-
def load(self) -> None:
|
33
|
-
if self._loaded:
|
34
|
-
return
|
35
|
-
if os.path.exists(self.index_file):
|
36
|
-
try:
|
37
|
-
with open(self.index_file, "r", encoding="utf-8") as f:
|
38
|
-
self._data = json.load(f)
|
39
|
-
except Exception:
|
40
|
-
self._data = {}
|
41
|
-
self._loaded = True
|
42
|
-
|
43
|
-
def save(self) -> None:
|
44
|
-
try:
|
45
|
-
with open(self.index_file, "w", encoding="utf-8") as f:
|
46
|
-
json.dump(self._data, f, ensure_ascii=False, indent=2)
|
47
|
-
except Exception:
|
48
|
-
pass
|
49
|
-
|
50
|
-
def _key(self, root_path: str) -> str:
|
51
|
-
return os.path.abspath(root_path)
|
52
|
-
|
53
|
-
def get(self, root_path: str) -> Dict:
|
54
|
-
self.load()
|
55
|
-
return self._data.get(self._key(root_path))
|
56
|
-
|
57
|
-
def set(self, root_path: str, entries: List[Tuple[str, int]]) -> None:
|
58
|
-
self.load()
|
59
|
-
now_iso = datetime.utcnow().isoformat()
|
60
|
-
self._data[self._key(root_path)] = {
|
61
|
-
"updated_at": now_iso,
|
62
|
-
"entries": [{"path": p, "size": s} for p, s in entries],
|
63
|
-
}
|
64
|
-
self.save()
|
65
|
-
|
66
|
-
def is_fresh(self, root_path: str, ttl_hours: int) -> bool:
|
67
|
-
self.load()
|
68
|
-
rec = self._data.get(self._key(root_path))
|
69
|
-
if not rec:
|
70
|
-
return False
|
71
|
-
try:
|
72
|
-
updated_at = datetime.fromisoformat(rec.get("updated_at"))
|
73
|
-
return datetime.utcnow() - updated_at <= timedelta(hours=ttl_hours)
|
74
|
-
except Exception:
|
75
|
-
return False
|
76
|
-
|
77
|
-
# 命名缓存(非路径键),适合应用分析等聚合结果
|
78
|
-
def get_named(self, name: str) -> Dict:
|
79
|
-
self.load()
|
80
|
-
return self._data.get(name)
|
81
|
-
|
82
|
-
def set_named(self, name: str, entries: List[Tuple[str, int]]) -> None:
|
83
|
-
self.load()
|
84
|
-
now_iso = datetime.utcnow().isoformat()
|
85
|
-
self._data[name] = {
|
86
|
-
"updated_at": now_iso,
|
87
|
-
"entries": [{"name": p, "size": s} for p, s in entries],
|
88
|
-
}
|
89
|
-
self.save()
|
90
|
-
|
91
|
-
def is_fresh_named(self, name: str, ttl_hours: int) -> bool:
|
92
|
-
self.load()
|
93
|
-
rec = self._data.get(name)
|
94
|
-
if not rec:
|
95
|
-
return False
|
96
|
-
try:
|
97
|
-
updated_at = datetime.fromisoformat(rec.get("updated_at"))
|
98
|
-
return datetime.utcnow() - updated_at <= timedelta(hours=ttl_hours)
|
99
|
-
except Exception:
|
100
|
-
return False
|
101
|
-
|
102
|
-
|
103
|
-
class SpaceAnalyzer:
|
104
|
-
"""磁盘空间分析器"""
|
105
|
-
|
106
|
-
def __init__(self):
|
107
|
-
self.warning_threshold = 80 # 警告阈值百分比
|
108
|
-
self.critical_threshold = 90 # 严重阈值百分比
|
109
|
-
|
110
|
-
def get_disk_usage(self, path: str = "/") -> Dict:
|
111
|
-
"""获取磁盘使用情况"""
|
112
|
-
try:
|
113
|
-
statvfs = os.statvfs(path)
|
114
|
-
|
115
|
-
# 计算磁盘空间信息
|
116
|
-
total_bytes = statvfs.f_frsize * statvfs.f_blocks
|
117
|
-
free_bytes = statvfs.f_frsize * statvfs.f_bavail
|
118
|
-
used_bytes = total_bytes - free_bytes
|
119
|
-
|
120
|
-
# 计算百分比
|
121
|
-
usage_percent = (used_bytes / total_bytes) * 100
|
122
|
-
|
123
|
-
return {
|
124
|
-
'total': total_bytes,
|
125
|
-
'used': used_bytes,
|
126
|
-
'free': free_bytes,
|
127
|
-
'usage_percent': usage_percent,
|
128
|
-
'path': path
|
129
|
-
}
|
130
|
-
except Exception as e:
|
131
|
-
print(f"错误:无法获取磁盘使用情况 - {e}")
|
132
|
-
return None
|
133
|
-
|
134
|
-
def get_disk_health_status(self, usage_info: Dict) -> Tuple[str, str]:
|
135
|
-
"""评估磁盘健康状态"""
|
136
|
-
if not usage_info:
|
137
|
-
return "未知", "无法获取磁盘信息"
|
138
|
-
|
139
|
-
usage_percent = usage_info['usage_percent']
|
140
|
-
|
141
|
-
if usage_percent >= self.critical_threshold:
|
142
|
-
return "严重", "磁盘空间严重不足!请立即清理磁盘空间"
|
143
|
-
elif usage_percent >= self.warning_threshold:
|
144
|
-
return "警告", "磁盘空间不足,建议清理一些文件"
|
145
|
-
else:
|
146
|
-
return "良好", "磁盘空间充足"
|
147
|
-
|
148
|
-
def format_bytes(self, bytes_value: int) -> str:
|
149
|
-
"""格式化字节数为人类可读格式"""
|
150
|
-
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
|
151
|
-
if bytes_value < 1024.0:
|
152
|
-
return f"{bytes_value:.1f} {unit}"
|
153
|
-
bytes_value /= 1024.0
|
154
|
-
return f"{bytes_value:.1f} PB"
|
155
|
-
|
156
|
-
def get_directory_size(self, path: str) -> int:
|
157
|
-
"""高性能计算目录大小。
|
158
|
-
|
159
|
-
优先使用 macOS 的 du -sk(以 KiB 为单位,速度快,原生命令可处理边界情况),
|
160
|
-
若 du 调用失败则回退到基于 os.scandir 的非递归遍历实现(避免 os.walk 的函数调用开销)。
|
161
|
-
"""
|
162
|
-
# 优先尝试 du -sk(BSD du 在 macOS 可用)。
|
163
|
-
try:
|
164
|
-
# du 输出形如: "<kib>\t<path>\n"
|
165
|
-
result = subprocess.run([
|
166
|
-
'du', '-sk', path
|
167
|
-
], capture_output=True, text=True, check=True)
|
168
|
-
out = result.stdout.strip().split('\t', 1)[0].strip()
|
169
|
-
kib = int(out)
|
170
|
-
return kib * 1024
|
171
|
-
except Exception:
|
172
|
-
# du 不可用或失败时回退到 Python 实现
|
173
|
-
pass
|
174
|
-
|
175
|
-
total_size = 0
|
176
|
-
# 基于栈的迭代遍历,避免递归栈与 os.walk 的额外开销
|
177
|
-
stack = [path]
|
178
|
-
while stack:
|
179
|
-
current = stack.pop()
|
180
|
-
try:
|
181
|
-
with os.scandir(current) as it:
|
182
|
-
for entry in it:
|
183
|
-
# 跳过符号链接,避免循环与跨文件系统问题
|
184
|
-
try:
|
185
|
-
if entry.is_symlink():
|
186
|
-
continue
|
187
|
-
if entry.is_file(follow_symlinks=False):
|
188
|
-
try:
|
189
|
-
total_size += entry.stat(follow_symlinks=False).st_size
|
190
|
-
except (OSError, FileNotFoundError, PermissionError):
|
191
|
-
continue
|
192
|
-
elif entry.is_dir(follow_symlinks=False):
|
193
|
-
stack.append(entry.path)
|
194
|
-
except (OSError, FileNotFoundError, PermissionError):
|
195
|
-
continue
|
196
|
-
except (OSError, FileNotFoundError, PermissionError):
|
197
|
-
# 无法进入该目录则跳过
|
198
|
-
continue
|
199
|
-
return total_size
|
200
|
-
|
201
|
-
def analyze_largest_files(self, root_path: str = "/", top_n: int = 50,
|
202
|
-
min_size_bytes: int = 0) -> List[Tuple[str, int]]:
|
203
|
-
"""扫描并返回体积最大的文件列表"""
|
204
|
-
print("正在扫描大文件,这可能需要一些时间...")
|
205
|
-
heap: List[Tuple[int, str]] = [] # 最小堆 (size, path)
|
206
|
-
scanned = 0
|
207
|
-
try:
|
208
|
-
for dirpath, dirnames, filenames in os.walk(root_path):
|
209
|
-
# 进度提示:单行覆盖当前目录
|
210
|
-
dirpath_display = dirpath[-80:] # 截取最后50个字符
|
211
|
-
if dirpath_display == "":
|
212
|
-
dirpath_display = dirpath
|
213
|
-
sys.stdout.write(f"\r\033[K-> 正在读取: \033[36m{dirpath_display}\033[0m")
|
214
|
-
sys.stdout.flush()
|
215
|
-
for filename in filenames:
|
216
|
-
filepath = os.path.join(dirpath, filename)
|
217
|
-
try:
|
218
|
-
size = os.path.getsize(filepath)
|
219
|
-
except (OSError, FileNotFoundError, PermissionError):
|
220
|
-
continue
|
221
|
-
if size < min_size_bytes:
|
222
|
-
continue
|
223
|
-
if len(heap) < top_n:
|
224
|
-
heapq.heappush(heap, (size, filepath))
|
225
|
-
else:
|
226
|
-
if size > heap[0][0]:
|
227
|
-
heapq.heapreplace(heap, (size, filepath))
|
228
|
-
scanned += 1
|
229
|
-
if scanned % 500 == 0:
|
230
|
-
dirpath_display = dirpath[-80:] # 截取最后50个字符
|
231
|
-
if dirpath_display == "":
|
232
|
-
dirpath_display = dirpath
|
233
|
-
# 间隔性进度输出(单行覆盖)
|
234
|
-
sys.stdout.write(f"\r\033[K-> 正在读取: \033[36m{dirpath_display}\033[0m 已扫描文件数: \033[32m{scanned}\033[0m")
|
235
|
-
sys.stdout.flush()
|
236
|
-
except KeyboardInterrupt:
|
237
|
-
print("\n用户中断扫描,返回当前结果...")
|
238
|
-
except Exception as e:
|
239
|
-
print(f"扫描时出错: {e}")
|
240
|
-
finally:
|
241
|
-
sys.stdout.write("\n")
|
242
|
-
sys.stdout.flush()
|
243
|
-
# 转换为按体积降序列表
|
244
|
-
result = sorted([(p, s) for s, p in heap], key=lambda x: x[1], reverse=False)
|
245
|
-
result.sort(key=lambda x: x[1])
|
246
|
-
result = sorted([(p, s) for s, p in heap], key=lambda x: x[1])
|
247
|
-
# 正确:按 size 降序
|
248
|
-
result = sorted([(p, s) for s, p in heap], key=lambda x: x[1], reverse=True)
|
249
|
-
# 以上为了避免编辑器误合并,最终以最后一行排序为准
|
250
|
-
return result
|
251
|
-
|
252
|
-
def analyze_largest_directories(self, root_path: str = "/", max_depth: int = 2, top_n: int = 20,
|
253
|
-
index: IndexStore = None, use_index: bool = True,
|
254
|
-
reindex: bool = False, index_ttl_hours: int = 24,
|
255
|
-
prompt: bool = True) -> List[Tuple[str, int]]:
|
256
|
-
"""分析占用空间最大的目录(支持索引缓存)"""
|
257
|
-
# 索引命中
|
258
|
-
if use_index and index and not reindex and index.is_fresh(root_path, index_ttl_hours):
|
259
|
-
cached = index.get(root_path)
|
260
|
-
if cached and cached.get("entries"):
|
261
|
-
if prompt and sys.stdin.isatty():
|
262
|
-
try:
|
263
|
-
ans = input("检测到最近索引,是否使用缓存结果而不重新索引?[Y/n]: ").strip().lower()
|
264
|
-
if ans in ("", "y", "yes"):
|
265
|
-
return [(e["path"], int(e["size"])) for e in cached["entries"]][:top_n]
|
266
|
-
except EOFError:
|
267
|
-
pass
|
268
|
-
else:
|
269
|
-
return [(e["path"], int(e["size"])) for e in cached["entries"]][:top_n]
|
270
|
-
|
271
|
-
print("正在分析目录大小,这可能需要一些时间...")
|
272
|
-
|
273
|
-
# 忽略的目录列表, 这些目录时系统目录,不需要分析
|
274
|
-
ignore_dir_list = [
|
275
|
-
"/System", # 系统目录
|
276
|
-
"/Volumes", # 外部挂载卷
|
277
|
-
"/private", # 私有目录
|
278
|
-
]
|
279
|
-
|
280
|
-
|
281
|
-
directory_sizes = []
|
282
|
-
|
283
|
-
try:
|
284
|
-
# 获取根目录下的直接子目录
|
285
|
-
for item in os.listdir(root_path):
|
286
|
-
item_path = os.path.join(root_path, item)
|
287
|
-
|
288
|
-
# 跳过隐藏文件和系统文件
|
289
|
-
if item.startswith('.') and item not in ['.Trash', '.localized']:
|
290
|
-
continue
|
291
|
-
|
292
|
-
if item_path in ignore_dir_list:
|
293
|
-
continue
|
294
|
-
|
295
|
-
if os.path.isdir(item_path):
|
296
|
-
try:
|
297
|
-
# 进度提示:当前正在读取的目录(单行覆盖)
|
298
|
-
sys.stdout.write(f"\r\033[K-> 正在读取: \033[36m{item_path}\033[0m")
|
299
|
-
sys.stdout.flush()
|
300
|
-
size = self.get_directory_size(item_path)
|
301
|
-
directory_sizes.append((item_path, size))
|
302
|
-
#print(f"已分析: {item_path} ({self.format_bytes(size)})")
|
303
|
-
print(f" ({self.format_bytes(size)})\033[0m")
|
304
|
-
except (OSError, PermissionError):
|
305
|
-
print(f"跳过无法访问的目录: {item_path}")
|
306
|
-
continue
|
307
|
-
# 结束时换行,避免后续输出粘连在同一行
|
308
|
-
sys.stdout.write("\n")
|
309
|
-
sys.stdout.flush()
|
310
|
-
|
311
|
-
# 按大小排序
|
312
|
-
directory_sizes.sort(key=lambda x: x[1], reverse=True)
|
313
|
-
# 写入索引
|
314
|
-
if index:
|
315
|
-
try:
|
316
|
-
index.set(root_path, directory_sizes)
|
317
|
-
except Exception:
|
318
|
-
pass
|
319
|
-
return directory_sizes[:top_n]
|
320
|
-
|
321
|
-
except Exception as e:
|
322
|
-
print(f"分析目录时出错: {e}")
|
323
|
-
return []
|
324
|
-
|
325
|
-
def get_system_info(self) -> Dict:
|
326
|
-
"""获取系统信息(包括 CPU、内存、GPU、硬盘等硬件信息)"""
|
327
|
-
system_info = {}
|
328
|
-
|
329
|
-
try:
|
330
|
-
# 获取系统版本信息
|
331
|
-
result = subprocess.run(['sw_vers'], capture_output=True, text=True)
|
332
|
-
for line in result.stdout.split('\n'):
|
333
|
-
if ':' in line:
|
334
|
-
key, value = line.split(':', 1)
|
335
|
-
system_info[key.strip()] = value.strip()
|
336
|
-
except Exception:
|
337
|
-
system_info["ProductName"] = "macOS"
|
338
|
-
system_info["ProductVersion"] = "未知"
|
339
|
-
|
340
|
-
try:
|
341
|
-
# 获取 CPU 信息
|
342
|
-
cpu_result = subprocess.run(['sysctl', '-n', 'machdep.cpu.brand_string'],
|
343
|
-
capture_output=True, text=True)
|
344
|
-
if cpu_result.returncode == 0:
|
345
|
-
system_info["CPU"] = cpu_result.stdout.strip()
|
346
|
-
|
347
|
-
# 获取 CPU 核心数
|
348
|
-
cores_result = subprocess.run(['sysctl', '-n', 'hw.ncpu'],
|
349
|
-
capture_output=True, text=True)
|
350
|
-
if cores_result.returncode == 0:
|
351
|
-
system_info["CPU核心数"] = cores_result.stdout.strip()
|
352
|
-
|
353
|
-
except Exception:
|
354
|
-
system_info["CPU"] = "未知"
|
355
|
-
system_info["CPU核心数"] = "未知"
|
356
|
-
|
357
|
-
try:
|
358
|
-
# 获取内存信息
|
359
|
-
mem_result = subprocess.run(['sysctl', '-n', 'hw.memsize'],
|
360
|
-
capture_output=True, text=True)
|
361
|
-
if mem_result.returncode == 0:
|
362
|
-
mem_bytes = int(mem_result.stdout.strip())
|
363
|
-
system_info["内存"] = self.format_bytes(mem_bytes)
|
364
|
-
except Exception:
|
365
|
-
system_info["内存"] = "未知"
|
366
|
-
|
367
|
-
|
368
|
-
try:
|
369
|
-
# 获取启动时间
|
370
|
-
boot_result = subprocess.run(['uptime'], capture_output=True, text=True)
|
371
|
-
if boot_result.returncode == 0:
|
372
|
-
uptime_line = boot_result.stdout.strip()
|
373
|
-
system_info["运行时间"] = uptime_line
|
374
|
-
except Exception:
|
375
|
-
system_info["运行时间"] = "未知"
|
376
|
-
|
377
|
-
return system_info
|
378
|
-
|
379
|
-
|
380
|
-
class SpaceCli:
|
381
|
-
"""SpaceCli 主类"""
|
382
|
-
|
383
|
-
def __init__(self):
|
384
|
-
self.analyzer = SpaceAnalyzer()
|
385
|
-
self.index = IndexStore()
|
386
|
-
# 应用分析缓存存放于 ~/.cache/spacecli/apps.json
|
387
|
-
home = str(Path.home())
|
388
|
-
app_cache_dir = os.path.join(home, ".cache", "spacecli")
|
389
|
-
os.makedirs(app_cache_dir, exist_ok=True)
|
390
|
-
self.app_index = IndexStore(index_file=os.path.join(app_cache_dir, "apps.json"))
|
391
|
-
|
392
|
-
# —— 应用删除相关 ——
|
393
|
-
def _candidate_app_paths(self, app_name: str) -> List[str]:
|
394
|
-
"""根据应用名推导可能占用空间的相关目录/文件路径列表。"""
|
395
|
-
home = str(Path.home())
|
396
|
-
candidates: List[str] = []
|
397
|
-
possible_bases = [
|
398
|
-
("/Applications", f"{app_name}.app"),
|
399
|
-
(os.path.join(home, "Applications"), f"{app_name}.app"),
|
400
|
-
("/Library/Application Support", app_name),
|
401
|
-
(os.path.join(home, "Library", "Application Support"), app_name),
|
402
|
-
("/Library/Caches", app_name),
|
403
|
-
(os.path.join(home, "Library", "Caches"), app_name),
|
404
|
-
("/Library/Logs", app_name),
|
405
|
-
(os.path.join(home, "Library", "Logs"), app_name),
|
406
|
-
(os.path.join(home, "Library", "Containers"), app_name),
|
407
|
-
]
|
408
|
-
# 直接拼接命中
|
409
|
-
for base, tail in possible_bases:
|
410
|
-
path = os.path.join(base, tail)
|
411
|
-
if os.path.exists(path):
|
412
|
-
candidates.append(path)
|
413
|
-
# 模糊扫描:包含应用名的目录
|
414
|
-
scan_dirs = [
|
415
|
-
"/Applications",
|
416
|
-
os.path.join(home, "Applications"),
|
417
|
-
"/Library/Application Support",
|
418
|
-
os.path.join(home, "Library", "Application Support"),
|
419
|
-
"/Library/Caches",
|
420
|
-
os.path.join(home, "Library", "Caches"),
|
421
|
-
"/Library/Logs",
|
422
|
-
os.path.join(home, "Library", "Logs"),
|
423
|
-
os.path.join(home, "Library", "Containers"),
|
424
|
-
]
|
425
|
-
app_lower = app_name.lower()
|
426
|
-
for base in scan_dirs:
|
427
|
-
if not os.path.exists(base):
|
428
|
-
continue
|
429
|
-
try:
|
430
|
-
for item in os.listdir(base):
|
431
|
-
item_path = os.path.join(base, item)
|
432
|
-
# 只收集目录或 .app 包
|
433
|
-
if not os.path.isdir(item_path):
|
434
|
-
continue
|
435
|
-
name_lower = item.lower()
|
436
|
-
if app_lower in name_lower:
|
437
|
-
candidates.append(item_path)
|
438
|
-
except (PermissionError, OSError):
|
439
|
-
continue
|
440
|
-
# 去重并按路径长度降序(先删更深层,避免空目录残留)
|
441
|
-
uniq: List[str] = []
|
442
|
-
seen = set()
|
443
|
-
for p in sorted(set(candidates), key=lambda x: len(x), reverse=True):
|
444
|
-
if p not in seen:
|
445
|
-
uniq.append(p)
|
446
|
-
seen.add(p)
|
447
|
-
return uniq
|
448
|
-
|
449
|
-
def _delete_paths_and_sum(self, paths: List[str]) -> Tuple[int, List[Tuple[str, str]]]:
|
450
|
-
"""删除给定路径列表,返回释放的总字节数与失败列表(路径, 原因)。"""
|
451
|
-
total_freed = 0
|
452
|
-
failures: List[Tuple[str, str]] = []
|
453
|
-
|
454
|
-
def _try_fix_permissions(path: str) -> None:
|
455
|
-
"""尝试修复权限与不可变标记以便删除。"""
|
456
|
-
try:
|
457
|
-
# 去除不可变标记(普通用户能去除的场景)
|
458
|
-
subprocess.run(["chflags", "-R", "nouchg", path], capture_output=True)
|
459
|
-
except Exception:
|
460
|
-
pass
|
461
|
-
try:
|
462
|
-
os.chmod(path, 0o777)
|
463
|
-
except Exception:
|
464
|
-
pass
|
465
|
-
|
466
|
-
def _onerror(func, path, exc_info):
|
467
|
-
# 当 rmtree 无法删除时,尝试修复权限并重试一次
|
468
|
-
_try_fix_permissions(path)
|
469
|
-
try:
|
470
|
-
func(path)
|
471
|
-
except Exception:
|
472
|
-
# 让上层捕获
|
473
|
-
raise
|
474
|
-
for p in paths:
|
475
|
-
try:
|
476
|
-
size_before = 0
|
477
|
-
try:
|
478
|
-
if os.path.isdir(p):
|
479
|
-
size_before = self.analyzer.get_directory_size(p)
|
480
|
-
elif os.path.isfile(p):
|
481
|
-
size_before = os.path.getsize(p)
|
482
|
-
except Exception:
|
483
|
-
size_before = 0
|
484
|
-
if os.path.isdir(p) and not os.path.islink(p):
|
485
|
-
try:
|
486
|
-
shutil.rmtree(p, ignore_errors=False, onerror=_onerror)
|
487
|
-
except Exception:
|
488
|
-
# 目录删除失败,降级为逐项尝试删除(尽量清理可删部分)
|
489
|
-
for dirpath, dirnames, filenames in os.walk(p, topdown=False):
|
490
|
-
for name in filenames:
|
491
|
-
fpath = os.path.join(dirpath, name)
|
492
|
-
try:
|
493
|
-
_try_fix_permissions(fpath)
|
494
|
-
os.remove(fpath)
|
495
|
-
except Exception:
|
496
|
-
continue
|
497
|
-
for name in dirnames:
|
498
|
-
dpath = os.path.join(dirpath, name)
|
499
|
-
try:
|
500
|
-
_try_fix_permissions(dpath)
|
501
|
-
os.rmdir(dpath)
|
502
|
-
except Exception:
|
503
|
-
continue
|
504
|
-
# 最后尝试删除顶层目录
|
505
|
-
_try_fix_permissions(p)
|
506
|
-
os.rmdir(p)
|
507
|
-
else:
|
508
|
-
os.remove(p)
|
509
|
-
total_freed += size_before
|
510
|
-
except Exception as e:
|
511
|
-
failures.append((p, str(e)))
|
512
|
-
return total_freed, failures
|
513
|
-
|
514
|
-
def _offer_app_delete(self, apps: List[Tuple[str, int]]) -> None:
|
515
|
-
"""在已打印的应用列表后,提供按序号一键删除功能。"""
|
516
|
-
if not sys.stdin.isatty() or getattr(self.args, 'no_prompt', False):
|
517
|
-
return
|
518
|
-
try:
|
519
|
-
ans = input("是否要一键删除某个应用?输入序号或回车跳过: ").strip()
|
520
|
-
except EOFError:
|
521
|
-
ans = ""
|
522
|
-
if not ans:
|
523
|
-
return
|
524
|
-
try:
|
525
|
-
idx = int(ans)
|
526
|
-
except ValueError:
|
527
|
-
print("❌ 无效的输入(应为数字序号)")
|
528
|
-
return
|
529
|
-
if idx < 1 or idx > len(apps):
|
530
|
-
print("❌ 序号超出范围")
|
531
|
-
return
|
532
|
-
app_name, app_size = apps[idx - 1]
|
533
|
-
size_str = self.analyzer.format_bytes(app_size)
|
534
|
-
try:
|
535
|
-
confirm = input(f"确认删除应用及相关缓存: {app_name} (约 {size_str})?[y/N]: ").strip().lower()
|
536
|
-
except EOFError:
|
537
|
-
confirm = ""
|
538
|
-
if confirm not in ("y", "yes"):
|
539
|
-
print("已取消删除")
|
540
|
-
return
|
541
|
-
related_paths = self._candidate_app_paths(app_name)
|
542
|
-
if not related_paths:
|
543
|
-
print("未找到可删除的相关目录/文件")
|
544
|
-
return
|
545
|
-
print("将尝试删除以下路径:")
|
546
|
-
for p in related_paths:
|
547
|
-
print(f" - {p}")
|
548
|
-
try:
|
549
|
-
confirm2 = input("再次确认删除以上路径?[y/N]: ").strip().lower()
|
550
|
-
except EOFError:
|
551
|
-
confirm2 = ""
|
552
|
-
if confirm2 not in ("y", "yes"):
|
553
|
-
print("已取消删除")
|
554
|
-
return
|
555
|
-
freed, failures = self._delete_paths_and_sum(related_paths)
|
556
|
-
print(f"✅ 删除完成,预计释放空间: {self.analyzer.format_bytes(freed)}")
|
557
|
-
if failures:
|
558
|
-
print("以下路径删除失败,可能需要手动或管理员权限:")
|
559
|
-
for p, reason in failures:
|
560
|
-
print(f" - {p} -> {reason}")
|
561
|
-
# 常见提示:Operation not permitted(SIP/容器元数据等)
|
562
|
-
if any("Operation not permitted" in r for _, r in failures):
|
563
|
-
print("提示:部分系统受保护或容器元数据文件无法删除。可尝试:")
|
564
|
-
print(" - 先退出相关应用(如 Docker)再重试")
|
565
|
-
print(" - 给予当前终端“完全磁盘访问权限”(系统设置 → 隐私与安全性)")
|
566
|
-
print(" - 仅删除用户目录下缓存,保留系统级容器元数据")
|
567
|
-
|
568
|
-
# 通用渲染:目录与应用(减少重复)
|
569
|
-
def _render_dirs(self, entries: List[Tuple[str, int]], total_bytes: int) -> None:
|
570
|
-
for i, (dir_path, size) in enumerate(entries, 1):
|
571
|
-
size_str = self.analyzer.format_bytes(size)
|
572
|
-
percentage = (size / total_bytes) * 100 if total_bytes else 0
|
573
|
-
# 1G 以上红色,否则绿色
|
574
|
-
color = "\033[31m" if size >= 1024**3 else "\033[32m"
|
575
|
-
print(f"{i:2d}. \033[36m{dir_path}\033[0m -- 大小: {color}{size_str}\033[0m (\033[33m{percentage:.2f}%\033[0m)")
|
576
|
-
|
577
|
-
def _render_apps(self, entries: List[Tuple[str, int]], disk_total: int) -> None:
|
578
|
-
for i, (app, size) in enumerate(entries, 1):
|
579
|
-
size_str = self.analyzer.format_bytes(size)
|
580
|
-
pct = (size / disk_total) * 100 if disk_total else 0
|
581
|
-
suggestion = "建议卸载或清理缓存" if size >= 5 * 1024**3 else "可保留,定期清理缓存"
|
582
|
-
# 3G 以上红色,否则绿色
|
583
|
-
color = "\033[31m" if size >= 3 * 1024**3 else "\033[32m"
|
584
|
-
print(f"{i:2d}. \033[36m{app}\033[0m -- 占用: {color}{size_str}\033[0m ({pct:.2f}%) — {suggestion}")
|
585
|
-
|
586
|
-
def analyze_app_directories(self, top_n: int = 20,
|
587
|
-
index: IndexStore = None,
|
588
|
-
use_index: bool = True,
|
589
|
-
reindex: bool = False,
|
590
|
-
index_ttl_hours: int = 24,
|
591
|
-
prompt: bool = True) -> List[Tuple[str, int]]:
|
592
|
-
"""分析应用安装与数据目录占用,按应用归并估算大小(支持缓存)"""
|
593
|
-
|
594
|
-
# 命中命名缓存
|
595
|
-
cache_name = "apps_aggregate"
|
596
|
-
if use_index and index and not reindex and index.is_fresh_named(cache_name, index_ttl_hours):
|
597
|
-
cached = index.get_named(cache_name)
|
598
|
-
if cached and cached.get("entries"):
|
599
|
-
if prompt and sys.stdin.isatty():
|
600
|
-
try:
|
601
|
-
ans = input("检测到最近应用分析索引,是否使用缓存结果?[Y/n]: ").strip().lower()
|
602
|
-
if ans in ("", "y", "yes"):
|
603
|
-
return [(e["name"], int(e["size"])) for e in cached["entries"]][:top_n]
|
604
|
-
except EOFError:
|
605
|
-
pass
|
606
|
-
else:
|
607
|
-
return [(e["name"], int(e["size"])) for e in cached["entries"]][:top_n]
|
608
|
-
# 关注目录
|
609
|
-
home = str(Path.home())
|
610
|
-
target_dirs = [
|
611
|
-
"/Applications",
|
612
|
-
os.path.join(home, "Applications"),
|
613
|
-
"/Library/Application Support",
|
614
|
-
"/Library/Caches",
|
615
|
-
"/Library/Logs",
|
616
|
-
os.path.join(home, "Library", "Application Support"),
|
617
|
-
os.path.join(home, "Library", "Caches"),
|
618
|
-
os.path.join(home, "Library", "Logs"),
|
619
|
-
os.path.join(home, "Library", "Containers"),
|
620
|
-
]
|
621
|
-
|
622
|
-
def app_key_from_path(p: str) -> str:
|
623
|
-
# 优先用.app 名称,其次用顶级目录名
|
624
|
-
parts = Path(p).parts
|
625
|
-
for i in range(len(parts)-1, -1, -1):
|
626
|
-
if parts[i].endswith('.app'):
|
627
|
-
return parts[i].replace('.app', '')
|
628
|
-
# 否则返回倒数第二级或最后一级作为应用键
|
629
|
-
return parts[-1] if parts else p
|
630
|
-
|
631
|
-
app_size_map: Dict[str, int] = {}
|
632
|
-
scanned_dirs: List[str] = []
|
633
|
-
|
634
|
-
for base in target_dirs:
|
635
|
-
if not os.path.exists(base):
|
636
|
-
continue
|
637
|
-
try:
|
638
|
-
for item in os.listdir(base):
|
639
|
-
item_path = os.path.join(base, item)
|
640
|
-
if not os.path.isdir(item_path):
|
641
|
-
continue
|
642
|
-
key = app_key_from_path(item_path)
|
643
|
-
# 进度提示:当前应用相关目录(单行覆盖)
|
644
|
-
item_path = item_path[:100]
|
645
|
-
sys.stdout.write(f"\r\033[K-> 正在读取: \033[36m{item_path}\033[0m")
|
646
|
-
sys.stdout.flush()
|
647
|
-
size = self.analyzer.get_directory_size(item_path)
|
648
|
-
scanned_dirs.append(item_path)
|
649
|
-
app_size_map[key] = app_size_map.get(key, 0) + size
|
650
|
-
except (PermissionError, OSError):
|
651
|
-
continue
|
652
|
-
# 结束时换行
|
653
|
-
sys.stdout.write("\n")
|
654
|
-
sys.stdout.flush()
|
655
|
-
|
656
|
-
# 转为排序列表
|
657
|
-
result = sorted(app_size_map.items(), key=lambda x: x[1], reverse=True)
|
658
|
-
# 写入命名缓存
|
659
|
-
if index:
|
660
|
-
try:
|
661
|
-
index.set_named(cache_name, result)
|
662
|
-
except Exception:
|
663
|
-
pass
|
664
|
-
return result[:top_n]
|
665
|
-
|
666
|
-
def print_disk_health(self, path: str = "/"):
|
667
|
-
"""打印磁盘健康状态"""
|
668
|
-
print("=" * 60)
|
669
|
-
print("🔍 磁盘空间健康度分析")
|
670
|
-
print("=" * 60)
|
671
|
-
|
672
|
-
usage_info = self.analyzer.get_disk_usage(path)
|
673
|
-
if not usage_info:
|
674
|
-
print("❌ 无法获取磁盘使用情况")
|
675
|
-
return
|
676
|
-
|
677
|
-
status, message = self.analyzer.get_disk_health_status(usage_info)
|
678
|
-
|
679
|
-
# 状态图标
|
680
|
-
status_icon = {
|
681
|
-
"良好": "✅",
|
682
|
-
"警告": "⚠️",
|
683
|
-
"严重": "🚨"
|
684
|
-
}.get(status, "❓")
|
685
|
-
|
686
|
-
print(f"磁盘路径: \033[36m{usage_info['path']}\033[0m")
|
687
|
-
print(f"总容量: \033[36m{self.analyzer.format_bytes(usage_info['total'])}\033[0m")
|
688
|
-
print(f"已使用: \033[36m{self.analyzer.format_bytes(usage_info['used'])}\033[0m")
|
689
|
-
print(f"可用空间: \033[36m{self.analyzer.format_bytes(usage_info['free'])}\033[0m")
|
690
|
-
print(f"使用率: \033[36m{usage_info['usage_percent']:.1f}%\033[0m")
|
691
|
-
print(f"健康状态: {status_icon} \033[36m{status}\033[0m")
|
692
|
-
print(f"建议: \033[36m{message}\033[0m")
|
693
|
-
print()
|
694
|
-
|
695
|
-
def print_largest_directories(self, path: str = "/Library", top_n: int = 20):
|
696
|
-
"""打印占用空间最大的目录"""
|
697
|
-
print("=" * 60)
|
698
|
-
print("📊 占用空间最大的目录")
|
699
|
-
print("=" * 60)
|
700
|
-
|
701
|
-
# 若有缓存:直接显示缓存,然后再询问是否重新分析
|
702
|
-
if self.args.use_index:
|
703
|
-
cached = self.index.get(path)
|
704
|
-
if cached and cached.get("entries"):
|
705
|
-
cached_entries = [(e["path"], int(e["size"])) for e in cached["entries"]][:top_n]
|
706
|
-
total_info = self.analyzer.get_disk_usage(path)
|
707
|
-
total_bytes = total_info['total'] if total_info else 1
|
708
|
-
print(f"(来自索引) 显示前 {min(len(cached_entries), top_n)} 个最大的目录:\n")
|
709
|
-
self._render_dirs(cached_entries, total_bytes)
|
710
|
-
if sys.stdin.isatty() and not self.args.no_prompt:
|
711
|
-
try:
|
712
|
-
ans = input("是否重新分析以刷新索引?[y/N]: ").strip().lower()
|
713
|
-
except EOFError:
|
714
|
-
ans = ""
|
715
|
-
if ans not in ("y", "yes"):
|
716
|
-
# 提供下探分析选项
|
717
|
-
self._offer_drill_down_analysis(cached_entries, path)
|
718
|
-
return
|
719
|
-
else:
|
720
|
-
return
|
721
|
-
|
722
|
-
directories = self.analyzer.analyze_largest_directories(
|
723
|
-
path,
|
724
|
-
top_n=top_n,
|
725
|
-
index=self.index,
|
726
|
-
use_index=self.args.use_index,
|
727
|
-
reindex=True, # 走到这里表示要刷新
|
728
|
-
index_ttl_hours=self.args.index_ttl,
|
729
|
-
prompt=False,
|
730
|
-
)
|
731
|
-
if not directories:
|
732
|
-
print("❌ 无法分析目录大小")
|
733
|
-
return
|
734
|
-
total_info = self.analyzer.get_disk_usage(path)
|
735
|
-
total_bytes = total_info['total'] if total_info else 1
|
736
|
-
print("\n已重新分析,最新结果:\n")
|
737
|
-
self._render_dirs(directories, total_bytes)
|
738
|
-
|
739
|
-
# 提供下探分析选项
|
740
|
-
self._offer_drill_down_analysis(directories, path)
|
741
|
-
|
742
|
-
def _offer_drill_down_analysis(self, directories: List[Tuple[str, int]], current_path: str) -> None:
|
743
|
-
"""提供交互式下探分析选项"""
|
744
|
-
if not sys.stdin.isatty() or getattr(self.args, 'no_prompt', False):
|
745
|
-
return
|
746
|
-
|
747
|
-
print("\n" + "=" * 60)
|
748
|
-
print("🔍 下探分析选项")
|
749
|
-
print("=" * 60)
|
750
|
-
print("选择序号进行深度分析,选择0返回上一级,直接回车退出:")
|
751
|
-
|
752
|
-
try:
|
753
|
-
choice = input("请输入选择 [回车=退出]: ").strip()
|
754
|
-
except EOFError:
|
755
|
-
return
|
756
|
-
|
757
|
-
if not choice:
|
758
|
-
return
|
759
|
-
|
760
|
-
try:
|
761
|
-
idx = int(choice)
|
762
|
-
except ValueError:
|
763
|
-
print("❌ 无效的输入(应为数字序号)")
|
764
|
-
return
|
765
|
-
|
766
|
-
if idx == 0:
|
767
|
-
# 返回上一级
|
768
|
-
parent_path = os.path.dirname(current_path.rstrip('/'))
|
769
|
-
if parent_path != current_path and parent_path != '/':
|
770
|
-
print(f"\n🔄 返回上一级: {parent_path}")
|
771
|
-
self.print_largest_directories(parent_path, self.args.top_n)
|
772
|
-
else:
|
773
|
-
print("❌ 已在根目录,无法返回上一级")
|
774
|
-
return
|
775
|
-
|
776
|
-
if idx < 1 or idx > len(directories):
|
777
|
-
print("❌ 序号超出范围")
|
778
|
-
return
|
779
|
-
|
780
|
-
selected_path, selected_size = directories[idx - 1]
|
781
|
-
size_str = self.analyzer.format_bytes(selected_size)
|
782
|
-
|
783
|
-
print(f"\n🔍 正在分析: {selected_path} ({size_str})")
|
784
|
-
print("=" * 60)
|
785
|
-
|
786
|
-
# 递归调用下探分析
|
787
|
-
self.print_largest_directories(selected_path, self.args.top_n)
|
788
|
-
|
789
|
-
def print_app_analysis(self, top_n: int = 20):
|
790
|
-
"""打印应用目录占用分析,并给出卸载建议"""
|
791
|
-
print("=" * 60)
|
792
|
-
print("🧩 应用目录空间分析与卸载建议")
|
793
|
-
print("=" * 60)
|
794
|
-
|
795
|
-
# 先显示缓存,再决定是否刷新
|
796
|
-
if self.args.use_index:
|
797
|
-
cached = self.app_index.get_named("apps_aggregate")
|
798
|
-
if cached and cached.get("entries"):
|
799
|
-
cached_entries = [(e["name"], int(e["size"])) for e in cached["entries"]][:top_n]
|
800
|
-
total = self.analyzer.get_disk_usage("/")
|
801
|
-
disk_total = total['total'] if total else 1
|
802
|
-
print(f"(来自索引) 显示前 {min(len(cached_entries), top_n)} 个空间占用最高的应用:\n")
|
803
|
-
self._render_apps(cached_entries, disk_total)
|
804
|
-
# 提供一键删除
|
805
|
-
self._offer_app_delete(cached_entries)
|
806
|
-
if sys.stdin.isatty() and not self.args.no_prompt:
|
807
|
-
try:
|
808
|
-
ans = input("是否重新分析应用以刷新索引?[y/N]: ").strip().lower()
|
809
|
-
except EOFError:
|
810
|
-
ans = ""
|
811
|
-
if ans not in ("y", "yes"):
|
812
|
-
return
|
813
|
-
else:
|
814
|
-
return
|
815
|
-
|
816
|
-
apps = self.analyze_app_directories(
|
817
|
-
top_n=top_n,
|
818
|
-
index=self.app_index,
|
819
|
-
use_index=self.args.use_index,
|
820
|
-
reindex=True,
|
821
|
-
index_ttl_hours=self.args.index_ttl,
|
822
|
-
prompt=False,
|
823
|
-
)
|
824
|
-
if not apps:
|
825
|
-
print("❌ 未发现可分析的应用目录")
|
826
|
-
return
|
827
|
-
total = self.analyzer.get_disk_usage("/")
|
828
|
-
disk_total = total['total'] if total else 1
|
829
|
-
print("\n已重新分析,最新应用占用结果:\n")
|
830
|
-
self._render_apps(apps, disk_total)
|
831
|
-
# 提供一键删除
|
832
|
-
self._offer_app_delete(apps)
|
833
|
-
|
834
|
-
def print_home_deep_analysis(self, top_n: int = 20):
|
835
|
-
"""对用户目录的 Library / Downloads / Documents 分别下探分析"""
|
836
|
-
home = str(Path.home())
|
837
|
-
targets = [
|
838
|
-
("Library", os.path.join(home, "Library")),
|
839
|
-
("Downloads", os.path.join(home, "Downloads")),
|
840
|
-
("Documents", os.path.join(home, "Documents")),
|
841
|
-
]
|
842
|
-
|
843
|
-
for label, target in targets:
|
844
|
-
if not os.path.exists(target):
|
845
|
-
continue
|
846
|
-
print("=" * 60)
|
847
|
-
print(f"🏠 用户目录下探 - {label}")
|
848
|
-
print("=" * 60)
|
849
|
-
directories = self.analyzer.analyze_largest_directories(
|
850
|
-
target,
|
851
|
-
top_n=top_n,
|
852
|
-
index=self.index,
|
853
|
-
use_index=self.args.use_index,
|
854
|
-
reindex=self.args.reindex,
|
855
|
-
index_ttl_hours=self.args.index_ttl,
|
856
|
-
prompt=not self.args.no_prompt,
|
857
|
-
)
|
858
|
-
if not directories:
|
859
|
-
print("❌ 无法分析目录大小")
|
860
|
-
continue
|
861
|
-
total_info = self.analyzer.get_disk_usage("/")
|
862
|
-
total_bytes = total_info['total'] if total_info else 1
|
863
|
-
print(f"显示前 {min(len(directories), top_n)} 个最大的目录:\n")
|
864
|
-
for i, (dir_path, size) in enumerate(directories, 1):
|
865
|
-
size_str = self.analyzer.format_bytes(size)
|
866
|
-
percentage = (size / total_bytes) * 100
|
867
|
-
color = "\033[31m" if size >= 1024**3 else "\033[32m"
|
868
|
-
print(f"{i:2d}. \033[36m{dir_path}\033[0m -- 大小: {color}{size_str}\033[0m (\033[33m{percentage:.2f}%\033[0m)")
|
869
|
-
#print()
|
870
|
-
|
871
|
-
def print_big_files(self, path: str, top_n: int = 50, min_size_bytes: int = 0):
|
872
|
-
"""打印大文件列表"""
|
873
|
-
print("=" * 60)
|
874
|
-
print("🗄️ 大文件分析")
|
875
|
-
print("=" * 60)
|
876
|
-
files = self.analyzer.analyze_largest_files(path, top_n=top_n, min_size_bytes=min_size_bytes)
|
877
|
-
if not files:
|
878
|
-
print("❌ 未找到符合条件的大文件")
|
879
|
-
return
|
880
|
-
total = self.analyzer.get_disk_usage("/")
|
881
|
-
disk_total = total['total'] if total else 1
|
882
|
-
for i, (file_path, size) in enumerate(files, 1):
|
883
|
-
size_str = self.analyzer.format_bytes(size)
|
884
|
-
pct = (size / disk_total) * 100
|
885
|
-
color = "\033[31m" if size >= 5 * 1024**3 else ("\033[33m" if size >= 1024**3 else "\033[32m")
|
886
|
-
print(f"{i:2d}. \033[36m{file_path}\033[0m -- 大小: {color}{size_str}\033[0m (\033[33m{pct:.2f}%\033[0m)")
|
887
|
-
print()
|
888
|
-
|
889
|
-
def print_system_info(self):
|
890
|
-
"""打印系统信息"""
|
891
|
-
print("=" * 60)
|
892
|
-
print("💻 系统信息")
|
893
|
-
print("=" * 60)
|
894
|
-
|
895
|
-
system_info = self.analyzer.get_system_info()
|
896
|
-
|
897
|
-
for key, value in system_info.items():
|
898
|
-
print(f"{key}: \033[36m{value}\033[0m")
|
899
|
-
print()
|
900
|
-
|
901
|
-
def export_report(self, output_file: str, path: str = "/"):
|
902
|
-
"""导出分析报告到JSON文件"""
|
903
|
-
print(f"正在生成报告并保存到: {output_file}")
|
904
|
-
|
905
|
-
usage_info = self.analyzer.get_disk_usage(path)
|
906
|
-
status, message = self.analyzer.get_disk_health_status(usage_info)
|
907
|
-
directories = self.analyzer.analyze_largest_directories(path)
|
908
|
-
system_info = self.analyzer.get_system_info()
|
909
|
-
# 可选:大文件分析
|
910
|
-
largest_files = []
|
911
|
-
try:
|
912
|
-
if getattr(self, 'args', None) and getattr(self.args, 'big_files', False):
|
913
|
-
files = self.analyzer.analyze_largest_files(
|
914
|
-
path,
|
915
|
-
top_n=getattr(self.args, 'big_files_top', 20),
|
916
|
-
min_size_bytes=getattr(self.args, 'big_files_min_bytes', 0),
|
917
|
-
)
|
918
|
-
largest_files = [
|
919
|
-
{
|
920
|
-
"path": file_path,
|
921
|
-
"size_bytes": size,
|
922
|
-
"size_formatted": self.analyzer.format_bytes(size),
|
923
|
-
}
|
924
|
-
for file_path, size in files
|
925
|
-
]
|
926
|
-
except Exception:
|
927
|
-
largest_files = []
|
928
|
-
|
929
|
-
report = {
|
930
|
-
"timestamp": subprocess.run(['date'], capture_output=True, text=True).stdout.strip(),
|
931
|
-
"system_info": system_info,
|
932
|
-
"disk_usage": usage_info,
|
933
|
-
"health_status": {
|
934
|
-
"status": status,
|
935
|
-
"message": message
|
936
|
-
},
|
937
|
-
"largest_directories": [
|
938
|
-
{
|
939
|
-
"path": dir_path,
|
940
|
-
"size_bytes": size,
|
941
|
-
"size_formatted": self.analyzer.format_bytes(size)
|
942
|
-
}
|
943
|
-
for dir_path, size in directories
|
944
|
-
],
|
945
|
-
"largest_files": largest_files
|
946
|
-
}
|
947
|
-
|
948
|
-
try:
|
949
|
-
with open(output_file, 'w', encoding='utf-8') as f:
|
950
|
-
json.dump(report, f, ensure_ascii=False, indent=2)
|
951
|
-
print(f"✅ 报告已保存到: {output_file}")
|
952
|
-
except Exception as e:
|
953
|
-
print(f"❌ 保存报告失败: {e}")
|
16
|
+
from space_cli import SpaceAnalyzer, SpaceCli, IndexStore
|
954
17
|
|
955
18
|
|
956
19
|
def main():
|
@@ -1066,7 +129,7 @@ def main():
|
|
1066
129
|
parser.add_argument(
|
1067
130
|
'--version',
|
1068
131
|
action='version',
|
1069
|
-
version='SpaceCli 1.
|
132
|
+
version='SpaceCli 1.5.0'
|
1070
133
|
)
|
1071
134
|
|
1072
135
|
args = parser.parse_args()
|
@@ -1088,116 +151,142 @@ def main():
|
|
1088
151
|
return 0
|
1089
152
|
args.big_files_min_bytes = parse_size(getattr(args, 'big_files_min', '0'))
|
1090
153
|
|
1091
|
-
#
|
1092
|
-
|
1093
|
-
|
1094
|
-
|
1095
|
-
|
1096
|
-
|
1097
|
-
|
1098
|
-
|
1099
|
-
|
1100
|
-
|
1101
|
-
|
1102
|
-
|
1103
|
-
|
1104
|
-
|
154
|
+
# 将主要执行流程提取为函数,便于交互模式复用
|
155
|
+
def run_once(run_args, interactive: bool = False):
|
156
|
+
# --home 优先设置路径
|
157
|
+
if getattr(run_args, 'home', False):
|
158
|
+
run_args.path = str(Path.home())
|
159
|
+
|
160
|
+
# 检查路径是否存在
|
161
|
+
if not os.path.exists(run_args.path):
|
162
|
+
print(f"❌ 错误: 路径 '{run_args.path}' 不存在")
|
163
|
+
if interactive:
|
164
|
+
return
|
165
|
+
sys.exit(1)
|
166
|
+
|
167
|
+
# 创建SpaceCli实例
|
168
|
+
space_cli = SpaceCli()
|
169
|
+
# 让 SpaceCli 实例可访问参数(用于索引与提示控制)
|
170
|
+
space_cli.args = run_args
|
171
|
+
|
1105
172
|
try:
|
1106
|
-
|
1107
|
-
|
1108
|
-
|
173
|
+
# 显示系统信息
|
174
|
+
space_cli.print_system_info()
|
175
|
+
|
176
|
+
# 显示磁盘健康状态
|
177
|
+
if run_args.health_only:
|
178
|
+
space_cli.print_disk_health(run_args.path)
|
179
|
+
|
180
|
+
# 显示目录分析
|
181
|
+
if run_args.directories_only or run_args.path !='/':
|
182
|
+
space_cli.print_largest_directories(run_args.path, run_args.top_n)
|
183
|
+
# 若分析路径为当前用户目录,做深度分析
|
184
|
+
if os.path.abspath(run_args.path) == os.path.abspath(str(Path.home())):
|
185
|
+
space_cli.print_home_deep_analysis(run_args.top_n)
|
186
|
+
|
187
|
+
# 应用目录分析
|
188
|
+
if run_args.apps:
|
189
|
+
space_cli.print_app_analysis(run_args.top_n)
|
190
|
+
|
191
|
+
# 大文件分析
|
192
|
+
if run_args.big_files:
|
193
|
+
space_cli.print_big_files(run_args.path, top_n=run_args.big_files_top, min_size_bytes=run_args.big_files_min_bytes)
|
194
|
+
|
195
|
+
# 内存释放优化
|
196
|
+
if getattr(run_args, 'memory_cleanup', False):
|
197
|
+
space_cli.print_memory_cleanup()
|
198
|
+
|
199
|
+
# 导出报告
|
200
|
+
if run_args.export:
|
201
|
+
space_cli.export_report(run_args.export, run_args.path)
|
202
|
+
|
203
|
+
print("=" * 60)
|
204
|
+
print("✅ 分析完成!")
|
205
|
+
print("=" * 60)
|
206
|
+
|
207
|
+
except KeyboardInterrupt:
|
208
|
+
print("\n\n❌ 用户中断操作")
|
209
|
+
if interactive:
|
210
|
+
return
|
211
|
+
sys.exit(1)
|
212
|
+
except Exception as e:
|
213
|
+
print(f"\n❌ 发生错误: {e}")
|
214
|
+
if interactive:
|
215
|
+
return
|
216
|
+
sys.exit(1)
|
217
|
+
|
218
|
+
# 交互式菜单:当未传入任何参数时触发(默认执行全部),执行完后返回菜单
|
219
|
+
if len(sys.argv) == 1:
|
220
|
+
while True:
|
221
|
+
print("=" * 60)
|
222
|
+
print("🧭 SpaceCli 菜单(直接回车 = 执行全部项目)")
|
223
|
+
print("=" * 60)
|
224
|
+
home_path = str(Path.home())
|
225
|
+
# 动态获取磁盘与内存占用率
|
226
|
+
try:
|
227
|
+
analyzer_for_menu = SpaceAnalyzer()
|
228
|
+
disk_info = analyzer_for_menu.get_disk_usage('/')
|
229
|
+
disk_usage_display = f"{disk_info['usage_percent']:.1f}%" if disk_info else "未知"
|
230
|
+
sysinfo = analyzer_for_menu.get_system_info()
|
231
|
+
mem_usage_display = sysinfo.get("内存使用率", "未知")
|
232
|
+
except Exception:
|
233
|
+
disk_usage_display = "未知"
|
234
|
+
mem_usage_display = "未知"
|
235
|
+
|
236
|
+
print("1) \033[36m执行主要项目(系统信息 + 健康 + 应用)\033[0m")
|
237
|
+
print(f"2) \033[36m当前用户目录分析(路径: {home_path})\033[0m")
|
238
|
+
print("3) \033[36m仅显示系统信息\033[0m")
|
239
|
+
print(f"4) \033[36m仅显示磁盘健康状态\033[0m — 当前磁盘占用: \033[33m{disk_usage_display}\033[0m")
|
240
|
+
print("5) \033[36m交互式目录空间分析\033[0m")
|
241
|
+
print("6) \033[36m仅分析程序应用目录空间\033[0m")
|
242
|
+
print("7) \033[36m仅进行大文件分析(比较耗时,可随时终止)\033[0m")
|
243
|
+
print(f"8) \033[36m内存释放优化\033[0m — 当前内存使用率: \033[33m{mem_usage_display}\033[0m")
|
244
|
+
print("0) \033[36m退出\033[0m")
|
245
|
+
try:
|
246
|
+
choice = input("请选择 [回车=1]: ").strip()
|
247
|
+
except EOFError:
|
248
|
+
choice = ""
|
1109
249
|
|
1110
|
-
|
1111
|
-
sys.exit(0)
|
1112
|
-
elif choice == "2": # 仅显示当前用户目录分析
|
1113
|
-
args.path = home_path
|
1114
|
-
args.apps = False
|
1115
|
-
args.health_only = False
|
1116
|
-
args.directories_only = False
|
1117
|
-
elif choice == "3": # 仅显示系统信息
|
1118
|
-
args.health_only = False
|
1119
|
-
args.directories_only = False
|
1120
|
-
args.apps = False
|
1121
|
-
args.big_files = False
|
1122
|
-
elif choice == "4": # 仅显示磁盘健康状态
|
1123
|
-
args.health_only = True
|
1124
|
-
args.directories_only = False
|
1125
|
-
args.apps = False
|
1126
|
-
args.big_files = False
|
1127
|
-
elif choice == "5": # 仅显示最大目录列表
|
1128
|
-
args.health_only = False
|
1129
|
-
args.directories_only = True
|
1130
|
-
args.apps = False
|
1131
|
-
args.big_files = False
|
1132
|
-
elif choice == "6": # 仅显示应用目录分析与建议
|
1133
|
-
args.health_only = False
|
1134
|
-
args.directories_only = False
|
1135
|
-
args.apps = True
|
1136
|
-
args.big_files = False
|
1137
|
-
elif choice == "7": # 仅显示大文件分析
|
250
|
+
# 重置
|
1138
251
|
args.health_only = False
|
1139
252
|
args.directories_only = False
|
1140
253
|
args.apps = False
|
1141
|
-
args.big_files = True
|
1142
|
-
else: # 默认执行全部(用户不选择,或者选择1)
|
1143
|
-
args.health_only = True
|
1144
|
-
args.directories_only = False
|
1145
254
|
args.big_files = False
|
1146
|
-
args.
|
1147
|
-
|
1148
|
-
|
1149
|
-
|
1150
|
-
|
1151
|
-
|
1152
|
-
|
1153
|
-
|
1154
|
-
|
1155
|
-
|
1156
|
-
|
1157
|
-
|
1158
|
-
|
1159
|
-
|
1160
|
-
|
1161
|
-
|
1162
|
-
|
1163
|
-
|
1164
|
-
|
1165
|
-
|
1166
|
-
|
1167
|
-
|
1168
|
-
|
1169
|
-
space_cli.print_disk_health(args.path)
|
1170
|
-
|
1171
|
-
# 显示目录分析
|
1172
|
-
if args.directories_only or args.path !='/':
|
1173
|
-
space_cli.print_largest_directories(args.path, args.top_n)
|
1174
|
-
# 若分析路径为当前用户目录,做深度分析
|
1175
|
-
if os.path.abspath(args.path) == os.path.abspath(str(Path.home())):
|
1176
|
-
space_cli.print_home_deep_analysis(args.top_n)
|
255
|
+
args.memory_cleanup = False
|
256
|
+
args.path = '/'
|
257
|
+
|
258
|
+
if choice == "0":
|
259
|
+
sys.exit(0)
|
260
|
+
elif choice == "2":
|
261
|
+
args.path = home_path
|
262
|
+
args.directories_only = True
|
263
|
+
elif choice == "3":
|
264
|
+
pass
|
265
|
+
elif choice == "4":
|
266
|
+
args.health_only = True
|
267
|
+
elif choice == "5":
|
268
|
+
args.directories_only = True
|
269
|
+
elif choice == "6":
|
270
|
+
args.apps = True
|
271
|
+
elif choice == "7":
|
272
|
+
args.big_files = True
|
273
|
+
elif choice == "8":
|
274
|
+
args.memory_cleanup = True
|
275
|
+
else:
|
276
|
+
args.health_only = True
|
277
|
+
args.apps = True
|
1177
278
|
|
1178
|
-
|
1179
|
-
if args.apps:
|
1180
|
-
space_cli.print_app_analysis(args.top_n)
|
279
|
+
run_once(args, interactive=True)
|
1181
280
|
|
1182
|
-
|
1183
|
-
|
1184
|
-
|
1185
|
-
|
1186
|
-
|
1187
|
-
|
1188
|
-
|
1189
|
-
|
1190
|
-
|
1191
|
-
print("=" * 60)
|
1192
|
-
print("✅ 分析完成!")
|
1193
|
-
print("=" * 60)
|
1194
|
-
|
1195
|
-
except KeyboardInterrupt:
|
1196
|
-
print("\n\n❌ 用户中断操作")
|
1197
|
-
sys.exit(1)
|
1198
|
-
except Exception as e:
|
1199
|
-
print(f"\n❌ 发生错误: {e}")
|
1200
|
-
sys.exit(1)
|
281
|
+
try:
|
282
|
+
back = input("按回车返回菜单,输入 q 退出: ").strip().lower()
|
283
|
+
except EOFError:
|
284
|
+
back = ""
|
285
|
+
if back == 'q':
|
286
|
+
sys.exit(0)
|
287
|
+
else:
|
288
|
+
# 非交互:按参数执行一次
|
289
|
+
run_once(args, interactive=False)
|
1201
290
|
|
1202
291
|
|
1203
292
|
if __name__ == "__main__":
|
@@ -1,6 +0,0 @@
|
|
1
|
-
space_cli.py,sha256=qEEhU_3nuiG--fWGbUDdQytrL9mL1CZTKGTMFpCyBNk,48380
|
2
|
-
myspace_cli-1.4.0.dist-info/METADATA,sha256=DDp6iHPcaGr_nCmJg5GHqeVhfqY-2fpzuJQ-4izUlVg,12747
|
3
|
-
myspace_cli-1.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
4
|
-
myspace_cli-1.4.0.dist-info/entry_points.txt,sha256=sIVEmPf6W8aNa7KiqOwAI6JrsgHlQciO5xH2G29tKPQ,45
|
5
|
-
myspace_cli-1.4.0.dist-info/top_level.txt,sha256=lnUfbQX9h-9ZjecMVCOWucS2kx69FwTndlrb48S20Sc,10
|
6
|
-
myspace_cli-1.4.0.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|