深度扫描目录改为全自动发现,界面撤掉目录配置(学习 Mole 零配置)

- 引擎自动发现项目容器:各固定磁盘根下一层的 repos/code/dev/projects/
  work/src/documents 等目录(大小写不敏感、去重),主目录本体浅层兜底;
  不存在的目录概念从此消失,settings.toml 里手写 purge_roots 仍作追加生效。
- 空间清理页「深度扫描目录」从按钮+弹层改为一行说明「自动发现:桌面、
  文档、各磁盘根目录下的项目目录(无需设置)」;概览页智能扫描同步传空。
- 移除 roots_status 命令与前端弹层组件;内置默认 purge_roots 清空。
- 实测本机 dry-run:自动发现 4 处根、命中 21.36 GB 构建产物(此前配置清单
  15 处里 14 处不存在)。无头断言:静态说明渲染、弹层入口消失、
  purge_scan 收到空 roots。fmt/test/clippy×2/pnpm check+build 全绿。
dev
lijunjie 2026-11-21 10:51:53 +08:00
parent a246f2aa87
commit 6a664515b3
9 changed files with 137 additions and 243 deletions

View File

@ -44,28 +44,9 @@ impl Default for Settings {
delete_mode: DeleteMode::Trash,
whitelist: Vec::new(),
disabled_rules: Vec::new(),
purge_roots: vec![
// Windows-style project homes first; the classic dev names
// stay (case variants dedupe at check time), and every entry
// is skipped silently when absent — Mole's default-list habit.
"~/Desktop".into(),
"~/Documents".into(),
"~/Documents/WeChat Projects".into(),
"~/source/repos".into(),
"~/code".into(),
"~/Code".into(),
"~/dev".into(),
"~/Dev".into(),
"~/develop".into(),
"~/projects".into(),
"~/Projects".into(),
"~/repos".into(),
"~/Repos".into(),
"~/src".into(),
"~/work".into(),
"~/Work".into(),
"~/.codex/worktrees".into(),
],
// Auto-discovery (purge::resolve_roots) owns the default story;
// this list is now only for hand-edited extra folders.
purge_roots: Vec::new(),
purge_min_age_days: 7,
purge_max_entries: 200_000,
show_allocated: true,

View File

@ -196,9 +196,17 @@ pub fn scan(
let mut candidates: Vec<Candidate> = Vec::new();
let mut visited = 0usize;
for root in &roots {
let top_level = roots.len() > 1 && root.components().count() <= 3;
let cap = if top_level { depth.min(4) } else { depth };
walk(root, cap, &mut candidates, &mut visited, progress, cancel)?;
// Shallow roots (the home folder itself) only get a depth-reduced
// walk; project containers are worth the full depth.
let cap = if root.shallow { depth.min(4) } else { depth };
walk(
&root.path,
cap,
&mut candidates,
&mut visited,
progress,
cancel,
)?;
}
candidates.sort_by(|a, b| a.path.cmp(&b.path));
candidates.dedup_by(|a, b| a.path == b.path);
@ -419,34 +427,120 @@ fn item_for(candidate: &Candidate) -> CleanupItem {
.with_note(project)
}
/// Default roots: everything the user configured, plus the home folder itself
/// (shallow) so a project in an unexpected place is still found.
fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec<PathBuf> {
/// Default roots are auto-discovered (Mole habit, but without the config
/// file): the home folder, container-named children of the home
/// (`~/source`, `~/repos`, …) and container-named children sitting directly
/// under each fixed drive root (`D:\Projects`). A user who wants more passes
/// explicit roots; a user who edits `purge_roots` in settings.toml keeps
/// those extras honoured as well.
fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec<RootSpec> {
if !options.roots.is_empty() {
let chosen: Vec<PathBuf> = options
let chosen: Vec<RootSpec> = options
.roots
.iter()
.map(|root| squid_core::paths::expand(&root.to_string_lossy()))
.filter(|path| path.is_dir())
.map(|path| RootSpec {
path,
shallow: false,
})
.collect();
// All the caller's paths are dead (classic case: the default roots
// are macOS-flavoured ~/code-style folders that never exist on
// Windows). Falling through to settings + home beats a scan that
// refuses to run and tells the user to pick a folder that is
// already in the box.
if !chosen.is_empty() {
return chosen;
}
}
let mut roots = engine.settings().purge_root_paths();
let home = squid_core::paths::home_dir();
if !roots.iter().any(|root| root == &home) {
roots.push(home);
let mut roots: Vec<RootSpec> = Vec::new();
let push = |path: PathBuf, shallow: bool, roots: &mut Vec<RootSpec>| {
if path.is_dir()
&& !roots
.iter()
.any(|seen| squid_core::paths::same_path(&seen.path, &path))
{
roots.push(RootSpec { path, shallow });
}
};
// Extras the user maintains by hand in settings.toml (not a UI concept).
for root in engine.settings().purge_root_paths() {
push(root, false, &mut roots);
}
roots.retain(|root| root.is_dir());
let home = squid_core::paths::home_dir();
// Container-named homes: full depth, high value.
for container in container_children(&home) {
push(container, false, &mut roots);
}
for mount in drive_roots(engine) {
for container in container_children(&mount) {
push(container, false, &mut roots);
}
}
// The home itself last, walked shallow: it still catches projects parked
// on Desktop / Documents without diving through the whole profile.
push(home, true, &mut roots);
roots
}
/// One walk start point. `shallow` roots (the home folder) get the reduced
/// depth cap; project containers are walked to the full depth.
struct RootSpec {
path: PathBuf,
shallow: bool,
}
/// Names that, one level under the home or a drive root, mean "my projects
/// live here". `documents`/`desktop` belong on drive roots (Windows users
/// keep code under `D:\Documents`, VS writes `Documents\source\repos`);
/// under the home folder they are reached by the shallow home walk anyway.
const CONTAINER_NAMES: &[&str] = &[
"repos",
"repo",
"git",
"github",
"code",
"coding",
"dev",
"develop",
"development",
"projects",
"project",
"workspace",
"workspaces",
"work",
"src",
"source",
"documents",
"desktop",
];
fn container_children(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
entries
.flatten()
.filter(|entry| {
let name = entry.file_name().to_string_lossy().into_owned();
CONTAINER_NAMES
.iter()
.any(|wanted| name.eq_ignore_ascii_case(wanted))
&& entry.path().is_dir()
})
.map(|entry| entry.path())
.collect()
}
/// Fixed drive mount points (Windows) / the root volume only elsewhere —
/// removable and network media are not project homes worth walking.
fn drive_roots(engine: &Engine) -> Vec<PathBuf> {
let Ok(volumes) = engine.platform().volumes() else {
return Vec::new();
};
volumes
.into_iter()
.filter(|volume| !volume.is_removable)
.map(|volume| volume.mount_point)
.collect()
}
fn walk(
root: &Path,
max_depth: usize,

View File

@ -1010,44 +1010,6 @@ pub fn stop_process(app: AppHandle, process: ProcessSample) -> Result<(), String
/// Write a UTF-8 text file (B5 clean-list export; the UI picked the path
/// through the save dialog, so this is a plain, bounded write).
/// Existence check for the 深度扫描目录 picker: Mole's manage screen shows
/// per-path ✓ / not-found, so the UI needs the same facts. `~` expands.
/// Without an explicit list the persisted one is reported on.
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RootStatus {
raw: String,
expanded: String,
exists: bool,
}
#[tauri::command]
pub async fn roots_status(roots: Option<Vec<String>>) -> Result<Vec<RootStatus>, String> {
let list = tauri::async_runtime::spawn_blocking(move || -> Result<Vec<RootStatus>, String> {
let list = match roots {
Some(list) => list,
None => {
let (settings, _) = Settings::load();
settings.purge_roots
}
};
Ok(list
.iter()
.map(|raw| {
let path = squid_core::paths::expand(raw);
RootStatus {
raw: raw.clone(),
expanded: squid_core::paths::pretty(&path),
exists: path.is_dir(),
}
})
.collect())
})
.await
.map_err(|error| error.to_string())??;
Ok(list)
}
#[tauri::command]
pub async fn write_text_file(path: String, contents: String) -> Result<(), String> {
tauri::async_runtime::spawn_blocking(move || {

View File

@ -131,7 +131,6 @@ pub fn run() {
app::storage_explore,
app::storage_insights,
app::write_text_file,
app::roots_status,
app::storage_largest_files,
app::system_snapshot,
app::stop_process,

View File

@ -16,7 +16,6 @@ import type {
PopupClosedEvent,
PopupWindowItem,
PreflightResult,
RootStatus,
ScanResult,
SettingsView,
SpaceInsight,
@ -80,8 +79,6 @@ export const api = {
whitelistAdd: (path: string) => invoke<SettingsView>("whitelist_add", { path }),
whitelistRemove: (pattern: string) => invoke<SettingsView>("whitelist_remove", { pattern }),
whitelistAudit: () => invoke<{ pattern: string; live: boolean }[]>("whitelist_audit"),
rootsStatus: (roots: string[] | null) =>
invoke<RootStatus[]>("roots_status", { roots: roots ?? null }),
writeTextFile: (path: string, contents: string) =>
invoke<void>("write_text_file", { path, contents }),
revealPath: (path: string) => invoke<void>("reveal_path", { path }),

View File

@ -108,7 +108,8 @@ export function OverviewPage({
if (!scanned) {
void cleanup.runScan().then(() =>
purge.runScan({
roots: bootstrap.settings.purgeRoots,
// Empty = engine auto-discovery of project containers.
roots: [],
minAgeDays: bootstrap.settings.purgeMinAgeDays || 7,
force: false,
}),

View File

@ -16,7 +16,7 @@ import {
ShieldCheck,
Trash2,
} from "lucide-react";
import { open, save } from "@tauri-apps/plugin-dialog";
import { save } from "@tauri-apps/plugin-dialog";
import {
useCallback,
useEffect,
@ -40,7 +40,6 @@ import type {
DeleteMode,
DeleteResult,
PreflightResult,
RootStatus,
} from "../types";
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
import {
@ -455,11 +454,6 @@ export function SpacePage({
}) {
const { t, lang, bin } = useI18n();
const { push } = useToast();
// 深度扫描目录: the persisted list, edited in a checklist popover that
// mirrors Mole's manage screen (every path shown, ✓ / 不存在 marked).
const [roots, setRoots] = useState<string[]>(bootstrap.settings.purgeRoots);
const [rootsOpen, setRootsOpen] = useState(false);
const [rootStatuses, setRootStatuses] = useState<RootStatus[]>([]);
const [minAge, setMinAge] = useState(bootstrap.settings.purgeMinAgeDays || 7);
const [confirming, setConfirming] = useState(false);
// Open accordions. On first results we auto-expand the biggest category so
@ -492,80 +486,19 @@ export function SpacePage({
try {
await cleanup.runScan();
await purge.runScan({
roots,
// Empty = the engine's auto-discovery (drive-root containers + home).
roots: [],
minAgeDays: minAge > 0 ? minAge : null,
force: false,
});
} finally {
inFlight.current = false;
}
}, [cleanup, deleting, minAge, purge, roots, scanning]);
}, [cleanup, deleting, minAge, purge, scanning]);
// Default checking is seeded at scan time by the workspaces' selection
// policy (App.tsx spaceDefaults): daily groups on, opt-in groups off.
// Every roots edit lands on disk right away (Mole persists its list file;
// a restart must never silently revert to defaults).
const saveRoots = async (next: string[]) => {
setRoots(next);
try {
await api.settingsSave({ purgeRoots: next });
} catch {
// Scan still uses the in-memory list; persistence can retry next edit.
}
};
const refreshRootStatuses = async (list: string[]) => {
try {
setRootStatuses(await api.rootsStatus(list));
} catch {
setRootStatuses([]);
}
};
const toggleRootsPopover = () => {
const next = !rootsOpen;
setRootsOpen(next);
if (next) void refreshRootStatuses(roots);
};
const addRoots = async () => {
const chosen = await open({
directory: true,
multiple: true,
title: t("Choose project folders to inspect", "选择要检查的项目目录"),
});
if (!chosen) return;
const picked = (Array.isArray(chosen) ? chosen : [chosen]).filter(
(path) => !roots.some((root) => root.toLowerCase() === path.toLowerCase()),
);
if (picked.length > 0) {
const next = [...roots, ...picked];
await saveRoots(next);
void refreshRootStatuses(next);
}
};
const removeRoot = async (raw: string) => {
const next = roots.filter((root) => root !== raw);
await saveRoots(next);
void refreshRootStatuses(next);
};
const resetRoots = async () => {
await saveRoots([]);
// [] on disk means defaults again: the Rust patch swaps in the built-in
// list, so re-read it to keep the popover honest.
try {
const status = await api.rootsStatus(null);
setRoots(status.map((row) => row.raw));
setRootStatuses(status);
} catch {
setRootStatuses([]);
}
push(t("Scan folders restored to defaults", "扫描目录已恢复默认"), "success");
};
const entries = useMemo<Entry[]>(() => {
const all: Entry[] = [];
for (const source of [cleanup, purge]) {
@ -1091,87 +1024,11 @@ export function SpacePage({
<span className="space-config-label">
{t("Deep-scan folders", "深度扫描目录")}
</span>
<span className="space-roots-wrap">
<button
type="button"
className="space-config-value"
onClick={toggleRootsPopover}
aria-expanded={rootsOpen}
>
{(() => {
const living = rootStatuses.filter((row) => row.exists).length;
const missing = rootStatuses.length - living;
if (!rootStatuses.length) {
return roots.length
? t(`${roots.length} folder(s) · click to view`, `共 ${roots.length} 处 · 点击检视`)
: t("Defaults · click to view", "默认目录 · 点击检视");
}
return missing > 0
? t(
`${living} active · ${missing} missing (skipped)`,
`${living} 处有效 · ${missing} 处不存在已跳过`,
)
: t(`${living} active folders`, `${living} 处目录全部有效`);
})()}
<ChevronRight
size={12}
style={{ transform: rootsOpen ? "rotate(90deg)" : undefined }}
/>
</button>
{rootsOpen ? (
<div className="space-roots-pop">
<div className="space-roots-list">
{(rootStatuses.length ? rootStatuses : roots.map((raw) => ({ raw, expanded: raw, exists: true }))).map(
(row) => (
<div
className={`space-roots-row ${row.exists ? "" : "is-missing"}`}
key={row.raw}
>
<span className="space-roots-state">
{row.exists ? "✓" : "⌀"}
</span>
<span className="space-roots-path" title={row.expanded}>
{row.expanded}
</span>
{!row.exists ? (
<small>{t("missing · skipped", "不存在 · 跳过")}</small>
) : null}
<button
type="button"
className="space-roots-x"
aria-label={t("Remove folder", "移除该目录")}
onClick={() => void removeRoot(row.raw)}
>
×
</button>
</div>
),
)}
{roots.length === 0 ? (
<p className="space-roots-empty">
{t(
"No folders — the built-in defaults are used.",
"未设置目录,使用内置默认清单。",
)}
</p>
) : null}
</div>
<div className="space-roots-acts">
<Button variant="ghost" size="sm" icon={<FolderOpen size={13} />} onClick={() => void addRoots()}>
{t("Add folder", "+ 添加目录")}
</Button>
<Button variant="ghost" size="sm" onClick={() => void resetRoots()}>
{t("Restore defaults", "恢复默认")}
</Button>
<small>
{t(
"Saved automatically; missing folders are skipped at scan time.",
"改动即时保存;扫描时不存在的目录自动跳过。",
)}
</small>
</div>
</div>
) : null}
<span className="space-config-static">
{t(
"Auto-discovered: Desktop, Documents, project folders on every drive",
"自动发现:桌面、文档、各磁盘根目录下的项目目录(无需设置)",
)}
</span>
<span className="space-config-label">
{t("Older than", "仅处理早于")}
@ -1267,8 +1124,8 @@ export function SpacePage({
<ScanSearch size={22} />
<span>
{t(
"Not scanned yet. Start scan checks known cache spots and searches the project folders above.",
"尚未扫描。点击「开始扫描」,Squid 会检查已知缓存位置并搜索上方项目目录里的构建产物。",
"Not scanned yet. Start scan checks known cache spots and auto-discovers project folders across the machine.",
"尚未扫描。点击「开始扫描」,Squid 会检查已知缓存位置,并自动发现本机各处的项目构建目录。",
)}
</span>
</div>

View File

@ -5379,6 +5379,16 @@ select:focus-visible,
}
/* 深度扫描目录 checklist popover (Mole manage-screen habit). */
.space-config-static {
min-width: 0;
flex: 1;
overflow: hidden;
color: #9a8a70;
font-size: var(--nex-text-2xs);
text-overflow: ellipsis;
white-space: nowrap;
}
.space-roots-wrap {
position: relative;
display: inline-flex;

View File

@ -286,13 +286,6 @@ export interface PreflightResult {
blocked: { path: string; reason: string }[];
}
/** One 深度扫描目录 with its existence verdict (Mole manage-screen habit). */
export interface RootStatus {
raw: string;
expanded: string;
exists: boolean;
}
export interface LargestFile {
path: string;
logical: number;