cli_util 0.2.35

Command-line utilitiy for unix based systems
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
//! # List directory contents.
//! Supported arguments list below
//!
//!    `Syntax`
//!
//!       ls [-Option(s)] [file ...]
//!          l      List files in long format 'ls -l'
//!
//!          ll     List files in long format, showing invisible files 'ls -la'
//!    `Options`
//!
//!    `-a`     List all entries including those starting with a dot .
//!
//!    `-C`     Force multi-column output; this is the default when output is to
//!           a terminal.
//!
//!    `-c`     Use time when file status was last changed for sorting or printing.
//!
//!    `-d`      Directories are listed as plain files (not searched recursively).
//!
//!    `-l`     List in long format. Ownership, Date/Time etc. (See below)
//!           For terminal output, a total sum of all the file sizes is output on
//!           a line before the long listing.
//!           If the file is a symbolic link the pathname of the linked-to file is
//!           preceded by ->
//!
//!    `-g`     in the long (`-l`) format output, the owner name is suppressed.
//!
//!    `-o`     List in long format, but omit the group id.
//!
//!    `-R`     Recursively list subdirectories encountered.
//!
//!    `-h`     When used with the `-l` option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte,
//!           Terabyte and Petabyte in order to reduce the number of digits to three or less
//!           using base 2 for sizes.
//!
//!    `-c`     Use time when file status was last changed for sorting or printing.
//!
//!    `-S`     Sort files by size
//!
//!    `-t`     Sort by time modified (most recently modified first) before
//!           sorting the operands by lexicographical order.
//!
//!    `-u`     Use time of last access, instead of last modification of the file
//!           for sorting (`-t`) or printing (`-l`).
//!
//!    `-f`     Output is not sorted.
//!
//!    `-r`     Reverse the order of the sort to get reverse lexicographical
//!           order or the oldest entries first.
//!           (or largest files last, if combined with sort by size)
//!
//!    `-T`     When used with the `-l` (lowercase letter 'ell') option, display
//!           complete time information for the file, including month, day,
//!           hour, minute, second, and year.
//!
//!    `-U`     Use time of created for sorting or printing.
//!

use crate::working_directory;
use chrono::DateTime;
use chrono::Local;
use chrono::Utc;
use std::fs;
use std::fs::DirEntry;
use std::fs::Permissions;
use std::io;
use std::io::Write;
use std::os::unix::fs::MetadataExt;
use std::os::unix::fs::PermissionsExt;
use std::time::SystemTime;

#[derive(Copy, Clone)]
enum SortBy {
    None,
    Size,
    Modified,
    LatsAccess,
    Created,
}
/// argument parameters
struct LsParams<'a> {
    /// write handle
    handle: &'a mut Box<dyn Write>,
    hidden: bool,
    long_list: bool,
    print_owner: bool,
    print_group: bool,
    recursive: bool,
    reverse: bool,
    sort_by: SortBy,
    time_display: SortBy,
    unit_suffixes: bool,
    is_longtime_format: bool,
}

/// Determine the parameters, and then call print_directory for given path
pub fn ls(args: &str, handle: &mut Box<dyn Write>) -> Result<(), Box<dyn std::error::Error>> {
    let mut params = LsParams {
        handle,
        hidden: false,
        long_list: false,
        print_owner: true,
        print_group: true,
        recursive: false,
        reverse: false,
        sort_by: SortBy::None,
        time_display: SortBy::Modified,
        unit_suffixes: false,
        is_longtime_format: false,
    };

    let mut directory = working_directory()?;
    //let args = ;
    for arg in args.split_whitespace() {
        let mut options = arg.chars();
        if options.next() == Some('-') {
            loop {
                match options.next() {
                    None | Some(' ') => break,
                    Some('a') => params.hidden = true,
                    Some('l') => if params.long_list == false {
                        params.long_list = true;
                    }
                    else {
                        params.hidden = true;
                    },
                    Some('C') => params.long_list = false,
                    Some('g') => {
                        params.long_list = true;
                        params.print_owner = false
                    }
                    Some('o') => {
                        params.long_list = true;
                        params.print_group = false
                    }
                    Some('R') => params.recursive = true,
                    Some('h') => params.unit_suffixes = true,
                    Some('c') => params.time_display = SortBy::Modified,
                    Some('S') => params.sort_by = SortBy::Size,
                    Some('t') => params.sort_by = params.time_display,
                    Some('u') => params.time_display = SortBy::LatsAccess,
                    Some('f') => params.sort_by = SortBy::None,
                    Some('r') => params.reverse = true,
                    Some('T') => params.is_longtime_format = true,
                    Some('U') => params.time_display = SortBy::Created,
                    Some(invalid) => {
                        eprintln!("Invalid argument {}", invalid);
                        return Ok(());
                    }
                }
            }
        } else {
            directory = arg.to_string();
        }
    }
    let ret = print_directory(directory, &mut params);
    match ret {
        Ok(()) => {}
        Err(error) => {
            eprintln!("Error: {}", error);
        }
    }
    Ok(())
}
/// Write the given directory information to the given file handle.
/// If necessary, navigate through subdirectories recursively.
#[cfg(not(docsrs))]
fn print_directory(
    directory: String,
    ls_params: &mut LsParams,
) -> Result<(), Box<dyn std::error::Error>> {
    if ls_params.recursive {
        writeln!(ls_params.handle, "\n{}", directory)?;
    }

    let mut paths: Vec<_> = fs::read_dir(directory.clone())?
        .map(|r| r.map_err(|e| Box::new(e) as Box<dyn std::error::Error>))
        .collect::<Result<Vec<_>, _>>()?;

    // calculate file_name_width
    // TODO: bu sadece kısa döküm için olmalı
    let width = longest_filename_length(&paths)?;

    //calculate dir size
    if ls_params.long_list {
        let size = sum_file_sizes(&paths, ls_params.hidden)?;
        writeln!(ls_params.handle, "total {}", size)?;
    }

    sort(&mut paths, &ls_params);

    // Short list
    if ls_params.long_list == false {
        write!(ls_params.handle, "\n")?;
    }


    for path in paths {
        let __filename = path.file_name();
        let _filename = __filename.to_str().ok_or("Invalid UTF-8 in file name")?;
        let file_type = path.file_type()?;
        let mut symbolic_filename = String::new();
        if file_type.is_symlink() {
            match fs::read_link(path.path()) {
                Ok(target) => {
                    symbolic_filename = target.to_str().ok_or("Invalid UTF-8 in file name")?.to_string();
                    symbolic_filename = format!(" -> {}", symbolic_filename);
                },
                Err(e) => eprintln!("Failed to read symlink target for {}: {}", _filename, e),
            }
        }
        let filename = format!("{}{}", _filename, symbolic_filename);

        if ls_params.hidden == false && filename.starts_with('.') {
            continue;
        }
        if ls_params.long_list == false {
            write!(ls_params.handle, "{:width$}", filename, width = width)?;
        } else {
            if let Ok(metadata) = path.metadata() {
                let file_len = if ls_params.unit_suffixes {
                    unit_suffixes(metadata.len())
                } else {
                    format!("{}", metadata.len())
                };
                let permissions = permission_text(metadata.permissions());
                let owner: String = match get_user_by_uid(metadata.uid()) {
                        Some(user) => user.name().to_string_lossy().into_owned(),
                        None => String::new(),
                    };

                let group: String = match get_group_by_gid(metadata.gid()) {
                    Some(a) => {
                        a.name().to_string_lossy().to_string()
                    },
                    None => String::new()
                };

                let file_date = match ls_params.time_display {
                    SortBy::LatsAccess => metadata.accessed(),
                    SortBy::Created => metadata.created(),
                    _ => metadata.modified(),
                };
                //Convert file modification time from SystemTime to DateTime<Utc>
                let utc_time: DateTime<Utc> = file_date?.into();
                // Convert UTC time to local time
                let local_time: DateTime<Local> = utc_time.with_timezone(&Local);
                let file_date = if ls_params.is_longtime_format {
                    format!("{}", local_time.format("%Y-%m-%d %H:%M:%S"))
                } else {
                    format!("{}", local_time.format("%d/%m/%Y %H:%M"))
                };

                let is_dir = path.path().is_dir();
                //                    permissions.chars().next() == Some('d');

                // Using format! to handle dynamic width
                let formatted_owner = if ls_params.print_owner {
                    format!("{:10}", owner)
                } else {
                    String::new()
                };
                let formatted_group = if ls_params.print_group {
                    format!("{:10}", group)
                } else {
                    String::new()
                };

                writeln!(
                    ls_params.handle,
                    "{} {} {} {:>7} {:3} {} {}",
                    permissions,
                    formatted_owner,
                    formatted_group,
                    file_len,
                    if is_dir { "dir" } else { "   " }, // Assuming you want "dir" for directories, space for files
                    file_date,
                    filename
                )
                    .expect("Failed to write to handle");
            }
        }
    }

    if ls_params.long_list == false {
        writeln!(ls_params.handle, "")?;
    }
    if ls_params.recursive {
        let paths = fs::read_dir(directory.clone());
        match paths {
            Ok(paths) => {
                for path in paths {
                    let path = path?;
                    let is_dir = path.path().is_dir();
                    if is_dir {
                        let filename = path.file_name();
                        let dir_name = filename.to_str().ok_or("Invalid UTF-8 in file name")?;
                        print_directory(
                            format!("{directory}/{}", &dir_name.to_string()),
                            ls_params,
                        )?;
                    }
                }
            }
            Err(error) => {
                if error.kind() == io::ErrorKind::PermissionDenied {
                    return Ok(());
                }
                eprintln!("{} {}", directory, error);
                return Ok(());
            }
        }
    }
    Ok(())
}
#[cfg(docsrs)]
fn print_directory(
    directory: String,
    ls_params: &mut LsParams,
) -> Result<(), Box<dyn std::error::Error>> {
    if ls_params.recursive {
        writeln!(ls_params.handle, "\n{}", directory)?;
    }
        // line intentionally marked comment
    //let mut paths: Vec<_> = fs::read_dir(directory.clone())?
        .map(|r| r.map_err(|e| Box::new(e) as Box<dyn std::error::Error>))
        .collect::<Result<Vec<_>, _>>()?;

    // calculate file_name_width
    let width = longest_filename_length(&paths)?;

    //calculate dir size
    if ls_params.long_list {
        let size = sum_file_sizes(&paths, ls_params.hidden)?;
        writeln!(ls_params.handle, "total {}", size)?;
    }

    sort(&mut paths, &ls_params);

    // Short list
    if ls_params.long_list == false {
        write!(ls_params.handle, "\n")?;
    }


    for path in paths {
        let __filename = path.file_name();
        let _filename = __filename.to_str().ok_or("Invalid UTF-8 in file name")?;
        let file_type = path.file_type()?;
        let mut symbolic_filename = String::new();
        if file_type.is_symlink() {
            match fs::read_link(path.path()) {
                Ok(target) => {
                    symbolic_filename = target.to_str().ok_or("Invalid UTF-8 in file name")?.to_string();
                    symbolic_filename = format!(" -> {}", symbolic_filename);
                },
                Err(e) => eprintln!("Failed to read symlink target for {}: {}", _filename, e),
            }
        }
        let filename = format!("{}{}", _filename, symbolic_filename);

        if ls_params.hidden == false && filename.starts_with('.') {
            continue;
        }
        if ls_params.long_list == false {
            write!(ls_params.handle, "{:width$}", filename, width = width)?;
        } else {
            if let Ok(metadata) = path.metadata() {
                let file_len = if ls_params.unit_suffixes {
                    unit_suffixes(metadata.len())
                } else {
                    format!("{}", metadata.len())
                };
                let permissions = permission_text(metadata.permissions());
                let owner: String = id_to_username(metadata.uid())?;
                let group = id_to_username(metadata.gid())?;

                let file_date = match ls_params.time_display {
                    SortBy::LatsAccess => metadata.accessed(),
                    SortBy::Created => metadata.created(),
                    _ => metadata.modified(),
                };
                //Convert file modification time from SystemTime to DateTime<Utc>
                let utc_time: DateTime<Utc> = file_date?.into();
                // Convert UTC time to local time
                let local_time: DateTime<Local> = utc_time.with_timezone(&Local);
                let file_date = if ls_params.is_longtime_format {
                    format!("{}", local_time.format("%Y-%m-%d %H:%M:%S"))
                } else {
                    format!("{}", local_time.format("%d/%m/%Y %H:%M"))
                };

                let is_dir = path.path().is_dir();
                //                    permissions.chars().next() == Some('d');

                // Using format! to handle dynamic width
                let formatted_owner = if ls_params.print_owner {
                    format!("{:10}", owner)
                } else {
                    String::new()
                };
                let formatted_group = if ls_params.print_group {
                    format!("{:10}", group)
                } else {
                    String::new()
                };

                writeln!(
                    ls_params.handle,
                    "{} {} {} {:>7} {:3} {} {}",
                    permissions,
                    formatted_owner,
                    formatted_group,
                    file_len,
                    if is_dir { "dir" } else { "   " }, // Assuming you want "dir" for directories, space for files
                    file_date,
                    filename
                )
                    .expect("Failed to write to handle");
            }
        }
    }

    if ls_params.long_list == false {
        writeln!(ls_params.handle, "")?;
    }
    if ls_params.recursive {
        //line intentionally marked comment
        //let paths = fs::read_dir(directory.clone());
        match paths {
            Ok(paths) => {
                for path in paths {
                    let path = path?;
                    let is_dir = path.path().is_dir();
                    if is_dir {
                        let filename = path.file_name();
                        let dir_name = filename.to_str().ok_or("Invalid UTF-8 in file name")?;
                        print_directory(
                            format!("{directory}/{}", &dir_name.to_string()),
                            ls_params,
                        )?;
                    }
                }
            }
            Err(error) => {
                if error.kind() == io::ErrorKind::PermissionDenied {
                    return Ok(());
                }
                eprintln!("{} {}", directory, error);
                return Ok(());
            }
        }
    }
    Ok(())
}
/// Sort directory vector by given field
fn sort(paths: &mut Vec<DirEntry>, ls_params: &LsParams) {
    match ls_params.sort_by {
        SortBy::None => {
            paths.sort_by_key(|dir| {
                dir.file_name()
                    .into_string()
                    .unwrap_or_else(|_| String::from(""))
            });
            if ls_params.reverse {
                paths.reverse();
            }
        }
        SortBy::Size => {
            paths.sort_by_key(|dir| dir.metadata().map(|m| m.len()).unwrap_or(0));
            if ls_params.reverse == false {
                paths.reverse();
            }
        }
        SortBy::Modified => {
            paths.sort_by(|a, b| {
                let a_time = a.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH);
                let b_time = b.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH);
                // To reverse the order, we swap b and a.
                if ls_params.reverse {
                    a_time.cmp(&b_time)
                } else {
                    a_time.cmp(&b_time)
                }
            });

        }
        SortBy::LatsAccess => {
            paths.sort_by(|a, b| {
                let time_a = a
                    .metadata()
                    .and_then(|m| m.accessed())
                    .unwrap_or(SystemTime::UNIX_EPOCH);
                let time_b = b
                    .metadata()
                    .and_then(|m| m.accessed())
                    .unwrap_or(SystemTime::UNIX_EPOCH);
                if ls_params.reverse {
                    time_a.cmp(&time_b)
                } else {
                    time_b.cmp(&time_a)
                }
                // To reverse the order, we swap b and a.
            });
        }
        SortBy::Created => {
            paths.sort_by(|a, b| {
                let time_a = a
                    .metadata()
                    .and_then(|m| m.created())
                    .unwrap_or(SystemTime::UNIX_EPOCH);
                let time_b = b
                    .metadata()
                    .and_then(|m| m.created())
                    .unwrap_or(SystemTime::UNIX_EPOCH);
                if ls_params.reverse {
                    time_a.cmp(&time_b)
                } else {
                    time_b.cmp(&time_a)
                }
            });
        }
    }
}


/// permission field to text
fn permission_text(permissions: Permissions) -> String {
    let mut perms = permissions.mode();
    let mut retval = String::new();
    for _i in 0..3 {
        let p = perms & 0o7;
        retval.push(if (p & 1) > 0 { 'x' } else { '-' });
        retval.push(if (p & 2) > 0 { 'w' } else { '-' });
        retval.push(if (p & 4) > 0 { 'r' } else { '-' });
        perms >>= 3;
    }
    retval.push(
        if perms == 32 { 'd' }     // Directory
            else if perms == 80 { 'l' } // symbolic-link file
            else { '-' }
    );
    // String returns in reverse order
    retval.chars().rev().collect::<String>()
}

/// Unit with suffixes: in Byte, Kilobyte, Megabyte, Gigabyte.
///
///  for ls -h option.
///
/// Example:
///
///      1025 -> 1KB

fn unit_suffixes(size: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if size >= GB {
        format!("{:.2}G", size as f64 / GB as f64)
    } else if size >= MB {
        format!("{:.1}M", size as f64 / MB as f64)
    } else if size >= KB {
        format!("{:.0}K", size as f64 / KB as f64)
    } else {
        format!("{}B", size)
    }
}

/// longest filename length in given directory
fn longest_filename_length(entries: &[DirEntry]) -> io::Result<usize> {
    entries
        .iter()
        .map(|entry| {
            entry
                .file_name()
                .to_str()
                .ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8 in file name")
                })
                .map(|name| name.len())
        })
        .collect::<io::Result<Vec<usize>>>()?
        .into_iter()
        .max()
        .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "No valid file names found"))
}

use std::path::PathBuf;
use users::{get_group_by_gid, get_user_by_uid};
use nix::sys::stat::lstat;

/// Returns the number of 512-byte blocks allocated for the file.
/// Does not follow symbolic links; analyzes the link itself.
#[cfg(not(docsrs))]
fn get_block_size(path: &PathBuf) -> io::Result<u64> {
    let stat = lstat(path)?;
    let blocks_allocated = stat.st_blocks as u64;
    Ok(blocks_allocated)
}

#[cfg(docsrs)]
fn get_block_size(path: &PathBuf) -> io::Result<u64> {
    Ok(0)
}

/// Calculates the total size of files in the given directory entries.
///
/// Ignores hidden files (starting with '.') if `hidden` is false.
/// Returns the sum of block sizes in bytes.
fn sum_file_sizes(entries: &[fs::DirEntry], hidden: bool) -> io::Result<u64> {
    let mut total_size: u64 = 0;

    for entry in entries {
        // Get the file name as an OsString
        let path_os:PathBuf = entry.path();

        // Try to convert OsString to &str for checking hidden files
        if let Some(path_str) = path_os.to_str() {
            // Skip hidden files if hidden is false
            if !hidden && path_str.starts_with('.') {
                continue;
            }
        } else {
            // If filename is not valid UTF-8, skip or handle it (örneğin, logla)
            continue; // Ya da başka bir strateji: total_size'a ekleme yapmadan geç
        }

        // Get the block size for the file
        let block_size = get_block_size(&path_os)?;
        total_size += block_size;
    }

    Ok(total_size)
}