summaryrefslogtreecommitdiff
path: root/src/cmd/sort.zig
blob: 9c04c1ed0f46e6a02c5d1879425c135ad5ec7058 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const print = std.debug.print;

const types = @import("./lib/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 };
    }
};