Skip to content

Commit

Permalink
Merge pull request #39 from baoyachi/current_branch
Browse files Browse the repository at this point in the history
add current branch, semver version const
  • Loading branch information
baoyachi committed Jan 14, 2021
2 parents 21b54e9 + 683d2b7 commit 53303b3
Show file tree
Hide file tree
Showing 9 changed files with 183 additions and 49 deletions.
16 changes: 8 additions & 8 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ jobs:
- name: Run tests
run: cargo test --all --verbose -- --exact -Z unstable-options --format=json --show-output

# build on nightly
- uses: actions-rs/toolchain@v1
with:
toolchain: nightly
override: true
- name: Build on nightly
run: cargo build --release

# examples
- name: Check examples format
run: cargo fmt --all -- --check
Expand All @@ -48,11 +56,3 @@ jobs:
- name: Run examples
run: cargo run --release && target/release/example_shadow -V
working-directory: ./example_shadow

# build on nightly
- uses: actions-rs/toolchain@v1
with:
toolchain: nightly
override: true
- name: Build on nightly
run: cargo build --release
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "shadow-rs"
version = "0.5.9"
version = "0.5.10"
authors = ["baoyachi <[email protected]>"]
edition = "2018"
description = "A build script write by Rust"
Expand Down
88 changes: 58 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
[![DepStatus](https://deps.rs/repo/github/baoyachi/shadow-rs/status.svg)](https://deps.rs/repo/github/baoyachi/shadow-rs)
[![Gitter](https://badges.gitter.im/shadow-rs/community.svg)](https://gitter.im/shadow-rs/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)


`shadow-rs` allows you to recall properties of the build process and environment at runtime, including:

* `Cargo.toml` project version
Expand All @@ -24,11 +23,15 @@
You can use this tool to check in production exactly where a binary came from and how it was built.

# Full Examples
* Check out the [shadow_example](https://github.com/baoyachi/shadow-rs/tree/master/example_shadow) for a simple demonstration of how `shadow-rs` might be used to provide build-time information at run-time.

* Check out the [shadow_example](https://github.com/baoyachi/shadow-rs/tree/master/example_shadow) for a simple
demonstration of how `shadow-rs` might be used to provide build-time information at run-time.
* built in method:[examples](https://github.com/baoyachi/shadow-rs/tree/master/examples).

# Setup Guide

### 1) Modify `Cargo.toml` fields

Modify your `Cargo.toml` like so:

```TOML
Expand Down Expand Up @@ -63,43 +66,65 @@ extern crate shadow_rs;
shadow!(build);
```

**Notice that the `shadow!` macro is provided the identifier `build`. You can now use this identifier to access build-time information.**
**Notice that the `shadow!` macro is provided the identifier `build`. You can now use this identifier to access
build-time information.**

### 4) Done. Use Shadow.

```rust
fn main() {
println!("{}", shadow_rs::is_debug()); // check if this is a debug build

println!("{}", build::version()); // the version (description binary detail information)
println!("{}", build::BRANCH); // the branch, e.g. 'master'
println!("{}", build::TAG); // the tag, e.g. 'v1.0.0'
println!("{}", build::SHORT_COMMIT); // short commit hash, e.g. '8405e28e'
println!("{}", build::COMMIT_HASH); // full commit hash, e.g. '8405e28e64080a09525a6cf1b07c22fcaf71a5c5'
println!("{}", build::COMMIT_DATE); // commit date, e.g. '2020-08-16 11:52:47'
println!("{}", build::COMMIT_AUTHOR); // commit author, e.g. 'baoyachi'
println!("{}", build::COMMIT_EMAIL); // commit email, e.g. '[email protected]'

println!("{}", build::BUILD_OS); // the OS that built the binary, e.g. 'macos-x86_64'
println!("{}", build::RUST_VERSION); // rustc version e.g. 'rustc 1.45.0 (5c1f21c3b 2020-07-13)'
println!("{}", build::RUST_CHANNEL); // rust toolchain e.g. 'stable-x86_64-apple-darwin (default)'
println!("{}", build::CARGO_VERSION); // cargo version e.g. 'cargo 1.45.0 (744bd1fbb 2020-06-15)'
println!("{}", build::PKG_VERSION); // e.g. '0.3.13'
println!("{}", build::CARGO_TREE); // e.g. the output of '$ cargo tree'

println!("{}", build::PROJECT_NAME); // your project name, e.g. 'shadow-rs'
println!("{}", build::BUILD_TIME); // time when start build occurred, e.g. '2020-08-16 14:50:25'
println!("{}", build::BUILD_RUST_CHANNEL); // e.g. 'debug'

//shadow-rs built in method
println!("{}", shadow_rs::is_debug()); // check if this is a debug build
println!("{}", shadow_rs::branch()); // get current project git branch. e.g.'master'

//shadow-rs built in const
println!("{}", build::version()); // the version (description binary detail information)
println!("{}", build::PKG_VERSION); // current package version. e.g. '1.3.15-beta2'
println!("{}", build::PKG_VERSION_MAJOR); //current package major version. e.g. '1'
println!("{}", build::PKG_VERSION_MINOR); //current package minor version. e.g. '3'
println!("{}", build::PKG_VERSION_PATCH); //current package minor version. e.g. '15'
println!("{}", build::PKG_VERSION_PRE); //current package minor version. e.g. 'beta2'
println!("{}", build::BRANCH); // the branch, e.g. 'master'
println!("{}", build::TAG); // the tag, e.g. 'v1.0.0'
println!("{}", build::SHORT_COMMIT); // short commit hash, e.g. '8405e28e'
println!("{}", build::COMMIT_HASH); // full commit hash, e.g. '8405e28e64080a09525a6cf1b07c22fcaf71a5c5'
println!("{}", build::COMMIT_DATE); // commit date, e.g. '2020-08-16 11:52:47'
println!("{}", build::COMMIT_AUTHOR); // commit author, e.g. 'baoyachi'
println!("{}", build::COMMIT_EMAIL); // commit email, e.g. '[email protected]'

println!("{}", build::BUILD_OS); // the OS that built the binary, e.g. 'macos-x86_64'
println!("{}", build::RUST_VERSION); // rustc version e.g. 'rustc 1.45.0 (5c1f21c3b 2020-07-13)'
println!("{}", build::RUST_CHANNEL); // rust toolchain e.g. 'stable-x86_64-apple-darwin (default)'
println!("{}", build::CARGO_VERSION); // cargo version e.g. 'cargo 1.45.0 (744bd1fbb 2020-06-15)'
println!("{}", build::CARGO_TREE); // e.g. the output of '$ cargo tree'

println!("{}", build::PROJECT_NAME); // your project name, e.g. 'shadow-rs'
println!("{}", build::BUILD_TIME); // time when start build occurred, e.g. '2020-08-16 14:50:25'
println!("{}", build::BUILD_RUST_CHANNEL); // e.g. 'debug'
}
```

## Clap Example
And you can also use `shadow-rs` with [`clap`](https://github.com/baoyachi/shadow-rs/blob/master/example_shadow/src/main.rs).
## Clap Example

And you can also use `shadow-rs`
with [`clap`](https://github.com/baoyachi/shadow-rs/blob/master/example_shadow/src/main.rs).

## Support const,method in table

#### shadow-rs built in method.
* how to use 👉:[examples](https://github.com/baoyachi/shadow-rs/tree/master/examples)
| method | desc |
| ------ | ------ |
| is_debug() | check if this is a debug build.e.g.'true/false' |
| branch() | get current project branch.e.g.'master/develop' |

#### shadow-rs support build const.
* how to use see 👉:[shadow_example](https://github.com/baoyachi/shadow-rs/tree/master/example_shadow)

## Support const table
| const | example |
| ------ | ------ |
| version() | master/develop |
| version() | support mini version information.It's use easy. |
| BRANCH | master/develop |
| TAG | v1.0.0 |
| SHORT_COMMIT | 8405e28e |
Expand All @@ -117,10 +142,13 @@ And you can also use `shadow-rs` with [`clap`](https://github.com/baoyachi/shado
| BUILD_TIME | 2020-08-16 14:50:25 |
| BUILD_RUST_CHANNEL | debug/release |

If you have any questions, please create an [issue](https://github.com/baoyachi/shadow-rs/issues/new) so we may improve the documentation where it may be unclear.
If you have any questions, please create an [issue](https://github.com/baoyachi/shadow-rs/issues/new) so we may improve
the documentation where it may be unclear.

## People using Shadow
If you are using `shadow-rs`, please tell me! Or instead, consider making a note here: [Shadow Users Collection](https://github.com/baoyachi/shadow-rs/issues/19).

If you are using `shadow-rs`, please tell me! Or instead, consider making a note
here: [Shadow Users Collection](https://github.com/baoyachi/shadow-rs/issues/19).

<table>
<tr>
Expand Down
4 changes: 2 additions & 2 deletions example_shadow/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "example_shadow"
version = "0.1.0"
version = "0.1.8-beta3"
authors = ["baoyachi <[email protected]>"]
edition = "2018"
build = "build.rs"
Expand All @@ -12,4 +12,4 @@ clap = "2.33.3"
shadow-rs = "0.5"

[build-dependencies]
shadow-rs = "0.5"
shadow-rs = "0.5"
12 changes: 10 additions & 2 deletions example_shadow/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,16 @@ fn main() {
.version(build::version().as_str())
.get_matches(); //USAGE: ./example_shadow -V

println!("debug:{}", shadow_rs::is_debug()); //get build mode
// shadow-rs built in method
println!("is_debug:{}", shadow_rs::is_debug());
println!("branch:{}", shadow_rs::branch());

println!("version:{}", build::version());
println!("pkg_version:{}", build::PKG_VERSION);
println!("pkg_version_major:{}", build::PKG_VERSION_MAJOR);
println!("pkg_version_minor:{}", build::PKG_VERSION_MINOR);
println!("pkg_version_patch:{}", build::PKG_VERSION_PATCH);
println!("pkg_version_pre:{}", build::PKG_VERSION_PRE);

println!("tag:{}", build::TAG);
println!("branch:{}", build::BRANCH);
Expand All @@ -24,7 +33,6 @@ fn main() {
println!("rust_version:{}", build::RUST_VERSION);
println!("rust_channel:{}", build::RUST_CHANNEL);
println!("cargo_version:{}", build::CARGO_VERSION);
println!("pkg_version:{}", build::PKG_VERSION);
println!("cargo_tree:{}", build::CARGO_TREE);

println!("project_name:{}", build::PROJECT_NAME);
Expand Down
4 changes: 4 additions & 0 deletions examples/builtin_method.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
fn main() {
println!("debug:{}", shadow_rs::is_debug()); // check if this is a debug build. e.g 'true/false'
println!("branch:{}", shadow_rs::branch()); // get current project branch. e.g 'master/develop'
}
35 changes: 35 additions & 0 deletions src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ const CARGO_VERSION: ShadowConst = "CARGO_VERSION";
const CARGO_TREE: ShadowConst = "CARGO_TREE";
// const CARGO_METADATA: ShadowConst = "CARGO_METADATA";
const PKG_VERSION: ShadowConst = "PKG_VERSION";
const PKG_VERSION_MAJOR: ShadowConst = "PKG_VERSION_MAJOR";
const PKG_VERSION_MINOR: ShadowConst = "PKG_VERSION_MINOR";
const PKG_VERSION_PATCH: ShadowConst = "PKG_VERSION_PATCH";
const PKG_VERSION_PRE: ShadowConst = "PKG_VERSION_PRE";

impl SystemEnv {
fn init(&mut self, std_env: &HashMap<String, String>) -> SdResult<()> {
Expand Down Expand Up @@ -74,6 +78,20 @@ impl SystemEnv {
update_val(PKG_VERSION, v.to_string());
}

if let Some(v) = std_env.get("CARGO_PKG_VERSION_MAJOR") {
update_val(PKG_VERSION_MAJOR, v.to_string());
}

if let Some(v) = std_env.get("CARGO_PKG_VERSION_MINOR") {
update_val(PKG_VERSION_MINOR, v.to_string());
}
if let Some(v) = std_env.get("CARGO_PKG_VERSION_PATCH") {
update_val(PKG_VERSION_PATCH, v.to_string());
}
if let Some(v) = std_env.get("CARGO_PKG_VERSION_PRE") {
update_val(PKG_VERSION_PRE, v.to_string());
}

Ok(())
}
}
Expand Down Expand Up @@ -134,6 +152,23 @@ pub fn new_system_env(std_env: &HashMap<String, String>) -> HashMap<ShadowConst,
ConstVal::new("display build current project version"),
);

env.map.insert(
PKG_VERSION_MAJOR,
ConstVal::new("display build current project major version"),
);
env.map.insert(
PKG_VERSION_MINOR,
ConstVal::new("display build current project minor version"),
);
env.map.insert(
PKG_VERSION_PATCH,
ConstVal::new("display build current project patch version"),
);
env.map.insert(
PKG_VERSION_PRE,
ConstVal::new("display build current project preview version"),
);

if let Err(e) = env.init(std_env) {
println!("{}", e.to_string());
}
Expand Down
61 changes: 56 additions & 5 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ use crate::build::{ConstType, ConstVal, ShadowConst};
use crate::ci::CIType;
use crate::err::*;
use chrono::{DateTime, Local, NaiveDateTime, Utc};
use git2::Reference;
use git2::Error as git2Error;
use git2::{Reference, Repository};
use std::collections::HashMap;
use std::path::Path;
use std::process::Command;

pub const BRANCH: ShadowConst = "BRANCH";
Expand Down Expand Up @@ -31,8 +33,8 @@ impl Git {
}
}

fn init(&mut self, path: &std::path::Path, std_env: &HashMap<String, String>) -> SdResult<()> {
let repo = git2::Repository::discover(path)?;
fn init(&mut self, path: &Path, std_env: &HashMap<String, String>) -> SdResult<()> {
let repo = git_repo(path)?;
let reference = repo.head()?;

let (branch, tag) = self.get_branch_tag(&reference, &std_env)?;
Expand Down Expand Up @@ -83,8 +85,12 @@ impl Git {
let mut tag = String::new();

//get branch
if let Some(v) = reference.shorthand() {
branch = v.to_string();
if let Some(v) = reference
.shorthand()
.map(|x| x.trim().to_string())
.or_else(command_current_branch)
{
branch = v
}

//get HEAD branch
Expand Down Expand Up @@ -165,6 +171,38 @@ pub fn new_git(
git.map
}

/// get current repository git branch.
///
/// When current repository exists git folder.
///
/// This method try use `git2` crates get current branch.
/// If get error,then try use `Command` to get.
pub fn branch() -> String {
git_repo(".")
.map(|x| git2_current_branch(&x))
.unwrap_or_else(|_| command_current_branch())
.unwrap_or_default()
}

fn git_repo<P: AsRef<Path>>(path: P) -> Result<Repository, git2Error> {
git2::Repository::discover(path)
}

fn git2_current_branch(repo: &Repository) -> Option<String> {
repo.head()
.map(|x| x.shorthand().map(|x| x.to_string()))
.unwrap_or(None)
}

fn command_current_branch() -> Option<String> {
Command::new("git")
.args(&["symbolic-ref", "--short", "HEAD"])
.output()
.map(|x| String::from_utf8(x.stdout).ok())
.map(|x| x.map(|x| x.trim().to_string()))
.unwrap_or(None)
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -177,4 +215,17 @@ mod tests {
let map = new_git(Path::new("./"), CIType::Github, &map);
println!("map:{:?}", map);
}

#[test]
fn test_current_branch() {
let git2_branch = git_repo(".")
.map(|x| git2_current_branch(&x))
.unwrap_or(None);
let command_branch = command_current_branch();
assert!(git2_branch.is_some());
assert!(command_branch.is_some());
assert_eq!(command_branch, git2_branch);

assert_eq!(Some(branch()), git2_branch);
}
}
10 changes: 9 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,17 @@
//! # Full Examples
//! * Check out the [shadow_example](https://github.com/baoyachi/shadow-rs/tree/master/example_shadow) for a simple demonstration of how `shadow-rs` might be used to provide build-time information at run-time.
//!
//! ## Built in method
//! * Check out the [examples](https://github.com/baoyachi/shadow-rs/tree/master/examples) for a simple demonstration of how `shadow-rs` might be used to provide build in method.
//!
//! # Example
//!
//! ```
//! pub const PKG_VERSION :&str = "1.3.8-beta3";
//! pub const PKG_VERSION_MAJOR :&str = "1";
//! pub const PKG_VERSION_MINOR :&str = "3";
//! pub const PKG_VERSION_PATCH :&str = "8";
//! pub const PKG_VERSION_PRE :&str = "beta3";
//! pub const RUST_VERSION :&str = "rustc 1.45.0 (5c1f21c3b 2020-07-13)";
//! pub const BUILD_RUST_CHANNEL :&str = "debug";
//! pub const COMMIT_AUTHOR :&str = "baoyachi";
Expand Down Expand Up @@ -46,7 +54,6 @@
//! pub const CARGO_VERSION :&str = "cargo 1.45.0 (744bd1fbb 2020-06-15)";
//! pub const BUILD_OS :&str = "macos-x86_64";
//! pub const COMMIT_HASH :&str = "386741540d73c194a3028b96b92fdeb53ca2788a";
//! pub const PKG_VERSION :&str = "0.3.13";
//! ```
//! # Setup Guide
//!
Expand Down Expand Up @@ -143,6 +150,7 @@ use std::path::Path;
pub use channel::BuildRustChannel;
use chrono::Local;
pub use err::SdResult;
pub use git::branch;

const SHADOW_RS: &str = "shadow.rs";

Expand Down

0 comments on commit 53303b3

Please sign in to comment.