Skip to content

Commit 3b46be9

Browse files
committed
Refactor the ls command to use the cli macro
1 parent 0835e5e commit 3b46be9

File tree

2 files changed

+277
-307
lines changed

2 files changed

+277
-307
lines changed

src/bin/ls/main.rs

Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,38 +6,34 @@ use rustix::{
66
fs::{Dir, Mode, OFlags, open},
77
termios::tcgetwinsize,
88
};
9-
use std::io::{BufWriter, Stdout, Write, stdout};
9+
use std::io::{self, BufWriter, stdout};
1010

11-
const VERSION: &str = coreutils::version_text!("ls");
12-
const HELP: &str = coreutils::help_text!("ls");
1311
const CURRENT_DIR_PATH: &str = ".";
1412

1513
fn main() -> Result {
16-
let mut out = BufWriter::new(stdout());
14+
let mut stdout = stdout();
1715
let winsize = get_win_size();
18-
let (cfg, help_or_version) =
19-
settings::parse_arguments(winsize.ws_col, &mut out, HELP, VERSION)?;
20-
21-
if !help_or_version {
22-
drop(cfg);
23-
let fd = open(
24-
CURRENT_DIR_PATH,
25-
OFlags::DIRECTORY | OFlags::RDONLY,
26-
Mode::RUSR,
27-
)?;
28-
29-
let dir = Dir::new(fd)?;
30-
31-
// bad bad bad
32-
// FIXME: do not allocate
33-
let names = dir
34-
.filter_map(Result::ok)
35-
.map(|entry| entry.file_name().to_string_lossy().into_owned())
36-
.filter(|entry| !entry.starts_with('.'))
37-
.collect::<Vec<_>>();
38-
39-
print_all(names, out)?;
40-
}
16+
let _cfg = settings::parse_arguments(winsize.ws_col, &mut stdout)?;
17+
18+
let fd = open(
19+
CURRENT_DIR_PATH,
20+
OFlags::DIRECTORY | OFlags::RDONLY,
21+
Mode::RUSR,
22+
)?;
23+
24+
let dir = Dir::new(fd)?;
25+
26+
// bad bad bad
27+
// FIXME: do not allocate
28+
let names = dir
29+
.filter_map(Result::ok)
30+
.map(|entry| entry.file_name().to_string_lossy().into_owned())
31+
.filter(|entry| !entry.starts_with('.'))
32+
.collect::<Vec<_>>();
33+
34+
let mut stdout = BufWriter::new(stdout);
35+
36+
print_all(names, &mut stdout)?;
4137

4238
Ok(())
4339
}
@@ -49,7 +45,7 @@ fn get_win_size() -> rustix::termios::Winsize {
4945

5046
// FIXME: This algorithm to print out lines is incredibly simplistic
5147
// and slightly worse than the one used in GNU's ls.
52-
fn print_all(cols: Vec<String>, stdout: BufWriter<Stdout>) -> Result {
48+
fn print_all<O: io::Write>(cols: Vec<String>, stdout: &mut O) -> Result {
5349
const MIN_COLUMN_WIDTH: u16 = 3;
5450

5551
let len = cols.len();
@@ -63,7 +59,7 @@ fn print_all(cols: Vec<String>, stdout: BufWriter<Stdout>) -> Result {
6359
print_into_columns(cols.iter().map(String::as_str), max_cols, stdout)
6460
}
6561

66-
fn print_into_columns<I>(iter: I, columns: usize, mut stdout: BufWriter<Stdout>) -> Result
62+
fn print_into_columns<I, O: io::Write>(iter: I, columns: usize, stdout: &mut O) -> Result
6763
where
6864
I: IntoIterator<Item: AsRef<str> + core::fmt::Display>,
6965
{

0 commit comments

Comments
 (0)