Debian Codegraph @

debian/rust-vendor/codspeed/src/utils.rs

raw
1 use std::io;
2 use std::path::{Path, PathBuf};
3
4 fn get_parent_git_repo_path(abs_path: &Path) -> io::Result<PathBuf> {
5 if abs_path.join(".git").exists() {
6 Ok(abs_path.to_path_buf())
7 } else {
8 get_parent_git_repo_path(
9 abs_path
10 .parent()
11 .ok_or(io::Error::from(io::ErrorKind::NotFound))?,
12 )
13 }
14 }
15
16 pub fn get_git_relative_path<P>(abs_path: P) -> PathBuf
17 where
18 P: AsRef<Path>,
19 {
20 if let Ok(canonicalized_abs_path) = abs_path.as_ref().canonicalize() {
21 // `repo_path` is still canonicalized as it is a subpath of `canonicalized_abs_path`
22 if let Ok(repo_path) = get_parent_git_repo_path(&canonicalized_abs_path) {
23 canonicalized_abs_path
24 .strip_prefix(repo_path)
25 .expect("Repository path is malformed.")
26 .to_path_buf()
27 } else {
28 canonicalized_abs_path
29 }
30 } else {
31 abs_path.as_ref().to_path_buf()
32 }
33 }
34
35 /// Builds a benchmark URI by joining the non-empty segments with `::`.
36 ///
37 /// Segments can be empty when `criterion_group!`/`criterion_main!` are bypassed (custom main):
38 /// `current_file` and `macro_group` are not set in that case and must not produce empty
39 /// `::` parts (e.g. `::::my_group::my_bench`).
40 pub fn build_uri(segments: &[&str]) -> String {
41 segments
42 .iter()
43 .filter(|s| !s.is_empty())
44 .copied()
45 .collect::<Vec<_>>()
46 .join("::")
47 }
48
49 /// Resolves the caller's source file path for URI generation, anchored to the
50 /// workspace root when running under the CodSpeed runner.
51 ///
52 /// `#[track_caller]` so the location resolves to the original benchmark call site
53 /// rather than this helper.
54 #[track_caller]
55 pub fn caller_file_path() -> String {
56 let caller = std::panic::Location::caller();
57 match std::env::var("CODSPEED_CARGO_WORKSPACE_ROOT") {
58 Ok(workspace_root) => PathBuf::from(workspace_root)
59 .join(caller.file())
60 .to_string_lossy()
61 .into_owned(),
62 Err(_) => caller.file().to_string(),
63 }
64 }
65
66 /// Fixes spaces around `::` created by stringify!($function).
67 pub fn get_formated_function_path(function_path: impl Into<String>) -> String {
68 let function_path = function_path.into();
69 function_path.replace(" :: ", "::")
70 }
71
72 pub fn running_with_codspeed_runner() -> bool {
73 std::env::var("CODSPEED_ENV").is_ok()
74 }
75
76 pub fn is_perf_enabled() -> bool {
77 std::env::var("CODSPEED_PERF_ENABLED").is_ok()
78 }
79
80 /// Generate a statistically unique ID in a format resembling UUID v4.
81 pub fn generate_unique_id() -> String {
82 // Generate random bytes for UUID v4
83 let mut bytes = [0u8; 16];
84 getrandom::fill(&mut bytes).expect("Failed to generate random bytes");
85
86 // Extract values from bytes
87 let r1 = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
88 let r2 = u16::from_be_bytes([bytes[4], bytes[5]]);
89 let r3 = u16::from_be_bytes([bytes[6], bytes[7]]);
90 let r4 = u16::from_be_bytes([bytes[8], bytes[9]]);
91 let r5 = u32::from_be_bytes([bytes[10], bytes[11], bytes[12], bytes[13]]);
92 let r6 = u16::from_be_bytes([bytes[14], bytes[15]]);
93
94 // Set version (4) and variant bits according to UUID v4 spec
95 let r3_v4 = (r3 & 0x0fff) | 0x4000; // Version 4
96 let r4_variant = (r4 & 0x3fff) | 0x8000; // Variant 10
97
98 // Format as standard UUID: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
99 // where y is one of 8, 9, A, or B
100 format!("{r1:08x}-{r2:04x}-{r3_v4:04x}-{r4_variant:04x}-{r5:08x}{r6:04x}")
101 }
102
103 #[cfg(test)]
104 mod tests {
105 use super::*;
106 use std::fs;
107 use tempfile::tempdir;
108
109 #[test]
110 fn test_get_git_relative_path_found() {
111 // Create a temp directory.
112 let dir = tempdir().unwrap();
113 let git_dir = dir.path().join(".git");
114 fs::create_dir(git_dir).unwrap();
115 let nested_dir = dir.path().join("folder").join("nested_folder");
116 fs::create_dir_all(&nested_dir).unwrap();
117
118 let relative_path = get_git_relative_path(&nested_dir);
119 assert_eq!(relative_path, PathBuf::from("folder/nested_folder"));
120 }
121
122 #[test]
123 fn test_get_git_relative_path_not_found() {
124 let dir = tempdir().unwrap();
125 let path_dir = dir.path().join("folder");
126 fs::create_dir_all(&path_dir).unwrap();
127
128 let relative_path = get_git_relative_path(&path_dir);
129 assert_eq!(relative_path, path_dir.canonicalize().unwrap());
130 }
131
132 #[cfg(unix)]
133 #[test]
134 fn test_get_git_relative_path_not_found_with_symlink() {
135 let dir = tempdir().unwrap();
136 let path_dir = dir.path().join("folder");
137 fs::create_dir_all(&path_dir).unwrap();
138 let symlink = dir.path().join("symlink");
139 std::os::unix::fs::symlink(&path_dir, &symlink).unwrap();
140
141 let relative_path = get_git_relative_path(&symlink);
142 assert_eq!(relative_path, symlink.canonicalize().unwrap());
143 }
144
145 /// COD-2324: empty segments (no file/macro group when `criterion_group!` is bypassed)
146 /// must not produce URIs like `::::my_group::my_bench`.
147 #[test]
148 fn test_build_uri_skips_empty_segments() {
149 assert_eq!(
150 build_uri(&["", "", "my_group::my_bench"]),
151 "my_group::my_bench"
152 );
153 assert_eq!(
154 build_uri(&["benches/custom_main.rs", "", "my_group::my_bench"]),
155 "benches/custom_main.rs::my_group::my_bench"
156 );
157 assert_eq!(
158 build_uri(&[
159 "benches/bench.rs",
160 "benches::bench_fn",
161 "my_group::my_bench"
162 ]),
163 "benches/bench.rs::benches::bench_fn::my_group::my_bench"
164 );
165 }
166
167 #[test]
168 fn test_get_formated_function_path() {
169 let input = "std :: vec :: Vec :: new";
170 let expected_output = "std::vec::Vec::new".to_string();
171 assert_eq!(get_formated_function_path(input), expected_output);
172 }
173 }