fix sed-lite implementation

This commit is contained in:
Emil Lerch 2026-02-04 17:06:46 -08:00
parent 1f6cb4eb0c
commit e01e8857e1
Signed by: lobo
GPG key ID: A7B62D657EF764F8
2 changed files with 17 additions and 10 deletions

View file

@ -2,7 +2,7 @@
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
rev: v6.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer

View file

@ -9,7 +9,7 @@ pub fn main() !u8 {
var stdout_writer = std.fs.File.stdout().writer(&stdout_buffer);
var stderr_writer = std.fs.File.stdout().writer(&.{});
const stdout = &stdout_writer.interface;
defer stdout.flush() catch {};
defer stdout.flush() catch @panic("flush failed!");
const stderr = &stderr_writer.interface;
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
@ -89,7 +89,17 @@ const Substitution = struct {
fn substituteLines(reader: *std.Io.Reader, writer: *std.Io.Writer, substitutions: []const Substitution) !usize {
var subs: usize = 0;
while (reader.takeDelimiterExclusive('\n')) |line| {
var first_line = true;
while (reader.takeDelimiter('\n')) |line_opt| {
// takeDelimiter returns null at EOF
const line = line_opt orelse break;
// Write newline before each line except the first
if (!first_line) {
try writer.writeByte('\n');
}
first_line = false;
var substituted = false;
for (substitutions) |sub| {
if (std.mem.eql(u8, line, sub.original)) {
@ -101,9 +111,6 @@ fn substituteLines(reader: *std.Io.Reader, writer: *std.Io.Writer, substitutions
}
if (!substituted)
try writer.writeAll(line);
if (reader.peekByte() != error.EndOfStream)
try writer.writeByte('\n');
} else |err| if (err != error.EndOfStream) return err;
return subs;
}
@ -120,7 +127,7 @@ test "substitute lines exact match" {
.{ .original = "replace_me", .replacement = "new_line" },
};
try substituteLines(
_ = try substituteLines(
&input_stream,
&output_stream,
&substitutions,
@ -141,7 +148,7 @@ test "no match found" {
.{ .original = "nonexistent", .replacement = "replacement" },
};
try substituteLines(
_ = try substituteLines(
&input_stream,
&output_stream,
&substitutions,
@ -163,7 +170,7 @@ test "partial match not replaced" {
.{ .original = "match", .replacement = "replaced" },
};
try substituteLines(
_ = try substituteLines(
&input_stream,
&output_stream,
&substitutions,
@ -186,7 +193,7 @@ test "multiple substitutions" {
.{ .original = "replace_also", .replacement = "also_new" },
};
try substituteLines(
_ = try substituteLines(
&input_stream,
&output_stream,
&substitutions,