From 13723f267eb87f8c28ef0769cdf7e233b971326e Mon Sep 17 00:00:00 2001 From: Luke Edwards Date: Wed, 29 May 2024 16:16:27 -0700 Subject: feat: Add `Deno.exitCode` API (#23609) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commits adds the ability to set a would-be exit code for the Deno process without forcing an immediate exit, through the new `Deno.exitCode` API. - **Implements `Deno.exitCode` getter and setter**: Adds support for setting and retrieving a would-be exit code via `Deno.exitCode`. This allows for asynchronous cleanup before process termination without immediately exiting. - **Ensures type safety**: The setter for `Deno.exitCode` validates that the provided value is a number, throwing a TypeError if not, to ensure that only valid exit codes are set. Closes to #23605 --------- Co-authored-by: Bartek IwaƄczuk --- runtime/js/30_os.js | 21 ++++++++++++++++++++- runtime/js/99_main.js | 8 ++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) (limited to 'runtime/js') diff --git a/runtime/js/30_os.js b/runtime/js/30_os.js index 8948cf1ad..866fad287 100644 --- a/runtime/js/30_os.js +++ b/runtime/js/30_os.js @@ -7,6 +7,7 @@ import { op_exec_path, op_exit, op_get_env, + op_get_exit_code, op_gid, op_hostname, op_loadavg, @@ -21,7 +22,9 @@ import { const { Error, FunctionPrototypeBind, + NumberParseInt, SymbolFor, + TypeError, } = primordials; import { Event, EventTarget } from "ext:deno_web/02_event.js"; @@ -75,7 +78,7 @@ function exit(code) { if (typeof code === "number") { op_set_exit_code(code); } else { - code = 0; + code = op_get_exit_code(); } // Dispatches `unload` only when it's not dispatched yet. @@ -94,6 +97,20 @@ function exit(code) { throw new Error("Code not reachable"); } +function getExitCode() { + return op_get_exit_code(); +} + +function setExitCode(value) { + const code = NumberParseInt(value, 10); + if (typeof code !== "number") { + throw new TypeError( + `Exit code must be a number, got: ${code} (${typeof code}).`, + ); + } + op_set_exit_code(code); +} + function setEnv(key, value) { op_set_env(key, value); } @@ -126,12 +143,14 @@ export { env, execPath, exit, + getExitCode, gid, hostname, loadavg, networkInterfaces, osRelease, osUptime, + setExitCode, setExitHandler, systemMemoryInfo, uid, diff --git a/runtime/js/99_main.js b/runtime/js/99_main.js index 3fa9fc41b..4f949b214 100644 --- a/runtime/js/99_main.js +++ b/runtime/js/99_main.js @@ -674,6 +674,14 @@ ObjectDefineProperties(finalDenoNs, { return internals.future ? undefined : customInspect; }, }, + exitCode: { + get() { + return os.getExitCode(); + }, + set(value) { + os.setExitCode(value); + }, + }, }); const { -- cgit v1.2.3