Skip to content

Commit

Permalink
feat: #1491 add duplicate package checker plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
jeasonnow committed Aug 19, 2024
1 parent bdd09fa commit 82b981a
Show file tree
Hide file tree
Showing 24 changed files with 285 additions and 8 deletions.
18 changes: 10 additions & 8 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/mako/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ puffin_egui = { version = "0.22.0", optional = true }
rayon = "1.7.0"
regex = "1.9.3"
sailfish = "0.8.3"
semver = "1.0.23"
serde-xml-rs = "0.6.0"
serde_yaml = "0.9.22"
svgr-rs = "0.1.3"
Expand Down
9 changes: 9 additions & 0 deletions crates/mako/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,15 @@ impl Compiler {
)));
}

if let Some(duplicate_package_checker) = &config.check_duplicate_package {
plugins.push(Arc::new(
plugins::duplicate_package_checker::DuplicatePackageCheckerPlugin::new()
.show_help(duplicate_package_checker.show_help)
.emit_error(duplicate_package_checker.emit_error)
.verbose(duplicate_package_checker.verbose),
));
}

if config.experimental.require_context {
plugins.push(Arc::new(plugins::require_context::RequireContextPlugin {}))
}
Expand Down
25 changes: 25 additions & 0 deletions crates/mako/src/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ create_deserialize_fn!(deserialize_manifest, ManifestConfig);
create_deserialize_fn!(deserialize_code_splitting, CodeSplitting);
create_deserialize_fn!(deserialize_px2rem, Px2RemConfig);
create_deserialize_fn!(deserialize_progress, ProgressConfig);
create_deserialize_fn!(
deserialize_check_duplicate_package,
DuplicatePackageCheckerConfig
);
create_deserialize_fn!(deserialize_umd, String);
create_deserialize_fn!(deserialize_devtool, DevtoolConfig);
create_deserialize_fn!(deserialize_tree_shaking, TreeShakingStrategy);
Expand Down Expand Up @@ -261,6 +265,16 @@ pub struct ProgressConfig {
pub progress_chars: String,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct DuplicatePackageCheckerConfig {
#[serde(rename = "verbose", default)]
pub verbose: bool,
#[serde(rename = "emitError", default)]
pub emit_error: bool,
#[serde(rename = "showHelp", default)]
pub show_help: bool,
}

impl Default for Px2RemConfig {
fn default() -> Self {
Px2RemConfig {
Expand Down Expand Up @@ -560,6 +574,12 @@ pub struct Config {
pub watch: WatchConfig,
pub use_define_for_class_fields: bool,
pub emit_decorator_metadata: bool,
#[serde(
rename = "duplicatePackageChecker",
deserialize_with = "deserialize_check_duplicate_package",
default
)]
pub check_duplicate_package: Option<DuplicatePackageCheckerConfig>,
}

#[derive(Deserialize, Serialize, Clone, Debug, Default)]
Expand Down Expand Up @@ -724,6 +744,11 @@ const DEFAULT_CONFIG: &str = r#"
"progress": {
"progressChars": "▨▨"
},
"duplicatePackageChecker": {
"verbose": false,
"showHelp": false,
"emitError": false,
},
"emitAssets": true,
"cssModulesExportOnlyLocales": false,
"inlineCSS": false,
Expand Down
167 changes: 167 additions & 0 deletions crates/mako/src/plugins/duplicate_package_checker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

use semver::Version;

use crate::compiler::Context;
use crate::module_graph::ModuleGraph;
use crate::plugin::Plugin;
use crate::resolve::ResolverResource;

#[derive(Debug, Clone)]
struct PackageInfo {
name: String,
version: Version,
path: PathBuf,
}

#[derive(Default)]
pub struct DuplicatePackageCheckerPlugin {
verbose: bool,
show_help: bool,
emit_error: bool,
}

/// Cleans the path by replacing /node_modules/ or \node_modules\ with /~/
fn clean_path(module_path: &Path) -> PathBuf {
let path_str = module_path.to_string_lossy();
let cleaned_path = path_str
.replace("/node_modules/", "/~/")
.replace("\\node_modules\\", "/~/");
PathBuf::from(cleaned_path)
}

/// Makes the cleaned path relative to the given context
fn clean_path_relative_to_context(module_path: &Path, context: &Path) -> PathBuf {
let cleaned_path = clean_path(module_path);
let context_str = context.to_str().unwrap();
let cleaned_path_str = cleaned_path.to_str().unwrap();

if cleaned_path_str.starts_with(context_str) {
let relative_path = cleaned_path_str.trim_start_matches(context_str);
PathBuf::from(format!(".{}", relative_path))
} else {
cleaned_path
}
}

impl DuplicatePackageCheckerPlugin {
pub fn new() -> Self {
Self::default()
}

pub fn verbose(mut self, verbose: bool) -> Self {
self.verbose = verbose;
self
}

pub fn show_help(mut self, show_help: bool) -> Self {
self.show_help = show_help;
self
}

pub fn emit_error(mut self, emit_error: bool) -> Self {
self.emit_error = emit_error;
self
}

fn find_duplicates(packages: Vec<PackageInfo>) -> HashMap<String, Vec<PackageInfo>> {
let mut package_map: HashMap<String, Vec<PackageInfo>> = HashMap::new();

for package in packages {
package_map
.entry(package.name.clone())
.or_default()
.push(package);
}

package_map
.into_iter()
.filter(|(_, versions)| versions.len() > 1)
.collect()
}

fn check_duplicates(
&self,
module_graph: &RwLock<ModuleGraph>,
) -> HashMap<String, Vec<PackageInfo>> {
let mut packages = Vec::new();

module_graph
.read()
.unwrap()
.modules()
.iter()
.for_each(|module| {
if let Some(ResolverResource::Resolved(resource)) = module
.info
.as_ref()
.and_then(|info| info.resolved_resource.as_ref())
{
let package_json = resource.0.package_json().unwrap();
let raw_json = package_json.raw_json();
let default_version = serde_json::Value::String("0.0.0".to_string());
let version = raw_json
.as_object()
.unwrap()
.get("version")
.unwrap_or(&default_version)
.as_str()
.unwrap();
let package_info = PackageInfo {
name: package_json.name.clone().unwrap_or("mako-pkg".to_string()),
version: semver::Version::parse(version).unwrap(),
path: package_json.path.clone(),
};
packages.push(package_info);
}
});

Self::find_duplicates(packages)
}
}

impl Plugin for DuplicatePackageCheckerPlugin {
fn name(&self) -> &str {
"DuplicatePackageCheckerPlugin"
}

fn after_build(
&self,
context: &Arc<Context>,
_compiler: &crate::compiler::Compiler,
) -> anyhow::Result<()> {
let duplicates = self.check_duplicates(&context.module_graph);

if !duplicates.is_empty() && self.verbose {
let mut message = String::new();

for (name, instances) in duplicates {
message.push_str(&format!("\nMultiple versions of {} found:\n", name));
for instance in instances {
let mut line = format!(" {} {}", instance.version, instance.name);
let path = instance.path.clone();
line.push_str(&format!(
" from {}",
clean_path_relative_to_context(&path, &context.root).display()
));
message.push_str(&line);
message.push('\n');
}
}

if self.show_help {
message.push_str("\nCheck how you can resolve duplicate packages: \nhttps://github.com/darrenscerri/duplicate-package-checker-webpack-plugin#resolving-duplicate-packages-in-your-bundle\n");
}

if !self.emit_error {
println!("{}", message);
} else {
eprintln!("{}", message);
}
}

Ok(())
}
}
1 change: 1 addition & 0 deletions crates/mako/src/plugins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod bundless_compiler;
pub mod context_module;
pub mod copy;
pub mod detect_circular_dependence;
pub mod duplicate_package_checker;
pub mod emotion;
pub mod graphviz;
pub mod hmr_runtime;
Expand Down
3 changes: 3 additions & 0 deletions crates/mako/test/build/duplicate-package/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
require('a');
require('b');
require('c');
6 changes: 6 additions & 0 deletions crates/mako/test/build/duplicate-package/mako.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"duplicatePackageChecker": {
"verbose": true,
"showHelp": true
}
}

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

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

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

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

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

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

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

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

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

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

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

8 changes: 8 additions & 0 deletions crates/mako/test/build/duplicate-package/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "test",
"version": "1.0.0",
"dependencies": {
"a": "~1.0.0",
"b": "~1.0.0"
}
}
Loading

0 comments on commit 82b981a

Please sign in to comment.