#![cfg_attr(windows, allow(dead_code))]
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
type Vars = HashMap<String, String>;
pub fn quiet_sed_in_place(command: &str, cwd: Option<&str>) -> bool {
if cfg!(windows) {
return false; }
let Some(cwd) = cwd.map(Path::new).filter(|c| c.is_absolute() && c.is_dir()) else { return false };
let Some(acts) = walk(command, cwd) else { return false };
let mut repos: Vec<(PathBuf, Vec<String>)> = Vec::new();
for act in &acts {
let Act::Sed(ops) = act else { continue };
for op in ops.iter().filter(|o| !o.scratch) {
let Some((top, rel)) = locate(&op.dir, &op.path) else { return false };
match repos.iter_mut().find(|r| r.0 == top) {
Some(r) => r.1.push(rel),
None => repos.push((top, vec![rel])),
}
}
}
repos.iter().all(|(top, rel)| all_tracked_and_clean(top, rel))
}
pub fn quiet_branch_delete(command: &str, cwd: Option<&str>) -> bool {
if cfg!(windows) {
return false;
}
let Some(cwd) = cwd.map(Path::new).filter(|c| c.is_absolute() && c.is_dir()) else { return false };
let Some(acts) = walk(command, cwd) else { return false };
let mut any = false;
for act in &acts {
if let Act::Branch(b) = act {
any = true;
if b.names.is_empty() || !b.names.iter().all(|n| branch_is_safe_to_delete(&b.dir, n)) {
return false;
}
}
}
any
}
struct Operand {
path: String,
dir: PathBuf,
scratch: bool,
}
struct Branch {
names: Vec<String>,
dir: PathBuf,
}
enum Act {
Sed(Vec<Operand>),
Branch(Branch),
}
struct Seg {
words: Vec<String>,
depth: usize,
}
fn is_sed(w: &str) -> bool {
w == "sed" || w.ends_with("/sed")
}
fn walk(command: &str, cwd: &Path) -> Option<Vec<Act>> {
let segs = understood(command)?;
let home = std::env::var("HOME").ok();
let mut dir = cwd.to_path_buf();
let mut vars: Vars = HashMap::new();
let mut stack: Vec<(PathBuf, Vars)> = Vec::new();
let mut copies: Vec<(PathBuf, String)> = Vec::new();
let mut acts = Vec::new();
for seg in &segs {
let w = &seg.words[..];
if w == ["("] {
stack.push((dir.clone(), vars.clone()));
continue;
}
if w == [")"] {
(dir, vars) = stack.pop()?;
continue;
}
let mut i = 0;
let mut pending: Vec<(String, Option<String>)> = Vec::new();
while i < w.len() {
if matches!(w[i].as_str(), "sudo" | "command" | "time" | "nohup" | "env") {
i += 1;
} else if is_assignment(&w[i]) {
let (k, v) = w[i].split_once('=').unwrap_or_default();
pending.push((k.to_string(), expand(v, &vars, home.as_deref())));
i += 1;
} else {
break;
}
}
let words = &w[i..];
let Some(head) = words.first() else {
for (k, v) in pending {
match v {
Some(v) => vars.insert(k, v),
None => vars.remove(&k),
};
}
continue;
};
match head.as_str() {
"cd" | "pushd" => {
let arg = words.iter().skip(1).find(|a| !a.starts_with('-') || *a == "-")?;
if arg == "-" || seg.depth > 0 {
return None;
}
let target = expand(arg, &vars, home.as_deref())?;
dir = if Path::new(&target).is_absolute() { PathBuf::from(target) } else { dir.join(target) };
}
"export" | "declare" | "local" | "readonly" => {
for a in words.iter().skip(1).filter(|a| is_assignment(a)) {
let (k, v) = a.split_once('=').unwrap_or_default();
match expand(v, &vars, home.as_deref()) {
Some(v) => vars.insert(k.to_string(), v),
None => vars.remove(k),
};
}
}
h if is_sed(h) => {
let mut ops = Vec::new();
for p in in_place_operands(&words[1..], seg.depth > 0)? {
let path = expand(&p, &vars, home.as_deref()).filter(|p| !p.contains(['*', '?', '[', '{']))?;
let scratch = copies.iter().any(|(d, c)| *d == dir && *c == path);
ops.push(Operand { path, dir: dir.clone(), scratch });
}
acts.push(Act::Sed(ops));
}
"git" => {
if let Some(b) = branch_delete(words, &dir, &vars, home.as_deref())? {
acts.push(Act::Branch(b));
}
}
"cp" | "mv" | "tee" | "install" => {
if let Some(last) = words.iter().skip(1).rfind(|a| !a.starts_with('-')) {
if let Some(p) = expand(last, &vars, home.as_deref()) {
copies.push((dir.clone(), p));
}
}
}
_ => {
if words.iter().skip(1).any(|a| is_sed(a)) {
return None; }
}
}
}
Some(acts)
}
fn branch_delete(words: &[String], dir: &Path, vars: &Vars, home: Option<&str>) -> Option<Option<Branch>> {
let mut dir = dir.to_path_buf();
let mut i = 1;
while i < words.len() && words[i].starts_with('-') {
match words[i].as_str() {
"-C" => {
let target = expand(words.get(i + 1)?, vars, home)?;
dir = if Path::new(&target).is_absolute() { PathBuf::from(target) } else { dir.join(target) };
i += 2;
}
"-c" | "--git-dir" | "--work-tree" => return None,
_ => i += 1,
}
}
if words.get(i).map(String::as_str) != Some("branch") {
return Some(None);
}
let (mut delete, mut force) = (false, false);
let mut names = Vec::new();
for w in &words[i + 1..] {
if let Some(long) = w.strip_prefix("--") {
match long {
"delete" => delete = true,
"force" => force = true,
_ => return None, }
} else if let Some(short) = w.strip_prefix('-').filter(|s| !s.is_empty()) {
for c in short.chars() {
match c {
'D' => {
delete = true;
force = true;
}
'd' => delete = true,
'f' => force = true,
_ => return None, }
}
} else {
names.push(expand(w, vars, home)?);
}
}
Some((delete && force).then_some(Branch { names, dir }))
}
fn expand(word: &str, vars: &Vars, home: Option<&str>) -> Option<String> {
let mut out = String::new();
let mut rest = word;
if let Some(after) = rest.strip_prefix('~') {
if after.is_empty() || after.starts_with('/') {
out.push_str(home?);
rest = after;
} else {
return None;
}
}
let mut chars = rest.chars().peekable();
while let Some(c) = chars.next() {
match c {
'`' => return None,
'$' => {
let mut name = String::new();
if chars.peek() == Some(&'{') {
chars.next();
loop {
match chars.next()? {
'}' => break,
ch if ch.is_ascii_alphanumeric() || ch == '_' => name.push(ch),
_ => return None,
}
}
} else {
while let Some(&ch) = chars.peek() {
if ch.is_ascii_alphanumeric() || ch == '_' {
name.push(ch);
chars.next();
} else {
break;
}
}
}
if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
return None;
}
out.push_str(vars.get(&name)?);
}
ch => out.push(ch),
}
}
Some(out)
}
fn branch_is_safe_to_delete(cwd: &Path, name: &str) -> bool {
if name.is_empty() || name.starts_with('-') || name.contains(['*', '?', '[', '$']) {
return false;
}
let full = format!("refs/heads/{name}");
let Some((exists, tip)) = git(cwd, &["rev-parse", "--verify", "-q", &full]) else { return false };
if !exists {
return git_top(cwd).is_some();
}
let Some((ok, refs)) = git(cwd, &["for-each-ref", "--contains", &tip, "--format=%(refname)"]) else { return false };
ok && refs.lines().any(|r| r != full)
}
fn understood(command: &str) -> Option<Vec<Seg>> {
let text = strip_heredocs(command)?;
let (raw, substitutions) = segments(&text)?;
if substitutions.iter().any(|s| s.split(|c: char| !c.is_alphanumeric() && c != '/' && c != '_').any(is_sed)) {
return None;
}
let mut depth = 0usize;
let mut segs = Vec::new();
for words in raw {
let head = words.iter().find(|w| !is_assignment(w) && !matches!(w.as_str(), "sudo" | "command" | "time" | "nohup" | "env")).cloned().unwrap_or_default();
match head.as_str() {
"eval" | "ssh" | "parallel" | "su" if words.iter().any(|w| w.contains("sed")) => return None,
"bash" | "sh" | "zsh" | "dash" | "ksh" if words.iter().skip(1).any(|w| w.contains("sed")) => return None,
"for" | "while" | "until" => depth += 1,
_ => {}
}
segs.push(Seg { words: words.clone(), depth });
if head == "done" {
depth = depth.saturating_sub(1);
}
}
Some(segs)
}
fn strip_heredocs(command: &str) -> Option<String> {
let mut out = String::new();
let mut tags: Vec<String> = Vec::new();
for line in command.split('\n') {
if let Some(tag) = tags.first() {
if line.trim() == tag {
tags.remove(0);
}
continue;
}
out.push_str(line);
out.push('\n');
let mut rest = line;
while let Some(at) = rest.find("<<") {
let before = &rest[..at];
let after = &rest[at + 2..];
if after.starts_with('<') {
rest = &after[1..]; continue;
}
let after = after.strip_prefix('-').unwrap_or(after).trim_start();
let quote = after.chars().next().filter(|c| *c == '\'' || *c == '"');
let t: String = after.trim_start_matches(['\'', '"']).chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
if t.is_empty() {
return None;
}
let _ = quote;
let receiver = before.rsplit([';', '|', '&', '(']).next().unwrap_or("").split_whitespace().find(|w| !is_assignment(w) && !matches!(*w, "sudo" | "env" | "time"));
if receiver.is_some_and(|r| matches!(r.rsplit('/').next().unwrap_or(r), "bash" | "sh" | "zsh" | "dash" | "ksh" | "ssh" | "su" | "source" | ".")) {
return None;
}
tags.push(t);
rest = after;
}
}
Some(out)
}
fn is_assignment(w: &str) -> bool {
w.split_once('=').is_some_and(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
}
fn in_place_operands(args: &[String], in_loop: bool) -> Option<Vec<String>> {
let mut in_place = false;
let mut script_given = false;
let mut positional: Vec<&String> = Vec::new();
let mut i = 0;
let mut opts_done = false;
while i < args.len() {
let a = &args[i];
i += 1;
if opts_done || !a.starts_with('-') || a == "-" {
positional.push(a);
continue;
}
if a == "--" {
opts_done = true;
continue;
}
if a == "--in-place" {
in_place = true;
} else if a.starts_with("--in-place=") {
return Some(vec![]); } else if a == "--expression" || a == "--file" {
script_given = true;
i += 1;
} else if a.starts_with("--expression=") || a.starts_with("--file=") {
script_given = true;
} else if a.starts_with("--") {
} else {
let body = &a[1..];
for (k, c) in body.char_indices() {
match c {
'e' | 'f' => {
script_given = true;
if k + 1 == body.len() {
i += 1; }
break;
}
'i' => {
if k + 1 == body.len() {
in_place = true;
if args.get(i).is_some_and(|n| n.is_empty()) {
i += 1;
}
} else {
return Some(vec![]); }
break;
}
'l' => {
i += 1;
break;
}
_ => {}
}
}
}
}
if !in_place {
return Some(vec![]);
}
if in_loop {
return None;
}
if !script_given {
if positional.is_empty() {
return None;
}
positional.remove(0);
}
let files: Vec<String> = positional.into_iter().cloned().collect();
if files.iter().any(|f| f.is_empty() || f.contains(['*', '?', '[', '{', '\n'])) {
return None;
}
Some(files)
}
fn segments(cmd: &str) -> Option<(Vec<Vec<String>>, Vec<String>)> {
let mut segs: Vec<Vec<String>> = vec![vec![]];
let mut subs: Vec<String> = Vec::new();
let mut cur = String::new();
let mut has = false;
let mut chars = cmd.chars().peekable();
macro_rules! flush {
() => {
if has {
segs.last_mut().unwrap().push(std::mem::take(&mut cur));
has = false;
}
};
}
fn substitution(chars: &mut std::iter::Peekable<std::str::Chars<'_>>, cur: &mut String, subs: &mut Vec<String>, tick: bool) -> Option<()> {
let mut inner = String::new();
if tick {
cur.push('`');
loop {
match chars.next()? {
'`' => break,
ch => inner.push(ch),
}
}
cur.push_str(&inner);
cur.push('`');
} else {
cur.push_str("$(");
chars.next(); let mut depth = 1;
loop {
let ch = chars.next()?;
match ch {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
inner.push(ch);
}
cur.push_str(&inner);
cur.push(')');
}
subs.push(inner);
Some(())
}
while let Some(c) = chars.next() {
match c {
'\'' => {
has = true;
loop {
match chars.next()? {
'\'' => break,
ch => cur.push(ch),
}
}
}
'"' => {
has = true;
loop {
match chars.next()? {
'"' => break,
'\\' => {
let n = chars.next()?;
if !matches!(n, '"' | '\\' | '$' | '`') {
cur.push('\\');
}
cur.push(n);
}
'$' if chars.peek() == Some(&'(') => substitution(&mut chars, &mut cur, &mut subs, false)?,
'`' => substitution(&mut chars, &mut cur, &mut subs, true)?,
ch => cur.push(ch),
}
}
}
'\\' => {
has = true;
cur.push(chars.next()?);
}
'$' if chars.peek() == Some(&'(') => {
has = true;
substitution(&mut chars, &mut cur, &mut subs, false)?;
}
'`' => {
has = true;
substitution(&mut chars, &mut cur, &mut subs, true)?;
}
'(' | ')' => {
flush!();
if !segs.last().is_some_and(Vec::is_empty) {
segs.push(vec![]);
}
segs.last_mut().unwrap().push(c.to_string());
segs.push(vec![]);
}
';' | '|' | '&' | '\n' => {
flush!();
if !segs.last().is_some_and(Vec::is_empty) {
segs.push(vec![]);
}
}
c if c.is_whitespace() => flush!(),
c => {
has = true;
cur.push(c);
}
}
}
if has {
segs.last_mut().unwrap().push(cur);
}
Some((segs.into_iter().filter(|s| !s.is_empty()).collect(), subs))
}
fn git(cwd: &Path, args: &[&str]) -> Option<(bool, String)> {
let o = Command::new("git").arg("-C").arg(cwd).args(args).stdin(Stdio::null()).stderr(Stdio::null()).output().ok()?;
Some((o.status.success(), String::from_utf8_lossy(&o.stdout).trim().to_string()))
}
fn git_top(cwd: &Path) -> Option<PathBuf> {
let (ok, out) = git(cwd, &["rev-parse", "--show-toplevel"])?;
(ok && !out.is_empty()).then(|| PathBuf::from(out))
}
fn locate(cwd: &Path, file: &str) -> Option<(PathBuf, String)> {
let joined = if Path::new(file).is_absolute() { PathBuf::from(file) } else { cwd.join(file) };
let mut parts: Vec<std::ffi::OsString> = Vec::new();
for c in joined.components() {
use std::path::Component::*;
match c {
Prefix(_) | RootDir => parts.clear(),
CurDir => {}
ParentDir => {
parts.pop()?;
}
Normal(p) => parts.push(p.to_owned()),
}
}
let abs: PathBuf = std::iter::once(std::ffi::OsString::from("/")).chain(parts).collect();
let name = abs.file_name()?.to_owned();
let dir = abs.parent()?.canonicalize().ok()?;
let top = git_top(&dir)?;
let top_real = top.canonicalize().unwrap_or(top);
let file_real = dir.join(&name);
let rel = file_real.strip_prefix(&top_real).ok()?.to_string_lossy().into_owned();
(!rel.is_empty()).then_some((top_real, rel))
}
fn all_tracked_and_clean(top: &Path, rel: &[String]) -> bool {
let mut args: Vec<&str> = vec!["ls-files", "--error-unmatch", "--"];
args.extend(rel.iter().map(String::as_str));
if !git(top, &args).is_some_and(|r| r.0) {
return false;
}
let mut args: Vec<&str> = vec!["diff", "--quiet", "HEAD", "--"];
args.extend(rel.iter().map(String::as_str));
git(top, &args).is_some_and(|r| r.0)
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
fn placed(c: &str) -> Option<Vec<(String, String)>> {
walk(c, Path::new("/w")).map(|acts| {
acts.into_iter()
.flat_map(|a| match a {
Act::Sed(ops) => ops.into_iter().filter(|o| !o.scratch).map(|o| (o.dir.to_string_lossy().into_owned(), o.path)).collect(),
Act::Branch(_) => vec![],
})
.collect()
})
}
fn files(c: &str) -> Option<Vec<String>> {
placed(c).map(|v| v.into_iter().map(|p| p.1).collect())
}
#[test]
fn reads_the_file_operands_of_an_in_place_sed() {
assert_eq!(files("sed -i 's/a/b/' src/main.rs"), Some(vec!["src/main.rs".into()]));
assert_eq!(files("sed -i -e 's/a/b/' -e 's/c/d/' a.txt b.txt"), Some(vec!["a.txt".into(), "b.txt".into()]));
assert_eq!(files("sed -ri 's/a|b/c/' x.conf"), Some(vec!["x.conf".into()]));
assert_eq!(files("sed --in-place 's/a/b/' x"), Some(vec!["x".into()]));
assert_eq!(files("sed -i '' 's/a/b/' x"), Some(vec!["x".into()]));
assert_eq!(files("sed -i -f fix.sed file.txt"), Some(vec!["file.txt".into()]));
assert_eq!(files("cd app && sed -i 's/a/b/' x.yaml && git diff"), Some(vec!["x.yaml".into()]));
}
#[test]
fn a_sed_that_keeps_a_backup_or_is_not_in_place_has_nothing_to_check() {
for c in ["sed -i.bak 's/a/b/' x", "sed --in-place=.bak 's/a/b/' x", "sed -n 's/a/b/p' x", "sed 's/a/b/' x | head"] {
assert_eq!(files(c), Some(vec![]), "{c}");
}
}
#[test]
fn fan_out_and_unknown_operands_are_not_understood() {
for c in [
"sed -i 's/a/b/' src/*.rs",
"sed -i 's/a/b/' $FILE",
"sed -i 's/a/b/' $(git ls-files)",
"find . -name '*.rs' | xargs sed -i 's/a/b/'",
"find . -type f -exec sed -i 's/a/b/' {} +",
"for f in a b; do sed -i 's/x/y/' $f; done",
"while read f; do sed -i 's/x/y/' \"$f\"; done < list",
"bash -c \"sed -i 's/a/b/' x\"",
"ssh host sed -i s/a/b/ x",
"echo sed -i 's/a/b/' x",
"x=$(sed -i 's/a/b/' y)",
"bash <<EOF\nsed -i s/a/b/ y\nEOF",
] {
assert_eq!(files(c), None, "{c}");
}
}
#[test]
fn heredoc_text_substitutions_and_unrelated_loops_do_not_hide_the_edit() {
assert_eq!(files("cat > fix.sh <<'EOF'\nsed -i 's/a/b/' src/main.rs\nEOF\nchmod +x fix.sh"), Some(vec![]));
assert_eq!(files("d=$(date +%F); sed -i \"s/x/$d/\" notes.md"), Some(vec!["notes.md".into()]));
assert_eq!(files("echo $(pwd); sed -i 's/a/b/' src/a.rs"), Some(vec!["src/a.rs".into()]));
assert_eq!(files("for f in a b; do echo $f; done; sed -i 's/x/y/' z.txt"), Some(vec!["z.txt".into()]));
}
#[test]
fn cd_assignments_home_and_subshells_are_followed() {
std::env::set_var("HOME", "/home/u");
assert_eq!(placed("cd sub && sed -i 's/a/b/' f.txt"), Some(vec![("/w/sub".into(), "f.txt".into())]));
assert_eq!(placed("cd /abs/dir; sed -i 's/a/b/' f.txt"), Some(vec![("/abs/dir".into(), "f.txt".into())]));
assert_eq!(placed("cd ~/proj && sed -i 's/a/b/' f"), Some(vec![("/home/u/proj".into(), "f".into())]));
assert_eq!(placed("f=src/a.rs; sed -i 's/x/y/' \"$f\""), Some(vec![("/w".into(), "src/a.rs".into())]));
assert_eq!(placed("D=~/p; F=$D/m.md; sed -i 's/x/y/' $F"), Some(vec![("/w".into(), "/home/u/p/m.md".into())]));
assert_eq!(placed("sed -i 's/x/y/' ~/.bashrc"), Some(vec![("/w".into(), "/home/u/.bashrc".into())]));
assert_eq!(placed("(cd a && ls); sed -i 's/x/y/' f"), Some(vec![("/w".into(), "f".into())]));
assert_eq!(placed("sed -i 's/x/y/' $UNSET"), None);
assert_eq!(placed("cd $UNSET && sed -i 's/x/y/' f"), None);
assert_eq!(placed("cd - && sed -i 's/x/y/' f"), None);
}
#[test]
fn a_file_the_command_just_copied_is_scratch() {
assert_eq!(files("cp config.yaml /tmp/x.yaml && sed -i 's/a/b/' /tmp/x.yaml"), Some(vec![]));
assert_eq!(files("cp config.yaml /tmp/x.yaml && sed -i 's/a/b/' config.yaml"), Some(vec!["config.yaml".into()]));
}
fn repo(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("instinct-narrow-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(d.join("src")).unwrap();
let run = |args: &[&str]| {
assert!(Command::new("git")
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args(args)
.current_dir(&d)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.unwrap()
.success());
};
run(&["init", "-q"]);
std::fs::write(d.join("src/a.rs"), "a\n").unwrap();
std::fs::write(d.join("src/b.rs"), "b\n").unwrap();
run(&["add", "-A"]);
run(&["commit", "-q", "-m", "x"]);
d
}
#[test]
fn branch_delete_is_quiet_only_when_the_commits_live_elsewhere() {
let d = repo("branch");
let at = d.to_str();
let run = |args: &[&str]| {
assert!(Command::new("git").args(["-c", "user.name=t", "-c", "user.email=t@t"]).args(args).current_dir(&d).stdout(Stdio::null()).stderr(Stdio::null()).status().unwrap().success(), "{args:?}");
};
run(&["branch", "merged"]);
assert!(quiet_branch_delete("git branch -D merged", at));
run(&["checkout", "-q", "-b", "wip"]);
std::fs::write(d.join("src/new.rs"), "n\n").unwrap();
run(&["add", "-A"]);
run(&["commit", "-q", "-m", "wip"]);
run(&["checkout", "-q", "-"]);
assert!(!quiet_branch_delete("git branch -D wip", at));
assert!(!quiet_branch_delete("git branch -D merged wip", at));
assert!(quiet_branch_delete("git branch --delete --force ghost", at));
assert!(!quiet_branch_delete("git branch -d merged", at));
assert!(!quiet_branch_delete("git branch -D -r origin/x", at));
assert!(!quiet_branch_delete("git branch | xargs git branch -D", at));
assert!(!quiet_branch_delete("git branch -D merged", None));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn quiet_only_for_tracked_unmodified_files_in_the_repo() {
let d = repo("quiet");
let at = d.to_str();
assert!(quiet_sed_in_place("sed -i 's/a/b/' src/a.rs", at));
assert!(quiet_sed_in_place("sed -i 's/a/b/' src/a.rs src/b.rs", at));
assert!(quiet_sed_in_place(&format!("sed -i 's/a/b/' {}/src/a.rs", d.display()), at));
std::fs::write(d.join("src/new.rs"), "n\n").unwrap();
assert!(!quiet_sed_in_place("sed -i 's/a/b/' src/new.rs", at));
assert!(!quiet_sed_in_place("sed -i 's/a/b/' src/none.rs", at));
assert!(!quiet_sed_in_place("sed -i 's/a/b/' ../other", at));
assert!(!quiet_sed_in_place("sed -i 's/a/b/' /etc/hosts", at));
assert!(!quiet_sed_in_place("sed -i 's/a/b/' src/*.rs", at));
std::fs::write(d.join("src/b.rs"), "changed\n").unwrap();
assert!(!quiet_sed_in_place("sed -i 's/a/b/' src/b.rs", at));
assert!(quiet_sed_in_place("sed -i 's/a/b/' src/a.rs", at));
assert!(!quiet_sed_in_place("sed -i 's/a/b/' src/a.rs", None));
assert!(!quiet_sed_in_place("sed -i 's/a/b/' src/a.rs", Some("relative/dir")));
let plain = std::env::temp_dir().join(format!("instinct-narrow-{}-plain", std::process::id()));
std::fs::create_dir_all(&plain).unwrap();
std::fs::write(plain.join("f"), "x\n").unwrap();
assert!(!quiet_sed_in_place("sed -i 's/a/b/' f", plain.to_str()));
let _ = std::fs::remove_dir_all(&d);
let _ = std::fs::remove_dir_all(&plain);
}
}