Initial Commit.

This commit is contained in:
Olivia Brooks
2026-01-25 21:20:03 -05:00
commit ef07526d57
15 changed files with 1561 additions and 0 deletions

59
src/cli.rs Normal file
View File

@@ -0,0 +1,59 @@
use std::sync::LazyLock;
use clap::{ArgAction, Parser, Subcommand};
pub static CONFIG: LazyLock<Args> = LazyLock::new(|| Args::parse());
#[derive(Debug, Parser)]
pub struct Args {
#[command(subcommand)]
pub command: Command,
}
#[derive(Debug, Subcommand)]
pub enum Command {
/// Create a new raven project
New { project_name: String },
/// Create a new raven project in an existing directory
Init,
/// Compile the current project
Build,
/// Run the current project
#[command(arg_required_else_help = true)]
Run {
#[arg(required = true)]
entry_point: String,
#[clap(flatten)]
assertions: Assertions,
},
/// Run the tests
Test {
#[clap(flatten)]
assertions: Assertions,
},
/// Remove the target directory
Clean,
}
impl Command {
pub fn depends_on_nest(&self) -> bool {
match self {
Self::Init | Self::New { .. } => false,
_ => true,
}
}
}
#[derive(Debug, clap::Args)]
pub struct Assertions {
/// Disable assertions.
#[arg(short, long = "no-assert", action = ArgAction::SetFalse)]
disable_assert: bool,
}
impl Into<bool> for &Assertions {
fn into(self) -> bool {
!self.disable_assert
}
}

44
src/env.rs Normal file
View File

@@ -0,0 +1,44 @@
use std::io;
use std::path::Path;
use std::str::FromStr;
use std::sync::LazyLock;
use crate::java::{JAVA_VM, VMFlag};
use anyhow::Context;
static JAVA_VERSION: LazyLock<String> = LazyLock::new(|| {
crate::io::run_process(&[JAVA_VM, VMFlag::Version.to_string().as_str()])
.expect("Failed to call java")
.0
.expect("Failed to read java version from stdout")
});
pub fn get_javac_ver() -> anyhow::Result<semver::Version> {
/*
* $ java --version
* openjdk 21.0.9 2025-10-21
* OpenJDK Runtime Environment (build 21.0.9+10)
* OpenJDK 64-Bit Server VM (build 21.0.9+10, mixed mode, sharing)
*/
semver::Version::from_str(
JAVA_VERSION
.lines()
.nth(0)
.context("stdout from Java is all f-cked up")?
.split_ascii_whitespace()
.nth(1)
.context("Java version position is all f-cked up")?,
)
.context("Failed to produce a version struct from string")
}
pub fn set_cwd<P: AsRef<Path>>(path: P) -> io::Result<()> {
let mut cwd = crate::PROJECT_ROOT
.lock()
.expect("Failed to lock Mutex")
.to_owned();
cwd.push(path.as_ref());
std::env::set_current_dir(cwd)
}

16
src/fs.rs Normal file
View File

@@ -0,0 +1,16 @@
use std::path::{Path, PathBuf};
pub fn expand_files<P: AsRef<Path>>(path: P) -> anyhow::Result<Vec<PathBuf>> {
let path = path.as_ref();
if path.is_file() {
return Ok(vec![path.to_path_buf()]);
}
Ok(std::fs::read_dir(path)?
.filter_map(|entry| {
let path = entry.ok()?.path();
if path.is_file() { Some(path) } else { None }
})
.collect())
}

30
src/io.rs Normal file
View File

@@ -0,0 +1,30 @@
use std::ffi;
use anyhow::Context;
pub fn run_process<S>(argv: &[S]) -> anyhow::Result<(Option<String>, Option<String>)>
where
S: AsRef<ffi::OsStr>,
{
let mut process = subprocess::Popen::create(
argv,
subprocess::PopenConfig {
stdout: subprocess::Redirection::Pipe,
..Default::default()
},
)?;
let result = process
.communicate(None)
.context("Failed to communicate with subprocess");
if process
.wait_timeout(std::time::Duration::from_secs(5))
.is_err()
|| process.exit_status().is_none()
{
process.terminate()?;
}
result
}

227
src/java.rs Normal file
View File

@@ -0,0 +1,227 @@
use std::fmt;
use std::path::{Path, PathBuf};
use anyhow::Context;
use bytesize::ByteSize;
pub const JAVA_VM: &str = "java";
pub const JAVA_COMPILER: &str = "javac";
pub const JAVA_EXT_SOURCE: &str = "java";
pub const JAVA_EXT_CLASS: &str = "class";
// TODO: Builder-pattern JVM wrapper.
#[derive(Debug, Default, Clone)]
pub struct JVMBuilder {
assertions: bool,
monitor: bool,
ram_min: Option<ByteSize>,
ram_max: Option<ByteSize>,
}
impl JVMBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn assertions(&mut self, assertions: bool) -> &mut Self {
self.assertions = assertions;
self
}
pub fn ram_min(&mut self, ram_min: ByteSize) -> &mut Self {
self.ram_min = Some(ram_min);
self
}
pub fn ram_max(&mut self, ram_max: ByteSize) -> &mut Self {
self.ram_max = Some(ram_max);
self
}
/// Monitor stdout and stderr in raven's process.
pub fn monitor(&mut self, monitor: bool) -> &mut Self {
self.monitor = monitor;
self
}
pub fn build(&self) -> JVM {
let mut flags = vec![];
if self.assertions {
flags.push(VMFlag::EnableAssert);
}
if let Option::Some(size) = self.ram_min {
flags.push(VMFlag::HeapMin { size });
}
if let Option::Some(size) = self.ram_max {
flags.push(VMFlag::HeapMax { size });
}
JVM {
monitor: self.monitor,
flags,
}
}
}
pub struct JVM {
monitor: bool,
flags: Vec<VMFlag>,
}
impl JVM {
pub fn run<P: AsRef<Path>>(
self,
entry_point: P,
) -> anyhow::Result<(Option<String>, Option<String>)> {
let mut cmd = vec![JAVA_VM.to_string()];
cmd.extend(
self.flags
.clone()
.into_iter()
.flat_map(|f| Into::<Vec<String>>::into(f)),
);
cmd.push(entry_point.as_ref().display().to_string());
let result = crate::io::run_process(cmd.as_slice());
if self.monitor
&& let Result::Ok((stdout, stderr)) = &result
{
if let Option::Some(stdout) = stdout
&& stdout.len() > 0
{
print!("{stdout}");
}
if let Option::Some(stderr) = stderr
&& stderr.len() > 0
{
eprintln!("{stderr}");
}
}
result
}
}
#[derive(Debug, Clone)]
pub enum VMFlag {
EnableAssert,
HeapMax { size: ByteSize },
HeapMin { size: ByteSize },
Version,
}
impl Into<Vec<String>> for VMFlag {
fn into(self) -> Vec<String> {
match self {
Self::EnableAssert => vec![String::from("-ea")],
Self::HeapMax { size } => vec![format!("Xmx{}", size)],
Self::HeapMin { size } => vec![format!("Xms{}", size)],
Self::Version => vec![String::from("--version")],
}
}
}
// Currently being kept around because it's fine for the current branches,
// and is currently serving a to_string() method for the Java version fetch.
impl fmt::Display for VMFlag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"-{}",
match self {
Self::EnableAssert => String::from("ea"),
Self::HeapMax { size } => format!("Xmx{}", size),
Self::HeapMin { size } => format!("Xms{}", size),
Self::Version => String::from("-version"), // --version
}
)
}
}
#[derive(Debug, Default, Clone)]
pub struct CompilerBuilder {
class_path: Option<PathBuf>,
destination: Option<PathBuf>,
}
impl CompilerBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn class_path<S: AsRef<Path>>(&mut self, class_path: S) -> &mut Self {
self.class_path = Some(class_path.as_ref().to_path_buf());
self
}
pub fn destination<S: AsRef<Path>>(&mut self, destination: S) -> &mut Self {
self.destination = Some(destination.as_ref().to_path_buf());
self
}
pub fn build(&self) -> Compiler {
let mut flags = vec![];
if let Option::Some(path) = self.destination.to_owned() {
flags.push(CompilerFlag::Destination { path });
}
if let Option::Some(path) = self.class_path.to_owned() {
flags.push(CompilerFlag::Classpath { path });
}
Compiler { flags }
}
}
#[derive(Debug, Clone)]
pub struct Compiler {
flags: Vec<CompilerFlag>,
}
impl Compiler {
pub fn compile<P: AsRef<Path>>(
self,
path: P,
) -> anyhow::Result<(Option<String>, Option<String>)> {
let mut cmd: Vec<String> = vec![JAVA_COMPILER.to_string()];
cmd.extend(
self.flags
.clone()
.into_iter()
.flat_map(|f| Into::<Vec<String>>::into(f)),
);
cmd.extend(crate::fs::expand_files(path)?.into_iter().filter_map(|f| {
Some(
f.to_str()
.context("Failed to cast PathBuf to &str")
.ok()?
.to_string(),
)
}));
crate::io::run_process(cmd.as_slice())
}
}
#[derive(Debug, Clone)]
pub enum CompilerFlag {
Destination { path: PathBuf },
Classpath { path: PathBuf },
}
impl Into<Vec<String>> for CompilerFlag {
fn into(self) -> Vec<String> {
match self {
Self::Classpath { path } => vec!["-cp".to_string(), path.display().to_string()],
Self::Destination { path } => vec!["-d".to_string(), path.display().to_string()],
}
}
}

261
src/main.rs Normal file
View File

@@ -0,0 +1,261 @@
mod cli;
mod env;
mod fs;
mod io;
mod java;
mod nest;
use std::fs::OpenOptions;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use cli::{CONFIG, Command};
use java::{JAVA_EXT_CLASS, JAVA_EXT_SOURCE};
use nest::{Class, NEST, NestLock};
use anyhow::Context;
use bytesize::ByteSize;
const DIR_TARGET: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("target/"));
const DIR_TEST: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("test/"));
const DIR_SRC: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("src/"));
const F_NEST_TOML: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("Nest.toml"));
const F_NEST_LOCK: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("Nest.lock"));
/// This may not actually be the project root.
pub static PROJECT_ROOT: LazyLock<Mutex<PathBuf>> = LazyLock::new(|| {
Mutex::new(std::env::current_dir().expect("Failed to get current working directory"))
});
fn main() -> anyhow::Result<()> {
// Ensure that Nest.toml exists, if the requested command depends upon it.
if CONFIG.command.depends_on_nest() && NEST.is_err() {
println!("No Nest.toml found in project directory");
println!("Aborting...");
return Ok(());
}
match &CONFIG.command {
Command::Init => init()?,
Command::New { project_name } => {
new(project_name.to_owned())?;
init()?;
}
Command::Build => {
build()?;
}
Command::Run {
entry_point,
assertions,
} => {
build()?;
run(entry_point, assertions.into())?;
}
Command::Test { assertions } => {
test(assertions.into())?;
}
Command::Clean => clean(),
}
println!("Done.");
Ok(())
}
fn init() -> anyhow::Result<()> {
let is_empty = std::fs::read_dir(PROJECT_ROOT.lock().expect("Failed to lock mutex").as_path())
.is_ok_and(|tree| tree.count() == 0);
let project_name = PROJECT_ROOT
.lock()
.expect("Failed to lock mutex")
.file_name()
.context("Invalid directory name")?
.to_str()
.context("Unable to convert OsStr to str")?
.to_owned();
// Make src, target, tests
for dir in [DIR_SRC, DIR_TARGET, DIR_TEST] {
std::fs::create_dir(dir.clone())?;
}
// Make config file.
if let Result::Ok(mut f) = OpenOptions::new()
.write(true)
.create_new(true)
.open(F_NEST_TOML.as_path())
{
f.write_all(
toml::to_string_pretty(&nest::Nest {
package: nest::Package {
name: project_name.to_owned(),
..Default::default()
},
})?
.as_bytes(),
)?;
}
// Make .java-version
if let Result::Ok(mut f) = OpenOptions::new()
.write(true)
.create_new(true)
.open(PathBuf::from(".java-version"))
{
f.write_all(
{
let mut version = crate::env::get_javac_ver()?.major.to_string();
version.push('\n');
version
}
.as_bytes(),
)?;
}
// Make Main.java
if let Result::Ok(mut f) = OpenOptions::new()
.write(true)
.create_new(is_empty)
.open(DIR_SRC.clone().join("Main").with_extension(JAVA_EXT_SOURCE))
{
f.write_all(include_bytes!("../assets/Main.java"))?;
}
// git init .
crate::io::run_process(&["git", "init", "."])?;
// Append to .gitignore
if let Result::Ok(mut f) = OpenOptions::new()
.append(true)
.create(true)
.read(true)
.open(".gitignore")
{
dbg!();
let mut buf = String::new();
f.read_to_string(&mut buf)?;
for ignored in [
DIR_TARGET.as_path().display().to_string(),
format!("*.{}", JAVA_EXT_CLASS),
] {
if dbg!(!buf.contains(&ignored)) {
f.write(format!("{}\n", ignored).as_bytes())?;
}
}
}
Ok(())
}
fn new(project_name: String) -> anyhow::Result<()> {
let cwd = PROJECT_ROOT
.lock()
.expect("Failed to lock mutex")
.join(project_name);
std::fs::create_dir(&cwd)?;
std::env::set_current_dir(&cwd)?;
// Replace PathBuf within mutex
let mut state = PROJECT_ROOT.lock().expect("Failed to lock mutex");
*state = std::env::current_dir().expect("Failed to change current working directory");
Ok(())
}
fn build() -> anyhow::Result<()> {
let mut targets = crate::fs::expand_files(DIR_SRC.as_path())?;
let mut nest_lock = NestLock::load().unwrap_or_default();
nest_lock.update();
let mut retained_targets = vec![];
for path in targets.into_iter() {
if let Option::Some((_path, class)) = nest_lock.0.get_key_value(&path)
&& class.is_updated()
{
continue;
}
retained_targets.push(path);
}
targets = retained_targets;
let javac = java::CompilerBuilder::new()
.class_path(DIR_TARGET.as_path())
.destination(DIR_TARGET.as_path())
.build();
for target in targets {
println!("Compiling {}", target.display());
if javac.clone().compile(target.as_path()).is_ok()
&& let Result::Ok(class) = Class::try_from(target.clone())
{
nest_lock.0.insert(target, class);
}
}
OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(F_NEST_LOCK.as_path())?
.write_all(toml::to_string_pretty(&nest_lock)?.as_bytes())
.with_context(|| format!("Failed to write {}", F_NEST_LOCK.display()))
}
fn run<P: AsRef<Path>>(
entry_point: P,
assertions: bool,
) -> anyhow::Result<(Option<String>, Option<String>)> {
crate::env::set_cwd(DIR_TARGET.as_path())?;
java::JVMBuilder::new()
.assertions(assertions)
.monitor(true)
.build()
.run(entry_point)
}
fn test(assertions: bool) -> anyhow::Result<(Option<String>, Option<String>)> {
java::CompilerBuilder::new()
.class_path(DIR_TARGET.as_path())
.destination(DIR_TARGET.as_path())
.build()
.compile(DIR_TEST.as_path())?;
// Change cwd to avoid Java pathing issues.
crate::env::set_cwd(
PROJECT_ROOT
.lock()
.expect("Failed to lock mutex")
.join(DIR_TARGET.as_path()),
)?;
java::JVMBuilder::new()
.assertions(assertions)
.ram_min(ByteSize::mib(128))
.ram_max(ByteSize::mib(512))
.monitor(true)
.build()
.run(DIR_TEST.as_path())
}
fn clean() {
let _ = std::fs::remove_file(
PROJECT_ROOT
.lock()
.expect("Failed to lock mutex")
.join(F_NEST_LOCK.as_path()),
);
let _ = std::fs::remove_dir_all(
PROJECT_ROOT
.lock()
.expect("Failed to lock mutex")
.join(DIR_TARGET.as_path()),
);
}

173
src/nest.rs Normal file
View File

@@ -0,0 +1,173 @@
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::Read;
use std::path::PathBuf;
use std::sync::LazyLock;
use crate::java::{JAVA_EXT_CLASS, JAVA_EXT_SOURCE};
use crate::{DIR_SRC, DIR_TARGET, DIR_TEST, F_NEST_LOCK, F_NEST_TOML, PROJECT_ROOT};
use anyhow::Context;
use semver::Version;
use serde::{Deserialize, Serialize};
pub static NEST: LazyLock<anyhow::Result<Nest>> = LazyLock::new(|| {
Nest::try_from(
PROJECT_ROOT
.lock()
.expect("Failed to lock mutex")
.join(F_NEST_TOML.as_path()),
)
});
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Nest {
pub package: Package,
}
impl TryFrom<File> for Nest {
type Error = anyhow::Error;
fn try_from(value: File) -> Result<Self, Self::Error> {
let mut value = value;
let mut buf = String::new();
value
.read_to_string(&mut buf)
.context("Failed to read Nest")?;
toml::from_str(buf.as_str()).context("Failed to deserialize Nest")
}
}
impl TryFrom<PathBuf> for Nest {
type Error = anyhow::Error;
fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
Nest::try_from(
OpenOptions::new()
.read(true)
.open(value)
.expect("Failed to load Nest.toml"),
)
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Package {
pub name: String,
pub version: semver::Version,
}
impl Default for Package {
fn default() -> Self {
Self {
name: String::from("MyPackage"),
version: Version::new(0, 1, 0),
}
}
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct NestLock(pub HashMap<PathBuf, Class>);
impl NestLock {
pub fn load() -> anyhow::Result<NestLock> {
NestLock::try_from(F_NEST_LOCK.clone())
}
/// Update, retaining all classes that still exist and whose paths are still files, rather than
/// being shifted into a package.
pub fn update(&mut self) {
self.0 = self
.0
.clone()
.into_iter()
.filter_map(|(path, class)| {
if path.exists() && path.is_file() {
return Some((path, class));
}
None
})
.collect();
}
}
impl TryFrom<File> for NestLock {
type Error = anyhow::Error;
fn try_from(value: File) -> Result<Self, Self::Error> {
let mut value = value;
let mut buf = String::new();
value.read_to_string(&mut buf)?;
toml::from_str(buf.as_str()).context("Failed to deserialize NestLock")
}
}
impl TryFrom<PathBuf> for NestLock {
type Error = anyhow::Error;
fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
NestLock::try_from(
OpenOptions::new()
.read(true)
.open(&value)
.with_context(|| format!("Failed to open {}", value.display()))?,
)
.context("")
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Class {
pub name: PathBuf,
pub checksum: String,
pub test: bool,
}
impl Class {
/// Returns true if the class needs updating.
/// This may also cautionarily return true if it cannot digest the file.
pub fn is_updated(&self) -> bool {
// If the source file exists, hasn't been moved to a package (path is a file) and
// the associated compiled class file exists in DIR_TARGET
PROJECT_ROOT
.lock()
.expect("Failed to lock mutex")
.join(DIR_TARGET.as_path())
.join(self.name.as_path())
.with_extension(JAVA_EXT_CLASS)
.exists()
&& sha256::try_digest(
PROJECT_ROOT
.lock()
.expect("Failed to lock mutex")
.join(if self.test {
DIR_TEST.clone()
} else {
DIR_SRC.clone()
})
.join(self.name.as_path())
.with_extension(JAVA_EXT_SOURCE),
)
.is_ok_and(|hash| self.checksum == hash)
}
}
impl TryFrom<PathBuf> for Class {
type Error = anyhow::Error;
fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
Ok(Self {
name: PathBuf::from(
value
.file_name()
.context("Failed to get file name from PathBuf for class")?,
)
.with_extension(""),
checksum: sha256::try_digest(&value)?,
test: value.is_relative() && value.starts_with(DIR_TEST.as_path()),
})
}
}