Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
fn draw(
&mut self,
frame: &mut Frame,
area: Rect,
data: Option<&FileMatchData>,
line_buffer: usize,
replace: &str,
focus: bool,
) {
let Some((line_map, match_positions)) = data else {
self.len = 0;
return;
};
self.len = match_positions.len();
let mut scroll_offset = 0;
let replace = "hello\nthe\nworld";
let replace_queue = replace.split('\n').collect::<Vec<_>>();
const CURSOR: &str = "> ";
let line_number_padding = match_positions.last().unwrap().end.0.to_string().len();
let text = match_positions
.iter()
.enumerate()
.flat_map(
|(
match_index,
MatchPosition {
char_range: _,
start,
end,
},
)| {
let mut lines = Vec::new();
let single_line_match = start.0 == end.0;
for line_number in
(start.0.saturating_sub(line_buffer))..end.0 + line_buffer + 1
{
if let Some(origin) = line_map.get(&line_number) {
let origin = origin.as_str();
let line_number_string = (line_number + 1).to_string();
let padded_line_number = " "
.repeat((line_number_padding - line_number_string.len()).max(0))
+ &line_number_string
+ " ";
if (start.0..end.0 + 1).contains(&line_number) {
let mut line = Line::raw("");
line.push_span(Span::raw(if focus && match_index == self.index {
Cow::from(CURSOR)
} else {
" ".repeat(CURSOR.len()).into()
}));
line.push_span(Span::raw(padded_line_number));
if line_number == start.0 {
line.push_span(Span::raw(&origin[..start.1]));
}
if single_line_match {
if line_number == start.0 {
line.push_span(Span::styled(
&origin[start.1..end.1],
Style::new().fg(ratatui::style::Color::Red),
));
}
} else if line_number == start.0 {
line.push_span(Span::styled(
&origin[start.1..],
Style::new().fg(ratatui::style::Color::Red),
));
} else if line_number == end.0 {
line.push_span(Span::styled(
&origin[..end.1],
Style::new().fg(ratatui::style::Color::Red),
));
} else {
line.push_span(Span::styled(
origin,
Style::new().fg(ratatui::style::Color::Red),
));
}
let mut after: Option<Vec<Line>> = None;
if line_number == end.0 {
if !replace_queue.is_empty() {
line.push_span(Span::styled(
replace_queue[0],
Style::new().fg(ratatui::style::Color::Green),
));
}
if replace_queue.len() == 1 {
line.push_span(Span::raw(&origin[end.1..]));
} else if replace_queue.len() > 1 {
after = Some(Vec::new());
let iter = replace_queue.iter().skip(1);
iter.enumerate().for_each(|(i, s)| {
let mut spans = vec![Span::styled(
" ".repeat(line_number_padding + 1) + *s,
Style::new().fg(ratatui::style::Color::Green),
)];
if i + 2 == replace_queue.len() {
spans.push(Span::raw(&origin[end.1..]));
}
after.as_mut().unwrap().push(Line::from(spans));
});
}
}
lines.push(line);
if let Some(ls) = after {
lines.extend(ls);
}
} else {
lines.push(Line::styled(
" ".repeat(CURSOR.len()) + &padded_line_number + origin,
Style::new().fg(ratatui::style::Color::DarkGray),
));
}
} else {
break;
}
}
if match_index + 1 < match_positions.len() {
lines.push(Line::from("-".repeat(area.width.into())));
}
if match_index <= self.index {
scroll_offset += lines.len();
}
lines
},
)
.collect::<Vec<_>>();
frame.render_widget(
Paragraph::new(Text::from(text)).scroll((
if scroll_offset > area.height.into() {
(scroll_offset - area.height as usize).try_into().unwrap()
} else {
0
},
0,
)),
area,
);
}
help me refactor & rename where necessary
Here's a refactored version with better structure and naming:
fn draw(
&mut self,
frame: &mut Frame,
area: Rect,
data: Option<&FileMatchData>,
context_lines: usize,
replacement: &str,
focus: bool,
) {
let Some((line_map, matches)) = data else {
self.len = 0;
return;
};
self.len = matches.len();
let replacement_lines: Vec<&str> = replacement.split('\n').collect();
let line_num_width = matches.last().unwrap().end.0.to_string().len();
let (lines, scroll_to) = self.build_display_lines(
matches,
line_map,
context_lines,
&replacement_lines,
line_num_width,
area.width,
focus
);
let scroll_y = if scroll_to > area.height as usize {
(scroll_to - area.height as usize) as u16
} else {
0
};
frame.render_widget(
Paragraph::new(Text::from(lines)).scroll((scroll_y, 0)),
area,
);
}
fn build_display_lines(
&self,
matches: &[MatchPosition],
line_map: &HashMap<usize, String>,
context_lines: usize,
replacement_lines: &[&str],
line_num_width: usize,
area_width: u16,
focus: bool,
) -> (Vec<Line>, usize) {
const CURSOR: &str = "> ";
let mut all_lines = Vec::new();
let mut scroll_target = 0;
for (match_idx, match_pos) in matches.iter().enumerate() {
let match_lines = self.build_match_lines(
match_pos,
line_map,
context_lines,
replacement_lines,
line_num_width,
match_idx,
focus,
);
if match_idx <= self.index {
scroll_target += match_lines.len();
}
all_lines.extend(match_lines);
// Add separator between matches
if match_idx + 1 < matches.len() {
all_lines.push(Line::from("-".repeat(area_width as usize)));
}
}
(all_lines, scroll_target)
}
fn build_match_lines(
&self,
match_pos: &MatchPosition,
line_map: &HashMap<usize, String>,
context_lines: usize,
replacement_lines: &[&str],
line_num_width: usize,
match_idx: usize,
focus: bool,
) -> Vec<Line> {
const CURSOR: &str = "> ";
let mut lines = Vec::new();
let MatchPosition { start, end, .. } = match_pos;
let is_single_line = start.0 == end.0;
let line_range = start.0.saturating_sub(context_lines)..end.0 + context_lines + 1;
for line_num in line_range {
let Some(content) = line_map.get(&line_num) else { break };
let line_prefix = self.format_line_prefix(line_num, line_num_width, match_idx, focus);
let is_match_line = (start.0..=end.0).contains(&line_num);
if is_match_line {
let line = self.build_match_line(
content,
line_num,
match_pos,
is_single_line,
replacement_lines,
line_prefix,
line_num_width,
);
lines.extend(line);
} else {
lines.push(Line::styled(
line_prefix + content,
Style::new().fg(Color::DarkGray),
));
}
}
lines
}
fn format_line_prefix(&self, line_num: usize, width: usize, match_idx: usize, focus: bool) -> String {
const CURSOR: &str = "> ";
let cursor_part = if focus && match_idx == self.index {
CURSOR
} else {
&" ".repeat(CURSOR.len())
};
let line_num_str = (line_num + 1).to_string();
let padding = " ".repeat(width.saturating_sub(line_num_str.len()));
format!("{}{}{} ", cursor_part, padding, line_num_str)
}
fn build_match_line(
&self,
content: &str,
line_num: usize,
match_pos: &MatchPosition,
is_single_line: bool,
replacement_lines: &[&str],
line_prefix: String,
line_num_width: usize,
) -> Vec<Line> {
let MatchPosition { start, end, .. } = match_pos;
let mut result = Vec::new();
let mut line = Line::raw(line_prefix);
// Add content before match
if line_num == start.0 {
line.push_span(Span::raw(&content[..start.1]));
}
// Add highlighted match content
let match_text = if is_single_line && line_num == start.0 {
&content[start.1..end.1]
} else if line_num == start.0 {
&content[start.1..]
} else if line_num == end.0 {
&content[..end.1]
} else {
content
};
line.push_span(Span::styled(match_text, Style::new().fg(Color::Red)));
// Add replacement and remaining content
if line_num == end.0 {
self.add_replacement_content(&mut line, &mut result, content, end.1, replacement_lines, line_num_width);
}
result.push(line);
result
}
fn add_replacement_content(
&self,
line: &mut Line,
result: &mut Vec<Line>,
content: &str,
end_col: usize,
replacement_lines: &[&str],
line_num_width: usize,
) {
if replacement_lines.is_empty() {
line.push_span(Span::raw(&content[end_col..]));
return;
}
// Add first replacement line
line.push_span(Span::styled(
replacement_lines[0],
Style::new().fg(Color::Green),
));
if replacement_lines.len() == 1 {
line.push_span(Span::raw(&content[end_col..]));
} else {
// Add additional replacement lines
let indent = " ".repeat(line_num_width + 1);
for (i, &repl_line) in replacement_lines.iter().skip(1).enumerate() {
let mut spans = vec![Span::styled(
format!("{}{}", indent, repl_line),
Style::new().fg(Color::Green),
)];
// Add remaining content after last replacement line
if i + 2 == replacement_lines.len() {
spans.push(Span::raw(&content[end_col..]));
}
result.push(Line::from(spans));
}
}
}
I have a cli tools the modify file content, suggest how can I create reproducable tests
Here are several strategies for creating reproducible tests for your CLI file modification tool:
use tempfile::TempDir;
use std::fs;
#[test]
fn test_replace_in_single_file() {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("test.txt");
// Setup
fs::write(&file_path, "hello world\nfoo bar").unwrap();
// Execute
your_cli_tool(&file_path, &[6..11], "universe");
// Verify
let result = fs::read_to_string(&file_path).unwrap();
assert_eq!(result, "hello universe\nfoo bar");
// temp_dir automatically cleaned up when dropped
}
use insta::assert_snapshot;
#[test]
fn test_complex_replacement() {
let temp_dir = setup_test_files(&[
("file1.txt", "original content 1"),
("file2.txt", "original content 2"),
]);
run_cli_command(&["replace", "--pattern", "original", "--with", "modified"]);
let results = collect_file_contents(&temp_dir);
assert_snapshot!(results);
}
// tests/fixtures/
// ├── input/
// │ ├── file1.txt
// │ └── file2.txt
// └── expected/
// ├── file1.txt
// └── file2.txt
#[test]
fn test_with_fixtures() {
let temp_dir = TempDir::new().unwrap();
copy_fixtures("tests/fixtures/input", &temp_dir);
run_your_tool(&temp_dir);
assert_dirs_equal(&temp_dir, "tests/fixtures/expected");
}
fn assert_dirs_equal(actual: &Path, expected: &str) {
let expected_dir = Path::new(expected);
for entry in fs::read_dir(expected_dir).unwrap() {
let entry = entry.unwrap();
let relative_path = entry.path().strip_prefix(expected_dir).unwrap();
let actual_file = actual.join(relative_path);
assert_eq!(
fs::read_to_string(&actual_file).unwrap(),
fs::read_to_string(&entry.path()).unwrap(),
"Files differ: {:?}", relative_path
);
}
}
use proptest::prelude::*;
proptest! {
#[test]
fn test_replacement_preserves_file_structure(
content in ".*",
ranges in prop::collection::vec(0usize..100, 0..5),
replacement in ".*"
) {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join("test.txt");
fs::write(&file_path, &content).unwrap();
// Convert to valid ranges
let valid_ranges: Vec<Range<usize>> = ranges
.windows(2)
.filter_map(|w| {
if w[0] < w[1] && w[1] <= content.len() {
Some(w[0]..w[1])
} else {
None
}
})
.collect();
if !valid_ranges.is_empty() {
let original_len = content.len();
your_replace_function(&file_path, &valid_ranges, &replacement);
let result = fs::read_to_string(&file_path).unwrap();
// Property: file should still be valid UTF-8
assert!(result.is_ascii() || content.is_ascii());
}
}
}
forget about everything.
is there a way to remove the binary systemd-nspawn from nixos?
Yes, you can remove systemd-nspawn from NixOS, but the approach depends on what you're trying to achieve:
# configuration.nix
{
systemd.services.systemd-nspawn = {
enable = false;
};
}
# configuration.nix
{
systemd.package = pkgs.systemd.override {
withNss = false;
withMachined = false;
withImportd = false;
};
}
# configuration.nix
{
systemd.package = pkgs.systemd.overrideAttrs (oldAttrs: {
postInstall = oldAttrs.postInstall + ''
rm -f $out/bin/systemd-nspawn
'';
});
}
# configuration.nix
{
environment.systemPackages = with pkgs; [
# your other packages
];
# Remove from PATH
environment.variables = {
PATH = lib.mkForce (lib.makeBinPath (
builtins.filter (pkg: pkg.pname or "" != "systemd") config.environment.systemPackages
));
};
}
Note: Removing systemd components can break other system functionality since many NixOS services depend on systemd. The safest approach is usually Option 1 (disabling the service) unless you have specific security requirements.
What's your use case for removing it?
Key improvements:
line_buffer → context_lines, replace → replacementmatch_positions → matches, single_line_match → is_single_line, etc.build_*, format_*, add_*)The code is now much more maintainable and easier to understand, with each function having a single clear responsibility.
pub struct TestEnvironment {
temp_dir: TempDir,
}
impl TestEnvironment {
pub fn new() -> Self {
Self {
temp_dir: TempDir::new().unwrap(),
}
}
pub fn create_file(&self, name: &str, content: &str) -> PathBuf {
let path = self.temp_dir.path().join(name);
fs::write(&path, content).unwrap();
path
}
pub fn run_cli(&self, args: &[&str]) -> std::process::Output {
std::process::Command::new("your-cli-tool")
.args(args)
.current_dir(self.temp_dir.path())
.output()
.unwrap()
}
pub fn assert_file_contains(&self, name: &str, expected: &str) {
let content = fs::read_to_string(self.temp_dir.path().join(name)).unwrap();
assert_eq!(content, expected);
}
pub fn assert_file_unchanged(&self, name: &str, original: &str) {
self.assert_file_contains(name, original);
}
}
#[test]
fn test_cli_workflow() {
let env = TestEnvironment::new();
env.create_file("input.txt", "hello world");
let output = env.run_cli(&["replace", "world", "universe", "input.txt"]);
assert!(output.status.success());
env.assert_file_contains("input.txt", "hello universe");
}
use test_case::test_case;
#[test_case("simple.txt", "hello world", &[6..11], "universe", "hello universe")]
#[test_case("multiline.txt", "line1\nline2", &[0..5], "start", "start\nline2")]
#[test_case("empty.txt", "", &[], "anything", "")]
fn test_replacements(
filename: &str,
input: &str,
ranges: &[Range<usize>],
replacement: &str,
expected: &str,
) {
let temp_dir = TempDir::new().unwrap();
let file_path = temp_dir.path().join(filename);
fs::write(&file_path, input).unwrap();
replace_ranges_in_file(&file_path, ranges, replacement);
let result = fs::read_to_string(&file_path).unwrap();
assert_eq!(result, expected);
}
tempfile crate for automatic cleanupThis approach gives you comprehensive, fast, and reliable tests that don't interfere with each other or your development environment.