Skip to content

Commit

Permalink
Refactor unused_finder/logger into standalone package (#100)
Browse files Browse the repository at this point in the history
This is so it can be compiled separately. In the future, it may be
referenced from other packages that want to do logging without creating
dependency cyles.

---------

Co-authored-by: Max Huang-Hobbs <[email protected]>
  • Loading branch information
Adjective-Object and Max Huang-Hobbs authored Nov 14, 2024
1 parent 9b4dcff commit 8e5bf47
Show file tree
Hide file tree
Showing 17 changed files with 115 additions and 65 deletions.
19 changes: 19 additions & 0 deletions Cargo.lock

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

8 changes: 0 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,8 @@ regex = "1"
relative-path = "1.7.2"
serde = { version = "1.0.117", features = ["rc", "derive"] }
serde_json = "1.0.59"
swc = "0.284.1"
swc_common = "0.37.4"
swc_compiler_base = "0.18.1"
swc_core = { version = "0.101.3", features = [
"ecma_plugin_transform",
"ecma_loader_node",
"ecma_loader_tsc",
"ecma_loader_lru",
"ecma_loader_parking_lot",
] }
swc_ecma_ast = "0.118.2"
swc_ecma_loader = "0.49.1"
swc_ecma_parser = "0.149.0"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "none",
"comment": "refactor logger from unused_finder into own package",
"packageName": "@good-fences/api",
"email": "[email protected]",
"dependentChangeType": "none"
}
11 changes: 11 additions & 0 deletions crates/logger/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "logger"
version = "0.2.0"
authors = ["Maxwell Huang-Hobbs <[email protected]>"]
edition = "2018"

[lib]
crate-type = ["lib"]

[dependencies]
anyhow.workspace = true
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::sync::Mutex;

use anyhow::anyhow;

pub trait Logger: Send + Sync + Clone {
fn log(&self, message: impl Into<String>);
}
Expand Down
13 changes: 13 additions & 0 deletions crates/logger_console/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@

[package]
name = "logger_console"
version = "0.2.0"
authors = ["Maxwell Huang-Hobbs <[email protected]>"]
edition = "2018"

[lib]
crate-type = ["lib"]

[dependencies]
logger = { version = "0.2.0", path = "../logger" }
napi.workspace = true
49 changes: 49 additions & 0 deletions crates/logger_console/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use std::sync::Arc;

use napi::{
threadsafe_function::{
ErrorStrategy::{self},
ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode,
},
JsFunction, JsObject, Result, Status,
};

use logger::Logger;

#[derive(Clone)]
pub struct ConsoleLogger {
logfn: Arc<ThreadsafeFunction<String, ErrorStrategy::CalleeHandled>>,
}

impl ConsoleLogger {
pub fn new(console: JsObject) -> Result<Self> {
let logfn = console.get_named_property::<JsFunction>("log")?;
Ok(Self {
logfn: Arc::new(logfn.create_threadsafe_function(
// allow queueing console responses?
100,
|ctx: ThreadSafeCallContext<String>| {
let js_str = ctx.env.create_string(&ctx.value)?;
// return as an argv array
Ok(vec![js_str])
},
)?),
})
}
}

impl Logger for ConsoleLogger {
fn log(&self, message: impl Into<String>) {
let message_string: String = message.into();
let status = self
.logfn
.call(Ok(message_string), ThreadsafeFunctionCallMode::Blocking);
match status {
Status::Ok => {}
_ => {
eprintln!();
panic!("Error calling console.log from Rust. Unexpected threadsafe function call mode {}", status);
}
}
}
}
1 change: 1 addition & 0 deletions crates/unused_bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ anyhow.workspace = true
parking_lot.workspace = true
rstack-self = { version = "0.3.0", default-features = false, optional = true }
serde-hjson = "1.1.0"
logger = { version = "0.2.0", path = "../logger" }

[features]
default = []
Expand Down
6 changes: 2 additions & 4 deletions crates/unused_bin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@ extern crate unused_finder;

use anyhow::{Context, Result};
use clap::Parser;
use logger::{Logger, StdioLogger};
use std::{convert::TryInto, env, fs, path::Path};
use unused_finder::{
logger::{Logger, StdioLogger},
UnusedFinderConfig,
};
use unused_finder::UnusedFinderConfig;

#[derive(Parser, Debug)]
struct CliArgs {
Expand Down
1 change: 1 addition & 0 deletions crates/unused_finder/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ abspath = { version = "0.2.0", path = "../abspath" }
itertools = "0.13.0"
debug_print = "1.0.0"
schemars.workspace = true
logger = { version = "0.2.0", path = "../logger" }

[dev-dependencies]
stringreader = "0.1.1"
Expand Down
2 changes: 1 addition & 1 deletion crates/unused_finder/src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ use anyhow::Result;
use rayon::prelude::*;

use crate::{
logger::Logger,
parse::{ExportedSymbol, ResolvedImportExportInfo},
tag::UsedTag,
walked_file::ResolvedSourceFile,
};
use logger::Logger;

// graph node used to represent a file during the "used file" walk
#[derive(Debug, Clone, Default)]
Expand Down
1 change: 0 additions & 1 deletion crates/unused_finder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ extern crate test_tmpdir;
mod cfg;
mod graph;
mod ignore_file;
pub mod logger;
mod parse;
mod report;
mod tag;
Expand Down
2 changes: 1 addition & 1 deletion crates/unused_finder/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use path_slash::PathBufExt;
use test_tmpdir::{amap, test_tmpdir};

use crate::{
cfg::package_match_rules::PackageMatchRules, logger, report::SymbolReport, tag::UsedTag,
cfg::package_match_rules::PackageMatchRules, report::SymbolReport, tag::UsedTag,
SymbolReportWithTags, UnusedFinder, UnusedFinderConfig, UnusedFinderReport,
};

Expand Down
2 changes: 1 addition & 1 deletion crates/unused_finder/src/unused_finder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::{
cfg::{UnusedFinderConfig, UnusedFinderJSONConfig},
graph::Graph,
ignore_file::IgnoreFile,
logger::Logger,
parse::{get_file_import_export_info, ExportedSymbol},
report::UnusedFinderReport,
tag::UsedTag,
Expand All @@ -21,6 +20,7 @@ use import_resolver::swc_resolver::{
MonorepoResolver,
};
use js_err::JsErr;
use logger::Logger;
use rayon::{iter::Either, prelude::*};
use swc_ecma_loader::{resolve::Resolve, TargetEnv};

Expand Down
4 changes: 2 additions & 2 deletions crates/unused_finder/src/walk.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::ignore_file::IgnoreFile;
use crate::logger::Logger;
use crate::parse::exports_visitor_runner::SourceFileParseError;
use crate::parse::{get_file_import_export_info, RawImportExportInfo};
use crate::walked_file::{WalkedPackage, WalkedSourceFile};
use ahashmap::AHashMap;
use anyhow::Context;
use ignore::overrides::OverrideBuilder;
use ignore::DirEntry;
use logger::Logger;
use rayon::iter::Either;
use rayon::prelude::*;
use std::ffi::OsStr;
Expand Down Expand Up @@ -401,7 +401,7 @@ fn split_errs<A, B>(x: Result<A, B>) -> Either<A, B> {

#[cfg(test)]
mod test {
use crate::logger::StdioLogger;
use logger::StdioLogger;

use super::*;
use test_tmpdir::test_tmpdir;
Expand Down
2 changes: 2 additions & 0 deletions crates/unused_finder_napi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ napi-derive.workspace = true
unused_finder = { version = "0.2.0", path = "../unused_finder" }
serde.workspace = true
js_err_napi = { version = "0.2.0", path = "../js_err_napi" }
logger_console = { version = "0.2.0", path = "../logger_console" }
logger = { version = "0.2.0", path = "../logger" }

[build-dependencies]
napi-build = "2.0.1"
50 changes: 3 additions & 47 deletions crates/unused_finder_napi/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
use std::{collections::HashMap, sync::Arc};
use std::collections::HashMap;

use js_err_napi::ToNapi;
use napi::{
threadsafe_function::{
ErrorStrategy::{self},
ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode,
},
JsFunction, JsObject, Result, Status,
};
use napi::{JsObject, Result};

use logger_console::ConsoleLogger;
use napi_derive::napi;
use serde::{Deserialize, Serialize};
use unused_finder::logger::Logger;

/// A JSON serializable proxy for the UnusedFinderConfig struct
///
Expand Down Expand Up @@ -175,44 +169,6 @@ impl From<unused_finder::UnusedFinderReport> for UnusedFinderReport {
}
}

#[derive(Clone)]
struct ConsoleLogger {
logfn: Arc<ThreadsafeFunction<String, ErrorStrategy::CalleeHandled>>,
}

impl ConsoleLogger {
fn new(console: JsObject) -> Result<Self> {
let logfn = console.get_named_property::<JsFunction>("log")?;
Ok(Self {
logfn: Arc::new(logfn.create_threadsafe_function(
// allow queueing console responses?
100,
|ctx: ThreadSafeCallContext<String>| {
let js_str = ctx.env.create_string(&ctx.value)?;
// return as an argv array
Ok(vec![js_str])
},
)?),
})
}
}

impl Logger for ConsoleLogger {
fn log(&self, message: impl Into<String>) {
let message_string: String = message.into();
let status = self
.logfn
.call(Ok(message_string), ThreadsafeFunctionCallMode::Blocking);
match status {
Status::Ok => {}
_ => {
eprintln!();
panic!("Error calling console.log from Rust. Unexpected threadsafe function call mode {}", status);
}
}
}
}

// Holds an in-memory representation of the file tree.
// That representation can be used used to find unused files and exports
// within a project
Expand Down

0 comments on commit 8e5bf47

Please sign in to comment.