add src/journal/journal.zig

This commit is contained in:
Luna 2019-05-08 23:34:12 -03:00
parent 97b2c0b6a9
commit 6afa1f1f3a
2 changed files with 76 additions and 7 deletions

View file

@ -6,15 +6,18 @@ pub fn build(b: *Builder) void {
exe.setBuildMode(mode);
exe.linkSystemLibrary("c");
//exe.addCompileFlags([][]const u8{"-W -O"});
const source_files = [][]const u8{
"src/journal/main.c",
"src/journal/journal.c",
};
const source_files = [][]const u8{"src/journal/main.c"};
for (source_files) |source| {
exe.addCSourceFile(source, [][]const u8{});
exe.addCSourceFile(source, [][]const u8{"-W -O"});
}
const zig_sources = [][]const u8{"src/journal/journal.zig"};
for (zig_sources) |source| {
const obj = b.addObject("journal", source);
obj.linkSystemLibrary("c");
exe.addObject(obj);
}
// enable us to run the main journal executable via

66
src/journal/journal.zig Normal file
View file

@ -0,0 +1,66 @@
const c = @cImport({
@cInclude("stdio.h");
@cInclude("stdlib.h");
@cInclude("sys/stat.h");
@cInclude("string.h");
@cInclude("time.h");
});
const std = @import("std");
const warn = std.debug.warn;
const allocator = std.heap.c_allocator;
fn alloc_str(size: c_ulong) [*c]u8 {
return @ptrCast([*c]u8, @alignCast(@alignOf(u8), c.malloc(c_ulong(size))));
}
export fn journal_open(topic: [*c]u8) [*c](c.FILE) {
var home_path: [*c]const u8 = c.getenv(c"HOME");
var journal_dir: [*c]u8 = alloc_str(512);
var journal_path: [*c]u8 = alloc_str(1024);
_ = c.snprintf(journal_dir, c_ulong(512), c"%s/.lunabot", home_path);
warn("uwu journal_dir = '{}'", journal_dir.*);
//c.mkdir(journal_dir, c.S_IRWXU | c.S_IRGRP | c.S_IROTH);
// taken off `zig translate-c`. this is cursed, i'm sorry.
_ = c.mkdir(journal_dir, c.__mode_t((((256 | 128) | 64) | (256 >> @import("std").math.Log2Int(c_int)(3))) | ((256 >> @import("std").math.Log2Int(c_int)(3)) >> @import("std").math.Log2Int(c_int)(3))));
_ = c.snprintf(journal_path, c_ulong(1024), c"%s/%s", journal_dir, topic);
warn("journal_path = {}", journal_path.*);
var res: [*c](c.FILE) = c.fopen(journal_path, c"a");
c.free(@ptrCast(?*c_void, journal_path));
c.free(@ptrCast(?*c_void, journal_dir));
return res;
}
export fn journal_write(journal: [*c]c.FILE, message: [*c]u8) void {
_ = c.fwrite(message, c.strlen(message), 1, journal);
}
export fn journal_close(journal: [*c]c.FILE) void {
_ = c.fclose(journal);
}
export fn journal_write_topic(journal: *c.FILE, topic: [*c]u8, message: [*c]u8) void {
var tstamp: [*c]u8 = alloc_str(128);
var fmt_msg: [*c]u8 = alloc_str(128);
var rawtime: c.time_t = undefined;
_ = c.time(&rawtime);
var cur_time: [*c]const c.struct_tm = c.gmtime(&rawtime);
_ = c.strftime(tstamp, usize(128), c"%c", cur_time);
_ = c.sprintf(fmt_msg, c"[%s] [%s]: %s\n", tstamp, topic, message);
c.free(@ptrCast(?*c_void, tstamp));
journal_write(journal, fmt_msg);
}