Skip to content
3 changes: 0 additions & 3 deletions crates/prek/src/cli/run/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,9 +332,6 @@ async fn collect_files_from_args(
// so `pre-commit` will ignore user provided directories.
// We do the same here for compatibility.
// For `types: [directory]`, `pre-commit` passes the directory names to the hook directly.

// Fun fact: if a hook specified `types: [directory]`, it won't run in `--all-files` mode.

let (exists, non_exists): (FxHashSet<_>, Vec<_>) =
files.into_iter().partition_map(|filename| {
if std::fs::exists(&filename).unwrap_or(false) {
Expand Down
15 changes: 15 additions & 0 deletions crates/prek/src/hooks/builtin_hooks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ pub(crate) enum BuiltinHooks {
EndOfFileFixer,
FileContentsSorter,
FixByteOrderMarker,
ForbidNewSubmodules,
MixedLineEnding,
NoCommitToBranch,
TrailingWhitespace,
Expand Down Expand Up @@ -95,6 +96,9 @@ impl BuiltinHooks {
Self::FixByteOrderMarker => {
pre_commit_hooks::fix_byte_order_marker(hook, filenames).await
}
Self::ForbidNewSubmodules => {
pre_commit_hooks::forbid_new_submodules(hook, filenames).await
}
Self::MixedLineEnding => pre_commit_hooks::mixed_line_ending(hook, filenames).await,
Self::NoCommitToBranch => pre_commit_hooks::no_commit_to_branch(hook).await,
Self::TrailingWhitespace => {
Expand Down Expand Up @@ -340,6 +344,17 @@ impl BuiltinHook {
..Default::default()
},
},
BuiltinHooks::ForbidNewSubmodules => BuiltinHook {
id: "forbid-new-submodules".to_string(),
name: "forbid new submodules".to_string(),
entry: "forbid-new-submodules".to_string(),
priority: None,
options: HookOptions {
description: Some("Prevent addition of new git submodules.".to_string()),
types: Some(tags::TAG_SET_DIRECTORY),
Comment thread
j178 marked this conversation as resolved.
Resolved
..Default::default()
},
},
BuiltinHooks::MixedLineEnding => BuiltinHook {
id: "mixed-line-ending".to_string(),
name: "mixed line ending".to_string(),
Expand Down
131 changes: 131 additions & 0 deletions crates/prek/src/hooks/pre_commit_hooks/forbid_new_submodules.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
use std::borrow::Cow;
use std::path::Path;

use itertools::Itertools;
use prek_consts::env_vars::EnvVars;

use crate::git;
use crate::hook::Hook;

pub(crate) async fn forbid_new_submodules(
hook: &Hook,
filenames: &[&Path],
) -> Result<(i32, Vec<u8>), anyhow::Error> {
let diff_arg = if let (Ok(from_ref), Ok(to_ref)) = (
EnvVars::var("PRE_COMMIT_FROM_REF"),
EnvVars::var("PRE_COMMIT_TO_REF"),
) {
Cow::Owned(format!("{from_ref}...{to_ref}"))
} else {
Cow::Borrowed("--staged")
Comment thread
j178 marked this conversation as resolved.
Resolved
};

let stdout = git::git_cmd("git diff")?
.current_dir(hook.work_dir())
.arg("diff")
.arg("--relative")
.arg("--diff-filter=A")
Comment thread
j178 marked this conversation as resolved.
Resolved
.arg("--no-ext-diff")
.arg("--raw")
.arg("-z")
.arg(diff_arg.as_ref())
Comment thread
j178 marked this conversation as resolved.
Resolved
.arg("--")
.args(filenames)
.check(true)
Comment thread
j178 marked this conversation as resolved.
Resolved
.output()
.await?
.stdout;

let new_submodules = collect_new_submodules(&stdout);
if new_submodules.is_empty() {
Ok((0, Vec::new()))
} else {
let message = render_message(&new_submodules);
Ok((1, message.into_bytes()))
}
}

fn render_message(new_submodules: &[&str]) -> String {
let mut message = new_submodules
.iter()
.map(|filename| format!("{filename}: new submodule introduced"))
.join("\n");

message.push_str("\n\n");
message.push_str(indoc::indoc! {"
This commit introduces new git submodules.
Did you unintentionally `git add .`?
To fix this, run `git rm <submodule>`.
Also check `.gitmodules` for any unintended changes.
"});

message
}

fn collect_new_submodules(stdout: &[u8]) -> Vec<&str> {
let mut entries = stdout
.split(|&b| b == b'\0')
.filter(|entry| !entry.is_empty());
let mut new_submodules = Vec::new();

while let Some(metadata) = entries.next() {
let Some(filename) = entries.next() else {
break;
};

let Ok(metadata) = std::str::from_utf8(metadata) else {
continue;
};
let Ok(filename) = std::str::from_utf8(filename) else {
continue;
};

// https://git-scm.com/docs/gitdatamodel#Documentation/gitdatamodel.txt-tree
if metadata.split_whitespace().nth(1) == Some("160000") {
new_submodules.push(filename);
}
}

new_submodules
}

#[cfg(test)]
mod tests {
#[test]
fn collect_new_submodules_ignores_non_submodules() {
let stdout = b":000000 100644 0000000 abcdef1 A\0.gitmodules\0";

let new_submodules = super::collect_new_submodules(stdout);

assert!(new_submodules.is_empty());
}
Comment thread
j178 marked this conversation as resolved.
Resolved

#[test]
fn collect_new_submodules_finds_new_submodules() {
let stdout = b":000000 100644 0000000 abcdef1 A\0.gitmodules\0\
:000000 160000 0000000 abcdef2 A\0project2/sub module\0\
:000000 160000 0000000 abcdef3 A\0vendor/dep\0";

let new_submodules = super::collect_new_submodules(stdout);

assert_eq!(new_submodules, vec!["project2/sub module", "vendor/dep"]);
}

#[test]
fn render_message() {
let message = super::render_message(&["project2/sub module", "vendor/dep"]);

assert_eq!(
message,
indoc::indoc! {"
project2/sub module: new submodule introduced
vendor/dep: new submodule introduced

This commit introduces new git submodules.
Did you unintentionally `git add .`?
To fix this, run `git rm <submodule>`.
Also check `.gitmodules` for any unintended changes.
"}
);
}
}
4 changes: 4 additions & 0 deletions crates/prek/src/hooks/pre_commit_hooks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod file_contents_sorter;
mod fix_byte_order_marker;
mod fix_end_of_file;
mod fix_trailing_whitespace;
mod forbid_new_submodules;
mod mixed_line_ending;
mod no_commit_to_branch;
mod shebangs;
Expand All @@ -43,6 +44,7 @@ pub(crate) use file_contents_sorter::file_contents_sorter;
pub(crate) use fix_byte_order_marker::fix_byte_order_marker;
pub(crate) use fix_end_of_file::fix_end_of_file;
pub(crate) use fix_trailing_whitespace::fix_trailing_whitespace;
pub(crate) use forbid_new_submodules::forbid_new_submodules;
pub(crate) use mixed_line_ending::mixed_line_ending;
pub(crate) use no_commit_to_branch::no_commit_to_branch;

Expand All @@ -58,6 +60,7 @@ pub(crate) enum PreCommitHooks {
FileContentsSorter,
EndOfFileFixer,
FixByteOrderMarker,
ForbidNewSubmodules,
CheckJson,
CheckSymlinks,
CheckMergeConflict,
Expand Down Expand Up @@ -95,6 +98,7 @@ impl PreCommitHooks {
Self::FileContentsSorter => file_contents_sorter(hook, filenames).await,
Self::EndOfFileFixer => fix_end_of_file(hook, filenames).await,
Self::FixByteOrderMarker => fix_byte_order_marker(hook, filenames).await,
Self::ForbidNewSubmodules => forbid_new_submodules(hook, filenames).await,
Self::CheckJson => check_json(hook, filenames).await,
Self::CheckSymlinks => check_symlinks(hook, filenames).await,
Self::CheckMergeConflict => check_merge_conflict(hook, filenames).await,
Expand Down
71 changes: 71 additions & 0 deletions crates/prek/tests/builtin_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,77 @@ fn file_contents_sorter_hook() -> Result<()> {
Ok(())
}

#[test]
fn forbid_new_submodules_hook_in_workspace_project() -> Result<()> {
let context = TestContext::new();
let cwd = context.work_dir();
context.init_project();

context.write_pre_commit_config("repos: []\n");
cwd.child("project2").create_dir_all()?;
cwd.child("project2")
.child(PRE_COMMIT_CONFIG_YAML)
.write_str(indoc::indoc! {r"
repos:
- repo: builtin
hooks:
- id: forbid-new-submodules
"})?;

context.git_add(".");
context.git_commit("Initial commit");

let submodule_path = cwd.child("project2/sub module");
submodule_path.create_dir_all()?;
git_cmd(&submodule_path)
.arg("-c")
.arg("init.defaultBranch=master")
.arg("init")
.assert()
.success();
submodule_path.child("README.md").write_str("submodule\n")?;
git_cmd(&submodule_path)
.arg("add")
.arg("README.md")
.assert()
.success();
git_cmd(&submodule_path)
.args(["commit", "-m", "Initial commit"])
.assert()
.success();

git_cmd(cwd)
.args([
"submodule",
"add",
"./project2/sub module",
"project2/sub module",
])
.assert()
.success();

cmd_snapshot!(context.filters(), context.run(), @r"
success: false
exit_code: 1
----- stdout -----
Running hooks for `project2`:
forbid new submodules....................................................Failed
- hook id: forbid-new-submodules
- exit code: 1

sub module: new submodule introduced

This commit introduces new git submodules.
Did you unintentionally `git add .`?
To fix this, run `git rm <submodule>`.
Also check `.gitmodules` for any unintended changes.

----- stderr -----
");

Ok(())
}

#[test]
fn check_yaml_hook() -> Result<()> {
let context = TestContext::new();
Expand Down
9 changes: 9 additions & 0 deletions crates/prek/tests/list_builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ fn list_builtins_basic() {
end-of-file-fixer
file-contents-sorter
fix-byte-order-marker
forbid-new-submodules
mixed-line-ending
no-commit-to-branch
trailing-whitespace
Expand Down Expand Up @@ -98,6 +99,9 @@ fn list_builtins_verbose() {
fix-byte-order-marker
removes utf-8 byte order marker.

forbid-new-submodules
Prevent addition of new git submodules.

mixed-line-ending
replaces or checks mixed line ending.

Expand Down Expand Up @@ -210,6 +214,11 @@ fn list_builtins_json() {
"name": "fix utf-8 byte order marker",
"description": "removes utf-8 byte order marker."
},
{
"id": "forbid-new-submodules",
"name": "forbid new submodules",
"description": "Prevent addition of new git submodules."
},
{
"id": "mixed-line-ending",
"name": "mixed line ending",
Expand Down
1 change: 1 addition & 0 deletions docs/builtin.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Currently, only part of hooks from `https://github.com/pre-commit/pre-commit-hoo
- [`end-of-file-fixer`](https://github.com/pre-commit/pre-commit-hooks#end-of-file-fixer) (Ensure newline at EOF)
- [`file-contents-sorter`](https://github.com/pre-commit/pre-commit-hooks#file-contents-sorter) (Sort lines in explicitly targeted files)
- [`fix-byte-order-marker`](https://github.com/pre-commit/pre-commit-hooks#fix-byte-order-marker) (Remove UTF-8 byte order marker)
- [`forbid-new-submodules`](https://github.com/pre-commit/pre-commit-hooks#forbid-new-submodules) (Prevent addition of new git submodules.)
- [`check-json`](https://github.com/pre-commit/pre-commit-hooks#check-json) (Validate JSON files)
- [`check-toml`](https://github.com/pre-commit/pre-commit-hooks#check-toml) (Validate TOML files)
- [`check-vcs-permalinks`](https://github.com/pre-commit/pre-commit-hooks#check-vcs-permalinks) (Check that VCS links are permalinks)
Expand Down
1 change: 1 addition & 0 deletions prek.schema.json

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

Loading