11use anyhow:: { bail, Context } ;
2- use std:: env;
32use std:: io:: ErrorKind ;
43use std:: process:: { Command , Stdio } ;
54
65fn main ( ) -> anyhow:: Result < ( ) > {
76 println ! ( "cargo:rerun-if-changed=.git/HEAD" ) ;
87 println ! ( "cargo:rerun-if-changed=.git/refs" ) ;
9- let manifest_dir = getenv ( "CARGO_MANIFEST_DIR" ) ?;
108 let pkg_version = getenv ( "CARGO_PKG_VERSION" ) ?;
9+ if let Some ( commit) = get_commit_hash ( ) ? {
10+ println ! ( "cargo:rustc-env=VERSION_WITH_GIT={pkg_version} (commit: {commit})" ) ;
11+ } else {
12+ println ! ( "cargo:rustc-env=VERSION_WITH_GIT={pkg_version}" ) ;
13+ }
14+ Ok ( ( ) )
15+ }
16+
17+ fn get_commit_hash ( ) -> anyhow:: Result < Option < String > > {
18+ let manifest_dir = getenv ( "CARGO_MANIFEST_DIR" ) ?;
1119 match Command :: new ( "git" )
1220 . arg ( "rev-parse" )
1321 . arg ( "--git-dir" )
@@ -31,34 +39,22 @@ fn main() -> anyhow::Result<()> {
3139 output. status
3240 ) ;
3341 }
34- let mut revision = String :: from_utf8 ( output. stdout )
35- . context ( "`git rev-parse --short HEAD` output was not UTF-8" ) ?;
36- chomp ( & mut revision) ;
37- println ! ( "cargo:rustc-env=VERSION_WITH_GIT={pkg_version} (commit: {revision})" ) ;
38- }
39- Ok ( _) => {
40- // We are not in a Git repository
41- println ! ( "cargo:rustc-env=VERSION_WITH_GIT={pkg_version}" ) ;
42+ let revision = std:: str:: from_utf8 ( & output. stdout )
43+ . context ( "`git rev-parse --short HEAD` output was not UTF-8" ) ?
44+ . trim ( )
45+ . to_owned ( ) ;
46+ Ok ( Some ( revision) )
4247 }
48+ Ok ( _) => Ok ( None ) , // We are not in a Git repository
4349 Err ( e) if e. kind ( ) == ErrorKind :: NotFound => {
4450 // Git doesn't seem to be installed, so assume we're not in a Git
4551 // repository
46- println ! ( "cargo:rustc-env=VERSION_WITH_GIT={pkg_version}" ) ;
52+ Ok ( None )
4753 }
48- Err ( e) => return Err ( e) . context ( "failed to run `git rev-parse --git-dir`" ) ,
54+ Err ( e) => Err ( e) . context ( "failed to run `git rev-parse --git-dir`" ) ,
4955 }
50- Ok ( ( ) )
5156}
5257
5358fn getenv ( name : & str ) -> anyhow:: Result < String > {
54- env:: var ( name) . with_context ( || format ! ( "{name} envvar not set" ) )
55- }
56-
57- fn chomp ( s : & mut String ) {
58- if s. ends_with ( '\n' ) {
59- s. pop ( ) ;
60- if s. ends_with ( '\r' ) {
61- s. pop ( ) ;
62- }
63- }
59+ std:: env:: var ( name) . with_context ( || format ! ( "{name} envvar not set" ) )
6460}
0 commit comments