How to use a float as an env var in cargo/rust? - rust

Like the title suggests, how can I create an env variable in cargo that is of type float?
I have a created .cargo/config.toml file and would like to add all the game related env variables like so:
[env]
test = "testtingggg"
yo = "yoyoyoyoyoyo"
game_zero_level = "hello"
game_zero_multiplier = 0.1
# game_one_level = 1
# game_one_multiplier = 1.0
# game_two_level = 2
# game_two_multiplier = 2.5
# game_three_level = 3
# game_three_multiplier = 5.0
# game_four_level = 3
#[derive(Serialize, Deserialize, Debug)]
pub struct Config {
pub level_zero: LevelZero,
pub level_one: LevelOne,
pub level_two: LevelTwo,
pub level_three: LevelThree,
pub level_four: LevelFour,
}
impl Config {
pub fn new() -> Self {
// Get env variables
let temp = option_env!("game_zero_level").unwrap();
msg!("simple env read for first game...");
msg!("{}", temp);
// load them into struct
// template for now
Config {
level_zero: LevelZero { level: 0, multiplier: 1.0 },
level_one: LevelOne { level: 1, multiplier: 1.0 },
level_two: LevelTwo { level: 2, multiplier: 1.0 },
level_three: LevelThree { level: 3, multiplier: 1.0 },
level_four: LevelFour { level: 4, multiplier: 1.0 },
}
}
}
Code
However, I got an error:
2022-12-24T18:22:59.802122509Z ERROR cargo_build_sbf] Failed to obtain packag
e metadata: `cargo metadata` exited with an error: error: could not load Cargo
configuration
Caused by:
failed to load TOML configuration from `/home/tai/Code/solana/techniques
/env-vars3/programs/env-vars3/.cargo/config.toml`
Caused by:
failed to parse key `env`
Caused by:
failed to parse key `game_zero_multiplier`
Caused by:
found TOML configuration value of unknown type `float`
error
Any suggestions would be soo appreciated! Thanks

Related

Can't build RustDesk - Android

I tried to build RustDesk project following documentation at documentation - android build
After executing:
VCPKG_ROOT=/opt/vcpkg ANDROID_NDK_HOME=/opt/android-ndk-r22b flutter/ndk_arm64.sh
I cp-ed vcpkg and android-ndk-r22b from home to /opt to make sure that path is right
I'm getting this one error message:
[2023-01-13T09:59:47Z INFO cargo_ndk::cli] Using NDK at path: /opt/android-ndk-r22b (ANDROID_NDK_HOME)
[2023-01-13T09:59:47Z INFO cargo_ndk::cli] NDK API level: 21
[2023-01-13T09:59:47Z INFO cargo_ndk::cli] Building targets: arm64-v8a
[2023-01-13T09:59:47Z INFO cargo_ndk::cli] Building arm64-v8a (aarch64-linux-android)
warning: function `patch` is never used
--> libs/hbb_common/src/config.rs:239:4
|
239 | fn patch(path: PathBuf) -> PathBuf {
| ^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `hbb_common` (lib) generated 1 warning
Compiling rustdesk v1.2.0 (/home/mwitek/rustdesk)
error: failed to run custom build command for `rustdesk v1.2.0 (/home/mwitek/rustdesk)`
Caused by:
process didn't exit successfully: `/home/mwitek/rustdesk/target/release/build/rustdesk-9caa4dac4ffa2754/build-script-build` (exit status: 101)
--- stdout
cargo:rustc-link-search=/opt/vcpkg/installed/arm64-android/lib
cargo:rustc-link-lib=oboe
cargo:rustc-link-lib=c++
cargo:rustc-link-lib=OpenSLES
cargo:rerun-if-changed=src/flutter_ffi.rs
--- stderr
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Failed to run build_runner for /home/mwitek/rustdesk/flutter: ', build.rs:108:56
stack backtrace:
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
And to be honest I don't know how to get rid of it, I already tried to understand what is wrong from code-side but I can only find this section in build.rs:
fn install_oboe() {
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
if target_os != "android" {
return;
}
let mut target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
if target_arch == "x86_64" {
target_arch = "x64".to_owned();
} else if target_arch == "aarch64" {
target_arch = "arm64".to_owned();
} else {
target_arch = "arm".to_owned();
}
let target = format!("{}-android", target_arch);
let vcpkg_root = std::env::var("VCPKG_ROOT").unwrap();
let mut path: std::path::PathBuf = vcpkg_root.into();
path.push("installed");
path.push(target);
println!(
"{}",
format!(
"cargo:rustc-link-search={}",
path.join("lib").to_str().unwrap()
)
);
println!("cargo:rustc-link-lib=oboe");
println!("cargo:rustc-link-lib=c++");
println!("cargo:rustc-link-lib=OpenSLES");
// I always got some strange link error with oboe, so as workaround, put oboe.cc into oboe src: src/common/AudioStreamBuilder.cpp
// also to avoid libc++_shared not found issue, cp ndk's libc++_shared.so to jniLibs, e.g.
// ./flutter_hbb/android/app/src/main/jniLibs/arm64-v8a/libc++_shared.so
// let include = path.join("include");
//cc::Build::new().file("oboe.cc").include(include).compile("oboe_wrapper");
}
But it doesn't look like anything for me
Also here is function that's generating exception:
fn gen_flutter_rust_bridge() {
let llvm_path = match std::env::var("LLVM_HOME") {
Ok(path) => Some(vec![path]),
Err(_) => None,
};
// Tell Cargo that if the given file changes, to rerun this build script.
println!("cargo:rerun-if-changed=src/flutter_ffi.rs");
// settings for fbr_codegen
let opts = lib_flutter_rust_bridge_codegen::Opts {
// Path of input Rust code
rust_input: "src/flutter_ffi.rs".to_string(),
// Path of output generated Dart code
dart_output: "flutter/lib/generated_bridge.dart".to_string(),
// Path of output generated C header
c_output: Some(vec!["flutter/macos/Runner/bridge_generated.h".to_string()]),
// for other options lets use default
llvm_path,
..Default::default()
};
// run fbr_codegen
lib_flutter_rust_bridge_codegen::frb_codegen(opts).unwrap();
}
Where it's last line is the one that throws this error.
lib_flutter_rust_bridge_codegen::frb_codegen(opts).unwrap();
I know this question really specific but documentation and self-investigation does not helping.
Also my OS properties: Ubuntu 20.04 x64 [Freshly installed]

Jaxb generating Java from multiple .xsd Files failed

i'm having this error and have no idea how it comes to this: it worked the last time I checked and I haven´t made any single change
Build file 'D:\getVersionSoap\build.gradle' line: 134
Execution failed for task ':genJaxb'.
unable to parse the schema. Error messages should have been provided
Here is the piece of code:
"Line 134" is the line "xjc(destdir: sourcesDir)"
task genJaxb {
ext.sourcesDir = "${buildDir}/generated_sources/jaxb"
ext.classesDir = "${buildDir}/classes/jaxb"
ext.schemaDir = "${projectDir}/src/main/resources"
outputs.dir sourcesDir
doLast() {
project.ant {
taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask",
classpath: configurations.jaxb.asPath
mkdir(dir: sourcesDir)
mkdir(dir: classesDir)
xjc(destdir: sourcesDir) {
schema(dir: schemaDir, includes: "**/ /* *.xsd")
arg(value: "-wsdl")
produces(dir: sourcesDir, includes: "**/ /* *.java")
}
javac(destdir: classesDir, source: 1.8, target: 1.8, debug: true,
debugLevel: "lines,vars,source",
classpath: configurations.jaxb.asPath,
includeantruntime: "false") {
src(path: sourcesDir)
include(name: "**/ /* *.java")
include(name: "*.java")
}
copy(todir: classesDir) {
fileset(dir: sourcesDir, erroronmissingdir: false) {
exclude(name: "**/ /* *.java")
}
}
}
}
}
Any idea? Thank you!

Load yaml config with array type

I am writing a code where I am trying to load config.yaml file
impl ::std::default::Default for MyConfig {
fn default() -> Self { Self { foo: "".into(), conf: vec![] } }
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MyConfig {
foo: String,
conf: Vec<String>
}
let cfg: MyConfig = confy::load("config")?;
println!("{:#?}", cfg);
Config.yaml file
foo: "test"
conf:
gg
gb
gg
bb
Output
MyConfig {
url: "",
jobs: [],
}
I have kept the config.yaml file in the same folder where it is getting called. It looks like it is not able to load the file itself. What is getting missed there?
EDIT: When I changed the extension from yaml to toml, and provided full path, it found the file but the structure is expecting is
config.toml
foo = "test"
conf = ["gg","gb","gv","gx"]
full path
confy::load("c:/test/config")?;
Tried multiple places to keep it but not getting it, looks like it requires full path.
But I got the output
MyConfig {
url: "test",
jobs: [
"gg",
"gb",
"gv",
"gx",
],
}
While David Chopin's answer is correct that the YAML is not right, there is a couple of deeper issues.
Firstly, while it is not really documented, looking at the confy source, it expects TOML formatted data, not YAML - for simple cases they can be similar I think. (Turns out this is not 100% correct - the github page says you can switch to YAML this using features = ["yaml_conf"] in the Cargo.toml file)
Secondly, I'm guessing the root problem is that confy is not finding your configuration file.
The docs for confy::load state:
Load an application configuration from disk
A new configuration file is created with default values if none exists.
So, I think it's looking somewhere else, not finding your file and instead of erroring creating a nice default file in that location then returning that default for you.
I believe it should be formatted as follows:
foo: "test"
conf:
- gg
- gb
- gg
- bb

Is there a way to make clap override the [ -h | --help ] flags help text?

I'm following the sample code from Rust Clap Package's docs but can't find any reference regarding help text for auto-generated flags [-h and --help].
extern crate clap;
use clap::{App, Arg, SubCommand};
fn main() {
let matches = App::new("Command One")
.version("1.0")
.author("Some Author <the_account#provider.com>")
.about("Descripción del comando.")
.arg(Arg::with_name("config")
.short("c")
.long("config")
.value_name("FILE")
.help("Sets a custom config file")
.takes_value(true))
.arg(Arg::with_name("INPUT")
.help("Sets the input file to use")
.required(true)
.index(1))
.arg(Arg::with_name("v")
.short("v")
.multiple(true)
.help("Sets the level of verbosity"))
// *** I'm trying this ***
.arg(Arg::with_name("help")
.short("h")
.long("help")
.help("A new help text."))
// ***********
.subcommand(SubCommand::with_name("test")
.about("controls testing features")
.version("1.3")
.author("Someone E. <someone_else#other.com>")
.arg(Arg::with_name("debug")
.short("d")
.help("print debug information verbosely")))
.get_matches();
let config = matches.value_of("config").unwrap_or("default.conf");
println!("Value for config: {}", config);
println!("Using input file: {}", matches.value_of("INPUT").unwrap());
match matches.occurrences_of("v") {
0 => println!("No verbose info"),
1 => println!("Some verbose info"),
2 => println!("Tons of verbose info"),
3 | _ => println!("Don't be crazy"),
}
if let Some(matches) = matches.subcommand_matches("test") {
if matches.is_present("debug") {
println!("Printing debug info...");
} else {
println!("Printing normally...");
}
}
}
To change the description of the -h/--help parameter in the help text, use the help_message method. Likewise, to change the description of -V/--version, use version_message.
extern crate clap;
use clap::App;
fn main() {
let matches = App::new("app")
.help_message("this is the help command")
.version_message("this is the version command")
.get_matches_from(&["app", "--help"]);
}
Output:
app
USAGE:
app
FLAGS:
-h, --help this is the help command
-V, --version this is the version command

Not able to parse JsonPath in restassured

Using Restassured 3.0.1
I have a Json ::
json = {
"prices": {
"Test": {
"PriceMap": {
"30": "295"
}
}
}
}
JsonPath jsonPath = new JsonPath(json);
jsonPath.get("prices.Test.PriceMap.*")
getting error :
Caused by: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: unexpected token: * # line 1, column 48.
otObject.prices.Test.PriceMap.*
You can use the getMap call to get the object as a map -- jsonPath.getMap("prices.Test.PriceMap")
System.out.println(jsonPath.getMap("prices.Test.PriceMap").keySet());
//Output : [30]
System.out.println(jsonPath.getMap("prices.Test.PriceMap").values());
//[295]
System.out.println(jsonPath.getMap("prices.Test.PriceMap").get("30"));
//295

Resources