Add hosts mapping print

This commit is contained in:
Muaz Ahmad 2024-05-13 01:14:40 +05:00
parent ec18ac2152
commit 8145ff694b

View file

@ -3,6 +3,8 @@ const util = @import("util.zig");
const hosts_header = "# local-etc-hosts-updater";
const FILE_LINE_BUFF_SIZE = 50;
pub fn update_hosts(ip: util.IP) !void {
try create_tmp_hosts(ip);
try move_tmp_hosts();
@ -20,7 +22,7 @@ inline fn check_purge(line: []u8, purging: *bool, skip_last_line: *bool) void {
}
fn purge_existing(old_hosts: std.fs.File, tmp_hosts: std.fs.File) !void {
var buff = [_]u8{0x00} ** 50;
var buff = [_]u8{0x00} ** FILE_LINE_BUFF_SIZE;
var buff_stream = std.io.fixedBufferStream(&buff);
const buff_reader = buff_stream.reader();
const buff_writer = buff_stream.writer();
@ -29,7 +31,7 @@ fn purge_existing(old_hosts: std.fs.File, tmp_hosts: std.fs.File) !void {
var purging = false;
var skip_last_line = false;
while (old_reader.streamUntilDelimiter(buff_writer, '\n', 50 - 1)) |_| {
while (old_reader.streamUntilDelimiter(buff_writer, '\n', FILE_LINE_BUFF_SIZE - 1)) |_| {
defer buff_stream.pos = 0;
var n = buff_stream.pos;
// do things to line
@ -41,14 +43,16 @@ fn purge_existing(old_hosts: std.fs.File, tmp_hosts: std.fs.File) !void {
}
if (skip_last_line) {
skip_last_line = false;
if (std.mem.eql(u8, buff[0..n], "")) {
continue;
}
}
// copy line
buff[n] = '\n';
n += 1;
buff_stream.pos = 0;
try buff_reader.streamUntilDelimiter(tmp_writer, '\n', 50);
try buff_reader.streamUntilDelimiter(tmp_writer, '\n', FILE_LINE_BUFF_SIZE);
try tmp_writer.writeByte('\n');
} else |err| {
if (err != error.EndOfStream) {
@ -58,9 +62,8 @@ fn purge_existing(old_hosts: std.fs.File, tmp_hosts: std.fs.File) !void {
}
fn append_new(tmp_hosts: std.fs.File, addr: std.net.Address) !void {
_ = addr;
const writer = tmp_hosts.writer();
var buff = [_]u8{0x00} ** 50;
var buff = [_]u8{0x00} ** FILE_LINE_BUFF_SIZE;
// write output
const header_len = hosts_header.*.len;
@ -70,9 +73,19 @@ fn append_new(tmp_hosts: std.fs.File, addr: std.net.Address) !void {
var subdomains = try get_subdomains();
const domain = try util.getenv("TARGET_DOMAIN");
while (subdomains.next()) |subdomain| {
std.debug.print("{s}.{s}\n", .{ subdomain, domain });
var addr_buff = [_]u8{0x00} ** 50;
var addr_str = try std.fmt.bufPrint(&addr_buff, "{}", .{addr});
if (addr_str[0] == '[') {
addr_str = addr_str[1 .. addr_str.len - 3]; // [fd00::0000]:0
} else {
addr_str = addr_str[0 .. addr_str.len - 2]; // 192.168.0.0:0
}
while (subdomains.next()) |subdomain| {
try std.fmt.format(writer, "{s} {s}.{s}\n", .{ addr_str, subdomain, domain });
}
// add extra final newline
try writer.writeByte('\n');
}