ziro 0.0.24

Cross-platform port management tool - quickly find and kill processes occupying ports
Documentation
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
use crate::ui::Theme;
use anyhow::{Context, Result, anyhow};
use std::fs;
use std::path::{Path, PathBuf};

/// Windows deletion retry parameters
#[cfg(target_os = "windows")]
const RETRY_MAX_ATTEMPTS: u32 = 5;
#[cfg(target_os = "windows")]
const RETRY_INITIAL_WAIT_MS: u64 = 100;
#[cfg(target_os = "windows")]
const RETRY_MAX_WAIT_MS: u64 = 1000;

#[derive(Debug, Clone)]
pub struct FileInfo {
    pub path: PathBuf,
    pub is_dir: bool,
    pub size: u64,
    pub is_symlink: bool,
}

/// Validate that paths exist
pub fn validate_paths(paths: &[PathBuf]) -> Result<()> {
    for path in paths {
        if !path.exists() {
            return Err(anyhow!("Path does not exist: {}", path.display()));
        }
    }
    Ok(())
}

/// Collect file/directory info for removal
pub fn collect_files_to_remove(paths: &[PathBuf], recursive: bool) -> Result<Vec<FileInfo>> {
    let mut files = Vec::new();

    for path in paths {
        let metadata = path
            .symlink_metadata()
            .with_context(|| format!("Failed to get file metadata: {}", path.display()))?;
        let is_symlink = metadata.file_type().is_symlink();
        let is_dir = metadata.is_dir() && !is_symlink;

        if is_dir {
            if recursive {
                collect_dir_files(path, &mut files)?;
                files.push(FileInfo {
                    path: path.clone(),
                    is_dir: true,
                    size: 0,
                    is_symlink: false,
                });
            } else {
                // Non-recursive mode: only allow empty directories
                if path.read_dir()?.next().is_some() {
                    return Err(anyhow!(
                        "Directory requires -r/--recursive flag: {}",
                        path.display()
                    ));
                }
                files.push(FileInfo {
                    path: path.clone(),
                    is_dir: true,
                    size: 0,
                    is_symlink: false,
                });
            }
        } else {
            files.push(FileInfo {
                path: path.clone(),
                is_dir: false,
                size: metadata.len(),
                is_symlink,
            });
        }
    }

    Ok(files)
}

/// Recursively collect directory contents (does not follow symlinks)
fn collect_dir_files(dir: &Path, files: &mut Vec<FileInfo>) -> Result<()> {
    for entry in
        fs::read_dir(dir).with_context(|| format!("Failed to read directory: {}", dir.display()))?
    {
        let entry =
            entry.with_context(|| format!("Failed to read directory entry: {}", dir.display()))?;
        let path = entry.path();
        let metadata = path
            .symlink_metadata()
            .with_context(|| format!("Failed to get file metadata: {}", path.display()))?;
        let is_symlink = metadata.file_type().is_symlink();
        let is_dir = metadata.is_dir() && !is_symlink;

        if is_dir {
            collect_dir_files(&path, files)?;
            files.push(FileInfo {
                path,
                is_dir: true,
                size: 0,
                is_symlink: false,
            });
        } else {
            files.push(FileInfo {
                path,
                is_dir: false,
                size: metadata.len(),
                is_symlink,
            });
        }
    }

    Ok(())
}

/// Execute deletion
pub fn remove_files(
    files: &[FileInfo],
    dry_run: bool,
    verbose: bool,
    anyway: bool,
) -> Vec<(PathBuf, Result<()>)> {
    let theme = Theme::new();

    // Windows special handling: try bulk deletion
    #[cfg(target_os = "windows")]
    if let Some(results) = try_windows_bulk_remove(files, dry_run, verbose, anyway, &theme) {
        return results;
    }

    // Generic individual deletion logic
    remove_files_individually(files, dry_run, verbose, anyway, &theme)
}

/// Windows special handling: try bulk deletion of root directory
#[cfg(target_os = "windows")]
fn try_windows_bulk_remove(
    files: &[FileInfo],
    dry_run: bool,
    verbose: bool,
    anyway: bool,
    theme: &Theme,
) -> Option<Vec<(PathBuf, Result<()>)>> {
    // Find the root directory specified by the user
    let root_dir = files.iter().find(|f| {
        f.is_dir
            && !files
                .iter()
                .any(|other| other.path != f.path && f.path.starts_with(&other.path))
    })?;

    if dry_run {
        return Some(vec![(root_dir.path.clone(), Ok(()))]);
    }

    // Try to use remove_dir_all to delete the entire directory tree, with retries
    use crate::core::process::{find_processes_by_file, kill_process_force};

    let mut wait_ms = RETRY_INITIAL_WAIT_MS;
    let mut last_err = None;
    let mut success = false;

    for attempt in 0..=RETRY_MAX_ATTEMPTS {
        match remove_dir_all_with_symlinks(&root_dir.path) {
            Ok(_) => {
                success = true;
                break;
            }
            Err(e) => {
                last_err = Some(e);

                let io_err = last_err
                    .as_ref()
                    .and_then(|e| e.downcast_ref::<std::io::Error>());
                let should_retry = io_err.is_some_and(is_retryable_error);

                if !should_retry || attempt == RETRY_MAX_ATTEMPTS {
                    break;
                }

                if anyway {
                    if let Ok(pids) = find_processes_by_file(&root_dir.path) {
                        for pid in pids {
                            let _ = kill_process_force(pid);
                        }
                    }
                }

                if verbose {
                    println!(
                        "{} {}",
                        theme.icon_warning(),
                        theme.muted(format!(
                            "Retrying ({}/{})...",
                            attempt + 1,
                            RETRY_MAX_ATTEMPTS
                        ))
                    );
                }

                std::thread::sleep(std::time::Duration::from_millis(wait_ms));
                wait_ms = (wait_ms * 2).min(RETRY_MAX_WAIT_MS);
            }
        }
    }

    if success {
        if verbose {
            println!(
                "{} {}",
                theme.icon_success(),
                theme.muted(format!("Removed {}", root_dir.path.display()))
            );
        }
        Some(vec![(root_dir.path.clone(), Ok(()))])
    } else {
        if verbose {
            println!(
                "{} {}",
                theme.icon_warning(),
                theme.warning(format!(
                    "Bulk delete failed, trying individual deletion: {}",
                    last_err.unwrap_or_else(|| anyhow::anyhow!("Unknown error"))
                ))
            );
        }
        None
    }
}

/// Delete files individually (generic logic)
fn remove_files_individually(
    files: &[FileInfo],
    dry_run: bool,
    verbose: bool,
    anyway: bool,
    theme: &Theme,
) -> Vec<(PathBuf, Result<()>)> {
    let mut results = Vec::new();

    // Ensure files are deleted before directories (depth-first)
    let mut sorted = files.to_vec();
    sorted.sort_by(|a, b| {
        if a.is_dir && !b.is_dir {
            std::cmp::Ordering::Greater
        } else if !a.is_dir && b.is_dir {
            std::cmp::Ordering::Less
        } else {
            let depth_a = a.path.components().count();
            let depth_b = b.path.components().count();
            depth_b.cmp(&depth_a)
        }
    });

    for file in sorted {
        let result = if dry_run {
            Ok(())
        } else {
            remove_with_retry(&file, anyway)
        };

        if verbose {
            match &result {
                Ok(_) => println!(
                    "{} {}",
                    theme.icon_success(),
                    theme.muted(format!("Removed {}", file.path.display()))
                ),
                Err(e) => println!(
                    "{} {}",
                    theme.icon_error(),
                    theme.error(format!("Failed to delete {} - {}", file.path.display(), e))
                ),
            }
        }

        results.push((file.path, result));
    }

    results
}

/// Delete directories containing symlinks on Windows
#[cfg(target_os = "windows")]
fn remove_dir_all_with_symlinks(path: &Path) -> Result<()> {
    use std::os::windows::ffi::OsStrExt;

    // Convert to Windows long path format (\\?\ prefix)
    // This bypasses the MAX_PATH (260 character) limit
    let long_path = to_long_path(path)?;

    // Use Windows API to delete directory
    unsafe {
        use windows_sys::Win32::Foundation::GetLastError;
        use windows_sys::Win32::Storage::FileSystem::{
            DeleteFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_READONLY,
            FILE_ATTRIBUTE_REPARSE_POINT, GetFileAttributesW, INVALID_FILE_ATTRIBUTES,
            RemoveDirectoryW, SetFileAttributesW,
        };

        let path_wide: Vec<u16> = long_path
            .as_os_str()
            .encode_wide()
            .chain(std::iter::once(0))
            .collect();

        // Get file attributes
        let attrs = GetFileAttributesW(path_wide.as_ptr());
        if attrs == INVALID_FILE_ATTRIBUTES {
            return Err(anyhow!("Failed to get file attributes: {}", path.display()));
        }

        // Check if it is a symlink (reparse point)
        let is_reparse_point = (attrs & FILE_ATTRIBUTE_REPARSE_POINT) != 0;

        if is_reparse_point {
            // For symlinks, use DeleteFileW
            if DeleteFileW(path_wide.as_ptr()) == 0 {
                let err = GetLastError();
                return Err(std::io::Error::from_raw_os_error(err as i32))
                    .with_context(|| format!("Failed to delete symlink: {}", path.display()));
            }
        } else if (attrs & FILE_ATTRIBUTE_DIRECTORY) != 0 {
            // For directories, recursively delete contents
            remove_directory_recursive(&long_path).with_context(|| {
                format!(
                    "Failed to recursively delete directory contents: {}",
                    path.display()
                )
            })?;

            // Remove read-only attribute from root directory
            SetFileAttributesW(path_wide.as_ptr(), attrs & !FILE_ATTRIBUTE_READONLY);

            // Delete empty directory
            if RemoveDirectoryW(path_wide.as_ptr()) == 0 {
                let err = GetLastError();
                return Err(std::io::Error::from_raw_os_error(err as i32))
                    .with_context(|| format!("Failed to delete directory: {}", path.display()));
            }
        } else {
            // Remove read-only attribute from file
            SetFileAttributesW(path_wide.as_ptr(), attrs & !FILE_ATTRIBUTE_READONLY);

            // For files, use DeleteFileW
            if DeleteFileW(path_wide.as_ptr()) == 0 {
                let err = GetLastError();
                return Err(std::io::Error::from_raw_os_error(err as i32))
                    .with_context(|| format!("Failed to delete file: {}", path.display()));
            }
        }
    }

    Ok(())
}

/// Recursively delete directory contents (using long paths)
#[cfg(target_os = "windows")]
unsafe fn remove_directory_recursive(path: &Path) -> Result<()> {
    use std::os::windows::ffi::OsStrExt;
    use windows_sys::Win32::Storage::FileSystem::{
        DeleteFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_READONLY,
        FILE_ATTRIBUTE_REPARSE_POINT, FindClose, FindFirstFileW, FindNextFileW, RemoveDirectoryW,
        SetFileAttributesW, WIN32_FIND_DATAW,
    };

    // Build search pattern: path\*
    let mut search_pattern = path.to_path_buf();
    search_pattern.push("*");
    let search_wide: Vec<u16> = search_pattern
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();

    let mut find_data: WIN32_FIND_DATAW = unsafe { std::mem::zeroed() };
    let find_handle = unsafe { FindFirstFileW(search_wide.as_ptr(), &mut find_data) };

    if find_handle == windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE {
        // Directory is empty or error occurred, return success
        return Ok(());
    }

    loop {
        // Skip . and ..
        let name = find_data.cFileName[..]
            .iter()
            .take_while(|&&c| c != 0)
            .copied()
            .collect::<Vec<_>>();
        let name_str = String::from_utf16_lossy(&name);

        if name_str != "." && name_str != ".." {
            let mut item_path = path.to_path_buf();
            item_path.push(&name_str);

            let item_wide: Vec<u16> = item_path
                .as_os_str()
                .encode_wide()
                .chain(std::iter::once(0))
                .collect();

            let is_dir = (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
            let is_reparse_point = (find_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;

            if is_dir && !is_reparse_point {
                // Recursively delete subdirectory
                unsafe {
                    remove_directory_recursive(&item_path)?;
                }
                // Remove read-only attribute
                unsafe {
                    SetFileAttributesW(
                        item_wide.as_ptr(),
                        find_data.dwFileAttributes & !FILE_ATTRIBUTE_READONLY,
                    );
                }
                // Delete empty directory
                if unsafe { RemoveDirectoryW(item_wide.as_ptr()) } == 0 {
                    let err = unsafe { windows_sys::Win32::Foundation::GetLastError() };
                    unsafe {
                        FindClose(find_handle);
                    }
                    return Err(std::io::Error::from_raw_os_error(err as i32)).with_context(|| {
                        format!("Failed to delete directory: {}", item_path.display())
                    });
                }
            } else {
                // Remove read-only attribute
                unsafe {
                    SetFileAttributesW(
                        item_wide.as_ptr(),
                        find_data.dwFileAttributes & !FILE_ATTRIBUTE_READONLY,
                    );
                }
                // Delete file or symlink
                if unsafe { DeleteFileW(item_wide.as_ptr()) } == 0 {
                    let err = unsafe { windows_sys::Win32::Foundation::GetLastError() };
                    unsafe {
                        FindClose(find_handle);
                    }
                    return Err(std::io::Error::from_raw_os_error(err as i32)).with_context(|| {
                        format!("Failed to delete file: {}", item_path.display())
                    });
                }
            }
        }

        if unsafe { FindNextFileW(find_handle, &mut find_data) } == 0 {
            break;
        }
    }

    unsafe {
        FindClose(find_handle);
    }
    Ok(())
}

/// Convert path to Windows long path format
#[cfg(target_os = "windows")]
fn to_long_path(path: &Path) -> Result<PathBuf> {
    // Try to get absolute path, fall back to original if failed
    let absolute = match fs::canonicalize(path) {
        Ok(p) => p,
        Err(_) => {
            // If canonicalize fails (possibly due to long path), use absolute path
            if path.is_absolute() {
                path.to_path_buf()
            } else {
                std::env::current_dir()
                    .ok()
                    .map(|cwd| cwd.join(path))
                    .unwrap_or_else(|| path.to_path_buf())
            }
        }
    };

    // Check if already a UNC path
    let path_str = absolute.to_string_lossy().to_string();
    let has_prefix = path_str.starts_with(r"\\?\") || path_str.starts_with(r"\\?\UNC\");

    if has_prefix {
        return Ok(absolute);
    }

    // Add \\?\ prefix
    let long_path = if let Some(stripped) = path_str.strip_prefix(r"\\") {
        // UNC path: \\?\UNC\server\share
        PathBuf::from(format!(r"\\?\UNC\{}", stripped))
    } else {
        // Regular path: \\?\C:\path
        PathBuf::from(format!(r"\\?{}", path_str))
    };

    Ok(long_path)
}

/// Recursively remove read-only attributes from directory and its contents
#[cfg(target_os = "windows")]
fn remove_readonly_recursively(path: &Path) -> Result<()> {
    let metadata = path
        .symlink_metadata()
        .with_context(|| format!("Failed to get path metadata: {}", path.display()))?;

    // Only process files and directories, skip symlinks
    if !metadata.file_type().is_symlink() {
        #[allow(clippy::permissions_set_readonly_false)]
        {
            let mut perms = metadata.permissions();
            perms.set_readonly(false);
            fs::set_permissions(path, perms)
                .with_context(|| format!("Failed to set permissions: {}", path.display()))?;
        }

        if metadata.is_dir() {
            for entry in fs::read_dir(path)
                .with_context(|| format!("Failed to read directory: {}", path.display()))?
            {
                let entry = entry.with_context(|| {
                    format!("Failed to read directory entry: {}", path.display())
                })?;
                remove_readonly_recursively(&entry.path())?;
            }
        }
    }
    Ok(())
}

/// Determine if an IO error is retryable (Windows-specific)
/// Retries are triggered only for:
/// - PermissionDenied
/// - Windows error code 32 (ERROR_SHARING_VIOLATION)
/// - Windows error code 33 (ERROR_LOCK_VIOLATION)
/// - Windows error code 5 (ERROR_ACCESS_DENIED)
#[cfg(target_os = "windows")]
fn is_retryable_error(e: &std::io::Error) -> bool {
    match e.kind() {
        std::io::ErrorKind::PermissionDenied => true,
        _ => {
            let os_code = e.raw_os_error();
            matches!(os_code, Some(5) | Some(32) | Some(33))
        }
    }
}

/// File deletion with exponential backoff retry
#[cfg(target_os = "windows")]
fn remove_with_retry(file: &FileInfo, anyway: bool) -> Result<()> {
    use crate::core::process::{find_processes_by_file, kill_process_force};
    use std::thread;
    use std::time::Duration;

    let mut wait_ms = RETRY_INITIAL_WAIT_MS;

    for attempt in 0..=RETRY_MAX_ATTEMPTS {
        match remove_entry(file) {
            Ok(()) => return Ok(()),
            Err(err) => {
                let io_err = err.downcast_ref::<std::io::Error>();
                let should_retry = io_err.is_some_and(is_retryable_error);

                if !should_retry || attempt == RETRY_MAX_ATTEMPTS {
                    return Err(err.context(format!(
                        "Deletion failed (after {} retries): {}",
                        attempt,
                        file.path.display()
                    )));
                }

                eprintln!(
                    "  Retrying ({}/{})... file may be in use: {}",
                    attempt + 1,
                    RETRY_MAX_ATTEMPTS,
                    file.path.display()
                );

                if anyway {
                    if let Ok(pids) = find_processes_by_file(&file.path) {
                        for pid in pids {
                            let _ = kill_process_force(pid);
                        }
                    }
                }

                thread::sleep(Duration::from_millis(wait_ms));
                wait_ms = (wait_ms * 2).min(RETRY_MAX_WAIT_MS);
            }
        }
    }

    unreachable!()
}

#[cfg(not(target_os = "windows"))]
fn remove_with_retry(file: &FileInfo, _anyway: bool) -> Result<()> {
    remove_entry(file)
}

fn remove_entry(file: &FileInfo) -> Result<()> {
    // On Windows, symlinks require special handling
    #[cfg(target_os = "windows")]
    {
        if file.is_symlink {
            // For symlinks, always use remove_file
            // This deletes the link itself, not the target
            match fs::remove_file(&file.path) {
                Ok(_) => return Ok(()),
                Err(e) => {
                    // If it fails, try Windows-specific methods
                    if e.kind() == std::io::ErrorKind::PermissionDenied {
                        // Try to get file attributes and remove read-only
                        if let Ok(metadata) = file.path.metadata() {
                            #[allow(clippy::permissions_set_readonly_false)]
                            {
                                let mut attrs = metadata.permissions();
                                attrs.set_readonly(false);
                                if let Err(_) = fs::set_permissions(&file.path, attrs) {
                                    // If unable to modify permissions, continue trying to delete
                                }
                            }
                        }
                        // Try deleting again
                        return fs::remove_file(&file.path).with_context(|| {
                            format!("Failed to delete symlink: {}", file.path.display())
                        });
                    }
                    return Err(e.into());
                }
            }
        }
    }

    // Regular handling for non-symlinks
    let result = if file.is_symlink {
        fs::remove_file(&file.path)
    } else if file.is_dir {
        // For directories, try remove_dir first (empty directory)
        match fs::remove_dir(&file.path) {
            Ok(_) => Ok(()),
            Err(e) => {
                // If it's a permission error, try modifying permissions then delete
                if e.kind() == std::io::ErrorKind::PermissionDenied {
                    // Recursively modify permissions of directory and its contents
                    #[cfg(target_os = "windows")]
                    if let Err(_) = remove_readonly_recursively(&file.path) {
                        // If unable to modify permissions, continue trying to delete
                    }
                    // Try deleting again
                    fs::remove_dir_all(&file.path)
                } else {
                    Err(e)
                }
            }
        }
    } else {
        fs::remove_file(&file.path)
    };

    result.with_context(|| format!("Deletion failed: {}", file.path.display()))
}

/// Format file size
pub fn format_size(size: u64) -> String {
    const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
    let mut size = size as f64;
    let mut unit_index = 0;

    while size >= 1024.0 && unit_index < UNITS.len() - 1 {
        size /= 1024.0;
        unit_index += 1;
    }

    if unit_index == 0 {
        format!("{} {}", size as u64, UNITS[unit_index])
    } else {
        format!("{:.1} {}", size, UNITS[unit_index])
    }
}