Skip to content
This repository has been archived by the owner on May 27, 2024. It is now read-only.

update rust binary module to current standards #289

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 42 additions & 35 deletions rust-module-hello-world/module-src/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions rust-module-hello-world/module-src/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
[package]
name = "helloworld"
version = "0.1.0"
authors = ["Sviatoslav Sydorenko <[email protected]>"]
authors = ["Sviatoslav Sydorenko <[email protected]>", "Follpvosten <[email protected]>"]
edition = "2018"

[dependencies]
serde = "1.0.66"
serde_derive = "1.0.66"
serde_json = "1.0.20"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
anyhow = "1"
120 changes: 32 additions & 88 deletions rust-module-hello-world/module-src/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,107 +1,51 @@
extern crate serde;
extern crate serde_json;

use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::process;

#[macro_use]
extern crate serde_derive;

use serde_json::Error;

use anyhow::{anyhow, Context};
use serde::{Deserialize, Serialize};
use std::{env, fs, process};

fn default_name_arg() -> String {
String::from("World")
}


#[derive(Serialize, Deserialize)]
#[derive(Deserialize)]
struct ModuleArgs {
#[serde(default = "default_name_arg")]
name: String,
}


#[derive(Clone, Serialize, Deserialize)]
#[derive(Clone, Serialize)]
struct Response {
msg: String,
changed: bool,
failed: bool,
}


fn exit_json(response_body: Response) {
return_response(response_body)
msg: String,
changed: bool,
failed: bool,
}


fn fail_json(response_body: Response) {
let failed_response = &mut response_body.clone();
failed_response.failed = true;
return_response(failed_response.clone())
}


fn return_response(resp: Response) {
println!("{}", serde_json::to_string(&resp).unwrap());
process::exit(resp.failed as i32);
}


fn read_file_contents(file_name: &str) -> Result<String, Box<std::io::Error>> {
let mut json_string = String::new();
File::open(file_name)?.read_to_string(&mut json_string)?;
Ok(json_string)
}


fn parse_module_args(json_input: String) -> Result<ModuleArgs, Error> {
Ok(
ModuleArgs::from(
serde_json::from_str(
json_input.as_str()
)?
)
)
}


fn main() {
let args: Vec<String> = env::args().collect();
let program = &args[0];
let input_file_name = match args.len() {
2 => &args[1],
_ => {
eprintln!("module '{}' expects exactly one argument!", program);
fail_json(Response {
msg: "No module arguments file provided".to_owned(),
let (response, code) = match run_module() {
Ok(response) => (response, 0),
Err(err) => (
Response {
msg: err.to_string(),
changed: false,
failed: true,
});
""
}
},
1,
),
};
let json_input = read_file_contents(input_file_name).map_err(|err| {
eprintln!("Could not read file '{}': {}", input_file_name, err);
fail_json(Response {
msg: format!("Could not read input JSON file '{}': {}", input_file_name, err),
changed: false,
failed: true,
})
}).unwrap();
let module_args = parse_module_args(json_input).map_err(|err| {
eprintln!("Error during parsing JSON module arguments: {}", err);
fail_json(Response {
msg: format!("Malformed input JSON module arguments: {}", err),
changed: false,
failed: true,
})
}).unwrap();
exit_json(Response {
msg: format!("Hello, {}!", module_args.name.as_str()),
println!("{}", serde_json::to_string(&response).unwrap());
process::exit(code);
}

fn run_module() -> anyhow::Result<Response> {
let input_filename = env::args().nth(1).ok_or(anyhow!(
"module '{}' expects exactly one argument!",
env::args().next().unwrap()
))?;
let json_input = fs::read_to_string(&input_filename)
.with_context(|| format!("Could not read file '{}'", input_filename))?;
let module_args: ModuleArgs = serde_json::from_str(&json_input)
.with_context(|| format!("Malformed input JSON module arguments"))?;
Ok(Response {
msg: format!("Hello, {}!", module_args.name),
changed: true,
failed: false,
});
})
}