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: autofix root-package-private-field #17

Merged
merged 1 commit into from
Nov 1, 2023
Merged
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
36 changes: 31 additions & 5 deletions src/rules/root_package_private_field.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
use super::{Issue, IssueLevel};
use super::{Issue, IssueLevel, PackageType};
use anyhow::Result;
use colored::Colorize;
use std::borrow::Cow;
use std::{borrow::Cow, fs, path::PathBuf};

#[derive(Debug)]
pub struct RootPackagePrivateFieldIssue;
pub struct RootPackagePrivateFieldIssue {
fixed: bool,
}

impl RootPackagePrivateFieldIssue {
pub fn new() -> Box<Self> {
Box::new(Self)
Box::new(Self { fixed: false })
}
}

Expand All @@ -17,7 +20,10 @@ impl Issue for RootPackagePrivateFieldIssue {
}

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

fn message(&self) -> String {
Expand All @@ -37,6 +43,26 @@ impl Issue for RootPackagePrivateFieldIssue {
fn why(&self) -> Cow<'static, str> {
Cow::Borrowed("The root package.json should be private to prevent accidentaly publishing it to a registry.")
}

fn fix(&mut self, package_type: &PackageType) -> Result<()> {
if let PackageType::Root = package_type {
let path = PathBuf::from("package.json");
let value = fs::read_to_string(&path)?;
let mut value = serde_json::from_str::<serde_json::Value>(&value)?;

value.as_object_mut().unwrap().insert(
"private".to_string(),
serde_json::Value::String("true".to_string()),
);

let value = serde_json::to_string_pretty(&value)?;
fs::write(path, value)?;

self.fixed = true;
}

Ok(())
}
}

#[cfg(test)]
Expand Down
Loading