From 52def0a32d4d1bf4b5a8be9c567cf4d180d70885 Mon Sep 17 00:00:00 2001 From: emma Date: Mon, 15 Jan 2024 16:30:00 -0700 Subject: [PATCH] Makefile, fop(1): added argument parsing and -d option --- Makefile | 2 +- src/fop.rs | 37 +++++++++++++++++++++++++++++-------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index bee2f00..33cc695 100644 --- a/Makefile +++ b/Makefile @@ -65,7 +65,7 @@ sysexits: build libgetopt: src/getopt-rs/lib.rs $(RUSTC) $(RUSTCFLAGS) --crate-type=lib --crate-name=getopt \ - -o build/o/libgetopt.rlib src/lib.rs + -o build/o/libgetopt.rlib src/getopt-rs/lib.rs false: src/false.rs build $(RUSTC) $(RUSTFLAGS) -o build/bin/false src/false.rs diff --git a/src/fop.rs b/src/fop.rs index 1ed31fd..cd04f85 100644 --- a/src/fop.rs +++ b/src/fop.rs @@ -18,33 +18,54 @@ use std::{ env::args, - io::{ stdin, Write }, + io::{ Read, stdin, Write }, process::{ Command, exit, Stdio }, }; extern crate sysexits; +extern crate getopt; + +use getopt::{ Opt, Parser }; use sysexits::{ EX_DATAERR, EX_USAGE }; fn main() { let argv = args().collect::>(); + let mut d = '␞'; + let mut arg_parser = Parser::new(&argv, "d:"); - argv.get(2).unwrap_or_else(|| { + while let Some(opt) = arg_parser.next() { + match opt { + Ok(Opt('d', Some(arg))) => { + let arg_char = arg.chars().collect::>(); + 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; + + argv.get(command_arg).unwrap_or_else(|| { eprintln!("Usage: {} index command [args...]", argv[0]); exit(EX_USAGE); }); - let index = argv[1].parse::().unwrap_or_else(|_| { + let index = argv[index_arg].parse::().unwrap_or_else(|_| { eprintln!("{}: {}: Not an integer.", argv[0], argv[1]); exit(EX_DATAERR); }); let mut buf = String::new(); - stdin().read_line(&mut buf).unwrap(); - let mut fields = buf.split('␞').collect::>(); + stdin().read_to_string(&mut buf).unwrap(); + let mut fields = buf.split(d).collect::>(); - let opts = argv.iter().clone().skip(3).collect::>(); + let opts = argv.iter().clone().skip(command_arg + 1).collect::>(); - let mut spawned = Command::new(argv.get(2).unwrap()) + let mut spawned = Command::new(argv.get(command_arg).unwrap()) .args(opts) .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -71,5 +92,5 @@ fn main() { fields[index] = &new_field; - print!("{}", fields.join("␞")); + print!("{}", fields.join(&d.to_string())); }