Skip to content

Commit 8e0a687

Browse files
committed
Turn stream into factory
1 parent 8462c7b commit 8e0a687

File tree

4 files changed

+24
-20
lines changed

4 files changed

+24
-20
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
/target
22

33
example.yml
4-
4+
example.sh

Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "github-hook-rs"
3-
version = "0.1.2"
3+
version = "0.1.3"
44
edition = "2021"
55

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

src/script.rs

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
11
use std::io::Read;
2-
2+
use std::io::BufRead;
3+
use std::thread::spawn;
4+
use std::thread::JoinHandle;
35
use rand::RngCore;
46

5-
fn stream<R: Sized + Read>(id: &str, name: &str, reader: R) {
6-
let mut reader = std::io::BufReader::new(reader);
7-
let mut line = String::new();
8-
while std::io::BufRead::read_line(&mut reader, &mut line).unwrap() > 0 {
9-
log::info!("Job {id}:{name}: {}", line.trim());
10-
line.clear();
11-
}
7+
fn stream<R: Read + Send + 'static>(
8+
id: String,
9+
name: &'static str,
10+
reader: R,
11+
) -> JoinHandle<()> {
12+
spawn(move || {
13+
let lines = std::io::BufReader::new(reader).lines();
14+
15+
for line in lines {
16+
log::info!("Job {id}:{name}: {}", line.unwrap());
17+
}
18+
})
1219
}
1320

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

32-
3339
let out_h = {
34-
let job_id = job_id.clone();
35-
let stdout = child.stdout.take().unwrap();
36-
std::thread::spawn(move || stream(&job_id, "stdout", stdout))
40+
let stdout = child.stdout.take().unwrap();
41+
stream(job_id.to_string(), "stdout", stdout)
3742
};
3843

3944
let err_h = {
40-
let job_id = job_id.clone();
41-
let stderr = child.stderr.take().unwrap();
42-
std::thread::spawn(move || stream(&job_id, "stderr", stderr))
45+
let stderr = child.stderr.take().unwrap();
46+
stream(job_id.to_string(), "stderr", stderr)
4347
};
4448

4549
// wait out_h and err_h to finish

0 commit comments

Comments
 (0)