tmux-copyrat/src/main.rs

48 lines
1.3 KiB
Rust
Raw Normal View History

2020-05-24 21:02:11 +02:00
use clap::Clap;
2020-05-25 23:32:37 +02:00
use std::fs::OpenOptions;
use std::io::prelude::*;
2020-05-24 21:02:11 +02:00
use std::io::{self, Read};
2020-06-02 20:03:16 +02:00
2020-05-27 10:04:42 +02:00
use copyrat::{run, CliOpt};
2020-06-02 20:03:16 +02:00
fn main() {
2020-05-27 10:04:42 +02:00
let opt = CliOpt::parse();
2020-05-24 21:02:11 +02:00
// Copy the pane contents (piped in via stdin) into a buffer, and split lines.
let stdin = io::stdin();
let mut handle = stdin.lock();
let mut buffer = String::new();
handle.read_to_string(&mut buffer).unwrap();
2020-05-25 23:32:37 +02:00
// Execute copyrat over the buffer (will take control over stdout).
// This returns the selected matches.
2020-05-27 10:04:42 +02:00
let selections: Vec<(String, bool)> = run(buffer, &opt);
// Early exit, signaling no selections were found.
if selections.is_empty() {
std::process::exit(1);
}
let output = selections
.iter()
.map(|(text, _)| text.as_str())
.collect::<Vec<&str>>()
.join("\n");
2020-05-25 23:32:37 +02:00
// Write output to a target_path if provided, else print to original stdout.
match opt.target_path {
None => println!("{}", output),
Some(target) => {
let mut file = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(target)
.expect("Unable to open the target file");
file.write(output.as_bytes()).unwrap();
}
}
2020-06-02 20:03:16 +02:00
}