I'm attempting to start my first project in Rust using VScode. I added the '''image = "0.24.5"''' to the dependencies section of the Cargo.toml file, built the project with cargo build. However, whenever I try and run the file I get an error that says:
error[E0433]: failed to resolve: maybe a missing crate `image`?
--> main.rs:1:5
|
1 | use image::io::Reader;
| ^^^^^ maybe a missing crate `image`?
|
= help: consider adding `extern crate image` to use the `image` crate
This is the main file:
use image::io::Reader;
fn main() {
println!("Hello, world!");
}
Cargo.toml
[package]
name = "imaging"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
image = "0.24.5"
Not quite sure why I'm getting this error. My guess is that it may be that VScode is unable to find the dependency.
Related
I'm trying to build a hello_world cc_grpc_library using bazel 6.0.0 on Ubuntu 22.04, but I'm unable to do so.
Source tree:
WORKSPACE
MODULE.bazel
BUILD
helloworld.proto
.bazelrc
.bazelversion
My WORKSPACE file is empty. WORKSPACE.bzlmod does not exist.
MODULE.bazel contains:
module(name = "helloworld", version = "1.0")
bazel_dep(name = "grpc", version = "1.47.0", repo_name = "com_github_grpc_grpc")
BUILD contains:
load("#rules_proto//proto:defs.bzl", "proto_library")
load("#com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
load("#com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps")
load("#com_github_grpc_grpc//bazel:cc_grpc_library.bzl", "cc_grpc_library")
grpc_deps()
grpc_extra_deps()
proto_library(
name = "helloworld_proto",
srcs = ["helloworld.proto"],
)
cc_proto_library(
name = "helloworld_cc_proto",
deps = [":helloworld_proto"],
)
cc_grpc_library(
name = "helloworld_cc_grpc",
srcs = [":helloworld_proto"],
grpc_only = True,
deps = [":helloworld_cc_proto"],
)
helloworld.proto is a copy of gRPC's helloworld.proto
When I type bazel build :helloworld_cc_grpc I get the following error and don't know how to solve it:
...external/grpc~1.47.0/bazel/grpc_deps.bzl", line 23, column 11, in grpc_bind_deps
native.bind(
Error: no native function or rule 'bind'
Available attributes: aar_import, action_listener, alias, android_binary, android_device, android_device_script_fixture, android_host_service_fixture, android_instrumentation_test, android_library, android_local_test, android_sdk, android_tools_defaults_jar, apple_cc_toolchain, available_xcodes, cc_binary, cc_host_toolchain_alias, cc_import, cc_libc_top_alias, cc_library, cc_proto_library, cc_shared_library, cc_shared_library_permissions, cc_test, cc_toolchain, cc_toolchain_alias, cc_toolchain_suite, config_feature_flag, config_setting, constraint_setting, constraint_value, environment, existing_rule, existing_rules, exports_files, extra_action, fdo_prefetch_hints, fdo_profile, filegroup, genquery, genrule, glob, j2objc_library, java_binary, java_import, java_library, java_lite_proto_library, java_package_configuration, java_plugin, java_plugins_flag_alias, java_proto_library, java_runtime, java_test, java_toolchain, label_flag, label_setting, objc_import, objc_library, package, package_group, package_name, platform, propeller_optimize, proto_lang_toolchain, proto_library, py_binary, py_library, py_runtime, py_test, repository_name, sh_binary, sh_library, sh_test, subpackages, test_suite, toolchain, toolchain_type, xcode_config, xcode_config_alias, xcode_version
bazel version output:
Bazelisk version: v1.15.0
Build label: 6.0.0
Build target: bazel-out/k8-opt/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Mon Dec 19 15:52:35 2022 (1671465155)
Build timestamp: 1671465155
Build timestamp as int: 1671465155
I've also found this gRPC github issue but I'm not sure what to do with it.
How to build gRPC's hello world example using bzlmod to manage external dependencies?
I've tried building it with bazel's cc_grpc_library but that wraps actual dependency (gRPC) into yet another layer as it is visible from the comment on the provided link. Either way it wasn't building but I don't recall actual error.
gRPC doesn't yet support Bazel module so it can break but in your case, it looks weird to call grpc_deps() and grpc_extra_deps() functions in BUILD file because those are expected to be called in WORKSPACE file. If it turns out that module doesn't work yet, you may want to use it without module. Please take a look at this example.
On using serde_json in my pallet dependency it throws this throws these error:-
``
#[weight=10_000]
pub fn insert_data_class(origin,app_id:Vec<u8>,db_id:Vec<u8>,cid:Vec<u8>,data:Vec<u8>,signature:H512)->DispatchResult{
let caller = ensure_signed(origin)?;
let app_data = alioth_register::Module::<T>::check_ownership(&caller,&app_id);
ensure!(app_data.0,Error::<T>::AppNotFound);
let data_str = String::from_utf8(data.clone()).unwrap();
let data_json = json!(data_str);
let uid:Vec<u8> = data_json["uid"].to_string().as_bytes().to_vec();
//let uuid_str = data_json["uuid"].to_string();
let uuid:Vec<u8> = data_json["uuid"].to_string().as_bytes().to_vec();
let data1 = data.clone();
let data1 = String::from_utf8(data1).unwrap();
let user_data = alioth_users::Module::<T>::check_user_extern(&uuid,&app_id);
ensure!(user_data.0,Error::<T>::UserNotFound);
let class_data = alioth_class::Module::<T>::check_class(&db_id,&cid);
ensure!(class_data.0,Error::<T>::ClassOrDatabaseNotFound);
//I needed a public key for this purpose we are going to write a function in alioth-users
let pub_key_ref:(bool,H256) = alioth_users::Module::<T>::get_public_key(&uuid,&app_id);
ensure!(pub_key_ref.0,Error::<T>::ObjectNotCreated);
//now we are going to verify the signature for the further transaction
ensure!(sp_io::crypto::sr25519_verify(&Signature::from_h512(signature),data1.as_bytes(),&Public::from_h256(pub_key_ref.1)),Error::<T>::SignatureNotVerified);
//its over now we are going ahead to check the uniqness of data and insert it later.
let data_from_self = Self::check_obj_store(&uid,&cid);
ensure!(!data_from_self.0,Error::<T>::DataIsNotUnique);
let struct_data = ObjectData{
duid:uid,
object:data,
};
if data_from_self.1==0{
let vec_data = vec![struct_data];
<ObjectStore>::insert(cid,vec_data);
Self::deposit_event(Event::ObjectCreated());
}
else{
let mut vec_data = <ObjectStore>::get(&cid);
vec_data.insert(vec_data.len(),struct_data);
<ObjectStore>::insert(cid,vec_data);
Self::deposit_event(Event::ObjectCreated());
}
Ok(())
}**this code uses serde_json::json macro**
error: failed to run custom build command for node-template-runtime v3.0.0 (/home/corteri/Desktop/blockchain/new_tmp/substrate-node-template/runtime)
Caused by:
process didn't exit successfully: /home/corteri/Desktop/blockchain/new_tmp/substrate-node-template/target/debug/build/node-template-runtime-e56bc02a2834241f/build-script-build (exit status: 1)
--- stdout
Information that should be included in a bug report.
Executing build command: "rustup" "run" "nightly" "cargo" "-Zfeatures=build_dep" "rustc" "--target=wasm32-unknown-unknown" "--manifest-path=/home/corteri/Desktop/blockchain/new_tmp/substrate-node-template/target/debug/wbuild/node-template-runtime/Cargo.toml" "--color=always" "--release"
Using rustc version: rustc 1.56.0-nightly (b7404c898 2021-09-03)
--- stderr
warning: flag -Z features has been stabilized in the 1.51 release, and is no longer necessary
The new feature resolver is now available by specifying resolver = "2" in Cargo.toml.
See https://doc.rust-lang.org/nightly/cargo/reference/features.html#feature-resolver-version-2 for more information.
Compiling getrandom v0.2.1
error: target is not supported, for more information see: https://docs.rs/getrandom/#unsupported-targets
--> /home/corteri/.cargo/registry/src/github.com-1ecc6299db9ec823/getrandom-0.2.1/src/lib.rs:214:9
|
214 | / compile_error!("target is not supported, for more information see:
215 | | https://docs.rs/getrandom/#unsupported-targets");
| |_________________________________________________________________________^
error[E0433]: failed to resolve: use of undeclared crate or module imp
--> /home/corteri/.cargo/registry/src/github.com-1ecc6299db9ec823/getrandom-0.2.1/src/lib.rs:236:5
|
236 | imp::getrandom_inner(dest)
| ^^^ use of undeclared crate or module imp
For more information about this error, try rustc --explain E0433.
error: could not compile getrandom due to 2 previous errors
getrandom/js feature needs to be activated in your Cargo.toml:
# We enable it only for web-wasm check
# See https://docs.rs/getrandom/0.2.1/getrandom/#webassembly-support
getrandom = { version = "0.2", features = ["js"] }
(I don't think this is a serde_json specific error btw)
Building Yew App on Windows
I'm building a yew app alongside a rocket backend on Windows following
this tutorial
(although the tutorial is for a Linux environment). I'm trying to build the yew app
using wasm-pack. I'm not using the Linux subsystem to build the app, though
I do have it installed.
Code / Configuration
The repository.
I have already installed the wasm toolchain and cargo make:
rustup target add wasm32-unknown-unknown
The following is my toolchain list:
stable-x86_64-pc-windows-gnu
stable-x86_64-pc-windows-msvc
nightly-x86_64-pc-windows-msvc (default)
1.30.0-x86_64-pc-windows-msvc
Here is my folder structure:
Project root
├───backend <-- rocket backend
| ├───Cargo.toml
│ └───src
│ ├───bin
│ └───db
├───frontend <-- yew frontend
│ ├───pkg
│ ├───src
| ├───Cargo.toml
| └───Makefile.toml
├───src
├───Cargo.toml
└───Makefile.toml
This is rootdir\Cargo.toml:
[package]
name = "sentinel"
version = "0.1.0"
authors = ["zachdelano <email>"]
edition = "2018"
[workspace]
members = ["backend", "frontend"]
This is rootdir\Makefile.toml:
[env]
CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = "true"
[tasks.default]
clear = true
dependencies = ["build"]
This is rootdir\frontend\Cargo.toml:
[dependencies]
sentinel = { path = ".." }
yew = "0.17.3"
wasm-pack = "0.9.1"
wasm-bindgen = "0.2.68"
web-sys = "0.3.45"
[lib]
crate-type = ["cdylib", "rlib"]
This is rootdir\frontend\Makefile.toml:
[tasks.default]
dependencies = ["create_wasm"]
[tasks.create_wasm]
command = "wasm-pack"
args = ["build", "--target", "web", "--out-name", "package", "--dev"]
dependencies = ["build"]
Expected result
I expect the app to finish building with no errors when I run
cargo make. The Yew tutorial
seems to indicate nothing else is needed.
Actual output
I get a host of errors when running cargo make (from the root directory) like the following:
error[E0433]: failed to resolve: could not find `unix` in `os`
--> C:\Users\Zach\.cargo\registry\src\github.com-1ecc6299db9ec823\dirs-1.0.5\src\lin.rs:41:18
|
41 | use std::os::unix::ffi::OsStringExt;
| ^^^^ could not find `unix` in `os`
See the entire list of errors.
Is this a toolchain sort of thing? How can I fix this?
Running rustup update
I get the following output
from running rustup update.
Now when I run cargo make from the root directory, I get different errors:
error[E0432]: unresolved import `crate::sys`
--> C:\Users\Zach\.cargo\registry\src\github.com-1ecc6299db9ec823\socket2-0.3.15\src\socket.rs:23:5
|
23 | use crate::sys;
| ^^^^^^^^^^ no `sys` in the root
See the full list of errors.
Some of the code changed in the repository.
The issue ended up being that I was trying to install wasm-pack and web-sys. I don't know why that was an issue but when I commented them out and ran cargo make, everything built just fine. I also deleted target and reran cargo make just to make sure.
[package]
name = "frontend"
version = "0.1.0"
authors = ["zachdelano <email>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
sentinel = { path = ".." }
yew = "0.17.3"
wasm-bindgen = "0.2.68"
# wasm-pack = "0.9.1"
# web-sys = "0.3.45"
[lib]
crate-type = ["cdylib", "rlib"]
I'm trying to build the hasura cli: https://github.com/hasura/graphql-engine/tree/master/cli with the following code (deps derived from dep2nix):
{ buildGoPackage, fetchFromGitHub }:
buildGoPackage rec {
version = "1.0.0-beta.2";
name = "hasura-${version}";
goPackagePath = "github.com/hasura/graphql-engine";
subPackages = [ "cli" ];
src = fetchFromGitHub {
owner = "hasura";
repo = "graphql-engine";
rev = "v${version}";
sha256 = "1b40s41idkp1nyb9ygxgsvrwv8rsll6dnwrifpn25bvnfk8idafr";
};
goDeps = ./deps.nix;
}
but I get the following errors after the post-installation fixup step:
find: '/nix/store/gkck68cm2z9k1qxgmh350pq3kwsbyn8q-hasura-cli-1.0.0-beta.2': No such file or directory.
What am I doing wrong here? For reference, I'm on macOS and using home-manager.
For anyone still wondering:
There are a couple of things to consider:
dep has been deprecated in favor of go modules
This is also reflected in Nix, as buildGoPackage is now legacy and moved to buildGoModule
There is already a hasura-cli package in nixpkgs. You can just use it with nix-shell -p hasura-cli
I want to conditionally enable run-time checks and logging, independently from each other and from debug and release mode. So I've started adding two features to my project, one called "invariant-checking" and one called "logging". Ultimately i want their use to be through macros I define in a crate which is visible project-wide.
I had assumed that if I filled out the features section the same way in all of the crates the same way then when I activated the feature while compiling the bin crate, then all the lib crates would also have the feature enabled, but this is not the case! How can I enable and disable features across multiple crates? Hopefully this can be done by only changing one thing like the command-line arguments to cargo.
To clarify exactly what I want, here's an example, which I will also reproduce below:
There are three crates, the main, bin, crate, and two lib crates, called "middle" and "common". Here are the relevant parts of the relevant files:
main.rs
extern crate common;
extern crate middle;
fn main() {
common::check!();
middle::run();
println!("done");
}
the main Cargo.toml
[dependencies]
[dependencies.common]
path = "libs/common"
[dependencies.middle]
path = "libs/middle"
[features]
default = []
invariant-checking = []
logging = []
middle's lib.rs
extern crate common;
pub fn run() {
common::check!();
common::run();
}
middle's Cargo.toml
[dependencies]
[dependencies.common]
path = "../common"
[features]
default = []
invariant-checking = []
logging = []
common's lib.rs
#[macro_export]
macro_rules! check {
() => {{
if cfg!(feature = "invariant-checking") {
println!("invariant-checking {}:{}", file!(), line!());
}
if cfg!(feature = "logging") {
println!("logging {}:{}", file!(), line!());
}
}};
}
pub fn run() {
check!()
}
and finally common's Cargo.toml
[dependencies]
[features]
default = []
invariant-checking = []
logging = []
When i run cargo run --features "invariant-checking,logging" I get the following output
invariant-checking src\main.rs:5
logging src\main.rs:5
done
but want it to log in middle and common as well. How can I transform this project such that it will do that, and still allow me to get only "done" as output by changing only one place?
How can I enable and disable features across multiple crates?
A Cargo.toml can add features that transitively enable other features which are allowed to belong to dependencies.
For example, in the Cargo.toml of a crate which depends on crates foo and bar:
[dependencies]
foo = "0.1"
bar = "0.1"
[features]
default = []
invariant-checking = [ "foo/invariant-checking", "bar/invariant-checking" ]
logging = [ "foo/logging", "bar/logging" ]
This crate adds the invariant-checking and logging features. Enabling them transitively enables the respective features of the crates foo and bar, so that
cargo build --features=logging,invariant-checking
will enable the logging and invariant-checking features in this crate and also in its dependencies foo and bar as well.
In your particular case, you probably want main to transitively enable the features of middle and common, and for middle to transitively enable the features of common.
The macro definitions in their current form have a problem: The code inside the macro gets inlined whenever the macro is used, and then compiled in the context where it got inlined. Since you use runtime feature checks like
if cfg!(feature = "invariant-checking")
this means that you need to define the features in every crate where you are using the macro. In the common crate itself, on the other hand, the feature is never queried and thus redundant.
This seems completely backwards to me. The feature flag should be only queried in the common crate, and using the macro should not require first defining a feature flag in the crate that uses it. For this reason, I suggest using compile-time checks to select what macro to define:
#[cfg(feature = "invariant-checking")]
macro_rules! check_invariant {
() => ( println!("invariant-checking {}:{}", file!(), line!()); )
}
#[cfg(not(feature = "invariant-checking"))]
macro_rules! check_invariant {
() => ()
}
#[cfg(feature = "logging")]
macro_rules! logging {
() => ( println!("logging {}:{}", file!(), line!()); )
}
#[cfg(not(feature = "logging"))]
macro_rules! logging {
() => ()
}
#[macro_export]
macro_rules! check {
() => ( check_invariant!(); logging!(); )
}
This way, you will only need to define the feature in the common crate, as it should be. As long as you only use a single version of that crate, switching the flag on and off has global effect.