chore(core): format rust code (#30954)

## Current Behavior
Rust formatting isn't checked in CI

## Expected Behavior
Rust formatting is checked in CI

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->

Fixes #
This commit is contained in:
Craigory Coppola 2025-05-01 08:49:50 -04:00 committed by GitHub
parent d9cb931116
commit 981dd94671
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
23 changed files with 143 additions and 117 deletions

View File

@ -94,7 +94,7 @@ jobs:
pnpm nx run-many -t check-imports check-commit check-lock-files check-codeowners --parallel=1 --no-dte & pnpm nx run-many -t check-imports check-commit check-lock-files check-codeowners --parallel=1 --no-dte &
pids+=($!) pids+=($!)
pnpm nx affected --targets=lint,test,build,e2e,e2e-ci & pnpm nx affected --targets=lint,test,build,e2e,e2e-ci,format-native &
pids+=($!) pids+=($!)
for pid in "${pids[@]}"; do for pid in "${pids[@]}"; do

View File

@ -2,3 +2,4 @@ pnpm check-lock-files
pnpm check-commit pnpm check-commit
pnpm documentation pnpm documentation
pnpm pretty-quick --check pnpm pretty-quick --check
pnpm nx format-native nx

View File

@ -139,6 +139,19 @@
"parallel": false "parallel": false
} }
}, },
"test-native": {} "test-native": {},
"format-native": {
"command": "cargo fmt",
"cache": true,
"options": {
"cwd": "{projectRoot}/src/native",
"args": ["--all", "--check"]
},
"configurations": {
"fix": {
"args": ["--all"]
}
}
}
} }
} }

View File

@ -1,9 +1,9 @@
use super::contains_glob_pattern;
use crate::native::glob::glob_group::GlobGroup; use crate::native::glob::glob_group::GlobGroup;
use crate::native::glob::glob_parser::parse_glob; use crate::native::glob::glob_parser::parse_glob;
use itertools::Either::{Left, Right};
use itertools::Itertools; use itertools::Itertools;
use std::collections::HashSet; use std::collections::HashSet;
use itertools::Either::{Left, Right};
use super::contains_glob_pattern;
#[derive(Debug)] #[derive(Debug)]
enum GlobType { enum GlobType {
@ -120,8 +120,7 @@ pub fn partition_glob(glob: &str) -> anyhow::Result<(String, Vec<String>)> {
let (leading_dir_segments, pattern_segments): (Vec<String>, _) = groups let (leading_dir_segments, pattern_segments): (Vec<String>, _) = groups
.into_iter() .into_iter()
.filter(|group| !group.is_empty()) .filter(|group| !group.is_empty())
.partition_map(|group| { .partition_map(|group| match &group[0] {
match &group[0] {
GlobGroup::NonSpecial(value) if !contains_glob_pattern(&value) && !has_patterns => { GlobGroup::NonSpecial(value) if !contains_glob_pattern(&value) && !has_patterns => {
Left(value.to_string()) Left(value.to_string())
} }
@ -129,7 +128,6 @@ pub fn partition_glob(glob: &str) -> anyhow::Result<(String, Vec<String>)> {
has_patterns = true; has_patterns = true;
Right(group) Right(group)
} }
}
}); });
Ok(( Ok((
@ -267,7 +265,8 @@ mod test {
#[test] #[test]
fn should_partition_glob_with_leading_dirs() { fn should_partition_glob_with_leading_dirs() {
let (leading_dirs, globs) = super::partition_glob("dist/app/**/!(README|LICENSE).(js|ts)").unwrap(); let (leading_dirs, globs) =
super::partition_glob("dist/app/**/!(README|LICENSE).(js|ts)").unwrap();
assert_eq!(leading_dirs, "dist/app"); assert_eq!(leading_dirs, "dist/app");
assert_eq!(globs, ["!**/{README,LICENSE}.{js,ts}", "**/*.{js,ts}",]); assert_eq!(globs, ["!**/{README,LICENSE}.{js,ts}", "**/*.{js,ts}",]);
} }

View File

@ -9,12 +9,16 @@ pub fn hash(content: &[u8]) -> String {
#[napi] #[napi]
pub fn hash_array(input: Vec<Option<String>>) -> String { pub fn hash_array(input: Vec<Option<String>>) -> String {
let joined = input.iter().filter_map(|s| { let joined = input
.iter()
.filter_map(|s| {
if s.is_none() { if s.is_none() {
trace!("Encountered None value in hash_array input: {:?}", input); trace!("Encountered None value in hash_array input: {:?}", input);
} }
s.as_deref() s.as_deref()
}).collect::<Vec<_>>().join(","); })
.collect::<Vec<_>>()
.join(",");
let content = joined.as_bytes(); let content = joined.as_bytes();
hash(content) hash(content)
} }
@ -41,7 +45,7 @@ pub fn hash_file_path<P: AsRef<Path>>(path: P) -> Option<String> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::native::hasher::{hash_file, hash_array}; use crate::native::hasher::{hash_array, hash_file};
use assert_fs::prelude::*; use assert_fs::prelude::*;
use assert_fs::TempDir; use assert_fs::TempDir;

View File

@ -8,4 +8,3 @@ use crate::native::project_graph::types::ProjectGraph;
pub fn transfer_project_graph(project_graph: ProjectGraph) -> External<ProjectGraph> { pub fn transfer_project_graph(project_graph: ProjectGraph) -> External<ProjectGraph> {
External::new(project_graph) External::new(project_graph)
} }

View File

@ -32,14 +32,8 @@ impl RustPseudoTerminal {
quiet: Option<bool>, quiet: Option<bool>,
tty: Option<bool>, tty: Option<bool>,
) -> napi::Result<ChildProcess> { ) -> napi::Result<ChildProcess> {
self.pseudo_terminal.run_command( self.pseudo_terminal
command, .run_command(command, command_dir, js_env, exec_argv, quiet, tty)
command_dir,
js_env,
exec_argv,
quiet,
tty,
)
} }
/// This allows us to run a pseudoterminal with a fake node ipc channel /// This allows us to run a pseudoterminal with a fake node ipc channel

View File

@ -33,14 +33,8 @@ impl RustPseudoTerminal {
quiet: Option<bool>, quiet: Option<bool>,
tty: Option<bool>, tty: Option<bool>,
) -> napi::Result<ChildProcess> { ) -> napi::Result<ChildProcess> {
self.pseudo_terminal.run_command( self.pseudo_terminal
command, .run_command(command, command_dir, js_env, exec_argv, quiet, tty)
command_dir,
js_env,
exec_argv,
quiet,
tty,
)
} }
/// This allows us to run a pseudoterminal with a fake node ipc channel /// This allows us to run a pseudoterminal with a fake node ipc channel

View File

@ -117,7 +117,9 @@ impl PseudoTerminal {
let mut content = String::from_utf8_lossy(&buf[0..len]).to_string(); let mut content = String::from_utf8_lossy(&buf[0..len]).to_string();
if content.contains("\x1B[6n") { if content.contains("\x1B[6n") {
trace!("Prevented terminal escape sequence ESC[6n from being printed."); trace!(
"Prevented terminal escape sequence ESC[6n from being printed."
);
content = content.replace("\x1B[6n", ""); content = content.replace("\x1B[6n", "");
} }

View File

@ -4,8 +4,8 @@ mod hash_project_config;
mod hash_project_files; mod hash_project_files;
mod hash_runtime; mod hash_runtime;
mod hash_task_output; mod hash_task_output;
mod hash_workspace_files;
mod hash_tsconfig; mod hash_tsconfig;
mod hash_workspace_files;
pub use hash_env::*; pub use hash_env::*;
pub use hash_external::*; pub use hash_external::*;
@ -13,5 +13,5 @@ pub use hash_project_config::*;
pub use hash_project_files::*; pub use hash_project_files::*;
pub use hash_runtime::*; pub use hash_runtime::*;
pub use hash_task_output::*; pub use hash_task_output::*;
pub use hash_workspace_files::*;
pub use hash_tsconfig::*; pub use hash_tsconfig::*;
pub use hash_workspace_files::*;

View File

@ -158,12 +158,15 @@ mod tests {
let hash_result = hash_project_files(proj_name, proj_root, file_sets, &file_map).unwrap(); let hash_result = hash_project_files(proj_name, proj_root, file_sets, &file_map).unwrap();
assert_eq!( assert_eq!(
hash_result, hash_result,
hash(&[ hash(
&[
file_data1.hash.as_bytes(), file_data1.hash.as_bytes(),
file_data1.file.as_bytes(), file_data1.file.as_bytes(),
file_data3.hash.as_bytes(), file_data3.hash.as_bytes(),
file_data3.file.as_bytes() file_data3.file.as_bytes()
].concat()) ]
.concat()
)
); );
} }
@ -205,12 +208,15 @@ mod tests {
let hash_result = hash_project_files(proj_name, proj_root, file_sets, &file_map).unwrap(); let hash_result = hash_project_files(proj_name, proj_root, file_sets, &file_map).unwrap();
assert_eq!( assert_eq!(
hash_result, hash_result,
hash(&[ hash(
&[
file_data1.hash.as_bytes(), file_data1.hash.as_bytes(),
file_data1.file.as_bytes(), file_data1.file.as_bytes(),
file_data3.hash.as_bytes(), file_data3.hash.as_bytes(),
file_data3.file.as_bytes(), file_data3.file.as_bytes(),
].concat()) ]
.concat()
)
); );
} }
} }

View File

@ -1,9 +1,9 @@
use std::path::Path;
use crate::native::cache::expand_outputs::get_files_for_outputs; use crate::native::cache::expand_outputs::get_files_for_outputs;
use crate::native::glob::build_glob_set; use crate::native::glob::build_glob_set;
use crate::native::hasher::{hash_array, hash_file}; use crate::native::hasher::{hash_array, hash_file};
use anyhow::*; use anyhow::*;
use rayon::prelude::*; use rayon::prelude::*;
use std::path::Path;
use tracing::trace; use tracing::trace;
pub fn hash_task_output(workspace_root: &str, glob: &str, outputs: &[String]) -> Result<String> { pub fn hash_task_output(workspace_root: &str, glob: &str, outputs: &[String]) -> Result<String> {
@ -14,7 +14,15 @@ pub fn hash_task_output(workspace_root: &str, glob: &str, outputs: &[String]) ->
let hashes = output_files let hashes = output_files
.into_par_iter() .into_par_iter()
.filter(|file| glob.is_match(file)) .filter(|file| glob.is_match(file))
.filter_map(|file| hash_file(Path::new(workspace_root).join(file).to_str().expect("path contains invalid utf-8").to_owned())) .filter_map(|file| {
hash_file(
Path::new(workspace_root)
.join(file)
.to_str()
.expect("path contains invalid utf-8")
.to_owned(),
)
})
.collect::<Vec<_>>(); .collect::<Vec<_>>();
Ok(hash_array(hashes.into_iter().map(Some).collect())) Ok(hash_array(hashes.into_iter().map(Some).collect()))
} }

View File

@ -9,6 +9,6 @@ mod utils;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
pub mod details; pub mod details;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
pub mod task_history;
#[cfg(not(target_arch = "wasm32"))]
pub mod running_tasks_service; pub mod running_tasks_service;
#[cfg(not(target_arch = "wasm32"))]
pub mod task_history;

View File

@ -99,9 +99,11 @@ impl CountdownPopup {
pub fn render(&mut self, f: &mut Frame<'_>, area: Rect) { pub fn render(&mut self, f: &mut Frame<'_>, area: Rect) {
// Add a safety check to prevent rendering outside buffer bounds (this can happen if the user resizes the window a lot before it stabilizes it seems) // Add a safety check to prevent rendering outside buffer bounds (this can happen if the user resizes the window a lot before it stabilizes it seems)
if area.height == 0 || area.width == 0 || if area.height == 0
area.x >= f.area().width || || area.width == 0
area.y >= f.area().height { || area.x >= f.area().width
|| area.y >= f.area().height
{
return; // Area is out of bounds, don't try to render return; // Area is out of bounds, don't try to render
} }

View File

@ -27,9 +27,11 @@ impl HelpText {
pub fn render(&self, f: &mut Frame<'_>, area: Rect) { pub fn render(&self, f: &mut Frame<'_>, area: Rect) {
// Add a safety check to prevent rendering outside buffer bounds (this can happen if the user resizes the window a lot before it stabilizes it seems) // Add a safety check to prevent rendering outside buffer bounds (this can happen if the user resizes the window a lot before it stabilizes it seems)
if area.height == 0 || area.width == 0 || if area.height == 0
area.x >= f.area().width || || area.width == 0
area.y >= f.area().height { || area.x >= f.area().width
|| area.y >= f.area().height
{
return; // Area is out of bounds, don't try to render return; // Area is out of bounds, don't try to render
} }

View File

@ -252,11 +252,7 @@ impl LayoutManager {
} }
// Prevent divide-by-zero // Prevent divide-by-zero
let task_list_height = if area.height < 3 { let task_list_height = if area.height < 3 { 1 } else { area.height / 3 };
1
} else {
area.height / 3
};
// Apply padding only if there's enough space // Apply padding only if there's enough space
let padding_height = if area.height > task_list_height + self.vertical_padding { let padding_height = if area.height > task_list_height + self.vertical_padding {
@ -311,11 +307,7 @@ impl LayoutManager {
} }
// Prevent divide-by-zero // Prevent divide-by-zero
let task_list_width = if area.width < 3 { let task_list_width = if area.width < 3 { 1 } else { area.width / 3 };
1
} else {
area.width / 3
};
// Apply padding only if there's enough space // Apply padding only if there's enough space
let padding_width = if area.width > task_list_width + self.horizontal_padding { let padding_width = if area.width > task_list_width + self.horizontal_padding {
@ -440,7 +432,10 @@ mod tests {
fn test_default_properties() { fn test_default_properties() {
let layout_manager = LayoutManager::new(5); let layout_manager = LayoutManager::new(5);
assert_eq!(layout_manager.get_pane_arrangement(), PaneArrangement::None); assert_eq!(layout_manager.get_pane_arrangement(), PaneArrangement::None);
assert_eq!(layout_manager.get_task_list_visibility(), TaskListVisibility::Visible); assert_eq!(
layout_manager.get_task_list_visibility(),
TaskListVisibility::Visible
);
assert_eq!(layout_manager.get_task_count(), 5); assert_eq!(layout_manager.get_task_count(), 5);
} }

View File

@ -18,9 +18,13 @@ impl NxCondvar {
Self(Condvar::new()) Self(Condvar::new())
} }
pub fn wait<'a, T, F>(&'a self, mut guard: MutexGuard<'a, T>, condition: F) -> anyhow::Result<MutexGuard<'a, T>> pub fn wait<'a, T, F>(
&'a self,
mut guard: MutexGuard<'a, T>,
condition: F,
) -> anyhow::Result<MutexGuard<'a, T>>
where where
F: Fn(&MutexGuard<'a, T>) -> bool F: Fn(&MutexGuard<'a, T>) -> bool,
{ {
if condition(&guard) { if condition(&guard) {
self.0.wait(&mut guard); self.0.wait(&mut guard);

View File

@ -18,9 +18,13 @@ impl NxCondvar {
Self(Condvar::new()) Self(Condvar::new())
} }
pub fn wait<'a, T, F>(&self, mutex_guard: MutexGuard<'a, T>, condition: F) -> LockResult<MutexGuard<'a, T>> pub fn wait<'a, T, F>(
&self,
mutex_guard: MutexGuard<'a, T>,
condition: F,
) -> LockResult<MutexGuard<'a, T>>
where where
F: Fn(&mut T) -> bool F: Fn(&mut T) -> bool,
{ {
self.0.wait_while(mutex_guard, condition) self.0.wait_while(mutex_guard, condition)
} }

View File

@ -1,4 +1,4 @@
use crate::native::{utils::normalize_trait::Normalize, types::FileData}; use crate::native::{types::FileData, utils::normalize_trait::Normalize};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
impl Normalize for Path { impl Normalize for Path {
@ -65,13 +65,9 @@ mod test {
FileData { FileData {
file: "foo-other/not-child".into(), file: "foo-other/not-child".into(),
hash: "123".into(), hash: "123".into(),
} },
]; ];
let child_files = get_child_files(&directory, files); let child_files = get_child_files(&directory, files);
assert_eq!(child_files, [ assert_eq!(child_files, ["foo/bar", "foo/baz", "foo/child/bar",]);
"foo/bar",
"foo/baz",
"foo/child/bar",
]);
} }
} }

View File

@ -50,14 +50,13 @@ where
!ignore_glob_set.is_match(path.as_ref()) !ignore_glob_set.is_match(path.as_ref())
}) })
.filter_map(move |entry| { .filter_map(move |entry| {
entry entry.ok().and_then(|e| {
.ok()
.and_then(|e|
e.path() e.path()
.strip_prefix(&base_dir).ok() .strip_prefix(&base_dir)
.ok()
.filter(|p| !p.to_string_lossy().is_empty()) .filter(|p| !p.to_string_lossy().is_empty())
.map(|p| p.to_owned()) .map(|p| p.to_owned())
) })
}) })
} }

View File

@ -61,7 +61,11 @@ fn hash_files(files: Vec<NxFile>) -> Vec<(String, NxFileHashed)> {
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
} else { } else {
trace!("hashing workspace files in {} chunks of {}", num_parallelism, chunks); trace!(
"hashing workspace files in {} chunks of {}",
num_parallelism,
chunks
);
files files
.par_chunks(chunks) .par_chunks(chunks)
.flat_map_iter(|chunks| { .flat_map_iter(|chunks| {