Giter Site home page Giter Site logo

baoyachi / shadow-rs Goto Github PK

View Code? Open in Web Editor NEW
394.0 5.0 35.0 705 KB

A build-time information stored in your rust project.(binary,lib,cdylib,dylib)

Home Page: https://docs.rs/shadow-rs

License: MIT License

Rust 100.00%
build shadow compile compiler metadata flags rust-build cargo cargo-plugin cargo-build

shadow-rs's Introduction

shadow-rs: Build-time information stored in your Rust project (binary, lib, cdylib, dylib).

shadow-rs build tool

GitHub Actions Crates.io Docs.rs Download DepStatus Gitter Coverage Status shadow-rs allows you to access properties of the build process and environment at runtime, including:

  • Cargo.toml information, such as the project version
  • Dependency information
  • Git information, such as the commit that produced the build artifact
  • What version of the Rust toolchain was used in compilation
  • The build variant, e.g. debug or release
  • ... And more!

You can use this crate to programmatically check where a binary came from and how it was built.

Currently, integration into wasm is also supported. For detailed settings, please refer to the link example_wasm.

build_module

Note on Caching

shadow-rs build information is not always rebuilt when you build a project. shadow-rs outputs several hints to Cargo in order to force rebuilds when required, but this does not always work. You can enforce up-to-date build information by running cargo clean before the build, or use a CI/CD pipeline tool. For more details, see #95.

Examples

  • Check out the example_shadow for a simple demonstration of how shadow-rs might be used to provide build-time information at run-time.
  • Check out the example_shadow_hook for a demonstration of how custom hooks can be used to add extra information to shadow-rs's output.
  • Check out the builtin_fn example for a simple demonstration of the built-in functions that shadow-rs provides.

Setup

1) Modify Cargo.toml fields

Modify your Cargo.toml like so:

[package]
build = "build.rs"

[dependencies]
shadow-rs = "{latest version}"

[build-dependencies]
shadow-rs = "{latest version}"

About build = "build.rs",this is an optional addition where, by default, build points to the build.rs file. It is recommended to use it as such. However, if your build script file is not named build.rs, please manually specify it. For example: build = "gen.rs".

2) Create build.rs file

Now in the root of your project (same directory as Cargo.toml) add a file build.rs:

fn main() -> shadow_rs::SdResult<()> {
    shadow_rs::new()
}

If you want to exclude some build constants, you can use [new_deny] instead of [new].

3) Integrate Shadow

In your main Rust file (usually main.rs or lib.rs), add this:

use shadow_rs::shadow;

shadow!(build);

The shadow! macro uses the given identifier to create a module with that name.

4) Use Shadow Constants

You can now use the module defined with shadow! to access build-time information.

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'
    println!("tag:{}", shadow_rs::tag()); // get current project tag. e.g 'v1.3.5'
    println!("git_clean:{}", shadow_rs::git_clean()); // get current project clean. e.g 'true/false'
    println!("git_status_file:{}", shadow_rs::git_status_file()); // get current project statue file. e.g '  * examples/builtin_fn.rs (dirty)'

    println!("{}", build::VERSION); //print version const
    println!("{}", build::CLAP_LONG_VERSION); //print CLAP_LONG_VERSION const
    println!("{}", build::BRANCH); //master
    println!("{}", build::SHORT_COMMIT);//8405e28e
    println!("{}", build::COMMIT_HASH);//8405e28e64080a09525a6cf1b07c22fcaf71a5c5
    println!("{}", build::COMMIT_DATE);//2021-08-04 12:34:03 +00:00
    println!("{}", build::COMMIT_AUTHOR);//baoyachi
    println!("{}", build::COMMIT_EMAIL);//[email protected]

    println!("{}", build::BUILD_OS);//macos-x86_64
    println!("{}", build::RUST_VERSION);//rustc 1.45.0 (5c1f21c3b 2020-07-13)
    println!("{}", build::RUST_CHANNEL);//stable-x86_64-apple-darwin (default)
    println!("{}", build::CARGO_VERSION);//cargo 1.45.0 (744bd1fbb 2020-06-15)
    println!("{}", build::PKG_VERSION);//0.3.13
    println!("{}", build::CARGO_TREE); //like command:cargo tree
    println!("{}", build::CARGO_MANIFEST_DIR); // /User/baoyachi/shadow-rs/ |

    println!("{}", build::PROJECT_NAME);//shadow-rs
    println!("{}", build::BUILD_TIME);//2020-08-16 14:50:25
    println!("{}", build::BUILD_RUST_CHANNEL);//debug
    println!("{}", build::GIT_CLEAN);//false
    println!("{}", build::GIT_STATUS_FILE);//* src/lib.rs (dirty)
}

Reproducibility

This tool includes the current time in the binary which would normally make it non-reproducible. However, it respects the SOURCE_DATE_EPOCH variable - if set to a Unix timestamp it will override the value of build time.

Clap

You can also use shadow-rs to provide information to command-line interface crates such as clap. An example of this can be found in example_shadow.

List of Constants and Functions

Functions

Function Description
is_debug() true if this is a build with debug assertions.
branch() Git branch at build time.
tag() Current Git tag at build time.
git_clean() Whether Git working tree was clean at build time.
git_status_file() git status-like output, e.g. * examples/builtin_fn.rs (dirty)

Constants

Constant Example
VERSION 3.4.5
CLAP_LONG_VERSION (A multi-line string containing branch, commit hash, build time, Rust version and toolchain channel)
BRANCH master
TAG v1.0.0
SHORT_COMMIT 8405e28e
COMMIT_HASH 8405e28e64080a09525a6cf1b07c22fcaf71a5c5
COMMIT_DATE 2021-08-04 12:34:03 +00:00
COMMIT_DATE_2822 Thu, 24 Jun 2021 21:33:59 +0800
COMMIT_DATE_3339 2021-06-24T21:33:59.972494+08:00
COMMIT_AUTHOR baoyachi
COMMIT_EMAIL [email protected]
BUILD_OS macos-x86_64
BUILD_TARGET x86_64-apple-darwin
BUILD_TARGET_ARCH x86_64
RUST_VERSION rustc 1.45.0 (5c1f21c3b 2020-07-13)
RUST_CHANNEL stable-x86_64-apple-darwin (default)
CARGO_VERSION cargo 1.45.0 (744bd1fbb 2020-06-15)
PKG_VERSION 0.3.13
CARGO_TREE (Output of cargo tree)
CARGO_MANIFEST_DIR /User/baoyachi/shadow-rs/
PROJECT_NAME shadow-rs
BUILD_TIME 2021-06-24 21:33:59
BUILD_TIME_2822 Thu, 24 Jun 2021 21:33:59 +0800
BUILD_TIME_3339 2021-06-24T15:53:55+08:00
BUILD_RUST_CHANNEL release
GIT_CLEAN true
GIT_STATUS_FILE * src/lib.rs (dirty)

If you have any questions, please create an issue so we may improve the documentation where it may be unclear.

People using shadow-rs

If you are using shadow-rs, please tell me! Or instead, consider making a note here: Shadow Users Collection.

nushell
nushell

starship
starship

exocore
exocore

starship
bagua-core

starship
inclavare-containers

shadow-rs's People

Contributors

alerque avatar baoyachi avatar davidkna avatar dependabot[bot] avatar epage avatar guoyucode avatar kianmeng avatar kijewski avatar kixunil avatar kleinesfilmroellchen avatar kpcyrd avatar lopopolo avatar sameo avatar skyfallwastaken avatar thinkgos avatar valterschutz avatar wbrickner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

shadow-rs's Issues

cargo tree support hide path dep

...
│   │   [build-dependencies]
│   │   └── clap v2.33.3 (*)
│   ├── nu-data v0.25.2 (/Users/baoyachi/nushell/crates/nu-data) (*)
│   ├── nu-errors v0.25.2 (/Users/baoyachi/nushell/crates/nu-errors) (*)
│   ├── nu-plugin v0.25.2 (/Users/baoyachi/nushell/crates/nu-plugin) (*)
│   ├── nu-protocol v0.25.2 (/Users/baoyachi/nushell/crates/nu-protocol) (*)
│   ├── nu-source v0.25.2 (/Users/baoyachi/nushell/crates/nu-source) (*)
│   ├── term_size v0.3.2 (*)
│   └── url v2.2.0 (*)
└── pretty_env_logger v0.4.0

replace with

...
│   │   [build-dependencies]
│   │   └── clap v2.33.3 (*)
│   ├── nu-data v0.25.2 (private)
│   ├── nu-errors v0.25.2 (private)
│   ├── nu-plugin v0.25.2 (private)
│   ├── nu-protocol v0.25.2 (private)
│   ├── nu-source v0.25.2 (private)
│   ├── term_size v0.3.2 (*)
│   └── url v2.2.0 (*)
└── pretty_env_logger v0.4.0

Please add support for SOURCE_DATE_EPOCH to enable reproducible builds

Currently this library is blocking every project that uses it from passing reproducible build checks. The primary offender is here:

let time = Local::now();

The standardized solution to this it to support SOURCE_DATE_EPOCH. This way distro build systems and anything that is trying to verify whether packages are reproducible can keep ephemeral time information from being embedded in the binaries during test builds.

As an example of where this is a problem, see projects such as starship that are showing up in the BAD list on Arch Linux's reproducible status dashboard. The relevant bit from the diffoscope output is this snippet:

│ │ ├── strings --all --bytes=8 {}
│ │ │ @@ -5266,15 +5266,15 @@
│ │ │  - Build Time: 
│ │ │  #### Relevant Shell Configuration
│ │ │  #### Starship Configuration
│ │ │  releasestarship::utilssrc/utils.rsExecuting command  failed by: You can set command_timeout in your config to a higher value to allow longer-running commands to keep executing. timed out., stderr: , exit code: "Unable to decode stderr: Unable to decode stdout: Unable to run Unable to find  in PATH, Using  with args --version
│ │ │  pkg_version:
│ │ │  commit_hash:
│ │ │  build_time:
│ │ │ -build_env:,rustc 1.53.02021-07-18 19:25:400.56.0fg:bg:redsrc/config.rsCould not parse color in string: Read predefined color: Read ANSI color string: Read RGB color string: Could not parse hexadecimal string: Attempting to read hexadecimal color string: Parsing color_string: /build/rust/src/rustc-1.53.0-src/library/std/src/thread/local.rsFile read sucessfullyError reading file: ErrOkTrying to read from Unable to parse the config file: Config parsed: assertion failed: self.next_value.is_none()Unable to read table valuesassertion failed: self.values.next().is_none()attempt to join into collection with len > usize::MAX/build/rust/src/rustc-1.53.0-src/library/alloc/src/str.rs$__toml_private_datetimeUnable to read config file content: Config file content: "
│ │ │ +build_env:,rustc 1.53.02021-08-02 14:35:450.56.0fg:bg:redsrc/config.rsCould not parse color in string: Read predefined color: Read ANSI color string: Read RGB color string: Could not parse hexadecimal string: Attempting to read hexadecimal color string: Parsing color_string: /build/rust/src/rustc-1.53.0-src/library/std/src/thread/local.rsFile read sucessfullyError reading file: ErrOkTrying to read from Unable to parse the config file: Config parsed: assertion failed: self.next_value.is_none()Unable to read table valuesassertion failed: self.values.next().is_none()attempt to join into collection with len > usize::MAX/build/rust/src/rustc-1.53.0-src/library/alloc/src/str.rs$__toml_private_datetimeUnable to read config file content: Config file content: "
│ │ │  Using default config path: STARSHIP_CONFIG is not setSTARSHIP_CONFIG is set: Config found for "": No config found for "": Option "" not foundStarship::get_config called with an empty pathcustomCustom config found for "env_varformatscan_timeoutcommand_timeoutadd_newlinesrc/configs/starship_root.rsDid you mean ''?Unknown config key 'awsbatterycharactercmakecmd_durationcondacrystaldirectorydocker_contextdotnetelixirelmerlanggcloudgit_branchgit_commitgit_metricsgit_stategit_statusgolanghg_branchjuliakotlinkubernetesline_breakluamemory_usagenimnix_shellnodejsocamlopenstackpackagephppurescriptpythonrlangscalashellshlvlsingularityswiftterraformvagrantvlangzigon [$symbol($profile )(\($region\) )(\[$duration\])]($style)bold yellowX[$symbol$percentage]($style) [
│ │ │  ](bold green)[
│ │ │  ](bold red)[
│ │ │  ](bold green)CMakeLists.txtCMakeCache.txtv${raw}bold bluetook [$duration]($style) yellow boldvia [$symbol$environment]($style) 
│ │ │   green boldcrshard.yml
│ │ │   [$symbol($output )]($style)<custom config>pubspec.yamlpubspec.ymlpubspec.lock.dart_tool
│ │ │   mod.tsdeps.tsmod.jsdeps.js
│ │ ├── readelf --wide --decompress --hex-dump=.rodata {}
│ │ │ @@ -27659,16 +27659,16 @@
│ │ │    0x0048c080 66696e64 2020696e 20504154 482c2055 find  in PATH, U
│ │ │    0x0048c090 73696e67 20207769 74682061 72677320 sing  with args 
│ │ │    0x0048c0a0 2d2d7665 7273696f 6e0a0a0a 706b675f --version...pkg_
│ │ │    0x0048c0b0 76657273 696f6e3a 0a746167 3a0a636f version:.tag:.co
│ │ │    0x0048c0c0 6d6d6974 5f686173 683a0a62 75696c64 mmit_hash:.build
│ │ │    0x0048c0d0 5f74696d 653a0a62 75696c64 5f656e76 _time:.build_env
│ │ │    0x0048c0e0 3a2c7275 73746320 312e3533 2e303230 :,rustc 1.53.020
│ │ │ -  0x0048c0f0 32312d30 372d3138 2031393a 32353a34 21-07-18 19:25:4
│ │ │ -  0x0048c100 30302e35 362e3066 673a6267 3a726564 00.56.0fg:bg:red
│ │ │ +  0x0048c0f0 32312d30 382d3032 2031343a 33353a34 21-08-02 14:35:4
│ │ │ +  0x0048c100 35302e35 362e3066 673a6267 3a726564 50.56.0fg:bg:red
│ │ │    0x0048c110 7372632f 636f6e66 69672e72 73436f75 src/config.rsCou
│ │ │    0x0048c120 6c64206e 6f742070 61727365 20636f6c ld not parse col
│ │ │    0x0048c130 6f722069 6e207374 72696e67 3a205265 or in string: Re
│ │ │    0x0048c140 61642070 72656465 66696e65 6420636f ad predefined co
│ │ │    0x0048c150 6c6f723a 20526561 6420414e 53492063 lor: Read ANSI c
│ │ │    0x0048c160 6f6c6f72 20737472 696e673a 20526561 olor string: Rea
│ │ │    0x0048c170 64205247 4220636f 6c6f7220 73747269 d RGB color stri

Only support reproducible output by default

Reproducible builds is a strong area of interest for people but shadow is generated code that is inherently not reproducible and relies on people only calling a subset of calls and the compiler optimizing the rest away.

Time-derive data is an a clear case of this. git-derived data is more debatable.

Detect target features

In clap, we have clap-rs/clap#1363. I'm tempted to close this out by pointing to shadow. One thing mentioned in that issue but that I'm not seeing in shadow is checking target_feature support (simd flags).

fix warnings please

Hey @baoyachi,
Would you mind fixing these warnings so we can build without warnings in nushell?

warning: function is never used: `version`
   --> /home/folder/src/forks/nushell/target/release/build/nu-command-907562c9e57f4e61/out/shadow.rs:681:8    |
681 | pub fn version() -> String {
    |        ^^^^^^^
    |
    = note: `#[warn(dead_code)]` on by default

warning: function is never used: `clap_version`
   --> /home/folder/src/forks/nushell/target/release/build/nu-command-907562c9e57f4e61/out/shadow.rs:692:8    |
692 | pub fn clap_version() -> String {
    |        ^^^^^^^^^^^^

the generate version method with branch value is not correct

when ci use tag, the branch output value is tag value,not branch name .

~ ./shadow_example -V
branch:v0.5.1 # this is tag value,not branch name
commit-hash:9224dbf4a
build_time:2020-12-04 21:15:40
build_env:rustc 1.41.1 (f3e1a954d 2020-02-24),stable (default)

It's need fix

make method return String to be &'static str

#[repr(C)]
pub union PtrToRef<'a, T: ?Sized> {
    pub ptr: *const T,
    pub reff: &'a T,
}

fn main() {
    let hello = b"Hello union Rust";
    let key = unsafe {
        let string: &'static str = {
            PtrToRef {
                ptr: hello as *const [u8] as *const str,
            }.reff
        };
        string
    };
    println!("{}", key);
}

RUST_VERSION and RUST_CHANNEL may disagree in presence of rust-toolchain.toml

RUST_VERSION is computed by running rustc -V, while RUST_CHANNEL by running rustup default
In presence of rust-toolchain.toml these may disagree.
Example: I have nightly configured by default (hence rustup default reports nightly channel), however in my crate I have

rust-toolchain.toml

[toolchain]
channel = "stable"

So, rustc -V reports the current stable version (as installed).
Understanding the discrepancy when these are reported by the running binary may be a tough exercise

version 0.6.9 without git feature fails to compile

Hi,

Version 0.6.9 fails to compile if git feature is disabled.

Cargo.toml

shadow-rs = {version = "0.6", default-features = false}

Outputs

error[E0432]: unresolved import `git2`
 --> /home/appaquet/.cargo/registry/src/github.com-1ecc6299db9ec823/shadow-rs-0.6.9/src/git.rs:7:5
  |
7 | use git2::Repository;
  |     ^^^^ use of undeclared crate or module `git2`

error[E0432]: unresolved import `git2`
 --> /home/appaquet/.cargo/registry/src/github.com-1ecc6299db9ec823/shadow-rs-0.6.9/src/git.rs:7:5
  |
7 | use git2::Repository;
  |     ^^^^ use of undeclared crate or module `git2`

Cargo audit informs a possibility of a vulnerability

From cargo audit checking:

Fetching advisory database from `https://github.com/RustSec/advisory-db.git`
      Loaded [39](https://gitlab.com/my_project/-/jobs/2118924918#L39)8 security advisories (from my_project/.cargo/advisory-db)
    Updating crates.io index
    Updating crates.io index
    Scanning Cargo.lock for vulnerabilities (260 crate dependencies)
Crate:         chrono
Version:       0.4.19
Title:         Potential segfault in `localtime_r` invocations
Date:          2020-11-10
ID:            RUSTSEC-2020-0159
URL:           https://rustsec.org/advisories/RUSTSEC-2020-0159
Solution:      No safe upgrade is available!
Dependency tree: 
chrono 0.4.19
└── shadow-rs 0.8.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.