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