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
1 change: 1 addition & 0 deletions crates/prek/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 7 additions & 5 deletions crates/prek/src/cli/update/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,19 @@ struct RepoUsage<'a> {
current_frozen_site: Option<FrozenCommentSite>,
}

/// 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,
/// The currently configured `rev` for this target.
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<RepoUsage<'a>>,
}

Expand Down Expand Up @@ -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))
Expand All @@ -439,8 +442,7 @@ pub(crate) async fn update(
let outcomes: Vec<RepoUpdate<'_>> = 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
})
Expand Down
46 changes: 27 additions & 19 deletions crates/prek/src/cli/update/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<RepoTargetKey<'a>, 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<u8>,
filesystem: Option<&FilesystemOptions>,
) -> Result<Vec<RepoSource<'a>>> {
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
Expand Down Expand Up @@ -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(),
})
Expand All @@ -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 }
Expand Down Expand Up @@ -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<Vec<RepoUpdate<'a>>> {
let tmp_dir = tempfile::tempdir()?;
Expand Down Expand Up @@ -240,7 +250,6 @@ pub(super) async fn evaluate_repo_source<'a>(
repo_path,
target,
bleeding_edge,
freeze,
&tag_timestamps,
&update_tag_timestamps,
)
Expand All @@ -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<ResolvedRepoUpdate<'a>> {
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 6 additions & 2 deletions crates/prek/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1143,6 +1143,7 @@ where
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub(crate) struct UpdateOptions {
pub(crate) cooldown_days: Option<u8>,
pub(crate) freeze: Option<bool>,
}

// TODO: warn sensible regex
Expand Down Expand Up @@ -1946,13 +1947,16 @@ mod tests {
let yaml = indoc::indoc! {r"
update:
cooldown_days: 7
freeze: true
repos: []
"};
let result = serde_saphyr::from_str::<Config>(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)))
);
}

Comment thread
j178 marked this conversation as resolved.
Resolved
Expand Down
80 changes: 70 additions & 10 deletions crates/prek/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PathBuf> {
if let Some(path) = EnvVars.var_os(EnvVars::PREK_INTERNAL__USER_CONFIG_PATH) {
return Some(PathBuf::from(path));
Expand Down Expand Up @@ -87,50 +89,59 @@ pub(crate) struct Options {
#[serde(default, rename_all = "snake_case")]
struct UpdateOptions {
cooldown_days: Option<u8>,
freeze: Option<bool>,
}

/// 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<u8>,
project: Option<&ProjectUpdateOptions>,
filesystem: Option<&FilesystemOptions>,
project_cooldown_days: Option<u8>,
) -> 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() {
let options: Options = toml::from_str(
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)))
);
Comment thread
j178 marked this conversation as resolved.
Resolved
}

Expand All @@ -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);
}
}
12 changes: 10 additions & 2 deletions crates/prek/tests/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -1069,7 +1071,7 @@ fn update_freeze() -> Result<()> {
.chain([(r"[a-f0-9]{40}", r"[COMMIT_SHA]")])
.collect::<Vec<_>>();

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 -----
Expand All @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -2843,7 +2851,7 @@ fn update_freeze_toml() -> Result<()> {
.chain([(r"[a-f0-9]{40}", r"[COMMIT_SHA]")])
.collect::<Vec<_>>();

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 -----
Expand Down
1 change: 1 addition & 0 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand Down
Loading
Loading