diff --git a/crates/prek-consts/src/env_vars.rs b/crates/prek-consts/src/env_vars.rs index cc830dddd..b18f1a40f 100644 --- a/crates/prek-consts/src/env_vars.rs +++ b/crates/prek-consts/src/env_vars.rs @@ -35,6 +35,7 @@ impl EnvVars { // PREK internal environment variables pub const PREK_INTERNAL__TEST_DIR: &'static str = "PREK_INTERNAL__TEST_DIR"; + pub const PREK_INTERNAL__USER_CONFIG_PATH: &'static str = "PREK_INTERNAL__USER_CONFIG_PATH"; pub const PREK_INTERNAL__SORT_FILENAMES: &'static str = "PREK_INTERNAL__SORT_FILENAMES"; pub const PREK_INTERNAL__SKIP_POST_CHECKOUT: &'static str = "PREK_INTERNAL__SKIP_POST_CHECKOUT"; pub const PREK_INTERNAL__RUN_ORIGINAL_PRE_COMMIT: &'static str = diff --git a/crates/prek/src/cli/mod.rs b/crates/prek/src/cli/mod.rs index 366fb2c3f..b3fccd0d7 100644 --- a/crates/prek/src/cli/mod.rs +++ b/crates/prek/src/cli/mod.rs @@ -757,14 +757,10 @@ pub(crate) struct AutoUpdateArgs { /// Minimum release age (in days) required for a version to be eligible. /// /// The age is computed from the tag creation timestamp for annotated tags, or from the tagged commit timestamp for lightweight tags. + /// Defaults to `auto_update.cooldown_days` in the global config, or `0` when unset. /// A value of `0` disables this check. - #[arg( - long, - value_name = "DAYS", - default_value_t = 0, - conflicts_with = "bleeding_edge" - )] - pub(crate) cooldown_days: u8, + #[arg(long, value_name = "DAYS", conflicts_with = "bleeding_edge")] + pub(crate) cooldown_days: Option, } #[derive(Debug, Args)] diff --git a/crates/prek/src/main.rs b/crates/prek/src/main.rs index 744b60b5a..b56859acf 100644 --- a/crates/prek/src/main.rs +++ b/crates/prek/src/main.rs @@ -26,6 +26,7 @@ use crate::cli::{ use crate::cli::{SelfCommand, SelfNamespace, SelfUpdateArgs}; use crate::printer::Printer; use crate::run::USE_COLOR; +use crate::settings::{AutoUpdateSettings, FilesystemOptions}; use crate::store::Store; mod archive; @@ -49,6 +50,7 @@ mod resource_limit; mod run; #[cfg(feature = "schemars")] mod schema; +mod settings; mod store; mod version; mod warnings; @@ -373,6 +375,10 @@ async fn run(cli: Cli) -> Result { } Command::SampleConfig(args) => cli::sample_config(args.file.into(), args.format, printer), Command::AutoUpdate(args) => { + let filesystem = FilesystemOptions::user()?; + let settings = AutoUpdateSettings::resolve(&args, filesystem.as_ref()); + show_settings!(settings); + cli::auto_update( &store, cli.globals.config, @@ -388,7 +394,7 @@ async fn run(cli: Cli) -> Result { args.jobs, args.dry_run || args.check, args.exit_code || args.check, - args.cooldown_days, + settings.cooldown_days, printer, ) .await diff --git a/crates/prek/src/settings.rs b/crates/prek/src/settings.rs new file mode 100644 index 000000000..f1e5a7d43 --- /dev/null +++ b/crates/prek/src/settings.rs @@ -0,0 +1,112 @@ +use std::io::ErrorKind; +use std::ops::Deref; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use etcetera::BaseStrategy; +use prek_consts::env_vars::EnvVars; +use serde::Deserialize; + +use crate::cli::AutoUpdateArgs; + +fn user_config_path() -> Option { + if let Some(path) = EnvVars::var_os(EnvVars::PREK_INTERNAL__USER_CONFIG_PATH) { + return Some(PathBuf::from(path)); + } + + etcetera::choose_base_strategy() + .ok() + .map(|strategy| strategy.config_dir().join("prek").join("prek.toml")) +} + +/// Options loaded from a user-level `prek.toml` file. +#[derive(Debug, Clone)] +pub(crate) struct FilesystemOptions(Options); + +impl FilesystemOptions { + /// Load user-level options from the platform config directory. + pub(crate) fn user() -> Result> { + let Some(path) = user_config_path() else { + tracing::trace!( + "Skipping global config lookup because no platform config directory was found" + ); + return Ok(None); + }; + + tracing::trace!(path = %path.display(), "Searching for global config"); + Self::from_file(&path) + } + + fn from_file(path: &Path) -> Result> { + let content = match fs_err::read_to_string(path) { + Ok(content) => { + tracing::debug!(path = %path.display(), "Read global config"); + content + } + Err(err) + if matches!( + err.kind(), + ErrorKind::NotFound | ErrorKind::NotADirectory | ErrorKind::PermissionDenied + ) => + { + tracing::trace!( + path = %path.display(), + "Global config not found or inaccessible, skipping" + ); + return Ok(None); + } + Err(err) => { + return Err(err) + .with_context(|| format!("Failed to read global config `{}`", path.display())); + } + }; + + toml::from_str(&content) + .map(Self) + .map(Some) + .with_context(|| format!("Failed to parse global config `{}`", path.display())) + } +} + +impl Deref for FilesystemOptions { + type Target = Options; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +/// Options as represented in the global `prek.toml` file. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default, rename_all = "snake_case")] +pub(crate) struct Options { + auto_update: Option, +} + +/// Options for the `auto-update` command. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default, rename_all = "snake_case")] +struct AutoUpdateOptions { + cooldown_days: Option, +} + +/// Resolved settings for the `auto-update` command. +#[derive(Debug, Clone, Copy)] +pub(crate) struct AutoUpdateSettings { + pub(crate) cooldown_days: u8, +} + +impl AutoUpdateSettings { + pub(crate) fn resolve(args: &AutoUpdateArgs, filesystem: Option<&FilesystemOptions>) -> Self { + Self { + cooldown_days: args + .cooldown_days + .or_else(|| { + filesystem + .and_then(|fs| fs.auto_update.as_ref()) + .and_then(|au| au.cooldown_days) + }) + .unwrap_or_default(), + } + } +} diff --git a/crates/prek/tests/common/mod.rs b/crates/prek/tests/common/mod.rs index 8350a1e3e..2ec907f11 100644 --- a/crates/prek/tests/common/mod.rs +++ b/crates/prek/tests/common/mod.rs @@ -169,6 +169,11 @@ impl TestContext { cmd }; + cmd.env( + EnvVars::PREK_INTERNAL__USER_CONFIG_PATH, + self.user_config_path().path(), + ); + // Disable git autocrlf to avoid line ending issues in tests. cmd.env("GIT_CONFIG_COUNT", "1") .env("GIT_CONFIG_KEY_0", "core.autocrlf") @@ -177,6 +182,23 @@ impl TestContext { cmd } + fn user_config_path(&self) -> ChildPath { + self.home_dir + .child("config") + .child("prek") + .child("prek.toml") + } + + pub fn write_user_config(&self, content: &str) { + let config_dir = self.home_dir.child("config").child("prek"); + config_dir + .create_dir_all() + .expect("Failed to create user config directory"); + self.user_config_path() + .write_str(content) + .expect("Failed to write user config"); + } + pub fn run(&self) -> Command { let mut command = self.command(); command.arg("run"); diff --git a/crates/prek/tests/global_config.rs b/crates/prek/tests/global_config.rs new file mode 100644 index 000000000..7c5ff328f --- /dev/null +++ b/crates/prek/tests/global_config.rs @@ -0,0 +1,182 @@ +use crate::common::{TestContext, cmd_snapshot}; + +mod common; + +#[test] +fn global_config_missing_file_uses_defaults() { + let context = TestContext::new(); + + cmd_snapshot!(context.filters(), context.auto_update().arg("--show-settings"), @" + success: true + exit_code: 0 + ----- stdout ----- + GlobalArgs { + config: None, + cd: None, + color: Auto, + refresh: false, + help: (), + no_progress: false, + quiet: 0, + verbose: 0, + log_file: None, + no_log_file: false, + version: (), + show_settings: true, + } + AutoUpdateSettings { + cooldown_days: 0, + } + + ----- stderr ----- + "); +} + +#[test] +fn global_config_applies_cooldown_days() { + let context = TestContext::new(); + context.write_user_config(indoc::indoc! {r" + [auto_update] + cooldown_days = 3 + "}); + + cmd_snapshot!(context.filters(), context.auto_update().arg("--show-settings"), @" + success: true + exit_code: 0 + ----- stdout ----- + GlobalArgs { + config: None, + cd: None, + color: Auto, + refresh: false, + help: (), + no_progress: false, + quiet: 0, + verbose: 0, + log_file: None, + no_log_file: false, + version: (), + show_settings: true, + } + AutoUpdateSettings { + cooldown_days: 3, + } + + ----- stderr ----- + "); +} + +#[test] +fn global_config_cli_args_override_file() { + let context = TestContext::new(); + context.write_user_config(indoc::indoc! {r" + [auto_update] + cooldown_days = 3 + "}); + + cmd_snapshot!( + context.filters(), + context + .auto_update() + .arg("--show-settings") + .arg("--cooldown-days") + .arg("0"), + @" + success: true + exit_code: 0 + ----- stdout ----- + GlobalArgs { + config: None, + cd: None, + color: Auto, + refresh: false, + help: (), + no_progress: false, + quiet: 0, + verbose: 0, + log_file: None, + no_log_file: false, + version: (), + show_settings: true, + } + AutoUpdateSettings { + cooldown_days: 0, + } + + ----- stderr ----- + "); +} + +#[test] +fn global_config_ignores_unknown_options() { + let context = TestContext::new(); + context.write_user_config(indoc::indoc! {r#" + future_option = true + + [auto_update] + cooldown_days = 3 + future_option = "ignored" + "#}); + + cmd_snapshot!(context.filters(), context.auto_update().arg("--show-settings"), @" + success: true + exit_code: 0 + ----- stdout ----- + GlobalArgs { + config: None, + cd: None, + color: Auto, + refresh: false, + help: (), + no_progress: false, + quiet: 0, + verbose: 0, + log_file: None, + no_log_file: false, + version: (), + show_settings: true, + } + AutoUpdateSettings { + cooldown_days: 3, + } + + ----- stderr ----- + "); +} + +#[test] +fn global_config_invalid_file_reports_parse_error() { + let context = TestContext::new(); + context.write_user_config(indoc::indoc! {r#" + [auto_update] + cooldown_days = "soon" + "#}); + + cmd_snapshot!(context.filters(), context.auto_update().arg("--show-settings"), @r#" + success: false + exit_code: 2 + ----- stdout ----- + GlobalArgs { + config: None, + cd: None, + color: Auto, + refresh: false, + help: (), + no_progress: false, + quiet: 0, + verbose: 0, + log_file: None, + no_log_file: false, + version: (), + show_settings: true, + } + + ----- stderr ----- + error: Failed to parse global config `[HOME]/config/prek/prek.toml` + caused by: TOML parse error at line 2, column 17 + | + 2 | cooldown_days = "soon" + | ^^^^^^ + invalid type: string "soon", expected u8 + "#); +} diff --git a/docs/configuration.md b/docs/configuration.md index d22a08dd1..2542df5c9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -24,6 +24,24 @@ Both formats are first-class and will be supported long-term. They describe the - id: trailing-whitespace ``` +## Global configuration + +`prek` also reads an optional user-level global config from the platform config directory: + +- Linux and macOS: `~/.config/prek/prek.toml` (or `$XDG_CONFIG_HOME/prek/prek.toml` when `XDG_CONFIG_HOME` is set) +- 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. + +The first supported global setting is the default cooldown for `prek auto-update`: + +```toml +[auto_update] +cooldown_days = 7 +``` + +`prek auto-update --cooldown-days ` overrides this value for a single command invocation. + ## Pre-commit compatibility `prek` is **fully compatible** with [`pre-commit`](https://pre-commit.com/) YAML configs, so your existing `.pre-commit-config.yaml` files work unchanged. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 2fbd6b776..06e1fe3cb 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -561,8 +561,8 @@ prek auto-update [OPTIONS]
  • never: Disables colored output
  • --config, -c config

    Path to alternate config file

    --cooldown-days days

    Minimum release age (in days) required for a version to be eligible.

    -

    The age is computed from the tag creation timestamp for annotated tags, or from the tagged commit timestamp for lightweight tags. A value of 0 disables this check.

    -

    [default: 0]

    --dry-run

    Do not write changes to the config file, only display what would be changed

    +

    The age is computed from the tag creation timestamp for annotated tags, or from the tagged commit timestamp for lightweight tags. Defaults to auto_update.cooldown_days in the global config, or 0 when unset. A value of 0 disables this check.

    +
    --dry-run

    Do not write changes to the config file, only display what would be changed

    --exclude-repo repo

    Do not update this repository. This option may be specified multiple times

    --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.

    diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 694d43875..0a1846dac 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -2,6 +2,30 @@ This page documents the configuration keys that `prek` understands. +## Global config file + +`prek` reads an optional user-level global config from: + +- Linux and macOS: `~/.config/prek/prek.toml` (or `$XDG_CONFIG_HOME/prek/prek.toml` when `XDG_CONFIG_HOME` is set) +- Windows: `%APPDATA%\prek\prek.toml` + +This file stores user-level `prek` settings and does not define project hooks. + +### `auto_update.cooldown_days` + +Default cooldown for `prek auto-update`. + +- Type: integer days +- Default: `0` +- CLI override: `prek auto-update --cooldown-days ` + +```toml +[auto_update] +cooldown_days = 7 +``` + +The age is computed from the tag creation timestamp for annotated tags, or from the tagged commit timestamp for lightweight tags. A value of `0` disables the cooldown check. + ## Top-level keys ### `repos` (required)