gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit359c79f7359c79f7gitoria 010: re-vendor Hybriel master f9614007 (plugins whole, bin/ git-ignored)mre359c79f7/plugins/fs/fs.zig

52.4 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. /// changeTime(path) → the path's last status change (ctime, which no write can set
  380. /// back) as milliseconds since the epoch, or null when it is not there (#195). The
  381. /// build cache asks it of everything a build read: an input changed after the build
  382. /// began (a file edited, a checkout, a file made or removed in a listed directory)
  383. /// makes what the build saw differ from what the record would say. Not traced.
  384. export fn hl_fs_change_time(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  385. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  386. const path_str = argv[0].data.string;
  387. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  388. defer allocator.free(resolved);
  389. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  390. defer allocator.free(path_z);
  391. var statx_buf: std.os.linux.Statx = undefined;
  392. const rc = std.os.linux.statx(
  393. std.os.linux.AT.FDCWD,
  394. path_z,
  395. 0,
  396. std.os.linux.STATX.BASIC_STATS,
  397. &statx_buf,
  398. );
  399. if (@as(isize, @bitCast(rc)) != 0) return api.makeNull();
  400. const sec: f64 = @floatFromInt(statx_buf.ctime.sec);
  401. const nsec: f64 = @floatFromInt(statx_buf.ctime.nsec);
  402. return api.makeNumber(sec * 1000.0 + nsec / 1000000.0);
  403. }
  404. export fn hl_fs_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  405. return readWhole(argc, argv, false);
  406. }
  407. /// tryReadFile(path) → the file as a string, or null when the path is not
  408. /// there (ENOENT/ENOTDIR). Any other failure is an error as in readFile. For a
  409. /// file another process may delete between a probe and the read (a shared
  410. /// cache): the vanishing is an answer, not a fault.
  411. export fn hl_fs_try_read_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  412. return readWhole(argc, argv, true);
  413. }
  414. fn readWhole(argc: u32, argv: [*]const HlValue, absent_is_null: bool) HlValue {
  415. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.readFile expects a string path");
  416. const path_str = argv[0].data.string;
  417. const path = path_str.ptr[0..path_str.len];
  418. const resolved = resolvePath(path) orelse return api.makeNull();
  419. defer allocator.free(resolved);
  420. traceAccess('r', resolved);
  421. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  422. defer allocator.free(path_z);
  423. const rc = linuxOpenRc(path_z, .{}, 0);
  424. if (rc < 0) {
  425. const en: usize = @intCast(-rc);
  426. if (absent_is_null and (en == @intFromEnum(linux.E.NOENT) or en == @intFromEnum(linux.E.NOTDIR))) return api.makeNull();
  427. return makeOpenError("fs.readFile", path, en);
  428. }
  429. const fd: i32 = @intCast(rc);
  430. defer _ = linux.close(fd);
  431. // The whole file: no size cap (a 10 MiB cap once truncated silently, ticket #112).
  432. // A failed read is an error naming the path, never a short string.
  433. var content = std.array_list.Managed(u8).init(allocator);
  434. defer content.deinit();
  435. var buf: [65536]u8 = undefined;
  436. while (true) {
  437. const n_read: isize = @bitCast(linux.read(fd, &buf, buf.len));
  438. if (n_read == 0) break;
  439. if (n_read < 0) {
  440. const errno: usize = @intCast(-n_read);
  441. if (errno == @intFromEnum(linux.E.INTR)) continue;
  442. return makeReadError("fs.readFile", path, errno);
  443. }
  444. content.appendSlice(buf[0..@intCast(n_read)]) catch return api.makeError("fs.readFile: out of memory reading the file");
  445. }
  446. const result_slice = content.toOwnedSlice() catch return api.makeNull();
  447. var result = api.makeString(result_slice);
  448. result.deinit_fn = &readFileDeinit;
  449. return result;
  450. }
  451. // =========================================================================
  452. // hl_fs_list_dir — streaming directory iterator with metadata
  453. // =========================================================================
  454. const DirIterState = struct {
  455. fd: i32,
  456. base_path: []const u8,
  457. allocated_strings: std.array_list.Managed([]u8),
  458. // Linux getdents64 buffer
  459. dents_buf: [4096]u8,
  460. dents_pos: usize,
  461. dents_len: usize,
  462. done: bool,
  463. };
  464. export fn hl_fs_list_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  465. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.listDir expects a string path");
  466. const path_str = argv[0].data.string;
  467. const path = path_str.ptr[0..path_str.len];
  468. const resolved = resolvePath(path) orelse return api.makeNull();
  469. defer allocator.free(resolved);
  470. traceAccess('l', resolved);
  471. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  472. defer allocator.free(path_z);
  473. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  474. if (rc < 0) return makeOpenError("fs.listDir", path, @intCast(-rc));
  475. const fd: i32 = @intCast(rc);
  476. const path_copy = allocator.dupe(u8, path) catch return api.makeNull();
  477. const state = allocator.create(DirIterState) catch return api.makeNull();
  478. state.* = .{
  479. .fd = fd,
  480. .base_path = path_copy,
  481. .allocated_strings = std.array_list.Managed([]u8).init(allocator),
  482. .dents_buf = undefined,
  483. .dents_pos = 0,
  484. .dents_len = 0,
  485. .done = false,
  486. };
  487. const iter = allocator.create(HlIterator) catch return api.makeNull();
  488. iter.* = .{
  489. .context = @ptrCast(state),
  490. .next_fn = &dirIterNext,
  491. .deinit_fn = &dirIterDeinit,
  492. };
  493. return api.makeIterator(iter);
  494. }
  495. fn dirIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  496. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  497. if (state.done) return api.makeNull();
  498. while (true) {
  499. // Need more directory entries?
  500. if (state.dents_pos >= state.dents_len) {
  501. const rc = std.os.linux.getdents64(state.fd, &state.dents_buf, state.dents_buf.len);
  502. if (@as(isize, @bitCast(rc)) <= 0) {
  503. state.done = true;
  504. return api.makeNull();
  505. }
  506. state.dents_len = rc;
  507. state.dents_pos = 0;
  508. }
  509. // Parse next dirent64
  510. const entry_ptr: *align(1) std.os.linux.dirent64 = @ptrCast(&state.dents_buf[state.dents_pos]);
  511. state.dents_pos += entry_ptr.reclen;
  512. // Get name
  513. const name_ptr: [*]const u8 = @ptrCast(&entry_ptr.name);
  514. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  515. const name = name_ptr[0..name_len];
  516. // Skip . and ..
  517. if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
  518. const name_copy = allocator.dupe(u8, name) catch return api.makeNull();
  519. state.allocated_strings.append(name_copy) catch return api.makeNull();
  520. // Build full path
  521. const full_path = std.fmt.allocPrint(allocator, "{s}/{s}", .{ state.base_path, name }) catch return api.makeNull();
  522. state.allocated_strings.append(full_path) catch return api.makeNull();
  523. // Entry type from d_type
  524. const kind_str: []const u8 = switch (entry_ptr.type) {
  525. std.os.linux.DT.DIR => "directory",
  526. std.os.linux.DT.REG => "file",
  527. std.os.linux.DT.LNK => "symlink",
  528. else => "other",
  529. };
  530. // Stat for size, chmod, uid, gid
  531. var size: f64 = 0;
  532. var chmod: f64 = 0;
  533. var e_uid: f64 = 0;
  534. var e_gid: f64 = 0;
  535. // null-terminate name for statx
  536. var name_z_buf: [256]u8 = undefined;
  537. if (name.len < name_z_buf.len) {
  538. @memcpy(name_z_buf[0..name.len], name);
  539. name_z_buf[name.len] = 0;
  540. var statx_buf: std.os.linux.Statx = undefined;
  541. const src = std.os.linux.statx(
  542. state.fd,
  543. @ptrCast(name_z_buf[0 .. name.len + 1]),
  544. 0,
  545. std.os.linux.STATX.BASIC_STATS,
  546. &statx_buf,
  547. );
  548. if (src == 0) {
  549. size = @floatFromInt(statx_buf.size);
  550. chmod = @floatFromInt(statx_buf.mode & 0o7777);
  551. e_uid = @floatFromInt(statx_buf.uid);
  552. e_gid = @floatFromInt(statx_buf.gid);
  553. }
  554. }
  555. const mime = mimeFromName(name_copy);
  556. // Build object: name, path, type, size, mime, chmod, user, group
  557. // The runtime's hlObjectToValue will call entryObjDeinit after conversion,
  558. // so these objects are freed immediately upon consumption.
  559. const field_count: usize = 8;
  560. const fields = allocator.alloc(HlField, field_count) catch return api.makeNull();
  561. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  562. fields[1] = .{ .key = hlStr("path"), .value = api.makeString(full_path) };
  563. fields[2] = .{ .key = hlStr("type"), .value = api.makeString(kind_str) };
  564. fields[3] = .{ .key = hlStr("size"), .value = api.makeNumber(size) };
  565. fields[4] = .{ .key = hlStr("mime"), .value = api.makeString(mime) };
  566. fields[5] = .{ .key = hlStr("chmod"), .value = api.makeNumber(chmod) };
  567. fields[6] = .{ .key = hlStr("user"), .value = api.makeNumber(e_uid) };
  568. fields[7] = .{ .key = hlStr("group"), .value = api.makeNumber(e_gid) };
  569. const obj = allocator.create(HlObject) catch return api.makeNull();
  570. obj.* = .{
  571. .fields = fields.ptr,
  572. .field_count = field_count,
  573. .deinit_fn = &entryObjDeinit,
  574. };
  575. return api.makeObject(obj);
  576. }
  577. }
  578. fn entryObjDeinit(obj: *HlObject) callconv(.c) void {
  579. allocator.free(obj.fields[0..obj.field_count]);
  580. allocator.destroy(obj);
  581. }
  582. fn dirIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  583. const state: *DirIterState = @ptrCast(@alignCast(ctx orelse return));
  584. _ = linux.close(state.fd);
  585. for (state.allocated_strings.items) |s| {
  586. allocator.free(s);
  587. }
  588. state.allocated_strings.deinit();
  589. allocator.free(@constCast(state.base_path));
  590. allocator.destroy(state);
  591. }
  592. // =========================================================================
  593. // Helpers
  594. // =========================================================================
  595. /// Raw open: >= 0 is the fd, < 0 is -errno.
  596. fn linuxOpenRc(path_z: [*:0]const u8, flags: linux.O, mode: u32) isize {
  597. const rc = linux.open(path_z, flags, mode);
  598. return @bitCast(rc);
  599. }
  600. fn linuxRead(fd: i32, buf: []u8) ?usize {
  601. const rc = linux.read(fd, buf.ptr, buf.len);
  602. if (@as(isize, @bitCast(rc)) <= 0) return null;
  603. return rc;
  604. }
  605. fn hlStr(comptime s: []const u8) HlString {
  606. return .{ .ptr = s.ptr, .len = s.len };
  607. }
  608. fn mimeFromName(name: []const u8) []const u8 {
  609. const ext = if (std.mem.lastIndexOfScalar(u8, name, '.')) |dot|
  610. name[dot..]
  611. else
  612. return "application/octet-stream";
  613. if (std.mem.eql(u8, ext, ".txt")) return "text/plain";
  614. if (std.mem.eql(u8, ext, ".html") or std.mem.eql(u8, ext, ".htm")) return "text/html";
  615. if (std.mem.eql(u8, ext, ".css")) return "text/css";
  616. if (std.mem.eql(u8, ext, ".js")) return "text/javascript";
  617. if (std.mem.eql(u8, ext, ".json")) return "application/json";
  618. if (std.mem.eql(u8, ext, ".xml")) return "application/xml";
  619. if (std.mem.eql(u8, ext, ".png")) return "image/png";
  620. if (std.mem.eql(u8, ext, ".jpg") or std.mem.eql(u8, ext, ".jpeg")) return "image/jpeg";
  621. if (std.mem.eql(u8, ext, ".gif")) return "image/gif";
  622. if (std.mem.eql(u8, ext, ".svg")) return "image/svg+xml";
  623. if (std.mem.eql(u8, ext, ".pdf")) return "application/pdf";
  624. if (std.mem.eql(u8, ext, ".zip")) return "application/zip";
  625. if (std.mem.eql(u8, ext, ".gz")) return "application/gzip";
  626. if (std.mem.eql(u8, ext, ".mp3")) return "audio/mpeg";
  627. if (std.mem.eql(u8, ext, ".mp4")) return "video/mp4";
  628. if (std.mem.eql(u8, ext, ".wasm")) return "application/wasm";
  629. if (std.mem.eql(u8, ext, ".hl")) return "text/x-hybriel";
  630. if (std.mem.eql(u8, ext, ".md")) return "text/markdown";
  631. if (std.mem.eql(u8, ext, ".yml") or std.mem.eql(u8, ext, ".yaml")) return "text/yaml";
  632. if (std.mem.eql(u8, ext, ".toml")) return "application/toml";
  633. if (std.mem.eql(u8, ext, ".csv")) return "text/csv";
  634. if (std.mem.eql(u8, ext, ".ts")) return "text/typescript";
  635. if (std.mem.eql(u8, ext, ".c") or std.mem.eql(u8, ext, ".h")) return "text/x-c";
  636. if (std.mem.eql(u8, ext, ".zig")) return "text/x-zig";
  637. if (std.mem.eql(u8, ext, ".rs")) return "text/x-rust";
  638. if (std.mem.eql(u8, ext, ".py")) return "text/x-python";
  639. if (std.mem.eql(u8, ext, ".sh")) return "text/x-shellscript";
  640. if (std.mem.eql(u8, ext, ".sql")) return "application/sql";
  641. if (std.mem.eql(u8, ext, ".webp")) return "image/webp";
  642. if (std.mem.eql(u8, ext, ".ico")) return "image/x-icon";
  643. if (std.mem.eql(u8, ext, ".woff2")) return "font/woff2";
  644. if (std.mem.eql(u8, ext, ".woff")) return "font/woff";
  645. if (std.mem.eql(u8, ext, ".ttf")) return "font/ttf";
  646. return "application/octet-stream";
  647. }
  648. // ── fs.watch: an inotify LOOP SOURCE (the dev-reload bell) ───────────────────
  649. // `watch(path)` returns an event-loop source whose wake_fd IS the inotify fd,
  650. // so the loop's own epoll_wait wakes on a save — no polling anywhere. Watches
  651. // the directory RECURSIVELY at registration (dot-dirs skipped); directories
  652. // created afterwards are picked up the next time the app is restarted, which
  653. // is the honest v1 for a dev tool.
  654. //
  655. // EXCLUSIONS (mission 266). `watch(path, exclude)` takes a second argument —
  656. // a path STRING or a LIST of them, the same either-shape the plugin surface
  657. // already uses in `hl_proc_spawn` — naming directories the descent must not
  658. // enter. One argument still means "watch everything": the argument is optional
  659. // and a null is the same as absent.
  660. //
  661. // This exists because a program that knows, at startup, about a directory it
  662. // will write to constantly (hl:web's session store is the first) had NO way to
  663. // say so. The only skip the walker possessed was "the name starts with a dot",
  664. // so the framework's advice was to RENAME the directory — a lecture standing
  665. // in for a fix. The dot-dir skip STAYS; `.git` is its reason and it is a good
  666. // one. This is a second, explicit reason to skip, not a replacement.
  667. const WatchState = struct {
  668. ifd: i32,
  669. buf: [4096]u8 align(4) = undefined,
  670. len: usize = 0,
  671. pos: usize = 0,
  672. };
  673. /// LEXICAL path normalisation — collapses `//` and resolves `.` / `..`
  674. /// without touching the filesystem. It must be lexical: an excluded directory
  675. /// need not exist yet at the moment the watch is armed (hl:web resolves its
  676. /// session dir before it creates it), and realpath(2) on a missing path fails.
  677. /// Both the watch root and every exclusion go through this, so the comparison
  678. /// below is between two paths written the same way.
  679. fn normalizePath(path: []const u8) ?[]u8 {
  680. const absolute = path.len > 0 and path[0] == '/';
  681. var parts = std.ArrayListUnmanaged([]const u8).empty;
  682. defer parts.deinit(allocator);
  683. var it = std.mem.tokenizeScalar(u8, path, '/');
  684. while (it.next()) |seg| {
  685. if (std.mem.eql(u8, seg, ".")) continue;
  686. if (std.mem.eql(u8, seg, "..")) {
  687. if (parts.items.len > 0 and !std.mem.eql(u8, parts.items[parts.items.len - 1], "..")) {
  688. _ = parts.pop();
  689. continue;
  690. }
  691. if (absolute) continue; // ".." above "/" is "/"
  692. }
  693. parts.append(allocator, seg) catch return null;
  694. }
  695. var out = std.ArrayListUnmanaged(u8).empty;
  696. defer out.deinit(allocator);
  697. for (parts.items, 0..) |seg, i| {
  698. if (absolute or i > 0) out.append(allocator, '/') catch return null;
  699. out.appendSlice(allocator, seg) catch return null;
  700. }
  701. if (out.items.len == 0) out.appendSlice(allocator, if (absolute) "/" else ".") catch return null;
  702. return allocator.dupe(u8, out.items) catch null;
  703. }
  704. /// Is `child` the directory `root`, or somewhere under it? Both must already
  705. /// be normalised. A bare `startsWith` would call `/a/sessions-old` a child of
  706. /// `/a/sessions`, which is the whole reason this is a function: the byte after
  707. /// the prefix has to BE a separator.
  708. fn pathIsInside(child: []const u8, root: []const u8) bool {
  709. if (root.len == 0) return false;
  710. if (std.mem.eql(u8, child, root)) return true;
  711. if (child.len <= root.len) return false;
  712. if (!std.mem.startsWith(u8, child, root)) return false;
  713. if (root[root.len - 1] == '/') return true; // root is "/" itself
  714. return child[root.len] == '/';
  715. }
  716. fn addWatchesRecursive(ifd: i32, dir_path: []const u8, depth: u32, excludes: []const []const u8) void {
  717. if (depth > 8) return;
  718. // The SECOND reason to skip a directory (mission 266). `dir_path` is
  719. // normalised: the root was normalised before the first call and every
  720. // child below is that root plus one plain name.
  721. for (excludes) |ex| if (pathIsInside(dir_path, ex)) return;
  722. const path_z = allocator.dupeZ(u8, dir_path) catch return;
  723. defer allocator.free(path_z);
  724. const mask: u32 = linux.IN.CLOSE_WRITE | linux.IN.CREATE | linux.IN.DELETE | linux.IN.MOVED_TO | linux.IN.MOVED_FROM;
  725. _ = linux.inotify_add_watch(ifd, path_z, mask);
  726. // The descent walks getdents64 directly, like hl_fs_list_dir does — this
  727. // plugin speaks raw syscalls throughout and never pulls in std.fs.
  728. const rc = linuxOpenRc(path_z, .{ .DIRECTORY = true }, 0);
  729. if (rc < 0) return;
  730. const fd: i32 = @intCast(rc);
  731. defer _ = linux.close(fd);
  732. var dents: [4096]u8 align(8) = undefined;
  733. while (true) {
  734. const got = linux.getdents64(fd, &dents, dents.len);
  735. if (@as(isize, @bitCast(got)) <= 0) break;
  736. var pos: usize = 0;
  737. while (pos < got) {
  738. const entry: *align(1) linux.dirent64 = @ptrCast(&dents[pos]);
  739. pos += entry.reclen;
  740. if (entry.type != linux.DT.DIR) continue;
  741. const name_ptr: [*]const u8 = @ptrCast(&entry.name);
  742. const name_len = std.mem.indexOfScalar(u8, name_ptr[0..256], 0) orelse continue;
  743. const name = name_ptr[0..name_len];
  744. // "." and ".." would recurse forever; every other dot-dir is noise
  745. // for a dev watcher (.git alone would cost thousands of watches).
  746. if (name.len == 0 or name[0] == '.') continue;
  747. const child = std.fmt.allocPrint(allocator, "{s}/{s}", .{ dir_path, name }) catch continue;
  748. defer allocator.free(child);
  749. addWatchesRecursive(ifd, child, depth + 1, excludes);
  750. }
  751. }
  752. }
  753. /// One exclusion, resolved against the script dir like every other hl:fs path
  754. /// and then normalised. Appends nothing on an empty string.
  755. fn appendExclusion(list: *std.ArrayListUnmanaged([]u8), raw: []const u8) bool {
  756. if (raw.len == 0) return true;
  757. const resolved = resolvePath(raw) orelse return false;
  758. defer allocator.free(resolved);
  759. const norm = normalizePath(resolved) orelse return false;
  760. list.append(allocator, norm) catch {
  761. allocator.free(norm);
  762. return false;
  763. };
  764. return true;
  765. }
  766. export fn hl_fs_watch(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  767. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("hl:fs: watch(path) needs a path string");
  768. const raw = argv[0].data.string.ptr[0..argv[0].data.string.len];
  769. const resolved = resolvePath(raw) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  770. defer allocator.free(resolved);
  771. const path = normalizePath(resolved) orelse return api.makeError("hl:fs: watch: could not resolve the path");
  772. defer allocator.free(path);
  773. // THE OPTIONAL SECOND ARGUMENT: absent or null → watch everything, exactly
  774. // as before. A string is one directory; an object with numeric keys is the
  775. // loader's list shape (`hl_proc_spawn` reads its argv list the same way).
  776. var excludes = std.ArrayListUnmanaged([]u8).empty;
  777. defer {
  778. for (excludes.items) |e| allocator.free(e);
  779. excludes.deinit(allocator);
  780. }
  781. if (argc >= 2) {
  782. switch (argv[1].type) {
  783. .hl_null => {},
  784. .hl_string => {
  785. const sv = argv[1].data.string;
  786. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  787. },
  788. .hl_object => {
  789. const obj_in = argv[1].data.object;
  790. for (obj_in.fields[0..obj_in.field_count]) |field| {
  791. if (field.value.type == .hl_null) continue;
  792. if (field.value.type != .hl_string) return api.makeError("hl:fs: watch(path, exclude): every exclusion must be a path string");
  793. const sv = field.value.data.string;
  794. if (!appendExclusion(&excludes, sv.ptr[0..sv.len])) return api.makeError("hl:fs: out of memory");
  795. }
  796. },
  797. else => return api.makeError("hl:fs: watch(path, exclude): exclude is a path string or a list of path strings"),
  798. }
  799. }
  800. const rc = linux.inotify_init1(linux.IN.NONBLOCK);
  801. const ifd: i32 = @intCast(@as(isize, @bitCast(rc)));
  802. if (ifd < 0) return api.makeError("hl:fs: watch: inotify unavailable");
  803. addWatchesRecursive(ifd, path, 0, excludes.items);
  804. const state = allocator.create(WatchState) catch return api.makeError("hl:fs: out of memory");
  805. state.* = .{ .ifd = ifd };
  806. const iter = allocator.create(HlIterator) catch return api.makeError("hl:fs: out of memory");
  807. iter.* = .{
  808. .context = @ptrCast(state),
  809. .next_fn = &watchTryNext, // non-blocking either way — event loop only
  810. .try_next_fn = &watchTryNext,
  811. .deinit_fn = &watchDeinit,
  812. .wake_fd = ifd,
  813. };
  814. return api.makeIterator(iter);
  815. }
  816. fn watchTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  817. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  818. if (st.pos >= st.len) {
  819. const r = linux.read(st.ifd, &st.buf, st.buf.len);
  820. const n: isize = @bitCast(r);
  821. if (n <= 0) return api.makeNull(); // EAGAIN: drained
  822. st.len = @intCast(n);
  823. st.pos = 0;
  824. }
  825. // one inotify_event: wd(i32) mask(u32) cookie(u32) len(u32) name[len]
  826. const base = st.pos;
  827. if (st.len - base < 16) {
  828. st.pos = st.len;
  829. return api.makeNull();
  830. }
  831. const name_len = std.mem.readInt(u32, st.buf[base + 12 ..][0..4], .little);
  832. const name_start = base + 16;
  833. var name: []const u8 = "";
  834. if (name_len > 0 and name_start + name_len <= st.len) {
  835. const raw_name = st.buf[name_start .. name_start + name_len];
  836. name = std.mem.sliceTo(raw_name, 0);
  837. }
  838. st.pos = name_start + name_len;
  839. const fields = allocator.alloc(api.HlField, 1) catch return api.makeNull();
  840. const name_copy = allocator.dupe(u8, name) catch {
  841. allocator.free(fields);
  842. return api.makeNull();
  843. };
  844. fields[0] = .{ .key = hlStr("name"), .value = api.makeString(name_copy) };
  845. const obj = allocator.create(api.HlObject) catch {
  846. allocator.free(name_copy);
  847. allocator.free(fields);
  848. return api.makeNull();
  849. };
  850. obj.* = .{ .fields = fields.ptr, .field_count = 1, .deinit_fn = &watchEventDeinit };
  851. return api.makeObject(obj);
  852. }
  853. /// An event is the loader's to copy and ours to free (the emit soak, 2026-10-02): with
  854. /// no deinit, every inotify event of the dev watcher — each write a db makes under the
  855. /// watched root — kept its name, its field and its object for good.
  856. fn watchEventDeinit(obj: *api.HlObject) callconv(.c) void {
  857. const sv = obj.fields[0].value.data.string;
  858. allocator.free(@constCast(sv.ptr)[0..sv.len]);
  859. allocator.free(obj.fields[0..obj.field_count]);
  860. allocator.destroy(obj);
  861. }
  862. fn watchDeinit(ctx: ?*anyopaque) callconv(.c) void {
  863. const st: *WatchState = @ptrCast(@alignCast(ctx orelse return));
  864. _ = linux.close(st.ifd);
  865. allocator.destroy(st);
  866. }
  867. // =========================================================================
  868. // THE WRITE SURFACE (2026-08-28)
  869. //
  870. // hl:fs was READ-ONLY until this block: file, readFile, listDir, exists,
  871. // watch. It could report a file's `chmod` and never set one. Session
  872. // persistence is the first thing in this tree that has to put bytes on a
  873. // disk, and the rule when the framework can do something the language
  874. // cannot is that the LANGUAGE is missing it — so the capability lands here,
  875. // as an ordinary hl:fs surface any program can use, not as a private hook
  876. // the session store reaches through.
  877. //
  878. // Three calls, and the shape of each is a decision:
  879. //
  880. // writeFile(path, contents, mode?) ATOMIC. Writes a sibling temp file,
  881. // fsyncs it, then rename()s it over the target — so a reader sees
  882. // either the whole previous file or the whole new one, never a torn
  883. // one. A half-written session file that revives as garbage is a
  884. // silent logout, and the crash that produces it is exactly the crash
  885. // nobody can reproduce. rename(2) within one directory is atomic on
  886. // every filesystem Linux ships; that is the whole reason the temp
  887. // file is a SIBLING rather than in /tmp (a cross-device rename fails).
  888. // mkDir(path, mode?) recursive, and succeeds when the
  889. // directory is already there — the caller wants it to exist, not to
  890. // be the one who created it.
  891. // remove(path) IDEMPOTENT: true when the path is
  892. // gone on return, including when it was already gone. A sweep
  893. // deleting an expired file must not fail because something else
  894. // deleted it first.
  895. //
  896. // MODES ARE EXPLICIT AND DEFAULT TIGHT. hybrilior passes no mode anywhere,
  897. // so its session files land at whatever the umask says — 0644 on a shared
  898. // box, i.e. every session on the machine readable by every other tenant.
  899. // Here the default is 0600 for a file and 0700 for a directory, and a
  900. // caller who wants them looser has to say so. This is not the kind of bug
  901. // that shows up in a test; it shows up in someone else's logs.
  902. // =========================================================================
  903. fn makeWriteError(op: []const u8, path: []const u8, errno: usize) api.HlValue {
  904. 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
  905. return api.makeError("fs: write failed");
  906. var v = api.makeError(msg);
  907. v.deinit_fn = &errDeinit;
  908. return v;
  909. }
  910. /// mkdir every missing component of `path`. Returns 0, or the errno of the
  911. /// first component that could not be created for a reason other than "it is
  912. /// already there".
  913. fn mkdirRecursive(path: []const u8, mode: u32) usize {
  914. if (path.len == 0) return 0;
  915. const buf = allocator.dupeZ(u8, path) catch return 12; // ENOMEM
  916. defer allocator.free(buf);
  917. // Walk the separators left to right, creating each prefix in turn. Index
  918. // 0 is skipped so a leading '/' is never itself a component to create.
  919. var i: usize = 1;
  920. while (i <= buf.len) : (i += 1) {
  921. const at_end = i == buf.len;
  922. if (!at_end and buf[i] != '/') continue;
  923. if (!at_end) buf[i] = 0;
  924. const rc: isize = @bitCast(linux.mkdir(buf.ptr, mode));
  925. if (!at_end) buf[i] = '/';
  926. if (rc < 0) {
  927. const errno: usize = @intCast(-rc);
  928. // EEXIST is the success case: the caller wants it to exist.
  929. if (errno != 17) return errno;
  930. }
  931. }
  932. return 0;
  933. }
  934. export fn hl_fs_mk_dir(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  935. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.mkDir expects a string path");
  936. const path_str = argv[0].data.string;
  937. const path = path_str.ptr[0..path_str.len];
  938. var mode: u32 = 0o700;
  939. if (argc >= 2 and argv[1].type == .hl_number) mode = @intFromFloat(argv[1].data.number);
  940. const resolved = resolvePath(path) orelse return api.makeError("fs.mkDir: out of memory");
  941. defer allocator.free(resolved);
  942. const errno = mkdirRecursive(resolved, mode);
  943. if (errno != 0) return makeWriteError("fs.mkDir", path, errno);
  944. return api.makeBool(true);
  945. }
  946. const write_usage = "fs.writeFile expects (String path, String or Bytes contents, Number mode?)";
  947. export fn hl_fs_write_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  948. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  949. return api.makeError(write_usage);
  950. }
  951. const path_str = argv[0].data.string;
  952. const body_str = argv[1].data.string;
  953. return writeWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  954. }
  955. /// hl_fs_write_file_hex(path, hex, mode?) — writeFile with a Bytes (ticket
  956. /// #88): a Bytes crosses the plugin boundary as its hex text (the ABI has no
  957. /// Bytes, as hl:proc's write_hex says), is decoded here and written raw.
  958. export fn hl_fs_write_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  959. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  960. return api.makeError(write_usage);
  961. }
  962. const path_str = argv[0].data.string;
  963. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  964. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.writeFile: out of memory");
  965. defer allocator.free(raw);
  966. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.writeFile: not a Bytes");
  967. return writeWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  968. }
  969. fn modeArg(argc: u32, argv: [*]const HlValue) u32 {
  970. if (argc >= 3 and argv[2].type == .hl_number) return @intFromFloat(argv[2].data.number);
  971. return 0o600;
  972. }
  973. fn writeWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  974. const resolved = resolvePath(path) orelse return api.makeError("fs.writeFile: out of memory");
  975. defer allocator.free(resolved);
  976. // The temp name is a SIBLING (see the block comment): rename(2) is only
  977. // atomic within one filesystem, and /tmp is routinely a different one.
  978. // The pid keeps two processes writing the same path off each other's temp
  979. // file; the rename itself settles who wins the target.
  980. const pid = linux.getpid();
  981. const tmp = std.fmt.allocPrintSentinel(allocator, "{s}.hltmp{d}", .{ resolved, pid }, 0) catch
  982. return api.makeError("fs.writeFile: out of memory");
  983. defer allocator.free(tmp);
  984. const rc = linuxOpenRc(tmp.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, mode);
  985. if (rc < 0) return makeWriteError("fs.writeFile", path, @intCast(-rc));
  986. const fd: i32 = @intCast(rc);
  987. var wrote: usize = 0;
  988. while (wrote < body.len) {
  989. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  990. if (n <= 0) {
  991. _ = linux.close(fd);
  992. _ = linux.unlink(tmp.ptr);
  993. return makeWriteError("fs.writeFile", path, if (n < 0) @intCast(-n) else 5);
  994. }
  995. wrote += @intCast(n);
  996. }
  997. // fsync BEFORE the rename, or the rename can land while the bytes are
  998. // still only in the page cache — a power cut then leaves an EMPTY file
  999. // where a complete one used to be, which is worse than either outcome.
  1000. _ = linux.fsync(fd);
  1001. _ = linux.close(fd);
  1002. // O_CREAT honours the mode only through the umask; say it outright so a
  1003. // 0600 request is 0600 whatever the process umask happens to be.
  1004. _ = linux.chmod(tmp.ptr, mode);
  1005. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.writeFile: out of memory");
  1006. defer allocator.free(path_z);
  1007. const ren: isize = @bitCast(linux.rename(tmp.ptr, path_z.ptr));
  1008. if (ren < 0) {
  1009. _ = linux.unlink(tmp.ptr);
  1010. return makeWriteError("fs.writeFile", path, @intCast(-ren));
  1011. }
  1012. return api.makeBool(true);
  1013. }
  1014. const append_usage = "fs.appendFile expects (String path, String or Bytes contents, Number mode?)";
  1015. export fn hl_fs_append_file(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1016. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1017. return api.makeError(append_usage);
  1018. }
  1019. const path_str = argv[0].data.string;
  1020. const body_str = argv[1].data.string;
  1021. return appendWhole(path_str.ptr[0..path_str.len], body_str.ptr[0..body_str.len], modeArg(argc, argv));
  1022. }
  1023. /// hl_fs_append_file_hex(path, hex, mode?) — appendFile with a Bytes (ticket
  1024. /// #88), the same hex-text crossing writeFile's hex sibling uses.
  1025. export fn hl_fs_append_file_hex(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1026. if (argc < 2 or argv[0].type != .hl_string or argv[1].type != .hl_string) {
  1027. return api.makeError(append_usage);
  1028. }
  1029. const path_str = argv[0].data.string;
  1030. const hex = argv[1].data.string.ptr[0..argv[1].data.string.len];
  1031. const raw = allocator.alloc(u8, hex.len / 2) catch return api.makeError("fs.appendFile: out of memory");
  1032. defer allocator.free(raw);
  1033. _ = std.fmt.hexToBytes(raw, hex) catch return api.makeError("fs.appendFile: not a Bytes");
  1034. return appendWhole(path_str.ptr[0..path_str.len], raw, modeArg(argc, argv));
  1035. }
  1036. /// APPEND, NOT ATOMIC BY RENAME (writeFile's block comment above): an append
  1037. /// MUTATES the file that is already there, so there is no whole "old" or
  1038. /// "new" version to swap in — O_APPEND gives a narrower guarantee instead.
  1039. /// The kernel positions a single write() at the file's CURRENT end and
  1040. /// performs it as one operation, so two processes each appending a line never
  1041. /// interleave their bytes mid-line and a reader never sees a torn append —
  1042. /// which is why this is ONE write() of the whole body where writeFile's is
  1043. /// (short-write retries aside). The file is created at `mode` (default 0600,
  1044. /// same default as writeFile) if it is not there yet; O_APPEND on an existing
  1045. /// file leaves its mode untouched, same as any other open of it.
  1046. fn appendWhole(path: []const u8, body: []const u8, mode: u32) HlValue {
  1047. const resolved = resolvePath(path) orelse return api.makeError("fs.appendFile: out of memory");
  1048. defer allocator.free(resolved);
  1049. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.appendFile: out of memory");
  1050. defer allocator.free(path_z);
  1051. const rc = linuxOpenRc(path_z.ptr, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, mode);
  1052. if (rc < 0) return makeWriteError("fs.appendFile", path, @intCast(-rc));
  1053. const fd: i32 = @intCast(rc);
  1054. defer _ = linux.close(fd);
  1055. var wrote: usize = 0;
  1056. while (wrote < body.len) {
  1057. const n: isize = @bitCast(linux.write(fd, body.ptr + wrote, body.len - wrote));
  1058. if (n <= 0) {
  1059. return makeWriteError("fs.appendFile", path, if (n < 0) @intCast(-n) else 5);
  1060. }
  1061. wrote += @intCast(n);
  1062. }
  1063. return api.makeBool(true);
  1064. }
  1065. export fn hl_fs_remove(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1066. if (argc < 1 or argv[0].type != .hl_string) return api.makeError("fs.remove expects a string path");
  1067. const path_str = argv[0].data.string;
  1068. const path = path_str.ptr[0..path_str.len];
  1069. const resolved = resolvePath(path) orelse return api.makeError("fs.remove: out of memory");
  1070. defer allocator.free(resolved);
  1071. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeError("fs.remove: out of memory");
  1072. defer allocator.free(path_z);
  1073. var rc: isize = @bitCast(linux.unlink(path_z.ptr));
  1074. // an empty directory goes too (EISDIR): hybriel.hl's scratch directories
  1075. // (mission 326 rung 12), with no `rmdir` to shell out to
  1076. if (rc == -21) rc = @bitCast(linux.rmdir(path_z.ptr));
  1077. if (rc < 0) {
  1078. const errno: usize = @intCast(-rc);
  1079. // ENOENT is success: the caller asked for the path to be gone.
  1080. if (errno == 2) return api.makeBool(true);
  1081. return makeWriteError("fs.remove", path, errno);
  1082. }
  1083. return api.makeBool(true);
  1084. }
  1085. /// realPath(path) → the canonical absolute path (symlinks resolved, `.`/`..`
  1086. /// folded; realpath(3)), or null when the path is not there or cannot be
  1087. /// resolved. `/proc/self/exe` answers the running binary without a shell.
  1088. export fn hl_fs_real_path(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1089. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  1090. const path_str = argv[0].data.string;
  1091. const resolved = resolvePath(path_str.ptr[0..path_str.len]) orelse return api.makeNull();
  1092. defer allocator.free(resolved);
  1093. traceAccess('e', resolved);
  1094. const path_z = allocator.dupeZ(u8, resolved) catch return api.makeNull();
  1095. defer allocator.free(path_z);
  1096. var buf: [std.posix.PATH_MAX]u8 = undefined;
  1097. const out = std.c.realpath(path_z.ptr, &buf) orelse return api.makeNull();
  1098. const text = allocator.dupe(u8, std.mem.span(out)) catch return api.makeNull();
  1099. var result = api.makeString(text);
  1100. result.deinit_fn = &readFileDeinit;
  1101. return result;
  1102. }

Branches

Latest commits

  • 359c79f7gitoria 010: re-vendor Hybriel master f9614007 (plugins whole, bin/ git-ignored)mre
  • 6bd7fb3cgitoria 009: theme re-copied from layouts 76f99f6 (menu marks the current page), current = true on the menu item, e2e marker checks, reportmre
  • 44de915cidentkit: refuse a taken ident port, cold-start deadline, abort on dead ident, clear no-code error (as notes)mre
  • 2bf5343egitoria 007: theme re-copied from layouts dbe3de7 (44 px taps), redundant tap overrides dropped, crumbs class, real-browser walk test, reportmre
  • 18843648deploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the script silently (grep under pipefail) — print check-theme's summary, as layouts doesmre
  • e6dff0cbgitoria#23: report 005, STATUS, LOGmre
  • 7f992d62gitoria#23: phone first on the shared theme — brand, branch and pull links 44 px, readme code 14 px; gate block "phone first" (15 pages at 390 + the three dropdowns, fails 20 on old), dropdown-aware login/logout clicks, check-theme in GATESmre
  • a2a840a5gitoria#23 WIP (quota stop): theme from layouts, styles inherit it, shell on the theme's header/menus/sidebar, phone measurement script; gates not runmre
  • 12b665b0mission brief 005mre
  • b680c483Revert "gitoria#22: RepoTabs wrapping component for the repo tabs (active tab, no content for a missing repo)"mre
  • 4fda244fgitoria#22: RepoTabs wrapping component for the repo tabs (active tab, no content for a missing repo)mre
  • 0fd5e280mission brief 004mre
  • e1d425e7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • e59ff114deploy.sh: wait up to DEPLOY_URL_WAIT (120 s) for 200 after the restart, as the other apps (cold compile, hybriel#148)mre
  • bcafcceb003: compose cache volume + tmpfs /tmp, gate start waits 120 s, report/LOG/STATUSmre
  • bed3f2d5Re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ is git-ignored)mre
  • 3207e128mission brief 003mre
  • 18ab71fbtests/ticketskit: wait up to 120 s for tickets (native Hybriel cold compile ~25 s, hybriel#148)mre
  • 4fffa966docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 4f47843egate: ticket links use the tickets short URL (/<slug>/<n>, tickets#25)mre