gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/fs/fs.zig

66.5 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_create_file(path, text, mode?) / hl_fs_create_file_hex(path, hex, mode?)
  9. // hl_fs_append_file(path, text, mode?) / hl_fs_append_file_hex(path, hex, mode?)
  10. // hl_fs_list_dir(path) → streaming directory iterator
  11. const std = @import("std");
  12. const api = @import("plugin_api");
  13. const linux = std.os.linux;
  14. const HlValue = api.HlValue;
  15. const HlObject = api.HlObject;
  16. const HlField = api.HlField;
  17. const HlIterator = api.HlIterator;
  18. const HlString = api.HlString;
  19. // the plugins' allocator (plugin_api.zig)
  20. const allocator = api.allocator;
  21. // =========================================================================
  22. // Path resolution (mission 068)
  23. //
  24. // CONTRACT: relative paths passed to hl:fs resolve against the MAIN SCRIPT's
  25. // directory, not the process CWD — Hybriel path resolution is file-relative
  26. // everywhere (import, inherit, plugin discovery), and fs follows suit.
  27. // Absolute paths are used as-is. The runtime injects the script dir via the
  28. // optional plugin hook hl_fs_set_script_dir right after dlopen.
  29. // =========================================================================
  30. var script_dir: ?[]u8 = null;
  31. export fn hl_fs_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  32. if (script_dir) |old| allocator.free(old);
  33. script_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  34. }
  35. /// A compiled binary's unpacked `ship` files (mission 316): a relative path
  36. /// one of them answers resolves there; any other as it would without it.
  37. var ship_dir: ?[]u8 = null;
  38. export fn hl_fs_set_ship_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  39. if (ship_dir) |old| allocator.free(old);
  40. ship_dir = allocator.dupe(u8, ptr[0..len]) catch null;
  41. }
  42. /// THE READ TRACE (326 rung 12, the build cache): while a trace file is named
  43. /// — by hl:fs `traceReads(path)`, or by HL_FS_TRACE in the environment, which a build
  44. /// hands the programs it runs — every path this plugin reads, lists or probes
  45. /// is appended to it as one line, `r <path>`, `l <path>` or `e <path>`, the
  46. /// path as resolved (absolute when the process's was). A build records what it
  47. /// depends on this way; nothing else changes.
  48. var trace_path: ?[:0]u8 = null;
  49. var trace_env_read = false;
  50. export fn hl_fs_trace(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  51. trace_env_read = true;
  52. if (trace_path) |old| allocator.free(old);
  53. trace_path = null;
  54. if (argc >= 1 and argv[0].type == .hl_string) {
  55. const p = argv[0].data.string.ptr[0..argv[0].data.string.len];
  56. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  57. }
  58. return api.makeNull();
  59. }
  60. fn traceAccess(kind: u8, resolved: []const u8) void {
  61. if (!trace_env_read) {
  62. trace_env_read = true;
  63. if (std.c.getenv("HL_FS_TRACE")) |e| {
  64. const p = std.mem.span(e);
  65. if (p.len > 0) trace_path = allocator.dupeZ(u8, p) catch null;
  66. }
  67. }
  68. const tp = trace_path orelse return;
  69. var cwd_buf: [4096]u8 = undefined;
  70. const line = if (resolved.len > 0 and resolved[0] == '/')
  71. std.fmt.allocPrint(allocator, "{c} {s}\n", .{ kind, resolved }) catch return
  72. else blk: {
  73. const rc: isize = @bitCast(linux.getcwd(&cwd_buf, cwd_buf.len));
  74. if (rc <= 0) return;
  75. const cwd = std.mem.sliceTo(&cwd_buf, 0);
  76. break :blk std.fmt.allocPrint(allocator, "{c} {s}/{s}\n", .{ kind, cwd, resolved }) catch return;
  77. };
  78. defer allocator.free(line);
  79. const rc = linuxOpenRc(tp, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, 0o600);
  80. if (rc < 0) return;
  81. const fd: i32 = @intCast(rc);
  82. defer _ = linux.close(fd);
  83. _ = linux.write(fd, line.ptr, line.len);
  84. }
  85. /// hl_fs_digest(path) — the SHA-256 of a file's bytes as 64 hex digits, or
  86. /// null when it cannot be read; hl_fs_digest_text(text) — of a text's. The
  87. /// build cache's content keys (326 rung 12): hashed here, in the plugin, so
  88. /// every engine has them and nothing crosses as a value but the answer.
  89. export fn hl_fs_digest(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  90. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digest expects a string path");
  91. const path_str = argv[0].data.string;
  92. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  93. defer allocator.free(resolved);
  94. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  95. defer allocator.free(path_z);
  96. const rc = linuxOpenRc(path_z, .{}, 0);
  97. if (rc < 0) return api.makeNull();
  98. const fd: i32 = @intCast(rc);
  99. defer _ = linux.close(fd);
  100. var h = std.crypto.hash.sha2.Sha256.init(.{});
  101. var buf: [65536]u8 = undefined;
  102. while (true) {
  103. const n: isize = @bitCast(linux.read(fd, &buf, buf.len));
  104. if (n == 0) break;
  105. if (n < 0) {
  106. if (@as(usize, @intCast(-n)) == @intFromEnum(linux.E.INTR)) continue;
  107. return api.makeNull();
  108. }
  109. h.update(buf[0..@intCast(n)]);
  110. }
  111. return hexDigest(&h);
  112. }
  113. export fn hl_fs_digest_text(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  114. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.digestText expects a string");
  115. const t = argv[0].data.string;
  116. var h = std.crypto.hash.sha2.Sha256.init(.{});
  117. h.update(t.ptr[0..t.len]);
  118. return hexDigest(&h);
  119. }
  120. fn hexDigest(h: *std.crypto.hash.sha2.Sha256) HlValue {
  121. var d: [32]u8 = undefined;
  122. h.final(&d);
  123. const out = allocator.alloc(u8, 64) catch return api.makeNull();
  124. const hex = "0123456789abcdef";
  125. for (d, 0..) |b, i| {
  126. out[i * 2] = hex[b >> 4];
  127. out[i * 2 + 1] = hex[b & 15];
  128. }
  129. return api.makeString(out);
  130. }
  131. /// Resolve a (possibly relative) path against the script dir. Returned slice
  132. /// is allocated with the plugin allocator; caller frees.
  133. fn resolvePath(path: []const u8) ?[]u8 {
  134. if (path.len == 0) return allocator.dupe(u8, path) catch null;
  135. if (path[0] == '/') return allocator.dupe(u8, path) catch null;
  136. if (ship_dir) |sd| {
  137. if (std.fmt.allocPrintSentinel(allocator, "{s}/{s}", .{ sd, path }, 0)) |shipped| {
  138. defer allocator.free(shipped);
  139. if (std.c.access(shipped.ptr, 0) == 0) return allocator.dupe(u8, shipped) catch null;
  140. } else |_| {}
  141. }
  142. if (script_dir) |sd| {
  143. return std.fmt.allocPrint(allocator, "{s}/{s}", .{ sd, path }) catch null;
  144. }
  145. return allocator.dupe(u8, path) catch null;
  146. }
  147. // =========================================================================
  148. // Error values (mission 068): open failures are LOUD — api.makeError with
  149. // the operation, the path as the caller wrote it, and the OS reason. The
  150. // runtime turns a top-level error value into a located runtime error.
  151. // =========================================================================
  152. fn errnoText(errno: usize) []const u8 {
  153. return switch (errno) {
  154. 2 => "no such file or directory",
  155. 13 => "permission denied",
  156. 20 => "not a directory",
  157. 21 => "is a directory",
  158. 1 => "operation not permitted",
  159. 17 => "file exists",
  160. 23 => "too many open files in the system",
  161. 24 => "too many open files",
  162. 28 => "no space left on device",
  163. 30 => "read-only file system",
  164. 36 => "file name too long",
  165. 40 => "too many levels of symbolic links",
  166. else => "I/O error",
  167. };
  168. }
  169. /// What to do about it, for the two descriptor-limit errors (fd403): a docker soft limit of
  170. /// 1024 turned a boot into an unexplained "I/O error (errno 24)".
  171. fn errnoHint(errno: usize) []const u8 {
  172. return switch (errno) {
  173. 23, 24 => "raise the open-file limit (ulimit -n) or close handles",
  174. else => "relative paths resolve against the script's directory",
  175. };
  176. }
  177. fn errDeinit(val: *api.HlValue) callconv(.c) void {
  178. if (val.type == .hl_error) {
  179. const s = val.data.string;
  180. allocator.free(@constCast(s.ptr[0..s.len]));
  181. }
  182. }
  183. fn makeOpenError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  184. const msg = std.fmt.allocPrint(allocator, "{s}: cannot open '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catch
  185. return api.makeError("fs: cannot open file");
  186. var v = api.makeError(msg);
  187. v.deinit_fn = &errDeinit;
  188. return v;
  189. }
  190. fn makeReadError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  191. const msg = std.fmt.allocPrint(allocator, "{s}: cannot read '{s}' — {s} (errno {d})", .{ op, path, errnoText(errno), errno }) catch
  192. return api.makeError("fs: cannot read file");
  193. var v = api.makeError(msg);
  194. v.deinit_fn = &errDeinit;
  195. return v;
  196. }
  197. // =========================================================================
  198. // hl_fs_file — file descriptor with metadata + line iterator
  199. // =========================================================================
  200. const FileIterState = struct {
  201. fd: i32,
  202. allocated_strings: std.array_list.Managed([]u8),
  203. done: bool,
  204. buf: [4096]u8,
  205. buf_pos: usize,
  206. buf_len: usize,
  207. };
  208. export fn hl_fs_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  209. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.file expects a string path");
  210. const path_str = argv[0].data.string;
  211. const path = path_str.ptr[0..path_str.len];
  212. // Resolve relative paths against the script dir; keep the caller's path
  213. // for the descriptor's name/path fields.
  214. const resolved = resolvePath(path) orelse return api.makeNull();
  215. defer allocator.free(resolved);
  216. traceAccess('r', resolved);
  217. // We need a null-terminated path for the OS
  218. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  219. defer allocator.free(path_z);
  220. // Open file
  221. const rc = linuxOpenRc(path_z, .{}, 0);
  222. if (rc < 0) return makeOpenError("fs.file", path, @intCast(-rc));
  223. const fd: i32 = @intCast(rc);
  224. // Stat for size, chmod, uid, gid
  225. var size: f64 = 0;
  226. var chmod: f64 = 0;
  227. var uid: f64 = 0;
  228. var gid: f64 = 0;
  229. var stat_ok = false;
  230. var statx_buf: std.os.linux.Statx = undefined;
  231. const statx_rc = std.os.linux.statx(
  232. fd,
  233. "",
  234. std.os.linux.AT.EMPTY_PATH,
  235. std.os.linux.STATX.BASIC_STATS,
  236. &statx_buf,
  237. );
  238. if (statx_rc == 0) {
  239. size = @floatFromInt(statx_buf.size);
  240. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  241. uid = @floatFromInt(statx_buf.uid);
  242. gid = @floatFromInt(statx_buf.gid);
  243. stat_ok = true;
  244. }
  245. // Extract name from path
  246. const name = if (std.mem.lastIndexOfScalar(u8, path, '/')) |idx|
  247. path[idx + 1 ..]
  248. else
  249. path;
  250. // Mime from extension
  251. const mime = mimeFromName(name);
  252. // Build fields: name, path, size, mime, chmod, user, group = 7 fields
  253. const field_count: usize = 7;
  254. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  255. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name) };
  256. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(path) };
  257. fields[2] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  258. fields[3] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  259. fields[4] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  260. if (stat_ok) {
  261. fields[5] = .{ .key = hlStr("user"), .value = api.makeNumber(uid) };
  262. fields[6] = .{ .key = hlStr("group"), .value = api.makeNumber(gid) };
  263. } else {
  264. fields[5] = .{ .key = hlStr("user"), .value = api.makeNull() };
  265. fields[6] = .{ .key = hlStr("group"), .value = api.makeNull() };
  266. }
  267. const obj = allocator.create(HlObject) catch return api.makeNull();
  268. obj.* = .{
  269. .fields = fields.ptr,
  270. .field_count = field_count,
  271. .deinit_fn = &fileObjDeinit,
  272. };
  273. // Create line iterator
  274. const iter_state = allocator.create(FileIterState) catch return api.makeNull();
  275. iter_state.* = .{
  276. .fd = fd,
  277. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  278. .done = false,
  279. .buf = undefined,
  280. .buf_pos = 0,
  281. .buf_len = 0,
  282. };
  283. const iter = allocator.create(HlIterator) catch return api.makeNull();
  284. iter.* = .{
  285. .context = @ptrCast(iter_state),
  286. .next_fn = &fileIterNext,
  287. .deinit_fn = &fileIterDeinit,
  288. };
  289. // Return object — runtime will see it has both object fields and an iterator
  290. // We pack the iterator pointer into the object by adding one more field
  291. const full_fields = allocator.alloc(HlField, field_count + 1) catch return api.makeNull();
  292. @memcpy(full_fields[0..field_count], fields);
  293. full_fields[field_count] = .{ .key = hlStr("__iter"), .value = api.makeIterator(iter) };
  294. // Free the original fields, use full_fields
  295. allocator.free(fields);
  296. obj.fields = full_fields.ptr;
  297. obj.field_count = field_count + 1;
  298. return api.makeObject(obj);
  299. }
  300. fn fileIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  301. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  302. if (state.done) return api.makeNull();
  303. var line_buf = std.array_list.Managed(u8).init(allocator);
  304. while (true) {
  305. if (state.buf_pos < state.buf_len) {
  306. const remaining = state.buf[state.buf_pos..state.buf_len];
  307. if (std.mem.indexOfScalar(u8, remaining, '\n')) |nl_pos| {
  308. line_buf.appendSlice(remaining[0..nl_pos]) catch return api.makeNull();
  309. state.buf_pos += nl_pos + 1;
  310. break;
  311. } else {
  312. line_buf.appendSlice(remaining) catch return api.makeNull();
  313. state.buf_pos = 0;
  314. state.buf_len = 0;
  315. }
  316. }
  317. // Read from file using posix read
  318. const n = linuxRead(state.fd, &state.buf) orelse {
  319. state.done = true;
  320. break;
  321. };
  322. if (n == 0) {
  323. state.done = true;
  324. break;
  325. }
  326. state.buf_pos = 0;
  327. state.buf_len = n;
  328. }
  329. if (state.done) closeIterFd(state);
  330. if (line_buf.items.len == 0 and state.done) {
  331. line_buf.deinit();
  332. return api.makeNull();
  333. }
  334. const line = line_buf.toOwnedSlice() catch return api.makeNull();
  335. state.allocated_strings.append(line) catch return api.makeNull();
  336. return api.makeString(line);
  337. }
  338. /// An iterator that ran to its end gives its fd back at once (fd403: the compiler's
  339. /// directory walks held one fd per listDir until the GC finalized them: > 1024 at boot).
  340. /// The fd is -1 afterwards; deinit closes only a still-open one.
  341. fn closeIterFd(state: anytype) void {
  342. if (state.fd >= 0) {
  343. _ = linux.close(state.fd);
  344. state.fd = -1;
  345. }
  346. }
  347. fn fileIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  348. const state: *FileIterState = @ptrCast(@alignCast(ctx orelse return));
  349. closeIterFd(state);
  350. for (state.allocated_strings.items) |s| {
  351. allocator.free(s);
  352. }
  353. state.allocated_strings.deinit();
  354. allocator.destroy(state);
  355. }
  356. fn fileObjDeinit(obj: *HlObject) callconv(.c) void {
  357. const fields = obj.fields[0..obj.field_count];
  358. // Check for iterator field and clean it up (only if not already nulled out by runtime)
  359. for (fields) |field| {
  360. if (field.value.type == .hl_iterator) {
  361. const iter = field.value.data.iterator;
  362. if (iter.deinit_fn) |deinit_fn| {
  363. deinit_fn(iter.context);
  364. }
  365. allocator.destroy(iter);
  366. }
  367. }
  368. allocator.free(fields);
  369. allocator.destroy(obj);
  370. }
  371. // =========================================================================
  372. // hl_fs_read_file — read entire file as string
  373. // =========================================================================
  374. fn readFileDeinit(val: *HlValue) callconv(.c) void {
  375. if (val.type == .hl_string) {
  376. const s = val.data.string;
  377. allocator.free(@constCast(s.ptr[0..s.len]));
  378. }
  379. }
  380. /// exists(path) → Boolean (mission 077, 074 GAP 8). The ONLY hl:fs entry point
  381. /// that never errors: it answers a question, and "no" is an answer, not a
  382. /// failure. Same script-relative resolution as everything else. Without it the
  383. /// only way to test a path was to open it and survive the error — which is why
  384. /// the retired live_server used to index `static/` blind instead of probing it.
  385. export fn hl_fs_exists(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  386. if (argc < 1 or argv[0].type != .hl_string) return api.makeBool(false);
  387. const path_str = argv[0].data.string;
  388. const path = path_str.ptr[0..path_str.len];
  389. const resolved = resolvePath(path) orelse return api.makeBool(false);
  390. defer allocator.free(resolved);
  391. traceAccess('e', resolved);
  392. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeBool(false);
  393. defer allocator.free(path_z);
  394. // statx, not open: a directory, a symlink target, a device — anything the
  395. // OS can name — counts, and nothing is opened (no fd, no side effect).
  396. var statx_buf: std.os.linux.Statx = undefined;
  397. const rc = std.os.linux.statx(
  398. std.os.linux.AT.FDCWD,
  399. path_z,
  400. 0,
  401. std.os.linux.STATX.BASIC_STATS,
  402. &statx_buf,
  403. );
  404. return api.makeBool(@as(isize, @bitCast(rc)) == 0);
  405. }
  406. /// changeTime(path) → the path's last status change (ctime, which no write can set
  407. /// back) as milliseconds since the epoch, or null when it is not there (#195). The
  408. /// build cache asks it of everything a build read: an input changed after the build
  409. /// began (a file edited, a checkout, a file made or removed in a listed directory)
  410. /// makes what the build saw differ from what the record would say. Not traced.
  411. export fn hl_fs_change_time(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  412. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  413. const path_str = argv[0].data.string;
  414. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  415. defer allocator.free(resolved);
  416. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  417. defer allocator.free(path_z);
  418. var statx_buf: std.os.linux.Statx = undefined;
  419. const rc = std.os.linux.statx(
  420. std.os.linux.AT.FDCWD,
  421. path_z,
  422. 0,
  423. std.os.linux.STATX.BASIC_STATS,
  424. &statx_buf,
  425. );
  426. if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();
  427. const sec: f64 = @floatFromInt(statx_buf.ctime.sec);
  428. const nsec: f64 = @floatFromInt(statx_buf.ctime.nsec);
  429. return api.makeNumber(sec * 1000.0 + nsec / 1000000.0);
  430. }
  431. /// stat(path) → { size, mtime, ctime, type } without opening or reading the file, or
  432. /// null when the path is not there (the way changeTime treats a missing path). `size`
  433. /// is in bytes; `mtime` and `ctime` are milliseconds since the epoch, the same form
  434. /// changeTime answers in; `type` is "file", "directory" or "other" (the words listDir
  435. /// uses). Symlinks are followed, so the answer describes what the link points at.
  436. /// Not traced (like changeTime, it reads no content).
  437. export fn hl_fs_stat(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  438. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.stat expects a string path");
  439. const path_str = argv[0].data.string;
  440. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  441. defer allocator.free(resolved);
  442. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  443. defer allocator.free(path_z);
  444. var sx: std.os.linux.Statx = undefined;
  445. const rc = std.os.linux.statx(std.os.linux.AT.FDCWD, path_z, 0, std.os.linux.STATX.BASIC_STATS, &sx);
  446. if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();
  447. const fmt = sx.mode & std.os.linux.S.IFMT;
  448. const kind: []const u8 = if (fmt == std.os.linux.S.IFREG) "file" else if (fmt == std.os.linux.S.IFDIR) "directory" else "other";
  449. const m_ms: f64 = @as(f64, @floatFromInt(sx.mtime.sec)) * 1000.0 + @as(f64, @floatFromInt(sx.mtime.nsec)) / 1000000.0;
  450. const c_ms: f64 = @as(f64, @floatFromInt(sx.ctime.sec)) * 1000.0 + @as(f64, @floatFromInt(sx.ctime.nsec)) / 1000000.0;
  451. const field_count: usize = 4;
  452. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  453. fields[0] = .{ .key = hlStr("size"), .value = api.makeNumber(@floatFromInt(sx.size)) };
  454. fields[1] = .{ .key = hlStr("mtime"), .value = api.makeNumber(m_ms) };
  455. fields[2] = .{ .key = hlStr("ctime"), .value = api.makeNumber(c_ms) };
  456. fields[3] = .{ .key = hlStr("type"), .value = api.makeString(kind) };
  457. const obj = allocator.create(HlObject) catch return api.makeNull();
  458. obj.* = .{ .fields = fields.ptr, .field_count = field_count, .deinit_fn = &entryObjDeinit };
  459. return api.makeObject(obj);
  460. }
  461. /// readRange(path, offset, length) → at most `length` bytes starting at byte `offset`,
  462. /// as a string of raw bytes (the Hybriel side wraps it in Bytes). Only that range is
  463. /// read (pread), never the rest of the file. An offset at or past the end gives an empty
  464. /// result; a length running past the end gives the shorter rest. Offset and length must
  465. /// be whole numbers, zero or more; anything else is an error. A missing file is an error
  466. /// like readFile's.
  467. export fn hl_fs_read_range(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  468. if (argc < 3 or argv[0].type != .hl_string) return api.makeError("fs.readBytes expects a string path, an offset and a length");
  469. if (argv[1].type != .hl_number or argv[2].type != .hl_number) return api.makeError("fs.readBytes: offset and length must both be numbers (or both left out to read the whole file)");
  470. const off_f: f64 = argv[1].data.number;
  471. const len_f: f64 = argv[2].data.number;
  472. if (!(off_f >= 0) or !(len_f >= 0) or off_f != @floor(off_f) or len_f != @floor(len_f) or off_f > 9.0e15 or len_f > 9.0e15)
  473. return api.makeError("fs.readBytes: offset and length must be whole numbers, zero or more");
  474. const offset: u64 = @intFromFloat(off_f);
  475. const want: u64 = @intFromFloat(len_f);
  476. const path_str = argv[0].data.string;
  477. const path = path_str.ptr[0..path_str.len];
  478. const resolved = resolvePath(path) orelse return api.makeNull();
  479. defer allocator.free(resolved);
  480. traceAccess('r', resolved);
  481. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  482. defer allocator.free(path_z);
  483. const rc = linuxOpenRc(path_z, .{}, 0);
  484. if (rc < 0) return makeOpenError("fs.readBytes", path, @intCast(-rc));
  485. const fd: i32 = @intCast(rc);
  486. defer _ = linux.close(fd);
  487. // Never allocate more than the file can still give: a huge length on a small file is cheap.
  488. var cap: u64 = want;
  489. var sx: std.os.linux.Statx = undefined;
  490. const src = std.os.linux.statx(fd, "", std.os.linux.AT.EMPTY_PATH, std.os.linux.STATX.BASIC_STATS, &sx);
  491. if (@as(isize, @bitCast(src)) == 0 and (sx.mode & std.os.linux.S.IFMT) == std.os.linux.S.IFREG) {
  492. cap = if (offset >= sx.size) 0 else @min(want, sx.size - offset);
  493. }
  494. var content = std.array_list.Managed(u8).init(allocator);
  495. defer content.deinit();
  496. var buf: [65536]u8 = undefined;
  497. var got: u64 = 0;
  498. while (got < cap) {
  499. const chunk: usize = @intCast(@min(@as(u64, buf.len), cap - got));
  500. const n_read: isize = @bitCast(linux.pread(fd, &buf, chunk, @intCast(offset + got)));
  501. if (n_read == 0) break;
  502. if (n_read < 0) {
  503. const errno: usize = @intCast(-n_read);
  504. if (errno == @intFromEnum(linux.E.INTR)) continue;
  505. return makeReadError("fs.readBytes", path, errno);
  506. }
  507. content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readBytes: out of memory reading the range");
  508. got += @intCast(n_read);
  509. }
  510. const result_slice = content.toOwnedSlice() catch return api.makeNull();
  511. var result = api.makeString(result_slice);
  512. result.deinit_fn = &readFileDeinit;
  513. return result;
  514. }
  515. export fn hl_fs_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  516. return readWhole(argc, argv, false);
  517. }
  518. /// tryReadFile(path) → the file as a string, or null when the path is not
  519. /// there (ENOENT/ENOTDIR). Any other failure is an error as in readFile. For a
  520. /// file another process may delete between a probe and the read (a shared
  521. /// cache): the vanishing is an answer, not a fault.
  522. export fn hl_fs_try_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  523. return readWhole(argc, argv, true);
  524. }
  525. fn readWhole(argc: u32, argv: [*]const HlValue, absent_is_null: bool) HlValue {
  526. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.readFile expects a string path");
  527. const path_str = argv[0].data.string;
  528. const path = path_str.ptr[0..path_str.len];
  529. const resolved = resolvePath(path) orelse return api.makeNull();
  530. defer allocator.free(resolved);
  531. traceAccess('r', resolved);
  532. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  533. defer allocator.free(path_z);
  534. const rc = linuxOpenRc(path_z, .{}, 0);
  535. if (rc < 0) {
  536. const en: usize = @intCast(-rc);
  537. if (absent_is_null and (en == @intFromEnum(linux.E.NOENT) or en == @intFromEnum(linux.E.NOTDIR))) return api.makeNull();
  538. return makeOpenError("fs.readFile", path, en);
  539. }
  540. const fd: i32 = @intCast(rc);
  541. defer _ = linux.close(fd);
  542. // The whole file: no size cap (a 10 MiB cap once truncated silently, ticket #112).
  543. // A failed read is an error naming the path, never a short string.
  544. var content = std.array_list.Managed(u8).init(allocator);
  545. defer content.deinit();
  546. var buf: [65536]u8 = undefined;
  547. while (true) {
  548. const n_read: isize = @bitCast(linux.read(fd, &buf, buf.len));
  549. if (n_read == 0) break;
  550. if (n_read < 0) {
  551. const errno: usize = @intCast(-n_read);
  552. if (errno == @intFromEnum(linux.E.INTR)) continue;
  553. return makeReadError("fs.readFile", path, errno);
  554. }
  555. content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readFile: out of memory reading the file");
  556. }
  557. const result_slice = content.toOwnedSlice() catch return api.makeNull();
  558. var result = api.makeString(result_slice);
  559. result.deinit_fn = &readFileDeinit;
  560. return result;
  561. }
  562. // =========================================================================
  563. // hl_fs_list_dir — streaming directory iterator with metadata
  564. // =========================================================================
  565. const DirIterState = struct {
  566. base_path: []const u8,
  567. // Snapshot at call time, in filesystem order: type byte, name, NUL.
  568. // Each syscall becomes one compact chunk, released as it is consumed.
  569. chunks: std.array_list.Managed([]u8),
  570. chunk_index: usize = 0,
  571. chunk_pos: usize = 0,
  572. dir_resolved: []u8,
  573. done: bool = false,
  574. };
  575. export fn hl_fs_list_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  576. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.listDir expects a string path");
  577. const path_str = argv[0].data.string;
  578. const path = path_str.ptr[0..path_str.len];
  579. const resolved = resolvePath(path) orelse return api.makeNull();
  580. defer allocator.free(resolved);
  581. traceAccess('l', resolved);
  582. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  583. defer allocator.free(path_z);
  584. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  585. if (rc < 0) return makeOpenError("fs.listDir", path, @intCast(-rc));
  586. const fd: i32 = @intCast(rc);
  587. const path_copy = allocator.dupe(u8, path) catch {
  588. _ = linux.close(fd);
  589. return api.makeNull();
  590. };
  591. const state = allocator.create(DirIterState) catch {
  592. allocator.free(path_copy);
  593. _ = linux.close(fd);
  594. return api.makeNull();
  595. };
  596. state.* = .{
  597. .base_path = path_copy,
  598. .chunks = std.array_list.Managed([]u8).init(allocator),
  599. .dir_resolved = allocator.dupe(u8, resolved) catch {
  600. allocator.free(path_copy);
  601. allocator.destroy(state);
  602. _ = linux.close(fd);
  603. return api.makeNull();
  604. },
  605. };
  606. var chunk: [4096]u8 align(8) = undefined;
  607. var compact: [4096]u8 = undefined;
  608. while (true) {
  609. const got = std.os.linux.getdents64(fd, &chunk, chunk.len);
  610. if (@as(isize, @bitCast(got)) <= 0) break;
  611. var pos: usize = 0;
  612. var used: usize = 0;
  613. while (pos < got) {
  614. const entry: *align(1) const linux.dirent64 = @ptrCast(&chunk[pos]);
  615. const reclen = entry.reclen;
  616. if (reclen < 20 or reclen > got - pos) break;
  617. const name = std.mem.sliceTo(chunk[pos + 19 .. pos + reclen], 0);
  618. pos += reclen;
  619. if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
  620. compact[used] = entry.type;
  621. @memcpy(compact[used + 1 ..][0..name.len], name);
  622. compact[used + 1 + name.len] = 0;
  623. used += name.len + 2;
  624. }
  625. if (used == 0) continue;
  626. const copy = allocator.dupe(u8, compact[0..used]) catch {
  627. _ = linux.close(fd);
  628. dirIterDeinit(state);
  629. return api.makeNull();
  630. };
  631. state.chunks.append(copy) catch {
  632. allocator.free(copy);
  633. _ = linux.close(fd);
  634. dirIterDeinit(state);
  635. return api.makeNull();
  636. };
  637. }
  638. _ = linux.close(fd);
  639. const iter = allocator.create(HlIterator) catch {
  640. dirIterDeinit(state);
  641. return api.makeNull();
  642. };
  643. iter.* = .{
  644. .context = @ptrCast(state),
  645. .next_fn = &dirIterNext,
  646. .deinit_fn = &dirIterDeinit,
  647. .close_fn = &dirIterClose,
  648. };
  649. return api.makeIterator(iter);
  650. }
  651. fn dirIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  652. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  653. if (state.done) return api.makeNull();
  654. while (true) {
  655. while (state.chunk_index < state.chunks.items.len and
  656. state.chunk_pos == state.chunks.items[state.chunk_index].len)
  657. {
  658. allocator.free(state.chunks.items[state.chunk_index]);
  659. state.chunk_index += 1;
  660. state.chunk_pos = 0;
  661. }
  662. if (state.chunk_index == state.chunks.items.len) {
  663. dirIterClose(ctx);
  664. return api.makeNull();
  665. }
  666. const chunk = state.chunks.items[state.chunk_index];
  667. const kind = chunk[state.chunk_pos];
  668. const name = std.mem.sliceTo(chunk[state.chunk_pos + 1 ..], 0);
  669. state.chunk_pos += name.len + 2;
  670. const name_copy = allocator.dupe(u8, name) catch return api.makeNull();
  671. const full_path = std.fmt.allocPrint(allocator, "{s}/{s}", .{ state.base_path, name }) catch {
  672. allocator.free(name_copy);
  673. return api.makeNull();
  674. };
  675. // Entry type from d_type
  676. const kind_str: []const u8 = switch (kind) {
  677. std.os.linux.DT.DIR => "directory",
  678. std.os.linux.DT.REG => "file",
  679. std.os.linux.DT.LNK => "symlink",
  680. else => "other",
  681. };
  682. // Stat for size, chmod, uid, gid
  683. var size: f64 = 0;
  684. var chmod: f64 = 0;
  685. var e_uid: f64 = 0;
  686. var e_gid: f64 = 0;
  687. // null-terminate name for statx
  688. var name_z_buf: [256]u8 = undefined;
  689. if (name.len < name_z_buf.len) {
  690. @memcpy(name_z_buf[0..name.len], name);
  691. name_z_buf[name.len] = 0;
  692. var statx_buf: std.os.linux.Statx = undefined;
  693. var stat_path: [4096]u8 = undefined;
  694. const stat_z = std.fmt.bufPrintZ(&stat_path, "{s}/{s}", .{ state.dir_resolved, name }) catch null;
  695. const src = if (stat_z) |sz| std.os.linux.statx(
  696. std.os.linux.AT.FDCWD,
  697. sz.ptr,
  698. 0,
  699. std.os.linux.STATX.BASIC_STATS,
  700. &statx_buf,
  701. ) else @as(usize, 1);
  702. if (src == 0) {
  703. size = @floatFromInt(statx_buf.size);
  704. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  705. e_uid = @floatFromInt(statx_buf.uid);
  706. e_gid = @floatFromInt(statx_buf.gid);
  707. }
  708. }
  709. const mime = mimeFromName(name_copy);
  710. // Build object: name, path, type, size, mime, chmod, user, group
  711. // The runtime's hlObjectToValue will call dirEntryObjDeinit after conversion,
  712. // so these objects are freed immediately upon consumption.
  713. const field_count: usize = 8;
  714. const fields = allocator.alloc(HlField, field_count) catch {
  715. allocator.free(name_copy);
  716. allocator.free(full_path);
  717. return api.makeNull();
  718. };
  719. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  720. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(full_path) };
  721. fields[2] = .{ .key = hlStr("type"), .value = api.makeString(kind_str) };
  722. fields[3] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  723. fields[4] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  724. fields[5] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  725. fields[6] = .{ .key = hlStr("user"), .value = api.makeNumber(e_uid) };
  726. fields[7] = .{ .key = hlStr("group"), .value = api.makeNumber(e_gid) };
  727. const obj = allocator.create(HlObject) catch {
  728. allocator.free(fields);
  729. allocator.free(name_copy);
  730. allocator.free(full_path);
  731. return api.makeNull();
  732. };
  733. obj.* = .{
  734. .fields = fields.ptr,
  735. .field_count = field_count,
  736. .deinit_fn = &dirEntryObjDeinit,
  737. };
  738. return api.makeObject(obj);
  739. }
  740. }
  741. fn dirEntryObjDeinit(obj: *HlObject) callconv(.c) void {
  742. // hl_pvResultObject has copied every field; the iterator owns neither string.
  743. for (obj.fields[0..2]) |field| {
  744. const str = field.value.data.string;
  745. allocator.free(@constCast(str.ptr[0..str.len]));
  746. }
  747. entryObjDeinit(obj);
  748. }
  749. fn entryObjDeinit(obj: *HlObject) callconv(.c) void {
  750. allocator.free(obj.fields[0..obj.field_count]);
  751. allocator.destroy(obj);
  752. }
  753. fn dirIterClose(ctx: ?*anyopaque) callconv(.c) void {
  754. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return));
  755. if (state.done) return;
  756. state.done = true;
  757. for (state.chunks.items[state.chunk_index..]) |chunk| allocator.free(chunk);
  758. state.chunks.deinit();
  759. allocator.free(state.dir_resolved);
  760. allocator.free(@constCast(state.base_path));
  761. }
  762. fn dirIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  763. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return));
  764. dirIterClose(ctx);
  765. allocator.destroy(state);
  766. }
  767. // =========================================================================
  768. // Helpers
  769. // =========================================================================
  770. /// Raw open: >= 0 is the fd, < 0 is -errno.
  771. fn linuxOpenRc(path_z: [*:0]const u8, flags: linux.O, mode: u32) isize {
  772. const rc = linux.open(path_z, flags, mode);
  773. return @bitCast(rc);
  774. }
  775. fn linuxRead(fd: i32, buf: []u8) ?usize {
  776. const rc = linux.read(fd, buf.ptr, buf.len);
  777. if (@as(isize, @bitCast(rc)) <= 0) return null;
  778. return rc;
  779. }
  780. fn hlStr(comptime s: []const u8) HlString {
  781. return .{ .ptr = s.ptr, .len = s.len };
  782. }
  783. fn mimeFromName(name: []const u8) []const u8 {
  784. const ext = if (std.mem.lastIndexOfScalar(u8, name, '.')) |dot|
  785. name[dot..]
  786. else
  787. return "application/octet-stream";
  788. if (std.mem.eql(u8, ext, ".txt")) return "text/plain";
  789. if (std.mem.eql(u8, ext, ".html") or std.mem.eql(u8, ext, ".htm")) return "text/html";
  790. if (std.mem.eql(u8, ext, ".css")) return "text/css";
  791. if (std.mem.eql(u8, ext, ".js")) return "text/javascript";
  792. if (std.mem.eql(u8, ext, ".json")) return "application/json";
  793. if (std.mem.eql(u8, ext, ".xml")) return "application/xml";
  794. if (std.mem.eql(u8, ext, ".png")) return "image/png";
  795. if (std.mem.eql(u8, ext, ".jpg") or std.mem.eql(u8, ext, ".jpeg")) return "image/jpeg";
  796. if (std.mem.eql(u8, ext, ".gif")) return "image/gif";
  797. if (std.mem.eql(u8, ext, ".svg")) return "image/svg+xml";
  798. if (std.mem.eql(u8, ext, ".pdf")) return "application/pdf";
  799. if (std.mem.eql(u8, ext, ".zip")) return "application/zip";
  800. if (std.mem.eql(u8, ext, ".gz")) return "application/gzip";
  801. if (std.mem.eql(u8, ext, ".mp3")) return "audio/mpeg";
  802. if (std.mem.eql(u8, ext, ".mp4")) return "video/mp4";
  803. if (std.mem.eql(u8, ext, ".wasm")) return "application/wasm";
  804. if (std.mem.eql(u8, ext, ".hl")) return "text/x-hybriel";
  805. if (std.mem.eql(u8, ext, ".md")) return "text/markdown";
  806. if (std.mem.eql(u8, ext, ".yml") or std.mem.eql(u8, ext, ".yaml")) return "text/yaml";
  807. if (std.mem.eql(u8, ext, ".toml")) return "application/toml";
  808. if (std.mem.eql(u8, ext, ".csv")) return "text/csv";
  809. if (std.mem.eql(u8, ext, ".ts")) return "text/typescript";
  810. if (std.mem.eql(u8, ext, ".c") or std.mem.eql(u8, ext, ".h")) return "text/x-c";
  811. if (std.mem.eql(u8, ext, ".zig")) return "text/x-zig";
  812. if (std.mem.eql(u8, ext, ".rs")) return "text/x-rust";
  813. if (std.mem.eql(u8, ext, ".py")) return "text/x-python";
  814. if (std.mem.eql(u8, ext, ".sh")) return "text/x-shellscript";
  815. if (std.mem.eql(u8, ext, ".sql")) return "application/sql";
  816. if (std.mem.eql(u8, ext, ".webp")) return "image/webp";
  817. if (std.mem.eql(u8, ext, ".ico")) return "image/x-icon";
  818. if (std.mem.eql(u8, ext, ".woff2")) return "font/woff2";
  819. if (std.mem.eql(u8, ext, ".woff")) return "font/woff";
  820. if (std.mem.eql(u8, ext, ".ttf")) return "font/ttf";
  821. return "application/octet-stream";
  822. }
  823. // ── fs.watch: an inotify LOOP SOURCE (the dev-reload bell) ───────────────────
  824. // `watch(path)` returns an event-loop source whose wake_fd combines inotify
  825. // readability and a bell for events already buffered by a read. Watches
  826. // the directory RECURSIVELY at registration (dot-dirs skipped); directories
  827. // created afterwards are picked up the next time the app is restarted, which
  828. // is the honest v1 for a dev tool.
  829. //
  830. // EXCLUSIONS (mission 266). `watch(path, exclude)` takes a second argument —
  831. // a path STRING or a LIST of them, the same either-shape the plugin surface
  832. // already uses in `hl_proc_spawn` — naming directories the descent must not
  833. // enter. One argument still means "watch everything": the argument is optional
  834. // and a null is the same as absent.
  835. //
  836. // This exists because a program that knows, at startup, about a directory it
  837. // will write to constantly (hl:web's session store is the first) had NO way to
  838. // say so. The only skip the walker possessed was "the name starts with a dot",
  839. // so the framework's advice was to RENAME the directory — a lecture standing
  840. // in for a fix. The dot-dir skip STAYS; `.git` is its reason and it is a good
  841. // one. This is a second, explicit reason to skip, not a replacement.
  842. const WatchState = struct {
  843. ifd: i32,
  844. wake_fd: i32 = -1, // epoll over ifd and bell_fd; readable while either is ready
  845. bell_fd: i32 = -1,
  846. buf: [4096]u8 align(4) = undefined,
  847. len: usize = 0,
  848. pos: usize = 0,
  849. };
  850. /// LEXICAL path normalisation — collapses `//` and resolves `.` / `..`
  851. /// without touching the filesystem. It must be lexical: an excluded directory
  852. /// need not exist yet at the moment the watch is armed (hl:web resolves its
  853. /// session dir before it creates it), and realpath(2) on a missing path fails.
  854. /// Both the watch root and every exclusion go through this, so the comparison
  855. /// below is between two paths written the same way.
  856. fn normalizePath(path: []const u8) ?[]u8 {
  857. const absolute = path.len > 0 and path[0] == '/';
  858. var parts = std.ArrayListUnmanaged([]const u8).empty;
  859. defer parts.deinit(allocator);
  860. var it = std.mem.tokenizeScalar(u8, path, '/');
  861. while (it.next()) |seg| {
  862. if (std.mem.eql(u8, seg, ".")) continue;
  863. if (std.mem.eql(u8, seg, "..")) {
  864. if (parts.items.len > 0 and !std.mem.eql(u8, parts.items[parts.items.len - 1], "..")) {
  865. _ = parts.pop();
  866. continue;
  867. }
  868. if (absolute) continue; // ".." above "/" is "/"
  869. }
  870. parts.append(allocator, seg) catch return null;
  871. }
  872. var out = std.ArrayListUnmanaged(u8).empty;
  873. defer out.deinit(allocator);
  874. for (parts.items, 0..) |seg, i| {
  875. if (absolute or i > 0) out.append(allocator, '/') catch return null;
  876. out.appendSlice(allocator, seg) catch return null;
  877. }
  878. if (out.items.len == 0) out.appendSlice(allocator, if (absolute) "/" else ".") catch return null;
  879. return allocator.dupe(u8, out.items) catch null;
  880. }
  881. /// Is `child` the directory `root`, or somewhere under it? Both must already
  882. /// be normalised. A bare `startsWith` would call `/a/sessions-old` a child of
  883. /// `/a/sessions`, which is the whole reason this is a function: the byte after
  884. /// the prefix has to BE a separator.
  885. fn pathIsInside(child: []const u8, root: []const u8) bool {
  886. if (root.len == 0) return false;
  887. if (std.mem.eql(u8, child, root)) return true;
  888. if (child.len <= root.len) return false;
  889. if (!std.mem.startsWith(u8, child, root)) return false;
  890. if (root[root.len - 1] == '/') return true; // root is "/" itself
  891. return child[root.len] == '/';
  892. }
  893. fn addWatchesRecursive(ifd: i32, dir_path: []const u8, depth: u32, excludes: []const []const u8) void {
  894. if (depth > 8) return;
  895. // The SECOND reason to skip a directory (mission 266). `dir_path` is
  896. // normalised: the root was normalised before the first call and every
  897. // child below is that root plus one plain name.
  898. for (excludes) |ex| if (pathIsInside(dir_path, ex)) return;
  899. const path_z = allocator.dupeZ(u8, dir_path) catch return;
  900. defer allocator.free(path_z);
  901. const mask: u32 = linux.IN.CLOSE_WRITE | linux.IN.CREATE | linux.IN.DELETE | linux.IN.MOVED_TO | linux.IN.MOVED_FROM;
  902. _ = linux.inotify_add_watch(ifd, path_z, mask);
  903. // The descent walks getdents64 directly, like hl_fs_list_dir does — this
  904. // plugin speaks raw syscalls throughout and never pulls in std.fs.
  905. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  906. if (rc < 0) return;
  907. const fd: i32 = @intCast(rc);
  908. defer _ = linux.close(fd);
  909. var dents: [4096]u8 align(8) = undefined;
  910. while (true) {
  911. const got = linux.getdents64(fd, &dents, dents.len);
  912. if (@as(isize, @bitCast(got)) <= 0) break;
  913. var pos: usize = 0;
  914. while (pos < got) {
  915. const entry: *align(1) linux.dirent64 = @ptrCast(&dents[pos]);
  916. pos += entry.reclen;
  917. if (entry.type != linux.DT.DIR) continue;
  918. const name_ptr: [*]const u8 = @ptrCast(&entry.name);
  919. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  920. const name = name_ptr[0..name_len];
  921. // "." and ".." would recurse forever; every other dot-dir is noise
  922. // for a dev watcher (.git alone would cost thousands of watches).
  923. if (name.len == 0 or name[0] == '.') continue;
  924. const child = std.fmt.allocPrint(allocator, "{s}/{s}", .{ dir_path, name }) catch continue;
  925. defer allocator.free(child);
  926. addWatchesRecursive(ifd, child, depth + 1, excludes);
  927. }
  928. }
  929. }
  930. /// One exclusion, resolved against the script dir like every other hl:fs path
  931. /// and then normalised. Appends nothing on an empty string.
  932. fn appendExclusion(list: *std.ArrayListUnmanaged([]u8), raw: []const u8) bool {
  933. if (raw.len == 0) return true;
  934. const resolved = resolvePath(raw) orelse return false;
  935. defer allocator.free(resolved);
  936. const norm = normalizePath(resolved) orelse return false;
  937. list.append(allocator, norm) catch {
  938. allocator.free(norm);
  939. return false;
  940. };
  941. return true;
  942. }
  943. export fn hl_fs_watch(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  944. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:fs: watch(path) needs a path string");
  945. const raw = argv[0].data.string.ptr[0..argv[0].data.string.len];
  946. const resolved = resolvePath(raw) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  947. defer allocator.free(resolved);
  948. const path = normalizePath(resolved) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  949. defer allocator.free(path);
  950. // THE OPTIONAL SECOND ARGUMENT: absent or null → watch everything, exactly
  951. // as before. A string is one directory; an object with numeric keys is the
  952. // loader's list shape (`hl_proc_spawn` reads its argv list the same way).
  953. var excludes = std.ArrayListUnmanaged([]u8).empty;
  954. defer {
  955. for (excludes.items) |e| allocator.free(e);
  956. excludes.deinit(allocator);
  957. }
  958. if (argc >= 2) {
  959. switch (argv[1].type) {
  960. .hl_null => {},
  961. .hl_string => {
  962. const sv = argv[1].data.string;
  963. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  964. },
  965. .hl_object => {
  966. const obj_in = argv[1].data.object;
  967. for (obj_in.fields[0..obj_in.field_count]) |field| {
  968. if (field.value.type == .hl_null) continue;
  969. if (field.value.type != .hl_string) return api.makeError("hl:fs: watch(path, exclude): every exclusion must be a path string");
  970. const sv = field.value.data.string;
  971. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  972. }
  973. },
  974. else => return api.makeError("hl:fs: watch(path, exclude): exclude is a path string or a list of path strings"),
  975. }
  976. }
  977. const rc = linux.inotify_init1(linux.IN.NONBLOCK);
  978. const ifd: i32 = @intCast(@as(isize, @bitCast(rc)));
  979. if (ifd < 0) return api.makeError("hl:fs: watch: inotify unavailable");
  980. addWatchesRecursive(ifd, path, 0, excludes.items);
  981. const state = allocator.create(WatchState) catch return api.makeError("hl:fs: out of memory");
  982. state.* = .{ .ifd = ifd };
  983. watchWakeInit(state);
  984. const iter = allocator.create(HlIterator) catch {
  985. watchDeinit(state);
  986. return api.makeError("hl:fs: out of memory");
  987. };
  988. iter.* = .{
  989. .context = @ptrCast(state),
  990. .next_fn = &watchTryNext, // non-blocking either way — event loop only
  991. .try_next_fn = &watchTryNext,
  992. .deinit_fn = &watchDeinit,
  993. .wake_fd = state.wake_fd,
  994. };
  995. return api.makeIterator(iter);
  996. }
  997. // An epoll fd is itself pollable. The runtime's eight-byte bell read on it
  998. // fails harmlessly, leaving protocol bytes to this source alone. No thread is
  999. // needed: the inotify fd wakes for new events, the bell for buffered events.
  1000. fn watchWakeInit(st: *WatchState) void {
  1001. const erc: isize = @bitCast(linux.epoll_create1(linux.EPOLL.CLOEXEC));
  1002. if (erc < 0) return; // -1 retains the runtime's polled fallback
  1003. const ep: i32 = @intCast(erc);
  1004. const brc: isize = @bitCast(linux.eventfd(0, linux.EFD.NONBLOCK | linux.EFD.CLOEXEC));
  1005. if (brc < 0) {
  1006. _ = linux.close(ep);
  1007. return;
  1008. }
  1009. const bell: i32 = @intCast(brc);
  1010. for ([_]i32{ st.ifd, bell }) |fd| {
  1011. var ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = fd } };
  1012. const rc: isize = @bitCast(linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, fd, &ev));
  1013. if (rc < 0) {
  1014. _ = linux.close(bell);
  1015. _ = linux.close(ep);
  1016. return;
  1017. }
  1018. }
  1019. st.wake_fd = ep;
  1020. st.bell_fd = bell;
  1021. }
  1022. fn watchTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  1023. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  1024. var sink: u64 = 0;
  1025. if (st.bell_fd >= 0) _ = linux.read(st.bell_fd, @ptrCast(&sink), 8);
  1026. if (st.pos >= st.len) {
  1027. const r = linux.read(st.ifd, &st.buf, st.buf.len);
  1028. const n: isize = @bitCast(r);
  1029. if (n <= 0) return api.makeNull(); // EAGAIN: drained
  1030. st.len = @intCast(n);
  1031. st.pos = 0;
  1032. }
  1033. // one inotify_event: wd(i32) mask(u32) cookie(u32) len(u32) name[len]
  1034. const base = st.pos;
  1035. if (st.len - base < 16) {
  1036. st.pos = st.len;
  1037. return api.makeNull();
  1038. }
  1039. const name_len = std.mem.readInt(u32, st.buf[base + 12 ..][0..4], .little);
  1040. const name_start = base + 16;
  1041. var name: []const u8 = "";
  1042. if (name_len > 0 and name_start + name_len <= st.len) {
  1043. const raw_name = st.buf[name_start .. name_start + name_len];
  1044. name = std.mem.sliceTo(raw_name, 0);
  1045. }
  1046. st.pos = name_start + name_len;
  1047. if (st.pos < st.len and st.bell_fd >= 0) {
  1048. const one: u64 = 1;
  1049. _ = linux.write(st.bell_fd, @ptrCast(&one), 8);
  1050. }
  1051. const fields = allocator.alloc(api.HlField, 1) catch return api.makeNull();
  1052. const name_copy = allocator.dupe(u8, name) catch {
  1053. allocator.free(fields);
  1054. return api.makeNull();
  1055. };
  1056. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  1057. const obj = allocator.create(api.HlObject) catch {
  1058. allocator.free(name_copy);
  1059. allocator.free(fields);
  1060. return api.makeNull();
  1061. };
  1062. obj.* = .{ .fields = fields.ptr, .field_count = 1, .deinit_fn = &watchEventDeinit };
  1063. return api.makeObject(obj);
  1064. }
  1065. /// An event is the loader's to copy and ours to free (the emit soak, 2026-10-02): with
  1066. /// no deinit, every inotify event of the dev watcher — each write a db makes under the
  1067. /// watched root — kept its name, its field and its object for good.
  1068. fn watchEventDeinit(obj: *api.HlObject) callconv(.c) void {
  1069. const sv = obj.fields[0].value.data.string;
  1070. allocator.free(@constCast(sv.ptr)[0..sv.len]);
  1071. allocator.free(obj.fields[0..obj.field_count]);
  1072. allocator.destroy(obj);
  1073. }
  1074. fn watchDeinit(ctx: ?*anyopaque) callconv(.c) void {
  1075. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return));
  1076. if (st.wake_fd >= 0) _ = linux.close(st.wake_fd);
  1077. if (st.bell_fd >= 0) _ = linux.close(st.bell_fd);
  1078. _ = linux.close(st.ifd);
  1079. allocator.destroy(st);
  1080. }
  1081. // =========================================================================
  1082. // THE WRITE SURFACE (2026-08-28)
  1083. //
  1084. // hl:fs was READ-ONLY until this block: file, readFile, listDir, exists,
  1085. // watch. It could report a file's `chmod` and never set one. Session
  1086. // persistence is the first thing in this tree that has to put bytes on a
  1087. // disk, and the rule when the framework can do something the language
  1088. // cannot is that the LANGUAGE is missing it — so the capability lands here,
  1089. // as an ordinary hl:fs surface any program can use, not as a private hook
  1090. // the session store reaches through.
  1091. //
  1092. // Three calls, and the shape of each is a decision:
  1093. //
  1094. // writeFile(path, contents, mode?) ATOMIC. Writes a sibling temp file,
  1095. // fsyncs it, then rename()s it over the target — so a reader sees
  1096. // either the whole previous file or the whole new one, never a torn
  1097. // one. A half-written session file that revives as garbage is a
  1098. // silent logout, and the crash that produces it is exactly the crash
  1099. // nobody can reproduce. rename(2) within one directory is atomic on
  1100. // every filesystem Linux ships; that is the whole reason the temp
  1101. // file is a SIBLING rather than in /tmp (a cross-device rename fails).
  1102. // mkDir(path, mode?) recursive, and succeeds when the
  1103. // directory is already there — the caller wants it to exist, not to
  1104. // be the one who created it.
  1105. // remove(path) IDEMPOTENT: true when the path is
  1106. // gone on return, including when it was already gone. A sweep
  1107. // deleting an expired file must not fail because something else
  1108. // deleted it first.
  1109. //
  1110. // MODES ARE EXPLICIT AND DEFAULT TIGHT. hybrilior passes no mode anywhere,
  1111. // so its session files land at whatever the umask says — 0644 on a shared
  1112. // box, i.e. every session on the machine readable by every other tenant.
  1113. // Here the default is 0600 for a file and 0700 for a directory, and a
  1114. // caller who wants them looser has to say so. This is not the kind of bug
  1115. // that shows up in a test; it shows up in someone else's logs.
  1116. // =========================================================================
  1117. fn makeWriteError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  1118. const msg = std.fmt.allocPrint(allocator, "{s}: cannot write '{s}' — {s} (errno {d}); {s}", .{ op, path, errnoText(errno), errno, errnoHint(errno) }) catch
  1119. return api.makeError("fs: write failed");
  1120. var v = api.makeError(msg);
  1121. v.deinit_fn = &errDeinit;
  1122. return v;
  1123. }
  1124. /// mkdir every missing component of `path`. Returns 0, or the errno of the
  1125. /// first component that could not be created for a reason other than "it is
  1126. /// already there".
  1127. fn mkdirRecursive(path: []const u8, mode: u32) usize {
  1128. if (path.len == 0) return 0;
  1129. const buf = allocator.dupeZ(u8, path) catch return 12; // ENOMEM
  1130. defer allocator.free(buf);
  1131. // Walk the separators left to right, creating each prefix in turn. Index
  1132. // 0 is skipped so a leading '/' is never itself a component to create.
  1133. var i: usize = 1;
  1134. while (i <= buf.len) : (i += 1) {
  1135. const at_end = i == buf.len;
  1136. if (!at_end and buf[i] != '/') continue;
  1137. if (!at_end) buf[i] = 0;
  1138. const rc: isize = @bitCast(linux.mkdir(buf.ptr, mode));
  1139. if (!at_end) buf[i] = '/';
  1140. if (rc < 0) {
  1141. const errno: usize = @intCast(-rc);
  1142. // EEXIST is the success case: the caller wants it to exist.
  1143. if (errno != 17) return errno;
  1144. }
  1145. }
  1146. return 0;
  1147. }
  1148. export fn hl_fs_mk_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1149. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.mkDir expects a string path");
  1150. const path_str = argv[0].data.string;
  1151. const path = path_str.ptr[0..path_str.len];
  1152. var mode: u32 = 0o700;
  1153. if (argc >= 2 and argv[1].type == .hl_number) mode = @intFromFloat(argv[1].data.number);
  1154. const resolved = resolvePath(path) orelse return api.makeError("fs.mkDir: out of memory");
  1155. defer allocator.free(resolved);
  1156. const errno = mkdirRecursive(resolved, mode);
  1157. if (errno != 0) return makeWriteError("fs.mkDir", path, errno);
  1158. return api.makeBool(true);
  1159. }
  1160. const write_usage = "fs.writeFile expects (String path, String or Bytes contents, Number mode?)";
  1161. export fn hl_fs_write_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1162. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1163. return api.makeError(write_usage);
  1164. }
  1165. const path_str = argv[0].data.string;
  1166. const body_str = argv[1].data.string;
  1167. return writeWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1168. }
  1169. /// hl_fs_write_file_hex(path, hex, mode?) — writeFile with a Bytes (ticket
  1170. /// #88): a Bytes crosses the plugin boundary as its hex text (the ABI has no
  1171. /// Bytes, as hl:proc's write_hex says), is decoded here and written raw.
  1172. export fn hl_fs_write_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1173. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1174. return api.makeError(write_usage);
  1175. }
  1176. const path_str = argv[0].data.string;
  1177. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1178. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.writeFile: out of memory");
  1179. defer allocator.free(raw);
  1180. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.writeFile: not a Bytes");
  1181. return writeWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1182. }
  1183. fn modeArg(argc: u32, argv: [*]const HlValue) u32 {
  1184. if (argc >= 3 and argv[2].type == .hl_number) return @intFromFloat(argv[2].data.number);
  1185. return 0o600;
  1186. }
  1187. fn writeWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1188. const resolved = resolvePath(path) orelse return api.makeError("fs.writeFile: out of memory");
  1189. defer allocator.free(resolved);
  1190. // The temp name is a SIBLING (see the block comment): rename(2) is only
  1191. // atomic within one filesystem, and /tmp is routinely a different one.
  1192. // The pid keeps two processes writing the same path off each other's temp
  1193. // file; the rename itself settles who wins the target.
  1194. const pid = linux.getpid();
  1195. const tmp = std.fmt.allocPrintSentinel(allocator, "{s}.hltmp{d}", .{ resolved, pid }, 0) catch
  1196. return api.makeError("fs.writeFile: out of memory");
  1197. defer allocator.free(tmp);
  1198. const rc = linuxOpenRc(tmp.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, mode);
  1199. if (rc < 0) return makeWriteError("fs.writeFile", path, @intCast(-rc));
  1200. const fd: i32 = @intCast(rc);
  1201. var wrote: usize = 0;
  1202. while (wrote < body.len) {
  1203. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1204. if (n <= 0) {
  1205. _ = linux.close(fd);
  1206. _ = linux.unlink(tmp.ptr);
  1207. return makeWriteError("fs.writeFile", path, if (n < 0) @intCast(-n) else 5);
  1208. }
  1209. wrote += @intCast(n);
  1210. }
  1211. // fsync BEFORE the rename, or the rename can land while the bytes are
  1212. // still only in the page cache — a power cut then leaves an EMPTY file
  1213. // where a complete one used to be, which is worse than either outcome.
  1214. _ = linux.fsync(fd);
  1215. _ = linux.close(fd);
  1216. // O_CREAT honours the mode only through the umask; say it outright so a
  1217. // 0600 request is 0600 whatever the process umask happens to be.
  1218. _ = linux.chmod(tmp.ptr, mode);
  1219. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.writeFile: out of memory");
  1220. defer allocator.free(path_z);
  1221. const ren: isize = @bitCast(linux.rename(tmp.ptr, path_z.ptr));
  1222. if (ren < 0) {
  1223. _ = linux.unlink(tmp.ptr);
  1224. return makeWriteError("fs.writeFile", path, @intCast(-ren));
  1225. }
  1226. return api.makeBool(true);
  1227. }
  1228. const create_usage = "fs.createFile expects (String path, String or Bytes contents, Number mode?)";
  1229. export fn hl_fs_create_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1230. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1231. return api.makeError(create_usage);
  1232. }
  1233. const path_str = argv[0].data.string;
  1234. const body_str = argv[1].data.string;
  1235. return createWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1236. }
  1237. /// Bytes cross the plugin ABI as hex, just as writeFile does.
  1238. export fn hl_fs_create_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1239. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1240. return api.makeError(create_usage);
  1241. }
  1242. const path_str = argv[0].data.string;
  1243. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1244. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.createFile: out of memory");
  1245. defer allocator.free(raw);
  1246. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.createFile: not a Bytes");
  1247. return createWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1248. }
  1249. /// Exclusive creation publishes the path before writing its content.
  1250. fn createWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1251. const resolved = resolvePath(path) orelse return api.makeError("fs.createFile: out of memory");
  1252. defer allocator.free(resolved);
  1253. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.createFile: out of memory");
  1254. defer allocator.free(path_z);
  1255. const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, mode);
  1256. if (rc == -17) return api.makeBool(false); // EEXIST: another creator won.
  1257. if (rc < 0) return makeWriteError("fs.createFile", path, @intCast(-rc));
  1258. const fd: i32 = @intCast(rc);
  1259. defer _ = linux.close(fd);
  1260. // Set the requested mode through the descriptor, even with a restrictive umask.
  1261. const chmod_rc: isize = @bitCast(linux.fchmod(fd, mode));
  1262. if (chmod_rc < 0) return makeWriteError("fs.createFile", path, @intCast(-chmod_rc));
  1263. var wrote: usize = 0;
  1264. while (wrote < body.len) {
  1265. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1266. if (n == -4) continue; // EINTR
  1267. if (n <= 0) {
  1268. return makeWriteError("fs.createFile", path, if (n < 0) @intCast(-n) else 5);
  1269. }
  1270. wrote += @intCast(n);
  1271. }
  1272. return api.makeBool(true);
  1273. }
  1274. const append_usage = "fs.appendFile expects (String path, String or Bytes contents, Number mode?)";
  1275. export fn hl_fs_append_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1276. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1277. return api.makeError(append_usage);
  1278. }
  1279. const path_str = argv[0].data.string;
  1280. const body_str = argv[1].data.string;
  1281. return appendWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1282. }
  1283. /// hl_fs_append_file_hex(path, hex, mode?) — appendFile with a Bytes (ticket
  1284. /// #88), the same hex-text crossing writeFile's hex sibling uses.
  1285. export fn hl_fs_append_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1286. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1287. return api.makeError(append_usage);
  1288. }
  1289. const path_str = argv[0].data.string;
  1290. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1291. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.appendFile: out of memory");
  1292. defer allocator.free(raw);
  1293. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.appendFile: not a Bytes");
  1294. return appendWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1295. }
  1296. /// APPEND, NOT ATOMIC BY RENAME (writeFile's block comment above): an append
  1297. /// MUTATES the file that is already there, so there is no whole "old" or
  1298. /// "new" version to swap in — O_APPEND gives a narrower guarantee instead.
  1299. /// The kernel positions a single write() at the file's CURRENT end and
  1300. /// performs it as one operation, so two processes each appending a line never
  1301. /// interleave their bytes mid-line and a reader never sees a torn append —
  1302. /// which is why this is ONE write() of the whole body where writeFile's is
  1303. /// (short-write retries aside). The file is created at `mode` (default 0600,
  1304. /// same default as writeFile) if it is not there yet; O_APPEND on an existing
  1305. /// file leaves its mode untouched, same as any other open of it.
  1306. fn appendWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1307. const resolved = resolvePath(path) orelse return api.makeError("fs.appendFile: out of memory");
  1308. defer allocator.free(resolved);
  1309. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.appendFile: out of memory");
  1310. defer allocator.free(path_z);
  1311. const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, mode);
  1312. if (rc < 0) return makeWriteError("fs.appendFile", path, @intCast(-rc));
  1313. const fd: i32 = @intCast(rc);
  1314. defer _ = linux.close(fd);
  1315. var wrote: usize = 0;
  1316. while (wrote < body.len) {
  1317. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1318. if (n <= 0) {
  1319. return makeWriteError("fs.appendFile", path, if (n < 0) @intCast(-n) else 5);
  1320. }
  1321. wrote += @intCast(n);
  1322. }
  1323. return api.makeBool(true);
  1324. }
  1325. export fn hl_fs_remove(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1326. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.remove expects a string path");
  1327. const path_str = argv[0].data.string;
  1328. const path = path_str.ptr[0..path_str.len];
  1329. const resolved = resolvePath(path) orelse return api.makeError("fs.remove: out of memory");
  1330. defer allocator.free(resolved);
  1331. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.remove: out of memory");
  1332. defer allocator.free(path_z);
  1333. var rc: isize = @bitCast(linux.unlink(path_z.ptr));
  1334. // an empty directory goes too (EISDIR): hybriel.hl's scratch directories
  1335. // (mission 326 rung 12), with no `rmdir` to shell out to
  1336. if (rc == -21) rc = @bitCast(linux.rmdir(path_z.ptr));
  1337. if (rc < 0) {
  1338. const errno: usize = @intCast(-rc);
  1339. // ENOENT is success: the caller asked for the path to be gone.
  1340. if (errno == 2) return api.makeBool(true);
  1341. return makeWriteError("fs.remove", path, errno);
  1342. }
  1343. return api.makeBool(true);
  1344. }
  1345. /// realPath(path) → the canonical absolute path (symlinks resolved, `.`/`..`
  1346. /// folded; realpath(3)), or null when the path is not there or cannot be
  1347. /// resolved. `/proc/self/exe` answers the running binary without a shell.
  1348. export fn hl_fs_real_path(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1349. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  1350. const path_str = argv[0].data.string;
  1351. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  1352. defer allocator.free(resolved);
  1353. traceAccess('e', resolved);
  1354. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  1355. defer allocator.free(path_z);
  1356. var buf: [std.posix.PATH_MAX]u8 = undefined;
  1357. const out = std.c.realpath(path_z.ptr, &buf) orelse return api.makeNull();
  1358. const text = allocator.dupe(u8, std.mem.span(out)) catch return api.makeNull();
  1359. var result = api.makeString(text);
  1360. result.deinit_fn = &readFileDeinit;
  1361. return result;
  1362. }
  1363. test "wake burst fs buffered inotify events" {
  1364. const w = @import("wake_test");
  1365. const tmp = std.c.getenv("TMPDIR") orelse return error.NoScratchDirectory;
  1366. const dir = try std.fmt.allocPrintSentinel(allocator, "{s}/fs-wake-{d}", .{ std.mem.span(tmp), linux.getpid() }, 0);
  1367. defer allocator.free(dir);
  1368. _ = linux.mkdir(dir, 0o700);
  1369. defer _ = linux.rmdir(dir);
  1370. var passed: usize = 0;
  1371. for (0..10) |_| {
  1372. const args = [_]api.HlValue{api.makeString(dir)};
  1373. const v = hl_fs_watch(1, &args);
  1374. try std.testing.expect(v.type == .hl_iterator);
  1375. const it = v.data.iterator;
  1376. defer allocator.destroy(it);
  1377. defer watchDeinit(it.context);
  1378. // 32 creates fit in one read. There are no writes/close-write events.
  1379. for (0..32) |i| {
  1380. const path = try std.fmt.allocPrintSentinel(allocator, "{s}/{d}", .{ dir, i }, 0);
  1381. defer allocator.free(path);
  1382. const fd = linuxOpenRc(path, .{ .CREAT = true, .ACCMODE = .RDONLY }, 0o600);
  1383. try std.testing.expect(fd >= 0);
  1384. _ = linux.close(@intCast(fd));
  1385. }
  1386. if (w.burst(it.wake_fd, it.context, &watchTryNext, 32)) passed += 1;
  1387. for (0..32) |i| {
  1388. const path = try std.fmt.allocPrintSentinel(allocator, "{s}/{d}", .{ dir, i }, 0);
  1389. defer allocator.free(path);
  1390. _ = linux.unlink(path);
  1391. }
  1392. }
  1393. try w.result("fs inotify buffer", passed);
  1394. try w.require(&.{passed});
  1395. }

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre