Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

paste: Implment #163

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DragonflyBSD.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
"nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
1 change: 1 addition & 0 deletions FreeBSD.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
"nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
1 change: 1 addition & 0 deletions Fuchsia.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
# "nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
1 change: 1 addition & 0 deletions Haiku.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ members = [
"nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
1 change: 1 addition & 0 deletions Illumos.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
"nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
1 change: 1 addition & 0 deletions Linux.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
"nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
1 change: 1 addition & 0 deletions MacOS.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
"nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
1 change: 1 addition & 0 deletions NetBSD.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
"nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
1 change: 1 addition & 0 deletions OpenBSD.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
"nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ cargo install --path .
| nl | | | X |
| nohup | | | X |
| od | X | | |
| paste | X | | |
| paste | | | X |
| patch | X | | |
| printf | | | X |
| pwd | | | X |
Expand Down Expand Up @@ -172,6 +172,7 @@ Without them, this project would not be what it is today.
- [@bojan88](https://github.com/bojan88) - _Bojan Đurđević_
- [@Celeo](https://github.com/Celeo) - _Celeo_
- [@FedericoPonzi](https://github.com/FedericoPonzi) - _Federico Ponzi_
- [@wojciech-graj](https://github.com/wojciech-graj) - _Wojciech Graj_
- [@Larisho](https://github.com/Larisho) - _Gab David_
- [@silverweed](https://github.com/silverweed) - _Giacomo Parolini_
- [@marcospb19](https://github.com/marcospb19) - _João M. Bezerra_
Expand Down
1 change: 1 addition & 0 deletions Unix.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ members = [
"nice",
"nl",
"nohup",
"paste",
"printf",
"pwd",
"rm",
Expand Down
22 changes: 22 additions & 0 deletions paste/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "paste"
version = "0.1.0"
authors = ["Wojciech Graj <[email protected]>"]
license = "MPL-2.0-no-copyleft-exception"
build = "build.rs"
edition = "2021"
rust-version = "1.61.0"
description = """
Concatenate lines from files, delimited by TABs.

Use - as a FILE to read from standard input. An absence of FILEs will be treated as -.
"""

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = { version = "3.0.0", features = ["cargo", "wrap_help"] }

[build-dependencies]
clap = { version = "3.0.0", features = ["cargo"] }
clap_generate = "3.0.0"
36 changes: 36 additions & 0 deletions paste/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use std::{env, fs::File, io::BufWriter};

use clap::crate_name;
use clap_generate::{Generator, Shell};

#[path = "src/cli.rs"]
mod cli;

fn main() {
let mut app = cli::create_app();
app.set_bin_name(crate_name!());

let out_dir = match env::var("OUT_DIR") {
Ok(dir) => dir,
Err(err) => {
eprintln!("No OUT_DIR: {}", err);
return;
},
};

let shells = [Shell::Bash, Shell::Elvish, Shell::Fish, Shell::PowerShell, Shell::Zsh];

for shell in shells {
let file_name = format!("{}/{}", out_dir, shell.file_name(app.get_name()));
let mut file = BufWriter::new(
File::options()
.read(true)
.write(true)
.create(true)
.open(file_name)
.expect("Unable to open file"),
);

shell.generate(&app, &mut file)
}
}
30 changes: 30 additions & 0 deletions paste/src/cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use clap::{crate_authors, crate_description, crate_name, crate_version, App, Arg};

pub(crate) fn create_app<'help>() -> App<'help> {
App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.mut_arg("help", |help| help.help("Display help information.").short('?'))
.mut_arg("version", |v| v.help("Display version information."))
.arg(Arg::new("FILE").help("").multiple_occurrences(true))
.arg(
Arg::new("delimiters")
.help("Loop through characters from LIST instead of using TABs.")
.long("delimiters")
.short('d')
.value_name("LIST"),
)
.arg(
Arg::new("serial")
.help("Apply paste to lines from each file separately.")
.long("serial")
.short('s'),
)
.arg(
Arg::new("zero-terminated")
.help("Replace newline with NUL as line delimiter.")
.long("zero-terminated")
.short('z'),
)
}
128 changes: 128 additions & 0 deletions paste/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
use std::{error::Error, fs::File, io};

use clap::ArgMatches;

mod cli;

fn main() {
let matches = cli::create_app().get_matches();

let flags = PasteFlags::from_matches(&matches);

let mut readers: Vec<Box<dyn io::BufRead>> = match matches.values_of("FILE") {
None => vec![Box::new(io::BufReader::new(io::stdin()))],
Some(filenames) => filenames
.map(|filename| -> Box<dyn io::BufRead> {
match filename {
"-" => Box::new(io::BufReader::new(io::stdin())),
filename => match File::open(filename) {
Ok(file) => Box::new(io::BufReader::new(file)),
Err(why) => {
eprintln!("paste: {}: {}", filename, why);
std::process::exit(1);
},
},
}
})
.collect(),
};

std::process::exit(match paste(&mut readers, &flags) {
Ok(_) => 0,
Err(why) => {
eprintln!("paste: {}", why);
1
},
});
}

fn paste(
readers: &mut Vec<Box<dyn io::BufRead>>, flags: &PasteFlags,
) -> Result<(), Box<dyn Error>> {
let line_terminator = if flags.zero_terminated { b'\0' } else { b'\n' };

let mut out_line_no = 0;
loop {
let mut flag = false;
let mut out_buf: Vec<u8> = Vec::new();
let mut inp_line_no = 0;
loop {
let reader_idx = if flags.serial { out_line_no } else { inp_line_no };
if reader_idx >= readers.len() {
break;
}

let mut inp_buf: Vec<u8> = Vec::new();
match (*readers[reader_idx]).read_until(line_terminator, &mut inp_buf) {
Ok(0) => {
// EOF
if flags.serial {
break;
}
},
Ok(_) => {
if pop_if_last(&mut inp_buf, b'\n') {
pop_if_last(&mut inp_buf, b'\t');
}
flag = true;
},
Err(why) => {
return Err(Box::new(why));
},
}

if inp_line_no != 0 {
match &flags.delimiters {
None => out_buf.push(b'\t'),
Some(list) => out_buf.extend([list[(inp_line_no - 1) % list.len()] as u8]),
};
}

out_buf.extend(inp_buf);

inp_line_no += 1;
}
if !flag {
break;
}
let s = match String::from_utf8(out_buf) {
Ok(string) => string,
Err(why) => {
return Err(Box::new(why));
},
};
println!("{}", s);
out_line_no += 1;
}
Ok(())
}

// Pop the last element from `buf` if it equals `tgt`
fn pop_if_last<T>(buf: &mut Vec<T>, tgt: T) -> bool
where
T: Copy + std::cmp::PartialEq,
{
if let Some(last) = buf.last().copied() {
if last == tgt {
buf.pop();
return true;
}
}
false
}

struct PasteFlags {
pub delimiters: Option<Vec<char>>,
pub serial: bool,
pub zero_terminated: bool,
}

impl PasteFlags {
pub fn from_matches(matches: &ArgMatches) -> Self {
PasteFlags {
delimiters: matches.get_one::<String>("delimiters").map(|list| list.chars().collect()),
serial: matches.is_present("serial"),
zero_terminated: matches.is_present("zero-terminated"),
}
}
}