chore: extract local copier to struct

This commit is contained in:
Kasper Juul Hermansen 2025-01-10 09:07:44 +01:00
parent 27796dd359
commit 327fd3098a
Signed by: kjuulh
SSH Key Fingerprint: SHA256:RjXh0p7U6opxnfd3ga/Y9TCo18FYlHFdSpRIV72S/QM
3 changed files with 65 additions and 21 deletions

View File

@ -0,0 +1,48 @@
use std::process::Stdio;
use anyhow::Context;
use tokio::io::AsyncWriteExt;
use crate::state::State;
#[derive(Default)]
pub struct LocalCopier {}
impl LocalCopier {
pub fn new() -> Self {
Self {}
}
pub async fn copy(&self, input: &[u8]) -> anyhow::Result<()> {
// FIXME: hardcode for macos
let mut copy_process = tokio::process::Command::new("pbcopy")
.stdin(Stdio::piped())
.spawn()?;
if let Some(mut stdin_handle) = copy_process.stdin.take() {
stdin_handle
.write_all(input)
.await
.context("failed to write input to copy process")?;
stdin_handle
.flush()
.await
.context("failed to flush to program")?;
}
let status = copy_process.wait().await?;
tracing::info!("copy process ended with status: {:?}", status);
Ok(())
}
}
pub trait LocalCopierState {
fn local_copier(&self) -> LocalCopier;
}
impl LocalCopierState for State {
fn local_copier(&self) -> LocalCopier {
LocalCopier::new()
}
}

View File

@ -1,8 +1,12 @@
use std::{io::Read, process::Stdio};
use std::io::Read;
use anyhow::Context;
use clap::{Parser, Subcommand};
use tokio::io::AsyncWriteExt;
use copy::LocalCopierState;
use state::State;
mod copy;
mod state;
#[derive(Parser)]
#[command(author, version, about, long_about = None, subcommand_required = true)]
@ -25,6 +29,8 @@ async fn main() -> anyhow::Result<()> {
let cli = Command::parse();
tracing::debug!("Starting cli");
let state = State::new();
match cli.command.unwrap() {
Commands::Listen {} => {}
Commands::Copy {} => {
@ -39,25 +45,7 @@ async fn main() -> anyhow::Result<()> {
}
tracing::debug!(content = &input, "found content");
// FIXME: hardcode for macos
let mut copy_process = tokio::process::Command::new("pbcopy")
.stdin(Stdio::piped())
.spawn()?;
if let Some(mut stdin_handle) = copy_process.stdin.take() {
stdin_handle
.write_all(input.as_bytes())
.await
.context("failed to write input to copy process")?;
stdin_handle
.flush()
.await
.context("failed to flush to program")?;
}
let status = copy_process.wait().await?;
tracing::info!("copy process ended with status: {:?}", status);
state.local_copier().copy(input.as_bytes()).await?;
}
_ => (),
}

View File

@ -0,0 +1,8 @@
#[derive(Clone)]
pub struct State {}
impl State {
pub fn new() -> Self {
Self {}
}
}