From 6a664515b3c4a4a599602966ac1dbe66a8b713c6 Mon Sep 17 00:00:00 2001 From: lijunjie Date: Sat, 21 Nov 2026 10:51:53 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=B1=E5=BA=A6=E6=89=AB=E6=8F=8F=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E6=94=B9=E4=B8=BA=E5=85=A8=E8=87=AA=E5=8A=A8=E5=8F=91?= =?UTF-8?q?=E7=8E=B0=EF=BC=8C=E7=95=8C=E9=9D=A2=E6=92=A4=E6=8E=89=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E9=85=8D=E7=BD=AE=EF=BC=88=E5=AD=A6=E4=B9=A0=20Mole?= =?UTF-8?q?=20=E9=9B=B6=E9=85=8D=E7=BD=AE=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 引擎自动发现项目容器:各固定磁盘根下一层的 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 全绿。 --- crates/squid-core/src/settings.rs | 25 +---- crates/squid-engine/src/purge.rs | 128 ++++++++++++++++++++--- src-tauri/src/app.rs | 38 ------- src-tauri/src/lib.rs | 1 - src/lib/api.ts | 3 - src/pages/OverviewPage.tsx | 3 +- src/pages/SpacePage.tsx | 165 ++---------------------------- src/styles.css | 10 ++ src/types.ts | 7 -- 9 files changed, 137 insertions(+), 243 deletions(-) diff --git a/crates/squid-core/src/settings.rs b/crates/squid-core/src/settings.rs index fa85bf0..7264462 100644 --- a/crates/squid-core/src/settings.rs +++ b/crates/squid-core/src/settings.rs @@ -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, diff --git a/crates/squid-engine/src/purge.rs b/crates/squid-engine/src/purge.rs index dddacc0..ba9ac0a 100644 --- a/crates/squid-engine/src/purge.rs +++ b/crates/squid-engine/src/purge.rs @@ -196,9 +196,17 @@ pub fn scan( let mut candidates: Vec = 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 { +/// 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 { if !options.roots.is_empty() { - let chosen: Vec = options + let chosen: Vec = 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 = Vec::new(); + let push = |path: PathBuf, shallow: bool, roots: &mut Vec| { + 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 { + 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 { + 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, diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs index 1ffbc9e..7cadeef 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -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>) -> Result, String> { - let list = tauri::async_runtime::spawn_blocking(move || -> Result, 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 || { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cc0ace5..8646d15 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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, diff --git a/src/lib/api.ts b/src/lib/api.ts index cb8ce68..7df003d 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -16,7 +16,6 @@ import type { PopupClosedEvent, PopupWindowItem, PreflightResult, - RootStatus, ScanResult, SettingsView, SpaceInsight, @@ -80,8 +79,6 @@ export const api = { whitelistAdd: (path: string) => invoke("whitelist_add", { path }), whitelistRemove: (pattern: string) => invoke("whitelist_remove", { pattern }), whitelistAudit: () => invoke<{ pattern: string; live: boolean }[]>("whitelist_audit"), - rootsStatus: (roots: string[] | null) => - invoke("roots_status", { roots: roots ?? null }), writeTextFile: (path: string, contents: string) => invoke("write_text_file", { path, contents }), revealPath: (path: string) => invoke("reveal_path", { path }), diff --git a/src/pages/OverviewPage.tsx b/src/pages/OverviewPage.tsx index 71d5bf4..7b9dd45 100644 --- a/src/pages/OverviewPage.tsx +++ b/src/pages/OverviewPage.tsx @@ -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, }), diff --git a/src/pages/SpacePage.tsx b/src/pages/SpacePage.tsx index 1b18ca3..740126b 100644 --- a/src/pages/SpacePage.tsx +++ b/src/pages/SpacePage.tsx @@ -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(bootstrap.settings.purgeRoots); - const [rootsOpen, setRootsOpen] = useState(false); - const [rootStatuses, setRootStatuses] = useState([]); 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(() => { const all: Entry[] = []; for (const source of [cleanup, purge]) { @@ -1091,87 +1024,11 @@ export function SpacePage({ {t("Deep-scan folders", "深度扫描目录")} - - - {rootsOpen ? ( -
-
- {(rootStatuses.length ? rootStatuses : roots.map((raw) => ({ raw, expanded: raw, exists: true }))).map( - (row) => ( -
- - {row.exists ? "✓" : "⌀"} - - - {row.expanded} - - {!row.exists ? ( - {t("missing · skipped", "不存在 · 跳过")} - ) : null} - -
- ), - )} - {roots.length === 0 ? ( -

- {t( - "No folders — the built-in defaults are used.", - "未设置目录,使用内置默认清单。", - )} -

- ) : null} -
-
- - - - {t( - "Saved automatically; missing folders are skipped at scan time.", - "改动即时保存;扫描时不存在的目录自动跳过。", - )} - -
-
- ) : null} + + {t( + "Auto-discovered: Desktop, Documents, project folders on every drive", + "自动发现:桌面、文档、各磁盘根目录下的项目目录(无需设置)", + )} {t("Older than", "仅处理早于")} @@ -1267,8 +1124,8 @@ export function SpacePage({ {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 会检查已知缓存位置,并自动发现本机各处的项目构建目录。", )} diff --git a/src/styles.css b/src/styles.css index a1c17fa..4d1cdb0 100644 --- a/src/styles.css +++ b/src/styles.css @@ -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; diff --git a/src/types.ts b/src/types.ts index 0b76fb3..000d1e1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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;