Skip to content

Commit 0fa2929

Browse files
authored
Add hook group filters to prek run (#2141)
1 parent 9b0047f commit 0fa2929

33 files changed

Lines changed: 1373 additions & 146 deletions

‎crates/prek/src/cli/hook_impl.rs‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,10 @@ use anstream::eprintln;
88
use anyhow::Result;
99
use itertools::Itertools;
1010
use owo_colors::OwoColorize;
11-
use tokio::io::{AsyncReadExt, AsyncWriteExt};
12-
1311
use prek_consts::env_vars::EnvVars;
12+
use tokio::io::{AsyncReadExt, AsyncWriteExt};
1413

15-
use crate::cli::{self, ExitStatus, RunArgs, flag};
14+
use crate::cli::{self, ExitStatus, RunOptions, flag};
1615
use crate::config::HookType;
1716
use crate::fs::CWD;
1817
use crate::git::GIT_ROOT;
@@ -125,6 +124,8 @@ pub(crate) async fn hook_impl(
125124
config,
126125
includes,
127126
skips,
127+
vec![],
128+
vec![],
128129
Some(hook_type.into()),
129130
run_args.from_ref,
130131
run_args.to_ref,
@@ -244,8 +245,8 @@ async fn to_run_args(
244245
hook_type: HookType,
245246
args: &[OsString],
246247
stdin: &[u8],
247-
) -> Result<Option<RunArgs>> {
248-
let mut run_args = RunArgs::default();
248+
) -> Result<Option<RunOptions>> {
249+
let mut run_args = RunOptions::default();
249250

250251
match hook_type {
251252
HookType::PrePush => {

‎crates/prek/src/cli/mod.rs‎

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ pub(crate) struct RunExtraArgs {
468468

469469
#[allow(clippy::struct_excessive_bools)]
470470
#[derive(Debug, Clone, Default, Args)]
471-
pub(crate) struct RunArgs {
471+
pub(crate) struct RunOptions {
472472
/// Include the specified hooks or projects.
473473
///
474474
/// Supports flexible selector syntax:
@@ -546,15 +546,6 @@ pub(crate) struct RunArgs {
546546
#[arg(long, conflicts_with_all = ["all_files", "files", "directory", "from_ref", "to_ref"])]
547547
pub(crate) last_commit: bool,
548548

549-
/// The stage during which the hook is fired.
550-
///
551-
/// When specified, only hooks configured for that stage (for example `manual`,
552-
/// `pre-commit`, or `pre-push`) will run.
553-
/// Defaults to `pre-commit` if not specified.
554-
/// For hooks specified directly in the command line, fallback to `manual` stage if no hooks found for `pre-commit` stage.
555-
#[arg(long, value_enum, alias = "hook-stage")]
556-
pub(crate) stage: Option<Stage>,
557-
558549
/// When hooks fail, run `git diff` directly afterward.
559550
#[arg(long)]
560551
pub(crate) show_diff_on_failure: bool,
@@ -575,6 +566,37 @@ pub(crate) struct RunArgs {
575566
pub(crate) extra: RunExtraArgs,
576567
}
577568

569+
#[derive(Debug, Clone, Default, Args)]
570+
pub(crate) struct RunArgs {
571+
#[command(flatten)]
572+
pub(crate) options: RunOptions,
573+
574+
/// The stage during which the hook is fired.
575+
///
576+
/// When specified, only hooks configured for that stage (for example `manual`,
577+
/// `pre-commit`, or `pre-push`) will run.
578+
/// When not specified and no group filter is active, this command starts with
579+
/// hooks eligible for `pre-commit`. If no hook is selected and the command
580+
/// named hook IDs, those same IDs are matched again against hooks configured
581+
/// for `manual`. With `--group` or `--no-group`, omitting the stage lets
582+
/// hooks from any configured stage match, using the default file input mode;
583+
/// hooks that only run at `commit-msg` or `prepare-commit-msg` are ignored.
584+
#[arg(long, value_enum, alias = "hook-stage")]
585+
pub(crate) stage: Option<Stage>,
586+
587+
/// Run hooks belonging to the specified group.
588+
///
589+
/// Can be specified multiple times.
590+
#[arg(long = "group", value_name = "GROUP")]
591+
pub(crate) groups: Vec<String>,
592+
593+
/// Do not run hooks belonging to the specified group.
594+
///
595+
/// Can be specified multiple times. Exclusion wins over inclusion.
596+
#[arg(long = "no-group", value_name = "GROUP")]
597+
pub(crate) no_groups: Vec<String>,
598+
}
599+
578600
#[derive(Debug, Clone, Default, Args)]
579601
pub(crate) struct TryRepoArgs {
580602
/// Repository to source hooks from.
@@ -585,7 +607,17 @@ pub(crate) struct TryRepoArgs {
585607
pub(crate) rev: Option<String>,
586608

587609
#[command(flatten)]
588-
pub(crate) run_args: RunArgs,
610+
pub(crate) run_args: RunOptions,
611+
612+
/// The stage during which the hook is fired.
613+
///
614+
/// When specified, only hooks configured for that stage (for example `manual`,
615+
/// `pre-commit`, or `pre-push`) will run.
616+
/// When not specified, this command starts with hooks eligible for
617+
/// `pre-commit`. If no hook is selected and the command named hook IDs,
618+
/// those same IDs are matched again against hooks configured for `manual`.
619+
#[arg(long, value_enum, alias = "hook-stage")]
620+
pub(crate) stage: Option<Stage>,
589621
}
590622

591623
#[derive(Debug, Clone, Copy, clap::ValueEnum, Default, Serialize, Deserialize)]

‎crates/prek/src/cli/run/filter.rs‎

Lines changed: 40 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ impl<'a> ProjectFiles<'a> {
340340

341341
#[derive(Default)]
342342
pub(crate) struct CollectOptions {
343-
pub(crate) hook_stage: Stage,
343+
pub(crate) input_mode: RunInputMode,
344344
pub(crate) from_ref: Option<String>,
345345
pub(crate) to_ref: Option<String>,
346346
pub(crate) all_files: bool,
@@ -358,6 +358,30 @@ impl CollectOptions {
358358
}
359359
}
360360

361+
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
362+
pub(crate) enum RunInputMode {
363+
#[default]
364+
Files,
365+
MessageFile,
366+
NoFiles,
367+
}
368+
369+
impl From<Stage> for RunInputMode {
370+
fn from(stage: Stage) -> Self {
371+
match stage {
372+
Stage::CommitMsg | Stage::PrepareCommitMsg => Self::MessageFile,
373+
Stage::Manual | Stage::PreCommit | Stage::PreMergeCommit | Stage::PrePush => {
374+
Self::Files
375+
}
376+
Stage::PostCheckout
377+
| Stage::PostCommit
378+
| Stage::PostMerge
379+
| Stage::PostRewrite
380+
| Stage::PreRebase => Self::NoFiles,
381+
}
382+
}
383+
}
384+
361385
pub(crate) enum RunInput {
362386
/// File paths relative to the workspace root.
363387
Files(Vec<PathBuf>),
@@ -378,10 +402,10 @@ impl RunInput {
378402
}
379403
}
380404

381-
/// Get hook input for the selected stage.
405+
/// Get hook input for the selected input mode.
382406
pub(crate) async fn collect_run_input(root: &Path, opts: CollectOptions) -> Result<RunInput> {
383407
let CollectOptions {
384-
hook_stage,
408+
input_mode,
385409
from_ref,
386410
to_ref,
387411
all_files,
@@ -390,13 +414,17 @@ pub(crate) async fn collect_run_input(root: &Path, opts: CollectOptions) -> Resu
390414
commit_msg_filename,
391415
} = opts;
392416

393-
if matches!(hook_stage, Stage::PrepareCommitMsg | Stage::CommitMsg) {
394-
let path = commit_msg_filename.expect("commit_msg_filename should be set");
395-
return Ok(RunInput::MessageFile(GIT_ROOT.as_ref()?.join(path)));
396-
}
397-
398417
let git_root = GIT_ROOT.as_ref()?;
399418

419+
match input_mode {
420+
RunInputMode::Files => {}
421+
RunInputMode::MessageFile => {
422+
let path = commit_msg_filename.expect("commit_msg_filename should be set");
423+
return Ok(RunInput::MessageFile(git_root.join(path)));
424+
}
425+
RunInputMode::NoFiles => return Ok(RunInput::Files(vec![])),
426+
}
427+
400428
// The workspace root relative to the git root.
401429
let relative_root = root.strip_prefix(git_root).with_context(|| {
402430
format!(
@@ -409,7 +437,6 @@ pub(crate) async fn collect_run_input(root: &Path, opts: CollectOptions) -> Resu
409437
let filenames = collect_files_from_args(
410438
git_root,
411439
root,
412-
hook_stage,
413440
from_ref,
414441
to_ref,
415442
all_files,
@@ -448,17 +475,12 @@ fn adjust_relative_path(path: &str, new_cwd: &Path) -> Result<PathBuf, std::io::
448475
async fn collect_files_from_args(
449476
git_root: &Path,
450477
workspace_root: &Path,
451-
hook_stage: Stage,
452478
from_ref: Option<String>,
453479
to_ref: Option<String>,
454480
all_files: bool,
455481
files: Vec<String>,
456482
directories: Vec<String>,
457483
) -> Result<Vec<PathBuf>> {
458-
if !hook_stage.operate_on_files() {
459-
return Ok(vec![]);
460-
}
461-
462484
if let (Some(from_ref), Some(to_ref)) = (from_ref, to_ref) {
463485
let files = git::get_changed_files(&from_ref, &to_ref, workspace_root).await?;
464486
debug!(
@@ -533,6 +555,10 @@ async fn collect_files_from_args(
533555
Ok(files)
534556
}
535557

558+
pub(super) const fn stage_uses_message_file_input(stage: Stage) -> bool {
559+
matches!(stage, Stage::CommitMsg | Stage::PrepareCommitMsg)
560+
}
561+
536562
#[cfg(test)]
537563
mod tests {
538564
use super::*;

‎crates/prek/src/cli/run/keeper.rs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@ use std::sync::{Arc, Mutex};
55
use anstream::eprintln;
66
use anyhow::Result;
77
use owo_colors::OwoColorize;
8-
use tracing::{debug, error, trace};
9-
108
use prek_consts::env_vars::EnvVars;
9+
use tracing::{debug, error, trace};
1110

1211
use crate::cleanup::add_cleanup;
1312
use crate::fs::Simplified;

‎crates/prek/src/cli/run/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ pub(crate) use filter::{
55
pub(crate) use install::{InstallCache, install_hooks};
66
pub(crate) use reporter::{HookRunReporter, project_status_marker};
77
pub(crate) use run::run;
8-
pub(crate) use selector::{SelectorSource, Selectors};
8+
pub(crate) use selector::{GroupFilters, SelectorSource, Selectors};
99

1010
mod diff;
1111
mod filter;

0 commit comments

Comments
 (0)