tmux-copyrat/src/bin/copyrat.rs

44 lines
1.2 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
2021-03-21 07:12:14 +01:00
use copyrat::{config::CliOpt, run, ui::Selection};
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).
2021-03-13 18:51:31 +01:00
// This returns the selected matche.
let selection: Option<Selection> = run(buffer, &opt);
2020-05-27 10:04:42 +02:00
// Early exit, signaling no selections were found.
2020-05-29 18:43:17 +02:00
if selection.is_none() {
2020-05-27 10:04:42 +02:00
std::process::exit(1);
}
let Selection { text, .. } = selection.unwrap();
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 {
2020-05-29 18:43:17 +02:00
None => println!("{}", text),
2020-05-25 23:32:37 +02:00
Some(target) => {
let mut file = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(target)
.expect("Unable to open the target file");
2021-03-13 18:51:31 +01:00
file.write_all(text.as_bytes()).unwrap();
2020-05-25 23:32:37 +02:00
}
}
2020-06-02 20:03:16 +02:00
}