Skip to content

Commit

Permalink
add lib support
Browse files Browse the repository at this point in the history
  • Loading branch information
borney committed May 31, 2023
1 parent b0d76e8 commit b8db264
Show file tree
Hide file tree
Showing 22 changed files with 187 additions and 59 deletions.
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.

10 changes: 9 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pidcat"
version = "0.1.0"
version = "0.2.0"
authors = ["Borney"]
edition = "2021"
license = "MIT"
Expand All @@ -16,6 +16,14 @@ keywords = [
readme = "README.md"
repository = "https://github.com/borneygit/pidcat"

[[bin]]
name="pidcat"
path="src/main.rs"

[lib]
name="pidcat"
path="src/lib.rs"

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

[dependencies]
Expand Down
30 changes: 28 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pidcat toor

![ScreenShot](/asset/screen.png)

# Install
# Install terminal
First install the rust environment
```
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Expand All @@ -22,7 +22,7 @@ Then use cargo to install pidcat
cargo install --path .
```

# How to use
# How to use terminal

```rust
pidcat --help
Expand Down Expand Up @@ -86,6 +86,32 @@ Options:
Print version
```

# Use by crate
add dep for Cargo.toml
```
[dependencies]
pidcat="0.2.0"
```
You can use the following code to capture the adb logcat logs and process them twice according to your needs
```rust
use futures::StreamExt;
use pidcat::LogStream;
use pidcat::source::*;

#[tokio::main]
async fn main() {
let source = ADBSource::new(None);

let mut logs: LogStream = source.source().await;

while let Some(r) = logs.next().await {
if let Ok(log) = r {
println!("{}", log);
}
}
}
```

# Thanks
https://github.com/JakeWharton/pidcat </br>
https://github.com/flxo/rogcat
6 changes: 1 addition & 5 deletions examples/colored.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,21 @@ lazy_static! {
u8::from_str_radix(&"#ff2600"[3..5], 16).unwrap(),
u8::from_str_radix(&"#ff2600"[5..7], 16).unwrap()
);

static ref VERBOSE: Color = Color(
u8::from_str_radix(&"#ffffff"[1..3], 16).unwrap(),
u8::from_str_radix(&"#ffffff"[3..5], 16).unwrap(),
u8::from_str_radix(&"#ffffff"[5..7], 16).unwrap()
);

static ref INFO: Color = Color(
u8::from_str_radix(&"#05d702"[1..3], 16).unwrap(),
u8::from_str_radix(&"#05d702"[3..5], 16).unwrap(),
u8::from_str_radix(&"#05d702"[5..7], 16).unwrap()
);

static ref WARNING: Color = Color(
u8::from_str_radix(&"#d75f02"[1..3], 16).unwrap(),
u8::from_str_radix(&"#d75f02"[3..5], 16).unwrap(),
u8::from_str_radix(&"#d75f02"[5..7], 16).unwrap()
);

static ref DEBUG: Color = Color(
u8::from_str_radix(&"#5fafff"[1..3], 16).unwrap(),
u8::from_str_radix(&"#5fafff"[3..5], 16).unwrap(),
Expand Down Expand Up @@ -71,4 +67,4 @@ fn main() {
debug!("hello {} {}", 123, "abc");
warn!("hello {} {}", 123, "abc");
verbose!("hello {} {}", 123, "abc");
}
}
16 changes: 16 additions & 0 deletions examples/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use futures::StreamExt;
use pidcat::source::*;
use pidcat::LogStream;

#[tokio::main]
async fn main() {
let source = ADBSource::new(None);

let mut logs: LogStream = source.source().await;

while let Some(r) = logs.next().await {
if let Ok(log) = r {
println!("{}", log);
}
}
}
32 changes: 19 additions & 13 deletions examples/logcat.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::fmt::{Display, Formatter};
use std::pin::Pin;
use futures::{Sink, Stream, StreamExt};
use anyhow::Result;
use async_stream::stream;
use std::collections::HashMap;
use async_trait::async_trait;
use futures::{Sink, Stream, StreamExt};
use regex::Regex;
use tokio::io::AsyncBufReadExt;
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::pin::Pin;
use tokio::io::AsyncBufReadExt;
use tokio::process::{Child, Command};

#[derive(Debug, Clone)]
Expand All @@ -24,11 +24,15 @@ pub(crate) struct Log {

impl Display for Log {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {} {} {} {} {} {}", self.date, self.time, self.pid, self.tid, self.level, self.tag, self.message)
write!(
f,
"{} {} {} {} {} {} {}",
self.date, self.time, self.pid, self.tid, self.level, self.tag, self.message
)
}
}

type LogStream = Pin<Box<dyn Stream<Item=Result<Log, Box<dyn Error + Send>>> + Send>>;
type LogStream = Pin<Box<dyn Stream<Item = Result<Log, Box<dyn Error + Send>>> + Send>>;

#[async_trait]
trait Source {
Expand All @@ -45,8 +49,7 @@ impl AdbSource {
command.arg("-D");
command.arg("-v").arg("long");
command.arg("-b").arg("all");
command.spawn()
.expect("Failed to execute adb logcat")
command.spawn().expect("Failed to execute adb logcat")
}
}

Expand All @@ -55,7 +58,9 @@ impl Source for AdbSource {
async fn source(&self) -> LogStream {
let mut logcat = self.spawn_adb_logcat().await;
let mut reader = tokio::io::BufReader::new(logcat.stdout.take().unwrap());
let re = Regex::new(r"\[ (\d{2}-\d{2})\s(\d{2}:\d{2}:\d{2}\.\d{3})\s+(\d+):\s+(\d+)\s+(.*) ]").unwrap();
let re =
Regex::new(r"\[ (\d{2}-\d{2})\s(\d{2}:\d{2}:\d{2}\.\d{3})\s+(\d+):\s+(\d+)\s+(.*) ]")
.unwrap();

let s = stream! {
let mut line = String::new();
Expand Down Expand Up @@ -125,6 +130,7 @@ async fn main() {
Err(_) => {}
}
}
}).await.expect("TODO: panic message");

}
})
.await
.expect("TODO: panic message");
}
11 changes: 3 additions & 8 deletions examples/ps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ use tokio::process::{Child, Command};
#[tokio::main]
async fn main() {
let mut ps = spawn_ps().await;
let pids = Vec::from([
"launcher",
"com.android.phone",
"genymotion"
]);
let pids = Vec::from(["launcher", "com.android.phone", "genymotion"]);

let reader_task = tokio::spawn(async move {
let mut reader = tokio::io::BufReader::new(ps.stdout.take().unwrap());
Expand All @@ -20,7 +16,7 @@ async fn main() {
}
let spl = line.trim().split_whitespace().collect::<Vec<&str>>();
let name = spl[8];
let pid= spl[1];
let pid = spl[1];
for p in pids.iter() {
if name.contains(p) {
println!("{}:{}", name, pid);
Expand All @@ -38,6 +34,5 @@ async fn spawn_ps() -> Child {
command.stdout(std::process::Stdio::piped());
command.arg("shell");
command.arg("ps");
command.spawn()
.expect("Failed to execute adb shell ps")
command.spawn().expect("Failed to execute adb shell ps")
}
4 changes: 2 additions & 2 deletions examples/re.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fn main() {
"[ 05-24 05:54:17.377 181: 181 I/vold ]",
"[546,1000,system,89723904,77209600,0]",
"[3849]> SIGNAL_STRENGTH [SUB0]",
"[ 05-26 05:45:32.733 1440: 1440 W/System.err ]"
"[ 05-26 05:45:32.733 1440: 1440 W/System.err ]",
];
let re = Regex::new(r"\[ (\d{2}-\d{2})\s(\d{2}:\d{2}:\d{2}\.\d{3})\s+(\d+):(.*) ]").unwrap();

Expand All @@ -36,4 +36,4 @@ fn main() {
println!("{}---->{}", s, re.is_match(s));
}
}
}
}
3 changes: 2 additions & 1 deletion src/filter/buffer_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ pub(crate) struct BufferFilter {
}

impl BufferFilter {
pub fn new(buffers: Vec<String>, filter: Option<Arc<dyn Filter>>) -> Self {
#[allow(dead_code)]
pub(crate) fn new(buffers: Vec<String>, filter: Option<Arc<dyn Filter>>) -> Self {
let mut s = Self {
buffers,
filter,
Expand Down
3 changes: 2 additions & 1 deletion src/filter/level_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ pub(crate) struct LevelFilter {
}

impl LevelFilter {
pub fn new(level: Level, filter: Option<Arc<dyn Filter>>) -> Self {
#[allow(dead_code)]
pub(crate) fn new(level: Level, filter: Option<Arc<dyn Filter>>) -> Self {
Self { level, filter }
}
}
Expand Down
14 changes: 12 additions & 2 deletions src/filter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,29 @@ mod pid_filter;
mod revert_filter;
mod tag_filter;

#[allow(unused_imports)]
pub(crate) use buffer_filter::BufferFilter;
#[allow(unused_imports)]
pub(crate) use level_filter::LevelFilter;
#[allow(unused_imports)]
pub(crate) use pid_filter::PidFilter;
#[allow(unused_imports)]
pub(crate) use revert_filter::RevertFilter;
#[allow(unused_imports)]
pub(crate) use tag_filter::TagFilter;

use crate::log::Log;

use std::sync::Arc;
use async_trait::async_trait;
use std::sync::Arc;

#[allow(dead_code)]
pub(crate) type ArcFilter = Arc<dyn Filter>;

///
/// Filter trait used to filter log
///
#[async_trait]
pub(crate) trait Filter: Send + Sync {
pub trait Filter: Send + Sync {
async fn filter(&self, log: Log) -> Option<Log>;
}
3 changes: 2 additions & 1 deletion src/filter/pid_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ pub(crate) struct PidFilter {
}

impl PidFilter {
pub fn new(process: Vec<String>, filter: Option<Arc<dyn Filter>>) -> Self {
#[allow(dead_code)]
pub(crate) fn new(process: Vec<String>, filter: Option<Arc<dyn Filter>>) -> Self {
Self {
filter,
process: DashSet::from_iter(process.into_iter()),
Expand Down
3 changes: 2 additions & 1 deletion src/filter/revert_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ pub(crate) struct RevertFilter {
}

impl RevertFilter {
pub fn new(revert: String, ignore: bool, filter: Option<Arc<dyn Filter>>) -> Self {
#[allow(dead_code)]
pub(crate) fn new(revert: String, ignore: bool, filter: Option<Arc<dyn Filter>>) -> Self {
Self {
filter,
revert: revert.clone(),
Expand Down
3 changes: 2 additions & 1 deletion src/filter/tag_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ pub(crate) struct TagFilter {
}

impl TagFilter {
pub fn new(tag: String, ignore: bool, filter: Option<Arc<dyn Filter>>) -> Self {
#[allow(dead_code)]
pub(crate) fn new(tag: String, ignore: bool, filter: Option<Arc<dyn Filter>>) -> Self {
Self {
filter,
tag: tag.clone(),
Expand Down
10 changes: 10 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
mod log;
pub use log::{Log, LogStream};

pub mod source;

mod filter;
pub use filter::Filter;

mod sink;
pub use sink::Sink;
Loading

0 comments on commit b8db264

Please sign in to comment.