diff options
Diffstat (limited to 'src/cmd/sort.zig')
-rw-r--r-- | src/cmd/sort.zig | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/src/cmd/sort.zig b/src/cmd/sort.zig new file mode 100644 index 0000000..fb08f0b --- /dev/null +++ b/src/cmd/sort.zig @@ -0,0 +1,63 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; +const print = std.debug.print; + +const types = @import("./types.zig"); +const CommandStatus = types.CommandStatus; +const OutputCapture = types.OutputCapture; +const InputSource = types.InputSource; + +pub const Sort = struct { + pub fn eval(sort: Sort, allocator: Allocator, output_capture: ?*OutputCapture, input_source: ?*InputSource) !CommandStatus { + _ = sort; + + var lines = ArrayList([]const u8).init(allocator); + defer { + for (lines.items) |line| { + allocator.free(line); + } + lines.deinit(); + } + + // Read input lines + if (input_source) |source| { + // Read from input redirection + while (try source.readLine(allocator)) |line| { + try lines.append(line); + } + } else { + // Read from stdin (simplified - just show message) + const msg = "SORT: Use input redirection (< file.txt) to sort file contents\n"; + if (output_capture) |capture| { + try capture.write(msg); + } else { + print("{s}", .{msg}); + } + return CommandStatus{ .Code = 0 }; + } + + // Sort the lines + std.mem.sort([]const u8, lines.items, {}, struct { + fn lessThan(_: void, lhs: []const u8, rhs: []const u8) bool { + return std.mem.order(u8, lhs, rhs) == .lt; + } + }.lessThan); + + // Output sorted lines + var output_buffer = ArrayList(u8).init(allocator); + defer output_buffer.deinit(); + + for (lines.items) |line| { + try output_buffer.writer().print("{s}\n", .{line}); + } + + if (output_capture) |capture| { + try capture.write(output_buffer.items); + } else { + print("{s}", .{output_buffer.items}); + } + + return CommandStatus{ .Code = 0 }; + } +}; |