Skip to content

Commit

Permalink
#4 building out
Browse files Browse the repository at this point in the history
  • Loading branch information
hlafaille committed Mar 19, 2024
1 parent bd6e8c9 commit d0625cc
Show file tree
Hide file tree
Showing 10 changed files with 124 additions and 27 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ once_cell = "1.19.0"
walkdir = "2.5.0"
reqwest = "0.11.26"
tokio = { version = "1.36.0", features = ["full"] }
serde_json = "1.0.114"
19 changes: 0 additions & 19 deletions src/backend/dependency/manage.rs

This file was deleted.

1 change: 0 additions & 1 deletion src/backend/dependency/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod manage;
pub mod resolve;
72 changes: 70 additions & 2 deletions src/backend/dependency/resolve.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,72 @@
use std::{collections::HashMap, error, fmt::format, result};
use serde::{Serialize, Deserialize};

use crate::util::error::EspressoError;

/// Represents a resolved dependency
pub struct ResolvedDependency {

#[derive(Serialize, Deserialize)]
pub struct QueryPackagesResponse {
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")]
pub ref_: String,
}

/// Represents a package's metadata.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PackageMetadata {
pub source_repository: String,
pub versions: Vec<PackageVersion>,
}

/// Represents a specific release/version of the package.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PackageVersion {
pub version: String,
pub flags: Vec<Flags>,
pub vulnerabilities: HashMap<String, String>,
pub artifact_url: String,
pub sha512sum: String,
}

/// Represents the supported package types. This will dictate how they're applied at compile time.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum Flags {
#[serde(rename = "annotation_processor")]
AnnotationProcessor,
}

/// 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")
.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) {
Ok(v) => v,
Err(_) => {
return Err(
EspressoError::nib(format!("Failed to deserialize response: Response content was: {}", response_text).as_str())
)
}
};
Ok(query_packages_response.packages)
}
1 change: 0 additions & 1 deletion src/backend/project.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::util::pathutil;

use super::{context::{get_project_context, AbsoltuePaths, ProjectContext}, lock, Config, Project, Toolchain};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, error, fs, io, result};

/**
Expand Down
3 changes: 2 additions & 1 deletion src/frontend/command.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use clap::Command;
use clap::{Arg, Command};
use once_cell::sync::Lazy;

pub static BUILD_CMD: Lazy<Command> = Lazy::new(|| {
Expand All @@ -23,4 +23,5 @@ pub static ADD_CMD: Lazy<Command> = Lazy::new(|| {
Command::new("add")
.about("Add a dependency from Maven Repository to your project")
.alias("a")
.subcommand_value_name(value_name)
});
16 changes: 14 additions & 2 deletions src/frontend/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,23 @@ pub fn init() {
}

/// Service function for the `add` command.
pub fn add(
pub async fn add(
p_ctx: ProjectContext,
tc_ctx: ToolchainContext,
q: String
) -> result::Result<(ProjectContext, ToolchainContext), Box<dyn error::Error>> {
//
print_general(format!("Searching for '{}'", q).as_str());
let packages = backend::dependency::resolve::query(q).await?;
for (elem, package) in packages.iter().enumerate() {
print_general(format!("{}) G:{} | A:{}", elem + 1, package.group_id, package.artifact_id).as_str());
}

// collect the package selection
let mut package_selection = String::new();
print_sameline(format!("Select a package (1-{}): ", packages.len()).as_str());
if let Err(_) = io::stdin().read_line(&mut package_selection) {
print_err("Failed to read user package selection")
}

// pass ownership back
Ok((p_ctx, tc_ctx))
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ async fn main() {
}
Some("add") => {
let (p_ctx, tc_ctx) = get_contexts();
match frontend::service::add(p_ctx, tc_ctx) {
match frontend::service::add(p_ctx, tc_ctx).await {
Ok(_) => (),
Err(e) => print_err(format!("Error occurred running command: {}", e).as_str()),
}
Expand Down
35 changes: 35 additions & 0 deletions src/util/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use std::{error::Error, fmt};

/// General error for use in Espresso projects
#[derive(Debug)]
pub struct EspressoError {
msg: String
}

impl EspressoError {
/// Creates a error
///
/// # Arguments
/// * `msg`: The error message
pub fn new(msg: &str) -> EspressoError {
EspressoError {
msg: msg.to_string()
}
}

/// Creates a new-in-box error
///
/// # Arguments
/// * `msg`: The error message
pub fn nib(msg: &str) -> Box<EspressoError> {
Box::new(Self::new(msg))
}
}

impl fmt::Display for EspressoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.msg)
}
}

impl Error for EspressoError {}
1 change: 1 addition & 0 deletions src/util/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod directory;
pub mod pathutil;
pub mod net;
pub mod error;

0 comments on commit d0625cc

Please sign in to comment.