ffrm 0.1.2

查看谁占用了本地文件,解除占用,并删除文件
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
mod lock;

use std::ffi::OsString;
use std::io::{self, IsTerminal, Write};
use std::path::PathBuf;

use lock::critical_block;

pub use lock::{
    block_reason, delete_path, display_name, inspect, is_critical, release, Inspection, Locker,
};

fn help_body() -> String {
    format!(
        "\
ffrm {version}
查看谁占用了本地文件,解除占用,并删除文件。
不带参数,或直接传入路径时,打开桌面窗口。

用法:
  ffrm
  ffrm <路径>...
  ffrm status <路径>...
  ffrm unlock <路径>... [--force] [--yes]
  ffrm delete <路径>... [--unlock] [--force] [--yes] [--recursive]",
        version = env!("CARGO_PKG_VERSION")
    )
}

const HELP_TAIL: &str = "

命令:
  status   列出占用该文件的进程
  unlock   让占用进程退出以释放文件
  delete   删除文件或目录

选项:
  --unlock       delete 时若文件被占用,先解除占用
  --force, -f    进程无响应时强制结束
  --yes, -y      不再询问确认
  --recursive, -r
                 删除非空目录
  -h, --help     显示帮助
  -V, --version  显示版本

直接传入路径只会打开窗口并加入队列,不会删除。
不会删除磁盘根目录、Windows 目录、用户主目录或 Program Files 本身。
unlock 会关闭正在使用该文件的程序。程序若没有退出,会结束该进程。关键系统进程会被拒绝。
";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command {
    pub action: Action,
    pub paths: Vec<PathBuf>,
    pub unlock: bool,
    pub force: bool,
    pub yes: bool,
    pub recursive: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    Status,
    Unlock,
    Delete,
}

#[derive(Debug)]
pub enum Parsed {
    Help,
    Version,
    Run(Command),
}

pub fn parse_args<I, S>(args: I) -> Result<Parsed, String>
where
    I: IntoIterator<Item = S>,
    S: Into<OsString>,
{
    let mut action = None;
    let mut paths = Vec::new();
    let mut unlock = false;
    let mut force = false;
    let mut yes = false;
    let mut recursive = false;
    let mut positional = false;

    for arg in args {
        let arg = arg.into();
        let text = arg.to_string_lossy();
        if !positional && text == "--" {
            positional = true;
            continue;
        }
        if !positional && (text == "-h" || text == "--help") {
            return Ok(Parsed::Help);
        }
        if !positional && (text == "-V" || text == "--version") {
            return Ok(Parsed::Version);
        }
        if !positional && text.starts_with('-') {
            match text.as_ref() {
                "--unlock" => unlock = true,
                "--force" | "-f" => force = true,
                "--yes" | "-y" => yes = true,
                "--recursive" | "-r" => recursive = true,
                other => return Err(format!("未知选项: {other}")),
            }
            continue;
        }
        if action.is_none() && !positional {
            action = Some(parse_action(&text)?);
            continue;
        }
        paths.push(PathBuf::from(arg));
    }

    let action = action.ok_or_else(|| "请指定 status、unlock 或 delete".to_string())?;
    if paths.is_empty() {
        return Err("请至少提供一个路径".to_string());
    }
    match action {
        Action::Status if unlock || force || recursive => {
            return Err("status 只接受路径".to_string());
        }
        Action::Unlock if unlock || recursive => {
            return Err("unlock 不接受 --unlock 或 --recursive".to_string());
        }
        Action::Delete if force && !unlock => {
            return Err("delete 使用 --force 时必须同时加上 --unlock".to_string());
        }
        _ => {}
    }

    Ok(Parsed::Run(Command {
        action,
        paths,
        unlock,
        force,
        yes,
        recursive,
    }))
}

pub fn execute(command: &Command) -> Result<(), String> {
    match command.action {
        Action::Status => status(command),
        Action::Unlock => unlock(command),
        Action::Delete => delete(command),
    }
}

pub fn help_text() -> String {
    format!("{}{HELP_TAIL}", help_body())
}

fn parse_action(text: &str) -> Result<Action, String> {
    match text {
        "status" => Ok(Action::Status),
        "unlock" => Ok(Action::Unlock),
        "delete" => Ok(Action::Delete),
        other => Err(format!("未知命令: {other}")),
    }
}

fn status(command: &Command) -> Result<(), String> {
    for path in &command.paths {
        print_inspection(&inspect(path)?)?;
    }
    Ok(())
}

fn unlock(command: &Command) -> Result<(), String> {
    let inspections = inspect_all(command)?;
    let lockers = all_lockers(&inspections);
    if inspections.iter().any(|item| item.list_denied) && lockers.is_empty() {
        if inspections.iter().any(|item| item.sharing_violation) {
            return Err("文件正被占用,但没有权限列出占用进程,无法解除占用。".to_string());
        }
        emit("没有权限列出占用进程,也没有检测到文件被占用。");
        return Ok(());
    }
    if lockers.is_empty() && inspections.iter().all(|item| !item.sharing_violation) {
        emit("没有进程占用这些文件。");
        return Ok(());
    }
    if let Some(reason) = critical_block(&lockers) {
        return Err(reason);
    }
    if lockers.is_empty() {
        return Err("文件正被占用,但没有列出可关闭的进程。请先关闭相关程序。".to_string());
    }
    emit("将关闭以下程序以释放文件:");
    print_lockers(&lockers);
    confirm(command.yes)?;
    for inspection in &inspections {
        if inspection.lockers.is_empty() {
            continue;
        }
        release(&inspection.path, command.force)?;
        let again = inspect(&inspection.path)?;
        if again.sharing_violation || !again.lockers.is_empty() {
            return Err(format!("{} 仍被占用", inspection.path.display()));
        }
        emit(&format!("已释放 {}", inspection.path.display()));
    }
    Ok(())
}

fn delete(command: &Command) -> Result<(), String> {
    for path in &command.paths {
        if let Some(reason) = block_reason(path) {
            return Err(format!("{}: {reason}", path.display()));
        }
    }
    let inspections = inspect_all(command)?;
    let lockers = all_lockers(&inspections);
    if inspections
        .iter()
        .any(|item| item.list_denied && item.sharing_violation)
    {
        return Err("文件正被占用,但没有权限列出占用进程。".to_string());
    }
    let busy = inspections.iter().any(|item| item.sharing_violation) || !lockers.is_empty();
    if busy && !command.unlock {
        for inspection in &inspections {
            print_inspection(inspection)?;
        }
        return Err("文件被占用。确认要关闭占用程序并删除时,请加上 --unlock。".to_string());
    }
    if let Some(reason) = critical_block(&lockers) {
        return Err(reason);
    }
    if command.unlock && lockers.is_empty() && busy {
        return Err("文件正被占用,但没有列出可关闭的进程。请先关闭相关程序。".to_string());
    }
    emit("将删除:");
    for inspection in &inspections {
        emit(&format!("  {}", inspection.path.display()));
    }
    if command.unlock && !lockers.is_empty() {
        emit("将关闭以下程序:");
        print_lockers(&lockers);
    }
    confirm(command.yes)?;
    for inspection in &inspections {
        if command.unlock && !inspection.lockers.is_empty() {
            release(&inspection.path, command.force)?;
        }
        let removed = delete_path(&inspection.path, command.recursive)?;
        emit(&format!("已删除 {}", removed.display()));
    }
    Ok(())
}

fn inspect_all(command: &Command) -> Result<Vec<Inspection>, String> {
    command.paths.iter().map(|path| inspect(path)).collect()
}

fn all_lockers(inspections: &[Inspection]) -> Vec<Locker> {
    let mut lockers = Vec::new();
    for inspection in inspections {
        for locker in &inspection.lockers {
            if !lockers
                .iter()
                .any(|existing: &Locker| existing.pid == locker.pid)
            {
                lockers.push(locker.clone());
            }
        }
    }
    lockers
}

fn print_inspection(inspection: &Inspection) -> Result<(), String> {
    emit(&inspection.path.display().to_string());
    if inspection.list_denied {
        emit("  没有权限列出占用进程");
    }
    if inspection.lockers.is_empty() && !inspection.sharing_violation {
        if !inspection.list_denied {
            emit("  没有进程占用此文件");
        }
        return Ok(());
    }
    if inspection.lockers.is_empty() {
        emit("  文件正被占用,但没有列出可关闭的进程");
        return Ok(());
    }
    print_lockers(&inspection.lockers);
    Ok(())
}

fn print_lockers(lockers: &[Locker]) {
    for locker in lockers {
        let mut line = format!("  pid {}  {}", locker.pid, display_name(locker));
        if let Some(image) = &locker.image {
            line.push_str("  ");
            line.push_str(image);
        }
        if is_critical(locker) {
            line.push_str("  [关键系统进程]");
        }
        emit(&line);
    }
}

fn confirm(yes: bool) -> Result<(), String> {
    if yes {
        return Ok(());
    }
    if !io::stdin().is_terminal() {
        return Err("当前不是交互终端,请加上 --yes".to_string());
    }
    emit_raw_err("输入 y 继续: ")?;
    let mut line = String::new();
    io::stdin()
        .read_line(&mut line)
        .map_err(|err| format!("无法读取确认: {err}"))?;
    let answer = line.trim();
    if answer.eq_ignore_ascii_case("y") || answer.eq_ignore_ascii_case("yes") || answer == "是" {
        Ok(())
    } else {
        Err("已取消".to_string())
    }
}

fn emit(line: &str) {
    let _ = write_line(io::stdout(), line);
}

fn emit_raw_err(text: &str) -> Result<(), String> {
    if write_console(&io::stderr(), text) {
        return Ok(());
    }
    let mut error = io::stderr();
    error
        .write_all(text.as_bytes())
        .and_then(|()| error.flush())
        .map_err(|err| format!("无法写出提示: {err}"))
}

pub fn emit_err(line: &str) {
    let _ = write_line(io::stderr(), line);
}

fn write_line<T>(target: T, line: &str) -> io::Result<()>
where
    T: Write + std::os::windows::io::AsRawHandle,
{
    let mut text = String::from(line);
    text.push('\n');
    if write_console(&target, &text) {
        return Ok(());
    }
    let mut target = target;
    target.write_all(text.as_bytes())?;
    target.flush()
}

fn write_console(target: &impl std::os::windows::io::AsRawHandle, text: &str) -> bool {
    use windows_sys::Win32::System::Console::WriteConsoleW;

    let handle = target.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE;
    if handle.is_null() {
        return false;
    }
    let wide: Vec<u16> = text.encode_utf16().collect();
    let mut written = 0u32;
    let ok = unsafe {
        WriteConsoleW(
            handle,
            wide.as_ptr(),
            wide.len() as u32,
            &mut written,
            std::ptr::null(),
        )
    };
    ok != 0
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_delete_command() {
        let parsed = parse_args([
            "delete",
            r"D:\temp\a.txt",
            "--unlock",
            "--force",
            "--yes",
            "--recursive",
        ])
        .unwrap();
        match parsed {
            Parsed::Run(command) => {
                assert_eq!(command.action, Action::Delete);
                assert!(command.unlock && command.force && command.yes && command.recursive);
                assert_eq!(command.paths, vec![PathBuf::from(r"D:\temp\a.txt")]);
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn rejects_force_delete_without_unlock() {
        let error = parse_args(["delete", r"D:\temp\a.txt", "--force"]).unwrap_err();
        assert!(error.contains("--unlock"));
    }

    #[test]
    fn help_and_missing_path() {
        assert!(matches!(parse_args(["--help"]), Ok(Parsed::Help)));
        assert!(parse_args(["status"]).is_err());
    }
}