Skip to content

Commit

Permalink
cat 実装
Browse files Browse the repository at this point in the history
  • Loading branch information
zztkm committed Jun 1, 2024
1 parent e96d145 commit 87642c0
Show file tree
Hide file tree
Showing 5 changed files with 331 additions and 1 deletion.
237 changes: 237 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ version = "0.1.0"
edition = "2021"

[dependencies]
clap = { version = "4.5.4", features = ["derive"] }
11 changes: 11 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.PHONY: all
all:
cargo build

.PHONY: fmt
fmt:
cargo fmt

.PHONY: lint
lint:
cargo clippy
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,37 @@

zztkm tool box.

Rust の練習がてら Linux コマンドを再実装したり、自分がほしいコマンドを実装したりしています。

## Usage

```bash
# 引数がない場合は標準入力から読み取ります
$ cat README.md | cargo run -- cat at 01:46:25
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/ztb cat`
# ztb

zztkm tool box.

# 引数ありの場合
$ cargo run -- cat README.md Makefile at 01:48:46
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/ztb cat README.md Makefile`
# ztb

zztkm tool box.

.PHONY: all
all:
cargo build

.PHONY: fmt
fmt:
cargo fmt

.PHONY: lint
lint:
cargo clippy
```

49 changes: 48 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,50 @@
use clap::{Parser, Subcommand};
use std::io::{Read, Write};

#[derive(Parser)]
struct Cli {
#[command(subcommand)]
command: Commands,
}

#[derive(Subcommand)]
enum Commands {
Cat { files: Option<Vec<String>> },
}

fn main() {
println!("Hello, world!");
let cli = Cli::parse();

match &cli.command {
Commands::Cat { files } => {
if let Some(files) = files {
// stdout のロックを取得
let stdout = std::io::stdout();
let mut stdout = stdout.lock();

// files を入力順に stdout に出力する
// 最後のファイルは改行をしない
let mut iter = files.iter().peekable();
while let Some(file) = iter.next() {
let content = std::fs::read_to_string(file).unwrap();
if iter.peek().is_none() {
write!(&mut stdout, "{}", content).unwrap();
} else {
writeln!(&mut stdout, "{}", content).unwrap();
}
}
} else {
// files の指定がない場合は標準入力から読み取る
let mut buffer = String::new();
let stdin = std::io::stdin();
let mut stdin = stdin.lock();
stdin.read_to_string(&mut buffer).unwrap();

// 標準出力に書き込む
let stdout = std::io::stdout();
let mut stdout = stdout.lock();
write!(&mut stdout, "{}", buffer).unwrap();
}
}
}
}

0 comments on commit 87642c0

Please sign in to comment.