101 lines
2.6 KiB
Rust
101 lines
2.6 KiB
Rust
// Copyright (c) 2022 YAC
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
/* This file is part of YAC coreutils.
|
|
*
|
|
* YAC coreutils is free software: you can redistribute it and/or modify it
|
|
* under the terms of the GNU Affero General Public License as published by the
|
|
* Free Software Foundation, either version 3 of the License, or (at your
|
|
* option) any later version.
|
|
*
|
|
* YAC coreutils is distributed in the hope that it will be useful, but WITHOUT
|
|
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
|
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
|
* details.
|
|
*
|
|
* You should have received a copy of the GNU Affero General Public License
|
|
* along with this program. If not, see https://www.gnu.org/licenses/.
|
|
*/
|
|
|
|
use std::env;
|
|
use std::fs::{File, read_to_string};
|
|
use std::io;
|
|
use std::io::{ BufRead, Read };
|
|
use std::str;
|
|
|
|
use arg::Args;
|
|
|
|
use sysexits::ExitCode;
|
|
|
|
#[derive(Args, Debug)]
|
|
struct Arguments {
|
|
#[arg(short = "u")]
|
|
u: bool,
|
|
|
|
paths: Vec<String>,
|
|
}
|
|
|
|
fn main() -> ExitCode {
|
|
let mut arguments = env::args().collect::<Vec<String>>();
|
|
let argv0 = arguments.remove(0);
|
|
|
|
let mut args = Arguments::from_args(arguments
|
|
.iter()
|
|
.map(String::as_str)
|
|
.collect::<Vec<&str>>()
|
|
).unwrap();
|
|
|
|
let mut output = String::new();
|
|
|
|
if args.paths.is_empty() { args.paths.push("-".to_string()); }
|
|
|
|
while args.u {
|
|
for path in &args.paths {
|
|
if path == "-" {
|
|
loop {
|
|
let mut buf = String::new();
|
|
match io::stdin().lock().read_line(&mut buf) {
|
|
Ok(bytes) => {
|
|
if bytes == 0 { break };
|
|
print!("{}", buf);
|
|
},
|
|
Err(err) => println!("{}", err),
|
|
};
|
|
}
|
|
} else {
|
|
let mut input = String::new();
|
|
match File::open(path) {
|
|
Ok(input) => {},
|
|
Err(_) => {
|
|
println!("{}: {}: No such file or directory.", &argv0, path);
|
|
return ExitCode::NoInput;
|
|
},
|
|
};
|
|
}
|
|
}
|
|
return ExitCode::Ok;
|
|
}
|
|
|
|
for path in args.paths {
|
|
if path == "-" {
|
|
let mut bytes: Vec<u8> = Vec::new();
|
|
io::stdin().lock().read_to_end(&mut bytes).unwrap();
|
|
|
|
for byte in &bytes {
|
|
output.push_str(str::from_utf8(&[byte.to_owned()]).unwrap());
|
|
}
|
|
} else {
|
|
match read_to_string(&path) {
|
|
Ok(contents) => { output.push_str(&contents) },
|
|
Err(_) => {
|
|
eprintln!("{}: {}: No such file or directory.", &argv0, &path);
|
|
return ExitCode::NoInput;
|
|
},
|
|
};
|
|
}
|
|
print!("{}", output);
|
|
output.clear();
|
|
}
|
|
ExitCode::Ok
|
|
}
|