Skip to content

Commit

Permalink
refactor: get client version from crate and git
Browse files Browse the repository at this point in the history
  • Loading branch information
Eason committed Aug 7, 2023
1 parent 8f3eded commit 15d8b4d
Show file tree
Hide file tree
Showing 14 changed files with 123 additions and 49 deletions.
38 changes: 23 additions & 15 deletions Cargo.lock

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

12 changes: 11 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ version = "0.1.0-beta.5"
authors = ["Nervos Dev <dev@nervos.org>"]
edition = "2021"
repository = "https://github.com/axonweb3/axon"
build = "build.rs"

[dependencies]
clap = { version = "4.2", features = ["cargo"] }
clap = { version = "4.3", features = ["cargo"] }

# byzantine = { path = "./byzantine" }
common-version = { path = "./common/version" }
core-api = { path = "./core/api" }
core-cli = { path = "./core/cli" }
core-consensus = { path = "./core/consensus" }
Expand All @@ -28,6 +30,7 @@ members = [
"common/memory-tracker",
"common/merkle",
"common/pubsub",
"common/version",
"core/api",
"core/cli",
"core/consensus",
Expand Down Expand Up @@ -61,6 +64,13 @@ debug = true
overflow-checks = true
opt-level = 3

[lib]
path = "src/lib.rs"

[[bin]]
name = "axon"
path = "src/main.rs"

[[example]]
name = "custom_chain"
crate-type = ["bin"]
19 changes: 12 additions & 7 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
fn main() {
let desc = std::process::Command::new("git")
.args(["describe", "--always", "--dirty", "--exclude", "*"])
let commit_id = std::process::Command::new("git")
.args([
"describe",
"--always",
"--match",
"__EXCLUDE__",
"--abbrev=7",
])
.output()
.ok()
.and_then(|r| String::from_utf8(r.stdout).ok())
.map(|d| format!(" {d}"))
.unwrap_or_default();
println!("cargo:rustc-env=AXON_GIT_DESCRIPTION={desc}");
.map(|r| String::from_utf8(r.stdout).unwrap())
.unwrap();

println!("cargo:rustc-env=AXON_COMMIT_ID={}", commit_id);
}
2 changes: 0 additions & 2 deletions common/config-parser/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,6 @@ pub struct ConfigApi {
pub maxconn: u32,
pub max_payload_size: u32,
pub enable_dump_profile: Option<bool>,
#[serde(default)]
pub client_version: String,
}

#[derive(Clone, Debug, Deserialize)]
Expand Down
9 changes: 9 additions & 0 deletions common/version/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "common-version"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
semver = "1.0"
42 changes: 42 additions & 0 deletions common/version/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use std::fmt::{Display, Formatter};
use std::str::FromStr;

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version {
inner: semver::Version,
}

impl FromStr for Version {
type Err = semver::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
semver::Version::from_str(s).map(|inner| Version { inner })
}
}

impl Display for Version {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.inner)
}
}

impl Version {
pub fn new(ver: &str) -> Self {
Version::from_str(ver).unwrap_or_else(|e| panic!("Parse version error {:?}", e))
}

pub fn new_with_commit_id(ver: &str, commit_id: &str) -> Self {
Version::new(ver).set_commit_id(commit_id)
}

pub fn commit_id(&self) -> String {
self.inner.build.to_ascii_lowercase()
}

fn set_commit_id(mut self, commit_id: &str) -> Self {
self.inner.build = semver::BuildMetadata::new(commit_id)
.unwrap_or_else(|e| panic!("Parse commit id error {:?}", e));

self
}
}
6 changes: 3 additions & 3 deletions core/api/src/jsonrpc/impl/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ pub struct NodeRpcImpl {
}

impl NodeRpcImpl {
pub fn new(version: &str, path: PathBuf) -> Self {
pub fn new(ver: String, path: PathBuf) -> Self {
NodeRpcImpl {
version: version.to_string(),
pprof: Arc::new(AtomicBool::default()),
version: ver,
pprof: Arc::new(AtomicBool::new(false)),
_path: path.join("api"),
}
}
Expand Down
4 changes: 2 additions & 2 deletions core/api/src/jsonrpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ pub trait CkbLightClientRpc {
}

pub async fn run_jsonrpc_server<Adapter: APIAdapter + 'static>(
version: String,
config: Config,
adapter: Arc<Adapter>,
) -> ProtocolResult<(Option<ServerHandle>, Option<ServerHandle>)> {
Expand All @@ -253,8 +254,7 @@ pub async fn run_jsonrpc_server<Adapter: APIAdapter + 'static>(
)
.into_rpc();

let node_rpc =
r#impl::NodeRpcImpl::new(&config.rpc.client_version, config.data_path).into_rpc();
let node_rpc = r#impl::NodeRpcImpl::new(version, config.data_path).into_rpc();
let axon_rpc = r#impl::AxonRpcImpl::new(Arc::clone(&adapter)).into_rpc();
let filter =
r#impl::filter_module(Arc::clone(&adapter), config.web3.log_filter_max_block_range)
Expand Down
3 changes: 2 additions & 1 deletion core/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = "4.2"
clap = { version = "4.3", features = ["cargo", "string"] }
semver = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Expand All @@ -14,5 +14,6 @@ thiserror = "1.0"

common-config-parser = { path = "../../common/config-parser" }
common-logger = { path = "../../common/logger" }
common-version = { path = "../../common/version" }
core-run = { path = "../../core/run" }
protocol = { path = "../../protocol", package = "axon-protocol" }
12 changes: 6 additions & 6 deletions core/cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ use std::path::Path;

use clap::{Arg, ArgMatches, Command};
use protocol::ProtocolError;
use semver::Version;
use thiserror::Error;

use common_config_parser::{parse_file, types::Config, ParseError};
use common_version::Version;
use core_run::{Axon, KeyProvider, SecioKeyPair};
use protocol::types::RichBlock;

Expand Down Expand Up @@ -52,9 +52,9 @@ pub struct AxonCli {
}

impl AxonCli {
pub fn init(axon_version: Version, cli_version: &'static str) -> Self {
pub fn init(axon_version: Version) -> Self {
let matches = Command::new("axon")
.version(cli_version)
.version(axon_version.to_string())
.subcommand_required(true)
.subcommand(
Command::new("run")
Expand Down Expand Up @@ -112,7 +112,7 @@ impl AxonCli {

register_log(&config);

Axon::new(config, genesis)
Axon::new(self.version.to_string(), config, genesis)
.run(key_provider)
.map_err(Error::Running)
}
Expand Down Expand Up @@ -149,7 +149,7 @@ fn check_version(p: &Path, current: &Version, least_compatible: Version) -> Resu
return Ok(());
}

let prev_version = Version::parse(&ver_str).unwrap();
let prev_version = Version::new(&ver_str);
if prev_version < least_compatible {
return Err(Error::CheckingVersion(Box::new(CheckingVersionError {
least_compatible,
Expand Down Expand Up @@ -184,7 +184,7 @@ fn atomic_write(p: &Path, content: &[u8]) -> io::Result<()> {
}

fn latest_compatible_version() -> Version {
Version::parse("0.1.0-alpha.9").unwrap()
Version::new("0.1.0-beta.1")
}

fn register_log(config: &Config) {
Expand Down
6 changes: 4 additions & 2 deletions core/run/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,16 @@ pub static JEMALLOC: Jemalloc = Jemalloc;

#[derive(Debug)]
pub struct Axon {
version: String,
config: Config,
genesis: RichBlock,
state_root: MerkleRoot,
}

impl Axon {
pub fn new(config: Config, genesis: RichBlock) -> Axon {
pub fn new(version: String, config: Config, genesis: RichBlock) -> Axon {
Axon {
version,
config,
genesis,
state_root: MerkleRoot::default(),
Expand Down Expand Up @@ -381,7 +383,7 @@ impl Axon {
Arc::clone(&trie_db),
Arc::new(network_handle),
));
let _handles = run_jsonrpc_server(self.config.clone(), api_adapter).await?;
let _handles = run_jsonrpc_server(self.version, self.config.clone(), api_adapter).await?;

// Run sync
tokio::spawn(async move {
Expand Down
2 changes: 1 addition & 1 deletion devtools/abi-generator/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = { version = "4.1", features = ["derive"] }
clap = { version = "4.3", features = ["derive"] }
ethers = "2.0"
5 changes: 2 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ use core_executor::FEE_ALLOCATOR;
pub fn run(
fee_allocator: impl FeeAllocate + 'static,
key_provider: impl KeyProvider,
cli_version: &'static str,
version: &'static str,
) -> Result<()> {
FEE_ALLOCATOR.swap(Arc::new(Box::new(fee_allocator)));
AxonCli::init(clap::crate_version!().parse().unwrap(), cli_version)
.start_with_custom_key_provider(Some(key_provider))
AxonCli::init(version.parse().unwrap()).start_with_custom_key_provider(Some(key_provider))
}
12 changes: 6 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use clap::crate_version;

use common_version::Version;
use core_cli::AxonCli;

fn main() {
let result = AxonCli::init(
clap::crate_version!().parse().unwrap(),
concat!(clap::crate_version!(), env!("AXON_GIT_DESCRIPTION")),
)
.start();
if let Err(e) = result {
let version = Version::new_with_commit_id(crate_version!(), env!("AXON_COMMIT_ID"));

if let Err(e) = AxonCli::init(version).start() {
eprintln!("Error {e}");
std::process::exit(1);
}
Expand Down

0 comments on commit 15d8b4d

Please sign in to comment.