Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

Git: browsing a folder runs none of the programs its repository names

gelenmedya7443968a9c2d
diff --git a/crates/rf-win/src/git.rs b/crates/rf-win/src/git.rs
index c88c1580..97f56050 100644
--- a/crates/rf-win/src/git.rs
+++ b/crates/rf-win/src/git.rs
@@ -108,81 +108,110 @@ pub fn repo_root(dir: &Path) -> Option<PathBuf> {
dir.ancestors().find(|a| a.join(".git").exists()).map(Path::to_path_buf)
}
-/// Settings in a repository's own config that make `git status` run a program: a file monitor, and clean / process filters (status
-/// runs them to compare files), in its submodules too. A folder someone else made (a downloaded project) could start anything that way
-/// just by being browsed; for the commands we run they are switched off.
-///
-/// The filters are asked of Git's own reading of the repository's config, not read from `.git/config` by us: a private security report
-/// showed four ways past a reading of our own (a section name in capitals, `[FILTER "x"]`; a `.git` FILE pointing at the real folder;
-/// filters in a file the config includes; a filter whose name holds `=`, which `-c` cannot name). A filter `-c` cannot switch off, or a
-/// config that cannot be read, makes the command refuse to run (see [`REFUSE`]).
-fn neutralize_repo_programs(c: &mut Command, root: &Path) {
- c.args(["-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false"]);
- // (a submodule's status is read by a Git run inside it, with ITS config)
- c.args(["-c", "status.submoduleSummary=false", "-c", "submodule.recurse=false", "-c", "diff.ignoreSubmodules=all"]);
- match repo_filters(root) {
- Some(names) => {
- for name in names {
- for key in ["clean", "smudge", "process"] {
- c.args(["-c", &format!("filter.{name}.{key}=")]);
- }
- c.args(["-c", &format!("filter.{name}.required=false")]);
- }
+/// What a repository's own settings need before git may look at its files.
+#[derive(Debug, Default, PartialEq, Eq)]
+struct RepoOverrides {
+ /// `-c` arguments that switch the repository's filters off.
+ args: Vec<String>,
+ /// A partial clone: objects can be missing here, and git would fetch them on the way.
+ partial: bool,
+}
+
+/// A clean / smudge / process filter is a program, and git runs it to compare files: a folder someone else made (a downloaded
+/// project) could start anything that way just by being browsed. `listing` is git's own list of the settings in effect
+/// (`config --list -z --name-only`, with each one's scope in front when `scoped`); it runs nothing, and it knows what a reading of
+/// `.git/config` cannot (every spelling, includes, worktrees, submodules). The filters the repository defines are switched off; the
+/// user's own (the system's and the global ones, such as Git LFS) stay. Without scopes all of them are taken for the repository's.
+/// `Err` when a filter's name cannot be put on a command line safely: nothing that reads files may run then.
+fn overrides_from(listing: &[u8], scoped: bool) -> Result<RepoOverrides> {
+ let mut fields: Vec<&[u8]> = listing.split(|&b| b == 0).collect();
+ fields.pop(); // after the last NUL
+ // a Git inside WSL may be started by a shell that greets first (see `git_program`): the greeting stands before the first field
+ if let Some(first) = fields.first_mut() {
+ *first = first.rsplit(|&b| b == b'\n').next().unwrap_or_default();
+ // one that does not end its line hides where the first name begins; a scope it hides is not the user's, which is safe
+ if !scoped && first.windows(7).skip(1).any(|w| w.eq_ignore_ascii_case(b"filter.")) {
+ bail!("git config çıktısı anlaşılamadı");
}
- None => {
- c.arg(REFUSE);
+ }
+ if scoped && fields.len() % 2 != 0 {
+ bail!("git config çıktısı anlaşılamadı");
+ }
+ let entries: Vec<(bool, &[u8])> = if scoped {
+ fields.chunks_exact(2).map(|e| (!matches!(e[0], b"system" | b"global" | b"command"), e[1])).collect()
+ } else {
+ fields.into_iter().map(|k| (true, k)).collect()
+ };
+ let starts = |key: &[u8], prefix: &str| key.get(..prefix.len()).is_some_and(|k| k.eq_ignore_ascii_case(prefix.as_bytes()));
+ let ends = |key: &[u8], suffix: &str| {
+ key.len().checked_sub(suffix.len()).is_some_and(|at| key[at..].eq_ignore_ascii_case(suffix.as_bytes()))
+ };
+ // Git LFS runs the programs of its extensions, so a repository that names one makes the user's own filter run it
+ let every = entries.iter().any(|&(repo, key)| repo && starts(key, "lfs.extension."));
+ let mut names = std::collections::BTreeSet::new();
+ let mut partial = false;
+ for (repo, key) in entries {
+ partial |= ends(key, ".promisor") || ends(key, ".partialclonefilter") || ends(key, "extensions.partialclone");
+ if (!repo && !every) || !starts(key, "filter.") {
+ continue;
}
+ // filter.<name>.<variable>; `filter.<variable>` alone belongs to no filter. The name may be empty: `* filter=` uses that one.
+ let rest = &key["filter.".len()..];
+ let Some(dot) = rest.iter().rposition(|&b| b == b'.') else { continue };
+ let name = &rest[..dot];
+ // `-c` ends the key at the first '=', and quotes, backslashes, `$`, other bytes… may not reach git as they are (Windows'
+ // command line, a git run through a shell, Unicode forms). No real filter has such a name.
+ if !name.iter().all(|b| b.is_ascii_alphanumeric() || b"-_. ".contains(b)) {
+ bail!("Depo ayarlarındaki bir süzgeç güvenle kapatılamıyor: {}", String::from_utf8_lossy(name));
+ }
+ names.insert(String::from_utf8_lossy(name).into_owned());
}
+ let mut args = Vec::new();
+ for name in names {
+ for setting in ["clean=", "smudge=", "process=", "required=false"] {
+ args.extend(["-c".to_string(), format!("filter.{name}.{setting}")]);
+ }
+ }
+ Ok(RepoOverrides { args, partial })
}
-/// An option Git does not know: given before the command, Git stops at once with a usage error, before it reads the repository. What
-/// a repository we cannot make safe gets instead of its command.
-const REFUSE: &str = "--rustyfiles-refuses-this-repository";
-
-/// The names of the filters the repository's own config (and what it includes) defines, as Git reads them; `None` when one cannot be
-/// switched off by `-c` (its name holds `=` or a character no key may have) or the config cannot be read.
-fn repo_filters(root: &Path) -> Option<Vec<String>> {
- let mut c = git_program::command();
- c.args(["-c", "core.fsmonitor=false", "config", "--local", "--includes", "--list", "-z", "--name-only"])
- .current_dir(root)
- .env("GIT_TERMINAL_PROMPT", "0")
- .stdin(Stdio::null())
- .creation_flags(CREATE_NO_WINDOW);
- let out = output(&mut c).ok()?;
- // (an empty config: exit code 1 and nothing printed)
- if !out.status.success() && !out.stdout.is_empty() {
- return None;
+fn repo_overrides(root: &Path) -> Result<RepoOverrides> {
+ // (by the same program that will look at the files: a Git inside WSL has other settings than one of Windows)
+ let list = |args: &[&str]| output(git_base(root).args(["config", "--list", "-z", "--name-only"]).args(args)).map_err(spawn_err);
+ let out = list(&["--show-scope"])?;
+ if out.status.success() {
+ return overrides_from(whole(&out.stdout, true)?, true);
}
- filter_names(&String::from_utf8_lossy(&out.stdout))
+ // git before 2.26 has no --show-scope
+ let out = list(&[])?;
+ if !out.status.success() {
+ bail!("git config başarısız: {}", String::from_utf8_lossy(&out.stderr).trim());
+ }
+ overrides_from(whole(&out.stdout, false)?, false)
}
-/// The filter names among `git config --list -z --name-only`'s keys (`filter.<name>.<key>`, the name keeping its case and its dots).
-/// `None` when a name cannot be given to `-c` safely.
-fn filter_names(listed: &str) -> Option<Vec<String>> {
- let mut names: Vec<String> = Vec::new();
- for key in listed.split(['\0', '\n']).filter(|k| !k.is_empty()) {
- let Some(rest) = key.strip_prefix("filter.").or_else(|| key.get(..7).filter(|p| p.eq_ignore_ascii_case("filter.")).map(|_| &key[7..])) else {
- continue;
- };
- let Some((name, _var)) = rest.rsplit_once('.') else { continue };
- if name.is_empty() || name.contains('=') || name.chars().any(|ch| ch.is_control()) {
- return None;
- }
- if !names.iter().any(|n| n == name) {
- names.push(name.to_string());
- }
+/// `listing` if git came to its end: the last settings it lists are the ones [`git_base`] gives it. A chosen program that says all
+/// is well and passes on only a part, or nothing, must not read as "no filters".
+fn whole(listing: &[u8], scoped: bool) -> Result<&[u8]> {
+ let ours: &[u8] = if scoped { b"command\0core.untrackedcache\0" } else { b"core.untrackedcache\0" };
+ if !listing.windows(ours.len()).any(|w| w == ours) {
+ bail!("git config çıktısı eksik");
}
- Some(names)
+ Ok(listing)
}
-/// A Git command (the program is the one chosen in Settings). Run it with [`output`] or [`spawn`].
-fn git_cmd(root: &Path) -> Command {
+/// A Git command (the program is the one chosen in Settings) in `root`, without the file monitor the repository may name (a program
+/// too). Does not switch its filters off: only for what never looks at a file's content. Run it with [`output`] or [`spawn`].
+fn git_base(root: &Path) -> Command {
let mut c = git_program::command();
- neutralize_repo_programs(&mut c, root);
- c.arg("--no-optional-locks")
+ c.args(["-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false", "--no-optional-locks"])
+ // (a submodule's status is read by a Git run inside it, with ITS config)
+ .args(["-c", "status.submoduleSummary=false", "-c", "submodule.recurse=false", "-c", "diff.ignoreSubmodules=all"])
.current_dir(root)
.env("GIT_OPTIONAL_LOCKS", "0")
.env("GIT_TERMINAL_PROMPT", "0")
+ // `git config` would list this file instead of the settings the other commands use
+ .env_remove("GIT_CONFIG")
.stdin(Stdio::null())
.creation_flags(CREATE_NO_WINDOW);
c
@@ -198,10 +227,45 @@ fn spawn(c: &mut Command) -> std::io::Result<Child> {
c.spawn()
}
+/// [`git_base`] for reading while browsing: nothing of the repository's settings that only a deeper look would need is run either.
+/// In a partial clone git fetches a missing object by itself, with the program (`remote.<name>.uploadpack`, `core.sshCommand`…) the
+/// repository names, and `log.showSignature` runs its `gpg.program`. The `-c` forms are for a git the environment does not reach.
+fn git_read(root: &Path) -> Command {
+ let mut c = git_base(root);
+ c.args(["-c", "log.showSignature=false", "-c", "protocol.allow=never"]);
+ for p in ["file", "ssh", "git", "http", "https", "ext", "fd"] {
+ c.args(["-c", &format!("protocol.{p}.allow=never")]);
+ }
+ c.env("GIT_NO_LAZY_FETCH", "1").env("GIT_ALLOW_PROTOCOL", "none");
+ c
+}
+
+/// [`git_base`] with the repository's filters switched off ([`overrides_from`]).
+fn git_cmd(root: &Path) -> Result<Command> {
+ let o = repo_overrides(root)?;
+ let mut c = git_base(root);
+ c.args(o.args);
+ Ok(c)
+}
+
+const STATUS: [&str; 7] =
+ ["status", "--porcelain=v2", "--branch", "-z", "--untracked-files=normal", "--ignored=traditional", "--ignore-submodules=dirty"];
+
+/// Added to [`STATUS`] in a partial clone. 1.0 is git's way to write 100% without a `%`, which a chosen program is not given.
+const EXACT_RENAMES: &str = "--find-renames=1.0";
+
/// Runs `git status` for the repository at `repo_root` (use [`repo_root`] to find it).
-/// Errors when git is not installed or the command fails.
+/// Errors when git is not installed or the command fails. A submodule counts as changed when another commit is checked out in it,
+/// not when its files are: to tell, git would run status inside it, with filters of its own that cannot be named from here.
pub fn status(repo_root: &Path) -> Result<GitStatus> {
- let out = run_git(repo_root, &["status", "--porcelain=v2", "--branch", "-z", "--untracked-files=normal", "--ignored=traditional"])?;
+ let o = repo_overrides(repo_root)?;
+ let mut c = git_read(repo_root);
+ c.args(o.args).args(STATUS);
+ if o.partial {
+ // telling a renamed and changed file needs contents a partial clone may not have: identical ones only
+ c.arg(EXACT_RENAMES);
+ }
+ let out = output(&mut c).map_err(spawn_err)?;
if !out.status.success() {
bail!("git status başarısız: {}", String::from_utf8_lossy(&out.stderr).trim());
}
@@ -430,7 +494,10 @@ fn spawn_err(e: std::io::Error) -> anyhow::Error {
/// Runs git and returns the raw output (even on a non-zero exit).
fn run_git(root: &Path, args: &[&str]) -> Result<Output> {
- output(git_cmd(root).args(args)).map_err(spawn_err)
+ // these never look at a file, so they need not ask for the repository's filters first
+ let reads = args.first().is_some_and(|a| ["config", "for-each-ref", "remote", "show-ref", "symbolic-ref"].contains(a));
+ let mut c = if reads { git_read(root) } else { git_cmd(root)? };
+ output(c.args(args)).map_err(spawn_err)
}
/// Runs git and returns stdout; on failure bails with `what: <stderr>`.
@@ -771,7 +838,7 @@ fn upstream_of(root: &Path, branch: &str) -> Option<String> {
/// `git fetch --all --prune` with live progress lines.
pub fn fetch(root: &Path, on_progress: &mut dyn FnMut(&str)) -> Result<()> {
require_remote(root)?;
- let mut c = git_cmd(root);
+ let mut c = git_cmd(root)?;
c.args(["fetch", "--all", "--prune", "--progress"]);
run_streaming(c, "git fetch", on_progress)
}
@@ -785,7 +852,7 @@ pub fn pull(root: &Path, on_progress: &mut dyn FnMut(&str)) -> Result<()> {
if upstream_of(root, &branch).is_none() {
bail!("'{branch}' dalının izlediği bir uzak dal yok");
}
- let mut c = git_cmd(root);
+ let mut c = git_cmd(root)?;
let has_rebase_cfg = run_git(root, &["config", "--get", "pull.rebase"]).map(|o| o.status.success()).unwrap_or(false);
if !has_rebase_cfg {
c.args(["-c", "pull.rebase=false"]);
@@ -801,7 +868,7 @@ pub fn push(root: &Path, on_progress: &mut dyn FnMut(&str)) -> Result<()> {
let Some(branch) = current_branch(root) else {
bail!("Ayrık HEAD durumunda gönderilemez");
};
- let mut c = git_cmd(root);
+ let mut c = git_cmd(root)?;
c.args(["push", "--progress"]);
if upstream_of(root, &branch).is_none() {
let remote = remotes.iter().find(|r| *r == "origin").unwrap_or(&remotes[0]);
@@ -869,7 +936,7 @@ pub fn commit_all(root: &Path, message: &str) -> Result<()> {
return git_text(root, &["commit", "-q", "-m", message], FAILED).map(|_| ());
}
// A chosen program is handed the message on its input: as an argument it may meet a shell (see `git_program`).
- let mut c = git_cmd(root);
+ let mut c = git_cmd(root)?;
c.args(["commit", "-q", "-F", "-"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = spawn(&mut c).map_err(spawn_err)?;
let mut stdin = child.stdin.take().expect("stdin piped");
@@ -898,7 +965,7 @@ pub fn clone(url: &str, dest_parent: &Path, on_progress: &mut dyn FnMut(&str)) -
let name = last.strip_suffix(".git").unwrap_or(last);
let name = if name.is_empty() { "repo" } else { name };
std::fs::create_dir_all(dest_parent).map_err(|e| anyhow::Error::new(e).context("Hedef klasör oluşturulamadı"))?;
- let mut c = git_cmd(dest_parent);
+ let mut c = git_cmd(dest_parent)?;
// (a repository named "remote" is one wslgit would take for a command, see `git_program`; "./remote" is not)
let dest = if git_program::may_use_shell() { format!("./{name}") } else { name.to_string() };
c.args(["clone", "--progress", "--", url, &dest]);
@@ -920,7 +987,7 @@ pub struct Commit {
/// `git log -1` for `path` (or HEAD when `None`). `None` when there is no such commit.
pub fn last_commit(root: &Path, path: Option<&Path>) -> Option<Commit> {
- let mut c = git_cmd(root);
+ let mut c = git_read(root);
c.args(["log", "-1", "--format=%h%x00%s%x00%an%x00%ct"]);
if let Some(p) = path {
c.arg("--").arg(p);
@@ -951,7 +1018,7 @@ pub fn last_commits_of_children(root: &Path, dir: &Path, names: &[String], max_c
if wanted.is_empty() {
return out;
}
- let mut c = git_cmd(root);
+ let mut c = git_read(root);
c.args(["-c", "core.quotepath=false", "log", "--no-renames", "--name-only", "--format=%x01%h%x1f%s%x1f%an%x1f%ct", "--"])
.arg(if rel.is_empty() { ".".to_string() } else { rel.clone() })
.stdout(Stdio::piped())
@@ -1094,11 +1161,368 @@ mod tests {
}
}
+ /// A repository made to run a program when git looks at it. The program is a shell command (git runs these with its own shell
+ /// on Windows too) that leaves a marker behind.
+ struct Evil {
+ tmp: PathBuf,
+ repo: PathBuf,
+ }
+
+ impl Drop for Evil {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.tmp);
+ }
+ }
+
+ impl Evil {
+ /// `None` without git. `f.txt` is committed and then changed to as many bytes, so that git has to compare the contents.
+ fn new(tag: &str) -> Option<Evil> {
+ let tmp = std::env::temp_dir().join(format!("rf-git-evil-{tag}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let repo = tmp.join("repo");
+ std::fs::create_dir_all(&repo).unwrap();
+ let e = Evil { tmp, repo };
+ if !git(&e.tmp, &["--version"]) {
+ return None;
+ }
+ Self::fill(&e.repo);
+ Some(e)
+ }
+
+ fn fill(repo: &Path) {
+ assert!(git(repo, &["init", "-q"]));
+ std::fs::write(repo.join("f.txt"), "a\n").unwrap();
+ assert!(git(repo, &["add", "f.txt"]));
+ assert!(git(repo, &["commit", "-q", "-m", "x"]));
+ std::fs::write(repo.join("f.txt"), "b\n").unwrap();
+ }
+
+ fn marker(&self) -> PathBuf {
+ self.tmp.join("ran")
+ }
+
+ /// The program, for a config file. Works as a filter and as any other program git starts.
+ fn program(&self) -> String {
+ format!("echo x > '{}'; :", self.marker().display().to_string().replace('\\', "/"))
+ }
+
+ /// The `clean =` line; the value is quoted, as `;` would start a comment.
+ fn clean(&self) -> String {
+ format!("clean = \"{}\"\n", self.program())
+ }
+
+ fn append(&self, file: &str, text: &str) {
+ let path = self.repo.join(file);
+ let old = std::fs::read_to_string(&path).unwrap_or_default();
+ std::fs::write(path, old + text).unwrap();
+ }
+
+ /// Whether the program ran since the last call.
+ fn ran(&self) -> bool {
+ std::fs::remove_file(self.marker()).is_ok()
+ }
+
+ /// Plain git does run the program in `dir` (else the test shows nothing); our status must not, whatever its answer is.
+ #[track_caller]
+ fn check(&self, dir: &Path) -> Result<GitStatus> {
+ let _ = self.ran();
+ git(dir, &["--no-optional-locks", "status", "--porcelain=v2"]);
+ assert!(self.ran(), "plain git does not run the program: the test is wrong");
+ let st = status(dir);
+ assert!(!self.ran(), "a program from the repository's config ran");
+ st
+ }
+
+ /// [`check`](Self::check) for a filter in `.git/config` whose section is spelled `section` and that `.gitattributes` calls
+ /// `attr`.
+ #[track_caller]
+ fn check_filter(tag: &str, section: &str, attr: &str) -> Option<Result<GitStatus>> {
+ let e = Evil::new(tag)?;
+ e.append(".git/config", &format!("{section} {}", e.clean()));
+ e.append(".gitattributes", &format!("* filter={attr}\n"));
+ Some(e.check(&e.repo))
+ }
+ }
+
+ #[test]
+ fn status_runs_no_filter_however_its_section_is_spelled() {
+ for (i, (section, attr)) in [
+ ("[filter \"ev\"]\n", "ev"),
+ ("[filter \"ev\"]", "ev"),
+ ("[Filter \"ev\"]\n", "ev"),
+ ("[FILTER \"ev\"] # c\n", "ev"),
+ ("[filter.EV]\n", "ev"),
+ ("[core] x = 1\n[filter \"ev\"]\n", "ev"),
+ ("[filter \"e\\v\"]\n", "ev"),
+ ("[filter \"a.b-c_d\"]\n", "a.b-c_d"),
+ // `* filter=` uses the filter without a name
+ ("[filter \"\"]\n", ""),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let Some(st) = Evil::check_filter(&format!("spelling{i}"), section, attr) else { return };
+ let st = st.unwrap_or_else(|e| panic!("{section}: {e:#}"));
+ assert_eq!(st.files.get(Path::new("f.txt")), Some(&FileState::Modified), "{section}");
+ }
+ }
+
+ #[test]
+ fn status_refuses_a_filter_whose_name_cannot_be_overridden() {
+ for (i, (section, attr)) in [
+ ("[filter \"a=b\"]\n", "a=b"),
+ ("[filter \"a\\\"b\"]\n", "a\"b"),
+ ("[filter \"a\\\\b\"]\n", "a\\b"),
+ ("[filter \"a$b\"]\n", "a$b"),
+ ("[filter \"süzgeç\"]\n", "süzgeç"),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let Some(st) = Evil::check_filter(&format!("name{i}"), section, attr) else { return };
+ assert!(st.is_err(), "{section}");
+ }
+ }
+
+ #[test]
+ fn status_runs_no_smudge_or_process_filter() {
+ let Some(e) = Evil::new("process") else { return };
+ e.append(".git/config", &format!("[Filter \"ev\"]\nrequired = true\nprocess = \"{}\"\n", e.program()));
+ e.append(".gitattributes", "* filter=ev\n");
+ assert!(e.check(&e.repo).is_ok());
+ }
+
+ #[test]
+ fn status_runs_no_filter_of_an_included_file() {
+ for (i, (include, more)) in [
+ ("[include]", ""),
+ ("[includeIf \"gitdir:**\"]", ""),
+ ("[includeIf \"hasconfig:remote.*.url:https://e/**\"]", "[remote \"o\"]\nurl = https://e/x\n"),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let Some(e) = Evil::new(&format!("include{i}")) else { return };
+ e.append(".git/extra", &format!("[filter \"ev\"]\n{}", e.clean()));
+ e.append(".git/config", &format!("{include}\npath = extra\n{more}"));
+ e.append(".gitattributes", "* filter=ev\n");
+ assert!(e.check(&e.repo).is_ok(), "{include}");
+ }
+ }
+
+ #[test]
+ fn status_runs_no_filter_of_a_worktrees_config() {
+ // .git is a file there, and the config is the main repository's
+ let Some(e) = Evil::new("linked") else { return };
+ let linked = e.tmp.join("linked");
+ assert!(git(&e.repo, &["worktree", "add", "-q", "../linked", "HEAD"]));
+ e.append(".git/config", &format!("[filter \"ev\"]\n{}", e.clean()));
+ std::fs::write(linked.join(".gitattributes"), "* filter=ev\n").unwrap();
+ std::fs::write(linked.join("f.txt"), "b\n").unwrap();
+ assert!(linked.join(".git").is_file());
+ assert!(e.check(&linked).is_ok());
+
+ let Some(e) = Evil::new("wtconfig") else { return };
+ e.append(".git/config", "[extensions]\nworktreeConfig = true\n");
+ e.append(".git/config.worktree", &format!("[filter \"ev\"]\n{}", e.clean()));
+ e.append(".gitattributes", "* filter=ev\n");
+ assert!(e.check(&e.repo).is_ok());
+ }
+
+ #[test]
+ fn status_runs_no_filter_of_a_submodule() {
+ let Some(e) = Evil::new("submodule") else { return };
+ let sub = e.repo.join("sub");
+ std::fs::create_dir_all(&sub).unwrap();
+ Evil::fill(&sub);
+ // the repository asking for it changes nothing: in .gitmodules, which comes with the files, and in its config
+ e.append(".gitmodules", "[submodule \"sub\"]\npath = sub\nurl = ./sub\nignore = none\n");
+ assert!(git(&e.repo, &["add", "sub", ".gitmodules"]));
+ assert!(git(&e.repo, &["commit", "-q", "-m", "sub"]));
+ e.append("sub/.git/config", &format!("[filter \"ev\"]\n{}", e.clean()));
+ e.append(".git/config", "[diff]\nignoreSubmodules = none\n");
+ e.append("sub/.gitattributes", "* filter=ev\n");
+ let st = e.check(&e.repo).unwrap();
+ assert_eq!(st.files.get(Path::new("sub")), None);
+ // inside the submodule, its own config
+ assert!(e.check(&sub).is_ok());
+ // another commit checked out in it still shows
+ assert!(git(&sub, &["-c", "filter.ev.clean=", "commit", "-q", "-a", "-m", "y"]));
+ let _ = e.ran();
+ assert_eq!(status(&e.repo).unwrap().files.get(Path::new("sub")), Some(&FileState::Modified));
+ assert!(!e.ran());
+ }
+
+ #[test]
+ fn reading_runs_no_diff_program() {
+ let Some(e) = Evil::new("diff") else { return };
+ e.append(
+ ".git/config",
+ &format!("[diff]\nexternal = \"{0}\"\n[diff \"ev\"]\ntextconv = \"{0}\"\ncommand = \"{0}\"\n[status]\nsubmoduleSummary = true\n", e.program()),
+ );
+ e.append(".gitattributes", "* diff=ev\n");
+ git(&e.repo, &["diff"]);
+ assert!(e.ran(), "plain git diff does not run the program: the test is wrong");
+ assert!(status(&e.repo).is_ok());
+ assert_eq!(last_commits_of_children(&e.repo, &e.repo, &["f.txt".into()], 10).len(), 1);
+ assert!(last_commit(&e.repo, None).is_some());
+ assert!(!e.ran());
+ }
+
#[test]
- fn filter_names_come_from_gits_keys() {
- assert_eq!(filter_names("core.bare\0filter.lfs.clean\0filter.lfs.smudge\0filter.My.Dotted.process\0"), Some(vec!["lfs".to_string(), "My.Dotted".to_string()]));
- assert_eq!(filter_names("filter.a=b.clean\0"), None, "a name -c cannot switch off");
- assert_eq!(filter_names(""), Some(vec![]));
+ fn reading_a_signed_commit_does_not_run_the_repos_gpg() {
+ let Some(e) = Evil::new("gpg") else { return };
+ let out = Command::new("git").args(["cat-file", "commit", "HEAD"]).current_dir(&e.repo).output().unwrap();
+ let text = String::from_utf8(out.stdout).unwrap();
+ let signed = text.replacen("\n\n", "\ngpgsig -----BEGIN PGP SIGNATURE-----\n \n x\n -----END PGP SIGNATURE-----\n\n", 1);
+ std::fs::write(e.tmp.join("commit"), signed).unwrap();
+ let out =
+ Command::new("git").args(["hash-object", "-t", "commit", "-w", "--no-filters", "../commit"]).current_dir(&e.repo).output().unwrap();
+ let id = String::from_utf8(out.stdout).unwrap();
+ assert!(git(&e.repo, &["update-ref", "HEAD", id.trim()]));
+ // gpg.program is started without a shell, so it cannot be a command line here: a script. Git writes it: one this process had
+ // open for writing can be "text file busy" while another test starts a program.
+ let script = e.repo.join("gpg.sh");
+ std::fs::write(&script, format!("#!/bin/sh\n{}\n", e.program())).unwrap();
+ assert!(git(&e.repo, &["add", "--chmod=+x", "gpg.sh"]));
+ std::fs::remove_file(&script).unwrap();
+ assert!(git(&e.repo, &["checkout-index", "gpg.sh"]));
+ e.append(".git/config", &format!("[log]\nshowSignature = true\n[gpg]\nprogram = {}\n", script.display().to_string().replace('\\', "/")));
+ git(&e.repo, &["log", "-1"]);
+ assert!(e.ran(), "plain git log does not run the program: the test is wrong");
+ assert_eq!(last_commit(&e.repo, None).unwrap().message, "x");
+ assert_eq!(last_commits_of_children(&e.repo, &e.repo, &["f.txt".into()], 10).len(), 1);
+ assert!(!e.ran());
+ }
+
+ #[test]
+ fn reading_a_partial_clone_fetches_nothing() {
+ let Some(e) = Evil::new("partial") else { return };
+ let other = e.tmp.join("other");
+ std::fs::create_dir_all(&other).unwrap();
+ Evil::fill(&other);
+ e.append(
+ ".git/config",
+ &format!(
+ "[core]\nrepositoryformatversion = 1\n[extensions]\npartialClone = o\n[protocol \"file\"]\nallow = always\n\
+ [remote \"o\"]\npromisor = true\nurl = {}\nuploadpack = \"{}\"\n",
+ other.display().to_string().replace('\\', "/"),
+ e.program()
+ ),
+ );
+ // without its tree HEAD cannot be compared: git wants to fetch it
+ let out = Command::new("git").args(["rev-parse", "HEAD^{tree}"]).current_dir(&e.repo).output().unwrap();
+ let tree = String::from_utf8(out.stdout).unwrap();
+ let object = e.repo.join(".git/objects").join(&tree[..2]).join(tree[2..].trim());
+ std::fs::rename(object, e.tmp.join("tree")).unwrap();
+ assert!(e.check(&e.repo).is_err());
+ let _ = last_commits_of_children(&e.repo, &e.repo, &["f.txt".into()], 10);
+ let _ = last_commit(&e.repo, Some(Path::new("f.txt")));
+ assert!(!e.ran());
+ // a Git that the environment does not reach (one in WSL): the arguments alone are enough
+ let mut c = git_read(&e.repo);
+ c.env_remove("GIT_NO_LAZY_FETCH").env_remove("GIT_ALLOW_PROTOCOL").args(["status", "--porcelain"]);
+ assert!(!c.output().unwrap().status.success());
+ assert!(!e.ran());
+ }
+
+ #[test]
+ fn status_of_a_partial_clone_does_not_need_the_missing_contents() {
+ let Some(e) = Evil::new("partial-rename") else { return };
+ std::fs::write(e.repo.join("old"), "line\n".repeat(50)).unwrap();
+ assert!(git(&e.repo, &["add", "old"]) && git(&e.repo, &["commit", "-q", "-m", "y"]));
+ let out = Command::new("git").args(["rev-parse", "HEAD:old"]).current_dir(&e.repo).output().unwrap();
+ let blob = String::from_utf8(out.stdout).unwrap();
+ assert!(git(&e.repo, &["mv", "old", "new"]));
+ std::fs::write(e.repo.join("new"), "line\n".repeat(51)).unwrap();
+ assert!(git(&e.repo, &["add", "new"]));
+ e.append(".git/config", "[remote \"o\"]\npromisor = true\npartialclonefilter = blob:none\nurl = https://e.invalid/x\n");
+ let object = e.repo.join(".git/objects").join(&blob[..2]).join(blob[2..].trim());
+ std::fs::rename(object, e.tmp.join("blob")).unwrap();
+ let st = status(&e.repo).unwrap();
+ assert_eq!(st.files.get(Path::new("new")), Some(&FileState::Added));
+ }
+
+ /// The `-c` values of the filters that are switched off, one of them per name.
+ fn off(listing: &str, scoped: bool) -> Vec<String> {
+ let o = overrides_from(listing.as_bytes(), scoped).unwrap();
+ assert!(o.args.len().is_multiple_of(8));
+ o.args.iter().filter_map(|a| Some(a.strip_prefix("filter.")?.strip_suffix(".clean=")?.to_string())).collect()
+ }
+
+ #[test]
+ fn only_the_repositorys_own_filters_are_switched_off() {
+ let users = "system\0filter.lfs.clean\0global\0filter.crypt.process\0command\0filter.c.clean\0";
+ assert!(off(users, true).is_empty());
+ assert_eq!(off(&format!("{users}local\0filter.ev.smudge\0worktree\0filter.wt.required\0"), true), ["ev", "wt"]);
+ assert_eq!(off(&format!("{users}local\0filter.lfs.clean\0"), true), ["lfs"]);
+ // a scope git may add one day is not the user's
+ assert_eq!(off("new\0filter.ev.clean\0", true), ["ev"]);
+ // an odd name is only in the way where the repository made it
+ assert!(off("global\0filter.a=b.clean\0", true).is_empty());
+ assert!(overrides_from(b"local\0filter.a=b.clean\0", true).is_err());
+ assert!(overrides_from(b"local\0filter.\xff.clean\0", true).is_err());
+ assert!(overrides_from(b"local\0filter.ev.clean\0local\0", true).is_err(), "cut short");
+ // no filter
+ assert!(off("local\0filter.clean\0local\0core.bare\0local\0filterx.a.clean\0", true).is_empty());
+ assert!(off("", true).is_empty());
+ }
+
+ #[test]
+ fn every_filter_is_switched_off_when_scopes_are_unknown_or_the_repository_extends_lfs() {
+ assert_eq!(off("filter.lfs.clean\0core.bare\0filter.ev.clean\0", false), ["ev", "lfs"]);
+ let users = "system\0filter.lfs.clean\0global\0filter.media.clean\0";
+ assert_eq!(off(&format!("{users}local\0lfs.Extension.x.clean\0"), true), ["lfs", "media"]);
+ assert!(off(&format!("{users}global\0lfs.extension.x.clean\0local\0lfs.url\0"), true).is_empty());
+ }
+
+ #[test]
+ fn a_shells_greeting_before_the_listing_hides_no_filter() {
+ // the user's own filter stays the user's, the repository's stays the repository's
+ assert!(off("Welcome to Ubuntu\n\nsystem\0filter.lfs.clean\0", true).is_empty());
+ assert_eq!(off("Welcome\nlocal\0filter.ev.clean\0", true), ["ev"]);
+ assert_eq!(off("Welcome> local\0filter.ev.clean\0", true), ["ev"]);
+ assert_eq!(off("Welcome> system\0filter.ev.clean\0", true), ["ev"], "not known to be the user's");
+ assert_eq!(off("Welcome\nfilter.ev.clean\0core.bare\0", false), ["ev"]);
+ assert!(overrides_from(b"Welcome> filter.ev.clean\0core.bare\0", false).is_err());
+ assert_eq!(off("Welcome> core.bare\0filter.ev.clean\0", false), ["ev"]);
+ }
+
+ #[test]
+ fn a_listing_that_is_cut_short_is_no_listing() {
+ let end = "command\0core.fsmonitor\0command\0core.untrackedcache\0";
+ assert!(whole(format!("local\0filter.ev.clean\0{end}").as_bytes(), true).is_ok());
+ assert!(whole(b"", true).is_err());
+ assert!(whole(b"system\0filter.lfs.clean\0", true).is_err());
+ assert!(whole(b"local\0core.untrackedcache\0", true).is_err(), "the repository's own setting of that name");
+ assert!(whole(b"core.bare\0core.fsmonitor\0core.untrackedcache\0", false).is_ok());
+ assert!(whole(b"core.bare\0", false).is_err());
+ }
+
+ /// What is run while browsing must get past the guard for a chosen program that may use a shell, or there would be no status.
+ #[test]
+ fn a_chosen_program_is_given_our_commands() {
+ let root = Path::new(".");
+ let o = overrides_from(b"local\0filter.lfs.clean\0local\0filter.a.b-c_d.process\0local\0filter..clean\0", true).unwrap();
+ let refused = |c: &Command| git_program::refused(c.get_args());
+ let mut c = git_base(root);
+ assert_eq!(refused(c.args(["config", "--list", "-z", "--name-only", "--show-scope"])), None);
+ let mut c = git_read(root);
+ assert_eq!(refused(c.args(&o.args).args(STATUS).arg(EXACT_RENAMES)), None);
+ let mut c = git_read(root);
+ assert_eq!(refused(c.args(["log", "-1", "--format=%h%x00%s%x00%an%x00%ct", "--", "src/a b.txt"])), None);
+ // a name with a space is one it might change on the way: refused, so nothing runs
+ let o = overrides_from(b"local\0filter.a b.clean\0", true).unwrap();
+ let mut c = git_read(root);
+ assert!(refused(c.args(&o.args).args(STATUS)).is_some());
+ }
+
+ #[test]
+ fn a_partial_clone_is_recognised() {
+ for key in ["extensions.partialclone", "remote.o.promisor", "remote.o.partialclonefilter"] {
+ assert!(overrides_from(format!("local\0{key}\0").as_bytes(), true).unwrap().partial, "{key}");
+ }
+ assert!(!overrides_from(b"local\0remote.o.url\0", true).unwrap().partial);
}
#[test]
diff --git a/crates/rf-win/src/git_program.rs b/crates/rf-win/src/git_program.rs
index e513ddfe..49239c6b 100644
--- a/crates/rf-win/src/git_program.rs
+++ b/crates/rf-win/src/git_program.rs
@@ -51,7 +51,7 @@ pub(crate) fn command() -> Command {
return Command::new(AUTOMATIC);
}
let mut c = Command::new(program);
- // (the variables `git::git_cmd` sets reach a Git inside WSL only when they are named here; without them it may wait for a
+ // (the variables `git::git_base` and `git::git_read` set reach a Git inside WSL only when they are named here; without them it may wait for a
// password in a console nobody sees)
c.env("WSLENV", shared_with_wsl(std::env::var("WSLENV").ok().as_deref()));
c
@@ -60,7 +60,7 @@ pub(crate) fn command() -> Command {
/// `WSLENV` with the variables of our Git commands added to what it already names.
fn shared_with_wsl(current: Option<&str>) -> String {
let mut names: Vec<&str> = current.unwrap_or_default().split(':').filter(|n| !n.is_empty()).collect();
- for ours in ["GIT_TERMINAL_PROMPT", "GIT_OPTIONAL_LOCKS"] {
+ for ours in ["GIT_TERMINAL_PROMPT", "GIT_OPTIONAL_LOCKS", "GIT_NO_LAZY_FETCH", "GIT_ALLOW_PROTOCOL"] {
if !names.iter().any(|n| n.split('/').next() == Some(ours)) {
names.push(ours);
}
@@ -214,7 +214,7 @@ pub(crate) fn check(c: &Command) -> io::Result<()> {
}
/// The first argument a program that may use a shell is not given.
-fn refused<'a>(args: impl Iterator<Item = &'a OsStr>) -> Option<String> {
+pub(crate) fn refused<'a>(args: impl Iterator<Item = &'a OsStr>) -> Option<String> {
// wslgit puts what these commands print through a shell too, and takes the word for one wherever it stands among the arguments
// (a folder or a branch named "remote")
const PRINT_THROUGH_SHELL: [&str; 3] = ["rev-parse", "remote", "init"];
@@ -282,10 +282,11 @@ mod tests {
#[test]
fn our_variables_are_shared_with_wsl_once() {
- assert_eq!(shared_with_wsl(None), "GIT_TERMINAL_PROMPT:GIT_OPTIONAL_LOCKS");
- assert_eq!(shared_with_wsl(Some("")), "GIT_TERMINAL_PROMPT:GIT_OPTIONAL_LOCKS");
- assert_eq!(shared_with_wsl(Some("A/p:B")), "A/p:B:GIT_TERMINAL_PROMPT:GIT_OPTIONAL_LOCKS");
- assert_eq!(shared_with_wsl(Some("GIT_OPTIONAL_LOCKS/u:A")), "GIT_OPTIONAL_LOCKS/u:A:GIT_TERMINAL_PROMPT");
+ const OURS: &str = "GIT_TERMINAL_PROMPT:GIT_OPTIONAL_LOCKS:GIT_NO_LAZY_FETCH:GIT_ALLOW_PROTOCOL";
+ assert_eq!(shared_with_wsl(None), OURS);
+ assert_eq!(shared_with_wsl(Some("")), OURS);
+ assert_eq!(shared_with_wsl(Some("A/p:B")), format!("A/p:B:{OURS}"));
+ assert_eq!(shared_with_wsl(Some("GIT_OPTIONAL_LOCKS/u:A")), "GIT_OPTIONAL_LOCKS/u:A:GIT_TERMINAL_PROMPT:GIT_NO_LAZY_FETCH:GIT_ALLOW_PROTOCOL");
}
/// The commands `git` runs, as it runs them.