Skip to content

Commit

Permalink
chore: refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
madonuko committed Jul 17, 2023
1 parent 3bb9e49 commit 6b18cc4
Show file tree
Hide file tree
Showing 34 changed files with 673 additions and 1,463 deletions.
436 changes: 225 additions & 211 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ license = "MIT"
exclude = [
"anda-build",
"anda-config",
"rpmspec-rs",
"andax",
".devcontainer",
".github",
Expand Down Expand Up @@ -57,6 +56,5 @@ itertools = "0.10.5"
members = [
"anda-config",
"xtask",
"rpmspec-rs",
"andax",
]
1 change: 1 addition & 0 deletions anda-config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ regex = "~1"
walkdir = "2.3.2"
ignore = "0.4"
once_cell = "1.16"
parking_lot = "0.12.1"

[dev-dependencies]
env_logger = "0.10.0"
47 changes: 29 additions & 18 deletions anda-config/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,26 @@ pub struct Config {
}

impl Manifest {
#[must_use]
pub fn find_key_for_value(&self, value: &Project) -> Option<&String> {
self.project.iter().find_map(|(key, val)| if val == value { Some(key) } else { None })
}

#[must_use]
pub fn get_project(&self, key: &str) -> Option<&Project> {
if let Some(project) = self.project.get(key) {
Some(project)
} else {
// check for alias
self.project.iter().find_map(|(_k, v)| {
if let Some(alias) = &v.alias {
self.project.get(key).map_or_else(
|| {
self.project.iter().find_map(|(_k, v)| {
let Some(alias) = &v.alias else { return None };
if alias.contains(&key.to_string()) {
return Some(v);
Some(v)
} else {
None
}
}
None
})
}
})
},
Some,
)
}
}

Expand Down Expand Up @@ -88,6 +90,7 @@ pub struct Docker {
}

/// Turn a string into a BTreeMap<String, String>
#[must_use]
pub fn parse_map(input: &str) -> Option<BTreeMap<String, String>> {
let mut map = BTreeMap::new();
for item in input.split(',') {
Expand Down Expand Up @@ -116,7 +119,11 @@ pub struct Flatpak {
pub post_script: Option<PathBuf>,
}

pub fn to_string(config: Manifest) -> Result<String, hcl::Error> {
/// Converts a [`Manifest`] to `String` (.hcl).
///
/// # Errors
/// - [`hcl::Error`] : Cannot convert to HCL.
pub fn to_string(config: &Manifest) -> Result<String, hcl::Error> {
let config = hcl::to_string(&config)?;
Ok(config)
}
Expand Down Expand Up @@ -176,10 +183,11 @@ pub fn load_from_file(path: &PathBuf) -> Result<Manifest, ProjectError> {
check_config(config)
}

#[must_use]
pub fn prefix_config(mut config: Manifest, prefix: &str) -> Manifest {
let mut new_config = config.clone();

for (project_name, project) in config.project.iter_mut() {
for (project_name, project) in &mut config.project {
// set project name to prefix
let new_project_name = format!("{prefix}/{project_name}");
// modify project data
Expand Down Expand Up @@ -236,7 +244,7 @@ pub fn generate_alias(config: &mut Manifest) {
}
}

for (name, project) in config.project.iter_mut() {
for (name, project) in &mut config.project {
if config.config.strip_prefix.is_some() || config.config.strip_suffix.is_some() {
let mut new_name = name.clone();
if let Some(strip_prefix) = &config.config.strip_prefix {
Expand All @@ -263,8 +271,11 @@ pub fn load_from_string(config: &str) -> Result<Manifest, ProjectError> {
check_config(config)
}

// Lints and checks the config for errors.
pub fn check_config(config: Manifest) -> Result<Manifest, ProjectError> {
/// Lints and checks the config for errors.
///
/// # Errors
/// - nothing. This function literally does nothing. For now.
pub const fn check_config(config: Manifest) -> Result<Manifest, ProjectError> {
// do nothing for now
Ok(config)
}
Expand All @@ -291,11 +302,11 @@ mod test_parser {

let body = hcl::parse(config).unwrap();

print!("{:#?}", body);
print!("{body:#?}");

let config = load_from_string(config);

println!("{:#?}", config);
println!("{config:#?}");
}

#[test]
Expand Down
27 changes: 14 additions & 13 deletions anda-config/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,24 @@ use hcl::Value;

// once_cell for global context
use once_cell::sync::OnceCell;
use std::sync::Mutex;
use parking_lot::Mutex;

// todo: let this be mutable
static GLOBAL_CONTEXT: OnceCell<Mutex<Context>> = OnceCell::new();

/// HCL Function for loading environment variables
pub fn env_func(args: FuncArgs) -> Result<Value, String> {
let env = std::env::vars().collect::<BTreeMap<String, String>>();
let key = args[0].as_str().unwrap();
let value = env.get(key).unwrap();
Ok(Value::String(value.to_string()))
}

/// Generate Context for HCL evaluation
///
/// # Panics
/// - cannot lock mutex (poison?)
/// - cannot convert FuncArgs to str
/// - cannot find FuncArgs as key in environment variables
pub fn hcl_context() -> Context<'static> {
let env_func = |args: FuncArgs| {
let env = std::env::vars().collect::<BTreeMap<String, String>>();
let key = args[0].as_str().unwrap();
let value = env.get(key).unwrap();
Ok(Value::String(value.to_string()))
};
let c = GLOBAL_CONTEXT.get_or_init(|| {
dotenv::dotenv().ok();
let mut ctx = Context::new();
Expand All @@ -29,13 +32,11 @@ pub fn hcl_context() -> Context<'static> {
let env = std::env::vars().collect::<BTreeMap<String, String>>();
let mut map = hcl::Map::new();

for (key, value) in env.iter() {
map.insert(key.to_string(), Value::String(value.to_string()));
}
map.extend(env.into_iter().map(|(k,v)| (k, Value::String(v))));

ctx.declare_var("env", Value::Object(map));

Mutex::new(ctx)
});
c.lock().unwrap().clone()
c.lock().clone()
}
12 changes: 6 additions & 6 deletions anda-config/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,22 @@ pub enum ProjectError {

impl From<hcl::error::Error> for ProjectError {
fn from(e: hcl::error::Error) -> Self {
ProjectError::HclError(e)
Self::HclError(e)
}
}

impl std::fmt::Display for ProjectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ProjectError::NoManifest => write!(f, "No manifest found"),
ProjectError::InvalidManifest(e) => write!(f, "Invalid manifest: {}", e),
ProjectError::Other(msg) => write!(f, "{}", msg),
ProjectError::HclError(e) => write!(
Self::NoManifest => write!(f, "No manifest found"),
Self::InvalidManifest(e) => write!(f, "Invalid manifest: {e}"),
Self::Other(msg) => write!(f, "{msg}"),
Self::HclError(e) => write!(
f,
"Error parsing HCL: {e}{}",
e.location().map(|l| format!(" at {}:{}", l.line, l.col)).unwrap_or_default()
),
ProjectError::Multiple(errors) => {
Self::Multiple(errors) => {
write!(f, "Multiple errors:")?;
for error in errors {
write!(f, "\n - {error}")?;
Expand Down
5 changes: 5 additions & 0 deletions anda-config/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![warn(clippy::disallowed_types)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::module_name_repetitions)]
pub mod config;
pub mod context;
pub mod error;
Expand Down
7 changes: 6 additions & 1 deletion anda-config/src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ use hcl::eval::Evaluate;
use hcl::template::Template;
use std::str::FromStr;

/// Parse an HCL template.
///
/// # Errors
/// - cannot parse template
/// - cannot evaluate template
pub fn parse_template(template: &str) -> Result<String, String> {
let template = Template::from_str(template).map_err(|e| e.to_string())?;
let ctx = hcl_context();
Expand All @@ -14,7 +19,7 @@ pub fn parse_template(template: &str) -> Result<String, String> {
fn test_templ() {
let template = "hello ${env.USER}";
let result = parse_template(template).unwrap();
println!("{}", result);
println!("{result}");
// get current username
let username = std::env::var("USER").unwrap();
assert_eq!(result, format!("hello {username}"));
Expand Down
4 changes: 2 additions & 2 deletions andax/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl Display for TbErr {
}
}

pub(crate) trait AndaxRes<T> {
pub trait AndaxRes<T> {
fn ehdl(self, ctx: &rhai::NativeCallContext) -> Result<T, Box<EvalAltResult>>;
}

Expand All @@ -59,7 +59,7 @@ where
}
}

pub(crate) const EARTH: &str = r#"
pub const EARTH: &str = r#"
. . * . . . . * . . . . . . * . . . .
* . . * . . . * . . * . . . * . . .
. * . . . . . * . . . .-o--. . * .
Expand Down
15 changes: 9 additions & 6 deletions andax/src/fns/build.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
/// This file contains functions for andax
/// which implements procedures from building RPMs
/// see anda rpm_spec.rs
use rhai::plugin::*;
//! This file contains functions for andax
//! which implements procedures from building RPMs
//! see `anda::rpm_spec.rs`
use rhai::plugin::{
export_module, mem, Dynamic, FnAccess, FnNamespace, ImmutableString, Module, NativeCallContext,
PluginFunction, RhaiResult, TypeId,
};

// 正にこうです。 :3
macro_rules! rpmargs {
Expand Down Expand Up @@ -33,10 +36,10 @@ macro_rules! rpmargs {

#[export_module]
pub mod ar {
pub(crate) fn cmd_srpm(spec: &str, sources: Option<&str>) -> Vec<String> {
pub fn cmd_srpm(spec: &str, sources: Option<&str>) -> Vec<String> {
rpmargs!("--buildsrpm", spec, sources)
}
pub(crate) fn cmd_rpm(spec: &str, sources: Option<&str>) -> Vec<String> {
pub fn cmd_rpm(spec: &str, sources: Option<&str>) -> Vec<String> {
rpmargs!("--rebuild", spec, sources)
}
}
19 changes: 11 additions & 8 deletions andax/src/fns/cfg.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
use crate::error::AndaxRes;
use anda_config::load_from_file;
use rhai::{plugin::*, EvalAltResult};
use rhai::{
plugin::{
export_module, mem, Dynamic, FnAccess, FnNamespace, ImmutableString, Module,
NativeCallContext, PluginFunction, RhaiResult, TypeId,
},
EvalAltResult,
};
use std::path::PathBuf;

type Res<T> = Result<T, Box<EvalAltResult>>;

#[export_module]
pub mod ar {
#[rhai_fn(return_raw)]
pub(crate) fn load_file(ctx: NativeCallContext, path: &str) -> Res<rhai::Map> {
pub fn load_file(ctx: NativeCallContext, path: &str) -> Res<rhai::Map> {
let m = load_from_file(&PathBuf::from(path)).ehdl(&ctx)?;
let mut manifest = rhai::Map::new();
let mut conf = rhai::Map::new();
Expand Down Expand Up @@ -44,7 +50,7 @@ fn _pb(pb: Option<PathBuf>) -> Dynamic {
pb.map_or(().into(), |s| s.to_str().unwrap_or("").into())
}
fn _rpm(o: Option<anda_config::RpmBuild>) -> Dynamic {
o.map(|r| {
o.map_or(().into(), |r| {
let mut m = rhai::Map::new();
m.insert("spec".into(), r.spec.to_str().unwrap_or("").into());
m.insert("sources".into(), _pb(r.sources));
Expand All @@ -60,10 +66,9 @@ fn _rpm(o: Option<anda_config::RpmBuild>) -> Dynamic {
m.insert("opts".into(), r.opts.unwrap_or_default().into());
m.into()
})
.unwrap_or_else(|| ().into())
}
fn _docker(o: Option<anda_config::Docker>) -> Dynamic {
o.map(|d| {
o.map_or(().into(), |d| {
let mut m = rhai::Map::new();
m.insert(
"image".into(),
Expand All @@ -82,15 +87,13 @@ fn _docker(o: Option<anda_config::Docker>) -> Dynamic {
);
m.into()
})
.unwrap_or_else(|| ().into())
}
fn _flatpak(o: Option<anda_config::Flatpak>) -> Dynamic {
o.map(|f| {
o.map_or(().into(), |f| {
let mut m = rhai::Map::new();
m.insert("manifest".into(), _pb(Some(f.manifest)));
m.insert("pre_script".into(), _pb(f.pre_script));
m.insert("post_script".into(), _pb(f.post_script));
m.into()
})
.unwrap_or_else(|| ().into())
}
Loading

0 comments on commit 6b18cc4

Please sign in to comment.