diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 823dd4c..188285d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,11 @@ jobs: - uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1 with: version: 0.17.1 + # The decimal digit table is pinned to Unicode 16.0.0, the unicodedata + # of Python 3.14; the parity test skips its comparison under another. + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.14" - run: zig fmt --check build.zig build.zig.zon src tests - run: zig build test --summary all - name: parity with python's json and text calls @@ -43,6 +48,14 @@ jobs: fi zig build fs-lock-parity-probe python3 tests/test_fs_lock_parity.py + - name: parity with python's tempfile.gettempdir + run: | + if ! command -v python3 >/dev/null 2>&1; then + echo "python3 not found, skipping the parity test" + exit 0 + fi + zig build tempdir-probe + python3 tests/test_gettempdir_parity.py - name: no site names in the tree run: | ! git grep -nIiE 'snellius|surf\.nl|/gpfs/|/projects/0|rg\.terra|scratch-shared' -- . ':!.github/workflows/ci.yml' diff --git a/build.zig b/build.zig index 360fddf..1080c5c 100644 --- a/build.zig +++ b/build.zig @@ -57,6 +57,27 @@ pub fn build(b: *std.Build) void { const install_ap_probe = b.addInstallArtifact(ap_probe, .{}); b.step("argparse-parity-probe", "Build the argparse parity probe").dependOn(&install_ap_probe.step); + // Rewrite src/pytext_nd.zig from the Python on PATH, which moves the + // table's Unicode pin to that Python's. The library never needs Python + // to build; tests/test_json_pytext_parity.py fails when the file no + // longer matches unicodedata of the Unicode version it is pinned to. + const gen_nd = b.addSystemCommand(&.{ "python3", "tools/gen_pytext_nd.py" }); + const update_nd = b.addUpdateSourceFiles(); + update_nd.addCopyFileToSource(gen_nd.captureStdOut(.{}), "src/pytext_nd.zig"); + b.step("gen-pytext-nd", "Regenerate src/pytext_nd.zig from unicodedata").dependOn(&update_nd.step); + + // The temporary directory probe, whose output + // tests/test_gettempdir_parity.py compares with tempfile.gettempdir. + const tempdir_mod = b.createModule(.{ + .root_source_file = b.path("tests/tempdir_probe.zig"), + .target = target, + .optimize = optimize, + }); + tempdir_mod.addImport("zig_common", mod); + const tempdir_probe = b.addExecutable(.{ .name = "tempdir_probe", .root_module = tempdir_mod }); + const install_tempdir = b.addInstallArtifact(tempdir_probe, .{}); + b.step("tempdir-probe", "Build the tempfile parity probe").dependOn(&install_tempdir.step); + // The API reference from the doc comments, into /docs. const lib = b.addLibrary(.{ .name = "zig_common", .root_module = mod }); const docs = b.addInstallDirectory(.{ diff --git a/changelog.d/+fsx-gettempdir.feature.md b/changelog.d/+fsx-gettempdir.feature.md new file mode 100644 index 0000000..985c6a7 --- /dev/null +++ b/changelog.d/+fsx-gettempdir.feature.md @@ -0,0 +1 @@ +Add `fsx.TempDir`, a port of `tempfile.gettempdir`. It probes the candidates from the environment first and the system directories after. Each probe is a file write, as in Python. The answer is made absolute and normalized, and it is kept for later calls. A failure gives the text of Python's FileNotFoundError, which lists the candidates. The `TempDir` owns the answer and the message, and `deinit` frees them. `fsx.tempDirCandidates` returns the list alone, and `fsx.freeTempDirCandidates` frees it. diff --git a/changelog.d/+fsx-mkdtemp-report.feature.md b/changelog.d/+fsx-mkdtemp-report.feature.md new file mode 100644 index 0000000..2b3cc45 --- /dev/null +++ b/changelog.d/+fsx-mkdtemp-report.feature.md @@ -0,0 +1 @@ +`fsx.mkdtempReport` is `mkdtemp` with a `Why`. A failed create reports the OSError text that Python gives, with the whole path it tried, random name included, in one repr. diff --git a/changelog.d/+fsx-mkstemp.feature.md b/changelog.d/+fsx-mkstemp.feature.md new file mode 100644 index 0000000..dbb6558 --- /dev/null +++ b/changelog.d/+fsx-mkstemp.feature.md @@ -0,0 +1 @@ +Add `fsx.mkstemp` to create a private `0600` file with a random suffix under a given directory. The file is open for reading and writing. As in Python, a relative directory is made absolute, so the path is absolute. A refused open reports its path, so the caller can format the error as Python does. diff --git a/changelog.d/+pytext-decimal-digits.feature.md b/changelog.d/+pytext-decimal-digits.feature.md new file mode 100644 index 0000000..f82b83f --- /dev/null +++ b/changelog.d/+pytext-decimal-digits.feature.md @@ -0,0 +1 @@ +Add `pytext.decimalDigit` and `pytext.decimalToAscii`. They read the decimal digits of every script as Python's `float()` and `int()` do. A generator script under tools builds the table from `unicodedata`, and the table is pinned to Unicode 16.0.0, the data of Python 3.14. diff --git a/docs/orgmode/explanation/python-compatibility.org b/docs/orgmode/explanation/python-compatibility.org index 40f23ea..4c58475 100644 --- a/docs/orgmode/explanation/python-compatibility.org +++ b/docs/orgmode/explanation/python-compatibility.org @@ -27,6 +27,8 @@ A cache entry the other build cannot read is a miss on every task, and a journal Text stays bytes, read as Python reads them. A Python tool decodes a byte string from the system with surrogateescape, so a byte that is not UTF-8 becomes one character, U+DC80 to U+DCFF, which encodes back to the same byte. [[zig:zig_common.pytext.nextChar]] reads a byte string as that decoder does, and [[zig:zig_common.pytext.pyStrip]], [[zig:zig_common.pytext.pySplit]], [[zig:zig_common.pytext.shellQuote]] and [[zig:zig_common.json.pyTextLess]], Python's string order, work on those characters. +[[zig:zig_common.pytext.decimalToAscii]] writes the decimal digits of any script as ASCII digits, as =float()= and =int()= read their text, from a table that =tools/gen_pytext_nd.py= generates from =unicodedata=. +The table is pinned to Unicode 16.0.0, the data of Python 3.14, and its parity test compares it only under a Python with that data. JSON strings come in the two encodings the tools used: diff --git a/docs/orgmode/reference/api.org b/docs/orgmode/reference/api.org index 7bafcc4..15fa015 100644 --- a/docs/orgmode/reference/api.org +++ b/docs/orgmode/reference/api.org @@ -157,6 +157,8 @@ Error sets: [[zig:zig_common.json.ParseError]], [[zig:zig_common.json.DecodeErro | [[zig:zig_common.pytext.decodeReplace]]| =Allocator.Error= | | [[zig:zig_common.pytext.pyWhitespace]] | none | | [[zig:zig_common.pytext.pyStrip]] | none | +| [[zig:zig_common.pytext.decimalDigit]] | none | +| [[zig:zig_common.pytext.decimalToAscii]]| =Allocator.Error= | | [[zig:zig_common.pytext.pySplit]] | =Allocator.Error= | | [[zig:zig_common.pytext.shellQuote]] | =Allocator.Error= | | [[zig:zig_common.pytext.reprStr]] | =Allocator.Error= | diff --git a/src/fsx.zig b/src/fsx.zig index 5ba7900..3a98713 100644 --- a/src/fsx.zig +++ b/src/fsx.zig @@ -3,6 +3,8 @@ const std = @import("std"); const linux = std.os.linux; const sys = @import("sys.zig"); +const atomic = @import("atomic.zig"); +const pytext = @import("pytext.zig"); const Allocator = std.mem.Allocator; /// A file descriptor, as `sys.fd_t`. @@ -610,18 +612,49 @@ pub fn replaceContents(gpa: Allocator, dir: fd_t, name: []const u8, bytes: []con done = true; } +/// Eight random characters from `a-z`, `0-9` and `_`, the alphabet of +/// Python's `tempfile`. +fn randomName() Error![8]u8 { + const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789_"; + var rnd: [8]u8 = undefined; + // A name from bytes getrandom did not fill would not be random. + const got = try sys.call(linux.getrandom, .{ &rnd, rnd.len, 0 }); + if (got != rnd.len) return error.Unexpected; + for (&rnd) |*b| b.* = alphabet[b.* % alphabet.len]; + return rnd; +} + /// Create a private 0700 directory `{dir}/{prefix}XXXXXXXX` with a random /// suffix, retrying on `error.Exists`, and return its path allocated from /// `gpa`. The caller owns the returned slice. pub fn mkdtemp(gpa: Allocator, dir: []const u8, prefix: []const u8) (Error || Allocator.Error)![]u8 { - const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789_"; + var why: atomic.Why = .{}; + defer why.deinit(gpa); + return mkdtempReport(gpa, dir, prefix, &why); +} + +/// mkdtemp that names the directory it failed in: on failure `why` holds +/// the OSError text Python gives, `pytext.osError` of the path. When the +/// failure is the create itself, the path is the directory joined with the +/// name it tried, random part included, in one repr as Python writes it. +pub fn mkdtempReport(gpa: Allocator, dir: []const u8, prefix: []const u8, why: *atomic.Why) (Error || Allocator.Error)![]u8 { + return mkdtempReportInner(gpa, dir, prefix, why) catch |err| { + if (why.msg.len == 0) reportMkError(gpa, why, err, dir, null); + return err; + }; +} + +fn reportMkError(gpa: Allocator, why: *atomic.Why, err: anyerror, dir: []const u8, name: ?[]const u8) void { + why.deinit(gpa); + const path = if (name) |n| std.fs.path.join(gpa, &.{ dir, n }) catch return else dir; + defer if (name != null) gpa.free(path); + why.msg = pytext.osError(gpa, err, path) catch return; +} + +fn mkdtempReportInner(gpa: Allocator, dir: []const u8, prefix: []const u8, why: *atomic.Why) (Error || Allocator.Error)![]u8 { var tries: usize = 0; while (tries < 100) : (tries += 1) { - var rnd: [8]u8 = undefined; - // A name from bytes getrandom did not fill would not be random. - const got = try sys.call(linux.getrandom, .{ &rnd, rnd.len, 0 }); - if (got != rnd.len) return error.Unexpected; - for (&rnd) |*b| b.* = alphabet[b.* % alphabet.len]; + const rnd = try randomName(); const name = try std.fmt.allocPrint(gpa, "{s}{s}", .{ prefix, rnd }); defer gpa.free(name); const path = try std.fs.path.join(gpa, &.{ dir, name }); @@ -633,7 +666,10 @@ pub fn mkdtemp(gpa: Allocator, dir: []const u8, prefix: []const u8) (Error || Al gpa.free(path); continue; }, - else => return err, + else => { + reportMkError(gpa, why, err, dir, name); + return err; + }, }; return path; } @@ -647,6 +683,62 @@ test "selfExe names this program as a readable regular file" { try std.testing.expect(st.isReg()); } +/// Fail unless `msg` is `pytext.osError` of `err` and the path a create +/// tried, `dir` joined with `prefix` and eight characters of the random +/// alphabet. Those characters need no escape and do not change the quote +/// repr picks, so they are the eight bytes before the closing quote. +fn expectTriedPath(gpa: Allocator, msg: []const u8, err: anyerror, dir: []const u8, prefix: []const u8) !void { + try std.testing.expect(msg.len > 9); + const rnd = msg[msg.len - 9 .. msg.len - 1]; + for (rnd) |b| try std.testing.expect(std.ascii.isLower(b) or std.ascii.isDigit(b) or b == '_'); + const name = try std.mem.concat(gpa, u8, &.{ prefix, rnd }); + defer gpa.free(name); + const tried = try std.fs.path.join(gpa, &.{ dir, name }); + defer gpa.free(tried); + const want = try pytext.osError(gpa, err, tried); + defer gpa.free(want); + try std.testing.expectEqualStrings(want, msg); +} + +test "mkdtempReport names the path a failed create tried" { + const gpa = std.testing.allocator; + var cwd_buf: [sys.path_max]u8 = undefined; + const here = try realpath(cwd, ".", &cwd_buf); + var pb: [sys.path_max]u8 = undefined; + const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-mkdtemp-report-{d}", .{ here, linux.getpid() }); + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(cwd, (try sys.z(&zb, base)).ptr, 0o700); + defer sys.unlinkat(cwd, sys.z(&zb, base) catch "", linux.AT.REMOVEDIR) catch {}; + + var why: atomic.Why = .{}; + defer why.deinit(gpa); + // a missing directory: the whole path the create tried is in one repr + const missing = try std.fmt.allocPrint(gpa, "{s}/missing", .{base}); + defer gpa.free(missing); + try std.testing.expectError(error.NotFound, mkdtempReport(gpa, missing, "pre-", &why)); + try expectTriedPath(gpa, why.msg, error.NotFound, missing, "pre-"); + + // a quote in the directory makes repr pick the other quote for all of it + const quoted = try std.fmt.allocPrint(gpa, "{s}/it's", .{base}); + defer gpa.free(quoted); + try std.testing.expectError(error.NotFound, mkdtempReport(gpa, quoted, "pre-", &why)); + try std.testing.expect(std.mem.endsWith(u8, why.msg, "\"")); + try expectTriedPath(gpa, why.msg, error.NotFound, quoted, "pre-"); + + // a file in the parent's place: ENOTDIR's errno text, the same path + const blocker = try std.fmt.allocPrint(gpa, "{s}/blocker", .{base}); + defer gpa.free(blocker); + const fd = try sys.openat(cwd, blocker, .{ .ACCMODE = .WRONLY, .CREAT = true }, 0o644); + sys.writeAll(fd, "x") catch {}; + sys.close(fd); + var zb2: [sys.path_max:0]u8 = undefined; + defer sys.unlinkat(cwd, sys.z(&zb2, blocker) catch "", 0) catch {}; + const under = try std.fmt.allocPrint(gpa, "{s}/blocker/sub", .{base}); + defer gpa.free(under); + try std.testing.expectError(error.NotDir, mkdtempReport(gpa, under, "pre-", &why)); + try expectTriedPath(gpa, why.msg, error.NotDir, under, "pre-"); +} + test "mkdtemp creates private 0700 directories with distinct names" { const gpa = std.testing.allocator; var cwd_buf: [sys.path_max]u8 = undefined; @@ -681,6 +773,369 @@ test "mkdtemp creates private 0700 directories with distinct names" { try std.testing.expectError(error.NotFound, mkdtemp(gpa, missing, "pre-")); } +/// A file `mkstemp` made. +pub const TempFile = struct { + /// Open for reading and writing, close-on-exec. + fd: fd_t, + /// The path, allocated from the `gpa` given to `mkstemp`. + path: []u8, +}; + +/// `tempfile.mkstemp(prefix=prefix, dir=dir)`: a new file +/// `{dir}/{prefix}XXXXXXXX` with a random suffix, mode 0600, opened for +/// reading and writing without following a link. Like Python, it makes +/// `dir` absolute with `absPath` first, so the path is absolute for a +/// relative `dir` too. Python tries 10000 names and goes on only after a +/// name that exists. When the open fails with another error, `failed` +/// receives the path that was refused, for the caller to format with +/// `pytext.osError`, as Python's error names it. It is null when no name +/// was tried or when every name existed. +pub fn mkstemp(gpa: Allocator, dir: []const u8, prefix: []const u8, failed: *?[]u8) (Error || Allocator.Error)!TempFile { + failed.* = null; + const abs = try absPath(gpa, dir); + defer gpa.free(abs); + var tries: usize = 0; + while (tries < 10000) : (tries += 1) { + const rnd = try randomName(); + const name = try std.fmt.allocPrint(gpa, "{s}{s}", .{ prefix, rnd }); + defer gpa.free(name); + const path = try std.fs.path.join(gpa, &.{ abs, name }); + const fd = sys.openat(cwd, path, .{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true, .NOFOLLOW = true, .CLOEXEC = true }, 0o600) catch |err| switch (err) { + error.Exists => { + gpa.free(path); + continue; + }, + else => { + failed.* = path; + return err; + }, + }; + return .{ .fd = fd, .path = path }; + } + return error.Exists; +} + +test "mkstemp makes a private file and names the path it was refused" { + const gpa = std.testing.allocator; + var cwd_buf: [sys.path_max]u8 = undefined; + const here = try realpath(cwd, ".", &cwd_buf); + var pb: [sys.path_max]u8 = undefined; + const base = try std.fmt.bufPrint(&pb, "{s}/.zig-cache/zig-common-mkstemp-{d}", .{ here, linux.getpid() }); + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(cwd, (try sys.z(&zb, base)).ptr, 0o700); + defer deleteTree(gpa, cwd, base) catch {}; + + var failed: ?[]u8 = null; + const made = try mkstemp(gpa, base, "pre-", &failed); + defer gpa.free(made.path); + defer sys.close(made.fd); + try std.testing.expect(failed == null); + const expected_prefix = try std.fmt.allocPrint(gpa, "{s}/pre-", .{base}); + defer gpa.free(expected_prefix); + try std.testing.expect(std.mem.startsWith(u8, made.path, expected_prefix)); + try std.testing.expectEqual(expected_prefix.len + 8, made.path.len); + const st = try fstat(made.fd); + try std.testing.expect(st.isReg()); + try std.testing.expectEqual(@as(u32, 0o600), st.perm()); + try sys.writeAll(made.fd, "x"); + + const missing = try std.fmt.allocPrint(gpa, "{s}/missing", .{base}); + defer gpa.free(missing); + try std.testing.expectError(error.NotFound, mkstemp(gpa, missing, "pre-", &failed)); + defer if (failed) |p| gpa.free(p); + const path = failed orelse return error.TestUnexpectedResult; + try std.testing.expect(std.mem.startsWith(u8, path, missing)); + try std.testing.expectEqual(missing.len + "/pre-".len + 8, path.len); +} + +test "mkstemp makes a relative directory absolute as Python does" { + const gpa = std.testing.allocator; + var cwd_buf: [sys.path_max]u8 = undefined; + const here = try realpath(cwd, ".", &cwd_buf); + var rb: [sys.path_max]u8 = undefined; + const rel = try std.fmt.bufPrint(&rb, ".zig-cache/zig-common-mkstemp-rel-{d}", .{linux.getpid()}); + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(cwd, (try sys.z(&zb, rel)).ptr, 0o700); + defer deleteTree(gpa, cwd, rel) catch {}; + const abs = try std.fs.path.join(gpa, &.{ here, rel }); + defer gpa.free(abs); + + var failed: ?[]u8 = null; + const dotted = try std.fmt.allocPrint(gpa, "./{s}/../{s}", .{ rel, std.fs.path.basename(rel) }); + defer gpa.free(dotted); + const made = try mkstemp(gpa, dotted, "pre-", &failed); + defer gpa.free(made.path); + defer sys.close(made.fd); + const expected_prefix = try std.fmt.allocPrint(gpa, "{s}/pre-", .{abs}); + defer gpa.free(expected_prefix); + try std.testing.expect(std.mem.startsWith(u8, made.path, expected_prefix)); + try std.testing.expectEqual(expected_prefix.len + 8, made.path.len); + + const missing = try std.fmt.allocPrint(gpa, "{s}/missing", .{rel}); + defer gpa.free(missing); + try std.testing.expectError(error.NotFound, mkstemp(gpa, missing, "pre-", &failed)); + defer if (failed) |p| gpa.free(p); + const refused = failed orelse return error.TestUnexpectedResult; + const missing_prefix = try std.fmt.allocPrint(gpa, "{s}/missing/pre-", .{abs}); + defer gpa.free(missing_prefix); + try std.testing.expect(std.mem.startsWith(u8, refused, missing_prefix)); + try std.testing.expectEqual(missing_prefix.len + 8, refused.len); +} + +/// The directories `tempfile.gettempdir` tries, in its order: the values of +/// TMPDIR, TEMP and TMP that are set and not empty, then `/tmp`, +/// `/var/tmp` and `/usr/tmp`, then the working directory, or "." when that +/// cannot be read. `env` is anything with `get(name) ?[]const u8`, such as +/// `Env` or a string map. The strings are as given, not made absolute. The +/// last one, the working directory, is a copy allocated from `gpa`; +/// `freeTempDirCandidates` frees it with the list. +pub fn tempDirCandidates(gpa: Allocator, env: anytype) Allocator.Error![]const []const u8 { + var list: std.ArrayList([]const u8) = .empty; + errdefer list.deinit(gpa); + for ([_][]const u8{ "TMPDIR", "TEMP", "TMP" }) |name| { + const v = env.get(name) orelse continue; + if (v.len > 0) try list.append(gpa, v); + } + try list.appendSlice(gpa, &.{ "/tmp", "/var/tmp", "/usr/tmp" }); + var buf: [sys.path_max]u8 = undefined; + const here = try gpa.dupe(u8, getcwd(&buf) catch "."); + errdefer gpa.free(here); + try list.append(gpa, here); + return list.toOwnedSlice(gpa); +} + +/// Free a list `tempDirCandidates` returned, with the copy at its end. +pub fn freeTempDirCandidates(gpa: Allocator, candidates: []const []const u8) void { + gpa.free(candidates[candidates.len - 1]); + gpa.free(candidates); +} + +/// `os.getcwd()`: the working directory as the kernel names it, which is an +/// error when the directory has been removed. +fn getcwd(buf: *[sys.path_max]u8) Error![]const u8 { + const n = try sys.call(linux.getcwd, .{ buf, buf.len }); + return buf[0..n -| 1]; +} + +/// `tempfile._get_default_tempdir`'s probe of one directory: a new file with +/// a random name, `blat` written to it, closed and removed. Python tries +/// 100 names, goes on only after a name that exists, and gives up on the +/// directory at any other error. A short write is not an error there. +fn tempDirUsable(gpa: Allocator, dir: []const u8) bool { + var tries: usize = 0; + while (tries < 100) : (tries += 1) { + const rnd = randomName() catch return false; + const path = std.fs.path.join(gpa, &.{ dir, &rnd }) catch return false; + defer gpa.free(path); + const fd = sys.openat(cwd, path, .{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true, .NOFOLLOW = true, .CLOEXEC = true }, 0o600) catch |err| switch (err) { + error.Exists => continue, + else => return false, + }; + const wrote = if (sys.call(linux.write, .{ fd, "blat", 4 })) |_| true else |_| false; + sys.close(fd); + sys.unlinkat(cwd, path, 0) catch return false; + return wrote; + } + return false; +} + +/// The directory `_get_default_tempdir` probes for `candidate`, as a copy +/// allocated from `gpa`: "." as it is, any other value made absolute and +/// normalized like `os.path.abspath`. A relative value needs `os.getcwd()`, +/// and Python lets its error out of gettempdir. +fn tempDirPath(gpa: Allocator, candidate: []const u8) (Error || Allocator.Error)![]u8 { + if (std.mem.eql(u8, candidate, ".")) return gpa.dupe(u8, candidate); + if (candidate[0] == '/') return normPath(gpa, candidate); + var buf: [sys.path_max]u8 = undefined; + const here = try getcwd(&buf); + const joined = try std.mem.concat(gpa, u8, &.{ here, "/", candidate }); + defer gpa.free(joined); + return normPath(gpa, joined); +} + +/// `tempfile.gettempdir`: the first of `tempDirCandidates` that takes the +/// probe file, made absolute and normalized like `os.path.abspath`. Python +/// keeps the answer for the life of the process, and so does `path` here: +/// a later call returns it without looking at the environment or the +/// directory again. A failure is not kept; each call tries again. +/// +/// `path` and `message` are allocated from the `gpa` given to `get` and +/// owned by the `TempDir`; `deinit` frees them. Nothing else a call +/// allocates outlives it. +pub const TempDir = struct { + /// The directory once one has been found. + path: ?[]const u8 = null, + /// After `error.NoTempDir`, `str()` of the FileNotFoundError Python + /// raises, "[Errno 2] No usable temporary directory found in [...]", + /// with the candidates as repr writes them, or "[Errno 2] No such file + /// or directory" when a relative value needed a working directory that + /// was removed. Each failed call replaces it. + message: []const u8 = "", + + /// Free `path` and `message` and reset `td`. + pub fn deinit(td: *TempDir, gpa: Allocator) void { + if (td.path) |p| gpa.free(p); + if (td.message.len > 0) gpa.free(td.message); + td.* = .{}; + } + + /// The directory, from the cache or by trying the candidates. + pub fn get(td: *TempDir, gpa: Allocator, env: anytype) error{ NoTempDir, OutOfMemory }![]const u8 { + if (td.path) |p| return p; + const candidates = try tempDirCandidates(gpa, env); + defer freeTempDirCandidates(gpa, candidates); + for (candidates) |candidate| { + const dir = tempDirPath(gpa, candidate) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + else => |e| { + td.setMessage(gpa, try gpa.dupe(u8, sys.describe(e))); + return error.NoTempDir; + }, + }; + if (tempDirUsable(gpa, dir)) { + td.path = dir; + return dir; + } + gpa.free(dir); + } + td.setMessage(gpa, try noTempDirMessage(gpa, candidates)); + return error.NoTempDir; + } + + fn setMessage(td: *TempDir, gpa: Allocator, message: []const u8) void { + if (td.message.len > 0) gpa.free(td.message); + td.message = message; + } +}; + +fn noTempDirMessage(gpa: Allocator, candidates: []const []const u8) Allocator.Error![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + try out.appendSlice(gpa, "[Errno 2] No usable temporary directory found in ["); + for (candidates, 0..) |c, i| { + if (i > 0) try out.appendSlice(gpa, ", "); + try pytext.reprStr(&out, gpa, c); + } + try out.append(gpa, ']'); + return out.toOwnedSlice(gpa); +} + +test "tempDirCandidates follows tempfile's order and skips empty values" { + const gpa = std.testing.allocator; + var env: std.StringHashMapUnmanaged([]const u8) = .empty; + defer env.deinit(gpa); + try env.put(gpa, "TMP", "/m"); + try env.put(gpa, "TMPDIR", "rel/./dir/"); + try env.put(gpa, "TEMP", ""); + const got = try tempDirCandidates(gpa, env); + defer freeTempDirCandidates(gpa, got); + var buf: [sys.path_max]u8 = undefined; + const here = try realpath(cwd, ".", &buf); + const want = [_][]const u8{ "rel/./dir/", "/m", "/tmp", "/var/tmp", "/usr/tmp", here }; + try std.testing.expectEqual(want.len, got.len); + for (want, got) |w, g| try std.testing.expectEqualStrings(w, g); + const bare = try tempDirCandidates(gpa, std.StringHashMapUnmanaged([]const u8).empty); + defer freeTempDirCandidates(gpa, bare); + try std.testing.expectEqual(@as(usize, 4), bare.len); +} + +test "TempDir takes the first usable candidate and keeps it" { + const gpa = std.testing.allocator; + var buf: [sys.path_max]u8 = undefined; + const here = try realpath(cwd, ".", &buf); + var pb: [sys.path_max]u8 = undefined; + const base = try std.fmt.bufPrint(&pb, "{s}/.zig-cache/zig-common-tempdir-{d}", .{ here, linux.getpid() }); + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(cwd, (try sys.z(&zb, base)).ptr, 0o700); + defer deleteTree(gpa, cwd, base) catch {}; + + var env: std.StringHashMapUnmanaged([]const u8) = .empty; + defer env.deinit(gpa); + const unnormalized = try std.fmt.allocPrint(gpa, "{s}/./sub/..//", .{base}); + defer gpa.free(unnormalized); + try env.put(gpa, "TMPDIR", "/nonexistent-zig-common-dir"); + try env.put(gpa, "TEMP", unnormalized); + var td: TempDir = .{}; + defer td.deinit(gpa); + try std.testing.expectEqualStrings(base, try td.get(gpa, env)); + + try env.put(gpa, "TEMP", "/nonexistent-zig-common-dir"); + try std.testing.expectEqualStrings(base, try td.get(gpa, env)); + + var fresh: TempDir = .{}; + defer fresh.deinit(gpa); + const system = try fresh.get(gpa, env); + try std.testing.expect(!std.mem.eql(u8, system, base)); + try std.testing.expect(system[0] == '/'); +} + +test "TempDir frees what its failed calls allocate" { + // std.testing.allocator fails the test on a leak, so each candidate + // that fails, each join of a relative value and each replaced message + // must be freed, and deinit must free what the TempDir keeps. + const gpa = std.testing.allocator; + var env: std.StringHashMapUnmanaged([]const u8) = .empty; + defer env.deinit(gpa); + try env.put(gpa, "TMPDIR", "/nonexistent-zig-common-dir/./x/.."); + try env.put(gpa, "TEMP", "relative-zig-common-missing"); + try env.put(gpa, "TMP", "it's"); + var td: TempDir = .{}; + defer td.deinit(gpa); + + { + // Under a file size limit of 0 with SIGXFSZ ignored, every probe + // write fails with EFBIG, so every candidate fails, twice over. + var lim: linux.rlimit = undefined; + try std.testing.expectEqual(@as(usize, 0), linux.getrlimit(.FSIZE, &lim)); + const ignore: linux.Sigaction = .{ .handler = .{ .handler = linux.SIG.IGN }, .mask = linux.sigemptyset(), .flags = 0 }; + var old: linux.Sigaction = undefined; + _ = linux.sigaction(linux.SIG.XFSZ, &ignore, &old); + defer _ = linux.sigaction(linux.SIG.XFSZ, &old, null); + const zero: linux.rlimit = .{ .cur = 0, .max = lim.max }; + try std.testing.expectEqual(@as(usize, 0), linux.setrlimit(.FSIZE, &zero)); + defer _ = linux.setrlimit(.FSIZE, &lim); + try std.testing.expectError(error.NoTempDir, td.get(gpa, env)); + try std.testing.expectError(error.NoTempDir, td.get(gpa, env)); + } + try std.testing.expect(td.path == null); + try std.testing.expect(std.mem.startsWith(u8, td.message, "[Errno 2] No usable temporary directory found in ['/nonexistent-zig-common-dir/./x/..', 'relative-zig-common-missing', \"it's\", '/tmp', ")); + + { + // A relative value under a removed working directory replaces the + // message with the error of os.getcwd(). + var here_buf: [sys.path_max]u8 = undefined; + const here = try realpath(cwd, ".", &here_buf); + var hz: [sys.path_max:0]u8 = undefined; + const here_z = try sys.z(&hz, here); + var gb: [sys.path_max]u8 = undefined; + const gone = try std.fmt.bufPrint(&gb, "{s}/.zig-cache/zig-common-tempdir-gone-{d}", .{ here, linux.getpid() }); + var gz: [sys.path_max:0]u8 = undefined; + const gone_z = try sys.z(&gz, gone); + try std.testing.expectEqual(@as(usize, 0), linux.mkdirat(cwd, gone_z.ptr, 0o700)); + try std.testing.expectEqual(@as(usize, 0), linux.chdir(gone_z.ptr)); + defer _ = linux.chdir(here_z.ptr); + try sys.unlinkat(cwd, gone, linux.AT.REMOVEDIR); + try std.testing.expectError(error.NoTempDir, td.get(gpa, env)); + try std.testing.expectEqualStrings("[Errno 2] No such file or directory", td.message); + } + + try env.put(gpa, "TMPDIR", "/tmp/./"); + const dir = try td.get(gpa, env); + try std.testing.expectEqualStrings("/tmp", dir); + try std.testing.expectEqual(dir.ptr, (try td.get(gpa, env)).ptr); +} + +test "the temporary directory message quotes candidates as repr does" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const msg = try noTempDirMessage(a, &.{ "/tmp", "it's", "a\"b'c\n", "\xff" }); + try std.testing.expectEqualStrings( + "[Errno 2] No usable temporary directory found in ['/tmp', \"it's\", 'a\"b\\'c\\n', '\\udcff']", + msg, + ); +} + /// The `d_type` values of a directory entry, as `std.os.linux.DT`: /// `DT.REG`, `DT.DIR`, `DT.LNK`, `DT.UNKNOWN` and the rest. pub const DT = linux.DT; diff --git a/src/pytext.zig b/src/pytext.zig index 2ae1401..5db5380 100644 --- a/src/pytext.zig +++ b/src/pytext.zig @@ -5,6 +5,7 @@ const std = @import("std"); const linux = std.os.linux; const sys = @import("sys.zig"); +const nd = @import("pytext_nd.zig"); const Allocator = std.mem.Allocator; @@ -99,6 +100,42 @@ pub fn pyWhitespace(cp: u21) bool { }; } +/// The value of the decimal digit `cp`, as unicodedata.decimal gives it, or +/// null when `cp` has no decimal value. These are the characters Python's +/// float() and int() read as digits. +pub fn decimalDigit(cp: u21) ?u4 { + var lo: usize = 0; + var hi: usize = nd.zeros.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (nd.zeros[mid] <= cp) lo = mid + 1 else hi = mid; + } + if (lo == 0) return null; + const offset = cp - nd.zeros[lo - 1]; + return if (offset < 10) @intCast(offset) else null; +} + +/// `s` with each decimal digit written as the ASCII digit of its value, the +/// way Python's float() and int() read their text before they parse it. The +/// other characters, and the bytes that are not valid UTF-8, are copied as +/// they are. The caller owns the result. +pub fn decimalToAscii(gpa: Allocator, s: []const u8) Allocator.Error![]u8 { + var out = try std.ArrayList(u8).initCapacity(gpa, s.len); + errdefer out.deinit(gpa); + var i: usize = 0; + while (i < s.len) { + const ch = nextChar(s[i..]); + if (ch.cp) |cp| if (decimalDigit(cp)) |d| { + out.appendAssumeCapacity('0' + @as(u8, d)); + i += ch.len; + continue; + }; + out.appendSliceAssumeCapacity(s[i .. i + ch.len]); + i += ch.len; + } + return out.toOwnedSlice(gpa); +} + /// str.strip(): `s` without leading and trailing Unicode whitespace. pub fn pyStrip(s: []const u8) []const u8 { var a: usize = 0; @@ -284,3 +321,34 @@ test "osError and osErrorErrno format OSError messages with Python path quoting" defer gpa.free(e3); try std.testing.expectEqualStrings("[Errno 36] File name too long: '/long'", e3); } + +test "decimalDigit reads the runs of ten decimal digits" { + try std.testing.expectEqual(@as(?u4, null), decimalDigit(0x2f)); + try std.testing.expectEqual(@as(?u4, 0), decimalDigit('0')); + try std.testing.expectEqual(@as(?u4, 9), decimalDigit('9')); + try std.testing.expectEqual(@as(?u4, null), decimalDigit(':')); + try std.testing.expectEqual(@as(?u4, 3), decimalDigit(0x663)); + try std.testing.expectEqual(@as(?u4, 9), decimalDigit(0xff19)); + try std.testing.expectEqual(@as(?u4, null), decimalDigit(0xff1a)); + try std.testing.expectEqual(@as(?u4, 0), decimalDigit(0x1d7ce)); + try std.testing.expectEqual(@as(?u4, 9), decimalDigit(0x1d7ff)); + try std.testing.expectEqual(@as(?u4, null), decimalDigit(0x1d800)); + try std.testing.expectEqual(@as(?u4, null), decimalDigit(0xb2)); + try std.testing.expectEqual(@as(?u4, null), decimalDigit(0x10ffff)); +} + +test "decimalToAscii writes decimal digits as ASCII and keeps the rest" { + const gpa = std.testing.allocator; + const cases = [_][2][]const u8{ + .{ "", "" }, + .{ "12.5", "12.5" }, + .{ "\xd9\xa3", "3" }, + .{ "\xef\xbc\x91\xef\xbc\x90_\xef\xbc\x90", "10_0" }, + .{ "\xc2\xb2x\xff\xd9\xa7", "\xc2\xb2x\xff7" }, + }; + for (cases) |cs| { + const r = try decimalToAscii(gpa, cs[0]); + defer gpa.free(r); + try std.testing.expectEqualStrings(cs[1], r); + } +} diff --git a/src/pytext_nd.zig b/src/pytext_nd.zig new file mode 100644 index 0000000..c80208e --- /dev/null +++ b/src/pytext_nd.zig @@ -0,0 +1,83 @@ +//! The code point of each decimal digit zero in Unicode, from Python's +//! unicodedata. Generated by tools/gen_pytext_nd.py; do not edit. +//! +//! Python 3.14.10, Unicode 16.0.0, 76 runs of ten digits. + +pub const zeros = [_]u21{ + 0x30, + 0x660, + 0x6f0, + 0x7c0, + 0x966, + 0x9e6, + 0xa66, + 0xae6, + 0xb66, + 0xbe6, + 0xc66, + 0xce6, + 0xd66, + 0xde6, + 0xe50, + 0xed0, + 0xf20, + 0x1040, + 0x1090, + 0x17e0, + 0x1810, + 0x1946, + 0x19d0, + 0x1a80, + 0x1a90, + 0x1b50, + 0x1bb0, + 0x1c40, + 0x1c50, + 0xa620, + 0xa8d0, + 0xa900, + 0xa9d0, + 0xa9f0, + 0xaa50, + 0xabf0, + 0xff10, + 0x104a0, + 0x10d30, + 0x10d40, + 0x11066, + 0x110f0, + 0x11136, + 0x111d0, + 0x112f0, + 0x11450, + 0x114d0, + 0x11650, + 0x116c0, + 0x116d0, + 0x116da, + 0x11730, + 0x118e0, + 0x11950, + 0x11bf0, + 0x11c50, + 0x11d50, + 0x11da0, + 0x11f50, + 0x16130, + 0x16a60, + 0x16ac0, + 0x16b50, + 0x16d70, + 0x1ccf0, + 0x1d7ce, + 0x1d7d8, + 0x1d7e2, + 0x1d7ec, + 0x1d7f6, + 0x1e140, + 0x1e2f0, + 0x1e4f0, + 0x1e5f1, + 0x1e950, + 0x1fbf0, +}; diff --git a/tests/parity_probe.zig b/tests/parity_probe.zig index ab85163..b986379 100644 --- a/tests/parity_probe.zig +++ b/tests/parity_probe.zig @@ -342,6 +342,26 @@ fn errnoStdin() !void { try sys.writeAll(1, all.items); } +/// pytext.decimalToAscii over every code point that UTF-8 can carry, in +/// blocks of 1024 so that the case set stays small, and over a few strings +/// with bytes that are not UTF-8. +fn digitCases() void { + var cp: u32 = 0; + while (cp < 0x110000) : (cp += 1024) { + var buf: std.ArrayList(u8) = .empty; + var c = cp; + while (c < cp + 1024) : (c += 1) { + if (c >= 0xd800 and c <= 0xdfff) continue; + var enc: [4]u8 = undefined; + const n = std.unicode.utf8Encode(@intCast(c), &enc) catch unreachable; + buf.appendSlice(A, enc[0..n]) catch unreachable; + } + emit("digits", buf.items, pytext.decimalToAscii(A, buf.items) catch unreachable); + } + const odd = [_][]const u8{ "\xff", "\xd9\xa3\xff\xd9\xa4", "\xd9", "\xf0\x9d\x9f", "\xef\xbc\x91\xe0\x80\xef\xbc\x92", "1_0", "" }; + for (odd) |in| emit("digits", in, pytext.decimalToAscii(A, in) catch unreachable); +} + pub fn main(init: std.process.Init) !void { arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); A = arena_state.allocator(); @@ -391,6 +411,7 @@ pub fn main(init: std.process.Init) !void { textCases(buf); } + digitCases(); for (edge_floats) |f| floatCaseBits(@bitCast(f)); for (0..2000) |_| floatCaseBits(rand.int(u64)); diff --git a/tests/tempdir_probe.zig b/tests/tempdir_probe.zig new file mode 100644 index 0000000..af6a89e --- /dev/null +++ b/tests/tempdir_probe.zig @@ -0,0 +1,50 @@ +//! The temporary directory probe: prints what `fsx.TempDir` makes of this +//! process's environment and working directory, as one line. The Python +//! test beside it runs the probe and `tempfile.gettempdir` under the same +//! environment, working directory and limits and compares the lines. +//! +//! The line is `ok`, a tab and the directory, or `err`, a tab, the Python +//! class name and the `str()` of the error, tab separated. Like Python, the +//! probe ignores SIGXFSZ, so a write past a file size limit fails with +//! EFBIG instead of ending the process. +const std = @import("std"); +const linux = std.os.linux; +const common = @import("zig_common"); + +const fsx = common.fsx; +const sys = common.sys; + +const Env = struct { + blob: []const u8, + + pub fn get(e: Env, name: []const u8) ?[]const u8 { + var it = std.mem.splitScalar(u8, e.blob, 0); + while (it.next()) |entry| { + const eq = std.mem.findScalar(u8, entry, '=') orelse continue; + if (std.mem.eql(u8, entry[0..eq], name)) return entry[eq + 1 ..]; + } + return null; + } +}; + +pub fn main() !void { + var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator); + const a = arena_state.allocator(); + const ignore: linux.Sigaction = .{ + .handler = .{ .handler = linux.SIG.IGN }, + .mask = linux.sigemptyset(), + .flags = 0, + }; + _ = linux.sigaction(linux.SIG.XFSZ, &ignore, null); + + const fd = try sys.openat(fsx.cwd, "/proc/self/environ", .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, 0); + const env: Env = .{ .blob = try fsx.readAll(a, fd, 1 << 24) }; + var td: fsx.TempDir = .{}; + const line = if (td.get(a, env)) |dir| + try std.fmt.allocPrint(a, "ok\t{s}\n", .{dir}) + else |err| switch (err) { + error.NoTempDir => try std.fmt.allocPrint(a, "err\tFileNotFoundError\t{s}\n", .{td.message}), + error.OutOfMemory => return err, + }; + _ = linux.write(1, line.ptr, line.len); +} diff --git a/tests/test_gettempdir_parity.py b/tests/test_gettempdir_parity.py new file mode 100644 index 0000000..244bc98 --- /dev/null +++ b/tests/test_gettempdir_parity.py @@ -0,0 +1,172 @@ +"""Parity test for fsx.TempDir against tempfile.gettempdir. + +The probe (tests/tempdir_probe.zig, built by `zig build tempdir-probe`) +and a Python one-liner run in a fresh process under the same environment, +working directory and file size limit, and their output lines are compared +byte for byte. The scenarios are generated here, in a temporary tree, so +no fixture is committed: writable and unwritable directories, files and +links in place of directories, relative and unnormalized values, empty +values, the three variable names in every order of precedence, a removed +working directory, and a file size limit that makes the probe write fail. +A directory of mode 0500 is unwritable only where permission checks apply, +and the comparison holds either way. The case that needs an unwritable +candidate uses /proc, where no user can create a file. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from typing import Dict, List, Optional + +ROOT = Path(__file__).resolve().parent.parent +PROBE = ROOT / "zig-out" / "bin" / "tempdir_probe" + +LAUNCHER = r""" +import os, resource, sys +cap, gone = sys.argv[1], sys.argv[2] +if gone != "-": + os.mkdir(gone) + os.chdir(gone) + os.rmdir(gone) +if cap != "-": + n = int(cap) + resource.setrlimit(resource.RLIMIT_FSIZE, (n, n)) +os.execv(sys.argv[3], sys.argv[3:]) +""" + +PYTHON_PROBE = r""" +import os, sys, tempfile +try: + line = b"ok\t" + os.fsencode(tempfile.gettempdir()) + b"\n" +except OSError as exc: + line = ( + b"err\t" + type(exc).__name__.encode() + b"\t" + os.fsencode(str(exc)) + b"\n" + ) +os.write(1, line) +""" + + +def _bytes(value: object) -> bytes: + return value if isinstance(value, bytes) else os.fsencode(value) + + +class GetTempDirParityTests(unittest.TestCase): + def setUp(self) -> None: + if not PROBE.exists(): + self.skipTest("run `zig build tempdir-probe` first") + self.root = Path(tempfile.mkdtemp(prefix="gettempdir-parity-")).resolve() + self.addCleanup(self._cleanup) + self.work = self.root / "work" + self.work.mkdir() + self.good = self.root / "good" + self.good.mkdir() + self.good2 = self.root / "good2" + self.good2.mkdir() + self.locked = self.root / "locked" + self.locked.mkdir() + self.locked.chmod(0o500) + self.plain = self.root / "plain-file" + self.plain.write_bytes(b"x") + self.link = self.root / "link" + self.link.symlink_to(self.good) + self.missing = self.root / "missing" + + def _cleanup(self) -> None: + for path in self.root.rglob("*"): + if path.is_dir() and not path.is_symlink(): + path.chmod(0o700) + shutil.rmtree(self.root, ignore_errors=True) + + def _run(self, program: List[str], env: Dict[object, object], cap: Optional[int], gone: bool): + argv = [ + sys.executable, + "-c", + LAUNCHER, + "-" if cap is None else str(cap), + str(self.root / "gone") if gone else "-", + *program, + ] + raw = {_bytes(k): _bytes(v) for k, v in env.items()} + return subprocess.run( + argv, + env=raw, + cwd=self.work, + capture_output=True, + timeout=20, + check=False, + ) + + def _agree(self, label: str, env: Dict[object, object], cap: Optional[int] = None, gone: bool = False): + env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), **env} + python = self._run([sys.executable, "-S", "-c", PYTHON_PROBE], env, cap, gone) + probe = self._run([str(PROBE)], env, cap, gone) + with self.subTest(case=label): + self.assertEqual(python.returncode, 0, python.stderr) + self.assertEqual(probe.returncode, 0, probe.stderr) + self.assertEqual(probe.stdout, python.stdout) + return python.stdout + + def test_variable_precedence_and_system_fallback(self) -> None: + good, good2 = str(self.good), str(self.good2) + bad = { + "locked": str(self.locked), + "file": str(self.plain), + "missing": str(self.missing), + "empty": "", + } + self._agree("no variables", {}) + self._agree("TMPDIR", {"TMPDIR": good}) + self._agree("TEMP only", {"TEMP": good}) + self._agree("TMP only", {"TMP": good}) + self._agree("TMPDIR over TEMP", {"TMPDIR": good, "TEMP": good2}) + self._agree("TEMP over TMP", {"TEMP": good, "TMP": good2}) + for name, value in bad.items(): + self._agree("%s TMPDIR, TEMP good" % name, {"TMPDIR": value, "TEMP": good}) + self._agree("%s TMPDIR, TMP good" % name, {"TMPDIR": value, "TMP": good}) + self._agree("%s all three" % name, {"TMPDIR": value, "TEMP": value, "TMP": value}) + self._agree("mode 0500 then writable", {"TMPDIR": str(self.locked), "TEMP": good}) + out = self._agree("unwritable then writable", {"TMPDIR": "/proc", "TEMP": good}) + self.assertEqual(out, b"ok\t" + good.encode() + b"\n") + + def test_values_are_made_absolute_and_normalized(self) -> None: + good = str(self.good) + self._agree("trailing slashes", {"TMPDIR": good + "///"}) + self._agree("dot segments", {"TMPDIR": good + "/./sub/../."}) + self._agree("double slash", {"TMPDIR": good.replace("/", "//", 1)}) + (self.work / "rel").mkdir() + self._agree("relative", {"TMPDIR": "rel"}) + self._agree("relative dot segments", {"TMPDIR": "./rel/../rel/."}) + self._agree("relative parent", {"TMPDIR": "../good"}) + self._agree("dot", {"TMPDIR": "."}) + self._agree("link is not resolved", {"TMPDIR": str(self.link)}) + + def test_file_size_limit(self) -> None: + env = {"TMPDIR": str(self.good)} + self._agree("limit of the probe size", env, cap=4) + self._agree("limit under the probe size", env, cap=3) + self._agree("limit of one byte", env, cap=1) + + def test_failure_text(self) -> None: + env: Dict[object, object] = {"TMPDIR": str(self.good)} + out = self._agree("every probe write fails", env, cap=0) + self.assertTrue(out.startswith(b"err\tFileNotFoundError\t[Errno 2] No usable"), out) + self._agree("all variables", {"TMPDIR": "it's", "TEMP": 'a"b', "TMP": "back\\slash"}, cap=0) + self._agree( + "non-UTF-8 and control bytes", + {b"TMPDIR": b"x\xffy\n", b"TEMP": b"\t\x01\xc3\xa9", b"TMP": b"/p\xed\xa0\x80"}, + cap=0, + ) + self._agree("quote and double quote", {"TMPDIR": "it's \"x\""}, cap=0) + self._agree("removed working directory", env, cap=0, gone=True) + self._agree("removed working directory, writable", env, gone=True) + self._agree("removed working directory, relative value", {"TMPDIR": "rel"}, gone=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_json_pytext_parity.py b/tests/test_json_pytext_parity.py index 32ac6ac..b6b4775 100644 --- a/tests/test_json_pytext_parity.py +++ b/tests/test_json_pytext_parity.py @@ -10,6 +10,7 @@ that has the probe built; the test builds it when zig is on PATH and the binary is missing. ZIG_COMMON_PARITY_PROBE names another binary. """ +import importlib.util import json import os import random @@ -17,14 +18,18 @@ import struct import subprocess import sys +import tempfile +import unicodedata import unittest REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEFAULT_PROBE = os.path.join(REPO, "zig-out", "bin", "parity_probe") +DIGIT_TABLE = os.path.join(REPO, "src", "pytext_nd.zig") +DIGIT_TOOL = os.path.join(REPO, "tools", "gen_pytext_nd.py") # The kinds the probe must cover. A kind with no cases means the parity # is silently unchecked, so the counts are asserted, not just the lines. -KINDS = ("cache", "wire", "quote", "strip", "split", "replace", "float", "dumps", "strerror", "oserror", "dumpscompact") +KINDS = ("cache", "wire", "quote", "strip", "split", "replace", "digits", "float", "dumps", "strerror", "oserror", "dumpscompact") MIN_CASES = { "cache": 1500, "wire": 1500, @@ -32,6 +37,7 @@ "strip": 1500, "split": 1500, "replace": 1500, + "digits": 1000, "float": 2000, "dumps": 90, "strerror": 300, @@ -82,6 +88,52 @@ def replace_expected(data): return data.decode("utf-8", "replace").encode("utf-8") +def digits_expected(data): + text = data.decode("utf-8", "surrogateescape") + out = [] + for char in text: + value = unicodedata.decimal(char, None) + out.append(char if value is None else str(value)) + return "".join(out).encode("utf-8", "surrogateescape") + + +def digit_tool(): + """tools/gen_pytext_nd.py as a module, loaded without writing bytecode.""" + spec = importlib.util.spec_from_file_location("gen_pytext_nd", DIGIT_TOOL) + module = importlib.util.module_from_spec(spec) + writes, sys.dont_write_bytecode = sys.dont_write_bytecode, True + try: + spec.loader.exec_module(module) + finally: + sys.dont_write_bytecode = writes + return module + + +def pinned_unicode(): + """The Unicode version the checked-in digit table names in its header.""" + with open(DIGIT_TABLE, encoding="utf-8") as handle: + pin = digit_tool().pinned_unicode(handle.read()) + if pin is None: + raise AssertionError("%s names no Unicode version" % DIGIT_TABLE) + return pin + + +def skip_unless_pinned_unicode(case): + """Skip a comparison with unicodedata under another Unicode version. + + The table in src/pytext_nd.zig is pinned to one Unicode version, and + unicodedata of another version has other digits. CI runs Python 3.14, + whose unicodedata is the pinned version, so it never skips. + """ + pin = pinned_unicode() + if unicodedata.unidata_version != pin: + case.skipTest( + "the decimal digit table is pinned to Unicode %s and this Python's " + "unicodedata is Unicode %s; run with Python 3.14 to compare them" + % (pin, unicodedata.unidata_version) + ) + + def float_expected(data): return json.dumps(struct.unpack(" src/pytext_nd.zig + python3 tools/gen_pytext_nd.py --check src/pytext_nd.zig + +Python's float() and int() read every character with a decimal value as +that digit. unicodedata.decimal is the same property. Each run of decimal +digits in Unicode is ten consecutive code points from the digit zero, so +the table holds the code point of each zero, and the script stops if the +data ever stops being laid out that way. The header names the Python and +Unicode versions the table came from. + +The checked-in table pins the Unicode version. --check reads the version +from the file's header and compares the table only under a Python whose +unicodedata is that version, ignoring the header; it fails when the data +has digits the file does not. Under any other Unicode version it compares +nothing and exits with status 3 and a message that names both versions. +""" + +import re +import sys +import unicodedata + +HEADER = "//! " +OTHER_UNICODE = 3 + + +def pinned_unicode(text): + """The Unicode version a table's header names, or None.""" + match = re.search(r"^//! Python \S+, Unicode (\S+),", text, re.MULTILINE) + return match.group(1) if match else None + + +def zero_starts(): + digits = {} + for cp in range(0x110000): + value = unicodedata.decimal(chr(cp), None) + if value is not None: + digits[cp] = value + starts = [] + for cp in sorted(digits): + if digits[cp] == 0: + starts.append(cp) + covered = {} + for zero in starts: + for offset in range(10): + covered[zero + offset] = offset + if covered != digits: + raise SystemExit("the decimal digits are not runs of ten from a zero") + return starts + + +def render(): + starts = zero_starts() + lines = [ + "//! The code point of each decimal digit zero in Unicode, from Python's", + "//! unicodedata. Generated by tools/gen_pytext_nd.py; do not edit.", + "//!", + "//! Python %s, Unicode %s, %d runs of ten digits." + % (sys.version.split()[0], unicodedata.unidata_version, len(starts)), + "", + "pub const zeros = [_]u21{", + ] + lines.extend(" 0x%x," % cp for cp in starts) + lines.append("};") + return "\n".join(lines) + "\n" + + +def body(text): + return [line for line in text.splitlines() if not line.startswith(HEADER)] + + +def main(argv): + if len(argv) == 3 and argv[1] == "--check": + with open(argv[2], encoding="utf-8") as handle: + have = handle.read() + pin = pinned_unicode(have) + if pin is None: + sys.stderr.write("%s names no Unicode version in its header\n" % argv[2]) + return 1 + if pin != unicodedata.unidata_version: + sys.stderr.write( + "%s is pinned to Unicode %s, and this Python's unicodedata is " + "Unicode %s; nothing was compared. Run the check with a Python " + "whose unicodedata is Unicode %s.\n" + % (argv[2], pin, unicodedata.unidata_version, pin) + ) + return OTHER_UNICODE + if body(have) != body(render()): + sys.stderr.write( + "%s does not match unicodedata; run tools/gen_pytext_nd.py\n" % argv[2] + ) + return 1 + return 0 + if len(argv) != 1: + sys.stderr.write("usage: gen_pytext_nd.py [--check FILE]\n") + return 2 + sys.stdout.write(render()) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv))