From f02f588f280b589393ab06600d9ef234c5136cba Mon Sep 17 00:00:00 2001 From: Jo <10510431+j178@users.noreply.github.com> Date: Tue, 24 Mar 2026 19:19:50 +0800 Subject: [PATCH] Use a bitset for hook stages --- crates/prek/src/cli/list.rs | 2 +- crates/prek/src/config.rs | 106 ++++++++++++------ crates/prek/src/hook.rs | 40 +++---- ...s__read_config_with_nested_merge_keys.snap | 6 +- 4 files changed, 88 insertions(+), 66 deletions(-) diff --git a/crates/prek/src/cli/list.rs b/crates/prek/src/cli/list.rs index b0687a596..133e906b9 100644 --- a/crates/prek/src/cli/list.rs +++ b/crates/prek/src/cli/list.rs @@ -116,7 +116,7 @@ pub(crate) async fn list( .map(|h| { let id = h.id.clone(); let full_id = h.full_id(); - let stages = h.stages.to_vec(); + let stages = h.stages.iter().collect(); SerializableHook { id, full_id, diff --git a/crates/prek/src/config.rs b/crates/prek/src/config.rs index 224f005d3..f3ff69df2 100644 --- a/crates/prek/src/config.rs +++ b/crates/prek/src/config.rs @@ -1,11 +1,10 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::error::Error as _; use std::fmt::Display; use std::ops::RangeInclusive; use std::path::Path; use anyhow::Result; -use clap::ValueEnum; use fancy_regex::Regex; use globset::{Glob, GlobSet, GlobSetBuilder}; use itertools::Itertools; @@ -13,6 +12,7 @@ use prek_identify::TagSet; use rustc_hash::FxHashMap; use serde::de::{DeserializeSeed, Error as DeError, MapAccess, Visitor}; use serde::{Deserialize, Deserializer, Serialize}; +use strum::EnumCount; use crate::fs::Simplified; use crate::install_source::InstallSource; @@ -320,10 +320,12 @@ impl HookType { clap::ValueEnum, strum::AsRefStr, strum::Display, + strum::EnumCount, )] #[serde(rename_all = "kebab-case")] #[strum(serialize_all = "kebab-case")] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[repr(u8)] pub(crate) enum Stage { Manual, CommitMsg, @@ -360,6 +362,28 @@ impl From for Stage { } impl Stage { + const ORDER: [Self; Self::COUNT] = [ + Self::Manual, + Self::CommitMsg, + Self::PostCheckout, + Self::PostCommit, + Self::PostMerge, + Self::PostRewrite, + Self::PreCommit, + Self::PreMergeCommit, + Self::PrePush, + Self::PreRebase, + Self::PrepareCommitMsg, + ]; + + const fn bit(self) -> u16 { + 1u16 << (self as u8) + } + + fn from_index(index: u32) -> Self { + Self::ORDER[index as usize] + } + pub fn operate_on_files(self) -> bool { matches!( self, @@ -373,56 +397,58 @@ impl Stage { } } -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub(crate) enum Stages { - All, - Some(BTreeSet), -} +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) struct Stages(u16); impl Stages { - pub(crate) fn is_empty(&self) -> bool { - matches!(self, Self::Some(stages) if stages.is_empty()) + const ALL_BITS: u16 = (1u16 << Stage::COUNT) - 1; + + pub(crate) const ALL: Self = Self(Self::ALL_BITS); + + pub(crate) fn iter(self) -> impl Iterator { + let mut bits = self.0; + std::iter::from_fn(move || { + if bits == 0 { + return None; + } + let index = bits.trailing_zeros(); + bits &= bits - 1; + Some(Stage::from_index(index)) + }) } - pub(crate) fn contains(&self, stage: Stage) -> bool { - match self { - Self::All => true, - Self::Some(stages) => stages.contains(&stage), - } + pub(crate) fn is_empty(self) -> bool { + self.0 == 0 } - pub(crate) fn to_vec(&self) -> Vec { - match self { - Self::All => Stage::value_variants().to_vec(), - Self::Some(stages) => stages.iter().copied().collect(), - } + pub(crate) fn contains(self, stage: Stage) -> bool { + (self.0 & stage.bit()) != 0 } } impl Display for Stages { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::All => write!(f, "all"), - Self::Some(stages) => { - if stages.is_empty() { - write!(f, "none") - } else { - let stages_str = stages.iter().map(ToString::to_string).join(", "); - write!(f, "{stages_str}") - } - } + if *self == Self::ALL { + write!(f, "all") + } else if self.is_empty() { + write!(f, "none") + } else { + let stages_str = self.iter().map(|stage| stage.to_string()).join(", "); + write!(f, "{stages_str}") } } } +impl std::fmt::Debug for Stages { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Stages({self})") + } +} + impl From> for Stages { fn from(value: Vec) -> Self { - let stages: BTreeSet<_> = value.into_iter().collect(); - if stages.len() == Stage::value_variants().len() { - Self::All - } else { - Self::Some(stages) - } + let bits = value.into_iter().fold(0, |bits, stage| bits | stage.bit()); + Self(bits & Self::ALL_BITS) } } @@ -1342,6 +1368,7 @@ where #[cfg(test)] mod tests { use super::*; + use clap::ValueEnum; use std::io::Write as _; /// Filter to replace dynamic version in snapshots @@ -1358,7 +1385,7 @@ mod tests { } let parsed: Wrapper = serde_saphyr::from_str("stages: []\n").expect("stages should parse"); - assert_eq!(parsed.stages, Stages::Some(BTreeSet::new())); + assert_eq!(parsed.stages, Stages::from([])); assert!(!parsed.stages.contains(Stage::Manual)); assert!(!parsed.stages.contains(Stage::PreCommit)); } @@ -1368,7 +1395,7 @@ mod tests { let parsed: Config = serde_saphyr::from_str("repos: []\ndefault_stages: []\n").expect("config should parse"); - assert_eq!(parsed.default_stages, Some(Stages::Some(BTreeSet::new()))); + assert_eq!(parsed.default_stages, Some(Stages::from([]))); } #[test] @@ -1392,6 +1419,11 @@ mod tests { assert!(!parsed.stages.contains(Stage::PrePush)); } + #[test] + fn stages_full_set_normalizes_to_all() { + assert_eq!(Stages::from(Stage::value_variants().to_vec()), Stages::ALL); + } + #[test] fn parse_file_patterns_regex_and_glob() { #[derive(Debug, Deserialize)] diff --git a/crates/prek/src/hook.rs b/crates/prek/src/hook.rs index d5cc792c8..c1a3b071b 100644 --- a/crates/prek/src/hook.rs +++ b/crates/prek/src/hook.rs @@ -84,8 +84,13 @@ impl HookSpec { .and_then(|v| v.get(&language).cloned()); } - if self.options.stages.as_ref().is_none_or(Stages::is_empty) { - self.options.stages = Some(config.default_stages.clone().unwrap_or(Stages::All)); + if self + .options + .stages + .as_ref() + .is_none_or(|stages| stages.is_empty()) + { + self.options.stages = Some(config.default_stages.unwrap_or(Stages::ALL)); } } } @@ -327,7 +332,7 @@ impl HookBuilder { let pass_filenames = options.pass_filenames.unwrap_or(PassFilenames::All); let require_serial = options.require_serial.unwrap_or(false); let verbose = options.verbose.unwrap_or(false); - let stages = options.stages.unwrap_or(Stages::All); + let stages = options.stages.unwrap_or(Stages::ALL); let additional_dependencies = options .additional_dependencies .unwrap_or_default() @@ -926,11 +931,7 @@ mod tests { }, ), default_stages: Some( - Some( - { - Manual, - }, - ), + Stages(manual), ), files: None, exclude: None, @@ -986,11 +987,7 @@ mod tests { ), log_file: None, require_serial: false, - stages: Some( - { - Manual, - }, - ), + stages: Stages(manual), verbose: true, minimum_prek_version: None, priority: 42, @@ -1019,7 +1016,7 @@ mod tests { language: Language::Python, priority: None, options: HookOptions { - stages: Some(Stages::Some(std::collections::BTreeSet::new())), + stages: Some(Stages::from([])), ..Default::default() }, }; @@ -1028,10 +1025,7 @@ mod tests { .build() .await?; - assert_eq!( - hook.stages, - Stages::Some([Stage::Manual].into_iter().collect()) - ); + assert_eq!(hook.stages, Stages::from([Stage::Manual])); Ok(()) } @@ -1050,7 +1044,7 @@ mod tests { hook_spec.apply_project_defaults(&config); - assert_eq!(hook_spec.options.stages, Some(Stages::All)); + assert_eq!(hook_spec.options.stages, Some(Stages::ALL)); } #[tokio::test] @@ -1078,7 +1072,7 @@ mod tests { .build() .await?; - assert_eq!(hook.stages, Stages::Some(std::collections::BTreeSet::new())); + assert_eq!(hook.stages, Stages::from([])); Ok(()) } @@ -1107,7 +1101,7 @@ mod tests { .build() .await?; - assert_eq!(hook.stages, Stages::All); + assert_eq!(hook.stages, Stages::ALL); Ok(()) } @@ -1131,7 +1125,7 @@ mod tests { language: Language::Python, priority: None, options: HookOptions { - stages: Some(Stages::Some(std::collections::BTreeSet::new())), + stages: Some(Stages::from([])), ..Default::default() }, }; @@ -1140,7 +1134,7 @@ mod tests { .build() .await?; - assert_eq!(hook.stages, Stages::All); + assert_eq!(hook.stages, Stages::ALL); Ok(()) } diff --git a/crates/prek/src/snapshots/prek__config__tests__read_config_with_nested_merge_keys.snap b/crates/prek/src/snapshots/prek__config__tests__read_config_with_nested_merge_keys.snap index 3912f1434..ad6b08ad9 100644 --- a/crates/prek/src/snapshots/prek__config__tests__read_config_with_nested_merge_keys.snap +++ b/crates/prek/src/snapshots/prek__config__tests__read_config_with_nested_merge_keys.snap @@ -36,11 +36,7 @@ Config { true, ), stages: Some( - Some( - { - PreCommit, - }, - ), + Stages(pre-commit), ), verbose: None, minimum_prek_version: None,