Skip to content

Commit

Permalink
feat: dry-run operation for validation only
Browse files Browse the repository at this point in the history
Signed-off-by: Lincoln Wallace <lincoln.wallace@canonical.com>
  • Loading branch information
locnnil committed Jul 19, 2024
1 parent 8442928 commit 3d7336d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 16 deletions.
57 changes: 43 additions & 14 deletions extensions/env-injector/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use hyper::{Method, Request};
use hyper_util::client::legacy::Client;
use hyperlocal::{UnixClientExt, UnixConnector, Uri};
use std::error::Error;
use std::fmt::format;
use std::process::Command;
use std::collections::HashMap;
use std::path::Path;
Expand All @@ -19,7 +20,7 @@ async fn snapdapi_req() -> Result<serde_json::Value, Box<dyn Error + Send + Sync
let snap_context = std::env::var("SNAP_CONTEXT")?;

let request_body = format!(
r#"{{"context-id":"{}","args":["get","env", "envfile", "apps"]}}"#,
r#"{{"context-id":"{}","args":["get", "env", "envfile", "apps"]}}"#,
snap_context
);

Expand Down Expand Up @@ -74,17 +75,6 @@ fn set_env_vars(app: &str, json: &serde_json::Value) -> Result<(), Box<dyn std::
}

fn source_env_file(file_path: &str) -> std::io::Result<HashMap<String, String>> {
let path = Path::new(file_path);

if !path.exists() {
eprintln!("File does not exist: {}", file_path);
return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "File does not exist"));
}

if !path.is_file() {
eprintln!("File is not readable: {}", file_path);
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "File is not readable"));
}

let file = std::fs::File::open(file_path)?;
let reader = std::io::BufReader::new(file);
Expand Down Expand Up @@ -128,16 +118,55 @@ fn set_env_vars_from_file(app: &str, json: &serde_json::Value) -> Result<(), Bo
Ok(())
}


fn validate(json: &serde_json::Value) -> Result<(), Box<dyn Error + Send + Sync>> {

if let Some(global_envfile) = json["envfile"].as_str() {
file_validation(global_envfile)?;
}

if let Some(app_envfile) = json["apps"]["envfile"].as_str() {
file_validation(app_envfile)?;
}

Ok(())
}

fn file_validation(file_path: &str) -> std::io::Result<()> {
let path = Path::new(&file_path);

if !path.exists() {
let err = format!("File does not exist: {}", file_path);
eprintln!("{}", &err);
return Err(std::io::Error::new(std::io::ErrorKind::NotFound, err, ));
}

if !path.is_file() {
let err = format!("File is not readable: {}", file_path);
eprintln!("{}", &err);
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, err));
}

Ok(())
}



#[tokio::main]
async fn run() -> Result<(), Box<dyn Error + Send + Sync>> {

let dryrun = std::env::var("DRY_RUN").is_ok();

let json = snapdapi_req().await?;

let app = std::env::var("env_alias")?;

set_env_vars_from_file(&app, &json)?;
set_env_vars(&app, &json)?;
validate(&json)?;

if !dryrun {
set_env_vars_from_file(&app, &json)?;
set_env_vars(&app, &json)?;
}
Ok(())
}

Expand Down
7 changes: 5 additions & 2 deletions snapcraft/extensions/env_injector.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,13 @@ def get_root_snippet(self) -> Dict[str, Any]:


@overrides
def get_app_snippet(self) -> Dict[str, Any]:
def get_app_snippet(self, *, app_name: str) -> Dict[str, Any]:
"""Return the app snippet to apply."""
return {
"command-chain": [ "bin/command-chain/env-exporter"],
"environment": {
"env_alias": f"{app_name}",
}
}

@overrides
Expand All @@ -90,7 +93,7 @@ def get_parts_snippet(self) -> Dict[str, Any]:
toolchain = self.get_toolchain()
return {
f"env-injector/env-injector": {
"source": f"{get_extensions_data_dir()}/envs",
"source": f"{get_extensions_data_dir()}/env-injector",
"plugin": "nil",
"build-snaps": [
f"rustup",
Expand Down

0 comments on commit 3d7336d

Please sign in to comment.