fix(core) Deduplicate prefix_rules before appending (#10309)

## Summary
We ideally shouldn't make it to this point in the first place, but if we
do try to append a rule that already exists, we shouldn't append the
same rule twice.

## Testing
- [x] Added unit test for this case
This commit is contained in:
Dylan Hurd
2026-02-01 20:30:38 -08:00
committed by GitHub
parent 03fcd12e77
commit 6c22360bcb
2 changed files with 37 additions and 23 deletions
+16 -23
View File
@@ -105,35 +105,28 @@ fn append_locked_line(policy_path: &Path, line: &str) -> Result<(), AmendError>
source,
})?;
let len = file
.metadata()
.map_err(|source| AmendError::PolicyMetadata {
file.seek(SeekFrom::Start(0))
.map_err(|source| AmendError::SeekPolicyFile {
path: policy_path.to_path_buf(),
source,
})?
.len();
})?;
let mut contents = String::new();
file.read_to_string(&mut contents)
.map_err(|source| AmendError::ReadPolicyFile {
path: policy_path.to_path_buf(),
source,
})?;
// Ensure file ends in a newline before appending.
if len > 0 {
file.seek(SeekFrom::End(-1))
.map_err(|source| AmendError::SeekPolicyFile {
if contents.lines().any(|existing| existing == line) {
return Ok(());
}
if !contents.is_empty() && !contents.ends_with('\n') {
file.write_all(b"\n")
.map_err(|source| AmendError::WritePolicyFile {
path: policy_path.to_path_buf(),
source,
})?;
let mut last = [0; 1];
file.read_exact(&mut last)
.map_err(|source| AmendError::ReadPolicyFile {
path: policy_path.to_path_buf(),
source,
})?;
if last[0] != b'\n' {
file.write_all(b"\n")
.map_err(|source| AmendError::WritePolicyFile {
path: policy_path.to_path_buf(),
source,
})?;
}
}
file.write_all(format!("{line}\n").as_bytes())