implment config file parsing via iterator

This commit is contained in:
Dusk 2023-09-28 18:22:44 +02:00
parent be50d94f78
commit 6b32f45534
2 changed files with 80 additions and 17 deletions

View File

@ -2,27 +2,85 @@ const std = @import("std");
const fs = std.fs; const fs = std.fs;
const io = std.io; const io = std.io;
pub fn getConfig(path: []const u8) void { pub const Option = struct {
var file = fs.cwd().createFile(path, .{.read = true, .truncate = false}) catch |err| { key: []const u8,
// TODO: Tirar error cap a dalt value: []const u8,
std.debug.print("Error opening config file '{s}': {any}", .{ path, err }); };
return;
};
defer file.close();
var buf: [256]u8 = undefined; pub const ConfigIterator = struct {
filename: []const u8,
file: fs.File,
buf: [1024]u8,
i: i32 = 0,
var fbs = io.fixedBufferStream(&buf); pub fn next(self: *ConfigIterator) ?Option {
if (self.i >= 1024) {
var reader = file.reader(); std.debug.print("WARNING: Maximum number of lines in config reached, ignoring the rest.\n", .{});
return null;
while (true) {
reader.streamUntilDelimiter(fbs.writer(), '\n', buf.len) catch |err| {
std.debug.print("{any}\n", .{err});
break;
};
defer fbs.reset();
std.debug.print("{s}\n", .{fbs.getWritten()});
} }
var reader = self.file.reader();
var fbs = io.fixedBufferStream(&self.buf);
var writer = fbs.writer();
reader.streamUntilDelimiter(writer, '\n', self.buf.len) catch |err| {
if (err == error.EndOfStream) {
return null;
} else {
std.debug.print("ConfigIterator Error: {any}\n", .{err});
unreachable;
}
};
var line = fbs.getWritten();
var keyval = std.mem.split(u8, line, "=");
var result = Option{
.key = keyval.next() orelse {
std.debug.print("Config {s}: line {} with contents '{s}' is invalid. Skipping.\n", .{
self.filename,
self.i,
line,
});
self.i += 1;
return self.next();
},
.value = keyval.next() orelse {
std.debug.print("Config {s}: line {} with contents '{s}' is invalid. Skipping.\n", .{
self.filename,
self.i,
line,
});
self.i += 1;
return self.next();
},
};
if (keyval.next() != null) {
std.debug.print("Config {s}: line {} with contents '{s}' is invalid. Skipping.\n", .{
self.filename,
self.i,
line,
});
self.i += 1;
return self.next();
}
self.i += 1;
return result;
}
pub fn deinit(self: *ConfigIterator) void {
self.file.close();
}
};
pub fn getConfigIterator(path: []const u8) !ConfigIterator {
var iterator = ConfigIterator{
.filename = path,
.file = try fs.cwd().createFile(path, .{ .read = true, .truncate = false }),
.buf = undefined,
};
return iterator;
} }

View File

@ -11,7 +11,12 @@ const State = @import("flow.zig").State;
pub fn main() !void { pub fn main() !void {
config.getConfig("test"); var configIterator = config.getConfigIterator("test") catch unreachable;
while (configIterator.next()) |option| {
std.debug.print("Key: {s}, Option: {s}\n", .{option.key, option.value});
}
configIterator.deinit();
var renderer = try Renderer.init(); var renderer = try Renderer.init();
defer renderer.deinit(); defer renderer.deinit();