Skip to content

Commit

Permalink
updating pathbuf
Browse files Browse the repository at this point in the history
  • Loading branch information
hlafaille committed Apr 14, 2024
1 parent 6601b14 commit d82dbce
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 41 deletions.
27 changes: 16 additions & 11 deletions src/backend/context.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use std::{env, error, io, path, result};

use super::{lock::{self, StateLockFile}, project::get_config_from_fs, Config};
use super::{
lock::{self, StateLockFile},
project::get_config_from_fs,
Config,
};

/// Represents the context of the currently loaded project.
pub struct ProjectContext {
Expand Down Expand Up @@ -89,7 +93,7 @@ pub fn get_absolute_paths(debug_mode: &bool) -> io::Result<AbsoltuePaths> {
dependencies: (cwd_string.clone() + "/.espresso/dependencies").into(),
state_lockfile: (cwd_string.clone() + "/.espresso/state.lock.toml").into(),
dependencies_extracted: (cwd_string.clone() + "/.espresso/dependencies_extracted").into(),
build: (cwd_string.clone() + "/build").into()
build: (cwd_string.clone() + "/build").into(),
})
}

Expand All @@ -104,13 +108,14 @@ pub fn get_absolute_paths(debug_mode: &bool) -> io::Result<AbsoltuePaths> {
///
/// DynamicAbsolutePaths
pub fn get_dynamic_absolute_paths(ap: &AbsoltuePaths, config: &Config) -> DynamicAbsolutePaths {
let base_package = ap.source.clone()
+ "/" + config
.project
.base_package
.clone()
.replace(".", "/")
.as_str();
let base_package = ap.source.clone().to_string_lossy()
+ "/"
+ config
.project
.base_package
.clone()
.replace(".", "/")
.as_str();
DynamicAbsolutePaths { base_package }
}

Expand All @@ -125,12 +130,12 @@ pub fn get_project_context() -> result::Result<ProjectContext, Box<dyn error::Er
let config = get_config_from_fs(&absolute_paths)?;
let state_lock_file = lock::get_state_lockfile_from_fs(&absolute_paths)?;
let dynamic_absolute_paths = get_dynamic_absolute_paths(&absolute_paths, &config);

Ok(ProjectContext {
config,
state_lock_file,
absolute_paths,
debug_mode,
dynamic_absolute_paths,
})
}
}
4 changes: 2 additions & 2 deletions src/backend/dependency/manifest.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, error, fs, result};
use std::{collections::HashMap, error, fs, path, result};

/// Represents the common fields in a MANIFEST.MF file
pub enum CommonFields {
Expand Down Expand Up @@ -30,7 +30,7 @@ impl CommonFields {
///
/// # Returns
/// A `HashMap<String, String>` representing the key/value pairs in the manifest.
pub fn parse(path: &String) -> result::Result<HashMap<String, String>, Box<dyn error::Error>> {
pub fn parse(path: &path::PathBuf) -> result::Result<HashMap<String, String>, Box<dyn error::Error>> {
let content = fs::read_to_string(path)?;
let mut manifest_hashmap: HashMap<String, String> = HashMap::new();
for line in content.lines() {
Expand Down
48 changes: 31 additions & 17 deletions src/backend/dependency/resolve.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
use std::{collections::HashMap, error, fmt::format, result};
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, error, path, result};

use crate::{backend::context::ProjectContext, frontend::terminal::print_err, util::{self, error::EspressoError, net::download_file}};
use crate::{
backend::context::ProjectContext,
util::{self, error::EspressoError, net::download_file},
};

/// Represents a resolved dependency
#[derive(Serialize, Deserialize)]
pub struct QueryPackagesResponse {
pub packages: Vec<Package>
pub packages: Vec<Package>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Package {
pub metadata: PackageMetadata,
pub group_id: String,
pub artifact_id: String,
#[serde(rename="ref")]
#[serde(rename = "ref")]
pub ref_: String,
}

Expand Down Expand Up @@ -43,52 +46,63 @@ pub enum Flags {
}

/// Query for packages from the Espresso Registry
///
///
/// # Arguments
/// * `q`: The query string
///
///
/// # Returns
/// Propagated errors, returns a `Vec` of `Package` struct(s). The `Vec` will be empty if no packages were returned in the query.
pub async fn query(q: &String) -> result::Result<Vec<Package>, Box<dyn error::Error>> {
let client = reqwest::Client::new();

// make a request to the registry
let response = client.get("https://registry.espresso.hlafaille.xyz/v1/search")
let response = client
.get("https://registry.espresso.hlafaille.xyz/v1/search")
.query(&[("q", q)])
.send()
.await?;

// handle our response from the registry
let response_text = response.text().await?;
let query_packages_response: QueryPackagesResponse = match serde_json::from_str(&response_text) {
let query_packages_response: QueryPackagesResponse = match serde_json::from_str(&response_text)
{
Ok(v) => v,
Err(_) => {
return Err(
EspressoError::nib(format!("Failed to deserialize response: Response content was: {}", response_text).as_str())
)
return Err(EspressoError::nib(
format!(
"Failed to deserialize response: Response content was: {}",
response_text
)
.as_str(),
))
}
};
Ok(query_packages_response.packages)
}

/// Download the latest version of a package
pub async fn download(p_ctx: &ProjectContext, package: &Package) -> result::Result<String, Box<dyn error::Error>> {
pub async fn download(
p_ctx: &ProjectContext,
package: &Package,
) -> result::Result<path::PathBuf, Box<dyn error::Error>> {
// get the latest version of this project
let version = match package.metadata.versions.get(0) {
Some(v) => v,
None => {
return Err(EspressoError::nib("Failed to get the latest version of the package (there are no versions)"))
return Err(EspressoError::nib(
"Failed to get the latest version of the package (there are no versions)",
))
}
};

// establish our full path
let download_path = p_ctx.absolute_paths.dependencies.clone() + format!("/{}.jar", version.sha512sum).as_str();
let download_path = p_ctx.absolute_paths.dependencies.join(format!("/{}.jar", version.sha512sum));

// download the file
download_file(&version.artifact_url, &download_path).await?;

// ensure integrity
util::pathutil::ensure_integrity_sha512(&download_path, &version.sha512sum).await?;

Ok(download_path)
}
}
4 changes: 2 additions & 2 deletions src/backend/dependency/uberjar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ pub fn copy_classes(
p_ctx: &ProjectContext,
dependency: &StateLockFileDependency
) -> result::Result<(), Box<dyn error::Error>>{
let source = p_ctx.absolute_paths.dependencies_extracted.clone() + "/" + dependency.checksum.as_str();
let source = p_ctx.absolute_paths.dependencies_extracted.join(format!("/{}", dependency.checksum.as_str()));

// get our directory tree
let dir_tree = util::directory::walk_dir_tree(&source)?;

let manifest = manifest::parse(&(source + "/META-INF/MANIFEST.MF"));
let manifest = manifest::parse(&source.join("META-INF/MANIFEST.MF"))?;

// copy
// println!("{:?}", class_files);
Expand Down
8 changes: 4 additions & 4 deletions src/util/directory.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{error, fs, io::Error, result, vec};
use std::{error, fs, io::Error, path, result, vec};

/// Get a list of all files within a directory
///
Expand Down Expand Up @@ -33,12 +33,12 @@ pub fn read_files_recursively(path: String) -> Result<Vec<String>, Error> {
///
/// # Returns
/// Propagated errors, a `Vec<String>` containing absolute paths to all the dirs.
pub fn walk_dir_tree(path: &String) -> result::Result<Vec<String>, Box<dyn error::Error>> {
let mut dirs: Vec<String> = vec![];
pub fn walk_dir_tree(path: &path::PathBuf) -> result::Result<Vec<path::PathBuf>, Box<dyn error::Error>> {
let mut dirs: Vec<path::PathBuf> = vec![];
for i in fs::read_dir(path)? {
let entry = i?;
if entry.file_type()?.is_dir() {
let path = entry.path().to_string_lossy().into_owned();
let path = entry.path().into();
let rec_dir_tree = walk_dir_tree(&path)?;
if rec_dir_tree.len() == 0 {
dirs.push(path);
Expand Down
4 changes: 2 additions & 2 deletions src/util/net.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::error;
use std::{error, path};

use tokio::{fs::File, io::AsyncWriteExt};

Expand All @@ -10,7 +10,7 @@ use tokio::{fs::File, io::AsyncWriteExt};
///
/// # Returns
/// Propagates any errors
pub async fn download_file(url: &String, path: &String) -> Result<(), Box<dyn error::Error>> {
pub async fn download_file(url: &String, path: &path::PathBuf) -> Result<(), Box<dyn error::Error>> {
let response = reqwest::get(url).await?;

if response.status().is_success() {
Expand Down
6 changes: 3 additions & 3 deletions src/util/pathutil.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use core::panic;
use std::{error, path::Path, result};
use std::{error, path::{self, Path}, result};
use tokio::fs;
use sha2::{Digest, Sha512};
use super::error::EspressoError;
Expand All @@ -23,7 +23,7 @@ pub fn does_path_exist(path: &String) -> bool {
/// # Returns
/// SHA512 checksum as a hex string, propagated errors.
pub async fn get_sha512_of_path(
path: &String
path: &path::PathBuf
) -> result::Result<String, Box<dyn error::Error>> {
let contents = fs::read(path).await?;

Expand All @@ -42,7 +42,7 @@ pub async fn get_sha512_of_path(
/// * `path`: Reference to a `String` containing the path of the file to check
/// * `expected_sha512_hex`: SHA512 hexadecimal string to compare against
pub async fn ensure_integrity_sha512(
path: &String,
path: &path::PathBuf,
expected_sha512_hex: &String,
) -> result::Result<(), Box<dyn error::Error>> {
let sha512hex = get_sha512_of_path(path).await?;
Expand Down

0 comments on commit d82dbce

Please sign in to comment.