1
0
forked from bonsai/harakit
coreutils/src/fop.rs

97 lines
2.6 KiB
Rust
Raw Normal View History

2023-12-27 22:44:19 +00:00
/*
* Copyright (c) 2023 Emma Tebibyte <emma@tebibyte.media>
* SPDX-License-Identifier: AGPL-3.0-or-later
*
* This program 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.
*
* This program 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::args,
io::{ Read, stdin, Write },
2023-12-27 22:44:19 +00:00
process::{ Command, exit, Stdio },
};
extern crate sysexits;
extern crate getopt;
use getopt::{ Opt, Parser };
2023-12-28 05:47:06 +00:00
use sysexits::{ EX_DATAERR, EX_USAGE };
2023-12-27 22:44:19 +00:00
fn main() {
let argv = args().collect::<Vec<String>>();
let mut d = '␞';
let mut arg_parser = Parser::new(&argv, "d:");
while let Some(opt) = arg_parser.next() {
match opt {
Ok(Opt('d', Some(arg))) => {
let arg_char = arg.chars().collect::<Vec<char>>();
if arg_char.len() > 1 {
eprintln!("{}: {}: Not a character.", argv[0], arg);
exit(EX_USAGE);
} else { d = arg_char[0]; }
},
_ => {},
};
}
let index_arg = arg_parser.index();
let command_arg = arg_parser.index() + 1;
2023-12-27 22:44:19 +00:00
argv.get(command_arg).unwrap_or_else(|| {
2023-12-29 05:42:05 +00:00
eprintln!("Usage: {} index command [args...]", argv[0]);
exit(EX_USAGE);
});
let index = argv[index_arg].parse::<usize>().unwrap_or_else(|_| {
2023-12-29 05:42:05 +00:00
eprintln!("{}: {}: Not an integer.", argv[0], argv[1]);
exit(EX_DATAERR);
});
2023-12-27 22:44:19 +00:00
let mut buf = String::new();
stdin().read_to_string(&mut buf).unwrap();
let mut fields = buf.split(d).collect::<Vec<&str>>();
2023-12-27 22:44:19 +00:00
let opts = argv.iter().clone().skip(command_arg + 1).collect::<Vec<&String>>();
2023-12-27 22:44:19 +00:00
let mut spawned = Command::new(argv.get(command_arg).unwrap())
2023-12-27 22:44:19 +00:00
.args(opts)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
let field = fields.get(index).unwrap_or_else(|| {
eprintln!(
"{}: {}: No such index in input.",
argv[0],
index.to_string()
);
2023-12-28 05:47:06 +00:00
exit(EX_DATAERR);
2023-12-27 22:44:19 +00:00
});
if let Some(mut child_stdin) = spawned.stdin.take() {
child_stdin.write_all(field.as_bytes()).unwrap();
drop(child_stdin);
}
let output = spawned.wait_with_output().unwrap();
let new_field = String::from_utf8(output.stdout).unwrap();
fields[index] = &new_field;
print!("{}", fields.join(&d.to_string()));
2023-12-27 22:44:19 +00:00
}