Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: unsynced-similar-deps rule #105

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@ use crate::rules::multiple_dependency_versions::MultipleDependencyVersionsIssue;
use crate::rules::non_existant_packages::NonExistantPackagesIssue;
use crate::rules::packages_without_package_json::PackagesWithoutPackageJsonIssue;
use crate::rules::types_in_dependencies::TypesInDependenciesIssue;
use crate::rules::unsync_similar_dependencies::{
SimilarDependency, UnsyncSimilarDependenciesIssue,
};
use crate::rules::{BoxIssue, IssuesList, PackageType};
use anyhow::{anyhow, Result};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fs::{self};
use std::path::PathBuf;

Expand Down Expand Up @@ -302,7 +306,18 @@ pub fn collect_issues(args: &Args, packages_list: PackagesList) -> IssuesList<'_
}
}

let mut similar_dependencies = IndexMap::new();

for (name, versions) in all_dependencies {
if let Ok(similar_dependency) = SimilarDependency::try_from(name.as_str()) {
similar_dependencies
.entry(similar_dependency)
.or_insert_with(IndexMap::new)
.entry(name.clone())
.or_insert_with(Vec::new)
.extend(versions.clone());
}

let mut filtered_versions = versions
.iter()
.filter(|(_, version)| {
Expand Down Expand Up @@ -330,6 +345,22 @@ pub fn collect_issues(args: &Args, packages_list: PackagesList) -> IssuesList<'_
}
}

for (similar_dependency, versions) in similar_dependencies {
if versions.len() > 1 {
let mut unique_versions = HashSet::new();
for (_, version) in versions.iter().flat_map(|(_, versions)| versions) {
unique_versions.insert(version);
}

if unique_versions.len() > 1 {
issues.add_raw(
PackageType::None,
UnsyncSimilarDependenciesIssue::new(similar_dependency, versions),
);
}
}
}

issues
}

Expand Down
2 changes: 1 addition & 1 deletion src/packages/semversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use anyhow::{anyhow, Result};
use semver::{Prerelease, Version, VersionReq};
use std::{cmp::Ordering, fmt::Display};

#[derive(Debug, PartialEq, Eq, Clone)]
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum SemVersion {
Exact(Version),
Range(VersionReq),
Expand Down
1 change: 1 addition & 0 deletions src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub mod root_package_manager_field;
pub mod root_package_private_field;
pub mod types_in_dependencies;
pub mod unordered_dependencies;
pub mod unsync_similar_dependencies;

pub const ERROR: &str = "⨯";
pub const WARNING: &str = "⚠️";
Expand Down
127 changes: 127 additions & 0 deletions src/rules/unsync_similar_dependencies.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
use super::Issue;
use crate::packages::semversion::SemVersion;
use colored::Colorize;
use indexmap::IndexMap;
use std::{borrow::Cow, fmt::Display};

#[derive(Debug, Hash, PartialEq, Eq)]
pub enum SimilarDependency {
NextJS,
Turborepo,
}

impl Display for SimilarDependency {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NextJS => write!(f, "Next.js"),
Self::Turborepo => write!(f, "Turborepo"),
}
}
}

impl TryFrom<&str> for SimilarDependency {
type Error = anyhow::Error;

fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
// Next.js
"next" => Ok(Self::NextJS),
"@next/eslint-plugin-next" => Ok(Self::NextJS),
"eslint-config-next" => Ok(Self::NextJS),
"@next/bundle-analyzer" => Ok(Self::NextJS),
"@next/third-parties" => Ok(Self::NextJS),
"@next/mdx" => Ok(Self::NextJS),
// Turborepo
"turbo" => Ok(Self::Turborepo),
"turbo-ignore" => Ok(Self::Turborepo),
"eslint-config-turbo" => Ok(Self::Turborepo),
"eslint-plugin-turbo" => Ok(Self::Turborepo),
"@turbo/gen" => Ok(Self::Turborepo),
"@turbo/workspaces" => Ok(Self::Turborepo),
_ => Err(anyhow::anyhow!("Unknown similar dependency")),
}
}
}

#[derive(Debug)]
pub struct UnsyncSimilarDependenciesIssue {
r#type: SimilarDependency,
versions: IndexMap<String, Vec<(String, SemVersion)>>,
fixed: bool,
}

impl UnsyncSimilarDependenciesIssue {
pub fn new(
r#type: SimilarDependency,
versions: IndexMap<String, Vec<(String, SemVersion)>>,
) -> Box<Self> {
Box::new(Self {
r#type,
versions,
fixed: false,
})
}
}

impl Issue for UnsyncSimilarDependenciesIssue {
fn name(&self) -> &str {
"unsync-similar-dependencies"
}

fn level(&self) -> super::IssueLevel {
match self.fixed {
true => super::IssueLevel::Fixed,
false => super::IssueLevel::Error,
}
}

fn message(&self) -> String {
self.versions
.iter()
.map(|(dependency, versions)| {
// let version_pad = " ".repeat(if dependency.len() >= 26 {
// 3
// } else {
// 26 - dependency.len()
// });
//
// format!(
// " {}{}{}",
// dependency.bright_black(),
// version_pad,
// versions.get(0).unwrap().1
// )

versions
.iter()
.map(|(package, version)| {
let location = format!(
"{} {}",
dependency.white(),
format!("in {}", package).bright_black()
);
let len = format!("{} in {}", dependency, package).len();
let version_pad = " ".repeat(if len >= 50 { 3 } else { 50 - len });

format!(
" {}{}{}",
location,
version_pad,
version.to_string().yellow()
)
})
.collect::<Vec<String>>()
.join("\n")
})
.collect::<Vec<String>>()
.join("\n")
}

fn why(&self) -> Cow<'static, str> {
Cow::Owned(format!("Dependencies for {} aren't synced.", self.r#type))
}

fn fix(&mut self, _package_type: &super::PackageType) -> anyhow::Result<()> {
Ok(())
}
}
Loading