From 6f1c762e789cd746e20cd7597aab0316d2c2fcd9 Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Fri, 5 Dec 2025 03:31:01 -0300 Subject: codecrafters submit [skip ci] --- src/parser.zig | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) (limited to 'src/parser.zig') diff --git a/src/parser.zig b/src/parser.zig index 13c3b42..680eadb 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -3,6 +3,7 @@ const std = @import("std"); pub const ParsedCommand = struct { name: []const u8, args: ?[]const u8, + output_redirect: ?[]const u8, }; pub fn parseCommand(input: []const u8) ParsedCommand { @@ -13,7 +14,7 @@ pub fn parseCommand(input: []const u8) ParsedCommand { while (i < input.len and input[i] == ' ') : (i += 1) {} if (i >= input.len) { - return .{ .name = "", .args = null }; + return .{ .name = "", .args = null, .output_redirect = null }; } if (input[i] == '\'' or input[i] == '"') { @@ -36,10 +37,42 @@ pub fn parseCommand(input: []const u8) ParsedCommand { while (i < input.len and input[i] == ' ') : (i += 1) {} + var redirect_pos: ?usize = null; + var j = i; + while (j < input.len) : (j += 1) { + if (input[j] == '>' or (input[j] == '1' and j + 1 < input.len and input[j + 1] == '>')) { + redirect_pos = j; + break; + } + } + const cmd_name = cmd_buf.toOwnedSlice(std.heap.page_allocator) catch ""; - const args = if (i < input.len) input[i..] else null; + var args: ?[]const u8 = null; + var output_redirect: ?[]const u8 = null; + + if (redirect_pos) |pos| { + if (pos > i) args = input[i..pos]; + + var k = pos; + if (input[k] == '1') k += 1; + if (k < input.len and input[k] == '>') k += 1; + + while (k < input.len and input[k] == ' ') : (k += 1) {} + + if (k < input.len) { + var redir_buf = std.ArrayList(u8){}; + defer redir_buf.deinit(std.heap.page_allocator); + + while (k < input.len and input[k] != ' ') : (k += 1) { + _ = redir_buf.append(std.heap.page_allocator, input[k]) catch {}; + } + output_redirect = redir_buf.toOwnedSlice(std.heap.page_allocator) catch null; + } + } else if (i < input.len) { + args = input[i..]; + } - return .{ .name = cmd_name, .args = args }; + return .{ .name = cmd_name, .args = args, .output_redirect = output_redirect }; } pub fn parseArgs(allocator: std.mem.Allocator, cmd_name: []const u8, args_str: ?[]const u8) ![]const []const u8 { -- cgit v1.2.3