refactor: ♻️ Add toolchain module and remove utils.rs

This commit is contained in:
Sergio Gasquez 2022-10-05 12:53:43 +02:00
parent 64bc296d62
commit bc4e620e56
8 changed files with 134 additions and 116 deletions

15
src/lib.rs Normal file
View File

@ -0,0 +1,15 @@
pub mod emoji;
pub mod targets;
pub mod toolchain;
pub mod logging {
use env_logger::{Builder, Env, WriteStyle};
/// Initializes the logger
pub fn initialize_logger(log_level: &str) {
Builder::from_env(Env::default().default_filter_or(log_level))
.format_target(false)
.format_timestamp_secs()
.write_style(WriteStyle::Always)
.init();
}
}

View File

@ -1,26 +1,29 @@
use crate::espidf::{get_install_path, get_tool_path, EspIdfRepo};
use crate::gcc_toolchain::install_gcc_targets;
use crate::llvm_toolchain::LlvmToolchain;
use crate::rust_toolchain::{
check_rust_installation, get_rustup_home, install_riscv_target, RustCrate, RustToolchain,
};
use crate::targets::{parse_targets, Target};
#[cfg(windows)]
use crate::utils::check_arguments;
use crate::utils::{clear_dist_folder, export_environment, logging::initialize_logger};
use anyhow::Result; use anyhow::Result;
use clap::Parser; use clap::Parser;
use embuild::espidf::{parse_esp_idf_git_ref, EspIdfRemote}; use embuild::espidf::{parse_esp_idf_git_ref, EspIdfRemote};
use espup::{
emoji,
logging::initialize_logger,
targets::{parse_targets, Target},
toolchain::{
espidf::{
get_dist_path, get_install_path, get_tool_path, EspIdfRepo, DEFAULT_GIT_REPOSITORY,
},
gcc_toolchain::install_gcc_targets,
llvm_toolchain::LlvmToolchain,
rust_toolchain::{
check_rust_installation, get_rustup_home, install_riscv_target, RustCrate,
RustToolchain,
},
},
};
use log::{debug, info}; use log::{debug, info};
use std::{collections::HashSet, fs::remove_dir_all, path::PathBuf}; use std::{
collections::HashSet,
mod emoji; fs::{remove_dir_all, File},
mod espidf; io::Write,
mod gcc_toolchain; path::PathBuf,
mod llvm_toolchain; };
mod rust_toolchain;
mod targets;
mod utils;
#[cfg(windows)] #[cfg(windows)]
const DEFAULT_EXPORT_FILE: &str = "export-esp.ps1"; const DEFAULT_EXPORT_FILE: &str = "export-esp.ps1";
@ -230,7 +233,7 @@ fn uninstall(args: UninstallOpts) -> Result<()> {
info!("{} Deleting ESP-IDF", emoji::WRENCH); info!("{} Deleting ESP-IDF", emoji::WRENCH);
let repo = EspIdfRemote { let repo = EspIdfRemote {
git_ref: parse_esp_idf_git_ref(espidf_version), git_ref: parse_esp_idf_git_ref(espidf_version),
repo_url: Some(espidf::DEFAULT_GIT_REPOSITORY.to_string()), repo_url: Some(DEFAULT_GIT_REPOSITORY.to_string()),
}; };
remove_dir_all(get_install_path(repo).parent().unwrap())?; remove_dir_all(get_install_path(repo).parent().unwrap())?;
} }
@ -268,3 +271,55 @@ fn main() -> Result<()> {
SubCommand::Uninstall(args) => uninstall(args), SubCommand::Uninstall(args) => uninstall(args),
} }
} }
/// Deletes dist folder.
fn clear_dist_folder() -> Result<()> {
info!("{} Clearing dist folder", emoji::WRENCH);
remove_dir_all(&get_dist_path(""))?;
Ok(())
}
/// Creates the export file with the necessary environment variables.
pub fn export_environment(export_file: &PathBuf, exports: &[String]) -> Result<()> {
info!("{} Creating export file", emoji::WRENCH);
let mut file = File::create(export_file)?;
for e in exports.iter() {
file.write_all(e.as_bytes())?;
file.write_all(b"\n")?;
}
#[cfg(windows)]
info!(
"{} PLEASE set up the environment variables running: '.\\{}'",
emoji::INFO,
export_file.display()
);
#[cfg(unix)]
info!(
"{} PLEASE set up the environment variables running: '. {}'",
emoji::INFO,
export_file.display()
);
info!(
"{} This step must be done every time you open a new terminal.",
emoji::WARN
);
Ok(())
}
#[cfg(windows)]
/// For Windows, we need to check that we are installing all the targets if we are installing esp-idf.
pub fn check_arguments(targets: &HashSet<Target>, espidf_version: &Option<String>) -> Result<()> {
if espidf_version.is_some()
&& (!targets.contains(&Target::ESP32)
|| !targets.contains(&Target::ESP32C3)
|| !targets.contains(&Target::ESP32S2)
|| !targets.contains(&Target::ESP32S3))
{
bail!(
"{} When installing esp-idf in Windows, only --targets \"all\" is supported.",
emoji::ERROR
);
}
Ok(())
}

View File

@ -2,10 +2,10 @@
use crate::emoji; use crate::emoji;
use log::debug; use log::debug;
use std::collections::HashSet; use std::{collections::HashSet, str::FromStr};
use strum::{Display, EnumString}; use strum::Display;
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug, Display, EnumString)] #[derive(Clone, Copy, Hash, PartialEq, Eq, Debug, Display)]
pub enum Target { pub enum Target {
/// Xtensa LX7 based dual core /// Xtensa LX7 based dual core
@ -22,14 +22,16 @@ pub enum Target {
ESP32C3, ESP32C3,
} }
impl Target { impl FromStr for Target {
pub fn from_str(s: &str) -> Option<Self> { type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s { match s {
"esp32" => Some(Target::ESP32), "esp32" => Ok(Target::ESP32),
"esp32s2" => Some(Target::ESP32S2), "esp32s2" => Ok(Target::ESP32S2),
"esp32s3" => Some(Target::ESP32S3), "esp32s3" => Ok(Target::ESP32S3),
"esp32c3" => Some(Target::ESP32C3), "esp32c3" => Ok(Target::ESP32C3),
_ => None, _ => Err(()),
} }
} }
} }
@ -52,7 +54,7 @@ pub fn parse_targets(targets_str: &str) -> Result<HashSet<Target>, String> {
}; };
for target in targets_str { for target in targets_str {
targets.insert(Target::from_str(target).unwrap()); targets.insert(FromStr::from_str(target).unwrap());
} }
debug!("{} Parsed targets: {:?}", emoji::DEBUG, targets); debug!("{} Parsed targets: {:?}", emoji::DEBUG, targets);
Ok(targets) Ok(targets)
@ -60,8 +62,8 @@ pub fn parse_targets(targets_str: &str) -> Result<HashSet<Target>, String> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::parse_targets; use espup::parse_targets;
use crate::Target; use espup::Target;
#[test] #[test]
fn test_parse_targets() { fn test_parse_targets() {
assert_eq!( assert_eq!(

View File

@ -1,9 +1,13 @@
//! GCC Toolchain source and installation tools //! GCC Toolchain source and installation tools
use crate::emoji; use crate::{
use crate::gcc_toolchain::{get_toolchain_name, get_ulp_toolchain_name}; emoji,
use crate::targets::Target; targets::Target,
use crate::utils::get_home_dir; toolchain::{
gcc_toolchain::{get_toolchain_name, get_ulp_toolchain_name},
get_home_dir,
},
};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use embuild::{espidf, espidf::EspIdfRemote, git}; use embuild::{espidf, espidf::EspIdfRemote, git};
use log::{debug, info}; use log::{debug, info};

View File

@ -1,9 +1,10 @@
//! GCC Toolchain source and installation tools //! GCC Toolchain source and installation tools
use crate::emoji; use crate::{
use crate::espidf::get_tool_path; emoji,
use crate::targets::Target; targets::Target,
use crate::utils::download_file; toolchain::{download_file, espidf::get_tool_path},
};
use anyhow::Result; use anyhow::Result;
use embuild::espidf::EspIdfVersion; use embuild::espidf::EspIdfVersion;
use log::{debug, info}; use log::{debug, info};

View File

@ -1,8 +1,9 @@
//! LLVM Toolchain source and installation tools //! LLVM Toolchain source and installation tools
use crate::emoji; use crate::{
use crate::espidf::get_tool_path; emoji,
use crate::utils::download_file; toolchain::{download_file, espidf::get_tool_path},
};
use anyhow::{bail, Ok, Result}; use anyhow::{bail, Ok, Result};
use log::info; use log::info;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -146,7 +147,7 @@ fn get_release_with_underscores(version: &str) -> String {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::llvm_toolchain::get_release_with_underscores; use espup::llvm_toolchain::get_release_with_underscores;
#[test] #[test]
fn test_get_release_with_underscores() { fn test_get_release_with_underscores() {

View File

@ -1,5 +1,4 @@
use crate::emoji; use crate::emoji;
use crate::espidf::get_dist_path;
#[cfg(windows)] #[cfg(windows)]
use crate::targets::Target; use crate::targets::Target;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
@ -9,32 +8,17 @@ use log::info;
#[cfg(windows)] #[cfg(windows)]
use std::collections::HashSet; use std::collections::HashSet;
use std::{ use std::{
fs::{create_dir_all, remove_dir_all, File}, fs::{create_dir_all, File},
io::{copy, BufReader, Write}, io::{copy, BufReader},
path::{Path, PathBuf}, path::Path,
}; };
use tar::Archive; use tar::Archive;
use xz2::read::XzDecoder; use xz2::read::XzDecoder;
pub mod logging { pub mod espidf;
use env_logger::{Builder, Env, WriteStyle}; pub mod gcc_toolchain;
pub mod llvm_toolchain;
/// Initializes the logger pub mod rust_toolchain;
pub fn initialize_logger(log_level: &str) {
Builder::from_env(Env::default().default_filter_or(log_level))
.format_target(false)
.format_timestamp_secs()
.write_style(WriteStyle::Always)
.init();
}
}
/// Deletes dist folder.
pub fn clear_dist_folder() -> Result<()> {
info!("{} Clearing dist folder", emoji::WRENCH);
remove_dir_all(&get_dist_path(""))?;
Ok(())
}
/// Returns the path to the home directory. /// Returns the path to the home directory.
pub fn get_home_dir() -> String { pub fn get_home_dir() -> String {
@ -112,48 +96,3 @@ pub fn download_file(
} }
Ok(format!("{}/{}", output_directory, file_name)) Ok(format!("{}/{}", output_directory, file_name))
} }
/// Creates the export file with the necessary environment variables.
pub fn export_environment(export_file: &PathBuf, exports: &[String]) -> Result<()> {
info!("{} Creating export file", emoji::WRENCH);
let mut file = File::create(export_file)?;
for e in exports.iter() {
file.write_all(e.as_bytes())?;
file.write_all(b"\n")?;
}
#[cfg(windows)]
info!(
"{} PLEASE set up the environment variables running: '.\\{}'",
emoji::INFO,
export_file.display()
);
#[cfg(unix)]
info!(
"{} PLEASE set up the environment variables running: '. {}'",
emoji::INFO,
export_file.display()
);
info!(
"{} This step must be done every time you open a new terminal.",
emoji::WARN
);
Ok(())
}
#[cfg(windows)]
/// For Windows, we need to check that we are installing all the targets if we are installing esp-idf.
pub fn check_arguments(targets: &HashSet<Target>, espidf_version: &Option<String>) -> Result<()> {
if espidf_version.is_some()
&& (!targets.contains(&Target::ESP32)
|| !targets.contains(&Target::ESP32C3)
|| !targets.contains(&Target::ESP32S2)
|| !targets.contains(&Target::ESP32S3))
{
bail!(
"{} When installing esp-idf in Windows, only --targets \"all\" is supported.",
emoji::ERROR
);
}
Ok(())
}

View File

@ -1,8 +1,9 @@
//! Xtensa Rust Toolchain source and installation tools //! Xtensa Rust Toolchain source and installation tools
use crate::emoji; use crate::{
use crate::espidf::get_dist_path; emoji,
use crate::utils::{download_file, get_home_dir}; toolchain::{download_file, espidf::get_dist_path, get_home_dir},
};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use embuild::cmd; use embuild::cmd;
use log::{info, warn}; use log::{info, warn};