Skip to content

Commit

Permalink
added code docuementation
Browse files Browse the repository at this point in the history
  • Loading branch information
MordechaiHadad committed Jun 13, 2024
1 parent 5fb270c commit 6821ff1
Show file tree
Hide file tree
Showing 21 changed files with 1,700 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use reqwest::{Client, Error};
use tracing::{error, info};

/// Creates a new `reqwest::Client` with default headers.
///
/// This function fetches the `GITHUB_TOKEN` environment variable and uses it to set the `Authorization` header for the client.
///
/// # Returns
///
/// This function returns a `Result` that contains a `reqwest::Client` if the client was successfully created, or an `Error` if the client could not be created.
///
/// # Example
///
/// ```rust
/// let client = create_reqwest_client();
/// ```
///
/// # Errors
///
/// This function will return an error if the `reqwest::Client` could not be built.
fn create_reqwest_client() -> Result<Client, Error> {
// fetch env variable
let github_token = std::env::var("GITHUB_TOKEN");
Expand All @@ -32,6 +49,8 @@ fn create_reqwest_client() -> Result<Client, Error> {
Ok(client)
}


/// The `Cli` enum represents the different commands that can be used in the command-line interface.
#[derive(Debug, Parser)]
#[command(version)]
enum Cli {
Expand Down Expand Up @@ -86,6 +105,23 @@ enum Cli {
Update(Update),
}

/// Represents an update command in the CLI.
///
/// This struct contains options for the update command, such as the version to update and whether to update all versions.
///
/// # Fields
///
/// * `version: Option<String>` - The version to update. This can be either "nightly" or "stable". This field conflicts with the `all` field, meaning you can't specify a version and use `all` at the same time.
/// * `all: bool` - Whether to apply the update to all versions. If this is `true`, the `version` field must be `None`.
///
/// # Example
///
/// ```rust
/// let update = Update {
/// version: Some("nightly".to_string()),
/// all: false,
/// };
/// ```
#[derive(Args, Debug)]
pub struct Update {
/// Update specified version |nightly|stable|
Expand All @@ -97,6 +133,24 @@ pub struct Update {
pub all: bool,
}

/// Starts the CLI application.
///
/// This function takes a `Config` object as input and returns a `Result`. It creates a Reqwest client, parses the CLI arguments, and then handles the arguments based on their type.
///
/// # Arguments
///
/// * `config: Config` - The configuration for the application.
///
/// # Returns
///
/// * `Result<()>` - Returns a `Result`. If the function completes successfully, it returns `Ok(())`. If an error occurs, it returns `Err`.
///
/// # Example
///
/// ```rust
/// let config = Config::default();
/// start(config).await.unwrap();
/// ```
pub async fn start(config: Config) -> Result<()> {
let client = create_reqwest_client()?;
let cli = Cli::parse();
Expand Down
90 changes: 90 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,34 @@ use serde::{Deserialize, Serialize};
use std::env;
use tokio::fs::{self};

/// Represents the application configuration.
///
/// This struct contains various configuration options for the application, such as whether to enable nightly info, whether to enable release build, the location for downloads, the location for installation, the location for the version sync file, the GitHub mirror to use, and the rollback limit.
///
/// # Fields
///
/// * `enable_nightly_info: Option<bool>` - Whether to enable nightly info. This is optional and may be `None`.
/// * `enable_release_build: Option<bool>` - Whether to enable release build. This is optional and may be `None`.
/// * `downloads_location: Option<String>` - The location for downloads. This is optional and may be `None`.
/// * `installation_location: Option<String>` - The location for installation. This is optional and may be `None`.
/// * `version_sync_file_location: Option<String>` - The location for the version sync file. This is optional and may be `None`.
/// * `github_mirror: Option<String>` - The GitHub mirror to use. This is optional and may be `None`.
/// * `rollback_limit: Option<u8>` - The rollback limit. This is optional and may be `None`.
///
/// # Example
///
/// ```rust
/// let config = Config {
/// enable_nightly_info: Some(true),
/// enable_release_build: Some(false),
/// downloads_location: Some("/path/to/downloads".to_string()),
/// installation_location: Some("/path/to/installation".to_string()),
/// version_sync_file_location: Some("/path/to/version_sync_file".to_string()),
/// github_mirror: Some("https://github.com".to_string()),
/// rollback_limit: Some(5),
/// };
/// println!("The configuration is {:?}", config);
/// ```
#[derive(Serialize, Deserialize, Debug)]
pub struct Config {
pub enable_nightly_info: Option<bool>,
Expand All @@ -15,6 +43,20 @@ pub struct Config {
pub rollback_limit: Option<u8>,
}

/// Handles the application configuration.
///
/// This function reads the configuration file, which can be in either TOML or JSON format, and returns a `Config` object. If the configuration file does not exist, it returns a `Config` object with all fields set to `None`.
///
/// # Returns
///
/// * `Result<Config>` - Returns a `Result` that contains a `Config` object if the function completes successfully. If an error occurs, it returns `Err`.
///
/// # Example
///
/// ```rust
/// let config = handle_config().await.unwrap();
/// println!("The configuration is {:?}", config);
/// ```
pub async fn handle_config() -> Result<Config> {
let config_file = crate::helpers::directories::get_config_file()?;
let config = match fs::read_to_string(&config_file).await {
Expand Down Expand Up @@ -43,6 +85,33 @@ pub async fn handle_config() -> Result<Config> {
Ok(config)
}

/// Handles environment variables in the configuration.
///
/// This function takes a mutable reference to a `Config` object. It creates a `Regex` to match environment variables in the format `$VARIABLE_NAME`. It then calls the `handle_envar` function for each field in the `Config` object that may contain an environment variable.
///
/// # Arguments
///
/// * `config: &mut Config` - A mutable reference to a `Config` object that may contain environment variables.
///
/// # Returns
///
/// * `Result<()>` - Returns `Ok(())` if the function completes successfully. If an error occurs, it returns `Err`.
///
/// # Example
///
/// ```rust
/// let mut config = Config {
/// downloads_location: Some("DOWNLOADS=${DOWNLOADS}".to_string()),
/// github_mirror: Some("GITHUB=${GITHUB}".to_string()),
/// installation_location: Some("INSTALL=${INSTALL}".to_string()),
/// version_sync_file_location: Some("SYNC=${SYNC}".to_string()),
/// };
/// handle_envars(&mut config).unwrap();
/// assert_eq!(config.downloads_location, Some(format!("DOWNLOADS={}", env::var("DOWNLOADS").unwrap())));
/// assert_eq!(config.github_mirror, Some(format!("GITHUB={}", env::var("GITHUB").unwrap())));
/// assert_eq!(config.installation_location, Some(format!("INSTALL={}", env::var("INSTALL").unwrap())));
/// assert_eq!(config.version_sync_file_location, Some(format!("SYNC={}", env::var("SYNC").unwrap())));
/// ```
fn handle_envars(config: &mut Config) -> Result<()> {
let re = Regex::new(r"\$([A-Z_]+)").unwrap();

Expand All @@ -57,6 +126,27 @@ fn handle_envars(config: &mut Config) -> Result<()> {
Ok(())
}

/// Handles environment variables in the configuration.
///
/// This function takes a mutable reference to an `Option<String>` and a reference to a `Regex`. If the `Option<String>` is `None`, the function returns `Ok(())`. If the `Option<String>` is `Some(value)`, the function checks if the `value` matches the `Regex`. If it does, the function extracts the environment variable from the `value`, replaces the environment variable in the `value` with its value from the environment, and updates the `Option<String>` with the new `value`.
///
/// # Arguments
///
/// * `item: &mut Option<String>` - A mutable reference to an `Option<String>` that may contain an environment variable.
/// * `re: &Regex` - A reference to a `Regex` to match the environment variable in the `Option<String>`.
///
/// # Returns
///
/// * `Result<()>` - Returns `Ok(())` if the function completes successfully. If an error occurs, it returns `Err`.
///
/// # Example
///
/// ```rust
/// let mut item = Some("HOME=${HOME}".to_string());
/// let re = Regex::new(r"\$\{(.+?)\}").unwrap();
/// handle_envar(&mut item, &re).unwrap();
/// assert_eq!(item, Some(format!("HOME={}", env::var("HOME").unwrap())));
/// ```
fn handle_envar(item: &mut Option<String>, re: &Regex) -> Result<()> {
let value = if let Some(value) = item.as_ref() {
value
Expand Down
Loading

0 comments on commit 6821ff1

Please sign in to comment.