summaryrefslogtreecommitdiff
path: root/src/parser.zig
diff options
context:
space:
mode:
authorLucas Faria Mendes <lucas.oliveira1676@etec.sp.gov.br>2025-12-05 06:31:01 +0000
committerLucas Faria Mendes <lucas.oliveira1676@etec.sp.gov.br>2025-12-05 06:31:01 +0000
commit6f1c762e789cd746e20cd7597aab0316d2c2fcd9 (patch)
tree36ee2dd94e54eea37230f61f574a99054aefdf88 /src/parser.zig
parent5a676cada89ccdd33de496e2a1a1a130a26894f6 (diff)
downloadshell-zig-6f1c762e789cd746e20cd7597aab0316d2c2fcd9.tar.gz
shell-zig-6f1c762e789cd746e20cd7597aab0316d2c2fcd9.zip
codecrafters submit [skip ci]
Diffstat (limited to 'src/parser.zig')
-rw-r--r--src/parser.zig39
1 files changed, 36 insertions, 3 deletions
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 {