Skip to content

Commit

Permalink
chore!: remove unsafe std::env::set_var (#228)
Browse files Browse the repository at this point in the history
  • Loading branch information
dj8yfo authored Oct 18, 2024
1 parent 1a10a97 commit 634877a
Show file tree
Hide file tree
Showing 44 changed files with 827 additions and 517 deletions.
7 changes: 6 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,13 @@ jobs:

steps:
- uses: actions/checkout@v4
- name: Install packages (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install --assume-yes libudev-dev
- name: run cargo doc
run: RUSTDOCFLAGS="-D warnings" cargo doc -p cargo-near-build --features build_script
run: |
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --features cargo-near-build/build_script
cargo test --workspace --features cargo-near-build/build_script --doc
audit:
runs-on: ubuntu-latest
Expand Down
52 changes: 27 additions & 25 deletions Cargo.lock

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

18 changes: 12 additions & 6 deletions cargo-near-build/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,15 @@ near-abi = { version = "0.4.0", features = ["__chunked-entries"] }
zstd = "0.13"
schemars = "0.8"
rustc_version = "0.4"
bon = "2.3.0"
url = { version = "2.5.0", features = ["serde"], optional = true }
serde = { version = "1.0.197", optional = true }
git2 = { version = "0.19", optional = true }
home = { version = "0.5.9", optional = true }
pathdiff = { version = "0.2.1", features = ["camino"], optional = true }
unix_path = { version = "1.0.1", optional = true }
tempfile = { version = "3.10.1", optional = true }
shell-words = { version = "1.0.0", optional = true}
shell-words = { version = "1.0.0", optional = true }
wasm-opt = "=0.116.1"
humantime = "2.1.0"

Expand All @@ -47,10 +48,15 @@ dist = false
[features]
default = []
build_script = []
abi_build = []
abi_build = []
docker = [
"dep:url", "dep:serde", "dep:git2",
"dep:home", "dep:pathdiff", "dep:unix_path",
"dep:tempfile", "dep:nix", "dep:shell-words"
"dep:url",
"dep:serde",
"dep:git2",
"dep:home",
"dep:pathdiff",
"dep:unix_path",
"dep:tempfile",
"dep:nix",
"dep:shell-words",
]

16 changes: 8 additions & 8 deletions cargo-near-build/src/cargo_native/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@ use eyre::{ContextCompat, WrapErr};
use std::io::BufRead;

use crate::types::near::build::input::ColorPreference;
use crate::types::{
cargo::manifest_path::ManifestPath,
near::build::{output::version_mismatch::VersionMismatch, output::CompilationArtifact},
};
use crate::types::{cargo::manifest_path::ManifestPath, near::build::output::CompilationArtifact};

use super::ArtifactType;

Expand All @@ -36,10 +33,13 @@ where
let rustflags: &mut String = final_env
.entry(key)
.or_insert_with(|| std::env::var(key).unwrap_or_default());
if !rustflags.is_empty() {
rustflags.push(' ');
// helps avoids situation on complete match `RUSTFLAGS="-C link-arg=-s -C link-arg=-s"`
if !rustflags.contains(value) {
if !rustflags.is_empty() {
rustflags.push(' ');
}
rustflags.push_str(value);
}
rustflags.push_str(value);
}
_ => {
final_env.insert(key, value.to_string());
Expand Down Expand Up @@ -84,7 +84,7 @@ where
path,
fresh: !compile_artifact.fresh,
from_docker: false,
builder_version_mismatch: VersionMismatch::None,
builder_version_info: None,
artifact_type: PhantomData,
}),
_ => eyre::bail!(
Expand Down
11 changes: 5 additions & 6 deletions cargo-near-build/src/env_keys.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
/// this is [`CARGO_TARGET_DIR`](https://doc.rust-lang.org/cargo/reference/environment-variables.html)
pub const CARGO_TARGET_DIR: &str = "CARGO_TARGET_DIR";
/// this variable is set to `"true"` during ABI generation operation
pub const BUILD_RS_ABI_STEP_HINT: &str = "CARGO_NEAR_ABI_GENERATION";

pub(crate) const CARGO_NEAR_ABI_PATH: &str = "CARGO_NEAR_ABI_PATH";

pub(crate) const CARGO_NEAR_VERSION: &str = "CARGO_NEAR_VERSION";
pub(crate) const CARGO_NEAR_ABI_SCHEMA_VERSION: &str = "CARGO_NEAR_ABI_SCHEMA_VERSION";

Expand Down Expand Up @@ -32,12 +36,7 @@ pub mod nep330 {

pub(crate) fn print_env() {
tracing::info!("Variables, relevant for reproducible builds:");
for key in [
BUILD_ENVIRONMENT,
BUILD_COMMAND,
CONTRACT_PATH,
SOURCE_CODE_SNAPSHOT,
] {
for key in [BUILD_ENVIRONMENT, CONTRACT_PATH, SOURCE_CODE_SNAPSHOT] {
let value = std::env::var(key)
.map(|val| format!("'{}'", val))
.unwrap_or("unset".to_string());
Expand Down
70 changes: 42 additions & 28 deletions cargo-near-build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
//!
//! 1. [camino] is re-exported, because it is used in [BuildOpts], and [BuildArtifact] as type of some of fields
//! 2. [near_abi] is re-exported, because details of ABI generated depends on specific version of `near-abi` dependency
//! 3. [bon] is re-exported for the convenience of [bon::vec] helper macro
//!
//! ## Sample usage:
//!
Expand All @@ -28,11 +29,8 @@
//! With some options set:
//!
//! ```no_run
//! let build_opts = cargo_near_build::BuildOpts {
//! features: Some("some_contract_feature_1".into()),
//! ..Default::default()
//! };
//! let artifact = cargo_near_build::build(build_opts).expect("some error during build");
//! let build_opts = cargo_near_build::BuildOpts::builder().features("some_contract_feature_1").build();
//! let artifact = cargo_near_build::build(build_opts).expect("some error during build");
//! ```
pub(crate) mod cargo_native;
/// module contains names of environment variables, exported during
Expand Down Expand Up @@ -67,39 +65,54 @@ pub use build_exports::*;
/// Potential import may look like this:
/// ```ignore
/// [build-dependencies.cargo-near-build]
/// version = "0.1.0"
/// version = "x.y.z"
/// features = ["build_script"]
/// ```
///
/// Usage example:
///
/// ```no_run
/// use cargo_near_build::extended::BuildScriptOpts;
/// let opts = cargo_near_build::extended::BuildOptsExtended {
/// workdir: "../another-contract",
/// env: vec![
/// // unix path of target contract from root of repo
/// (cargo_near_build::env_keys::nep330::CONTRACT_PATH, "another-contract")
/// ],
/// build_opts: cargo_near_build::BuildOpts::default(),
/// build_script_opts: BuildScriptOpts {
/// result_env_key: Some("BUILD_RS_SUB_BUILD_ARTIFACT_1"),
/// rerun_if_changed_list: vec!["../another-contract", "../Cargo.toml", "../Cargo.lock"],
/// build_skipped_when_env_is: vec![
/// // shorter build for `cargo check`
/// ("PROFILE", "debug"),
/// (cargo_near_build::env_keys::BUILD_RS_ABI_STEP_HINT, "true"),
/// ],
/// distinct_target_dir: Some("../target/build-rs-another-contract"),
/// stub_path: Some("../target/stub.bin"),
/// },
/// };
/// cargo_near_build::extended::build(opts).expect("sub-contract build error");
/// use cargo_near_build::{bon, extended};
/// use cargo_near_build::BuildOpts;
/// use std::str::FromStr;
///
/// // directory of target sub-contract's crate
/// let workdir = "../another-contract";
/// // unix path to target sub-contract's crate from root of the repo
/// let nep330_contract_path = "another-contract";
/// let manifest = camino::Utf8PathBuf::from_str(workdir)
/// .expect("pathbuf from str")
/// .join("Cargo.toml");
///
/// let build_opts = BuildOpts::builder()
/// .manifest_path(manifest)
/// .override_nep330_contract_path(nep330_contract_path)
/// // a distinct target is needed to avoid deadlock during build
/// .override_cargo_target_dir("../target/build-rs-another-contract")
/// .build(); // default opts
///
/// let build_script_opts = extended::BuildScriptOpts::builder()
/// .rerun_if_changed_list(bon::vec![workdir, "../Cargo.toml", "../Cargo.lock",])
/// .build_skipped_when_env_is(vec![
/// // shorter build for `cargo check`
/// ("PROFILE", "debug"),
/// (cargo_near_build::env_keys::BUILD_RS_ABI_STEP_HINT, "true"),
/// ])
/// .stub_path("../target/stub.bin")
/// .result_env_key("BUILD_RS_SUB_BUILD_ARTIFACT_1")
/// .build();
///
/// let extended_opts = extended::BuildOptsExtended::builder()
/// .build_opts(build_opts)
/// .build_script_opts(build_script_opts)
/// .build();
///
/// cargo_near_build::extended::build(extended_opts).expect("sub-contract build error");
/// ```
#[cfg(feature = "build_script")]
pub mod extended {
pub use crate::near::build_extended::run as build;
pub use crate::types::near::build_extended::build_script::Opts as BuildScriptOpts;
pub use crate::types::near::build_extended::build_script::{EnvPairs, Opts as BuildScriptOpts};
pub use crate::types::near::build_extended::OptsExtended as BuildOptsExtended;
}

Expand All @@ -109,5 +122,6 @@ pub mod docker {
pub use crate::types::near::docker_build::Opts as DockerBuildOpts;
}

pub use bon;
pub use camino;
pub use near_abi;
7 changes: 4 additions & 3 deletions cargo-near-build/src/near/abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::types::near::abi as abi_types;
pub mod generate;

#[cfg(feature = "abi_build")]
pub fn build(args: abi_types::Opts) -> eyre::Result<()> {
pub fn build(args: abi_types::Opts) -> eyre::Result<camino::Utf8PathBuf> {
// imports #[cfg(feature = "abi_build")]
use crate::{
pretty_print,
Expand All @@ -22,7 +22,8 @@ pub fn build(args: abi_types::Opts) -> eyre::Result<()> {
} else {
"Cargo.toml".into()
};
CrateMetadata::collect(ManifestPath::try_from(manifest_path)?, args.no_locked)
let manifest_path = ManifestPath::try_from(manifest_path)?;
CrateMetadata::collect(manifest_path, args.no_locked, None)
})?;

let out_dir = crate_metadata.resolve_output_dir(args.out_dir.map(Into::into))?;
Expand Down Expand Up @@ -53,7 +54,7 @@ pub fn build(args: abi_types::Opts) -> eyre::Result<()> {
pretty_print::success("ABI Successfully Generated!");
eprintln!(" - ABI: {}", abi_path.to_string().yellow().bold());

Ok(())
Ok(abi_path)
}

pub fn write_to_file(
Expand Down
32 changes: 0 additions & 32 deletions cargo-near-build/src/near/build/export.rs

This file was deleted.

Loading

0 comments on commit 634877a

Please sign in to comment.