Skip to content

Instantly share code, notes, and snippets.

@Dirbaio

Dirbaio/build.rs Secret

Created June 13, 2022 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dirbaio/1ba937df7b3f82edf18d80e8025f3fcf to your computer and use it in GitHub Desktop.
Save Dirbaio/1ba937df7b3f82edf18d80e8025f3fcf to your computer and use it in GitHub Desktop.
use std::fmt::Write;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{env, error::Error, fs, path::PathBuf, process::Command};
fn get_output(cmd: &mut Command) -> Result<String, Box<dyn Error>> {
let output = cmd.output()?;
assert!(output.status.success());
Ok(String::from_utf8(output.stdout)?.trim().into())
}
fn binstring(len: usize, s: String) -> String {
let b = s.as_bytes();
let mut res: String = "[".into();
for i in 0..len {
write!(res, "0x{:x},", b.get(i).cloned().unwrap_or(0)).unwrap()
}
write!(res, "]").unwrap();
res
}
fn main() -> Result<(), Box<dyn Error>> {
let out = &PathBuf::from(env::var("OUT_DIR").unwrap());
let git_commit = get_output(Command::new("git").args(&["rev-parse", "HEAD"])).unwrap();
let git_diff = get_output(Command::new("git").args(&["diff-index", "HEAD"])).unwrap();
let build_user = binstring(16, get_output(&mut Command::new("whoami")).unwrap());
let build_hostname = binstring(16, get_output(&mut Command::new("hostname")).unwrap());
let mut flags = 0;
if !git_diff.is_empty() {
flags |= 1; // GIT_DIRTY
}
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
fs::write(
out.join("build_info_generated.rs"),
format!(
r#"
const FLAGS: u32 = {};
const TIMESTAMP: u32 = {};
const GIT_COMMIT: [u8;20] = hex!("{}");
const USER: [u8;16] = {};
const HOSTNAME: [u8;16] = {};
"#,
flags, timestamp, git_commit, build_user, build_hostname,
),
)
.unwrap();
Ok(())
}
use hex_literal::hex;
pub const MAGIC: u32 = 0x12341234;
pub const FLAG_GIT_DIRTY: u32 = 1;
include!(concat!(env!("OUT_DIR"), "/build_info_generated.rs"));
#[repr(C)]
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct BuildInfo {
magic: u32,
hardware_code: u32,
timestamp: u32,
flags: u32,
git_commit: [u8; 20],
user: [u8; 16],
hostname: [u8; 16],
}
#[used]
#[no_mangle]
#[link_section = ".build_info"]
static BUILD_INFO: BuildInfo = BuildInfo {
magic: MAGIC,
hardware_code: crate::hardware_codes::HARDWARE_CODE,
timestamp: TIMESTAMP,
flags: FLAGS,
git_commit: GIT_COMMIT,
user: USER,
hostname: HOSTNAME,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment