gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb37875ccb37875ccident mission 012 part 3: real-Chrome fixes (brand 44 px, identity form width), e2e walk, report, logmreb37875cc/plugins/fs/fs.zig

50.2 KB

  1. // hl:fs plugin — native shared library
  2. // Compiled to fs.so, loaded by runtime via dlopen
  3. //
  4. // Exports:
  5. // hl_fs_file(path) → file descriptor with metadata + line iterator
  6. // hl_fs_read_file(path) → entire file as string (raw bytes, unchecked)
  7. // hl_fs_write_file(path, text, mode?) / hl_fs_write_file_hex(path, hex, mode?)
  8. // hl_fs_append_file(path, text, mode?) / hl_fs_append_file_hex(path, hex, mode?)
  9. // hl_fs_list_dir(path) → streaming directory iterator
  10. const std = @import("std");
  11. const api = @import("plugin_api");
  12. const linux = std.os.linux;
  13. const HlValue = api.HlValue;
  14. const HlObject = api.HlObject;
  15. const HlField = api.HlField;
  16. const HlIterator = api.HlIterator;
  17. const HlString = api.HlString;
  18. // the plugins' allocator (plugin_api.zig)
  19. const allocator = api.allocator;
  20. // =========================================================================
  21. // Path resolution (mission 068)
  22. //
  23. // CONTRACT: relative paths passed to hl:fs resolve against the MAIN SCRIPT's
  24. // directory, not the process CWD — Hybriel path resolution is file-relative
  25. // everywhere (import, inherit, plugin discovery), and fs follows suit.
  26. // Absolute paths are used as-is. The runtime injects the script dir via the
  27. // optional plugin hook hl_fs_set_script_dir right after dlopen.
  28. // =========================================================================
  29. var script_dir: ?[]u8 = null;
  30. export fn hl_fs_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  31. if (script_dir) |old| allocator.free(old);
  32. script_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  33. }
  34. /// A compiled binary's unpacked `ship` files (mission 316): a relative path
  35. /// one of them answers resolves there; any other as it would without it.
  36. var ship_dir: ?[]u8 = null;
  37. export fn hl_fs_set_ship_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  38. if (ship_dir) |old| allocator.free(old);
  39. ship_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  40. }
  41. /// THE READ TRACE (326 rung 12, the build cache): while a trace file is named
  42. /// — by hl:fs `traceReads(path)`, or by HL_FS_TRACE in the environment, which a build
  43. /// hands the programs it runs — every path this plugin reads, lists or probes
  44. /// is appended to it as one line, `r <path>`, `l <path>` or `e <path>`, the
  45. /// path as resolved (absolute when the process's was). A build records what it
  46. /// depends on this way; nothing else changes.
  47. var trace_path: ?[:0]u8 = null;
  48. var trace_env_read = false;
  49. export fn hl_fs_trace(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  50. trace_env_read = true;
  51. if (trace_path) |old| allocator.free(old);
  52. trace_path = null;
  53. if (argc >= 1 and argv[0].type == .hl_string) {
  54. const p = argv[0].data.string.ptr[0..argv[0].data.string.len];
  55. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  56. }
  57. return api.makeNull();
  58. }
  59. fn traceAccess(kind: u8, resolved: []const u8) void {
  60. if (!trace_env_read) {
  61. trace_env_read = true;
  62. if (std.c.getenv("HL_FS_TRACE")) |e| {
  63. const p = std.mem.span(e);
  64. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  65. }
  66. }
  67. const tp = trace_path orelse return;
  68. var cwd_buf: [4096]u8 = undefined;
  69. const line = if (resolved.len > 0 and resolved[0] == '/')
  70. std.fmt.allocPrint(allocator, "{c} {s}\n", .{ kind, resolved }) catch return
  71. else blk: {
  72. const rc: isize = @bitCast(linux.getcwd(&cwd_buf, cwd_buf.len));
  73. if (rc <= 0) return;
  74. const cwd = std.mem.sliceTo(&cwd_buf, 0);
  75. break :blk std.fmt.allocPrint(allocator, "{c} {s}/{s}\n", .{ kind, cwd, resolved }) catch return;
  76. };
  77. defer allocator.free(line);
  78. const rc = linuxOpenRc(tp, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, 0o600);
  79. if (rc < 0) return;
  80. const fd: i32 = @intCast(rc);
  81. defer _ = linux.close(fd);
  82. _ = linux.write(fd, line.ptr, line.len);
  83. }
  84. /// hl_fs_digest(path) — the SHA-256 of a file's bytes as 64 hex digits, or
  85. /// null when it cannot be read; hl_fs_digest_text(text) — of a text's. The
  86. /// build cache's content keys (326 rung 12): hashed here, in the plugin, so
  87. /// every engine has them and nothing crosses as a value but the answer.
  88. export fn hl_fs_digest(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  89. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digest expects a string path");
  90. const path_str = argv[0].data.string;
  91. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  92. defer allocator.free(resolved);
  93. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  94. defer allocator.free(path_z);
  95. const rc = linuxOpenRc(path_z, .{}, 0);
  96. if (rc < 0) return api.makeNull();
  97. const fd: i32 = @intCast(rc);
  98. defer _ = linux.close(fd);
  99. var h = std.crypto.hash.sha2.Sha256.init(.{});
  100. var buf: [65536]u8 = undefined;
  101. while (true) {
  102. const n: isize = @bitCast(linux.read(fd, &buf, buf.len));
  103. if (n == 0) break;
  104. if (n < 0) {
  105. if (@as(usize, @intCast(-n)) == @intFromEnum(linux.E.INTR)) continue;
  106. return api.makeNull();
  107. }
  108. h.update(buf[0..@intCast(n)]);
  109. }
  110. return hexDigest(&h);
  111. }
  112. export fn hl_fs_digest_text(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  113. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digestText expects a string");
  114. const t = argv[0].data.string;
  115. var h = std.crypto.hash.sha2.Sha256.init(.{});
  116. h.update(t.ptr[0..t.len]);
  117. return hexDigest(&h);
  118. }
  119. fn hexDigest(h: *std.crypto.hash.sha2.Sha256) HlValue {
  120. var d: [32]u8 = undefined;
  121. h.final(&d);
  122. const out = allocator.alloc(u8, 64) catch return api.makeNull();
  123. const hex = "0123456789abcdef";
  124. for (d, 0..) |b, i| {
  125. out[i * 2] = hex[b >> 4];
  126. out[i * 2 + 1] = hex[b & 15];
  127. }
  128. return api.makeString(out);
  129. }
  130. /// Resolve a (possibly relative) path against the script dir. Returned slice
  131. /// is allocated with the plugin allocator; caller frees.
  132. fn resolvePath(path: []const u8) ?[]u8 {
  133. if (path.len == 0) return allocator.dupe(u8, path) catch null;
  134. if (path[0] == '/') return allocator.dupe(u8, path) catch null;
  135. if (ship_dir) |sd| {
  136. if (std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ sd, path }, 0)) |shipped| {
  137. defer allocator.free(shipped);
  138. if (std.c.access(shipped.ptr, 0) == 0) return allocator.dupe(u8, shipped) catch null;
  139. } else |_| {}
  140. }
  141. if (script_dir) |sd| {
  142. return std.fmt.allocPrint(allocator, "{s}/{s}", .{ sd, path }) catch null;
  143. }
  144. return allocator.dupe(u8, path) catch null;
  145. }
  146. // =========================================================================
  147. // Error values (mission 068): open failures are LOUD — api.makeError with
  148. // the operation, the path as the caller wrote it, and the OS reason. The
  149. // runtime turns a top-level error value into a located runtime error.
  150. // =========================================================================
  151. fn errnoText(errno: usize) []const u8 {
  152. return switch (errno) {
  153. 2 => "no such file or directory",
  154. 13 => "permission denied",
  155. 20 => "not a directory",
  156. 21 => "is a directory",
  157. else => "I/O error",
  158. };
  159. }
  160. fn errDeinit(val: *api.HlValue) callconv(.c) void {
  161. if (val.type == .hl_error) {
  162. const s = val.data.string;
  163. allocator.free(@constCast(s.ptr[0..s.len]));
  164. }
  165. }
  166. fn makeOpenError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  167. const msg = std.fmt.allocPrint(allocator, "{s}: cannot open '{s}' — {s} (errno {d}); relative paths resolve against the script's directory", .{ op, path, errnoText(errno), errno }) catch
  168. return api.makeError("fs: cannot open file");
  169. var v = api.makeError(msg);
  170. v.deinit_fn = &errDeinit;
  171. return v;
  172. }
  173. fn makeReadError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  174. const msg = std.fmt.allocPrint(allocator, "{s}: cannot read '{s}' — {s} (errno {d})", .{ op, path, errnoText(errno), errno }) catch
  175. return api.makeError("fs: cannot read file");
  176. var v = api.makeError(msg);
  177. v.deinit_fn = &errDeinit;
  178. return v;
  179. }
  180. // =========================================================================
  181. // hl_fs_file — file descriptor with metadata + line iterator
  182. // =========================================================================
  183. const FileIterState = struct {
  184. fd: i32,
  185. allocated_strings: std.array_list.Managed([]u8),
  186. done: bool,
  187. buf: [4096]u8,
  188. buf_pos: usize,
  189. buf_len: usize,
  190. };
  191. export fn hl_fs_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  192. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.file expects a string path");
  193. const path_str = argv[0].data.string;
  194. const path = path_str.ptr[0..path_str.len];
  195. // Resolve relative paths against the script dir; keep the caller's path
  196. // for the descriptor's name/path fields.
  197. const resolved = resolvePath(path) orelse return api.makeNull();
  198. defer allocator.free(resolved);
  199. traceAccess('r', resolved);
  200. // We need a null-terminated path for the OS
  201. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  202. defer allocator.free(path_z);
  203. // Open file
  204. const rc = linuxOpenRc(path_z, .{}, 0);
  205. if (rc < 0) return makeOpenError("fs.file", path, @intCast(-rc));
  206. const fd: i32 = @intCast(rc);
  207. // Stat for size, chmod, uid, gid
  208. var size: f64 = 0;
  209. var chmod: f64 = 0;
  210. var uid: f64 = 0;
  211. var gid: f64 = 0;
  212. var stat_ok = false;
  213. var statx_buf: std.os.linux.Statx = undefined;
  214. const statx_rc = std.os.linux.statx(
  215. fd,
  216. "",
  217. std.os.linux.AT.EMPTY_PATH,
  218. std.os.linux.STATX.BASIC_STATS,
  219. &statx_buf,
  220. );
  221. if (statx_rc == 0) {
  222. size = @floatFromInt(statx_buf.size);
  223. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  224. uid = @floatFromInt(statx_buf.uid);
  225. gid = @floatFromInt(statx_buf.gid);
  226. stat_ok = true;
  227. }
  228. // Extract name from path
  229. const name = if (std.mem.lastIndexOfScalar(u8, path, '/')) |idx|
  230. path[idx + 1 ..]
  231. else
  232. path;
  233. // Mime from extension
  234. const mime = mimeFromName(name);
  235. // Build fields: name, path, size, mime, chmod, user, group = 7 fields
  236. const field_count: usize = 7;
  237. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  238. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name) };
  239. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(path) };
  240. fields[2] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  241. fields[3] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  242. fields[4] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  243. if (stat_ok) {
  244. fields[5] = .{ .key = hlStr("user"), .value = api.makeNumber(uid) };
  245. fields[6] = .{ .key = hlStr("group"), .value = api.makeNumber(gid) };
  246. } else {
  247. fields[5] = .{ .key = hlStr("user"), .value = api.makeNull() };
  248. fields[6] = .{ .key = hlStr("group"), .value = api.makeNull() };
  249. }
  250. const obj = allocator.create(HlObject) catch return api.makeNull();
  251. obj.* = .{
  252. .fields = fields.ptr,
  253. .field_count = field_count,
  254. .deinit_fn = &fileObjDeinit,
  255. };
  256. // Create line iterator
  257. const iter_state = allocator.create(FileIterState) catch return api.makeNull();
  258. iter_state.* = .{
  259. .fd = fd,
  260. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  261. .done = false,
  262. .buf = undefined,
  263. .buf_pos = 0,
  264. .buf_len = 0,
  265. };
  266. const iter = allocator.create(HlIterator) catch return api.makeNull();
  267. iter.* = .{
  268. .context = @ptrCast(iter_state),
  269. .next_fn = &fileIterNext,
  270. .deinit_fn = &fileIterDeinit,
  271. };
  272. // Return object — runtime will see it has both object fields and an iterator
  273. // We pack the iterator pointer into the object by adding one more field
  274. const full_fields = allocator.alloc(HlField, field_count + 1) catch return api.makeNull();
  275. @memcpy(full_fields[0..field_count], fields);
  276. full_fields[field_count] = .{ .key = hlStr("__iter"), .value = api.makeIterator(iter) };
  277. // Free the original fields, use full_fields
  278. allocator.free(fields);
  279. obj.fields = full_fields.ptr;
  280. obj.field_count = field_count + 1;
  281. return api.makeObject(obj);
  282. }
  283. fn fileIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  284. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  285. if (state.done) return api.makeNull();
  286. var line_buf = std.array_list.Managed(u8).init(allocator);
  287. while (true) {
  288. if (state.buf_pos < state.buf_len) {
  289. const remaining = state.buf[state.buf_pos..state.buf_len];
  290. if (std.mem.indexOfScalar(u8, remaining, '\n')) |nl_pos| {
  291. line_buf.appendSlice(remaining[0..nl_pos]) catch return api.makeNull();
  292. state.buf_pos += nl_pos + 1;
  293. break;
  294. } else {
  295. line_buf.appendSlice(remaining) catch return api.makeNull();
  296. state.buf_pos = 0;
  297. state.buf_len = 0;
  298. }
  299. }
  300. // Read from file using posix read
  301. const n = linuxRead(state.fd, &state.buf) orelse {
  302. state.done = true;
  303. break;
  304. };
  305. if (n == 0) {
  306. state.done = true;
  307. break;
  308. }
  309. state.buf_pos = 0;
  310. state.buf_len = n;
  311. }
  312. if (line_buf.items.len == 0 and state.done) {
  313. line_buf.deinit();
  314. return api.makeNull();
  315. }
  316. const line = line_buf.toOwnedSlice() catch return api.makeNull();
  317. state.allocated_strings.append(line) catch return api.makeNull();
  318. return api.makeString(line);
  319. }
  320. fn fileIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  321. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return));
  322. _ = linux.close(state.fd);
  323. for (state.allocated_strings.items) |s| {
  324. allocator.free(s);
  325. }
  326. state.allocated_strings.deinit();
  327. allocator.destroy(state);
  328. }
  329. fn fileObjDeinit(obj: *HlObject) callconv(.c) void {
  330. const fields = obj.fields[0..obj.field_count];
  331. // Check for iterator field and clean it up (only if not already nulled out by runtime)
  332. for (fields) |field| {
  333. if (field.value.type == .hl_iterator) {
  334. const iter = field.value.data.iterator;
  335. if (iter.deinit_fn) |deinit_fn| {
  336. deinit_fn(iter.context);
  337. }
  338. allocator.destroy(iter);
  339. }
  340. }
  341. allocator.free(fields);
  342. allocator.destroy(obj);
  343. }
  344. // =========================================================================
  345. // hl_fs_read_file — read entire file as string
  346. // =========================================================================
  347. fn readFileDeinit(val: *HlValue) callconv(.c) void {
  348. if (val.type == .hl_string) {
  349. const s = val.data.string;
  350. allocator.free(@constCast(s.ptr[0..s.len]));
  351. }
  352. }
  353. /// exists(path) → Boolean (mission 077, 074 GAP 8). The ONLY hl:fs entry point
  354. /// that never errors: it answers a question, and "no" is an answer, not a
  355. /// failure. Same script-relative resolution as everything else. Without it the
  356. /// only way to test a path was to open it and survive the error — which is why
  357. /// the retired live_server used to index `static/` blind instead of probing it.
  358. export fn hl_fs_exists(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  359. if (argc < 1 or argv[0].type != .hl_string) return api.makeBool(false);
  360. const path_str = argv[0].data.string;
  361. const path = path_str.ptr[0..path_str.len];
  362. const resolved = resolvePath(path) orelse return api.makeBool(false);
  363. defer allocator.free(resolved);
  364. traceAccess('e', resolved);
  365. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeBool(false);
  366. defer allocator.free(path_z);
  367. // statx, not open: a directory, a symlink target, a device — anything the
  368. // OS can name — counts, and nothing is opened (no fd, no side effect).
  369. var statx_buf: std.os.linux.Statx = undefined;
  370. const rc = std.os.linux.statx(
  371. std.os.linux.AT.FDCWD,
  372. path_z,
  373. 0,
  374. std.os.linux.STATX.BASIC_STATS,
  375. &statx_buf,
  376. );
  377. return api.makeBool(@as(isize, @bitCast(rc)) == 0);
  378. }
  379. export fn hl_fs_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  380. return readWhole(argc, argv, false);
  381. }
  382. /// tryReadFile(path) → the file as a string, or null when the path is not
  383. /// there (ENOENT/ENOTDIR). Any other failure is an error as in readFile. For a
  384. /// file another process may delete between a probe and the read (a shared
  385. /// cache): the vanishing is an answer, not a fault.
  386. export fn hl_fs_try_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  387. return readWhole(argc, argv, true);
  388. }
  389. fn readWhole(argc: u32, argv: [*]const HlValue, absent_is_null: bool) HlValue {
  390. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.readFile expects a string path");
  391. const path_str = argv[0].data.string;
  392. const path = path_str.ptr[0..path_str.len];
  393. const resolved = resolvePath(path) orelse return api.makeNull();
  394. defer allocator.free(resolved);
  395. traceAccess('r', resolved);
  396. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  397. defer allocator.free(path_z);
  398. const rc = linuxOpenRc(path_z, .{}, 0);
  399. if (rc < 0) {
  400. const en: usize = @intCast(-rc);
  401. if (absent_is_null and (en == @intFromEnum(linux.E.NOENT) or en == @intFromEnum(linux.E.NOTDIR))) return api.makeNull();
  402. return makeOpenError("fs.readFile", path, en);
  403. }
  404. const fd: i32 = @intCast(rc);
  405. defer _ = linux.close(fd);
  406. // The whole file: no size cap (a 10 MiB cap once truncated silently, ticket #112).
  407. // A failed read is an error naming the path, never a short string.
  408. var content = std.array_list.Managed(u8).init(allocator);
  409. defer content.deinit();
  410. var buf: [65536]u8 = undefined;
  411. while (true) {
  412. const n_read: isize = @bitCast(linux.read(fd, &buf, buf.len));
  413. if (n_read == 0) break;
  414. if (n_read < 0) {
  415. const errno: usize = @intCast(-n_read);
  416. if (errno == @intFromEnum(linux.E.INTR)) continue;
  417. return makeReadError("fs.readFile", path, errno);
  418. }
  419. content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readFile: out of memory reading the file");
  420. }
  421. const result_slice = content.toOwnedSlice() catch return api.makeNull();
  422. var result = api.makeString(result_slice);
  423. result.deinit_fn = &readFileDeinit;
  424. return result;
  425. }
  426. // =========================================================================
  427. // hl_fs_list_dir — streaming directory iterator with metadata
  428. // =========================================================================
  429. const DirIterState = struct {
  430. fd: i32,
  431. base_path: []const u8,
  432. allocated_strings: std.array_list.Managed([]u8),
  433. // Linux getdents64 buffer
  434. dents_buf: [4096]u8,
  435. dents_pos: usize,
  436. dents_len: usize,
  437. done: bool,
  438. };
  439. export fn hl_fs_list_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  440. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.listDir expects a string path");
  441. const path_str = argv[0].data.string;
  442. const path = path_str.ptr[0..path_str.len];
  443. const resolved = resolvePath(path) orelse return api.makeNull();
  444. defer allocator.free(resolved);
  445. traceAccess('l', resolved);
  446. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  447. defer allocator.free(path_z);
  448. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  449. if (rc < 0) return makeOpenError("fs.listDir", path, @intCast(-rc));
  450. const fd: i32 = @intCast(rc);
  451. const path_copy = allocator.dupe(u8, path) catch return api.makeNull();
  452. const state = allocator.create(DirIterState) catch return api.makeNull();
  453. state.* = .{
  454. .fd = fd,
  455. .base_path = path_copy,
  456. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  457. .dents_buf = undefined,
  458. .dents_pos = 0,
  459. .dents_len = 0,
  460. .done = false,
  461. };
  462. const iter = allocator.create(HlIterator) catch return api.makeNull();
  463. iter.* = .{
  464. .context = @ptrCast(state),
  465. .next_fn = &dirIterNext,
  466. .deinit_fn = &dirIterDeinit,
  467. };
  468. return api.makeIterator(iter);
  469. }
  470. fn dirIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  471. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  472. if (state.done) return api.makeNull();
  473. while (true) {
  474. // Need more directory entries?
  475. if (state.dents_pos >= state.dents_len) {
  476. const rc = std.os.linux.getdents64(state.fd, &state.dents_buf, state.dents_buf.len);
  477. if (@as(isize, @bitCast(rc)) <= 0) {
  478. state.done = true;
  479. return api.makeNull();
  480. }
  481. state.dents_len = rc;
  482. state.dents_pos = 0;
  483. }
  484. // Parse next dirent64
  485. const entry_ptr: *align(1) std.os.linux.dirent64 = @ptrCast(&state.dents_buf[state.dents_pos]);
  486. state.dents_pos += entry_ptr.reclen;
  487. // Get name
  488. const name_ptr: [*]const u8 = @ptrCast(&entry_ptr.name);
  489. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  490. const name = name_ptr[0..name_len];
  491. // Skip . and ..
  492. if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
  493. const name_copy = allocator.dupe(u8, name) catch return api.makeNull();
  494. state.allocated_strings.append(name_copy) catch return api.makeNull();
  495. // Build full path
  496. const full_path = std.fmt.allocPrint(allocator, "{s}/{s}", .{ state.base_path, name }) catch return api.makeNull();
  497. state.allocated_strings.append(full_path) catch return api.makeNull();
  498. // Entry type from d_type
  499. const kind_str: []const u8 = switch (entry_ptr.type) {
  500. std.os.linux.DT.DIR => "directory",
  501. std.os.linux.DT.REG => "file",
  502. std.os.linux.DT.LNK => "symlink",
  503. else => "other",
  504. };
  505. // Stat for size, chmod, uid, gid
  506. var size: f64 = 0;
  507. var chmod: f64 = 0;
  508. var e_uid: f64 = 0;
  509. var e_gid: f64 = 0;
  510. // null-terminate name for statx
  511. var name_z_buf: [256]u8 = undefined;
  512. if (name.len < name_z_buf.len) {
  513. @memcpy(name_z_buf[0..name.len], name);
  514. name_z_buf[name.len] = 0;
  515. var statx_buf: std.os.linux.Statx = undefined;
  516. const src = std.os.linux.statx(
  517. state.fd,
  518. @ptrCast(name_z_buf[0 .. name.len + 1]),
  519. 0,
  520. std.os.linux.STATX.BASIC_STATS,
  521. &statx_buf,
  522. );
  523. if (src == 0) {
  524. size = @floatFromInt(statx_buf.size);
  525. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  526. e_uid = @floatFromInt(statx_buf.uid);
  527. e_gid = @floatFromInt(statx_buf.gid);
  528. }
  529. }
  530. const mime = mimeFromName(name_copy);
  531. // Build object: name, path, type, size, mime, chmod, user, group
  532. // The runtime's hlObjectToValue will call entryObjDeinit after conversion,
  533. // so these objects are freed immediately upon consumption.
  534. const field_count: usize = 8;
  535. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  536. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  537. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(full_path) };
  538. fields[2] = .{ .key = hlStr("type"), .value = api.makeString(kind_str) };
  539. fields[3] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  540. fields[4] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  541. fields[5] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  542. fields[6] = .{ .key = hlStr("user"), .value = api.makeNumber(e_uid) };
  543. fields[7] = .{ .key = hlStr("group"), .value = api.makeNumber(e_gid) };
  544. const obj = allocator.create(HlObject) catch return api.makeNull();
  545. obj.* = .{
  546. .fields = fields.ptr,
  547. .field_count = field_count,
  548. .deinit_fn = &entryObjDeinit,
  549. };
  550. return api.makeObject(obj);
  551. }
  552. }
  553. fn entryObjDeinit(obj: *HlObject) callconv(.c) void {
  554. allocator.free(obj.fields[0..obj.field_count]);
  555. allocator.destroy(obj);
  556. }
  557. fn dirIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  558. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return));
  559. _ = linux.close(state.fd);
  560. for (state.allocated_strings.items) |s| {
  561. allocator.free(s);
  562. }
  563. state.allocated_strings.deinit();
  564. allocator.free(@constCast(state.base_path));
  565. allocator.destroy(state);
  566. }
  567. // =========================================================================
  568. // Helpers
  569. // =========================================================================
  570. /// Raw open: >= 0 is the fd, < 0 is -errno.
  571. fn linuxOpenRc(path_z: [*:0]const u8, flags: linux.O, mode: u32) isize {
  572. const rc = linux.open(path_z, flags, mode);
  573. return @bitCast(rc);
  574. }
  575. fn linuxRead(fd: i32, buf: []u8) ?usize {
  576. const rc = linux.read(fd, buf.ptr, buf.len);
  577. if (@as(isize, @bitCast(rc)) <= 0) return null;
  578. return rc;
  579. }
  580. fn hlStr(comptime s: []const u8) HlString {
  581. return .{ .ptr = s.ptr, .len = s.len };
  582. }
  583. fn mimeFromName(name: []const u8) []const u8 {
  584. const ext = if (std.mem.lastIndexOfScalar(u8, name, '.')) |dot|
  585. name[dot..]
  586. else
  587. return "application/octet-stream";
  588. if (std.mem.eql(u8, ext, ".txt")) return "text/plain";
  589. if (std.mem.eql(u8, ext, ".html") or std.mem.eql(u8, ext, ".htm")) return "text/html";
  590. if (std.mem.eql(u8, ext, ".css")) return "text/css";
  591. if (std.mem.eql(u8, ext, ".js")) return "text/javascript";
  592. if (std.mem.eql(u8, ext, ".json")) return "application/json";
  593. if (std.mem.eql(u8, ext, ".xml")) return "application/xml";
  594. if (std.mem.eql(u8, ext, ".png")) return "image/png";
  595. if (std.mem.eql(u8, ext, ".jpg") or std.mem.eql(u8, ext, ".jpeg")) return "image/jpeg";
  596. if (std.mem.eql(u8, ext, ".gif")) return "image/gif";
  597. if (std.mem.eql(u8, ext, ".svg")) return "image/svg+xml";
  598. if (std.mem.eql(u8, ext, ".pdf")) return "application/pdf";
  599. if (std.mem.eql(u8, ext, ".zip")) return "application/zip";
  600. if (std.mem.eql(u8, ext, ".gz")) return "application/gzip";
  601. if (std.mem.eql(u8, ext, ".mp3")) return "audio/mpeg";
  602. if (std.mem.eql(u8, ext, ".mp4")) return "video/mp4";
  603. if (std.mem.eql(u8, ext, ".wasm")) return "application/wasm";
  604. if (std.mem.eql(u8, ext, ".hl")) return "text/x-hybriel";
  605. if (std.mem.eql(u8, ext, ".md")) return "text/markdown";
  606. if (std.mem.eql(u8, ext, ".yml") or std.mem.eql(u8, ext, ".yaml")) return "text/yaml";
  607. if (std.mem.eql(u8, ext, ".toml")) return "application/toml";
  608. if (std.mem.eql(u8, ext, ".csv")) return "text/csv";
  609. if (std.mem.eql(u8, ext, ".ts")) return "text/typescript";
  610. if (std.mem.eql(u8, ext, ".c") or std.mem.eql(u8, ext, ".h")) return "text/x-c";
  611. if (std.mem.eql(u8, ext, ".zig")) return "text/x-zig";
  612. if (std.mem.eql(u8, ext, ".rs")) return "text/x-rust";
  613. if (std.mem.eql(u8, ext, ".py")) return "text/x-python";
  614. if (std.mem.eql(u8, ext, ".sh")) return "text/x-shellscript";
  615. if (std.mem.eql(u8, ext, ".sql")) return "application/sql";
  616. if (std.mem.eql(u8, ext, ".webp")) return "image/webp";
  617. if (std.mem.eql(u8, ext, ".ico")) return "image/x-icon";
  618. if (std.mem.eql(u8, ext, ".woff2")) return "font/woff2";
  619. if (std.mem.eql(u8, ext, ".woff")) return "font/woff";
  620. if (std.mem.eql(u8, ext, ".ttf")) return "font/ttf";
  621. return "application/octet-stream";
  622. }
  623. // ── fs.watch: an inotify LOOP SOURCE (the dev-reload bell) ───────────────────
  624. // `watch(path)` returns an event-loop source whose wake_fd IS the inotify fd,
  625. // so the loop's own epoll_wait wakes on a save — no polling anywhere. Watches
  626. // the directory RECURSIVELY at registration (dot-dirs skipped); directories
  627. // created afterwards are picked up the next time the app is restarted, which
  628. // is the honest v1 for a dev tool.
  629. //
  630. // EXCLUSIONS (mission 266). `watch(path, exclude)` takes a second argument —
  631. // a path STRING or a LIST of them, the same either-shape the plugin surface
  632. // already uses in `hl_proc_spawn` — naming directories the descent must not
  633. // enter. One argument still means "watch everything": the argument is optional
  634. // and a null is the same as absent.
  635. //
  636. // This exists because a program that knows, at startup, about a directory it
  637. // will write to constantly (hl:web's session store is the first) had NO way to
  638. // say so. The only skip the walker possessed was "the name starts with a dot",
  639. // so the framework's advice was to RENAME the directory — a lecture standing
  640. // in for a fix. The dot-dir skip STAYS; `.git` is its reason and it is a good
  641. // one. This is a second, explicit reason to skip, not a replacement.
  642. const WatchState = struct {
  643. ifd: i32,
  644. buf: [4096]u8 align(4) = undefined,
  645. len: usize = 0,
  646. pos: usize = 0,
  647. };
  648. /// LEXICAL path normalisation — collapses `//` and resolves `.` / `..`
  649. /// without touching the filesystem. It must be lexical: an excluded directory
  650. /// need not exist yet at the moment the watch is armed (hl:web resolves its
  651. /// session dir before it creates it), and realpath(2) on a missing path fails.
  652. /// Both the watch root and every exclusion go through this, so the comparison
  653. /// below is between two paths written the same way.
  654. fn normalizePath(path: []const u8) ?[]u8 {
  655. const absolute = path.len > 0 and path[0] == '/';
  656. var parts = std.ArrayListUnmanaged([]const u8).empty;
  657. defer parts.deinit(allocator);
  658. var it = std.mem.tokenizeScalar(u8, path, '/');
  659. while (it.next()) |seg| {
  660. if (std.mem.eql(u8, seg, ".")) continue;
  661. if (std.mem.eql(u8, seg, "..")) {
  662. if (parts.items.len > 0 and !std.mem.eql(u8, parts.items[parts.items.len - 1], "..")) {
  663. _ = parts.pop();
  664. continue;
  665. }
  666. if (absolute) continue; // ".." above "/" is "/"
  667. }
  668. parts.append(allocator, seg) catch return null;
  669. }
  670. var out = std.ArrayListUnmanaged(u8).empty;
  671. defer out.deinit(allocator);
  672. for (parts.items, 0..) |seg, i| {
  673. if (absolute or i > 0) out.append(allocator, '/') catch return null;
  674. out.appendSlice(allocator, seg) catch return null;
  675. }
  676. if (out.items.len == 0) out.appendSlice(allocator, if (absolute) "/" else ".") catch return null;
  677. return allocator.dupe(u8, out.items) catch null;
  678. }
  679. /// Is `child` the directory `root`, or somewhere under it? Both must already
  680. /// be normalised. A bare `startsWith` would call `/a/sessions-old` a child of
  681. /// `/a/sessions`, which is the whole reason this is a function: the byte after
  682. /// the prefix has to BE a separator.
  683. fn pathIsInside(child: []const u8, root: []const u8) bool {
  684. if (root.len == 0) return false;
  685. if (std.mem.eql(u8, child, root)) return true;
  686. if (child.len <= root.len) return false;
  687. if (!std.mem.startsWith(u8, child, root)) return false;
  688. if (root[root.len - 1] == '/') return true; // root is "/" itself
  689. return child[root.len] == '/';
  690. }
  691. fn addWatchesRecursive(ifd: i32, dir_path: []const u8, depth: u32, excludes: []const []const u8) void {
  692. if (depth > 8) return;
  693. // The SECOND reason to skip a directory (mission 266). `dir_path` is
  694. // normalised: the root was normalised before the first call and every
  695. // child below is that root plus one plain name.
  696. for (excludes) |ex| if (pathIsInside(dir_path, ex)) return;
  697. const path_z = allocator.dupeZ(u8, dir_path) catch return;
  698. defer allocator.free(path_z);
  699. const mask: u32 = linux.IN.CLOSE_WRITE | linux.IN.CREATE | linux.IN.DELETE | linux.IN.MOVED_TO | linux.IN.MOVED_FROM;
  700. _ = linux.inotify_add_watch(ifd, path_z, mask);
  701. // The descent walks getdents64 directly, like hl_fs_list_dir does — this
  702. // plugin speaks raw syscalls throughout and never pulls in std.fs.
  703. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  704. if (rc < 0) return;
  705. const fd: i32 = @intCast(rc);
  706. defer _ = linux.close(fd);
  707. var dents: [4096]u8 align(8) = undefined;
  708. while (true) {
  709. const got = linux.getdents64(fd, &dents, dents.len);
  710. if (@as(isize, @bitCast(got)) <= 0) break;
  711. var pos: usize = 0;
  712. while (pos < got) {
  713. const entry: *align(1) linux.dirent64 = @ptrCast(&dents[pos]);
  714. pos += entry.reclen;
  715. if (entry.type != linux.DT.DIR) continue;
  716. const name_ptr: [*]const u8 = @ptrCast(&entry.name);
  717. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  718. const name = name_ptr[0..name_len];
  719. // "." and ".." would recurse forever; every other dot-dir is noise
  720. // for a dev watcher (.git alone would cost thousands of watches).
  721. if (name.len == 0 or name[0] == '.') continue;
  722. const child = std.fmt.allocPrint(allocator, "{s}/{s}", .{ dir_path, name }) catch continue;
  723. defer allocator.free(child);
  724. addWatchesRecursive(ifd, child, depth + 1, excludes);
  725. }
  726. }
  727. }
  728. /// One exclusion, resolved against the script dir like every other hl:fs path
  729. /// and then normalised. Appends nothing on an empty string.
  730. fn appendExclusion(list: *std.ArrayListUnmanaged([]u8), raw: []const u8) bool {
  731. if (raw.len == 0) return true;
  732. const resolved = resolvePath(raw) orelse return false;
  733. defer allocator.free(resolved);
  734. const norm = normalizePath(resolved) orelse return false;
  735. list.append(allocator, norm) catch {
  736. allocator.free(norm);
  737. return false;
  738. };
  739. return true;
  740. }
  741. export fn hl_fs_watch(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  742. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:fs: watch(path) needs a path string");
  743. const raw = argv[0].data.string.ptr[0..argv[0].data.string.len];
  744. const resolved = resolvePath(raw) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  745. defer allocator.free(resolved);
  746. const path = normalizePath(resolved) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  747. defer allocator.free(path);
  748. // THE OPTIONAL SECOND ARGUMENT: absent or null → watch everything, exactly
  749. // as before. A string is one directory; an object with numeric keys is the
  750. // loader's list shape (`hl_proc_spawn` reads its argv list the same way).
  751. var excludes = std.ArrayListUnmanaged([]u8).empty;
  752. defer {
  753. for (excludes.items) |e| allocator.free(e);
  754. excludes.deinit(allocator);
  755. }
  756. if (argc >= 2) {
  757. switch (argv[1].type) {
  758. .hl_null => {},
  759. .hl_string => {
  760. const sv = argv[1].data.string;
  761. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  762. },
  763. .hl_object => {
  764. const obj_in = argv[1].data.object;
  765. for (obj_in.fields[0..obj_in.field_count]) |field| {
  766. if (field.value.type == .hl_null) continue;
  767. if (field.value.type != .hl_string) return api.makeError("hl:fs: watch(path, exclude): every exclusion must be a path string");
  768. const sv = field.value.data.string;
  769. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  770. }
  771. },
  772. else => return api.makeError("hl:fs: watch(path, exclude): exclude is a path string or a list of path strings"),
  773. }
  774. }
  775. const rc = linux.inotify_init1(linux.IN.NONBLOCK);
  776. const ifd: i32 = @intCast(@as(isize, @bitCast(rc)));
  777. if (ifd < 0) return api.makeError("hl:fs: watch: inotify unavailable");
  778. addWatchesRecursive(ifd, path, 0, excludes.items);
  779. const state = allocator.create(WatchState) catch return api.makeError("hl:fs: out of memory");
  780. state.* = .{ .ifd = ifd };
  781. const iter = allocator.create(HlIterator) catch return api.makeError("hl:fs: out of memory");
  782. iter.* = .{
  783. .context = @ptrCast(state),
  784. .next_fn = &watchTryNext, // non-blocking either way — event loop only
  785. .try_next_fn = &watchTryNext,
  786. .deinit_fn = &watchDeinit,
  787. .wake_fd = ifd,
  788. };
  789. return api.makeIterator(iter);
  790. }
  791. fn watchTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  792. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  793. if (st.pos >= st.len) {
  794. const r = linux.read(st.ifd, &st.buf, st.buf.len);
  795. const n: isize = @bitCast(r);
  796. if (n <= 0) return api.makeNull(); // EAGAIN: drained
  797. st.len = @intCast(n);
  798. st.pos = 0;
  799. }
  800. // one inotify_event: wd(i32) mask(u32) cookie(u32) len(u32) name[len]
  801. const base = st.pos;
  802. if (st.len - base < 16) {
  803. st.pos = st.len;
  804. return api.makeNull();
  805. }
  806. const name_len = std.mem.readInt(u32, st.buf[base + 12 ..][0..4], .little);
  807. const name_start = base + 16;
  808. var name: []const u8 = "";
  809. if (name_len > 0 and name_start + name_len <= st.len) {
  810. const raw_name = st.buf[name_start .. name_start + name_len];
  811. name = std.mem.sliceTo(raw_name, 0);
  812. }
  813. st.pos = name_start + name_len;
  814. const fields = allocator.alloc(api.HlField, 1) catch return api.makeNull();
  815. const name_copy = allocator.dupe(u8, name) catch {
  816. allocator.free(fields);
  817. return api.makeNull();
  818. };
  819. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  820. const obj = allocator.create(api.HlObject) catch {
  821. allocator.free(name_copy);
  822. allocator.free(fields);
  823. return api.makeNull();
  824. };
  825. obj.* = .{ .fields = fields.ptr, .field_count = 1, .deinit_fn = &watchEventDeinit };
  826. return api.makeObject(obj);
  827. }
  828. /// An event is the loader's to copy and ours to free (the emit soak, 2026-10-02): with
  829. /// no deinit, every inotify event of the dev watcher — each write a db makes under the
  830. /// watched root — kept its name, its field and its object for good.
  831. fn watchEventDeinit(obj: *api.HlObject) callconv(.c) void {
  832. const sv = obj.fields[0].value.data.string;
  833. allocator.free(@constCast(sv.ptr)[0..sv.len]);
  834. allocator.free(obj.fields[0..obj.field_count]);
  835. allocator.destroy(obj);
  836. }
  837. fn watchDeinit(ctx: ?*anyopaque) callconv(.c) void {
  838. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return));
  839. _ = linux.close(st.ifd);
  840. allocator.destroy(st);
  841. }
  842. // =========================================================================
  843. // THE WRITE SURFACE (2026-08-28)
  844. //
  845. // hl:fs was READ-ONLY until this block: file, readFile, listDir, exists,
  846. // watch. It could report a file's `chmod` and never set one. Session
  847. // persistence is the first thing in this tree that has to put bytes on a
  848. // disk, and the rule when the framework can do something the language
  849. // cannot is that the LANGUAGE is missing it — so the capability lands here,
  850. // as an ordinary hl:fs surface any program can use, not as a private hook
  851. // the session store reaches through.
  852. //
  853. // Three calls, and the shape of each is a decision:
  854. //
  855. // writeFile(path, contents, mode?) ATOMIC. Writes a sibling temp file,
  856. // fsyncs it, then rename()s it over the target — so a reader sees
  857. // either the whole previous file or the whole new one, never a torn
  858. // one. A half-written session file that revives as garbage is a
  859. // silent logout, and the crash that produces it is exactly the crash
  860. // nobody can reproduce. rename(2) within one directory is atomic on
  861. // every filesystem Linux ships; that is the whole reason the temp
  862. // file is a SIBLING rather than in /tmp (a cross-device rename fails).
  863. // mkDir(path, mode?) recursive, and succeeds when the
  864. // directory is already there — the caller wants it to exist, not to
  865. // be the one who created it.
  866. // remove(path) IDEMPOTENT: true when the path is
  867. // gone on return, including when it was already gone. A sweep
  868. // deleting an expired file must not fail because something else
  869. // deleted it first.
  870. //
  871. // MODES ARE EXPLICIT AND DEFAULT TIGHT. hybrilior passes no mode anywhere,
  872. // so its session files land at whatever the umask says — 0644 on a shared
  873. // box, i.e. every session on the machine readable by every other tenant.
  874. // Here the default is 0600 for a file and 0700 for a directory, and a
  875. // caller who wants them looser has to say so. This is not the kind of bug
  876. // that shows up in a test; it shows up in someone else's logs.
  877. // =========================================================================
  878. fn makeWriteError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  879. const msg = std.fmt.allocPrint(allocator, "{s}: cannot write '{s}' — {s} (errno {d}); relative paths resolve against the script's directory", .{ op, path, errnoText(errno), errno }) catch
  880. return api.makeError("fs: write failed");
  881. var v = api.makeError(msg);
  882. v.deinit_fn = &errDeinit;
  883. return v;
  884. }
  885. /// mkdir every missing component of `path`. Returns 0, or the errno of the
  886. /// first component that could not be created for a reason other than "it is
  887. /// already there".
  888. fn mkdirRecursive(path: []const u8, mode: u32) usize {
  889. if (path.len == 0) return 0;
  890. const buf = allocator.dupeZ(u8, path) catch return 12; // ENOMEM
  891. defer allocator.free(buf);
  892. // Walk the separators left to right, creating each prefix in turn. Index
  893. // 0 is skipped so a leading '/' is never itself a component to create.
  894. var i: usize = 1;
  895. while (i <= buf.len) : (i += 1) {
  896. const at_end = i == buf.len;
  897. if (!at_end and buf[i] != '/') continue;
  898. if (!at_end) buf[i] = 0;
  899. const rc: isize = @bitCast(linux.mkdir(buf.ptr, mode));
  900. if (!at_end) buf[i] = '/';
  901. if (rc < 0) {
  902. const errno: usize = @intCast(-rc);
  903. // EEXIST is the success case: the caller wants it to exist.
  904. if (errno != 17) return errno;
  905. }
  906. }
  907. return 0;
  908. }
  909. export fn hl_fs_mk_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  910. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.mkDir expects a string path");
  911. const path_str = argv[0].data.string;
  912. const path = path_str.ptr[0..path_str.len];
  913. var mode: u32 = 0o700;
  914. if (argc >= 2 and argv[1].type == .hl_number) mode = @intFromFloat(argv[1].data.number);
  915. const resolved = resolvePath(path) orelse return api.makeError("fs.mkDir: out of memory");
  916. defer allocator.free(resolved);
  917. const errno = mkdirRecursive(resolved, mode);
  918. if (errno != 0) return makeWriteError("fs.mkDir", path, errno);
  919. return api.makeBool(true);
  920. }
  921. const write_usage = "fs.writeFile expects (String path, String or Bytes contents, Number mode?)";
  922. export fn hl_fs_write_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  923. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  924. return api.makeError(write_usage);
  925. }
  926. const path_str = argv[0].data.string;
  927. const body_str = argv[1].data.string;
  928. return writeWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  929. }
  930. /// hl_fs_write_file_hex(path, hex, mode?) — writeFile with a Bytes (ticket
  931. /// #88): a Bytes crosses the plugin boundary as its hex text (the ABI has no
  932. /// Bytes, as hl:proc's write_hex says), is decoded here and written raw.
  933. export fn hl_fs_write_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  934. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  935. return api.makeError(write_usage);
  936. }
  937. const path_str = argv[0].data.string;
  938. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  939. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.writeFile: out of memory");
  940. defer allocator.free(raw);
  941. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.writeFile: not a Bytes");
  942. return writeWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  943. }
  944. fn modeArg(argc: u32, argv: [*]const HlValue) u32 {
  945. if (argc >= 3 and argv[2].type == .hl_number) return @intFromFloat(argv[2].data.number);
  946. return 0o600;
  947. }
  948. fn writeWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  949. const resolved = resolvePath(path) orelse return api.makeError("fs.writeFile: out of memory");
  950. defer allocator.free(resolved);
  951. // The temp name is a SIBLING (see the block comment): rename(2) is only
  952. // atomic within one filesystem, and /tmp is routinely a different one.
  953. // The pid keeps two processes writing the same path off each other's temp
  954. // file; the rename itself settles who wins the target.
  955. const pid = linux.getpid();
  956. const tmp = std.fmt.allocPrintSentinel(allocator, "{s}.hltmp{d}", .{ resolved, pid }, 0) catch
  957. return api.makeError("fs.writeFile: out of memory");
  958. defer allocator.free(tmp);
  959. const rc = linuxOpenRc(tmp.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, mode);
  960. if (rc < 0) return makeWriteError("fs.writeFile", path, @intCast(-rc));
  961. const fd: i32 = @intCast(rc);
  962. var wrote: usize = 0;
  963. while (wrote < body.len) {
  964. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  965. if (n <= 0) {
  966. _ = linux.close(fd);
  967. _ = linux.unlink(tmp.ptr);
  968. return makeWriteError("fs.writeFile", path, if (n < 0) @intCast(-n) else 5);
  969. }
  970. wrote += @intCast(n);
  971. }
  972. // fsync BEFORE the rename, or the rename can land while the bytes are
  973. // still only in the page cache — a power cut then leaves an EMPTY file
  974. // where a complete one used to be, which is worse than either outcome.
  975. _ = linux.fsync(fd);
  976. _ = linux.close(fd);
  977. // O_CREAT honours the mode only through the umask; say it outright so a
  978. // 0600 request is 0600 whatever the process umask happens to be.
  979. _ = linux.chmod(tmp.ptr, mode);
  980. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.writeFile: out of memory");
  981. defer allocator.free(path_z);
  982. const ren: isize = @bitCast(linux.rename(tmp.ptr, path_z.ptr));
  983. if (ren < 0) {
  984. _ = linux.unlink(tmp.ptr);
  985. return makeWriteError("fs.writeFile", path, @intCast(-ren));
  986. }
  987. return api.makeBool(true);
  988. }
  989. const append_usage = "fs.appendFile expects (String path, String or Bytes contents, Number mode?)";
  990. export fn hl_fs_append_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  991. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  992. return api.makeError(append_usage);
  993. }
  994. const path_str = argv[0].data.string;
  995. const body_str = argv[1].data.string;
  996. return appendWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  997. }
  998. /// hl_fs_append_file_hex(path, hex, mode?) — appendFile with a Bytes (ticket
  999. /// #88), the same hex-text crossing writeFile's hex sibling uses.
  1000. export fn hl_fs_append_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1001. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1002. return api.makeError(append_usage);
  1003. }
  1004. const path_str = argv[0].data.string;
  1005. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1006. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.appendFile: out of memory");
  1007. defer allocator.free(raw);
  1008. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.appendFile: not a Bytes");
  1009. return appendWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1010. }
  1011. /// APPEND, NOT ATOMIC BY RENAME (writeFile's block comment above): an append
  1012. /// MUTATES the file that is already there, so there is no whole "old" or
  1013. /// "new" version to swap in — O_APPEND gives a narrower guarantee instead.
  1014. /// The kernel positions a single write() at the file's CURRENT end and
  1015. /// performs it as one operation, so two processes each appending a line never
  1016. /// interleave their bytes mid-line and a reader never sees a torn append —
  1017. /// which is why this is ONE write() of the whole body where writeFile's is
  1018. /// (short-write retries aside). The file is created at `mode` (default 0600,
  1019. /// same default as writeFile) if it is not there yet; O_APPEND on an existing
  1020. /// file leaves its mode untouched, same as any other open of it.
  1021. fn appendWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1022. const resolved = resolvePath(path) orelse return api.makeError("fs.appendFile: out of memory");
  1023. defer allocator.free(resolved);
  1024. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.appendFile: out of memory");
  1025. defer allocator.free(path_z);
  1026. const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, mode);
  1027. if (rc < 0) return makeWriteError("fs.appendFile", path, @intCast(-rc));
  1028. const fd: i32 = @intCast(rc);
  1029. defer _ = linux.close(fd);
  1030. var wrote: usize = 0;
  1031. while (wrote < body.len) {
  1032. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1033. if (n <= 0) {
  1034. return makeWriteError("fs.appendFile", path, if (n < 0) @intCast(-n) else 5);
  1035. }
  1036. wrote += @intCast(n);
  1037. }
  1038. return api.makeBool(true);
  1039. }
  1040. export fn hl_fs_remove(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1041. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.remove expects a string path");
  1042. const path_str = argv[0].data.string;
  1043. const path = path_str.ptr[0..path_str.len];
  1044. const resolved = resolvePath(path) orelse return api.makeError("fs.remove: out of memory");
  1045. defer allocator.free(resolved);
  1046. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.remove: out of memory");
  1047. defer allocator.free(path_z);
  1048. var rc: isize = @bitCast(linux.unlink(path_z.ptr));
  1049. // an empty directory goes too (EISDIR): hybriel.hl's scratch directories
  1050. // (mission 326 rung 12), with no `rmdir` to shell out to
  1051. if (rc == -21) rc = @bitCast(linux.rmdir(path_z.ptr));
  1052. if (rc < 0) {
  1053. const errno: usize = @intCast(-rc);
  1054. // ENOENT is success: the caller asked for the path to be gone.
  1055. if (errno == 2) return api.makeBool(true);
  1056. return makeWriteError("fs.remove", path, errno);
  1057. }
  1058. return api.makeBool(true);
  1059. }

Branches

Latest commits

  • b37875ccident mission 012 part 3: real-Chrome fixes (brand 44 px, identity form width), e2e walk, report, logmre
  • f989c2ebident mission 012: stopgap reload after in-place sign-in/sign-out (until hybriel#193), gates wait for cold start, welcome end reloadsmre
  • 443291d4ident mission 012: /start on its own shell (no account), browser gate 152/0, reportmre
  • 021dd0fcident mission 012: browser gate waits cold start (IDENT_COLD_MS), header selectors, e2e checks; shell events from a page do not reach it (probe), current not marked, account-bar link 44 pxmre
  • 97f77b07ident mission 012 (WIP): onto the layouts theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ContentFirst, styles cut, check-theme gatemre
  • 8e4f435bpaths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • fa288f63ident mission 011: report wording (Intl zone names)mre
  • 961fae01ident mission 011: report, LOG, STATUSmre
  • 65348039ident#7: delivery gate — console check split at the gate's own server restart (49 checks)mre
  • dfa7b783ident#7: README (Delivery, env, gate, files, data), deploy.sh runs tests/delivery.mjsmre
  • ab6331f4ident#7: tests/delivery.mjs — fake clock gate: Vienna/New York/Tokyo/UTC 17:00, urgent, mail off, restart, DST days, zone changemre
  • 7869f57bident#7: delivery — the daily mail at 17:00 in the user's zone (digests table, once per local day, test clock IDENT_TEST_CLOCK), urgent mailed at once, push hookmre
  • 371ef1b5ident#7: lib/mail.hl sendNotificationMail (sink: <sink>.mail, one JSON line per mail)mre
  • 39749e0bident#7: time zones through hl:time — server checks isZone, an account without a known zone reads as UTC, allAccountsmre
  • 7a54fe72mission brief 011mre
  • a6a874cdident mission 010: vendor hybriel 0f396652 (plugins + compose cache volume/tmpfs + deploy URL wait + report)mre
  • 4e7cf78emission brief 010mre
  • e8b2b0f7docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 5fdbb6b2ident mission 009: report — scratch folder notemre
  • 74235815ident mission 009 (4/4): docs (README files map + same-output test, STATUS, LOG), report, tests/letcount.py + realdata-baseline/comparemre