vergen-lib-9.1.0/.cargo_vcs_info.json0000644000000001501046102023000131130ustar { "git": { "sha1": "a55365ffc0133c6f86fd33bc6b5c9ac46b36e245" }, "path_in_vcs": "vergen-lib" }vergen-lib-9.1.0/Cargo.lock0000644000000213651046102023000111010ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "anyhow" version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" [[package]] name = "bitflags" version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" [[package]] name = "cfg-if" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "darling" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ "darling_core", "darling_macro", ] [[package]] name = "darling_core" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", "strsim", "syn", ] [[package]] name = "darling_macro" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core", "quote", "syn", ] [[package]] name = "derive_builder" version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" dependencies = [ "derive_builder_macro", ] [[package]] name = "derive_builder_core" version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" dependencies = [ "darling", "proc-macro2", "quote", "syn", ] [[package]] name = "derive_builder_macro" version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" dependencies = [ "derive_builder_core", "syn", ] [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "futures-core" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" [[package]] name = "futures-executor" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" dependencies = [ "futures-core", "futures-task", "futures-util", ] [[package]] name = "futures-task" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" [[package]] name = "futures-util" version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" dependencies = [ "futures-core", "futures-task", "pin-project-lite", "pin-utils", "slab", ] [[package]] name = "ident_case" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "libc" version = "0.2.180" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc" [[package]] name = "lock_api" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" dependencies = [ "scopeguard", ] [[package]] name = "log" version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "parking_lot" version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", "windows-link", ] [[package]] name = "pin-project-lite" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" [[package]] name = "pin-utils" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "proc-macro2" version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "535d180e0ecab6268a3e718bb9fd44db66bbbc256257165fc699dadf70d16fe7" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc74d9a594b72ae6656596548f56f667211f8a97b3d4c3d467150794690dc40a" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ "bitflags", ] [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "scc" version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46e6f046b7fef48e2660c57ed794263155d713de679057f2d0c169bfc6e756cc" dependencies = [ "sdd", ] [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sdd" version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "490dcfcbfef26be6800d11870ff2df8774fa6e86d047e3e8c8a76b25655e41ca" [[package]] name = "serial_test" version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d0b343e184fc3b7bb44dff0705fffcf4b3756ba6aff420dddd8b24ca145e555" dependencies = [ "futures-executor", "futures-util", "log", "once_cell", "parking_lot", "scc", "serial_test_derive", ] [[package]] name = "serial_test_derive" version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f50427f258fb77356e4cd4aa0e87e2bd2c66dbcee41dc405282cae2bfc26c83" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "slab" version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" [[package]] name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "syn" version = "2.0.114" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "temp-env" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96374855068f47402c3121c6eed88d29cb1de8f3ab27090e273e420bdabcf050" dependencies = [ "parking_lot", ] [[package]] name = "unicode-ident" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" [[package]] name = "vergen-lib" version = "9.1.0" dependencies = [ "anyhow", "derive_builder", "rustversion", "serial_test", "temp-env", ] [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" vergen-lib-9.1.0/Cargo.toml0000644000000041051046102023000111150ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2024" rust-version = "1.88.0" name = "vergen-lib" version = "9.1.0" authors = ["Jason Ozias "] build = "build.rs" autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Common code used to support the vergen libraries" homepage = "https://github.com/rustyhorde/vergen" documentation = "https://docs.rs/vergen-lib" readme = "README.md" keywords = [ "cargo", "instructions", "build", "tool", ] categories = [ "development-tools", "development-tools::build-utils", ] license = "MIT OR Apache-2.0" repository = "https://github.com/rustyhorde/vergen" resolver = "2" [[package.metadata.cargo-matrix.channel]] name = "default" always_deny = ["unstable"] [[package.metadata.cargo-matrix.channel]] name = "nightly" always_deny = [] always_include = ["unstable"] [[package.metadata.cargo-matrix.channel]] name = "llvm-cov" always_deny = ["emit_and_set"] always_include = ["unstable"] [package.metadata.docs.rs] features = [ "build", "cargo", "git", "rustc", "si", ] rustdoc-args = [ "--cfg", "docsrs", ] [features] build = [] cargo = [] default = [] emit_and_set = [] git = [] rustc = [] si = [] unstable = [] [lib] name = "vergen_lib" path = "src/lib.rs" [dependencies.anyhow] version = "1.0.100" [dependencies.derive_builder] version = "0.20.2" [dev-dependencies.serial_test] version = "3.3.1" [dev-dependencies.temp-env] version = "0.3.6" [build-dependencies.rustversion] version = "1.0.22" [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = ["cfg(coverage,coverage_nightly)"] vergen-lib-9.1.0/Cargo.toml.orig000064400000000000000000000026211046102023000145550ustar 00000000000000[package] authors = ["Jason Ozias "] categories = ["development-tools", "development-tools::build-utils"] description = "Common code used to support the vergen libraries" documentation = "https://docs.rs/vergen-lib" edition = "2024" homepage = "https://github.com/rustyhorde/vergen" keywords = ["cargo", "instructions", "build", "tool"] license = "MIT OR Apache-2.0" rust-version = "1.88.0" name = "vergen-lib" readme = "README.md" repository = "https://github.com/rustyhorde/vergen" version = "9.1.0" [package.metadata.cargo-matrix] [[package.metadata.cargo-matrix.channel]] name = "default" always_deny = ["unstable"] [[package.metadata.cargo-matrix.channel]] name = "nightly" always_deny = [] always_include = ["unstable"] [[package.metadata.cargo-matrix.channel]] name = "llvm-cov" always_deny = ["emit_and_set"] always_include = ["unstable"] [features] default = [] build = [] cargo = [] emit_and_set = [] git = [] rustc = [] unstable = [] si = [] [dependencies] anyhow = "1.0.100" derive_builder = "0.20.2" [build-dependencies] rustversion = "1.0.22" [dev-dependencies] serial_test = "3.3.1" temp-env = "0.3.6" test_util = { path = "../test_util", features = ["unstable"] } [package.metadata.docs.rs] features = ["build", "cargo", "git", "rustc", "si"] rustdoc-args = ["--cfg", "docsrs"] [lints.rust] unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage,coverage_nightly)'] }vergen-lib-9.1.0/LICENSE-APACHE000064400000000000000000000251411046102023000136140ustar 00000000000000 Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. vergen-lib-9.1.0/LICENSE-MIT000064400000000000000000000020571046102023000133250ustar 00000000000000Copyright (c) 2016 The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. vergen-lib-9.1.0/README.md000064400000000000000000000000771046102023000131500ustar 00000000000000# vergen-lib - Common code used to support the vergen librariesvergen-lib-9.1.0/build.rs000064400000000000000000000004741046102023000133370ustar 00000000000000pub fn main() { println!("cargo:rerun-if-changed=build.rs"); nightly(); } #[rustversion::nightly] fn nightly() { println!("cargo:rustc-check-cfg=cfg(nightly)"); println!("cargo:rustc-cfg=nightly"); } #[rustversion::not(nightly)] fn nightly() { println!("cargo:rustc-check-cfg=cfg(nightly)"); } vergen-lib-9.1.0/src/constants.rs000064400000000000000000000204421046102023000150400ustar 00000000000000// Copyright (c) 2022 vergen developers // // Licensed under the Apache License, Version 2.0 // or the MIT // license , at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. //! Internal Constants /// The default idempotent output string pub const VERGEN_IDEMPOTENT_DEFAULT: &str = "VERGEN_IDEMPOTENT_OUTPUT"; #[cfg(any( feature = "build", feature = "cargo", feature = "git", feature = "rustc", feature = "si" ))] pub use self::features::*; /// The names used by [`crate::VergenKey`] for each enabled output #[cfg(any( feature = "build", feature = "cargo", feature = "git", feature = "rustc", feature = "si" ))] pub mod features { /// The timestamp of the current build #[cfg(feature = "build")] pub const BUILD_TIMESTAMP_NAME: &str = "VERGEN_BUILD_TIMESTAMP"; /// The date of the current build #[cfg(feature = "build")] pub const BUILD_DATE_NAME: &str = "VERGEN_BUILD_DATE"; /// The current branch name #[cfg(feature = "git")] pub const GIT_BRANCH_NAME: &str = "VERGEN_GIT_BRANCH"; /// The most recent commit author email address #[cfg(feature = "git")] pub const GIT_COMMIT_AUTHOR_EMAIL: &str = "VERGEN_GIT_COMMIT_AUTHOR_EMAIL"; /// The most recent commit author name #[cfg(feature = "git")] pub const GIT_COMMIT_AUTHOR_NAME: &str = "VERGEN_GIT_COMMIT_AUTHOR_NAME"; /// The commit count #[cfg(feature = "git")] pub const GIT_COMMIT_COUNT: &str = "VERGEN_GIT_COMMIT_COUNT"; /// The most recent commit message #[cfg(feature = "git")] pub const GIT_COMMIT_MESSAGE: &str = "VERGEN_GIT_COMMIT_MESSAGE"; /// The most recent commit date #[cfg(feature = "git")] pub const GIT_COMMIT_DATE_NAME: &str = "VERGEN_GIT_COMMIT_DATE"; /// The most recent commit timestamp #[cfg(feature = "git")] pub const GIT_COMMIT_TIMESTAMP_NAME: &str = "VERGEN_GIT_COMMIT_TIMESTAMP"; /// The output of git describe #[cfg(feature = "git")] pub const GIT_DESCRIBE_NAME: &str = "VERGEN_GIT_DESCRIBE"; /// The most recent commit SHA #[cfg(feature = "git")] pub const GIT_SHA_NAME: &str = "VERGEN_GIT_SHA"; /// The current dirty status #[cfg(feature = "git")] pub const GIT_DIRTY_NAME: &str = "VERGEN_GIT_DIRTY"; /// The channel of rustc used for the build (stable, beta, nightly) #[cfg(feature = "rustc")] pub const RUSTC_CHANNEL_NAME: &str = "VERGEN_RUSTC_CHANNEL"; /// The host triple of rustc used for the build #[cfg(feature = "rustc")] pub const RUSTC_HOST_TRIPLE_NAME: &str = "VERGEN_RUSTC_HOST_TRIPLE"; /// The version of rustc used for the build #[cfg(feature = "rustc")] pub const RUSTC_SEMVER_NAME: &str = "VERGEN_RUSTC_SEMVER"; /// The commit hash of rustc used for the build #[cfg(feature = "rustc")] pub const RUSTC_COMMIT_HASH: &str = "VERGEN_RUSTC_COMMIT_HASH"; /// The commit date of rustc used for the build #[cfg(feature = "rustc")] pub const RUSTC_COMMIT_DATE: &str = "VERGEN_RUSTC_COMMIT_DATE"; /// The LLVM version underlying rustc used for the build (if applicable) #[cfg(feature = "rustc")] pub const RUSTC_LLVM_VERSION: &str = "VERGEN_RUSTC_LLVM_VERSION"; /// The value of the `DEBUG` environment variable at build time #[cfg(feature = "cargo")] pub const CARGO_DEBUG: &str = "VERGEN_CARGO_DEBUG"; /// The current dependency list (potentiall filtered) #[cfg(feature = "cargo")] pub const CARGO_DEPENDENCIES: &str = "VERGEN_CARGO_DEPENDENCIES"; /// The value of the `CARGO_FEATURES` environment variable at build time #[cfg(feature = "cargo")] pub const CARGO_FEATURES: &str = "VERGEN_CARGO_FEATURES"; /// The value of the `OPT_LEVEL` environment variable at build time #[cfg(feature = "cargo")] pub const CARGO_OPT_LEVEL: &str = "VERGEN_CARGO_OPT_LEVEL"; /// The value of the `TARGET_TRIPLE` environment variable at build time #[cfg(feature = "cargo")] pub const CARGO_TARGET_TRIPLE: &str = "VERGEN_CARGO_TARGET_TRIPLE"; /// The system name #[cfg(feature = "si")] pub const SYSINFO_NAME: &str = "VERGEN_SYSINFO_NAME"; /// The OS version #[cfg(feature = "si")] pub const SYSINFO_OS_VERSION: &str = "VERGEN_SYSINFO_OS_VERSION"; /// The user that ran the build #[cfg(feature = "si")] pub const SYSINFO_USER: &str = "VERGEN_SYSINFO_USER"; /// The total memory on the system used to run the build #[cfg(feature = "si")] pub const SYSINFO_MEMORY: &str = "VERGEN_SYSINFO_TOTAL_MEMORY"; /// The CPU vender on the system used to run the build #[cfg(feature = "si")] pub const SYSINFO_CPU_VENDOR: &str = "VERGEN_SYSINFO_CPU_VENDOR"; /// The CPU core count on the system use to run the build #[cfg(feature = "si")] pub const SYSINFO_CPU_CORE_COUNT: &str = "VERGEN_SYSINFO_CPU_CORE_COUNT"; /// The CPU name on the system use to run the build #[cfg(feature = "si")] pub const SYSINFO_CPU_NAME: &str = "VERGEN_SYSINFO_CPU_NAME"; /// The CPU brand on the system use to run the build #[cfg(feature = "si")] pub const SYSINFO_CPU_BRAND: &str = "VERGEN_SYSINFO_CPU_BRAND"; /// The CPU frequency on the system use to run the build #[cfg(feature = "si")] pub const SYSINFO_CPU_FREQUENCY: &str = "VERGEN_SYSINFO_CPU_FREQUENCY"; } /// An empty list of names to use with [`crate::VergenKey`] when /// no features are enabled. #[cfg(not(any( feature = "build", feature = "cargo", feature = "git", feature = "rustc", feature = "si" )))] pub mod features {} #[cfg(all( test, any( feature = "build", feature = "cargo", feature = "git", feature = "rustc", feature = "si" ) ))] mod test { use super::*; #[cfg(feature = "build")] #[test] fn build_constants_dont_change() { // Build Constants assert_eq!(BUILD_TIMESTAMP_NAME, "VERGEN_BUILD_TIMESTAMP"); assert_eq!(BUILD_DATE_NAME, "VERGEN_BUILD_DATE"); } #[cfg(feature = "cargo")] #[test] fn cargo_constants_dont_change() { // cargo Constants assert_eq!(CARGO_TARGET_TRIPLE, "VERGEN_CARGO_TARGET_TRIPLE"); assert_eq!(CARGO_FEATURES, "VERGEN_CARGO_FEATURES"); } #[cfg(feature = "git")] #[test] fn git_constants_dont_change() { // git Constants assert_eq!(GIT_BRANCH_NAME, "VERGEN_GIT_BRANCH"); assert_eq!(GIT_COMMIT_AUTHOR_EMAIL, "VERGEN_GIT_COMMIT_AUTHOR_EMAIL"); assert_eq!(GIT_COMMIT_AUTHOR_NAME, "VERGEN_GIT_COMMIT_AUTHOR_NAME"); assert_eq!(GIT_COMMIT_COUNT, "VERGEN_GIT_COMMIT_COUNT"); assert_eq!(GIT_COMMIT_MESSAGE, "VERGEN_GIT_COMMIT_MESSAGE"); assert_eq!(GIT_COMMIT_DATE_NAME, "VERGEN_GIT_COMMIT_DATE"); assert_eq!(GIT_COMMIT_TIMESTAMP_NAME, "VERGEN_GIT_COMMIT_TIMESTAMP"); assert_eq!(GIT_DESCRIBE_NAME, "VERGEN_GIT_DESCRIBE"); assert_eq!(GIT_SHA_NAME, "VERGEN_GIT_SHA"); assert_eq!(GIT_DIRTY_NAME, "VERGEN_GIT_DIRTY"); } #[cfg(feature = "rustc")] #[test] fn rustc_constants_dont_change() { // rustc Constants assert_eq!(RUSTC_SEMVER_NAME, "VERGEN_RUSTC_SEMVER"); assert_eq!(RUSTC_CHANNEL_NAME, "VERGEN_RUSTC_CHANNEL"); assert_eq!(RUSTC_HOST_TRIPLE_NAME, "VERGEN_RUSTC_HOST_TRIPLE"); assert_eq!(RUSTC_COMMIT_HASH, "VERGEN_RUSTC_COMMIT_HASH"); assert_eq!(RUSTC_COMMIT_DATE, "VERGEN_RUSTC_COMMIT_DATE"); assert_eq!(RUSTC_LLVM_VERSION, "VERGEN_RUSTC_LLVM_VERSION"); } #[cfg(feature = "si")] #[test] fn sysinfo_constants_dont_change() { // sysinfo Constants assert_eq!(SYSINFO_NAME, "VERGEN_SYSINFO_NAME"); assert_eq!(SYSINFO_OS_VERSION, "VERGEN_SYSINFO_OS_VERSION"); assert_eq!(SYSINFO_USER, "VERGEN_SYSINFO_USER"); assert_eq!(SYSINFO_MEMORY, "VERGEN_SYSINFO_TOTAL_MEMORY"); assert_eq!(SYSINFO_CPU_VENDOR, "VERGEN_SYSINFO_CPU_VENDOR"); assert_eq!(SYSINFO_CPU_CORE_COUNT, "VERGEN_SYSINFO_CPU_CORE_COUNT"); assert_eq!(SYSINFO_CPU_NAME, "VERGEN_SYSINFO_CPU_NAME"); assert_eq!(SYSINFO_CPU_BRAND, "VERGEN_SYSINFO_CPU_BRAND"); assert_eq!(SYSINFO_CPU_FREQUENCY, "VERGEN_SYSINFO_CPU_FREQUENCY"); } } vergen-lib-9.1.0/src/emitter.rs000064400000000000000000000412301046102023000144730ustar 00000000000000// Copyright (c) 2022 vergen developers // // Licensed under the Apache License, Version 2.0 // or the MIT // license , at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. use crate::{AddCustomEntries, AddEntries, CargoRustcEnvMap, DefaultConfig}; use anyhow::Result; use std::{ collections::BTreeMap, env, io::{self, Write}, }; /// The `Emitter` will emit cargo instructions (i.e. cargo:rustc-env=NAME=VALUE) /// base on the configuration you enable. #[derive(Clone, Debug, PartialEq)] pub struct Emitter { idempotent: bool, fail_on_error: bool, quiet: bool, custom_buildrs: Option<&'static str>, #[doc(hidden)] cargo_rustc_env_map: CargoRustcEnvMap, #[doc(hidden)] cargo_rustc_env_map_custom: BTreeMap, #[doc(hidden)] cargo_rerun_if_changed: Vec, #[doc(hidden)] cargo_warning: Vec, } impl Default for Emitter { fn default() -> Self { Self::new() } } impl Emitter { #[doc(hidden)] #[must_use] pub fn cargo_rustc_env_map(&self) -> &CargoRustcEnvMap { &self.cargo_rustc_env_map } #[doc(hidden)] #[must_use] pub fn cargo_rustc_env_map_custom(&self) -> &BTreeMap { &self.cargo_rustc_env_map_custom } #[doc(hidden)] #[must_use] pub fn cargo_rerun_if_changed(&self) -> &Vec { &self.cargo_rerun_if_changed } #[doc(hidden)] #[must_use] pub fn cargo_warning(&self) -> &Vec { &self.cargo_warning } /// Instantiate the builder to configure the cargo instruction emits #[must_use] pub fn new() -> Self { Self { idempotent: matches!(env::var("VERGEN_IDEMPOTENT"), Ok(_val)), fail_on_error: false, quiet: false, custom_buildrs: None, cargo_rustc_env_map: CargoRustcEnvMap::default(), cargo_rustc_env_map_custom: BTreeMap::default(), cargo_rerun_if_changed: Vec::default(), cargo_warning: Vec::default(), } } /// Enable the `idempotent` feature /// /// **NOTE** - This feature can also be enabled via the `VERGEN_IDEMPOTENT` /// environment variable. /// /// When this feature is enabled, certain vergen output (i.e. timestamps, sysinfo) /// will be set to an idempotent default. This will allow systems that /// depend on deterministic builds to override user requested `vergen` /// impurities. This will mainly allow for package maintainers to build /// packages that depend on `vergen` in a deterministic manner. /// /// See [this issue](https://github.com/rustyhorde/vergen/issues/141) for /// more details /// /// | Variable | Sample | /// | ------- | ------ | /// | `VERGEN_BUILD_DATE` | `VERGEN_IDEMPOTENT_OUTPUT` | /// | `VERGEN_BUILD_TIMESTAMP` | `VERGEN_IDEMPOTENT_OUTPUT` | /// /// # Example /// /// ``` /// # use anyhow::Result; /// # use vergen_lib::Emitter; /// # /// # fn main() -> Result<()> { /// Emitter::new().idempotent().emit()?; /// // or /// # temp_env::with_var("VERGEN_IDEMPOTENT", Some("true"), || { /// # let result = || -> Result<()> { /// // set::env("VERGEN_IDEMPOTENT", "true"); /// Emitter::new().emit()?; /// # Ok(()) /// # }(); /// # }); /// # Ok(()) /// # } /// ``` /// pub fn idempotent(&mut self) -> &mut Self { self.idempotent = true; self } /// Enable the `fail_on_error` feature /// /// By default `vergen` will emit the instructions you requested. If for some /// reason those instructions cannot be generated correctly, placeholder values /// will be used instead. `vergen` will also emit [`cargo:warning`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) /// instructions notifying you this has happened. /// /// For example, if you configure `vergen` to emit `VERGEN_GIT_*` instructions and /// you run a build from a source tarball with no `.git` directory, the instructions /// will be populated with placeholder values, rather than information gleaned through git. /// /// You can turn off this behavior by enabling `fail_on_error`. /// /// # Example /// /// ``` /// # use anyhow::Result; /// # use vergen_lib::Emitter; /// # /// # fn main() -> Result<()> { /// Emitter::new().fail_on_error().emit()?; /// # Ok(()) /// # } /// ``` pub fn fail_on_error(&mut self) -> &mut Self { self.fail_on_error = true; self } /// Enable the quiet feature /// /// Suppress the emission of the `cargo:warning` instructions. /// /// # Example /// /// ``` /// # use anyhow::Result; /// # use vergen_lib::Emitter; /// # /// # fn main() -> Result<()> { /// Emitter::new().quiet().emit()?; /// # Ok(()) /// # } /// ``` pub fn quiet(&mut self) -> &mut Self { self.quiet = true; self } /// Set a custom build.rs path if you are using a non-standard path /// /// By default `vergen` will use `build.rs` as the build path for the /// `cargo:rerun-if-changed` emit. You can specify a custom `build.rs` /// path here if you have changed this default /// /// # Example /// /// ``` /// # use anyhow::Result; /// # use vergen_lib::Emitter; /// # /// # fn main() -> Result<()> { /// Emitter::new().custom_build_rs("my/custom/build.rs").emit()?; /// # Ok(()) /// # } /// ``` pub fn custom_build_rs(&mut self, path: &'static str) -> &mut Self { self.custom_buildrs = Some(path); self } /// Add a set of instructions to the emitter output /// /// # Errors /// pub fn add_instructions(&mut self, generator: &dyn AddEntries) -> Result<&mut Self> { generator .add_map_entries( self.idempotent, &mut self.cargo_rustc_env_map, &mut self.cargo_rerun_if_changed, &mut self.cargo_warning, ) .or_else(|e| { let default_config = DefaultConfig::new(self.fail_on_error, e); generator.add_default_entries( &default_config, &mut self.cargo_rustc_env_map, &mut self.cargo_rerun_if_changed, &mut self.cargo_warning, ) })?; Ok(self) } /// Add a set of custom instructions to the emitter output /// /// # Errors /// /// Errors may be generated if `fail_on_error` has been configured. /// pub fn add_custom_instructions( &mut self, generator: &impl AddCustomEntries, ) -> Result<&mut Self> where K: Into + Ord, V: Into, { let mut map = BTreeMap::default(); generator .add_calculated_entries( self.idempotent, &mut map, &mut self.cargo_rerun_if_changed, &mut self.cargo_warning, ) .or_else(|e| { let default_config = DefaultConfig::new(self.fail_on_error, e); generator.add_default_entries( &default_config, &mut map, &mut self.cargo_rerun_if_changed, &mut self.cargo_warning, ) })?; self.cargo_rustc_env_map_custom.extend(Self::map_into(map)); Ok(self) } fn map_into(map: BTreeMap) -> impl Iterator where K: Into + Ord, V: Into, { map.into_iter().map(|(k, v)| (k.into(), v.into())) } fn emit_output(&self, stdout: &mut T) -> Result<()> where T: Write, { self.emit_instructions(stdout) } fn emit_instructions(&self, stdout: &mut T) -> Result<()> where T: Write, { // Emit the 'cargo:rustc-env' instructions for (k, v) in &self.cargo_rustc_env_map { let sanitized_value = Self::filter_newlines(v); writeln!(stdout, "cargo:rustc-env={}={sanitized_value}", k.name())?; } // Emit the 'cargo:rustc-env' custom instructions for (k, v) in &self.cargo_rustc_env_map_custom { let sanitized_value = Self::filter_newlines(v); writeln!(stdout, "cargo:rustc-env={k}={sanitized_value}")?; } // Emit the `cargo:warning` instructions if !self.quiet { for warning in &self.cargo_warning { let sanitized_output = Self::filter_newlines(warning); writeln!(stdout, "cargo:warning={sanitized_output}")?; } } // Emit the 'cargo:rerun-if-changed' instructions for the git paths (if added) for path in &self.cargo_rerun_if_changed { let sanitized_output = Self::filter_newlines(path); writeln!(stdout, "cargo:rerun-if-changed={sanitized_output}")?; } // Emit the 'cargo:rerun-if-changed' instructions if !self.cargo_rustc_env_map.is_empty() || !self.cargo_warning.is_empty() { let buildrs = self.custom_buildrs.unwrap_or("build.rs"); let sanitized_output = Self::filter_newlines(buildrs); writeln!(stdout, "cargo:rerun-if-changed={sanitized_output}")?; writeln!(stdout, "cargo:rerun-if-env-changed=VERGEN_IDEMPOTENT")?; writeln!(stdout, "cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH")?; } Ok(()) } fn filter_newlines(s: &str) -> String { s.chars().filter(|c| *c != '\n').collect() } /// Emit cargo instructions from your build script /// /// - Will emit [`cargo:rustc-env=VAR=VALUE`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-envvarvalue) for each feature you have enabled. /// - Will emit [`cargo:rerun-if-changed=PATH`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed) if the git feature is enabled. This is done to ensure any git variables are regenerated when commits are made. /// - Can emit [`cargo:warning`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) outputs if the /// [`fail_on_error`](Self::fail_on_error) feature is not enabled and the requested variable is defaulted through error or /// the [`idempotent`](Self::idempotent) flag. /// /// # Errors /// * The [`writeln!`](std::writeln!) macro can throw a [`std::io::Error`] /// /// # Example /// /// ``` /// # use anyhow::Result; /// # use std::env; /// # use vergen_lib::Emitter; /// # /// # fn main() -> Result<()> { /// let emitter = Emitter::default().emit()?; /// # Ok(()) /// # } /// ``` /// /// # Sample Output /// /// **NOTE** - You won't see this output unless you invoke cargo with the `-vv` flag. /// The instruction output is not displayed by default. /// /// ```text /// cargo:rustc-env=VERGEN_BUILD_DATE=2023-01-04 /// cargo:rustc-env=VERGEN_BUILD_TIMESTAMP=2023-01-04T15:38:11.097507114Z /// cargo:rustc-env=VERGEN_CARGO_DEBUG=true /// cargo:rustc-env=VERGEN_CARGO_FEATURES=build,git /// cargo:rustc-env=VERGEN_CARGO_OPT_LEVEL=1 /// cargo:rustc-env=VERGEN_CARGO_TARGET_TRIPLE=x86_64-unknown-linux-gnu /// cargo:rustc-env=VERGEN_GIT_BRANCH=feature/version8 /// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_EMAIL=your@email.com /// cargo:rustc-env=VERGEN_GIT_COMMIT_AUTHOR_NAME=Yoda /// cargo:rustc-env=VERGEN_GIT_COMMIT_COUNT=476 /// cargo:rustc-env=VERGEN_GIT_COMMIT_DATE=2023-01-03 /// cargo:rustc-env=VERGEN_GIT_COMMIT_MESSAGE=The best message /// cargo:rustc-env=VERGEN_GIT_COMMIT_TIMESTAMP=2023-01-03T14:08:12.000000000-05:00 /// cargo:rustc-env=VERGEN_GIT_DESCRIBE=7.4.4-103-g53ae8a6 /// cargo:rustc-env=VERGEN_GIT_SHA=53ae8a69ab7917a2909af40f2e5d015f5b29ae28 /// cargo:rustc-env=VERGEN_RUSTC_CHANNEL=nightly /// cargo:rustc-env=VERGEN_RUSTC_COMMIT_DATE=2023-01-03 /// cargo:rustc-env=VERGEN_RUSTC_COMMIT_HASH=c7572670a1302f5c7e245d069200e22da9df0316 /// cargo:rustc-env=VERGEN_RUSTC_HOST_TRIPLE=x86_64-unknown-linux-gnu /// cargo:rustc-env=VERGEN_RUSTC_LLVM_VERSION=15.0 /// cargo:rustc-env=VERGEN_RUSTC_SEMVER=1.68.0-nightly /// cargo:rustc-env=VERGEN_SYSINFO_NAME=Arch Linux /// cargo:rustc-env=VERGEN_SYSINFO_OS_VERSION=Linux Arch Linux /// cargo:rustc-env=VERGEN_SYSINFO_USER=jozias /// cargo:rustc-env=VERGEN_SYSINFO_TOTAL_MEMORY=31 GiB /// cargo:rustc-env=VERGEN_SYSINFO_CPU_VENDOR=AuthenticAMD /// cargo:rustc-env=VERGEN_SYSINFO_CPU_CORE_COUNT=8 /// cargo:rustc-env=VERGEN_SYSINFO_CPU_NAME=cpu0,cpu1,cpu2,cpu3,cpu4,cpu5,cpu6,cpu7 /// cargo:rustc-env=VERGEN_SYSINFO_CPU_BRAND=AMD Ryzen Threadripper 1900X 8-Core Processor /// cargo:rustc-env=VERGEN_SYSINFO_CPU_FREQUENCY=3792 /// cargo:rerun-if-changed=.git/HEAD /// cargo:rerun-if-changed=.git/refs/heads/feature/version8 /// cargo:rerun-if-changed=build.rs /// cargo:rerun-if-env-changed=VERGEN_IDEMPOTENT /// cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH /// ``` /// pub fn emit(&self) -> Result<()> { self.emit_output(&mut io::stdout()) } /// Emit cargo instructions from your build script and set environment variables for use in `build.rs` /// /// - Will emit [`cargo:rustc-env=VAR=VALUE`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-envvarvalue) for each feature you have enabled. /// - Will emit [`cargo:rerun-if-changed=PATH`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#rerun-if-changed) if the git feature is enabled. This is done to ensure any git variables are regenerated when commits are made. /// - Can emit [`cargo:warning`](https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargo-warning) outputs if the /// [`fail_on_error`](Self::fail_on_error) feature is not enabled and the requested variable is defaulted through error or /// the [`idempotent`](Self::idempotent) flag. /// /// # Errors /// * The [`writeln!`](std::writeln!) macro can throw a [`std::io::Error`] /// /// # Example /// /// ``` /// # use anyhow::Result; /// # use std::env; /// # use vergen_lib::Emitter; /// # /// # fn main() -> Result<()> { /// Emitter::new().emit_and_set()?; /// # Ok(()) /// # } /// ``` /// #[cfg(feature = "emit_and_set")] #[cfg_attr(coverage_nightly, coverage(off))] #[allow(unsafe_code)] pub fn emit_and_set(&self) -> Result<()> { self.emit_output(&mut io::stdout()).map(|()| { for (k, v) in &self.cargo_rustc_env_map { if env::var(k.name()).is_err() { unsafe { env::set_var(k.name(), v); } } } }) } #[doc(hidden)] /// Emit the cargo build script instructions to the given [`Write`](std::io::Write). /// /// **NOTE** - This is generally only used for testing and probably shouldn't be used /// within a `build.rs` file. /// /// # Errors /// * The [`writeln!`](std::writeln!) macro can throw a [`std::io::Error`] /// pub fn emit_to(&self, stdout: &mut T) -> Result where T: Write, { self.emit_output(stdout).map(|()| false) } #[doc(hidden)] #[must_use] pub fn test_emit(&self) -> Emitter { self.clone() } } #[cfg(test)] pub(crate) mod test { use super::Emitter; use anyhow::Result; use serial_test::serial; use std::io::Write; #[test] #[serial] #[allow(clippy::clone_on_copy, clippy::redundant_clone)] fn emitter_clone_works() { let emitter = Emitter::default(); let another = emitter.clone(); assert_eq!(another, emitter); } #[test] #[serial] fn emitter_debug_works() -> Result<()> { let emitter = Emitter::default(); let mut buf = vec![]; write!(buf, "{emitter:?}")?; assert!(!buf.is_empty()); Ok(()) } #[test] #[serial] fn default_is_no_emit() -> Result<()> { let mut stdout_buf = vec![]; _ = Emitter::new().emit_to(&mut stdout_buf)?; assert!(stdout_buf.is_empty()); Ok(()) } #[test] #[serial] fn default_emit_is_ok() { assert!(Emitter::new().emit().is_ok()); } } vergen-lib-9.1.0/src/entries.rs000064400000000000000000000206451046102023000145020ustar 00000000000000use crate::VergenKey; use anyhow::{Error, Result}; use std::collections::BTreeMap; /// The map used to emit `cargo:rustc-env=NAME=VALUE` cargo instructions pub type CargoRustcEnvMap = BTreeMap; /// The vector of strings used to emit `cargo:rerun-if-changed=VALUE` cargo instructions pub type CargoRerunIfChanged = Vec; /// The vector of strings used to emit `cargo:warning=VALUE` cargo instructions pub type CargoWarning = Vec; /// The default configuration to use when an issue has occured generating instructions #[derive(Debug)] pub struct DefaultConfig { /// Should we fail if an error occurs or output idempotent values on error? fail_on_error: bool, /// The error that caused us to try default instruction output. error: Error, } impl DefaultConfig { /// Create a new [`DefaultConfig`] struct with the given values. #[must_use] pub fn new(fail_on_error: bool, error: Error) -> Self { Self { fail_on_error, error, } } /// Should we fail if an error occurs or output idempotent values on error? #[must_use] pub fn fail_on_error(&self) -> &bool { &self.fail_on_error } /// The error that caused us to try default instruction output. #[must_use] pub fn error(&self) -> &Error { &self.error } } /// This trait should be implemented to allow the `vergen` emitter /// to properly emit instructions for your feature. pub trait Add { /// Try to add instructions entries to the various given arguments. /// /// * Write to the `cargo_rustc_env` map to emit 'cargo:rustc-env=NAME=VALUE' instructions. /// * Write to the `cargo_rerun_if_changed` vector to emit 'cargo:rerun-if-changed=VALUE' instructions. /// * Write to the `cargo_warning` vector to emit 'cargo:warning=VALUE' instructions. /// /// # Errors /// /// If an error occurs, the `vergen` emitter will use `add_default_entries` to generate output. /// This assumes generating instructions may fail in some manner so a [`anyhow::Result`] is returned. /// fn add_map_entries( &self, idempotent: bool, cargo_rustc_env: &mut CargoRustcEnvMap, cargo_rerun_if_changed: &mut CargoRerunIfChanged, cargo_warning: &mut CargoWarning, ) -> Result<()>; /// Based on the given configuration, emit either default idempotent output or generate a failue. /// /// * Write to the `cargo_rustc_env` map to emit 'cargo:rustc-env=NAME=VALUE' instructions. /// * Write to the `cargo_rerun_if_changed` vector to emit 'cargo:rerun-if-changed=VALUE' instructions. /// * Write to the `cargo_warning` vector to emit 'cargo:warning=VALUE' instructions. /// /// # Errors /// /// This assumes generating instructions may fail in some manner so a [`anyhow::Result`] is returned. /// fn add_default_entries( &self, config: &DefaultConfig, cargo_rustc_env_map: &mut CargoRustcEnvMap, cargo_rerun_if_changed: &mut CargoRerunIfChanged, cargo_warning: &mut CargoWarning, ) -> Result<()>; } /// This trait should be implemented to allow the `vergen` emitter to properly emit your custom instructions. /// /// # Example /// ``` /// # use anyhow::Result; /// # use std::collections::BTreeMap; /// # use vergen_lib::{AddCustomEntries, CargoRerunIfChanged, CargoWarning, DefaultConfig}; /// #[derive(Default)] /// struct Custom {} /// /// impl AddCustomEntries<&str, &str> for Custom { /// fn add_calculated_entries( /// &self, /// _idempotent: bool, /// cargo_rustc_env_map: &mut BTreeMap<&str, &str>, /// _cargo_rerun_if_changed: &mut CargoRerunIfChanged, /// cargo_warning: &mut CargoWarning, /// ) -> Result<()> { /// cargo_rustc_env_map.insert("vergen-cl", "custom_instruction"); /// cargo_warning.push("custom instruction generated".to_string()); /// Ok(()) /// } /// /// fn add_default_entries( /// &self, /// _config: &DefaultConfig, /// _cargo_rustc_env_map: &mut BTreeMap<&str, &str>, /// _cargo_rerun_if_changed: &mut CargoRerunIfChanged, /// _cargo_warning: &mut CargoWarning, /// ) -> Result<()> { /// Ok(()) /// } /// } /// ``` /// ## Then in [`build.rs`] /// /// ```will_not_compile /// let build = BuildBuilder::all_build()?; /// let cargo = CargoBuilder::all_cargo()?; /// let gix = GixBuilder::all_git()?; /// let rustc = RustcBuilder::all_rustc()?; /// let si = SysinfoBuilder::all_sysinfo()?; /// Emitter::default() /// .add_instructions(&build)? /// .add_instructions(&cargo)? /// .add_instructions(&gix)? /// .add_instructions(&rustc)? /// .add_instructions(&si)? /// .add_custom_instructions(&Custom::default())? /// .emit() /// ``` pub trait AddCustom + Ord, V: Into> { /// Try to add instructions entries to the various given arguments. /// /// * Write to the `cargo_rustc_env` map to emit 'cargo:rustc-env=NAME=VALUE' instructions. /// * Write to the `cargo_rerun_if_changed` vector to emit 'cargo:rerun-if-changed=VALUE' instructions. /// * Write to the `cargo_warning` vector to emit 'cargo:warning=VALUE' instructions. /// /// # Errors /// /// If an error occurs, the `vergen` emitter will use `add_default_entries` to generate output. /// This assumes generating instructions may fail in some manner so a [`anyhow::Result`] is returned. /// fn add_calculated_entries( &self, idempotent: bool, cargo_rustc_env_map: &mut BTreeMap, cargo_rerun_if_changed: &mut CargoRerunIfChanged, cargo_warning: &mut CargoWarning, ) -> Result<()>; /// Based on the given configuration, emit either default idempotent output or generate a failue. /// /// * Write to the `cargo_rustc_env` map to emit 'cargo:rustc-env=NAME=VALUE' instructions. /// * Write to the `cargo_rerun_if_changed` vector to emit 'cargo:rerun-if-changed=VALUE' instructions. /// * Write to the `cargo_warning` vector to emit 'cargo:warning=VALUE' instructions. /// /// # Errors /// /// This assumes generating instructions may fail in some manner so a [`anyhow::Result`] is returned. /// fn add_default_entries( &self, config: &DefaultConfig, cargo_rustc_env_map: &mut BTreeMap, cargo_rerun_if_changed: &mut CargoRerunIfChanged, cargo_warning: &mut CargoWarning, ) -> Result<()>; } #[doc(hidden)] pub(crate) mod test_gen { use crate::{AddCustomEntries, CargoRerunIfChanged, CargoWarning}; use anyhow::{Result, anyhow}; use derive_builder::Builder; use std::collections::BTreeMap; #[doc(hidden)] #[derive(Builder, Clone, Copy, Debug, Default)] pub struct CustomInsGen { fail: bool, } impl AddCustomEntries<&str, &str> for CustomInsGen { fn add_calculated_entries( &self, idempotent: bool, cargo_rustc_env_map: &mut BTreeMap<&str, &str>, _cargo_rerun_if_changed: &mut CargoRerunIfChanged, _cargo_warning: &mut CargoWarning, ) -> Result<()> { if self.fail { Err(anyhow!("We have failed")) } else { if idempotent { let _ = cargo_rustc_env_map.insert("test", "VERGEN_IDEMPOTENT_OUTPUT"); } else { let _ = cargo_rustc_env_map.insert("test", "value"); } Ok(()) } } fn add_default_entries( &self, config: &crate::DefaultConfig, cargo_rustc_env_map: &mut BTreeMap<&str, &str>, _cargo_rerun_if_changed: &mut CargoRerunIfChanged, _cargo_warning: &mut CargoWarning, ) -> Result<()> { if *config.fail_on_error() { let error = anyhow!(format!("{}", config.error())); Err(error) } else { let _ = cargo_rustc_env_map.insert("test", "VERGEN_IDEMPOTENT_OUTPUT"); Ok(()) } } } } #[cfg(test)] mod test { use super::DefaultConfig; use anyhow::{Result, anyhow}; use std::io::Write; #[test] fn default_config_debug() -> Result<()> { let config = DefaultConfig::new(true, anyhow!("blah")); let mut buf = vec![]; write!(buf, "{config:?}")?; assert!(!buf.is_empty()); Ok(()) } } vergen-lib-9.1.0/src/keys.rs000064400000000000000000000304651046102023000140050ustar 00000000000000// Copyright (c) 2022 vergen developers // // Licensed under the Apache License, Version 2.0 // or the MIT // license , at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. /// The [`VergenKey`] enum to use based on the configured features. #[cfg(any( feature = "build", feature = "cargo", feature = "git", feature = "rustc", feature = "si" ))] pub(crate) mod vergen_key { #[cfg(feature = "build")] use crate::constants::{BUILD_DATE_NAME, BUILD_TIMESTAMP_NAME}; #[cfg(feature = "cargo")] use crate::constants::{ CARGO_DEBUG, CARGO_DEPENDENCIES, CARGO_FEATURES, CARGO_OPT_LEVEL, CARGO_TARGET_TRIPLE, }; #[cfg(feature = "git")] use crate::constants::{ GIT_BRANCH_NAME, GIT_COMMIT_AUTHOR_EMAIL, GIT_COMMIT_AUTHOR_NAME, GIT_COMMIT_COUNT, GIT_COMMIT_DATE_NAME, GIT_COMMIT_MESSAGE, GIT_COMMIT_TIMESTAMP_NAME, GIT_DESCRIBE_NAME, GIT_DIRTY_NAME, GIT_SHA_NAME, }; #[cfg(feature = "rustc")] use crate::constants::{ RUSTC_CHANNEL_NAME, RUSTC_COMMIT_DATE, RUSTC_COMMIT_HASH, RUSTC_HOST_TRIPLE_NAME, RUSTC_LLVM_VERSION, RUSTC_SEMVER_NAME, }; #[cfg(feature = "si")] use crate::constants::{ SYSINFO_CPU_BRAND, SYSINFO_CPU_CORE_COUNT, SYSINFO_CPU_FREQUENCY, SYSINFO_CPU_NAME, SYSINFO_CPU_VENDOR, SYSINFO_MEMORY, SYSINFO_NAME, SYSINFO_OS_VERSION, SYSINFO_USER, }; /// The keys used in the [`crate::CargoRustcEnvMap`] #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub enum VergenKey { /// The build date. (`VERGEN_BUILD_DATE`) #[cfg(feature = "build")] BuildDate, /// The build timestamp. (`VERGEN_BUILD_TIMESTAMP`) #[cfg(feature = "build")] BuildTimestamp, /// The cargo debug flag (`VERGEN_CARGO_DEBUG`) #[cfg(feature = "cargo")] CargoDebug, /// The cargo features (`VERGEN_CARGO_FEATURES`) #[cfg(feature = "cargo")] CargoFeatures, /// The cargo opt level (`VERGEN_CARGO_OPT_LEVEL`) #[cfg(feature = "cargo")] CargoOptLevel, /// The cargo target triple (`VERGEN_CARGO_TARGET_TRIPLE`) #[cfg(feature = "cargo")] CargoTargetTriple, /// The cargo dependencies (`VERGEN_CARGO_DEPENDENCIES`) #[cfg(feature = "cargo")] CargoDependencies, /// The current working branch name (`VERGEN_GIT_BRANCH`) #[cfg(feature = "git")] GitBranch, /// The commit author's email. (`VERGEN_GIT_COMMIT_AUTHOR_EMAIL`) #[cfg(feature = "git")] GitCommitAuthorEmail, /// The commit author's name. (`VERGEN_GIT_COMMIT_AUTHOR_NAME`) #[cfg(feature = "git")] GitCommitAuthorName, /// Number of commits in current branch. (`VERGEN_GIT_COMMIT_COUNT`) #[cfg(feature = "git")] GitCommitCount, /// The commit date. (`VERGEN_GIT_COMMIT_DATE`) #[cfg(feature = "git")] GitCommitDate, /// Commit message (`VERGEN_GIT_COMMIT_MESSAGE`) #[cfg(feature = "git")] GitCommitMessage, /// The commit timestamp. (`VERGEN_GIT_COMMIT_TIMESTAMP`) #[cfg(feature = "git")] GitCommitTimestamp, /// The semver version from the last git tag. (`VERGEN_GIT_SEMVER`) #[cfg(feature = "git")] GitDescribe, /// The latest commit SHA. (`VERGEN_GIT_SHA`) #[cfg(feature = "git")] GitSha, /// Whether the repository is dirty. (`VERGEN_GIT_DIRTY`) #[cfg(feature = "git")] GitDirty, /// The release channel of the rust compiler. (`VERGEN_RUSTC_CHANNEL`) #[cfg(feature = "rustc")] RustcChannel, /// The rustc commit date. (`VERGEN_RUSTC_COMMIT_DATE`) #[cfg(feature = "rustc")] RustcCommitDate, /// The rustc commit hash. (`VERGEN_RUSTC_COMMIT_HASH`) #[cfg(feature = "rustc")] RustcCommitHash, /// The host triple. (`VERGEN_HOST_TRIPLE`) #[cfg(feature = "rustc")] RustcHostTriple, /// The rustc LLVM version. (`VERGEN_RUSTC_LLVM_VERSION`) #[cfg(feature = "rustc")] RustcLlvmVersion, /// The version information of the rust compiler. (`VERGEN_RUSTC_SEMVER`) #[cfg(feature = "rustc")] RustcSemver, /// The sysinfo system name (`VERGEN_SYSINFO_NAME`) #[cfg(feature = "si")] SysinfoName, /// The sysinfo os version (`VERGEN_SYSINFO_OS_VERSION`) #[cfg(feature = "si")] SysinfoOsVersion, /// The sysinfo user name (`VERGEN_SYSINFO_USER`) #[cfg(feature = "si")] SysinfoUser, /// The sysinfo total memory (`VERGEN_SYSINFO_TOTAL_MEMORY`) #[cfg(feature = "si")] SysinfoMemory, /// The sysinfo cpu vendor (`VERGEN_SYSINFO_CPU_VENDOR`) #[cfg(feature = "si")] SysinfoCpuVendor, /// The sysinfo cpu core count (`VERGEN_SYSINFO_CPU_CORE_COUNT`) #[cfg(feature = "si")] SysinfoCpuCoreCount, /// The sysinfo cpu core count (`VERGEN_SYSINFO_CPU_NAME`) #[cfg(feature = "si")] SysinfoCpuName, /// The sysinfo cpu core count (`VERGEN_SYSINFO_CPU_BRAND`) #[cfg(feature = "si")] SysinfoCpuBrand, /// The sysinfo cpu core count (`VERGEN_SYSINFO_CPU_FREQUENCY`) #[cfg(feature = "si")] SysinfoCpuFrequency, } impl VergenKey { /// Get the name for the given key. #[must_use] pub fn name(self) -> &'static str { match self { #[cfg(feature = "build")] VergenKey::BuildDate => BUILD_DATE_NAME, #[cfg(feature = "build")] VergenKey::BuildTimestamp => BUILD_TIMESTAMP_NAME, #[cfg(feature = "cargo")] VergenKey::CargoDebug => CARGO_DEBUG, #[cfg(feature = "cargo")] VergenKey::CargoFeatures => CARGO_FEATURES, #[cfg(feature = "cargo")] VergenKey::CargoOptLevel => CARGO_OPT_LEVEL, #[cfg(feature = "cargo")] VergenKey::CargoTargetTriple => CARGO_TARGET_TRIPLE, #[cfg(feature = "cargo")] VergenKey::CargoDependencies => CARGO_DEPENDENCIES, #[cfg(feature = "git")] VergenKey::GitBranch => GIT_BRANCH_NAME, #[cfg(feature = "git")] VergenKey::GitCommitAuthorEmail => GIT_COMMIT_AUTHOR_EMAIL, #[cfg(feature = "git")] VergenKey::GitCommitAuthorName => GIT_COMMIT_AUTHOR_NAME, #[cfg(feature = "git")] VergenKey::GitCommitCount => GIT_COMMIT_COUNT, #[cfg(feature = "git")] VergenKey::GitCommitDate => GIT_COMMIT_DATE_NAME, #[cfg(feature = "git")] VergenKey::GitCommitMessage => GIT_COMMIT_MESSAGE, #[cfg(feature = "git")] VergenKey::GitCommitTimestamp => GIT_COMMIT_TIMESTAMP_NAME, #[cfg(feature = "git")] VergenKey::GitDescribe => GIT_DESCRIBE_NAME, #[cfg(feature = "git")] VergenKey::GitSha => GIT_SHA_NAME, #[cfg(feature = "git")] VergenKey::GitDirty => GIT_DIRTY_NAME, #[cfg(feature = "rustc")] VergenKey::RustcChannel => RUSTC_CHANNEL_NAME, #[cfg(feature = "rustc")] VergenKey::RustcCommitDate => RUSTC_COMMIT_DATE, #[cfg(feature = "rustc")] VergenKey::RustcCommitHash => RUSTC_COMMIT_HASH, #[cfg(feature = "rustc")] VergenKey::RustcHostTriple => RUSTC_HOST_TRIPLE_NAME, #[cfg(feature = "rustc")] VergenKey::RustcLlvmVersion => RUSTC_LLVM_VERSION, #[cfg(feature = "rustc")] VergenKey::RustcSemver => RUSTC_SEMVER_NAME, #[cfg(feature = "si")] VergenKey::SysinfoName => SYSINFO_NAME, #[cfg(feature = "si")] VergenKey::SysinfoOsVersion => SYSINFO_OS_VERSION, #[cfg(feature = "si")] VergenKey::SysinfoUser => SYSINFO_USER, #[cfg(feature = "si")] VergenKey::SysinfoMemory => SYSINFO_MEMORY, #[cfg(feature = "si")] VergenKey::SysinfoCpuVendor => SYSINFO_CPU_VENDOR, #[cfg(feature = "si")] VergenKey::SysinfoCpuCoreCount => SYSINFO_CPU_CORE_COUNT, #[cfg(feature = "si")] VergenKey::SysinfoCpuName => SYSINFO_CPU_NAME, #[cfg(feature = "si")] VergenKey::SysinfoCpuBrand => SYSINFO_CPU_BRAND, #[cfg(feature = "si")] VergenKey::SysinfoCpuFrequency => SYSINFO_CPU_FREQUENCY, } } } } /// The [`VergenKey`] enum to use when no features are configured. #[cfg(not(any( feature = "build", feature = "cargo", feature = "git", feature = "rustc", feature = "si" )))] pub(crate) mod vergen_key { /// The [`VergenKey`] enum to use when no features are configured. #[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub enum VergenKey { /// An empty vergen key Empty, } impl VergenKey { /// Get the name for the given key. #[must_use] pub fn name(self) -> &'static str { match self { VergenKey::Empty => "", } } } } #[cfg(all( test, not(any( feature = "build", feature = "cargo", feature = "git", feature = "rustc", feature = "si" )) ))] mod test { use super::vergen_key::VergenKey; use anyhow::Result; use std::{ cmp::Ordering, collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, io::Write, }; #[test] fn empty_name() { assert!(VergenKey::Empty.name().is_empty()); } #[test] #[allow(clippy::clone_on_copy, clippy::redundant_clone)] fn vergen_key_clone_works() { let key = VergenKey::Empty; let another = key.clone(); assert_eq!(another, key); } #[test] fn vergen_key_debug_works() -> Result<()> { let key = VergenKey::Empty; let mut buf = vec![]; write!(buf, "{key:?}")?; assert!(!buf.is_empty()); Ok(()) } #[test] fn vergen_key_ord_works() { assert_eq!(VergenKey::Empty.cmp(&VergenKey::Empty), Ordering::Equal); } #[test] fn vergen_key_partial_ord_works() { assert_eq!( VergenKey::Empty.partial_cmp(&VergenKey::Empty), Some(Ordering::Equal) ); } #[test] fn vergen_key_hash_works() { let mut hasher = DefaultHasher::new(); VergenKey::Empty.hash(&mut hasher); assert_eq!(15_130_871_412_783_076_140, hasher.finish()); } } #[cfg(all(test, all(feature = "build", feature = "cargo")))] mod test { use super::vergen_key::VergenKey; use anyhow::Result; use std::{ cmp::Ordering, collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, io::Write, }; #[test] #[allow(clippy::clone_on_copy, clippy::redundant_clone)] fn vergen_key_clone_works() { let key = VergenKey::BuildDate; let another = key.clone(); assert_eq!(another, key); } #[test] fn vergen_key_debug_works() -> Result<()> { let key = VergenKey::BuildDate; let mut buf = vec![]; write!(buf, "{key:?}")?; assert!(!buf.is_empty()); Ok(()) } #[test] fn vergen_key_ord_works() { assert_eq!( VergenKey::CargoDebug.cmp(&VergenKey::BuildDate), Ordering::Greater ); } #[test] fn vergen_key_partial_ord_works() { assert_eq!( VergenKey::CargoDebug.partial_cmp(&VergenKey::BuildDate), Some(Ordering::Greater) ); } #[test] fn vergen_key_hash_works() { let mut hasher = DefaultHasher::new(); VergenKey::BuildDate.hash(&mut hasher); assert_eq!(13_646_096_770_106_105_413, hasher.finish()); } } vergen-lib-9.1.0/src/lib.rs000064400000000000000000000201211046102023000135640ustar 00000000000000// Copyright (c) 2022 vergen developers // // Licensed under the Apache License, Version 2.0 // or the MIT // license , at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. //! # vergen-lib - Common structs, enums and constants used to support [`vergen`](https://docs.rs/vergen) //! // rustc lints #![cfg_attr( all(feature = "unstable", nightly), feature( multiple_supertrait_upcastable, must_not_suspend, non_exhaustive_omitted_patterns_lint, rustdoc_missing_doc_code_examples, strict_provenance_lints, supertrait_item_shadowing, unqualified_local_imports, ) )] #![cfg_attr(nightly, allow(single_use_lifetimes))] #![cfg_attr( nightly, deny( absolute_paths_not_starting_with_crate, ambiguous_glob_imports, ambiguous_glob_reexports, ambiguous_negative_literals, ambiguous_wide_pointer_comparisons, anonymous_parameters, array_into_iter, asm_sub_register, async_fn_in_trait, bad_asm_style, bare_trait_objects, boxed_slice_into_iter, break_with_label_and_loop, clashing_extern_declarations, closure_returning_async_block, coherence_leak_check, confusable_idents, const_evaluatable_unchecked, const_item_mutation, dangling_pointers_from_temporaries, dead_code, dependency_on_unit_never_type_fallback, deprecated, deprecated_in_future, deprecated_safe_2024, deprecated_where_clause_location, deref_into_dyn_supertrait, deref_nullptr, double_negations, drop_bounds, dropping_copy_types, dropping_references, duplicate_macro_attributes, dyn_drop, edition_2024_expr_fragment_specifier, elided_lifetimes_in_paths, ellipsis_inclusive_range_patterns, explicit_outlives_requirements, exported_private_dependencies, ffi_unwind_calls, forbidden_lint_groups, forgetting_copy_types, forgetting_references, for_loops_over_fallibles, function_item_references, hidden_glob_reexports, if_let_rescope, impl_trait_overcaptures, impl_trait_redundant_captures, improper_ctypes, improper_ctypes_definitions, inline_no_sanitize, internal_features, invalid_from_utf8, invalid_macro_export_arguments, invalid_nan_comparisons, invalid_value, irrefutable_let_patterns, keyword_idents_2018, keyword_idents_2024, large_assignments, late_bound_lifetime_arguments, legacy_derive_helpers, let_underscore_drop, macro_use_extern_crate, map_unit_fn, meta_variable_misuse, mismatched_lifetime_syntaxes, missing_abi, missing_copy_implementations, missing_debug_implementations, missing_docs, missing_unsafe_on_extern, mixed_script_confusables, named_arguments_used_positionally, never_type_fallback_flowing_into_unsafe, no_mangle_generic_items, non_ascii_idents, non_camel_case_types, non_contiguous_range_endpoints, non_fmt_panics, non_local_definitions, non_shorthand_field_patterns, non_snake_case, non_upper_case_globals, noop_method_call, opaque_hidden_inferred_bound, out_of_scope_macro_calls, overlapping_range_endpoints, path_statements, private_bounds, private_interfaces, ptr_to_integer_transmute_in_consts, redundant_imports, redundant_lifetimes, redundant_semicolons, refining_impl_trait_internal, refining_impl_trait_reachable, renamed_and_removed_lints, repr_transparent_non_zst_fields, rust_2021_incompatible_closure_captures, rust_2021_incompatible_or_patterns, rust_2021_prefixes_incompatible_syntax, rust_2021_prelude_collisions, rust_2024_guarded_string_incompatible_syntax, rust_2024_incompatible_pat, rust_2024_prelude_collisions, self_constructor_from_outer_item, semicolon_in_expressions_from_macros, single_use_lifetimes, special_module_name, stable_features, static_mut_refs, suspicious_double_ref_op, tail_expr_drop_order, trivial_bounds, trivial_casts, trivial_numeric_casts, type_alias_bounds, tyvar_behind_raw_pointer, uncommon_codepoints, unconditional_recursion, uncovered_param_in_projection, unexpected_cfgs, unfulfilled_lint_expectations, ungated_async_fn_track_caller, uninhabited_static, unit_bindings, unknown_lints, unknown_or_malformed_diagnostic_attributes, unnameable_test_items, unnameable_types, unpredictable_function_pointer_comparisons, unreachable_code, unreachable_patterns, unreachable_pub, unsafe_attr_outside_unsafe, unsafe_code, unsafe_op_in_unsafe_fn, unstable_name_collisions, unstable_syntax_pre_expansion, unused_allocation, unused_assignments, unused_associated_type_bounds, unused_attributes, unused_braces, unused_comparisons, unused_crate_dependencies, unused_doc_comments, unused_extern_crates, unused_features, unused_import_braces, unused_imports, unused_labels, unused_lifetimes, unused_macro_rules, unused_macros, unused_must_use, unused_mut, unused_parens, unused_qualifications, unused_results, unused_unsafe, unused_variables, useless_ptr_null_checks, uses_power_alignment, variant_size_differences, while_true, ) )] // If nightly and unstable, allow `incomplete_features` and `unstable_features` #![cfg_attr( all(feature = "unstable", nightly), allow(incomplete_features, unstable_features) )] // If nightly and not unstable, deny `incomplete_features` and `unstable_features` #![cfg_attr( all(not(feature = "unstable"), nightly), deny(incomplete_features, unstable_features) )] // The unstable lints #![cfg_attr( all(feature = "unstable", nightly), deny( fuzzy_provenance_casts, lossy_provenance_casts, multiple_supertrait_upcastable, must_not_suspend, non_exhaustive_omitted_patterns, unqualified_local_imports, ) )] // clippy lints #![cfg_attr(nightly, deny(clippy::all, clippy::pedantic))] // rustdoc lints #![cfg_attr( nightly, deny( rustdoc::bare_urls, rustdoc::broken_intra_doc_links, rustdoc::invalid_codeblock_attributes, rustdoc::invalid_html_tags, rustdoc::missing_crate_level_docs, rustdoc::private_doc_tests, rustdoc::private_intra_doc_links, ) )] #![cfg_attr( all(nightly, feature = "unstable"), deny(rustdoc::missing_doc_code_examples) )] #![cfg_attr(all(docsrs), feature(doc_cfg))] #![cfg_attr(coverage_nightly, feature(coverage_attribute))] #[cfg(test)] use {temp_env as _, test_util as _}; pub mod constants; mod emitter; mod entries; mod keys; mod utils; pub use self::emitter::Emitter; pub use self::entries::Add as AddEntries; pub use self::entries::AddCustom as AddCustomEntries; pub use self::entries::CargoRerunIfChanged; pub use self::entries::CargoRustcEnvMap; pub use self::entries::CargoWarning; pub use self::entries::DefaultConfig; #[doc(hidden)] pub use self::entries::test_gen::CustomInsGen; #[doc(hidden)] pub use self::entries::test_gen::CustomInsGenBuilder; pub use self::keys::vergen_key::VergenKey; pub use self::utils::add_default_map_entry; pub use self::utils::add_map_entry; pub use self::utils::count_idempotent; vergen-lib-9.1.0/src/utils.rs000064400000000000000000000050541046102023000141660ustar 00000000000000use crate::{CargoRustcEnvMap, CargoWarning, VergenKey, constants::VERGEN_IDEMPOTENT_DEFAULT}; use std::env; /// Add a [`VergenKey`] entry as a default string into the [`CargoRustcEnvMap`]. /// The value is either from an environment variable override or [`crate::constants::VERGEN_IDEMPOTENT_DEFAULT`] /// /// # Example /// ``` /// # use std::collections::BTreeMap; /// # use temp_env::with_var; /// # use vergen_lib::{add_default_map_entry, CargoRustcEnvMap, CargoWarning, VergenKey}; /// with_var("VERGEN_BUILD_DATE", Some("my own date"), || { /// let mut map: CargoRustcEnvMap = BTreeMap::new(); /// let mut warning: CargoWarning = vec![]; #[cfg_attr( feature = "build", doc = r" add_default_map_entry(VergenKey::BuildDate, &mut map, &mut warning); assert_eq!(1, map.len()); assert_eq!(1, warning.len());" )] /// }); /// ``` /// pub fn add_default_map_entry( key: VergenKey, map: &mut CargoRustcEnvMap, warnings: &mut CargoWarning, ) { if let Ok(value) = env::var(key.name()) { add_map_entry(key, value, map); warnings.push(format!("{} overidden", key.name())); } else { add_map_entry(key, VERGEN_IDEMPOTENT_DEFAULT, map); warnings.push(format!("{} set to default", key.name())); } } /// Add a [`VergenKey`] entry as a string into the [`CargoRustcEnvMap`]. /// /// # Example /// ``` /// # use std::collections::BTreeMap; /// # use vergen_lib::{add_map_entry, CargoRustcEnvMap, VergenKey}; /// let mut map: CargoRustcEnvMap = BTreeMap::new(); #[cfg_attr( feature = "build", doc = r#"add_map_entry(VergenKey::BuildDate, "test", &mut map); assert_eq!(1, map.len());"# )] /// ``` /// pub fn add_map_entry(key: VergenKey, value: T, map: &mut CargoRustcEnvMap) where T: Into, { let _old = map.insert(key, value.into()); } /// Count the number of idempotent entries in a [`CargoRustcEnvMap`] /// /// **NOTE** - This is mainly used for testing. /// /// # Example /// /// ``` /// # use std::collections::BTreeMap; /// # use vergen_lib::{count_idempotent, CargoRustcEnvMap, VergenKey, constants::VERGEN_IDEMPOTENT_DEFAULT}; /// # /// let mut map: CargoRustcEnvMap = BTreeMap::new(); /// assert_eq!(0, count_idempotent(&map)); #[cfg_attr( feature = "build", doc = r"_ = map.insert(VergenKey::BuildDate, VERGEN_IDEMPOTENT_DEFAULT.to_string());" )] #[cfg_attr(feature = "build", doc = r"assert_eq!(1, count_idempotent(&map));")] /// ``` /// #[must_use] pub fn count_idempotent(map: &CargoRustcEnvMap) -> usize { map.values() .filter(|x| *x == VERGEN_IDEMPOTENT_DEFAULT) .count() }