Skip to content

Commit

Permalink
Support for many new things
Browse files Browse the repository at this point in the history
  • Loading branch information
Pencilcaseman committed Aug 12, 2024
1 parent befcecd commit aab1ed2
Show file tree
Hide file tree
Showing 10 changed files with 307 additions and 169 deletions.
6 changes: 6 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use_small_heuristics = "Max"
max_width = 80

unstable_features = true
imports_granularity = "Crate"
group_imports = "StdExternalCrate"
46 changes: 30 additions & 16 deletions src/builders/make.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use crate::{builders::builder_trait::BuilderImpl, cli::child_logger, log, shell::Shell};
use pyo3::prelude::PyAnyMethods;
use pyo3::{Bound, PyAny};
use std::{fs, path, path::Path, process::Command};

use pyo3::{prelude::PyAnyMethods, Bound, PyAny};

use crate::{
builders::builder_trait::BuilderImpl, cli::child_logger, log, shell::Shell,
};

#[derive(Debug, Clone)]
pub struct Make {
pub configure: bool,
Expand All @@ -26,14 +29,21 @@ impl Make {

fs::create_dir_all(build_path).map_err(|e| e.to_string())?;

let source_path = path::absolute(source_path).map_err(|err| err.to_string())?;
let build_path = path::absolute(build_path).map_err(|err| err.to_string())?;
let install_path = path::absolute(install_path).map_err(|err| err.to_string())?;
let source_path =
path::absolute(source_path).map_err(|err| err.to_string())?;
let build_path =
path::absolute(build_path).map_err(|err| err.to_string())?;
let install_path =
path::absolute(install_path).map_err(|err| err.to_string())?;

let mut shell = Shell::default();
shell.set_current_dir(&build_path);

println!("Module Source: {source_path:?}");
println!("{dependencies:?}");

for dep in dependencies {
log::info(&format!("Loading module: {dep}"));
shell.add_command(&format!("module load {dep}"));
}

Expand Down Expand Up @@ -99,9 +109,13 @@ impl BuilderImpl for Make {
fn from_py(object: &Bound<PyAny>) -> Result<Self, String> {
let configure: bool = object
.getattr("configure")
.map_err(|_| "Failed to read attribute 'configure' of Builder object")?
.map_err(|_| {
"Failed to read attribute 'configure' of Builder object"
})?
.extract()
.map_err(|_| "Failed to convert attribute 'configure' to Rust bool")?;
.map_err(|_| {
"Failed to convert attribute 'configure' to Rust bool"
})?;

let jobs: usize = object
.getattr("jobs")
Expand All @@ -115,11 +129,7 @@ impl BuilderImpl for Make {
.extract()
.map_err(|_| "Failed to convert attribute 'configure_flags' to Rust Vec<String>")?;

Ok(Self {
configure,
jobs,
configure_flags,
})
Ok(Self { configure, jobs, configure_flags })
}

fn build<
Expand All @@ -145,13 +155,17 @@ impl BuilderImpl for Make {
install_path: &P2,
dependencies: &[String],
) -> Result<(), String> {
let build_path = path::absolute(build_path).map_err(|err| err.to_string())?;
let install_path = path::absolute(install_path).map_err(|err| err.to_string())?;
let build_path =
path::absolute(build_path).map_err(|err| err.to_string())?;
let install_path =
path::absolute(install_path).map_err(|err| err.to_string())?;

fs::create_dir_all(install_path).map_err(|e| e.to_string())?;

if !build_path.exists() {
return Err(format!("Source directory {build_path:?} does not exist"));
return Err(format!(
"Source directory {build_path:?} does not exist"
));
}

let mut shell = Shell::default();
Expand Down
57 changes: 36 additions & 21 deletions src/callbacks.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use std::io::Write;

use colored::Colorize;

use crate::{
config, log,
module::{self, get_modules, Module},
module_resolver,
};
use colored::Colorize;
use std::io::Write;

/// Internal boilerplate handler which, given a set of partials and a function,
/// finds the specified module and passes it to the function.
Expand All @@ -19,7 +21,9 @@ pub fn resolver_boilerplate(
match module_resolver::resolve(partials)? {
module_resolver::ResolveMatch::Full(m) => func(&m),
module_resolver::ResolveMatch::Partial(m) => {
let mut err = String::from("Multiple modules match the provided partial(s):\n");
let mut err = String::from(
"Multiple modules match the provided partial(s):\n",
);

// Always valid, as `m.len()` >= 1, so `log(m.len())` >= 0
#[allow(
Expand All @@ -44,7 +48,8 @@ pub fn resolver_boilerplate(
)]
let digits = (index as f64 + 0.05).log10() as usize;

let mut index_str = String::from(" ").repeat(max_digits - digits);
let mut index_str =
String::from(" ").repeat(max_digits - digits);
index_str.push_str(&format!("{index}"));

err.push_str(&format!(
Expand All @@ -66,20 +71,18 @@ pub fn resolver_boilerplate(

match std::io::stdin().read_line(&mut selection) {
Ok(_) if selection.trim() == "all" => all = true,
Ok(_) => {
match selection.trim().parse::<usize>() {
Ok(num) if num < m.len() => {
valid = true;
selection_index = num;
}
Ok(_) => {
log::warn("Invalid index selected");
}
Err(_) => {
log::warn("Invalid input received. Input must be a positive integer or 'all'");
}
Ok(_) => match selection.trim().parse::<usize>() {
Ok(num) if num < m.len() => {
valid = true;
selection_index = num;
}
}
Ok(_) => {
log::warn("Invalid index selected");
}
Err(_) => {
log::warn("Invalid input received. Input must be a positive integer or 'all'");
}
},
Err(_) => {
log::warn("Failed to read input");
}
Expand Down Expand Up @@ -141,7 +144,10 @@ pub fn list_callback(_config: &config::Config) -> Result<(), String> {
///
/// Will error if a single module cannot be resolved from the specified name,
/// or if the call to [`Module.download`] fails.
pub fn download_module(partials: &[&str], _config: &config::Config) -> Result<(), String> {
pub fn download_module(
partials: &[&str],
_config: &config::Config,
) -> Result<(), String> {
resolver_boilerplate(partials, module::download)
}

Expand All @@ -164,7 +170,10 @@ pub fn download_all(_config: &config::Config) -> Result<(), String> {
///
/// Errors if a single module cannot be resolved from the specified name,
/// or if the call to [`Module.build`] fails.
pub fn build_module(partials: &[&str], _config: &config::Config) -> Result<(), String> {
pub fn build_module(
partials: &[&str],
_config: &config::Config,
) -> Result<(), String> {
resolver_boilerplate(partials, module::build)
}

Expand All @@ -187,11 +196,17 @@ pub fn build_all(_config: &config::Config) -> Result<(), String> {
///
/// Returns [`Err(string)`] if a single module cannot be resolved from the
/// specified name, or if the call to [`Module.install`] fails.
pub fn install_module(partials: &[&str], _config: &config::Config) -> Result<(), String> {
pub fn install_module(
partials: &[&str],
_config: &config::Config,
) -> Result<(), String> {
resolver_boilerplate(partials, module::install)
}

pub fn write_modulefile(partials: &[&str], _config: &config::Config) -> Result<(), String> {
pub fn write_modulefile(
partials: &[&str],
_config: &config::Config,
) -> Result<(), String> {
resolver_boilerplate(partials, module::modulefile)
}

Expand Down
49 changes: 32 additions & 17 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use std::io;
use std::io::{BufRead, ErrorKind};
use std::process::ExitStatus;
use std::thread;
use std::{
io,
io::{BufRead, ErrorKind},
process::ExitStatus,
thread,
};

use anstyle::AnsiColor;
use clap::builder::styling::Styles;
Expand Down Expand Up @@ -41,20 +43,21 @@ pub fn child_logger(
let stdout_reader = io::BufReader::new(stdout);
let stderr_reader = io::BufReader::new(stderr);

let console_width = crossterm::terminal::size().unwrap_or((24_u16, 80_u16)).0 as usize;
let console_width =
crossterm::terminal::size().unwrap_or((24_u16, 80_u16)).0 as usize;

let stdout_lines = stdout_reader.lines().map_while(Result::ok);
let stderr_lines = stderr_reader.lines().map_while(Result::ok);

let mut stdout = Vec::new();
let mut stderr = Vec::new();

let stdout_thread = thread::Builder::new()
.name("STDOUT".to_string())
.spawn(move || {
let stdout_thread =
thread::Builder::new().name("STDOUT".to_string()).spawn(move || {
for mut line in stdout_lines {
stdout.push(line.clone());
let trunc = line.floor_char_boundary(console_width.max(13) - 13);
let trunc =
line.floor_char_boundary(console_width.max(13) - 13);
line.truncate(trunc);
log::info_carriage(&line);
}
Expand All @@ -67,12 +70,12 @@ pub fn child_logger(
}
let stdout_thread = stdout_thread.unwrap();

let stderr_thread = thread::Builder::new()
.name("STDERR".to_string())
.spawn(move || {
let stderr_thread =
thread::Builder::new().name("STDERR".to_string()).spawn(move || {
for mut line in stderr_lines {
stderr.push(line.clone());
let trunc = line.floor_char_boundary(console_width.max(13) - 13);
let trunc =
line.floor_char_boundary(console_width.max(13) - 13);
line.truncate(trunc);
log::warn_carriage(&line);
}
Expand Down Expand Up @@ -109,20 +112,31 @@ pub trait CommandBuilder {
fn add_subcommand(self, cmd: clap::Command) -> Self;

#[must_use]
fn add_argument(self, name: &'static str, help: &'static str, num_params: &NumParams) -> Self;
fn add_argument(
self,
name: &'static str,
help: &'static str,
num_params: &NumParams,
) -> Self;
}

#[must_use]
pub fn command_group(id: &'static str, multiple: bool) -> clap::Command {
clap::Command::new("sccmod").group(clap::ArgGroup::new(id).multiple(multiple))
clap::Command::new("sccmod")
.group(clap::ArgGroup::new(id).multiple(multiple))
}

impl CommandBuilder for clap::Command {
fn add_subcommand(self, cmd: clap::Command) -> Self {
self.subcommand(cmd)
}

fn add_argument(self, name: &'static str, help: &'static str, num_params: &NumParams) -> Self {
fn add_argument(
self,
name: &'static str,
help: &'static str,
num_params: &NumParams,
) -> Self {
self.arg(
clap::Arg::new(name)
.help(help)
Expand Down Expand Up @@ -206,7 +220,8 @@ impl Command {
// }

if let Some(values) = matches.get_many::<String>(arg.name) {
let values: Vec<&str> = values.map(std::string::String::as_str).collect();
let values: Vec<&str> =
values.map(std::string::String::as_str).collect();
(arg.callback)(&values, config)?;
arg_count += 1;

Expand Down
Loading

0 comments on commit aab1ed2

Please sign in to comment.