Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/prek/src/cli/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
106 changes: 69 additions & 37 deletions crates/prek/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
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;
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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -360,6 +362,28 @@ impl From<HookType> 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,
Expand All @@ -373,56 +397,58 @@ impl Stage {
}
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Stages {
All,
Some(BTreeSet<Stage>),
}
#[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<Item = Stage> {
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<Stage> {
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<Vec<Stage>> for Stages {
fn from(value: Vec<Stage>) -> 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)
}
}

Expand Down Expand Up @@ -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
Expand All @@ -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));
}
Expand All @@ -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]
Expand All @@ -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)]
Expand Down
40 changes: 17 additions & 23 deletions crates/prek/src/hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
}
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -926,11 +931,7 @@ mod tests {
},
),
default_stages: Some(
Some(
{
Manual,
},
),
Stages(manual),
),
files: None,
exclude: None,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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()
},
};
Expand All @@ -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(())
}

Expand All @@ -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]
Expand Down Expand Up @@ -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(())
}

Expand Down Expand Up @@ -1107,7 +1101,7 @@ mod tests {
.build()
.await?;

assert_eq!(hook.stages, Stages::All);
assert_eq!(hook.stages, Stages::ALL);
Ok(())
}

Expand All @@ -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()
},
};
Expand All @@ -1140,7 +1134,7 @@ mod tests {
.build()
.await?;

assert_eq!(hook.stages, Stages::All);
assert_eq!(hook.stages, Stages::ALL);
Ok(())
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,7 @@ Config {
true,
),
stages: Some(
Some(
{
PreCommit,
},
),
Stages(pre-commit),
),
verbose: None,
minimum_prek_version: None,
Expand Down
Loading