Skip to content

Commit

Permalink
🦄 refactor(Logger):
Browse files Browse the repository at this point in the history
Add loglevel, move loggers into macro
  • Loading branch information
wychlw committed Sep 6, 2024
1 parent 32ffbeb commit efd4b01
Show file tree
Hide file tree
Showing 10 changed files with 113 additions and 65 deletions.
18 changes: 9 additions & 9 deletions src/exec/cli_exec.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use std::{
any::Any, error::Error, thread::sleep, time::{Duration, Instant}
any::Any,
error::Error,
thread::sleep,
time::{Duration, Instant},
};

use crate::{
consts::DURATION,
logger::err,
err,
term::tty::{DynTty, Tty, WrapperTty},
util::{anybase::AnyBase, util::rand_string},
};
Expand Down Expand Up @@ -90,14 +93,15 @@ impl CliTestApi for CliTester {
break;
}
if begin.elapsed().as_secs() > timeout as u64 {
err(format!(
err!(
"Timeout! Expected: {}, Actual: {}",
expected,
String::from_utf8(buf.clone()).unwrap()
));
);
return Err(Box::<dyn Error>::from("Timeout"));
}
}

Ok(())
}
fn script_run(&mut self, script: &str, timeout: u32) -> Result<(), Box<dyn Error>> {
Expand All @@ -122,11 +126,7 @@ impl CliTestApi for CliTester {
}
res
}
fn assert_script_run(
&mut self,
script: &str,
timeout: u32,
) -> Result<(), Box<dyn Error>> {
fn assert_script_run(&mut self, script: &str, timeout: u32) -> Result<(), Box<dyn Error>> {
let mut cmd = script.to_owned();
let echo_content_rand = String::from_utf8(rand_string(8)).unwrap();

Expand Down
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#![feature(box_into_inner)]

pub mod consts;
pub mod logger;
pub mod term {
pub mod tty;

Expand Down Expand Up @@ -29,6 +28,8 @@ pub mod device {
pub mod util {
pub mod anybase;
pub mod util;
pub mod singleton;
pub mod logger;
}
pub mod pythonapi {
pub mod shell_like;
Expand All @@ -40,12 +41,13 @@ pub mod pythonapi {
}

use pyo3::prelude::*;
use pythonapi::{pyshell::PyShell, shell_like::PyTty};
use pythonapi::{pyexec::PyExec, pyshell::PyShell, shell_like::PyTty};

#[pymodule]
#[pyo3(name = "tester")]
fn tester(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyTty>()?;
m.add_class::<PyShell>()?;
m.add_class::<PyExec>()?;
Ok(())
}
15 changes: 0 additions & 15 deletions src/logger.rs

This file was deleted.

18 changes: 10 additions & 8 deletions src/pythonapi/shell_like.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ use pyo3::{exceptions::PyTypeError, prelude::*};
use serde::Deserialize;

use crate::{
logger::log, term::{
log,
term::{
asciicast::Asciicast,
recorder::{Recorder, SimpleRecorder},
serial::Serial,
shell::Shell,
ssh::Ssh,
tty::{DynTty, WrapperTty},
}, util::anybase::heap_raw
},
util::anybase::heap_raw,
};

use super::{pyexec::handel_clitester, pyshell::handel_shell};
Expand Down Expand Up @@ -64,9 +66,7 @@ pub struct PyTty {

impl PyTty {
pub fn build(inner: PyTtyWrapper) -> Self {
PyTty {
inner
}
PyTty { inner }
}
}

Expand All @@ -93,7 +93,10 @@ struct PyTtyExecConf {
sudo: Option<bool>,
}

pub fn handel_wrap(inner: &mut Option<PyTtyWrapper>, be_wrapped: Option<&mut PyTty>) -> PyResult<()> {
pub fn handel_wrap(
inner: &mut Option<PyTtyWrapper>,
be_wrapped: Option<&mut PyTty>,
) -> PyResult<()> {
if be_wrapped.is_none() {
return Err(PyTypeError::new_err(
"be_wrapped must be provided when wrap is true",
Expand Down Expand Up @@ -165,7 +168,7 @@ impl PyTty {
#[new]
#[pyo3(signature = (conf, be_wrapped=None))]
fn py_new(conf: &str, be_wrapped: Option<&mut PyTty>) -> PyResult<Self> {
log(format!("Got conf: {}", conf));
log!("Got conf: {}", conf);

let conf: PyTtyConf = toml::from_str(conf).unwrap();

Expand Down Expand Up @@ -400,4 +403,3 @@ impl PyTty {
}
}
}

10 changes: 5 additions & 5 deletions src/term/serial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::time::Duration;
use serialport::{self, SerialPort};

use crate::consts::SHELL_DURATION;
use crate::logger::err;
use crate::err;
use crate::term::tty::Tty;
use crate::util::anybase::AnyBase;

Expand All @@ -20,7 +20,7 @@ impl Serial {
let inner = serialport::new(port, baud).open();

if let Err(e) = inner {
err(format!("Open serial port failed! Reason: {}", e));
err!("Open serial port failed! Reason: {}", e);
return Err(Box::new(e));
}

Expand Down Expand Up @@ -55,7 +55,7 @@ impl Tty for Serial {
}
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => {
err(format!("Read from serial port failed. Reason: {}", e));
err!("Read from serial port failed. Reason: {}", e);
return Err(Box::new(e));
}
}
Expand All @@ -76,7 +76,7 @@ impl Tty for Serial {
}
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => {
err(format!("Read line from serial port failed. Reason: {}", e));
err!("Read line from serial port failed. Reason: {}", e);
return Err(Box::new(e));
}
}
Expand All @@ -89,7 +89,7 @@ impl Tty for Serial {
Ok(_) => break,
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => {
err(format!("Write to serial port failed. Reason: {}", e));
err!("Write to serial port failed. Reason: {}", e);
return Err(Box::new(e));
}
}
Expand Down
25 changes: 12 additions & 13 deletions src/term/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ use std::{
time::Duration,
};

use crate::{
use crate::{log, err,
consts::SHELL_DURATION,
logger::{err, log},
util::anybase::AnyBase,
};

Expand All @@ -27,7 +26,7 @@ impl Shell {
pub fn build(shell: Option<&str>) -> Result<Shell, Box<dyn Error>> {
let shell = shell.unwrap_or("/bin/sh");

log(format!("Spawn shell process: {}", shell));
log!("Spawn shell process: {}", shell);

let inner = Command::new("stdbuf")
.args(&["-oL", "-eL", shell,])
Expand All @@ -36,28 +35,28 @@ impl Shell {
.stderr(Stdio::piped())
.spawn();
if let Err(e) = inner {
err(format!("Failed to spawn shell process. Reason: {}", e));
err!("Failed to spawn shell process. Reason: {}", e);
return Err(Box::new(e));
}
let mut inner = inner.unwrap();

let stdin = inner.stdin.take();
if let None = stdin {
err("Failed to get stdin of shell process.");
err!("Failed to get stdin of shell process.");
return Err(Box::<dyn Error>::from(""));
}
let stdin = stdin.unwrap();

let stdout = inner.stdout.take();
if let None = stdout {
err("Failed to get stdout of shell process.");
err!("Failed to get stdout of shell process.");
return Err(Box::<dyn Error>::from(""));
}
let stdout = stdout.unwrap();

let stderr = inner.stderr.take();
if let None = stderr {
err("Failed to get stderr of shell process.");
err!("Failed to get stderr of shell process.");
return Err(Box::<dyn Error>::from(""));
}
let stderr = stderr.unwrap();
Expand All @@ -79,14 +78,14 @@ impl Shell {
{
let stop = stop_clone.lock().unwrap();
if *stop {
log("Stop shell process");
log!("Stop shell process");
return;
}
}
let mut buf = [0u8];
let sz = reader.read(&mut buf);
if let Err(e) = sz {
err(format!("Read from shell process failed. Reason: {}", e));
err!("Read from shell process failed. Reason: {}", e);
break;
}
if buf[0] == 0x0 {
Expand All @@ -104,15 +103,15 @@ impl Shell {
fn __stop(&mut self) {
let stop = self.stop.lock();
if let Err(e) = stop {
err(format!("Failed to lock stop mutex. Reason: {}", e));
err!("Failed to lock stop mutex. Reason: {}", e);
return;
}
let mut stop = stop.unwrap();
if *stop {
return;
}
*stop = true;
log("Try to stop shell process");
log!("Try to stop shell process");
// if let Some(handle) = self.handle.take() {
// handle.join().unwrap();
// self.inner.wait().unwrap();
Expand Down Expand Up @@ -174,14 +173,14 @@ impl Tty for Shell {
Ok(_) => break,
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => {
err(format!("Write to shell process failed. Reason: {}", e));
err!("Write to shell process failed. Reason: {}", e);
return Err(Box::new(e));
}
}
}
let res = self.stdin.flush();
if let Err(e) = res {
err(format!("Flush to shell process failed. Reason: {}", e));
err!("Flush to shell process failed. Reason: {}", e);
return Err(Box::<dyn Error>::from(e));
}
return Ok(());
Expand Down
18 changes: 8 additions & 10 deletions src/term/ssh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ use std::{
use ssh2::Channel;

use crate::{
consts::SHELL_DURATION,
logger::{err, log},
util::anybase::AnyBase,
consts::SHELL_DURATION, err, log, util::anybase::AnyBase
};

use super::tty::Tty;
Expand Down Expand Up @@ -70,7 +68,7 @@ impl Ssh {

let e = channel.shell();
if let Err(e) = e {
err(format!("Failed to open SSH shell. Reason: {}", e));
err!("Failed to open SSH shell. Reason: {}", e);
}

let channel = Arc::new(Mutex::new(channel));
Expand All @@ -84,15 +82,15 @@ impl Ssh {
let handle = spawn(move || loop {
let stop = stop_clone.lock().unwrap();
if *stop {
log("Stop SSH shell.");
log!("Stop SSH shell.");
break;
}

let mut channel = channel_clone.lock().unwrap();
let mut buf = [0u8];
let sz = channel.read(&mut buf);
if let Err(e) = sz {
err(format!("Read from SSH channel failed. Reason: {}", e));
err!("Read from SSH channel failed. Reason: {}", e);
break;
}
if buf[0] == 0x0 {
Expand All @@ -114,15 +112,15 @@ impl Ssh {
pub fn exit(self) {
let stop = self.stop.lock();
if let Err(e) = stop {
err(format!("Failed to lock stop mutex. Reason: {}", e));
err!("Failed to lock stop mutex. Reason: {}", e);
return;
}
let mut stop = stop.unwrap();
if *stop {
return;
}
*stop = true;
log("Try to stop SSH shell.");
log!("Try to stop SSH shell.");
// if let Some(handle) = self.handle.take() {
// handle.join().unwrap();
// self.inner.wait().unwrap();
Expand Down Expand Up @@ -181,15 +179,15 @@ impl Tty for Ssh {
Ok(_) => break,
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => {
err(format!("Write to shell process failed. Reason: {}", e));
err!("Write to shell process failed. Reason: {}", e);
return Err(Box::new(e));
}
}
}
let mut channel = self.channel.lock().unwrap();
let res = channel.flush();
if let Err(e) = res {
err(format!("Flush to shell process failed. Reason: {}", e));
err!("Flush to shell process failed. Reason: {}", e);
return Err(Box::<dyn Error>::from(e));
}
return Ok(());
Expand Down
Loading

0 comments on commit efd4b01

Please sign in to comment.