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

fix clippy pedantic violations #194

Merged
merged 1 commit into from
Sep 8, 2023
Merged
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
12 changes: 6 additions & 6 deletions build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ New-Item -ItemType Directory $target > $null

$windows_projects = @("pal", "ntreg", "ntstatuserror", "ntuserinfo", "registry")
$projects = @("dsc_lib", "dsc", "osinfo", "process", "test_group_resource", "y2j", "powershellgroup")
$pedantic_clean_projects = @("dsc_lib", "dsc", "osinfo", "process", "y2j", "pal", "ntstatuserror", "ntuserinfo", "test_group_resource", "sshdconfig")
$pedantic_unclean_projects = @("ntreg")

if ($IsWindows) {
$projects += $windows_projects
Expand All @@ -108,14 +108,14 @@ foreach ($project in $projects) {
if (Test-Path "./Cargo.toml")
{
if ($Clippy) {
if ($pedantic_clean_projcets -contains $project) {
Write-Verbose -Verbose "Running clippy with pedantic for $project"
cargo clippy @flags --% -- -Dwarnings -Dclippy::pedantic
}
else {
if ($pedantic_unclean_projects -contains $project) {
Write-Verbose -Verbose "Running clippy for $project"
cargo clippy @flags -- -Dwarnings
}
else {
Write-Verbose -Verbose "Running clippy with pedantic for $project"
cargo clippy @flags --% -- -Dwarnings -Dclippy::pedantic
}
}
else {
cargo build @flags
Expand Down
23 changes: 13 additions & 10 deletions dsc/src/resource_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@ pub fn get(dsc: &mut DscManager, resource: &str, input: &Option<String>, stdin:
let mut input = get_input(input, stdin);
let mut resource = get_resource(dsc, resource);
//TODO: add to debug stream: println!("handle_resource_get - {} implemented_as - {:?}", resource.type_name, resource.implemented_as);
if resource.requires.is_some()
{
if let Some(requires) = resource.requires {
input = add_type_name_to_json(input, resource.type_name);
resource = get_resource(dsc, &resource.requires.clone().unwrap());
resource = get_resource(dsc, &requires.clone());
}

//TODO: add to debug stream: println!("handle_resource_get - input - {}", input);
Expand Down Expand Up @@ -79,10 +78,9 @@ pub fn set(dsc: &mut DscManager, resource: &str, input: &Option<String>, stdin:

//TODO: add to debug stream: println!("handle_resource_set - {} implemented_as - {:?}", resource.type_name, resource.implemented_as);

if resource.requires.is_some()
{
if let Some(requires) = resource.requires {
input = add_type_name_to_json(input, resource.type_name);
resource = get_resource(dsc, &resource.requires.clone().unwrap());
resource = get_resource(dsc, &requires.clone());
}

//TODO: add to debug stream: println!("handle_resource_get - input - {}", input);
Expand Down Expand Up @@ -112,10 +110,9 @@ pub fn test(dsc: &mut DscManager, resource: &str, input: &Option<String>, stdin:

//TODO: add to debug stream: println!("handle_resource_test - {} implemented_as - {:?}", resource.type_name, resource.implemented_as);

if resource.requires.is_some()
{
if let Some(requires) = resource.requires {
input = add_type_name_to_json(input, resource.type_name);
resource = get_resource(dsc, &resource.requires.clone().unwrap());
resource = get_resource(dsc, &requires.clone());
}

//TODO: add to debug stream: println!("handle_resource_test - input - {}", input);
Expand Down Expand Up @@ -165,7 +162,13 @@ pub fn export(dsc: &mut DscManager, resource: &str, format: &Option<OutputFormat

let mut conf = Configuration::new();

add_resource_export_results_to_configuration(&dsc_resource, &mut conf);
match add_resource_export_results_to_configuration(&dsc_resource, &mut conf) {
Ok(_) => (),
Err(err) => {
eprintln!("Error: {err}");
exit(EXIT_DSC_ERROR);
}
}

let json = match serde_json::to_string(&conf) {
Ok(json) => json,
Expand Down
65 changes: 32 additions & 33 deletions dsc/src/subcommand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use jsonschema::{JSONSchema, ValidationError};
use serde_yaml::Value;
use std::process::exit;

pub fn config_get(configurator: Configurator, format: &Option<OutputFormat>)
pub fn config_get(configurator: &Configurator, format: &Option<OutputFormat>)
{
match configurator.invoke_get(ErrorAction::Continue, || { /* code */ }) {
Ok(result) => {
Expand All @@ -40,7 +40,7 @@ pub fn config_get(configurator: Configurator, format: &Option<OutputFormat>)
}
}

pub fn config_set(configurator: Configurator, format: &Option<OutputFormat>)
pub fn config_set(configurator: &Configurator, format: &Option<OutputFormat>)
{
match configurator.invoke_set(ErrorAction::Continue, || { /* code */ }) {
Ok(result) => {
Expand All @@ -63,7 +63,7 @@ pub fn config_set(configurator: Configurator, format: &Option<OutputFormat>)
}
}

pub fn config_test(configurator: Configurator, format: &Option<OutputFormat>)
pub fn config_test(configurator: &Configurator, format: &Option<OutputFormat>)
{
match configurator.invoke_test(ErrorAction::Continue, || { /* code */ }) {
Ok(result) => {
Expand All @@ -86,7 +86,7 @@ pub fn config_test(configurator: Configurator, format: &Option<OutputFormat>)
}
}

pub fn config_export(configurator: Configurator, format: &Option<OutputFormat>)
pub fn config_export(configurator: &Configurator, format: &Option<OutputFormat>)
{
match configurator.invoke_export(ErrorAction::Continue, || { /* code */ }) {
Ok(result) => {
Expand Down Expand Up @@ -116,15 +116,15 @@ pub fn config_export(configurator: Configurator, format: &Option<OutputFormat>)
}

pub fn config(subcommand: &ConfigSubCommand, format: &Option<OutputFormat>, stdin: &Option<String>) {
if stdin.is_none() {
let Some(stdin) = stdin else {
eprintln!("Configuration must be piped to STDIN");
exit(EXIT_INVALID_ARGS);
}
};

let json: serde_json::Value = match serde_json::from_str(stdin.as_ref().unwrap()) {
let json: serde_json::Value = match serde_json::from_str(stdin.as_ref()) {
Ok(json) => json,
Err(_) => {
match serde_yaml::from_str::<Value>(stdin.as_ref().unwrap()) {
match serde_yaml::from_str::<Value>(stdin.as_ref()) {
Ok(yaml) => {
match serde_json::to_value(yaml) {
Ok(json) => json,
Expand Down Expand Up @@ -153,23 +153,24 @@ pub fn config(subcommand: &ConfigSubCommand, format: &Option<OutputFormat>, stdi

match subcommand {
ConfigSubCommand::Get => {
config_get(configurator, format);
config_get(&configurator, format);
},
ConfigSubCommand::Set => {
config_set(configurator, format);
config_set(&configurator, format);
},
ConfigSubCommand::Test => {
config_test(configurator, format);
config_test(&configurator, format);
},
ConfigSubCommand::Validate => {
validate_config(&json_string);
},
ConfigSubCommand::Export => {
config_export(configurator, format);
config_export(&configurator, format);
}
}
}

#[allow(clippy::too_many_lines)]
pub fn validate_config(config: &str) {
// first validate against the config schema
let schema = match serde_json::to_value(get_schema(DscType::Configuration)) {
Expand Down Expand Up @@ -198,7 +199,7 @@ pub fn validate_config(config: &str) {
for e in err {
error.push_str(&format!("\n{e} "));
}
eprintln!("{}", error);
eprintln!("{error}");
exit(EXIT_INVALID_INPUT);
};

Expand All @@ -211,7 +212,11 @@ pub fn validate_config(config: &str) {
};

// then validate each resource
for resource_block in config_value["resources"].as_array().unwrap().iter() {
let Some(resources) = config_value["resources"].as_array() else {
eprintln!("Error: Resources not specified");
exit(EXIT_INVALID_INPUT);
};
for resource_block in resources {
let type_name = resource_block["type"].as_str().unwrap_or_else(|| {
eprintln!("Error: Resource type not specified");
exit(EXIT_INVALID_INPUT);
Expand Down Expand Up @@ -305,45 +310,39 @@ pub fn resource(subcommand: &ResourceSubCommand, format: &Option<OutputFormat>,
}
};
let mut write_table = false;
let mut table = Table::new(vec!["Type", "Version", "Requires", "Description"]);
let mut table = Table::new(&["Type", "Version", "Requires", "Description"]);
if format.is_none() && atty::is(Stream::Stdout) {
// write as table if fornat is not specified and interactive
write_table = true;
}
for resource in dsc.find_resource(&resource_name.clone().unwrap_or_default()) {
// if description is specified, skip if resource description does not contain it
if description.is_some() || tags.is_some() {
if resource.manifest.is_none() {
let Some(ref resource_manifest) = resource.manifest else {
continue;
}

let resource_manifest = match serde_json::from_value::<ResourceManifest>(resource.clone().manifest.unwrap().clone()) {
};
let manifest = match serde_json::from_value::<ResourceManifest>(resource_manifest.clone()) {
Ok(resource_manifest) => resource_manifest,
Err(err) => {
eprintln!("Error in manifest for {0}: {err}", resource.type_name);
continue;
}
};

if description.is_some() {
if resource_manifest.description.is_none() {
continue;
}

if !resource_manifest.description.unwrap().to_lowercase().contains(&description.as_ref().unwrap().to_lowercase()) {
continue;
}
if description.is_some() &&
(manifest.description.is_none() | !manifest.description.unwrap_or_default().to_lowercase().contains(&description.as_ref().unwrap_or(&String::new()).to_lowercase())) {
continue;
}

// if tags is specified, skip if resource tags do not contain the tags
if tags.is_some() {
if resource_manifest.tags.is_none() {
if let Some(tags) = tags {
let Some(manifest_tags) = manifest.tags else {
continue;
}
};

let mut found = false;
for tag_to_find in tags.clone().unwrap() {
for tag in resource_manifest.tags.clone().unwrap() {
for tag_to_find in tags {
for tag in &manifest_tags {
if tag.to_lowercase() == tag_to_find.to_lowercase() {
found = true;
break;
Expand Down Expand Up @@ -385,7 +384,7 @@ pub fn resource(subcommand: &ResourceSubCommand, format: &Option<OutputFormat>,
table.print();
}
},
ResourceSubCommand::Get { resource, input, all } => {
ResourceSubCommand::Get { resource, input, all } => {
if *all { resource_command::get_all(&mut dsc, resource, input, stdin, format); }
else { resource_command::get(&mut dsc, resource, input, stdin, format); };
},
Expand Down
24 changes: 20 additions & 4 deletions dsc/src/tablewriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,34 @@ pub struct Table {
}

impl Table {
pub fn new(header: Vec<&str>) -> Table {
/// Create a new table.
///
/// # Arguments
///
/// * `header` - The header row
///
/// # Returns
///
/// * `Table` - The new table
#[must_use]
pub fn new(header: &[&str]) -> Table {
let mut column_widths = Vec::new();
for header_text in header.iter() {
for header_text in header {
column_widths.push(header_text.len());
}
let header = header.iter().map(|s| s.to_string()).collect::<Vec<String>>();
let header = header.iter().map(|s| (*s).to_string()).collect::<Vec<String>>();
Table {
header,
rows: Vec::new(),
column_widths,
}
}

/// Add a row to the table.
///
/// # Arguments
///
/// * `row` - The row to add
pub fn add_row(&mut self, row: Vec<String>) {
for (i, column) in row.iter().enumerate() {
if column.len() > self.column_widths[i] {
Expand All @@ -29,8 +44,9 @@ impl Table {
self.rows.push(row);
}

/// Print the table to the console.
pub fn print(&self) {
let (width, _) = size().unwrap();
let (width, _) = size().unwrap_or((80, 25));
// make header bright green
println!("\x1b[1;32m");
let mut header_row = String::new();
Expand Down
Loading