Skip to content

Commit

Permalink
Turn stream into factory
Browse files Browse the repository at this point in the history
  • Loading branch information
max-lt committed Mar 7, 2024
1 parent 8462c7b commit 8e0a687
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 20 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/target

example.yml
example.sh
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "github-hook-rs"
version = "0.1.2"
version = "0.1.3"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
38 changes: 21 additions & 17 deletions src/script.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
use std::io::Read;

use std::io::BufRead;
use std::thread::spawn;
use std::thread::JoinHandle;
use rand::RngCore;

fn stream<R: Sized + Read>(id: &str, name: &str, reader: R) {
let mut reader = std::io::BufReader::new(reader);
let mut line = String::new();
while std::io::BufRead::read_line(&mut reader, &mut line).unwrap() > 0 {
log::info!("Job {id}:{name}: {}", line.trim());
line.clear();
}
fn stream<R: Read + Send + 'static>(
id: String,
name: &'static str,
reader: R,
) -> JoinHandle<()> {
spawn(move || {
let lines = std::io::BufReader::new(reader).lines();

for line in lines {
log::info!("Job {id}:{name}: {}", line.unwrap());
}
})
}

pub fn run_script(script: String) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
pub fn run_script(script: String) -> JoinHandle<()> {
spawn(move || {
let job_id = {
let mut data = [0u8; 4];
rand::thread_rng().fill_bytes(&mut data);
Expand All @@ -29,17 +36,14 @@ pub fn run_script(script: String) -> std::thread::JoinHandle<()> {
.spawn()
.expect("Failed to start script");


let out_h = {
let job_id = job_id.clone();
let stdout = child.stdout.take().unwrap();
std::thread::spawn(move || stream(&job_id, "stdout", stdout))
let stdout = child.stdout.take().unwrap();
stream(job_id.to_string(), "stdout", stdout)
};

let err_h = {
let job_id = job_id.clone();
let stderr = child.stderr.take().unwrap();
std::thread::spawn(move || stream(&job_id, "stderr", stderr))
let stderr = child.stderr.take().unwrap();
stream(job_id.to_string(), "stderr", stderr)
};

// wait out_h and err_h to finish
Expand Down

0 comments on commit 8e0a687

Please sign in to comment.