Skip to content

Commit acedcf9

Browse files
committed
Add basic cat command implementation
1 parent e311c9d commit acedcf9

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

docs/cat.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Usage: cat [OPTION]... [FILE]...
2+
Concatenate FILE(s) to standard output.

src/bin/cat.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use std::{
2+
fs::File,
3+
io::{self, BufReader, BufWriter, Write, stdin, stdout},
4+
};
5+
6+
use puppyutils::{Result, cli};
7+
8+
pub fn main() -> Result {
9+
let mut stdout = stdout();
10+
let mut files = Vec::new();
11+
12+
cli! {
13+
"cat", stdout, #error
14+
Value(value) => {
15+
files.push(value.to_owned());
16+
}
17+
};
18+
19+
let mut stdout = BufWriter::new(stdout);
20+
21+
// FIXME: so much repetition, can we do better?
22+
if files.is_empty() {
23+
let mut stdin = BufReader::new(stdin());
24+
io::copy(&mut stdin, &mut stdout)?;
25+
} else {
26+
for file_path in files {
27+
// "-" means stdin
28+
if file_path == "-" {
29+
// TODO: maybe the handling for - should be at the arg parser stage?
30+
let mut stdin = BufReader::new(stdin());
31+
io::copy(&mut stdin, &mut stdout)?;
32+
} else {
33+
let mut reader = BufReader::new(File::open(&file_path)?); // Is it fine to error here? or should we keep going
34+
io::copy(&mut reader, &mut stdout)?;
35+
}
36+
}
37+
}
38+
39+
stdout.flush()?;
40+
41+
Ok(())
42+
}

src/main.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::{borrow::Cow, env::current_exe, os::unix::ffi::OsStrExt, path::PathBuf}
33
use puppyutils::{Exit, Result};
44

55
pub mod bin {
6+
pub mod cat;
67
pub mod r#false;
78
#[path = "ls/main.rs"]
89
pub mod ls;
@@ -25,6 +26,7 @@ fn main() -> Result {
2526
.ok_or::<Exit>("Failed to get util name".into())?;
2627

2728
match util.as_bytes() {
29+
b"calse" => bin::cat::main(),
2830
b"false" => bin::r#false::main(),
2931
b"ls" => bin::ls::main(),
3032
b"mkdir" => bin::mkdir::main(),

0 commit comments

Comments
 (0)