1use serde::de::{self, Deserialize, DeserializeOwned, Deserializer};
2use serde_derive::Deserialize;
3use std::env;
4use std::error::Error;
5use std::ffi::OsStr;
6use std::fs;
7use std::path::PathBuf;
8
9pub fn find() -> Option<Vec<String>> {
10 try_find().ok()
11}
12
13struct Ignored;
14
15impl<E: Error> From<E> for Ignored {
16 fn from(_error: E) -> Self {
17 Ignored
18 }
19}
20
21#[derive(Deserialize)]
22struct Build {
23 #[serde(deserialize_with = "from_json")]
24 features: Vec<String>,
25}
26
27fn try_find() -> Result<Vec<String>, Ignored> {
28 let test_binary = env::args_os().next().ok_or(Ignored)?;
31
32 let test_binary_lossy = test_binary.to_string_lossy();
35 let hash = test_binary_lossy
36 .get(test_binary_lossy.len() - 17..)
37 .ok_or(Ignored)?;
38 if !hash.starts_with('-') || !hash[1..].bytes().all(is_lower_hex_digit) {
39 return Err(Ignored);
40 }
41
42 let binary_path = PathBuf::from(&test_binary);
43
44 let up = binary_path
47 .parent()
48 .ok_or(Ignored)?
49 .parent()
50 .ok_or(Ignored)?;
51 let fingerprint_dir = up.join(".fingerprint");
52 if !fingerprint_dir.is_dir() {
53 return Err(Ignored);
54 }
55
56 let mut hash_matches = Vec::new();
57 for entry in fingerprint_dir.read_dir()? {
58 let entry = entry?;
59 let is_dir = entry.file_type()?.is_dir();
60 let matching_hash = entry.file_name().to_string_lossy().ends_with(hash);
61 if is_dir && matching_hash {
62 hash_matches.push(entry.path());
63 }
64 }
65
66 if hash_matches.len() != 1 {
67 return Err(Ignored);
68 }
69
70 let mut json_matches = Vec::new();
71 for entry in hash_matches[0].read_dir()? {
72 let entry = entry?;
73 let is_file = entry.file_type()?.is_file();
74 let is_json = entry.path().extension() == Some(OsStr::new("json"));
75 if is_file && is_json {
76 json_matches.push(entry.path());
77 }
78 }
79
80 if json_matches.len() != 1 {
81 return Err(Ignored);
82 }
83
84 let build_json = fs::read_to_string(&json_matches[0])?;
85 let build: Build = serde_json::from_str(&build_json)?;
86 Ok(build.features)
87}
88
89fn is_lower_hex_digit(byte: u8) -> bool {
90 matches!(byte, b'0'..=b'9' | b'a'..=b'f')
91}
92
93fn from_json<'de, T, D>(deserializer: D) -> Result<T, D::Error>
94where
95 T: DeserializeOwned,
96 D: Deserializer<'de>,
97{
98 let json = String::deserialize(deserializer)?;
99 serde_json::from_str(&json).map_err(de::Error::custom)
100}