trident_client/utils.rs
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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
use crate::test_generator::Error;
use crate::versions_config::TridentVersionsConfig;
use crate::constants::*;
use cargo_metadata::Package;
use fehler::{throw, throws};
use std::path::Path;
use std::{fs::File, io::prelude::*};
use std::{fs::OpenOptions, io, path::PathBuf};
use tokio::fs;
use toml::{value::Table, Value};
#[macro_export]
macro_rules! construct_path {
($root:expr, $($component:expr),*) => {
{
let mut path = $root.to_owned();
$(path = path.join($component);)*
path
}
};
}
#[macro_export]
macro_rules! load_template {
($file:expr) => {
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), $file))
};
}
#[throws]
pub async fn create_directory_all(path: &PathBuf) {
match path.exists() {
true => {}
false => {
fs::create_dir_all(path).await?;
}
};
}
#[throws]
pub async fn create_directory(path: &PathBuf) {
match path.exists() {
true => {}
false => {
fs::create_dir(path).await?;
}
};
}
#[throws]
pub async fn create_file(root: &PathBuf, path: &PathBuf, content: &str) {
let file = path.strip_prefix(root)?.to_str().unwrap_or_default();
match path.exists() {
true => {
println!("{SKIP} [{file}] already exists")
}
false => {
fs::write(path, content).await?;
println!("{FINISH} [{file}] created");
}
};
}
#[throws]
pub fn get_fuzz_id(fuzz_dir_path: &Path) -> i32 {
if fuzz_dir_path.read_dir()?.next().is_none() {
0
} else {
let entries = fuzz_dir_path.read_dir()?;
let mut max_num = -1;
for entry in entries {
let entry = entry?;
let file_name = entry.file_name().into_string().unwrap_or_default();
if file_name.starts_with("fuzz_") {
let stripped = file_name.strip_prefix("fuzz_").unwrap_or_default();
let num = stripped.parse::<i32>()?;
max_num = max_num.max(num);
}
}
max_num + 1
}
}
#[throws]
pub async fn collect_program_packages() -> Vec<cargo_metadata::Package> {
let packages: Vec<cargo_metadata::Package> = program_packages().collect();
if packages.is_empty() {
throw!(Error::NoProgramsFound)
} else {
packages
}
}
pub fn program_packages() -> impl Iterator<Item = cargo_metadata::Package> {
let cargo_toml_data = cargo_metadata::MetadataCommand::new()
.no_deps()
.exec()
.expect("Cargo.toml reading failed");
cargo_toml_data.packages.into_iter().filter(|package| {
// TODO less error-prone test if the package is a _program_?
if let Some("programs") = package.manifest_path.iter().nth_back(2) {
return true;
}
false
})
}
#[throws]
pub fn update_gitignore(root: &PathBuf, ignored_path: &str) {
let gitignore_path = construct_path!(root, GIT_IGNORE);
if gitignore_path.exists() {
let file = File::open(&gitignore_path)?;
for line in io::BufReader::new(file).lines().map_while(Result::ok) {
if line == ignored_path {
// INFO do not add the ignored path again if it is already in the .gitignore file
println!("{SKIP} [{GIT_IGNORE}], already contains [{ignored_path}]");
return;
}
}
// Check if the file ends with a newline
let mut file = File::open(&gitignore_path)?;
let mut buf = [0; 1];
file.seek(io::SeekFrom::End(-1))?;
file.read_exact(&mut buf)?;
let file = OpenOptions::new().append(true).open(gitignore_path);
if let Ok(mut file) = file {
if buf[0] == b'\n' {
writeln!(file, "{}", ignored_path)?;
} else {
writeln!(file, "\n{}", ignored_path)?;
}
println!("{FINISH} [{GIT_IGNORE}] update with [{ignored_path}]");
}
} else {
println!("{SKIP} [{GIT_IGNORE}], not found");
}
}
/// Ensures that a table exists in the given TOML content, and returns a mutable reference to it.
pub fn ensure_table<'a>(content: &'a mut Value, table_name: &str) -> Result<&'a mut Table, Error> {
content
.as_table_mut()
.ok_or(Error::ParsingCargoTomlDependenciesFailed)?
.entry(table_name)
.or_insert(Value::Table(toml::Table::new()))
.as_table_mut()
.ok_or(Error::ParsingCargoTomlDependenciesFailed)
}
// #[throws]
// pub async fn initialize_package_metadata(
// packages: &[Package],
// versions_config: &TridentVersionsConfig,
// ) {
// for package in packages {
// let manifest_path = package.manifest_path.as_std_path();
// let cargo_toml_content = fs::read_to_string(&manifest_path).await?;
// let mut cargo_toml: Value = toml::from_str(&cargo_toml_content)?;
// // Ensure the 'trident-fuzzing' feature exists with the required dependency.
// let features_table = ensure_table(&mut cargo_toml, "features")?;
// features_table.insert(
// "trident-fuzzing".to_string(),
// Value::Array(vec![Value::String("dep:trident-fuzz".to_string())]),
// );
// // Ensure the required dependencies are present in the 'dependencies' section.
// let dependencies_table = ensure_table(&mut cargo_toml, "dependencies")?;
// // Add 'trident-derive-accounts-snapshots' dependency in table format.
// dependencies_table.insert(
// "trident-derive-accounts-snapshots".to_string(),
// Value::Table({
// let mut snapshots_table = toml::Table::new();
// snapshots_table.insert(
// "version".to_string(),
// Value::String(versions_config.trident_derive_accounts_snapshots.clone()),
// );
// snapshots_table
// }),
// );
// // Add 'trident-fuzz' dependency with specified attributes if not present.
// dependencies_table.insert(
// "trident-fuzz".to_string(),
// Value::Table({
// let mut trident_fuzz_table = toml::Table::new();
// trident_fuzz_table.insert(
// "version".to_string(),
// Value::String(versions_config.trident_fuzz.clone()),
// );
// trident_fuzz_table.insert("optional".to_string(), Value::Boolean(true));
// trident_fuzz_table
// }),
// );
// // Write the updated Cargo.toml back to the file.
// fs::write(&manifest_path, toml::to_string(&cargo_toml).unwrap()).await?;
// }
// }
// #[throws]
// pub async fn update_package_metadata(
// packages: &[Package],
// versions_config: &TridentVersionsConfig,
// ) {
// for package in packages {
// let manifest_path = package.manifest_path.as_std_path();
// let cargo_toml_content = fs::read_to_string(&manifest_path).await?;
// let mut cargo_toml: Value = toml::from_str(&cargo_toml_content)?;
// // Ensure the 'trident-fuzzing' feature exists with the required dependency.
// let features_table = ensure_table(&mut cargo_toml, "features")?;
// if features_table.contains_key("trident-fuzzing") {
// println!(
// "{SKIP} 'trident-fuzzing' feature already exists in package: {}",
// package.name
// );
// } else {
// features_table.insert(
// "trident-fuzzing".to_string(),
// Value::Array(vec![Value::String("dep:trident-fuzz".to_string())]),
// );
// }
// // Ensure the required dependencies are present in the 'dependencies' section.
// let dependencies_table = ensure_table(&mut cargo_toml, "dependencies")?;
// // Add 'trident-derive-accounts-snapshots' dependency in table format.
// if dependencies_table.contains_key("trident-derive-accounts-snapshots") {
// println!("{SKIP} 'trident-derive-accounts-snapshots' dependency already exists in package: {}", package.name);
// } else {
// dependencies_table.insert(
// "trident-derive-accounts-snapshots".to_string(),
// Value::Table({
// let mut snapshots_table = toml::Table::new();
// snapshots_table.insert(
// "version".to_string(),
// Value::String(versions_config.trident_derive_accounts_snapshots.clone()),
// );
// snapshots_table
// }),
// );
// }
// // Add 'trident-fuzz' dependency with specified attributes if not present.
// if dependencies_table.contains_key("trident-fuzz") {
// println!(
// "{SKIP} 'trident-fuzz' dependency already exists in package: {}",
// package.name
// );
// } else {
// dependencies_table.insert(
// "trident-fuzz".to_string(),
// Value::Table({
// let mut trident_fuzz_table = toml::Table::new();
// trident_fuzz_table.insert(
// "version".to_string(),
// Value::String(versions_config.trident_fuzz.clone()),
// );
// trident_fuzz_table.insert("optional".to_string(), Value::Boolean(true));
// trident_fuzz_table
// }),
// );
// }
// // Write the updated Cargo.toml back to the file.
// fs::write(&manifest_path, toml::to_string(&cargo_toml).unwrap()).await?;
// }
// }
#[throws]
pub async fn add_workspace_member(root: &Path, member: &str) {
// Construct the path to the Cargo.toml file
let cargo = root.join("Cargo.toml");
// Read and parse the Cargo.toml file
let cargo_toml_content = fs::read_to_string(&cargo).await?;
let mut cargo_toml: Value = toml::from_str(&cargo_toml_content)?;
// Ensure that the 'workspace' table exists
let workspace_table = ensure_table(&mut cargo_toml, "workspace")?;
// Ensure that the 'members' array exists within the 'workspace' table
let members = workspace_table
.entry("members")
.or_insert(Value::Array(Vec::new()))
.as_array_mut()
.ok_or(Error::CannotParseCargoToml)?;
// Check if the new member already exists in the 'members' array
if !members.iter().any(|x| x.as_str() == Some(member)) {
// Add the new member to the 'members' array
members.push(Value::String(member.to_string()));
println!("{FINISH} [{CARGO_TOML}] updated with [{member}]");
// Write the updated Cargo.toml back to the file
let updated_toml = toml::to_string(&cargo_toml).unwrap();
fs::write(cargo, updated_toml).await?;
} else {
println!("{SKIP} [{CARGO_TOML}], already contains [{member}]");
}
}
#[throws]
pub async fn add_bin_target(cargo_path: &PathBuf, name: &str, path: &str) {
// Read the existing Cargo.toml file
let cargo_toml_content = fs::read_to_string(cargo_path).await?;
let mut cargo_toml: Value = toml::from_str(&cargo_toml_content)?;
// Create a new bin table
let mut bin_table = Table::new();
bin_table.insert("name".to_string(), Value::String(name.to_string()));
bin_table.insert("path".to_string(), Value::String(path.to_string()));
// Add the new [[bin]] section to the [[bin]] array
if let Some(bin_array) = cargo_toml.get_mut("bin") {
if let Value::Array(bin_array) = bin_array {
bin_array.push(Value::Table(bin_table));
} else {
// If "bin" exists but is not an array, replace it with an array
let bin_array = vec![Value::Table(bin_table)];
cargo_toml
.as_table_mut()
.unwrap()
.insert("bin".to_string(), Value::Array(bin_array));
}
} else {
// If there is no existing [[bin]] array, create one
let bin_array = vec![Value::Table(bin_table)];
cargo_toml
.as_table_mut()
.unwrap()
.insert("bin".to_string(), Value::Array(bin_array));
}
// Write the updated Cargo.toml file
let updated_toml = toml::to_string(&cargo_toml).unwrap();
fs::write(cargo_path, updated_toml).await?;
}
#[throws]
pub async fn initialize_fuzz_tests_manifest(
versions_config: &TridentVersionsConfig,
packages: &[Package],
cargo_dir: &PathBuf,
) {
let cargo_path = cargo_dir.join("Cargo.toml");
let cargo_toml_content = fs::read_to_string(&cargo_path).await?;
let mut cargo_toml: Value = toml::from_str(&cargo_toml_content)?;
// Ensure the required dependencies are present in the 'dependencies' section.
let dependencies_table = ensure_table(&mut cargo_toml, "dependencies")?;
// Add 'trident-client' dependency in table format.
dependencies_table.insert(
"trident-client".to_string(),
Value::Table({
let mut trident_client = toml::Table::new();
trident_client.insert(
"version".to_string(),
Value::String(versions_config.trident_client.clone()),
);
trident_client
}),
);
for package in packages {
let manifest_path = package.manifest_path.parent().unwrap().as_std_path();
let relative_path = pathdiff::diff_paths(manifest_path, cargo_dir).unwrap();
let relative_path_str = relative_path.to_str().unwrap_or_default();
let package_name = package.name.clone();
dependencies_table.insert(
package_name,
Value::Table({
let mut package_entry = toml::Table::new();
package_entry.insert(
"path".to_string(),
Value::String(relative_path_str.to_owned()),
);
// package_entry.insert(
// "features".to_string(),
// Value::Array(vec![Value::String("trident-fuzzing".to_string())]),
// );
package_entry
}),
);
}
fs::write(cargo_path, toml::to_string(&cargo_toml).unwrap()).await?;
}
#[throws]
pub async fn update_fuzz_tests_manifest(
versions_config: &TridentVersionsConfig,
packages: &[Package],
cargo_dir: &PathBuf,
) {
let cargo_path = cargo_dir.join("Cargo.toml");
let cargo_toml_content = fs::read_to_string(&cargo_path).await?;
let mut cargo_toml: Value = toml::from_str(&cargo_toml_content)?;
// Ensure the required dependencies are present in the 'dependencies' section.
let dependencies_table = ensure_table(&mut cargo_toml, "dependencies")?;
// Add 'trident-client' dependency in table format.
dependencies_table
.entry("trident-client")
.or_insert_with(|| {
let mut trident_client = toml::Table::new();
trident_client.insert(
"version".to_string(),
Value::String(versions_config.trident_client.clone()),
);
Value::Table(trident_client)
});
for package in packages {
let manifest_path = package.manifest_path.parent().unwrap().as_std_path();
let relative_path = pathdiff::diff_paths(manifest_path, cargo_dir).unwrap();
let relative_path_str = relative_path.to_str().unwrap_or_default();
dependencies_table.entry(&package.name).or_insert_with(|| {
let mut package_entry = toml::Table::new();
package_entry.insert(
"path".to_string(),
Value::String(relative_path_str.to_owned()),
);
package_entry.insert(
"features".to_string(),
Value::Array(vec![Value::String("trident-fuzzing".to_string())]),
);
Value::Table(package_entry)
});
}
fs::write(cargo_path, toml::to_string(&cargo_toml).unwrap()).await?;
}