diff options
| author | Lucas Faria Mendes <lucas.oliveira1676@etec.sp.gov.br> | 2025-12-05 06:24:57 +0000 |
|---|---|---|
| committer | Lucas Faria Mendes <lucas.oliveira1676@etec.sp.gov.br> | 2025-12-05 06:24:57 +0000 |
| commit | 5a676cada89ccdd33de496e2a1a1a130a26894f6 (patch) | |
| tree | 562d5b85229817829412be10db1017e8c8321244 /src/parser.zig | |
| parent | c3c3c2202cf312842230f7316c69a89c28c60ce9 (diff) | |
| download | shell-zig-5a676cada89ccdd33de496e2a1a1a130a26894f6.tar.gz shell-zig-5a676cada89ccdd33de496e2a1a1a130a26894f6.zip | |
codecrafters submit [skip ci]
Diffstat (limited to 'src/parser.zig')
| -rw-r--r-- | src/parser.zig | 37 |
1 files changed, 33 insertions, 4 deletions
diff --git a/src/parser.zig b/src/parser.zig index 7289057..13c3b42 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -6,11 +6,40 @@ pub const ParsedCommand = struct { }; pub fn parseCommand(input: []const u8) ParsedCommand { - const space_pos = std.mem.indexOfScalar(u8, input, ' '); - if (space_pos) |pos| { - return .{ .name = input[0..pos], .args = input[pos + 1 ..] }; + var i: usize = 0; + var cmd_buf = std.ArrayList(u8){}; + defer cmd_buf.deinit(std.heap.page_allocator); + + while (i < input.len and input[i] == ' ') : (i += 1) {} + + if (i >= input.len) { + return .{ .name = "", .args = null }; + } + + if (input[i] == '\'' or input[i] == '"') { + const quote = input[i]; + i += 1; + while (i < input.len and input[i] != quote) : (i += 1) { + _ = cmd_buf.append(std.heap.page_allocator, input[i]) catch {}; + } + if (i < input.len) i += 1; + } else { + while (i < input.len and input[i] != ' ') : (i += 1) { + if (input[i] == '\\' and i + 1 < input.len) { + i += 1; + _ = cmd_buf.append(std.heap.page_allocator, input[i]) catch {}; + } else { + _ = cmd_buf.append(std.heap.page_allocator, input[i]) catch {}; + } + } } - return .{ .name = input, .args = null }; + + while (i < input.len and input[i] == ' ') : (i += 1) {} + + const cmd_name = cmd_buf.toOwnedSlice(std.heap.page_allocator) catch ""; + const args = if (i < input.len) input[i..] else null; + + return .{ .name = cmd_name, .args = args }; } pub fn parseArgs(allocator: std.mem.Allocator, cmd_name: []const u8, args_str: ?[]const u8) ![]const []const u8 { |