Skip to content

Commit

Permalink
feat: Added the ability to use the TEACH-ME mode (#221)
Browse files Browse the repository at this point in the history
```
./cargo-near --teach-me near new test
```
![Screenshot 2024-10-03 at 19 51
28](https://github.com/user-attachments/assets/09e9dfef-e2a3-4e1e-85d3-3ed16db90a47)

```
./cargo-near --teach-me near build --manifest-path /Users/frovolod/Documents/NEAR/neardevhub-contract-1/Cargo.toml
```
![Screenshot 2024-10-04 at 08 08
49](https://github.com/user-attachments/assets/cf01e7b9-e1b1-4d27-b526-651361c6f11d)

```
./cargo-near --teach-me near deploy --manifest-path /Users/frovolod/Documents/NEAR/neardevhub-contract-1/Cargo.toml
```


https://github.com/user-attachments/assets/9c205faa-4e0f-4b13-a4c8-66e408ed1346

---------

Co-authored-by: FroVolod <[email protected]>
  • Loading branch information
FroVolod and FroVolod authored Nov 14, 2024
1 parent fa934ed commit 175aaeb
Show file tree
Hide file tree
Showing 16 changed files with 312 additions and 154 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ cargo near

Starts interactive mode that will allow to explore all the available commands.

---
Use `--teach-me` flag if you want to know "how it works".

```console
cargo near --teach-me
```

Starts an interactive mode with an explanation of the execution of the selected command.

---
Additionally depends on [Git](https://git-scm.com/) binary being installed, besides [cargo](https://github.com/rust-lang/cargo).

Expand Down
1 change: 1 addition & 0 deletions cargo-near-build/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ tempfile = { version = "3.10.1", optional = true }
shell-words = { version = "1.0.0", optional = true }
wasm-opt = "=0.116.1"
humantime = "2.1.0"
indenter = "0.3"

[target.'cfg(target_os = "linux")'.dependencies]
nix = { version = "0.29.0", features = ["user", "process"], optional = true }
Expand Down
9 changes: 7 additions & 2 deletions cargo-near-build/src/cargo_native/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use cargo_metadata::{Artifact, Message};
use eyre::{ContextCompat, WrapErr};
use std::io::BufRead;

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

Expand Down Expand Up @@ -121,7 +122,6 @@ where

if let Some(path) = working_dir {
let path = crate::fs::force_canonicalize_dir(path.as_ref())?;
tracing::debug!("Setting cargo working dir to '{}'", path);
cmd.current_dir(path);
}

Expand All @@ -134,7 +134,12 @@ where
ColorPreference::Never => cmd.args(["--color", "never"]),
};

tracing::info!("Invoking cargo: {:#?}", cmd);
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Invoking cargo:\n{}",
pretty_print::indent_payload(&format!("{:#?}", cmd))
);

let mut child = cmd
// capture the stdout to return from this function as bytes
Expand Down
33 changes: 26 additions & 7 deletions cargo-near-build/src/cargo_native/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use std::{ffi::OsStr, io::BufRead, path::PathBuf, process::Command};

use eyre::WrapErr;

use crate::pretty_print;

pub const COMPILATION_TARGET: &str = "wasm32-unknown-unknown";

pub fn wasm32_exists() -> bool {
Expand All @@ -11,12 +13,16 @@ pub fn wasm32_exists() -> bool {
Ok(wasm32_target_libdir_path) => {
if wasm32_target_libdir_path.exists() {
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Found {COMPILATION_TARGET} in {:?}",
wasm32_target_libdir_path
);
true
} else {
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Failed to find {COMPILATION_TARGET} in {:?}",
wasm32_target_libdir_path
);
Expand All @@ -38,16 +44,24 @@ pub fn wasm32_exists() -> bool {
}

fn get_rustc_wasm32_unknown_unknown_target_libdir() -> eyre::Result<PathBuf> {
let command = Command::new("rustc")
.args(["--target", COMPILATION_TARGET, "--print", "target-libdir"])
.output()?;
let mut command = Command::new("rustc");
command.args(["--target", COMPILATION_TARGET, "--print", "target-libdir"]);

tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Command execution:\n{}",
pretty_print::indent_payload(&format!("`{:?}`", command).replace("\"", ""))
);

if command.status.success() {
Ok(String::from_utf8(command.stdout)?.trim().into())
let output = command.output()?;

if output.status.success() {
Ok(String::from_utf8(output.stdout)?.trim().into())
} else {
eyre::bail!(
"Getting rustc's wasm32-unknown-unknown target wasn't successful. Got {}",
command.status,
output.status,
)
}
}
Expand All @@ -62,7 +76,12 @@ where
let mut cmd = Command::new(rustup);
cmd.args(args);

tracing::info!("Invoking rustup: {:?}", cmd);
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Invoking rustup:\n{}",
pretty_print::indent_payload(&format!("`{}`", format!("{:?}", cmd).replace("\"", "")))
);

let child = cmd
.stdout(std::process::Stdio::piped())
Expand Down
16 changes: 11 additions & 5 deletions cargo-near-build/src/env_keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ pub(crate) const CARGO_NEAR_ABI_SCHEMA_VERSION: &str = "CARGO_NEAR_ABI_SCHEMA_VE
/// module contains variables, which are set to configure build with WASM reproducibility,
/// which correspond to some fields of `ContractSourceMetadata` in <https://github.com/near/NEPs/blob/master/neps/nep-0330.md>
pub mod nep330 {
use crate::pretty_print;
use std::collections::HashMap;

// ====================== NEP-330 1.2.0 - Build Details Extension ===========
/// NEP-330 1.2.0
Expand All @@ -35,12 +37,16 @@ pub mod nep330 {
}

pub(crate) fn print_env() {
tracing::info!("Variables, relevant for reproducible builds:");
let mut env_map: HashMap<&str, String> = HashMap::new();
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());
tracing::info!("{}={}", key, value);
let value = std::env::var(key).unwrap_or("unset".to_string());
env_map.insert(key, value);
}
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Variables, relevant for reproducible builds:\n{}",
pretty_print::indent_payload(&format!("{:#?}", env_map))
);
}
}
12 changes: 10 additions & 2 deletions cargo-near-build/src/near/abi/generate/dylib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::fs;
use camino::Utf8Path;

use crate::cargo_native::Dylib;
use crate::pretty_print;
use crate::types::near::build::output::CompilationArtifact;

pub fn extract_abi_entries(
Expand All @@ -12,7 +13,9 @@ pub fn extract_abi_entries(
let dylib_path: &Utf8Path = &artifact.path;
let dylib_file_contents = fs::read(dylib_path)?;
let object = symbolic_debuginfo::Object::parse(&dylib_file_contents)?;
tracing::debug!(
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"A dylib was built at {:?} with format {} for architecture {}",
&dylib_path,
&object.file_format(),
Expand All @@ -26,7 +29,12 @@ pub fn extract_abi_entries(
if near_abi_symbols.is_empty() {
eyre::bail!("No NEAR ABI symbols found in the dylib");
}
tracing::debug!("Detected NEAR ABI symbols: {:?}", &near_abi_symbols);
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Detected NEAR ABI symbols:\n{}",
pretty_print::indent_payload(&format!("{:#?}", &near_abi_symbols))
);

let mut entries = vec![];
unsafe {
Expand Down
8 changes: 7 additions & 1 deletion cargo-near-build/src/near/docker_build/subprocess_step.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::{
use nix::unistd::{getgid, getuid};

use crate::env_keys;
use crate::pretty_print;
use crate::types::near::docker_build::subprocess::{container_paths, env_vars};
use crate::types::near::docker_build::{cloned_repo, metadata};

Expand Down Expand Up @@ -83,7 +84,12 @@ pub fn run(
docker_args.extend(vec![&docker_image, "/bin/bash", "-c"]);

docker_args.push(&shell_escaped_cargo_cmd);
tracing::debug!("docker command : {:#?}", docker_args);
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Docker command:\n{}",
pretty_print::indent_payload(&format!("{:#?}", docker_args))
);
docker_args
};

Expand Down
11 changes: 11 additions & 0 deletions cargo-near-build/src/pretty_print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,14 @@ pub fn duration(start: Instant, activity: &str) {
humantime::format_duration(duration)
);
}

pub fn indent_payload(s: &str) -> String {
use std::fmt::Write;

let mut indented_string = String::new();
indenter::indented(&mut indented_string)
.with_str(" | ")
.write_str(s)
.ok();
indented_string
}
20 changes: 17 additions & 3 deletions cargo-near-build/src/types/cargo/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use cargo_metadata::{MetadataCommand, Package};
use colored::Colorize;
use eyre::{ContextCompat, OptionExt, WrapErr};

use crate::pretty_print;
use crate::types::near::build::buildtime_env;

use super::manifest_path::ManifestPath;
Expand Down Expand Up @@ -67,7 +68,11 @@ impl CrateMetadata {
} else {
self.target_directory.clone()
};
tracing::debug!("resolved output directory: {}", result);
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Resolved output directory: {}", result
);
Ok(result)
}

Expand Down Expand Up @@ -136,7 +141,11 @@ fn get_cargo_metadata(
no_locked: bool,
cargo_target_dir: Option<&buildtime_env::CargoTargetDir>,
) -> eyre::Result<(cargo_metadata::Metadata, Package)> {
tracing::info!("Fetching cargo metadata for {}", manifest_path.path);
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Fetching cargo metadata for {}", manifest_path.path
);
let mut cmd = MetadataCommand::new();
if !no_locked {
cmd.other_options(["--locked".to_string()]);
Expand All @@ -146,7 +155,12 @@ fn get_cargo_metadata(
cmd.env(key, value);
}
let cmd = cmd.manifest_path(&manifest_path.path);
tracing::debug!("metadata command: {:#?}", cmd.cargo_command());
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Command execution:\n{}",
pretty_print::indent_payload(&format!("{:#?}", cmd.cargo_command()))
);
let metadata = cmd.exec();
if let Err(cargo_metadata::Error::CargoMetadata { stderr }) = metadata.as_ref() {
if stderr.contains("remove the --locked flag") {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod nep330_build_info;

const RUST_LOG_EXPORT: &str = "RUST_LOG=cargo_near=info";
const RUST_LOG_EXPORT: &str = "RUST_LOG=info";
use nep330_build_info::BuildInfo;

use crate::env_keys;
Expand Down
7 changes: 6 additions & 1 deletion cargo-near/src/commands/build_command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,12 @@ fn get_env_key_vals(input: Vec<String>) -> Vec<(String, String)> {
let dedup_map: HashMap<String, String> = HashMap::from_iter(iterator);

let result = dedup_map.into_iter().collect();
tracing::trace!("passed additional environment pairs: {:#?}", result);
tracing::info!(
target: "near_teach_me",
parent: &tracing::Span::none(),
"Passed additional environment pairs:\n{}",
near_cli_rs::common::indent_payload(&format!("{:#?}", result))
);
result
}

Expand Down
Loading

0 comments on commit 175aaeb

Please sign in to comment.