Compare commits

...

18 Commits

Author SHA1 Message Date
Olivia Brooks
3636916ac3 Add documentation. 2026-02-22 15:18:09 -05:00
Olivia Brooks
4e961dac40 Add documentation. 2026-02-22 13:46:03 -05:00
Olivia Brooks
fee63a2d4b Add documentation. 2026-02-22 13:45:53 -05:00
Cutieguwu
6ad82c3339 Update Cargo.lock 2026-02-16 20:41:34 -05:00
Cutieguwu
f0d22e6b79 Speed up brute force building with Prey.lock hashing and caching. 2026-02-16 20:41:31 -05:00
Cutieguwu
1009a84c06 Improve javac version fetching. 2026-02-16 20:40:36 -05:00
Cutieguwu
dcbf67e203 Update README.md 2026-02-15 20:41:56 -05:00
Cutieguwu
cfb6f5fb34 Fix raven clean 2026-02-15 20:36:54 -05:00
Cutieguwu
a3c208555a Add better handling of undefined entry points. 2026-02-15 20:27:57 -05:00
Cutieguwu
4404aba65f Update Cargo.lock 2026-02-15 20:22:12 -05:00
Cutieguwu
68743619f2 Bump java crate version. 2026-02-15 20:16:47 -05:00
Cutieguwu
e1827b13f4 Fix some issues with clap using the cli crate's versioning. 2026-02-15 20:16:32 -05:00
Cutieguwu
17f7b9dca9 Resolve some pathing issues; cleanup. 2026-02-15 20:15:26 -05:00
Cutieguwu
16accb8ab8 Shed old reference materials. 2026-02-15 19:46:59 -05:00
Cutieguwu
b338f76e06 Bump subprocess and toml. Also remove the demo project I accidentally
pushed.
2026-02-15 19:38:20 -05:00
Cutieguwu
79629391c5 I think I finished it... 2026-02-15 17:39:48 -05:00
Cutieguwu
0fad1b74bc Try to work on build some more. 2026-02-15 12:25:03 -05:00
Cutieguwu
a9fb52d8d7 Bump version numbers. 2026-02-15 09:50:36 -05:00
43 changed files with 626 additions and 1462 deletions

115
Cargo.lock generated
View File

@@ -54,9 +54,9 @@ dependencies = [
[[package]]
name = "anyhow"
version = "1.0.100"
version = "1.0.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea"
[[package]]
name = "async-trait"
@@ -66,14 +66,14 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.114",
"syn 2.0.116",
]
[[package]]
name = "bitflags"
version = "2.10.0"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
[[package]]
name = "block-buffer"
@@ -86,9 +86,9 @@ dependencies = [
[[package]]
name = "bytes"
version = "1.11.0"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "bytesize"
@@ -104,9 +104,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "clap"
version = "4.5.56"
version = "4.5.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75ca66430e33a14957acc24c5077b503e7d374151b2b4b3a10c83b4ceb4be0e"
checksum = "63be97961acde393029492ce0be7a1af7e323e6bae9511ebfac33751be5e6806"
dependencies = [
"clap_builder",
"clap_derive",
@@ -114,9 +114,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.5.56"
version = "4.5.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "793207c7fa6300a0608d1080b858e5fdbe713cdc1c8db9fb17777d8a13e63df0"
checksum = "7f13174bda5dfd69d7e947827e5af4b0f2f94a4a3ee92912fba07a66150f21e2"
dependencies = [
"anstream",
"anstyle",
@@ -133,18 +133,18 @@ dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.114",
"syn 2.0.116",
]
[[package]]
name = "clap_lex"
version = "0.7.7"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32"
checksum = "3a822ea5bc7590f9d40f1ba12c0dc3c2760f3482c6984db1573ad11031420831"
[[package]]
name = "cli"
version = "0.1.0"
version = "0.2.1"
dependencies = [
"clap",
]
@@ -155,26 +155,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]]
name = "const_format"
version = "0.2.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7faa7469a93a566e9ccc1c73fe783b4a65c274c5ace346038dca9c39fe0030ad"
dependencies = [
"const_format_proc_macros",
]
[[package]]
name = "const_format_proc_macros"
version = "0.2.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "convert_case"
version = "0.10.0"
@@ -186,17 +166,17 @@ dependencies = [
[[package]]
name = "core"
version = "0.1.0"
version = "0.1.4"
dependencies = [
"anyhow",
"derive_more",
"fs",
"io",
"java",
"pathsub",
"semver",
"serde",
"sha256",
"subprocess",
"toml",
]
@@ -238,7 +218,7 @@ dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"syn 2.0.114",
"syn 2.0.116",
"unicode-xid",
]
@@ -328,14 +308,6 @@ dependencies = [
"hashbrown",
]
[[package]]
name = "io"
version = "0.1.0"
dependencies = [
"derive_more",
"subprocess",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
@@ -344,13 +316,13 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "java"
version = "0.1.0"
version = "0.2.2"
dependencies = [
"bytesize",
"derive_more",
"fs",
"io",
"semver",
"subprocess",
]
[[package]]
@@ -367,15 +339,15 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "libc"
version = "0.2.180"
version = "0.2.182"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc"
checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
[[package]]
name = "memchr"
version = "2.7.6"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "once_cell_polyfill"
@@ -383,13 +355,6 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "path"
version = "0.1.0"
dependencies = [
"const_format",
]
[[package]]
name = "pathsub"
version = "0.1.1"
@@ -433,16 +398,14 @@ dependencies = [
[[package]]
name = "raven"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"anyhow",
"bytesize",
"cli",
"core",
"fs",
"io",
"java",
"path",
"toml",
]
@@ -492,7 +455,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.114",
"syn 2.0.116",
]
[[package]]
@@ -552,14 +515,14 @@ dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.114",
"syn 2.0.116",
]
[[package]]
name = "subprocess"
version = "0.2.14"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b09969f0abcf65111c0cbdd8bfaa292ca3c38b46bc8ecc7270467af2f4acb172"
checksum = "98e067360c7f5a302e35c9f9cd24cb583c378fbedc73d0237284dbdd0650fcc5"
dependencies = [
"libc",
"winapi",
@@ -578,9 +541,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.114"
version = "2.0.116"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"
checksum = "3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb"
dependencies = [
"proc-macro2",
"quote",
@@ -599,9 +562,9 @@ dependencies = [
[[package]]
name = "toml"
version = "0.9.11+spec-1.1.0"
version = "1.0.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3afc9a848309fe1aaffaed6e1546a7a14de1f935dc9d89d32afd9a44bab7c46"
checksum = "bbe30f93627849fa362d4a602212d41bb237dc2bd0f8ba0b2ce785012e124220"
dependencies = [
"indexmap",
"serde_core",
@@ -614,18 +577,18 @@ dependencies = [
[[package]]
name = "toml_datetime"
version = "0.7.5+spec-1.1.0"
version = "1.0.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
checksum = "32c2555c699578a4f59f0cc68e5116c8d7cabbd45e1409b989d4be085b53f13e"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.0.6+spec-1.1.0"
version = "1.0.8+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3198b4b0a8e11f09dd03e133c0280504d0801269e9afa46362ffde1cbeebf44"
checksum = "0742ff5ff03ea7e67c8ae6c93cac239e0d9784833362da3f9a9c1da8dfefcbdc"
dependencies = [
"winnow",
]
@@ -644,9 +607,9 @@ checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
[[package]]
name = "unicode-ident"
version = "1.0.22"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e"
[[package]]
name = "unicode-segmentation"

View File

@@ -10,7 +10,6 @@ license = "MIT"
repository = "https://gitea.cutieguwu.ca/Cutieguwu/raven"
publish = false
test = true
[workspace.dependencies]
#
@@ -18,10 +17,8 @@ test = true
#
cli = { path = "crates/cli" }
fs = { path = "crates/fs" }
io = { path = "crates/io" }
java = { path = "crates/java" }
core = { path = "crates/core" }
path = { path = "crates/path" }
pom = { path = "crates/pom" }
raven = { path = "crates/raven" }
@@ -36,8 +33,8 @@ lenient_semver = "0.4.2"
pathsub = "0.1.1"
ron = "0.12.0"
sha256 = "1.6"
subprocess = "0.2.13"
toml = "0.9.11"
subprocess = "1.0"
toml = "1.0"
derive_more = { version = "2.1", features = ["display", "from"] }
semver = { version = "1.0",features = ["serde"] }

View File

@@ -29,10 +29,12 @@ WSL *may* affect the behaviour of raven. Quirks to be worked out.
```bash
raven new demo
cd demo
raven run main.Main
raven run main
```
## Raven commands
```bash
Usage: raven <COMMAND>
Commands:
@@ -47,6 +49,7 @@ Commands:
Options:
-h, --help Print help
-V, --version Print version
```
## Future plans

View File

@@ -1,6 +1,6 @@
[package]
name = "cli"
version = "0.1.0"
version = "0.2.1"
edition.workspace = true
license.workspace = true
@@ -8,7 +8,6 @@ description = "Raven's CLI"
repository.workspace = true
publish.workspace = true
test.workspace = true
[dependencies.clap]
version = "4.5"

View File

@@ -6,8 +6,7 @@ use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum};
pub static CLI_ARGS: LazyLock<CliArgs> = LazyLock::new(|| CliArgs::parse());
#[derive(Debug, Parser)]
#[clap(author, version)]
#[command(help_template = "{author-section}\n{usage-heading} {usage}\n\n{all-args}")]
#[clap(name = "Raven", version = "0.2.0")]
pub struct CliArgs {
#[command(subcommand)]
pub command: Command,
@@ -19,7 +18,7 @@ pub enum Command {
New {
#[clap(flatten)]
type_: ProjectFlag,
name: String,
project_name: String,
},
/// Create a new raven project in an existing directory
Init,
@@ -49,7 +48,7 @@ pub struct Assertions {
assertions: bool,
}
impl Into<bool> for Assertions {
impl Into<bool> for &Assertions {
fn into(self) -> bool {
self.assertions
}

View File

@@ -1,6 +1,6 @@
[package]
name = "core"
version = "0.1.0"
version = "0.1.4"
edition.workspace = true
license.workspace = true
@@ -8,17 +8,16 @@ description = "Raven's core, including metadata tooling and resources"
repository.workspace = true
publish.workspace = true
test.workspace = true
[dependencies]
derive_more.workspace = true
fs.workspace = true
io.workspace = true
java.workspace = true
pathsub.workspace = true
semver.workspace = true
serde.workspace = true
sha256.workspace = true
subprocess.workspace = true
toml.workspace = true
[dependencies.anyhow]

View File

@@ -1,10 +1,74 @@
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use java::{JAVA_EXT_CLASS, JAVA_EXT_SOURCE};
use serde::{Deserialize, Serialize};
/// Data struct
use crate::{Error, Result};
/// [`Class`] represents a source file. It is a handler.
#[derive(Debug, Clone, Deserialize, Serialize, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Class {
/// Path relative to PACKAGE/java, without file extension.
pub path: PathBuf,
pub checksum: String,
}
impl Class {
/// Creates a new [`Class`].
///
/// # Error
///
/// * [`Error::MismatchedPackage`] if the provided `file_path` is absolute, and cannot be
/// subtracted to just its relative path within its parent package.
/// * [`Error::Io`] if the source file cannot be loaded and digested.
pub fn new<P: AsRef<Path>>(package_src_root: P, file_path: P) -> Result<Self> {
let mut file_path = file_path.as_ref().to_path_buf();
if file_path.is_absolute() {
file_path = pathsub::sub_paths(file_path.as_path(), package_src_root.as_ref())
.ok_or(Error::MismatchedPackage)?;
}
Ok(Self {
path: dbg!(file_path.with_extension("")),
checksum: sha256::try_digest(package_src_root.as_ref().join(file_path))?,
})
}
/// Returns a boolean representing if the class is up to date.
///
/// # Criteria
///
/// * The class path is local.
/// * The class has been compiled to `target/`
/// * The class' source file has not been updated.
///
/// # Errors
///
/// * [`Error::Io`]
pub fn is_updated<P: AsRef<Path>>(&self, class_path: P) -> Result<bool> {
// If the path is local and that file has not been updated.
Ok(class_path
.as_ref()
.join(self.path.as_path())
.with_extension(JAVA_EXT_CLASS)
.exists()
&& self.checksum == sha256::try_digest(self.path.clone())?)
}
/// Updates the class' checksum.
///
/// Only call this if you know that the class has been compiled successfully.
///
/// # Errors
///
/// * [`Error::Io`] if the source file cannot be loaded and digested.
pub fn update<P: AsRef<Path>>(&mut self, package_src_root: P) -> Result<()> {
self.checksum = sha256::try_digest(dbg!(
package_src_root
.as_ref()
.join(self.path.as_path())
.with_extension(JAVA_EXT_SOURCE),
))?;
Ok(())
}
}

View File

@@ -1,13 +1,15 @@
use semver::Version;
use serde::{Deserialize, Serialize};
use crate::Result;
use crate::package::PackageHandler;
/// Data struct
#[derive(Debug, Clone, Deserialize, Serialize, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Dependency {
name: String,
version: Version,
#[serde(skip_serializing_if = "<Option<_>>::is_none")]
version: Option<Version>,
pub checksum: String,
#[serde(skip_serializing_if = "<Option<_>>::is_none")]
source: Option<String>, // Path / URL
@@ -24,13 +26,19 @@ impl Dependency {
// TODO: Convert from reverse domain name to path.
return self.name.clone();
}
pub fn is_updated(&self) -> Result<bool> {
// If the path is local and that file has not been updated.
Ok(self.source.as_ref().is_some_and(|path| is_url(path))
&& self.checksum == sha256::try_digest(self.source.as_ref().unwrap())?)
}
}
impl From<PackageHandler> for Dependency {
fn from(value: PackageHandler) -> Self {
Dependency {
name: value.name(),
version: value.version(),
version: Some(value.version()),
checksum: String::new(),
source: None,
}
@@ -38,6 +46,6 @@ impl From<PackageHandler> for Dependency {
}
/// TODO: This is just a placeholder at present.
fn is_url<S: ToString>(path: S) -> bool {
fn is_url<S: ToString>(_path: S) -> bool {
return false;
}

View File

@@ -1,19 +1,22 @@
use derive_more::{Display, From};
pub type Result<T> = core::result::Result<T, Error>;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, From, Display)]
pub enum Error {
/// Attempted to replace a value in a hash collection,
/// but there was no prime present when one was expected.
AbsentPrimeHashingError,
#[from]
Io(io::Error),
Io(std::io::Error),
#[from]
Java(java::Error),
MissingFileName,
#[from]
StdIo(std::io::Error),
MismatchedPackage,
#[from]
TomlDeserialize(toml::de::Error),
@@ -21,5 +24,7 @@ pub enum Error {
#[from]
TomlSerialize(toml::ser::Error),
UndefinedEntryPoint,
UnknownPackage,
}

View File

@@ -1,5 +1,3 @@
#![allow(dead_code)]
pub mod class;
pub mod dependency;
pub mod error;

View File

@@ -5,8 +5,8 @@ use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::dependency::Dependency;
use crate::meta::Meta;
use crate::prelude::Dependency;
use crate::workspace::Workspace;
pub const F_NEST_TOML: &str = "Nest.toml";
@@ -29,11 +29,16 @@ impl Nest {
}
}
pub fn write<P: AsRef<Path>>(&self, path: P) -> crate::Result<()> {
pub fn write<P: AsRef<Path>>(&self, project_root: P) -> crate::Result<()> {
let mut project_root = project_root.as_ref().to_path_buf();
if project_root.is_dir() {
project_root = project_root.join(F_NEST_TOML);
}
Ok(OpenOptions::new()
.write(true)
.create(true)
.open(path)?
.open(project_root)?
.write_all(toml::to_string_pretty(&self)?.as_bytes())?)
}

View File

@@ -3,31 +3,38 @@ use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::class::Class;
use crate::prey::{F_PREY_LOCK, F_PREY_TOML, Prey, PreyLock};
pub const DIR_JAVA: &str = "java/";
/// Hashing is only based off the Prey.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackageHandler {
prey: Prey,
prey_lock: Option<PreyLock>,
prey_lock: PreyLock,
/// Path relative to WORKSPACE/src
package_root: PathBuf,
target_dir: PathBuf,
}
impl PackageHandler {
pub fn new<P: AsRef<Path>>(package_root: P, target_dir: P) -> crate::Result<Self> {
let package_root = package_root.as_ref().to_path_buf();
pub fn new<P: AsRef<Path>>(src_dir: P, package_root: P, target_dir: P) -> crate::Result<Self> {
let package_root = src_dir.as_ref().join(package_root.as_ref());
let prey_lock = if let Ok(prey_lock) = PreyLock::try_from(package_root.join(F_PREY_LOCK)) {
prey_lock
} else {
PreyLock::new(package_root.clone(), package_root.join(DIR_JAVA))?
};
Ok(Self {
prey: Prey::try_from(package_root.join(F_PREY_TOML))?,
prey_lock: PreyLock::try_from(package_root.join(F_PREY_LOCK)).ok(),
prey_lock,
package_root,
target_dir: target_dir.as_ref().to_path_buf(),
})
}
pub fn update_class_cache(&self) {}
pub fn entry_point(&self) -> PathBuf {
self.prey.entry_point()
}
@@ -39,6 +46,28 @@ impl PackageHandler {
pub fn version(&self) -> semver::Version {
self.prey.version()
}
pub fn prey_lock(&mut self) -> &mut PreyLock {
&mut self.prey_lock
}
pub fn get_outdated<P: AsRef<Path>>(&self, class_path: P) -> Vec<Class> {
self.prey_lock
.clone()
.classes()
.iter()
.filter(|class| {
class
.is_updated(class_path.as_ref())
.is_ok_and(|b| b == false)
})
.cloned()
.collect()
}
pub fn write_lock(&self) -> crate::Result<()> {
self.prey_lock.write(self.package_root.as_path())
}
}
impl Hash for PackageHandler {

View File

@@ -1,8 +1,9 @@
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::Read;
use std::path::PathBuf;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use fs::expand_files;
use serde::{Deserialize, Serialize};
use crate::class::Class;
@@ -20,6 +21,20 @@ pub struct Prey {
}
impl Prey {
pub fn new<S: ToString>(name: S) -> Self {
Self {
package: Package {
entry_point: PathBuf::from(""),
},
meta: Meta::new(name),
}
}
pub fn with_entry_point<P: AsRef<Path>>(&mut self, entry_point: P) -> &mut Self {
self.package.entry_point = entry_point.as_ref().to_path_buf();
self
}
pub fn entry_point(&self) -> PathBuf {
self.package.entry_point.clone()
}
@@ -53,11 +68,59 @@ impl TryFrom<File> for Prey {
}
/// Data struct
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct PreyLock {
classes: HashSet<Class>,
}
impl PreyLock {
pub fn new<P: AsRef<Path>>(package_root: P, package_src_root: P) -> crate::Result<Self> {
Ok(Self::from_paths(
expand_files(package_root)?,
package_src_root,
))
}
pub fn from_paths<P: AsRef<Path>>(paths: Vec<PathBuf>, package_src_root: P) -> Self {
let mut lock = Self::default();
lock.classes = paths
.iter()
.filter_map(|f| {
let dep = Class::new(package_src_root.as_ref().to_path_buf(), f.to_owned());
if dep.is_ok() {
Some(dep.unwrap())
} else {
None
}
})
.collect();
lock
}
pub fn write<P: AsRef<Path>>(&self, package_root: P) -> crate::Result<()> {
let mut package_root = package_root.as_ref().to_path_buf();
if package_root.is_dir() {
package_root = package_root.join(F_PREY_LOCK);
}
Ok(OpenOptions::new()
.write(true)
.create(true)
.open(package_root)?
.write_all(toml::to_string_pretty(&self)?.as_bytes())?)
}
pub fn with_class(&mut self, class: Class) -> &mut Self {
self.classes.insert(class);
self
}
pub fn classes(&mut self) -> &mut HashSet<Class> {
&mut self.classes
}
}
/// Load the PreyLock from Prey.lock file.
impl TryFrom<PathBuf> for PreyLock {
type Error = crate::Error;

View File

@@ -2,18 +2,23 @@ use std::collections::HashMap;
use std::fs::{OpenOptions, read_dir};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
use fs::{self, expand_files};
use io::run_process;
use java::{self, JAVA_EXT_CLASS, JAVA_EXT_SOURCE};
use fs::expand_files;
use java::{JAVA_EXT_CLASS, JAVA_EXT_SOURCE};
use serde::{Deserialize, Serialize};
use subprocess::Exec;
use crate::Error;
use crate::dependency::Dependency;
use crate::nest::{F_NEST_LOCK, F_NEST_TOML, Nest, NestLock};
use crate::package::PackageHandler;
use crate::prey::F_PREY_TOML;
use crate::prey::{F_PREY_LOCK, F_PREY_TOML, Prey};
use crate::{Error, package};
/// Represents a raven workspace.
///
/// [`WorkspaceHandler`] manages project compilation, cache writing,
/// and tracking of all packages that make up the workspace.
#[derive(Debug)]
pub struct WorkspaceHandler {
nest: Nest,
nest_lock: Option<NestLock>,
@@ -25,6 +30,13 @@ impl WorkspaceHandler {
const DIR_SRC: &str = "src/";
const DIR_TARGET: &str = "target/";
/// Creates a new [`WorkspaceHandler`] instance at the provided path.
///
/// # Errors
///
/// * [`Error::Io`] if the `project_root` cannot be canonicalized.
/// * [`Error::MissingFileName`] if a name for the workspace cannot be derived
/// from the `project_root`
pub fn new<P: AsRef<Path>>(project_root: P) -> crate::Result<Self> {
let project_root = project_root.as_ref().canonicalize()?;
@@ -41,6 +53,14 @@ impl WorkspaceHandler {
})
}
/// Loads an existing workspace from the provided path.
///
/// # Errors
///
/// * [`Error::Io`] for any number of IO-related errors.
/// Unwrap the [`std::io::Error`] for further information.
/// * [`Error::MissingFileName`] if a name for the workspace cannot be derived
/// from the `project_root`
pub fn load<P: AsRef<Path>>(project_root: P) -> crate::Result<Self> {
let project_root = project_root.as_ref().canonicalize()?;
@@ -56,62 +76,58 @@ impl WorkspaceHandler {
Ok(workspace_manager)
}
pub fn write(&self) -> crate::Result<()> {
self.nest.write(self.project_root.join(F_NEST_TOML))?;
/// Writes all lock files (Nest.toml, src/**/Prey.toml) to the disk.
pub fn write_locks(&self) -> crate::Result<()> {
if let Option::Some(lock) = self.nest_lock.clone() {
lock.write(self.project_root.join(F_NEST_LOCK))?;
}
Ok(())
}
//pub fn refresh_packages(&mut self) -> crate::Result<()> {}
/*
/// Future `build` method.
pub fn compile(&self, target: Option<PathBuf>) -> crate::Result<()> {
let mut target = target.unwrap_or(self.nest.default_package());
if !target.is_file() {
// Use is_file to skip messing with pathing for src/
// If target is not a file (explicit entry point), check if it's a known package
// and use that's package's default entry point.
target = target.join(
self.packages
.get(&target)
.ok_or(Error::UnknownPackage)?
.entry_point(),
);
for handler in self.packages.values() {
handler.write_lock()?;
}
//java::Compiler::new();
Ok(())
}
fn make_compiler_job<P: AsRef<Path>>(target: P) {
// Generate dependency tree.
}
*/
pub fn init(&mut self) -> crate::Result<()> {
/// Initializes a new workspace.
///
/// # Behaviour
///
/// Init will avoid overwriting or adding an example project if raven is being integrated into
/// an existing workspace codebase.
///
/// Init will always write:
///
/// * Nest.toml
/// * .java-version
/// * Attempt to append to .gitignore
///
/// If this is an empty workspace, init will include:
///
/// * Calling `git init`
/// * Writing an example project.
/// * Automatic package discovery.
///
/// # Errors
pub fn init(&mut self) -> crate::Result<&mut Self> {
// ORDER MATTERS.
let is_empty = read_dir(self.project_root.as_path()).is_ok_and(|tree| tree.count() == 0);
// ORDER MATTERS. THIS MUST COME FIRST.
// Make config file.
self.write_nest()?;
// Make .java-version
self.write_java_version()?;
// Make src/, target/, test/
self.write_dir_tree()?;
if !is_empty {
if is_empty {
self.write_example_project()?;
self.discover_packages()?;
run_process(&["git", "init", "."])?;
Exec::cmd("git")
.arg("init")
.arg(".")
.start()?
.wait_timeout(Duration::from_secs(10))?;
}
// Append to .gitignore
@@ -135,15 +151,148 @@ impl WorkspaceHandler {
}
}
Ok(())
Ok(self)
}
// This is the naive build
pub fn build(&mut self) -> crate::Result<()> {
Ok(())
/// This is a naive build; it attempts to build every source file individually.
///
/// It calls [`PackageHandler::get_outdated()`] on all known packages to determine
/// compile targets.
///
/// It will then attempt to write all locks to update the caches and avoid attempting to
/// needlessly recompile targets.
///
/// # Errors
///
/// * [`Error::AbsentPrimeError`]
/// * [`Error::Io`]
pub fn build(&mut self) -> crate::Result<&mut Self> {
let compiler = java::compiler::CompilerBuilder::new()
.class_path(Self::DIR_TARGET)
.destination(Self::DIR_TARGET)
.build();
// No unintentional deep copying anywhere, right?
// Probably not. We'll see.
for handler in self.packages.values_mut() {
let package_src_root = self
.project_root
.join(Self::DIR_SRC)
.join(handler.name())
.join(package::DIR_JAVA);
let targets = handler.get_outdated(self.project_root.join(Self::DIR_TARGET));
for mut target in targets {
dbg!(&target);
if let Ok(true) = compiler
.clone()
.compile(package_src_root.join(target.path.as_path()))
{
target.update(package_src_root.as_path())?;
handler
.prey_lock()
.classes()
.replace(target)
.ok_or(Error::AbsentPrimeHashingError)?;
}
}
}
self.write_locks()?;
Ok(self)
}
/// Add any newly created packages.
/// Attempts to call the JVM to run, in order of precedence:
///
/// 1. Provided entry point which includes a specific source file.
/// 2. Provided entry point to a package, using that package's default entry point
/// defined in it's `Prey.toml`
/// 3. The workspace's default package defined in `Nest.toml`, and that package's default
/// entry point as defined in it's `Prey.toml`.
///
/// # Errors
///
/// * [`Error::UnknownPackage`] if the package cannot be found.
/// * [`Error::UndefinedEntryPoint`] if no fallback entry point can be found.
/// * [`Error::Io`]
/// * [`Error::Java`]
pub fn run<P: AsRef<Path>>(
&mut self,
entry_point: Option<P>,
assertions: bool,
) -> crate::Result<&mut Self> {
let mut entry_point = if entry_point.is_none() {
self.nest.default_package()
} else {
entry_point.unwrap().as_ref().to_path_buf()
};
if !entry_point.is_file() {
// Use is_file to skip messing with pathing for src/
// If target is not a file (explicit entry point), check if it's a known package
// and use that's package's default entry point.
entry_point = self
.packages
.get(&entry_point)
.ok_or(Error::UnknownPackage)?
.entry_point();
}
if entry_point.file_name().is_none() {
return Err(Error::UndefinedEntryPoint);
}
java::runtime::JVMBuilder::new(Self::DIR_TARGET)
.assertions(assertions)
.monitor(true)
.build()
.run(entry_point)?;
Ok(self)
}
/// Cleans the workspace of it's caches:
///
/// * `target/`
/// * Nest.lock
/// * Prey.lock
pub fn clean(&mut self) -> crate::Result<&mut Self> {
// Clear Nest.lock
if let Err(err) = std::fs::remove_file(self.project_root.join(F_NEST_LOCK)) {
if err.kind() != std::io::ErrorKind::NotFound {
return Err(Error::from(err));
}
}
// Clear src/**/Prey.lock
for handler in self.packages.values() {
if let Err(err) = std::fs::remove_file(
self.project_root
.join(Self::DIR_SRC)
.join(handler.name())
.join(F_PREY_LOCK),
) {
if err.kind() != std::io::ErrorKind::NotFound {
return Err(Error::from(err));
}
}
}
// Clear target/
let _ = std::fs::remove_dir_all(Self::DIR_TARGET);
Ok(self)
}
/// Scan for newly created packages, wrapping them in [`PackageHandler`]s
/// and adding them to the [`WorkspaceHandler`]'s package map.
///
/// Packages are identified by their `Prey.toml` manifests.
///
/// # Errors
///
/// * [`Error::Io`]
fn discover_packages(&mut self) -> crate::Result<()> {
// Scan the src/ directory for entries,
// filter out the files,
@@ -157,7 +306,7 @@ impl WorkspaceHandler {
// Yes, I know this looks like shit.
// That's because it is.
for file in read_dir(Self::DIR_SRC)?
for file in read_dir(self.project_root.join(Self::DIR_SRC))?
// Get directories
.filter_map(|entry| {
if entry.as_ref().is_ok_and(|entry| entry.path().is_dir()) {
@@ -186,42 +335,53 @@ impl WorkspaceHandler {
})
.flatten()
{
let package_root =
pathsub::sub_paths(file.as_path(), PathBuf::from(Self::DIR_SRC).as_path()).unwrap();
let package_root = pathsub::sub_paths(
file.as_path(),
self.project_root.join(Self::DIR_SRC).as_path(),
)
.unwrap()
.parent()
.unwrap()
.to_path_buf();
self.packages.insert(
package_root.to_path_buf(),
PackageHandler::new(package_root, PathBuf::from(Self::DIR_TARGET))?,
PackageHandler::new(
self.project_root.join(Self::DIR_SRC),
package_root,
self.project_root.join(Self::DIR_TARGET),
)?,
);
}
Ok(())
}
/// Writes the [`WorkspaceHandler`]'s `Nest.toml` to disk.
fn write_nest(&self) -> crate::Result<()> {
if let Result::Ok(mut f) = OpenOptions::new()
.write(true)
.create_new(true)
.open(F_NEST_TOML)
{
f.write_all(toml::to_string_pretty(&self.nest)?.as_bytes())?;
}
Ok(())
Ok(self.nest.write(self.project_root.clone())?)
}
/// Writes a `.java-version` file for `jenv` to the disk with an automatically parsed
/// java version from [`java::get_javac_version()`].
///
/// # Errors
///
/// * [`Error::Io`]
/// * [`Error::Java`]
fn write_java_version(&self) -> crate::Result<()> {
if let Result::Ok(mut f) = OpenOptions::new()
.write(true)
.create_new(true)
.open(java::F_JAVA_VERSION)
{
f.write_all(format!("{}\n", java::get_javac_ver()?.major.to_string()).as_bytes())?;
f.write_all(format!("{}\n", java::get_javac_version()?.major.to_string()).as_bytes())?;
}
Ok(())
}
/// Writes an example project tree to disk.
fn write_dir_tree(&self) -> std::io::Result<()> {
for dir in [
format!("{}main/java", Self::DIR_SRC),
@@ -234,22 +394,51 @@ impl WorkspaceHandler {
Ok(())
}
fn write_example_project(&self) -> std::io::Result<()> {
/// Writes an example project to disk.
fn write_example_project(&self) -> crate::Result<()> {
let main: PathBuf = PathBuf::from(Self::DIR_SRC).join("main/");
let test: PathBuf = PathBuf::from(Self::DIR_SRC).join("test/");
// Make src/, target/, test/
self.write_dir_tree()?;
// Make src/main/Prey.toml
if let Result::Ok(mut f) = OpenOptions::new()
.write(true)
.create_new(true)
.open(main.join(F_PREY_TOML))
{
f.write_all(
toml::to_string_pretty(&Prey::new("main").with_entry_point("Main"))?.as_bytes(),
)?;
}
// Make src/main/Main.java
if let Result::Ok(mut f) = OpenOptions::new().write(true).create_new(true).open(
PathBuf::from(Self::DIR_SRC)
.join("main/java/Main")
.with_extension(JAVA_EXT_SOURCE),
) {
if let Result::Ok(mut f) = OpenOptions::new()
.write(true)
.create_new(true)
.open(main.join("java/Main").with_extension(JAVA_EXT_SOURCE))
{
f.write_all(include_bytes!("../assets/Main.java"))?;
}
// Make src/test/Prey.toml
if let Result::Ok(mut f) = OpenOptions::new()
.write(true)
.create_new(true)
.open(test.join(F_PREY_TOML))
{
f.write_all(
toml::to_string_pretty(&Prey::new("test").with_entry_point("MainTest"))?.as_bytes(),
)?;
}
// Make src/test/MainTest.java
if let Result::Ok(mut f) = OpenOptions::new().write(true).create_new(true).open(
PathBuf::from(Self::DIR_SRC)
.join("test/java/MainTest")
.with_extension(JAVA_EXT_SOURCE),
) {
if let Result::Ok(mut f) = OpenOptions::new()
.write(true)
.create_new(true)
.open(test.join("java/MainTest").with_extension(JAVA_EXT_SOURCE))
{
f.write_all(include_bytes!("../assets/MainTest.java"))?;
}

View File

@@ -8,7 +8,6 @@ description = "Raven's FS utilities"
repository.workspace = true
publish.workspace = true
test.workspace = true
[dependencies]
derive_more.workspace = true

View File

@@ -1,15 +0,0 @@
[package]
name = "io"
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "Raven's IO utilities"
repository.workspace = true
publish.workspace = true
test.workspace = true
[dependencies]
derive_more.workspace = true
subprocess.workspace = true

View File

@@ -1,11 +0,0 @@
use derive_more::{Display, From};
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, From, Display)]
pub enum Error {
#[from]
Io(std::io::Error),
#[from]
Popen(subprocess::PopenError),
}

View File

@@ -1,30 +0,0 @@
mod error;
use std::ffi;
pub use error::{Error, Result};
pub fn run_process<S>(argv: &[S]) -> 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)?;
if process
.wait_timeout(std::time::Duration::from_secs(5))
.is_err()
|| process.exit_status().is_none()
{
process.terminate()?;
}
Ok(result)
}

View File

@@ -3,7 +3,7 @@
[package]
name = "java"
version = "0.1.0"
version = "0.2.2"
edition.workspace = true
license.workspace = true
@@ -11,11 +11,10 @@ description = "Tools for interfacing with the Java Development Kit"
repository.workspace = true
publish.workspace = true
test.workspace = true
[dependencies]
bytesize.workspace = true
derive_more.workspace = true
fs.workspace = true
io.workspace = true
semver.workspace = true
subprocess.workspace = true

View File

@@ -1,6 +1,11 @@
use std::fmt::Display;
use std::path::{Path, PathBuf};
use subprocess::Exec;
use subprocess::Redirection;
use crate::JAVA_BIN_COMPILER;
use crate::JAVA_EXT_SOURCE;
use crate::Result;
#[derive(Debug, Default, Clone)]
@@ -45,22 +50,20 @@ pub struct Compiler {
}
impl Compiler {
pub fn compile<P: AsRef<Path>>(self, path: P) -> Result<(Option<String>, Option<String>)> {
let mut cmd: Vec<String> = vec![JAVA_BIN_COMPILER.to_string()];
cmd.extend(
self.flags
.clone()
.into_iter()
.flat_map(|f| Into::<Vec<String>>::into(f)),
);
cmd.extend(
fs::expand_files(path)?
.into_iter()
.filter_map(|f| Some(f.to_str()?.to_string())),
);
Ok(io::run_process(cmd.as_slice())?)
pub fn compile<P: AsRef<Path>>(self, path: P) -> Result<bool> {
Ok(Exec::cmd(JAVA_BIN_COMPILER)
.args(
self.flags
.clone()
.into_iter()
.flat_map(|f| Into::<Vec<String>>::into(f)),
)
.arg(path.as_ref().with_extension(JAVA_EXT_SOURCE))
.stdout(Redirection::Pipe)
.detached()
.start()?
.wait()?
.success())
}
}
@@ -68,6 +71,7 @@ impl Compiler {
pub enum CompilerFlag {
Classpath { path: PathBuf },
Destination { path: PathBuf },
Version,
}
impl Into<Vec<String>> for CompilerFlag {
@@ -75,6 +79,18 @@ impl Into<Vec<String>> for CompilerFlag {
match self {
Self::Classpath { path } => vec!["-classpath".to_string(), path.display().to_string()],
Self::Destination { path } => vec!["-d".to_string(), path.display().to_string()],
Self::Version => vec!["--version".to_string()],
}
}
}
// TODO: Clean this up a bit?
impl Display for CompilerFlag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Classpath { path } => write!(f, "-classpath {}", path.display()),
Self::Destination { path } => write!(f, "-d {}", path.display()),
Self::Version => write!(f, "--version"),
}
}
}

View File

@@ -1,19 +1,16 @@
use derive_more::{Display, From};
pub type Result<T> = core::result::Result<T, Error>;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, From, Display)]
pub enum Error {
EmptyStdout,
#[from]
Io(io::Error),
Io(std::io::Error),
NthOutOfBounds,
#[from]
Semver(semver::Error),
#[from]
StdIo(std::io::Error),
}

View File

@@ -6,6 +6,9 @@ use std::str::FromStr;
pub use error::{Error, Result};
use runtime::VMFlag;
use subprocess::Exec;
use crate::compiler::CompilerFlag;
pub const JAVA_BIN_VM: &str = "java";
pub const JAVA_BIN_COMPILER: &str = "javac";
@@ -15,24 +18,22 @@ pub const JAVA_EXT_CLASS: &str = "class";
pub const F_JAVA_VERSION: &str = ".java-version";
/// Uses the java binary to parse its stdout for version information.
///
/// This is non-caching.
pub fn get_javac_ver() -> Result<semver::Version> {
// TODO: Consider making this pull the version info from javac instead?
/*
* $ 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)
*/
/// Uses the javac binary to get information about the install compiler.
pub fn get_javac_version() -> Result<semver::Version> {
// Try to pull from javac first.
if let Ok(version) = semver::Version::from_str(
Exec::cmd(JAVA_BIN_COMPILER)
.arg(CompilerFlag::Version.to_string())
.capture()?
.stdout_str()
.replace("javac", "")
.trim(),
) {
return Ok(version);
}
Ok(semver::Version::from_str(
get_java_version_info()?
.lines()
.nth(0)
.ok_or(Error::EmptyStdout)?
.split_ascii_whitespace()
.nth(1)
.ok_or(Error::NthOutOfBounds)?,
@@ -41,9 +42,14 @@ pub fn get_javac_ver() -> Result<semver::Version> {
/// Calls the java binary, returning the complete stdout version information.
fn get_java_version_info() -> Result<String> {
Ok(
io::run_process(&[JAVA_BIN_VM, VMFlag::Version.to_string().as_str()])?
.0
.ok_or(Error::EmptyStdout)?,
)
/*
* $ 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)
*/
Ok(Exec::cmd(JAVA_BIN_VM)
.arg(VMFlag::Version.to_string())
.capture()?
.stdout_str())
}

View File

@@ -5,6 +5,7 @@ use crate::JAVA_BIN_VM;
use crate::Result;
use bytesize::ByteSize;
use subprocess::Exec;
#[derive(Debug, Default, Clone)]
pub struct JVMBuilder {
@@ -74,36 +75,32 @@ pub struct JVM {
}
impl JVM {
pub fn run<P: AsRef<Path>>(self, entry_point: P) -> Result<(Option<String>, Option<String>)> {
let mut cmd = vec![JAVA_BIN_VM.to_string()];
pub fn run<P: AsRef<Path>>(self, entry_point: P) -> Result<()> {
let capture = Exec::cmd(JAVA_BIN_VM)
.args(
self.flags
.clone()
.into_iter()
.flat_map(|f| Into::<Vec<String>>::into(f)),
)
.arg(entry_point.as_ref())
.capture()?;
cmd.extend(
self.flags
.clone()
.into_iter()
.flat_map(|f| Into::<Vec<String>>::into(f)),
);
cmd.push(entry_point.as_ref().to_path_buf().display().to_string());
let result = io::run_process(cmd.as_slice())?;
if self.monitor {
let (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}");
}
if !self.monitor {
return Ok(());
}
Ok(result)
let stdout = capture.stdout_str();
if stdout.len() > 0 {
println!("{stdout}");
}
let stderr = capture.stderr_str();
if stderr.len() > 0 {
eprintln!("{stderr}");
}
Ok(())
}
}

View File

@@ -1,14 +0,0 @@
[package]
name = "path"
version = "0.1.0"
edition.workspace = true
license.workspace = true
description = "Raven's pathing tools"
repository.workspace = true
publish.workspace = true
test.workspace = true
[dependencies]
const_format.workspace = true

View File

@@ -1,151 +0,0 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
//TODO: Clean this up. Shouldn't need duplicated DIR_SRC consts about the workspace.
const DIR_SRC: &str = "src/";
const DIR_TARGET: &str = "target/";
const DIR_MAIN: &str = const_format::concatcp!(DIR_SRC, "main/");
const DIR_TEST: &str = const_format::concatcp!(DIR_SRC, "test/");
#[derive(Debug, Clone)]
pub struct PathHandler {
root_path: PathBuf,
// This is a short-living binary. This doesn't need an LRU like Moka.
derived_path_cache: HashMap<String, PathBuf>,
}
impl PathHandler {
pub fn new(root_path: PathBuf) -> Self {
Self::from(root_path)
}
pub fn root_path(&self) -> PathBuf {
self.root_path.clone()
}
/// This is a readability helper.
/// Make sure to set the root of this `PathHandler` to the project root.
/// This simply calls upon the root_path() of the `PathHandler`.
pub fn project_root(&self) -> PathBuf {
self.root_path()
}
pub fn dir_src(&mut self) -> PathBuf {
self.get_path(DIR_SRC)
}
pub fn dir_target(&mut self) -> PathBuf {
self.get_path(DIR_TARGET)
}
pub fn dir_main(&mut self) -> PathBuf {
self.get_path(DIR_MAIN)
}
pub fn dir_test(&mut self) -> PathBuf {
self.get_path(DIR_TEST)
}
/// Attempts to load from cache, else generates the path and clones it to the cache.
/// Returns the requested path.
fn get_path<S>(&mut self, k: S) -> PathBuf
where
S: ToString + AsRef<str>,
{
self.from_cache(k.as_ref())
.unwrap_or_else(|| {
self.gen_key(k.to_string(), self.root_path().join(k.to_string()));
self.get_path(k.as_ref())
})
.to_path_buf()
}
/// Attempts to pull the value for the given key from the cache.
fn from_cache<S: AsRef<str>>(&self, path_key: S) -> Option<PathBuf> {
self.derived_path_cache
.get(path_key.as_ref())
.and_then(|v| Some(v.to_owned()))
}
/// Tries to generate a new key-value pair in the cache
fn gen_key<P, S>(&mut self, k: S, v: P) -> Option<PathBuf>
where
P: AsRef<Path>,
S: ToString,
{
self.derived_path_cache
.insert(k.to_string(), v.as_ref().to_path_buf())
}
}
impl<P> From<P> for PathHandler
where
P: AsRef<Path>,
{
fn from(value: P) -> Self {
Self {
root_path: value.as_ref().to_path_buf(),
derived_path_cache: Default::default(),
}
}
}
pub trait PathHandled {
fn set_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) {}
fn with_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) -> &mut Self {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
const ROOT: &str = "/root";
#[test]
fn ph_get_path() {
let root = PathBuf::from(ROOT);
let expected = root.join(DIR_SRC);
let mut ph = PathHandler::from(root);
assert!(ph.dir_src() == expected);
}
#[test]
fn ph_cache_gen() {
let root = PathBuf::from(ROOT);
let expected = root.join(DIR_SRC);
let ph = PathHandler::from(root);
assert!(
ph.derived_path_cache
.get(DIR_SRC)
.is_some_and(|v| *v == expected)
);
}
#[test]
fn ph_cache_pull() {
let faux_path = "faux/path";
let mut ph = PathHandler::from("false/root");
ph.derived_path_cache
.insert(faux_path.to_string(), PathBuf::from(faux_path));
// Use the method that attempts a fallback.
// By using a false root, this will create a different path to the injected one,
// making it possible to determine if the cache load fails.
//
// I.e.
// Expected: faux/path as PathBuf
// Failed: false/root/faux/path as PathBuf
assert!(ph.get_path(faux_path) == PathBuf::from(faux_path));
}
}

View File

@@ -8,7 +8,6 @@ description = "Library for serializing and deserializing Maven's POM"
repository.workspace = true
publish.workspace = true
test.workspace = true
[dependencies]
derive_more.workspace = true

View File

@@ -1,6 +1,6 @@
use derive_more::{Display, From};
pub type Result<T> = core::result::Result<T, Error>;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, From, Display)]
pub enum Error {

View File

@@ -1,6 +1,6 @@
[package]
name = "raven"
version = "0.1.0"
version = "0.2.0"
edition.workspace = true
license.workspace = true
@@ -10,7 +10,6 @@ categories = ["development-tools::build-utils"]
repository.workspace = true
publish.workspace = true
test.workspace = true
[dependencies]
anyhow.workspace = true
@@ -18,7 +17,5 @@ bytesize.workspace = true
cli.workspace = true
core.workspace = true
fs.workspace = true
io.workspace = true
java.workspace = true
path.workspace = true
toml.workspace = true

View File

@@ -1,19 +0,0 @@
use std::path::PathBuf;
use anyhow::Context;
pub fn in_path<S: AsRef<str>>(binary: S) -> Result<bool, std::env::VarError> {
std::env::var("PATH").and_then(|paths| {
Ok(paths
.split(":")
.map(|p| PathBuf::from(p).join(binary.as_ref()))
.any(|p| p.exists()))
})
}
pub fn get_project_root() -> anyhow::Result<PathBuf> {
nest::locate_nest().context(
"Attempted to find Nest.toml, but it could not be located.\n
It's likely that a call for get_project_root occurred before runtime checks were ran.",
)
}

View File

@@ -1,73 +1,49 @@
mod env;
mod manager;
use std::fs::OpenOptions;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use core::prelude::WorkspaceHandler;
use anyhow::anyhow;
use cli::{CLI_ARGS, Command};
use java::{FN_JAVA_VERSION, JAVA_EXT_CLASS, JAVA_EXT_SOURCE};
//use nest::prelude::{Class, F_NEST_LOCK, F_NEST_TOML, Nest, NestLock, Prey, PreyLock};
//use path::{PathHandled, PathHandler};
use anyhow::{Context, anyhow};
use bytesize::ByteSize;
fn main() -> anyhow::Result<()> {
// Ensure that ph is constructed with the assumption that it is at the project root.
let mut ph = match CLI_ARGS.command.clone() {
Command::Init => PathHandler::new(std::env::current_dir()?),
Command::New { name, .. } => PathHandler::new(std::env::current_dir()?.join(name)),
_ => PathHandler::new(crate::env::get_project_root()?),
};
// type_ is yet unused.
// Ensure that Nest.toml exists in the way functions need.
// Init does not need one, but it's easier to deal with the minor unnecessary computation
// of running the default contrustor, thand to fight the compiler.
let mut nest = match CLI_ARGS.command {
Command::Build | Command::Run { .. } => Nest::try_from(ph.project_root().join(F_NEST_TOML))
.map_err(|err| {
anyhow!(
"No {} found in project directory: {}.\n{}",
F_NEST_TOML,
ph.project_root().display(),
err.to_string()
)
})?,
_ => Nest::default(),
};
// `raven new` requires special behaviour.
// This will call the "new" part of the command,
// changing the cwd, before calling WorkspaceHandler.init()
// on the actual workspace directory.
if let Command::New { project_name, .. } = &CLI_ARGS.command {
new(project_name.to_owned())?;
}
match CLI_ARGS.command.clone() {
Command::Init => init(ph)?,
Command::New { name, .. } => {
new(name.to_owned())?;
init(ph)?;
}
Command::Build => {
build(&mut ph, &mut nest)?;
}
let project_root = std::env::current_dir()?;
let mut wh: WorkspaceHandler = match &CLI_ARGS.command {
Command::New { .. } | Command::Init => WorkspaceHandler::new(project_root),
_ => WorkspaceHandler::load(project_root),
}
.map_err(|err| anyhow!(err))?;
match &CLI_ARGS.command {
Command::New { .. } | Command::Init => wh.init(),
Command::Build => wh.build(),
Command::Run {
entry_point,
assertions,
} => {
build(&mut ph, &mut nest)?;
run(
&mut ph,
entry_point.unwrap_or(nest.workspace.default_package),
assertions.into(),
)?;
}
Command::Test { assertions } => {
test(&mut ph, assertions.into())?;
}
Command::Clean => clean(&mut ph),
} => wh
.build()
.map_err(|err| anyhow!(err))?
.run(entry_point.to_owned(), assertions.into()),
Command::Clean => wh.clean(),
Command::Test { .. } => unimplemented!(),
}
.map_err(|err| anyhow!(err))?;
Ok(())
}
/// Creates a new project directory and enters it.
fn new(project_name: String) -> anyhow::Result<()> {
// Because this messes around with the CWD, this should live external to any
// instance of a `WorkspaceHandler`.
let cwd = std::env::current_dir()?.join(project_name);
std::fs::create_dir(&cwd)?;
@@ -75,24 +51,3 @@ fn new(project_name: String) -> anyhow::Result<()> {
Ok(())
}
fn run<P: AsRef<Path>>(
ph: &mut PathHandler,
entry_point: P,
assertions: bool,
) -> anyhow::Result<(Option<String>, Option<String>)> {
// JRE pathing will be messed up without this.
std::env::set_current_dir(ph.dir_target())?;
java::runtime::JVMBuilder::new(ph.dir_target())
.assertions(assertions)
.monitor(true)
.build()
.run(entry_point)
.map_err(|err| anyhow!(err))
}
fn clean(ph: &mut PathHandler) {
let _ = std::fs::remove_file(ph.project_root().join(F_NEST_LOCK));
let _ = std::fs::remove_dir_all(ph.dir_target());
}

View File

@@ -1,11 +0,0 @@
use std::collections::HashSet;
use nest::prelude::{Nest, NestLock};
use path::PathHandler;
pub struct ProjectManager {
ph: PathHandler,
nest: Nest,
nest_lock: NestLock,
// HashSet<Crates { prey, prey_lock }>
}

View File

@@ -1,114 +0,0 @@
use std::hash::{self, Hash};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use crate::{Error, Result};
use java::{JAVA_EXT_CLASS, JAVA_EXT_SOURCE};
use path::PathHandler;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Class {
#[serde(skip_deserializing, skip_serializing)]
ph: Option<Arc<Mutex<PathHandler>>>,
path: PathBuf,
checksum: String,
}
impl Class {
pub fn new<P: AsRef<Path>>(ph: Arc<Mutex<PathHandler>>, path: P, checksum: String) -> Self {
Self {
ph: Some(ph),
path: path.as_ref().to_path_buf(),
checksum,
}
}
pub fn from_file<P: AsRef<Path>>(ph: Arc<Mutex<PathHandler>>, path: P) -> Result<Self> {
let mut path = path.as_ref().to_path_buf();
if path.is_relative() {
path = path.canonicalize()?;
}
let dir_src = ph.try_lock()?.dir_src();
Ok(Self {
ph: Some(ph),
path: PathBuf::from(
pathsub::sub_paths(path.as_path(), dir_src.as_path()).ok_or(Error::PathSub)?,
)
.with_extension(""),
checksum: sha256::try_digest(&path)?,
})
}
pub fn path(&self) -> PathBuf {
self.path.clone()
}
pub fn checksum(&self) -> String {
self.checksum.clone()
}
/// Returns the path such that src/ and target/ don't matter.
/// E.g., `main/Main.java` as_subpath is `Main.java`
/// allowing it to match with `target/main/Main.class`
/// because Java diregards the top level subdir in `src/`
fn subpath(&self) -> PathBuf {
let mut p = self.path.components();
p.next(); // Remove the top level dir.
p.as_path().to_path_buf()
}
/// Returns true if the class needs updating.
/// This may also cautionarily return true if it cannot digest the file.
pub fn is_updated(&mut self) -> Result<bool> {
// Still doesn't handle inter-dependency checks.
// Hopefully then I'll clean this horror up.
let mut ph = self
.ph
.as_ref()
.ok_or(Error::MissingPathHandler)?
.try_lock()?;
Ok(ph
.dir_target()
.join(self.subpath())
.with_extension(JAVA_EXT_CLASS)
.exists()
&& sha256::try_digest(
ph.dir_src()
.join(self.path())
.with_extension(JAVA_EXT_SOURCE),
)
.is_ok_and(|hash| self.checksum == hash))
}
pub fn set_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) {
self.ph = Some(ph);
}
pub fn with_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) -> &mut Self {
self.ph = Some(ph);
self
}
}
impl Hash for Class {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.path.hash(state);
}
}
impl PartialEq for Class {
fn eq(&self, other: &Self) -> bool {
self.path == other.path
}
fn ne(&self, other: &Self) -> bool {
self.path != other.path
}
}
impl Eq for Class {}

View File

@@ -1,7 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Hash, Default, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct Dependency {
name: String,
version: String,
}

View File

@@ -1,35 +0,0 @@
use std::sync::{MutexGuard, PoisonError, TryLockError};
use derive_more::{Display, From};
use path::PathHandler;
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, From, Display)]
pub enum Error {
#[from]
Io(std::io::Error),
MutexLock(String),
MutexTryLock(String),
PathSub,
#[from]
Toml(toml::de::Error),
MissingPathHandler,
}
impl From<PoisonError<MutexGuard<'_, PathHandler>>> for Error {
fn from(value: PoisonError<MutexGuard<PathHandler>>) -> Self {
Self::MutexLock(value.to_string())
}
}
impl From<TryLockError<MutexGuard<'_, PathHandler>>> for Error {
fn from(value: TryLockError<MutexGuard<PathHandler>>) -> Self {
Self::MutexTryLock(value.to_string())
}
}

View File

@@ -1,45 +0,0 @@
mod class;
mod dependency;
mod error;
//mod lock;
mod meta;
mod nest;
mod package;
pub mod prelude;
mod prey;
mod workspace;
pub use error::{Error, Result};
use std::io;
use std::path::PathBuf;
pub const FN_NEST: &str = "Nest";
pub const FN_PREY: &str = "Prey";
pub const F_NEST_TOML: &str = const_format::concatcp!(FN_NEST, fs::EXT_TOML);
pub const F_NEST_LOCK: &str = const_format::concatcp!(FN_NEST, fs::EXT_LOCK);
pub const F_PREY_TOML: &str = const_format::concatcp!(FN_PREY, fs::EXT_TOML);
pub const F_PREY_LOCK: &str = const_format::concatcp!(FN_PREY, fs::EXT_LOCK);
/// Return the location of the parent `Nest.toml` as [`PathBuf`]
///
/// # Errors
///
/// Possible cases:
///
/// * `Nest.toml` cannot be located.
/// * Current working directory does not exist.
/// * There are insufficient permissions to access the current directory.
pub fn locate_nest() -> io::Result<PathBuf> {
let cwd = std::env::current_dir()?;
let mut probe = cwd.clone();
while !probe.join(F_NEST_TOML).exists() {
if !probe.pop() {
return Err(io::ErrorKind::NotFound.into());
}
}
Ok(probe)
}

View File

@@ -1,99 +0,0 @@
use std::collections::HashSet;
use std::collections::hash_set::Iter;
use std::fs::OpenOptions;
use std::hash::Hash;
use std::io::Read;
use std::path::Path;
use std::sync::{Arc, Mutex};
use path::{PathHandled, PathHandler};
use serde::{Deserialize, Serialize};
use crate::Error;
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct Lock<T> {
#[serde(skip_deserializing, skip_serializing)]
ph: Option<Arc<Mutex<PathHandler>>>,
inner: HashSet<T>,
}
impl<T> Lock<T>
where
T: Lockable + Status + Deserialize<'de>,
{
pub fn new(ph: Arc<Mutex<PathHandler>>, inner: HashSet<T>) -> Self {
Self {
ph: Some(ph),
inner,
}
}
pub fn load<P>(ph: Arc<Mutex<PathHandler>>, path: P) -> crate::Result<Self>
where
P: AsRef<Path>,
{
let mut path = path.as_ref().to_path_buf();
if path.is_relative() {
path = path.canonicalize()?;
}
let mut buf = Vec::new();
OpenOptions::new()
.read(true)
.open(path)?
.read_to_end(&mut buf)?;
let lock: Lock<T> = toml::from_slice(buf.as_slice())?;
Ok(lock)
}
pub fn update(&mut self) -> crate::Result<()> {
let ph = self.ph.as_ref().ok_or(Error::MissingPathHandler)?.clone();
self.inner = self
.inner
.clone()
.into_iter()
.filter_map(|mut item| {
let item = item.with_path_handler(Arc::clone(&ph));
// If the class is up-to-date and no errors occurred during the check
if item.is_updated().is_ok_and(|b| b == true) {
Some(item.to_owned())
} else {
None
}
})
.collect();
Ok(())
}
pub fn set_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) {
self.ph = Some(ph);
}
pub fn with_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) -> &mut Self {
self.ph = Some(ph);
self
}
/// Iterates over the entries in `NestLock`.
pub fn iter(&self) -> Iter<'_, T> {
self.inner.iter()
}
pub fn insert(&mut self, class: T) -> bool {
self.inner.insert(class)
}
}
pub trait Lockable: Hash + Eq + Clone + PathHandled {}
trait Status {
type Error;
fn is_updated(&self) -> Result<bool, Self::Error>;
}

View File

@@ -1,62 +0,0 @@
use std::fmt::Display;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Meta {
name: String,
version: semver::Version,
#[serde(skip_serializing_if = "<Option<_>>::is_none")]
authors: Option<Vec<String>>,
#[serde(skip_serializing_if = "<Option<_>>::is_none")]
repository: Option<String>,
#[serde(skip_serializing_if = "<Option<_>>::is_none")]
license: Option<License>,
#[serde(skip_serializing_if = "<Option<_>>::is_none")]
license_file: Option<PathBuf>,
}
impl Meta {
pub fn new<S: ToString>(name: S) -> Self {
let mut meta = Self::default();
meta.name = name.to_string();
meta
}
pub fn name(&self) -> String {
self.name.clone()
}
}
impl Default for Meta {
fn default() -> Self {
Self {
name: Default::default(),
version: semver::Version::new(0, 1, 0),
authors: None,
repository: None,
license: None,
license_file: None,
}
}
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
pub enum License {
Mit,
Apache,
}
impl Display for License {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
License::Mit => "MIT",
License::Apache => "Apache",
}
)
}
}

View File

@@ -1,130 +0,0 @@
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::Read;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use crate::Error;
use crate::dependency::Dependency;
use crate::meta::Meta;
use crate::package::Package;
use crate::workspace::Workspace;
use path::{PathHandled, PathHandler};
use pom::Pom;
use serde::{Deserialize, Serialize};
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Nest {
pub workspace: Workspace,
pub meta: Meta,
#[serde(default, skip_serializing_if = "HashSet::is_empty")]
pub dependencies: HashSet<Dependency>,
#[serde(default, skip_serializing_if = "Pom::is_empty")]
pub pom: Pom,
}
impl Nest {
pub fn new<S: ToString>(name: S) -> Self {
Nest {
meta: Meta::new(name),
..Default::default()
}
}
}
impl TryFrom<File> for Nest {
type Error = 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)?;
Ok(toml::from_str(buf.as_str())?)
}
}
impl TryFrom<PathBuf> for Nest {
type Error = Error;
fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
Nest::try_from(OpenOptions::new().read(true).open(value)?)
}
}
// TODO: See if NestLock and PreyLock can be combined into one parent struct,
// but with different generics, and merely call upon a is_updated method set
// by the generics implementing a common IsUpdated trait.
//
// Not happening any time soon. An enum could get around the issue of being unable to
// implement Deserialize on a generic.
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct NestLock {
#[serde(skip_serializing, skip_deserializing)]
ph: Option<Arc<Mutex<PathHandler>>>,
pub packages: HashSet<Package>,
}
impl NestLock {
/// Update, retaining all packages that still exist.
///
/// Presently only supports packages under src/
pub fn update(&mut self) -> crate::Result<()> {
let dir_src = self
.ph
.as_ref()
.ok_or(Error::MissingPathHandler)?
.try_lock()?
.dir_src();
self.packages = self
.packages
.clone()
.into_iter()
.filter_map(|package| {
let path = dir_src.join(package.name());
if path.exists() && path.is_dir() {
return Some(package);
}
None
})
.collect();
Ok(())
}
}
impl TryFrom<File> for NestLock {
type Error = 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)?;
Ok(toml::from_str(buf.as_str())?)
}
}
impl TryFrom<PathBuf> for NestLock {
type Error = Error;
fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
NestLock::try_from(OpenOptions::new().read(true).open(&value)?)
}
}
impl PathHandled for NestLock {
fn set_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) {
self.ph = Some(ph);
}
fn with_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) -> &mut Self {
self.ph = Some(ph);
self
}
}

View File

@@ -1,38 +0,0 @@
use std::{collections::HashSet, hash::Hash};
use serde::{Deserialize, Serialize};
use crate::dependency::Dependency;
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct Package {
name: String,
version: semver::Version,
source: String,
checksum: String,
dependencies: HashSet<Dependency>,
}
impl Package {
pub fn name(&self) -> String {
self.name.clone()
}
}
impl Default for Package {
fn default() -> Self {
Self {
name: Default::default(),
version: semver::Version::new(0, 1, 0),
source: Default::default(),
checksum: Default::default(),
dependencies: Default::default(),
}
}
}
impl Hash for Package {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}

View File

@@ -1,10 +0,0 @@
#![allow(unused_imports)]
pub use crate::class::Class;
pub use crate::dependency::Dependency;
pub use crate::meta::Meta;
pub use crate::nest::{Nest, NestLock};
pub use crate::package::Package;
pub use crate::prey::{Prey, PreyLock};
pub use crate::workspace::Workspace;
pub use crate::{F_NEST_LOCK, F_NEST_TOML, F_PREY_LOCK, F_PREY_TOML, FN_NEST, FN_PREY};

View File

@@ -1,127 +0,0 @@
use std::collections::HashSet;
use std::collections::hash_set::Iter;
use std::fs::{File, OpenOptions};
use std::io::Read;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use path::{PathHandled, PathHandler};
use serde::{Deserialize, Serialize};
use crate::Error;
use crate::class::Class;
use crate::meta::Meta;
use crate::package::Package;
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct Prey {
package: Package,
meta: Meta,
}
impl Prey {
pub fn new<S: ToString>(name: S) -> Self {
Prey {
package: (),
meta: (),
}
}
}
impl TryFrom<File> for Prey {
type Error = 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)?;
Ok(toml::from_str(buf.as_str())?)
}
}
impl TryFrom<PathBuf> for Prey {
type Error = Error;
fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
Prey::try_from(OpenOptions::new().read(true).open(value)?)
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct PreyLock {
#[serde(skip_deserializing, skip_serializing)]
ph: Option<Arc<Mutex<PathHandler>>>,
classes: HashSet<Class>,
}
impl PreyLock {
pub fn new(ph: Arc<Mutex<PathHandler>>, classes: HashSet<Class>) -> Self {
Self {
ph: Some(ph),
classes,
}
}
pub fn update(&mut self) -> crate::Result<()> {
let ph = self.ph.as_ref().ok_or(Error::MissingPathHandler)?.clone();
self.classes = self
.classes
.clone()
.into_iter()
.filter_map(|mut class| {
let class = class.with_path_handler(Arc::clone(&ph));
// If the class is up-to-date and no errors occurred during the check
if class.is_updated().is_ok_and(|b| b == true) {
Some(class.to_owned())
} else {
None
}
})
.collect();
Ok(())
}
/// Iterates over the entries in `PreyLock`.
pub fn iter(&self) -> Iter<'_, Class> {
self.classes.iter()
}
pub fn insert(&mut self, class: Class) -> bool {
self.classes.insert(class)
}
}
impl TryFrom<File> for PreyLock {
type Error = 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)?;
Ok(toml::from_str(buf.as_str())?)
}
}
impl TryFrom<PathBuf> for PreyLock {
type Error = Error;
fn try_from(value: PathBuf) -> Result<Self, Self::Error> {
PreyLock::try_from(OpenOptions::new().read(true).open(value)?)
}
}
impl PathHandled for PreyLock {
fn set_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) {
self.ph = Some(ph);
}
fn with_path_handler(&mut self, ph: Arc<Mutex<PathHandler>>) -> &mut Self {
self.ph = Some(ph);
self
}
}

View File

@@ -1,8 +0,0 @@
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct Workspace {
pub default_package: PathBuf,
}

View File

@@ -1,196 +0,0 @@
#![allow(dead_code)]
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::hash::{self, Hash};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use crate::java::{JAVA_EXT_CLASS, JAVA_EXT_SOURCE};
use crate::{DIR_SRC, DIR_TARGET, 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.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"),
)
}
}
// Rename to Prey
// Mark as deprecated soon.
#[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 classes: HashSet<Class>,
}
impl NestLock {
pub fn load() -> anyhow::Result<NestLock> {
NestLock::try_from(PROJECT_ROOT.join(F_NEST_LOCK.as_path()))
}
/// 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.classes = self
.classes
.clone()
.into_iter()
.filter_map(|class| {
// Paths are almost correct, except that the target classes are expecting to path
// through:
// target/main/Main.class, not target/Main.class
// target/test/MainTest.class, not target/MainTest.class
if DIR_SRC
.join(&class.path)
.with_extension(JAVA_EXT_SOURCE)
.exists()
&& DIR_TARGET
.join(&class.subpath())
.with_extension(JAVA_EXT_CLASS)
.is_file()
{
return Some(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, PartialEq, Eq)]
pub struct Class {
path: PathBuf,
checksum: String,
}
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 {
// Still doesn't handle inter-dependency checks.
DIR_TARGET
.join(self.subpath())
.with_extension(JAVA_EXT_CLASS)
.exists()
&& sha256::try_digest(DIR_SRC.join(self.path()).with_extension(JAVA_EXT_SOURCE))
.is_ok_and(|hash| self.checksum == hash)
}
/// Returns the path such that src/ and target/ don't matter.
/// E.g., `main/Main.java` as_subpath is `Main.java`
/// allowing it to match with `target/main/Main.class`
/// because Java diregards the top level subdir in `src/`
fn subpath(&self) -> PathBuf {
let mut p = self.path.components();
p.next(); // Remove the top level dir.
p.as_path().to_path_buf()
}
pub fn path(&self) -> &Path {
self.path.as_path()
}
}
impl Hash for Class {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.path.hash(state);
}
}
impl TryFrom<PathBuf> for Class {
type Error = anyhow::Error;
fn try_from(mut value: PathBuf) -> Result<Self, Self::Error> {
if value.is_relative() {
value = value
.canonicalize()
.context("Failed to canonicalize path")?;
}
Ok(Self {
path: PathBuf::from(
pathsub::sub_paths(value.as_path(), DIR_SRC.as_path())
.context("Failed to subtract paths to get class path")?,
)
.with_extension(""),
checksum: sha256::try_digest(&value)?,
})
}
}