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-consts/src/env_vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
10 changes: 3 additions & 7 deletions crates/prek/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>,
}

#[derive(Debug, Args)]
Expand Down
8 changes: 7 additions & 1 deletion crates/prek/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -49,6 +50,7 @@ mod resource_limit;
mod run;
#[cfg(feature = "schemars")]
mod schema;
mod settings;
mod store;
mod version;
mod warnings;
Expand Down Expand Up @@ -373,6 +375,10 @@ async fn run(cli: Cli) -> Result<ExitStatus> {
}
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,
Expand All @@ -388,7 +394,7 @@ async fn run(cli: Cli) -> Result<ExitStatus> {
args.jobs,
args.dry_run || args.check,
args.exit_code || args.check,
args.cooldown_days,
settings.cooldown_days,
printer,
)
.await
Expand Down
112 changes: 112 additions & 0 deletions crates/prek/src/settings.rs
Original file line number Diff line number Diff line change
@@ -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<PathBuf> {
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<Option<Self>> {
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<Option<Self>> {
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
) =>
Comment thread
j178 marked this conversation as resolved.
Resolved
{
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<AutoUpdateOptions>,
}

/// Options for the `auto-update` command.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default, rename_all = "snake_case")]
struct AutoUpdateOptions {
cooldown_days: Option<u8>,
}

/// 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(),
}
}
}
22 changes: 22 additions & 0 deletions crates/prek/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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");
Expand Down
182 changes: 182 additions & 0 deletions crates/prek/tests/global_config.rs
Original file line number Diff line number Diff line change
@@ -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
"#);
}
Loading
Loading