Skip to content

Commit

Permalink
#4 building out extract
Browse files Browse the repository at this point in the history
  • Loading branch information
hlafaille committed Mar 26, 2024
1 parent 14a126f commit 8ee8286
Show file tree
Hide file tree
Showing 7 changed files with 127 additions and 31 deletions.
3 changes: 2 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"image": "mcr.microsoft.com/devcontainers/rust:dev-bookworm",
"containerEnv": {
"CARGO_BUILD_JOBS": "16",
"ESPRESSO_DEBUG": "1"
"ESPRESSO_DEBUG": "1",
"JAVA_HOME": "/usr/lib/jvm/java-17-openjdk-amd64"
},
"features": {
"ghcr.io/devcontainers-contrib/features/apt-get-packages": {
Expand Down
9 changes: 6 additions & 3 deletions src/backend/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ pub struct AbsoltuePaths {
pub config: String,
/// Path to the directory that contains inner working files (ex: state_lockfile, dependency jars, etc)
pub inner_workings: String,
/// Path to the directory containing downloaded dependencies.
/// Path to the inner workings directory containing downloaded dependencies.
pub dependencies: String,
/// Path to the state lockfile within the currently loaded project.
/// Path to the inner workings state lockfile within the currently loaded project.
pub state_lockfile: String,
/// Path to the inner workings directory containing extracted dependencies.
pub dependencies_extracted: String,
}

/// Contains absolute paths to critical resources within the currently loaded project. Determined at runtime.
Expand Down Expand Up @@ -83,7 +85,8 @@ pub fn get_absolute_paths(debug_mode: &bool) -> io::Result<AbsoltuePaths> {
config: cwd_string.clone() + "/espresso.toml",
inner_workings: cwd_string.clone() + "/.espresso",
dependencies: cwd_string.clone() + "/.espresso/dependencies",
state_lockfile: cwd_string.clone() + "/.espresso/state.lock.toml"
state_lockfile: cwd_string.clone() + "/.espresso/state.lock.toml",
dependencies_extracted: cwd_string.clone() + "/.espresso/dependencies_extracted"
})
}

Expand Down
37 changes: 34 additions & 3 deletions src/backend/dependency/uberjar.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,37 @@
use super::resolve::Package;
use std::{error, result};

/// Prepare
pub fn prepare(package: &Package) {
use crate::backend::{context::ProjectContext, lock::StateLockFileDependency, toolchain::{self, ToolchainContext}};

/// Helper function to extract the specified dependency
///
/// # Arguments
/// * `p_ctx`: Reference to a `ProjectContext` struct
/// * `tc_ctx`: Reference to a `ToolChainContext` struct
/// * `dependency`: Reference to a `StateLockFileDependency`, representing the local dependency to extract.
///
/// # Returns
/// Propagated errors
pub fn extract(
p_ctx: &ProjectContext,
tc_ctx: &ToolchainContext,
dependency: &StateLockFileDependency,
) -> result::Result<(), Box<dyn error::Error>> {
toolchain::extract_jar(p_ctx, tc_ctx, &(dependency.checksum.clone() + ".jar"))
}

/// Sync a dependency into the projcets class
///
/// # Arguments
/// * `p_ctx`: Reference to a `ProjectContext` struct
/// * `tc_ctx`: Reference to a `ToolChainContext` struct
/// * `dependency`: Reference to a `StateLockFileDependency`, representing the local dependency to extract.
///
/// # Returns
/// Propagated errors
pub fn sync(
p_ctx: &ProjectContext,
tc_ctx: &ToolchainContext,
dependency: &StateLockFileDependency
) -> result::Result<(), Box<dyn error::Error>>{
Ok(())
}
1 change: 1 addition & 0 deletions src/backend/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ fn ensure_environment(ap: &AbsoltuePaths, debug_mode: &bool) -> io::Result<()>{
// create the inner workings dirs
std::fs::create_dir_all(&ap.inner_workings)?;
std::fs::create_dir_all(&ap.dependencies)?;
std::fs::create_dir_all(&ap.dependencies_extracted)?;

Ok(())
}
Expand Down
81 changes: 66 additions & 15 deletions src/backend/toolchain.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
use crate::{
frontend::terminal::{print_debug, print_err},
util,
frontend::terminal::print_err,
util::{self, error::EspressoError},
};
use std::error;
use std::{error, fmt::format};
use std::{borrow::Cow, env, fs, io, path, process::Command, result, vec};

use super::context::ProjectContext;

/**
* Represents the context of the current Java toolchain
*/
/// Represents the current Java toolchain
pub struct ToolchainContext {
/// Path to `javac`
pub compiler_path: path::PathBuf,
/// Path to `java`
pub runtime_path: path::PathBuf,
/// Path to `jar`
pub packager_path: path::PathBuf,
/// Path to the JDK directory
pub toolchain_path: path::PathBuf,
}

Expand Down Expand Up @@ -77,8 +79,6 @@ pub fn compile_project(java_files: Vec<String>, p_ctx: &ProjectContext, tc_ctx:
&compiler_path, file, &p_ctx.absolute_paths.project, &p_ctx.absolute_paths.project
);

print_debug(format!("Running '{}'", cmd).as_str());

// call the java compiler
let output = Command::new("sh")
.arg("-c")
Expand Down Expand Up @@ -119,7 +119,10 @@ pub fn write_manifest(p_ctx: &ProjectContext) -> io::Result<()> {
*
* TODO: ensure we're using the proper toolchain
*/
pub fn build_jar(p_ctx: &ProjectContext, tc_ctx: &ToolchainContext) -> result::Result<(), Box<dyn error::Error>>{
pub fn build_jar(
p_ctx: &ProjectContext,
tc_ctx: &ToolchainContext,
) -> result::Result<(), Box<dyn error::Error>> {
// write our manifest
write_manifest(p_ctx).unwrap();

Expand All @@ -135,7 +138,6 @@ pub fn build_jar(p_ctx: &ProjectContext, tc_ctx: &ToolchainContext) -> result::R
tc_ctx.packager_path.to_string_lossy().clone(),
relative_base_package_path
);
print_debug(format!("Running '{}'", cmd).as_str());

// run the command
let output = Command::new("sh")
Expand All @@ -145,17 +147,22 @@ pub fn build_jar(p_ctx: &ProjectContext, tc_ctx: &ToolchainContext) -> result::R
.output()?;
if !output.status.success() {
let process_err = String::from_utf8(output.stderr)?;
Err(format!("Failed to package jar: Packager output was: {}", process_err))?
Err(format!(
"Failed to package jar: Packager output was: {}",
process_err
))?
}

Ok(())

}

/**
* Run our JAR file
*/
pub fn run_jar(p_ctx: &ProjectContext, tc_ctx: &ToolchainContext) -> result::Result<(), Box<dyn error::Error>>{
pub fn run_jar(
p_ctx: &ProjectContext,
tc_ctx: &ToolchainContext,
) -> result::Result<(), Box<dyn error::Error>> {
// build our packager command
let cmd = format!(
"{} -jar {}",
Expand All @@ -169,11 +176,55 @@ pub fn run_jar(p_ctx: &ProjectContext, tc_ctx: &ToolchainContext) -> result::Res
.arg("-c")
.arg(cmd)
.status()?;

// dela with our output. We wa
if !status.success() {
Err(format!("Java process exited with non-0 status code"))?
}

Ok(())
}

/// Extract a .jar
///
/// # Arguments
/// * `p_ctx`: Reference to a `ProjectContext` struct
/// * `tc_ctx`: Reference to a `ToolchainContext` struct
///
/// # Returns
/// `Ok` is a `String` containing the absolute path of the extracted .jar. `Err` is propagated errors.
pub fn extract_jar(
p_ctx: &ProjectContext,
tc_ctx: &ToolchainContext,
jar_name: &String,

) -> result::Result<(), Box<dyn error::Error>> {
// get a jar name without the suffix
let output_dir_name = match jar_name.strip_suffix(".jar") {
Some(v) => v,
None => {
return Err(EspressoError::nib("Invalid jar name"))?;
}
};
let absolute_output_dir = p_ctx.absolute_paths.dependencies_extracted.clone() + "/" + output_dir_name;

// create the extracted dependency directory
fs::create_dir_all(&absolute_output_dir)?;

// create our command
let cmd = format!(
"{} -x --file {}",
tc_ctx.packager_path.to_string_lossy(),
p_ctx.absolute_paths.dependencies.clone() + "/" + jar_name,
);

// run the command
let status = Command::new("sh")
.current_dir(& absolute_output_dir)
.arg("-c")
.arg(cmd)
.status()?;
if !status.success() {
Err(format!("Packager process exited with non-0 status code"))?;
}

Ok(())
}
19 changes: 14 additions & 5 deletions src/frontend/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{error, io, result};

use crate::backend::context::{AbsoltuePaths, ProjectContext};
use crate::backend::dependency::resolve::Package;
use crate::backend::toolchain::{compile_project, run_jar, ToolchainContext};
use crate::backend::toolchain::{self, compile_project, run_jar, ToolchainContext};
use crate::backend::{self, context};
use crate::frontend::terminal::{print_err, print_sameline};

Expand All @@ -20,11 +20,12 @@ pub fn run(
(p_ctx, tc_ctx) = build(p_ctx, tc_ctx)?;

// run it
print_general("-- RUNNING ARTIFACT -----");
print_general("-- RUNNING ARTIFACT ----");
match run_jar(&p_ctx, &tc_ctx) {
Ok(_) => (),
Err(e) => print_err(format!("Failed to run 'artifact.jar': {}", { e }).as_str()),
}
print_general("------------------------");
Ok(())
}

Expand All @@ -35,8 +36,16 @@ pub fn build(
p_ctx: ProjectContext,
tc_ctx: ToolchainContext,
) -> result::Result<(ProjectContext, ToolchainContext), Box<dyn error::Error>> {
// extract dependencies TODO cleanup
print_general("-- EXTRACTING DEPENDENCIES");
for (name, dep) in p_ctx.state_lock_file.dependencies.iter() {
print_general(format!("Extracting '{}'", name).as_str());
backend::dependency::uberjar::extract(&p_ctx, &tc_ctx, dep)?;
}
print_general("------------------------");

// walk our src directory, find source files
print_general("-- DISCOVERING ----------");
print_general("-- DISCOVERING");
let java_files = backend::toolchain::get_java_source_files(&p_ctx).unwrap();
print_general(
format!(
Expand All @@ -49,12 +58,12 @@ pub fn build(
print_general("------------------------");

// compile the project to class files
print_general("-- COMPILING ------------");
print_general("-- COMPILING");
compile_project(java_files, &p_ctx, &tc_ctx);
print_general("------------------------");

// build our jar
print_general("-- PACKAGING ------------");
print_general("-- PACKAGING");
match backend::toolchain::build_jar(&p_ctx, &tc_ctx) {
Ok(_) => (),
Err(e) => {
Expand Down
8 changes: 4 additions & 4 deletions src/frontend/terminal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,21 @@ pub fn print_err(msg: &str) {
let lines = msg.split("\n");
for line in lines {
if !line.is_empty() {
eprintln!("{} {}", "[X]".red().bold(), line.white());
eprintln!("{} {}", "error: ".red().bold(), line.bright_red());
}
}
exit(1);
}

pub fn print_general(msg: &str) {
println!("{} {}", "[.]".bright_white().bold(), msg.white())
println!("{} {}", "info: ".bright_white().bold(), msg.white())
}

pub fn print_debug(msg: &str) {
println!("{} {}", "[D]".green().bold(), msg.white())
println!("{} {}", "debug: ".green().bold(), msg.white())
}

pub fn print_sameline(msg: &str) {
print!("{} {}", "[?]".bold().yellow(), msg.white());
print!("{} {}", "input: ".bold().yellow(), msg.white());
io::stdout().flush().unwrap();
}

0 comments on commit 8ee8286

Please sign in to comment.