diff --git a/crates/prek/src/cli/mod.rs b/crates/prek/src/cli/mod.rs index 8d19160b7..d554fa0ad 100644 --- a/crates/prek/src/cli/mod.rs +++ b/crates/prek/src/cli/mod.rs @@ -774,6 +774,7 @@ pub(crate) struct UpdateArgs { #[arg(long)] pub(crate) bleeding_edge: bool, /// Store "frozen" hashes in `rev` instead of tag names. + /// Defaults to `update.freeze` in the project or global config, or `false` when unset. #[arg(long)] pub(crate) freeze: bool, /// Only update this repository. This option may be specified multiple times. diff --git a/crates/prek/src/cli/update/mod.rs b/crates/prek/src/cli/update/mod.rs index 671d02281..2467985a1 100644 --- a/crates/prek/src/cli/update/mod.rs +++ b/crates/prek/src/cli/update/mod.rs @@ -51,7 +51,7 @@ struct RepoUsage<'a> { current_frozen_site: Option, } -/// One distinct `repo + rev + hook set` target that should be evaluated. +/// One distinct `repo + rev + hook set + update settings` target that should be evaluated. struct RepoTarget<'a> { /// The remote repository URL. repo: &'a str, @@ -59,9 +59,11 @@ struct RepoTarget<'a> { current_rev: &'a str, /// The resolved cooldown window to apply when selecting an update for this target. cooldown_days: u8, + /// Whether the selected revision should be stored as a frozen commit hash. + freeze: bool, /// The sorted hook ids that must still exist after updating this target. required_hook_ids: Vec<&'a str>, - /// Every config usage that shares this exact `repo + rev + hook set`. + /// Every config usage that shares this exact target configuration. usages: Vec>, } @@ -430,7 +432,8 @@ pub(crate) async fn update( }; let reporter = UpdateReporter::new(printer); - let repo_sources = collect_repo_sources(&workspace, cooldown_days, filesystem.as_ref())?; + let repo_sources = + collect_repo_sources(&workspace, freeze, cooldown_days, filesystem.as_ref())?; warn_missing_repos(&repo_sources, &filter_repos, &tag_filters); let sources = repo_sources.iter().filter(|repo_source| { (filter_repos.is_empty() || filter_repos.iter().any(|repo| repo == repo_source.repo)) @@ -439,8 +442,7 @@ pub(crate) async fn update( let outcomes: Vec> = futures_util::stream::iter(sources) .map(async |repo_source| { let progress = reporter.on_update_start(repo_source.repo); - let result = - evaluate_repo_source(repo_source, bleeding_edge, freeze, &tag_filters).await; + let result = evaluate_repo_source(repo_source, bleeding_edge, &tag_filters).await; reporter.on_update_complete(progress); result }) diff --git a/crates/prek/src/cli/update/source.rs b/crates/prek/src/cli/update/source.rs index c0b07f10a..8f275eff5 100644 --- a/crates/prek/src/cli/update/source.rs +++ b/crates/prek/src/cli/update/source.rs @@ -21,29 +21,33 @@ use crate::fs::Simplified; use crate::settings::{FilesystemOptions, UpdateSettings}; use crate::workspace::Workspace; -type RepoTargetKey<'a> = (&'a str, Vec<&'a str>, u8); +/// Identifies repo usages that can share one update evaluation. +#[derive(Eq, Hash, PartialEq)] +struct RepoTargetKey<'a> { + current_rev: &'a str, + required_hook_ids: Vec<&'a str>, + cooldown_days: u8, + freeze: bool, +} + type RepoTargetsByKey<'a> = FxHashMap, RepoTarget<'a>>; type RepoSourcesByRepo<'a> = FxHashMap<&'a str, RepoTargetsByKey<'a>>; -/// Collects the configured remote repos grouped by fetch source, revision, and hook set. +/// Collects configured remote repos grouped by fetch source, revision, hooks, and settings. pub(super) fn collect_repo_sources<'a>( workspace: &'a Workspace, + cli_freeze: bool, cli_cooldown_days: Option, filesystem: Option<&FilesystemOptions>, ) -> Result>> { let mut repo_sources: RepoSourcesByRepo<'a> = FxHashMap::default(); for project in workspace.projects() { - let settings = UpdateSettings::resolve( - cli_cooldown_days, - filesystem, - project - .config() - .update - .as_ref() - .and_then(|options| options.cooldown_days), - ); - let cooldown_days = settings.cooldown_days; + let project_update = project.config().update.as_ref(); + let UpdateSettings { + cooldown_days, + freeze, + } = UpdateSettings::resolve(cli_freeze, cli_cooldown_days, project_update, filesystem); let remote_count = project .config() .repos @@ -82,15 +86,21 @@ pub(super) fn collect_repo_sources<'a>( required_hook_ids.dedup(); let targets = repo_sources.entry(remote_repo.repo.as_str()).or_default(); - let target_key = (remote_repo.rev.as_str(), required_hook_ids, cooldown_days); + let target_key = RepoTargetKey { + current_rev: remote_repo.rev.as_str(), + required_hook_ids, + cooldown_days, + freeze, + }; let target = match targets.entry(target_key) { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => { - let required_hook_ids = entry.key().1.clone(); + let required_hook_ids = entry.key().required_hook_ids.clone(); entry.insert(RepoTarget { repo: remote_repo.repo.as_str(), current_rev: remote_repo.rev.as_str(), cooldown_days, + freeze, required_hook_ids, usages: Vec::new(), }) @@ -116,6 +126,7 @@ pub(super) fn collect_repo_sources<'a>( a.current_rev .cmp(b.current_rev) .then_with(|| a.cooldown_days.cmp(&b.cooldown_days)) + .then_with(|| a.freeze.cmp(&b.freeze)) .then_with(|| a.required_hook_ids.cmp(&b.required_hook_ids)) }); RepoSource { repo, targets } @@ -194,7 +205,6 @@ async fn collect_frozen_mismatches<'a>( pub(super) async fn evaluate_repo_source<'a>( repo_source: &'a RepoSource<'a>, bleeding_edge: bool, - freeze: bool, tag_filters: &TagFilters, ) -> Result>> { let tmp_dir = tempfile::tempdir()?; @@ -240,7 +250,6 @@ pub(super) async fn evaluate_repo_source<'a>( repo_path, target, bleeding_edge, - freeze, &tag_timestamps, &update_tag_timestamps, ) @@ -252,12 +261,11 @@ pub(super) async fn evaluate_repo_source<'a>( Ok(updates) } -/// Resolves one configured `repo + rev + hook set` entry within an already-fetched remote repository. +/// Resolves one configured repo target within an already-fetched remote repository. async fn evaluate_repo_target<'a>( repo_path: &Path, target: &'a RepoTarget<'a>, bleeding_edge: bool, - freeze: bool, tag_timestamps: &[TagTimestamp], update_tag_timestamps: &[TagTimestamp], ) -> Result> { @@ -302,7 +310,7 @@ async fn evaluate_repo_target<'a>( } }; - let (rev, frozen) = if freeze { + let (rev, frozen) = if target.freeze { let exact = resolve_revision_to_commit(repo_path, &rev).await?; if rev.eq_ignore_ascii_case(&exact) { (rev, None) diff --git a/crates/prek/src/config.rs b/crates/prek/src/config.rs index 3faebb491..05715ec23 100644 --- a/crates/prek/src/config.rs +++ b/crates/prek/src/config.rs @@ -1143,6 +1143,7 @@ where #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub(crate) struct UpdateOptions { pub(crate) cooldown_days: Option, + pub(crate) freeze: Option, } // TODO: warn sensible regex @@ -1946,13 +1947,16 @@ mod tests { let yaml = indoc::indoc! {r" update: cooldown_days: 7 + freeze: true repos: [] "}; let result = serde_saphyr::from_str::(yaml).unwrap(); assert_eq!( - result.update.and_then(|options| options.cooldown_days), - Some(7) + result + .update + .map(|options| (options.cooldown_days, options.freeze)), + Some((Some(7), Some(true))) ); } diff --git a/crates/prek/src/settings.rs b/crates/prek/src/settings.rs index 94fbf23df..3e4dd788a 100644 --- a/crates/prek/src/settings.rs +++ b/crates/prek/src/settings.rs @@ -7,6 +7,8 @@ use etcetera::BaseStrategy; use prek_consts::env_vars::{EnvVars, EnvVarsRead}; use serde::Deserialize; +use crate::config::UpdateOptions as ProjectUpdateOptions; + fn user_config_path() -> Option { if let Some(path) = EnvVars.var_os(EnvVars::PREK_INTERNAL__USER_CONFIG_PATH) { return Some(PathBuf::from(path)); @@ -87,36 +89,42 @@ pub(crate) struct Options { #[serde(default, rename_all = "snake_case")] struct UpdateOptions { cooldown_days: Option, + freeze: Option, } /// Resolved settings for the `update` command. #[derive(Debug, Clone, Copy)] pub(crate) struct UpdateSettings { pub(crate) cooldown_days: u8, + pub(crate) freeze: bool, } impl UpdateSettings { pub(crate) fn resolve( + cli_freeze: bool, cli_cooldown_days: Option, + project: Option<&ProjectUpdateOptions>, filesystem: Option<&FilesystemOptions>, - project_cooldown_days: Option, ) -> Self { + let filesystem_update = filesystem.and_then(|fs| fs.update.as_ref()); Self { cooldown_days: cli_cooldown_days - .or(project_cooldown_days) - .or_else(|| { - filesystem - .and_then(|fs| fs.update.as_ref()) - .and_then(|options| options.cooldown_days) - }) + .or_else(|| project.and_then(|options| options.cooldown_days)) + .or_else(|| filesystem_update.and_then(|options| options.cooldown_days)) .unwrap_or_default(), + freeze: cli_freeze + || project + .and_then(|options| options.freeze) + .or_else(|| filesystem_update.and_then(|options| options.freeze)) + .unwrap_or_default(), } } } #[cfg(test)] mod tests { - use super::Options; + use super::{FilesystemOptions, Options, UpdateSettings}; + use crate::config::UpdateOptions as ProjectUpdateOptions; #[test] fn options_deserializes_update_settings() { @@ -124,13 +132,16 @@ mod tests { r" [update] cooldown_days = 7 + freeze = true ", ) .unwrap(); assert_eq!( - options.update.and_then(|options| options.cooldown_days), - Some(7) + options + .update + .map(|options| (options.cooldown_days, options.freeze)), + Some((Some(7), Some(true))) ); } @@ -149,4 +160,53 @@ mod tests { Some(7) ); } + + #[test] + fn update_settings_uses_global_freeze() { + let filesystem = FilesystemOptions( + toml::from_str( + r" + [update] + freeze = true + ", + ) + .unwrap(), + ); + + let settings = UpdateSettings::resolve(false, None, None, Some(&filesystem)); + + assert!(settings.freeze); + } + + #[test] + fn update_settings_project_freeze_overrides_global() { + let filesystem = FilesystemOptions( + toml::from_str( + r" + [update] + freeze = true + ", + ) + .unwrap(), + ); + + let project = ProjectUpdateOptions { + cooldown_days: None, + freeze: Some(false), + }; + let settings = UpdateSettings::resolve(false, None, Some(&project), Some(&filesystem)); + + assert!(!settings.freeze); + } + + #[test] + fn update_settings_cli_freeze_overrides_project() { + let project = ProjectUpdateOptions { + cooldown_days: None, + freeze: Some(false), + }; + let settings = UpdateSettings::resolve(true, None, Some(&project), None); + + assert!(settings.freeze); + } } diff --git a/crates/prek/tests/update.rs b/crates/prek/tests/update.rs index 1a976c8d1..f529f23fc 100644 --- a/crates/prek/tests/update.rs +++ b/crates/prek/tests/update.rs @@ -1054,6 +1054,8 @@ fn update_freeze() -> Result<()> { .success(); context.write_pre_commit_config(&indoc::formatdoc! {r" + update: + freeze: true repos: - repo: {} rev: v1.0.0 @@ -1069,7 +1071,7 @@ fn update_freeze() -> Result<()> { .chain([(r"[a-f0-9]{40}", r"[COMMIT_SHA]")]) .collect::>(); - cmd_snapshot!(filters.clone(), context.update().arg("--freeze").arg("--cooldown-days").arg("0"), @" + cmd_snapshot!(filters.clone(), context.update().arg("--cooldown-days").arg("0"), @" success: true exit_code: 0 ----- stdout ----- @@ -1084,6 +1086,8 @@ fn update_freeze() -> Result<()> { { filters => filters.clone() }, { assert_snapshot!(context.read(PRE_COMMIT_CONFIG_YAML), @" + update: + freeze: true repos: - repo: [HOME]/test-repos/freeze-repo rev: [COMMIT_SHA] # frozen: v1.1.0 @@ -2813,6 +2817,10 @@ fn update_freeze_toml() -> Result<()> { context.init_project(); let repo_path = create_local_git_repo(&context, "freeze-repo", &["v1.0.0", "v1.1.0"])?; + context.write_user_config(indoc::indoc! {r" + [update] + freeze = true + "}); // Make sure the "# frozen: v1.1.0" comment works correctly by adding a tag without dot git_cmd(&repo_path) .arg("tag") @@ -2843,7 +2851,7 @@ fn update_freeze_toml() -> Result<()> { .chain([(r"[a-f0-9]{40}", r"[COMMIT_SHA]")]) .collect::>(); - cmd_snapshot!(filters.clone(), context.update().arg("--freeze").arg("--cooldown-days").arg("0"), @" + cmd_snapshot!(filters.clone(), context.update().arg("--cooldown-days").arg("0"), @" success: true exit_code: 0 ----- stdout ----- diff --git a/docs/compatibility.md b/docs/compatibility.md index 0a969dc34..f9bab5bff 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -31,6 +31,7 @@ | Compatibility spelling | Preferred `prek` spelling | | -- | -- | | `auto_update.cooldown_days` | `update.cooldown_days` | +| `auto_update.freeze` | `update.freeze` | ## Why the CLI is reorganized diff --git a/docs/configuration.md b/docs/configuration.md index 625910f54..0154720b4 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -32,7 +32,7 @@ Both formats are first-class and will be supported long-term. They describe the - Windows: `%APPDATA%\prek\prek.toml` This file is for user-level `prek` settings, not hook definitions. Project hooks still live in the project config files described below. -For the supported global settings, see the [configuration reference](reference/configuration.md#global-updatecooldown_days). +For the supported global settings, see the [configuration reference](reference/configuration.md#global-config-file). ## Pre-commit compatibility @@ -51,6 +51,7 @@ They work in both YAML and TOML, but they only matter for compatibility if you s - Top-level: - [`update.cooldown_days`](reference/configuration.md#updatecooldown_days) + - [`update.freeze`](reference/configuration.md#updatefreeze) - [`default_env`](reference/configuration.md#default_env) - [`minimum_prek_version`](reference/configuration.md#prek-only-minimum-prek-version-config) - [`orphan`](reference/configuration.md#prek-only-orphan) diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 5f0de33ab..a4730cb04 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -575,7 +575,7 @@ prek update [OPTIONS]
--exclude-tag pattern

Ignore tags matching this glob pattern. This option may be specified multiple times.

For example, use --exclude-tag nightly to skip a moving tag, or --exclude-tag '*-{alpha,beta,rc}*' to skip common prerelease tags.

--exit-code

Exit with status 1 if updates are available

-
--freeze

Store "frozen" hashes in rev instead of tag names

+
--freeze

Store "frozen" hashes in rev instead of tag names. Defaults to update.freeze in the project or global config, or false when unset

--help, -h

Display the concise help for this command

--include-tag pattern

Only consider tags matching this glob pattern. This option may be specified multiple times.

For example, use --include-tag 'v*' to only consider version tags and ignore tags such as nightly.

diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 77b4196cb..ffe3f4160 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -11,6 +11,26 @@ This page documents the configuration keys that `prek` understands. This file stores user-level `prek` settings and does not define project hooks. +### Global `update.freeze` + +Whether [`prek update`](cli.md#prek-update) stores commit hashes in `rev` instead of tag names by default. + +- Type: boolean +- Default: `false` +- CLI override: [`prek update --freeze`](cli.md#prek-update--freeze) + +```toml +[update] +freeze = true +``` + +Project configs can also set [`update.freeze`](#updatefreeze). The effective precedence is: + +1. [`prek update --freeze`](cli.md#prek-update--freeze), which forces freezing on +2. project config +3. user-level global config +4. default `false` + ### Global `update.cooldown_days` Default cooldown for [`prek update`](cli.md#prek-update). @@ -357,6 +377,34 @@ Project default cooldown for [`prek update`](cli.md#prek-update). In workspace mode, this setting is scoped to the project config file that defines it. It applies only to that project and is not inherited by nested projects. Sub-projects use their own `update` setting, then the user-level global config, then the default. If two projects use the same repo URL with different cooldown settings, [`prek update`](cli.md#prek-update) fetches the repo once but evaluates each project with its own cooldown. +### `update.freeze` + +!!! note "prek-only" + + This top-level key is a `prek` extension and is not recognized by upstream `pre-commit`. + +Whether [`prek update`](cli.md#prek-update) stores commit hashes in `rev` instead of tag names by default. + +- Type: boolean +- Default: inherited from the user-level global config, or `false` +- CLI override: [`prek update --freeze`](cli.md#prek-update--freeze), which forces freezing on + +=== "prek.toml" + + ```toml + [update] + freeze = true + ``` + +=== ".pre-commit-config.yaml" + + ```yaml + update: + freeze: true + ``` + +In workspace mode, this setting is scoped to the project config file that defines it. It applies only to that project and is not inherited by nested projects. A project can set `freeze: false` to override a user-level `true`. If two projects use the same repo URL with different freeze settings, [`prek update`](cli.md#prek-update) fetches the repo once but writes each project's configured revision in the requested form. + ### `minimum_prek_version` diff --git a/prek.schema.json b/prek.schema.json index 77226e7b0..fdad66aeb 100644 --- a/prek.schema.json +++ b/prek.schema.json @@ -152,6 +152,9 @@ "type": "integer", "maximum": 255, "minimum": 0 + }, + "freeze": { + "type": "boolean" } } },