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
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ toml = { version = "0.9.5", default-features = false, features = [
"preserve_order",
"serde",
] }
toml_edit = { version = "0.24.0" }
tracing = { version = "0.1.40" }
tracing-subscriber = { version = "0.3.20", features = ["env-filter"] }
unicode-width = { version = "0.2.0", default-features = false }
Expand Down
9 changes: 6 additions & 3 deletions crates/prek-consts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ use std::path::Path;

use env_vars::EnvVars;

pub const CONFIG_FILE: &str = ".pre-commit-config.yaml";
pub const ALT_CONFIG_FILE: &str = ".pre-commit-config.yml";
pub const MANIFEST_FILE: &str = ".pre-commit-hooks.yaml";
pub const PRE_COMMIT_CONFIG_YAML: &str = ".pre-commit-config.yaml";
pub const PRE_COMMIT_CONFIG_YML: &str = ".pre-commit-config.yml";
pub const PREK_TOML: &str = "prek.toml";
pub const PRE_COMMIT_HOOKS_YAML: &str = ".pre-commit-hooks.yaml";

pub static CONFIG_FILENAMES: &[&str] = &[PREK_TOML, PRE_COMMIT_CONFIG_YAML, PRE_COMMIT_CONFIG_YML];

/// Prepend paths to the current $PATH, returning the joined result.
///
Expand Down
1 change: 1 addition & 0 deletions crates/prek/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ toml = { workspace = true, default-features = false, features = [
"preserve_order",
"serde",
] }
toml_edit = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
unicode-width = { workspace = true }
Expand Down
122 changes: 105 additions & 17 deletions crates/prek/src/cli/auto_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ use futures::StreamExt;
use itertools::Itertools;
use lazy_regex::regex;
use owo_colors::OwoColorize;
use prek_consts::MANIFEST_FILE;
use prek_consts::PRE_COMMIT_HOOKS_YAML;
use rustc_hash::FxHashMap;
use rustc_hash::FxHashSet;
use toml_edit::DocumentMut;
use tracing::{debug, trace};

use crate::cli::ExitStatus;
Expand Down Expand Up @@ -377,7 +378,7 @@ async fn checkout_and_validate_manifest(
if cfg!(windows) {
git::git_cmd("git show")?
.arg("show")
.arg(format!("{rev}:{MANIFEST_FILE}"))
.arg(format!("{rev}:{PRE_COMMIT_HOOKS_YAML}"))
.current_dir(repo_path)
.remove_git_envs()
.stdout(Stdio::null())
Expand All @@ -391,15 +392,15 @@ async fn checkout_and_validate_manifest(
.arg("--quiet")
.arg(rev)
.arg("--")
.arg(MANIFEST_FILE)
.arg(PRE_COMMIT_HOOKS_YAML)
.current_dir(repo_path)
.remove_git_envs()
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.await?;

let manifest = config::read_manifest(&repo_path.join(MANIFEST_FILE))?;
let manifest = config::read_manifest(&repo_path.join(PRE_COMMIT_HOOKS_YAML))?;
let new_hook_ids = manifest
.hooks
.into_iter()
Expand Down Expand Up @@ -452,8 +453,104 @@ async fn get_best_candidate_tag(repo: &Path, rev: &str, current_rev: &str) -> Re
}

async fn write_new_config(path: &Path, revisions: &[Option<Revision>]) -> Result<()> {
let mut lines = fs_err::tokio::read_to_string(path)
.await?
let content = fs_err::tokio::read_to_string(path).await?;
let new_content = match path.extension() {
Some(ext) if ext.eq_ignore_ascii_case("toml") => {
render_updated_toml_config(path, &content, revisions)?
}
_ => render_updated_yaml_config(path, &content, revisions)?,
};

fs_err::tokio::write(path, new_content)
.await
.with_context(|| {
format!(
"Failed to write updated config file `{}`",
path.user_display()
)
})?;

Ok(())
}

fn render_updated_toml_config(
path: &Path,
content: &str,
revisions: &[Option<Revision>],
) -> Result<String> {
let mut doc = content.parse::<DocumentMut>()?;
let Some(repos) = doc
.get_mut("repos")
.and_then(|item| item.as_array_of_tables_mut())
else {
anyhow::bail!("Missing `[[repos]]` array in `{}`", path.user_display());
};

let mut remote_repos = Vec::new();
for table in repos.iter_mut() {
let repo_value = table
.get("repo")
.and_then(|item| item.as_value())
.and_then(|value| value.as_str())
.unwrap_or_default();

if matches!(repo_value, "local" | "meta" | "builtin") {
continue;
}

if !table.contains_key("rev") {
anyhow::bail!(
"Found remote repo without `rev` in `{}`",
path.user_display()
);
}

remote_repos.push(table);
}

if remote_repos.len() != revisions.len() {
anyhow::bail!(
"Found {} remote repos in `{}` but expected {}, file content may have changed",
remote_repos.len(),
path.user_display(),
revisions.len()
);
}

for (table, revision) in remote_repos.into_iter().zip_eq(revisions) {
let Some(revision) = revision else {
continue;
};

let Some(value) = table.get_mut("rev").and_then(|item| item.as_value_mut()) else {
continue;
};

let suffix = value
.decor()
.suffix()
.and_then(|s| s.as_str())
.filter(|s| !s.trim_start().starts_with("# frozen:"))
.map(str::to_string);

*value = toml_edit::Value::from(revision.rev.clone());

if let Some(frozen) = &revision.frozen {
value.decor_mut().set_suffix(format!(" # frozen: {frozen}"));
} else if let Some(suffix) = suffix {
value.decor_mut().set_suffix(suffix);
}
}

Ok(doc.to_string())
}

fn render_updated_yaml_config(
path: &Path,
content: &str,
revisions: &[Option<Revision>],
) -> Result<String> {
let mut lines = content
.split_inclusive('\n')
.map(ToString::to_string)
.collect::<Vec<_>>();
Expand Down Expand Up @@ -495,7 +592,7 @@ async fn write_new_config(path: &Path, revisions: &[Option<Revision>]) -> Result

let comment = if let Some(frozen) = &revision.frozen {
format!(" # frozen: {frozen}")
} else if caps[5].trim().starts_with("# frozen:") {
} else if caps[5].trim_start().starts_with("# frozen:") {
String::new()
} else {
caps[5].to_string()
Expand All @@ -507,16 +604,7 @@ async fn write_new_config(path: &Path, revisions: &[Option<Revision>]) -> Result
);
}

fs_err::tokio::write(path, lines.join("").as_bytes())
.await
.with_context(|| {
format!(
"Failed to write updated config file `{}`",
path.user_display()
)
})?;

Ok(())
Ok(lines.join(""))
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion crates/prek/src/cli/cache_gc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ pub(crate) async fn cache_gc(
config
}
Err(err) => match err {
ConfigError::NotFound(_) => {
ConfigError::Io(e) if e.kind() == std::io::ErrorKind::NotFound => {
debug!(path = %config_path.display(), "Tracked config does not exist, dropping");
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/prek/src/cli/hook_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub(crate) async fn hook_impl(
} else {
// Try to discover a project from current directory (after `--cd`)
match Project::discover(config.as_deref(), &CWD) {
Err(e) if matches!(e, workspace::Error::MissingPreCommitConfig) => {
Err(e @ workspace::Error::MissingConfigFile) => {
return if allow_missing_config {
Ok(ExitStatus::Success)
} else {
Expand Down
4 changes: 2 additions & 2 deletions crates/prek/src/cli/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::sync::Arc;
use anyhow::{Context, Result};
use bstr::ByteSlice;
use owo_colors::OwoColorize;
use prek_consts::{ALT_CONFIG_FILE, CONFIG_FILE};
use prek_consts::CONFIG_FILENAMES;
use same_file::is_same_file;

use crate::cli::reporter::{HookInitReporter, HookInstallReporter};
Expand Down Expand Up @@ -137,7 +137,7 @@ fn get_hook_types(
.clone()
.unwrap_or_default()
} else {
let fallbacks = [CONFIG_FILE, ALT_CONFIG_FILE]
let fallbacks = CONFIG_FILENAMES
.iter()
.map(Path::new)
.filter(|p| p.exists());
Expand Down
41 changes: 35 additions & 6 deletions crates/prek/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ use clap::builder::styling::{AnsiColor, Effects};
use clap::builder::{ArgPredicate, Styles};
use clap::{ArgAction, Args, Parser, Subcommand, ValueHint};
use clap_complete::engine::ArgValueCompleter;
use serde::{Deserialize, Serialize};

use prek_consts::CONFIG_FILE;
use prek_consts::env_vars::EnvVars;
use serde::{Deserialize, Serialize};

use crate::config::{HookType, Language, Stage};

Expand Down Expand Up @@ -590,16 +588,47 @@ pub(crate) struct ValidateManifestArgs {
pub(crate) manifests: Vec<PathBuf>,
}

#[expect(clippy::option_option)]
#[derive(Debug, Args)]
pub(crate) struct SampleConfigArgs {
/// Write the sample config to a file (`.pre-commit-config.yaml` by default).
/// Write the sample config to a file.
///
/// Defaults to `.pre-commit-config.yaml` unless `--format toml` is set,
/// which uses `prek.toml`. If a path is provided without `--format`,
/// the format is inferred from the file extension (`.toml` uses TOML).
#[arg(
short,
long,
num_args = 0..=1,
default_missing_value = CONFIG_FILE,
)]
pub(crate) file: Option<PathBuf>,
pub(crate) file: Option<Option<PathBuf>>,

/// Select the sample configuration format.
#[arg(long, value_enum)]
pub(crate) format: Option<SampleConfigFormat>,
}
Comment thread
j178 marked this conversation as resolved.
Resolved

#[derive(Debug, Copy, Clone, clap::ValueEnum)]
pub(crate) enum SampleConfigFormat {
Yaml,
Toml,
}

#[derive(Debug)]
pub(crate) enum SampleConfigTarget {
Stdout,
DefaultFile,
Path(PathBuf),
}

impl From<Option<Option<PathBuf>>> for SampleConfigTarget {
fn from(value: Option<Option<PathBuf>>) -> Self {
match value {
None => Self::Stdout,
Some(None) => Self::DefaultFile,
Some(Some(path)) => Self::Path(path),
}
}
}

#[derive(Debug, Args)]
Expand Down
Loading
Loading