Skip to content

Commit

Permalink
Fully finished for push
Browse files Browse the repository at this point in the history
  • Loading branch information
lmcgee4 committed Dec 2, 2024
1 parent d38f7e5 commit b262969
Show file tree
Hide file tree
Showing 2 changed files with 141 additions and 178 deletions.
245 changes: 116 additions & 129 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use clap::{Arg, Command};
use semver::VersionReq;
use utils::abort;
use std::iter;

mod commands;
mod constants;
Expand All @@ -13,133 +14,119 @@ mod utils;
// spec_vals.push(format!("[aliases: {all_als}]"));

fn main() {
// let matches = Command::new("pen")
// .bin_name("pen")
// .version("0.5.0")
// .about("pen is a tool for managing Python environments with different Python versions.")
// .subcommand_required(true)
// .arg_required_else_help(true)
// .help_template("{about} (v{version})\n\n{usage-heading} {usage}\n\n{all-args}")

// .subcommand(Command::new("init")
// .visible_alias("c")
// // .styles(clap::builder::styling::Styles::styled()
// // .header(clap::builder::styling::AnsiColor::Green.on_default() | clap::builder::styling::Effects::BOLD)
// // )
// .about("Create a virtual environment with a Python version")
// .long_about("Create a new virtual environment with the specified Python version in the current directory")
// .arg(Arg::new("pyversion") // todo do we need required(true)
// .help("Specify the Python version (ex. pen init 3.11.9)")
// .index(1)))
// .subcommand(Command::new("sync")
// .visible_alias("s")
// .about("Syncs the installed packages and the .venv with the pen.toml file")
// .long_about("Creates the .venv according to the config"))
// .subcommand(Command::new("pkgs")
// .about("Lists packages todo")
// .long_about("todo"))
// .subcommand(Command::new("add")
// .about("Add a package to the current project")
// .long_about("Add a PyPI package to the current project (pip but faster)")
// .arg(Arg::new("name")
// .help("The package to install")
// .required(true)
// .index(1))
// .arg(Arg::new("version")
// .help("The version to install")
// .required(false)
// .index(2)))
// .subcommand(Command::new("activate")
// .about("Activate the virtual environment")
// .visible_alias("a"))
// .long_about("Activate the virtual environment in the current directory")
// .subcommand(Command::new("list")
// .visible_alias("l")
// .about("List Python versions")
// .long_about("List the installed Python versions from pen"))
// .subcommand(Command::new("delete")
// .about("Delete a Python version")
// .long_about("Delete a specific Python version")
// .arg(Arg::new("pyversion")
// .help("Specify the Python version to delete (this might break installed .venv until the version is installed again)")
// .required(true)
// .index(1)))
// .subcommand(Command::new("update")
// .about("Update pen")
// .long_about("Update pen to the latest version, if available"))
// .subcommand(Command::new("uninstall")
// .about("Uninstall pen")
// .long_about("Completely uninstall pen from the computer (does not include virtual environements)"))

// .get_matches();

// let dependencies = vec!["tar", "make"]; // todo goal of having no system dependencies
// utils::assert_dependencies(dependencies);
// utils::assert_global_paths();
// utils::clear_temp();

// match matches.subcommand() {
// // Python
// Some(("list", _args)) => {
// commands::py_list_versions();
// }
// Some(("delete", args)) => {
// let py_version: &String = args.get_one("pyversion").expect("required argument");
// commands::py_delete_version(py_version);
// }

// //* Pen
// Some(("init", args)) => {
// let version = utils::user_string_to_version(args.get_one::<String>("pyversion"));

// commands::env_init(version);
// }
// Some(("sync", _args)) => {
// commands::env_sync();
// }
// Some(("pkgs", _args)) => {
// commands::env_pkgs();
// }
// Some(("add", args)) => {
// let name = args.get_one::<String>("name").expect("required argument");
// let version = match args.get_one::<String>("version") {
// Some(version) => match VersionReq::parse(version) {
// Ok(version) => version,
// Err(e) => abort("Invalid version range", Some(&e)),
// },
// None => VersionReq::default(),
// };

// commands::env_add(name, &version);
// }
// Some(("activate", _args)) => {
// commands::pen_activate();
// }

// // Installation
// Some(("uninstall", _args)) => {
// commands::pen_uninstall();
// }
// Some(("update", _args)) => {
// let message = "Updating pen automatically is not yet implemented. For now, uninstall pen with `pen uninstall` and download it again to update it. Updates will be coming in v1.0.0 so keep an eye on the \x1b]8;;https://github.com/azomDev/pen\x1b\\\x1b[34mgithub\x1b[0m\x1b]8;;\x1b\\";
// println!("{}", message);
// }
// _ => {
// abort("Unknown command", None);
// }
// }

fetch_current();


let matches = Command::new("pen")
.bin_name("pen")
.version("0.5.0")
.about("pen is a tool for managing Python environments with different Python versions.")
.subcommand_required(true)
.arg_required_else_help(true)
.help_template("{about} (v{version})\n\n{usage-heading} {usage}\n\n{all-args}")

.subcommand(Command::new("init")
.visible_alias("c")
// .styles(clap::builder::styling::Styles::styled()
// .header(clap::builder::styling::AnsiColor::Green.on_default() | clap::builder::styling::Effects::BOLD)
// )
.about("Create a virtual environment with a Python version")
.long_about("Create a new virtual environment with the specified Python version in the current directory")
.arg(Arg::new("pyversion") // todo do we need required(true)
.help("Specify the Python version (ex. pen init 3.11.9)")
.index(1)))
.subcommand(Command::new("sync")
.visible_alias("s")
.about("Syncs the installed packages and the .venv with the pen.toml file")
.long_about("Creates the .venv according to the config"))
.subcommand(Command::new("pkgs")
.about("Lists packages todo")
.long_about("todo"))
.subcommand(Command::new("add")
.about("Add a package to the current project")
.long_about("Add a PyPI package to the current project (pip but faster)")
.arg(Arg::new("name")
.help("The package to install")
.required(true)
.index(1))
.arg(Arg::new("version")
.help("The version to install")
.required(false)
.index(2)))
.subcommand(Command::new("activate")
.about("Activate the virtual environment")
.visible_alias("a"))
.long_about("Activate the virtual environment in the current directory")
.subcommand(Command::new("list")
.visible_alias("l")
.about("List Python versions")
.long_about("List the installed Python versions from pen"))
.subcommand(Command::new("delete")
.about("Delete a Python version")
.long_about("Delete a specific Python version")
.arg(Arg::new("pyversion")
.help("Specify the Python version to delete (this might break installed .venv until the version is installed again)")
.required(true)
.index(1)))
.subcommand(Command::new("update")
.about("Update pen")
.long_about("Update pen to the latest version, if available"))
.subcommand(Command::new("uninstall")
.about("Uninstall pen")
.long_about("Completely uninstall pen from the computer (does not include virtual environements)"))

.get_matches();

let dependencies = vec!["tar", "make"]; // todo goal of having no system dependencies
utils::assert_dependencies(dependencies);
utils::assert_global_paths();
utils::clear_temp();

match matches.subcommand() {
// Python
Some(("list", _args)) => {
commands::py_list_versions();
}
Some(("delete", args)) => {
let py_version: &String = args.get_one("pyversion").expect("required argument");
commands::py_delete_version(py_version);
}

//* Pen
Some(("init", args)) => {
let version = utils::user_string_to_version(args.get_one::<String>("pyversion"));

commands::env_init(version);
}
Some(("sync", _args)) => {
commands::env_sync();
}
Some(("pkgs", _args)) => {
commands::env_pkgs();
}
Some(("add", args)) => {
let name = args.get_one::<String>("name").expect("required argument");
let version = match args.get_one::<String>("version") {
Some(version) => match VersionReq::parse(version) {
Ok(version) => version,
Err(e) => abort("Invalid version range", Some(&e)),
},
None => VersionReq::default(),
};

commands::env_add(name, &version);
}
Some(("activate", _args)) => {
commands::pen_activate();
}

// Installation
Some(("uninstall", _args)) => {
commands::pen_uninstall();
}
Some(("update", _args)) => {
let message = "Updating pen automatically is not yet implemented. For now, uninstall pen with `pen uninstall` and download it again to update it. Updates will be coming in v1.0.0 so keep an eye on the \x1b]8;;https://github.com/azomDev/pen\x1b\\\x1b[34mgithub\x1b[0m\x1b]8;;\x1b\\";
println!("{}", message);
}
_ => {
abort("Unknown command", None);
}
}
}

pub fn fetch_current() {
use serde_json::Value;

// Value could be any type that implements Deserialize!
let result = minreq::get("https://endoflife.date/api/python.json").send().unwrap().json::<Value>().unwrap();


println!("{:?}", result);
}
74 changes: 25 additions & 49 deletions src/utils/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,10 @@ pub fn download_file(file_url: &str, file_path: &PathBuf) {
/// Takes the iputted version and returns the current patch of python
///
/// # Arguments
/// - `version` : a string inputted to be checked
/// - `patch` : a string representing the "x.y" part of the release
///
/// # Output
/// - `patch` : the patch found from the provided version
/// - Will output the full version from provided
///
/// #Termination
/// - An error should be thrown if the file for checking is not found, or if the version is not found.
Expand All @@ -136,58 +136,34 @@ pub fn download_file(file_url: &str, file_path: &PathBuf) {
///
/// # Limitations
/// - The function assumes that all data passed to it is in the correct format and clean
pub fn fetch_current(version: &str) {
// get the file containing the versions
use serde_json::Value;
pub fn fetch_current(patch : &str) -> Option<String> {
// Currently a JSON file from endoflife: https://endoflife.date/python
use serde_json::{Value};

// Value could be any type that implements Deserialize!
// get the file containing the versions
// also specifies that the file returned is serde_json
let result = minreq::get("https://endoflife.date/api/python.json").send().unwrap().json::<Value>().unwrap();
//println!("User name is '{}'", user["name"]);

//let result = minreq::get("https://endoflife.date/api/python.json").send();

//let json: serde_json::Value = result.json();

// match Patch::parse(patch) {
// Ok(patch) => patch,
// Error(e) => abort(&format!("error"), Some(&e))
// };

println!("{:?}", result);

// let response = minreq::get("http://httpbin.org/anything")
// .with_body("Hello, world!")
// .send()?;

// // httpbin.org/anything returns the body in the json field "data":
// let json: serde_json::Value = response.json()?;
// println!("\"Hello, world!\" == {}", json["data"]);

// Ok(())
// Loop through the JSON to get the needed "latest"
// First, we create a reference for the file that the JSON is in, since it does not like looping through it itself
if let serde_json::Value::Array(ref json) = result {
// Since the JSON is an array of objects, we need to loop through the outer array
for i in json {
// Now we loop through the "key: value"s of each object
for (key, value) in i.as_object().unwrap() {
// We check if the "cycle" key equals the inputted "value"
if (key == "cycle") && (value == patch){
// returns the latest
return Some(i["latest"].to_string());
}
}
}
}

// If nothing is found, returns None
return None;
}
// use minreq;
// use serde::Deserialize;
// #[derive(Deserialize, Debug)]
// struct PythonVersion {
// version: String,
// end_of_life: String,
// }

// fn fetch_current() -> Result<(), Box<dyn std::error::Error>> {
// let url = "https://endoflife.date/api/python.json";

// // Send the GET request and deserialize the response directly into the Vec<PythonVersion>
// let response: Vec<PythonVersion> = minreq::get(url)
// .send()?
// .json()?;

// // Print the parsed JSON
// for version in response {
// println!("Version: {}, End of Life: {}", version.version, version.end_of_life);
// }

// Ok(())
// }

/// Checks if the specified dependencies are installed by running their `--help` command.
///
Expand Down

0 comments on commit b262969

Please sign in to comment.