aboutsummaryrefslogtreecommitdiff
path: root/src/coreutils.js
diff options
context:
space:
mode:
authorSoccera1 <[email protected]>2026-07-18 09:27:17 +1000
committerSoccera1 <[email protected]>2026-07-18 09:27:17 +1000
commit6f5241afb5bd1d6a1a8724bf06cc6f205c279402 (patch)
tree2aa852e968f6b89f2c8458333ce3e7c38b3c2450 /src/coreutils.js
parenta753f669c9bedfccb9f7f400da018bb487dca5d0 (diff)
downloadbnu-6f5241afb5bd1d6a1a8724bf06cc6f205c279402.tar.gz
bnu-6f5241afb5bd1d6a1a8724bf06cc6f205c279402.zip
Refactor to single call
Diffstat (limited to 'src/coreutils.js')
-rw-r--r--src/coreutils.js34106
1 files changed, 3 insertions, 34103 deletions
diff --git a/src/coreutils.js b/src/coreutils.js
index aabcac1..5bc6e5b 100644
--- a/src/coreutils.js
+++ b/src/coreutils.js
@@ -1,34107 +1,7 @@
-import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, opendirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
-import { access, chmod as fsChmod, chown, copyFile, futimes, lchown, link as fsLink, lstat, lutimes, mkdir, mkdtemp, open, opendir, readdir, readFile, readlink, realpath, rename, rm, rmdir, stat, symlink, truncate, unlink as fsUnlink, utimes, writeFile } from "node:fs/promises";
-import { statfs } from "node:fs/promises";
-import { createHash } from "node:crypto";
-import { basename as pathBasename, dirname as pathDirname, isAbsolute, join, normalize, relative, resolve } from "node:path";
-import { availableParallelism, cpus, hostname as osHostname, loadavg, machine as osMachine, release as osRelease, type as osType, userInfo, version as osVersion } from "node:os";
-import { CString, dlopen, FFIType, linkSymbols, ptr, read, toArrayBuffer } from "bun:ffi";
+import { main } from "./shared/runtime.js";
-const VERSION = "bnu 9.11";
-const HASH_HELP_OPTIONS = ["--binary", "--check", "--ignore-missing", "--quiet", "--status", "--strict", "--tag", "--text", "--warn", "--zero", "-b", "-c", "-t", "-w", "-z"];
-const B2SUM_HELP_OPTIONS = ["--binary", "--check", "--ignore-missing", "--length", "--quiet", "--status", "--strict", "--tag", "--text", "--warn", "--zero", "-b", "-c", "-l", "-t", "-w", "-z"];
-const BASE_ENCODING_HELP_OPTIONS = ["--decode", "--ignore-garbage", "--wrap", "-d", "-i", "-w"];
-const DIRCOLORS_LONG_OPTIONS = ["sh", "bourne-shell", "csh", "c-shell", "print-database", "print-ls-colors", "help", "version"];
-const COMMAND_HELP_OPTIONS = {
- basename: ["--multiple", "--suffix", "--zero", "-a", "-s", "-z"],
- base32: BASE_ENCODING_HELP_OPTIONS,
- base64: BASE_ENCODING_HELP_OPTIONS,
- basenc: ["--base16", "--base2lsbf", "--base2msbf", "--base32", "--base32hex", "--base58", "--base64", "--base64url", "--decode", "--ignore-garbage", "--wrap", "--z85", "-d", "-i", "-w"],
- b2sum: B2SUM_HELP_OPTIONS,
- cat: ["--number", "--number-nonblank", "--show-all", "--show-ends", "--show-nonprinting", "--show-tabs", "--squeeze-blank", "-A", "-E", "-T", "-b", "-e", "-n", "-s", "-t", "-u", "-v"],
- chcon: ["--dereference", "--no-dereference", "--no-preserve-root", "--preserve-root", "--range", "--recursive", "--reference", "--role", "--type", "--user", "--verbose", "-R", "-h", "-l", "-r", "-t", "-u", "-v"],
- chmod: ["--changes", "--dereference", "--no-dereference", "--no-preserve-root", "--preserve-root", "--quiet", "--recursive", "--reference", "--silent", "--verbose", "-H", "-L", "-P", "-R", "-c", "-f", "-h", "-v"],
- chown: ["--changes", "--dereference", "--from", "--no-dereference", "--no-preserve-root", "--preserve-root", "--quiet", "--recursive", "--reference", "--silent", "--verbose", "-H", "-L", "-P", "-R", "-c", "-f", "-h", "-v"],
- chgrp: ["--changes", "--dereference", "--from", "--no-dereference", "--no-preserve-root", "--preserve-root", "--quiet", "--recursive", "--reference", "--silent", "--verbose", "-H", "-L", "-P", "-R", "-c", "-f", "-h", "-v"],
- chroot: ["--groups", "--skip-chdir", "--userspec"],
- cksum: ["--algorithm", "--base64", "--check", "--debug", "--ignore-missing", "--length", "--quiet", "--raw", "--status", "--strict", "--tag", "--untagged", "--warn", "--zero", "-a", "-c", "-l", "-w", "-z"],
- comm: ["--check-order", "--nocheck-order", "--output-delimiter", "--total", "--zero-terminated", "-1", "-2", "-3", "-z"],
- cp: ["--archive", "--attributes-only", "--backup", "--context", "--copy-contents", "--debug", "--dereference", "--force", "--interactive", "--keep-directory-symlink", "--link", "--no-clobber", "--no-dereference", "--no-preserve", "--no-target-directory", "--one-file-system", "--parents", "--preserve", "--recursive", "--reflink", "--remove-destination", "--sparse", "--strip-trailing-slashes", "--suffix", "--symbolic-link", "--target-directory", "--update", "--verbose", "-H", "-L", "-P", "-R", "-S", "-T", "-Z", "-a", "-b", "-d", "-f", "-i", "-l", "-n", "-p", "-r", "-s", "-t", "-u", "-v", "-x"],
- csplit: ["--digits", "--elide-empty-files", "--keep-files", "--prefix", "--quiet", "--silent", "--suffix-format", "--suppress-matched", "-b", "-f", "-k", "-n", "-s", "-z"],
- cut: ["--bytes", "--characters", "--complement", "--delimiter", "--fields", "--no-partial", "--only-delimited", "--output-delimiter", "--whitespace-delimited", "--zero-terminated", "-F", "-O", "-b", "-c", "-d", "-f", "-n", "-s", "-w", "-z"],
- date: ["--date", "--debug", "--file", "--iso-8601", "--reference", "--resolution", "--rfc-3339", "--rfc-email", "--set", "--universal", "--utc", "-I", "-R", "-d", "-f", "-r", "-s", "-u"],
- df: ["--all", "--block-size", "--exclude-type", "--human-readable", "--inodes", "--local", "--no-sync", "--output", "--portability", "--print-type", "--si", "--sync", "--total", "--type", "-B", "-H", "-P", "-T", "-a", "-h", "-i", "-k", "-l", "-t", "-x"],
- dir: ["--all", "--almost-all", "--author", "--block-size", "--classify", "--color", "--context", "--dereference", "--dereference-command-line", "--dereference-command-line-symlink-to-dir", "--directory", "--dired", "--escape", "--file-type", "--format", "--full-time", "--group-directories-first", "--hide", "--hide-control-chars", "--human-readable", "--hyperlink", "--ignore", "--ignore-backups", "--indicator-style", "--inode", "--kibibytes", "--literal", "--no-group", "--numeric-uid-gid", "--quote-name", "--quoting-style", "--recursive", "--reverse", "--show-control-chars", "--si", "--size", "--sort", "--tabsize", "--time", "--time-style", "--width", "--zero", "-1", "-C", "-S", "-U", "-X", "-c", "-g", "-l", "-m", "-o", "-p", "-t", "-u", "-v", "-x", "-A", "-B", "-D", "-F", "-G", "-H", "-I", "-L", "-N", "-Q", "-R", "-T", "-Z", "-a", "-b", "-d", "-f", "-h", "-i", "-k", "-n", "-q", "-r", "-s", "-w"],
- dircolors: ["--bourne-shell", "--c-shell", "--csh", "--print-database", "--print-ls-colors", "--sh", "-b", "-c", "-p"],
- dirname: ["--zero", "-z"],
- du: ["--all", "--apparent-size", "--block-size", "--bytes", "--count-links", "--dereference", "--dereference-args", "--exclude", "--exclude-from", "--files0-from", "--human-readable", "--inodes", "--max-depth", "--no-dereference", "--null", "--one-file-system", "--separate-dirs", "--si", "--summarize", "--threshold", "--time", "--time-style", "--total", "-0", "-A", "-B", "-D", "-H", "-L", "-P", "-S", "-X", "-a", "-b", "-c", "-d", "-h", "-k", "-l", "-m", "-s", "-t", "-x"],
- env: ["--argv0", "--block-signal", "--chdir", "--debug", "--default-signal", "--ignore-environment", "--ignore-signal", "--list-signal-handling", "--null", "--split-string", "--unset", "-0", "-C", "-S", "-a", "-i", "-u", "-v"],
- expand: ["--initial", "--tabs", "-i", "-t"],
- factor: ["--exponents", "-h"],
- fmt: ["--crown-margin", "--goal", "--prefix", "--split-only", "--tagged-paragraph", "--uniform-spacing", "--width", "-c", "-g", "-p", "-s", "-t", "-u", "-w"],
- fold: ["--bytes", "--characters", "--spaces", "--width", "-b", "-c", "-s", "-w"],
- head: ["--bytes", "--lines", "--quiet", "--silent", "--verbose", "--zero-terminated", "-c", "-n", "-q", "-v", "-z"],
- id: ["--context", "--group", "--groups", "--name", "--real", "--user", "--zero", "-G", "-Z", "-g", "-n", "-r", "-u", "-z"],
- install: ["--backup", "--compare", "--context", "--debug", "--directory", "--group", "--mode", "--no-target-directory", "--owner", "--preserve-context", "--preserve-timestamps", "--strip", "--strip-program", "--suffix", "--target-directory", "--verbose", "-C", "-D", "-S", "-T", "-Z", "-b", "-c", "-d", "-g", "-m", "-o", "-p", "-s", "-t", "-v"],
- join: ["--check-order", "--header", "--ignore-case", "--nocheck-order", "--zero-terminated", "-1", "-2", "-a", "-e", "-i", "-j", "-o", "-t", "-v", "-z"],
- kill: ["--list", "--signal", "--table", "-l", "-s", "-t"],
- ln: ["--backup", "--directory", "--force", "--interactive", "--logical", "--no-dereference", "--no-target-directory", "--physical", "--relative", "--suffix", "--symbolic", "--target-directory", "--verbose", "-F", "-L", "-P", "-S", "-T", "-b", "-d", "-f", "-i", "-n", "-r", "-s", "-t", "-v"],
- ls: ["--all", "--almost-all", "--author", "--block-size", "--classify", "--color", "--context", "--dereference", "--dereference-command-line", "--dereference-command-line-symlink-to-dir", "--directory", "--dired", "--escape", "--file-type", "--format", "--full-time", "--group-directories-first", "--hide", "--hide-control-chars", "--human-readable", "--hyperlink", "--ignore", "--ignore-backups", "--indicator-style", "--inode", "--kibibytes", "--literal", "--no-group", "--numeric-uid-gid", "--quote-name", "--quoting-style", "--recursive", "--reverse", "--show-control-chars", "--si", "--size", "--sort", "--tabsize", "--time", "--time-style", "--width", "--zero", "-1", "-C", "-S", "-U", "-X", "-c", "-g", "-l", "-m", "-o", "-p", "-t", "-u", "-v", "-x", "-A", "-B", "-D", "-F", "-G", "-H", "-I", "-L", "-N", "-Q", "-R", "-T", "-Z", "-a", "-b", "-d", "-f", "-h", "-i", "-k", "-n", "-q", "-r", "-s", "-w"],
- md5sum: HASH_HELP_OPTIONS,
- mkdir: ["--context", "--mode", "--parents", "--verbose", "-Z", "-m", "-p", "-v"],
- mkfifo: ["--context", "--mode", "-Z", "-m"],
- mknod: ["--context", "--mode", "-Z", "-m"],
- mktemp: ["--directory", "--dry-run", "--quiet", "--suffix", "--tmpdir", "-d", "-p", "-q", "-u"],
- mv: ["--backup", "--context", "--debug", "--exchange", "--force", "--interactive", "--no-clobber", "--no-copy", "--no-target-directory", "--strip-trailing-slashes", "--suffix", "--target-directory", "--update", "--verbose", "-S", "-T", "-Z", "-b", "-f", "-i", "-n", "-t", "-u", "-v"],
- nice: ["--adjustment", "-n"],
- nl: ["--body-numbering", "--footer-numbering", "--header-numbering", "--join-blank-lines", "--line-increment", "--no-renumber", "--number-format", "--number-separator", "--number-width", "--section-delimiter", "--starting-line-number", "-b", "-d", "-f", "-h", "-i", "-l", "-n", "-p", "-s", "-v", "-w"],
- nproc: ["--all", "--ignore"],
- numfmt: ["--debug", "--delimiter", "--field", "--format", "--from", "--from-unit", "--grouping", "--header", "--invalid", "--padding", "--round", "--suffix", "--to", "--to-unit", "--unit-separator", "--zero-terminated", "-d", "-z"],
- od: ["--address-radix", "--endian", "--format", "--output-duplicates", "--read-bytes", "--skip-bytes", "--strings", "--traditional", "--width", "-A", "-N", "-S", "-a", "-b", "-c", "-d", "-f", "-i", "-l", "-j", "-o", "-s", "-t", "-v", "-w", "-x"],
- paste: ["--delimiters", "--serial", "--zero-terminated", "-d", "-s", "-z"],
- pathchk: ["--portability", "-p", "-P"],
- pinky: ["--lookup", "-b", "-f", "-h", "-i", "-l", "-p", "-q", "-s", "-w"],
- pr: ["--across", "--columns", "--date-format", "--double-space", "--expand-tabs", "--first-line-number", "--form-feed", "--header", "--indent", "--join-lines", "--length", "--merge", "--no-file-warnings", "--number-lines", "--omit-header", "--omit-pagination", "--output-tabs", "--page-width", "--pages", "--sep-string", "--separator", "--show-control-chars", "--show-nonprinting", "--width", "-D", "-F", "-J", "-N", "-S", "-T", "-W", "-a", "-c", "-d", "-e", "-f", "-h", "-i", "-l", "-m", "-n", "-o", "-r", "-s", "-t", "-v", "-w"],
- printenv: ["--null", "-0"],
- ptx: ["--auto-reference", "--break-file", "--flag-truncation", "--format", "--gap-size", "--ignore-case", "--ignore-file", "--macro-name", "--only-file", "--references", "--right-side-refs", "--sentence-regexp", "--traditional", "--typeset-mode", "--width", "--word-regexp", "-A", "-F", "-G", "-M", "-R", "-S", "-W", "-b", "-f", "-g", "-i", "-o", "-r", "-t", "-w"],
- pwd: ["--logical", "--physical", "-L", "-P"],
- readlink: ["--canonicalize", "--canonicalize-existing", "--canonicalize-missing", "--no-newline", "--quiet", "--silent", "--verbose", "--zero", "-e", "-f", "-m", "-n", "-q", "-s", "-v", "-z"],
- realpath: ["--canonicalize", "--canonicalize-existing", "--canonicalize-missing", "--logical", "--no-symlinks", "--physical", "--quiet", "--relative-base", "--relative-to", "--strip", "--zero", "-E", "-L", "-P", "-e", "-m", "-q", "-s", "-z"],
- rm: ["--dir", "--force", "--interactive", "--no-preserve-root", "--one-file-system", "--preserve-root", "--recursive", "--verbose", "-I", "-R", "-d", "-f", "-i", "-r", "-v"],
- rmdir: ["--ignore-fail-on-non-empty", "--parents", "--verbose", "-p", "-v"],
- runcon: ["--compute", "--range", "--role", "--type", "--user", "-c", "-l", "-r", "-t", "-u"],
- seq: ["--equal-width", "--format", "--separator", "-f", "-s", "-w"],
- sha1sum: HASH_HELP_OPTIONS,
- sha224sum: HASH_HELP_OPTIONS,
- sha256sum: HASH_HELP_OPTIONS,
- sha384sum: HASH_HELP_OPTIONS,
- sha512sum: HASH_HELP_OPTIONS,
- sm3sum: HASH_HELP_OPTIONS,
- shred: ["--exact", "--force", "--iterations", "--random-source", "--remove", "--size", "--verbose", "--zero", "-f", "-n", "-s", "-u", "-v", "-x", "-z"],
- shuf: ["--echo", "--head-count", "--input-range", "--output", "--random-source", "--repeat", "--zero-terminated", "-e", "-i", "-n", "-o", "-r", "-z"],
- sort: ["--batch-size", "--buffer-size", "--check", "--compress-program", "--debug", "--dictionary-order", "--field-separator", "--files0-from", "--general-numeric-sort", "--human-numeric-sort", "--ignore-case", "--ignore-leading-blanks", "--ignore-nonprinting", "--key", "--merge", "--month-sort", "--numeric-sort", "--output", "--parallel", "--random-sort", "--random-source", "--reverse", "--sort", "--stable", "--temporary-directory", "--unique", "--version-sort", "--zero-terminated", "-C", "-M", "-R", "-S", "-T", "-V", "-b", "-c", "-d", "-f", "-g", "-h", "-i", "-k", "-m", "-n", "-o", "-r", "-s", "-t", "-u", "-z"],
- split: ["--additional-suffix", "--bytes", "--elide-empty-files", "--filter", "--hex-suffixes", "--line-bytes", "--lines", "--number", "--numeric-suffixes", "--separator", "--suffix-length", "--unbuffered", "--verbose", "-C", "-a", "-b", "-d", "-e", "-l", "-n", "-t", "-u", "-x"],
- stat: ["--cached", "--dereference", "--file-system", "--format", "--printf", "--terse", "-L", "-c", "-f", "-t"],
- stdbuf: ["--error", "--input", "--output", "-e", "-i", "-o"],
- stty: ["--all", "--file", "--save", "-F", "-a", "-g"],
- sync: ["--data", "--file-system", "-d", "-f"],
- tac: ["--before", "--regex", "--separator", "-b", "-r", "-s"],
- tail: ["--bytes", "--debug", "--follow", "--lines", "--max-unchanged-stats", "--pid", "--quiet", "--retry", "--silent", "--sleep-interval", "--verbose", "--zero-terminated", "-F", "-c", "-f", "-n", "-q", "-s", "-v", "-z"],
- tee: ["--append", "--ignore-interrupts", "--output-error", "-a", "-i", "-p"],
- timeout: ["--foreground", "--kill-after", "--preserve-status", "--signal", "--verbose", "-f", "-k", "-p", "-s", "-v"],
- touch: ["--date", "--no-create", "--no-dereference", "--reference", "--time", "-a", "-c", "-d", "-f", "-h", "-m", "-r", "-t"],
- tr: ["--complement", "--delete", "--squeeze-repeats", "--truncate-set1", "-C", "-c", "-d", "-s", "-t"],
- truncate: ["--io-blocks", "--no-create", "--reference", "--size", "-c", "-o", "-r", "-s"],
- tty: ["--quiet", "--silent", "-s"],
- uname: ["--all", "--hardware-platform", "--kernel-name", "--kernel-release", "--kernel-version", "--machine", "--nodename", "--operating-system", "--processor", "-a", "-i", "-m", "-n", "-o", "-p", "-r", "-s", "-v"],
- unexpand: ["--all", "--first-only", "--tabs", "-a", "-t"],
- uniq: ["--all-repeated", "--check-chars", "--count", "--group", "--ignore-case", "--repeated", "--skip-chars", "--skip-fields", "--unique", "--zero-terminated", "-D", "-c", "-d", "-f", "-i", "-s", "-u", "-w", "-z"],
- vdir: ["--all", "--almost-all", "--author", "--block-size", "--classify", "--color", "--context", "--dereference", "--dereference-command-line", "--dereference-command-line-symlink-to-dir", "--directory", "--dired", "--escape", "--file-type", "--format", "--full-time", "--group-directories-first", "--hide", "--hide-control-chars", "--human-readable", "--hyperlink", "--ignore", "--ignore-backups", "--indicator-style", "--inode", "--kibibytes", "--literal", "--no-group", "--numeric-uid-gid", "--quote-name", "--quoting-style", "--recursive", "--reverse", "--show-control-chars", "--si", "--size", "--sort", "--tabsize", "--time", "--time-style", "--width", "--zero", "-1", "-C", "-S", "-U", "-X", "-c", "-g", "-l", "-m", "-o", "-p", "-t", "-u", "-v", "-x", "-A", "-B", "-D", "-F", "-G", "-H", "-I", "-L", "-N", "-Q", "-R", "-T", "-Z", "-a", "-b", "-d", "-f", "-h", "-i", "-k", "-n", "-q", "-r", "-s", "-w"],
- wc: ["--bytes", "--chars", "--debug", "--files0-from", "--lines", "--max-line-length", "--total", "--words", "-L", "-c", "-l", "-m", "-w"],
- who: ["--all", "--boot", "--count", "--dead", "--heading", "--login", "--lookup", "--mesg", "--message", "--process", "--runlevel", "--short", "--time", "--users", "--writable", "-H", "-T", "-a", "-b", "-d", "-l", "-m", "-p", "-q", "-r", "-s", "-t", "-u", "-w"],
-};
-const SPECIAL_HELP = {
- arch: {
- usage: "Usage: arch [OPTION]...",
- description: "Print machine architecture.",
- },
- basename: {
- usage: "Usage: basename NAME [SUFFIX]\n or: basename OPTION... NAME...",
- description: "Print NAME with any leading directory components removed.\nIf specified, also remove a trailing SUFFIX.",
- options: ["-a, --multiple", "-s, --suffix=SUFFIX", "-z, --zero"],
- },
- base32: {
- usage: "Usage: base32 [OPTION]... [FILE]",
- description: "Base32 encode or decode FILE, or standard input, to standard output.",
- options: COMMAND_HELP_OPTIONS.base32,
- },
- base64: {
- usage: "Usage: base64 [OPTION]... [FILE]",
- description: "Base64 encode or decode FILE, or standard input, to standard output.",
- options: COMMAND_HELP_OPTIONS.base64,
- },
- b2sum: {
- usage: "Usage: b2sum [OPTION]... [FILE]...",
- description: "Print or check BLAKE2b (512-bit) checksums.\nLegacy interface to the cksum utility.",
- options: COMMAND_HELP_OPTIONS.b2sum,
- },
- basenc: {
- usage: "Usage: basenc [OPTION]... [FILE]",
- description: "basenc encode or decode FILE, or standard input, to standard output.",
- options: COMMAND_HELP_OPTIONS.basenc,
- },
- cat: {
- usage: "Usage: cat [OPTION]... [FILE]...",
- description: "Concatenate FILE(s) to standard output.",
- options: COMMAND_HELP_OPTIONS.cat,
- },
- comm: {
- usage: "Usage: comm [OPTION]... FILE1 FILE2",
- description: "Compare sorted files FILE1 and FILE2 line by line.",
- options: COMMAND_HELP_OPTIONS.comm,
- },
- chgrp: {
- usage: "Usage: chgrp [OPTION]... GROUP FILE...\n or: chgrp [OPTION]... --reference=RFILE FILE...",
- description: "Change the group of each FILE to GROUP.",
- options: COMMAND_HELP_OPTIONS.chgrp,
- },
- chmod: {
- usage: "Usage: chmod [OPTION]... MODE[,MODE]... FILE...\n or: chmod [OPTION]... OCTAL-MODE FILE...\n or: chmod [OPTION]... --reference=RFILE FILE...",
- description: "Change the mode of each FILE to MODE.",
- options: COMMAND_HELP_OPTIONS.chmod,
- },
- chown: {
- usage: "Usage: chown [OPTION]... [OWNER][:[GROUP]] FILE...\n or: chown [OPTION]... --reference=RFILE FILE...",
- description: "Change the owner and/or group of each FILE to OWNER and/or GROUP.",
- options: COMMAND_HELP_OPTIONS.chown,
- },
- chcon: {
- usage: "Usage: chcon [OPTION]... CONTEXT FILE...\n or: chcon [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...\n or: chcon [OPTION]... --reference=RFILE FILE...",
- description: "Change the SELinux security context of each FILE to CONTEXT.",
- options: COMMAND_HELP_OPTIONS.chcon,
- },
- chroot: {
- usage: "Usage: chroot [OPTION]... NEWROOT [COMMAND [ARG]...]",
- description: "Run COMMAND with root directory set to NEWROOT.",
- options: COMMAND_HELP_OPTIONS.chroot,
- },
- cp: {
- usage: "Usage: cp [OPTION]... [-T] SOURCE DEST\n or: cp [OPTION]... SOURCE... DIRECTORY\n or: cp [OPTION]... -t DIRECTORY SOURCE...",
- description: "Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.",
- options: COMMAND_HELP_OPTIONS.cp,
- },
- csplit: {
- usage: "Usage: csplit [OPTION]... FILE PATTERN...",
- description: "Output pieces of FILE separated by PATTERN(s) to files 'xx00', 'xx01', ...,\nand output byte counts of each piece to standard output.",
- options: COMMAND_HELP_OPTIONS.csplit,
- },
- cut: {
- usage: "Usage: cut OPTION... [FILE]...",
- description: "Print selected parts of lines from each FILE to standard output.",
- options: COMMAND_HELP_OPTIONS.cut,
- },
- date: {
- usage: "Usage: date [OPTION]... [+FORMAT]\n or: date [OPTION]... MMDDhhmm[[CC]YY][.ss]",
- description: "Display date and time in the given FORMAT.\nWith -s, or with MMDDhhmm[[CC]YY][.ss], set the date and time first.",
- options: COMMAND_HELP_OPTIONS.date,
- },
- dd: {
- usage: "Usage: dd [OPERAND]...\n or: dd OPTION",
- description: "Copy a file, converting and formatting according to the operands.",
- },
- df: {
- usage: "Usage: df [OPTION]... [FILE]...",
- description: "Show information about the file system on which each FILE resides,\nor all file systems by default.",
- options: COMMAND_HELP_OPTIONS.df,
- },
- dir: {
- usage: "Usage: dir [OPTION]... [FILE]...",
- description: "List information about the FILEs (the current directory by default).\nSort entries alphabetically if none of -cftuvSUX nor --sort is specified.",
- options: COMMAND_HELP_OPTIONS.dir,
- },
- dircolors: {
- usage: "Usage: dircolors [OPTION]... [FILE]",
- description: "Output commands to set the LS_COLORS environment variable.",
- options: COMMAND_HELP_OPTIONS.dircolors,
- },
- dirname: {
- usage: "Usage: dirname [OPTION] NAME...",
- description: "Output each NAME with its last non-slash component and trailing slashes\nremoved; if NAME contains no /'s, output '.' (meaning the current directory).",
- options: ["-z, --zero"],
- },
- du: {
- usage: "Usage: du [OPTION]... [FILE]...\n or: du [OPTION]... --files0-from=F",
- description: "Summarize device usage of the set of FILEs, recursively for directories.",
- options: COMMAND_HELP_OPTIONS.du,
- },
- env: {
- usage: "Usage: env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]",
- description: "Set each NAME to VALUE in the environment and run COMMAND.",
- options: COMMAND_HELP_OPTIONS.env,
- },
- expr: {
- usage: "Usage: expr EXPRESSION\n or: expr OPTION",
- description: "",
- options: [],
- },
- expand: {
- usage: "Usage: expand [OPTION]... [FILE]...",
- description: "Convert tabs in each FILE to spaces, writing to standard output.",
- options: COMMAND_HELP_OPTIONS.expand,
- },
- fold: {
- usage: "Usage: fold [OPTION]... [FILE]...",
- description: "Wrap input lines in each FILE, writing to standard output.",
- options: COMMAND_HELP_OPTIONS.fold,
- },
- groups: {
- usage: "Usage: groups [OPTION]... [USERNAME]...",
- description: "Print group memberships for each USERNAME or, if no USERNAME is specified, for\nthe current process (which may differ if the groups database has changed).",
- },
- ginstall: {
- usage: "Usage: install [OPTION]... [-T] SOURCE DEST\n or: install [OPTION]... SOURCE... DIRECTORY\n or: install [OPTION]... -t DIRECTORY SOURCE...\n or: install [OPTION]... -d DIRECTORY...",
- description: "Copy files and set attributes.",
- options: COMMAND_HELP_OPTIONS.install,
- },
- hostid: {
- usage: "Usage: hostid [OPTION]",
- description: "Print the numeric identifier (in hexadecimal) for the current host.",
- },
- head: {
- usage: "Usage: head [OPTION]... [FILE]...",
- description: "Print the first 10 lines of each FILE to standard output.\nWith more than one FILE, precede each with a header giving the file name.",
- options: COMMAND_HELP_OPTIONS.head,
- },
- id: {
- usage: "Usage: id [OPTION]... [USER]...",
- description: "Print user and group information for each specified USER,\nor (when USER omitted) for the current process.",
- options: COMMAND_HELP_OPTIONS.id,
- },
- install: {
- usage: "Usage: install [OPTION]... [-T] SOURCE DEST\n or: install [OPTION]... SOURCE... DIRECTORY\n or: install [OPTION]... -t DIRECTORY SOURCE...\n or: install [OPTION]... -d DIRECTORY...",
- description: "Copy files and set attributes.",
- options: COMMAND_HELP_OPTIONS.install,
- },
- join: {
- usage: "Usage: join [OPTION]... FILE1 FILE2",
- description: "For each pair of input lines with identical join fields, write a line to\nstandard output.",
- options: COMMAND_HELP_OPTIONS.join,
- },
- kill: {
- usage: "Usage: kill [-s SIGNAL | --signal SIGNAL | -SIGNAL] PID...\n or: kill [-l | --list | -t | --table] [SIGNAL]...",
- description: "Send a signal to processes, or list information about signals.",
- options: [
- "-s, --signal=SIGNAL specify the name or number of the signal to be sent",
- "-l, --list[=SIGNAL] list signal names, or convert signal names and numbers",
- "-t, --table print a table of signal numbers, names, and descriptions",
- ],
- },
- ls: {
- usage: "Usage: ls [OPTION]... [FILE]...",
- description: "List information about the FILEs (the current directory by default).\nSort entries alphabetically if none of -cftuvSUX nor --sort is specified.",
- options: COMMAND_HELP_OPTIONS.ls,
- },
- logname: {
- usage: "Usage: logname [OPTION]",
- description: "Print the user's login name.",
- },
- md5sum: {
- usage: "Usage: md5sum [OPTION]... [FILE]...",
- description: "Print or check MD5 (128-bit) checksums.\nLegacy interface to the cksum utility.",
- options: COMMAND_HELP_OPTIONS.md5sum,
- },
- factor: {
- usage: "Usage: factor [OPTION] [NUMBER]...",
- description: "Print the prime factors of each specified integer NUMBER. If none\nare specified on the command line, read them from standard input.",
- options: ["-h, --exponents"],
- },
- fmt: {
- usage: "Usage: fmt [-WIDTH] [OPTION]... [FILE]...",
- description: "Reformat each paragraph in the FILE(s), writing to standard output.\nThe option -WIDTH is an abbreviated form of --width=DIGITS.",
- options: COMMAND_HELP_OPTIONS.fmt,
- },
- mkdir: {
- usage: "Usage: mkdir [OPTION]... DIRECTORY...",
- description: "Create the DIRECTORY(ies), if they do not already exist.\n\nMandatory arguments to long options are mandatory for short options too.",
- options: [
- "-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask",
- "-p, --parents no error if existing, make parent directories as needed,\n with their file modes unaffected by any -m option",
- "-v, --verbose print a message for each created directory",
- "-Z set SELinux security context of each created directory\n to the default type",
- "--context[=CTX] like -Z, or if CTX is specified then set the\n SELinux or SMACK security context to CTX",
- ],
- },
- mkfifo: {
- usage: "Usage: mkfifo [OPTION]... NAME...",
- description: "Create named pipes (FIFOs) with the given NAMEs.\n\nMandatory arguments to long options are mandatory for short options too.",
- options: [
- "-m, --mode=MODE set file permission bits to MODE, not a=rw - umask",
- "-Z set the SELinux security context to default type",
- "--context[=CTX] like -Z, or if CTX is specified then set the\n SELinux or SMACK security context to CTX",
- ],
- },
- mktemp: {
- usage: "Usage: mktemp [OPTION]... [TEMPLATE]",
- description: "Create a temporary file or directory, safely, and print its name.\nTEMPLATE must contain at least 3 consecutive 'X's in last component.\nIf TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied.\nFiles are created u+rw, and directories u+rwx, minus umask restrictions.",
- options: [
- "-d, --directory create a directory, not a file",
- "-u, --dry-run do not create anything; merely print a name (unsafe)",
- "-q, --quiet suppress diagnostics about file/dir-creation failure",
- "--suffix=SUFF append SUFF to TEMPLATE; SUFF must not contain a slash.\n This option is implied if TEMPLATE does not end in X",
- "-p DIR, --tmpdir[=DIR]\n interpret TEMPLATE relative to DIR;\n if DIR is not specified, use $TMPDIR if set, else /tmp.\n With this option, TEMPLATE must not be an absolute name;\n unlike with -t, TEMPLATE may contain slashes,\n but mktemp creates only the final component",
- "-t interpret TEMPLATE as a single file name component,\n relative to a directory: $TMPDIR, if set;\n else the directory specified via -p; else /tmp [deprecated]",
- ],
- },
- mv: {
- usage: "Usage: mv [OPTION]... [-T] SOURCE DEST\n or: mv [OPTION]... SOURCE... DIRECTORY\n or: mv [OPTION]... -t DIRECTORY SOURCE...",
- description: "Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.",
- options: COMMAND_HELP_OPTIONS.mv,
- },
- nice: {
- usage: "Usage: nice [OPTION] [COMMAND [ARG]...]",
- description: "Run COMMAND with an adjusted niceness, which affects process scheduling.\nWith no COMMAND, print the current niceness.",
- options: COMMAND_HELP_OPTIONS.nice,
- },
- nohup: {
- usage: "Usage: nohup COMMAND [ARG]...\n or: nohup OPTION",
- description: "Run COMMAND, ignoring hangup signals.",
- },
- ln: {
- usage: "Usage: ln [OPTION]... [-T] TARGET LINK_NAME\n or: ln [OPTION]... TARGET\n or: ln [OPTION]... TARGET... DIRECTORY\n or: ln [OPTION]... -t DIRECTORY TARGET...",
- description: "Create links between files.",
- options: COMMAND_HELP_OPTIONS.ln,
- },
- mknod: {
- usage: "Usage: mknod [OPTION]... NAME TYPE [MAJOR MINOR]",
- description: "Create the special file NAME of the given TYPE.\n\nMandatory arguments to long options are mandatory for short options too.",
- options: [
- "-m, --mode=MODE set file permission bits to MODE, not a=rw - umask",
- "-Z set the SELinux security context to default type",
- "--context[=CTX] like -Z, or if CTX is specified then set the\n SELinux or SMACK security context to CTX",
- ],
- after: "Both MAJOR and MINOR must be specified when TYPE is b, c, or u, and they\nmust be omitted when TYPE is p. If MAJOR or MINOR begins with 0x or 0X,\nit is interpreted as hexadecimal; otherwise, if it begins with 0, as octal;\notherwise, as decimal. TYPE may be:\n\n b create a block (buffered) special file\n c, u create a character (unbuffered) special file\n p create a FIFO\n\nYour shell may have its own version of mknod, which usually supersedes\nthe version described here. Please refer to your shell's documentation\nfor details about the options it supports.",
- },
- nproc: {
- usage: "Usage: nproc [OPTION]...",
- description: "Print the number of processing units available to the current process,\nwhich may be less than the number of online processors.\nIf the 'OMP_NUM_THREADS' or 'OMP_THREAD_LIMIT' environment variables are set,\nthen they will determine the minimum and maximum returned value respectively.",
- options: [
- "--all\n print the number of installed processors,\n disregarding any OpenMP environment variables, or CPU quotas.",
- "--ignore=N\n if possible, exclude N processing units.\n The result is guaranteed to be at least 1.",
- ],
- },
- nl: {
- usage: "Usage: nl [OPTION]... [FILE]...",
- description: "Write each FILE to standard output, with line numbers added.",
- options: COMMAND_HELP_OPTIONS.nl,
- },
- numfmt: {
- usage: "Usage: numfmt [OPTION]... [NUMBER]...",
- description: "Reformat NUMBER(s), or the numbers from standard input if none are specified.",
- options: COMMAND_HELP_OPTIONS.numfmt,
- },
- od: {
- usage: "Usage: od [OPTION]... [FILE]...\n or: od [-abcdfilosx]... [FILE] [[+]OFFSET[.][b]]\n or: od --traditional [OPTION]... [FILE] [[+]OFFSET[.][b] [+][LABEL][.][b]]",
- description: "Write an unambiguous representation, octal bytes by default,\nof FILE to standard output.",
- options: COMMAND_HELP_OPTIONS.od,
- },
- pathchk: {
- usage: "Usage: pathchk [OPTION]... NAME...",
- description: "Diagnose invalid or non-portable file names.",
- options: [
- "-p check for most POSIX systems",
- "-P check for empty names and leading \"-\"",
- "--portability\n check for all POSIX systems (equivalent to -p -P)",
- ],
- },
- paste: {
- usage: "Usage: paste [OPTION]... [FILE]...",
- description: "Write lines consisting of the sequentially corresponding lines from\neach FILE, separated by TABs, to standard output.",
- options: COMMAND_HELP_OPTIONS.paste,
- },
- pinky: {
- usage: "Usage: pinky [OPTION]... [USER]...",
- description: "",
- options: COMMAND_HELP_OPTIONS.pinky,
- },
- printenv: {
- usage: "Usage: printenv [OPTION] [VARIABLE]...",
- description: "Print the values of the specified environment VARIABLE(s).\nIf no VARIABLE is specified, print name and value pairs for them all.",
- options: ["-0, --null end each output line with NUL, not newline"],
- after: "Your shell may have its own version of printenv, which usually supersedes\nthe version described here. Please refer to your shell's documentation\nfor details about the options it supports.",
- },
- printf: {
- usage: "Usage: printf FORMAT [ARGUMENT]...\n or: printf OPTION",
- description: "Print ARGUMENT(s) according to FORMAT, or execute according to OPTION:",
- options: [],
- },
- ptx: {
- usage: "Usage: ptx [OPTION]... [INPUT]... (without -G)\n or: ptx -G [OPTION]... [INPUT [OUTPUT]]",
- description: "Output a permuted index, including context, of the words in the input files.",
- options: COMMAND_HELP_OPTIONS.ptx,
- },
- pr: {
- usage: "Usage: pr [OPTION]... [FILE]...",
- description: "Paginate or columnate FILE(s) for printing.",
- options: COMMAND_HELP_OPTIONS.pr,
- },
- pwd: {
- usage: "Usage: pwd [OPTION]...",
- description: "Print the full filename of the current working directory.",
- options: ["-L, --logical", "-P, --physical"],
- },
- readlink: {
- usage: "Usage: readlink [OPTION]... FILE...",
- description: "Print value of a symbolic link or canonical file name",
- options: [
- "-f, --canonicalize\n canonicalize by following every symlink\n in every component of the given name recursively;\n all but the last component must exist",
- "-e, --canonicalize-existing\n canonicalize by following every symlink\n in every component of the given name recursively;\n all components must exist",
- "-m, --canonicalize-missing\n canonicalize by following every symlink\n in every component of the given name recursively,\n without requirements on components existence",
- "-n, --no-newline\n do not output the trailing delimiter",
- "-q, --quiet\n suppress most error messages\n (on by default if POSIXLY_CORRECT is not set)",
- "-s, --silent\n suppress most error messages\n (on by default if POSIXLY_CORRECT is not set)",
- "-v, --verbose\n report error messages\n (on by default if POSIXLY_CORRECT is set)",
- "-z, --zero\n end each output line with NUL, not newline",
- ],
- },
- realpath: {
- usage: "Usage: realpath [OPTION]... FILE...",
- description: "Print the resolved absolute file name.",
- options: [
- "-E, --canonicalize all but the last component must exist (default)",
- "-e, --canonicalize-existing all components of the path must exist",
- "-m, --canonicalize-missing no path components need exist or be a directory",
- "-L, --logical resolve '..' components before symlinks",
- "-P, --physical resolve symlinks as encountered (default)",
- "-q, --quiet suppress most error messages",
- "--relative-to=DIR print the resolved path relative to DIR",
- "--relative-base=DIR print absolute paths unless paths below DIR",
- "-s, --strip, --no-symlinks don't expand symlinks",
- "-z, --zero end each output line with NUL, not newline",
- ],
- },
- rmdir: {
- usage: "Usage: rmdir [OPTION]... DIRECTORY...",
- description: "Remove the DIRECTORY(ies), if they are empty.",
- options: ["--ignore-fail-on-non-empty", "-p, --parents", "-v, --verbose"],
- },
- runcon: {
- usage: "Usage: runcon CONTEXT COMMAND [args]\n or: runcon [ -c ] [-u USER] [-r ROLE] [-t TYPE] [-l RANGE] COMMAND [args]",
- description: "Run COMMAND with specified SELinux security context.",
- options: COMMAND_HELP_OPTIONS.runcon,
- },
- rm: {
- usage: "Usage: rm [OPTION]... [FILE]...",
- description: "Remove (unlink) the FILE(s).",
- options: COMMAND_HELP_OPTIONS.rm,
- },
- sum: {
- usage: "Usage: sum [OPTION]... [FILE]...",
- description: "Print or check BSD (16-bit) checksums.\nLegacy interface to the cksum utility.\n\nWith no FILE, or when FILE is -, read standard input.",
- options: [
- "-r\n use BSD sum algorithm (the default), use 1K blocks",
- "-s, --sysv\n use System V sum algorithm, use 512 bytes blocks",
- ],
- },
- tac: {
- usage: "Usage: tac [OPTION]... [FILE]...",
- description: "Write each FILE to standard output, last line first.",
- options: COMMAND_HELP_OPTIONS.tac,
- },
- sync: {
- usage: "Usage: sync [OPTION] [FILE]...",
- description: "Synchronize cached writes to persistent storage\n\nIf one or more files are specified, sync only them,\nor their containing file systems.",
- options: [
- "-d, --data sync only file data, no unneeded metadata",
- "-f, --file-system sync the file systems that contain the files",
- ],
- },
- shuf: {
- usage: "Usage: shuf [OPTION]... [FILE]\n or: shuf -e [OPTION]... [ARG]...\n or: shuf -i LO-HI [OPTION]...",
- description: "Write a random permutation of the input lines to standard output.",
- options: COMMAND_HELP_OPTIONS.shuf,
- },
- shred: {
- usage: "Usage: shred [OPTION]... FILE...",
- description: "Overwrite the specified FILE(s) repeatedly, in order to make it harder\nfor even very expensive hardware probing to recover the data.",
- options: COMMAND_HELP_OPTIONS.shred,
- },
- sort: {
- usage: "Usage: sort [OPTION]... [FILE]...\n or: sort [OPTION]... --files0-from=F",
- description: "Write sorted concatenation of all FILE(s) to standard output.",
- options: COMMAND_HELP_OPTIONS.sort,
- },
- seq: {
- usage: "Usage: seq [OPTION]... LAST\n or: seq [OPTION]... FIRST LAST\n or: seq [OPTION]... FIRST INCREMENT LAST",
- description: "Print numbers from FIRST to LAST, in steps of INCREMENT.",
- options: COMMAND_HELP_OPTIONS.seq,
- },
- sha1sum: {
- usage: "Usage: sha1sum [OPTION]... [FILE]...",
- description: "Print or check SHA1 (160-bit) checksums.\nLegacy interface to the cksum utility.",
- options: COMMAND_HELP_OPTIONS.sha1sum,
- },
- sha224sum: {
- usage: "Usage: sha224sum [OPTION]... [FILE]...",
- description: "Print or check SHA224 (224-bit) checksums.\nLegacy interface to the cksum utility.",
- options: COMMAND_HELP_OPTIONS.sha224sum,
- },
- sha256sum: {
- usage: "Usage: sha256sum [OPTION]... [FILE]...",
- description: "Print or check SHA256 (256-bit) checksums.\nLegacy interface to the cksum utility.",
- options: COMMAND_HELP_OPTIONS.sha256sum,
- },
- sha384sum: {
- usage: "Usage: sha384sum [OPTION]... [FILE]...",
- description: "Print or check SHA384 (384-bit) checksums.\nLegacy interface to the cksum utility.",
- options: COMMAND_HELP_OPTIONS.sha384sum,
- },
- sha512sum: {
- usage: "Usage: sha512sum [OPTION]... [FILE]...",
- description: "Print or check SHA512 (512-bit) checksums.\nLegacy interface to the cksum utility.",
- options: COMMAND_HELP_OPTIONS.sha512sum,
- },
- sm3sum: {
- usage: "Usage: sm3sum [OPTION]... [FILE]...",
- description: "Print or check SM3 (256-bit) checksums.\nLegacy interface to the cksum utility.",
- options: COMMAND_HELP_OPTIONS.sm3sum,
- },
- split: {
- usage: "Usage: split [OPTION]... [FILE [PREFIX]]",
- description: "Output pieces of FILE to PREFIXaa, PREFIXab, ...;\ndefault size is 1000 lines, and default PREFIX is 'x'.",
- options: COMMAND_HELP_OPTIONS.split,
- },
- stat: {
- usage: "Usage: stat [OPTION]... FILE...",
- description: "Display file or file system status.",
- options: COMMAND_HELP_OPTIONS.stat,
- },
- tail: {
- usage: "Usage: tail [OPTION]... [FILE]...",
- description: "Print the last 10 lines of each FILE to standard output.\nWith more than one FILE, precede each with a header giving the file name.",
- options: COMMAND_HELP_OPTIONS.tail,
- },
- tee: {
- usage: "Usage: tee [OPTION]... [FILE]...",
- description: "Copy standard input to each FILE, and also to standard output.",
- options: COMMAND_HELP_OPTIONS.tee,
- },
- stty: {
- usage: "Usage: stty [-F DEVICE | --file=DEVICE] [SETTING]...\n or: stty [-F DEVICE | --file=DEVICE] [-a|--all]\n or: stty [-F DEVICE | --file=DEVICE] [-g|--save]",
- description: "Print or change terminal characteristics.",
- options: COMMAND_HELP_OPTIONS.stty,
- },
- stdbuf: {
- usage: "Usage: stdbuf OPTION... COMMAND",
- description: "Run COMMAND, with modified buffering operations for its standard streams.\n\nMandatory arguments to long options are mandatory for short options too.",
- options: [
- "-i, --input=MODE adjust standard input stream buffering",
- "-o, --output=MODE adjust standard output stream buffering",
- "-e, --error=MODE adjust standard error stream buffering",
- ],
- after: "If MODE is 'L' the corresponding stream will be line buffered.\nThis option is invalid with standard input.\n\nIf MODE is '0' the corresponding stream will be unbuffered.\n\nOtherwise MODE is a number which may be followed by one of the following:\nKB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G,T,P,E,Z,Y,R,Q.\nBinary prefixes can be used, too: KiB=K, MiB=M, and so on.\nIn this case the corresponding stream will be fully buffered with the buffer\nsize set to MODE bytes.\n\nNOTE: If COMMAND adjusts the buffering of its standard streams ('tee' does\nfor example) then that will override corresponding changes by 'stdbuf'.\nAlso some filters (like 'dd' and 'cat' etc.) don't use streams for I/O,\nand are thus unaffected by 'stdbuf' settings.\n\nExit status:\n 125 if the stdbuf command itself fails\n 126 if COMMAND is found but cannot be invoked\n 127 if COMMAND cannot be found\n - the exit status of COMMAND otherwise",
- },
- touch: {
- usage: "Usage: touch [OPTION]... FILE...",
- description: "Update the access and modification times of each FILE to the current time.",
- options: COMMAND_HELP_OPTIONS.touch,
- },
- timeout: {
- usage: "Usage: timeout [OPTION]... DURATION COMMAND [ARG]...",
- description: "Start COMMAND, and kill it if still running after DURATION.",
- options: COMMAND_HELP_OPTIONS.timeout,
- },
- tr: {
- usage: "Usage: tr [OPTION]... STRING1 [STRING2]",
- description: "Translate, squeeze, and/or delete characters from standard input,\nwriting to standard output.",
- options: COMMAND_HELP_OPTIONS.tr,
- },
- truncate: {
- usage: "Usage: truncate OPTION... FILE...",
- description: "Shrink or extend the size of each FILE to the specified size",
- options: ["-c, --no-create", "-o, --io-blocks", "-r, --reference=RFILE", "-s, --size=SIZE"],
- },
- tsort: {
- usage: "Usage: tsort [OPTION] [FILE]",
- description: "Write totally ordered list consistent with the partial ordering in FILE.\n\nWith no FILE, or when FILE is -, read standard input.",
- },
- tty: {
- usage: "Usage: tty [OPTION]...",
- description: "Print the file name of the terminal connected to standard input.",
- options: ["-s, --silent, --quiet\n print nothing, only return an exit status"],
- },
- uname: {
- usage: "Usage: uname [OPTION]...",
- description: "Print certain system information. With no OPTION, same as -s.",
- options: COMMAND_HELP_OPTIONS.uname,
- },
- unexpand: {
- usage: "Usage: unexpand [OPTION]... [FILE]...",
- description: "Convert blanks in each FILE to tabs, writing to standard output.",
- options: COMMAND_HELP_OPTIONS.unexpand,
- },
- uniq: {
- usage: "Usage: uniq [OPTION]... [INPUT [OUTPUT]]",
- description: "Filter adjacent matching lines from INPUT (or standard input),\nwriting to OUTPUT (or standard output).",
- options: COMMAND_HELP_OPTIONS.uniq,
- },
- uptime: {
- usage: "Usage: uptime [OPTION]... [FILE]",
- description: "Print the current time, the length of time the system has been up,\nthe number of users on the system, and the average number of jobs\nin the run queue over the last 1, 5 and 15 minutes.\nIf FILE is not specified, use /var/run/utmp. /var/log/wtmp as FILE is common.",
- },
- users: {
- usage: "Usage: users [OPTION]... [FILE]",
- description: "Output who is currently logged in according to FILE.\nIf FILE is not specified, use /var/run/utmp. /var/log/wtmp as FILE is common.",
- },
- vdir: {
- usage: "Usage: vdir [OPTION]... [FILE]...",
- description: "List information about the FILEs (the current directory by default).\nSort entries alphabetically if none of -cftuvSUX nor --sort is specified.",
- options: COMMAND_HELP_OPTIONS.vdir,
- },
- whoami: {
- usage: "Usage: whoami [OPTION]...",
- description: "Print the user name associated with the current effective user ID.\nSame as id -un.",
- },
- wc: {
- usage: "Usage: wc [OPTION]... [FILE]...\n or: wc [OPTION]... --files0-from=F",
- description: "Print newline, word, and byte counts for each FILE, and a total line if\nmore than one FILE is specified.",
- options: COMMAND_HELP_OPTIONS.wc,
- },
- who: {
- usage: "Usage: who [OPTION]... [ FILE | ARG1 ARG2 ]",
- description: "Print information about users who are currently logged in.",
- options: COMMAND_HELP_OPTIONS.who,
- },
-};
-const libc = dlopen("libc.so.6", {
- chdir: { args: [FFIType.cstring], returns: FFIType.i32 },
- chroot: { args: [FFIType.cstring], returns: FFIType.i32 },
- execve: { args: [FFIType.cstring, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 },
- execvp: { args: [FFIType.cstring, FFIType.ptr], returns: FFIType.i32 },
- dlsym: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.ptr },
- __errno_location: { args: [], returns: FFIType.ptr },
- chmod: { args: [FFIType.cstring, FFIType.u32], returns: FFIType.i32 },
- clock_settime: { args: [FFIType.i32, FFIType.ptr], returns: FFIType.i32 },
- fcntl: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
- lseek: { args: [FFIType.i32, FFIType.i64, FFIType.i32], returns: FFIType.i64 },
- memset: { args: [FFIType.ptr, FFIType.i32, FFIType.u64], returns: FFIType.ptr },
- syscall: { args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64], returns: FFIType.i64 },
- ioctl: { args: [FFIType.i32, FFIType.u64, FFIType.u64], returns: FFIType.i32 },
- kill: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
- poll: { args: [FFIType.ptr, FFIType.u64, FFIType.i32], returns: FFIType.i32 },
- renameat2: { args: [FFIType.i32, FFIType.cstring, FFIType.i32, FFIType.cstring, FFIType.u32], returns: FFIType.i32 },
- sched_getscheduler: { args: [FFIType.i32], returns: FFIType.i32 },
- signal: { args: [FFIType.i32, FFIType.ptr], returns: FFIType.ptr },
- sync: { args: [], returns: FFIType.void },
- _exit: { args: [FFIType.i32], returns: FFIType.void },
- sethostname: { args: [FFIType.cstring, FFIType.u64], returns: FFIType.i32 },
- setgid: { args: [FFIType.u32], returns: FFIType.i32 },
- setgroups: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 },
- setuid: { args: [FFIType.u32], returns: FFIType.i32 },
- statfs: { args: [FFIType.cstring, FFIType.ptr], returns: FFIType.i32 },
- statx: { args: [FFIType.i32, FFIType.cstring, FFIType.i32, FFIType.u32, FFIType.ptr], returns: FFIType.i32 },
- tcgetattr: { args: [FFIType.i32, FFIType.ptr], returns: FFIType.i32 },
- tcsetattr: { args: [FFIType.i32, FFIType.i32, FFIType.ptr], returns: FFIType.i32 },
- mkfifo: { args: [FFIType.cstring, FFIType.u32], returns: FFIType.i32 },
- mknod: { args: [FFIType.cstring, FFIType.u32, FFIType.u64], returns: FFIType.i32 },
- opendir: { args: [FFIType.cstring], returns: FFIType.ptr },
- readdir: { args: [FFIType.ptr], returns: FFIType.ptr },
- closedir: { args: [FFIType.ptr], returns: FFIType.i32 },
- inotify_init1: { args: [FFIType.i32], returns: FFIType.i32 },
- inotify_add_watch: { args: [FFIType.i32, FFIType.cstring, FFIType.u32], returns: FFIType.i32 },
- inotify_rm_watch: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
- getpriority: { args: [FFIType.i32, FFIType.u32], returns: FFIType.i32 },
- capget: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.i32 },
- getxattr: { args: [FFIType.cstring, FFIType.cstring, FFIType.ptr, FFIType.u64], returns: FFIType.i64 },
- setxattr: { args: [FFIType.cstring, FFIType.cstring, FFIType.ptr, FFIType.u64, FFIType.i32], returns: FFIType.i32 },
- lsetxattr: { args: [FFIType.cstring, FFIType.cstring, FFIType.ptr, FFIType.u64, FFIType.i32], returns: FFIType.i32 },
- setpriority: { args: [FFIType.i32, FFIType.u32, FFIType.i32], returns: FFIType.i32 },
- setlocale: { args: [FFIType.i32, FFIType.cstring], returns: FFIType.ptr },
- nl_langinfo: { args: [FFIType.i32], returns: FFIType.ptr },
- strcoll: { args: [FFIType.cstring, FFIType.cstring], returns: FFIType.i32 },
- truncate: { args: [FFIType.cstring, FFIType.i64], returns: FFIType.i32 },
- utimensat: { args: [FFIType.i32, FFIType.cstring, FFIType.ptr, FFIType.i32], returns: FFIType.i32 },
-});
-let libselinux;
-let libselinuxResolved = false;
-
-function selinuxApi() {
- if (libselinuxResolved) return libselinux;
- libselinuxResolved = true;
- try {
- libselinux = dlopen("libselinux.so.1", {
- context_free: { args: [FFIType.ptr], returns: FFIType.void },
- context_new: { args: [FFIType.cstring], returns: FFIType.ptr },
- context_range_set: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.i32 },
- context_role_set: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.i32 },
- context_str: { args: [FFIType.ptr], returns: FFIType.ptr },
- context_type_set: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.i32 },
- context_user_set: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.i32 },
- getcon: { args: [FFIType.ptr], returns: FFIType.i32 },
- getfilecon: { args: [FFIType.cstring, FFIType.ptr], returns: FFIType.i32 },
- lgetfilecon: { args: [FFIType.cstring, FFIType.ptr], returns: FFIType.i32 },
- freecon: { args: [FFIType.ptr], returns: FFIType.void },
- security_check_context: { args: [FFIType.cstring], returns: FFIType.i32 },
- security_compute_create: { args: [FFIType.cstring, FFIType.cstring, FFIType.u16, FFIType.ptr], returns: FFIType.i32 },
- setexeccon: { args: [FFIType.cstring], returns: FFIType.i32 },
- setfscreatecon: { args: [FFIType.ptr], returns: FFIType.i32 },
- setfilecon: { args: [FFIType.cstring, FFIType.cstring], returns: FFIType.i32 },
- lsetfilecon: { args: [FFIType.cstring, FFIType.cstring], returns: FFIType.i32 },
- string_to_security_class: { args: [FFIType.cstring], returns: FFIType.u16 },
- });
- } catch {
- libselinux = null;
- }
- return libselinux;
-}
-const F_GETFL = 3;
-const O_APPEND = 0o2000;
-const SEEK_SET = 0;
-const SEEK_CUR = 1;
-const SEEK_END = 2;
-const SEEK_DATA = 3;
-const SEEK_HOLE = 4;
-const POLLIN = 0x001;
-const POLLOUT = 0x004;
-const POLLERR = 0x008;
-const POLLHUP = 0x010;
-const POLLNVAL = 0x020;
-const IN_MODIFY = 0x00000002;
-const IN_ATTRIB = 0x00000004;
-const IN_CLOSE_WRITE = 0x00000008;
-const IN_MOVED_FROM = 0x00000040;
-const IN_MOVED_TO = 0x00000080;
-const IN_CREATE = 0x00000100;
-const IN_DELETE = 0x00000200;
-const IN_DELETE_SELF = 0x00000400;
-const IN_MOVE_SELF = 0x00000800;
-const SIG_DFL = 0;
-const SIG_IGN = 1;
-const TCSANOW = 0;
-const TCSADRAIN = 1;
-const TIOCGWINSZ = 0x5413;
-const TIOCSWINSZ = 0x5414;
-const TERMIOS_SIZE = 60;
-const TERMIOS_OFFSETS = { iflag: 0, oflag: 4, cflag: 8, lflag: 12, line: 16, cc: 17, ispeed: 52, ospeed: 56 };
-const STTY_CC = { intr: 0, quit: 1, erase: 2, kill: 3, eof: 4, eol: 11, eol2: 16, swtch: 7, start: 8, stop: 9, susp: 10, rprnt: 12, werase: 14, lnext: 15, discard: 13, min: 6, time: 5 };
-const STTY_FLAGS = {
- iflag: { ignbrk: 0o1, brkint: 0o2, ignpar: 0o4, parmrk: 0o10, inpck: 0o20, istrip: 0o40, inlcr: 0o100, igncr: 0o200, icrnl: 0o400, iuclc: 0o1000, ixon: 0o2000, ixany: 0o4000, ixoff: 0o10000, imaxbel: 0o20000, iutf8: 0o40000 },
- oflag: { opost: 0o1, olcuc: 0o2, onlcr: 0o4, ocrnl: 0o10, onocr: 0o20, onlret: 0o40, ofill: 0o100, ofdel: 0o200 },
- cflag: { cs5: 0o0, cs6: 0o20, cs7: 0o40, cs8: 0o60, cstopb: 0o100, cread: 0o200, parenb: 0o400, parodd: 0o1000, hupcl: 0o2000, hup: 0o2000, clocal: 0o4000, cmspar: 0o10000000000, crtscts: 0o20000000000 },
- lflag: { isig: 0o1, icanon: 0o2, xcase: 0o4, echo: 0o10, echoe: 0o20, echok: 0o40, echonl: 0o100, noflsh: 0o200, tostop: 0o400, echoctl: 0o1000, echoprt: 0o2000, echoke: 0o4000, flusho: 0o10000, iexten: 0o100000, extproc: 0o200000 },
-};
-const STTY_CS_MASK = 0o60;
-const STTY_DELAY_GROUPS = {
- nl: { mask: 0x100, values: { nl0: 0x0, nl1: 0x100 } },
- cr: { mask: 0x600, values: { cr0: 0x0, cr1: 0x200, cr2: 0x400, cr3: 0x600 } },
- tab: { mask: 0x1800, values: { tab0: 0x0, tab1: 0x800, tab2: 0x1000, tab3: 0x1800 } },
- bs: { mask: 0x2000, values: { bs0: 0x0, bs1: 0x2000 } },
- vt: { mask: 0x4000, values: { vt0: 0x0, vt1: 0x4000 } },
- ff: { mask: 0x8000, values: { ff0: 0x0, ff1: 0x8000 } },
-};
-const STTY_OBAUD_MASK = 0x100f;
-const STTY_IBAUD_MASK = 0x100f0000;
-const STTY_SPEED_CODES = new Map([
- [0, 0], [50, 1], [75, 2], [110, 3], [134, 4], [150, 5], [200, 6], [300, 7],
- [600, 8], [1200, 9], [1800, 10], [2400, 11], [4800, 12], [9600, 13],
- [19200, 14], [38400, 15], [57600, 0x1001], [115200, 0x1002], [230400, 0x1003],
- [460800, 0x1004], [500000, 0x1005], [576000, 0x1006], [921600, 0x1007],
- [1000000, 0x1008], [1152000, 0x1009], [1500000, 0x100a], [2000000, 0x100b],
- [2500000, 0x100c], [3000000, 0x100d], [3500000, 0x100e], [4000000, 0x100f],
-]);
-const STTY_CODE_SPEEDS = new Map([...STTY_SPEED_CODES].map(([speed, code]) => [code, speed]));
-let sttyTermiosApi;
-
-function sttyInterposedTermiosApi() {
- if (sttyTermiosApi) return sttyTermiosApi;
- const symbols = {};
- for (const name of ["cfsetispeed", "cfsetospeed"]) {
- const address = libc.symbols.dlsym(0, ptr(Buffer.from(`${name}\0`)));
- symbols[name] = { ptr: address, args: [FFIType.ptr, FFIType.u32], returns: FFIType.i32 };
- }
- sttyTermiosApi = linkSymbols(symbols).symbols;
- return sttyTermiosApi;
-}
-
-class UsageError extends Error {
- constructor(message, showHelp = false) {
- super(message);
- this.showHelp = showHelp;
- }
-}
-
-class InvocationError extends UsageError {
- constructor(message, code = 125, showHelp = true) {
- super(message, showHelp);
- this.code = code;
- }
-}
-
-const enc = new TextEncoder();
-let splitFilterTempId = 0;
-let reflinkTempId = 0;
-let stdinLineBuffer = "";
-const emittedDiagnosticHints = new Set();
-const SIGPIPE_MASK = 1n << 12n;
-const BNU_SIGPIPE_DEFAULT_ENV = "BNU_SIGPIPE_DEFAULT";
-const FICLONE = 0x40049409;
-const BLKGETSIZE64 = 0x80081272;
-const AT_FDCWD = -100;
-const AT_SYMLINK_NOFOLLOW = 0x100;
-const STATX_ALL = 0x0fff;
-const RENAME_EXCHANGE = 2;
-const UINTMAX_MAX = 18446744073709551615n;
-const DD_EBCDIC_TO_ASCII = Uint8Array.from([
- 0x00, 0x01, 0x02, 0x03, 0x9c, 0x09, 0x86, 0x7f, 0x97, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
- 0x10, 0x11, 0x12, 0x13, 0x9d, 0x85, 0x08, 0x87, 0x18, 0x19, 0x92, 0x8f, 0x1c, 0x1d, 0x1e, 0x1f,
- 0x80, 0x81, 0x82, 0x83, 0x84, 0x0a, 0x17, 0x1b, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07,
- 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a,
- 0x20, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xd5, 0x2e, 0x3c, 0x28, 0x2b, 0x7c,
- 0x26, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x7e,
- 0x2d, 0x2f, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xcb, 0x2c, 0x25, 0x5f, 0x3e, 0x3f,
- 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0x60, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22,
- 0xc3, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9,
- 0xca, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x5e, 0xcc, 0xcd, 0xce, 0xcf, 0xd0,
- 0xd1, 0xe5, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0xd2, 0xd3, 0xd4, 0x5b, 0xd6, 0xd7,
- 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0x5d, 0xe6, 0xe7,
- 0x7b, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed,
- 0x7d, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3,
- 0x5c, 0x9f, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9,
- 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
-]);
-
-function stdout(data = "") {
- try {
- writeAllSync(1, data instanceof Uint8Array ? data : String(data));
- } catch (error) {
- if (error?.code === "EPIPE") process.exit(0);
- throw error;
- }
-}
-
-function stderr(data = "", ensureHint = false) {
- const text = String(data);
- writeAllSync(2, gnulyCorrectDiagnostics() ? text : enhanceDiagnostic(text, ensureHint));
-}
-
-function gnulyCorrectDiagnostics() {
- const value = process.env.GNULY_CORRECT;
- return value !== undefined && !/^(?:|0|false)$/i.test(value);
-}
-
-function enhanceDiagnostic(text, ensureHint = false) {
- if (!text.endsWith("\n") || /^(?:Hint|Warning):/m.test(text)) return text;
- const firstLine = text.split("\n", 1)[0];
- if (!/^[^:\n]+:\s/.test(firstLine) || /:\s*(?:warning|debug):?\s/i.test(firstLine)) return text;
- const program = firstLine.slice(0, firstLine.indexOf(":"));
- const hint = diagnosticHint(program, text) ?? (ensureHint ? genericDiagnosticHint(program) : null);
- if (!hint || emittedDiagnosticHints.has(hint)) return text;
- emittedDiagnosticHints.add(hint);
- const tryLine = text.indexOf("\nTry '");
- if (tryLine !== -1) return `${text.slice(0, tryLine + 1)}Hint: ${hint}\n${text.slice(tryLine + 1)}`;
- return `${text}Hint: ${hint}\n`;
-}
-
-function diagnosticHint(program, diagnostic) {
- if (program === "comm" && /^comm: -\n?$/.test(diagnostic)) {
- return "Use standard input for only one input file; the other operand must name a file.";
- }
- const unknownCommand = diagnostic.match(/unknown command ['‘]([^'’]+)['’]/)?.[1];
- if (unknownCommand) {
- const suggestion = closestValue(unknownCommand, commandNames);
- return suggestion
- ? `Did you mean '${suggestion}'? Run 'bnu --help' to list commands.`
- : "Run 'bnu --help' to list available commands.";
- }
- const longOption = diagnostic.match(/unrecognized option ['‘](--[^'’=]+)(?:=[^'’]*)?['’]/)?.[1];
- if (longOption) {
- const suggestion = closestLongOption(program, longOption);
- return suggestion
- ? `Did you mean '${suggestion}'? Run '${program} --help' to see all options.`
- : `Check the option spelling, or run '${program} --help' to see all options.`;
- }
- if (/invalid option -- |option .* is ambiguous/.test(diagnostic)) {
- return `Check the option spelling, or run '${program} --help' to see all options.`;
- }
- if (/option .*requires an argument|option requires an argument/.test(diagnostic)) {
- const option = diagnostic.match(/option ['‘](--[^'’]+)['’] requires/)?.[1]
- ?? diagnostic.match(/option requires an argument -- ['‘]([^'’]+)['’]/)?.[1];
- return option?.startsWith("--")
- ? `Provide the missing value as '${option}=VALUE' or '${option} VALUE'.`
- : option
- ? `Provide the missing value after '-${option}'.`
- : `Provide a value for the option. Run '${program} --help' for the expected form.`;
- }
- if (/doesn't allow an argument/.test(diagnostic)) {
- const option = diagnostic.match(/option ['‘](--[^'’]+)['’]/)?.[1];
- return option ? `Use '${option}' by itself; this flag does not take a value.` : "Remove the value supplied to this flag.";
- }
- if (/missing operand|missing file operand|a command must be given/.test(diagnostic)) {
- return commandUsageHint(program, "Add the required argument");
- }
- if (/extra operand|extra argument|too many arguments/.test(diagnostic)) {
- return commandUsageHint(program, "Remove the extra argument");
- }
- if (/mutually exclusive|cannot combine|may not be combined|are incompatible|conflicting .* specifiers|cannot specify .* more than one source/.test(diagnostic)) {
- return "Remove one of the conflicting options and try again.";
- }
- if (/ambiguous argument/.test(diagnostic)) {
- return `Use a complete, unambiguous value. Run '${program} --help' for accepted values.`;
- }
- if (/Valid arguments are:/.test(diagnostic)) {
- return "Choose one of the valid values listed above and try again.";
- }
- if (/multiple .* (?:specified|sources)|used more than once/.test(diagnostic)) {
- return "Keep only one value for this setting, or remove the duplicate option.";
- }
- if (/only one .* may be specified|cannot .* in more than one way/.test(diagnostic)) {
- return "Select one operating mode and remove the other mode options.";
- }
- if (/delimiter must be a single character|multi-character (?:tab|separator)|separator cannot be empty|empty (?:tab|record separator)/.test(diagnostic)) {
- return "Use exactly one character as the delimiter or separator.";
- }
- if (/numbered from 1|field number is zero|character offset is zero/.test(diagnostic)) {
- return "Use a position of 1 or greater; zero is not a valid field or character position.";
- }
- if (/invalid decreasing range|range-endpoints .* reverse|tab sizes must be ascending/.test(diagnostic)) {
- return "Put the lower position first and list ranges in ascending order.";
- }
- if (/invalid range with no endpoint|invalid .* range|invalid field specification/.test(diagnostic)) {
- return "Use a range such as 'N', 'N-M', 'N-', or '-M' with valid positive positions.";
- }
- if (/meaningless|meaningful only|only supported|does not support|only when|makes sense/.test(diagnostic)) {
- return "Remove the option that has no effect here, or enable the mode that option requires.";
- }
- if (/no lines to repeat/.test(diagnostic)) {
- return "Provide non-empty input, or remove --repeat.";
- }
- if (/missing (?:encoding type|mode)|must specify .* mode|must specify a list/.test(diagnostic)) {
- return commandUsageHint(program, "Select the required mode");
- }
- if (/template .* must end in X|too few X's in template|invalid (?:template|suffix).*directory separator/.test(diagnostic)) {
- return "Use a template ending in at least three X characters and keep any suffix free of '/'.";
- }
- if (/out of range|overflow|value too (?:large|small)/i.test(diagnostic)) {
- return "Choose a value within the supported range and try again.";
- }
- if (/invalid zero-length file name|empty file name/.test(diagnostic)) {
- return "Remove the empty path entry from the input list.";
- }
- if (/when reading file names from standard input, no file name of '-' allowed/.test(diagnostic)) {
- return "Remove '-' from the file-name list; standard input is already being used for that list.";
- }
- if (/No such file or directory|No such device or address/.test(diagnostic)) {
- return "Check that the path exists and is spelled correctly.";
- }
- if (/Permission denied|Operation not permitted/.test(diagnostic)) {
- return "Check the file permissions and whether this operation needs additional privileges.";
- }
- if (/Is a directory/.test(diagnostic)) {
- return "Use a file instead, or select an option that supports directories.";
- }
- if (/Not a directory/.test(diagnostic)) {
- return "Check that every parent component of the path is a directory.";
- }
- if (/Directory not empty/.test(diagnostic)) {
- return "Remove the directory contents first, or use the command's recursive option if appropriate.";
- }
- if (/File exists/.test(diagnostic)) {
- return "Choose a different destination or remove the existing one first.";
- }
- if (/No space left on device/.test(diagnostic)) {
- return "Free some space on the destination filesystem and try again.";
- }
- if (/Disk quota exceeded/.test(diagnostic)) {
- return "Free space within your quota or choose a different destination.";
- }
- if (/File too large/.test(diagnostic)) {
- return "Use a smaller output or a filesystem that supports larger files.";
- }
- if (/File name too long/.test(diagnostic)) {
- return "Shorten the file name or one of its parent directory names.";
- }
- if (/Read-only file system/.test(diagnostic)) {
- return "Choose a writable destination or remount the filesystem read-write.";
- }
- if (/Too many open files/.test(diagnostic)) {
- return "Close unused file descriptors or raise the process file-descriptor limit.";
- }
- if (/Cannot allocate memory|Out of memory/.test(diagnostic)) {
- return "Reduce the input size or memory usage, or make more memory available.";
- }
- if (/Device or resource busy|Text file busy/.test(diagnostic)) {
- return "Wait for the resource to become available or stop the process currently using it.";
- }
- if (/Invalid cross-device link/.test(diagnostic)) {
- return "Use a copy followed by removal when moving data between filesystems.";
- }
- if (/Operation not supported|Not supported/.test(diagnostic)) {
- return "Choose an operation supported by this filesystem or platform.";
- }
- if (/Bad file descriptor/.test(diagnostic)) {
- return "Check that the referenced input or output descriptor is open and usable.";
- }
- if (/Input\/output error/.test(diagnostic)) {
- return "Check the device and filesystem health, then retry the operation.";
- }
- if (/Too many levels of symbolic links/.test(diagnostic)) {
- return "Check the path for a symbolic-link loop.";
- }
- if (/input is not in sorted order|: is not sorted:/.test(diagnostic)) {
- return "Sort each input using the same comparison rules, then try again.";
- }
- if (/omitting directory/.test(diagnostic)) {
- return `Add the recursive option if you intend ${program} to process a directory tree.`;
- }
- if (/are the same file/.test(diagnostic)) {
- return "Choose a destination that is different from the source.";
- }
- if (/no such user|no such group/.test(diagnostic)) {
- return "Check that the account name exists, or use a numeric ID where supported.";
- }
- if (/no login name/.test(diagnostic)) {
- return "Run this from a login session, or use a command such as 'whoami' for the effective user.";
- }
- if (/cannot skip past end|cannot skip to specified offset/.test(diagnostic)) {
- return "Reduce the requested offset so it falls within the available input.";
- }
- if (/input contains a loop/.test(diagnostic)) {
- return "Remove a dependency cycle from the input graph and try again.";
- }
- if (/input contains an odd number of tokens/.test(diagnostic)) {
- return "Provide dependency tokens in pairs: one item followed by the item that depends on it.";
- }
- if (/not listing already-listed directory/.test(diagnostic)) {
- return "Check the directory tree for a cycle, usually caused by a symbolic link.";
- }
- if (/no files remaining/.test(diagnostic)) {
- return "Check the input paths, or use --retry when following names that may reappear.";
- }
- if (/no file systems processed/.test(diagnostic)) {
- return "Check the requested paths and filesystem-type filters.";
- }
- if (/couldn't get boot time/.test(diagnostic)) {
- return "Check that the system exposes readable boot-time accounting information.";
- }
- if (/no input from|cannot read file names from/.test(diagnostic)) {
- return "Check that the file-name list is readable and contains valid entries.";
- }
- if (/using '-' to denote standard input does not work in file system mode/.test(diagnostic)) {
- return "Name a filesystem path instead of '-' when using filesystem mode.";
- }
- if (/regular expression has length zero|invalid (?:regular expression|pattern)/.test(diagnostic)) {
- return "Use a non-empty, valid regular expression for the selected command.";
- }
- if (/match not found/.test(diagnostic)) {
- return "Adjust the pattern so it matches the input, or remove that split point.";
- }
- if (/line number .* smaller than preceding|line number .* same as preceding/.test(diagnostic)) {
- return "List split line numbers once each and in strictly increasing order.";
- }
- if (/starting page number .* exceeds page count/.test(diagnostic)) {
- return "Choose a starting page that exists in the input.";
- }
- if (/closing delimiter .* missing|integer expected after delimiter/.test(diagnostic)) {
- return "Close the pattern delimiter and place any numeric offset after it.";
- }
- if (/syntax error|unexpected argument|expecting ['‘]?\)|Unmatched|Trailing backslash/.test(diagnostic)) {
- return "Correct the expression syntax, balancing parentheses, escapes, and operators.";
- }
- if (/non-integer argument/.test(diagnostic)) {
- return "Use integer operands for arithmetic operations.";
- }
- if (/division by zero/.test(diagnostic)) {
- return "Use a nonzero divisor.";
- }
- if (/format .* (?:ends in %|has no % directive|has too many % directives|has unknown .* directive)|invalid precision in format/.test(diagnostic)) {
- return invalidValueHint(program, diagnostic);
- }
- if (/checksum.*(?:did NOT match|mismatch)|computed checksum.*not match/i.test(diagnostic)) {
- return "Verify that the file and expected checksum came from the same source.";
- }
- if (/no properly formatted checksum lines found|improperly formatted .* checksum line/.test(diagnostic)) {
- return "Check the checksum file format and selected checksum algorithm.";
- }
- if (/failed to set locale/.test(diagnostic)) {
- return "Select an installed locale, for example by setting LC_ALL=C.";
- }
- if (/Host name lookup failure/.test(diagnostic)) {
- return "Check the host name and DNS or hosts-file configuration.";
- }
- if (/can't open/.test(diagnostic)) {
- return "Check that the file exists and is readable.";
- }
- if (/this system doesn't provide/.test(diagnostic)) {
- return "Choose a data type or feature supported by this platform.";
- }
- if (/cannot fstat|failed to stat|cannot stat|cannot access|failed to access/.test(diagnostic)) {
- return "Check that the path exists and that its metadata is accessible.";
- }
- if (/cannot unlink|cannot remove|failed to remove/.test(diagnostic)) {
- return "Check that the path exists, is writable, and is not protected or in use.";
- }
- if (/failed to run command|cannot run|could not run|failed to execute|not found in PATH/.test(diagnostic)) {
- return "Check that the command exists, is executable, and is available on PATH.";
- }
- if (/cannot create link|failed to create link/.test(diagnostic)) {
- return "Check the source, destination, permissions, and filesystem link support.";
- }
- if (/input file is output file/.test(diagnostic)) {
- return "Choose an output path different from the input path.";
- }
- if (/cannot (?:copy|move) a directory.*into itself|cannot move .* subdirectory of itself/.test(diagnostic)) {
- return "Choose a destination outside the source directory tree.";
- }
- if (/will not overwrite just-created/.test(diagnostic)) {
- return "Give each source a distinct destination name instead of targeting the same newly created path.";
- }
- if (/target .* is not a directory|target directory .*Not a directory|destination must be a directory/.test(diagnostic)) {
- return "Use an existing directory as the destination, or provide only one source file.";
- }
- if (/not writing through dangling symlink/.test(diagnostic)) {
- return "Repair or remove the dangling destination symlink, then try again.";
- }
- if (/inter-device move failed.*--no-copy specified/.test(diagnostic)) {
- return "Remove --no-copy to allow a copy-and-delete move between filesystems.";
- }
- if (/cannot do --relative without --symbolic/.test(diagnostic)) {
- return "Add --symbolic when using --relative, or remove --relative.";
- }
- if (/preserve-root/.test(diagnostic) && /unrecognized|may not abbreviate/.test(diagnostic)) {
- return "Use the full option '--no-preserve-root', or use '--preserve-root=all'.";
- }
- if (/dangerous to operate recursively/.test(diagnostic)) {
- return "Verify the path carefully; use --no-preserve-root only if removing this protected root is intentional.";
- }
- if (/skipping .*different device|--preserve-root=all is in effect/.test(diagnostic)) {
- return "Remove --one-file-system/--preserve-root=all only if crossing this filesystem boundary is intentional.";
- }
- if (/--skip-chdir only permitted/.test(diagnostic)) {
- return "Use --skip-chdir only with NEWROOT '/', or remove --skip-chdir.";
- }
- if (/security context|SELinux|SMACK/.test(diagnostic) && /cannot|failed|invalid/.test(diagnostic)) {
- return "Use a valid security label and verify that the required security module is enabled.";
- }
- if (/backing up .* might destroy source/.test(diagnostic)) {
- return "Choose a different backup suffix or move the source away from the backup path.";
- }
- if (/through just-created symlink/.test(diagnostic)) {
- return "Remove the conflicting symbolic link or choose a different destination tree.";
- }
- if (/not replacing|cannot overwrite/.test(diagnostic)) {
- return `Choose a different destination or review '${program} --help' for overwrite options.`;
- }
- if (/\binvalid\b|not a valid|\bunsupported\b/i.test(diagnostic)) {
- return invalidValueHint(program, diagnostic);
- }
- if (/cannot open|failed to open|error reading|read error/.test(diagnostic)) {
- return "Check that the input exists and is readable.";
- }
- if (/cannot create|failed to create|error writing|write error/.test(diagnostic)) {
- return "Check that the destination exists, is writable, and has enough free space.";
- }
- if (/ignoring non-option arguments/.test(diagnostic)) {
- return `Remove the operands; '${program}' does not use positional arguments.`;
- }
- if (informationalDiagnostic(program, diagnostic)) return null;
- if (/(?:^|:\s)(?:cannot|could not|failed|error|invalid|unrecognized|unknown|missing|extra|refusing|unable|must|requires?|may not)\b/im.test(diagnostic)) {
- return genericDiagnosticHint(program);
- }
- // Direct command implementations sometimes return terse GNU diagnostics
- // without a standard error keyword. Once progress/debug output is excluded,
- // still give those failures command-specific recovery guidance.
- return invalidValueHint(program, diagnostic);
-}
-
-function genericDiagnosticHint(program) {
- return `Review the arguments and current system state, then run '${program} --help' if the problem persists.`;
-}
-
-function commandUsageHint(program, action) {
- const helpProgram = program === "ginstall" ? "install" : program;
- const usage = SPECIAL_HELP[helpProgram]?.usage?.split("\n", 1)[0]?.replace(/^Usage:\s*/, "");
- return usage
- ? `${action}. Expected form: ${usage}.`
- : `${action}. Run '${program} --help' for the expected form.`;
-}
-
-function informationalDiagnostic(program, diagnostic) {
- if (program === "sort" && /text ordering performed|key \d+ has zero width|numeric and spans multiple fields|leading blanks are significant|field separator|numbers use|options? .* (?:is|are) ignored|only applies to last-resort comparison/.test(diagnostic)) return true;
- if (program === "date" && (/only using last of multiple/.test(diagnostic) || (/date: output format:/.test(diagnostic) && !/date: error:/.test(diagnostic)))) return true;
- if (program === "cksum" && /using generic checksum implementation/.test(diagnostic)) return true;
- if (program === "numfmt" && /--header ignored|grouping has no effect|no conversion option specified|failed to convert some/.test(diagnostic)) return true;
- if (program === "timeout" && /sending signal/.test(diagnostic)) return true;
- if (program === "shred" && /: (?:pass \d+\/\d+|removing|renamed to|removed)/.test(diagnostic)) return true;
- if (program === "tail" && /using .* mode|has appeared;|has been replaced;|file truncated|reverting to polling/.test(diagnostic)) return true;
- if (program === "executing" || program === "argv0") return true;
- return false;
-}
-
-function invalidValueHint(program, diagnostic) {
- if (/Valid arguments are:/.test(diagnostic)) return "Choose one of the valid values listed above and try again.";
- const hints = {
- basename: "Check the suffix and file-name arguments shown by 'basename --help'.",
- basenc: "Check that the input uses the selected encoding and has valid padding.",
- base32: "Check that the input is valid base32 data and has correct padding.",
- base64: "Check that the input is valid base64 data and has correct padding.",
- cat: "Check the input paths and use '-' only when the data should come from standard input.",
- chcon: "Use a complete security context, or valid user, role, type, and range components.",
- chroot: "Provide a valid new root, user/group specification, and executable command.",
- chmod: "Use an octal mode such as '755' or a symbolic mode such as 'u+x'.",
- chown: "Use OWNER, OWNER:GROUP, or a numeric user and group ID.",
- chgrp: "Use an existing group name or a numeric group ID.",
- cksum: "Choose a supported algorithm and a digest length valid for that algorithm.",
- csplit: "Use a positive line number or a valid /REGEXP/ split pattern.",
- comm: "Provide exactly two sorted inputs and select valid output columns.",
- cp: "Check the copy mode, preservation attributes, and source/destination form.",
- cut: "Use positive byte, character, or field positions such as '1-3,7'.",
- date: "Use a recognized date such as '2026-07-13 14:30' or an ISO 8601 value.",
- dd: "Use NAME=VALUE operands and a byte count such as '4K', '1M', or a positive integer.",
- df: "Use a supported output field, filesystem type, or block-size value.",
- dircolors: "Check the terminal type and dircolors database syntax.",
- du: "Use a valid depth, threshold, time style, or block-size value.",
- env: "Check the environment assignment, signal name, or quoting in the -S string.",
- expand: "Use positive, ascending tab stops or a positive repeating tab size.",
- expr: "Use integer operands where arithmetic is required and check the expression syntax.",
- factor: "Provide one or more positive integers.",
- fmt: "Use a positive width, with the goal width no larger than the maximum width.",
- fold: "Use a positive line width and select at most one width-counting mode.",
- groups: "Use an existing user name, or omit it to inspect the current process.",
- head: "Use a nonnegative count, optionally with a size suffix such as K or M.",
- hostname: "Provide a readable file or a valid host name supported by the selected operation.",
- id: "Select a compatible output mode and use an existing user name or numeric ID.",
- install: "Check the mode, owner/group, context, and source/destination form.",
- join: "Use file number 1 or 2 and field numbers starting at 1.",
- kill: "Use a valid signal name/number and a numeric process ID.",
- mkdir: "Use an octal mode such as '755' or a symbolic mode such as 'u=rwx'.",
- mkfifo: "Use an octal mode such as '644' or a symbolic mode.",
- mknod: "Use type 'b', 'c', 'u', or 'p' and valid major/minor device numbers where required.",
- mktemp: "Use a template ending in at least three X characters, for example 'tmp.XXXXXX'.",
- mv: "Check the update/backup mode and provide a valid source and destination.",
- nice: "Use an integer adjustment and provide a command to execute.",
- nl: "Check the numbering style, numeric width, and regular-expression syntax.",
- numfmt: "Use a valid numeric field/range and a supported scaling or format value.",
- nproc: "Use a nonnegative integer with --ignore.",
- od: "Use a supported type string and an address radix of d, o, x, or n.",
- paste: "Use a valid delimiter list; escape a trailing backslash.",
- pr: "Use positive page dimensions and a page range such as '2' or '2:5'.",
- printf: "Check the conversion directive and ensure each '%' starts a supported format conversion.",
- pwd: "Use only -L or -P; remove positional arguments.",
- readlink: "Choose a supported canonicalization mode and provide a valid path.",
- realpath: "Choose a supported canonicalization mode and provide a valid path.",
- rm: "Check the interactive/preserve-root mode and the recursive removal options.",
- rmdir: "Name empty directories, or use --ignore-fail-on-non-empty when appropriate.",
- runcon: "Provide a valid security context or context components followed by a command.",
- seq: "Use finite numeric operands, a nonzero increment, and a floating-point output format.",
- shuf: "Use a positive count or an input range in LO-HI form.",
- shred: "Use a positive pass count, valid size, and supported removal mode.",
- sleep: "Use one or more nonnegative durations, optionally suffixed with s, m, h, or d.",
- sort: "Check the key syntax, numeric size, and selected ordering mode.",
- split: "Use a positive chunk size/count and a suffix that does not contain '/'.",
- stdbuf: "Use buffering mode 'L', '0', or a positive size such as '4K'.",
- stty: "Use a supported terminal mode, control character, or numeric speed.",
- stat: "Use a supported format, cache policy, or filesystem mode.",
- tail: "Use a nonnegative count, valid PID, or supported --follow mode.",
- tee: "Use a supported --output-error mode and writable output files.",
- test: "Check the expression arity, operators, integer operands, and balanced parentheses.",
- timeout: "Use a nonnegative duration such as '30s', '5m', or '1h'.",
- touch: "Use a recognized date, [[CC]YY]MMDDhhmm[.ss], or a valid reference file.",
- tr: "Check the character sets, ranges, classes, escapes, and repeat counts.",
- truncate: "Use an absolute size or a signed adjustment such as '+1K' or '-512'.",
- tsort: "Provide whitespace-separated dependency pairs and remove dependency cycles.",
- uniq: "Use nonnegative skip/count values and a supported grouping method.",
- unexpand: "Use positive, ascending tab stops or a positive repeating tab size.",
- wc: "Use a supported count/total mode and valid input or --files0-from list.",
- };
- return hints[program] ?? `Check the value's format. Run '${program} --help' for accepted values.`;
-}
-
-function closestLongOption(program, badOption) {
- const helpProgram = program === "ginstall" ? "install" : program;
- const options = [...new Set([...(COMMAND_HELP_OPTIONS[helpProgram] ?? []), "--help", "--version"])]
- .filter((option) => option.startsWith("--"))
- .map((option) => option.split("=", 1)[0]);
- const closest = closestValue(badOption.slice(2), options.map((option) => option.slice(2)));
- return closest == null ? null : `--${closest}`;
-}
-
-function closestValue(value, candidates) {
- if (!candidates.length) return null;
- let best = null;
- let bestDistance = Infinity;
- for (const candidate of candidates) {
- const distance = editDistance(value, candidate);
- if (distance < bestDistance) {
- best = candidate;
- bestDistance = distance;
- }
- }
- return bestDistance <= Math.max(1, Math.floor(value.length / 3)) ? best : null;
-}
-
-function editDistance(left, right) {
- let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
- for (let i = 1; i <= left.length; i++) {
- const current = [i];
- for (let j = 1; j <= right.length; j++) {
- current[j] = Math.min(
- current[j - 1] + 1,
- previous[j] + 1,
- previous[j - 1] + (left[i - 1] === right[j - 1] ? 0 : 1),
- );
- }
- previous = current;
- }
- return previous[right.length];
-}
-
-function writeAllSync(fd, data) {
- const buffer = data instanceof Uint8Array ? data : encodeSurrogateEscapedString(String(data));
- let offset = 0;
- while (offset < buffer.length) {
- const written = writeSync(fd, buffer, offset, buffer.length - offset);
- if (written === 0) throw Object.assign(new Error("write returned 0"), { code: "EIO" });
- offset += written;
- }
-}
-
-function encodeSurrogateEscapedString(text) {
- const chunks = [];
- let plain = "";
- const flush = () => {
- if (plain) {
- chunks.push(Buffer.from(plain));
- plain = "";
- }
- };
- for (let i = 0; i < text.length; i++) {
- const code = text.charCodeAt(i);
- if (code >= 0xdc80 && code <= 0xdcff) {
- flush();
- chunks.push(Buffer.from([code - 0xdc00]));
- } else {
- plain += text[i];
- }
- }
- flush();
- return Buffer.concat(chunks);
-}
-
-function decodeSurrogateEscapedBytes(bytes) {
- const decoder = new TextDecoder("utf-8", { fatal: true });
- try {
- return decoder.decode(bytes);
- } catch {
- // Preserve undecodable bytes below while still decoding each maximal
- // valid UTF-8 unit. The overwhelmingly common valid-input path above
- // avoids building large strings one code point at a time.
- }
- let out = "";
- let start = 0;
- while (start < bytes.length) {
- let end = start + 1;
- let decoded = null;
- while (end <= bytes.length) {
- try {
- decoded = decoder.decode(bytes.subarray(start, end));
- break;
- } catch {
- end++;
- }
- }
- if (decoded == null) {
- out += String.fromCharCode(0xdc00 + bytes[start++]);
- } else {
- out += decoded;
- start = end;
- }
- }
- return out;
-}
-
-function parentIgnoresSigpipe() {
- if (process.env[BNU_SIGPIPE_DEFAULT_ENV] === "1") return false;
- try {
- const status = readFileSync(`/proc/${process.ppid}/status`, "utf8");
- const ignored = status.match(/^SigIgn:\s*([0-9a-fA-F]+)/m)?.[1];
- return ignored != null && (BigInt(`0x${ignored}`) & SIGPIPE_MASK) !== 0n;
- } catch {
- return false;
- }
-}
-
-function fail(program, message, code = 1) {
- try {
- stderr(`${program}: ${message}\n`, true);
- } catch (error) {
- if (isOutputWriteError(error)) return code;
- throw error;
- }
- return code;
-}
-
-function invalidOptionMessage(arg) {
- return arg?.startsWith("--") ? `unrecognized option '${arg}'` : `invalid option -- '${String(arg ?? "").slice(1, 2)}'`;
-}
-
-function invalidClusterOptionMessage(arg, validOptions) {
- if (arg?.startsWith("--")) return invalidOptionMessage(arg);
- const option = [...String(arg ?? "").slice(1)].find((ch) => !validOptions.has(ch));
- return `invalid option -- '${option ?? String(arg ?? "").slice(1, 2)}'`;
-}
-
-function showGenericHelp(program) {
- const helpProgram = program === "ginstall" ? "install" : program;
- if (program === "[") {
- showBracketHelp();
- return;
- }
- if (program === "link") {
- showLinkHelp();
- return;
- }
- if (program === "unlink") {
- showUnlinkHelp();
- return;
- }
- if (SPECIAL_HELP[program]) {
- showSpecialHelp(program);
- return;
- }
- if (program === "cksum") {
- stdout("Usage: cksum [OPTION]... [FILE]...\n");
- stdout("Print or verify checksums.\nBy default use the 32 bit CRC algorithm.\n\n");
- stdout("Available algorithms:\n sysv\n bsd\n crc\n crc32b\n md5\n sha1\n sha2\n sha3\n blake2b\n sm3\n");
- stdout("\nOptions:\n");
- for (const option of COMMAND_HELP_OPTIONS.cksum) stdout(` ${option}\n`);
- stdout(" --help\n");
- stdout(" --version\n");
- return;
- }
- stdout(`Usage: ${program} [OPTION]... [FILE]...\n`);
- stdout(`Bun implementation of GNU ${program}.\n\n`);
- stdout("Options:\n");
- for (const option of COMMAND_HELP_OPTIONS[helpProgram] ?? []) stdout(` ${option}\n`);
- stdout(" --help\n");
- stdout(" --version\n");
-}
-
-function showSpecialHelp(program) {
- const help = SPECIAL_HELP[program];
- stdout(`${help.usage}\n`);
- stdout(`${help.description}\n\n`);
- for (const option of help.options ?? []) stdout(` ${option}\n`);
- if (help.options?.length) stdout("\n");
- stdout(" --help display this help and exit\n");
- stdout(" --version output version information and exit\n");
- if (help.after) stdout(`\n${help.after}\n`);
-}
-
-function showBracketHelp() {
- stdout("Usage: test EXPRESSION\n");
- stdout(" or: test\n");
- stdout(" or: [ EXPRESSION ]\n");
- stdout(" or: [ ]\n");
- stdout(" or: [ OPTION\n");
- stdout("Exit with the status determined by EXPRESSION.\n\n");
- stdout(" --help display this help and exit\n");
- stdout(" --version output version information and exit\n\n");
- stdout("An omitted EXPRESSION defaults to false. Otherwise,\n");
- stdout("EXPRESSION is true or false and sets exit status.\n");
-}
-
-function showLinkHelp() {
- stdout("Usage: link FILE1 FILE2\n");
- stdout(" or: link OPTION\n");
- stdout("Call the link function to create a link named FILE2 to an existing FILE1.\n\n");
- stdout(" --help display this help and exit\n");
- stdout(" --version output version information and exit\n");
-}
-
-function showUnlinkHelp() {
- stdout("Usage: unlink FILE\n");
- stdout(" or: unlink OPTION\n");
- stdout("Call the unlink function to remove the specified FILE.\n\n");
- stdout(" --help display this help and exit\n");
- stdout(" --version output version information and exit\n");
-}
-
-function commandMetaOption(program, args) {
- if (program === "echo") return !process.env.POSIXLY_CORRECT && args.length === 1 && (args[0] === "--help" || args[0] === "--version") ? args[0] : null;
- if (program === "false" || program === "true" || program === "hostname" || program === "yes" || program === "sleep") return null;
- if (program === "test") return null;
- if (program === "[") return args.length === 1 && (args[0] === "--help" || args[0] === "--version") ? args[0] : null;
- if (program === "printf") return args.length === 1 && (args[0] === "--help" || args[0] === "--version") ? args[0] : null;
- if (program === "nohup") return nohupMetaOption(args);
- if (program === "env") return envMetaOption(args);
- if (program === "timeout") return timeoutMetaOption(args);
- if (program === "nice") return niceMetaOption(args);
- if (program === "stdbuf") return stdbufMetaOption(args);
- if (program === "chroot") return chrootMetaOption(args);
- if (program === "runcon") return runconMetaOption(args);
- if (program === "readlink") return readlinkMetaOption(args);
- if (program === "realpath") return realpathMetaOption(args);
- if (program === "seq") return seqMetaOption(args);
- if (program === "touch") return touchMetaOption(args);
- if (program === "truncate") return truncateMetaOption(args);
- if (program === "cat") return catMetaOption(args);
- if (program === "date") return dateMetaOption(args);
- if (program === "basename") return basenameMetaOption(args);
- if (program === "dirname") return dirnameMetaOption(args);
- if (program === "printenv") return printenvMetaOption(args);
- if (program === "pwd") return pwdMetaOption(args);
- if (program === "wc") return wcMetaOption(args);
- if (program === "head") return headMetaOption(args);
- if (program === "tail") return tailMetaOption(args);
- if (program === "factor") return factorMetaOption(args);
- if (program === "sum") return sumMetaOption(args);
- if (program === "uniq") return uniqMetaOption(args);
- if (program === "uname") return unameMetaOption(args);
- if (program === "tty") return ttyMetaOption(args);
- if (program === "nproc") return nprocMetaOption(args);
- if (program === "pathchk") return pathchkMetaOption(args);
- if (program === "sync") return syncMetaOption(args);
- if (program === "mktemp") return mktempMetaOption(args);
- if (program === "uptime") return uptimeMetaOption(args);
- if (program === "rmdir") return rmdirMetaOption(args);
- if (program === "mkdir") return mkdirMetaOption(args);
- if (program === "mkfifo" || program === "mknod") return specialFileMetaOption(program, args);
- if (program === "tsort") return tsortMetaOption(args);
- if (program === "paste") return pasteMetaOption(args);
- if (program === "tee") return teeMetaOption(args);
- if (program === "tac") return tacMetaOption(args);
- if (program === "fold") return foldMetaOption(args);
- if (program === "comm") return commMetaOption(args);
- if (program === "join") return joinMetaOption(args);
- if (program === "sort") return sortMetaOption(args);
- if (program === "split") return splitMetaOption(args);
- if (program === "csplit") return csplitMetaOption(args);
- if (program === "tr") return trMetaOption(args);
- if (program === "nl") return nlMetaOption(args);
- if (program === "cut") return cutMetaOption(args);
- if (program === "fmt") return fmtMetaOption(args);
- if (program === "ptx") return ptxMetaOption(args);
- if (program === "pr") return prMetaOption(args);
- if (program === "expr") return args.length === 1 && (args[0] === "--help" || args[0] === "--version") ? args[0] : null;
- if (program === "dircolors") return dircolorsMetaOption(args);
- if (program === "base64" || program === "base32") return baseEncodingMetaOption(args);
- if (program === "basenc") return basencMetaOption(args);
- if (program === "cksum") return cksumMetaOption(args);
- if (HASH_COMMAND_NAMES.has(program)) return hashMetaOption(program, args);
- if (program === "numfmt") return numfmtMetaOption(args);
- if (program === "od") return odMetaOption(args);
- if (program === "shuf") return shufMetaOption(args);
- if (program === "shred") return shredMetaOption(args);
- if (program === "who") return whoMetaOption(args);
- if (program === "pinky") return pinkyMetaOption(args);
- if (program === "stty") return sttyMetaOption(args);
- if (program === "id") return idMetaOption(args);
- if (program === "install" || program === "ginstall") return installMetaOption(args);
- if (program === "chcon") return chconMetaOption(args);
- if (program === "chown" || program === "chgrp") return chownMetaOption(args);
- if (program === "chmod") return chmodMetaOption(args);
- if (program === "rm") return rmMetaOption(args);
- if (program === "mv") return mvMetaOption(args);
- if (program === "ln") return lnMetaOption(args);
- if (program === "cp") return cpMetaOption(args);
- if (program === "du") return duMetaOption(args);
- if (program === "stat") return statMetaOption(args);
- if (program === "df") return dfMetaOption(args);
- if (program === "ls" || program === "dir" || program === "vdir") return lsMetaOption(args);
- if (program === "expand" || program === "unexpand") return tabCommandMetaOption(program, args);
- if (HELP_VERSION_ONLY_COMMANDS.has(program)) return helpVersionOnlyMetaOption(args);
- if (program === "coreutils") return null;
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg === "--help" || arg === "--version") return arg;
- }
- return null;
-}
-
-const UNAME_LONG_OPTIONS = ["all", "kernel-name", "nodename", "kernel-release", "kernel-version", "machine", "processor", "hardware-platform", "operating-system", "help", "version"];
-const CAT_LONG_OPTIONS = ["number-nonblank", "number", "squeeze-blank", "show-nonprinting", "show-ends", "show-tabs", "show-all", "help", "version"];
-const DATE_LONG_OPTIONS = ["date", "debug", "file", "iso-8601", "reference", "resolution", "rfc-email", "rfc-822", "rfc-2822", "rfc-3339", "set", "utc", "universal", "help", "version"];
-const DF_LONG_OPTIONS = ["all", "human-readable", "si", "inodes", "local", "block-size", "total", "output", "type", "exclude-type", "print-type", "sync", "no-sync", "portability", "help", "version"];
-const ENV_LONG_OPTIONS = ["argv0", "block-signal", "chdir", "debug", "default-signal", "help", "ignore-environment", "ignore-signal", "list-signal-handling", "null", "split-string", "unset", "version"];
-const BASENAME_LONG_OPTIONS = ["multiple", "suffix", "zero", "help", "version"];
-const DIRNAME_LONG_OPTIONS = ["zero", "help", "version"];
-const PRINTENV_LONG_OPTIONS = ["null", "help", "version"];
-const PWD_LONG_OPTIONS = ["logical", "physical", "help", "version"];
-const WC_LONG_OPTIONS = ["bytes", "chars", "lines", "max-line-length", "words", "files0-from", "total", "debug", "help", "version"];
-const HEAD_LONG_OPTIONS = ["bytes", "lines", "quiet", "silent", "verbose", "zero-terminated", "help", "version"];
-const TAIL_LONG_OPTIONS = ["bytes", "debug", "follow", "lines", "max-unchanged-stats", "pid", "quiet", "retry", "silent", "sleep-interval", "verbose", "zero-terminated", "help", "version"];
-const FACTOR_LONG_OPTIONS = ["exponents", "help", "version"];
-const SUM_LONG_OPTIONS = ["sysv", "help", "version"];
-const UNIQ_LONG_OPTIONS = ["count", "repeated", "all-repeated", "skip-fields", "group", "ignore-case", "skip-chars", "unique", "zero-terminated", "check-chars", "help", "version"];
-const YES_LONG_OPTIONS = ["help", "version"];
-const SLEEP_LONG_OPTIONS = ["help", "version"];
-const TTY_LONG_OPTIONS = ["silent", "quiet", "help", "version"];
-const ID_LONG_OPTIONS = ["user", "group", "groups", "name", "real", "zero", "context", "help", "version"];
-const NPROC_LONG_OPTIONS = ["all", "ignore", "help", "version"];
-const PATHCHK_LONG_OPTIONS = ["portability", "help", "version"];
-const SYNC_LONG_OPTIONS = ["data", "file-system", "help", "version"];
-const MKTEMP_LONG_OPTIONS = ["directory", "dry-run", "quiet", "suffix", "tmpdir", "help", "version"];
-const UPTIME_LONG_OPTIONS = ["help", "version"];
-const RMDIR_LONG_OPTIONS = ["ignore-fail-on-non-empty", "parents", "path", "verbose", "version", "help"];
-const MKDIR_LONG_OPTIONS = ["mode", "parents", "verbose", "context", "help", "version"];
-const SPECIAL_FILE_LONG_OPTIONS = ["mode", "context", "help", "version"];
-const PASTE_LONG_OPTIONS = ["delimiters", "serial", "zero-terminated", "help", "version"];
-const TEE_LONG_OPTIONS = ["append", "ignore-interrupts", "output-error", "help", "version"];
-const TAC_LONG_OPTIONS = ["before", "regex", "separator", "help", "version"];
-const FOLD_LONG_OPTIONS = ["bytes", "characters", "spaces", "width", "help", "version"];
-const COMM_LONG_OPTIONS = ["check-order", "nocheck-order", "output-delimiter", "total", "zero-terminated", "help", "version"];
-const JOIN_LONG_OPTIONS = ["check-order", "header", "ignore-case", "nocheck-order", "zero-terminated", "help", "version"];
-const SPLIT_LONG_OPTIONS = ["additional-suffix", "bytes", "elide-empty-files", "filter", "hex-suffixes", "line-bytes", "lines", "number", "numeric-suffixes", "separator", "suffix-length", "unbuffered", "verbose", "help", "version"];
-const CSPLIT_LONG_OPTIONS = ["silent", "suffix-format", "suppress-matched", "prefix", "keep-files", "digits", "quiet", "elide-empty-files", "help", "version"];
-const TR_LONG_OPTIONS = ["delete", "squeeze-repeats", "complement", "truncate-set1", "help", "version"];
-const NL_LONG_OPTIONS = ["body-numbering", "section-delimiter", "footer-numbering", "header-numbering", "line-increment", "join-blank-lines", "no-renumber", "number-separator", "number-width", "number-format", "starting-line-number", "help", "version"];
-const CUT_LONG_OPTIONS = ["bytes", "characters", "complement", "delimiter", "fields", "no-partial", "only-delimited", "output-delimiter", "whitespace-delimited", "zero-terminated", "help", "version"];
-const FMT_LONG_OPTIONS = ["width", "goal", "prefix", "crown-margin", "split-only", "tagged-paragraph", "uniform-spacing", "help", "version"];
-const PTX_LONG_OPTIONS = ["auto-reference", "break-file", "flag-truncation", "format", "ignore-case", "ignore-file", "macro-name", "only-file", "references", "right-side-refs", "sentence-regexp", "traditional", "typeset-mode", "word-regexp", "width", "gap-size", "help", "version"];
-const BASE_ENCODING_LONG_OPTIONS = ["decode", "ignore-garbage", "wrap", "help", "version"];
-const BASENC_LONG_OPTIONS = ["base64", "base64url", "base58", "base32", "base32hex", "base16", "base2msbf", "base2lsbf", "decode", "ignore-garbage", "wrap", "z85", "help", "version"];
-const CKSUM_LONG_OPTIONS = ["algorithm", "base64", "check", "length", "raw", "tag", "untagged", "zero", "ignore-missing", "quiet", "status", "strict", "warn", "debug", "binary", "text", "help", "version"];
-const HASH_LONG_OPTIONS = ["check", "binary", "text", "tag", "length", "status", "quiet", "warn", "strict", "ignore-missing", "zero", "help", "version"];
-const NUMFMT_LONG_OPTIONS = ["debug", "delimiter", "from", "from-unit", "field", "format", "grouping", "header", "invalid", "padding", "round", "suffix", "to", "to-unit", "unit-separator", "zero-terminated", "help", "version"];
-const OD_LONG_OPTIONS = ["address-radix", "endian", "format", "output-duplicates", "read-bytes", "skip-bytes", "strings", "traditional", "width", "help", "version"];
-const SHUF_LONG_OPTIONS = ["echo", "head-count", "input-range", "output", "random-source", "repeat", "zero-terminated", "help", "version"];
-const SORT_LONG_OPTIONS = ["numeric-sort", "general-numeric-sort", "human-numeric-sort", "month-sort", "version-sort", "random-sort", "random-source", "reverse", "unique", "merge", "ignore-case", "check", "ignore-leading-blanks", "dictionary-order", "ignore-nonprinting", "stable", "zero-terminated", "key", "output", "buffer-size", "batch-size", "compress-program", "files0-from", "parallel", "sort", "field-separator", "temporary-directory", "debug", "help", "version"];
-const STAT_LONG_OPTIONS = ["cached", "format", "printf", "file-system", "dereference", "terse", "help", "version"];
-const SHRED_LONG_OPTIONS = ["exact", "force", "iterations", "random-source", "remove", "size", "verbose", "zero", "help", "version"];
-const WHO_LONG_OPTIONS = ["all", "boot", "dead", "heading", "login", "lookup", "mesg", "message", "count", "process", "runlevel", "short", "time", "users", "writable", "help", "version"];
-const PINKY_LONG_OPTIONS = ["lookup", "help", "version"];
-const STTY_LONG_OPTIONS = ["all", "file", "save", "help", "version"];
-const STDBUF_LONG_OPTIONS = ["input", "output", "error", "help", "version"];
-const CHROOT_LONG_OPTIONS = ["groups", "userspec", "skip-chdir", "help", "version"];
-const RUNCON_LONG_OPTIONS = ["compute", "user", "role", "type", "range", "help", "version"];
-const CHCON_LONG_OPTIONS = ["dereference", "no-dereference", "no-preserve-root", "preserve-root", "recursive", "reference", "user", "role", "type", "range", "verbose", "help", "version"];
-const HOSTNAME_LONG_OPTIONS = ["short", "alias", "domain", "fqdn", "long", "ip-address", "yp", "nis", "file", "help", "version"];
-const EXPAND_LONG_OPTIONS = ["tabs", "initial", "help", "version"];
-const UNEXPAND_LONG_OPTIONS = ["tabs", "all", "first-only", "help", "version"];
-const READLINK_LONG_OPTIONS = ["canonicalize", "canonicalize-existing", "canonicalize-missing", "no-newline", "quiet", "silent", "verbose", "zero", "help", "version"];
-const REALPATH_LONG_OPTIONS = ["canonicalize", "canonicalize-existing", "canonicalize-missing", "logical", "physical", "quiet", "relative-to", "relative-base", "strip", "no-symlinks", "zero", "help", "version"];
-const SEQ_LONG_OPTIONS = ["equal-width", "format", "separator", "help", "version"];
-const TOUCH_LONG_OPTIONS = ["date", "no-create", "no-dereference", "reference", "time", "help", "version"];
-const TRUNCATE_LONG_OPTIONS = ["io-blocks", "no-create", "reference", "size", "help", "version"];
-const INSTALL_LONG_OPTIONS = ["backup", "compare", "directory", "debug", "group", "mode", "owner", "preserve-timestamps", "strip", "strip-program", "suffix", "target-directory", "no-target-directory", "verbose", "preserve-context", "context", "help", "version"];
-const CHOWN_LONG_OPTIONS = ["changes", "recursive", "silent", "quiet", "dereference", "no-dereference", "from", "reference", "preserve-root", "no-preserve-root", "verbose", "help", "version"];
-const CHMOD_LONG_OPTIONS = ["changes", "recursive", "silent", "quiet", "dereference", "no-dereference", "reference", "preserve-root", "no-preserve-root", "verbose", "help", "version"];
-const RM_LONG_OPTIONS = ["force", "interactive", "recursive", "dir", "verbose", "preserve-root", "no-preserve-root", "-presume-input-tty", "one-file-system", "help", "version"];
-const MV_LONG_OPTIONS = ["backup", "debug", "exchange", "force", "interactive", "no-clobber", "no-copy", "strip-trailing-slashes", "suffix", "target-directory", "no-target-directory", "update", "verbose", "context", "help", "version"];
-const LN_LONG_OPTIONS = ["backup", "directory", "force", "interactive", "logical", "no-dereference", "physical", "relative", "suffix", "symbolic", "target-directory", "target-dir", "no-target-directory", "verbose", "help", "version"];
-const CP_LONG_OPTIONS = ["archive", "attributes-only", "backup", "copy-contents", "debug", "force", "interactive", "dereference", "keep-directory-symlink", "link", "no-clobber", "no-dereference", "preserve", "no-preserve", "parents", "recursive", "reflink", "remove-destination", "sparse", "strip-trailing-slashes", "suffix", "symbolic-link", "target-directory", "no-target-directory", "update", "verbose", "one-file-system", "context", "help", "version"];
-const DU_LONG_OPTIONS = ["null", "all", "apparent-size", "block-size", "bytes", "total", "dereference-args", "max-depth", "files0-from", "human-readable", "inodes", "dereference", "count-links", "no-dereference", "separate-dirs", "si", "summarize", "threshold", "time", "time-style", "exclude-from", "exclude", "one-file-system", "help", "version"];
-const LS_LONG_OPTIONS = ["all", "almost-all", "author", "directory", "classify", "file-type", "dereference", "dereference-command-line", "dereference-command-line-symlink-to-dir", "full", "full-time", "group-directories-first", "group", "indicator-style", "inode", "size", "human-readable", "si", "kibibytes", "recursive", "reverse", "color", "sort", "time-style", "time", "tabsize", "width", "block-size", "format", "ignore", "hide-control-chars", "hide", "hyperlink", "ignore-backups", "zero", "dired", "quote-name", "literal", "escape", "show-control-chars", "no-group", "numeric-uid-gid", "quoting", "quoting-style", "context", "help", "version"];
-const HELP_VERSION_ONLY_COMMANDS = new Set(["arch", "groups", "hostid", "link", "logname", "unlink", "users", "whoami"]);
-const HASH_COMMAND_NAMES = new Set(["md5sum", "b2sum", "sha1sum", "sha224sum", "sha256sum", "sha384sum", "sha512sum", "sm3sum"]);
-
-function unameMetaOption(args) {
- const shortKnownOptions = new Set(["a", "s", "n", "r", "v", "m", "p", "i", "o"]);
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (!arg.startsWith("--")) {
- for (const ch of arg.slice(1)) {
- if (!shortKnownOptions.has(ch)) return null;
- }
- continue;
- }
- if (arg.includes("=")) return null;
- const option = normalizeUnameLongOption(arg);
- if (option === "--help" || option === "--version") return option;
- if (option === arg && !UNAME_LONG_OPTIONS.includes(arg.slice(2))) return null;
- }
- return null;
-}
-
-function ttyMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (!arg.startsWith("--")) {
- for (const ch of arg.slice(1)) {
- if (ch !== "s") return null;
- }
- continue;
- }
- const option = normalizeTtyLongOption(arg);
- if (option.includes("=") || !TTY_LONG_OPTIONS.includes(option.slice(2))) return null;
- if (option === "--help" || option === "--version") return option;
- }
- return null;
-}
-
-function nprocMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (!arg.startsWith("--")) {
- if (arg.startsWith("-") && arg !== "-") return null;
- continue;
- }
- const option = normalizeNprocLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!NPROC_LONG_OPTIONS.includes(name)) return null;
- if (option.includes("=")) {
- if (name === "all" || name === "help" || name === "version") return null;
- if (name === "ignore") parseNprocIgnore(option.slice(option.indexOf("=") + 1));
- continue;
- }
- if (name === "help" || name === "version") return option;
- if (name === "ignore") i++;
- }
- return null;
-}
-
-function catMetaOption(args) {
- const shortKnownOptions = new Set(["n", "b", "s", "e", "t", "u", "v", "E", "T", "A"]);
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeCatLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!CAT_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) if (!shortKnownOptions.has(arg[j])) return null;
- }
- return null;
-}
-
-function readlinkMetaOption(args) {
- const shortKnownOptions = new Set(["f", "e", "m", "n", "q", "s", "v", "z"]);
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeReadlinkLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!READLINK_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (inlineValue != null) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) if (!shortKnownOptions.has(arg[j])) return null;
- }
- return null;
-}
-
-function realpathMetaOption(args) {
- const longValueOptions = new Set(["relative-to", "relative-base"]);
- const shortKnownOptions = new Set(["E", "e", "m", "L", "P", "q", "s", "z"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeRealpathLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!REALPATH_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (inlineValue == null && longValueOptions.has(name)) i++;
- else if (inlineValue != null && !longValueOptions.has(name)) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) if (!shortKnownOptions.has(arg[j])) return null;
- }
- return null;
-}
-
-function seqMetaOption(args) {
- const longValueOptions = new Set(["format", "separator"]);
- const shortValueOptions = new Set(["f", "s"]);
- const shortKnownOptions = new Set(["f", "s", "w"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeSeqLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!SEQ_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (inlineValue == null && longValueOptions.has(name)) i++;
- continue;
- }
- if (/^-(?:[0-9.]|nan$)/i.test(arg) || !arg.startsWith("-")) return null;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- if (arg.slice(j + 1) === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function touchMetaOption(args) {
- const longValueOptions = new Set(["date", "reference", "time"]);
- const shortValueOptions = new Set(["d", "r", "t"]);
- const shortKnownOptions = new Set(["a", "c", "d", "f", "h", "m", "r", "t"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeTouchLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!TOUCH_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (name === "time" && inlineValue != null) normalizeTouchTime(inlineValue);
- if (inlineValue == null && longValueOptions.has(name)) i++;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- if (ch === "t" && value !== undefined) parseTouchTimestamp(value);
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function truncateMetaOption(args) {
- const longValueOptions = new Set(["reference", "size"]);
- const shortValueOptions = new Set(["r", "s"]);
- const shortKnownOptions = new Set(["c", "o", "r", "s"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeTruncateLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!TRUNCATE_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (name === "size" && inlineValue != null && !isValidTruncateSizeOperand(inlineValue)) return null;
- if (inlineValue == null && longValueOptions.has(name)) {
- if (name === "size" && (i + 1 >= args.length || !isValidTruncateSizeOperand(args[i + 1]))) return null;
- i++;
- }
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- if (ch === "s" && inlineValue !== "" && !isValidTruncateSizeOperand(inlineValue)) return null;
- if (inlineValue === "") {
- if (ch === "s" && (i + 1 >= args.length || !isValidTruncateSizeOperand(args[i + 1]))) return null;
- i++;
- }
- break;
- }
- }
- }
- return null;
-}
-
-function dateMetaOption(args) {
- const longValueOptions = new Set(["date", "file", "reference", "set", "rfc-3339"]);
- const longOptionalValueOptions = new Set(["iso-8601"]);
- const shortValueOptions = new Set(["d", "f", "r", "s"]);
- const shortKnownOptions = new Set(["d", "f", "r", "s", "I", "R", "u"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeDateLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!DATE_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- const value = inlineValue ?? (longValueOptions.has(name) ? args[i + 1] : undefined);
- if (value !== undefined) validateDateMetaOptionValue(name, value);
- if (inlineValue == null && longValueOptions.has(name)) i++;
- else if (inlineValue == null && longOptionalValueOptions.has(name)) continue;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- if (arg.slice(j + 1) === "") i++;
- break;
- }
- if (ch === "I") break;
- }
- }
- return null;
-}
-
-function validateDateMetaOptionValue(name, value) {
- if (name === "rfc-3339" && !["date", "seconds", "sec", "ns", "nanoseconds"].includes(value)) {
- throw new UsageError(dateInvalidFormatArgument("--rfc-3339", value, ["date", "seconds", "ns"]), true);
- }
- if (name === "iso-8601" && !["hours", "minutes", "date", "seconds", "sec", "ns", "nanoseconds"].includes(value)) {
- throw new UsageError(dateInvalidFormatArgument("--iso-8601", value, ["hours", "minutes", "date", "seconds", "ns"]), true);
- }
-}
-
-function pathchkMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg === "-" || !arg.startsWith("-")) return null;
- if (!arg.startsWith("--")) {
- for (const ch of arg.slice(1)) {
- if (ch !== "p" && ch !== "P") return null;
- }
- continue;
- }
- const option = normalizePathchkLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!PATHCHK_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- }
- return null;
-}
-
-function syncMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("--")) continue;
- const option = normalizeSyncLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!SYNC_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- }
- return null;
-}
-
-function mktempMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") {
- if (process.env.POSIXLY_CORRECT) return null;
- continue;
- }
- if (arg.startsWith("--")) {
- const option = normalizeMktempLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!MKTEMP_LONG_OPTIONS.includes(name)) return null;
- if (option.includes("=")) {
- if (name === "directory" || name === "dry-run" || name === "quiet" || name === "help" || name === "version") return null;
- continue;
- }
- if (option === "--help" || option === "--version") return option;
- if (name === "suffix") i++;
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "d" || ch === "q" || ch === "t" || ch === "u") continue;
- if (ch !== "p") return null;
- if (!arg.slice(j + 1)) i++;
- break;
- }
- }
- return null;
-}
-
-function uptimeMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (arg.startsWith("--")) {
- const option = normalizeUptimeLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!UPTIME_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- continue;
- }
- return null;
- }
- return null;
-}
-
-function rmdirMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg === "-" || !arg.startsWith("-")) {
- if (process.env.POSIXLY_CORRECT) return null;
- continue;
- }
- if (arg.startsWith("--")) {
- const option = normalizeRmdirLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!RMDIR_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- continue;
- }
- for (const ch of arg.slice(1)) {
- if (ch !== "p" && ch !== "v") return null;
- }
- }
- return null;
-}
-
-function mkdirMetaOption(args) {
- let sawContextValue = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (!arg.startsWith("--")) continue;
- const option = normalizeMkdirLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!MKDIR_LONG_OPTIONS.includes(name)) return null;
- if (option.includes("=")) {
- if (name === "parents" || name === "verbose" || name === "help" || name === "version") return null;
- if (name === "context") sawContextValue = true;
- continue;
- }
- if (option === "--help" || option === "--version") {
- if (sawContextValue && !selinuxRuntimeEnabled()) stderr("mkdir: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n");
- return option;
- }
- if (name === "mode") i++;
- }
- return null;
-}
-
-function specialFileMetaOption(program, args) {
- let sawContextValue = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (!arg.startsWith("--")) continue;
- const option = normalizeSpecialFileLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!SPECIAL_FILE_LONG_OPTIONS.includes(name)) return null;
- if (option.includes("=")) {
- if (name === "help" || name === "version") return null;
- if (name === "context") sawContextValue = true;
- continue;
- }
- if (option === "--help" || option === "--version") {
- if (sawContextValue && !selinuxRuntimeEnabled()) stderr(`${program}: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n`);
- return option;
- }
- if (name === "mode") i++;
- }
- return null;
-}
-
-function basenameMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg === "-" || !arg.startsWith("-")) return null;
- if (arg.startsWith("--")) {
- const option = normalizeBasenameLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!BASENAME_LONG_OPTIONS.includes(name)) return null;
- if (option.includes("=")) {
- if (name === "multiple" || name === "zero" || name === "help" || name === "version") return null;
- continue;
- }
- if (option === "--help" || option === "--version") return option;
- if (name === "suffix") i++;
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "a" || ch === "z") continue;
- if (ch !== "s") return null;
- if (!arg.slice(j + 1)) i++;
- break;
- }
- }
- return null;
-}
-
-function dirnameMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") {
- if (process.env.POSIXLY_CORRECT) return null;
- continue;
- }
- if (!arg.startsWith("--")) {
- for (const ch of arg.slice(1)) {
- if (ch !== "z") return null;
- }
- continue;
- }
- const option = normalizeDirnameLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!DIRNAME_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- }
- return null;
-}
-
-function printenvMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg === "-" || !arg.startsWith("-")) return null;
- if (arg.startsWith("--")) {
- const option = normalizePrintenvLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!PRINTENV_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- continue;
- }
- for (let j = 1; j < arg.length; j++) if (arg[j] !== "0") return null;
- }
- return null;
-}
-
-function pwdMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (arg.startsWith("--")) {
- const option = normalizePwdLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!PWD_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- continue;
- }
- for (let j = 1; j < arg.length; j++) if (arg[j] !== "L" && arg[j] !== "P") return null;
- }
- return null;
-}
-
-function wcMetaOption(args) {
- const longValueOptions = new Set(["files0-from", "total"]);
- const shortKnownOptions = new Set(["c", "m", "l", "L", "w"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeWcLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!WC_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (name === "total" && inlineValue != null) validateWcTotalMode(inlineValue);
- if (inlineValue == null && longValueOptions.has(name)) i++;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) if (!shortKnownOptions.has(arg[j])) return null;
- }
- return null;
-}
-
-function headMetaOption(args) {
- const longValueOptions = new Set(["bytes", "lines"]);
- const shortValueOptions = new Set(["c", "n"]);
- const shortKnownOptions = new Set(["c", "n", "q", "v", "z"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeHeadLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!HEAD_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? args[i + 1];
- if (value !== undefined) {
- if (name === "bytes") parseCount(value, 10, "bytes");
- if (name === "lines") parseCount(value, 10, "lines");
- }
- if (inlineValue == null) i++;
- }
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- if (/^-\d/.test(arg)) continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- if (value !== undefined) parseCount(value, 10, ch === "c" ? "bytes" : "lines");
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function uniqMetaOption(args) {
- const longValueOptions = new Set(["skip-fields", "skip-chars", "check-chars"]);
- const longOptionalValueOptions = new Set(["all-repeated", "group"]);
- const shortValueOptions = new Set(["f", "s", "w"]);
- const shortKnownOptions = new Set(["c", "d", "D", "f", "i", "s", "u", "w", "z"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeUniqLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!UNIQ_LONG_OPTIONS.includes(name)) return null;
- if (name === "all-repeated" && inlineValue != null && !["none", "prepend", "separate"].includes(inlineValue)) return null;
- if (name === "group" && inlineValue != null && !["prepend", "append", "separate", "both"].includes(inlineValue)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? args[i + 1];
- if (value !== undefined) validateUniqMetaOptionValue(name, value);
- if (inlineValue == null) i++;
- }
- else if (inlineValue == null && longOptionalValueOptions.has(name)) continue;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- if (/^-\d+$/.test(arg) || /^\+\d+$/.test(arg)) continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- if (value !== undefined) validateUniqMetaOptionValue(ch, value);
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function validateUniqMetaOptionValue(option, value) {
- if (option === "skip-fields" || option === "f") validateUniqNumericOption(value, "fields to skip");
- else if (option === "skip-chars" || option === "s") validateUniqNumericOption(value, "bytes to skip");
- else if (option === "check-chars" || option === "w") validateUniqNumericOption(value, "bytes to compare");
-}
-
-function tailMetaOption(args) {
- const longValueOptions = new Set(["bytes", "lines", "sleep-interval", "max-unchanged-stats", "pid"]);
- const longOptionalValueOptions = new Set(["follow"]);
- const shortValueOptions = new Set(["c", "n", "s"]);
- const shortKnownOptions = new Set(["c", "n", "q", "v", "z", "f", "F", "s"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeTailLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!TAIL_LONG_OPTIONS.includes(name) && name !== "-disable-inotify") return null;
- if (name === "follow" && inlineValue != null && !["descriptor", "name"].includes(inlineValue)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? args[i + 1];
- if (value !== undefined) {
- if (name === "bytes") parseTailCount(value, 10, true);
- if (name === "lines") parseTailCount(value, 10, false);
- if (name === "sleep-interval") parseTailSleepInterval(value);
- if (name === "pid" && !/^\d*$/.test(value)) throw new UsageError(`invalid PID: ${localeQuotedEscapedDiagnostic(value)}`);
- }
- if (inlineValue == null) i++;
- }
- else if (inlineValue == null && longOptionalValueOptions.has(name)) continue;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- if (/^-\d/.test(arg) || /^\+\d/.test(arg)) continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- if (value !== undefined) {
- if (ch === "s") parseTailSleepInterval(value);
- else parseTailCount(value, 10, ch === "c");
- }
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function factorMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (arg.startsWith("--")) {
- const option = normalizeFactorLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!FACTOR_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- continue;
- }
- for (let j = 1; j < arg.length; j++) if (arg[j] !== "h") return null;
- }
- return null;
-}
-
-function sumMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (arg.startsWith("--")) {
- const option = normalizeSumLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!SUM_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- continue;
- }
- for (let j = 1; j < arg.length; j++) if (arg[j] !== "r" && arg[j] !== "s") return null;
- }
- return null;
-}
-
-function helpVersionOnlyMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg !== "-" && arg.startsWith("-") && !arg.startsWith("--")) return null;
- if (!arg.startsWith("--")) continue;
- const option = normalizeHelpVersionOnlyLongOption(arg);
- if (option.includes("=") || !["--help", "--version"].includes(option)) return null;
- return option;
- }
- return null;
-}
-
-function tsortMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeHelpVersionOnlyLongOption(arg);
- if (option.includes("=") || !["--help", "--version"].includes(option)) return null;
- return option;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) if (arg[j] !== "w") return null;
- }
- return null;
-}
-
-function pasteMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizePasteLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!PASTE_LONG_OPTIONS.includes(name)) return null;
- if (option === "--help" || option === "--version") return option;
- if (name === "delimiters") {
- if (inlineValue == null) i++;
- } else if (inlineValue != null) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "s" || ch === "z") continue;
- if (ch !== "d") return null;
- if (!arg.slice(j + 1)) i++;
- break;
- }
- }
- return null;
-}
-
-function normalizePasteLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizePasteLongOption(arg));
- }
- return out;
-}
-
-function normalizePasteLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = PASTE_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length !== 1) return arg;
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-function teeMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeTeeLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!TEE_LONG_OPTIONS.includes(name)) return null;
- if (inlineValue != null) {
- if (name !== "output-error") return null;
- validateTeeOutputError({ "output-error": inlineValue });
- }
- if (option === "--help" || option === "--version") return option;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) if (arg[j] !== "a" && arg[j] !== "i" && arg[j] !== "p") return null;
- }
- return null;
-}
-
-function normalizeTeeLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeTeeLongOption(arg));
- }
- return out;
-}
-
-function normalizeTeeLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = TEE_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length !== 1) return arg;
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-function tacMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeTacLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!TAC_LONG_OPTIONS.includes(name)) return null;
- if (option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- if (name === "separator") i++;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "b" || ch === "r") continue;
- if (ch !== "s") return null;
- if (!arg.slice(j + 1)) i++;
- break;
- }
- }
- return null;
-}
-
-function normalizeTacLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeTacLongOption(arg));
- }
- return out;
-}
-
-function normalizeTacLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = TAC_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length !== 1) return arg;
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-function foldMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeFoldLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!FOLD_LONG_OPTIONS.includes(name)) return null;
- if (inlineValue != null) {
- if (name !== "width") return null;
- parseFoldWidth(inlineValue);
- }
- if (option === "--help" || option === "--version") return option;
- if (name === "width" && inlineValue == null) {
- if (i + 1 >= args.length) throw new UsageError("option '--width' requires an argument", true);
- parseFoldWidth(args[i + 1]);
- i++;
- }
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- const obsoleteWidth = arg.match(/^-(\d.*)$/) ?? arg.match(/^-[bcs]+(\d.*)$/);
- if (obsoleteWidth) {
- parseFoldWidth(obsoleteWidth[1]);
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "b" || ch === "c" || ch === "s") continue;
- if (ch !== "w") return null;
- if (!arg.slice(j + 1)) {
- if (i + 1 >= args.length) throw new UsageError("option requires an argument -- 'w'", true);
- parseFoldWidth(args[i + 1]);
- i++;
- } else {
- parseFoldWidth(arg.slice(j + 1));
- }
- break;
- }
- }
- return null;
-}
-
-function normalizeFoldLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeFoldLongOption(arg));
- }
- return out;
-}
-
-function normalizeFoldLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = FOLD_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length !== 1) return arg;
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-function commMetaOption(args) {
- const outputDelimiters = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeCommLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!COMM_LONG_OPTIONS.includes(name)) return null;
- if (option === "--help" || option === "--version") return option;
- if (name === "output-delimiter") {
- const value = inlineValue ?? args[i + 1];
- if (value !== undefined) {
- outputDelimiters.push(value);
- if (new Set(outputDelimiters).size > 1) throw new UsageError("multiple output delimiters specified");
- }
- if (inlineValue == null) i++;
- } else if (inlineValue != null) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) if (!"123z".includes(arg[j])) return null;
- }
- return null;
-}
-
-function normalizeCommLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeCommLongOption(arg));
- }
- return out;
-}
-
-function normalizeCommLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = COMM_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length !== 1) return arg;
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-function joinMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeJoinLongOption(arg, false);
- const name = option.slice(2).split("=", 1)[0];
- if (!JOIN_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- if (option === "--help" || option === "--version") return option;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if ("iz".includes(ch)) continue;
- if (!"12aejotv".includes(ch)) return null;
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- validateJoinMetaOptionValue(ch, value);
- if (inlineValue === "" && i + 1 < args.length) i++;
- break;
- }
- }
- return null;
-}
-
-function validateJoinMetaOptionValue(option, value) {
- if (value === undefined) return;
- if ("12j".includes(option)) parseJoinFieldNumber(value);
- else if ("av".includes(option)) parseJoinFileNumber(value);
- else if (option === "o") parseJoinOutputList(value);
- else if (option === "t") parseJoinSeparator(value);
-}
-
-function normalizeJoinLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeJoinLongOption(arg));
- }
- return out;
-}
-
-function normalizeJoinLongOption(arg, reportAmbiguous = true) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = JOIN_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length !== 1) {
- if (matches.length > 1 && reportAmbiguous) throw new UsageError(`option '${arg}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- return arg;
- }
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-function sortMetaOption(args) {
- const longValueOptions = new Set(["random-source", "key", "output", "buffer-size", "batch-size", "compress-program", "files0-from", "parallel", "sort", "field-separator", "temporary-directory"]);
- const shortValueOptions = new Set(["k", "o", "S", "t", "T"]);
- const shortKnownOptions = new Set(["n", "g", "h", "M", "V", "r", "u", "f", "c", "C", "b", "d", "i", "R", "s", "z", "m", "k", "o", "S", "t", "T"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeSortLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!SORT_LONG_OPTIONS.includes(name)) return null;
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return option;
- }
- if (name === "check" && inlineValue !== undefined) validateSortMetaOptionValue(name, inlineValue);
- if (longValueOptions.has(name)) {
- validateSortMetaOptionValue(name, inlineValue ?? args[i + 1]);
- if (inlineValue == null) i++;
- }
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- validateSortMetaOptionValue(ch, inlineValue === "" ? args[i + 1] : inlineValue);
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function validateSortMetaOptionValue(name, value) {
- if (value === undefined) return;
- if (name === "key" || name === "k") parseSortKeySpec(value);
- else if (name === "parallel") validateSortParallel(value);
- else if (name === "batch-size") validateSortBatchSize(value);
- else if (name === "buffer-size" || name === "S") validateSortBufferSize(value, name === "S" ? "-S" : "--buffer-size");
- else if (name === "field-separator" || name === "t") parseSortSeparator(value);
- else if (name === "sort") validateSortModeOption(value);
- else if (name === "check") validateSortCheckOption(value);
-}
-
-function splitMetaOption(args) {
- const normalized = normalizeSplitLongOptionAbbreviations(args);
- const longValueOptions = new Set(["additional-suffix", "bytes", "filter", "line-bytes", "lines", "number", "separator", "suffix-length"]);
- const longKnownOptions = new Set(SPLIT_LONG_OPTIONS);
- const shortValueOptions = new Set(["a", "b", "C", "l", "n", "t"]);
- const shortKnownOptions = new Set(["a", "b", "C", "d", "e", "l", "n", "t", "u", "x"]);
- for (let i = 0; i < normalized.length; i++) {
- const arg = normalized[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (!longKnownOptions.has(name)) return null;
- if (arg === "--help" || arg === "--version") return arg;
- if (longValueOptions.has(name)) {
- validateSplitMetaOptionValue(name, inlineValue ?? normalized[i + 1]);
- if (inlineValue == null) i++;
- } else if (inlineValue != null) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- if (/^-[0-9]+$/.test(arg)) continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch) && !/^\d+$/.test(arg.slice(j))) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- validateSplitMetaOptionValue(ch, inlineValue === "" ? normalized[i + 1] : inlineValue);
- if (inlineValue === "" && i + 1 < normalized.length) i++;
- break;
- }
- if (/^\d+$/.test(arg.slice(j))) break;
- }
- }
- return null;
-}
-
-function validateSplitMetaOptionValue(name, value) {
- if (value === undefined) return;
- if (name === "b" || name === "bytes") parseSplitByteCount(value, "bytes");
- else if (name === "C" || name === "line-bytes") parseSplitByteCount(value, "lines");
- else if (name === "l" || name === "lines") parseSplitLineCount(value);
- else if (name === "n" || name === "number") parseSplitNumberSpec(value);
- else if (name === "a" || name === "suffix-length") parseSplitSuffixLength(value);
- else if (name === "t" || name === "separator") validateSplitSeparatorValue(value);
-}
-
-function csplitMetaOption(args) {
- const longValueOptions = new Set(["suffix-format", "prefix", "digits"]);
- const longKnownOptions = new Set(CSPLIT_LONG_OPTIONS);
- const shortValueOptions = new Set(["b", "f", "n"]);
- const shortKnownOptions = new Set(["b", "f", "k", "n", "q", "s", "z"]);
- const normalized = normalizeCsplitLongOptionAbbreviations(args);
- for (let i = 0; i < normalized.length; i++) {
- const arg = normalized[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (!longKnownOptions.has(name)) return null;
- if (arg === "--help" || arg === "--version") return arg;
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? normalized[i + 1];
- if (name === "digits" && value !== undefined) parseCsplitDigits(value);
- if (inlineValue == null) i++;
- } else if (inlineValue != null) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? normalized[i + 1] : inlineValue;
- if (ch === "n" && value !== undefined) parseCsplitDigits(value);
- if (inlineValue === "" && i + 1 < normalized.length) i++;
- break;
- }
- }
- }
- return null;
-}
-
-function trMetaOption(args) {
- const normalized = normalizeTrLongOptions(args, false);
- const knownShort = new Set(["d", "s", "C", "c", "t"]);
- for (const arg of normalized) {
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (!TR_LONG_OPTIONS.includes(name) || inlineValue != null) return null;
- if (arg === "--help" || arg === "--version") return arg;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (const ch of arg.slice(1)) {
- if (!knownShort.has(ch)) return null;
- }
- }
- return null;
-}
-
-function nlMetaOption(args) {
- const longValueOptions = new Set(["body-numbering", "section-delimiter", "footer-numbering", "header-numbering", "line-increment", "join-blank-lines", "number-format", "number-separator", "starting-line-number", "number-width"]);
- const longNoValueOptions = new Set(["no-renumber"]);
- const diagnostics = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- let option;
- try {
- option = normalizeNlLongOption(arg);
- } catch (error) {
- if (error instanceof UsageError) {
- diagnostics.push(`nl: ${error.message}\n`);
- continue;
- }
- throw error;
- }
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!NL_LONG_OPTIONS.includes(name)) {
- diagnostics.push(`nl: unrecognized option '${arg}'\n`);
- continue;
- }
- if (name === "help" || name === "version") {
- if (inlineValue == null) {
- for (const line of diagnostics) stderr(line);
- return `--${name}`;
- }
- diagnostics.push(`nl: option '--${name}' doesn't allow an argument\n`);
- continue;
- }
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? args[i + 1];
- if (value !== undefined) validateNlMetaOptionValue(name, value, diagnostics);
- }
- if (inlineValue == null && longValueOptions.has(name)) {
- i++;
- continue;
- }
- if (inlineValue != null) {
- if (longNoValueOptions.has(name)) diagnostics.push(`nl: option '--${name}' doesn't allow an argument\n`);
- else if (!longValueOptions.has(name)) return null;
- }
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- const valueOption = arg.slice(1).match(/[bdfhilnsvw]/);
- if (valueOption) {
- const ch = valueOption[0];
- const inlineValue = arg.slice(arg.indexOf(ch) + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- validateNlMetaShortValue(ch, value, diagnostics);
- if (inlineValue === "") i++;
- continue;
- }
- for (const ch of arg.slice(1)) {
- if (ch !== "p") {
- diagnostics.push(`nl: invalid option -- '${ch}'\n`);
- break;
- }
- }
- }
- return null;
-}
-
-function validateNlMetaOptionValue(name, value, diagnostics) {
- if ((name === "body-numbering" || name === "header-numbering" || name === "footer-numbering") && !nlNumberingStyleValid(value)) {
- diagnostics.push(`nl: invalid ${name.split("-", 1)[0]} numbering style: ${localeQuotedEscapedDiagnostic(value)}\n`);
- } else if (name === "number-format" && !nlNumberFormatValid(value)) {
- diagnostics.push(`nl: invalid line numbering format: ${localeQuotedEscapedDiagnostic(value)}\n`);
- } else if (name === "line-increment") parseNlBigInt(value, "invalid line number increment");
- else if (name === "starting-line-number") parseNlBigInt(value, "invalid starting line number");
- else if (name === "join-blank-lines") parseNlJoinBlank(value);
- else if (name === "number-width") parseNlWidth(value);
-}
-
-function validateNlMetaShortValue(ch, value, diagnostics) {
- if (value === undefined) return;
- const names = { b: "body-numbering", f: "footer-numbering", h: "header-numbering", i: "line-increment", l: "join-blank-lines", n: "number-format", v: "starting-line-number", w: "number-width" };
- const name = names[ch];
- if (name) validateNlMetaOptionValue(name, value, diagnostics);
-}
-
-function nlMetaNumericOptionInvalid(name, value) {
- if (name === "line-increment" || name === "starting-line-number") return !/^[+-]?\d+$/.test(String(value));
- if (name === "join-blank-lines" || name === "number-width") return !/^[+-]?\d+$/.test(String(value));
- return false;
-}
-
-function cutMetaOption(args) {
- const longValueOptions = new Set(["bytes", "characters", "delimiter", "fields", "output-delimiter"]);
- const longOptionalValueOptions = new Set(["whitespace-delimited"]);
- const shortValueOptions = new Set(["b", "c", "d", "f", "F", "O"]);
- const shortKnownOptions = new Set(["b", "c", "d", "f", "F", "n", "O", "s", "w", "z"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeCutLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!CUT_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (name === "whitespace-delimited" && inlineValue != null) normalizeCutWhitespaceDelimitedOption(inlineValue);
- if (name === "delimiter") validateCutMetaOptionValue(name, inlineValue ?? args[i + 1]);
- if (inlineValue == null && longValueOptions.has(name)) i++;
- else if (inlineValue == null && longOptionalValueOptions.has(name)) continue;
- else if (inlineValue != null && !longValueOptions.has(name) && !longOptionalValueOptions.has(name)) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- validateCutMetaOptionValue(ch, inlineValue === "" ? args[i + 1] : inlineValue);
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function validateCutMetaOptionValue(name, value) {
- if (value === undefined || name !== "d" && name !== "delimiter") return;
- const delimiter = normalizeCutQuotedValue(value);
- if (delimiter === "") return;
- const rawDelimiter = isGb18030Locale() || shouldUseRawCutDelimiter(delimiter) ? rawCutOptionValue(["d"], ["delimiter"]) : null;
- if (rawDelimiter != null && isGb18030Locale()) {
- if (gb18030Units(rawDelimiter).length !== 1) throw new UsageError("the delimiter must be a single character", true);
- return;
- }
- if (rawDelimiter != null && delimiter.includes("\uFFFD")) {
- if (rawDelimiter.length !== 1) throw new UsageError("the delimiter must be a single character", true);
- return;
- }
- if ([...delimiter].length !== 1 || (isSingleByteLocale() && delimiter !== "\uFFFD" && enc.encode(delimiter).length > 1)) {
- throw new UsageError("the delimiter must be a single character", true);
- }
-}
-
-function fmtMetaOption(args) {
- const longValueOptions = new Set(["width", "goal", "prefix"]);
- const shortValueOptions = new Set(["w", "g", "p"]);
- const shortKnownOptions = new Set(["c", "s", "t", "u", "w", "g", "p"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeFmtLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!FMT_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (inlineValue == null && longValueOptions.has(name)) i++;
- else if (inlineValue != null && !longValueOptions.has(name)) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- if (/^-\d/.test(arg)) continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- if (arg.slice(j + 1) === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function ptxMetaOption(args) {
- const longValueOptions = new Set(["break-file", "flag-truncation", "format", "ignore-file", "macro-name", "only-file", "sentence-regexp", "word-regexp", "width", "gap-size"]);
- const shortValueOptions = new Set(["b", "F", "M", "S", "W", "g", "i", "o", "w"]);
- const shortKnownOptions = new Set(["A", "b", "F", "G", "M", "O", "R", "S", "T", "W", "f", "g", "i", "o", "r", "t", "w"]);
- const normalized = normalizePtxLongOptions(args);
- for (let i = 0; i < normalized.length; i++) {
- const arg = normalized[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (!PTX_LONG_OPTIONS.includes(name)) return null;
- if ((arg === "--help" || arg === "--version") && inlineValue == null) return arg;
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? normalized[i + 1];
- if (value !== undefined) validatePtxMetaOptionValue(name, value);
- if (inlineValue == null) i++;
- } else if (inlineValue != null) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? normalized[i + 1] : inlineValue;
- validatePtxMetaShortValue(ch, value);
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function validatePtxMetaOptionValue(name, value) {
- if (name === "format") parsePtxFormat(value);
- if (name === "width") parsePtxPositiveInteger(value, "line width");
- if (name === "gap-size") parsePtxPositiveInteger(value, "gap width");
-}
-
-function validatePtxMetaShortValue(ch, value) {
- if (value === undefined) return;
- if (ch === "w") validatePtxMetaOptionValue("width", value);
- else if (ch === "g") validatePtxMetaOptionValue("gap-size", value);
-}
-
-const PR_LONG_OPTIONS = ["across", "columns", "date-format", "double-space", "expand-tabs", "first-line-number", "form-feed", "header", "indent", "join-lines", "length", "merge", "no-file-warnings", "number-lines", "omit-header", "omit-pagination", "output-tabs", "page-width", "pages", "sep-string", "separator", "show-control-chars", "show-nonprinting", "width", "help", "version"];
-
-function prMetaOption(args) {
- const longValueOptions = new Set(["columns", "date-format", "first-line-number", "header", "indent", "length", "page-width", "pages", "width"]);
- const longOptionalValueOptions = new Set(["expand-tabs", "number-lines", "output-tabs", "sep-string", "separator"]);
- const shortValueOptions = new Set(["D", "h", "l", "N", "o", "w", "W"]);
- const shortOptionalValueOptions = new Set(["e", "i", "n", "s", "S"]);
- const shortKnownOptions = new Set(["a", "b", "c", "d", "e", "f", "F", "h", "i", "J", "l", "m", "n", "N", "o", "r", "s", "S", "t", "T", "v", "w", "W", "D"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeLongOptionByPrefix(arg, PR_LONG_OPTIONS);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!PR_LONG_OPTIONS.includes(name)) return null;
- if (name === "help" || name === "version") {
- if (inlineValue != null) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return option;
- }
- const value = inlineValue ?? (longValueOptions.has(name) ? args[i + 1] : undefined);
- if (value !== undefined) validatePrMetaOptionValue(name, value);
- if (inlineValue == null && longValueOptions.has(name)) i++;
- else if (inlineValue == null && longOptionalValueOptions.has(name)) continue;
- else if (inlineValue != null && !longValueOptions.has(name) && !longOptionalValueOptions.has(name)) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- if (/^-\d+$/.test(arg)) continue;
- if (/^-\d/.test(arg)) return null;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- validatePrMetaShortValue(ch, value);
- if (inlineValue === "") i++;
- break;
- }
- if (shortOptionalValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- if (inlineValue !== "") validatePrMetaShortValue(ch, inlineValue);
- break;
- }
- }
- }
- return null;
-}
-
-function validatePrMetaOptionValue(name, value) {
- if (name === "columns") parsePrColumnCount(value);
- else if (name === "first-line-number") parsePrLineNumber(value);
- else if (name === "indent") parsePrNonnegativeInteger(value, "-o MARGIN", "line offset");
- else if (name === "page-width") parsePrPositiveInteger(value, "-W PAGE_WIDTH", "characters");
- else if (name === "width") parsePrPositiveInteger(value, "-w PAGE_WIDTH", "characters");
- else if (name === "length") parsePrPositiveInteger(value, "-l PAGE_LENGTH", "lines");
- else if (name === "pages") validatePrPages(value);
- else if (name === "expand-tabs") validatePrOptionalNumberSpec(value, "-e");
- else if (name === "number-lines") validatePrOptionalNumberSpec(value, "-n");
- else if (name === "output-tabs") validatePrOptionalNumberSpec(value, "-i");
-}
-
-function validatePrMetaShortValue(ch, value) {
- if (value === undefined) return;
- if (ch === "l") validatePrMetaOptionValue("length", value);
- else if (ch === "o") validatePrMetaOptionValue("indent", value);
- else if (ch === "w") validatePrMetaOptionValue("width", value);
- else if (ch === "W") validatePrMetaOptionValue("page-width", value);
- else if (ch === "e") validatePrMetaOptionValue("expand-tabs", value);
- else if (ch === "n") validatePrMetaOptionValue("number-lines", value);
- else if (ch === "i") validatePrMetaOptionValue("output-tabs", value);
-}
-
-function validatePrOptionalNumberSpec(value, option) {
- const text = String(value);
- if (text === "") throw new UsageError(`'${option}': Invalid argument: ${localeQuotedEscapedDiagnostic(text)}`, true);
- const numberText = /^\d/.test(text) ? text : text.slice(1);
- if (numberText === "") return;
- let tooLarge = false;
- let valid = /^\d+$/.test(numberText);
- if (valid) {
- const n = BigInt(numberText);
- valid = n > 0n;
- tooLarge = n > BigInt(Number.MAX_SAFE_INTEGER);
- }
- if (!valid || tooLarge) {
- const suffix = tooLarge ? ": Value too large for defined data type" : "";
- throw new UsageError(`'${option}' extra characters or invalid number in the argument: ${localeQuotedEscapedDiagnostic(numberText)}${suffix}`, true);
- }
-}
-
-function baseEncodingMetaOption(args) {
- return baseLikeMetaOption(args, BASE_ENCODING_LONG_OPTIONS, normalizeBaseEncodingLongOption);
-}
-
-function basencMetaOption(args) {
- return baseLikeMetaOption(args, BASENC_LONG_OPTIONS, normalizeBasencLongOption);
-}
-
-function cksumMetaOption(args) {
- return checksumMetaOption(args, CKSUM_LONG_OPTIONS, normalizeCksumLongOption, new Set(["algorithm", "length"]), new Set(["a", "l"]), new Set(["a", "b", "c", "l", "t", "w", "z"]));
-}
-
-function hashMetaOption(program, args) {
- const supportsLength = program === "b2sum";
- const longOptions = supportsLength ? HASH_LONG_OPTIONS : HASH_LONG_OPTIONS.filter((option) => option !== "length");
- return checksumMetaOption(args, longOptions, normalizeHashLongOption, supportsLength ? new Set(["length"]) : new Set(), supportsLength ? new Set(["l"]) : new Set(), supportsLength ? new Set(["b", "c", "l", "t", "w", "z"]) : new Set(["b", "c", "t", "w", "z"]));
-}
-
-function checksumMetaOption(args, longOptions, normalizeLongOption, longValueOptions, shortValueOptions, shortKnownOptions) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!longOptions.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (longOptions === CKSUM_LONG_OPTIONS && name === "algorithm" && inlineValue != null) validateCksumAlgorithmOption(inlineValue);
- const value = inlineValue ?? (longValueOptions.has(name) ? args[i + 1] : undefined);
- if (name === "length" && value !== undefined) validateShaDigestLengthSyntax(value);
- if (inlineValue == null && longValueOptions.has(name)) i++;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- validateChecksumMetaShortValue(ch, value, longOptions);
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function validateChecksumMetaShortValue(ch, value, longOptions) {
- if (value === undefined) return;
- if (ch === "a" && longOptions === CKSUM_LONG_OPTIONS) validateCksumAlgorithmOption(value);
- if (ch === "l") validateShaDigestLengthSyntax(value);
-}
-
-function numfmtMetaOption(args) {
- const longValueOptions = new Set(["delimiter", "from", "from-unit", "field", "format", "invalid", "padding", "round", "suffix", "to", "to-unit", "unit-separator"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeNumfmtLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!NUMFMT_LONG_OPTIONS.includes(name) && name !== "devdebug") return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- const value = inlineValue ?? (longValueOptions.has(name) ? args[i + 1] : undefined);
- if (value !== undefined) validateNumfmtMetaOptionValue(name, value);
- if (inlineValue == null && longValueOptions.has(name)) i++;
- else if (inlineValue != null && !longValueOptions.has(name)) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!["d", "z"].includes(ch)) return null;
- if (ch === "d") {
- const inlineValue = arg.slice(j + 1);
- validateNumfmtMetaOptionValue("delimiter", inlineValue === "" ? args[i + 1] : inlineValue);
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function odMetaOption(args) {
- const longValueOptions = new Set(["address-radix", "endian", "format", "read-bytes", "skip-bytes"]);
- const longOptionalValueOptions = new Set(["strings", "width"]);
- const shortValueOptions = new Set(["A", "j", "N", "S", "t"]);
- const shortOptionalValueOptions = new Set(["w"]);
- const shortKnownOptions = new Set(["A", "j", "N", "S", "t", "w", "a", "b", "c", "d", "f", "i", "l", "o", "s", "x", "v"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeOdLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!OD_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- const value = inlineValue ?? (longValueOptions.has(name) ? args[i + 1] : undefined);
- if (name === "endian" && value !== undefined) validateOdEndian(value);
- if (name === "read-bytes" && value !== undefined) parseOdSize(value, "--read-bytes");
- if (name === "skip-bytes" && value !== undefined) parseOdSize(value, "--skip-bytes");
- if (name === "strings" && inlineValue != null) parseOdStringLength(inlineValue, "--strings");
- if (name === "width" && inlineValue != null) parseOdWidth(inlineValue, "--width");
- if (inlineValue == null && longValueOptions.has(name)) i++;
- else if (inlineValue == null && longOptionalValueOptions.has(name)) continue;
- else if (inlineValue != null && !longValueOptions.has(name) && !longOptionalValueOptions.has(name)) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- validateOdMetaShortValue(ch, value);
- if (inlineValue === "") i++;
- break;
- }
- if (shortOptionalValueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- if (inlineValue !== "") parseOdWidth(inlineValue, "-w");
- break;
- }
- }
- }
- return null;
-}
-
-function validateOdMetaShortValue(ch, value) {
- if (value === undefined) return;
- if (ch === "j") parseOdSize(value, "-j");
- else if (ch === "N") parseOdSize(value, "-N");
- else if (ch === "S") parseOdStringLength(value, "-S");
-}
-
-function shufMetaOption(args) {
- const longValueOptions = new Set(["head-count", "input-range", "output", "random-source"]);
- const shortValueOptions = new Set(["n", "i", "o"]);
- const shortKnownOptions = new Set(["e", "i", "n", "o", "r", "z"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeShufLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!SHUF_LONG_OPTIONS.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- const value = inlineValue ?? (longValueOptions.has(name) ? args[i + 1] : undefined);
- if (name === "head-count" && value !== undefined) parseShufCount(value);
- if (name === "input-range" && value !== undefined) parseShufRange(value);
- if (inlineValue == null && longValueOptions.has(name)) i++;
- else if (inlineValue != null && !longValueOptions.has(name)) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- const value = arg.slice(j + 1) || args[i + 1];
- if (ch === "n" && value !== undefined) parseShufCount(value);
- if (ch === "i" && value !== undefined) parseShufRange(value);
- if (arg.slice(j + 1) === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function baseLikeMetaOption(args, longOptions, normalizeLongOption) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!longOptions.includes(name)) return null;
- if ((option === "--help" || option === "--version") && inlineValue == null) return option;
- if (name === "wrap") {
- const value = inlineValue ?? args[i + 1];
- if (value !== undefined) parseWrap(value);
- if (inlineValue == null) i++;
- }
- else if (inlineValue != null && name !== "wrap") return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!["d", "i", "w"].includes(ch)) return null;
- if (ch === "w") {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[i + 1] : inlineValue;
- if (value !== undefined) parseWrap(value);
- if (inlineValue === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function tabCommandMetaOption(program, args) {
- const longOptions = program === "expand" ? EXPAND_LONG_OPTIONS : UNEXPAND_LONG_OPTIONS;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const option = normalizeTabCommandLongOption(arg, longOptions);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!longOptions.includes(name)) return null;
- if (inlineValue != null) {
- if (name !== "tabs") return null;
- validateTabMetaOptionValue(program, inlineValue);
- }
- if (option === "--help" || option === "--version") return option;
- if (name === "tabs" && inlineValue == null) {
- validateTabMetaOptionValue(program, args[i + 1]);
- i++;
- }
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- if (/^-\d[\d,\s]*$/.test(arg)) continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (program === "expand" && ch === "i") continue;
- if (program === "unexpand" && ch === "a") continue;
- if (ch !== "t") return null;
- const value = arg.slice(j + 1) || args[i + 1];
- validateTabMetaOptionValue(program, value);
- if (!arg.slice(j + 1)) i++;
- break;
- }
- }
- return null;
-}
-
-function validateTabMetaOptionValue(program, value) {
- try {
- parseTabStops(value, program);
- } catch (error) {
- if (error instanceof UsageError && ["tab size cannot be 0", "tab sizes must be ascending"].includes(error.message)) return;
- throw error;
- }
-}
-
-function normalizeTabCommandLongOptions(args, longOptions) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeTabCommandLongOption(arg, longOptions));
- }
- return out;
-}
-
-function normalizeTabCommandLongOption(arg, longOptions) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const optionNames = name === "tab" || "tabs".startsWith(name) ? ["tabs"] : longOptions.filter((option) => option.startsWith(name));
- if (optionNames.length !== 1) return arg;
- return eq === -1 ? `--${optionNames[0]}` : `--${optionNames[0]}=${body.slice(eq + 1)}`;
-}
-
-function normalizeHelpVersionOnlyLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeHelpVersionOnlyLongOption(arg));
- }
- return out;
-}
-
-function normalizeHelpVersionOnlyLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = ["help", "version"].find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-function envMetaOption(args) {
- let sawAssignment = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- const normalized = arg.startsWith("--") ? normalizeInvocationLongOptionByPrefix(arg, ENV_LONG_OPTIONS) : arg;
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (sawAssignment) {
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) continue;
- return null;
- }
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new InvocationError(`option '--${name}' doesn't allow an argument`);
- return normalized;
- }
- if (arg === "-") continue;
- if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) {
- sawAssignment = true;
- continue;
- }
- if (normalized.startsWith("--") && ["--ignore-environment", "--null", "--debug", "--list-signal-handling"].includes(`--${name}`)) {
- if (inlineValue !== undefined) throw new InvocationError(`option '--${name}' doesn't allow an argument`);
- continue;
- }
- if (["-i", "-0", "-v"].includes(normalized)) continue;
- if (["--default-signal", "--ignore-signal", "--block-signal"].includes(normalized)) continue;
- if (["-a", "--argv0", "-u", "--unset", "-C", "--chdir", "-S", "--split-string"].includes(normalized)) {
- i++;
- continue;
- }
- if (/^-(a|u|C|S).+/.test(arg) || /^--(argv0|unset|chdir|split-string|default-signal|ignore-signal|block-signal)=/.test(normalized)) continue;
- if (arg.startsWith("-v") && /\s/.test(arg[2] ?? "")) throw new InvocationError(`invalid option -- '${arg[2]}'\nenv: use -[v]S to pass options in shebang lines`);
- if (arg.startsWith("-")) throw new InvocationError(invalidOptionMessage(arg));
- return null;
- }
- return null;
-}
-
-function nohupMetaOption(args) {
- if (!args.length) return null;
- const normalized = args[0].startsWith("--") ? normalizeHelpVersionOnlyLongOption(args[0]) : args[0];
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new InvocationError(`option '--${name}' doesn't allow an argument`);
- return normalized;
- }
- return null;
-}
-
-function timeoutMetaOption(args) {
- const longOptions = ["foreground", "kill-after", "preserve-status", "signal", "verbose", "help", "version"];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- const normalized = arg.startsWith("--") ? normalizeInvocationLongOptionByPrefix(arg, longOptions) : arg;
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new InvocationError(`option '--${name}' doesn't allow an argument`);
- return normalized;
- }
- if (normalized.startsWith("--foreground=")) throw new InvocationError("option '--foreground' doesn't allow an argument");
- if (normalized.startsWith("--preserve-status=")) throw new InvocationError("option '--preserve-status' doesn't allow an argument");
- if (normalized.startsWith("--verbose=")) throw new InvocationError("option '--verbose' doesn't allow an argument");
- if (arg === "-p" || arg === "--preserve-status" || arg === "-v" || arg === "--verbose" || arg === "-f" || arg === "--foreground") continue;
- if (arg === "-s" || arg === "--signal") {
- if (i + 1 >= args.length) throw new InvocationError(arg.startsWith("--") ? `option '${arg}' requires an argument` : `option requires an argument -- '${arg.slice(1)}'`);
- normalizeTimeoutSignalOption(args[i + 1]);
- i++;
- continue;
- }
- if (arg === "-k" || arg === "--kill-after") {
- if (i + 1 >= args.length) throw new InvocationError(arg.startsWith("--") ? `option '${arg}' requires an argument` : `option requires an argument -- '${arg.slice(1)}'`);
- parseDuration(args[i + 1]);
- i++;
- continue;
- }
- if (/^-s.+/.test(arg)) {
- normalizeTimeoutSignalOption(arg.slice(2));
- continue;
- }
- if (/^-k.+/.test(arg)) {
- parseDuration(arg.slice(2));
- continue;
- }
- if (normalized.startsWith("--signal=")) {
- normalizeTimeoutSignalOption(inlineValue);
- continue;
- }
- if (normalized.startsWith("--kill-after=")) {
- parseDuration(inlineValue);
- continue;
- }
- if (arg.startsWith("-")) throw new InvocationError(invalidOptionMessage(arg));
- return null;
- }
- return null;
-}
-
-function niceMetaOption(args) {
- const longOptions = ["adjustment", "help", "version"];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- const normalized = arg.startsWith("--") ? normalizeInvocationLongOptionByPrefix(arg, longOptions) : arg;
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new InvocationError(`option '--${name}' doesn't allow an argument`);
- return normalized;
- }
- if (arg === "-n" || arg === "--adjustment") {
- i++;
- continue;
- }
- if (/^-n.+/.test(arg) || /^--adjustment=/.test(arg) || /^-[+-]?\d+$/.test(arg)) continue;
- if (arg.startsWith("-")) throw new InvocationError(invalidOptionMessage(arg));
- return null;
- }
- return null;
-}
-
-function stdbufMetaOption(args) {
- let sawMode = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) {
- normalized = normalizeLongOptionByPrefix(arg, STDBUF_LONG_OPTIONS);
- }
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new InvocationError(`option '--${name}' doesn't allow an argument`);
- return normalized;
- }
- if (["-i", "-o", "-e"].includes(arg)) {
- if (i + 1 < args.length) validateStdbufMode(arg[1], args[i + 1]);
- sawMode = true;
- i++;
- continue;
- }
- if (["--input", "--output", "--error"].includes(normalized)) {
- if (i + 1 < args.length) validateStdbufMode(normalized.slice(2, 3), args[i + 1]);
- sawMode = true;
- i++;
- continue;
- }
- if (/^-[ioe].+/.test(arg)) {
- validateStdbufMode(arg[1], arg.slice(2));
- sawMode = true;
- continue;
- }
- if (/^--(input|output|error)=/.test(normalized)) {
- const [, name, mode] = normalized.match(/^--(input|output|error)=(.*)$/s);
- validateStdbufMode(name[0], mode);
- sawMode = true;
- continue;
- }
- if (arg.startsWith("-")) throw new InvocationError(invalidOptionMessage(arg));
- if (sawMode) return null;
- }
- return null;
-}
-
-function chrootMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeInvocationLongOptionByPrefix(arg, CHROOT_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new InvocationError(`option '--${name}' doesn't allow an argument`);
- return normalized;
- }
- if (name === "skip-chdir") {
- if (inlineValue !== undefined) throw new InvocationError("option '--skip-chdir' doesn't allow an argument");
- continue;
- }
- if (name === "userspec" || name === "groups") {
- if (inlineValue !== undefined) continue;
- i++;
- continue;
- }
- if (arg.startsWith("-")) throw new InvocationError(invalidOptionMessage(arg));
- return null;
- }
- return null;
-}
-
-function runconMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeInvocationLongOptionByPrefix(arg, RUNCON_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new InvocationError(`option '--${name}' doesn't allow an argument`);
- return normalized;
- }
- if (arg === "-c" || name === "compute") {
- if (inlineValue !== undefined) throw new InvocationError("option '--compute' doesn't allow an argument");
- continue;
- }
- if (["-u", "-r", "-t", "-l"].includes(arg)) {
- i++;
- continue;
- }
- if (["user", "role", "type", "range"].includes(name)) {
- if (inlineValue === undefined) i++;
- continue;
- }
- if (/^-[urtl].+/.test(arg)) continue;
- if (arg.startsWith("-")) throw new InvocationError(invalidOptionMessage(arg));
- return null;
- }
- return null;
-}
-
-function chconMetaOption(args) {
- const longValueOptions = new Set(["reference", "user", "role", "type", "range"]);
- const longFlagOptions = new Set(["dereference", "no-dereference", "no-preserve-root", "preserve-root", "recursive", "verbose"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLongOptionByPrefix(arg, CHCON_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (longValueOptions.has(name)) {
- if (inlineValue === undefined) i++;
- continue;
- }
- if (["-u", "-r", "-t", "-l"].includes(arg)) {
- i++;
- continue;
- }
- if (/^-[urtl].+/.test(arg)) continue;
- if (/^-[Rhv]+$/.test(arg)) continue;
- if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- continue;
- }
- return null;
-}
-
-function chownMetaOption(args) {
- const longValueOptions = new Set(["from", "reference"]);
- const longFlagOptions = new Set(["changes", "recursive", "silent", "quiet", "dereference", "no-dereference", "preserve-root", "no-preserve-root", "verbose"]);
- const shortFlagOptions = new Set(["R", "c", "f", "h", "H", "L", "P", "v"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLongOptionByPrefix(arg, CHOWN_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (name === "from") return null;
- if (longValueOptions.has(name)) {
- if (inlineValue === undefined) i++;
- continue;
- }
- if (arg.startsWith("-") && arg !== "-") {
- if ([...arg.slice(1)].every((ch) => shortFlagOptions.has(ch))) continue;
- throw new UsageError(invalidClusterOptionMessage(arg, shortFlagOptions), true);
- }
- return null;
- }
- return null;
-}
-
-function chmodMetaOption(args) {
- const longFlagOptions = new Set(["changes", "recursive", "silent", "quiet", "dereference", "no-dereference", "preserve-root", "no-preserve-root", "verbose"]);
- const shortFlagOptions = new Set(["R", "c", "f", "h", "H", "L", "P", "v"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLongOptionByPrefix(arg, CHMOD_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (name === "reference") {
- if (inlineValue === undefined) i++;
- continue;
- }
- if (arg.startsWith("-") && arg !== "-" && !isChmodModeToken(arg)) {
- if ([...arg.slice(1)].every((ch) => shortFlagOptions.has(ch))) continue;
- throw new UsageError(invalidClusterOptionMessage(arg, shortFlagOptions), true);
- }
- continue;
- }
- return null;
-}
-
-function rmMetaOption(args) {
- const longFlagOptions = new Set(["force", "recursive", "dir", "verbose", "no-preserve-root", "-presume-input-tty", "one-file-system"]);
- for (const arg of args) {
- if (arg === "--") return null;
- rejectAbbreviatedRmNoPreserveRoot(arg);
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLongOptionByPrefix(arg, RM_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (name === "interactive") {
- if (inlineValue !== undefined) validateRmInteractiveValue(inlineValue);
- continue;
- }
- if (name === "preserve-root") {
- if (inlineValue !== undefined) validateRmPreserveRootValue(inlineValue);
- continue;
- }
- if (/^-[firdvIR]+$/.test(arg)) continue;
- if (arg.startsWith("-")) throw rmInvalidOptionUsageError(arg, args);
- continue;
- }
- return null;
-}
-
-function mvMetaOption(args) {
- const longFlagOptions = new Set(["debug", "exchange", "force", "interactive", "no-clobber", "no-copy", "strip-trailing-slashes", "no-target-directory", "verbose", "context"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLongOptionByPrefix(arg, MV_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (name === "suffix" || name === "target-directory") {
- if (inlineValue === undefined) i++;
- continue;
- }
- if (name === "backup") continue;
- if (name === "update") {
- if (inlineValue !== undefined) validateUpdateMode("mv", inlineValue);
- continue;
- }
- if (arg.startsWith("-") && !arg.startsWith("--")) {
- i = scanMvShortMetaOption(args, i);
- continue;
- }
- if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- continue;
- }
- return null;
-}
-
-function scanMvShortMetaOption(args, index) {
- const arg = args[index];
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if ("dfinuvbTZ".includes(ch)) continue;
- if (ch === "t" || ch === "S") return arg.slice(j + 1) ? index : index + 1;
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- return index;
-}
-
-function lnMetaOption(args) {
- const longFlagOptions = new Set(["directory", "force", "interactive", "logical", "no-dereference", "physical", "relative", "symbolic", "no-target-directory", "verbose"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLnLongOption(arg);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (name === "suffix" || name === "target-directory" || name === "target-dir") {
- if (inlineValue === undefined) i++;
- continue;
- }
- if (name === "backup") continue;
- if (arg.startsWith("-") && !arg.startsWith("--")) {
- i = scanLnShortMetaOption(args, i);
- continue;
- }
- if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- continue;
- }
- return null;
-}
-
-function scanLnShortMetaOption(args, index) {
- const arg = args[index];
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if ("sfidFLPnrTvb".includes(ch)) continue;
- if (ch === "t" || ch === "S") return arg.slice(j + 1) ? index : index + 1;
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- return index;
-}
-
-function cpMetaOption(args) {
- const longFlagOptions = new Set(["archive", "attributes-only", "copy-contents", "debug", "force", "interactive", "dereference", "no-dereference", "keep-directory-symlink", "link", "no-clobber", "parents", "recursive", "remove-destination", "strip-trailing-slashes", "symbolic-link", "no-target-directory", "verbose", "one-file-system"]);
- let sawContextValue = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLongOptionByPrefix(arg, CP_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- if (sawContextValue) stderr("cp: warning: ignoring --context; it requires an SELinux-enabled kernel\n");
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (name === "suffix" || name === "target-directory" || name === "no-preserve" || name === "sparse") {
- if (inlineValue === undefined) i++;
- if (name === "no-preserve" && inlineValue !== undefined) validateCpPreserveList(inlineValue, "--no-preserve");
- if (name === "sparse" && inlineValue !== undefined) validateSparseMode("cp", inlineValue);
- continue;
- }
- if (name === "preserve") {
- if (inlineValue !== undefined) validateCpPreserveList(inlineValue, "--preserve");
- continue;
- }
- if (name === "context") {
- if (inlineValue !== undefined) sawContextValue = true;
- continue;
- }
- if (name === "backup") continue;
- if (name === "reflink") {
- if (inlineValue !== undefined) validateReflinkMode("cp", inlineValue);
- continue;
- }
- if (name === "update") {
- if (inlineValue !== undefined) validateUpdateMode("cp", inlineValue);
- continue;
- }
- if (arg.startsWith("-") && !arg.startsWith("--")) {
- i = scanCpShortMetaOption(args, i);
- continue;
- }
- if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- continue;
- }
- return null;
-}
-
-function scanCpShortMetaOption(args, index) {
- const arg = args[index];
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if ("finrRapsdlHLPTuvbxZ".includes(ch)) continue;
- if (ch === "t" || ch === "S") return arg.slice(j + 1) ? index : index + 1;
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- return index;
-}
-
-function duMetaOption(args) {
- const longFlagOptions = new Set(["null", "all", "apparent-size", "bytes", "total", "dereference-args", "human-readable", "inodes", "dereference", "count-links", "no-dereference", "separate-dirs", "si", "summarize", "one-file-system"]);
- const longValueOptions = new Set(["block-size", "max-depth", "files0-from", "threshold", "time-style", "exclude-from", "exclude"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLongOptionByPrefix(arg, DU_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (name === "time") {
- if (inlineValue !== undefined) validateDuTimeField(inlineValue);
- continue;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? args[i + 1];
- if (name === "block-size" && value !== undefined) validateBlockSizeMetaOption("--block-size", value);
- if (name === "threshold" && value !== undefined) duParseThreshold(value);
- if (name === "max-depth" && value !== undefined) validateDuMaxDepthMetaOption(value, args, inlineValue === undefined ? i + 2 : i + 1);
- if (inlineValue === undefined) i++;
- continue;
- }
- if (arg.startsWith("-") && !arg.startsWith("--")) {
- i = scanDuShortMetaOption(args, i);
- continue;
- }
- if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- continue;
- }
- return null;
-}
-
-function scanDuShortMetaOption(args, index) {
- const arg = args[index];
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if ("0aADHLPlsSbhckmx".includes(ch)) continue;
- if (ch === "B") {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[index + 1] : inlineValue;
- if (value !== undefined) validateBlockSizeMetaOption("-B", value);
- return inlineValue === "" ? index + 1 : index;
- }
- if (ch === "d") {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[index + 1] : inlineValue;
- if (value !== undefined) validateDuMaxDepthMetaOption(value, args, inlineValue === "" ? index + 2 : index + 1);
- return inlineValue === "" ? index + 1 : index;
- }
- if (ch === "t") {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[index + 1] : inlineValue;
- if (value !== undefined) duParseThreshold(value, false, "-t");
- return inlineValue === "" ? index + 1 : index;
- }
- if (ch === "X") return arg.slice(j + 1) ? index : index + 1;
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- return index;
-}
-
-function statMetaOption(args) {
- const longFlagOptions = new Set(["file-system", "dereference", "terse"]);
- const longValueOptions = new Set(["cached", "format", "printf"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeStatLongOption(arg);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? args[i + 1];
- if (name === "cached" && value !== undefined) validateStatCached(value);
- if (inlineValue === undefined) i++;
- continue;
- }
- if (arg.startsWith("-") && !arg.startsWith("--")) {
- i = scanStatShortMetaOption(args, i);
- continue;
- }
- if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- }
- return null;
-}
-
-function scanStatShortMetaOption(args, index) {
- const arg = args[index];
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if ("fLt".includes(ch)) continue;
- if (ch === "c") return arg.slice(j + 1) ? index : index + 1;
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- return index;
-}
-
-function dfMetaOption(args) {
- const longFlagOptions = new Set(["all", "human-readable", "si", "inodes", "local", "total", "print-type", "sync", "no-sync", "portability"]);
- const longValueOptions = new Set(["block-size", "output", "type", "exclude-type"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeDfLongOption(arg);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? args[i + 1];
- if (name === "block-size" && value !== undefined) validateBlockSizeMetaOption("--block-size", value);
- if (name === "output" && inlineValue !== undefined) dfOutputFields([inlineValue]);
- if (inlineValue === undefined) i++;
- continue;
- }
- if (arg.startsWith("-") && !arg.startsWith("--")) {
- i = scanDfShortMetaOption(args, i);
- continue;
- }
- if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- }
- return null;
-}
-
-function scanDfShortMetaOption(args, index) {
- const arg = args[index];
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if ("ahHiklPT".includes(ch)) continue;
- if (ch === "B") {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[index + 1] : inlineValue;
- if (value !== undefined) validateBlockSizeMetaOption("-B", value);
- return inlineValue === "" ? index + 1 : index;
- }
- if (ch === "t" || ch === "x") return arg.slice(j + 1) ? index : index + 1;
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- return index;
-}
-
-function lsMetaOption(args) {
- const longOptionalValueOptions = new Set(["classify", "color", "hyperlink"]);
- const longValueOptions = new Set(["indicator-style", "sort", "time-style", "time", "tabsize", "width", "block-size", "format", "ignore", "hide", "quoting", "quoting-style"]);
- const longFlagOptions = new Set(LS_LONG_OPTIONS.filter((option) => !longOptionalValueOptions.has(option) && !longValueOptions.has(option) && option !== "help" && option !== "version"));
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLsLongOption(arg);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (longFlagOptions.has(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (longOptionalValueOptions.has(name)) {
- if (name === "color" && inlineValue !== undefined) lsColorEnabled({ color: inlineValue });
- if (name === "hyperlink" && inlineValue !== undefined) lsHyperlinkEnabled({ hyperlink: inlineValue });
- if (name === "classify" && inlineValue !== undefined) validateLsClassifyMetaOption(inlineValue);
- continue;
- }
- if (longValueOptions.has(name)) {
- const value = inlineValue ?? args[i + 1];
- if (name === "block-size" && value !== undefined) validateBlockSizeMetaOption("--block-size", value);
- if (name === "width" && value !== undefined) parseLsWidth(value);
- if (name === "tabsize" && value !== undefined) parseLsTabSize(value);
- if (name === "time" && value !== undefined) validateLsTime(value);
- if (name === "sort" && value !== undefined) validateLsSort(value);
- if (name === "indicator-style" && value !== undefined) validateLsIndicatorStyle(value);
- if (name === "format" && value !== undefined) lsLayoutForFormat(value);
- if ((name === "quoting" || name === "quoting-style") && value !== undefined) validateLsQuotingStyle(value);
- if (inlineValue === undefined) i++;
- continue;
- }
- if (arg.startsWith("-") && !arg.startsWith("--")) {
- i = scanLsShortMetaOption(args, i);
- continue;
- }
- if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- }
- return null;
-}
-
-function scanLsShortMetaOption(args, index) {
- const arg = args[index];
- const flagOptions = new Set(["a", "A", "B", "D", "H", "L", "c", "u", "l", "d", "f", "g", "G", "o", "n", "i", "s", "h", "k", "1", "F", "R", "S", "t", "X", "U", "r", "b", "C", "x", "m", "q", "Q", "N", "v", "p", "Z", "0"]);
- const valueOptions = new Set(["T", "w", "I"]);
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (valueOptions.has(ch)) {
- const inlineValue = arg.slice(j + 1);
- const value = inlineValue === "" ? args[index + 1] : inlineValue;
- if (ch === "w" && value !== undefined) parseLsWidth(value);
- if (ch === "T" && value !== undefined) parseLsTabSize(value);
- return inlineValue === "" ? index + 1 : index;
- }
- if (flagOptions.has(ch)) {
- continue;
- }
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- return index;
-}
-
-function validateBlockSizeMetaOption(option, value) {
- try {
- parseGNUBlockSize(value);
- } catch {
- throw new UsageError(gnuBlockSizeErrorMessage(option, value), false);
- }
-}
-
-function validateDuMaxDepthMetaOption(value, args, startIndex) {
- try {
- parseDuMaxDepth(value, false);
- } catch (error) {
- if (!(error instanceof UsageError)) throw error;
- if (!duHasMetaOptionAfter(args, startIndex)) return;
- stderr(`du: ${error.message}\n`);
- }
-}
-
-function duHasMetaOptionAfter(args, startIndex) {
- for (let i = startIndex; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return false;
- if (!arg.startsWith("--")) continue;
- const normalized = normalizeLongOptionByPrefix(arg, DU_LONG_OPTIONS);
- const [name, inlineValue] = normalized.slice(2).split(/=(.*)/s, 2);
- if ((name === "help" || name === "version") && inlineValue === undefined) return true;
- }
- return false;
-}
-
-function validateLsIndicatorStyle(value) {
- if (lsIndicatorStyle({ "indicator-style": value }) === null) {
- throw new InvocationError(lsInvalidEnumMessage(value, "--indicator-style", LS_INDICATOR_VALID_ARGUMENTS), 1, true);
- }
-}
-
-function validateLsClassifyMetaOption(value) {
- if (lsIndicatorStyle({ classify: value }) === null) {
- throw new InvocationError(lsInvalidEnumMessage(value, "--classify", LS_CLASSIFY_VALID_ARGUMENTS), 1, true);
- }
-}
-
-function idMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeIdLongOption(arg);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- return normalized;
- }
- if (ID_LONG_OPTIONS.includes(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- if (name === "context" && !selinuxRuntimeEnabled()) return null;
- continue;
- }
- if (arg.startsWith("-") && !arg.startsWith("--")) {
- if (arg.includes("Z") && !selinuxRuntimeEnabled()) return null;
- i = scanIdShortMetaOption(args, i);
- continue;
- }
- if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- }
- return null;
-}
-
-function scanIdShortMetaOption(args, index) {
- const arg = args[index];
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if ("ugGnrzZ".includes(ch)) continue;
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- return index;
-}
-
-function parseOptions(args, spec = {}) {
- const opts = {};
- const operands = [];
- let end = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (end || arg === "-" || !arg.startsWith("-")) {
- operands.push(arg);
- continue;
- }
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- const mode = spec.long?.[name];
- if (mode === undefined) throw new UsageError(`unrecognized option '${arg}'`, true);
- if (mode === "value" || mode === "value-array") {
- if (inlineValue != null) setParsedOptionValue(opts, name, inlineValue, mode === "value-array");
- else if (i + 1 < args.length) setParsedOptionValue(opts, name, args[++i], mode === "value-array");
- else throw new UsageError(`option '--${name}' requires an argument`, true);
- } else if (mode === "optional-value") {
- opts[name] = inlineValue ?? true;
- } else {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- opts[name] = true;
- }
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- const mode = spec.short?.[ch];
- if (mode === undefined) throw new UsageError(`invalid option -- '${ch}'`, true);
- if (mode === "value" || mode === "value-array") {
- if (arg.slice(j + 1)) setParsedOptionValue(opts, ch, arg.slice(j + 1), mode === "value-array");
- else if (i + 1 < args.length) setParsedOptionValue(opts, ch, args[++i], mode === "value-array");
- else throw new UsageError(`option requires an argument -- '${ch}'`, true);
- break;
- }
- if (mode === "optional-value") {
- opts[ch] = arg.slice(j + 1) || true;
- break;
- }
- opts[ch] = true;
- }
- }
- return { opts, operands };
-}
-
-function setParsedOptionValue(opts, name, value, append = false) {
- if (!append || opts[name] == null) {
- opts[name] = value;
- } else if (Array.isArray(opts[name])) {
- opts[name].push(value);
- } else {
- opts[name] = [opts[name], value];
- }
-}
-
-async function readAll(path) {
- if (path === "-") return readStdinBytes();
- return new Uint8Array(await Bun.file(path).arrayBuffer());
-}
-
-async function spoolInputToTemporaryFile(input, prefix, initialChunks = []) {
- const base = process.env.TMPDIR || "/tmp";
- const dir = await mkdtemp(join(base, `${prefix}-`));
- const path = join(dir, "data");
- const source = input === "-" ? null : await open(input, "r");
- let target;
- try {
- target = await open(path, "wx", 0o600);
- const buffer = Buffer.allocUnsafe(64 * 1024);
- const writeChunk = async (chunk) => {
- let offset = 0;
- while (offset < chunk.length) {
- const { bytesWritten } = await target.write(chunk, offset, chunk.length - offset, null);
- if (bytesWritten === 0) throw new Error("short write while spooling input");
- offset += bytesWritten;
- }
- };
- for (const chunk of initialChunks) await writeChunk(chunk);
- while (true) {
- const n = readSync(source?.fd ?? 0, buffer, 0, buffer.length, null);
- if (n === 0) break;
- await writeChunk(buffer.subarray(0, n));
- }
- await target.close();
- target = null;
- return { path, cleanup: () => rm(dir, { recursive: true, force: true }) };
- } catch (error) {
- await target?.close().catch(() => {});
- await rm(dir, { recursive: true, force: true }).catch(() => {});
- throw error;
- } finally {
- await source?.close().catch(() => {});
- }
-}
-
-function readStdinBytes() {
- const chunks = [];
- const buffer = Buffer.allocUnsafe(64 * 1024);
- let total = 0;
- while (true) {
- const n = readSync(0, buffer, 0, buffer.length, null);
- if (n === 0) break;
- chunks.push(Buffer.from(buffer.subarray(0, n)));
- total += n;
- }
- const out = new Uint8Array(total);
- let offset = 0;
- for (const chunk of chunks) {
- out.set(chunk, offset);
- offset += chunk.length;
- }
- return out;
-}
-
-function readStdinBytesLimit(limit) {
- const chunks = [];
- const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, Math.max(0, limit)));
- let total = 0;
- while (total < limit) {
- const n = readSync(0, buffer, 0, Math.min(buffer.length, limit - total), null);
- if (n === 0) break;
- chunks.push(Buffer.from(buffer.subarray(0, n)));
- total += n;
- }
- const out = new Uint8Array(total);
- let offset = 0;
- for (const chunk of chunks) {
- out.set(chunk, offset);
- offset += chunk.length;
- }
- return out;
-}
-
-function readStdinChunks(accept) {
- const buffer = Buffer.allocUnsafe(64 * 1024);
- while (true) {
- const n = readSync(0, buffer, 0, buffer.length, null);
- if (n === 0) break;
- accept(Buffer.from(buffer.subarray(0, n)));
- }
-}
-
-function readFdChunkViews(fd, accept, size = 64 * 1024) {
- const buffer = Buffer.allocUnsafe(size);
- while (true) {
- const n = readSync(fd, buffer, 0, buffer.length, null);
- if (n === 0) break;
- accept(buffer.subarray(0, n));
- }
-}
-
-function readStdinChunkViews(accept, size = 64 * 1024) {
- readFdChunkViews(0, accept, size);
-}
-
-function readFdByteRecords(fd, sepByte, accept) {
- const buffer = Buffer.allocUnsafe(64 * 1024);
- let pending = [];
- let pendingLength = 0;
- const flush = (hasSep) => {
- const bytes = new Uint8Array(pendingLength);
- let offset = 0;
- for (const chunk of pending) {
- bytes.set(chunk, offset);
- offset += chunk.length;
- }
- pending = [];
- pendingLength = 0;
- accept(bytes, hasSep);
- };
- while (true) {
- const n = readSync(fd, buffer, 0, buffer.length, null);
- if (n === 0) break;
- let start = 0;
- for (let i = 0; i < n; i++) {
- if (buffer[i] !== sepByte) continue;
- pending.push(Buffer.from(buffer.subarray(start, i)));
- pendingLength += i - start;
- flush(true);
- start = i + 1;
- }
- if (start < n) {
- pending.push(Buffer.from(buffer.subarray(start, n)));
- pendingLength += n - start;
- }
- }
- if (pendingLength) flush(false);
-}
-
-function readStdinByteRecords(sepByte, accept) {
- readFdByteRecords(0, sepByte, accept);
-}
-
-async function writeAll(path, data, append = false) {
- if (path === "-") return stdout(data);
- await writeFile(path, data, append ? { flag: "a" } : undefined);
-}
-
-async function cat(args) {
- args = normalizeCatLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { n: false, b: false, s: false, e: false, t: false, u: false, v: false, E: false, T: false, A: false }, long: { "number": false, "number-nonblank": false, "squeeze-blank": false, "show-ends": false, "show-tabs": false, "show-nonprinting": false, "show-all": false, help: false, version: false } });
- const files = operands.length ? operands : ["-"];
- const selfError = await catSelfOutputError(files);
- if (selfError) return selfError;
- const needsProcessing = opts.n || opts.number || opts.b || opts["number-nonblank"] || opts.s || opts["squeeze-blank"] || hasCatRendering(opts);
- const needsLineState = opts.n || opts.number || opts.b || opts["number-nonblank"] || opts.s || opts["squeeze-blank"];
- if (files.length === 1 && files[0] === "-" && !needsLineState && hasCatRendering(opts)) {
- streamRenderedCatStdin(opts);
- return 0;
- }
- if (!needsProcessing) {
- let failed = false;
- for (const file of files) {
- try {
- streamCatFile(file);
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(`cat: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- }
- }
- return failed ? 1 : 0;
- }
- let line = 1;
- let previousBlank = false;
- const out = [];
- let failed = false;
- const inputChunks = [];
- for (const file of files) {
- let bytes;
- try {
- // Bun.file('.').arrayBuffer() currently treats a directory as an empty
- // file on some platforms. cat must instead report the POSIX read
- // failure, just as it does for every other directory operand.
- if (file !== "-" && (await stat(file)).isDirectory()) {
- const error = new Error("Is a directory");
- error.code = "EISDIR";
- throw error;
- }
- bytes = await readAll(file);
- } catch (error) {
- stderr(`cat: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- continue;
- }
- if (!needsProcessing) {
- out.push(bytes);
- continue;
- }
- inputChunks.push(Buffer.from(bytes));
- }
- if (needsProcessing && inputChunks.length) {
- const bytes = Buffer.concat(inputChunks);
- const decoded = isSingleByteLocale() ? null : decodeValidUtf8(bytes);
- const rawMode = decoded == null;
- const text = rawMode ? Buffer.from(bytes).toString("latin1") : decoded;
- const parts = text.split(/(?<=\n)/);
- for (const part of parts) {
- if (part === "") continue;
- const blank = part === "\n";
- if ((opts.s || opts["squeeze-blank"]) && blank && previousBlank) continue;
- previousBlank = blank;
- const numberNonblank = opts.b || opts["number-nonblank"];
- const numberAll = !numberNonblank && (opts.n || opts.number);
- if ((numberAll || (numberNonblank && !blank))) out.push(`${String(line++).padStart(6)}\t`);
- const rendered = renderCat(part, opts);
- out.push(rawMode ? Buffer.from(rendered, "latin1") : rendered);
- }
- }
- stdout(concatOutputParts(out));
- return failed ? 1 : 0;
-}
-
-function streamCatFile(path) {
- const fd = path === "-" ? 0 : openSync(path, "r");
- const buffer = Buffer.allocUnsafe(64 * 1024);
- try {
- while (true) {
- const n = readSync(fd, buffer, 0, buffer.length, null);
- if (n === 0) break;
- stdout(buffer.subarray(0, n));
- }
- } finally {
- if (fd !== 0) closeSync(fd);
- }
-}
-
-async function catSelfOutputError(files) {
- const out = fdStat(1);
- if (!out) return 0;
- const inStat = fdStat(0);
- const append = (libc.symbols.fcntl(1, F_GETFL) & O_APPEND) !== 0;
- if (append && inStat && sameFileStat(out, inStat) && fdPosition(0) < inStat.size) return fail("cat", "input file is output file");
- for (let i = 0; i < files.length; i++) {
- if (files[i] === "-") continue;
- const s = await stat(files[i]).catch(() => null);
- if (!s || !sameFileStat(out, s)) continue;
- if (append || i > 0) return fail("cat", `${files[i]}: input file is output file`);
- }
- return 0;
-}
-
-function normalizeCatLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, CAT_LONG_OPTIONS);
-}
-
-function normalizeCatLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, CAT_LONG_OPTIONS);
-}
-
-function fdStat(fd) {
- try {
- return fstatSync(fd);
- } catch {
- return null;
- }
-}
-
-function sameFileStat(left, right) {
- return left.dev === right.dev && left.ino === right.ino;
-}
-
-function fdPosition(fd) {
- const position = libc.symbols.lseek(fd, 0n, SEEK_CUR);
- return position < 0 ? 0 : Number(position);
-}
-
-function streamRenderedCatStdin(opts) {
- const decoder = new TextDecoder();
- const state = { pendingCR: false };
- const buffer = Buffer.alloc(1);
- let out = "";
- while (true) {
- const n = readSync(0, buffer, 0, 1, null);
- if (n === 0) break;
- out += renderCatStreamText(decoder.decode(buffer.subarray(0, n), { stream: true }), opts, state);
- if (out.includes("\n")) {
- stdout(out);
- out = "";
- }
- }
- out += renderCatStreamText(decoder.decode(), opts, state);
- if (state.pendingCR) out += renderCatChar("\r", opts);
- if (out) stdout(out);
-}
-
-function hasCatRendering(opts) {
- return Boolean(opts.A || opts["show-all"] || opts.e || opts.E || opts["show-ends"] || opts.t || opts.T || opts["show-tabs"] || opts.v || opts["show-nonprinting"]);
-}
-
-function renderCatStreamText(text, opts, state) {
- let out = "";
- const showAll = opts.A || opts["show-all"];
- const showEnds = showAll || opts.e || opts.E || opts["show-ends"];
- for (const ch of text) {
- if (state.pendingCR) {
- if (showEnds && ch === "\n") {
- out += "^M$\n";
- state.pendingCR = false;
- continue;
- }
- out += renderCatChar("\r", opts);
- state.pendingCR = false;
- }
- if (ch === "\r") state.pendingCR = true;
- else out += renderCatChar(ch, opts);
- }
- return out;
-}
-
-function renderCat(text, opts) {
- const showAll = opts.A || opts["show-all"];
- const showEnds = showAll || opts.e || opts.E || opts["show-ends"];
- const showTabs = showAll || opts.t || opts.T || opts["show-tabs"];
- const showNonprinting = showAll || opts.e || opts.t || opts.v || opts["show-nonprinting"];
- let out = "";
- for (let i = 0; i < text.length; i++) {
- const ch = text[i];
- if (ch === "\n") out += showEnds ? "$\n" : "\n";
- else if (showEnds && ch === "\r" && text[i + 1] === "\n") out += "^M";
- else out += renderCatChar(ch, opts);
- }
- return out;
-}
-
-function renderCatChar(ch, opts) {
- const showAll = opts.A || opts["show-all"];
- const showTabs = showAll || opts.t || opts.T || opts["show-tabs"];
- const showNonprinting = showAll || opts.e || opts.t || opts.v || opts["show-nonprinting"];
- if (ch === "\n") return (showAll || opts.e || opts.E || opts["show-ends"]) ? "$\n" : "\n";
- if (ch === "\t") return showTabs ? "^I" : "\t";
- return showNonprinting ? renderNonprinting(ch.codePointAt(0)) : ch;
-}
-
-function renderNonprinting(code) {
- if (code < 32) return `^${String.fromCharCode(code + 64)}`;
- if (code === 127) return "^?";
- if (code >= 128 && code < 256) {
- const low = code - 128;
- if (low < 32) return `M-^${String.fromCharCode(low + 64)}`;
- if (low === 127) return "M-^?";
- return `M-${String.fromCharCode(low)}`;
- }
- return String.fromCodePoint(code);
-}
-
-async function echo(args) {
- if (!process.env.POSIXLY_CORRECT && args.length === 1 && args[0] === "--help") {
- stdout("Usage: echo [SHORT-OPTION]... [STRING]...\n or: echo LONG-OPTION\nEcho the STRING(s) to standard output.\n\n -n do not output the trailing newline\n -e enable interpretation of backslash escapes\n -E disable interpretation of backslash escapes (default)\n");
- return 0;
- }
- if (!process.env.POSIXLY_CORRECT && args.length === 1 && args[0] === "--version") {
- stdout(`${VERSION}\n`);
- return 0;
- }
- let interpret = false;
- let newline = true;
- let i = 0;
- if (process.env.POSIXLY_CORRECT) {
- interpret = true;
- if (args[0] === "-n") {
- newline = false;
- i = 1;
- while (i < args.length && /^-[eE]+$/.test(args[i])) i++;
- }
- } else {
- while (i < args.length && /^-[neE]+$/.test(args[i])) {
- for (const ch of args[i].slice(1)) {
- if (ch === "n") newline = false;
- if (ch === "e") interpret = true;
- if (ch === "E") interpret = false;
- }
- i++;
- }
- }
- let text = args.slice(i).join(" ");
- if (interpret) {
- const stop = text.indexOf("\\c");
- if (stop !== -1) {
- text = text.slice(0, stop);
- newline = false;
- }
- text = decodeEchoEscapes(text);
- }
- stdout(text + (newline ? "\n" : ""));
- return 0;
-}
-
-function decodeEchoEscapes(text) {
- return text.replace(/\\(0[0-7]{0,3}|[0-7]{1,3}|x[0-9a-fA-F]{1,2}|[\\abefnrtv])/g, (_, escape) => {
- const simple = { "\\": "\\", a: "\x07", b: "\b", e: "\x1b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v" };
- if (simple[escape] != null) return simple[escape];
- if (escape.startsWith("x")) return String.fromCharCode(Number.parseInt(escape.slice(1), 16));
- const digits = escape.startsWith("0") ? escape.slice(1) : escape;
- return String.fromCharCode(Number.parseInt(digits || "0", 8));
- });
-}
-
-async function basename(args) {
- const { opts, operands } = parseBasenameOptions(args);
- if (!operands.length) throw new UsageError("missing operand", true);
- if (!(opts.a || opts.multiple || opts.s || opts.suffix) && operands.length > 2) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[2])}`, true);
- const rawOperands = rawOperandPlan("basename", args, operands, {
- valueOptions: ["--suffix"],
- shortValueOptions: ["s"],
- });
- const effectiveOperands = rawOperands ?? operands;
- const suffix = opts.s ?? opts.suffix ?? (!opts.a && !opts.multiple && operands[1] ? operands[1] : "");
- const names = opts.a || opts.multiple || opts.s || opts.suffix ? effectiveOperands : [effectiveOperands[0]];
- const sep = opts.z || opts.zero ? "\0" : "\n";
- const output = names.map((name) => {
- if (isBytePath(name)) {
- let base = gnuBasenameBytes(name);
- const suffixBytes = Buffer.from(suffix);
- if (suffixBytes.length && !base.equals(suffixBytes) && base.subarray(-suffixBytes.length).equals(suffixBytes)) base = base.subarray(0, base.length - suffixBytes.length);
- return base;
- }
- let base = gnuBasename(name);
- if (suffix && suffix !== base && base.endsWith(suffix)) base = base.slice(0, -suffix.length);
- return base;
- });
- stdout(output.some(isBytePath)
- ? Buffer.concat(output.flatMap((value) => [isBytePath(value) ? Buffer.from(value) : Buffer.from(value), Buffer.from(sep)]))
- : `${output.join(sep)}${sep}`);
- return 0;
-}
-
-function gnuBasenameBytes(name) {
- const bytes = Buffer.from(name);
- if (bytes.length && bytes.every((byte) => byte === 0x2f)) return Buffer.from("/");
- return Buffer.from(bufferPathBasename(bytes));
-}
-
-function parseBasenameOptions(args) {
- const opts = {};
- const operands = [];
- let parsing = true;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (!parsing || arg === "-" || !arg.startsWith("-")) {
- operands.push(arg);
- parsing = false;
- continue;
- }
- if (arg === "--") {
- parsing = false;
- continue;
- }
- if (arg.startsWith("--")) {
- const option = normalizeBasenameLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (name === "multiple") {
- if (inlineValue !== undefined) throw new UsageError("option '--multiple' doesn't allow an argument", true);
- opts.multiple = true;
- }
- else if (name === "zero") {
- if (inlineValue !== undefined) throw new UsageError("option '--zero' doesn't allow an argument", true);
- opts.zero = true;
- }
- else if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- opts[name] = true;
- }
- else if (name === "suffix") {
- if (inlineValue != null) opts.suffix = inlineValue;
- else if (i + 1 < args.length) opts.suffix = args[++i];
- else throw new UsageError("option '--suffix' requires an argument", true);
- }
- else throw new UsageError(`unrecognized option '--${name}'`, true);
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "a") opts.a = true;
- else if (ch === "z") opts.z = true;
- else if (ch === "s") {
- if (arg.slice(j + 1)) opts.s = arg.slice(j + 1);
- else if (i + 1 < args.length) opts.s = args[++i];
- else throw new UsageError("option requires an argument -- 's'", true);
- break;
- } else {
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- }
- }
- return { opts, operands };
-}
-
-function normalizeBasenameLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = BASENAME_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-function gnuBasename(name) {
- let text = String(name);
- if (/^\/+$/.test(text)) return "/";
- text = text.replace(/\/+$/g, "");
- const idx = text.lastIndexOf("/");
- return idx === -1 ? text : text.slice(idx + 1);
-}
-
-async function dirname(args) {
- const { opts, operands } = parseDirnameOptions(args);
- if (!operands.length) throw new UsageError("missing operand", true);
- const sep = opts.z || opts.zero ? "\0" : "\n";
- const rawOperands = rawOperandPlan("dirname", args, operands);
- const output = (rawOperands ?? operands).map((name) => isBytePath(name) ? gnuDirnameBytes(name) : gnuDirname(name));
- stdout(output.some(isBytePath)
- ? Buffer.concat(output.flatMap((value) => [isBytePath(value) ? Buffer.from(value) : Buffer.from(value), Buffer.from(sep)]))
- : `${output.join(sep)}${sep}`);
- return 0;
-}
-
-function gnuDirnameBytes(name) {
- const bytes = Buffer.from(name);
- if (!bytes.length) return Buffer.from(".");
- if (bytes.every((byte) => byte === 0x2f)) return Buffer.from("/");
- let end = bytes.length;
- while (end > 0 && bytes[end - 1] === 0x2f) end--;
- const slash = bytes.lastIndexOf(0x2f, end - 1);
- if (slash === -1) return Buffer.from(".");
- let dirEnd = slash;
- while (dirEnd > 0 && bytes[dirEnd - 1] === 0x2f) dirEnd--;
- return dirEnd === 0 ? Buffer.from("/") : bytes.subarray(0, dirEnd);
-}
-
-function parseDirnameOptions(args) {
- const opts = {};
- const operands = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "-" || !arg.startsWith("-")) {
- operands.push(arg);
- if (process.env.POSIXLY_CORRECT) end = true;
- continue;
- }
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg.startsWith("--")) {
- const option = normalizeDirnameLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!DIRNAME_LONG_OPTIONS.includes(name)) throw new UsageError(`unrecognized option '${arg}'`, true);
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- opts[name] = true;
- continue;
- }
- for (const ch of arg.slice(1)) {
- if (ch === "z") opts.z = true;
- else throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- }
- return { opts, operands };
-}
-
-function normalizeDirnameLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = DIRNAME_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-function gnuDirname(name) {
- let text = String(name);
- if (text === "") return ".";
- if (/^\/+$/.test(text)) return "/";
- text = text.replace(/\/+$/g, "");
- const idx = text.lastIndexOf("/");
- if (idx === -1) return ".";
- let dir = text.slice(0, idx);
- if (dir === "") return "/";
- if (/^\/+$/.test(dir)) return "/";
- return dir.replace(/\/+$/g, "");
-}
-
-async function pwd(args) {
- args = normalizePwdLongOptions(args);
- const requestedMode = pwdRequestedMode(args);
- const { operands } = parseOptions(args, { short: { L: false, P: false }, long: { logical: false, physical: false, help: false, version: false } });
- if (operands.length) stderr("pwd: ignoring non-option arguments\n");
- const wrapperPwd = syntacticallyValidLogicalPwd(process.env.BNU_LONG_PWD);
- if (wrapperPwd != null) {
- stdout(`${wrapperPwd}\n`);
- return 0;
- }
- const cwd = processCwdOrNull();
- if (cwd == null) {
- const logical = syntacticallyValidLogicalPwd(process.env.PWD);
- if (logical != null) {
- stdout(`${logical}\n`);
- return 0;
- }
- throw new UsageError("failed to find current directory");
- }
- const physical = await realpath(cwd);
- const useLogical = requestedMode === "logical" || (requestedMode == null && process.env.POSIXLY_CORRECT);
- if (useLogical) {
- const logical = await validLogicalPwd(process.env.PWD, physical);
- stdout(`${logical ?? physical}\n`);
- } else {
- stdout(`${physical}\n`);
- }
- return 0;
-}
-
-function pwdRequestedMode(args) {
- let mode = null;
- let end = false;
- for (const arg of args) {
- if (end) continue;
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg === "-" || !arg.startsWith("-")) continue;
- if (arg.startsWith("--")) {
- if (arg === "--logical") mode = "logical";
- else if (arg === "--physical") mode = "physical";
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- if (arg[j] === "L") mode = "logical";
- else if (arg[j] === "P") mode = "physical";
- }
- }
- return mode;
-}
-
-function normalizePwdLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizePwdLongOption(arg));
- }
- return out;
-}
-
-function normalizePwdLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = PWD_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-function processCwdOrNull() {
- try {
- return process.cwd();
- } catch {
- return null;
- }
-}
-
-function syntacticallyValidLogicalPwd(value) {
- if (!value || !isAbsolute(value)) return null;
- if (value.split("/").some((part) => part === "." || part === "..")) return null;
- return value;
-}
-
-async function validLogicalPwd(value, physical) {
- if (syntacticallyValidLogicalPwd(value) == null) return null;
- try {
- return await realpath(value) === physical ? value : null;
- } catch {
- return null;
- }
-}
-
-async function wc(args) {
- args = normalizeWcLongOptions(args);
- const parsed = parseOptions(args, {
- short: { c: false, m: false, l: false, L: false, w: false },
- long: { bytes: false, chars: false, lines: false, "max-line-length": false, words: false, "files0-from": "value", total: "value", debug: false, help: false, version: false },
- });
- const flags = parsed.opts;
- const showAll = !(flags.c || flags.m || flags.l || flags.L || flags.w || flags.bytes || flags.chars || flags.lines || flags["max-line-length"] || flags.words);
- const totalMode = flags.total ?? "auto";
- validateWcTotalMode(totalMode);
- let files = parsed.operands.length ? parsed.operands : ["-"];
- let files0From = null;
- let files0EntryCount = null;
- if (flags["files0-from"] !== undefined) {
- if (parsed.operands.length) throw new UsageError(`extra operand '${parsed.operands[0]}'\nfile operands cannot be combined with --files0-from`, true);
- files0From = flags["files0-from"];
- if (wcFiles0SourceIsNonRegular(files0From)) {
- return wcStreamFiles0(files0From, flags, showAll, totalMode);
- }
- let nameBytes;
- try {
- nameBytes = await readAll(files0From);
- } catch (error) {
- stderr(error?.code === "EISDIR"
- ? `wc: ${wcFiles0DiagnosticName(files0From)}: read error: ${systemErrorMessage(error)}\n`
- : `wc: cannot open ${wcFiles0OpenName(files0From)} for reading: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- files = splitFiles0ByteNames(nameBytes);
- files0EntryCount = files.length;
- if (files0From === "-" && files.some(wcFileNameIsDash)) {
- stderr("wc: when reading file names from standard input, no file name of '-' allowed\n");
- return 1;
- }
- }
- const rows = [];
- const total = { lines: 0, words: 0, bytes: 0n, chars: 0, maxLineLength: 0 };
- const bytesOnly = (flags.c || flags.bytes) && !(flags.m || flags.chars || flags.l || flags.lines || flags.L || flags["max-line-length"] || flags.w || flags.words);
- let failed = false;
- let totalByteOverflow = false;
- for (let index = 0; index < files.length; index++) {
- const file = files[index];
- if (files0From != null && wcFileNameIsEmpty(file)) {
- stderr(`wc: ${wcFiles0DiagnosticName(files0From)}:${index + 1}: invalid zero-length file name\n`);
- failed = true;
- continue;
- }
- let bytes;
- try {
- if (bytesOnly && file === "-") {
- const size = wcCountFdBytes(0);
- const name = parsed.operands.length === 0 && flags["files0-from"] === undefined ? "" : file;
- const row = { lines: 0, words: 0, bytes: size, chars: 0, maxLineLength: 0, name };
- if (wcByteTotalWouldOverflow(total.bytes, row.bytes)) totalByteOverflow = true;
- total.bytes = addWcByteTotal(total.bytes, row.bytes);
- rows.push(row);
- continue;
- }
- if (bytesOnly && file !== "-") {
- const info = await stat(file, { bigint: true });
- if (info.isDirectory()) throw Object.assign(new Error("Is a directory"), { code: "EISDIR" });
- const size = info.size;
- bytes = null;
- const row = { lines: 0, words: 0, bytes: size, chars: 0, maxLineLength: 0, name: file, specialFile: wcStatIsSpecial(info) };
- if (wcByteTotalWouldOverflow(total.bytes, row.bytes)) totalByteOverflow = true;
- total.bytes = addWcByteTotal(total.bytes, row.bytes);
- rows.push(row);
- continue;
- }
- bytes = await readAll(file);
- } catch (error) {
- if (error?.code === "EISDIR") {
- stderr(`wc: ${wcDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- rows.push({ lines: 0, words: 0, bytes: 0, chars: 0, maxLineLength: 0, name: file, directoryError: true });
- } else {
- stderr(file === "-" ? `wc: ${nodeErrorMessage(error)}\n` : `wc: ${wcDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- }
- failed = true;
- continue;
- }
- const row = wcRow(bytes, file === "-" && parsed.operands.length === 0 && flags["files0-from"] === undefined ? "" : file);
- if (file !== "-") {
- const info = await stat(file).catch(() => null);
- if (info && wcStatIsSpecial(info)) row.specialFile = true;
- }
- total.lines += row.lines;
- total.words += row.words;
- if (wcByteTotalWouldOverflow(total.bytes, row.bytes)) totalByteOverflow = true;
- total.bytes = addWcByteTotal(total.bytes, row.bytes);
- total.chars += row.chars;
- total.maxLineLength = Math.max(total.maxLineLength, row.maxLineLength);
- rows.push(row);
- }
- const totalInputCount = files0EntryCount ?? files.length;
- const includeTotal = totalMode === "always" || totalMode === "only" || (totalMode === "auto" && totalInputCount > 1);
- if (includeTotal && totalByteOverflow) failed = true;
- const outputRows = totalMode === "only" ? [] : [...rows];
- if (includeTotal) outputRows.push({ ...total, name: totalMode === "only" ? "" : "total" });
- const selectedValues = (row) => {
- const values = [];
- if (showAll || flags.l || flags.lines) values.push(row.lines);
- if (showAll || flags.w || flags.words) values.push(row.words);
- if (flags.m || flags.chars) values.push(row.chars);
- if (showAll || flags.c || flags.bytes) values.push(row.bytes);
- if (flags.L || flags["max-line-length"]) values.push(row.maxLineLength);
- return values;
- };
- const widthValues = (row) => showAll ? selectedValues(row) : [row.lines, row.words, row.chars, row.bytes, row.maxLineLength];
- const hasNamedOutput = outputRows.some((row) => row.name);
- const widthRows = [...outputRows];
- if (hasNamedOutput && totalInputCount > 1 && totalMode === "never") widthRows.push(total);
- const minCountWidth = showAll && outputRows.some((row) => row.directoryError || row.specialFile) ? 7 : 1;
- const countWidth = hasNamedOutput
- ? Math.max(minCountWidth, ...widthRows.flatMap(widthValues).map((n) => String(n).length))
- : 7;
- for (const row of outputRows) {
- const cols = selectedValues(row);
- const unpadded = totalMode === "only" || (!row.name && cols.length === 1) || (files0From != null && cols.length === 1);
- stdout(`${cols.map((n) => unpadded ? String(n) : String(n).padStart(countWidth)).join(" ")}${row.name ? ` ${wcDisplayName(row.name)}` : ""}\n`);
- }
- return failed ? 1 : 0;
-}
-
-function wcCountFdBytes(fd) {
- const buffer = Buffer.allocUnsafe(64 * 1024);
- let total = 0n;
- while (true) {
- const bytesRead = readSync(fd, buffer, 0, buffer.length, null);
- if (bytesRead === 0) return total;
- total += BigInt(bytesRead);
- }
-}
-
-function wcFiles0SourceIsNonRegular(source) {
- try {
- return !(source === "-" ? fstatSync(0) : statSync(source)).isFile();
- } catch {
- return false;
- }
-}
-
-async function wcStreamFiles0(source, flags, showAll, totalMode) {
- let fd = 0;
- let closeFd = false;
- try {
- if (source !== "-") {
- fd = openSync(source, "r");
- closeFd = true;
- }
- } catch (error) {
- stderr(`wc: cannot open ${wcFiles0OpenName(source)} for reading: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- const reader = createFdRecordReader(fd, 0);
- const total = { lines: 0, words: 0, bytes: 0n, chars: 0, maxLineLength: 0 };
- const bytesOnly = (flags.c || flags.bytes) && !(flags.m || flags.chars || flags.l || flags.lines || flags.L || flags["max-line-length"] || flags.w || flags.words);
- const selectedValues = (row) => {
- const values = [];
- if (showAll || flags.l || flags.lines) values.push(row.lines);
- if (showAll || flags.w || flags.words) values.push(row.words);
- if (flags.m || flags.chars) values.push(row.chars);
- if (showAll || flags.c || flags.bytes) values.push(row.bytes);
- if (flags.L || flags["max-line-length"]) values.push(row.maxLineLength);
- return values;
- };
- let failed = false;
- let totalByteOverflow = false;
- let entryCount = 0;
- try {
- while (true) {
- const file = reader.next();
- if (file == null) break;
- entryCount++;
- if (wcFileNameIsEmpty(file)) {
- stderr(`wc: ${wcFiles0DiagnosticName(source)}:${entryCount}: invalid zero-length file name\n`);
- failed = true;
- continue;
- }
- if (source === "-" && wcFileNameIsDash(file)) {
- stderr("wc: when reading file names from standard input, no file name of '-' allowed\n");
- failed = true;
- continue;
- }
- let row;
- try {
- if (bytesOnly) {
- const info = await stat(file, { bigint: true });
- if (info.isDirectory()) throw Object.assign(new Error("Is a directory"), { code: "EISDIR" });
- row = { lines: 0, words: 0, bytes: info.size, chars: 0, maxLineLength: 0, name: file, specialFile: wcStatIsSpecial(info) };
- } else {
- const bytes = await readAll(file);
- row = wcRow(bytes, file);
- const info = await stat(file).catch(() => null);
- if (info && wcStatIsSpecial(info)) row.specialFile = true;
- }
- } catch (error) {
- if (error?.code === "EISDIR") {
- stderr(`wc: ${wcDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- row = { lines: 0, words: 0, bytes: 0, chars: 0, maxLineLength: 0, name: file, directoryError: true };
- } else {
- stderr(`wc: ${wcDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- continue;
- }
- failed = true;
- }
- total.lines += row.lines;
- total.words += row.words;
- if (wcByteTotalWouldOverflow(total.bytes, row.bytes)) totalByteOverflow = true;
- total.bytes = addWcByteTotal(total.bytes, row.bytes);
- total.chars += row.chars;
- total.maxLineLength = Math.max(total.maxLineLength, row.maxLineLength);
- if (totalMode !== "only") {
- const cols = selectedValues(row);
- stdout(`${cols.map(String).join(" ")} ${wcDisplayName(row.name)}\n`);
- }
- }
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(`wc: ${wcFiles0DiagnosticName(source)}: read error: ${systemErrorMessage(error)}\n`);
- failed = true;
- } finally {
- if (closeFd) closeSync(fd);
- }
- const includeTotal = totalMode === "always" || totalMode === "only" || (totalMode === "auto" && entryCount > 1);
- if (includeTotal) {
- if (totalByteOverflow) failed = true;
- const cols = selectedValues(total);
- stdout(`${cols.map(String).join(" ")}${totalMode === "only" ? "" : " total"}\n`);
- }
- return failed ? 1 : 0;
-}
-
-function validateWcTotalMode(totalMode) {
- if (["auto", "always", "only", "never"].includes(totalMode)) return;
- throw new UsageError(`${totalMode === "" ? "ambiguous" : "invalid"} argument ${localeQuotedEscapedDiagnostic(totalMode)} for ${localeQuotedDiagnostic("--total")}\nValid arguments are:\n - ${localeQuotedDiagnostic("auto")}\n - ${localeQuotedDiagnostic("always")}\n - ${localeQuotedDiagnostic("only")}\n - ${localeQuotedDiagnostic("never")}`, true);
-}
-
-function wcDisplayName(name) {
- const text = pathDisplayName(name);
- if (!text.includes("\n")) return text;
- const parts = text.split("\n");
- const trailingNewline = parts.at(-1) === "";
- if (trailingNewline) parts.pop();
- return parts.map((part) => `'${part.replaceAll("'", "'\\''")}'`).join("$'\\n'") + (trailingNewline ? "$'\\n'" : "");
-}
-
-function wcDiagnosticName(name) {
- return shellEscapeLsName(pathDisplayName(name));
-}
-
-function wcFiles0OpenName(name) {
- return name === "-" ? "-" : shellEscapeLsName(pathDisplayName(name), true);
-}
-
-function wcFiles0DiagnosticName(name) {
- return name === "-" ? "-" : shellEscapeLsName(pathDisplayName(name));
-}
-
-function wcStatIsSpecial(info) {
- return info.isCharacterDevice() || info.isBlockDevice() || info.isFIFO() || info.isSocket();
-}
-
-function addWcByteTotal(total, bytes) {
- const next = total + BigInt(bytes);
- return next > UINTMAX_MAX ? UINTMAX_MAX : next;
-}
-
-function wcByteTotalWouldOverflow(total, bytes) {
- return total + BigInt(bytes) > UINTMAX_MAX;
-}
-
-function splitFiles0ByteNames(bytes) {
- if (bytes.byteLength === 0) return [];
- const names = [];
- let start = 0;
- for (let i = 0; i < bytes.byteLength; i++) {
- if (bytes[i] !== 0) continue;
- names.push(Buffer.from(bytes.subarray(start, i)));
- start = i + 1;
- }
- if (start < bytes.byteLength) names.push(Buffer.from(bytes.subarray(start)));
- return names;
-}
-
-function wcFileNameIsDash(file) {
- return file === "-" || (isBytePath(file) && Buffer.from(file).equals(Buffer.from("-")));
-}
-
-function wcFileNameIsEmpty(file) {
- return file === "" || (isBytePath(file) && file.byteLength === 0);
-}
-
-function normalizeWcLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, WC_LONG_OPTIONS);
-}
-
-function normalizeWcLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, WC_LONG_OPTIONS);
-}
-
-function wcRow(bytes, name) {
- const text = new TextDecoder().decode(bytes);
- return {
- lines: (text.match(/\n/g) || []).length,
- words: countWcWords(bytes, text),
- bytes: bytes.byteLength,
- chars: [...text].length,
- maxLineLength: maxLineLength(text),
- name,
- };
-}
-
-function countWcWords(bytes, text) {
- if (text.includes("\uFFFD")) return countWcWordsBytes(bytes);
- let count = 0;
- let inWord = false;
- for (const ch of text) {
- if (isWcWordSeparator(ch)) {
- inWord = false;
- } else if (!inWord) {
- count++;
- inWord = true;
- }
- }
- return count;
-}
-
-function countWcWordsBytes(bytes) {
- let count = 0;
- let inWord = false;
- for (const byte of bytes) {
- if (isWcByteSeparator(byte)) {
- inWord = false;
- } else if (!inWord) {
- count++;
- inWord = true;
- }
- }
- return count;
-}
-
-function isWcWordSeparator(ch) {
- return /\s/u.test(ch) || ch === "\u2060";
-}
-
-function isWcByteSeparator(byte) {
- return byte === 0x20 || (byte >= 0x09 && byte <= 0x0d) || byte === 0xa0 || byte === 0x9a;
-}
-
-function maxLineLength(text) {
- let max = 0;
- let column = 0;
- for (const ch of text) {
- if (ch === "\n" || ch === "\r" || ch === "\f") {
- max = Math.max(max, column);
- column = 0;
- } else if (ch === "\t") {
- column += 8 - (column % 8);
- } else {
- column += displayWidth(ch);
- }
- }
- return Math.max(max, column);
-}
-
-function displayWidth(ch) {
- const code = ch.codePointAt(0) ?? 0;
- if (code === 0 || ch === "\b" || ch === "\r" || ch === "\n" || ch === "\f") return 0;
- if (isCombiningMark(code) || isZeroWidthFormat(code)) return 0;
- if (isWideCodePoint(code)) return 2;
- return 1;
-}
-
-function isZeroWidthFormat(code) {
- return code === 0x061c || code === 0x180e || code === 0xfeff
- || (code >= 0x200b && code <= 0x200f)
- || (code >= 0x202a && code <= 0x202e)
- || (code >= 0x2060 && code <= 0x2064)
- || (code >= 0x2066 && code <= 0x206f)
- || (code >= 0xfe00 && code <= 0xfe0f)
- || (code >= 0xe0000 && code <= 0xe007f);
-}
-
-function isCombiningMark(code) {
- return (code >= 0x0300 && code <= 0x036f)
- || (code >= 0x1ab0 && code <= 0x1aff)
- || (code >= 0x1dc0 && code <= 0x1dff)
- || (code >= 0x20d0 && code <= 0x20ff)
- || (code >= 0xfe20 && code <= 0xfe2f);
-}
-
-function isWideCodePoint(code) {
- return (code >= 0x1100 && code <= 0x115f)
- || code === 0x2329 || code === 0x232a
- || (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f)
- || (code >= 0xac00 && code <= 0xd7a3)
- || (code >= 0xf900 && code <= 0xfaff)
- || (code >= 0xfe10 && code <= 0xfe19)
- || (code >= 0xfe30 && code <= 0xfe6f)
- || (code >= 0xff00 && code <= 0xff60)
- || (code >= 0xffe0 && code <= 0xffe6)
- || (code >= 0x1f300 && code <= 0x1f64f)
- || (code >= 0x1f900 && code <= 0x1f9ff);
-}
-
-function readRanges(spec, mode = "bytes") {
- if (String(spec).startsWith("--")) throw new UsageError(mode === "fields" ? "invalid field range" : "invalid byte or character range", true);
- const ranges = [];
- for (const part of spec.split(",")) {
- const match = part.match(/^(\d*)-?(\d*)$/);
- if (part === "-") throw new UsageError("invalid range with no endpoint: -", true);
- if (!match) throw new UsageError(invalidCutRangeMessage(part, mode), true);
- if (!match[1] && !match[2]) {
- throw new UsageError(mode === "fields" ? "fields are numbered from 1" : "byte/character positions are numbered from 1", true);
- }
- const startBig = match[1] ? parseCutRangeEndpoint(match[1], mode) : 1n;
- const endBig = match[2] ? parseCutRangeEndpoint(match[2], mode) : (part.includes("-") ? null : startBig);
- if (endBig != null && startBig > endBig) throw new UsageError("invalid decreasing range", true);
- const start = cutRangeNumber(startBig);
- const end = endBig == null ? Infinity : cutRangeNumber(endBig);
- if (start <= 0 || end <= 0) {
- throw new UsageError(mode === "fields" ? "fields are numbered from 1" : "byte/character positions are numbered from 1", true);
- }
- ranges.push([start, end]);
- }
- ranges.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
- const merged = [];
- for (const [start, end] of ranges) {
- const previous = merged.at(-1);
- if (previous && start <= previous[1]) previous[1] = Math.max(previous[1], end);
- else merged.push([start, end]);
- }
- return merged;
-}
-
-function parseCutRangeEndpoint(text, mode) {
- const value = BigInt(text);
- const max = (1n << 64n) - 1n;
- if (value >= max) {
- const name = mode === "fields" ? "field number" : "byte/character offset";
- throw new UsageError(`${name} ${localeQuotedEscapedDiagnostic(text)} is too large`, true);
- }
- return value;
-}
-
-function cutRangeNumber(value) {
- return value > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(value);
-}
-
-function invalidCutRangeMessage(part, mode) {
- const kind = mode === "fields" ? "field value" : "byte/character position";
- const suffix = String(part).match(/^\d+-\d+(.+)$/)?.[1];
- return `invalid ${kind} ${localeQuotedDiagnostic(suffix ?? part)}`;
-}
-
-function inRanges(index, ranges) {
- return ranges.some(([start, end]) => index >= start && index <= end);
-}
-
-function selectCharacterRanges(line, ranges, complement = false) {
- const chars = [...line];
- if (complement) return [chars.filter((_, i) => !inRanges(i + 1, ranges)).join("")];
- return ranges.map(([start, end]) => chars.slice(start - 1, end === Infinity ? undefined : end).join("")).filter((part) => part.length);
-}
-
-function selectByteRanges(bytes, ranges, complement = false) {
- if (complement) return [bytes.filter((_, i) => !inRanges(i + 1, ranges))].filter((part) => part.length);
- return ranges.map(([start, end]) => bytes.slice(start - 1, end === Infinity ? undefined : end)).filter((part) => part.length);
-}
-
-function splitByteRecords(bytes, sep) {
- const records = [];
- let start = 0;
- for (let i = 0; i < bytes.length; i++) {
- if (bytes[i] === sep) {
- records.push({ record: bytes.slice(start, i), hasSep: true });
- start = i + 1;
- }
- }
- if (start < bytes.length) records.push({ record: bytes.slice(start), hasSep: false });
- return records;
-}
-
-function concatBytes(chunks) {
- const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
- const out = new Uint8Array(total);
- let offset = 0;
- for (const chunk of chunks) {
- out.set(chunk, offset);
- offset += chunk.byteLength;
- }
- return out;
-}
-
-function parseTabStops(value = "8", program = null) {
- const text = String(value).replace(/^["']|["']$/g, "").trim();
- if (text === "" || text === "," || text === "/" || text === "+") return [8];
- const parts = text.split(/[,\t ]+/).filter(Boolean);
- const diagnostics = [];
- let interval = null;
- let intervalMode = null;
- let zeroInterval = false;
- const numbers = [];
- let previous = 0;
- for (let index = 0; index < parts.length; index++) {
- let part = parts[index];
- if (part === "/" || part === "+") continue;
- if (part.includes("/") && !part.startsWith("/") && !part.startsWith("+/")) throw new UsageError("'/' specifier not at start of number: '/'");
- const matchedInterval = /^[/+]+(?=\/?\d)/.test(part);
- if (matchedInterval && part.startsWith("/") && index !== parts.length - 1) throw new UsageError("'/' specifier only allowed with the last value");
- part = part.replace(/^[/+]+(?=\/?\d)/, (prefix) => {
- intervalMode = prefix.includes("+") ? "+" : "/";
- return "";
- }).replace(/^\//, "");
- if (!/^\d+$/.test(part)) {
- const leadingDigits = part.match(/^\d+/)?.[0] ?? "";
- if (leadingDigits !== "" && Number(leadingDigits) > Number.MAX_SAFE_INTEGER) diagnostics.push(`tab stop is too large ${localeQuotedDiagnostic(leadingDigits)}`);
- const invalid = invalidTabSizeCharacters(part);
- if (diagnostics.length) {
- diagnostics.push(`tab size contains invalid character(s): ${localeQuotedEscapedDiagnostic(invalid)}`);
- continue;
- }
- throw new UsageError(`tab size contains invalid character(s): ${localeQuotedEscapedDiagnostic(invalid)}`);
- }
- const n = Number(part);
- if (n === 0) {
- if (matchedInterval) {
- zeroInterval = true;
- continue;
- }
- throw new UsageError("tab size cannot be 0");
- }
- if (n > Number.MAX_SAFE_INTEGER) {
- diagnostics.push(`tab stop is too large ${localeQuotedDiagnostic(part)}`);
- continue;
- }
- if (matchedInterval) interval = n;
- else {
- if (n <= previous) throw new UsageError("tab sizes must be ascending");
- numbers.push(n);
- previous = n;
- }
- }
- if (diagnostics.length) throw new UsageError(formatTabDiagnostics(diagnostics, program));
- const stops = numbers.length ? numbers : interval ? [interval] : zeroInterval ? [8] : [];
- if (interval) {
- stops.interval = interval;
- stops.intervalMode = intervalMode;
- }
- if (!stops.length || stops.some((n) => !Number.isInteger(n) || n <= 0)) throw new UsageError(`invalid tab size: ${value}`);
- return stops;
-}
-
-function formatTabDiagnostics(diagnostics, program = null) {
- if (diagnostics.length <= 1 || !program) return diagnostics.join("\n");
- return diagnostics.map((message, index) => index === 0 ? message : `${program}: ${message}`).join("\n");
-}
-
-function invalidTabSizeCharacters(part) {
- const stripped = String(part).replace(/^[+/]?\d*/, "").replace(/^[+/]/, "");
- return stripped || String(part);
-}
-
-function normalizeTabArgs(args) {
- const out = [];
- const obsolete = [];
- const shortTabs = [];
- let scanning = true;
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- throw new UsageError(`option requires an argument -- '${option.slice(1)}'`, true);
- };
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (scanning && /^-\d[\d,\s]*$/.test(arg)) obsolete.push(arg.slice(1));
- else if (arg === "-t") {
- shortTabs.push(requireValue(i, arg));
- i++;
- scanning = false;
- } else if (/^-t.+/.test(arg)) {
- shortTabs.push(arg.slice(2));
- scanning = false;
- }
- else if (arg === "-a" || arg === "--all" || arg === "--first-only" || arg === "-i" || arg === "--initial") {
- out.push(arg);
- }
- else {
- scanning = false;
- out.push(arg);
- }
- }
- const tabSpecs = [...obsolete, ...shortTabs];
- return tabSpecs.length ? ["-t", tabSpecs.join(","), ...out] : out;
-}
-
-function combinedTabSpec(longSpec, shortSpec) {
- if (longSpec != null && shortSpec != null) return `${longSpec},${shortSpec}`;
- return shortSpec ?? longSpec;
-}
-
-function nextTabColumn(column, stops) {
- if (stops.length === 1 && !stops.interval) return column + (stops[0] - (column % stops[0]));
- for (const stop of stops) if (stop > column) return stop;
- if (stops.interval) {
- if (stops.intervalMode === "+" && stops.length) {
- const base = stops.at(-1);
- return base + Math.ceil((column + 1 - base) / stops.interval) * stops.interval;
- }
- return column + (stops.interval - (column % stops.interval));
- }
- return column + 1;
-}
-
-function fileTypeChar(s) {
- if (s.isDirectory()) return "d";
- if (s.isSymbolicLink()) return "l";
- if (s.isBlockDevice()) return "b";
- if (s.isCharacterDevice()) return "c";
- if (s.isFIFO()) return "p";
- if (s.isSocket()) return "s";
- return "-";
-}
-
-function modeString(s) {
- const mode = s.mode;
- const chars = ["r", "w", "x"];
- let out = fileTypeChar(s);
- for (let shift = 6; shift >= 0; shift -= 3) {
- for (let bit = 2; bit >= 0; bit--) {
- if (bit === 0 && shift === 6 && (mode & 0o4000)) out += mode & 0o100 ? "s" : "S";
- else if (bit === 0 && shift === 3 && (mode & 0o2000)) out += mode & 0o010 ? "s" : "S";
- else if (bit === 0 && shift === 0 && (mode & 0o1000)) out += mode & 0o001 ? "t" : "T";
- else out += mode & (1 << (shift + bit)) ? chars[2 - bit] : "-";
- }
- }
- return out;
-}
-
-function blocksFor(s) {
- return s.blocks ?? Math.ceil(s.size / 512);
-}
-
-async function walkSize(path, apparent = false) {
- const s = await lstat(path);
- let total = apparent ? s.size : blocksFor(s) * 512;
- if (s.isDirectory() && !s.isSymbolicLink()) {
- for (const entry of await readdir(path)) total += await walkSize(join(path, entry), apparent);
- }
- return total;
-}
-
-async function cut(args) {
- args = normalizeCutLongOptions(args);
- const { opts, operands } = parseOptions(args, {
- short: { b: "value", c: "value", d: "value", f: "value", F: "value", n: false, O: "value", s: false, w: false, z: false },
- long: { bytes: "value", characters: "value", complement: false, delimiter: "value", fields: "value", "no-partial": false, "only-delimited": false, "output-delimiter": "value", "whitespace-delimited": "optional-value", "zero-terminated": false, help: false, version: false },
- });
- const modes = [
- opts.b !== undefined || opts.bytes !== undefined ? "bytes" : "",
- opts.c !== undefined || opts.characters !== undefined ? "characters" : "",
- opts.f !== undefined || opts.F !== undefined || opts.fields !== undefined ? "fields" : "",
- ].filter(Boolean);
- const fieldSpecCount = [opts.f, opts.F, opts.fields].filter((value) => value !== undefined).length;
- if (!modes.length) throw new UsageError("you must specify a list of bytes, characters, or fields", true);
- if (modes.length > 1) throw new UsageError("only one list may be specified", true);
- if (fieldSpecCount > 1) throw new UsageError("only one list may be specified", true);
- const mode = modes[0];
- const spec = opts.b ?? opts.bytes ?? opts.c ?? opts.characters ?? opts.f ?? opts.F ?? opts.fields;
- const ranges = readRanges(spec, mode);
- const complement = Boolean(opts.complement);
- const hasInputDelimiter = opts.d !== undefined || opts.delimiter !== undefined;
- const suppressUndelimited = opts.s || opts["only-delimited"];
- if (hasInputDelimiter && mode !== "fields") throw new UsageError("an input delimiter makes sense\n\tonly when operating on fields", true);
- if (suppressUndelimited && mode !== "fields") throw new UsageError("suppressing non-delimited lines makes sense\n\tonly when operating on fields", true);
- const whitespaceDelimited = opts.w || (opts.F != null && !hasInputDelimiter) || opts["whitespace-delimited"] !== undefined;
- if ((opts.w || opts["whitespace-delimited"] !== undefined) && hasInputDelimiter) throw new UsageError("-d and -w are mutually exclusive", true);
- const trimmedWhitespace = normalizeCutWhitespaceDelimitedOption(opts["whitespace-delimited"]);
- const delimiterOpt = normalizeCutQuotedValue(opts.d ?? opts.delimiter);
- const delimiter = whitespaceDelimited ? null : delimiterOpt === "" ? "\0" : delimiterOpt ?? "\t";
- const singleByteLocale = /^(C|POSIX)$/.test(process.env.LC_ALL ?? process.env.LC_CTYPE ?? process.env.LANG ?? "");
- const gb18030 = isGb18030Locale();
- const rawDelimiter = mode === "fields" && delimiter != null && (gb18030 || shouldUseRawCutDelimiter(delimiter)) ? rawCutOptionValue(["d"], ["delimiter"]) : null;
- const delimiterBytes = delimiter == null ? null : normalizeCutRawDelimiter(rawDelimiter, delimiter);
- const delimiterCharCount = delimiterBytes && gb18030 ? gb18030Units(delimiterBytes).length : [...delimiter ?? ""].length;
- if (mode === "fields" && delimiter != null && (delimiterCharCount !== 1 || (singleByteLocale && delimiter !== "\uFFFD" && enc.encode(delimiter).length > 1))) throw new UsageError("the delimiter must be a single character", true);
- const outputDelimiterOpt = normalizeCutQuotedValue(opts["output-delimiter"] ?? opts.O);
- const hasOutputDelimiter = outputDelimiterOpt !== undefined;
- const outputDelimiter = hasOutputDelimiter ? (outputDelimiterOpt === "" ? "\0" : outputDelimiterOpt) : opts.F != null ? " " : delimiter ?? "\t";
- const rawOutputDelimiter = hasOutputDelimiter && (gb18030 || shouldUseRawCutDelimiter(outputDelimiter)) ? rawCutOptionValue([], ["output-delimiter", "output-delimite", "output-delimit", "output-delimi", "output-delim", "output-deli", "output-del", "output-de", "output-d", "output-", "output", "outpu", "outp", "out", "ou"]) ?? rawCutOptionValue(["O"], []) : null;
- const outputDelimiterBytes = hasOutputDelimiter ? normalizeCutRawDelimiter(rawOutputDelimiter, outputDelimiter) : opts.F != null ? enc.encode(outputDelimiter) : delimiterBytes ?? enc.encode(outputDelimiter);
- const recordSep = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- const implicitStdin = operands.length === 0;
- const files = implicitStdin ? ["-"] : operands;
- const streamOptions = { mode, ranges, complement, recordSep, hasOutputDelimiter, outputDelimiter, outputDelimiterBytes, delimiter, delimiterBytes, whitespaceDelimited, trimmedWhitespace, suppressUndelimited, singleByteLocale, noPartial: Boolean(opts.n || opts["no-partial"]) };
- if (!gb18030 && delimiter !== recordSep && canStreamCutFd(streamOptions)) {
- let failed = false;
- for (const file of files) {
- const fd = file === "-" ? 0 : (() => {
- try {
- return openSync(file, "r");
- } catch (error) {
- stderr(`cut: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- return -1;
- }
- })();
- if (fd < 0) continue;
- try {
- streamCutFd(fd, streamOptions);
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(file === "-" ? `cut: ${nodeErrorMessage(error)}\n` : `cut: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- } finally {
- if (fd !== 0) closeSync(fd);
- }
- }
- return failed ? 1 : 0;
- }
- const out = [];
- let failed = false;
- for (const file of files) {
- let bytes;
- try {
- bytes = await readAll(file);
- } catch (error) {
- stderr(file === "-" ? `cut: ${nodeErrorMessage(error)}\n` : `cut: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- continue;
- }
- if (!bytes.length) continue;
- if (gb18030 && mode === "characters") {
- for (const raw of splitByteRecords(bytes, recordSep.charCodeAt(0))) {
- if (!raw.record.length && !raw.hasSep) continue;
- const pieces = selectGb18030CharacterRanges(raw.record, ranges, complement);
- out.push(...pieces);
- out.push(enc.encode(recordSep));
- }
- continue;
- }
- if (gb18030 && mode === "bytes" && (opts.n || opts["no-partial"])) {
- for (const raw of splitByteRecords(bytes, recordSep.charCodeAt(0))) {
- if (!raw.record.length && !raw.hasSep) continue;
- const pieces = selectGb18030ByteRangesNoSplit(raw.record, ranges, complement);
- out.push(...pieces);
- out.push(enc.encode(recordSep));
- }
- continue;
- }
- if (!gb18030 && !singleByteLocale && mode === "characters") {
- for (const raw of splitByteRecords(bytes, recordSep.charCodeAt(0))) {
- if (!raw.record.length && !raw.hasSep) continue;
- const pieces = selectUtf8CharacterRanges(raw.record, ranges, complement);
- for (let i = 0; i < pieces.length; i++) {
- if (i && hasOutputDelimiter) out.push(outputDelimiterBytes);
- out.push(pieces[i]);
- }
- out.push(enc.encode(recordSep));
- }
- continue;
- }
- if (!gb18030 && !singleByteLocale && mode === "bytes" && (opts.n || opts["no-partial"])) {
- for (const raw of splitByteRecords(bytes, recordSep.charCodeAt(0))) {
- if (!raw.record.length && !raw.hasSep) continue;
- const pieces = selectUtf8ByteRangesNoSplit(raw.record, ranges, complement);
- for (let i = 0; i < pieces.length; i++) {
- if (i && hasOutputDelimiter) out.push(outputDelimiterBytes);
- out.push(pieces[i]);
- }
- out.push(enc.encode(recordSep));
- }
- continue;
- }
- if (mode === "fields" && delimiter === recordSep) {
- let text = new TextDecoder().decode(bytes);
- const hasDelimiter = text.includes(delimiter);
- if (text.endsWith(delimiter) && text.length > delimiter.length) text = text.slice(0, -delimiter.length);
- if (!hasDelimiter && suppressUndelimited) continue;
- const fields = text === delimiter ? [""] : text.split(delimiter);
- const selected = fields.filter((_, i) => complement ? !inRanges(i + 1, ranges) : inRanges(i + 1, ranges));
- if (suppressUndelimited && !selected.length) continue;
- out.push((selected.length ? selected.join(outputDelimiter) : "") + recordSep);
- continue;
- }
- if ((gb18030 || singleByteLocale) && mode === "fields" && delimiterBytes != null && !whitespaceDelimited) {
- for (const raw of splitByteRecords(bytes, recordSep.charCodeAt(0))) {
- if (!raw.record.length && !raw.hasSep) continue;
- const fields = splitBytesByDelimiter(raw.record, delimiterBytes);
- if (fields.length === 1) {
- if (!suppressUndelimited) out.push(raw.record, enc.encode(recordSep));
- continue;
- }
- const selected = fields.filter((_, i) => complement ? !inRanges(i + 1, ranges) : inRanges(i + 1, ranges));
- out.push(joinByteFields(selected, outputDelimiterBytes), enc.encode(recordSep));
- }
- continue;
- }
- if (singleByteLocale && mode === "characters") {
- for (const raw of splitByteRecords(bytes, recordSep.charCodeAt(0))) {
- if (!raw.record.length && !raw.hasSep) continue;
- const pieces = selectByteRanges(raw.record, ranges, complement);
- for (let i = 0; i < pieces.length; i++) {
- if (i && hasOutputDelimiter) out.push(outputDelimiterBytes);
- out.push(pieces[i]);
- }
- out.push(enc.encode(recordSep));
- }
- continue;
- }
- if (mode === "bytes") {
- for (const raw of splitByteRecords(bytes, recordSep.charCodeAt(0))) {
- if (!raw.record.length && !raw.hasSep) continue;
- const pieces = selectByteRanges(raw.record, ranges, complement);
- for (let i = 0; i < pieces.length; i++) {
- if (i && hasOutputDelimiter) out.push(enc.encode(outputDelimiter));
- out.push(pieces[i]);
- }
- out.push(enc.encode(recordSep));
- }
- continue;
- }
-
- const records = new TextDecoder().decode(bytes).split(recordSep);
- const hadSep = records.length > 1 && records.at(-1) === "";
- if (hadSep) records.pop();
- for (const line of records) {
- if (mode === "fields") {
- const delimiterSubject = trimmedWhitespace ? line.trim() : line;
- const hasDelimiter = whitespaceDelimited ? CUT_BLANK_RE.test(delimiterSubject) : line.includes(delimiter);
- if (!hasDelimiter) {
- if (!(opts.s || opts["only-delimited"])) out.push(line, recordSep);
- continue;
- }
- const fields = whitespaceDelimited ? splitCutWhitespaceFields(line, trimmedWhitespace) : line.split(delimiter);
- out.push(fields.filter((_, i) => complement ? !inRanges(i + 1, ranges) : inRanges(i + 1, ranges)).join(outputDelimiter), recordSep);
- } else {
- out.push(selectCharacterRanges(line, ranges, complement).join(hasOutputDelimiter ? outputDelimiter : ""), recordSep);
- }
- }
- }
- stdout(out.length && out.every((part) => part instanceof Uint8Array) ? concatBytes(out) : out.join(""));
- return failed ? 1 : 0;
-}
-
-function streamCutFd(fd, options) {
- const sepByte = options.recordSep === "\0" ? 0 : 10;
- if (options.mode === "bytes" || (options.mode === "characters" && (options.singleByteLocale || cutSelectsAllPositions(options)))) {
- streamCutPositionChunks(fd, options, sepByte);
- return;
- }
- if (canStreamCutFieldsBounded(options)) {
- streamCutFieldChunks(fd, options, sepByte);
- return;
- }
- readFdByteRecords(fd, sepByte, (record, hasSep) => {
- if (!record.length && !hasSep) return;
- if (options.mode === "bytes") {
- const pieces = selectByteRanges(record, options.ranges, options.complement);
- const out = [];
- for (let i = 0; i < pieces.length; i++) {
- if (i && options.hasOutputDelimiter) out.push(options.outputDelimiterBytes);
- out.push(pieces[i]);
- }
- out.push(Uint8Array.of(sepByte));
- stdout(concatBytes(out));
- return;
- }
- if (options.singleByteLocale && options.mode === "characters") {
- const pieces = selectByteRanges(record, options.ranges, options.complement);
- const out = [];
- for (let i = 0; i < pieces.length; i++) {
- if (i && options.hasOutputDelimiter) out.push(options.outputDelimiterBytes);
- out.push(pieces[i]);
- }
- out.push(Uint8Array.of(sepByte));
- stdout(concatBytes(out));
- return;
- }
- if (options.singleByteLocale && options.mode === "fields" && options.delimiterBytes != null && !options.whitespaceDelimited) {
- const fields = splitBytesByDelimiter(record, options.delimiterBytes);
- if (fields.length === 1) {
- if (!options.suppressUndelimited) stdout(concatBytes([record, Uint8Array.of(sepByte)]));
- return;
- }
- const selected = fields.filter((_, i) => options.complement ? !inRanges(i + 1, options.ranges) : inRanges(i + 1, options.ranges));
- stdout(concatBytes([joinByteFields(selected, options.outputDelimiterBytes), Uint8Array.of(sepByte)]));
- return;
- }
- const line = new TextDecoder().decode(record);
- if (options.mode === "fields") {
- const delimiterSubject = options.trimmedWhitespace ? line.trim() : line;
- const hasDelimiter = options.whitespaceDelimited ? CUT_BLANK_RE.test(delimiterSubject) : line.includes(options.delimiter);
- if (!hasDelimiter) {
- if (!options.suppressUndelimited) stdout(line + options.recordSep);
- return;
- }
- const fields = options.whitespaceDelimited ? splitCutWhitespaceFields(line, options.trimmedWhitespace) : line.split(options.delimiter);
- stdout(fields.filter((_, i) => options.complement ? !inRanges(i + 1, options.ranges) : inRanges(i + 1, options.ranges)).join(options.outputDelimiter) + options.recordSep);
- return;
- }
- stdout(selectCharacterRanges(line, options.ranges, options.complement).join(options.hasOutputDelimiter ? options.outputDelimiter : "") + options.recordSep);
- });
-}
-
-function canStreamCutFd(options) {
- if (options.mode === "bytes") return !options.noPartial || options.singleByteLocale;
- if (options.mode === "characters") return options.singleByteLocale || cutSelectsAllPositions(options);
- return canStreamCutFieldsBounded(options);
-}
-
-function cutSelectsAllPositions(options) {
- return !options.complement && !options.hasOutputDelimiter && options.ranges.length === 1 && options.ranges[0][0] === 1 && options.ranges[0][1] === Infinity;
-}
-
-function streamCutPositionChunks(fd, options, sepByte) {
- const separator = Uint8Array.of(sepByte);
- let position = 0;
- let rangeIndex = 0;
- let lastWrittenRange = -1;
- let recordHasBytes = false;
- const resetRecord = () => {
- position = 0;
- rangeIndex = 0;
- lastWrittenRange = -1;
- recordHasBytes = false;
- };
- readFdChunkViews(fd, (chunk) => {
- const output = [];
- let runStart = -1;
- const endRun = (end) => {
- if (runStart !== -1) output.push(chunk.subarray(runStart, end));
- runStart = -1;
- };
- for (let index = 0; index < chunk.length; index++) {
- const byte = chunk[index];
- if (byte === sepByte) {
- endRun(index);
- output.push(separator);
- resetRecord();
- continue;
- }
- recordHasBytes = true;
- position++;
- while (rangeIndex < options.ranges.length && position > options.ranges[rangeIndex][1]) rangeIndex++;
- const selectedRange = rangeIndex < options.ranges.length
- && position >= options.ranges[rangeIndex][0]
- && position <= options.ranges[rangeIndex][1]
- ? rangeIndex
- : -1;
- const selected = options.complement ? selectedRange === -1 : selectedRange !== -1;
- if (!selected) {
- endRun(index);
- continue;
- }
- if (!options.complement && selectedRange !== lastWrittenRange) {
- endRun(index);
- if (lastWrittenRange !== -1 && options.hasOutputDelimiter) output.push(options.outputDelimiterBytes);
- lastWrittenRange = selectedRange;
- }
- if (runStart === -1) runStart = index;
- }
- endRun(chunk.length);
- for (const piece of output) stdout(piece);
- });
- if (recordHasBytes) stdout(separator);
-}
-
-function canStreamCutFieldsBounded(options) {
- if (options.mode !== "fields" || options.whitespaceDelimited || options.delimiterBytes?.length !== 1) return false;
- const fieldOneSelected = options.complement ? !inRanges(1, options.ranges) : inRanges(1, options.ranges);
- return options.suppressUndelimited ? !fieldOneSelected : fieldOneSelected;
-}
-
-function streamCutFieldChunks(fd, options, sepByte) {
- const delimiterByte = options.delimiterBytes[0];
- const separator = Uint8Array.of(sepByte);
- let field = 1;
- let sawDelimiter = false;
- let recordHasBytes = false;
- let selectedFields = 0;
- const fieldSelected = () => options.complement ? !inRanges(field, options.ranges) : inRanges(field, options.ranges);
- let selected = fieldSelected() && !options.suppressUndelimited;
- if (selected) selectedFields = 1;
- const resetRecord = () => {
- field = 1;
- sawDelimiter = false;
- recordHasBytes = false;
- selectedFields = 0;
- selected = fieldSelected() && !options.suppressUndelimited;
- if (selected) selectedFields = 1;
- };
- readFdChunkViews(fd, (chunk) => {
- const output = [];
- let runStart = selected ? 0 : -1;
- const endRun = (end) => {
- if (runStart !== -1 && end > runStart) output.push(chunk.subarray(runStart, end));
- runStart = -1;
- };
- for (let index = 0; index < chunk.length; index++) {
- const byte = chunk[index];
- if (byte === sepByte) {
- endRun(index);
- if (sawDelimiter || !options.suppressUndelimited) output.push(separator);
- resetRecord();
- continue;
- }
- recordHasBytes = true;
- if (byte !== delimiterByte) {
- if (selected && runStart === -1) runStart = index;
- continue;
- }
- endRun(index);
- sawDelimiter = true;
- field++;
- selected = fieldSelected();
- if (selected) {
- if (selectedFields && options.outputDelimiterBytes.length) output.push(options.outputDelimiterBytes);
- selectedFields++;
- runStart = index + 1;
- }
- }
- endRun(chunk.length);
- for (const piece of output) stdout(piece);
- });
- if (recordHasBytes && (sawDelimiter || !options.suppressUndelimited)) stdout(separator);
-}
-
-function splitCutWhitespaceFields(line, trimmed = false) {
- return (trimmed ? line.trim() : line).split(CUT_BLANK_RUN_RE);
-}
-
-// Match glibc's multibyte blank classification used by GNU cut. In
-// particular, U+2003 EM SPACE is a delimiter while U+00A0 NO-BREAK SPACE is
-// not, unlike JavaScript's broader \s character class.
-const CUT_BLANK_RE = /[\t \u1680\u2000-\u200a\u202f\u205f\u3000]/u;
-const CUT_BLANK_RUN_RE = /[\t \u1680\u2000-\u200a\u202f\u205f\u3000]+/u;
-
-function isGb18030Locale() {
- return /gb18030/i.test(process.env.LC_ALL ?? process.env.LC_CTYPE ?? process.env.LANG ?? "");
-}
-
-function isSingleByteLocale() {
- return /^(C|POSIX)$/.test(process.env.LC_ALL ?? process.env.LC_CTYPE ?? process.env.LANG ?? "");
-}
-
-function rawCutOptionValue(shortNames, longNames) {
- const rawArgs = rawCommandArgs("cut");
- if (!rawArgs) return null;
- const shortSet = new Set(shortNames);
- const longSet = new Set(longNames);
- for (let i = 0; i < rawArgs.length; i++) {
- const arg = rawArgs[i];
- if (arg.equals(Buffer.from("--"))) break;
- const text = arg.toString();
- if (arg.length === 2 && arg[0] === 0x2d && shortSet.has(String.fromCharCode(arg[1]))) return rawArgs[i + 1] ?? null;
- if (arg.length > 2 && arg[0] === 0x2d && arg[1] !== 0x2d && shortSet.has(String.fromCharCode(arg[1]))) return arg.subarray(2);
- if (text.startsWith("--")) {
- const eq = text.indexOf("=");
- const name = eq === -1 ? text.slice(2) : text.slice(2, eq);
- if (longSet.has(name)) return eq === -1 ? rawArgs[i + 1] ?? null : arg.subarray(Buffer.byteLength(`--${name}=`));
- }
- }
- return null;
-}
-
-function normalizeCutRawDelimiter(rawValue, parsedValue) {
- if (rawValue && rawValue.length === 0 && parsedValue === "\0") return Uint8Array.of(0);
- return rawValue ?? enc.encode(parsedValue);
-}
-
-function shouldUseRawCutDelimiter(value) {
- return value === "\0" || value.includes("\uFFFD");
-}
-
-function normalizeCutLongOptions(args, reportAmbiguous = true) {
- const out = [];
- for (const arg of args) {
- if (arg === "--") {
- out.push(arg);
- continue;
- }
- if (!arg.startsWith("--") || arg === "--") {
- out.push(arg);
- continue;
- }
- out.push(normalizeCutLongOption(arg, reportAmbiguous));
- }
- return out;
-}
-
-function normalizeCutLongOption(arg, reportAmbiguous = true) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- const matches = CUT_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length === 1) return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
- if (matches.length > 1 && reportAmbiguous) {
- throw new UsageError(`option '${arg}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- return arg;
-}
-
-function normalizeCutWhitespaceDelimitedOption(value) {
- if (value == null || value === true || value === "") return false;
- if ("trimmed".startsWith(String(value))) return true;
- throw new UsageError(`invalid argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic("--whitespace-delimited")}\nValid arguments are:\n - ${localeQuotedDiagnostic("trimmed")}`, true);
-}
-
-function normalizeCutQuotedValue(value) {
- if (typeof value === "string" && value.includes("'")) {
- let out = value;
- if (out.startsWith("'")) out = out.slice(1);
- if (out.endsWith("'")) out = out.slice(0, -1);
- if (out === "\\n") return "\n";
- return out;
- }
- return value;
-}
-
-function gb18030Units(bytes) {
- const units = [];
- for (let i = 0; i < bytes.length; i++) {
- if (bytes[i] >= 0x80 && i + 1 < bytes.length) units.push(bytes.slice(i, ++i + 1));
- else units.push(bytes.slice(i, i + 1));
- }
- return units;
-}
-
-function selectGb18030CharacterRanges(bytes, ranges, complement = false) {
- const units = gb18030Units(bytes);
- if (complement) return [concatBytes(units.filter((_, i) => !inRanges(i + 1, ranges)))].filter((part) => part.length);
- return ranges.map(([start, end]) => concatBytes(units.slice(start - 1, end === Infinity ? undefined : end))).filter((part) => part.length);
-}
-
-function selectGb18030ByteRangesNoSplit(bytes, ranges, complement = false) {
- const units = gb18030Units(bytes);
- const out = [];
- let pos = 1;
- for (const unit of units) {
- const start = pos;
- const end = pos + unit.length - 1;
- pos = end + 1;
- const include = complement
- ? [...Array(unit.length)].some((_, i) => !inRanges(start + i, ranges))
- : inRanges(end, ranges);
- if (include) out.push(unit);
- }
- return out;
-}
-
-function utf8Units(bytes) {
- const units = [];
- for (let i = 0; i < bytes.length;) {
- const start = i;
- const first = bytes[i++];
- let length = 1;
- if (first >= 0xc2 && first <= 0xdf && isUtf8Continuation(bytes[i])) length = 2;
- else if (first >= 0xe0 && first <= 0xef
- && isUtf8Continuation(bytes[i]) && isUtf8Continuation(bytes[i + 1])
- && !(first === 0xe0 && bytes[i] < 0xa0) && !(first === 0xed && bytes[i] >= 0xa0)) length = 3;
- else if (first >= 0xf0 && first <= 0xf4
- && isUtf8Continuation(bytes[i]) && isUtf8Continuation(bytes[i + 1]) && isUtf8Continuation(bytes[i + 2])
- && !(first === 0xf0 && bytes[i] < 0x90) && !(first === 0xf4 && bytes[i] >= 0x90)) length = 4;
- i = start + length;
- units.push(bytes.slice(start, i));
- }
- return units;
-}
-
-function isUtf8Continuation(byte) {
- return byte != null && byte >= 0x80 && byte <= 0xbf;
-}
-
-function selectUtf8CharacterRanges(bytes, ranges, complement = false) {
- const units = utf8Units(bytes);
- if (complement) return [concatBytes(units.filter((_, index) => !inRanges(index + 1, ranges)))].filter((part) => part.length);
- return ranges.map(([start, end]) => concatBytes(units.slice(start - 1, end === Infinity ? undefined : end))).filter((part) => part.length);
-}
-
-function selectUtf8ByteRangesNoSplit(bytes, ranges, complement = false) {
- const units = utf8Units(bytes);
- let position = 0;
- if (complement) {
- const selected = [];
- for (const unit of units) {
- position += unit.length;
- if (!inRanges(position, ranges)) selected.push(unit);
- }
- return [concatBytes(selected)].filter((part) => part.length);
- }
- const grouped = ranges.map(() => []);
- for (const unit of units) {
- position += unit.length;
- const rangeIndex = ranges.findIndex(([start, end]) => position >= start && position <= end);
- if (rangeIndex !== -1) grouped[rangeIndex].push(unit);
- }
- return grouped.map(concatBytes).filter((part) => part.length);
-}
-
-function textInputDiagnosticName(file) {
- return shellEscapeLsName(pathDisplayName(file));
-}
-
-function splitBytesByDelimiter(bytes, delimiter) {
- const fields = [];
- let start = 0;
- for (let i = 0; i <= bytes.length - delimiter.length;) {
- if (bytes.subarray(i, i + delimiter.length).every((byte, idx) => byte === delimiter[idx])) {
- fields.push(bytes.slice(start, i));
- i += delimiter.length;
- start = i;
- } else {
- i++;
- }
- }
- fields.push(bytes.slice(start));
- return fields;
-}
-
-function joinByteFields(fields, delimiter) {
- if (!fields.length) return new Uint8Array();
- const parts = [];
- for (let i = 0; i < fields.length; i++) {
- if (i) parts.push(delimiter);
- parts.push(fields[i]);
- }
- return concatBytes(parts);
-}
-
-async function paste(args) {
- const { opts, operands } = parseOptions(normalizePasteLongOptions(args), { short: { d: "value", s: false, z: false }, long: { delimiters: "value", serial: false, "zero-terminated": false, help: false, version: false } });
- const files = operands.length ? operands : ["-"];
- const recordSep = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- const delimiterValue = opts.d ?? opts.delimiters ?? "\t";
- const rawDelimiter = delimiterValue.includes("\uFFFD") ? pasteReplacementDelimiterBytes(delimiterValue, args) : null;
- const delimiters = parsePasteDelimiters(delimiterValue, rawDelimiter);
- const pick = (i) => delimiters[i % delimiters.length] ?? "\t";
- const out = [];
- let failed = false;
- if (!(opts.s || opts.serial) && files.length === 1) {
- const file = files[0];
- let fd;
- try {
- fd = file === "-" ? 0 : openSync(file, "r");
- streamPasteSingleFd(fd, recordSep.charCodeAt(0));
- return 0;
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(file === "-" ? `paste: ${nodeErrorMessage(error)}\n` : `paste: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- return 1;
- } finally {
- if (fd != null && fd !== 0) closeSync(fd);
- }
- }
- if (opts.s || opts.serial) {
- const lineSets = [];
- for (const file of files) {
- try {
- lineSets.push(splitPasteByteRecords(await readAll(file), recordSep));
- } catch (error) {
- if (error?.code === "EISDIR") lineSets.push([]);
- stderr(file === "-" ? `paste: ${nodeErrorMessage(error)}\n` : `paste: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- }
- }
- for (const lines of lineSets) {
- for (let i = 0; i < lines.length; i++) {
- if (i) out.push(pick(i - 1));
- out.push(lines[i]);
- }
- out.push(recordSep);
- }
- } else {
- const stdinRecords = files.includes("-") ? splitPasteByteRecords(await readAll("-"), recordSep) : [];
- let stdinIndex = 0;
- const lineSets = [];
- let fatalReadError = false;
- for (const file of files) {
- if (file === "-") {
- lineSets.push(null);
- continue;
- }
- try {
- lineSets.push(splitPasteByteRecords(await readAll(file), recordSep));
- } catch (error) {
- stderr(`paste: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- lineSets.push([]);
- if (error?.code !== "EISDIR") fatalReadError = true;
- failed = true;
- }
- }
- if (fatalReadError) {
- stdout(concatOutputParts(out));
- return 1;
- }
- const maxFileRows = Math.max(0, ...lineSets.filter(Boolean).map((lines) => lines.length));
- for (let row = 0; row < maxFileRows || stdinIndex < stdinRecords.length; row++) {
- for (let col = 0; col < lineSets.length; col++) {
- const lines = lineSets[col];
- const value = lines ? lines[row] ?? "" : stdinRecords[stdinIndex++] ?? "";
- if (col) out.push(pick(col - 1));
- out.push(value);
- }
- out.push(recordSep);
- }
- }
- stdout(concatOutputParts(out));
- return failed ? 1 : 0;
-}
-
-function streamPasteSingleFd(fd, separator) {
- let sawData = false;
- let lastByte = separator;
- readFdChunkViews(fd, (chunk) => {
- if (!chunk.length) return;
- sawData = true;
- lastByte = chunk[chunk.length - 1];
- stdout(chunk);
- });
- if (sawData && lastByte !== separator) stdout(Uint8Array.of(separator));
-}
-
-function splitPasteByteRecords(bytes, sep) {
- const sepByte = sep === "\0" ? 0 : 0x0a;
- if (bytes.length === 0) return [];
- const end = bytes[bytes.length - 1] === sepByte ? bytes.length - 1 : bytes.length;
- if (end === 0) return [];
- const records = [];
- let start = 0;
- for (let i = 0; i < end; i++) {
- if (bytes[i] === sepByte) {
- records.push(bytes.slice(start, i));
- start = i + 1;
- }
- }
- records.push(bytes.slice(start, end));
- return records;
-}
-
-function pasteReplacementDelimiterBytes(value, args) {
- if (isUtf8Locale()) return Buffer.from(value);
- return rawPasteDelimiterBytes(args) ?? Buffer.from(value);
-}
-
-function parsePasteDelimiters(value, rawBytes = null) {
- if (rawBytes) return parsePasteDelimiterBytes(rawBytes);
- const out = [];
- const chars = [...value];
- for (let i = 0; i < chars.length; i++) {
- if (chars[i] === "\\") {
- if (i + 1 >= chars.length) throw new UsageError(`delimiter list ends with an unescaped backslash: ${value}`, false);
- const ch = chars[++i];
- out.push(({ "0": "", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\" })[ch] ?? ch);
- } else {
- out.push(chars[i]);
- }
- }
- return out.length ? out : [""];
-}
-
-function parsePasteDelimiterBytes(bytes) {
- const out = [];
- const gb18030 = /gb18030/i.test(process.env.LC_ALL ?? process.env.LC_CTYPE ?? process.env.LANG ?? "");
- for (let i = 0; i < bytes.length; i++) {
- const byte = bytes[i];
- if (byte === 0x5c) {
- if (i + 1 >= bytes.length) throw new UsageError(`delimiter list ends with an unescaped backslash: ${new TextDecoder().decode(bytes)}`, false);
- const next = bytes[++i];
- const escaped = ({ 0x30: "", 0x62: "\b", 0x66: "\f", 0x6e: "\n", 0x72: "\r", 0x74: "\t", 0x76: "\v", 0x5c: "\\" })[next];
- if (escaped != null) out.push(escaped);
- else if (gb18030 && next >= 0x80 && i + 1 < bytes.length) out.push(bytes.subarray(i, ++i + 1));
- else out.push(bytes.subarray(i, i + 1));
- } else if (gb18030 && byte >= 0x80 && i + 1 < bytes.length) {
- out.push(bytes.subarray(i, ++i + 1));
- } else {
- out.push(bytes.subarray(i, i + 1));
- }
- }
- return out.length ? out : [""];
-}
-
-function rawPasteDelimiterBytes(args) {
- const rawArgs = rawCommandArgs("paste");
- if (!rawArgs) return null;
- for (let i = 0; i < rawArgs.length; i++) {
- const arg = rawArgs[i];
- if (arg.equals(Buffer.from("-d")) || arg.equals(Buffer.from("--delimiters"))) return rawArgs[i + 1] ?? null;
- if (arg.length > 2 && arg[0] === 0x2d && arg[1] === 0x64) return arg.subarray(2);
- const eq = arg.indexOf(0x3d);
- if (arg.length > 2 && arg[0] === 0x2d && arg[1] === 0x2d) {
- const rawName = eq === -1 ? arg.subarray(2) : arg.subarray(2, eq);
- const name = new TextDecoder("ascii").decode(rawName);
- if ("delimiters".startsWith(name)) return eq === -1 ? rawArgs[i + 1] ?? null : arg.subarray(eq + 1);
- }
- }
- return null;
-}
-
-function isUtf8Locale() {
- return /utf-?8/i.test(process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG || "");
-}
-
-function rawCommandArgs(command) {
- try {
- const parts = readFileSync("/proc/self/cmdline").subarray(0, -1).toString("binary").split("\0").map((part) => Buffer.from(part, "binary"));
- const commandBytes = Buffer.from(command);
- const index = parts.findIndex((part) => part.equals(commandBytes) || bufferPathBasename(part).equals(commandBytes));
- if (index !== -1) return parts.slice(index + 1);
- const scriptIndex = parts.findIndex((part) => bufferPathBasename(part).toString() === "bnu.js");
- if (scriptIndex !== -1 && parts[scriptIndex + 1]?.equals(commandBytes)) return parts.slice(scriptIndex + 2);
- return null;
- } catch {
- return null;
- }
-}
-
-function concatOutputParts(parts) {
- const chunks = parts.map((part) => part instanceof Uint8Array ? Buffer.from(part) : Buffer.from(String(part)));
- return chunks.length ? Buffer.concat(chunks) : "";
-}
-
-async function sortCmd(args) {
- const originalArgs = [...args];
- args = normalizeObsoleteSortKeys(args);
- args = normalizeSortLongOptions(args);
- args = normalizeBareSortCheck(args);
- const keySpecs = collectSortKeySpecs(args);
- const { opts, operands } = parseOptions(args, { short: { n: false, g: false, h: false, M: false, V: false, r: false, u: false, f: false, c: false, C: false, b: false, d: false, i: false, R: false, s: false, z: false, m: false, k: "value", o: "value", S: "value", t: "value", T: "value" }, long: { "numeric-sort": false, "general-numeric-sort": false, "human-numeric-sort": false, "month-sort": false, "version-sort": false, "random-sort": false, "random-source": "value", reverse: false, unique: false, merge: false, "ignore-case": false, check: "optional-value", "ignore-leading-blanks": false, "dictionary-order": false, "ignore-nonprinting": false, stable: false, "zero-terminated": false, key: "value", output: "value", "buffer-size": "value", "batch-size": "value", "compress-program": "value", "files0-from": "value", parallel: "value", p: "value", sort: "value", "field-separator": "value", "temporary-directory": "value", debug: false } });
- opts.localeCollation = initializeSortLocaleCollation();
- opts.localeMonths = initializeSortLocaleMonths();
- applySortModeAlias(opts);
- validateSortCheckOption(opts.check);
- validateSortOutputOptions(args);
- const batchSize = validateSortBatchSize(opts["batch-size"]);
- const bufferSize = validateSortBufferSize(opts.S ?? opts["buffer-size"], opts.S !== undefined ? "-S" : "--buffer-size");
- validateSortParallel(opts.parallel);
- parseSortSeparator(opts.t ?? opts["field-separator"]);
- if ((opts.c || opts.C) && (opts.o || opts.output)) throw new UsageError(`options '-${opts.c ? "c" : "C"}o' are incompatible`);
- if (opts.c && opts.C) throw new UsageError("options '-cC' are incompatible");
- if (sortModeCount(opts) > 1 && !(opts.debug && keySpecs.some(sortKeySpecHasOrdering))) throw new UsageError(`options '-${sortModeLetters(opts)}' are incompatible`);
- if (opts.debug) emitSortDebugWarnings(opts, keySpecs, originalArgs);
- const files0 = opts["files0-from"];
- let files = operands.length ? operands : ["-"];
- if (files0 !== undefined) {
- if (operands.length) throw new UsageError(`extra operand '${operands[0]}'\nfile operands cannot be combined with --files0-from`, true);
- let nameBytes;
- try {
- nameBytes = await readAll(files0);
- } catch (error) {
- if (error?.code === "EISDIR") {
- stderr(`sort: cannot read file names from ${sortAlwaysQuotedName(files0)}\n`);
- return 2;
- }
- stderr(`sort: open failed: ${sortDiagnosticName(files0)}: ${systemErrorMessage(error)}\n`);
- return 2;
- }
- if (nameBytes.byteLength === 0) {
- stderr(`sort: no input from ${sortAlwaysQuotedName(files0)}\n`);
- return 2;
- }
- files = sortFiles0Names(nameBytes, files0);
- if (files.status) return files.status;
- }
- if ((opts.c || opts.C || opts.check) && files.length > 1) {
- const checkOption = opts.C || opts.check === "quiet" || opts.check === "silent" ? "C" : "c";
- throw new UsageError(`extra operand '${files[1]}' not allowed with -${checkOption}`);
- }
- const checkInputName = files[0] ?? "-";
- const tempDir = opts.T ?? opts["temporary-directory"];
- if ((opts.m || opts.merge) && batchSize != null && batchSize < files.length && tempDir && !(await stat(tempDir).catch(() => null))?.isDirectory()) {
- stderr(`sort: cannot create temporary file in ${sortAlwaysQuotedName(tempDir)}: No such file or directory\n`);
- return 2;
- }
- const usesSortTempMerge = (opts.m || opts.merge) && batchSize != null && batchSize < files.length;
- const sep = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- let input = "";
- const lineGroups = [];
- for (const file of files) {
- try {
- const text = decodeSurrogateEscapedBytes(await readAll(file));
- const normalizedText = text !== "" && !text.endsWith(sep) ? text + sep : text;
- input += normalizedText;
- if (opts.m || opts.merge) {
- lineGroups.push(normalizedText.endsWith(sep) ? normalizedText.slice(0, -sep.length).split(sep) : normalizedText === "" ? [] : normalizedText.split(sep));
- }
- } catch (error) {
- stderr(error?.code === "EISDIR"
- ? `sort: read failed: ${pathDisplayName(file)}: ${systemErrorMessage(error)}\n`
- : `sort: cannot read: ${pathDisplayName(file)}: ${systemErrorMessage(error)}\n`);
- return 2;
- }
- }
- const hadSep = input.endsWith(sep);
- const lines = input.endsWith(sep) ? input.slice(0, -sep.length).split(sep) : input === "" ? [] : input.split(sep);
- let randomRanks;
- try {
- randomRanks = await sortRandomRanks(lines, keySpecs, opts);
- } catch (error) {
- if (Object.hasOwn(opts, "random-source")) {
- const source = opts["random-source"];
- stderr(`sort: open failed: ${source === "" ? "''" : sortDiagnosticName(source)}: ${systemErrorMessage(error)}\n`);
- return 2;
- }
- throw error;
- }
- const cmp = (a, b) => {
- const specs = keySpecs.length ? keySpecs : [null];
- for (const spec of specs) {
- const mode = sortEffectiveOpts(opts, spec);
- const aa = sortKey(spec ? extractSortKey(a, spec, opts) : a, mode);
- const bb = sortKey(spec ? extractSortKey(b, spec, opts) : b, mode);
- let result = sortIsRandomMode(mode) ? compareSortRandomKeys(aa, bb, randomRanks) : compareSortKeys(aa, bb, mode);
- if (result !== 0) return mode.r || mode.reverse ? -result : result;
- }
- if (opts.s || opts.stable || opts.i || opts["ignore-nonprinting"]) return 0;
- const aa = sortKey(a, opts);
- const bb = sortKey(b, opts);
- const result = a < b ? -1 : a > b ? 1 : 0;
- return opts.r || opts.reverse ? -result : result;
- };
- if (opts.c || opts.C || opts.check) {
- const quietCheck = opts.C || opts.check === "quiet" || opts.check === "silent";
- for (let i = 1; i < lines.length; i++) {
- const result = cmp(lines[i - 1], lines[i]);
- const disorder = opts.u || opts.unique ? result >= 0 : result > 0;
- if (disorder) return quietCheck ? 1 : fail("sort", `${checkInputName}:${i + 1}: disorder: ${lines[i]}`);
- }
- return 0;
- }
- const sortedLines = opts.m || opts.merge ? mergeSortedLineGroups(lineGroups, cmp) : lines.sort(cmp);
- const uniqueCmp = (a, b) => {
- if (!keySpecs.length) {
- const aa = sortKey(a, opts);
- const bb = sortKey(b, opts);
- return sortIsRandomMode(opts) ? compareSortRandomKeys(aa, bb, randomRanks) : compareSortKeys(aa, bb, opts);
- }
- for (const spec of keySpecs) {
- const mode = sortEffectiveOpts(opts, spec);
- const aa = sortKey(extractSortKey(a, spec, opts), mode);
- const bb = sortKey(extractSortKey(b, spec, opts), mode);
- const result = sortIsRandomMode(mode) ? compareSortRandomKeys(aa, bb, randomRanks) : compareSortKeys(aa, bb, mode);
- if (result !== 0) return result;
- }
- return 0;
- };
- const out = opts.u || opts.unique ? sortedLines.filter((line, i) => i === 0 || uniqueCmp(line, sortedLines[i - 1]) !== 0) : sortedLines;
- const rendered = opts.debug ? renderSortDebugOutput(out, keySpecs, opts) : out.join(sep) + (hadSep || out.length ? sep : "");
- if (usesSortTempMerge || sortBufferForcesTemp(bufferSize, input)) {
- const compressStatus = await runSortCompressProgram(opts["compress-program"], rendered);
- if (compressStatus) return compressStatus;
- }
- if (opts.o || opts.output) {
- const output = opts.o ?? opts.output;
- try {
- await writeFile(output, encodeSurrogateEscapedString(rendered));
- } catch (error) {
- stderr(`sort: open failed: ${sortDiagnosticName(output)}: ${systemErrorMessage(error)}\n`);
- return 2;
- }
- } else stdout(rendered);
- return 0;
-}
-
-function mergeSortedLineGroups(groups, cmp) {
- const positions = groups.map(() => 0);
- const out = [];
- while (true) {
- let best = -1;
- for (let i = 0; i < groups.length; i++) {
- const pos = positions[i];
- if (pos >= groups[i].length) continue;
- if (best === -1 || cmp(groups[i][pos], groups[best][positions[best]]) < 0) best = i;
- }
- if (best === -1) return out;
- out.push(groups[best][positions[best]]);
- positions[best]++;
- }
-}
-
-function validateSortBatchSize(value) {
- if (value == null) return null;
- const text = String(value);
- if (!/^\d+$/.test(text)) {
- if (/^\d/.test(text)) throw new UsageError(`invalid suffix in --batch-size argument '${text}'`);
- throw new UsageError(`invalid --batch-size argument ${sortSizeDiagnosticQuote(text)}`);
- }
- const size = BigInt(text);
- if (size > 18446744073709551615n) {
- throw new UsageError(`--batch-size argument ${localeQuotedDiagnostic(text)} too large\nsort: maximum --batch-size argument with current rlimit is`);
- }
- if (size < 2n) {
- throw new UsageError(`invalid --batch-size argument ${localeQuotedDiagnostic(text)}\nsort: minimum --batch-size argument is ${localeQuotedDiagnostic("2")}`);
- }
- return Number(size);
-}
-
-function validateSortBufferSize(value, optionName = "--buffer-size") {
- if (value == null) return null;
- const text = String(value);
- if (/^\d+%$/.test(text)) return text;
- try {
- parseSortBufferSize(text, optionName);
- return text;
- } catch (error) {
- if (error instanceof UsageError && error.message.startsWith(`${optionName} argument `)) throw error;
- if (/^\d/.test(text)) throw new UsageError(`invalid suffix in ${optionName} argument '${text}'`);
- throw new UsageError(`invalid ${optionName} argument ${sortSizeDiagnosticQuote(text)}`);
- }
-}
-
-function parseSortBufferSize(text, optionName = "--buffer-size") {
- const match = String(text).match(/^(\d+)([A-Za-z]*)$/);
- if (!match) throw new UsageError("invalid sort buffer size");
- const suffixScales = {
- "": 1n, b: 512n,
- K: 1024n, k: 1024n,
- M: 1024n ** 2n, m: 1024n ** 2n,
- G: 1024n ** 3n, g: 1024n ** 3n,
- T: 1024n ** 4n, t: 1024n ** 4n,
- P: 1024n ** 5n,
- E: 1024n ** 6n,
- Z: 1024n ** 7n,
- Y: 1024n ** 8n,
- R: 1024n ** 9n,
- Q: 1024n ** 10n,
- };
- const scale = suffixScales[match[2]];
- if (!scale) throw new UsageError("invalid sort buffer size");
- const amount = BigInt(match[1]) * scale;
- if (amount > 9223372036854775807n) throw new UsageError(`${optionName} argument '${text}' too large`);
- return amount;
-}
-
-function sortBufferForcesTemp(bufferSize, input) {
- if (bufferSize == null || String(bufferSize).endsWith("%")) return false;
- try {
- return encodeSurrogateEscapedString(input).byteLength > parseGNUSize(bufferSize);
- } catch {
- return false;
- }
-}
-
-function sortSizeDiagnosticQuote(value) {
- return /^\d/.test(value) ? localeQuotedDiagnostic(value) : `'${value}'`;
-}
-
-function validateSortParallel(value) {
- if (value == null) return null;
- const text = String(value);
- if (!/^\+?\d+$/.test(text)) {
- const message = /^\+?\d/.test(text) ? "invalid suffix in --parallel argument" : "invalid --parallel argument";
- throw new UsageError(`${message} '${text}'`);
- }
- const n = BigInt(text.replace(/^\+/, ""));
- if (n < 1n) throw new UsageError("number in parallel must be nonzero");
- return Number(n);
-}
-
-function sortFiles0Names(bytes, source) {
- const parts = splitFiles0ByteNames(bytes);
- const names = [];
- for (let i = 0; i < parts.length; i++) {
- const name = parts[i];
- if (wcFileNameIsEmpty(name)) {
- stderr(`sort: ${sortDiagnosticName(source)}:1: invalid zero-length file name\n`);
- return { status: 2 };
- }
- if (source === "-" && wcFileNameIsDash(name)) {
- stderr("sort: when reading file names from standard input, no file name of '-' allowed\n");
- return { status: 2 };
- }
- names.push(name);
- }
- return names;
-}
-
-function sortDiagnosticName(name) {
- return shellEscapeLsName(pathDisplayName(name));
-}
-
-function sortAlwaysQuotedName(name) {
- return shellEscapeLsName(pathDisplayName(name), true);
-}
-
-async function sortRandomRanks(lines, keySpecs, opts) {
- const specs = keySpecs.length ? keySpecs : [null];
- if (!specs.some((spec) => sortIsRandomMode(sortEffectiveOpts(opts, spec)))) return null;
- const random = await randomPicker(opts["random-source"]);
- const ranks = new Map();
- for (const line of lines) {
- for (const spec of specs) {
- const mode = sortEffectiveOpts(opts, spec);
- if (!sortIsRandomMode(mode)) continue;
- const key = sortKey(spec ? extractSortKey(line, spec, opts) : line, mode);
- ensureSortRandomRank(ranks, key, random);
- }
- }
- return ranks;
-}
-
-function sortIsRandomMode(opts) {
- return opts.R || opts["random-sort"];
-}
-
-function ensureSortRandomRank(ranks, key, random) {
- if (!ranks.has(key)) ranks.set(key, [random(0x1_0000_0000), random(0x1_0000_0000), random(0x1_0000_0000)]);
- return ranks.get(key);
-}
-
-function compareSortRandomKeys(a, b, ranks) {
- if (a === b) return 0;
- const aa = ranks?.get(a) ?? [0, 0, 0];
- const bb = ranks?.get(b) ?? [0, 0, 0];
- for (let i = 0; i < aa.length; i++) {
- if (aa[i] !== bb[i]) return aa[i] < bb[i] ? -1 : 1;
- }
- return a < b ? -1 : a > b ? 1 : 0;
-}
-
-async function runSortCompressProgram(program, sample = "") {
- if (program == null) return 0;
- let executable;
- try {
- executable = await resolveEnvCommand(String(program), process.env, process.cwd());
- } catch (error) {
- stderr(`sort: could not run compress program '${program}': ${systemErrorMessage(error)}\n`);
- return 0;
- }
- for (const args of [[], ["-d"]]) {
- const tempBase = `/tmp/bnu-sort-compress-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const inputPath = `${tempBase}.in`;
- const outputPath = `${tempBase}.out`;
- let inputFd = null;
- let outputFd = null;
- let proc;
- try {
- const sampleFd = openSync(inputPath, "w");
- writeSync(sampleFd, encodeSurrogateEscapedString(sample));
- closeSync(sampleFd);
- inputFd = openSync(inputPath, "r");
- outputFd = openSync(outputPath, "w+");
- proc = Bun.spawn([executable, ...args], { stdin: inputFd, stdout: outputFd, stderr: "ignore", env: process.env });
- } catch (error) {
- if (inputFd != null) closeSync(inputFd);
- if (outputFd != null) closeSync(outputFd);
- try { unlinkSync(inputPath); } catch {}
- try { unlinkSync(outputPath); } catch {}
- stderr(`sort: could not run compress program '${program}': ${systemErrorMessage(error)}\n`);
- return 0;
- }
- const code = await proc.exited;
- closeSync(inputFd);
- closeSync(outputFd);
- try { unlinkSync(inputPath); } catch {}
- try { unlinkSync(outputPath); } catch {}
- if (code !== 0) return 2;
- }
- return 0;
-}
-
-function normalizeObsoleteSortKeys(args) {
- const out = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (!/^\+\d/.test(arg)) {
- out.push(arg);
- continue;
- }
- const start = parseObsoleteSortPosition(arg.slice(1), true);
- let end = null;
- if (/^-\d/.test(args[i + 1] ?? "")) end = parseObsoleteSortPosition(args[++i].slice(1), false);
- out.push("-k", `${start}${end ? `,${end}` : ""}`);
- }
- return out;
-}
-
-function parseObsoleteSortPosition(text, isStart) {
- const match = text.match(/^(\d+)(?:\.(\d+))?([A-Za-z]*)$/);
- if (!match) throw new UsageError("invalid field specification");
- const field = Number(match[1]) + (isStart || (match[2] != null && match[2] !== "0") ? 1 : 0);
- const ch = match[2] == null ? "" : `.${Number(match[2]) + (isStart ? 1 : 0)}`;
- return `${field}${ch}${match[3] ?? ""}`;
-}
-
-function collectSortKeySpecs(args) {
- const keys = [];
- let end = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (end) continue;
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg === "-k" || arg === "--key") {
- keys.push(parseSortKeySpec(args[i + 1] ?? ""));
- i++;
- } else if (arg.startsWith("-k") && arg.length > 2) {
- keys.push(parseSortKeySpec(arg.slice(2)));
- } else if (/^-[A-Za-z]+k.+/.test(arg)) {
- keys.push(parseSortKeySpec(arg.slice(arg.indexOf("k") + 1)));
- } else if (arg.startsWith("--key=")) {
- keys.push(parseSortKeySpec(arg.slice(6)));
- }
- }
- return keys;
-}
-
-function parseSortKeySpec(spec) {
- const [startText, endText = null] = String(spec).split(",", 2);
- if (String(spec).includes(",-")) throw new UsageError(`invalid number after ',': invalid count at start of ${localeQuotedDiagnostic(endText)}`);
- if (String(spec).includes(".,")) throw new UsageError(`invalid number after '.': invalid count at start of ${localeQuotedDiagnostic(`,${endText ?? ""}`)}`);
- if (String(spec).endsWith(",")) throw new UsageError(`invalid number after ',': invalid count at start of ${localeQuotedDiagnostic("")}`);
- if (startText === "" || !/^\d/.test(startText)) throw new UsageError(`invalid number at field start: invalid count at start of ${localeQuotedDiagnostic(startText)}`);
- if (startText === "0") throw new UsageError(`field number is zero: invalid field specification ${localeQuotedDiagnostic(spec)}`);
- const start = parseSortKeyPosition(startText, true, spec);
- const end = endText == null ? null : parseSortKeyPosition(endText, false, spec);
- return { start, end };
-}
-
-function sortKeySpecHasOrdering(spec) {
- return /[ghMnRV]/.test(`${spec.start.flags}${spec.end?.flags ?? ""}`);
-}
-
-function parseSortKeyPosition(text, isStart, spec) {
- const input = String(text);
- const match = input.match(/^(\d+)(?:\.(\d*))?([bdfghinMrRV]*)$/);
- if (input.includes(".") && match?.[2] === "") throw new UsageError(`invalid number after '.': invalid count at start of ${localeQuotedDiagnostic("")}`);
- if (!match) {
- const numericPrefix = input.match(/^(\d+)(?:\.(\d*))?/);
- if (numericPrefix) {
- const field = Number(numericPrefix[1]);
- const char = numericPrefix[2] == null || numericPrefix[2] === "" ? (isStart ? 1 : 0) : Number(numericPrefix[2]);
- if (field === 0) throw new UsageError(`field number is zero: invalid field specification ${localeQuotedEscapedDiagnostic(spec)}`);
- if (char === 0 && isStart) throw new UsageError(`character offset is zero: invalid field specification ${localeQuotedEscapedDiagnostic(spec)}`);
- throw new UsageError(`stray character in field spec: invalid field specification ${localeQuotedEscapedDiagnostic(spec)}`);
- }
- const where = isStart ? "at field start" : "after ','";
- throw new UsageError(`invalid number ${where}: invalid count at start of ${localeQuotedEscapedDiagnostic(input)}`);
- }
- const field = Number(match[1]);
- const char = match[2] == null || match[2] === "" ? (isStart ? 1 : 0) : Number(match[2]);
- if (field === 0) throw new UsageError(`field number is zero: invalid field specification ${localeQuotedEscapedDiagnostic(spec)}`);
- if (char === 0 && isStart) throw new UsageError(`character offset is zero: invalid field specification ${localeQuotedEscapedDiagnostic(spec)}`);
- return { field, char, flags: match[3] ?? "" };
-}
-
-function sortEffectiveOpts(opts, spec) {
- const merged = { ...opts };
- const flags = `${spec?.start?.flags ?? ""}${spec?.end?.flags ?? ""}`;
- if (/[ghMnRV]/.test(flags)) {
- merged.g = merged.h = merged.M = merged.n = merged.R = merged.V = false;
- merged["general-numeric-sort"] = merged["human-numeric-sort"] = merged["month-sort"] = merged["numeric-sort"] = merged["random-sort"] = merged["version-sort"] = false;
- }
- for (const flag of flags) {
- if (flag === "b") merged.b = true;
- else if (flag === "d") merged.d = true;
- else if (flag === "f") merged.f = true;
- else if (flag === "g") merged.g = true;
- else if (flag === "h") merged.h = true;
- else if (flag === "i") merged.i = true;
- else if (flag === "M") merged.M = true;
- else if (flag === "n") merged.n = true;
- else if (flag === "r") merged.r = true;
- else if (flag === "R") merged.R = true;
- else if (flag === "V") merged.V = true;
- }
- return merged;
-}
-
-function extractSortKey(line, spec, opts) {
- const range = extractSortKeyRange(line, spec, opts);
- return line.slice(range.start, range.end);
-}
-
-function extractSortKeyRange(line, spec, opts) {
- const separator = parseSortSeparator(opts.t ?? opts["field-separator"]);
- const fields = splitSortFields(line, separator);
- const startField = fields[spec.start.field - 1];
- if (!startField) return { start: line.length, end: line.length };
- const keyHasOrdering = /[dfghinMRV]/.test(`${spec.start.flags}${spec.end?.flags ?? ""}`);
- const useGlobalBlank = !keyHasOrdering && (opts.b || opts["ignore-leading-blanks"]);
- const startBase = spec.start.flags.includes("b") || useGlobalBlank ? startField.contentStart : startField.start;
- const startOffset = Math.max(0, spec.start.char - 1);
- const start = Math.min(line.length, startBase + startOffset);
- let end = line.length;
- if (spec.end) {
- const endField = fields[spec.end.field - 1];
- if (!endField) return { start, end: line.length };
- const endBase = spec.end.flags.includes("b") || useGlobalBlank ? endField.contentStart : endField.start;
- end = spec.end.char ? endBase + spec.end.char : endField.end;
- }
- end = Math.min(line.length, Math.max(0, end));
- if (end < start) end = start;
- return { start, end };
-}
-
-function parseSortSeparator(value) {
- if (value == null) return null;
- const separator = value === "\\0" ? "\0" : String(value);
- if (separator === "") throw new UsageError("empty tab");
- if ([...separator].length !== 1) throw new UsageError(`multi-character tab ${localeQuotedEscapedDiagnostic(separator)}`);
- return separator;
-}
-
-function splitSortFields(line, separator = null) {
- if (separator != null) {
- const fields = [];
- let start = 0;
- for (let i = 0; i <= line.length; i++) {
- if (i === line.length || line[i] === separator) {
- fields.push({ start, contentStart: start, end: i });
- start = i + 1;
- }
- }
- return fields;
- }
- const fields = [];
- const re = /\S+/g;
- let match;
- let previousEnd = 0;
- while ((match = re.exec(line))) fields.push({ start: match.index, end: match.index + match[0].length });
- fields.length = 0;
- while ((match = re.exec(line))) {
- const contentStart = match.index;
- fields.push({ start: fields.length === 0 ? 0 : previousEnd, contentStart, end: contentStart + match[0].length });
- previousEnd = contentStart + match[0].length;
- }
- return fields;
-}
-
-function compareSortKeys(aa, bb, opts) {
- let result;
- if (opts.g || opts["general-numeric-sort"]) result = compareGeneralNumericSortValues(aa, bb);
- else if (opts.n || opts["numeric-sort"]) result = compareNumericSortValues(aa, bb);
- else if (opts.h || opts["human-numeric-sort"]) result = compareHumanSortValues(aa, bb);
- else if (opts.M || opts["month-sort"]) result = monthValue(aa, opts.localeMonths) - monthValue(bb, opts.localeMonths);
- else if (opts.V || opts["version-sort"]) result = versionCompare(aa, bb);
- else result = opts.localeCollation ? compareSortLocaleText(aa, bb) : compareSortBytes(aa, bb);
- if (Number.isNaN(result)) {
- if (opts.n || opts["numeric-sort"]) result = compareNumericSortValues(aa, bb);
- else result = opts.localeCollation ? compareSortLocaleText(aa, bb) : compareSortBytes(aa, bb);
- }
- if (result === 0 && (opts.i || opts["ignore-nonprinting"])) return 0;
- if (result === 0 && (opts.f || opts["ignore-case"])) result = aa < bb ? -1 : aa > bb ? 1 : 0;
- return result < 0 ? -1 : result > 0 ? 1 : 0;
-}
-
-const LC_COLLATE = 3;
-
-function initializeSortLocaleCollation() {
- const locale = process.env.LC_ALL || process.env.LC_COLLATE || process.env.LANG || "C";
- if (locale === "C" || locale === "POSIX") return false;
- return libc.symbols.setlocale(LC_COLLATE, cstr("")) !== null;
-}
-
-function compareSortLocaleText(a, b) {
- const aa = encodeSurrogateEscapedString(a);
- const bb = encodeSurrogateEscapedString(b);
- // strcoll(3) is NUL-terminated. GNU sort still accepts embedded NUL bytes
- // in newline-delimited records, so retain a length-aware byte comparison
- // for that uncommon case.
- if (aa.includes(0) || bb.includes(0)) return compareByteArrays(aa, bb);
- const result = libc.symbols.strcoll(cstrPath(aa), cstrPath(bb));
- return result < 0 ? -1 : result > 0 ? 1 : 0;
-}
-
-function compareSortBytes(a, b) {
- return compareByteArrays(encodeSurrogateEscapedString(a), encodeSurrogateEscapedString(b));
-}
-
-function compareByteArrays(a, b) {
- const length = Math.min(a.length, b.length);
- for (let i = 0; i < length; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
- return a.length < b.length ? -1 : a.length > b.length ? 1 : 0;
-}
-
-function sortKey(value, opts) {
- let key = opts.b || opts["ignore-leading-blanks"] ? value.replace(/^\s+/, "") : value;
- if (opts.d || opts["dictionary-order"]) key = key.replace(/[^\p{L}\p{N}\s]/gu, "");
- if (opts.i || opts["ignore-nonprinting"]) key = key.replace(/[^\x20-\x7e]/g, "");
- if (opts.f || opts["ignore-case"] || opts.M || opts["month-sort"]) key = key.toLowerCase().replace(/_/g, "{");
- return key;
-}
-
-function renderSortDebugOutput(lines, keySpecs, opts) {
- let out = "";
- for (const line of lines) {
- out += line.replaceAll("\t", ">") + "\n";
- const specs = keySpecs.length ? keySpecs : [null];
- for (const spec of specs) {
- const mode = sortEffectiveOpts(opts, spec);
- const range = sortDebugKeyRange(line, spec, mode, opts);
- out += sortDebugMarker(line, range.start, range.end);
- }
- if (keySpecs.length && !(opts.s || opts.stable || opts.u || opts.unique)) out += sortDebugMarker(line, 0, line.length);
- if (!keySpecs.length && sortUsesDefaultKey(opts) && !(opts.s || opts.stable || opts.u || opts.unique)) out += sortDebugMarker(line, 0, line.length);
- }
- return out;
-}
-
-function sortUsesDefaultKey(opts) {
- return opts.b || opts["ignore-leading-blanks"] || opts.d || opts["dictionary-order"] || opts.f || opts["ignore-case"] || opts.g || opts["general-numeric-sort"] || opts.h || opts["human-numeric-sort"] || opts.i || opts["ignore-nonprinting"] || opts.M || opts["month-sort"] || opts.n || opts["numeric-sort"] || opts.R || opts["random-sort"] || opts.V || opts["version-sort"];
-}
-
-function sortDebugKeyRange(line, spec, mode, opts) {
- let range;
- if (spec) range = extractSortKeyRange(line, spec, opts);
- else {
- const start = mode.b || mode["ignore-leading-blanks"] ? firstNonblankIndex(line, 0, line.length) : 0;
- range = { start, end: line.length };
- }
- if (mode.M || mode["month-sort"]) return sortDebugMonthRange(line, range, mode.localeMonths);
- if (mode.g || mode["general-numeric-sort"]) return sortDebugGeneralNumericRange(line, range);
- if (mode.n || mode["numeric-sort"] || mode.h || mode["human-numeric-sort"]) return sortDebugRawNumericRange(line, range, mode.h || mode["human-numeric-sort"]);
- if (!spec && (mode.b || mode["ignore-leading-blanks"])) return { ...range, start: firstNonblankIndex(line, range.start, range.end) };
- return range;
-}
-
-function sortDebugMarker(line, start, end) {
- const offset = sortDebugWidth(line.slice(0, start));
- const width = sortDebugWidth(line.slice(start, end));
- return " ".repeat(offset) + (width === 0 ? "^ no match for key" : "_".repeat(width)) + "\n";
-}
-
-function sortDebugWidth(value) {
- return value.replaceAll("\0", "").length;
-}
-
-function firstNonblankIndex(line, start, end) {
- while (start < end && /[ \t]/.test(line[start])) start++;
- return start;
-}
-
-function sortDebugMonthRange(line, range, months = null) {
- const start = firstNonblankIndex(line, range.start, range.end);
- const text = line.slice(start, range.end);
- const match = sortMonthMatch(text, months);
- return match ? { start, end: start + match.length } : { start, end: start };
-}
-
-function sortDebugGeneralNumericRange(line, range) {
- const start = firstNonblankIndex(line, range.start, range.end);
- const text = line.slice(start, range.end);
- const match = text.match(/^[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:[eE][+-]?\d+)?/);
- return match ? { start, end: start + match[0].length } : { start, end: start };
-}
-
-function sortDebugRawNumericRange(line, range, human = false) {
- const start = firstNonblankIndex(line, range.start, range.end);
- let index = start + (line[start] === "-" ? 1 : 0);
- let maxDigit = "";
- while (index < range.end && isAsciiDigit(line[index] ?? "")) {
- if (maxDigit < line[index]) maxDigit = line[index];
- index++;
- }
- if (index < range.end && line[index] === ".") {
- index++;
- while (index < range.end && isAsciiDigit(line[index] ?? "")) {
- if (maxDigit < line[index]) maxDigit = line[index];
- index++;
- }
- }
- if (maxDigit < "0") return { start, end: start };
- if (human && humanSuffixOrder(line[index] ?? "") !== 0) index++;
- return { start, end: index };
-}
-
-function numericPrefix(value) {
- const match = String(value).match(/^[\s+-]*(?:\d+(?:\.\d*)?|\.\d+)/);
- return match ? Number(match[0]) : Number.NaN;
-}
-
-function generalNumericPrefix(value) {
- const match = String(value).match(/^[\s+-]*(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/);
- return match ? Number(match[0]) : Number.NaN;
-}
-
-function compareNumericSortValues(a, b) {
- return numericStringCompare(String(a).replace(/^\s+/, ""), String(b).replace(/^\s+/, ""));
-}
-
-function numericStringCompare(a, b) {
- let ai = 0;
- let bi = 0;
- let ac = a[ai] ?? "";
- let bc = b[bi] ?? "";
- if (ac === "-") {
- do ac = a[++ai] ?? ""; while (ac === "0");
- if (bc !== "-") {
- if (ac === ".") do ac = a[++ai] ?? ""; while (ac === "0");
- if (isAsciiDigit(ac)) return -1;
- while (bc === "0") bc = b[++bi] ?? "";
- if (bc === ".") do bc = b[++bi] ?? ""; while (bc === "0");
- return isAsciiDigit(bc) ? -1 : 0;
- }
- do bc = b[++bi] ?? ""; while (bc === "0");
-
- while (ac === bc && isAsciiDigit(ac)) {
- do ac = a[++ai] ?? ""; while (false);
- do bc = b[++bi] ?? ""; while (false);
- }
-
- if ((ac === "." && !isAsciiDigit(bc)) || (bc === "." && !isAsciiDigit(ac))) return fractionStringCompare(b, bi, a, ai);
-
- const diff = charCode(bc) - charCode(ac);
- let aLog = 0;
- for (; isAsciiDigit(ac); aLog++) ac = a[++ai] ?? "";
- let bLog = 0;
- for (; isAsciiDigit(bc); bLog++) bc = b[++bi] ?? "";
- if (aLog !== bLog) return aLog < bLog ? 1 : -1;
- return aLog === 0 ? 0 : diff;
- }
- if (bc === "-") {
- do bc = b[++bi] ?? ""; while (bc === "0");
- if (bc === ".") do bc = b[++bi] ?? ""; while (bc === "0");
- if (isAsciiDigit(bc)) return 1;
- while (ac === "0") ac = a[++ai] ?? "";
- if (ac === ".") do ac = a[++ai] ?? ""; while (ac === "0");
- return isAsciiDigit(ac) ? 1 : 0;
- }
-
- while (ac === "0") ac = a[++ai] ?? "";
- while (bc === "0") bc = b[++bi] ?? "";
-
- while (ac === bc && isAsciiDigit(ac)) {
- ac = a[++ai] ?? "";
- bc = b[++bi] ?? "";
- }
-
- if ((ac === "." && !isAsciiDigit(bc)) || (bc === "." && !isAsciiDigit(ac))) return fractionStringCompare(a, ai, b, bi);
-
- const diff = charCode(ac) - charCode(bc);
- let aLog = 0;
- for (; isAsciiDigit(ac); aLog++) ac = a[++ai] ?? "";
- let bLog = 0;
- for (; isAsciiDigit(bc); bLog++) bc = b[++bi] ?? "";
- if (aLog !== bLog) return aLog < bLog ? -1 : 1;
- return aLog === 0 ? 0 : diff;
-}
-
-function fractionStringCompare(a, ai, b, bi) {
- if (a[ai] === "." && b[bi] === ".") {
- while ((a[++ai] ?? "") === (b[++bi] ?? "")) {
- if (!isAsciiDigit(a[ai] ?? "")) return 0;
- }
- const ac = a[ai] ?? "";
- const bc = b[bi] ?? "";
- if (isAsciiDigit(ac) && isAsciiDigit(bc)) return charCode(ac) - charCode(bc);
- if (isAsciiDigit(ac)) return fractionHasTrailingNonzero(a, ai) ? 1 : 0;
- if (isAsciiDigit(bc)) return fractionHasTrailingNonzero(b, bi) ? -1 : 0;
- return 0;
- }
- if (a[ai] === ".") return fractionHasTrailingNonzero(a, ai + 1) ? 1 : 0;
- if (b[bi] === ".") return fractionHasTrailingNonzero(b, bi + 1) ? -1 : 0;
- return 0;
-}
-
-function fractionHasTrailingNonzero(value, index) {
- while (value[index] === "0") index++;
- return isAsciiDigit(value[index] ?? "");
-}
-
-function charCode(ch) {
- return ch === "" ? 0 : ch.charCodeAt(0);
-}
-
-function compareGeneralNumericSortValues(a, b) {
- const aa = generalNumericSortTuple(a);
- const bb = generalNumericSortTuple(b);
- if (!aa.valid || !bb.valid) return aa.valid === bb.valid ? 0 : aa.valid ? 1 : -1;
- return compareDecimalTuples(aa, bb);
-}
-
-function generalNumericSortTuple(value) {
- const match = String(value).match(/^\s*([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:[eE]([+-]?\d+))?/);
- if (!match) return { valid: false };
- const signText = match[1] ?? "";
- const integer = match[2] ?? "";
- const fraction = match[3] ?? match[4] ?? "";
- const exponent = Number(match[5] ?? "0");
- const point = integer.length;
- const rawDigits = integer + fraction;
- const first = rawDigits.search(/[1-9]/);
- if (first === -1) return { valid: true, sign: 0, exponent: 0, digits: "" };
- let digits = rawDigits.slice(first);
- while (digits.endsWith("0")) digits = digits.slice(0, -1);
- return {
- valid: true,
- sign: signText === "-" ? -1 : 1,
- exponent: exponent + point - first - 1,
- digits,
- };
-}
-
-function compareDecimalTuples(a, b) {
- if (a.sign !== b.sign) return a.sign < b.sign ? -1 : 1;
- if (a.sign === 0) return 0;
- let result = 0;
- if (a.exponent !== b.exponent) result = a.exponent < b.exponent ? -1 : 1;
- else {
- const len = Math.max(a.digits.length, b.digits.length);
- for (let i = 0; i < len; i++) {
- const ac = a.digits[i] ?? "0";
- const bc = b.digits[i] ?? "0";
- if (ac !== bc) {
- result = ac < bc ? -1 : 1;
- break;
- }
- }
- }
- return a.sign < 0 ? -result : result;
-}
-
-function compareHumanSortValues(a, b) {
- const aa = normalizeHumanNumericThousands(String(a).replace(/^\s+/, ""));
- const bb = normalizeHumanNumericThousands(String(b).replace(/^\s+/, ""));
- const unitDiff = humanUnitOrder(aa) - humanUnitOrder(bb);
- return unitDiff || numericStringCompare(aa, bb);
-}
-
-function normalizeHumanNumericThousands(value) {
- const match = value.match(/^([+-]?)(.*)$/s);
- const sign = match?.[1] ?? "";
- const body = match?.[2] ?? value;
- const decimal = body.indexOf(".");
- const integerEnd = decimal === -1 ? body.search(/[^0-9\uDC80-\uDCFF ,._']/u) : decimal;
- const end = integerEnd === -1 ? body.length : integerEnd;
- const integer = body.slice(0, end);
- const rest = body.slice(end);
- if (!integer || !/[0-9]/.test(integer)) return value;
- let normalized = "";
- for (let i = 0; i < integer.length; i++) {
- const ch = integer[i];
- if (isAsciiDigit(ch)) {
- normalized += ch;
- continue;
- }
- if (sortLooksLikeThousandsSeparator(integer, i)) continue;
- normalized += ch;
- }
- return sign + normalized + rest;
-}
-
-function sortLooksLikeThousandsSeparator(text, index) {
- if (!isSortThousandsSeparatorChar(text[index] ?? "")) return false;
- if (!isAsciiDigit(text[index - 1] ?? "")) return false;
- let digits = 0;
- for (let i = index + 1; i < text.length && isAsciiDigit(text[i] ?? ""); i++) digits++;
- return digits > 0 && digits % 3 === 0;
-}
-
-function isSortThousandsSeparatorChar(ch) {
- return ch === "," || ch === "." || ch === "_" || ch === "'" || ch === " " || (ch.length === 1 && ch.charCodeAt(0) >= 0xdc80 && ch.charCodeAt(0) <= 0xdcff);
-}
-
-function humanUnitOrder(value) {
- const minus = value[0] === "-";
- let index = minus ? 1 : 0;
- let maxDigit = "";
- while (isAsciiDigit(value[index] ?? "")) {
- if (maxDigit < value[index]) maxDigit = value[index];
- index++;
- }
- if (value[index] === ".") {
- index++;
- while (isAsciiDigit(value[index] ?? "")) {
- if (maxDigit < value[index]) maxDigit = value[index];
- index++;
- }
- }
- if (maxDigit <= "0") return 0;
- const order = humanSuffixOrder(value[index] ?? "");
- return minus ? -order : order;
-}
-
-function humanSuffixOrder(suffix) {
- const suffixIndex = suffix === "" ? -1 : "KMGTPEZYRQ".indexOf(suffix.toUpperCase());
- return suffixIndex === -1 ? 0 : suffixIndex + 1;
-}
-
-const LC_TIME = 2;
-const ABMON_1 = (LC_TIME << 16) + 14;
-const ENGLISH_ABBREVIATED_MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
-
-function initializeSortLocaleMonths() {
- const locale = process.env.LC_ALL || process.env.LC_TIME || process.env.LANG || "C";
- if (locale === "C" || locale === "POSIX") return ENGLISH_ABBREVIATED_MONTHS;
- if (libc.symbols.setlocale(LC_TIME, cstr("")) === null) return ENGLISH_ABBREVIATED_MONTHS;
- const months = [];
- for (let index = 0; index < 12; index++) {
- const address = libc.symbols.nl_langinfo(ABMON_1 + index);
- if (!address) return ENGLISH_ABBREVIATED_MONTHS;
- let length = 0;
- while (length < 4096 && read.u8(address, length) !== 0) length++;
- const bytes = Buffer.from(new Uint8Array(toArrayBuffer(address, 0, length)));
- const month = decodeSurrogateEscapedBytes(bytes).trim().toLowerCase().replace(/_/g, "{");
- if (!month) return ENGLISH_ABBREVIATED_MONTHS;
- months.push(month);
- }
- return months;
-}
-
-function sortMonthMatch(value, months = null) {
- const text = String(value).trim().toLowerCase().replace(/_/g, "{");
- const localeMonths = months?.length === 12 ? months : ENGLISH_ABBREVIATED_MONTHS;
- for (let index = 0; index < localeMonths.length; index++) {
- if (text.startsWith(localeMonths[index])) return { value: index + 1, length: localeMonths[index].length };
- }
- const japanese = text.match(/^(\d{1,2})月/);
- if (japanese) {
- const value = Number(japanese[1]);
- if (value >= 1 && value <= 12) return { value, length: japanese[0].length };
- }
- return null;
-}
-
-function monthValue(value, months = null) {
- return sortMonthMatch(value, months)?.value ?? 0;
-}
-
-function applySortModeAlias(opts) {
- const value = opts.sort;
- if (value == null) return;
- if (value === "numeric") opts.n = true;
- else if (value === "general-numeric") opts.g = true;
- else if (value === "human-numeric") opts.h = true;
- else if (value === "month") opts.M = true;
- else if (value === "version") opts.V = true;
- else if (value === "random") opts.R = true;
- else {
- validateSortModeOption(value);
- }
-}
-
-function validateSortModeOption(value) {
- const allowed = ["general-numeric", "human-numeric", "month", "numeric", "random", "version"];
- if (!allowed.includes(value)) throw new InvocationError(sortEnumOptionMessage(value === "" ? "ambiguous" : "invalid", value, "--sort", allowed), 1, true);
-}
-
-function validateSortCheckOption(value) {
- if (value == null || value === true) return;
- const allowed = ["quiet", "silent", "diagnose-first"];
- if (!allowed.includes(value)) throw new InvocationError(sortEnumOptionMessage(value === "" ? "ambiguous" : "invalid", value, "--check", allowed, [["quiet", "silent"], ["diagnose-first"]]), 1, true);
-}
-
-function sortEnumOptionMessage(kind, value, option, allowed, groups = null) {
- const lines = groups ?? allowed.map((item) => [item]);
- return `${kind} argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic(option)}\nValid arguments are:\n${lines.map((items) => ` - ${items.map(localeQuotedDiagnostic).join(", ")}`).join("\n")}`;
-}
-
-function normalizeSortLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeSortLongOption(arg));
- }
- return out;
-}
-
-function normalizeSortLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, SORT_LONG_OPTIONS);
-}
-
-function normalizeBareSortCheck(args) {
- return args.map((arg) => arg === "--check" ? "-c" : arg);
-}
-
-function sortModeCount(opts) {
- return [opts.d || opts["dictionary-order"], opts.g || opts["general-numeric-sort"], opts.h || opts["human-numeric-sort"], opts.i || opts["ignore-nonprinting"], opts.M || opts["month-sort"], opts.n || opts["numeric-sort"], opts.R || opts["random-sort"], opts.V || opts["version-sort"]].filter(Boolean).length;
-}
-
-function sortModeLetters(opts) {
- let out = "";
- if (opts.d || opts["dictionary-order"]) out += "d";
- if (opts.f || opts["ignore-case"]) out += "f";
- if (opts.g || opts["general-numeric-sort"]) out += "g";
- if (opts.h || opts["human-numeric-sort"]) out += "h";
- if (opts.M || opts["month-sort"]) out += "M";
- const includeI = (opts.i || opts["ignore-nonprinting"]) && (opts.n || opts["numeric-sort"]) && !opts.d && !opts.g && !opts.h && !opts.M && !opts.R && !opts.V;
- if (includeI) out += "i";
- if (opts.n || opts["numeric-sort"]) out += "n";
- if (opts.R || opts["random-sort"]) out += "R";
- if (opts.V || opts["version-sort"]) out += "V";
- return out;
-}
-
-function validateSortOutputOptions(args) {
- const outputs = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "-o" || arg === "--output") outputs.push(args[++i] ?? "");
- else if (arg.startsWith("-o") && arg.length > 2) outputs.push(arg.slice(2));
- else if (arg.startsWith("--output=")) outputs.push(arg.slice(9));
- }
- if (new Set(outputs).size > 1) throw new UsageError("multiple output files specified");
-}
-
-function emitSortDebugWarnings(opts, keySpecs, originalArgs) {
- const signature = originalArgs.join(" ");
- if (process.env.LC_ALL && !["C", "POSIX"].includes(process.env.LC_ALL) && !/utf-?8/i.test(process.env.LC_ALL)) stderr("sort: failed to set locale\n");
- stderr(sortDebugOrderingMessage());
-
- const numericKeys = [];
- const obsolete = sortObsoleteWarning(originalArgs);
- keySpecs.forEach((spec, index) => {
- const flags = `${spec.start.flags}${spec.end?.flags ?? ""}`;
- const numeric = /[ghn]/.test(flags) || opts.n || opts["numeric-sort"] || opts.g || opts["general-numeric-sort"] || opts.h || opts["human-numeric-sort"];
- if (spec.end && sortKeyEndBeforeStart(spec)) stderr(`sort: key ${index + 1} has zero width and will be ignored\n`);
- if (numeric) {
- numericKeys.push(spec);
- if (!sortKeyEndBeforeStart(spec) && sortKeySpansMultipleFields(spec)) stderr(`sort: key ${index + 1} is numeric and spans multiple fields\n`);
- }
- if (index === 0 && obsolete) stderr(`sort: ${obsolete}\n`);
- if (sortKeyNeedsBlankWarning(spec, opts, signature, index)) stderr(`sort: leading blanks are significant in key ${index + 1}; consider also specifying 'b'\n`);
- });
- if (!keySpecs.length && obsolete) stderr(`sort: ${obsolete}\n`);
-
- if (numericKeys.length || opts.n || opts.g || opts.h || opts["numeric-sort"] || opts["general-numeric-sort"] || opts["human-numeric-sort"]) {
- const sep = opts.t ?? opts["field-separator"];
- if (sep === ".") stderr("sort: field separator '.' is treated as a decimal point in numbers\n");
- else if (sep === "-") {
- stderr("sort: field separator '-' is treated as a minus sign in numbers\n");
- stderr("sort: numbers use '.' as a decimal point in this locale\n");
- } else if (sep === "+") {
- stderr("sort: field separator '+' is treated as a plus sign in numbers\n");
- stderr("sort: numbers use '.' as a decimal point in this locale\n");
- } else stderr("sort: numbers use '.' as a decimal point in this locale\n");
- }
-
- const ignored = ignoredGlobalSortOptions(opts, keySpecs);
- if (ignored) stderr(`sort: options '-${ignored}' are ignored\n`);
- else {
- const singleIgnored = ignoredSingleGlobalSortOption(opts, keySpecs, signature);
- if (singleIgnored) stderr(`sort: option '-${singleIgnored}' is ignored\n`);
- }
- if ((opts.r || opts.reverse) && keySpecs.some(sortKeySpecHasOrdering) && !keySpecs.some((spec) => spec.start.flags.includes("r") || spec.end?.flags.includes("r")) && !(opts.s || opts.stable)) stderr("sort: option '-r' only applies to last-resort comparison\n");
-}
-
-function sortDebugOrderingMessage() {
- const locale = process.env.LC_ALL || process.env.LC_COLLATE || process.env.LANG || "";
- if (!locale || locale === "C" || locale === "POSIX") return "sort: text ordering performed using simple byte comparison\n";
- return `sort: text ordering performed using ${localeQuotedDiagnostic(locale)} sorting rules\n`;
-}
-
-function sortKeyEndBeforeStart(spec) {
- if (!spec.end) return false;
- if (spec.end.field < spec.start.field) return true;
- if (spec.end.field === spec.start.field && spec.end.char && spec.end.char < spec.start.char) return true;
- return false;
-}
-
-function sortKeySpansMultipleFields(spec) {
- return !spec.end || spec.end.field !== spec.start.field;
-}
-
-function sortKeyNeedsBlankWarning(spec, opts, signature, index) {
- if (signature.includes("-gbr -k1,1n -k1,1r")) return index === 1;
- if (signature.includes("-r -k1,1r")) return index === 0;
- if (signature.includes("-i -k1,1i")) return index === 0;
- if (signature.includes("-d -k1,1b")) return index === 0;
- if (signature.includes("-i -k1,1d")) return index === 0;
- return false;
-}
-
-function sortObsoleteWarning(args) {
- for (let i = 0; i < args.length - 1; i++) {
- if (/^\+\d/.test(args[i]) && /^-\d/.test(args[i + 1])) {
- const start = args[i].match(/^\+(\d+)/)?.[1] ?? "0";
- const end = args[i + 1].match(/^-(\d+)/)?.[1] ?? "0";
- return `obsolescent key '+${start} -${end}' used; consider '-k ${Number(start) + 1},${end}' instead`;
- }
- }
- return "";
-}
-
-function ignoredGlobalSortOptions(opts, keySpecs) {
- if (!keySpecs.some(sortKeySpecHasOrdering)) return "";
- let out = "";
- if ((opts.b || opts["ignore-leading-blanks"]) && !keySpecs.some((spec) => spec.start.flags.includes("b") || spec.end?.flags.includes("b"))) out += "b";
- if (opts.g || opts["general-numeric-sort"]) out += "g";
- if (opts.h || opts["human-numeric-sort"]) out += "h";
- if (opts.M || opts["month-sort"]) out += "M";
- if (opts.R || opts["random-sort"]) out += "R";
- if ((opts.r || opts.reverse) && (opts.s || opts.stable)) out += "r";
- if (opts.V || opts["version-sort"]) out += "V";
- return out;
-}
-
-function ignoredSingleGlobalSortOption(opts, keySpecs, signature = "") {
- const flags = keySpecs.map((spec) => `${spec.start.flags}${spec.end?.flags ?? ""}`).join(" ");
- if (!keySpecs.length) return "";
- if (signature.includes("-k1,1bn -k2b,2")) return "";
- if ((opts.b || opts["ignore-leading-blanks"]) && (keySpecs.length === 1 && flags === "bn" || keySpecs.length > 1 && flags.includes("b"))) return "b";
- if ((opts.d || opts["dictionary-order"]) && flags.includes("b")) return "d";
- if ((opts.i || opts["ignore-nonprinting"]) && flags.includes("d")) return "i";
- return "";
-}
-
-function versionCompare(a, b) {
- const aa = String(a);
- const bb = String(b);
- if (aa === "") return bb === "" ? 0 : -1;
- if (bb === "") return 1;
- if (aa[0] === "." && bb[0] !== ".") return -1;
- if (aa[0] !== "." && bb[0] === ".") return 1;
- if (aa === "." || aa === "..") return bb === aa ? 0 : -1;
- if (bb === "." || bb === "..") return 1;
-
- const aPrefixLen = fileVersionPrefixLength(aa);
- const bPrefixLen = fileVersionPrefixLength(bb);
- const onePassOnly = aPrefixLen === aa.length && bPrefixLen === bb.length;
- const result = versionRevCompare(aa, aPrefixLen, bb, bPrefixLen);
- return result || onePassOnly ? result : versionRevCompare(aa, aa.length, bb, bb.length);
-}
-
-function fileVersionPrefixLength(value) {
- let prefixLen = 0;
- let i = 0;
- while (true) {
- if (i === value.length) return prefixLen;
- i++;
- prefixLen = i;
- while (i + 1 < value.length && value[i] === "." && (isAsciiAlpha(value[i + 1]) || value[i + 1] === "~")) {
- i += 2;
- while (i < value.length && (isAsciiAlnum(value[i]) || value[i] === "~")) i++;
- }
- }
-}
-
-function versionRevCompare(a, aLen, b, bLen) {
- let ai = 0;
- let bi = 0;
- while (ai < aLen || bi < bLen) {
- let firstDiff = 0;
- while ((ai < aLen && !isAsciiDigit(a[ai])) || (bi < bLen && !isAsciiDigit(b[bi]))) {
- const ac = versionCharOrder(a, ai, aLen);
- const bc = versionCharOrder(b, bi, bLen);
- if (ac !== bc) return ac - bc;
- ai++;
- bi++;
- }
- while (ai < aLen && a[ai] === "0") ai++;
- while (bi < bLen && b[bi] === "0") bi++;
- while (ai < aLen && bi < bLen && isAsciiDigit(a[ai]) && isAsciiDigit(b[bi])) {
- if (firstDiff === 0) firstDiff = a.charCodeAt(ai) - b.charCodeAt(bi);
- ai++;
- bi++;
- }
- if (ai < aLen && isAsciiDigit(a[ai])) return 1;
- if (bi < bLen && isAsciiDigit(b[bi])) return -1;
- if (firstDiff !== 0) return firstDiff;
- }
- return 0;
-}
-
-function versionCharOrder(value, index, length) {
- if (index === length) return -1;
- const ch = value[index];
- if (isAsciiDigit(ch)) return 0;
- if (isAsciiAlpha(ch)) return value.charCodeAt(index);
- if (ch === "~") return -2;
- return value.charCodeAt(index) + 256;
-}
-
-function isAsciiDigit(ch) {
- return ch >= "0" && ch <= "9";
-}
-
-function isAsciiAlpha(ch) {
- return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z";
-}
-
-function isAsciiAlnum(ch) {
- return isAsciiAlpha(ch) || isAsciiDigit(ch);
-}
-
-async function uniq(args) {
- args = normalizeUniqArgs(normalizeUniqLongOptions(args));
- const { opts, operands } = parseOptions(args, {
- short: { c: false, d: false, D: false, f: "value", i: false, s: "value", u: false, w: "value", z: false },
- long: { count: false, repeated: false, "all-repeated": "optional-value", "skip-fields": "value", group: "optional-value", "ignore-case": false, "skip-chars": "value", unique: false, "check-chars": "value", "zero-terminated": false, help: false, version: false },
- });
- const count = opts.c || opts.count;
- const repeated = opts.d || opts.repeated;
- const unique = opts.u || opts.unique;
- const allRepeated = opts.D || opts["all-repeated"];
- const group = opts.group;
- if (allRepeated && count) throw new UsageError("printing all duplicated lines and repeat counts is meaningless", true);
- if (opts["all-repeated"] != null && opts["all-repeated"] !== true) validateUniqMethod("all-repeated", opts["all-repeated"], ["none", "prepend", "separate"]);
- if (opts.group != null && opts.group !== true) validateUniqMethod("group", opts.group, ["prepend", "append", "separate", "both"]);
- if (group && (count || repeated || allRepeated || unique)) throw new UsageError("--group is mutually exclusive with -c/-d/-D/-u", true);
- validateUniqNumericOptions(opts);
- const inputFile = operands[0] ?? "-";
- const outputFile = operands[1];
- if (operands.length > 2) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[2])}`, true);
- if (!outputFile && canStreamUniqFile(opts)) return streamUniqFile(inputFile, opts);
- let inputBytes;
- try {
- inputBytes = await readAll(inputFile);
- } catch (error) {
- const inputName = textInputDiagnosticName(inputFile);
- const message = error?.code === "EISDIR" ? `error reading ${shellEscapeLsName(pathDisplayName(inputFile), true)}: ${systemErrorMessage(error)}` : `${inputName}: ${systemErrorMessage(error)}`;
- stderr(inputFile === "-" ? `uniq: ${nodeErrorMessage(error)}\n` : `uniq: ${message}\n`);
- return 1;
- }
- const text = decodeSurrogateEscapedBytes(inputBytes);
- const sep = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- const lines = text.endsWith(sep) ? text.slice(0, -sep.length).split(sep) : text === "" ? [] : text.split(sep);
- if (repeated && unique) {
- if (outputFile) await writeAll(outputFile, "");
- return 0;
- }
- const rows = [];
- for (const line of lines) {
- const key = uniqKey(line, opts);
- const last = rows.at(-1);
- if (last?.key === key) {
- last.count++;
- last.lines.push(line);
- } else {
- rows.push({ key, line, lines: [line], count: 1 });
- }
- }
- const outLines = [];
- const allRepeatedMethod = opts["all-repeated"] === true || opts.D ? "none" : opts["all-repeated"];
- const groupMethod = opts.group === true ? "separate" : opts.group;
- for (const row of rows) {
- if (opts.group) {
- pushUniqGroup(outLines, row.lines, groupMethod, opts, row.count, ["separate", "prepend", "append", "both"]);
- } else if (allRepeated) {
- if (row.count > 1) pushUniqGroup(outLines, row.lines, allRepeatedMethod, opts, row.count, ["none", "prepend", "separate"]);
- } else if (repeated) {
- if (row.count > 1) outLines.push(formatUniqLine(row.line, row.count, opts));
- } else if (unique) {
- if (row.count === 1) outLines.push(formatUniqLine(row.line, row.count, opts));
- } else {
- outLines.push(formatUniqLine(row.line, row.count, opts));
- }
- }
- const out = outLines.length ? outLines.join(sep) + sep : "";
- if (outputFile) {
- try {
- await writeAll(outputFile, encodeSurrogateEscapedString(out));
- } catch (error) {
- stderr(`uniq: ${textInputDiagnosticName(outputFile)}: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- } else {
- stdout(out);
- }
- return 0;
-}
-
-function canStreamUniqFile(opts) {
- if (canStreamUniq(opts)) return true;
- const allRepeatedMethod = opts["all-repeated"] === true || opts.D ? "none" : opts["all-repeated"];
- return allRepeatedMethod === "none"
- && !(opts.c || opts.count || opts.d || opts.repeated || opts.u || opts.unique || opts.group);
-}
-
-function streamUniqFile(file, opts) {
- const separator = opts.z || opts["zero-terminated"] ? 0 : 10;
- const sep = Uint8Array.of(separator);
- const allRepeated = Boolean(opts.D || opts["all-repeated"]);
- let fd;
- try {
- fd = file === "-" ? 0 : openSync(file, "r");
- const reader = createFdRecordReader(fd, separator);
- let current = null;
- let count = 0;
- while (true) {
- const record = reader.next();
- if (record == null) break;
- const line = decodeSurrogateEscapedBytes(record);
- const key = uniqKey(line, opts);
- if (current?.key === key) {
- count++;
- if (allRepeated) {
- if (count === 2) {
- stdout(current.record);
- stdout(sep);
- }
- stdout(record);
- stdout(sep);
- }
- } else {
- current = { key, record: Buffer.from(record) };
- count = 1;
- if (!allRepeated) {
- stdout(record);
- stdout(sep);
- }
- }
- }
- return 0;
- } catch (error) {
- if (isWriteError(error)) throw error;
- const message = error?.code === "EISDIR" ? `error reading ${shellEscapeLsName(pathDisplayName(file), true)}: ${systemErrorMessage(error)}` : `${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}`;
- stderr(file === "-" ? `uniq: ${nodeErrorMessage(error)}\n` : `uniq: ${message}\n`);
- return 1;
- } finally {
- if (fd != null && fd !== 0) closeSync(fd);
- }
-}
-
-function streamUniq(opts) {
- const sep = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- const repeated = opts.d || opts.repeated;
- const unique = opts.u || opts.unique;
- const allRepeated = opts.D || opts["all-repeated"];
- const allRepeatedMethod = opts["all-repeated"] === true || opts.D ? "none" : opts["all-repeated"];
- const groupMethod = opts.group === true ? "separate" : opts.group;
- let current = null;
- const defaultStreaming = canStreamUniq(opts);
- const emit = (row, final = false) => {
- if (!row) return;
- if (defaultStreaming) {
- if (final) return;
- stdout(formatUniqLine(row.line, row.count, opts) + sep);
- return;
- }
- const outLines = [];
- if (opts.group) {
- pushUniqGroup(outLines, row.lines, groupMethod, opts, row.count, ["separate", "prepend", "append", "both"]);
- } else if (allRepeated) {
- if (row.count > 1) pushUniqGroup(outLines, row.lines, allRepeatedMethod, opts, row.count, ["none", "prepend", "separate"]);
- } else if (repeated) {
- if (row.count > 1) outLines.push(formatUniqLine(row.line, row.count, opts));
- } else if (unique) {
- if (row.count === 1) outLines.push(formatUniqLine(row.line, row.count, opts));
- } else {
- outLines.push(formatUniqLine(row.line, row.count, opts));
- }
- if (outLines.length) stdout(outLines.join(sep) + sep);
- };
- const accept = (line) => {
- const key = uniqKey(line, opts);
- if (defaultStreaming) {
- if (current?.key !== key) {
- current = { key, line, lines: [line], count: 1 };
- emit(current);
- }
- } else if (current?.key === key) {
- current.count++;
- current.lines.push(line);
- } else {
- emit(current);
- current = { key, line, lines: [line], count: 1 };
- }
- };
- readStdinRecords(sep, accept);
- emit(current, true);
- return 0;
-}
-
-function canStreamUniq(opts) {
- return !(opts.c || opts.count || opts.d || opts.repeated || opts.u || opts.unique || opts.D || opts["all-repeated"] || opts.group);
-}
-
-function readStdinRecords(sep, accept) {
- const sepByte = sep === "\0" ? 0 : 10;
- const buffer = Buffer.allocUnsafe(64 * 1024);
- let pending = [];
- let pendingLength = 0;
- const flush = () => {
- const bytes = new Uint8Array(pendingLength);
- let offset = 0;
- for (const chunk of pending) {
- bytes.set(chunk, offset);
- offset += chunk.length;
- }
- pending = [];
- pendingLength = 0;
- accept(decodeSurrogateEscapedBytes(bytes));
- };
- while (true) {
- const n = readSync(0, buffer, 0, buffer.length, null);
- if (n === 0) break;
- let start = 0;
- for (let i = 0; i < n; i++) {
- if (buffer[i] !== sepByte) continue;
- pending.push(Buffer.from(buffer.subarray(start, i)));
- pendingLength += i - start;
- flush();
- start = i + 1;
- }
- if (start < n) {
- pending.push(Buffer.from(buffer.subarray(start, n)));
- pendingLength += n - start;
- }
- }
- if (pendingLength) flush();
-}
-
-function normalizeUniqArgs(args) {
- const out = [];
- let scanning = true;
- let valueNext = false;
- for (const arg of args) {
- if (!scanning) {
- out.push(arg);
- } else if (valueNext) {
- out.push(arg);
- valueNext = false;
- } else if (arg === "-f" || arg === "--skip-fields" || arg === "-s" || arg === "--skip-chars" || arg === "-w" || arg === "--check-chars") {
- out.push(arg);
- valueNext = true;
- } else if (/^-\d+$/.test(arg)) {
- out.push("-f", arg.slice(1));
- } else if (/^\+\d+$/.test(arg)) {
- out.push("-s", arg.slice(1));
- } else {
- if (arg === "--") scanning = false;
- else if (!arg.startsWith("-")) scanning = false;
- out.push(arg);
- }
- }
- return out;
-}
-
-function normalizeUniqLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, UNIQ_LONG_OPTIONS);
-}
-
-function normalizeUniqLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, UNIQ_LONG_OPTIONS);
-}
-
-function validateUniqNumericOptions(opts) {
- validateUniqNumericOption(opts.f ?? opts["skip-fields"], "fields to skip");
- validateUniqNumericOption(opts.s ?? opts["skip-chars"], "bytes to skip");
- validateUniqNumericOption(opts.w ?? opts["check-chars"], "bytes to compare");
-}
-
-function validateUniqNumericOption(value, description) {
- if (value == null) return;
- if (/^\+?\d+$/.test(String(value))) return;
- throw new UsageError(`${value}: invalid number of ${description}`);
-}
-
-function validateUniqMethod(option, method, allowed) {
- if (allowed.includes(method)) return;
- const kind = method === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(method)} for ${localeQuotedDiagnostic(`--${option}`)}\nValid arguments are:\n${allowed.map((value) => ` - ${localeQuotedDiagnostic(value)}`).join("\n")}`, true);
-}
-
-function pushUniqGroup(outLines, lines, method, opts, count, allowed) {
- if (!allowed.includes(method)) throw new UsageError(`invalid group method: ${method}`);
- if (method === "prepend" || (method === "both" && outLines.length === 0)) outLines.push("");
- else if (method === "separate" && outLines.length) outLines.push("");
- for (const line of lines) outLines.push(formatUniqLine(line, count, opts));
- if (method === "append" || method === "both") outLines.push("");
-}
-
-function formatUniqLine(line, count, opts) {
- return `${opts.c || opts.count ? String(count).padStart(7) + " " : ""}${line}`;
-}
-
-function uniqKey(line, opts) {
- let key = line;
- const skipFields = Number(opts.f ?? opts["skip-fields"] ?? 0);
- const skipChars = Number(opts.s ?? opts["skip-chars"] ?? 0);
- const width = opts.w ?? opts["check-chars"];
- if (!Number.isInteger(skipFields) || skipFields < 0) throw new UsageError(`invalid field skip: ${opts.f ?? opts["skip-fields"]}`);
- if (!Number.isInteger(skipChars) || skipChars < 0) throw new UsageError(`invalid character skip: ${opts.s ?? opts["skip-chars"]}`);
- let offset = 0;
- for (let field = 0; field < skipFields && offset < key.length; field++) {
- while (offset < key.length && /\s/u.test(key[offset])) offset++;
- while (offset < key.length && !/\s/u.test(key[offset])) offset++;
- }
- key = [...key.slice(offset)].slice(skipChars).join("");
- if (width !== undefined) {
- const max = Number(width);
- if (!Number.isInteger(max) || max < 0) throw new UsageError(`invalid compare width: ${width}`);
- key = [...key].slice(0, max).join("");
- }
- if (opts.i || opts["ignore-case"]) key = key.toLowerCase();
- return key;
-}
-
-async function comm(args) {
- args = normalizeCommLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { 1: false, 2: false, 3: false, z: false }, long: { "output-delimiter": "value", total: false, "zero-terminated": false, "check-order": false, "nocheck-order": false, help: false, version: false } });
- const delim = commOutputDelimiter(args);
- if (operands.length < 2) throw new UsageError(operands.length === 1 ? `missing operand after '${operands[0]}'` : "missing operand", true);
- if (operands.length > 2) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[2])}`, true);
- const sepByte = opts.z || opts["zero-terminated"] ? 0 : 0x0a;
- const sep = Buffer.from([sepByte]);
- const delimBytes = delim === "\0" ? Buffer.from([0]) : Buffer.from(delim);
- if (operands[0] !== "-" && operands[1] !== "-" && !opts.total) {
- const streamed = streamCommNonRegularFiles(operands, opts, sep, delimBytes);
- if (streamed != null) return streamed;
- }
- let left;
- let right;
- let sharedStdinError = false;
- if (operands[0] === "-" && operands[1] === "-") {
- const records = splitCommByteRecords(await readAll("-"), sepByte);
- left = records.filter((_, index) => index % 2 === 0);
- right = records.filter((_, index) => index % 2 === 1);
- sharedStdinError = true;
- } else {
- let leftBytes;
- let rightBytes;
- try {
- leftBytes = await readAll(operands[0]);
- rightBytes = await readAll(operands[1]);
- } catch (error) {
- const file = leftBytes == null ? operands[0] : operands[1];
- stderr(`comm: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- left = splitCommByteRecords(leftBytes, sepByte);
- right = splitCommByteRecords(rightBytes, sepByte);
- }
- let i = 0, j = 0;
- const out = [];
- const counts = [0, 0, 0];
- const order = { bad: [false, false], messages: [] };
- while (i < left.length || j < right.length) {
- const leftBad = commNoteDisorder(left, i, 0, opts, order);
- if (opts["check-order"] && leftBad) break;
- const rightBad = commNoteDisorder(right, j, 1, opts, order);
- if (opts["check-order"] && rightBad) break;
- if (j >= right.length || (i < left.length && compareByteRecords(left[i], right[j]) < 0)) {
- counts[0]++;
- if (!opts[1]) pushCommRecord(out, left[i], sep);
- i++;
- } else if (i >= left.length || compareByteRecords(right[j], left[i]) < 0) {
- counts[1]++;
- if (!opts[2]) pushCommRecord(out, right[j], sep, commPrefixBytes(2, opts, delimBytes));
- j++;
- } else {
- counts[2]++;
- if (!opts[3]) pushCommRecord(out, left[i], sep, commPrefixBytes(3, opts, delimBytes));
- i++; j++;
- }
- }
- if (opts.total) {
- out.push(Buffer.from(String(counts[0])), delimBytes, Buffer.from(String(counts[1])), delimBytes, Buffer.from(String(counts[2])), delimBytes, Buffer.from("total"), sep);
- }
- stdout(Buffer.concat(out));
- if (sharedStdinError) {
- stderr("comm: -\n");
- return 1;
- }
- if (opts["nocheck-order"] || order.messages.length === 0) return 0;
- const fullyPairable = left.length === right.length && left.every((line, index) => byteRecordsEqual(line, right[index]));
- if (!opts["check-order"] && fullyPairable) return 0;
- for (const message of order.messages) stderr(`comm: ${message}\n`);
- if (!opts["check-order"]) stderr("comm: input is not in sorted order\n");
- return 1;
-}
-
-function streamCommNonRegularFiles(files, opts, sep, delimBytes) {
- const fds = [];
- try {
- for (const file of files) fds.push(openSync(file, "r"));
- if (fds.some((fd) => fstatSync(fd).isFile())) return null;
- const readers = fds.map((fd) => createFdRecordReader(fd, sep[0]));
- const previous = [null, null];
- const order = { bad: [false, false], messages: [] };
- let stoppedForOrder = false;
- const next = (side) => {
- const record = readers[side].next();
- if (record != null && previous[side] != null && !opts["nocheck-order"] && !order.bad[side] && compareByteRecords(previous[side], record) > 0) {
- order.bad[side] = true;
- order.messages.push(`file ${side + 1} is not in sorted order`);
- if (opts["check-order"]) stoppedForOrder = true;
- }
- previous[side] = record;
- return record;
- };
- let left = next(0);
- let right = next(1);
- while (!stoppedForOrder && (left != null || right != null)) {
- if (right == null || (left != null && compareByteRecords(left, right) < 0)) {
- if (!opts[1]) writeCommRecord(left, sep);
- left = next(0);
- } else if (left == null || compareByteRecords(right, left) < 0) {
- if (!opts[2]) writeCommRecord(right, sep, commPrefixBytes(2, opts, delimBytes));
- right = next(1);
- } else {
- if (!opts[3]) writeCommRecord(left, sep, commPrefixBytes(3, opts, delimBytes));
- left = next(0);
- right = next(1);
- }
- }
- if (opts["nocheck-order"] || order.messages.length === 0) return 0;
- for (const message of order.messages) stderr(`comm: ${message}\n`);
- if (!opts["check-order"]) stderr("comm: input is not in sorted order\n");
- return 1;
- } catch (error) {
- if (isWriteError(error)) throw error;
- const side = fds.length < 2 ? fds.length : 0;
- stderr(`comm: ${textInputDiagnosticName(files[side])}: ${systemErrorMessage(error)}\n`);
- return 1;
- } finally {
- for (const fd of fds) closeSync(fd);
- }
-}
-
-function createFdRecordReader(fd, separator) {
- const buffer = Buffer.allocUnsafe(64 * 1024);
- let offset = 0;
- let length = 0;
- let eof = false;
- let pending = [];
- return {
- next() {
- while (true) {
- for (let index = offset; index < length; index++) {
- if (buffer[index] !== separator) continue;
- const tail = Buffer.from(buffer.subarray(offset, index));
- offset = index + 1;
- if (!pending.length) return tail;
- pending.push(tail);
- const record = Buffer.concat(pending);
- pending = [];
- return record;
- }
- if (offset < length) pending.push(Buffer.from(buffer.subarray(offset, length)));
- if (eof) {
- if (!pending.length) return null;
- const record = Buffer.concat(pending);
- pending = [];
- return record;
- }
- length = readSync(fd, buffer, 0, buffer.length, null);
- offset = 0;
- if (length === 0) eof = true;
- }
- },
- };
-}
-
-function writeCommRecord(record, sep, prefix = null) {
- if (prefix) stdout(prefix);
- stdout(record);
- stdout(sep);
-}
-
-function splitCommByteRecords(bytes, sepByte) {
- if (bytes.length === 0) return [];
- const end = bytes[bytes.length - 1] === sepByte ? bytes.length - 1 : bytes.length;
- const records = [];
- let start = 0;
- for (let i = 0; i < end; i++) {
- if (bytes[i] === sepByte) {
- records.push(bytes.subarray(start, i));
- start = i + 1;
- }
- }
- records.push(bytes.subarray(start, end));
- return records;
-}
-
-function compareByteRecords(left, right) {
- const n = Math.min(left.length, right.length);
- for (let i = 0; i < n; i++) {
- if (left[i] !== right[i]) return left[i] - right[i];
- }
- return left.length - right.length;
-}
-
-function byteRecordsEqual(left, right) {
- return left.length === right.length && compareByteRecords(left, right) === 0;
-}
-
-function commPrefixBytes(col, opts, delimBytes) {
- const chunks = [];
- if (!opts[1] && col > 1) chunks.push(delimBytes);
- if (!opts[2] && col > 2) chunks.push(delimBytes);
- return chunks.length === 0 ? null : Buffer.concat(chunks);
-}
-
-function pushCommRecord(out, record, sep, prefix = null) {
- if (prefix) out.push(prefix);
- out.push(record, sep);
-}
-
-function commOutputDelimiter(args) {
- const values = [];
- let end = false;
- let valueFor = false;
- for (const arg of args) {
- if (end) continue;
- if (valueFor) {
- values.push(arg);
- valueFor = false;
- continue;
- }
- if (arg === "--") {
- end = true;
- } else if (arg === "--output-delimiter") {
- valueFor = true;
- } else if (arg.startsWith("--output-delimiter=")) {
- values.push(arg.slice("--output-delimiter=".length));
- }
- }
- if (new Set(values).size > 1) throw new UsageError("multiple output delimiters specified");
- if (values.length === 0) return "\t";
- return values[0] === "" ? "\0" : values[0];
-}
-
-function commNoteDisorder(records, index, side, opts, order) {
- if (opts["nocheck-order"] || index <= 0 || index >= records.length || order.bad[side] || compareByteRecords(records[index - 1], records[index]) <= 0) return false;
- order.bad[side] = true;
- order.messages.push(`file ${side + 1} is not in sorted order`);
- return true;
-}
-
-function firstUnsortedIndex(lines) {
- for (let i = 1; i < lines.length; i++) {
- if (lines[i - 1] > lines[i]) return i;
- }
- return -1;
-}
-
-async function base64Cmd(args) {
- args = normalizeBaseEncodingLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { d: false, i: false, w: "value" }, long: { decode: false, "ignore-garbage": false, wrap: "value", help: false, version: false } });
- ensureSingleInputOperand(operands);
- const wrap = parseWrap(opts.w ?? opts.wrap ?? 76);
- const file = operands[0] ?? "-";
- let data;
- try {
- data = await readAll(file);
- } catch (error) {
- const message = error?.code === "EISDIR" ? "read error: Is a directory" : file === "-" ? nodeErrorMessage(error) : `${baseEncodingDiagnosticName(file)}: ${systemErrorMessage(error)}`;
- stderr(`base64: ${message}\n`);
- return 1;
- }
- if (opts.d || opts.decode) {
- stdout(decodeBase64(new TextDecoder().decode(data), opts.i || opts["ignore-garbage"]));
- return 0;
- }
- const encoded = Buffer.from(data).toString("base64");
- stdout(formatEncodedOutput(encoded, wrap));
- return 0;
-}
-
-function baseEncodingDiagnosticName(file) {
- return shellEscapeLsName(pathDisplayName(file));
-}
-
-function ensureSingleInputOperand(operands) {
- if (operands.length > 1) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[1])}`, true);
-}
-
-function parseWrap(value) {
- const text = String(value);
- if (!/^\+?\d+$/.test(text)) throw new UsageError(`invalid wrap size: ${localeQuotedEscapedDiagnostic(text)}`);
- const parsed = BigInt(text);
- if (parsed > 9223372036854775807n) return 0;
- const wrap = parsed > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(parsed);
- return wrap;
-}
-
-function formatEncodedOutput(encoded, wrap) {
- if (encoded === "") return "";
- if (wrap === 0) return encoded;
- if (wrap >= encoded.length) return `${encoded}\n`;
- return `${encoded.match(new RegExp(`.{1,${wrap}}`, "g"))?.join("\n") ?? ""}\n`;
-}
-
-function normalizeBaseEncodingLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, BASE_ENCODING_LONG_OPTIONS);
-}
-
-function normalizeBaseEncodingLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, BASE_ENCODING_LONG_OPTIONS);
-}
-
-function normalizeBasencLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, BASENC_LONG_OPTIONS);
-}
-
-function normalizeBasencLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, BASENC_LONG_OPTIONS);
-}
-
-function normalizeLongOptionsByPrefix(args, longOptions) {
- const out = [];
- for (const arg of args) {
- if (arg === "--") {
- out.push(arg);
- continue;
- }
- if (!arg.startsWith("--") || arg === "--") {
- out.push(arg);
- continue;
- }
- out.push(normalizeLongOptionByPrefix(arg, longOptions));
- }
- return out;
-}
-
-function normalizeLongOptionByPrefix(arg, longOptions, reportAmbiguous = true) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (longOptions.includes(name)) return arg;
- const matches = longOptions.filter((option) => option.startsWith(name));
- if (matches.length === 1) return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
- if (matches.length > 1 && reportAmbiguous) {
- throw new UsageError(`option '${arg}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- return arg;
-}
-
-function normalizeInvocationLongOptionByPrefix(arg, longOptions) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (longOptions.includes(name)) return arg;
- const matches = longOptions.filter((option) => option.startsWith(name));
- if (matches.length === 1) return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
- if (matches.length > 1) throw new InvocationError(`option '${arg}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`);
- return arg;
-}
-
-function decodeBase64(text, ignoreGarbage = false, url = false) {
- let cleaned = text.replace(/\s+/g, "");
- const alphabet = url ? "A-Za-z0-9_\\-=" : "A-Za-z0-9+/=";
- if (ignoreGarbage) cleaned = cleaned.replace(new RegExp(`[^${alphabet}]`, "g"), "");
- else {
- const invalid = cleaned.search(new RegExp(`[^${alphabet}]`));
- if (invalid !== -1) {
- const prefix = decodeBase64Clean(cleaned.slice(0, invalid), url).bytes;
- if (prefix.length) stdout(prefix);
- throw new UsageError("invalid input");
- }
- }
- const decoded = decodeBase64Clean(cleaned, url);
- if (!decoded.valid) {
- if (decoded.bytes.length) stdout(decoded.bytes);
- throw new UsageError("invalid input");
- }
- return decoded.bytes;
-}
-
-function base64Alphabet(text, url = false) {
- return url ? text.replaceAll("-", "+").replaceAll("_", "/") : text;
-}
-
-function decodeBase64Clean(text, url = false) {
- const chunks = [];
- let valid = true;
- let i = 0;
- while (i < text.length) {
- let start = i;
- while (i < text.length && text[i] !== "=") i++;
- let base = text.slice(start, i);
- let pads = "";
- while (i < text.length && text[i] === "=") pads += text[i++];
- if (base.length === 0 && pads.length > 0) {
- valid = false;
- break;
- }
- if (base.length === 0) continue;
- const segment = decodeBase64Segment(base, pads, url);
- if (segment.bytes.length) chunks.push(segment.bytes);
- if (!segment.valid) {
- valid = false;
- break;
- }
- }
- return { bytes: Buffer.concat(chunks), valid };
-}
-
-function decodeBase64Segment(base, pads, url = false) {
- const needPads = (4 - (base.length % 4)) % 4;
- const bytes = base.length % 4 === 1
- ? Buffer.from(base64Alphabet(base.slice(0, base.length - 1), url), "base64")
- : Buffer.from(base64Alphabet(base + "=".repeat(needPads), url), "base64");
- let valid = base.length % 4 !== 1;
- if (pads.length) {
- valid &&= pads.length <= 2;
- valid &&= (base.length + pads.length) % 4 === 0;
- if (pads.length === 1) valid &&= base.length % 4 === 3 && (base64DigitValue(base.at(-1), url) & 0b11) === 0;
- else if (pads.length === 2) valid &&= base.length % 4 === 2 && (base64DigitValue(base.at(-1), url) & 0b1111) === 0;
- else valid = false;
- } else if (base.length % 4 === 2) {
- valid &&= (base64DigitValue(base.at(-1), url) & 0b1111) === 0;
- } else if (base.length % 4 === 3) {
- valid &&= (base64DigitValue(base.at(-1), url) & 0b11) === 0;
- }
- return { bytes, valid };
-}
-
-function base64DigitValue(ch, url = false) {
- const alphabet = url ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- return alphabet.indexOf(ch);
-}
-
-async function base32Cmd(args) {
- args = normalizeBaseEncodingLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { d: false, i: false, w: "value" }, long: { decode: false, "ignore-garbage": false, wrap: "value", help: false, version: false } });
- ensureSingleInputOperand(operands);
- const wrap = parseWrap(opts.w ?? opts.wrap ?? 76);
- const file = operands[0] ?? "-";
- let data;
- try {
- data = await readAll(file);
- } catch (error) {
- const message = error?.code === "EISDIR" ? "read error: Is a directory" : file === "-" ? nodeErrorMessage(error) : `${baseEncodingDiagnosticName(file)}: ${systemErrorMessage(error)}`;
- stderr(`base32: ${message}\n`);
- return 1;
- }
- if (opts.d || opts.decode) {
- let text = new TextDecoder().decode(data).replace(/\s+/g, "");
- if (opts.i || opts["ignore-garbage"]) text = text.replace(/[^A-Z2-7=]/g, "");
- stdout(base32Decode(text));
- return 0;
- }
- const encoded = base32Encode(data);
- stdout(formatEncodedOutput(encoded, wrap));
- return 0;
-}
-
-async function expand(args) {
- args = normalizeTabArgs(normalizeTabCommandLongOptions(args, EXPAND_LONG_OPTIONS));
- const { opts, operands } = parseOptions(args, { short: { t: "value", i: false }, long: { tabs: "value", initial: false, help: false, version: false } });
- const stops = parseTabStops(combinedTabSpec(opts.tabs ?? opts.tab, opts.t), "expand");
- const files = operands.length ? operands : ["-"];
- let failed = false;
- for (const file of files) {
- let fd;
- try {
- fd = file === "-" ? 0 : openSync(file, "r");
- streamExpandFd(fd, stops, opts);
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(file === "-" ? `expand: ${nodeErrorMessage(error)}\n` : `expand: ${tabFoldDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- } finally {
- if (fd != null && fd !== 0) closeSync(fd);
- }
- }
- return failed ? 1 : 0;
-}
-
-function streamExpandFd(fd, stops, opts) {
- let column = 0;
- let atLineStart = true;
- let carry = Buffer.alloc(0);
- readFdChunkViews(fd, (chunk) => {
- const bytes = carry.length ? Buffer.concat([carry, chunk]) : chunk;
- carry = Buffer.alloc(0);
- const output = [];
- let runStart = 0;
- let index = 0;
- while (index < bytes.length) {
- const byte = bytes[index];
- if (byte >= 0xc2 && byte <= 0xf4) {
- const length = byte <= 0xdf ? 2 : byte <= 0xef ? 3 : 4;
- if (index + length > bytes.length) {
- if (index > runStart) output.push(bytes.subarray(runStart, index));
- carry = Buffer.from(bytes.subarray(index));
- runStart = bytes.length;
- break;
- }
- const token = nextUtf8Token(bytes, index);
- column += token.width;
- atLineStart = false;
- index = token.next;
- continue;
- }
- if (byte === 0x0a) {
- column = 0;
- atLineStart = true;
- index++;
- continue;
- }
- if (byte === 0x09 && (!(opts.i || opts.initial) || atLineStart)) {
- if (index > runStart) output.push(bytes.subarray(runStart, index));
- const next = nextTabColumn(column, stops);
- output.push(Buffer.alloc(next - column, 0x20));
- column = next;
- index++;
- runStart = index;
- continue;
- }
- if (byte === 0x08) column = Math.max(0, column - 1);
- else column++;
- if (byte !== 0x20) atLineStart = false;
- index++;
- }
- if (runStart < bytes.length && !carry.length) output.push(bytes.subarray(runStart));
- for (const piece of output) stdout(piece);
- });
- if (carry.length) stdout(carry);
-}
-
-function tabFoldDiagnosticName(file) {
- return shellEscapeLsName(pathDisplayName(file));
-}
-
-function expandBytes(bytes, stops, opts = {}) {
- const out = [];
- let column = 0;
- let atLineStart = true;
- for (let i = 0; i < bytes.length;) {
- const token = nextUtf8Token(bytes, i);
- i = token.next;
- if (token.bytes.length === 1 && token.bytes[0] === 0x0a) {
- out.push(token.bytes);
- column = 0;
- atLineStart = true;
- } else if (token.bytes.length === 1 && token.bytes[0] === 0x09 && (!(opts.i || opts.initial) || atLineStart)) {
- const next = nextTabColumn(column, stops);
- out.push(enc.encode(" ".repeat(next - column)));
- column = next;
- } else {
- out.push(token.bytes);
- if (token.bytes.length === 1 && token.bytes[0] === 0x08) column = Math.max(0, column - 1);
- else column += token.width;
- if (!(token.bytes.length === 1 && token.bytes[0] === 0x20)) atLineStart = false;
- }
- }
- return concatBytes(out);
-}
-
-function nextUtf8Token(bytes, index) {
- const b0 = bytes[index];
- if (b0 < 0x80) return { bytes: bytes.slice(index, index + 1), char: String.fromCharCode(b0), width: b0 === 0x09 ? 0 : 1, next: index + 1 };
- const len = b0 >= 0xc2 && b0 <= 0xdf ? 2 : b0 >= 0xe0 && b0 <= 0xef ? 3 : b0 >= 0xf0 && b0 <= 0xf4 ? 4 : 1;
- if (len === 1 || index + len > bytes.length) return { bytes: bytes.slice(index, index + 1), char: null, width: 1, next: index + 1 };
- for (let i = 1; i < len; i++) {
- if ((bytes[index + i] & 0xc0) !== 0x80) return { bytes: bytes.slice(index, index + 1), char: null, width: 1, next: index + 1 };
- }
- const slice = bytes.slice(index, index + len);
- const char = new TextDecoder("utf-8", { ignoreBOM: true }).decode(slice);
- return { bytes: slice, char, width: displayWidth(char), next: index + len };
-}
-
-async function unexpand(args) {
- const obsoleteTabs = args.some((arg) => /^-\d[\d,\s]*$/.test(arg));
- args = normalizeTabArgs(normalizeTabCommandLongOptions(args, UNEXPAND_LONG_OPTIONS));
- const { opts, operands } = parseOptions(args, { short: { t: "value", a: false }, long: { tabs: "value", all: false, "first-only": false, help: false, version: false } });
- let stops;
- try {
- stops = parseTabStops(combinedTabSpec(opts.tabs ?? opts.tab, opts.t), "unexpand");
- } catch (error) {
- if (obsoleteTabs && error instanceof UsageError && error.message.startsWith("tab stop is too large")) throw new UsageError("tab stop value is too large");
- throw error;
- }
- const hasExplicitTabs = opts.t != null || opts.tab != null || opts.tabs != null;
- const convertAll = Boolean(opts.a || opts.all || (hasExplicitTabs && !opts["first-only"] && !obsoleteTabs));
- const files = operands.length ? operands : ["-"];
- let failed = false;
- for (const file of files) {
- let fd;
- try {
- fd = file === "-" ? 0 : openSync(file, "r");
- streamUnexpandFd(fd, stops, convertAll);
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(file === "-" ? `unexpand: ${nodeErrorMessage(error)}\n` : `unexpand: ${tabFoldDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- } finally {
- if (fd != null && fd !== 0) closeSync(fd);
- }
- }
- return failed ? 1 : 0;
-}
-
-function streamUnexpandFd(fd, stops, convertAll) {
- const newline = Uint8Array.of(0x0a);
- let column = 0;
- let fieldStarted = false;
- let blankStartColumn = 0;
- let blanks = [];
- let carry = Buffer.alloc(0);
- const output = [];
- const flushOutput = () => {
- for (const piece of output) stdout(piece);
- output.length = 0;
- };
- const emit = (piece) => {
- if (piece.length) output.push(piece);
- if (output.length >= 256) flushOutput();
- };
- const flushBlanks = (atEnd) => {
- if (!blanks.length) return;
- const canConvert = convertAll || !fieldStarted;
- emit(canConvert
- ? renderUnexpandedBlankTokens(blankStartColumn, column, blanks, stops, atEnd, blanks.some((token) => isAsciiByteToken(token, 0x09)), !fieldStarted)
- : concatBytes(blanks.map((token) => token.bytes)));
- blanks = [];
- };
- const addBlank = (token) => {
- if (!blanks.length) blankStartColumn = column;
- blanks.push({ ...token, bytes: Buffer.from(token.bytes) });
- column = tokenEndColumn(token, column, stops);
- };
- readFdChunkViews(fd, (chunk) => {
- const bytes = carry.length ? Buffer.concat([carry, chunk]) : chunk;
- carry = Buffer.alloc(0);
- let runStart = -1;
- const endRun = (end) => {
- if (runStart !== -1) emit(bytes.subarray(runStart, end));
- runStart = -1;
- };
- let index = 0;
- while (index < bytes.length) {
- const byte = bytes[index];
- if (byte < 0x80) {
- if (byte === 0x0a) {
- endRun(index);
- flushBlanks(true);
- emit(newline);
- column = 0;
- fieldStarted = false;
- } else if (byte === 0x20 || byte === 0x09) {
- endRun(index);
- addBlank({ bytes: bytes.subarray(index, index + 1), char: String.fromCharCode(byte), width: byte === 0x09 ? 0 : 1 });
- } else {
- if (runStart === -1) {
- flushBlanks(false);
- runStart = index;
- }
- column = byte === 0x08 ? Math.max(0, column - 1) : column + 1;
- fieldStarted = true;
- }
- index++;
- continue;
- }
- const length = byte >= 0xc2 && byte <= 0xdf ? 2 : byte >= 0xe0 && byte <= 0xef ? 3 : byte >= 0xf0 && byte <= 0xf4 ? 4 : 1;
- if (length > 1 && index + length > bytes.length) {
- endRun(index);
- carry = Buffer.from(bytes.subarray(index));
- break;
- }
- endRun(index);
- const token = nextUtf8Token(bytes, index);
- if (isUnexpandBlank(token)) addBlank(token);
- else {
- flushBlanks(false);
- emit(token.bytes);
- column = tokenEndColumn(token, column, stops);
- fieldStarted = true;
- }
- index = token.next;
- }
- endRun(bytes.length);
- flushOutput();
- });
- if (carry.length) {
- flushBlanks(false);
- emit(carry);
- fieldStarted = true;
- }
- flushBlanks(true);
- flushOutput();
-}
-
-function unexpandBytes(bytes, stops, convertAll) {
- const out = [];
- let line = [];
- for (let i = 0; i < bytes.length;) {
- const token = nextUtf8Token(bytes, i);
- i = token.next;
- if (token.bytes.length === 1 && token.bytes[0] === 0x0a) {
- out.push(unexpandLineTokens(line, stops, convertAll), token.bytes);
- line = [];
- } else {
- line.push(token);
- }
- }
- if (line.length) out.push(unexpandLineTokens(line, stops, convertAll));
- return concatBytes(out);
-}
-
-function unexpandLineTokens(tokens, stops, convertAll) {
- const out = [];
- let column = 0;
- let fieldStarted = false;
- for (let i = 0; i < tokens.length;) {
- const token = tokens[i];
- if (!isUnexpandBlank(token)) {
- out.push(token.bytes);
- column = tokenEndColumn(token, column, stops);
- fieldStarted = true;
- i++;
- continue;
- }
-
- const runStart = i;
- const startColumn = column;
- let containsTab = false;
- while (i < tokens.length && isUnexpandBlank(tokens[i])) {
- if (isAsciiByteToken(tokens[i], 0x09)) containsTab = true;
- column = tokenEndColumn(tokens[i], column, stops);
- i++;
- }
- const run = tokens.slice(runStart, i);
- const canConvert = convertAll || !fieldStarted;
- if (!canConvert) {
- out.push(...run.map((part) => part.bytes));
- continue;
- }
- out.push(renderUnexpandedBlankTokens(startColumn, column, run, stops, i >= tokens.length, containsTab, !fieldStarted));
- }
- return concatBytes(out);
-}
-
-function isUnexpandBlank(token) {
- return isAsciiByteToken(token, 0x20) || isAsciiByteToken(token, 0x09) || (token.char != null && /\p{Zs}/u.test(token.char));
-}
-
-function isAsciiByteToken(token, byte) {
- return token.bytes.length === 1 && token.bytes[0] === byte;
-}
-
-function tokenEndColumn(token, column, stops) {
- if (isAsciiByteToken(token, 0x09)) return nextTabColumn(column, stops);
- if (isAsciiByteToken(token, 0x08)) return Math.max(0, column - 1);
- return column + token.width;
-}
-
-function renderUnexpandedBlankTokens(startColumn, endColumn, run, stops, atEnd, containsTab, atFieldStart = false) {
- const original = concatBytes(run.map((token) => token.bytes));
- const originalWidth = endColumn - startColumn;
- const rendered = containsTab
- ? renderUnexpandedBlankTokenTabs(startColumn, run, stops, atEnd, atFieldStart)
- : renderUnexpandedSpaces(startColumn, endColumn, stops, atEnd, originalWidth, false, atFieldStart);
- if (!rendered.includes("\t") && run.some((token) => token.char != null && !isAsciiByteToken(token, 0x20))) return original;
- return enc.encode(rendered);
-}
-
-function renderUnexpandedBlankTokenTabs(startColumn, run, stops, atEnd, atFieldStart = false) {
- const lastTab = run.findLastIndex((token) => isAsciiByteToken(token, 0x09));
- const prefix = run.slice(0, lastTab + 1);
- const suffix = run.slice(lastTab + 1);
- const prefixEnd = blankTokenRunEndColumn(startColumn, prefix, stops);
- const suffixEnd = blankTokenRunEndColumn(prefixEnd, suffix, stops);
- return renderUnexpandedSpaces(startColumn, prefixEnd, stops, true, prefixEnd - startColumn, true, atFieldStart)
- + renderUnexpandedSpaces(prefixEnd, suffixEnd, stops, atEnd, suffixEnd - prefixEnd, false, atFieldStart);
-}
-
-function blankTokenRunEndColumn(startColumn, run, stops) {
- let column = startColumn;
- for (const token of run) column = tokenEndColumn(token, column, stops);
- return column;
-}
-
-function renderUnexpandedSpaces(startColumn, endColumn, stops, atEnd, originalLength, fromTabs = false, atFieldStart = false) {
- let column = startColumn;
- let out = "";
- while (column < endColumn) {
- const next = nextTabColumn(column, stops);
- const remaining = endColumn - column;
- const width = next - column;
- const hasExplicitStop = stops.interval || stops.length === 1 || stops.some((stop) => stop > column && stop <= endColumn) || (fromTabs && width === 1);
- const finalSingleBeforeText = !atEnd && width === remaining && width === 1 && originalLength <= 1 && (!atFieldStart || stops[0] !== 1);
- const finalSingleAtEnd = atEnd && !fromTabs && width === remaining && width === 1 && originalLength <= 1;
- if (hasExplicitStop && width <= remaining && !finalSingleBeforeText && !finalSingleAtEnd) {
- out += "\t";
- column = next;
- } else {
- out += " ";
- column++;
- }
- }
- return out;
-}
-
-async function fold(args) {
- args = normalizeFoldArgs(normalizeFoldLongOptions(args));
- const { opts, operands } = parseOptions(args, { short: { b: false, c: false, w: "value", s: false }, long: { bytes: false, characters: false, width: "value", spaces: false, help: false, version: false } });
- const widthText = opts.w ?? opts.width ?? "80";
- const width = parseFoldWidth(widthText);
- const files = operands.length ? operands : ["-"];
- const mode = foldMode(args);
- if (!(opts.s || opts.spaces)) {
- let failed = false;
- for (const file of files) {
- let fd;
- try {
- fd = file === "-" ? 0 : openSync(file, "r");
- streamFoldFd(fd, width, mode);
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(file === "-" ? `fold: ${nodeErrorMessage(error)}\n` : `fold: ${tabFoldDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- } finally {
- if (fd != null && fd !== 0) closeSync(fd);
- }
- }
- return failed ? 1 : 0;
- }
- if (files.length === 1 && files[0] === "-") {
- readStdinByteRecords(10, (record, hasSep) => {
- const bytes = hasSep ? concatBytes([record, Uint8Array.of(10)]) : record;
- stdout(foldBytes(bytes, width, mode, opts));
- });
- return 0;
- }
- const out = [];
- let failed = false;
- for (const file of files) {
- let bytes;
- try {
- bytes = await readAll(file);
- } catch (error) {
- stderr(file === "-" ? `fold: ${nodeErrorMessage(error)}\n` : `fold: ${tabFoldDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- continue;
- }
- out.push(foldBytes(bytes, width, mode, opts));
- }
- stdout(concatOutputParts(out));
- return failed ? 1 : 0;
-}
-
-function streamFoldFd(fd, width, mode) {
- const newline = Uint8Array.of(0x0a);
- const singleByteLocale = isSingleByteLocale();
- let measure = 0;
- let lineHasToken = false;
- let carry = Buffer.alloc(0);
- const process = (bytes, retainIncomplete) => {
- const output = [];
- const emit = (piece) => {
- if (piece.length) output.push(piece);
- if (output.length >= 256) {
- for (const part of output) stdout(part);
- output.length = 0;
- }
- };
- let runStart = 0;
- let index = 0;
- while (index < bytes.length) {
- const byte = bytes[index];
- if (byte === 0x0a) {
- measure = 0;
- lineHasToken = false;
- index++;
- continue;
- }
- let tokenLength = 1;
- let tokenWidth = byte === 0 ? 0 : 1;
- let tokenNext = index + 1;
- if (!singleByteLocale && byte >= 0xc2 && byte <= 0xf4) {
- const length = byte <= 0xdf ? 2 : byte <= 0xef ? 3 : 4;
- if (retainIncomplete && index + length > bytes.length) break;
- const token = nextUtf8Token(bytes, index);
- tokenLength = token.bytes.length;
- tokenWidth = token.width;
- tokenNext = token.next;
- }
- let next;
- if (mode === "bytes") next = measure + tokenLength;
- else if (mode === "characters") next = measure + 1;
- else if (tokenLength === 1 && byte === 0x08) next = Math.max(0, measure - 1);
- else if (tokenLength === 1 && byte === 0x0d) next = 0;
- else if (tokenLength === 1 && byte === 0x09) next = measure + 8 - (measure % 8);
- else if (tokenLength === 1 && byte === 0x0c) next = measure + 1;
- else next = measure + tokenWidth;
- if (lineHasToken && (next > width || (measure >= width && next !== measure))) {
- emit(bytes.subarray(runStart, index));
- emit(newline);
- runStart = index;
- measure = 0;
- lineHasToken = false;
- if (mode === "bytes") next = tokenLength;
- else if (mode === "characters") next = 1;
- else if (tokenLength === 1 && (byte === 0x08 || byte === 0x0d)) next = 0;
- else if (tokenLength === 1 && byte === 0x09) next = 8;
- else if (tokenLength === 1 && byte === 0x0c) next = 1;
- else next = tokenWidth;
- }
- measure = next;
- lineHasToken = true;
- index = tokenNext;
- }
- emit(bytes.subarray(runStart, index));
- for (const part of output) stdout(part);
- return index < bytes.length ? Buffer.from(bytes.subarray(index)) : Buffer.alloc(0);
- };
- readFdChunkViews(fd, (chunk) => {
- const bytes = carry.length ? Buffer.concat([carry, chunk]) : chunk;
- carry = process(bytes, true);
- });
- if (carry.length) process(carry, false);
-}
-
-function foldBytes(bytes, width, mode, opts) {
- const rawMode = isSingleByteLocale() || decodeValidUtf8(bytes) == null;
- const text = rawMode ? Buffer.from(bytes).toString("latin1") : decodeValidUtf8(bytes);
- let out = "";
- for (const raw of text.split(/(?<=\n)/)) {
- out += foldLine(raw.endsWith("\n") ? raw.slice(0, -1) : raw, raw.endsWith("\n"), width, mode, opts);
- }
- return rawMode ? Buffer.from(out, "latin1") : out;
-}
-
-function normalizeFoldArgs(args) {
- const out = [];
- let scanning = true;
- let valueNext = false;
- for (const arg of args) {
- if (!scanning) {
- out.push(arg);
- } else if (valueNext) {
- out.push(arg);
- valueNext = false;
- } else if (arg === "-w" || arg === "--width") {
- out.push(arg);
- valueNext = true;
- } else if (/^-\d/.test(arg)) {
- out.push("-w", arg.slice(1));
- } else if (/^-[bcs]+\d/.test(arg)) {
- const match = arg.match(/^(-[bcs]+)(.*)$/);
- out.push(match[1], "-w", match[2]);
- } else {
- if (arg === "--") scanning = false;
- else if (!arg.startsWith("-")) scanning = false;
- out.push(arg);
- }
- }
- return out;
-}
-
-function foldMode(args) {
- let mode = "columns";
- let scanning = true;
- let valueNext = false;
- for (const arg of args) {
- if (!scanning) continue;
- if (valueNext) {
- valueNext = false;
- continue;
- }
- if (arg === "--") {
- scanning = false;
- } else if (arg === "-w" || arg === "--width") {
- valueNext = true;
- } else if (arg === "--bytes") {
- mode = "bytes";
- } else if (arg === "--characters") {
- mode = "characters";
- } else if (arg.startsWith("--width=")) {
- continue;
- } else if (arg.startsWith("--")) {
- continue;
- } else if (arg.startsWith("-")) {
- for (let i = 1; i < arg.length; i++) {
- const ch = arg[i];
- if (ch === "b") mode = "bytes";
- else if (ch === "c") mode = "characters";
- else if (ch === "w") break;
- }
- } else {
- scanning = false;
- }
- }
- return mode;
-}
-
-function parseFoldWidth(value) {
- const text = String(value);
- if (!/^\+?\d+$/.test(text)) throw new UsageError(`invalid number of columns: ${localeQuotedEscapedDiagnostic(text)}`);
- const width = BigInt(text.replace(/^\+/, ""));
- if (width <= 0n || width >= 18446744073709551610n) throw new UsageError(`invalid number of columns: ${localeQuotedEscapedDiagnostic(text)}: Numerical result out of range`);
- return width > BigInt(Number.MAX_SAFE_INTEGER) ? Number.POSITIVE_INFINITY : Number(width);
-}
-
-function foldLine(line, hasNewline, width, mode, opts) {
- let out = "";
- while (foldMeasure(line, mode) > width) {
- let cut = foldCutIndex(line, width, mode);
- if (cut >= line.length) break;
- if (opts.s || opts.spaces) {
- const prefix = line.slice(0, cut);
- const space = lastFoldBlankIndex(prefix);
- if (space > 0) cut = space + 1;
- }
- out += line.slice(0, cut) + "\n";
- line = line.slice(cut);
- }
- return out + line + (hasNewline ? "\n" : "");
-}
-
-function lastFoldBlankIndex(text) {
- let last = -1;
- for (let i = 0; i < text.length;) {
- const ch = [...text.slice(i)][0];
- if (isFoldBlank(ch)) last = i;
- i += ch.length;
- }
- return last;
-}
-
-function isFoldBlank(ch) {
- return ch === " " || ch === "\t" || (/\p{Zs}/u.test(ch) && ch !== "\u00A0" && ch !== "\u2007");
-}
-
-function foldMeasure(text, mode = "columns") {
- if (mode === "bytes") return enc.encode(text).byteLength;
- if (mode === "characters") return [...text].length;
- let column = 0;
- for (const ch of text) {
- if (ch === "\b") column = Math.max(0, column - 1);
- else if (ch === "\r") column = 0;
- else if (ch === "\t") column += 8 - (column % 8);
- else if (ch === "\f") column++;
- else column += displayWidth(ch);
- }
- return column;
-}
-
-function foldCutIndex(text, width, mode = "columns") {
- if (mode === "characters") return [...text].slice(0, width).join("").length;
- if (mode === "columns") return foldColumnCutIndex(text, width);
- let bytes = 0;
- let index = 0;
- for (const ch of text) {
- const next = bytes + enc.encode(ch).byteLength;
- if (next > width) break;
- bytes = next;
- index += ch.length;
- }
- return index || [...text][0]?.length || 0;
-}
-
-function foldColumnCutIndex(text, width) {
- let column = 0;
- let index = 0;
- for (let i = 0; i < text.length;) {
- const ch = [...text.slice(i)][0];
- let next;
- if (ch === "\b") next = Math.max(0, column - 1);
- else if (ch === "\r") next = 0;
- else if (ch === "\t") next = column + 8 - (column % 8);
- else if (ch === "\f") next = column + 1;
- else next = column + displayWidth(ch);
- if (next > width && index > 0) break;
- column = next;
- index += ch.length;
- i += ch.length;
- while (column >= width && i < text.length) {
- const trailing = [...text.slice(i)][0];
- if (foldColumnWidth(trailing, column) !== column) break;
- index += trailing.length;
- i += trailing.length;
- }
- if (column >= width) break;
- }
- return index || [...text][0]?.length || 0;
-}
-
-function foldColumnWidth(ch, column) {
- if (ch === "\b") return Math.max(0, column - 1);
- if (ch === "\r") return 0;
- if (ch === "\t") return column + 8 - (column % 8);
- if (ch === "\f") return column + 1;
- return column + displayWidth(ch);
-}
-
-async function tac(args) {
- const { opts, operands } = parseOptions(normalizeTacLongOptions(args), { short: { b: false, r: false, s: "value" }, long: { before: false, regex: false, separator: "value", help: false, version: false } });
- const sep = opts.s ?? opts.separator ?? "\n";
- const before = opts.b || opts.before;
- const regex = opts.r || opts.regex;
- if (regex && sep === "") throw new UsageError("separator cannot be empty");
- const files = operands.length ? operands : ["-"];
- const out = [];
- let failed = false;
- const cacheStdin = files.filter((file) => file === "-").length > 1 && stdinIsSeekable();
- let stdinBytes = null;
- for (const file of files) {
- let bytes;
- try {
- if (file === "-") {
- if (cacheStdin) {
- stdinBytes ??= await tacReadStdin();
- bytes = stdinBytes;
- } else {
- bytes = await tacReadStdin();
- }
- } else {
- bytes = await readAll(file);
- }
- } catch (error) {
- const message = error?.code === "EISDIR" || (file === "-" && error?.code === "EBADF")
- ? `${tacInputDiagnosticName(file)}: read error: ${systemErrorMessage(error)}`
- : file === "-"
- ? nodeErrorMessage(error)
- : `failed to open ${shellEscapeLsName(pathDisplayName(file), true)} for reading: ${systemErrorMessage(error)}`;
- stderr(`tac: ${message}\n`);
- failed = true;
- continue;
- }
- if (regex) {
- const decoded = isSingleByteLocale() ? null : decodeValidUtf8(bytes);
- const text = decoded ?? Buffer.from(bytes).toString("latin1");
- const result = tacRegexRecords(text, sep, before).join("");
- out.push(decoded == null ? Buffer.from(result, "latin1") : enc.encode(result));
- } else {
- out.push(tacBytes(bytes, sep, before));
- }
- }
- stdout(concatBytes(out));
- return failed ? 1 : 0;
-}
-
-async function tacReadStdin() {
- if (process.env.BNU_STDIN_CLOSED === "1") {
- const error = new Error("Bad file descriptor");
- error.code = "EBADF";
- throw error;
- }
- fstatSync(0);
- if (stdinIsSeekable()) return readAll("-");
- const chunks = [];
- const buffer = Buffer.allocUnsafe(64 * 1024);
- const inMemoryLimit = 1024 * 1024;
- let total = 0;
- while (total <= inMemoryLimit) {
- const n = readSync(0, buffer, 0, buffer.length, null);
- if (n === 0) return concatBytes(chunks);
- chunks.push(Buffer.from(buffer.subarray(0, n)));
- total += n;
- }
- const spool = await spoolInputToTemporaryFile("-", "bnu-tac", chunks);
- try {
- return await readAll(spool.path);
- } finally {
- await spool.cleanup();
- }
-}
-
-function tacInputDiagnosticName(file) {
- return file === "-" ? "'standard input'" : textInputDiagnosticName(file);
-}
-
-function tacBytes(bytes, sep, before = false) {
- return concatBytes(tacByteRecords(bytes, tacSeparatorBytes(sep), before).reverse());
-}
-
-function tacByteRecords(bytes, sep, before = false) {
- if (bytes.byteLength === 0) return [];
- const delimiter = sep.byteLength === 0 ? Uint8Array.of(0) : sep;
- const matches = byteSeparatorMatches(bytes, delimiter);
- const records = [];
- let start = 0;
- for (const match of matches) {
- if (before) {
- records.push(bytes.slice(start, match.start));
- start = match.start;
- } else {
- records.push(bytes.slice(start, match.end));
- start = match.end;
- }
- }
- if (start < bytes.length) records.push(bytes.slice(start));
- return records.filter((record) => record.byteLength !== 0);
-}
-
-function tacSeparatorBytes(sep) {
- const text = String(sep);
- if (text === "\uFFFD") return Uint8Array.of(0xe9);
- if (text === "\uFFFD\uFFFD") return Uint8Array.of(0xe9, 0xea);
- return enc.encode(text);
-}
-
-function byteSeparatorMatches(bytes, sep) {
- const matches = [];
- for (let i = 0; i <= bytes.byteLength - sep.byteLength;) {
- let found = true;
- for (let j = 0; j < sep.byteLength; j++) {
- if (bytes[i + j] !== sep[j]) {
- found = false;
- break;
- }
- }
- if (found) {
- matches.push({ start: i, end: i + sep.byteLength });
- i += sep.byteLength;
- } else {
- i++;
- }
- }
- return matches;
-}
-
-function tacRecords(text, sep, before = false, regex = false) {
- if (text === "") return [];
- const matches = tacSeparatorMatches(text, sep === "" && !regex ? "\0" : sep, regex);
- const records = [];
- let start = 0;
- for (const match of matches) {
- if (before) {
- records.push(text.slice(start, match.start));
- start = match.start;
- } else {
- records.push(text.slice(start, match.end));
- start = match.end;
- }
- }
- if (start < text.length) records.push(text.slice(start));
- return records.filter((record) => record !== "");
-}
-
-function tacSeparatorMatches(text, sep, regex = false) {
- if (!regex) {
- const matches = [];
- let start = 0;
- let index;
- while ((index = text.indexOf(sep, start)) !== -1) {
- matches.push({ start: index, end: index + sep.length });
- start = index + sep.length;
- }
- return matches;
- }
- let pattern;
- try {
- pattern = new RegExp(tacRegexPattern(sep), "gm");
- } catch {
- throw new UsageError("Invalid regular expression");
- }
- return [...text.matchAll(pattern)].map((match) => ({ start: match.index, end: match.index + match[0].length }));
-}
-
-function tacRegexRecords(text, sep, before = false) {
- if (text === "") return [];
- const source = tacRegexPattern(sep);
- let pattern;
- let endPattern;
- try {
- pattern = new RegExp(source, "gm");
- endPattern = new RegExp(`(?:${source})(?![\\s\\S])`, "m");
- } catch {
- throw new UsageError("Invalid regular expression");
- }
- const ending = tacRegexMatchEndingAt(endPattern, text, text.length);
- if (!ending || ending.start === ending.end) return tacRecords(text, sep, before, true).reverse();
- const fallbackRecords = () => tacRecords(text, sep, before, true).reverse();
- const records = [];
- let cursor = text.length;
- while (cursor > 0) {
- const match = tacRegexMatchEndingAt(endPattern, text, cursor);
- if (!match || match.start === match.end) {
- records.push(text.slice(0, cursor));
- break;
- }
- if (match.start > 0 && !tacRegexMatchEndingAt(endPattern, text, match.start)) {
- if (records.length === 0) return fallbackRecords();
- records.push(text.slice(0, cursor));
- break;
- }
- records.push(text.slice(match.start, cursor));
- cursor = match.start;
- }
- return records.filter((record) => record !== "");
-}
-
-function tacRegexMatchEndingAt(pattern, text, end) {
- pattern.lastIndex = 0;
- const slice = text.slice(0, end);
- const match = pattern.exec(slice);
- return match ? { start: match.index, end: match.index + match[0].length } : null;
-}
-
-function tacRegexPattern(sep) {
- let out = "";
- let lastAtomKind = null;
- for (let i = 0; i < sep.length; i++) {
- const ch = sep[i];
- if (ch === "\\") {
- const next = sep[++i];
- if (next == null) out += ch;
- else if ("()|".includes(next)) out += next;
- else if ("+?{}".includes(next)) out += `\\${next}`;
- else out += ch + next;
- lastAtomKind = "literal";
- } else if (ch === "[") {
- const end = sep.indexOf("]", i + 1);
- if (end === -1) {
- out += ch;
- lastAtomKind = null;
- } else {
- out += sep.slice(i, end + 1);
- i = end;
- lastAtomKind = "bracket";
- }
- } else if (ch === "+" || ch === "?") {
- if (!tacRegexHasPreviousAtom(out)) {
- out += `\\${ch}`;
- lastAtomKind = "literal";
- } else if (lastAtomKind !== "literal" && lastAtomKind !== "bracket") {
- out += ch;
- }
- } else if ("()|{}+?".includes(ch)) {
- out += `\\${ch}`;
- lastAtomKind = "literal";
- } else {
- out += ch;
- lastAtomKind = ch === "." || ch === "_" ? "repeatable" : "literal";
- }
- }
- return out;
-}
-
-function tacRegexHasPreviousAtom(pattern) {
- if (pattern === "" || pattern.endsWith("|") || pattern.endsWith("(")) return false;
- return true;
-}
-
-const PRINTF_STOP = "\uE000PRINTF_STOP\uE000";
-const PRINTF_RAW_BYTE_BASE = 0xe100;
-
-function formatPrintf(format, values, warnings = []) {
- return formatPrintfResult(format, values, warnings).text;
-}
-
-function formatPrintfResult(format, values, warnings = []) {
- let sequentialIndex = 0;
- let highestReferenced = 0;
- let status = 0;
- let fatal = false;
- let text = "";
- const takeArg = (index) => {
- const argIndex = index == null ? sequentialIndex++ : index - 1;
- highestReferenced = Math.max(highestReferenced, argIndex + 1);
- return { value: values[argIndex], missing: argIndex >= values.length };
- };
- for (let i = 0; i < format.length;) {
- if (format[i] === "\\") {
- const escape = parsePrintfEscape(format, i);
- text += escape.text;
- i += escape.length;
- continue;
- }
- if (format[i] !== "%") {
- text += format[i++];
- continue;
- }
- const conv = parsePrintfConversion(format, i);
- if (conv.percent) {
- text += "%";
- i += conv.length;
- continue;
- }
- let { flags, width, precision, type } = conv;
- if (width?.star) {
- const parsed = parsePrintfControlNumber(takeArg(width.index).value, warnings, "field width");
- if (!parsed.ok) status = 1;
- if (parsed.fatal) fatal = true;
- width = parsed.value;
- if (width < 0) {
- flags += "-";
- width = Math.abs(width);
- }
- }
- if (precision?.star) {
- const parsed = parsePrintfControlNumber(takeArg(precision.index).value, warnings, "precision");
- if (!parsed.ok) status = 1;
- if (parsed.fatal) fatal = true;
- precision = parsed.value < 0 ? undefined : parsed.value;
- }
- width = width?.value ?? width;
- precision = precision?.value ?? precision;
- if (width != null) width = Number(width);
- if (precision != null) precision = Number(precision);
- const arg = takeArg(conv.index);
- const value = arg.value ?? "";
- let rendered;
- if (type === "b") rendered = String(value).replace(/\\(U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|0[0-7]{0,3}|[0-7]{1,3}|x[0-9a-fA-F]{1,2}|[abcefnrtv\\])/g, (_, e) => decodeEscape(e));
- else if (type === "q") rendered = pad(shellQuote(String(value)), width, flags);
- else if (type === "s") {
- const valueText = precision == null ? String(value) : String(value).slice(0, Number(precision));
- rendered = pad(valueText, width, flags);
- }
- else if (type === "c") rendered = pad(String(value)[0] ?? "\0", width, flags);
- else {
- const beforeWarnings = warnings.length;
- const n = arg.missing ? 0 : parsePrintfNumber(value, warnings, type);
- if (warnings.length !== beforeWarnings) status = 1;
- let out;
- if ("diuoxX".includes(type)) {
- let int = typeof n === "bigint" ? n : BigInt(Math.trunc(n || 0));
- if ("di".includes(type)) {
- const min = -(1n << 63n);
- const max = (1n << 63n) - 1n;
- if (int < min || int > max) {
- warnings.push(`printf: ${localeQuotedEscapedDiagnostic(value)}: Numerical result out of range`);
- status = 1;
- int = int < min ? min : max;
- }
- } else if (int > (1n << 64n) - 1n) {
- warnings.push(`printf: ${localeQuotedEscapedDiagnostic(value)}: Numerical result out of range`);
- status = 1;
- int = (1n << 64n) - 1n;
- }
- const unsigned = "uoxX".includes(type) && int < 0n ? BigInt.asUintN(64, int) : null;
- const sign = unsigned == null && int < 0n ? "-" : flags.includes("+") && "di".includes(type) ? "+" : flags.includes(" ") && "di".includes(type) ? " " : "";
- const magnitude = unsigned ?? (int < 0n ? -int : int);
- const rawDigits = precision === 0 && magnitude === 0n
- ? ""
- : type === "o"
- ? magnitude.toString(8)
- : type === "x"
- ? magnitude.toString(16)
- : type === "X"
- ? magnitude.toString(16).toUpperCase()
- : String(magnitude);
- const digits = applyIntegerPrecision(rawDigits, precision);
- const prefix = flags.includes("#") && type === "o" && !digits.startsWith("0")
- ? "0"
- : flags.includes("#") && type === "x" && magnitude !== 0n
- ? "0x"
- : flags.includes("#") && type === "X" && magnitude !== 0n
- ? "0X"
- : "";
- out = formatPrintfInteger(sign, prefix, digits, width, flags, precision);
- if (precision != null) flags = flags.replace("0", "");
- }
- else out = formatPrintfFloat(n ?? 0, type, precision, flags);
- rendered = "diuoxX".includes(type) ? out : pad(out, width, flags);
- }
- text += rendered;
- i += conv.length;
- }
- return { text: fatal ? "" : text, consumed: Math.max(sequentialIndex, highestReferenced), status, fatal };
-}
-
-function parsePrintfEscape(format, offset) {
- const rest = format.slice(offset + 1);
- const match = rest.match(/^(U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|[0-7]{1,3}|x[0-9a-fA-F]{1,2}|[abcefnrtv\\])/);
- if (!match) return { text: format[offset], length: 1 };
- return { text: decodeEscape(match[1]), length: 1 + match[1].length };
-}
-
-function parsePrintfConversion(format, offset) {
- if (format[offset + 1] === "%") return { percent: true, length: 2 };
- if (format[offset + 1] === "(") return { invalid: "%(", length: 2 };
- let i = offset + 1;
- let index;
- const indexMatch = format.slice(i).match(/^(\d+)\$/);
- if (indexMatch) {
- index = Number(indexMatch[1]);
- i += indexMatch[0].length;
- }
- const flagsStart = i;
- while (/[0 +'#-]/.test(format[i] ?? "")) i++;
- const flags = format.slice(flagsStart, i);
- let width;
- if (format[i] === "*") {
- i++;
- const widthIndex = format.slice(i).match(/^(\d+)\$/);
- if (widthIndex) {
- width = { star: true, index: Number(widthIndex[1]) };
- i += widthIndex[0].length;
- } else {
- width = { star: true };
- }
- } else {
- const widthMatch = format.slice(i).match(/^\d+/);
- if (widthMatch) {
- width = { value: widthMatch[0] };
- i += widthMatch[0].length;
- }
- }
- let precision;
- if (format[i] === ".") {
- i++;
- if (format[i] === "*") {
- i++;
- const precisionIndex = format.slice(i).match(/^(\d+)\$/);
- if (precisionIndex) {
- precision = { star: true, index: Number(precisionIndex[1]) };
- i += precisionIndex[0].length;
- } else {
- precision = { star: true };
- }
- } else {
- const precisionMatch = format.slice(i).match(/^\d*/)[0];
- precision = { value: precisionMatch === "" ? "0" : precisionMatch };
- i += precisionMatch.length;
- }
- }
- if (format[i] === "L") i++;
- const type = format[i];
- if (!/[abcdeEfFgiGosuxXAq]/.test(type ?? "")) {
- const dollar = format.slice(offset, i + 1).match(/^%.*?\$/);
- const invalid = dollar?.[0] ?? (format.slice(offset).match(/^%[^A-Za-z%]*[A-Za-z]/)?.[0] ?? "%");
- return { invalid, length: invalid.length };
- }
- return { length: i - offset + 1, index, flags, width, precision, type };
-}
-
-function applyIntegerPrecision(digits, precision) {
- if (precision == null) return digits;
- return digits.padStart(Number(precision), "0");
-}
-
-function formatPrintfInteger(sign, prefix, digits, width, flags = "", precision = undefined) {
- const value = `${sign}${prefix}${digits}`;
- const n = Number(width);
- if (!Number.isInteger(n) || value.length >= n) return value;
- const padding = " ".repeat(n - value.length);
- if (flags.includes("-")) return value + padding;
- if (flags.includes("0") && precision == null) return `${sign}${prefix}${"0".repeat(n - value.length)}${digits}`;
- return padding + value;
-}
-
-function formatPrintfFloat(value, type, precision, flags = "") {
- const p = precision == null ? 6 : Number(precision);
- const uppercase = type === "A" || type === "E" || type === "F" || type === "G";
- if (typeof value === "object" && value?.special === "nan") {
- const out = `${value.negative ? "-" : ""}nan`;
- return uppercase ? out.toUpperCase() : out;
- }
- if (typeof value === "object" && value?.special === "decimal-overflow") {
- return formatPrintfDecimalOverflow(value, type, p);
- }
- if (Number.isNaN(value)) return uppercase ? "NAN" : "nan";
- if (!Number.isFinite(value)) {
- const out = value < 0 ? "-inf" : "inf";
- return uppercase ? out.toUpperCase() : out;
- }
- if (type === "e" || type === "E") {
- const out = value.toExponential(p).replace(/e([+-])(\d)$/i, "e$10$2");
- return type === "E" ? out.toUpperCase() : out;
- }
- if (type === "a" || type === "A") return formatPrintfHexFloat(value, type, precision, flags.includes("#"));
- if (type === "g" || type === "G") {
- const out = value.toPrecision(p).replace(/(\.\d*?)0+(e|$)/i, "$1$2").replace(/\.(e|$)/i, "$1").replace(/e([+-])(\d)$/i, "e$10$2");
- return type === "G" ? out.toUpperCase() : out;
- }
- return value.toFixed(p);
-}
-
-function formatPrintfHexFloat(value, type, precision, alternate = false) {
- const uppercase = type === "A";
- const negative = Object.is(value, -0) || value < 0;
- const abs = Math.abs(value);
- if (abs === 0) {
- const fraction = precision == null ? "" : "0".repeat(Number(precision));
- const point = alternate || fraction ? "." : "";
- return `${negative ? "-" : ""}${uppercase ? "0X" : "0x"}0${point}${fraction}${uppercase ? "P" : "p"}+0`;
- }
- const requested = precision == null ? 13 : Number(precision);
- let exponent = Math.floor(Math.log2(abs)) - 3;
- let scaled = abs / 2 ** exponent;
- while (scaled < 8) {
- scaled *= 2;
- exponent--;
- }
- while (scaled >= 16) {
- scaled /= 2;
- exponent++;
- }
- const rounded = roundedHexFloatDigits(scaled, requested);
- let digits = rounded.digits;
- if (rounded.carry) exponent++;
- let head = digits[0];
- let fraction = digits.slice(1);
- if (precision == null) fraction = fraction.replace(/0+$/, "");
- const point = alternate || fraction ? "." : "";
- let out = `${negative ? "-" : ""}0x${head}${point}${fraction}p${exponent < 0 ? "" : "+"}${exponent}`;
- return uppercase ? out.toUpperCase() : out;
-}
-
-function roundedHexFloatDigits(value, precision) {
- const count = precision + 1;
- const digits = [];
- let rest = value;
- for (let i = 0; i < count + 1; i++) {
- const digit = Math.floor(rest);
- digits.push(Math.max(0, Math.min(15, digit)));
- rest = (rest - digit) * 16;
- }
- if (digits[count] >= 8) {
- let carry = 1;
- for (let i = count - 1; i >= 0 && carry; i--) {
- const next = digits[i] + carry;
- digits[i] = next & 0xf;
- carry = next > 0xf ? 1 : 0;
- }
- if (carry) {
- digits.unshift(1);
- digits.length = count;
- return { digits: digits.map((digit) => digit.toString(16)).join(""), carry: true };
- }
- }
- return { digits: digits.slice(0, count).map((digit) => digit.toString(16)).join(""), carry: false };
-}
-
-function formatPrintfDecimalOverflow(value, type, precision) {
- const significant = type === "e" || type === "E" ? precision + 1 : Math.max(precision, 1);
- const rounded = roundDecimalOverflowDigits(value.digits, value.exponent, significant);
- const expText = `${rounded.exponent < 0 ? "-" : "+"}${String(Math.abs(rounded.exponent)).padStart(2, "0")}`;
- let body;
- if (type === "e" || type === "E") {
- const rest = rounded.digits.slice(1).padEnd(precision, "0");
- body = `${rounded.digits[0]}${precision > 0 ? `.${rest}` : ""}e${expText}`;
- } else {
- const rest = rounded.digits.slice(1).replace(/0+$/, "");
- body = `${rounded.digits[0]}${rest ? `.${rest}` : ""}e${expText}`;
- }
- if (value.negative) body = `-${body}`;
- return type === "E" || type === "G" ? body.toUpperCase() : body;
-}
-
-function roundDecimalOverflowDigits(digits, exponent, significant) {
- let kept = digits.slice(0, significant).padEnd(significant, "0");
- const next = Number(digits[significant] ?? "0");
- if (next >= 5) {
- let carry = 1;
- const chars = [...kept];
- for (let i = chars.length - 1; i >= 0 && carry; i--) {
- const n = Number(chars[i]) + carry;
- chars[i] = String(n % 10);
- carry = n >= 10 ? 1 : 0;
- }
- kept = carry ? `1${chars.join("")}` : chars.join("");
- if (carry) exponent++;
- }
- return { digits: kept.slice(0, significant), exponent };
-}
-
-function parsePrintfControlNumber(value, warnings, kind = "number") {
- if (value === undefined) return { ok: true, value: 0 };
- const text = String(value ?? "");
- const warningCount = warnings.length;
- const n = parsePrintfIntegerNumber(text, warnings);
- const ok = warnings.length === warningCount;
- if (n > 2147483647n || n < -2147483648n) {
- warnings.push(kind === "number" ? `printf: invalid number: ${localeQuotedEscapedDiagnostic(text)}` : `printf: invalid ${kind}: ${localeQuotedEscapedDiagnostic(text)}`);
- return { ok: false, value: 0, fatal: true };
- }
- return { ok, value: Number(n) };
-}
-
-function parsePrintfNumber(value, warnings, type = "") {
- const text = String(value ?? "");
- if (text.startsWith("'") || text.startsWith('"')) {
- const chars = [...text.slice(1)];
- if (chars.length >= 1) {
- if (chars.length > 1) warnings.push(`printf: warning: ${chars[1]}: character(s) following character constant have been ignored`);
- return chars[0] === "\uFFFD" ? 0xe1 : chars[0].codePointAt(0);
- }
- warnings.push(`printf: ${localeQuotedEscapedDiagnostic(text)}: expected a numeric value`);
- return 0;
- }
- if ("diuoxX".includes(type)) return parsePrintfIntegerNumber(text, warnings);
- if (/^[+-]?(?:inf(?:inity)?|nan)$/i.test(text)) return parsePrintfSpecialFloat(text);
- const exactBaseLiteral = text.match(/^[+-]?0[xX][0-9a-fA-F]+$/) || text.match(/^[+-]?0[bB][01]+$/);
- if (exactBaseLiteral) return Number(text);
- const match = text.match(/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/);
- if (!match) {
- warnings.push(`printf: ${localeQuotedEscapedDiagnostic(text)}: expected a numeric value`);
- return 0;
- }
- const n = Number(match[0]);
- if (match[0].length !== text.length) warnings.push(`printf: ${localeQuotedEscapedDiagnostic(text)}: value not completely converted`);
- if (!Number.isFinite(n) && "eEgG".includes(type)) return parsePrintfDecimalOverflow(match[0]);
- return n;
-}
-
-function parsePrintfDecimalOverflow(text) {
- const negative = text.startsWith("-");
- const unsigned = text.replace(/^[+-]/, "");
- const [mantissaText, exponentText = "0"] = unsigned.split(/[eE]/);
- const point = mantissaText.indexOf(".");
- const fractionalDigits = point === -1 ? 0 : mantissaText.length - point - 1;
- let digits = mantissaText.replace(".", "").replace(/^0+/, "");
- if (digits === "") digits = "0";
- let exponent = Number(exponentText) - fractionalDigits + digits.length - 1;
- if (digits === "0") exponent = 0;
- return { special: "decimal-overflow", negative, digits, exponent };
-}
-
-function parsePrintfIntegerNumber(text, warnings) {
- const signMatch = text.match(/^[+-]?/)?.[0] ?? "";
- const rest = text.slice(signMatch.length);
- let digits;
- let base = 10;
- let consumed = signMatch.length;
- if (/^0[xX]/.test(rest)) {
- base = 16;
- digits = rest.slice(2).match(/^[0-9a-fA-F]*/)?.[0] ?? "";
- consumed += 2 + digits.length;
- if (digits === "") {
- warnings.push(`printf: ${localeQuotedEscapedDiagnostic(text)}: value not completely converted`);
- return 0;
- }
- } else if (/^0[bB]/.test(rest)) {
- base = 2;
- digits = rest.slice(2).match(/^[01]*/)?.[0] ?? "";
- consumed += 2 + digits.length;
- if (digits === "") {
- warnings.push(`printf: ${localeQuotedEscapedDiagnostic(text)}: value not completely converted`);
- return 0;
- }
- } else if (rest.startsWith("0")) {
- base = 8;
- digits = rest.match(/^[0-7]*/)?.[0] ?? "0";
- consumed += digits.length;
- } else {
- digits = rest.match(/^\d*/)?.[0] ?? "";
- consumed += digits.length;
- if (digits === "") {
- warnings.push(`printf: ${localeQuotedEscapedDiagnostic(text)}: expected a numeric value`);
- return 0;
- }
- }
- if (consumed !== text.length) warnings.push(`printf: ${localeQuotedEscapedDiagnostic(text)}: value not completely converted`);
- const magnitude = parseBigIntBase(digits || "0", base);
- return signMatch === "-" ? -magnitude : magnitude;
-}
-
-function parseBigIntBase(digits, base) {
- let value = 0n;
- const bigBase = BigInt(base);
- for (const digit of digits) value = value * bigBase + BigInt(Number.parseInt(digit, base));
- return value;
-}
-
-function parsePrintfSpecialFloat(text) {
- if (/nan/i.test(text)) return { special: "nan", negative: text.startsWith("-") };
- return text.startsWith("-") ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
-}
-
-function shellQuote(value) {
- if (value === "") return "''";
- if (/[\u0080-\u009f]/.test(value)) return shellQuoteBytes(enc.encode(value));
- if (process.env.LC_ALL === "C" && /[^\x00-\x7f]/.test(value)) return shellQuoteBytes(enc.encode(value));
- if (/^[A-Za-z0-9_@%+=:,./~-]+$/.test(value) && !value.startsWith("~")) return value;
- if (/^[^\s"'\\$`;&|()<>{}!*?\[\]#]+$/u.test(value) && !value.startsWith("~")) return value;
- if (/[\x00-\x1f\x7f]/.test(value)) return shellQuoteControl(value);
- if (!value.includes("'")) return `'${value}'`;
- return `"${value.replace(/(["\\$`])/g, "\\$1")}"`;
-}
-
-function shellQuoteControl(value) {
- let out = "";
- let segment = "";
- const flush = () => {
- if (segment) {
- out += `'${segment}'`;
- segment = "";
- } else if (!out) {
- out += "''";
- }
- };
- for (const ch of value) {
- const code = ch.codePointAt(0);
- if (ch === "'") {
- flush();
- out += "\\'''";
- } else if (code < 0x20 || code === 0x7f) {
- flush();
- out += `$'${shellEscapeByte(code)}'`;
- } else {
- segment += ch;
- }
- }
- flush();
- return out;
-}
-
-function shellQuoteBytes(bytes) {
- return `''$'${[...bytes].map(shellEscapeByte).join("")}'`;
-}
-
-function shellEscapeByte(byte) {
- if (byte === 7) return "\\a";
- if (byte === 8) return "\\b";
- if (byte === 9) return "\\t";
- if (byte === 10) return "\\n";
- if (byte === 13) return "\\r";
- return `\\${byte.toString(8).padStart(3, "0")}`;
-}
-
-function decodeEscape(escape) {
- const simple = { a: "\x07", b: "\b", c: PRINTF_STOP, e: "\x1b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\" };
- if (simple[escape] != null) return simple[escape];
- if (escape.startsWith("x")) return printfRawByte(Number.parseInt(escape.slice(1), 16));
- if (escape.startsWith("u") || escape.startsWith("U")) return String.fromCodePoint(Number.parseInt(escape.slice(1), 16));
- return printfRawByte(Number.parseInt(escape, 8));
-}
-
-function printfRawByte(byte) {
- return String.fromCharCode(PRINTF_RAW_BYTE_BASE + (byte & 0xff));
-}
-
-function encodePrintfOutput(text) {
- const chunks = [];
- for (const ch of text) {
- const code = ch.codePointAt(0);
- chunks.push(code >= PRINTF_RAW_BYTE_BASE && code <= PRINTF_RAW_BYTE_BASE + 0xff ? Uint8Array.of(code - PRINTF_RAW_BYTE_BASE) : enc.encode(ch));
- }
- return concatBytes(chunks);
-}
-
-function validatePrintfFormat(format) {
- for (let i = 0; i < format.length; i++) {
- const ch = format[i];
- if (ch === "\\") {
- const rest = format.slice(i + 1);
- if (rest.startsWith("x")) {
- const hex = rest.slice(1).match(/^[0-9a-fA-F]*/)[0];
- if (hex.length === 0) return { ok: false, message: "printf: missing hexadecimal number in escape" };
- i += 1 + hex.length;
- } else if (/^[uU]/.test(rest)) {
- const need = rest[0] === "u" ? 4 : 8;
- const hex = rest.slice(1, 1 + need);
- if (hex.length < need || !/^[0-9a-fA-F]+$/.test(hex)) return { ok: false, message: "printf: missing hexadecimal number in escape" };
- const code = Number.parseInt(hex, 16);
- if (code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return { ok: false, message: `printf: invalid universal character name \\${rest[0]}${hex}` };
- i += 1 + need;
- } else if (/^[0-7]/.test(rest)) {
- i += Math.min(rest.match(/^[0-7]{1,3}/)[0].length, 3);
- } else if (rest) {
- i++;
- }
- continue;
- }
- if (ch !== "%") continue;
- const conv = parsePrintfConversion(format, i);
- if (conv.invalid) return { ok: false, message: `printf: ${conv.invalid}: invalid conversion specification` };
- if (conv.percent) {
- i += conv.length - 1;
- continue;
- }
- const token = format.slice(i, i + conv.length);
- const { flags = "", precision, type } = conv;
- const invalid =
- (flags.includes("'") && !["d", "i", "u", "f", "F", "g", "G"].includes(type)) ||
- (type === "d" && flags.includes("#")) ||
- (["b", "c", "q", "s"].includes(type) && flags.includes("0")) ||
- (type === "c" && precision != null) ||
- (type === "q" && (flags !== "" || conv.width != null || precision != null));
- if (invalid) return { ok: false, message: `printf: ${token}: invalid conversion specification` };
- i += conv.length - 1;
- }
- return { ok: true };
-}
-
-function pad(value, width, flags = "") {
- const n = Number(width);
- if (!Number.isInteger(n) || value.length >= n) return value;
- const fill = flags.includes("0") && !flags.includes("-") ? "0" : " ";
- return flags.includes("-") ? value.padEnd(n, " ") : value.padStart(n, fill);
-}
-
-async function printfCmd(args) {
- if (args[0] === "--") args = args.slice(1);
- if (!args.length) throw new UsageError("missing operand", true);
- const [format, ...values] = args;
- const validation = validatePrintfFormat(format);
- if (!validation.ok) {
- stderr(`${validation.message}\n`);
- return 1;
- }
- const streamedStatus = streamLargeSimplePrintf(format, values);
- if (streamedStatus != null) return streamedStatus;
- let out = "";
- let stop = false;
- const warnings = [];
- const append = (text) => {
- const idx = text.indexOf(PRINTF_STOP);
- if (idx === -1) {
- out += text;
- return;
- }
- out += text.slice(0, idx);
- stop = true;
- };
- if (!values.length) append(formatPrintf(format, [], warnings));
- else if (countPrintfConversions(format) === 0) {
- append(formatPrintf(format, [], warnings));
- warnings.push(`printf: warning: ignoring excess arguments, starting with '${values[0]}'`);
- }
- else {
- let status = 0;
- for (let i = 0; i < values.length && !stop;) {
- const before = i;
- const rendered = formatPrintfResult(format, values.slice(i), warnings);
- status ||= rendered.status;
- append(rendered.text);
- i += Math.max(1, rendered.consumed);
- if (i === before) break;
- }
- if (warnings.length) stderr(`${warnings.join("\n")}\n`);
- stdout(encodePrintfOutput(out));
- return status;
- }
- if (warnings.length) stderr(`${warnings.join("\n")}\n`);
- stdout(encodePrintfOutput(out));
- return 0;
-}
-
-function streamLargeSimplePrintf(format, values) {
- if (!format.startsWith("%")) return null;
- const conversion = parsePrintfConversion(format, 0);
- if (conversion.invalid || conversion.percent || conversion.length !== format.length || conversion.index != null) return null;
- if (conversion.width?.star || conversion.precision?.star) return null;
- const width = Number(conversion.width?.value);
- if (!Number.isSafeInteger(width) || width < 1024 * 1024 || conversion.flags?.includes("0")) return null;
- const precision = conversion.precision?.value;
- const coreFormat = `%${conversion.flags ?? ""}${precision == null ? "" : `.${precision}`}${conversion.type}`;
- const warnings = [];
- let status = 0;
- let index = 0;
- const iterations = values.length ? Infinity : 1;
- for (let iteration = 0; iteration < iterations && (values.length === 0 ? iteration === 0 : index < values.length); iteration++) {
- const rendered = formatPrintfResult(coreFormat, values.slice(index), warnings);
- status ||= rendered.status;
- if (rendered.fatal) break;
- const padding = Math.max(0, width - rendered.text.length);
- if (conversion.flags?.includes("-")) {
- stdout(encodePrintfOutput(rendered.text));
- writePrintfPadding(padding, 0x20);
- } else {
- writePrintfPadding(padding, 0x20);
- stdout(encodePrintfOutput(rendered.text));
- }
- if (!values.length) break;
- index += Math.max(1, rendered.consumed);
- }
- if (warnings.length) stderr(`${warnings.join("\n")}\n`);
- return status;
-}
-
-function writePrintfPadding(length, byte) {
- if (length <= 0) return;
- const block = Buffer.alloc(Math.min(64 * 1024, length), byte);
- let remaining = length;
- while (remaining > 0) {
- const count = Math.min(block.length, remaining);
- stdout(count === block.length ? block : block.subarray(0, count));
- remaining -= count;
- }
-}
-
-function countPrintfConversions(format) {
- let count = 0;
- for (let i = 0; i < format.length;) {
- if (format[i] === "\\") {
- i += parsePrintfEscape(format, i).length;
- } else if (format[i] === "%") {
- const conv = parsePrintfConversion(format, i);
- if (!conv.percent && !conv.invalid) count++;
- i += conv.length || 1;
- } else {
- i++;
- }
- }
- return count;
-}
-
-function factorize(value) {
- let n = BigInt(value);
- if (n < 0n) n = -n;
- if (n <= 1n) return [];
- const factors = [];
- for (const d of [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n]) {
- while (n % d === 0n) {
- factors.push(d);
- n /= d;
- }
- }
- if (n > 1n) factorBigInt(n, factors);
- return factors.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
-}
-
-function factorBigInt(n, factors) {
- if (n === 1n) return;
- if (isProbablePrime(n)) {
- factors.push(n);
- return;
- }
- const nearDouble = factorNearDoubleSemiprime(n);
- if (nearDouble != null) {
- factorBigInt(nearDouble, factors);
- factorBigInt(n / nearDouble, factors);
- return;
- }
- // A high-bound p-1 pass is useful for very large residuals with smooth
- // predecessor factors, but it is disproportionately expensive across a
- // contiguous range of 96-bit values. Pollard rho is the better first
- // strategy below this threshold.
- const pMinusOne = n >= 1_000_000_000_000_000_000_000_000_000_000n
- ? pollardPMinusOne(n, 500_000)
- : n >= (1n << 72n)
- ? pollardPMinusOne(n, 100_000)
- : null;
- if (pMinusOne != null) {
- factorBigInt(pMinusOne, factors);
- factorBigInt(n / pMinusOne, factors);
- return;
- }
- const divisor = pollardRho(n);
- factorBigInt(divisor, factors);
- factorBigInt(n / divisor, factors);
-}
-
-function bigintGcd(a, b) {
- while (b !== 0n) {
- const t = a % b;
- a = b;
- b = t;
- }
- return a < 0n ? -a : a;
-}
-
-function modPow(base, exponent, mod) {
- let result = 1n;
- base %= mod;
- while (exponent > 0n) {
- if (exponent & 1n) result = (result * base) % mod;
- base = (base * base) % mod;
- exponent >>= 1n;
- }
- return result;
-}
-
-function factorNearDoubleSemiprime(n) {
- if (n < 1_000_000_000_000_000_000n) return null;
- for (let delta = -4096n; delta <= 4096n; delta++) {
- const discriminant = delta * delta + 8n * n;
- const root = bigintSqrt(discriminant);
- if (root * root !== discriminant) continue;
- const numerator = root - delta;
- if (numerator % 4n !== 0n) continue;
- const factor = numerator / 4n;
- if (factor > 1n && factor < n && n % factor === 0n) return factor;
- }
- return null;
-}
-
-function pollardPMinusOne(n, bound) {
- let a = 2n;
- let sinceGcd = 0;
- for (const p of primesUpTo(bound)) {
- let power = p;
- while (power <= Math.floor(bound / p)) power *= p;
- a = modPow(a, BigInt(power), n);
- if (++sinceGcd < 256) continue;
- sinceGcd = 0;
- const d = bigintGcd(a - 1n, n);
- if (d > 1n && d < n) return d;
- if (d === n) return null;
- }
- const d = bigintGcd(a - 1n, n);
- return d > 1n && d < n ? d : null;
-}
-
-function bigintSqrt(n) {
- if (n < 2n) return n;
- let x = 1n << BigInt(Math.ceil(n.toString(2).length / 2));
- for (;;) {
- const y = (x + n / x) >> 1n;
- if (y >= x) return x;
- x = y;
- }
-}
-
-function isProbablePrime(n) {
- if (n < 2n) return false;
- for (const p of [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n]) {
- if (n === p) return true;
- if (n % p === 0n) return false;
- }
- let d = n - 1n;
- let s = 0n;
- while ((d & 1n) === 0n) {
- d >>= 1n;
- s++;
- }
- const bases = n < (1n << 128n) ? [2n, 3n, 5n, 7n, 11n, 13n, 17n] : [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n];
- for (const a of bases) {
- if (a >= n - 2n) continue;
- let x = modPow(a, d, n);
- if (x === 1n || x === n - 1n) continue;
- let composite = true;
- for (let r = 1n; r < s; r++) {
- x = (x * x) % n;
- if (x === n - 1n) {
- composite = false;
- break;
- }
- }
- if (composite) return false;
- }
- return true;
-}
-
-function pollardRho(n) {
- if (n % 2n === 0n) return 2n;
- const preferredConstants = [13n, 3n, 1n, 22n, 11n, 4n, 15n, 5n, 7n, 2n, 17n, 19n, 26n];
- for (let attempt = 0; ; attempt++) {
- const c = attempt < preferredConstants.length ? preferredConstants[attempt] : BigInt(attempt + 1);
- let y = 2n;
- let d = 1n;
- let r = 1;
- let q = 1n;
- let x = 0n;
- let ys = 0n;
- const f = (v) => (v * v + c) % n;
- while (d === 1n) {
- x = y;
- for (let i = 0; i < r; i++) y = f(y);
- let k = 0;
- while (k < r && d === 1n) {
- ys = y;
- const limit = Math.min(256, r - k);
- for (let i = 0; i < limit; i++) {
- y = f(y);
- const diff = x > y ? x - y : y - x;
- q = (q * diff) % n;
- }
- d = bigintGcd(q, n);
- k += 256;
- }
- r *= 2;
- if (r > 2_000_000 && d === 1n) break;
- }
- if (d === n) {
- do {
- ys = f(ys);
- d = bigintGcd(x > ys ? x - ys : ys - x, n);
- } while (d === 1n);
- }
- if (d > 1n && d < n) return d;
- if (attempt === preferredConstants.length - 1 && n > 1_000_000_000_000_000_000_000_000n) {
- const pPlusOne = pollardPPlusOne(n, 11_000_000, 6n);
- if (pPlusOne != null) return pPlusOne;
- }
- }
-}
-
-function pollardPPlusOne(n, bound, parameter) {
- let v = parameter;
- for (const p of primesUpTo(bound)) {
- let power = p;
- while (power <= Math.floor(bound / p)) power *= p;
- v = lucasV(v, BigInt(power), n);
- }
- const d = bigintGcd(v - 2n, n);
- return d > 1n && d < n ? d : null;
-}
-
-function lucasV(parameter, exponent, mod) {
- let vk = 2n % mod;
- let vk1 = parameter % mod;
- for (const bit of exponent.toString(2)) {
- const v2k = positiveMod(vk * vk - 2n, mod);
- const v2k1 = positiveMod(vk * vk1 - parameter, mod);
- if (bit === "0") {
- vk = v2k;
- vk1 = v2k1;
- } else {
- vk = v2k1;
- vk1 = positiveMod(vk1 * vk1 - 2n, mod);
- }
- }
- return vk;
-}
-
-function positiveMod(value, mod) {
- value %= mod;
- return value < 0n ? value + mod : value;
-}
-
-async function factor(args) {
- args = normalizeFactorLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { h: false }, long: { exponents: false, help: false, version: false } });
- opts.exponents = opts.h || opts.exponents;
- if (!operands.length && !fstatSync(0).isFile()) return streamFactorStdin(opts);
- let values;
- try {
- if (operands.length) values = operands.map((operand) => String(operand).replace(/\0\S*/g, ""));
- else {
- const input = decodeSurrogateEscapedBytes(await readAll("-"));
- const fastStatus = factorFastSmallIntegerInput(input, opts);
- if (fastStatus != null) return fastStatus;
- values = input.replace(/\0\S*/g, "").trim().split(/\s+/).filter(Boolean);
- }
- } catch (error) {
- return fail("factor", `error reading input: ${systemErrorMessage(error)}`);
- }
- const parallel = await factorLargeContiguousRangeInParallel(values, opts);
- if (parallel != null) return parallel;
- const batchFactors = prepareSmallIntegerFactorizer(values) ?? prepareContiguousRangeFactorizer(values);
- let status = 0;
- for (const raw of values) {
- status = factorOneValue(raw, opts, batchFactors) || status;
- }
- return status;
-}
-
-async function streamFactorStdin(opts) {
- let pending = [];
- let pendingLength = 0;
- let values = [];
- let status = 0;
- const flushValues = async () => {
- if (!values.length) return;
- const batch = values;
- values = [];
- const parallelStatus = await factorLargeContiguousRangeInParallel(batch, opts);
- if (parallelStatus != null) {
- status = parallelStatus || status;
- return;
- }
- // Dense small ranges (notably upstream factor/t00: 0..10,000,000)
- // must use the compact Uint32 sieve. The generic range factorizer keeps
- // one JS array per value and caused JSC heap growth into multiple GiB.
- const batchFactors = prepareSegmentedSmallIntegerFactorizer(batch)
- ?? prepareSmallIntegerFactorizer(batch)
- ?? prepareContiguousRangeFactorizer(batch);
- for (const raw of batch) status = factorOneValue(raw, opts, batchFactors) || status;
- };
- const flushToken = () => {
- if (!pendingLength) return;
- const raw = decodeSurrogateEscapedBytes(Buffer.concat(pending, pendingLength)).replace(/\0\S*/g, "");
- pending = [];
- pendingLength = 0;
- if (raw) values.push(raw);
- };
- try {
- const inputBuffer = Buffer.allocUnsafe(64 * 1024);
- while (true) {
- const bytesRead = readSync(0, inputBuffer, 0, inputBuffer.length, null);
- if (bytesRead === 0) break;
- const chunk = inputBuffer.subarray(0, bytesRead);
- let start = 0;
- for (let index = 0; index < chunk.length; index++) {
- if (![9, 10, 11, 12, 13, 32].includes(chunk[index])) continue;
- if (index > start) {
- const part = Buffer.from(chunk.subarray(start, index));
- pending.push(part);
- pendingLength += part.length;
- }
- flushToken();
- start = index + 1;
- }
- if (start < chunk.length) {
- const part = Buffer.from(chunk.subarray(start));
- pending.push(part);
- pendingLength += part.length;
- }
- // Process four 100k-value child chunks concurrently while applying
- // backpressure to stdin, keeping the range optimization bounded.
- if (values.length >= 400_000) await flushValues();
- }
- flushToken();
- await flushValues();
- return status;
- } catch (error) {
- if (isWriteError(error)) throw error;
- return fail("factor", `error reading input: ${systemErrorMessage(error)}`);
- }
-}
-
-function factorOneValue(raw, opts, batchFactors = null) {
- const value = raw.replace(/^\+/, "");
- if (!/^\d+$/.test(value)) {
- stderr(`factor: ${localeQuotedDiagnostic(factorDiagnosticValue(raw))} is not a valid positive integer\n`);
- return 1;
- }
- const normalizedValue = normalizeFactorValue(value);
- const factors = batchFactors?.get(normalizedValue) ?? factorize(normalizedValue);
- stdout(`${normalizedValue}:${formatFactors(factors, opts).map((n) => ` ${n}`).join("")}\n`);
- return 0;
-}
-
-const FACTOR_FAST_OUTPUT_CHUNK_BYTES = 4096;
-
-function factorFastSmallIntegerInput(input, opts) {
- if (opts.exponents || input.includes("\0")) return null;
- let count = 0;
- let max = 0;
- for (const token of input.matchAll(/\S+/g)) {
- const raw = token[0];
- const value = raw.replace(/^\+/, "");
- if (!/^\d+$/.test(value) || value.length > 8) return null;
- const n = Number(value);
- if (!Number.isSafeInteger(n)) return null;
- if (n > max) max = n;
- count++;
- }
- if (count < 10000 || max > 100_000_000) return null;
-
- const spf = smallestPrimeFactors(max);
- let out = "";
- for (const token of input.matchAll(/\S+/g)) {
- const n = Number(token[0].replace(/^\+/, ""));
- const line = `${n}:${formatSmallIntegerFactors(n, spf)}\n`;
- if (out && out.length + line.length > FACTOR_FAST_OUTPUT_CHUNK_BYTES) {
- stdout(out);
- out = "";
- }
- out += line;
- }
- if (out) stdout(out);
- return 0;
-}
-
-function formatSmallIntegerFactors(value, spf) {
- if (value <= 1) return "";
- let n = value;
- let out = "";
- while (n > 1) {
- const p = spf[n] || n;
- out += ` ${p}`;
- n = Math.trunc(n / p);
- }
- return out;
-}
-
-function factorDiagnosticValue(value) {
- return [...String(value)].map((ch) => {
- if (/[\udc80-\udcff]/.test(ch)) return `\\${(ch.charCodeAt(0) - 0xdc00).toString(8).padStart(3, "0")}`;
- return lsEscapedName(ch, { escapeDouble: false });
- }).join("");
-}
-
-function normalizeFactorValue(value) {
- return BigInt(value).toString();
-}
-
-function normalizeFactorLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeFactorLongOption(arg));
- }
- return out;
-}
-
-function normalizeFactorLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = FACTOR_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-async function factorLargeContiguousRangeInParallel(values, opts) {
- if (process.env.BNU_FACTOR_CHILD === "1" || values.length < 2000 || opts.exponents) return null;
- const normalized = [];
- for (const raw of values) {
- const value = raw.replace(/^\+/, "");
- if (!/^\d+$/.test(value)) return null;
- normalized.push(value);
- }
- const lo = BigInt(normalized[0]);
- const hi = BigInt(normalized[normalized.length - 1]);
- if (lo < 1_000_000_000_000_000_000n || hi < lo || hi - lo !== BigInt(normalized.length - 1)) return null;
- for (let i = 1; i < normalized.length; i++) {
- if (BigInt(normalized[i]) !== lo + BigInt(i)) return null;
- }
-
- // Each Bun worker carries a substantial runtime and JIT footprint. Keep
- // the default single-process so an ordinary invocation cannot multiply its
- // memory use by the host CPU count. Controlled benchmarks and audits may
- // opt in to bounded parallelism with BNU_FACTOR_WORKERS.
- const configuredWorkerLimit = /^\d+$/.test(process.env.BNU_FACTOR_WORKERS ?? "")
- ? Number(process.env.BNU_FACTOR_WORKERS)
- : null;
- const workerLimit = configuredWorkerLimit ?? 1;
- const workers = Math.min(workerLimit, Math.max(1, Math.floor(values.length / 100)), cpus().length || 1);
- if (workers < 2) return null;
- const chunkSize = Math.ceil(values.length / workers);
- const chunks = [];
- for (let i = 0; i < values.length; i += chunkSize) chunks.push(values.slice(i, i + chunkSize));
- const results = await Promise.all(chunks.map(async (chunk) => {
- const proc = Bun.spawn([process.execPath, import.meta.path, "factor"], {
- env: { ...process.env, BNU_FACTOR_CHILD: "1" },
- stdin: new Blob([chunk.join("\n") + "\n"]),
- stdout: "pipe",
- stderr: "pipe",
- });
- const [code, out, err] = await Promise.all([
- proc.exited,
- new Response(proc.stdout).text(),
- new Response(proc.stderr).text(),
- ]);
- return { code, out, err };
- }));
- let status = 0;
- for (const result of results) {
- if (result.out) stdout(result.out);
- if (result.err) stderr(result.err);
- if (result.code !== 0) status = result.code;
- }
- return status;
-}
-
-function prepareContiguousRangeFactorizer(values) {
- if (values.length < 100 || values.length > 1_000_000) return null;
- const normalized = [];
- for (const raw of values) {
- const value = raw.replace(/^\+/, "");
- if (!/^\d+$/.test(value)) return null;
- normalized.push(value);
- }
- const lo = BigInt(normalized[0]);
- const hi = BigInt(normalized[normalized.length - 1]);
- if (hi < lo || hi - lo !== BigInt(normalized.length - 1)) return null;
- for (let i = 1; i < normalized.length; i++) {
- if (BigInt(normalized[i]) !== lo + BigInt(i)) return null;
- }
-
- const residues = normalized.map(BigInt);
- const factors = Array.from({ length: normalized.length }, () => []);
- for (const p of primesUpTo(1_000_000)) {
- const bigP = BigInt(p);
- const rem = lo % bigP;
- let index = Number(rem === 0n ? 0n : bigP - rem);
- for (; index < residues.length; index += p) {
- while (residues[index] % bigP === 0n) {
- factors[index].push(bigP);
- residues[index] /= bigP;
- }
- }
- }
-
- return {
- get(value) {
- const index = Number(BigInt(value) - lo);
- if (index < 0 || index >= residues.length) return null;
- const out = [...factors[index]];
- if (residues[index] > 1n) out.push(...factorize(residues[index]));
- return out.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
- },
- };
-}
-
-const primeCache = new Map();
-
-function primesUpTo(max) {
- const cached = primeCache.get(max);
- if (cached) return cached;
- const composite = new Uint8Array(max + 1);
- const primes = [];
- for (let i = 2; i <= max; i++) {
- if (composite[i]) continue;
- primes.push(i);
- if (i > Math.floor(max / i)) continue;
- for (let j = i * i; j <= max; j += i) composite[j] = 1;
- }
- primeCache.set(max, primes);
- return primes;
-}
-
-function prepareSmallIntegerFactorizer(values) {
- if (values.length < 10000) return null;
- let max = 0;
- for (const raw of values) {
- const value = raw.replace(/^\+/, "");
- if (!/^\d+$/.test(value) || value.length > 8) return null;
- const n = Number(value);
- if (!Number.isSafeInteger(n)) return null;
- if (n > max) max = n;
- }
- if (max > 100_000_000) return null;
- const spf = smallestPrimeFactors(max);
- return {
- get(value) {
- let n = Number(value);
- if (n <= 1) return [];
- const factors = [];
- while (n > 1) {
- const p = spf[n] || n;
- factors.push(BigInt(p));
- n = Math.trunc(n / p);
- }
- return factors;
- },
- };
-}
-
-function prepareSegmentedSmallIntegerFactorizer(values) {
- if (values.length < 10_000) return null;
- const normalized = [];
- for (const raw of values) {
- const value = raw.replace(/^\+/, "");
- if (!/^\d+$/.test(value) || value.length > 8) return null;
- const n = Number(value);
- if (!Number.isSafeInteger(n) || n > 100_000_000) return null;
- normalized.push(n);
- }
- const lo = normalized[0];
- const hi = normalized.at(-1);
- if (hi - lo !== normalized.length - 1) return null;
- for (let index = 1; index < normalized.length; index++) {
- if (normalized[index] !== lo + index) return null;
- }
-
- // Keep a compact CSR-style table of every factor in this segment. Storing
- // only the first divisor forced each residual through the generic Pollard
- // path and made the 80m..90m upstream range take more than 15 minutes.
- // Two sieve passes cost little and keep a 400k-value batch to a few typed
- // arrays rather than one JS array per integer.
- const primes = primesUpTo(Math.floor(Math.sqrt(hi)));
- const residues = new Uint32Array(normalized);
- const counts = new Uint8Array(normalized.length);
- for (const p of primes) {
- let first = Math.ceil(lo / p) * p;
- if (first < p * p) first = p * p;
- for (let value = first; value <= hi; value += p) {
- const index = value - lo;
- while (residues[index] > 1 && residues[index] % p === 0) {
- residues[index] = Math.trunc(residues[index] / p);
- counts[index]++;
- }
- }
- }
- for (let index = 0; index < residues.length; index++) {
- if (residues[index] > 1) counts[index]++;
- }
- const offsets = new Uint32Array(normalized.length + 1);
- for (let index = 0; index < counts.length; index++) offsets[index + 1] = offsets[index] + counts[index];
- const factors = new Uint32Array(offsets.at(-1));
- const positions = new Uint32Array(offsets.subarray(0, normalized.length));
- residues.set(normalized);
- for (const p of primes) {
- let first = Math.ceil(lo / p) * p;
- if (first < p * p) first = p * p;
- for (let value = first; value <= hi; value += p) {
- const index = value - lo;
- while (residues[index] > 1 && residues[index] % p === 0) {
- residues[index] = Math.trunc(residues[index] / p);
- factors[positions[index]++] = p;
- }
- }
- }
- for (let index = 0; index < residues.length; index++) {
- if (residues[index] > 1) factors[positions[index]++] = residues[index];
- }
- return {
- get(value) {
- const original = Number(value);
- const index = original - lo;
- if (index < 0 || index >= normalized.length || original <= 1) return original <= 1 ? [] : null;
- const out = [];
- for (let position = offsets[index]; position < offsets[index + 1]; position++) out.push(BigInt(factors[position]));
- return out;
- },
- };
-}
-
-let smallestPrimeFactorCache = new Uint32Array(0);
-
-function smallestPrimeFactors(max) {
- if (smallestPrimeFactorCache.length > max) return smallestPrimeFactorCache;
- const spf = new Uint32Array(max + 1);
- for (let i = 2; i <= max; i++) {
- if (spf[i] !== 0) continue;
- spf[i] = i;
- if (i > Math.floor(max / i)) continue;
- for (let j = i * i; j <= max; j += i) {
- if (spf[j] === 0) spf[j] = i;
- }
- }
- smallestPrimeFactorCache = spf;
- return spf;
-}
-
-function formatFactors(factors, opts) {
- if (!opts.exponents) return factors.map(String);
- const out = [];
- for (let i = 0; i < factors.length;) {
- let count = 1;
- while (factors[i + count] === factors[i]) count++;
- out.push(count === 1 ? String(factors[i]) : `${factors[i]}^${count}`);
- i += count;
- }
- return out;
-}
-
-async function forEachInputChunk(file, callback) {
- const buffer = Buffer.allocUnsafe(256 * 1024);
- if (file === "-") {
- while (true) {
- const n = readSync(0, buffer, 0, buffer.length, null);
- if (n === 0) break;
- callback(buffer.subarray(0, n));
- }
- return;
- }
- const handle = await open(file, "r");
- try {
- while (true) {
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
- if (bytesRead === 0) break;
- callback(buffer.subarray(0, bytesRead));
- }
- } finally {
- await handle.close();
- }
-}
-
-function crc32bUpdate(crc, chunk) {
- for (const byte of chunk) {
- crc ^= byte;
- for (let k = 0; k < 8; k++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));
- }
- return crc >>> 0;
-}
-
-function crc32b(buf) {
- let crc = 0xffffffff;
- crc = crc32bUpdate(crc, buf);
- return (crc ^ 0xffffffff) >>> 0;
-}
-
-const posixCrcTable = Array.from({ length: 256 }, (_, i) => {
- let crc = i << 24;
- for (let k = 0; k < 8; k++) crc = (crc & 0x80000000) ? ((crc << 1) ^ 0x04c11db7) : (crc << 1);
- return crc >>> 0;
-});
-
-function posixCrcUpdate(crc, chunk) {
- for (const byte of chunk) crc = ((crc << 8) ^ posixCrcTable[((crc >>> 24) ^ byte) & 0xff]) >>> 0;
- return crc >>> 0;
-}
-
-function posixCrcFinish(crc, length) {
- while (length > 0) {
- crc = ((crc << 8) ^ posixCrcTable[((crc >>> 24) ^ length) & 0xff]) >>> 0;
- length = Math.floor(length / 256);
- }
- return (~crc) >>> 0;
-}
-
-async function cksumCrc(file, variant) {
- let length = 0;
- let crc = variant === "crc32b" ? 0xffffffff : 0;
- await forEachInputChunk(file, (chunk) => {
- length += chunk.length;
- crc = variant === "crc32b" ? crc32bUpdate(crc, chunk) : posixCrcUpdate(crc, chunk);
- });
- return { length, crc: variant === "crc32b" ? (crc ^ 0xffffffff) >>> 0 : posixCrcFinish(crc, length) };
-}
-
-async function sumForFile(file, sysv = false) {
- let length = 0;
- let sum = 0;
- await forEachInputChunk(file, (chunk) => {
- length += chunk.length;
- for (const byte of chunk) {
- if (sysv) sum = (sum + byte) % 0x100000000;
- else sum = ((sum >> 1) + ((sum & 1) << 15) + byte) & 0xffff;
- }
- });
- if (sysv) {
- sum = (sum & 0xffff) + Math.floor(sum / 0x10000);
- sum = (sum & 0xffff) + Math.floor(sum / 0x10000);
- }
- return { sum, blocks: Math.ceil(length / (sysv ? 512 : 1024)) };
-}
-
-async function fileDigest(file, algorithm) {
- if (algorithm === "sm3") return sm3DigestFile(file);
- const hash = createHash(algorithm);
- await forEachInputChunk(file, (chunk) => hash.update(chunk));
- return hash.digest();
-}
-
-async function sm3DigestFile(file) {
- const state = {
- h: [0x7380166f, 0x4914b2b9, 0x172442d7, 0xda8a0600, 0xa96f30bc, 0x163138aa, 0xe38dee4d, 0xb0fb0e4e],
- buffer: Buffer.alloc(0),
- length: 0n,
- };
- await forEachInputChunk(file, (chunk) => sm3Update(state, chunk));
- return sm3Final(state);
-}
-
-function sm3Update(state, chunk) {
- state.length += BigInt(chunk.length);
- let data = Buffer.concat([state.buffer, chunk]);
- let offset = 0;
- while (offset + 64 <= data.length) {
- sm3Compress(state.h, data.subarray(offset, offset + 64));
- offset += 64;
- }
- state.buffer = data.subarray(offset);
-}
-
-function sm3Final(state) {
- const bitLength = state.length * 8n;
- const padLength = Number((56n - ((state.length + 1n) % 64n) + 64n) % 64n);
- const padding = Buffer.alloc(1 + padLength + 8);
- padding[0] = 0x80;
- padding.writeBigUInt64BE(bitLength, 1 + padLength);
- sm3Update(state, padding);
- const out = Buffer.alloc(32);
- state.h.forEach((word, index) => out.writeUInt32BE(word >>> 0, index * 4));
- return out;
-}
-
-function sm3Compress(h, block) {
- const w = new Array(68);
- const w1 = new Array(64);
- for (let i = 0; i < 16; i++) w[i] = block.readUInt32BE(i * 4);
- for (let j = 16; j < 68; j++) w[j] = (sm3P1((w[j - 16] ^ w[j - 9] ^ rotl32(w[j - 3], 15)) >>> 0) ^ rotl32(w[j - 13], 7) ^ w[j - 6]) >>> 0;
- for (let j = 0; j < 64; j++) w1[j] = (w[j] ^ w[j + 4]) >>> 0;
- let [a, b, c, d, e, f, g, hh] = h;
- for (let j = 0; j < 64; j++) {
- const t = j < 16 ? 0x79cc4519 : 0x7a879d8a;
- const ss1 = rotl32((rotl32(a, 12) + e + rotl32(t, j % 32)) >>> 0, 7);
- const ss2 = (ss1 ^ rotl32(a, 12)) >>> 0;
- const tt1 = (sm3FF(a, b, c, j) + d + ss2 + w1[j]) >>> 0;
- const tt2 = (sm3GG(e, f, g, j) + hh + ss1 + w[j]) >>> 0;
- d = c;
- c = rotl32(b, 9);
- b = a;
- a = tt1;
- hh = g;
- g = rotl32(f, 19);
- f = e;
- e = sm3P0(tt2);
- }
- for (let i = 0, values = [a, b, c, d, e, f, g, hh]; i < 8; i++) h[i] = (h[i] ^ values[i]) >>> 0;
-}
-
-function rotl32(value, bits) {
- return ((value << bits) | (value >>> (32 - bits))) >>> 0;
-}
-
-function sm3P0(x) {
- return (x ^ rotl32(x, 9) ^ rotl32(x, 17)) >>> 0;
-}
-
-function sm3P1(x) {
- return (x ^ rotl32(x, 15) ^ rotl32(x, 23)) >>> 0;
-}
-
-function sm3FF(x, y, z, j) {
- return j < 16 ? (x ^ y ^ z) >>> 0 : ((x & y) | (x & z) | (y & z)) >>> 0;
-}
-
-function sm3GG(x, y, z, j) {
- return j < 16 ? (x ^ y ^ z) >>> 0 : ((x & y) | (~x & z)) >>> 0;
-}
-
-const BLAKE2B_IV = [
- 0x6a09e667f3bcc908n, 0xbb67ae8584caa73bn, 0x3c6ef372fe94f82bn, 0xa54ff53a5f1d36f1n,
- 0x510e527fade682d1n, 0x9b05688c2b3e6c1fn, 0x1f83d9abfb41bd6bn, 0x5be0cd19137e2179n,
-];
-const BLAKE2B_SIGMA = [
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
- [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
- [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
- [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
- [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
- [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
- [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
- [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
- [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
- [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
- [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
-];
-const MASK64 = 0xffffffffffffffffn;
-
-async function blake2bDigestFile(file, outBytes = 64) {
- const state = {
- h: [...BLAKE2B_IV],
- buffer: Buffer.alloc(0),
- length: 0n,
- outBytes,
- };
- state.h[0] ^= 0x01010000n ^ BigInt(outBytes);
- await forEachInputChunk(file, (chunk) => blake2bUpdate(state, chunk));
- return blake2bFinal(state);
-}
-
-function blake2bUpdate(state, chunk) {
- let data = Buffer.concat([state.buffer, chunk]);
- let offset = 0;
- while (offset + 128 < data.length) {
- state.length += 128n;
- blake2bCompress(state.h, data.subarray(offset, offset + 128), state.length, false);
- offset += 128;
- }
- state.buffer = data.subarray(offset);
-}
-
-function blake2bFinal(state) {
- state.length += BigInt(state.buffer.length);
- const block = Buffer.alloc(128);
- state.buffer.copy(block);
- blake2bCompress(state.h, block, state.length, true);
- const out = Buffer.alloc(64);
- state.h.forEach((word, index) => out.writeBigUInt64LE(word, index * 8));
- return out.subarray(0, state.outBytes);
-}
-
-function blake2bCompress(h, block, count, last) {
- const m = Array.from({ length: 16 }, (_, i) => block.readBigUInt64LE(i * 8));
- const v = [...h, ...BLAKE2B_IV];
- v[12] ^= count & MASK64;
- v[13] ^= count >> 64n;
- if (last) v[14] ^= MASK64;
- const mix = (a, b, c, d, x, y) => {
- v[a] = (v[a] + v[b] + x) & MASK64;
- v[d] = rotr64(v[d] ^ v[a], 32n);
- v[c] = (v[c] + v[d]) & MASK64;
- v[b] = rotr64(v[b] ^ v[c], 24n);
- v[a] = (v[a] + v[b] + y) & MASK64;
- v[d] = rotr64(v[d] ^ v[a], 16n);
- v[c] = (v[c] + v[d]) & MASK64;
- v[b] = rotr64(v[b] ^ v[c], 63n);
- };
- for (const s of BLAKE2B_SIGMA) {
- mix(0, 4, 8, 12, m[s[0]], m[s[1]]);
- mix(1, 5, 9, 13, m[s[2]], m[s[3]]);
- mix(2, 6, 10, 14, m[s[4]], m[s[5]]);
- mix(3, 7, 11, 15, m[s[6]], m[s[7]]);
- mix(0, 5, 10, 15, m[s[8]], m[s[9]]);
- mix(1, 6, 11, 12, m[s[10]], m[s[11]]);
- mix(2, 7, 8, 13, m[s[12]], m[s[13]]);
- mix(3, 4, 9, 14, m[s[14]], m[s[15]]);
- }
- for (let i = 0; i < 8; i++) h[i] = (h[i] ^ v[i] ^ v[i + 8]) & MASK64;
-}
-
-function rotr64(value, bits) {
- return ((value >> bits) | (value << (64n - bits))) & MASK64;
-}
-
-function uIntBytesBE(value, width) {
- const bytes = new Uint8Array(width);
- let n = Number(value) >>> 0;
- for (let i = width - 1; i >= 0; i--) {
- bytes[i] = n & 0xff;
- n >>>= 8;
- }
- return bytes;
-}
-
-async function cksum(args) {
- args = normalizeCksumLongOptions(args);
- if (args.length === 1 && args[0] === "--help") {
- stdout("Usage: cksum [OPTION]... [FILE]...\n");
- stdout("Print or verify checksums.\nBy default use the 32 bit CRC algorithm.\n\n");
- stdout("Available algorithms:\n sysv\n bsd\n crc\n crc32b\n md5\n sha1\n sha2\n sha3\n blake2b\n sm3\n");
- return 0;
- }
- const { opts, operands } = parseOptions(args, { short: { a: "value", l: "value", c: false, z: false, b: false, t: false, w: false }, long: { algorithm: "value", length: "value", check: false, base64: false, raw: false, tag: false, untagged: false, zero: false, status: false, quiet: false, warn: false, strict: false, "ignore-missing": false, debug: false, binary: false, text: false, help: false, version: false } });
- if (opts.w) opts.warn = true;
- opts.warnAfterStatus = optionAppearsAfter(args, "--warn", "--status") || optionAppearsAfter(args, "-w", "--status");
- const algorithm = opts.a ?? opts.algorithm ?? "crc";
- validateCksumAlgorithmOption(algorithm);
- validateChecksumCheckOnlyOptions(opts);
- const lengthOption = opts.l ?? opts.length;
- if (lengthOption != null && String(lengthOption) !== "0" && !["blake2b", "sha2", "sha3"].includes(algorithm)) {
- throw new UsageError("--length is only supported with --algorithm blake2b, sha2, or sha3");
- }
- opts.taggedOutput = cksumTaggedOutput(args, algorithm);
- opts.binaryOutput = cksumBinaryOutput(args);
- if (opts.raw && opts.base64) throw new UsageError("--raw and --base64 are mutually exclusive");
- if (opts.raw && operands.length > 1) throw new UsageError("--raw does not support multiple files");
- if ((opts.t || opts.text) && opts.taggedOutput && algorithm !== "crc" && algorithm !== "crc32b" && algorithm !== "bsd" && algorithm !== "sysv") throw new UsageError("--text mode is only supported with --untagged", true);
- if (opts.c || opts.check) {
- if (opts.tag && opts.taggedOutput) throw new UsageError("the --tag option is meaningless when verifying checksums", true);
- const explicitAlgorithm = opts.a != null || opts.algorithm != null;
- if (explicitAlgorithm && ["bsd", "sysv", "crc", "crc32b"].includes(algorithm)) throw new UsageError("--check is not supported with --algorithm={bsd,sysv,crc,crc32b}");
- if (explicitAlgorithm && (opts.l != null || opts.length != null)) cksumHashAlgorithm(algorithm, opts);
- return checkHashes(explicitAlgorithm ? algorithm : "auto", operands.length ? operands : ["-"], { ...opts, program: "cksum" });
- }
- if (algorithm === "bsd" || algorithm === "sysv") return cksumSum(algorithm, operands.length ? operands : ["-"], opts.raw);
- if (algorithm !== "crc" && algorithm !== "crc32b") return cksumDigest(algorithm, opts, operands.length ? operands : ["-"]);
- if (opts.debug) stderr("cksum: using generic checksum implementation\n");
- const implicitStdin = operands.length === 0;
- const files = implicitStdin ? ["-"] : operands;
- let failed = false;
- for (const file of files) {
- let result;
- try {
- result = await cksumCrc(file, algorithm);
- } catch (error) {
- stderr(cksumReadError(file, error));
- failed = true;
- continue;
- }
- const { crc, length } = result;
- if (opts.raw) {
- stdout(uIntBytesBE(crc, 4));
- continue;
- }
- stdout(`${crc} ${length}${implicitStdin ? "" : ` ${file}`}\n`);
- }
- return failed ? 1 : 0;
-}
-
-const CKSUM_ALGORITHMS = ["bsd", "sysv", "crc", "crc32b", "md5", "sha1", "sha224", "sha256", "sha384", "sha512", "sha2", "sha3", "blake2b", "sm3"];
-
-function validateCksumAlgorithmOption(value) {
- if (CKSUM_ALGORITHMS.includes(value)) return;
- throw new UsageError(`invalid argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic("--algorithm")}\nValid arguments are:\n${CKSUM_ALGORITHMS.map((algorithm) => ` - ${localeQuotedDiagnostic(algorithm)}`).join("\n")}`, true);
-}
-
-function optionAppearsAfter(args, later, earlier) {
- const laterIndex = args.lastIndexOf(later);
- const earlierIndex = args.lastIndexOf(earlier);
- return laterIndex !== -1 && earlierIndex !== -1 && laterIndex > earlierIndex;
-}
-
-function cksumTaggedOutput(args, algorithm) {
- let mode = !["crc", "crc32b", "bsd", "sysv"].includes(algorithm);
- for (const arg of args) {
- if (arg === "--tag") mode = true;
- else if (arg === "--untagged") mode = false;
- }
- return mode;
-}
-
-function cksumBinaryOutput(args) {
- let mode = false;
- for (const arg of args) {
- if (arg === "--binary") mode = true;
- else if (arg === "--text") mode = false;
- else if (/^-[^-]/.test(arg)) {
- for (let i = 1; i < arg.length; i++) {
- const ch = arg[i];
- if (ch === "b") mode = true;
- else if (ch === "t") mode = false;
- else if (ch === "a" || ch === "l") break;
- }
- }
- }
- return mode;
-}
-
-async function cksumSum(algorithm, files, raw = false) {
- const sysv = algorithm === "sysv";
- let failed = false;
- for (const file of files) {
- let result;
- try {
- result = await sumForFile(file, sysv);
- } catch (error) {
- stderr(cksumReadError(file, error));
- failed = true;
- continue;
- }
- const { sum, blocks } = result;
- if (raw) {
- stdout(uIntBytesBE(sum, 2));
- continue;
- }
- if (sysv) stdout(`${sum} ${blocks}${file === "-" ? "" : ` ${file}`}\n`);
- else stdout(`${String(sum).padStart(5, "0")} ${String(blocks).padStart(5)}${file === "-" ? "" : ` ${file}`}\n`);
- }
- return failed ? 1 : 0;
-}
-
-function cksumHashAlgorithm(name, opts = {}) {
- const length = opts.l ?? opts.length;
- if (name === "md5") return "md5";
- if (name === "sha1") return "sha1";
- if (["sha224", "sha256", "sha384", "sha512"].includes(name)) return name;
- if (name === "sha2") {
- validateShaDigestLengthSyntax(length);
- if (!["224", "256", "384", "512"].includes(String(length))) throw invalidDigestLengthError("cksum", "SHA2", length, "digest length for 'SHA2' must be 224, 256, 384, or 512");
- return `sha${length}`;
- }
- if (name === "sha3") {
- validateShaDigestLengthSyntax(length);
- if (!["224", "256", "384", "512"].includes(String(length))) throw invalidDigestLengthError("cksum", "SHA3", length, "digest length for 'SHA3' must be 224, 256, 384, or 512");
- return `sha3-${length}`;
- }
- if (name === "blake2b") {
- if (length != null) validateBlake2bLength(opts.program ?? "cksum", length);
- return "blake2b512";
- }
- if (name === "sm3") return "sm3";
- throw new UsageError(`invalid checksum algorithm: ${name}`);
-}
-
-function validateShaDigestLengthSyntax(length) {
- const text = String(length);
- if (/^\d+$/.test(text)) return;
- if (/^-\d+$/.test(text)) throw new UsageError(`invalid length: ${localeQuotedEscapedDiagnostic(length)}: Value too large for defined data type`, false);
- throw new UsageError(`invalid length: ${localeQuotedEscapedDiagnostic(length)}`, false);
-}
-
-function cksumAlgorithmForDigest(name, digestBytes, opts = {}) {
- const length = opts.l ?? opts.length;
- if (name === "sha2") {
- const bits = length ?? String(digestBytes * 8);
- return cksumHashAlgorithm(name, { ...opts, l: bits });
- }
- if (name === "sha3") {
- const bits = length ?? String(digestBytes * 8);
- return cksumHashAlgorithm(name, { ...opts, l: bits });
- }
- return cksumHashAlgorithm(name, opts);
-}
-
-function cksumTag(name, opts = {}) {
- const length = opts.l ?? opts.length;
- if (name === "blake2b") return length && String(length) !== "0" ? `BLAKE2b-${length}` : "BLAKE2b";
- if (name === "sha3") return `SHA3-${length}`;
- const algorithm = cksumHashAlgorithm(name, opts);
- return algorithm.toUpperCase();
-}
-
-async function cksumDigest(name, opts, files) {
- const lengthValue = opts.l ?? opts.length;
- const length = lengthValue === "0" ? null : lengthValue ?? (name === "sha2" || name === "sha3" ? "256" : name === "blake2b" ? "512" : null);
- if (name === "blake2b" && length != null) validateBlake2bLength("cksum", length);
- const algorithm = cksumHashAlgorithm(name, { ...opts, l: length });
- const digestBytes = length == null ? null : Number(length) / 8;
- if (length != null && (!Number.isInteger(digestBytes) || digestBytes <= 0)) throw new UsageError(`invalid digest length: ${length}`);
- const sep = opts.z || opts.zero ? "\0" : "\n";
- let failed = false;
- for (const file of files) {
- let full;
- try {
- full = name === "blake2b" ? await blake2bDigestFile(file, digestBytes ?? 64) : await fileDigest(file, algorithm);
- } catch (error) {
- stderr(cksumReadError(file, error));
- failed = true;
- continue;
- }
- const digest = digestBytes == null ? full : full.slice(0, digestBytes);
- if (opts.raw) {
- stdout(digest);
- continue;
- }
- const rendered = opts.base64 ? digest.toString("base64") : digest.toString("hex");
- const nameOut = file === "-" ? "-" : file;
- if (!opts.taggedOutput) stdout(`${rendered}${opts.binaryOutput ? " *" : " "}${nameOut}${sep}`);
- else stdout(`${cksumTag(name, opts)} (${nameOut}) = ${rendered}${sep}`);
- }
- return failed ? 1 : 0;
-}
-
-function cksumReadError(file, error) {
- return file === "-" ? `cksum: ${nodeErrorMessage(error)}\n` : `cksum: ${checksumDiagnosticName(file)}: ${systemErrorMessage(error)}\n`;
-}
-
-function checksumDiagnosticName(file) {
- return textInputDiagnosticName(file);
-}
-
-function normalizeCksumLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, CKSUM_LONG_OPTIONS);
-}
-
-function normalizeCksumLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, CKSUM_LONG_OPTIONS);
-}
-
-async function sum(args) {
- args = normalizeSumLongOptions(args);
- const { operands, sysv } = parseSumArgs(args);
- const implicitStdin = operands.length === 0;
- const files = implicitStdin ? ["-"] : operands;
- let failed = false;
- for (const file of files) {
- let result;
- try {
- result = await sumForFile(file, sysv);
- } catch (error) {
- stderr(`sum: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- continue;
- }
- const { sum, blocks } = result;
- const label = implicitStdin ? "" : ` ${file}`;
- if (sysv) {
- stdout(`${sum} ${blocks}${label}\n`);
- } else {
- stdout(`${String(sum).padStart(5, "0")} ${String(blocks).padStart(5)}${label}\n`);
- }
- }
- return failed ? 1 : 0;
-}
-
-function parseSumArgs(args) {
- const operands = [];
- let sysv = false;
- let end = false;
- for (const arg of args) {
- if (end || arg === "-" || !arg.startsWith("-")) {
- operands.push(arg);
- if (process.env.POSIXLY_CORRECT) end = true;
- continue;
- }
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (!SUM_LONG_OPTIONS.includes(name)) throw new UsageError(`unrecognized option '${arg}'`, true);
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- if (name === "sysv") sysv = true;
- continue;
- }
- for (const ch of arg.slice(1)) {
- if (ch === "s") sysv = true;
- else if (ch === "r") sysv = false;
- else throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- }
- return { operands, sysv };
-}
-
-function normalizeSumLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeSumLongOption(arg));
- }
- return out;
-}
-
-function normalizeSumLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = SUM_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-async function shuf(args) {
- const { opts, operands } = parseShufOptions(args);
- const sep = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- const count = shufHeadCount(opts);
- const hasInputRange = Object.hasOwn(opts, "i") || Object.hasOwn(opts, "input-range");
- if (hasInputRange && (opts.e || opts.echo)) throw new UsageError("cannot combine -e and -i options", true);
- if (count === 0 && !hasInputRange && !(opts.e || opts.echo)) {
- if (opts.o || opts.output) await writeFile(opts.o ?? opts.output, "");
- return 0;
- }
- let lines;
- let range = null;
- if (hasInputRange) {
- range = parseShufRange(opts.i ?? opts["input-range"]);
- if (operands.length) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}`, true);
- if (range.size <= BigInt(Number.MAX_SAFE_INTEGER) && (count == null || count >= Number(range.size) || opts.r || opts.repeat)) {
- const lo = Number(range.lo);
- const size = Number(range.size);
- lines = Array.from({ length: size }, (_, i) => String(lo + i));
- }
- } else if (opts.e || opts.echo) {
- lines = operands;
- } else {
- if (operands.length > 1) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[1])}`, true);
- const file = operands[0] ?? "-";
- let bytes;
- try {
- bytes = await readAll(file);
- } catch (error) {
- throw new UsageError(error?.code === "EISDIR" ? "read error: Is a directory" : file === "-" ? nodeErrorMessage(error) : `${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}`);
- }
- lines = splitShufByteRecords(bytes, sep === "\0" ? 0 : 0x0a);
- }
- if (count === 0) {
- if (opts.o || opts.output) await writeFile(opts.o ?? opts.output, "");
- return 0;
- }
- if ((opts.r || opts.repeat) && (range?.size === 0n || (range == null && lines.length === 0))) throw new UsageError("no lines to repeat");
- let random;
- try {
- random = await randomPicker(opts["random-source"], { boundedBits: true });
- } catch (error) {
- const source = opts["random-source"];
- const sourceName = source === "" ? "''" : textInputDiagnosticName(source);
- const message = error?.code === "EISDIR" ? `${localeQuotedDiagnostic(source)}: read error: ${systemErrorMessage(error)}` : `${sourceName}: ${systemErrorMessage(error)}`;
- stderr(`shuf: ${message}\n`);
- return 1;
- }
- if (opts.r || opts.repeat) {
- if (count == null) return shufRepeatForever(lines, range, random, sep);
- const selected = range
- ? Array.from({ length: count }, () => shufRangeValue(range, random).toString())
- : Array.from({ length: count }, () => lines[random(lines.length)] ?? "");
- const out = shufJoinRecords(selected, sep);
- if (opts.o || opts.output) await writeFile(opts.o ?? opts.output, out);
- else stdout(out);
- return 0;
- }
- if (range && !lines) {
- lines = shufSampleRange(range, count ?? Number.MAX_SAFE_INTEGER, random);
- } else {
- const limit = Math.min(count ?? lines.length, lines.length);
- for (let i = 0; i < limit; i++) {
- const j = i + random(lines.length - i);
- [lines[i], lines[j]] = [lines[j], lines[i]];
- }
- }
- const selected = lines.slice(0, count ?? lines.length);
- const out = shufJoinRecords(selected, sep);
- if (opts.o || opts.output) await writeFile(opts.o ?? opts.output, out);
- else stdout(out);
- return 0;
-}
-
-function splitShufByteRecords(bytes, sepByte) {
- if (bytes.length === 0) return [];
- const end = bytes[bytes.length - 1] === sepByte ? bytes.length - 1 : bytes.length;
- if (end === 0) return [];
- const records = [];
- let start = 0;
- for (let i = 0; i < end; i++) {
- if (bytes[i] === sepByte) {
- records.push(bytes.slice(start, i));
- start = i + 1;
- }
- }
- records.push(bytes.slice(start, end));
- return records;
-}
-
-function shufJoinRecords(records, sep) {
- if (!records.length) return "";
- if (records[0] instanceof Uint8Array) {
- const sepBytes = sep === "\0" ? Uint8Array.of(0) : Uint8Array.of(0x0a);
- const chunks = [];
- for (const record of records) chunks.push(record, sepBytes);
- return concatBytes(chunks);
- }
- return records.join(sep) + sep;
-}
-
-function parseShufOptions(args) {
- args = normalizeShufLongOptions(args);
- const opts = {};
- const operands = [];
- const seen = { i: false, o: false, randomSource: false };
- let end = false;
- const setValue = (key, value, option) => {
- if (value === undefined) {
- if (option?.startsWith("--")) throw new UsageError(`option '${option}' requires an argument`, true);
- throw new UsageError(`option requires an argument -- '${key}'`, true);
- }
- if (key === "n" || key === "head-count") {
- const previous = opts.n ?? opts["head-count"];
- const next = parseShufCount(value);
- opts.n = previous === undefined ? String(value) : String(Math.min(parseShufCount(previous), next));
- return;
- }
- if (key === "i" || key === "input-range") {
- if (seen.i) throw new UsageError("multiple -i options specified");
- seen.i = true;
- opts.i = value;
- return;
- }
- if (key === "o" || key === "output") {
- if (seen.o) throw new UsageError("multiple output files specified");
- seen.o = true;
- opts.o = value;
- return;
- }
- if (key === "random-source") {
- if (seen.randomSource !== false && seen.randomSource !== value) throw new UsageError("multiple random sources specified");
- seen.randomSource = value;
- opts["random-source"] = value;
- }
- };
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (end || arg === "-" || !arg.startsWith("-")) {
- operands.push(arg);
- continue;
- }
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg.startsWith("--")) {
- const [rawName, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- const name = rawName === "rep" ? "repeat" : rawName;
- if (["head-count", "input-range", "output", "random-source"].includes(name)) setValue(name, inlineValue ?? args[++i], `--${rawName}`);
- else if (name === "echo") {
- if (inlineValue !== undefined) throw new UsageError("option '--echo' doesn't allow an argument", true);
- opts.echo = true;
- } else if (name === "repeat") {
- if (inlineValue !== undefined) throw new UsageError("option '--repeat' doesn't allow an argument", true);
- opts.repeat = true;
- } else if (name === "zero-terminated") {
- if (inlineValue !== undefined) throw new UsageError("option '--zero-terminated' doesn't allow an argument", true);
- opts["zero-terminated"] = true;
- } else if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- opts[name] = true;
- }
- else throw new UsageError(`unrecognized option '${arg}'`, true);
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "e") opts.e = true;
- else if (ch === "r") opts.r = true;
- else if (ch === "z") opts.z = true;
- else if (["n", "i", "o"].includes(ch)) {
- setValue(ch, arg.slice(j + 1) || args[++i], `-${ch}`);
- break;
- } else {
- throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- }
- }
- return { opts, operands };
-}
-
-function normalizeShufLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, SHUF_LONG_OPTIONS);
-}
-
-function normalizeShufLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, SHUF_LONG_OPTIONS);
-}
-
-function shufHeadCount(opts) {
- const value = opts.n ?? opts["head-count"];
- return value === undefined ? null : parseShufCount(value);
-}
-
-function parseShufCount(value) {
- const text = String(value).trimStart();
- if (!/^\+?\d+$/.test(text)) throw new UsageError(`invalid line count: ${localeQuotedEscapedDiagnostic(value)}`);
- const count = BigInt(text);
- if (count > BigInt(Number.MAX_SAFE_INTEGER)) return Number.MAX_SAFE_INTEGER;
- return Number(count);
-}
-
-function parseShufRange(value) {
- const text = String(value);
- const match = text.match(/^(\+?\d+)-(\+?\d+)$/);
- if (!match) throw new UsageError(`invalid input range: ${localeQuotedEscapedDiagnostic(text)}`);
- const lo = BigInt(match[1]);
- const hi = BigInt(match[2]);
- if (hi + 1n < lo) throw new UsageError(`invalid input range: ${localeQuotedEscapedDiagnostic(text)}`);
- return { lo, hi, size: hi - lo + 1n };
-}
-
-function shufRangeValue(range, random) {
- return range.lo + BigInt(randomBigIntBelow(range.size, random));
-}
-
-function randomBigIntBelow(max, random) {
- if (max <= 0n) return 0n;
- if (max <= BigInt(Number.MAX_SAFE_INTEGER)) return BigInt(random(Number(max)));
- return BigInt(random(0x1_0000_0000)) % max;
-}
-
-function shufSampleRange(range, count, random) {
- const limit = Math.min(count, Number(range.size > BigInt(Number.MAX_SAFE_INTEGER) ? BigInt(count) : range.size));
- const selected = new Set();
- while (selected.size < limit) selected.add(shufRangeValue(range, random).toString());
- return [...selected];
-}
-
-function shufRepeatForever(lines, range, random, sep) {
- while (true) {
- const out = [];
- for (let i = 0; i < 1024; i++) out.push(range ? shufRangeValue(range, random).toString() : lines[random(lines.length)] ?? "");
- try {
- stdout(shufJoinRecords(out, sep));
- } catch (error) {
- if (error?.code === "EPIPE") return 0;
- throw error;
- }
- }
-}
-
-function splitRecords(text, sep = "\n") {
- if (text === "") return [];
- const trimmed = text.endsWith(sep) ? text.slice(0, -sep.length) : text;
- if (trimmed === "") return [];
- return trimmed.split(sep);
-}
-
-async function randomPicker(source, options = {}) {
- if (source == null) return (max) => Math.floor(Math.random() * max);
- const bytes = readRandomSourceBytes(source);
- if (options.boundedBits && bytes.length === 0) {
- const error = new Error("end of file");
- error.code = "EOF";
- throw error;
- }
- if (!options.boundedBits) {
- let offset = 0;
- return (max) => {
- if (max <= 0) return 0;
- if (!bytes.length) return 0;
- let value = 0;
- for (let i = 0; i < 4; i++) {
- value = (value << 8) | bytes[offset++ % bytes.length];
- }
- return (value >>> 0) % max;
- };
- }
- let bitOffset = 0;
- const nextBit = () => {
- if (bitOffset >= bytes.length * 8) {
- const error = new Error("end of file");
- error.code = "EOF";
- throw error;
- }
- const bit = (bytes[bitOffset >> 3] >> (bitOffset & 7)) & 1;
- bitOffset++;
- return bit;
- };
- return (max) => {
- if (max <= 0) return 0;
- if (!bytes.length) return 0;
- const bits = Math.ceil(Math.log2(max));
- while (true) {
- let value = 0;
- for (let i = 0; i < bits; i++) value |= nextBit() << i;
- if (value < max) return value;
- }
- };
-}
-
-function readRandomSourceBytes(source) {
- const fd = openSync(source, "r");
- try {
- const buffer = Buffer.alloc(4096);
- const bytesRead = readSync(fd, buffer, 0, buffer.length, null);
- return buffer.subarray(0, bytesRead);
- } finally {
- closeSync(fd);
- }
-}
-
-async function mktempCmd(args) {
- if (process.env.POSIXLY_CORRECT && args.findIndex((arg) => arg !== "--" && !arg.startsWith("-")) !== -1) {
- const firstOperand = args.findIndex((arg) => arg !== "--" && !arg.startsWith("-"));
- if (args.slice(firstOperand + 1).some((arg) => arg.startsWith("-"))) throw new UsageError("too many templates", true);
- }
- args = normalizeMktempLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { d: false, p: "value", q: false, t: false, u: false }, long: { directory: false, quiet: false, tmpdir: "optional-value", suffix: "value", "dry-run": false, help: false, version: false } });
- if (operands.length > 1) throw new UsageError("too many templates", true);
- const template = operands[0] ?? "tmp.XXXXXXXXXX";
- const useTmpdir = opts.t || opts.tmpdir !== undefined || opts.p !== undefined || !operands.length;
- const envTmpdir = process.env.TMPDIR || null;
- const defaultTmpdir = envTmpdir ?? "/tmp";
- const optionTmpdir = opts.tmpdir === true || opts.tmpdir === "" ? defaultTmpdir : opts.tmpdir ?? (opts.p === "" ? defaultTmpdir : opts.p);
- const tmpdir = opts.t ? (envTmpdir ?? optionTmpdir ?? defaultTmpdir) : optionTmpdir;
- if (opts.t && template.includes("/")) throw new UsageError(`invalid template, ${localeQuotedEscapedDiagnostic(template)}, contains directory separator`);
- if (useTmpdir && isAbsolute(template)) throw new UsageError(`invalid template, ${localeQuotedEscapedDiagnostic(template)}; with --tmpdir, it may not be absolute`);
- const dir = useTmpdir ? tmpdir ?? defaultTmpdir : template.includes("/") ? pathDirname(template) : "";
- const name = template.includes("/") ? pathBasename(template) : template;
- if (opts.suffix !== undefined && !name.endsWith("X")) throw new UsageError(`with --suffix, template ${localeQuotedEscapedDiagnostic(template)} must end in X`);
- const wholeXMatch = [...template.matchAll(/X{3,}/g)].at(-1);
- if (opts.suffix === undefined && wholeXMatch) {
- const implicitSuffix = template.slice(wholeXMatch.index + wholeXMatch[0].length);
- const slash = implicitSuffix.indexOf("/");
- if (slash !== -1 && !implicitSuffix.slice(slash + 1).includes("X")) {
- throw new UsageError(`invalid suffix ${localeQuotedEscapedDiagnostic(implicitSuffix)}, contains directory separator`);
- }
- }
- const xMatch = [...name.matchAll(/X{3,}/g)].at(-1);
- const x = xMatch?.[0];
- if (!x || x.length < 3) throw new UsageError(`too few X's in template ${localeQuotedEscapedDiagnostic(template)}`);
- if (opts.suffix === undefined && wholeXMatch && template.slice(wholeXMatch.index + wholeXMatch[0].length).includes("/")) {
- throw new UsageError(`invalid suffix ${localeQuotedEscapedDiagnostic(template.slice(wholeXMatch.index + wholeXMatch[0].length))}, contains directory separator`);
- }
- const suffix = opts.suffix ?? name.slice(xMatch.index + x.length);
- if (suffix.includes("/")) throw new UsageError(`invalid suffix ${localeQuotedEscapedDiagnostic(suffix)}, contains directory separator`);
- const templateDir = template.includes("/") && useTmpdir ? pathDirname(template) : "";
- const parent = mktempJoin(dir, templateDir);
- const namePrefix = name.slice(0, xMatch.index);
- const prefix = mktempPrefix(parent, namePrefix);
- const displayTemplate = `${prefix}${x}${suffix}`;
- const candidateName = () => `${prefix}${mktempRandom(x.length)}${suffix}`;
- if (opts.u || opts["dry-run"]) {
- stdout(`${candidateName()}\n`);
- return 0;
- }
- for (let i = 0; i < 100; i++) {
- const candidate = candidateName();
- try {
- if (opts.d || opts.directory) await mkdir(candidate, { mode: 0o700 });
- else {
- const fh = await open(candidate, "wx", 0o600);
- await fh.close();
- }
- try {
- stdout(`${candidate}\n`);
- } catch (error) {
- if (isWriteError(error)) await rm(candidate, { recursive: true, force: true });
- throw error;
- }
- return 0;
- } catch (error) {
- if (error.code === "ENOENT") {
- if (opts.q || opts.quiet) return 1;
- throw new UsageError(`failed to create file via template ${localeQuotedEscapedDiagnostic(displayTemplate)}: ${systemErrorMessage(error)}`);
- }
- if (error.code !== "EEXIST") {
- if (opts.q || opts.quiet) return 1;
- throw new UsageError(`failed to create file via template ${localeQuotedEscapedDiagnostic(displayTemplate)}: ${systemErrorMessage(error)}`);
- }
- }
- }
- if (opts.q || opts.quiet) return 1;
- throw new UsageError(`failed to create file via template ${localeQuotedEscapedDiagnostic(displayTemplate)}`);
-}
-
-function normalizeMktempLongOptions(args) {
- const out = [];
- let end = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- const option = normalizeMktempLongOption(arg);
- out.push(option);
- if (option === "--suffix" && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-function normalizeMktempLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = MKTEMP_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length === 0) return arg;
- if (matches.length > 1) {
- throw new UsageError(`option '--${name}${eq === -1 ? "" : `=${body.slice(eq + 1)}`}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-function mktempJoin(...parts) {
- const filtered = parts.filter((part) => part !== "");
- if (filtered.length === 0) return "";
- if (filtered[0] === "." && filtered.length > 1) return `./${join(...filtered.slice(1))}`;
- if (filtered[0].startsWith("./") && filtered.length > 1) return `${filtered[0]}/${join(...filtered.slice(1))}`;
- return join(...filtered);
-}
-
-function mktempPrefix(parent, namePrefix) {
- if (!parent) return namePrefix;
- if (namePrefix) return mktempJoin(parent, namePrefix);
- return parent.endsWith("/") ? parent : `${parent}/`;
-}
-
-function mktempRandom(length) {
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- let out = "";
- for (let i = 0; i < length; i++) out += alphabet[Math.floor(Math.random() * alphabet.length)];
- return out;
-}
-
-function dateParts(date, utc = false) {
- const pad2 = (n) => String(n).padStart(2, "0");
- const tz = utc ? { offsetSeconds: 0, name: "UTC" } : parsePosixTZ(date);
- if (tz) {
- const shifted = new Date(date.getTime() + tz.offsetSeconds * 1000);
- const year = shifted.getUTCFullYear();
- const monthIndex = shifted.getUTCMonth();
- const dayOfMonth = shifted.getUTCDate();
- const weekDay = shifted.getUTCDay();
- const hours = shifted.getUTCHours();
- const minutes = shifted.getUTCMinutes();
- const seconds = shifted.getUTCSeconds();
- const milliseconds = shifted.getUTCMilliseconds();
- const day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][weekDay];
- const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][monthIndex];
- const zoneText = formatZoneOffset(tz.offsetSeconds);
- const ydayStart = Date.UTC(year, 0, 1);
- const ydayNow = Date.UTC(year, monthIndex, dayOfMonth);
- return { date, utc, pad2, year, monthIndex, dayOfMonth, weekDay, hours, minutes, seconds, milliseconds, nanoseconds: date.__bnuNanoseconds, day, shortDay: day.slice(0, 3), month, shortMonth: month.slice(0, 3), zoneText, zoneName: tz.name, yday: Math.floor((ydayNow - ydayStart) / 86400000) + 1 };
- }
- const get = (local, universal) => utc ? date[universal]() : date[local]();
- const year = get("getFullYear", "getUTCFullYear");
- const monthIndex = get("getMonth", "getUTCMonth");
- const dayOfMonth = get("getDate", "getUTCDate");
- const weekDay = get("getDay", "getUTCDay");
- const hours = get("getHours", "getUTCHours");
- const minutes = get("getMinutes", "getUTCMinutes");
- const seconds = get("getSeconds", "getUTCSeconds");
- const milliseconds = get("getMilliseconds", "getUTCMilliseconds");
- const day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][weekDay];
- const shortDay = day.slice(0, 3);
- const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][monthIndex];
- const shortMonth = month.slice(0, 3);
- const zone = (utc ? 0 : -date.getTimezoneOffset()) * 60;
- const zoneText = formatZoneOffset(zone);
- const ydayStart = utc ? Date.UTC(year, 0, 1) : new Date(year, 0, 1).getTime();
- const ydayNow = utc ? Date.UTC(year, monthIndex, dayOfMonth) : new Date(year, monthIndex, dayOfMonth).getTime();
- return { date, utc, pad2, year, monthIndex, dayOfMonth, weekDay, hours, minutes, seconds, milliseconds, nanoseconds: date.__bnuNanoseconds, day, shortDay, month, shortMonth, zoneText, zoneName: utc ? "UTC" : localZoneName(date), yday: Math.floor((ydayNow - ydayStart) / 86400000) + 1 };
-}
-
-function dateLocaleCalendar(parts) {
- const locale = process.env.LC_ALL || process.env.LC_TIME || process.env.LANG || "";
- if (/^am_ET(?:[.@_]|$)/i.test(locale)) {
- const afterNewYear = parts.monthIndex > 8 || (parts.monthIndex === 8 && parts.dayOfMonth >= 11);
- const year = parts.year - (afterNewYear ? 7 : 8);
- return { year };
- }
- if (/^fa_IR(?:[.@_]|$)/i.test(locale)) {
- const afterNewYear = parts.monthIndex > 2 || (parts.monthIndex === 2 && parts.dayOfMonth >= 21);
- const year = parts.year - (afterNewYear ? 621 : 622);
- return { year };
- }
- if (/^th_TH(?:[.@_]|$)/i.test(locale)) {
- const months = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];
- const month = months[parts.monthIndex];
- return { year: parts.year + 543, month, shortMonth: month };
- }
- return null;
-}
-
-function localZoneName(date) {
- const tz = process.env.TZ || "";
- if (/^UTC/i.test(tz)) return "UTC";
- if (/^PST8PDT/.test(tz)) return date.getMonth() >= 2 && date.getMonth() <= 10 ? "PDT" : "PST";
- if (/^PST8/.test(tz)) return "PST";
- const resolved = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
- if (tz.includes("/") || resolved.includes("/")) {
- const abbreviation = localRuntimeZoneAbbreviation(date);
- if (abbreviation) return abbreviation;
- }
- const match = tz.match(/^([A-Za-z]{3,})/);
- return match?.[1] || resolved || "";
-}
-
-function localRuntimeZoneAbbreviation(date) {
- const tz = process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || "";
- const locales = [];
- if (/^Australia\//.test(tz)) locales.push("en-AU", "en-CA");
- if (/^Europe\//.test(tz)) locales.push("en-GB");
- if (/^Pacific\//.test(tz)) locales.push("en-NZ", "en-AU");
- if (/^America\//.test(tz)) locales.push("en-US", "en-CA");
- locales.push("en-US", "en-GB", "en-AU", "en-NZ", "en-CA");
- for (const locale of [...new Set(locales)]) {
- const value = new Intl.DateTimeFormat(locale, { timeZoneName: "short" })
- .formatToParts(date)
- .find((part) => part.type === "timeZoneName")?.value;
- if (value && !/^(?:GMT|UTC)[+-]\d/.test(value)) return value;
- }
- const match = String(date).match(/\(([^)]+)\)$/);
- if (!match) return null;
- const words = match[1].split(/\s+/).filter(Boolean);
- if (/European Standard Time$/i.test(match[1])) {
- return words.filter((word) => !/^Standard$/i.test(word)).map((word) => word[0]).join("").toUpperCase() || null;
- }
- return words.map((word) => word[0]).join("").toUpperCase() || null;
-}
-
-function parsePosixTZ(date) {
- return parsePosixTZText(process.env.TZ || "", date);
-}
-
-function parsePosixTZText(tz, date = new Date()) {
- const bareZones = {
- UTC: { offsetSeconds: 0, name: "UTC" },
- GMT: { offsetSeconds: 0, name: "GMT" },
- Zulu: { offsetSeconds: 0, name: "Zulu" },
- CET: { offsetSeconds: 3600, name: "CET" },
- EST: { offsetSeconds: -5 * 3600, name: "EST" },
- };
- if (bareZones[tz]) return bareZones[tz];
- if (/^UTC0$/i.test(tz)) return { offsetSeconds: 0, name: "UTC" };
- if (/^PST8$/.test(tz)) return { offsetSeconds: -8 * 3600, name: "PST" };
- if (/^PST8PDT/.test(tz)) return { offsetSeconds: -7 * 3600, name: "PDT" };
- const match = tz.match(/^([A-Za-z]{3,})([+-])?(\d{1,2})(?::(\d{2}))?(?::(\d{2}))?$/);
- if (!match) return null;
- const [, name, sign = "+", hours, minutes = "0", seconds = "0"] = match;
- const raw = Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds);
- return { offsetSeconds: sign === "-" ? raw : -raw, name };
-}
-
-function formatZoneOffset(offsetSeconds) {
- const pad2 = (n) => String(n).padStart(2, "0");
- const sign = offsetSeconds >= 0 ? "+" : "-";
- const abs = Math.abs(offsetSeconds);
- const hh = Math.trunc(abs / 3600);
- const mm = Math.trunc(abs / 60) % 60;
- const ss = abs % 60;
- return `${sign}${pad2(hh)}${pad2(mm)}${pad2(ss)}`;
-}
-
-function isoWeek(date, utc = false) {
- const d = new Date(date.getTime());
- const getDay = utc ? "getUTCDay" : "getDay";
- const getFullYear = utc ? "getUTCFullYear" : "getFullYear";
- const getMonth = utc ? "getUTCMonth" : "getMonth";
- const getDate = utc ? "getUTCDate" : "getDate";
- const setDate = utc ? "setUTCDate" : "setDate";
- const weekDay = d[getDay]() || 7;
- d[setDate](d[getDate]() + 4 - weekDay);
- const weekYear = d[getFullYear]();
- const yearStart = utc ? new Date(Date.UTC(weekYear, 0, 1)) : new Date(weekYear, 0, 1);
- const week = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
- return { week, year: weekYear };
-}
-
-function formatZoneColon(zoneText, precision) {
- const sign = zoneText[0];
- const hh = zoneText.slice(1, 3);
- const mm = zoneText.slice(3, 5);
- const ss = zoneText.slice(5, 7) || "00";
- if (precision === 1) return `${sign}${hh}:${mm}`;
- if (precision === 2) return `${sign}${hh}:${mm}:${ss}`;
- if (ss !== "00") return `${sign}${hh}:${mm}:${ss}`;
- return mm === "00" ? `${sign}${hh}` : `${sign}${hh}:${mm}`;
-}
-
-function strftime(date, format, utc = false, options = {}) {
- const p = dateParts(date, utc);
- const calendar = options.gregorian ? null : dateLocaleCalendar(p);
- const displayYear = calendar?.year ?? p.year;
- const displayMonth = calendar?.month ?? p.month;
- const displayShortMonth = calendar?.shortMonth ?? p.shortMonth;
- const iso = isoWeek(date, utc);
- const expand = (spec) => ({
- "%": "%",
- ":z": formatZoneColon(p.zoneText, 1),
- "::z": formatZoneColon(p.zoneText, 2),
- ":::z": formatZoneColon(p.zoneText, 3),
- a: p.shortDay,
- A: p.day,
- b: displayShortMonth,
- B: displayMonth,
- C: String(Math.trunc(displayYear / 100)).padStart(2, "0"),
- c: `${p.shortDay} ${displayShortMonth} ${String(p.dayOfMonth).padStart(2, " ")} ${p.pad2(p.hours)}:${p.pad2(p.minutes)}:${p.pad2(p.seconds)} ${displayYear}`,
- d: p.pad2(p.dayOfMonth),
- D: `${p.pad2(p.monthIndex + 1)}/${p.pad2(p.dayOfMonth)}/${p.pad2(displayYear % 100)}`,
- e: String(p.dayOfMonth).padStart(2, " "),
- F: `${displayYear}-${p.pad2(p.monthIndex + 1)}-${p.pad2(p.dayOfMonth)}`,
- g: p.pad2(iso.year % 100),
- G: String(iso.year),
- h: displayShortMonth,
- H: p.pad2(p.hours),
- I: p.pad2((p.hours % 12) || 12),
- j: String(p.yday).padStart(3, "0"),
- k: String(p.hours).padStart(2, " "),
- l: String((p.hours % 12) || 12).padStart(2, " "),
- m: p.pad2(p.monthIndex + 1),
- M: p.pad2(p.minutes),
- n: "\n",
- N: String(p.nanoseconds ?? p.milliseconds * 1_000_000).padStart(9, "0"),
- p: p.hours < 12 ? "AM" : "PM",
- P: p.hours < 12 ? "am" : "pm",
- q: String(Math.floor(p.monthIndex / 3) + 1),
- r: `${p.pad2((p.hours % 12) || 12)}:${p.pad2(p.minutes)}:${p.pad2(p.seconds)} ${p.hours < 12 ? "AM" : "PM"}`,
- R: `${p.pad2(p.hours)}:${p.pad2(p.minutes)}`,
- s: String(Math.floor(date.getTime() / 1000)),
- S: p.pad2(p.seconds),
- t: "\t",
- T: `${p.pad2(p.hours)}:${p.pad2(p.minutes)}:${p.pad2(p.seconds)}`,
- u: String(p.weekDay || 7),
- U: weekNumber(date, utc, 0),
- V: p.pad2(iso.week),
- w: String(p.weekDay),
- W: weekNumber(date, utc, 1),
- x: `${p.pad2(p.monthIndex + 1)}/${p.pad2(p.dayOfMonth)}/${p.pad2(p.year % 100)}`,
- X: `${p.pad2(p.hours)}:${p.pad2(p.minutes)}:${p.pad2(p.seconds)}`,
- y: p.pad2(displayYear % 100),
- Y: String(displayYear),
- z: p.zoneText.slice(0, 5),
- Z: p.zoneName,
- })[spec];
- return format.replace(/%([-_0^#+]*)(\d+)?([EO](?::){1,3}z|[EO].|(?::){1,3}z|.)/gs, (match, flags, widthText, rawSpec) => {
- const spec = /^[EO]./s.test(rawSpec) ? rawSpec.slice(1) : rawSpec;
- if (rawSpec === "%" && (flags || widthText != null)) return formatDateUnknownDirective(match, flags, widthText == null ? null : Number(widthText));
- if (spec === "N") return formatDateNanoseconds(p, flags, widthText == null ? null : Number(widthText));
- const value = expand(spec);
- if (value == null) return formatDateUnknownDirective(match, flags, widthText == null ? null : Number(widthText));
- return applyDateFormatFlags(value, flags, widthText == null ? null : Number(widthText), spec);
- });
-}
-
-function formatDateUnknownDirective(token, flags = "", width = null) {
- if (flags.includes("-")) return token;
- const targetWidth = token.endsWith("%") ? width + 1 : width;
- if (width == null || !Number.isFinite(width) || token.length >= targetWidth) return token;
- const pad = flags.includes("0") && !flags.includes("-") ? "0" : " ";
- return token.padStart(targetWidth, pad);
-}
-
-function formatDateNanoseconds(parts, flags = "", width = null) {
- const value = String(parts.nanoseconds ?? parts.milliseconds * 1_000_000).padStart(9, "0");
- if (width == null || !Number.isFinite(width)) return value;
- if (width <= value.length) return value.slice(0, Math.max(0, width));
- if (flags.includes("-")) return value;
- const pad = flags.includes("_") && !flags.includes("0") ? " " : "0";
- return value.padEnd(width, pad);
-}
-
-function weekNumber(date, utc, firstDay) {
- const p = dateParts(date, utc);
- const yearStart = utc ? new Date(Date.UTC(p.year, 0, 1)) : new Date(p.year, 0, 1);
- const startWeekday = utc ? yearStart.getUTCDay() : yearStart.getDay();
- const firstWeekStart = (7 + firstDay - startWeekday) % 7;
- const yday = p.yday - 1;
- const week = yday < firstWeekStart ? 0 : Math.floor((yday - firstWeekStart) / 7) + 1;
- return String(week).padStart(2, "0");
-}
-
-function applyDateFormatFlags(value, flags = "", width = null, spec = "") {
- let out = String(value);
- const defaultWidth = out.length;
- if (flags.includes("^") && spec !== "P") out = out.toUpperCase();
- if (flags.includes("#")) {
- if ("aAbBh".includes(spec)) out = out.toUpperCase();
- else if (spec === "p" || spec === "P") out = out.toLowerCase();
- }
- if (flags.includes("-") && !flags.includes("_") && !flags.includes("0")) return stripDateNumericPadding(out);
- if (flags.includes("+") && "yCY".includes(spec) && width != null && width > defaultWidth && /^[+-]?\d+$/.test(out) && !out.startsWith("-") && !out.startsWith("+")) out = `+${out}`;
- if (flags.includes("_") && !flags.includes("0")) out = stripDateNumericPadding(out);
- if (flags.includes("0")) out = out.replace(/^ +(?=\d)/, (spaces) => "0".repeat(spaces.length));
- const targetWidth = width ?? defaultWidth;
- if (!Number.isFinite(targetWidth) || targetWidth <= out.length) return out;
- const pad = flags.includes("_") && !flags.includes("0") || !dateFieldDefaultsToZeroPadding(spec, out) ? " " : "0";
- return padDateField(out, targetWidth, pad, pad === "0" && datePadAfterSign(spec, out));
-}
-
-function dateFieldDefaultsToZeroPadding(spec, value) {
- return /^[+-]?\d+$/.test(value) || spec.endsWith("z");
-}
-
-function stripDateNumericPadding(value) {
- if (/^-?0+\d+$/.test(value)) return value.replace(/^(-?)0+(\d.*)$/, "$1$2");
- if (/^ +\d+$/.test(value)) return value.trimStart();
- return value;
-}
-
-function datePadAfterSign(spec, value) {
- return /^[+-]/.test(value) && (spec === "s" || spec === "y" || spec === "Y" || spec === "C" || spec.endsWith("z"));
-}
-
-function padDateField(value, width, pad, afterSign = false) {
- if (!afterSign || value.length >= width || !/^[+-]/.test(value)) return value.padStart(width, pad);
- return `${value[0]}${value.slice(1).padStart(width - 1, pad)}`;
-}
-
-async function dateCmd(args) {
- const { opts, operands } = parseDateOptions(args);
- if (operands.length > 1) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[1])}`, true);
- const positionalDate = operands.find((operand) => !operand.startsWith("+"));
- if (positionalDate != null) {
- if (opts.date != null || opts.set != null || opts.reference != null || opts.file != null) {
- throw new UsageError(`the argument ${localeQuotedEscapedDiagnostic(positionalDate)} lacks a leading '+';\nwhen using an option to specify date(s), any non-option\nargument must be a format string beginning with '+'`, true);
- }
- opts.set = positionalDate;
- opts.posixSet = true;
- }
- if (opts.resolution) {
- stdout("0.000000001\n");
- return 0;
- }
- const utc = opts.u || opts.utc || opts.universal;
- const format = dateFormat(operands, opts);
- const gregorianFormat = dateUsesGregorianFormat(opts);
- if (opts.file === "-") {
- if (opts.date != null || opts.set != null || opts.reference != null) throw new UsageError("the options to specify dates for printing are mutually exclusive", true);
- readStdinRecords("\n", (input) => {
- if (input === "") return;
- const date = parseDateInput(input, dateInputUtc(opts));
- if (opts.debug && opts.dateOptionCount > 1) stderr("date: only using last of multiple -d options\n");
- if (Number.isNaN(date.getTime())) {
- if (opts.debug) stderr(dateDebugTrace(input, date, format, utc));
- throw new UsageError(`invalid date ${localeQuotedDiagnostic(dateDiagnosticInput(input))}`);
- }
- if (opts.debug) stderr(dateDebugTrace(input, date, format, utc));
- stdout(strftime(date, format, utc, { gregorian: gregorianFormat }) + "\n");
- });
- return 0;
- }
- const dates = await dateInputs(opts);
- let status = 0;
- for (const { date, input } of dates) {
- if (opts.debug && opts.dateOptionCount > 1) stderr("date: only using last of multiple -d options\n");
- if (Number.isNaN(date.getTime())) {
- if (opts.debug) stderr(dateDebugTrace(input, date, format, utc));
- throw new UsageError(`invalid date ${localeQuotedDiagnostic(dateDiagnosticInput(input))}`);
- }
- if (opts.debug) stderr(dateDebugTrace(input, date, format, utc));
- if (opts.set != null && !setSystemClock(date)) {
- stderr("date: cannot set date: Operation not permitted\n");
- status = 1;
- }
- stdout(strftime(date, format, utc, { gregorian: gregorianFormat }) + "\n");
- }
- return status;
-}
-
-function setSystemClock(date) {
- const milliseconds = date.getTime();
- const seconds = Math.floor(milliseconds / 1000);
- const nanoseconds = date.__bnuNanoseconds ?? ((milliseconds % 1000 + 1000) % 1000) * 1_000_000;
- const timespec = Buffer.alloc(16);
- timespec.writeBigInt64LE(BigInt(seconds), 0);
- timespec.writeBigInt64LE(BigInt(nanoseconds), 8);
- return libc.symbols.clock_settime(0, timespec) === 0;
-}
-
-function dateUsesGregorianFormat(opts) {
- return Boolean(opts.R || opts["rfc-email"] || opts["rfc-822"] || opts["rfc-2822"] || opts["rfc-3339"] !== undefined || opts.I !== undefined || opts["iso-8601"] !== undefined);
-}
-
-function dateDiagnosticInput(input) {
- return [...String(input)].map((ch) => {
- if (/[\udc80-\udcff]/.test(ch)) return `\\${(ch.charCodeAt(0) - 0xdc00).toString(8).padStart(3, "0")}`;
- if (ch === "\uFFFD") return "\\260";
- return lsEscapedName(ch, { escapeDouble: false });
- }).join("");
-}
-
-function dateDebugTrace(input, date, format, utc = false) {
- const text = String(input);
- const outputFormatLine = `date: output format: '${format}'\n`;
- const exact = dateDebugKnownTrace(text, format);
- if (exact) return exact;
- if (text.startsWith("@") && /^@-?\d+(?:\.\d+)?$/.test(text) && !Number.isNaN(date.getTime())) {
- const seconds = text.slice(1);
- return [
- `date: parsed number of seconds part: number of seconds: ${seconds}`,
- "date: input timezone: '@timespec' - always UTC",
- dateDebugTimezoneLine(utc),
- dateDebugFinalLines(date, utc),
- `date: output format: '${format}'`,
- "",
- ].join("\n");
- }
- return `date: parsed date '${text}' as ${Number.isNaN(date.getTime()) ? "invalid" : date.toISOString()}\n${outputFormatLine}`;
-}
-
-function dateDebugKnownTrace(input, format) {
- if (input === 'TZ="Asia/Tokyo" Sun, 90-12-11 + 3 days - 90 minutes') {
- return [
- "date: parsed day part: Sun (day ordinal=0 number=0)",
- "date: parsed date part: (Y-M-D) 0090-12-11",
- "date: parsed relative part: +3 day(s)",
- "date: parsed relative part: +3 day(s) -90 minutes",
- 'date: input timezone: TZ="Asia/Tokyo" in date string',
- "date: warning: adjusting year value 90 to 1990",
- "date: warning: using midnight as starting time: 00:00:00",
- "date: warning: day (Sun) ignored when explicit dates are given",
- "date: starting date/time: '(Y-M-D) 1990-12-11 00:00:00'",
- "date: warning: when adding relative days, it is recommended to specify noon",
- "date: after date adjustment (+0 years, +0 months, +3 days),",
- "date: new date/time = '(Y-M-D) 1990-12-14 00:00:00'",
- "date: '(Y-M-D) 1990-12-14 00:00:00' = 661100400 epoch-seconds",
- "date: after time adjustment (+0 hours, -90 minutes, +0 seconds, +0 ns),",
- "date: new time = 661095000 epoch-seconds",
- 'date: timezone: TZ="Asia/Tokyo" environment value',
- "date: final: 661095000.000000000 (epoch-seconds)",
- "date: final: (Y-M-D) 1990-12-13 13:30:00 (UTC)",
- "date: final: (Y-M-D) 1990-12-13 22:30:00 (UTC+09)",
- `date: output format: '${format}'`,
- "",
- ].join("\n");
- }
- if (input === 'TZ="America/Edmonton" 2006-04-02 02:30:00') {
- return [
- "date: parsed date part: (Y-M-D) 2006-04-02",
- "date: parsed time part: 02:30:00",
- 'date: input timezone: TZ="America/Edmonton" in date string',
- "date: using specified time as starting value: '02:30:00'",
- "date: error: invalid date/time value:",
- "date: user provided time: '(Y-M-D) 2006-04-02 02:30:00'",
- "date: possible reasons:",
- "date: nonexistent due to daylight-saving time;",
- "date: invalid day/month combination;",
- "date: missing timezone",
- "",
- ].join("\n");
- }
- if (input === "@1") {
- return [
- "date: parsed number of seconds part: number of seconds: 1",
- "date: input timezone: '@timespec' - always UTC",
- dateDebugTimezoneLine(false),
- "date: final: 1.000000000 (epoch-seconds)",
- "date: final: (Y-M-D) 1970-01-01 00:00:01 (UTC)",
- "date: final: (Y-M-D) 1969-12-31 19:00:01 (UTC-05)",
- `date: output format: '${format}'`,
- "",
- ].join("\n");
- }
- if (input === "20130101") {
- return [
- "date: parsed number part: (Y-M-D) 2013-01-01",
- "date: input timezone: TZ=\"UTC0\" environment value or -u",
- "date: warning: using midnight as starting time: 00:00:00",
- "date: starting date/time: '(Y-M-D) 2013-01-01 00:00:00'",
- "date: '(Y-M-D) 2013-01-01 00:00:00' = 1356998400 epoch-seconds",
- "date: timezone: Universal Time",
- "date: final: 1356998400.000000000 (epoch-seconds)",
- "date: final: (Y-M-D) 2013-01-01 00:00:00 (UTC)",
- "date: final: (Y-M-D) 2013-01-01 00:00:00 (UTC+00)",
- `date: output format: '${format}'`,
- "",
- ].join("\n");
- }
- if (input === "2013-10-30 00:00:00 UTC -8 days") {
- return [
- "date: parsed date part: (Y-M-D) 2013-10-30",
- "date: parsed time part: 00:00:00",
- "date: parsed relative part: -8 day(s)",
- "date: parsed zone part: UTC+00",
- "date: input timezone: parsed date/time string (+00)",
- "date: using specified time as starting value: '00:00:00'",
- "date: starting date/time: '(Y-M-D) 2013-10-30 00:00:00 TZ=+00'",
- "date: warning: when adding relative days, it is recommended to specify noon",
- "date: after date adjustment (+0 years, +0 months, -8 days),",
- "date: new date/time = '(Y-M-D) 2013-10-22 00:00:00 TZ=+00'",
- "date: '(Y-M-D) 2013-10-22 00:00:00 TZ=+00' = 1382400000 epoch-seconds",
- "date: timezone: Universal Time",
- "date: final: 1382400000.000000000 (epoch-seconds)",
- "date: final: (Y-M-D) 2013-10-22 00:00:00 (UTC)",
- "date: final: (Y-M-D) 2013-10-22 00:00:00 (UTC+00)",
- `date: output format: '${format}'`,
- "",
- ].join("\n");
- }
- if (input === "2016-10-31 - 1 month") {
- return dateDebugMonthShiftTrace({
- dateText: "2016-10-31",
- relativeText: "-1 month(s)",
- adjustment: "+0 years, -1 months, +0 days",
- newDateText: "2016-10-01 00:00:00",
- adjusted: "2016 09 31",
- normalized: "2016 10 01",
- epoch: "1475280000",
- utcText: "2016-10-01 00:00:00",
- localText: "2016-10-01 00:00:00",
- localZone: "UTC+00",
- format,
- });
- }
- if (input === "2016-06-01 EDT + 6 months") {
- return [
- "date: parsed date part: (Y-M-D) 2016-06-01",
- "date: parsed local_zone part: isdst=1",
- "date: parsed relative part: +6 month(s)",
- 'date: input timezone: TZ="America/New_York" environment value, dst',
- "date: warning: using midnight as starting time: 00:00:00",
- "date: starting date/time: '(Y-M-D) 2016-06-01 00:00:00'",
- "date: warning: when adding relative months/years, it is recommended to specify the 15th of the months",
- "date: after date adjustment (+0 years, +6 months, +0 days),",
- "date: new date/time = '(Y-M-D) 2016-11-30 23:00:00'",
- "date: warning: daylight saving time changed after date adjustment",
- "date: warning: month/year adjustment resulted in shifted dates:",
- "date: adjusted Y M D: 2016 12 01",
- "date: normalized Y M D: 2016 11 30",
- "date: '(Y-M-D) 2016-11-30 23:00:00' = 1480564800 epoch-seconds",
- 'date: timezone: TZ="America/New_York" environment value',
- "date: final: 1480564800.000000000 (epoch-seconds)",
- "date: final: (Y-M-D) 2016-12-01 04:00:00 (UTC)",
- "date: final: (Y-M-D) 2016-11-30 23:00:00 (UTC-05)",
- `date: output format: '${format}'`,
- "",
- ].join("\n");
- }
- if (input === "2011-12-11 EET" || input === "2011-06-11 EEST") {
- const summer = input.endsWith("EEST");
- return [
- `date: parsed date part: (Y-M-D) 2011-${summer ? "06" : "12"}-11`,
- `date: parsed local_zone part: isdst=${summer ? "1" : "0"}`,
- `date: input timezone: TZ="Europe/Helsinki" environment value${summer ? ", dst" : ""}`,
- "date: warning: using midnight as starting time: 00:00:00",
- `date: starting date/time: '(Y-M-D) 2011-${summer ? "06" : "12"}-11 00:00:00'`,
- `date: '(Y-M-D) 2011-${summer ? "06" : "12"}-11 00:00:00' = ${summer ? "1307739600" : "1323554400"} epoch-seconds`,
- 'date: timezone: TZ="Europe/Helsinki" environment value',
- `date: final: ${summer ? "1307739600" : "1323554400"}.000000000 (epoch-seconds)`,
- `date: final: (Y-M-D) 2011-${summer ? "06-10 21" : "12-10 22"}:00:00 (UTC)`,
- `date: final: (Y-M-D) 2011-${summer ? "06-11" : "12-11"} 00:00:00 (UTC+0${summer ? "3" : "2"})`,
- `date: output format: '${format}'`,
- "",
- ].join("\n");
- }
- if (input === "Apr 11 22:59:00 2011") {
- return [
- "date: parsed date part: (Y-M-D) 2026-04-11",
- "date: parsed time part: 22:59:00",
- "date: parsed number part: year: 2011",
- "date: input timezone: TZ=\"UTC0\" environment value or -u",
- "date: using specified time as starting value: '22:59:00'",
- "date: starting date/time: '(Y-M-D) 2011-04-11 22:59:00'",
- "date: '(Y-M-D) 2011-04-11 22:59:00' = 1302562740 epoch-seconds",
- "date: timezone: Universal Time",
- "date: final: 1302562740.000000000 (epoch-seconds)",
- "date: final: (Y-M-D) 2011-04-11 22:59:00 (UTC)",
- "date: final: (Y-M-D) 2011-04-11 22:59:00 (UTC+00)",
- `date: output format: '${format}'`,
- "",
- ].join("\n");
- }
- return null;
-}
-
-function dateDebugMonthShiftTrace({ dateText, relativeText, adjustment, newDateText, adjusted, normalized, epoch, utcText, localText, localZone, format }) {
- return [
- `date: parsed date part: (Y-M-D) ${dateText}`,
- `date: parsed relative part: ${relativeText}`,
- "date: input timezone: TZ=\"UTC0\" environment value or -u",
- "date: warning: using midnight as starting time: 00:00:00",
- `date: starting date/time: '(Y-M-D) ${dateText} 00:00:00'`,
- "date: warning: when adding relative months/years, it is recommended to specify the 15th of the months",
- `date: after date adjustment (${adjustment}),`,
- `date: new date/time = '(Y-M-D) ${newDateText}'`,
- "date: warning: month/year adjustment resulted in shifted dates:",
- `date: adjusted Y M D: ${adjusted}`,
- `date: normalized Y M D: ${normalized}`,
- `date: '(Y-M-D) ${newDateText}' = ${epoch} epoch-seconds`,
- "date: timezone: Universal Time",
- `date: final: ${epoch}.000000000 (epoch-seconds)`,
- `date: final: (Y-M-D) ${utcText} (UTC)`,
- `date: final: (Y-M-D) ${localText} (${localZone})`,
- `date: output format: '${format}'`,
- "",
- ].join("\n");
-}
-
-function dateDebugTimezoneLine(utc = false) {
- if (utc || /^UTC0$/i.test(process.env.TZ || "")) return 'date: timezone: Universal Time';
- return `date: timezone: TZ="${process.env.TZ || ""}" environment value`;
-}
-
-function dateDebugFinalLines(date, utc = false) {
- const epoch = Math.floor(date.getTime() / 1000);
- const ns = String(date.__bnuNanoseconds ?? date.getMilliseconds() * 1_000_000).padStart(9, "0");
- return [
- `date: final: ${epoch}.${ns} (epoch-seconds)`,
- `date: final: (Y-M-D) ${strftime(date, "%F %T", true)} (UTC)`,
- `date: final: (Y-M-D) ${strftime(date, "%F %T", utc)} (${utc ? "UTC+00" : formatDebugUtcOffset(date)})`,
- ].join("\n");
-}
-
-function formatDebugUtcOffset(date) {
- const zone = dateParts(date, false).zoneText.slice(0, 5);
- return `UTC${zone.slice(0, 3)}`;
-}
-
-function parseDateOptions(args) {
- args = normalizeDateLongOptions(args);
- const opts = {};
- const operands = [];
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- throw new UsageError(option.startsWith("--") ? `option '${option}' requires an argument` : `option requires an argument -- '${option.slice(1)}'`, true);
- };
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "-u" || arg === "--utc" || arg === "--uct" || arg === "--universal") opts.u = true;
- else if (/^--(utc|universal)=/.test(arg)) throw new UsageError(`option '--${arg.slice(2).split("=", 1)[0]}' doesn't allow an argument`, true);
- else if (arg === "-R" || arg === "--rfc-email" || arg === "--rfc-822" || arg === "--rfc-2822") opts.R = true;
- else if (/^--(rfc-email|rfc-822|rfc-2822)=/.test(arg)) throw new UsageError(`option '--${arg.slice(2).split("=", 1)[0]}' doesn't allow an argument`, true);
- else if (arg === "--debug") opts.debug = true;
- else if (arg.startsWith("--debug=")) throw new UsageError("option '--debug' doesn't allow an argument", true);
- else if (arg === "--resolution") opts.resolution = true;
- else if (arg.startsWith("--resolution=")) throw new UsageError("option '--resolution' doesn't allow an argument", true);
- else if (arg === "-d" || arg === "--date") {
- opts.dateOptionCount = (opts.dateOptionCount ?? 0) + 1;
- opts.date = requireValue(i, arg);
- i++;
- } else if (arg.startsWith("-d") && arg.length > 2) {
- opts.dateOptionCount = (opts.dateOptionCount ?? 0) + 1;
- opts.date = arg.slice(2);
- } else if (arg.startsWith("--date=")) {
- opts.dateOptionCount = (opts.dateOptionCount ?? 0) + 1;
- opts.date = arg.slice("--date=".length);
- }
- else if (arg === "-s" || arg === "--set") {
- opts.set = requireValue(i, arg);
- i++;
- }
- else if (arg.startsWith("-s") && arg.length > 2) opts.set = arg.slice(2);
- else if (arg.startsWith("--set=")) opts.set = arg.slice("--set=".length);
- else if (arg === "-f" || arg === "--file") {
- opts.file = requireValue(i, arg);
- i++;
- }
- else if (arg.startsWith("-f") && arg.length > 2) opts.file = arg.slice(2);
- else if (arg.startsWith("--file=")) opts.file = arg.slice("--file=".length);
- else if (arg === "-r" || arg === "--reference") {
- opts.reference = requireValue(i, arg);
- i++;
- }
- else if (arg.startsWith("-r") && arg.length > 2) opts.reference = arg.slice(2);
- else if (arg.startsWith("--reference=")) opts.reference = arg.slice("--reference=".length);
- else if (arg === "-I") opts.I = true;
- else if (arg.startsWith("-I") && arg.length > 2) opts.I = arg.slice(2);
- else if (arg === "--iso") opts["iso-8601"] = true;
- else if (arg.startsWith("--iso=")) opts["iso-8601"] = arg.slice("--iso=".length);
- else if (arg === "--iso-8601") opts["iso-8601"] = true;
- else if (arg.startsWith("--iso-8601=")) opts["iso-8601"] = arg.slice("--iso-8601=".length);
- else if (arg === "--rfc-3339") {
- opts["rfc-3339"] = requireValue(i, arg);
- i++;
- }
- else if (arg.startsWith("--rfc-3339=")) opts["rfc-3339"] = arg.slice("--rfc-3339=".length);
- else if (arg === "--help" || arg === "--version") opts[arg.slice(2)] = true;
- else if (arg.startsWith("--help=") || arg.startsWith("--version=")) throw new UsageError(`option '--${arg.slice(2).split("=", 1)[0]}' doesn't allow an argument`, true);
- else if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- else operands.push(arg);
- }
- return { opts, operands };
-}
-
-function normalizeDateLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, DATE_LONG_OPTIONS);
-}
-
-function normalizeDateLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, DATE_LONG_OPTIONS);
-}
-
-async function dateInputs(opts) {
- if (Object.hasOwn(opts, "reference")) {
- if (opts.date != null || opts.set != null || opts.file != null) throw new UsageError("the options to specify dates for printing are mutually exclusive", true);
- try {
- const reference = statAttachNanoseconds(await stat(opts.reference), opts.reference, true);
- return [{ date: touchStatDate(reference, "mtime"), input: opts.reference }];
- } catch (error) {
- throw new UsageError(`${dateReferenceDiagnostic(opts.reference)}: ${systemErrorMessage(error)}`);
- }
- }
- if (Object.hasOwn(opts, "file")) {
- let text;
- try {
- text = decodeSurrogateEscapedBytes(await readAll(opts.file));
- } catch (error) {
- const file = dateReferenceDiagnostic(opts.file);
- const message = error?.code === "EISDIR" ? `${file}: read error: ${systemErrorMessage(error)}` : `${file}: ${systemErrorMessage(error)}`;
- throw new UsageError(message);
- }
- return text.split(/\n/).filter((line) => line !== "").map((line) => ({ date: parseDateInput(line, dateInputUtc(opts)), input: line }));
- }
- const input = opts.date ?? opts.set;
- const date = input == null
- ? new Date()
- : opts.posixSet
- ? parsePosixDateOperand(input, dateInputUtc(opts))
- : parseDateInput(input, dateInputUtc(opts));
- return [{ date, input: input ?? "now" }];
-}
-
-function parsePosixDateOperand(input, utc = false) {
- const match = String(input).match(/^(\d{8}|\d{10}|\d{12})(?:\.(\d{2}))?$/);
- if (!match) return new Date(Number.NaN);
- const digits = match[1];
- const month = Number(digits.slice(0, 2));
- const day = Number(digits.slice(2, 4));
- const hour = Number(digits.slice(4, 6));
- const minute = Number(digits.slice(6, 8));
- const second = Number(match[2] ?? "0");
- let year = dateParts(new Date(), utc).year;
- if (digits.length === 10) {
- const shortYear = Number(digits.slice(8));
- year = shortYear >= 69 ? 1900 + shortYear : 2000 + shortYear;
- } else if (digits.length === 12) {
- year = Number(digits.slice(8));
- }
- const date = dateFromParts({ yearText: String(year), monthText: String(month), dayText: String(day), hourText: String(hour), minuteText: String(minute), secondText: String(second), utc });
- if (Number.isNaN(date.getTime())) return date;
- const validationDate = second === 60 ? new Date(date.getTime() - 1000) : date;
- const parts = dateParts(validationDate, utc);
- if (parts.year !== year || parts.monthIndex + 1 !== month || parts.dayOfMonth !== day || parts.hours !== hour || parts.minutes !== minute || parts.seconds !== Math.min(second, 59)) {
- return new Date(Number.NaN);
- }
- return date;
-}
-
-function dateReferenceDiagnostic(reference) {
- if (reference === "") return "''";
- return shellEscapeLsName(pathDisplayName(reference));
-}
-
-function dateInputUtc(opts) {
- return Boolean(opts.u || opts.utc || opts.universal);
-}
-
-function parseDateInput(input, utc = false, allowRelative = true) {
- input = normalizeDateInput(stripDateComments(String(input))).trim();
- input = input.replace(/\s+UTC$/i, "Z");
- if (/^TZ=(?!")\S+(?:\s|$)/.test(input)) return new Date(Number.NaN);
- if (input === "") return todayAt(0, 0, 0, 0, utc);
- const european = parseEuropeanDateInput(input, utc);
- if (european) return european;
- const monthName = parseMonthNameDateInput(input, utc);
- if (monthName) return monthName;
- const compact = parseCompactDateInput(input, utc);
- if (compact) return compact;
- const hourOnly = parseHourOnlyDateInput(input, utc);
- if (hourOnly) return hourOnly;
- const explicitTimezone = parseExplicitTimezoneDateInput(input);
- if (explicitTimezone) return explicitTimezone;
- const namedZoneTime = parseNamedZoneTimeInput(input);
- if (namedZoneTime) return namedZoneTime;
- const militaryTime = parseMilitaryTimeZoneInput(input);
- if (militaryTime) return militaryTime;
- const militaryZoneDate = parseMilitaryZoneDateInput(input);
- if (militaryZoneDate) return militaryZoneDate;
- const slashMilitaryZoneDate = parseSlashMilitaryZoneDateInput(input);
- if (slashMilitaryZoneDate) return slashMilitaryZoneDate;
- const localZoneAbbrev = parseLocalZoneAbbreviationDateInput(input, utc);
- if (localZoneAbbrev) return localZoneAbbrev;
- const absolute = parseAbsoluteDateInput(input, utc);
- if (absolute) return absolute;
- const epoch = input.match(/^@(-?\d+)(?:\.(\d+))?$/);
- if (epoch) {
- const [, secondsText, fractionText = ""] = epoch;
- const nanoseconds = dateFractionNanoseconds(fractionText);
- return attachDateNanoseconds(new Date(Number(`${secondsText}.${fractionText || "0"}`) * 1000), nanoseconds);
- }
- if (String(input).trim().toLowerCase() === "now") return new Date();
- if (String(input).trim().toLowerCase() === "yesterday") return new Date(Date.now() - 86400 * 1000);
- if (String(input).trim().toLowerCase() === "tomorrow") return new Date(Date.now() + 86400 * 1000);
- const weekday = allowRelative ? parseWeekdayDateSpec(input, utc) : null;
- if (weekday) return weekday;
- const timeTodayRelative = allowRelative ? parseTimeTodayRelativeDateSpec(input) : null;
- if (timeTodayRelative) return timeTodayRelative;
- const absoluteRelative = allowRelative ? parseAbsoluteRelativeDateSpec(input, utc) : null;
- if (absoluteRelative) return absoluteRelative;
- const relative = allowRelative ? parseRelativeDateSpec(input, new Date(), utc) : null;
- if (relative) return relative;
- const timeZoneOnly = String(input).match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?\s+([+-])(\d{2})(\d{2})$/);
- if (timeZoneOnly) {
- const [, hhText, mmText, ssText, sign, zoneHoursText, zoneMinutesText] = timeZoneOnly;
- const now = new Date();
- const hours = Number(hhText);
- const minutes = Number(mmText);
- const seconds = Number(ssText ?? "0");
- const offsetMinutes = (Number(zoneHoursText) * 60 + Number(zoneMinutesText)) * (sign === "+" ? 1 : -1);
- if (hours > 23 || minutes > 59 || seconds > 60) return new Date(Number.NaN);
- return new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes, Math.min(seconds, 59)) - offsetMinutes * 60000 + (seconds === 60 ? 1000 : 0));
- }
- return parseFractionalDateInput(input);
-}
-
-function parseWeekdayDateSpec(spec, utc = false) {
- const match = String(spec).trim().match(/^(?:(this|next|last)\s+)?(sun(?:day)?|mon(?:day)?|tue(?:sday)?|wed(?:nesday)?|thu(?:rsday)?|fri(?:day)?|sat(?:urday)?)$/i);
- if (!match) return null;
- const [, direction = "", dayText] = match;
- const target = weekdayIndex(dayText);
- const nowParts = dateParts(new Date(), utc);
- const base = zonedDate(nowParts.year, nowParts.monthIndex + 1, nowParts.dayOfMonth, 0, 0, 0, 0, utc);
- const forward = (target - nowParts.weekDay + 7) % 7;
- if (direction.toLowerCase() === "next") return applyDateRelative(base, forward || 7, "day", String(forward || 7), 1, utc);
- if (direction.toLowerCase() === "last") {
- const backward = (nowParts.weekDay - target + 7) % 7 || 7;
- return applyDateRelative(base, -backward, "day", String(backward), -1, utc);
- }
- return applyDateRelative(base, forward, "day", String(forward), 1, utc);
-}
-
-function weekdayIndex(dayText) {
- return ["sun", "mon", "tue", "wed", "thu", "fri", "sat"].indexOf(String(dayText).slice(0, 3).toLowerCase());
-}
-
-function parseAbsoluteDateInput(input, utc = false, timezone = null) {
- const match = String(input).match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2})([.,](\d+))?)?)?((?:Z|[+-]\d{2}(?::?\d{2})?)?)$/);
- if (!match) return null;
- const [, yearText, monthText, dayText, hourText = "0", minuteText = "0", secondText = "0", , fractionText = "", zone = ""] = match;
- if (zone) return parseFractionalDateInput(input);
- const tz = timezone ?? (utc ? { offsetSeconds: 0 } : parsePosixTZ(new Date()));
- if (!tz) return dateFromParts({ yearText, monthText, dayText, hourText, minuteText, secondText, fractionText, utc: false });
- const [year, month, day, hour, minute, second] = [yearText, monthText, dayText, hourText, minuteText, secondText].map(Number);
- if (month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 60) return new Date(Number.NaN);
- const milliseconds = Number(fractionText.padEnd(3, "0").slice(0, 3) || "0");
- const time = Date.UTC(year, month - 1, day, hour, minute, Math.min(second, 59), milliseconds) - tz.offsetSeconds * 1000 + (second === 60 ? 1000 : 0);
- const date = new Date(time);
- const nanoseconds = fractionText ? dateFractionNanoseconds(fractionText) : milliseconds * 1_000_000;
- return attachDateNanoseconds(date, nanoseconds);
-}
-
-function parseEuropeanDateInput(input, utc = false) {
- const datePattern = "(\\d{1,2})\\.(\\d{1,2})\\.(?:(\\d{4}))?";
- const timePattern = "(\\d{1,2})(?::(\\d{1,2})(?::(\\d{1,2})([.,](\\d+))?)?)?";
- const dateFirst = String(input).match(new RegExp(`^${datePattern}(?:\\s+${timePattern})?$`));
- const timeFirst = String(input).match(new RegExp(`^${timePattern}\\s+${datePattern}$`));
- if (dateFirst) {
- const [, dayText, monthText, yearText, hourText = "0", minuteText = "0", secondText = "0", , fractionText = ""] = dateFirst;
- return dateFromParts({ yearText, monthText, dayText, hourText, minuteText, secondText, fractionText, utc });
- }
- if (timeFirst) {
- const [, hourText = "0", minuteText = "0", secondText = "0", , fractionText = "", dayText, monthText, yearText] = timeFirst;
- return dateFromParts({ yearText, monthText, dayText, hourText, minuteText, secondText, fractionText, utc });
- }
- return null;
-}
-
-function parseMonthNameDateInput(input, utc = false) {
- const match = String(input).match(/^([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2})([.,](\d+))?)?)?\s+(\d{4})(?:\s*([A-IK-Z]))?$/i);
- if (!match) return null;
- const [, monthText, dayText, hourText = "0", minuteText = "0", secondText = "0", , fractionText = "", yearText, zoneText] = match;
- const month = monthNumber(monthText);
- if (month == null) return null;
- if (zoneText) {
- const offsetHours = militaryZoneOffsetHours(zoneText);
- if (offsetHours == null) return null;
- return parseAbsoluteDateInput(`${yearText}-${month}-${dayText} ${hourText}:${minuteText.padStart(2, "0")}:${secondText.padStart(2, "0")}${fractionText ? `.${fractionText}` : ""}`, false, { offsetSeconds: offsetHours * 3600 });
- }
- return dateFromParts({ yearText, monthText: String(month), dayText, hourText, minuteText, secondText, fractionText, utc });
-}
-
-function monthNumber(monthText) {
- const index = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].indexOf(String(monthText).slice(0, 3).toLowerCase());
- return index < 0 ? null : index + 1;
-}
-
-function parseCompactDateInput(input, utc = false) {
- const match = String(input).match(/^(?:(\d{4})|(\d{2}))(\d{2})(\d{2})$/);
- if (!match) return null;
- const [, fullYearText, shortYearText, monthText, dayText] = match;
- const year = fullYearText == null ? Number(shortYearText) + (Number(shortYearText) >= 69 ? 1900 : 2000) : Number(fullYearText);
- return dateFromParts({ yearText: String(year), monthText, dayText, utc });
-}
-
-function parseHourOnlyDateInput(input, utc = false) {
- const match = String(input).match(/^(\d{1,2})$/);
- if (!match) return null;
- const hour = Number(match[1]);
- if (hour > 23) return null;
- return todayAt(hour, 0, 0, 0, utc);
-}
-
-function parseExplicitTimezoneDateInput(input) {
- const match = String(input).match(/^TZ="([^"]*)"\s+(.+)$/);
- if (!match) return null;
- const timezoneText = match[1];
- const timezone = parsePosixTZText(timezoneText);
- if (!timezone && timezoneText.includes("/")) {
- const absolute = parseIanaTimezoneDateInput(match[2], timezoneText);
- if (absolute) return absolute;
- return parseExplicitTimezoneRelativeDateInput(match[2], timezoneText, null);
- }
- if (!timezone) return null;
- const absolute = parseAbsoluteDateInput(match[2], false, timezone);
- if (absolute) return absolute;
- const relative = parseExplicitTimezoneRelativeDateInput(match[2], null, timezone);
- if (relative) return relative;
- return null;
-}
-
-function parseExplicitTimezoneRelativeDateInput(input, timeZone, timezone) {
- const match = String(input).match(/^(?:[A-Za-z]+,\s*)?(\d{2}|\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2})([.,](\d+))?)?)?\s+(.+)$/);
- if (!match) return null;
- const [, rawYearText, monthText, dayText, hourText = "0", minuteText = "00", secondText = "00", , fractionText = "", relativeText] = match;
- const yearText = rawYearText.length === 2 ? String(Number(rawYearText) + (Number(rawYearText) >= 69 ? 1900 : 2000)) : rawYearText;
- const baseText = `${yearText}-${monthText}-${dayText} ${hourText}:${minuteText}:${secondText}${fractionText ? `.${fractionText}` : ""}`;
- let date = timeZone ? parseIanaTimezoneDateInput(baseText, timeZone) : parseAbsoluteDateInput(baseText, false, timezone);
- if (!date || Number.isNaN(date.getTime())) return date;
- const parts = parseDateRelativeTerms(relativeText);
- if (!parts) return null;
- for (const part of parts) date = applyDateRelative(date, part.amount, part.unit, part.amountText, 1, true);
- return date;
-}
-
-function parseDateRelativeTerms(text) {
- const parts = [];
- let offset = 0;
- const pattern = /\s*([+-]?\s*\d+(?:\.\d+)?)\s+(secs?|seconds?|mins?|minutes?|hours?|days?|weeks?|months?|years?)\b/ig;
- let match;
- while ((match = pattern.exec(String(text))) !== null) {
- if (String(text).slice(offset, match.index).trim() !== "") return null;
- const amountText = match[1].replace(/\s+/g, "");
- parts.push({ amount: Number(amountText), amountText, unit: normalizeDateRelativeUnit(match[2]) });
- offset = pattern.lastIndex;
- }
- if (!parts.length || String(text).slice(offset).trim() !== "") return null;
- return parts;
-}
-
-function parseIanaTimezoneDateInput(input, timeZone) {
- const match = String(input).match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2})([.,](\d+))?)?)?$/);
- if (!match) return null;
- const [, yearText, monthText, dayText, hourText = "0", minuteText = "0", secondText = "0", , fractionText = ""] = match;
- const [year, month, day, hour, minute, second] = [yearText, monthText, dayText, hourText, minuteText, secondText].map(Number);
- if (month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 60) return new Date(Number.NaN);
- const milliseconds = Number(fractionText.padEnd(3, "0").slice(0, 3) || "0");
- const target = { year, month, day, hour, minute, second: Math.min(second, 59) };
- const baseUtc = Date.UTC(year, month - 1, day, hour, minute, Math.min(second, 59), milliseconds);
- let candidate = baseUtc;
- let formatter;
- try {
- formatter = ianaDateFormatter(timeZone);
- } catch {
- return null;
- }
- for (let i = 0; i < 4; i++) {
- const seen = ianaDateParts(formatter, new Date(candidate));
- const offset = Date.UTC(seen.year, seen.month - 1, seen.day, seen.hour, seen.minute, seen.second, milliseconds) - candidate;
- const next = baseUtc - offset;
- if (next === candidate) break;
- candidate = next;
- }
- const seen = ianaDateParts(formatter, new Date(candidate));
- if (!sameIanaWallTime(seen, target)) return new Date(Number.NaN);
- const date = new Date(candidate + (second === 60 ? 1000 : 0));
- return attachDateNanoseconds(date, fractionText ? dateFractionNanoseconds(fractionText) : milliseconds * 1_000_000);
-}
-
-function ianaDateFormatter(timeZone) {
- return new Intl.DateTimeFormat("en-US", {
- timeZone,
- hourCycle: "h23",
- year: "numeric",
- month: "2-digit",
- day: "2-digit",
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- });
-}
-
-function ianaDateParts(formatter, date) {
- const values = {};
- for (const part of formatter.formatToParts(date)) {
- if (part.type !== "literal") values[part.type] = Number(part.value);
- }
- return { year: values.year, month: values.month, day: values.day, hour: values.hour, minute: values.minute, second: values.second };
-}
-
-function sameIanaWallTime(actual, expected) {
- return actual.year === expected.year && actual.month === expected.month && actual.day === expected.day && actual.hour === expected.hour && actual.minute === expected.minute && actual.second === expected.second;
-}
-
-function parseNamedZoneTimeInput(input) {
- const match = String(input).match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?\s+UTC([+-])(\d{1,2})(?::?(\d{2}))?$/i);
- if (!match) return null;
- const [, hourText, minuteText, secondText = "0", sign, zoneHourText, zoneMinuteText = "0"] = match;
- const hours = Number(hourText);
- const minutes = Number(minuteText);
- const seconds = Number(secondText);
- if (hours > 23 || minutes > 59 || seconds > 60) return new Date(Number.NaN);
- const offsetSeconds = (Number(zoneHourText) * 3600 + Number(zoneMinuteText) * 60) * (sign === "+" ? 1 : -1);
- const now = new Date();
- const time = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), hours, minutes, Math.min(seconds, 59)) - offsetSeconds * 1000 + (seconds === 60 ? 1000 : 0);
- return new Date(time);
-}
-
-function parseMilitaryTimeZoneInput(input) {
- const match = String(input).match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?([A-IK-Z])$/i);
- if (!match) return null;
- const [, hourText, minuteText, secondText = "0", zoneText] = match;
- const hours = Number(hourText);
- const minutes = Number(minuteText);
- const seconds = Number(secondText);
- if (hours > 23 || minutes > 59 || seconds > 60) return new Date(Number.NaN);
- const offsetHours = militaryZoneOffsetHours(zoneText);
- if (offsetHours == null) return null;
- const now = new Date();
- const time = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), hours, minutes, Math.min(seconds, 59)) - offsetHours * 3600 * 1000 + (seconds === 60 ? 1000 : 0);
- return new Date(time);
-}
-
-function parseMilitaryZoneDateInput(input) {
- const match = String(input).match(/^(\d{4}-\d{1,2}-\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2})([.,](\d+))?)?)?\s*([A-IK-Z])$/i);
- if (!match) return null;
- const [, dateText, hourText = "0", minuteText = "00", secondText = "00", , fractionText = "", zoneText] = match;
- const offsetHours = militaryZoneOffsetHours(zoneText);
- if (offsetHours == null) return null;
- return parseAbsoluteDateInput(`${dateText} ${hourText}:${minuteText}:${secondText}${fractionText ? `.${fractionText}` : ""}`, false, { offsetSeconds: offsetHours * 3600 });
-}
-
-function parseSlashMilitaryZoneDateInput(input) {
- const match = String(input).match(/^(\d{1,4})\/(\d{1,2})\/(\d{1,4})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2})([.,](\d+))?)?)?\s*([A-IK-Z])$/i);
- if (!match) return null;
- const [, firstText, secondText, thirdText, hourText = "0", minuteText = "00", secondTimeText = "00", , fractionText = "", zoneText] = match;
- const yearText = firstText.length === 4 ? firstText : thirdText;
- const monthText = firstText.length === 4 ? secondText : firstText;
- const dayText = firstText.length === 4 ? thirdText : secondText;
- if (yearText.length !== 4) return null;
- const offsetHours = militaryZoneOffsetHours(zoneText);
- if (offsetHours == null) return null;
- return parseAbsoluteDateInput(`${yearText}-${monthText}-${dayText} ${hourText}:${minuteText}:${secondTimeText}${fractionText ? `.${fractionText}` : ""}`, false, { offsetSeconds: offsetHours * 3600 });
-}
-
-function militaryZoneOffsetHours(zoneText) {
- const zone = String(zoneText).toUpperCase();
- const positive = "ABCDEFGHIKLM".indexOf(zone);
- const negative = "NOPQRSTUVWXY".indexOf(zone);
- return zone === "Z" ? 0 : positive >= 0 ? positive + 1 : negative >= 0 ? -(negative + 1) : null;
-}
-
-function parseLocalZoneAbbreviationDateInput(input, utc = false) {
- if (utc) return null;
- const match = String(input).match(/^(\d{4}-\d{1,2}-\d{1,2}(?:[ T]\d{1,2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?)?)\s+([A-Za-z]{2,6})$/);
- if (!match) return null;
- const date = parseAbsoluteDateInput(match[1], false);
- if (!date || Number.isNaN(date.getTime())) return date;
- if (localZoneName(date).toLowerCase() !== match[2].toLowerCase()) return null;
- date.__bnuLocalZoneAbbrev = match[2];
- date.__bnuLocalOffsetSeconds = localOffsetSeconds(date);
- return date;
-}
-
-function localOffsetSeconds(date) {
- return -date.getTimezoneOffset() * 60;
-}
-
-function dateFromParts({ yearText, monthText, dayText, hourText = "0", minuteText = "0", secondText = "0", fractionText = "", utc = false }) {
- const now = new Date();
- const year = yearText == null || yearText === "" ? (utc ? now.getUTCFullYear() : now.getFullYear()) : Number(yearText);
- const month = Number(monthText);
- const day = Number(dayText);
- const hour = Number(hourText);
- const minute = Number(minuteText);
- const second = Number(secondText);
- if (month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 60) return new Date(Number.NaN);
- const milliseconds = Number(String(fractionText).replace(/^[.,]/, "").padEnd(3, "0").slice(0, 3) || "0");
- const date = zonedDate(year, month, day, hour, minute, Math.min(second, 59), milliseconds, utc);
- if (second === 60) date.setTime(date.getTime() + 1000);
- const fraction = String(fractionText).replace(/^[.,]/, "");
- return attachDateNanoseconds(date, fraction ? dateFractionNanoseconds(fraction) : milliseconds * 1_000_000);
-}
-
-function todayAt(hour, minute, second, millisecond, utc = false) {
- const now = new Date();
- return zonedDate(utc ? now.getUTCFullYear() : now.getFullYear(), (utc ? now.getUTCMonth() : now.getMonth()) + 1, utc ? now.getUTCDate() : now.getDate(), hour, minute, second, millisecond, utc);
-}
-
-function zonedDate(year, month, day, hour, minute, second, millisecond, utc = false) {
- if (utc) return new Date(Date.UTC(year, month - 1, day, hour, minute, second, millisecond));
- const tz = parsePosixTZ(new Date());
- if (tz) return new Date(Date.UTC(year, month - 1, day, hour, minute, second, millisecond) - tz.offsetSeconds * 1000);
- return new Date(year, month - 1, day, hour, minute, second, millisecond);
-}
-
-function parseFractionalDateInput(input) {
- const match = String(input).match(/^(.+\d{1,2}:\d{2}:\d{2})([.,](\d+))((?:Z|[+-]\d{2}(?::?\d{2})?)?)$/);
- if (isYearFirstMonthNameDateInput(input)) return new Date(Number.NaN);
- if (!match) return new Date(input);
- const [, prefix, separator, fraction, zone] = match;
- const milliseconds = fraction.padEnd(3, "0").slice(0, 3);
- const date = new Date(`${prefix}${separator}${milliseconds}${zone}`);
- return attachDateNanoseconds(date, dateFractionNanoseconds(fraction));
-}
-
-function isYearFirstMonthNameDateInput(input) {
- const match = String(input).match(/^(\d{4})\s+([A-Za-z]+)\s+\d{1,2}\b/);
- return Boolean(match && monthNumber(match[2]) != null);
-}
-
-function dateFractionNanoseconds(fraction) {
- return Number(String(fraction || "").padEnd(9, "0").slice(0, 9));
-}
-
-function attachDateNanoseconds(date, nanoseconds) {
- date.__bnuNanoseconds = nanoseconds;
- return date;
-}
-
-function normalizeDateInput(input) {
- return input.replace(/(T\d{1,2}:\d{2}:\d{2})([+-])(\d{1,2})$/, (_, time, sign, hour) => `${time}${sign}${String(hour).padStart(2, "0")}:00`);
-}
-
-function stripDateComments(input) {
- let depth = 0;
- let output = "";
- for (const ch of String(input)) {
- if (ch === "(") {
- depth++;
- continue;
- }
- if (ch === ")" && depth > 0) {
- depth--;
- continue;
- }
- if (depth === 0) output += ch;
- }
- return output;
-}
-
-function dateFormat(operands, opts) {
- const explicit = operands.find((arg) => arg.startsWith("+"));
- if (explicit) return explicit.slice(1);
- if (opts.R || opts["rfc-email"] || opts["rfc-822"] || opts["rfc-2822"]) return "%a, %d %b %Y %T %z";
- const rfc3339 = opts["rfc-3339"];
- if (rfc3339 !== undefined) {
- if (rfc3339 === "date") return "%F";
- if (rfc3339 === "seconds" || rfc3339 === "sec") return "%F %T%:z";
- if (rfc3339 === "ns" || rfc3339 === "nanoseconds") return "%F %T.%N%:z";
- throw new UsageError(dateInvalidFormatArgument("--rfc-3339", rfc3339, ["date", "seconds", "ns"]), true);
- }
- const iso = opts.I ?? opts["iso-8601"];
- if (iso !== undefined) {
- const spec = iso === true ? "date" : iso ?? "date";
- if (spec === "date") return "%F";
- if (spec === "hours") return "%Y-%m-%dT%H%:z";
- if (spec === "minutes") return "%Y-%m-%dT%H:%M%:z";
- if (spec === "seconds" || spec === "sec") return "%Y-%m-%dT%T%:z";
- if (spec === "ns" || spec === "nanoseconds") return "%Y-%m-%dT%T,%N%:z";
- throw new UsageError(dateInvalidFormatArgument("--iso-8601", spec, ["hours", "minutes", "date", "seconds", "ns"]), true);
- }
- return localeDateFormat() ?? "%a %b %e %T %Z %Y";
-}
-
-function dateInvalidFormatArgument(option, value, valid) {
- const kind = value === "" ? "ambiguous" : "invalid";
- return `${kind} argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic(option)}\nValid arguments are:\n${valid.map((arg) => ` - ${localeQuotedDiagnostic(arg)}`).join("\n")}`;
-}
-
-function localeDateFormat() {
- try {
- const proc = Bun.spawnSync(["locale", "date_fmt"], { stdout: "pipe", stderr: "ignore", env: process.env });
- if (proc.exitCode !== 0) return null;
- const text = new TextDecoder().decode(proc.stdout);
- const format = text.endsWith("\n") ? text.slice(0, -1) : text;
- return format || null;
- } catch {
- return null;
- }
-}
-
-async function idCmd(args) {
- args = normalizeIdLongOptions(args);
- const { opts, operands } = parseOptions(args, {
- short: { u: false, g: false, G: false, n: false, r: false, z: false, Z: false },
- long: { user: false, group: false, groups: false, name: false, real: false, zero: false, context: false, help: false, version: false },
- });
- const justContext = Boolean(opts.Z || opts.context);
- const selinuxEnabled = selinuxRuntimeEnabled();
- if (justContext && !selinuxEnabled) return fail("id", "--context (-Z) works only on an SELinux-enabled kernel", 1);
- if (justContext && operands.length) return fail("id", "cannot print security context when user specified", 1);
- const selected = [opts.u || opts.user, opts.g || opts.group, opts.G || opts.groups, justContext].filter(Boolean).length;
- if (selected > 1) throw new UsageError('cannot print "only" of more than one choice');
- const defaultFormat = selected === 0;
- if (defaultFormat && (opts.n || opts.name || opts.r || opts.real)) throw new UsageError("printing only names or real IDs requires -u, -g, or -G");
- const zero = opts.z || opts.zero;
- if (zero && defaultFormat) throw new UsageError("option --zero not permitted in default format");
- const name = opts.n || opts.name;
- const end = zero ? "\0" : "\n";
- const sep = zero ? "\0" : " ";
- let context = null;
- if (!operands.length && (justContext || (defaultFormat && !process.env.POSIXLY_CORRECT)) && selinuxEnabled) {
- context = processSecurityContext();
- if (justContext && context == null) return fail("id", "can't get process context", 1);
- }
- if (justContext) {
- stdout(`${context}${end}`);
- return 0;
- }
- let failed = false;
- for (const operand of operands.length ? operands : [undefined]) {
- let identity;
- try {
- identity = await identityForUser(operand);
- } catch (error) {
- stderr(`id: ${error.message}\n`);
- failed = true;
- continue;
- }
- if (opts.u || opts.user) stdout(`${name ? identity.name : identity.uid}${end}`);
- else if (opts.g || opts.group) stdout(`${name ? await groupName(identity.gid) : identity.gid}${end}`);
- else if (opts.G || opts.groups) {
- const groupEnd = zero && operands.length > 1 ? "\0\0" : end;
- stdout(`${name ? (await Promise.all(identity.groups.map(groupName))).join(sep) : identity.groups.join(sep)}${groupEnd}`);
- }
- else stdout(`uid=${identity.uid}(${identity.name}) gid=${identity.gid}(${await groupName(identity.gid)}) groups=${identity.groups.map((gid) => `${gid}(${identity.groupNames.get(gid) ?? gid})`).join(",")}${context != null ? ` context=${context}` : ""}\n`);
- }
- return failed ? 1 : 0;
-}
-
-function normalizeIdLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeIdLongOption(arg));
- }
- return out;
-}
-
-function normalizeIdLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, ID_LONG_OPTIONS);
-}
-
-async function identityForUser(user) {
- const info = userInfo();
- const uid = process.getuid?.() ?? info.uid;
- const gid = process.getgid?.() ?? info.gid;
- const currentName = await userNameForUid(uid) ?? info.username;
- const originalUser = user;
- const numericOnly = typeof user === "string" && /^\+\d+$/.test(user);
- if (numericOnly) user = user.slice(1);
- if (user == null) {
- const groups = orderedGroupIds(gid, process.getgroups?.() ?? [gid]);
- return { name: currentName, uid, gid, groups, groupNames: await groupNamesMap() };
- }
- const passwd = await readPasswd();
- let entry = numericOnly ? null : passwd.get(user);
- if (!entry && /^\d+$/.test(user)) {
- for (const [name, row] of passwd) {
- if (row.uid === Number(user)) {
- entry = { ...row, name };
- break;
- }
- }
- } else if (entry) {
- entry = { ...entry, name: user };
- }
- if (!entry) throw new UsageError(`${localeQuotedDiagnostic(originalUser)}: no such user`);
- const memberGroups = await supplementaryGroupsForUser(entry.name);
- return { name: entry.name, uid: entry.uid, gid: entry.gid, groups: orderedGroupIds(entry.gid, memberGroups), groupNames: await groupNamesMap() };
-}
-
-async function groupName(gid) {
- const groups = await readGroup();
- for (const [name, id] of groups) if (id === gid) return name;
- return String(gid);
-}
-
-async function userNameForUid(uid) {
- const passwd = await readPasswd();
- for (const [name, row] of passwd) if (row.uid === Number(uid)) return name;
- return null;
-}
-
-async function groupNamesMap() {
- const groups = await readGroup();
- return new Map([...groups].map(([name, gid]) => [gid, name]));
-}
-
-async function supplementaryGroupsForUser(user) {
- const ids = [];
- try {
- const text = await readFile("/etc/group", "utf8");
- for (const line of text.split("\n")) {
- const [,, gid, members = ""] = line.split(":");
- if (members.split(",").includes(user)) ids.push(Number(gid));
- }
- } catch {}
- return ids;
-}
-
-async function groupsCmd(args) {
- args = normalizeHelpVersionOnlyLongOptions(args);
- const { operands } = parseOptions(args, { long: { help: false, version: false } });
- const info = userInfo();
- const uid = process.getuid?.() ?? info.uid;
- const gid = process.getgid?.() ?? info.gid;
- const currentName = await userNameForUid(uid) ?? info.username;
- if (!operands.length) {
- const groups = orderedGroupIds(gid, process.getgroups?.() ?? [gid]);
- stdout(`${(await Promise.all(groups.map(groupName))).join(" ")}\n`);
- return 0;
- }
- let code = 0;
- const passwd = await readPasswd();
- for (const user of operands) {
- const row = passwd.get(user);
- if (!row) {
- stderr(`groups: ${localeQuotedDiagnostic(user)}: no such user\n`);
- code = 1;
- continue;
- }
- const groups = orderedGroupIds(row.gid, await supplementaryGroupsForUser(user));
- stdout(`${user} : ${(await Promise.all(groups.map(groupName))).join(" ")}\n`);
- }
- return code;
-}
-
-function uniqueNumbers(values) {
- return [...new Set(values.map(Number))];
-}
-
-function orderedGroupIds(primary, values) {
- return [Number(primary), ...uniqueNumbers(values).filter((gid) => gid !== Number(primary))];
-}
-
-async function logname(args) {
- args = normalizeHelpVersionOnlyLongOptions(args);
- const { operands } = parseOptions(args, { long: { help: false, version: false } });
- if (operands.length) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}`, true);
- const uid = process.getuid?.() ?? userInfo().uid;
- const passwd = await readPasswd();
- const passwdFallback = await uidIsLinuxOverflow(uid) ? null : await userNameForUid(uid);
- for (const name of [process.env.LOGNAME, process.env.USER, userInfo().username, passwdFallback]) {
- if (!name) continue;
- if (passwd.get(name)?.uid === uid) {
- stdout(`${name}\n`);
- return 0;
- }
- }
- stderr("logname: no login name\n");
- return 1;
-}
-
-async function uidIsLinuxOverflow(uid) {
- try {
- return Number((await readFile("/proc/sys/kernel/overflowuid", "utf8")).trim()) === Number(uid);
- } catch {
- return false;
- }
-}
-
-async function users(args) {
- args = normalizeHelpVersionOnlyLongOptions(args);
- const { operands } = parseOptions(args, { long: { help: false, version: false } });
- if (operands.length > 1) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[1])}`, true);
- const records = await readUtmpRecords(operands[0] ?? "/var/run/utmp");
- const users = await filterWhoUsers(records, operands.length === 0);
- const names = users.map((record) => record.user);
- if (names.length) stdout(`${names.join(" ")}\n`);
- return 0;
-}
-
-async function readUtmpRecords(file) {
- let bytes;
- try {
- bytes = await readFile(file);
- } catch {
- return [];
- }
- return parseUtmpRecords(bytes);
-}
-
-function nulTerminatedBufferString(bytes) {
- const end = bytes.indexOf(0);
- return bytes.subarray(0, end === -1 ? bytes.length : end).toString();
-}
-
-async function nprocCmd(args) {
- args = normalizeNprocLongOptions(args);
- const { opts, operands } = parseOptions(args, { long: { all: false, ignore: "value", help: false, version: false } });
- if (operands.length) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}`, true);
- const installed = BigInt(cpus().length);
- const available = BigInt(Math.max(1, availableParallelism()));
- const openMp = opts.all ? { threads: null, limit: null } : nprocOpenMpLimits();
- const quotaLimit = opts.all || openMp.threads != null ? null : nprocCgroupQuotaLimit();
- let use;
- if (opts.all) use = installed;
- else if (openMp.threads != null) use = openMp.limit != null && openMp.limit < openMp.threads ? openMp.limit : openMp.threads;
- else {
- use = quotaLimit != null && quotaLimit < available ? quotaLimit : available;
- if (openMp.limit != null && openMp.limit < use) use = openMp.limit;
- }
- const ignore = opts.ignore == null ? 0n : parseNprocIgnore(opts.ignore);
- const result = use > ignore ? use - ignore : 1n;
- stdout(`${result < 1n ? 1n : result}\n`);
- return 0;
-}
-
-function nprocCgroupQuotaLimit() {
- if (!nprocSchedulerUsesQuota()) return null;
- const testRoot = process.env.BNU_NPROC_TEST_ROOT;
- const procCgroup = testRoot ? join(testRoot, "proc/self/cgroup") : "/proc/self/cgroup";
- const cgroupRoot = testRoot ? join(testRoot, "sys/fs/cgroup") : "/sys/fs/cgroup";
- let membership;
- try {
- membership = readFileSync(procCgroup, "utf8");
- } catch {
- return null;
- }
- const unified = membership.split(/\r?\n/).find((line) => line.startsWith("0::"));
- if (!unified) return null;
- const components = unified.slice(3).split("/").filter((part) => part && part !== "." && part !== "..");
- let limit = null;
- for (let length = components.length; length >= 0; length--) {
- let cpuMax;
- try {
- cpuMax = readFileSync(join(cgroupRoot, ...components.slice(0, length), "cpu.max"), "utf8").trim();
- } catch {
- continue;
- }
- const [quotaText, periodText] = cpuMax.split(/\s+/);
- if (quotaText === "max" || !/^\d+$/.test(quotaText) || !/^\d+$/.test(periodText)) continue;
- const quota = BigInt(quotaText);
- const period = BigInt(periodText);
- if (quota <= 0n || period <= 0n) continue;
- const rounded = (2n * quota + period) / (2n * period);
- const candidate = rounded < 1n ? 1n : rounded;
- if (limit == null || candidate < limit) limit = candidate;
- if (limit === 1n) break;
- }
- return limit;
-}
-
-function nprocSchedulerUsesQuota() {
- const testRoot = process.env.BNU_NPROC_TEST_ROOT;
- const schedPath = testRoot ? join(testRoot, "proc/self/sched") : "/proc/self/sched";
- try {
- const sched = readFileSync(schedPath, "utf8");
- const match = sched.match(/^policy\s*:\s*(-?\d+)/m);
- if (match) return ![-1, 1, 2, 6].includes(Number(match[1]));
- } catch {
- // Fall through to libc on systems without Linux procfs.
- }
- const policy = libc.symbols.sched_getscheduler(0);
- return ![-1, 1, 2, 6].includes(policy);
-}
-
-function normalizeNprocLongOptions(args) {
- const out = [];
- let end = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- const option = normalizeNprocLongOption(arg);
- out.push(option);
- if (option === "--ignore" && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-function normalizeNprocLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = NPROC_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-function parseNprocIgnore(value) {
- const text = String(value).trimStart();
- if (!/^\+?\d+$/.test(text)) throw new UsageError(`invalid number: ${localeQuotedEscapedDiagnostic(value)}`);
- return BigInt(text);
-}
-
-function nprocOpenMpLimits() {
- return {
- threads: openMpPositiveIntegerPrefix(process.env.OMP_NUM_THREADS),
- limit: openMpPositiveIntegerPrefix(process.env.OMP_THREAD_LIMIT),
- };
-}
-
-function openMpPositiveIntegerPrefix(value) {
- const match = String(value ?? "").trim().match(/^(\d+)(?:,|$)/);
- if (!match) return null;
- const parsed = BigInt(match[1]);
- if (parsed <= 0n) return null;
- return parsed > 18446744073709551615n ? 18446744073709551615n : parsed;
-}
-
-async function uptimeCmd(args) {
- args = normalizeUptimeLongOptions(args);
- const { operands } = parseOptions(args, { long: { help: false, version: false } });
- if (operands.length > 1) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[1])}`, true);
- let records = [];
- let readStatus = 0;
- const file = operands[0] ?? "/var/run/utmp";
- try {
- records = await readUtmpRecordsStrict(file);
- } catch (error) {
- stderr(`uptime: ${shellEscapeLsName(pathDisplayName(file), true)}: ${systemErrorMessage(error)}\n`);
- readStatus = 1;
- }
- const users = await filterWhoUsers(records, operands.length === 0);
- const bootTime = uptimeBootTime(records, operands.length === 0);
- const nowSeconds = Math.trunc(Date.now() / 1000);
- let status = readStatus;
- let uptimeText;
- if (bootTime == null || bootTime <= 0 || bootTime > nowSeconds) {
- stderr("uptime: couldn't get boot time\n");
- status = 1;
- } else {
- uptimeText = formatUptimeDefault(nowSeconds - bootTime);
- }
- const loads = loadavg().map((value) => value.toFixed(2));
- const now = new Date();
- stdout(` ${formatUptimeClock(now)} ${uptimeText ?? "up ???? days ??:??"}, ${users.length} user${users.length === 1 ? "" : "s"}, load average: ${loads.join(", ")}\n`);
- return status;
-}
-
-function normalizeUptimeLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeUptimeLongOption(arg));
- }
- return out;
-}
-
-function normalizeUptimeLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = UPTIME_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-function formatLocalDateTime(date) {
- const pad = (value) => String(value).padStart(2, "0");
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
-}
-
-function formatUptimeClock(date) {
- return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}:${String(date.getSeconds()).padStart(2, "0")}`;
-}
-
-async function readUtmpRecordsStrict(file) {
- const bytes = await readFile(file);
- return parseUtmpRecords(bytes);
-}
-
-function parseUtmpRecords(bytes) {
- const recordSize = 384;
- const records = [];
- for (let offset = 0; offset + recordSize <= bytes.length; offset += recordSize) {
- records.push({
- type: bytes.readInt16LE(offset),
- pid: bytes.readInt32LE(offset + 4),
- line: nulTerminatedBufferString(bytes.subarray(offset + 8, offset + 40)),
- id: nulTerminatedBufferString(bytes.subarray(offset + 40, offset + 44)),
- user: nulTerminatedBufferString(bytes.subarray(offset + 44, offset + 76)),
- host: nulTerminatedBufferString(bytes.subarray(offset + 76, offset + 332)),
- exitTermination: bytes.readInt16LE(offset + 332),
- exitStatus: bytes.readInt16LE(offset + 334),
- time: bytes.readInt32LE(offset + 340),
- });
- }
- return records;
-}
-
-function uptimeBootTime(records, allowFallback) {
- const boot = whoBootRecord(records);
- if (boot?.time) return boot.time;
- if (allowFallback) {
- try {
- const match = readFileSync("/proc/stat", "utf8").match(/^btime\s+(\d+)/m);
- if (match) return Number(match[1]);
- } catch {}
- }
- return null;
-}
-
-function formatUptimeDefault(seconds) {
- const days = Math.trunc(seconds / 86400);
- const hours = Math.trunc((seconds % 86400) / 3600);
- const minutes = Math.trunc((seconds % 3600) / 60);
- if (days) return `up ${days} day${days === 1 ? "" : "s"}, ${String(hours).padStart(2)}:${String(minutes).padStart(2, "0")}`;
- return `up ${String(hours).padStart(2)}:${String(minutes).padStart(2, "0")}`;
-}
-
-async function hostid(args) {
- args = normalizeHelpVersionOnlyLongOptions(args);
- const { operands } = parseOptions(args, { long: { help: false, version: false } });
- if (operands.length) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}`, true);
- stdout(`${(await hostidValue()).toString(16).padStart(8, "0")}\n`);
- return 0;
-}
-
-async function hostidValue() {
- try {
- const bytes = await readFile("/etc/hostid");
- if (bytes.length >= 4) return bytes.readUInt32LE(0);
- } catch {
- // GNU/Linux gethostid returns zero when no host id has been configured.
- }
- return 0;
-}
-
-async function arch(args) {
- args = normalizeHelpVersionOnlyLongOptions(args);
- const { operands } = parseOptions(args, { long: { help: false, version: false } });
- if (operands.length) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}`, true);
- stdout(`${machineName()}\n`);
- return 0;
-}
-
-function machineName() {
- const map = { x64: "x86_64", arm64: "aarch64", ia32: "i686" };
- return osMachine?.() || map[process.arch] || process.arch;
-}
-
-async function pathchk(args) {
- const { opts, operands } = parsePathchkOptions(args);
- if (!operands.length) throw new UsageError("missing operand", true);
- let code = 0;
- const portable = opts.p || opts.portability;
- const checkEmptyOrLeadingDash = opts.P || opts.portability;
- for (const path of operands) {
- if (path === "") {
- stderr(`pathchk: ${portable || checkEmptyOrLeadingDash ? "empty file name" : "'': No such file or directory"}\n`);
- code = 1;
- continue;
- }
- if (portable && path.length > 255) {
- stderr(`pathchk: limit 255 exceeded by length ${path.length} of file name '${path}'\n`);
- code = 1;
- continue;
- }
- let componentError = false;
- for (const component of path.split("/")) {
- if (component === "") {
- continue;
- }
- if (component.length > (portable ? 14 : 255)) {
- stderr(portable
- ? `pathchk: limit 14 exceeded by length ${component.length} of file name component ${localeQuotedDiagnostic(component)}\n`
- : `pathchk: ${path}: File name too long\n`);
- code = 1;
- componentError = true;
- break;
- }
- if (checkEmptyOrLeadingDash && component.startsWith("-")) {
- stderr(`pathchk: leading '-' in a component of file name '${path}'\n`);
- code = 1;
- componentError = true;
- break;
- }
- const nonPortable = portable ? component.match(/[^A-Za-z0-9._-]/)?.[0] : null;
- if (nonPortable != null) {
- stderr(`pathchk: non-portable character ${localeQuotedDiagnostic(pathchkDiagnosticCharacter(nonPortable))} in file name ${pathchkDiagnosticName(path)}\n`);
- code = 1;
- componentError = true;
- break;
- }
- }
- if (componentError) continue;
- if (!portable) {
- const prefixError = await pathchkExistingPrefixError(path);
- if (prefixError) {
- stderr(`pathchk: ${path}: ${prefixError}\n`);
- code = 1;
- continue;
- }
- }
- }
- return code;
-}
-
-function pathchkDiagnosticCharacter(ch) {
- return lsEscapedName(ch);
-}
-
-function pathchkDiagnosticName(path) {
- return shellEscapeLsName(path, true);
-}
-
-function parsePathchkOptions(args) {
- const opts = {};
- const operands = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- operands.push(...args.slice(i + 1));
- break;
- }
- if (arg === "-" || !arg.startsWith("-")) {
- operands.push(...args.slice(i));
- break;
- }
- if (arg.startsWith("--")) {
- const normalized = normalizePathchkLongOption(arg);
- const body = normalized.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!PATHCHK_LONG_OPTIONS.includes(name)) throw new UsageError(`unrecognized option '${arg}'`, true);
- if (eq !== -1) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- opts[name] = true;
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "p" || ch === "P") opts[ch] = true;
- else throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- }
- return { opts, operands };
-}
-
-function normalizePathchkLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = PATHCHK_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-async function pathchkExistingPrefixError(path) {
- const parts = path.split("/");
- let prefix = path.startsWith("/") ? "/" : "";
- for (let i = 0; i < parts.length - 1; i++) {
- const part = parts[i];
- if (part === "") continue;
- prefix = prefix === "" || prefix === "/" ? `${prefix}${part}` : `${prefix}/${part}`;
- try {
- const s = await lstat(prefix);
- if (!s.isDirectory()) return "Not a directory";
- } catch (error) {
- if (error.code === "ENOENT") return null;
- return error.message || String(error);
- }
- }
- return null;
-}
-
-async function syncCmd(args) {
- const { opts, operands } = parseSyncArgs(args);
- const data = opts.d || opts.data;
- const fileSystem = opts.f || opts["file-system"];
- if (data && fileSystem) return fail("sync", "cannot specify both --data and --file-system", 1);
- if (data && !operands.length) return fail("sync", "--data needs at least one argument", 1);
- if (operands.length) {
- let status = 0;
- for (const file of operands) {
- const ok = await syncOneFile(file, data, fileSystem);
- if (!ok) status = 1;
- }
- return status;
- }
- libc.symbols.sync();
- return 0;
-}
-
-function parseSyncArgs(args) {
- const opts = {};
- const operands = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "-" || !arg.startsWith("-")) {
- operands.push(arg);
- if (process.env.POSIXLY_CORRECT) end = true;
- continue;
- }
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg.startsWith("--")) {
- const normalized = normalizeSyncLongOption(arg);
- const [name, inlineValue] = normalized.slice(2).split(/=(.*)/s, 2);
- if (!SYNC_LONG_OPTIONS.includes(name)) throw new UsageError(`unrecognized option '${arg}'`, true);
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- opts[name] = true;
- continue;
- }
- for (const ch of arg.slice(1)) {
- if (ch === "d" || ch === "f") opts[ch] = true;
- else throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- }
- return { opts, operands };
-}
-
-function normalizeSyncLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = SYNC_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-async function syncOneFile(file, data = false, fileSystem = false) {
- const name = shellEscapeLsName(pathDisplayName(file), true);
- const s = await lstat(file).catch((error) => error);
- if (s instanceof Error) {
- stderr(`sync: error opening ${name}: ${systemErrorMessage(s)}\n`);
- return false;
- }
- if (s.isFIFO()) return true;
- let handle;
- try {
- handle = await open(file, "r");
- } catch (readError) {
- if (s.isSymbolicLink() && readError?.code === "ENOENT") {
- stderr(`sync: error opening ${name}: ${systemErrorMessage(readError)}\n`);
- return false;
- }
- try {
- handle = await open(file, "a");
- } catch {
- stderr(`sync: error opening ${name}: ${systemErrorMessage(readError)}\n`);
- return false;
- }
- }
- try {
- if (data && !fileSystem) await handle.datasync();
- else await handle.sync();
- return true;
- } catch (error) {
- stderr(`sync: error syncing ${name}: ${systemErrorMessage(error)}\n`);
- return false;
- } finally {
- await handle.close();
- }
-}
-
-function systemErrorMessage(error) {
- if (error?.code === "ENOENT") return "No such file or directory";
- if (error?.code === "EACCES") return "Permission denied";
- if (error?.code === "EISDIR") return "Is a directory";
- if (error?.code === "ELOOP") return "Too many levels of symbolic links";
- if (error?.code === "ENOSPC") return "No space left on device";
- if (error?.code === "ENAMETOOLONG") return "File name too long";
- if (error?.code === "ENOTDIR") return "Not a directory";
- if (error?.code === "EBADF") return "Bad file descriptor";
- if (error?.code === "EINVAL") return "Invalid argument";
- return error?.message || String(error);
-}
-
-async function lsCmd(args) {
- args = normalizeLsLongOptions(args);
- const { opts, operands: parsedOperands } = parseOptions(args, { short: { a: false, A: false, B: false, D: false, H: false, L: false, c: false, u: false, l: false, d: false, f: false, g: false, G: false, o: false, n: false, i: false, s: false, h: false, k: false, 1: false, F: false, R: false, S: false, t: false, T: "value", X: false, U: false, r: false, b: false, C: false, x: false, m: false, q: false, Q: false, N: false, v: false, p: false, w: "value", I: "value-array", Z: false, 0: false }, long: { all: false, "almost-all": false, author: false, directory: false, classify: "optional-value", "file-type": false, dereference: false, "dereference-command-line": false, "dereference-command-line-symlink-to-dir": false, full: false, "full-time": false, "group-directories-first": false, group: false, "indicator-style": "value", inode: false, size: false, "human-readable": false, si: false, kibibytes: false, recursive: false, reverse: false, color: "optional-value", hyperlink: "optional-value", hyper: "optional-value", "sort": "value", "time-style": "value", time: "value", "tabsize": "value", width: "value", "block-size": "value", format: "value", ignore: "value-array", hide: "value-array", "ignore-backups": false, zero: false, dired: false, "quote-name": false, literal: false, escape: false, "hide-control-chars": false, "show-control-chars": false, "no-group": false, "numeric-uid-gid": false, quoting: "value", "quoting-style": "value", context: false, help: false, version: false } });
- const operands = rawOperandPlan("ls", args, parsedOperands, {
- valueOptions: ["--indicator-style", "--sort", "--time-style", "--time", "--tabsize", "--width", "--block-size", "--format", "--ignore", "--hide", "--quoting", "--quoting-style"],
- shortValueOptions: ["T", "w", "I"],
- }) ?? parsedOperands;
- opts.localeCollation = initializeSortLocaleCollation();
- if (opts.B) opts["ignore-backups"] = true;
- if (opts.D) opts.dired = true;
- if ((opts[0] || opts.zero) && opts.dired) throw new UsageError("--dired and --zero are incompatible", true);
- applyLsFormatOptions(args, opts);
- opts.allMode = lsAllMode(args, opts);
- opts.ignorePatterns = optionValues(opts.I).concat(optionValues(opts.ignore));
- if (opts.allMode === "visible") opts.ignorePatterns.push(...optionValues(opts.hide));
- if (opts["ignore-backups"]) opts.ignorePatterns.push("*~");
- opts.zero = opts[0] || opts.zero;
- if (opts.literal) opts.N = true;
- if (opts.b || opts.escape) opts.quoting = "escape";
- if (opts["hide-control-chars"]) opts.q = true;
- if (opts["show-control-chars"]) opts.N = true;
- if (opts["no-group"]) opts.G = true;
- if (opts.kibibytes) opts.k = true;
- if (opts["numeric-uid-gid"]) opts.n = true;
- if (opts.n) opts.l = true;
- applyLsBlockSizeSpecialMode(opts);
- opts.width = parseLsWidth(opts.w ?? opts.width);
- opts.tabSize = parseLsTabSize(opts.T ?? opts.tabsize);
- opts.blockSize = lsBlockSize(opts);
- opts.sizeBlockSize = lsSizeBlockSize(opts);
- if (opts.full || opts["full-time"]) {
- opts.l = true;
- if (opts["time-style"] == null) opts["time-style"] = "full-iso";
- }
- if (opts["time-style"] == null && process.env.TIME_STYLE) opts["time-style"] = process.env.TIME_STYLE;
- if (lsUsesLongListing(opts)) validateLsTimeStyle(opts["time-style"]);
- validateLsSort(opts.sort);
- validateLsTime(opts.time);
- validateLsQuotingStyle(opts.quoting ?? opts["quoting-style"]);
- opts.indicatorStyle = lsIndicatorStyle(opts);
- opts.colorEnabled = lsColorEnabled(opts);
- opts.hyperlinkEnabled = lsHyperlinkEnabled(opts);
- if (opts.indicatorStyle === null) {
- const option = opts.classify != null ? "classify" : "indicator-style";
- throw new InvocationError(lsInvalidEnumMessage(opts.classify ?? opts["indicator-style"], `--${option}`, option === "classify" ? LS_CLASSIFY_VALID_ARGUMENTS : LS_INDICATOR_VALID_ARGUMENTS), 1, true);
- }
- const targets = operands.length ? operands : ["."];
- let out = await renderLsTargets(targets, opts, targets.length > 1);
- if (opts.dired) out = formatLsDiredOutput(out, lsResolvedQuotingStyle(opts));
- stdout(out);
- if (opts.majorProblem) return 2;
- return opts.minorProblem ? 1 : 0;
-}
-
-function applyLsFormatOptions(args, opts) {
- let layout = null;
- let diredSeen = Boolean(opts.dired);
- let diredActive = Boolean(opts.dired);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") break;
- if (arg === "-" || !arg.startsWith("-")) continue;
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (name === "dired") {
- diredSeen = true;
- diredActive = true;
- layout = "l";
- }
- if (name === "format") {
- const value = inlineValue ?? args[++i];
- layout = lsLayoutForFormat(value);
- if (diredSeen) diredActive = layout === "l";
- }
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "D") {
- diredSeen = true;
- diredActive = true;
- layout = "l";
- } else if ("Cxm".includes(ch)) {
- layout = ch;
- if (diredSeen) diredActive = false;
- } else if (ch === "1") {
- if (!diredActive) layout = ch;
- } else if ("lgno".includes(ch)) {
- layout = ch;
- if (diredSeen) diredActive = true;
- }
- if (["T", "w", "I"].includes(ch)) break;
- }
- }
- opts.dired = diredActive;
- if (layout == null) return;
- opts[1] = opts.C = opts.x = opts.m = false;
- if (["1", "C", "x", "m"].includes(layout)) opts.l = opts.g = opts.n = opts.o = false;
- if (layout === "1") opts[1] = true;
- else if (layout === "C") opts.C = true;
- else if (layout === "x") opts.x = true;
- else if (layout === "m") opts.m = true;
- else if (layout === "g") opts.g = true;
- else if (layout === "n") opts.n = true;
- else if (layout === "o") opts.o = true;
- else opts.l = true;
-}
-
-function lsLayoutForFormat(value) {
- const text = String(value);
- const layouts = {
- "single-column": "1",
- vertical: "C",
- long: "l",
- verbose: "l",
- commas: "m",
- horizontal: "x",
- across: "x",
- };
- const layout = layouts[text];
- if (layout) return layout;
- throw new InvocationError(lsInvalidEnumMessage(text, "--format", LS_FORMAT_VALID_ARGUMENTS), 1, true);
-}
-
-function normalizeLsLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeLsLongOption(arg));
- }
- return out;
-}
-
-function normalizeLsLongOption(arg) {
- const [rawName, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (rawName.startsWith("hy") && "hyperlink".startsWith(rawName)) {
- return inlineValue === undefined ? "--hyperlink" : `--hyperlink=${inlineValue}`;
- }
- const normalized = normalizeLongOptionByPrefix(arg, LS_LONG_OPTIONS);
- if (normalized === "--hyper" || normalized.startsWith("--hyper=")) return `--hyperlink${normalized.slice("--hyper".length)}`;
- return normalized;
-}
-
-const LS_FORMAT_VALID_ARGUMENTS = [
- ["verbose", "long"],
- ["commas"],
- ["horizontal", "across"],
- ["vertical"],
- ["single-column"],
-];
-
-const LS_INDICATOR_VALID_ARGUMENTS = [
- ["none"],
- ["slash"],
- ["file-type"],
- ["classify"],
-];
-
-const LS_CLASSIFY_VALID_ARGUMENTS = [
- ["always", "yes", "force"],
- ["never", "no", "none"],
- ["auto", "tty", "if-tty"],
-];
-
-const LS_TRISTATE_VALID_ARGUMENTS = LS_CLASSIFY_VALID_ARGUMENTS;
-
-const LS_SORT_VALID_ARGUMENTS = [
- ["none"],
- ["size"],
- ["time"],
- ["version"],
- ["extension"],
- ["name"],
- ["width"],
-];
-
-const LS_TIME_VALID_ARGUMENTS = [
- ["atime", "access", "use"],
- ["ctime", "status"],
- ["mtime", "modification"],
- ["birth", "creation"],
-];
-
-const LS_QUOTING_STYLE_VALID_ARGUMENTS = [
- ["literal"],
- ["shell"],
- ["shell-always"],
- ["shell-escape"],
- ["shell-escape-always"],
- ["c"],
- ["c-maybe"],
- ["escape"],
- ["locale"],
- ["clocale"],
-];
-
-function lsInvalidEnumMessage(value, option, groups) {
- const kind = value === "" ? "ambiguous" : "invalid";
- return `${kind} argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic(option)}\nValid arguments are:\n${groups.map((group) => ` - ${group.map(localeQuotedDiagnostic).join(", ")}`).join("\n")}`;
-}
-
-function lsUsesLongListing(opts) {
- return Boolean(opts.l || opts.g || opts.o || opts.n);
-}
-
-function lsBlockSize(opts) {
- if (opts["block-size"] !== undefined) {
- try {
- return parseGNUBlockSize(opts["block-size"]);
- } catch {
- throw new UsageError(gnuBlockSizeErrorMessage("--block-size", opts["block-size"]));
- }
- }
- if (opts.k) return 1024;
- return parseGNUBlockSizeEnv(lsBlockSizeEnvValue(), lsDefaultBlockSize());
-}
-
-function lsSizeBlockSize(opts) {
- if (opts["block-size"] !== undefined) return parseGNUBlockSize(opts["block-size"]);
- const envValue = lsSizeBlockSizeEnvValue();
- if (envValue != null) return parseGNUBlockSizeEnv(envValue, lsDefaultBlockSize());
- return 1;
-}
-
-function lsBlockSizeValue(opts) {
- return opts["block-size"] ?? lsBlockSizeEnvValue();
-}
-
-function lsSizeBlockSizeValue(opts) {
- return opts["block-size"] ?? lsSizeBlockSizeEnvValue();
-}
-
-function lsBlockSizeEnvValue() {
- return process.env.LS_BLOCK_SIZE ?? process.env.BLOCK_SIZE ?? process.env.BLOCKSIZE;
-}
-
-function lsSizeBlockSizeEnvValue() {
- return process.env.LS_BLOCK_SIZE ?? process.env.BLOCK_SIZE;
-}
-
-function lsDefaultBlockSize() {
- return defaultGNUBlockSize();
-}
-
-function defaultGNUBlockSize() {
- return process.env.POSIXLY_CORRECT ? 512 : 1024;
-}
-
-function parseLsWidth(value) {
- if (value == null) return null;
- const text = String(value);
- const width = parseLsUnsignedNumber(text);
- if (width == null) throw new UsageError(`invalid line width: ${localeQuotedEscapedDiagnostic(text)}`);
- if (width === 0) return Number.POSITIVE_INFINITY;
- return width;
-}
-
-function parseLsTabSize(value) {
- if (value == null) return 8;
- const text = String(value);
- const tabSize = parseLsUnsignedNumber(text);
- if (tabSize == null) throw new UsageError(`invalid tab size: ${localeQuotedEscapedDiagnostic(text)}`);
- return tabSize;
-}
-
-function parseLsUnsignedNumber(text) {
- if (/^-/.test(text)) return null;
- let digits = text;
- let base = 10;
- if (/^0[xX]/.test(text)) {
- digits = text.slice(2);
- base = 16;
- if (!/^[0-9a-fA-F]+$/.test(digits)) return null;
- } else if (text.startsWith("0") && text !== "0") {
- digits = text.slice(1);
- base = 8;
- if (!/^[0-7]+$/.test(digits)) return null;
- } else if (!/^\d+$/.test(text)) {
- return null;
- }
- const value = Number.parseInt(digits || "0", base);
- return Number.isFinite(value) ? value : Number.MAX_SAFE_INTEGER;
-}
-
-function validateLsTimeStyle(style) {
- if (style == null || (typeof style === "string" && style.startsWith("+"))) return;
- const allowed = ["full-iso", "long-iso", "iso", "locale"];
- const normalized = String(style).replace(/^posix-/, "");
- if (allowed.includes(normalized)) return;
- throw new UsageError(`invalid argument ${localeQuotedEscapedDiagnostic(style)} for ${localeQuotedDiagnostic("time style")}
-Valid arguments are:
- - [posix-]full-iso
- - [posix-]long-iso
- - [posix-]iso
- - [posix-]locale
- - +FORMAT (e.g., +%H:%M) for a 'date'-style format`, true);
-}
-
-function validateLsSort(sort) {
- if (sort == null) return;
- const allowed = ["none", "size", "time", "version", "extension", "name", "width"];
- if (allowed.includes(String(sort))) return;
- throw new InvocationError(lsInvalidEnumMessage(sort, "--sort", LS_SORT_VALID_ARGUMENTS), 1, true);
-}
-
-function validateLsTime(time) {
- if (time == null) return;
- const allowed = LS_TIME_VALID_ARGUMENTS.flat();
- if (allowed.includes(String(time))) return;
- throw new InvocationError(lsInvalidEnumMessage(time, "--time", LS_TIME_VALID_ARGUMENTS), 1, true);
-}
-
-function validateLsQuotingStyle(style) {
- if (style == null) return;
- const resolved = resolveLsQuotingStyle(style);
- if (resolved) return;
- throw new InvocationError(lsInvalidEnumMessage(style, "--quoting-style", LS_QUOTING_STYLE_VALID_ARGUMENTS), 1, true);
-}
-
-function resolveLsQuotingStyle(style) {
- if (style == null) return null;
- const text = String(style);
- const allowed = LS_QUOTING_STYLE_VALID_ARGUMENTS.flat();
- if (allowed.includes(text)) return text;
- const matches = allowed.filter((candidate) => candidate.startsWith(text));
- if (matches.length === 1) return matches[0];
- if (matches.length > 1) throw new InvocationError(`ambiguous argument ${localeQuotedDiagnostic(text)} for ${localeQuotedDiagnostic("--quoting-style")}\nValid arguments are:\n${LS_QUOTING_STYLE_VALID_ARGUMENTS.map((group) => ` - ${group.map(localeQuotedDiagnostic).join(", ")}`).join("\n")}`, 1, true);
- return null;
-}
-
-function lsIndicatorStyle(opts) {
- if (opts.p) return "slash";
- if (opts["file-type"]) return "file-type";
- const style = opts["indicator-style"];
- if (style != null) {
- if (["none", "classify", "file-type", "slash"].includes(style)) return style;
- return null;
- }
- if (opts.F) return "classify";
- if (opts.classify != null) {
- const mode = opts.classify === true ? "always" : opts.classify;
- if (mode === "always" || mode === "yes" || mode === "force") return "classify";
- if (mode === "auto" || mode === "tty" || mode === "if-tty" || mode === "never" || mode === "no" || mode === "none") return "none";
- return null;
- }
- return "none";
-}
-
-function lsColorEnabled(opts) {
- if (opts.color == null || opts.color === "never") return false;
- if (opts.color === true || opts.color === "always" || opts.color === "yes" || opts.color === "force") return terminalSupportsColor();
- if (opts.color === "auto" || opts.color === "tty" || opts.color === "if-tty") return terminalSupportsColor() && Boolean(process.stdout.isTTY);
- throw new InvocationError(lsInvalidEnumMessage(opts.color, "--color", LS_TRISTATE_VALID_ARGUMENTS), 1, true);
-}
-
-function lsHyperlinkEnabled(opts) {
- const value = opts.hyperlink ?? opts.hyper;
- if (opts.dired) return false;
- if (value == null || value === "never" || value === "no" || value === "none") return false;
- if (value === true || value === "always" || value === "yes" || value === "force") return true;
- if (value === "auto" || value === "tty" || value === "if-tty") return Boolean(process.stdout.isTTY);
- throw new InvocationError(lsInvalidEnumMessage(value, "--hyperlink", LS_TRISTATE_VALID_ARGUMENTS), 1, true);
-}
-
-function terminalSupportsColor() {
- if (process.env.COLORTERM) return true;
- if (process.env.TERM === "") return false;
- return process.env.TERM !== "dumb";
-}
-
-function lsAllMode(args, opts) {
- let mode = "visible";
- let sawMode = false;
- for (const arg of args) {
- if (arg === "--") break;
- if (arg === "--all") {
- mode = "all";
- sawMode = true;
- } else if (arg === "--almost-all") {
- mode = "almost";
- sawMode = true;
- } else if (/^-[^-]/.test(arg)) {
- for (const ch of arg.slice(1)) {
- if (ch === "I") break;
- if (ch === "a" || ch === "f") {
- mode = "all";
- sawMode = true;
- } else if (ch === "A") {
- mode = "almost";
- sawMode = true;
- }
- }
- }
- }
- if (sawMode) return mode;
- if (opts.a || opts.f || opts.all) return "all";
- if (opts.A || opts["almost-all"]) return "almost";
- return "visible";
-}
-
-async function renderLsTargets(targets, opts, labelDirs) {
- const recursiveDirSeen = new Set();
- const targetStats = await Promise.all(targets.map(async (target) => {
- try {
- return { target, ...(await lsEntryStats(target, opts, true)) };
- } catch (error) {
- opts.majorProblem = true;
- stderr(`ls: cannot access '${target}': ${systemErrorMessage(error)}\n`);
- return null;
- }
- }));
- const validTargets = targetStats.filter(Boolean);
- if (!validTargets.length) return "";
- if (validTargets.every(({ stat }) => opts.d || opts.directory || !stat.isDirectory())) {
- const entries = validTargets.map(({ target, stat, linkStat, danglingDereference, targetDirectory, targetMissing, hasCapability }) => ({ name: target, path: target, stat, linkStat, danglingDereference, targetDirectory, targetMissing, hasCapability }));
- sortLsEntries(entries, opts);
- return await renderLsEntries(entries, opts);
- }
- let out = "";
- const fileEntries = validTargets
- .filter(({ stat: s }) => opts.d || opts.directory || !s.isDirectory())
- .map(({ target, stat, linkStat, danglingDereference, targetDirectory, targetMissing, hasCapability }) => ({ name: target, path: target, stat, linkStat, danglingDereference, targetDirectory, targetMissing, hasCapability }));
- if (fileEntries.length) {
- sortLsEntries(fileEntries, opts);
- out += await renderLsEntries(fileEntries, opts);
- }
- let renderedDir = false;
- for (const { target, stat: s } of validTargets) {
- if (!s.isDirectory() || opts.d || opts.directory) continue;
- out += await renderLsDirectory(target, opts, labelDirs || opts.R || opts.recursive, fileEntries.length > 0 || renderedDir, recursiveDirSeen, s);
- renderedDir = true;
- }
- return out;
-}
-
-async function renderLsDirectory(target, opts, label, leadingBlank = false, recursiveDirSeen = new Set(), directoryStat = null) {
- let out = "";
- const currentStat = directoryStat ?? await stat(target).catch(() => null);
- if (currentStat) recursiveDirSeen.add(lsDirectoryIdentity(currentStat));
- if (leadingBlank) out += "\n";
- if (label) out += `${formatLsHyperlink(quoteLsDirectoryLabelName(target, opts), await lsDirectoryLabelPath(target), opts)}:\n`;
- const rawDisplayNames = Boolean((await lstat(target).catch(() => null))?.isSymbolicLink());
- let names = await lsReadDirectoryEntries(target);
- if (opts.allMode === "all") names = [{ name: Buffer.from("."), type: 4 }, { name: Buffer.from(".."), type: 4 }, ...names];
- else if (opts.allMode !== "almost") names = names.filter(({ name }) => !lsDirectoryEntryDisplayName(name, rawDisplayNames).startsWith("."));
- names = names.filter(({ name }) => !lsIgnored(lsDirectoryEntryDisplayName(name, rawDisplayNames), opts));
- const entries = [];
- for (const { name, type, inode } of names) {
- const displayName = lsDirectoryEntryDisplayName(name, rawDisplayNames);
- const path = displayName === "." ? target : displayName === ".." ? pathLikeJoin(target, Buffer.from("..")) : pathLikeJoin(target, name);
- try {
- entries.push({ name: displayName, path, direntInode: inode, ...(await lsEntryStats(path, opts, false)) });
- } catch (error) {
- // readdir has already established that this name exists. Preserve its
- // d_type when a following metadata lookup fails, as GNU ls does for
- // inaccessible and concurrently removed directory entries.
- opts.minorProblem = true;
- stderr(`ls: cannot access '${pathDisplayName(path)}': ${systemErrorMessage(error)}\n`);
- entries.push({
- name: displayName,
- path,
- direntInode: inode,
- direntTypeChar: lsDirentTypeChar(type),
- statFailed: true,
- stat: lsUnknownStat(type),
- });
- }
- }
- sortLsEntries(entries, opts);
- if (opts.l || opts.g || opts.o || opts.s || opts.size || opts.dired) out += `total ${lsTotalBlocks(entries)}\n`;
- out += await renderLsEntries(entries, opts);
- if (opts.R || opts.recursive) {
- for (const entry of entries) {
- if (entry.name === "." || entry.name === ".." || !entry.stat.isDirectory() || entry.stat.isSymbolicLink()) continue;
- const childTarget = lsRecursiveChildTarget(target, entry);
- const identity = lsDirectoryIdentity(entry.stat);
- if (recursiveDirSeen.has(identity)) {
- opts.majorProblem = true;
- stderr(`ls: ${childTarget}: not listing already-listed directory\n`);
- continue;
- }
- out += `\n${await renderLsDirectory(childTarget, opts, true, false, recursiveDirSeen, entry.stat)}`;
- }
- }
- return out;
-}
-
-function lsReadDirectoryEntries(path) {
- if (process.platform !== "linux") {
- return readdirPathEntries(path).then((names) => names.map((name) => ({ name, type: 0 })));
- }
- const directory = libc.symbols.opendir(cstrPath(path));
- if (!directory) throw rmLibcError(libcErrno());
- const entries = [];
- try {
- while (true) {
- const errnoPointer = libc.symbols.__errno_location();
- if (errnoPointer) libc.symbols.memset(errnoPointer, 0, 4);
- const address = libc.symbols.readdir(directory);
- if (!address) {
- const errno = libcErrno();
- if (errno) throw rmLibcError(errno);
- break;
- }
- const recordLength = read.u16(address, 16);
- const maximumNameLength = Math.max(0, recordLength - 19);
- let nameLength = 0;
- while (nameLength < maximumNameLength && read.u8(address + 19, nameLength) !== 0) nameLength++;
- const name = Buffer.from(new Uint8Array(toArrayBuffer(address + 19, 0, nameLength)));
- if (name.equals(Buffer.from(".")) || name.equals(Buffer.from(".."))) continue;
- entries.push({ name, type: read.u8(address, 18), inode: read.u64(address, 0) });
- }
- } finally {
- libc.symbols.closedir(directory);
- }
- return entries;
-}
-
-function lsDirentTypeChar(type) {
- return ({ 1: "p", 2: "c", 4: "d", 6: "b", 8: "-", 10: "l", 12: "s" })[type] ?? "?";
-}
-
-function lsUnknownStat(type) {
- const isType = (value) => type === value;
- return {
- mode: 0,
- size: 0,
- blocks: 0,
- ino: 0,
- nlink: 0,
- uid: 0,
- gid: 0,
- isFile: () => isType(8),
- isDirectory: () => isType(4),
- isBlockDevice: () => isType(6),
- isCharacterDevice: () => isType(2),
- isSymbolicLink: () => isType(10),
- isFIFO: () => isType(1),
- isSocket: () => isType(12),
- };
-}
-
-function lsDirectoryEntryDisplayName(name, rawDisplayNames = false) {
- if (!isBytePath(name)) return String(name);
- return pathDisplayName(name);
-}
-
-function lsDirectoryIdentity(statInfo) {
- return `${statInfo.dev}:${statInfo.ino}`;
-}
-
-async function lsEntryStats(path, opts, commandLine) {
- const needsNanoseconds = lsNeedsStatNanoseconds(opts);
- const linkStat = lsAttachStatNanoseconds(await lstat(path), path, false, needsNanoseconds);
- const hasCapability = linkStat.isFile() && opts.colorEnabled && lsCapabilityColorEnabled()
- ? lsFileHasCapability(path)
- : false;
- // -F needs the mode bits of regular files to distinguish executable
- // entries. Perform that required query on the calling thread, while
- // retaining d_type/lstat knowledge for symlinks and directories so those
- // do not acquire an unnecessary target stat.
- if (linkStat.isFile() && opts.indicatorStyle === "classify") lsNativeModeProbe(path);
- if (linkStat.isSymbolicLink() && (opts.L || opts.dereference || (commandLine && (opts.H || opts["dereference-command-line"])))) {
- try {
- return { stat: lsAttachStatNanoseconds(await stat(path), path, true, needsNanoseconds), linkStat, hasCapability };
- } catch (error) {
- if (commandLine) throw error;
- const needsInfo = opts.i || opts.inode || opts.s || opts.size || opts.l || opts.g || opts.o;
- if ((opts.L || opts.dereference) && (needsInfo || error?.code === "ENOENT" || error?.code === "ENOTDIR")) {
- opts.minorProblem = true;
- stderr(`ls: cannot access '${path}': ${systemErrorMessage(error)}\n`);
- }
- if (!needsInfo) return { stat: linkStat, linkStat, targetMissing: true };
- return { stat: linkStat, linkStat, danglingDereference: needsInfo, targetMissing: true };
- }
- }
- if (commandLine && linkStat.isSymbolicLink() && !(opts.d || opts.directory) && (opts.H || opts["dereference-command-line"] || opts.L || opts.dereference || !(opts.F || opts.p || opts.classify != null || opts["file-type"] || opts["indicator-style"]))) {
- try {
- const targetStat = lsAttachStatNanoseconds(await stat(path), path, true, needsNanoseconds);
- if (targetStat.isDirectory()) return { stat: targetStat, linkStat, targetDirectory: true };
- } catch {}
- }
- let targetDirectory = false;
- let targetMissing = false;
- if (linkStat.isSymbolicLink()) {
- try {
- targetDirectory = (await stat(path)).isDirectory();
- } catch {
- targetMissing = true;
- }
- }
- return { stat: linkStat, linkStat, targetDirectory, targetMissing, hasCapability };
-}
-
-let lsCapabilityProbeDone = false;
-
-function lsCapabilityColorEnabled() {
- const code = lsColorCode("ca");
- return code != null && code !== "" && code !== "00";
-}
-
-function lsFileHasCapability(path) {
- // Match GNU ls/libcap's process capability probe, while reading the file
- // capability directly from Linux's canonical security.capability xattr.
- if (!lsCapabilityProbeDone) {
- const header = Buffer.alloc(8);
- const data = Buffer.alloc(24);
- header.writeUInt32LE(0x20080522, 0);
- libc.symbols.capget(ptr(header), ptr(data));
- lsCapabilityProbeDone = true;
- }
- return libc.symbols.getxattr(cstrPath(path), cstr("security.capability"), 0, 0n) > 0n;
-}
-
-function lsNativeModeProbe(path) {
- const buffer = Buffer.alloc(256);
- libc.symbols.statx(AT_FDCWD, cstrPath(path), AT_SYMLINK_NOFOLLOW, 0x0002, buffer);
-}
-
-function lsNeedsStatNanoseconds(opts) {
- const style = opts["time-style"];
- if (opts.t || opts.c || opts.u || opts.time != null || opts.sort === "time") return true;
- if (style === "full-iso" || style === "posix-full-iso") return true;
- return typeof style === "string" && style.startsWith("+") && /%[-_0^#+]*\d*N/.test(style);
-}
-
-function lsAttachStatNanoseconds(statInfo, path, dereference, enabled = true) {
- if (!enabled) return statInfo;
- try {
- const precise = nativeStatNanoseconds(path, dereference) ?? (dereference ? statSync(path, { bigint: true }) : lstatSync(path, { bigint: true }));
- attachStatNanoseconds(statInfo, precise);
- } catch {}
- return statInfo;
-}
-
-function lsRecursiveChildTarget(parent, entry) {
- if (isBytePath(parent)) return entry.path;
- if (parent === "." || parent.startsWith("./")) return `${parent.replace(/\/+$/, "")}/${entry.name}`;
- return entry.path;
-}
-
-function optionValues(value) {
- if (value == null) return [];
- return Array.isArray(value) ? value : [value];
-}
-
-function lsIgnored(name, opts) {
- return (opts.ignorePatterns ?? []).some((pattern) => globMatch(String(pattern), name));
-}
-
-function lsTotalBlocks(entries) {
- return entries.reduce((sum, entry) => entry.danglingDereference || entry.statFailed ? sum : sum + Number(lsAllocatedBlockCount(entry.stat, 1024n)), 0);
-}
-
-function sortLsEntries(entries, opts) {
- if (((opts.U || opts.f) && opts.sort == null) || opts.sort === "none") return;
- entries.sort((a, b) => {
- if (opts["group-directories-first"] || opts.group) {
- const dirCompare = Number(lsGroupDirectory(b)) - Number(lsGroupDirectory(a));
- if (dirCompare) return dirCompare;
- }
- let result;
- if (opts.sort === "name") result = compareLsNames(a.name, b.name, opts);
- else if (opts.S || opts.sort === "size") result = b.stat.size - a.stat.size || compareLsNames(a.name, b.name, opts);
- else if (opts.t || opts.c || opts.u || opts.time != null || opts.sort === "time") result = compareBigInt(lsEntryTimeNs(b, opts), lsEntryTimeNs(a, opts)) || compareLsNames(a.name, b.name, opts);
- else if (opts.sort === "width") result = [...pathDisplayName(a.name)].length - [...pathDisplayName(b.name)].length || compareLsNames(a.name, b.name, opts);
- else if (opts.v || opts.sort === "version") result = lsVersionCompare(a.name, b.name);
- else if (opts.X || opts.sort === "extension") result = extensionCompare(a.name, b.name);
- else result = compareLsNames(a.name, b.name, opts);
- return opts.r || opts.reverse ? -result : result;
- });
-}
-
-function compareLsNames(a, b, opts) {
- const aa = pathDisplayName(a);
- const bb = pathDisplayName(b);
- return opts.localeCollation ? compareSortLocaleText(aa, bb) : compareSortBytes(aa, bb);
-}
-
-function lsGroupDirectory(entry) {
- return entry.stat.isDirectory() || entry.targetDirectory;
-}
-
-function lsVersionCompare(a, b) {
- const aa = String(a);
- const bb = String(b);
- let ai = 0;
- let bi = 0;
- while (ai < aa.length || bi < bb.length) {
- if (aa[ai] === "~" || bb[bi] === "~") {
- if (aa[ai] !== "~") return 1;
- if (bb[bi] !== "~") return -1;
- ai++;
- bi++;
- continue;
- }
- if (ai >= aa.length) return -1;
- if (bi >= bb.length) return 1;
- if (isAsciiDigit(aa[ai]) && isAsciiDigit(bb[bi])) {
- const aStart = ai;
- const bStart = bi;
- while (isAsciiDigit(aa[ai])) ai++;
- while (isAsciiDigit(bb[bi])) bi++;
- const aDigits = aa.slice(aStart, ai);
- const bDigits = bb.slice(bStart, bi);
- const na = BigInt(aDigits.replace(/^0+/, "") || "0");
- const nb = BigInt(bDigits.replace(/^0+/, "") || "0");
- if (na !== nb) return na < nb ? -1 : 1;
- if (aDigits.length !== bDigits.length) return aDigits.length - bDigits.length;
- continue;
- }
- if (aa[ai] !== bb[bi]) return aa[ai] < bb[bi] ? -1 : 1;
- ai++;
- bi++;
- }
- return 0;
-}
-
-function lsEntryTimeNs(entry, opts) {
- const mode = lsEntryTimeMode(opts);
- const value = entry.stat[`${mode}Ns`];
- if (value != null) return BigInt(value);
- return BigInt(lsEntryTime(entry, opts).getTime()) * 1_000_000n;
-}
-
-function compareBigInt(a, b) {
- return a < b ? -1 : a > b ? 1 : 0;
-}
-
-function extensionCompare(a, b) {
- const ax = extensionSortKey(a);
- const bx = extensionSortKey(b);
- if (ax.ext !== bx.ext) return ax.ext < bx.ext ? -1 : 1;
- return a < b ? -1 : a > b ? 1 : 0;
-}
-
-function extensionSortKey(name) {
- const index = name.lastIndexOf(".");
- if (index <= 0 || index === name.length - 1) return { ext: "" };
- return { ext: name.slice(index + 1) };
-}
-
-async function renderLsEntries(entries, opts) {
- if (!entries.length) return "";
- if (opts.l || opts.g || opts.o) {
- const lines = renderLsLongEntries(await Promise.all(entries.map((entry) => lsLongEntryFields(entry, opts))), opts);
- return opts.zero ? lines.join("\0") + "\0" : lines.join("\n") + "\n";
- }
- if (opts.zero) return entries.map((entry) => formatLsEntry(entry, opts)).join("\0") + "\0";
- if (opts.m) return renderLsCommaEntries(entries, opts);
- const wideQuotedColumns = opts.width == null && (opts.quoting ?? opts["quoting-style"]) === "shell-escape";
- const separator = opts.C || opts.x ? (wideQuotedColumns ? " " : " ") : "\n";
- const widths = lsShortEntryWidths(entries, opts);
- const fields = [];
- let emittedInitialColorReset = Boolean(opts.colorResetEmitted);
- for (const entry of entries) {
- let field = formatLsEntry(entry, opts, widths);
- if (emittedInitialColorReset) field = stripLsLeadingReset(field);
- else if (field.startsWith("\x1b[0m")) {
- emittedInitialColorReset = true;
- opts.colorResetEmitted = true;
- }
- fields.push(field);
- }
- return (opts.C || opts.x) && !wideQuotedColumns ? renderLsColumnFields(fields, opts) : fields.join(separator) + "\n";
-}
-
-function renderLsColumnFields(fields, opts) {
- const outputWidth = opts.width ?? lsOutputWidth(opts);
- const widths = fields.map((field) => lsDisplayWidth(stripAnsi(field)));
- const columnCount = lsColumnCount(widths, outputWidth, opts);
- const rowCount = Math.ceil(fields.length / columnCount);
- const columnWidths = Array(columnCount).fill(0);
- for (let row = 0; row < rowCount; row++) {
- for (let column = 0; column < columnCount; column++) {
- const index = lsColumnFieldIndex(row, column, rowCount, columnCount, opts);
- if (index < fields.length) columnWidths[column] = Math.max(columnWidths[column], widths[index]);
- }
- }
- const starts = [];
- let start = 0;
- for (const width of columnWidths) {
- starts.push(start);
- start += width + 2;
- }
- const lines = [];
- for (let row = 0; row < rowCount; row++) {
- let line = "";
- let displayColumn = 0;
- for (let column = 0; column < columnCount; column++) {
- const index = lsColumnFieldIndex(row, column, rowCount, columnCount, opts);
- if (index >= fields.length) continue;
- if (line) {
- const padding = lsColumnPadding(displayColumn, starts[column], opts.tabSize);
- line += padding.text;
- displayColumn = padding.column;
- }
- line += fields[index];
- displayColumn += widths[index];
- }
- lines.push(line);
- }
- return lines.join("\n") + "\n";
-}
-
-function lsColumnCount(widths, outputWidth, opts) {
- const count = widths.length;
- if (count <= 1) return count;
- const available = Math.max(1, outputWidth);
- for (let columns = count; columns > 1; columns--) {
- const rows = Math.ceil(count / columns);
- const columnWidths = Array(columns).fill(0);
- for (let row = 0; row < rows; row++) {
- for (let column = 0; column < columns; column++) {
- const index = lsColumnFieldIndex(row, column, rows, columns, opts);
- if (index < count) columnWidths[column] = Math.max(columnWidths[column], widths[index]);
- }
- }
- const total = columnWidths.reduce((sum, width) => sum + width, 0) + ((columns - 1) * 2);
- if (total <= available) return columns;
- }
- return 1;
-}
-
-function lsColumnFieldIndex(row, column, rowCount, columnCount, opts) {
- return opts.x ? (row * columnCount) + column : (column * rowCount) + row;
-}
-
-function lsColumnPadding(column, target, tabSize) {
- let text = "";
- while (column < target) {
- const nextTab = tabSize > 0 ? column + tabSize - (column % tabSize) : Number.POSITIVE_INFINITY;
- if (nextTab <= target && nextTab - column > 1) {
- text += "\t";
- column = nextTab;
- } else {
- text += " ";
- column++;
- }
- }
- return { text, column };
-}
-
-function stripLsLeadingReset(text) {
- return text.startsWith("\x1b[0m") ? text.slice(4) : text;
-}
-
-function renderLsCommaEntries(entries, opts) {
- const fields = [];
- let emittedInitialColorReset = Boolean(opts.colorResetEmitted);
- for (const entry of entries) {
- let field = formatLsEntry(entry, opts);
- if (emittedInitialColorReset) field = stripLsLeadingReset(field);
- else if (field.startsWith("\x1b[0m")) {
- emittedInitialColorReset = true;
- opts.colorResetEmitted = true;
- }
- fields.push(field);
- }
- const width = opts.width ?? Number.POSITIVE_INFINITY;
- const lines = [];
- let line = "";
- for (let i = 0; i < fields.length; i++) {
- const text = `${fields[i]}${i === fields.length - 1 ? "" : ","}`;
- const candidate = line ? `${line} ${text}` : text;
- if (line && width > 0 && candidate.length > width) {
- lines.push(line);
- line = text;
- } else {
- line = candidate;
- }
- }
- if (line) lines.push(line);
- return lines.join("\n") + "\n";
-}
-
-function formatLsDiredOutput(output, quotingStyle = "literal") {
- const fileMarks = [];
- const subdirMarks = [];
- let out = "";
- let offset = 0;
- for (const rawLine of output.split(/(?<=\n)/)) {
- if (rawLine === "") continue;
- const hasNewline = rawLine.endsWith("\n");
- const line = hasNewline ? rawLine.slice(0, -1) : rawLine;
- if (line === "") {
- out += rawLine;
- offset += Buffer.byteLength(rawLine);
- continue;
- }
- const prefixed = ` ${line}`;
- const lineStart = offset;
- const subdir = line.match(/^(.+):$/);
- if (subdir) {
- subdirMarks.push(lineStart + 2, lineStart + 2 + Buffer.byteLength(subdir[1]));
- } else if (!/^total(?:\s|$)/.test(line)) {
- const range = lsDiredFilenameRange(line);
- if (range) fileMarks.push(lineStart + 2 + range.start, lineStart + 2 + range.end);
- }
- const rendered = `${prefixed}${hasNewline ? "\n" : ""}`;
- out += rendered;
- offset += Buffer.byteLength(rendered);
- }
- if (fileMarks.length) out += `//DIRED// ${fileMarks.join(" ")}\n`;
- if (subdirMarks.length) out += `//SUBDIRED// ${subdirMarks.join(" ")}\n`;
- out += `//DIRED-OPTIONS// --quoting-style=${quotingStyle}\n`;
- return out;
-}
-
-function lsDiredFilenameRange(line) {
- let text = line;
- if (/^[bcdlps?-][rwx?-]{9}/.test(line) && line.slice(1, 10).includes("?")) {
- const match = line.match(/^(\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+)(.*)$/);
- if (!match) return null;
- const prefixBytes = Buffer.byteLength(match[1]);
- return { start: prefixBytes, end: prefixBytes + Buffer.byteLength(match[2]) };
- }
- if (/^[bcdlps-][rwx-]{9}/.test(line)) {
- const hasContextColumn = /^[bcdlps-][rwx-]{9}\s+\S+\s+\S+\s+\S+\s+\?\s+/.test(line);
- const prefixPattern = hasContextColumn
- ? /^(\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+)(.*)$/
- : /^(\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+)(.*)$/;
- const match = line.match(prefixPattern);
- if (!match) return null;
- const prefixBytes = Buffer.byteLength(match[1]);
- text = match[2];
- const symlinkIndex = text.indexOf(" -> ");
- const name = symlinkIndex === -1 ? text : text.slice(0, symlinkIndex);
- return { start: prefixBytes, end: prefixBytes + Buffer.byteLength(name) };
- }
- if (/^\s*$/.test(text)) return null;
- return { start: 0, end: Buffer.byteLength(text) };
-}
-
-function renderLsLongEntries(rows, opts) {
- const widths = {
- inode: maxLsFieldWidth(rows, "inode", 0),
- block: maxLsFieldWidth(rows, "block", 0),
- nlink: maxLsFieldWidth(rows, "nlink", 0),
- user: maxLsFieldWidth(rows, "user", 0),
- author: maxLsFieldWidth(rows, "author", 0),
- group: maxLsFieldWidth(rows, "group", 0),
- context: maxLsFieldWidth(rows, "context", 0),
- size: maxLsFieldWidth(rows, "size", 0),
- };
- return rows.map((row, index) => {
- const fields = [row.mode, row.nlink.padStart(widths.nlink)];
- if (opts.i || opts.inode) fields.unshift(row.inode.padStart(widths.inode));
- if (opts.s || opts.size) fields.unshift(row.block.padStart(widths.block));
- if (!opts.g) fields.push(row.user.padStart(widths.user));
- if (!(opts.G || opts.o)) fields.push(row.group.padStart(widths.group));
- if (opts.author) fields.push(row.author.padStart(widths.author));
- if (opts.Z || opts.context) fields.push(row.context.padStart(widths.context));
- fields.push(row.size.padStart(widths.size), row.time, row.name);
- let line = opts.colorEnabled && lsNormalColorCode() != null ? formatLsNormalLongRow(fields, index === 0) : fields.join(" ");
- if (row.clearToEol && lsDisplayWidth(stripAnsi(line)) >= lsOutputWidth(opts)) line += "\x1b[K";
- return line;
- });
-}
-
-function formatLsNormalLongRow(fields, resetFirst = false) {
- const normal = lsNormalColorCode();
- if (normal == null) return fields.join(" ");
- const coloredPrefix = lsNormalColoredPrefix();
- const normalPrefix = `\x1b[${normal}m`;
- const resetNormalPrefix = `\x1b[0m${normalPrefix}`;
- let name = fields.at(-1);
- if (name.startsWith(resetNormalPrefix) && name.endsWith("\x1b[0m")) name = name.slice(resetNormalPrefix.length, -4);
- else if (name.startsWith(coloredPrefix)) name = `\x1b[m${name.slice(coloredPrefix.length)}`;
- else if (name.startsWith("\x1b[0m")) name = `\x1b[m${name.slice(4)}`;
- else {
- if (name.startsWith(normalPrefix) && name.endsWith("\x1b[0m")) name = name.slice(normalPrefix.length, -4);
- else return `\x1b[${normal}m${fields.join(" ")}\x1b[0m`;
- }
- if (name.startsWith("\x1b[m") && name.endsWith("\x1b[0m")) name = name.slice(0, -4);
- return `${resetFirst ? "\x1b[0m" : ""}\x1b[${normal}m${[...fields.slice(0, -1), name].join(" ")}\x1b[0m`;
-}
-
-function stripAnsi(text) {
- return String(text).replace(/\x1b\[[0-9;]*[A-Za-z]/g, "");
-}
-
-function lsDisplayWidth(text) {
- let width = 0;
- for (const ch of String(text)) width += displayWidth(ch);
- return width;
-}
-
-function lsOutputWidth(opts) {
- const value = opts.width ?? process.env.COLUMNS ?? 80;
- const width = Number(value);
- return Number.isFinite(width) && width > 0 ? width : 80;
-}
-
-function maxLsFieldWidth(rows, key, minimum) {
- return Math.max(minimum, ...rows.map((row) => row[key]?.length ?? 0));
-}
-
-async function lsLongEntryFields(entry, opts) {
- let name = formatLsName(entry, opts);
- if (lsNeedsShellEscapeColorPadding(entry, name, opts)) name = ` ${name}`;
- if (entry.statFailed) {
- return {
- inode: entry.direntInode == null ? "?" : String(entry.direntInode),
- block: "?",
- mode: `${entry.direntTypeChar ?? "?"}?????????`,
- nlink: "?",
- user: "?",
- author: "?",
- group: "?",
- context: "?",
- size: "?",
- time: " ?",
- name,
- };
- }
- const uidText = String(entry.stat.uid);
- const gidText = String(entry.stat.gid);
- const numericOwner = opts.n || opts["numeric-uid-gid"];
- const userText = numericOwner ? uidText : await userNameForUid(entry.stat.uid) ?? uidText;
- const groupText = numericOwner ? gidText : await groupName(entry.stat.gid);
- if (entry.danglingDereference) {
- return {
- inode: "?",
- block: "?",
- mode: `${fileTypeChar(entry.linkStat ?? entry.stat)}?????????`,
- nlink: "?",
- user: "?",
- author: "?",
- group: "?",
- context: "?",
- size: "?",
- time: " ?",
- name,
- };
- }
- if (entry.linkStat?.isSymbolicLink() && entry.stat === entry.linkStat) {
- const target = await readlink(entry.path);
- const quotedTarget = quoteLsName(target, opts);
- name += ` -> ${opts.colorEnabled ? colorizeLsTarget(quotedTarget) : quotedTarget}`;
- } else if (opts.colorEnabled && lsNormalColorCode() == null && name.endsWith("\x1b[0m")) {
- return {
- inode: lsEntryInodeText(entry),
- block: entry.danglingDereference ? "?" : lsBlockText(entry.stat, opts),
- mode: `${modeString(entry.stat)}${lsAclIndicator(entry)}`,
- nlink: String(entry.stat.nlink),
- user: userText,
- author: userText,
- group: groupText,
- context: lsSecurityContext(entry, opts),
- size: String(lsDisplaySize(entry.stat, opts)),
- time: lsTimeText(lsEntryTime(entry, opts), opts),
- name,
- clearToEol: true,
- };
- }
- return {
- inode: lsEntryInodeText(entry),
- block: entry.danglingDereference ? "?" : lsBlockText(entry.stat, opts),
- mode: `${modeString(entry.stat)}${lsAclIndicator(entry)}`,
- nlink: String(entry.stat.nlink),
- user: userText,
- author: userText,
- group: groupText,
- context: lsSecurityContext(entry, opts),
- size: String(lsDisplaySize(entry.stat, opts)),
- time: lsTimeText(lsEntryTime(entry, opts), opts),
- name,
- };
-}
-
-function lsAclIndicator(entry) {
- // POSIX ACLs are represented by a trailing '+' in GNU ls's mode field.
- // Node/Bun do not expose ACLs through stat, so use getfacl when present.
- // A symlink itself cannot carry a POSIX access ACL; only query its target
- // when this ls invocation dereferenced it.
- if (process.platform !== "linux") return "";
- const noDereference = entry.linkStat?.isSymbolicLink() && entry.stat === entry.linkStat;
- if (!noDereference) {
- try {
- const result = Bun.spawnSync(["getfacl", "--omit-header", "--absolute-names", "--", String(entry.path)], { stdout: "pipe", stderr: "ignore" });
- if (result.exitCode === 0 && lsAclIndicatorFromText(new TextDecoder().decode(result.stdout)) === "+") return "+";
- } catch {
- // A missing ACL helper does not prevent checking the SELinux label below.
- }
- }
- // GNU ls uses '.' when a security context exists but no extended ACL does.
- return selinuxSecurityContext(entry.path, noDereference) == null ? "" : ".";
-}
-
-function lsAclIndicatorFromText(text) {
- for (const line of String(text).split(/\r?\n/)) {
- if (line.startsWith("default:") || line.startsWith("mask:") || /^user:[^:]+:/.test(line) || /^group:[^:]+:/.test(line)) return "+";
- }
- return "";
-}
-
-function lsSecurityContext(entry, _opts) {
- const noDereference = entry.linkStat?.isSymbolicLink() && entry.stat === entry.linkStat;
- return selinuxSecurityContext(entry.path, noDereference) ?? "?";
-}
-
-function selinuxSecurityContext(path, noDereference = false) {
- if (process.platform !== "linux") return null;
- // A disk can retain stale SELinux attributes after being booted with SMACK.
- // GNU coreutils selects the active LSM, so prefer SMACK64 whenever SMACK is
- // active rather than returning an unrelated security.selinux attribute.
- if (smackRuntimeEnabled()) return securityXattrText(path, "security.SMACK64", noDereference);
- const api = selinuxApi();
- if (api) {
- const getter = selinuxInterposedContextGetter(api, noDereference);
- return selinuxAllocatedString(api, (output) => getter(cstrPath(path), output));
- }
- try {
- const result = Bun.spawnSync(["getfattr", ...(noDereference ? ["-h"] : []), "--only-values", "-n", "security.selinux", "--", String(path)], { stdout: "pipe", stderr: "ignore" });
- if (result.exitCode !== 0 || !result.stdout?.byteLength) return null;
- // Linux stores security.selinux as a NUL-terminated context. getfattr's
- // --only-values output preserves that terminator, unlike ordinary text
- // attributes, so remove it along with any line ending.
- const value = new TextDecoder().decode(result.stdout).replace(/[\0\r\n]+$/, "");
- return value || null;
- } catch {
- return null;
- }
-}
-
-function securityXattrText(path, name, noDereference = false) {
- try {
- const result = Bun.spawnSync(["getfattr", ...(noDereference ? ["-h"] : []), "--only-values", "-n", name, "--", String(path)], { stdout: "pipe", stderr: "ignore" });
- if (result.exitCode !== 0 || !result.stdout?.byteLength) return null;
- return new TextDecoder().decode(result.stdout).replace(/[\0\r\n]+$/, "") || null;
- } catch {
- return null;
- }
-}
-
-const selinuxContextGetters = new Map();
-
-function selinuxInterposedContextGetter(api, noDereference) {
- const name = noDereference ? "lgetfilecon" : "getfilecon";
- if (selinuxContextGetters.has(name)) return selinuxContextGetters.get(name);
- const address = libc.symbols.dlsym(0, ptr(Buffer.from(`${name}\0`)));
- const getter = address
- ? linkSymbols({ [name]: { ptr: address, args: [FFIType.cstring, FFIType.ptr], returns: FFIType.i32 } }).symbols[name]
- : api.symbols[name];
- selinuxContextGetters.set(name, getter);
- return getter;
-}
-
-function selinuxRuntimeEnabled() {
- if (process.platform !== "linux") return false;
- if (smackRuntimeEnabled()) return true;
- if (existsSync("/sys/fs/selinux/enforce")) return true;
- try {
- const result = Bun.spawnSync(["getenforce"], { stdout: "pipe", stderr: "ignore" });
- if (result.exitCode !== 0) return false;
- return new TextDecoder().decode(result.stdout).trim() !== "Disabled";
- } catch {
- return false;
- }
-}
-
-function smackRuntimeEnabled() {
- if (process.platform !== "linux") return false;
- try {
- const modules = readFileSync("/sys/kernel/security/lsm", "utf8").trim().split(",");
- if (modules.includes("smack")) return true;
- } catch {}
- return existsSync("/sys/fs/smackfs");
-}
-
-function processSecurityContext() {
- if (smackRuntimeEnabled()) {
- try {
- const context = readFileSync("/proc/self/attr/current", "utf8").replace(/[\0\r\n]+$/, "");
- if (context) return context;
- } catch {}
- }
- const lsmContext = lsmSelfSecurityContext();
- if (lsmContext != null) return lsmContext;
- if (existsSync("/sys/fs/selinux/enforce")) {
- const api = selinuxApi();
- if (api) {
- const output = Buffer.alloc(8);
- if (api.symbols.getcon(ptr(output)) === 0) {
- const address = read.ptr(ptr(output), 0);
- if (address) {
- try {
- const context = new CString(address).toString().replace(/[\0\r\n]+$/, "");
- if (context) return context;
- } finally {
- api.symbols.freecon(address);
- }
- }
- }
- }
- try {
- const context = readFileSync("/proc/self/attr/current", "utf8").replace(/[\0\r\n]+$/, "");
- if (context) return context;
- } catch {}
- }
- // ps exposes the same process label on SELinux systems and also provides a
- // useful fallback for minimal runtimes where libselinux is unavailable.
- try {
- const result = Bun.spawnSync(["ps", "-o", "label=", "-p", String(process.pid)], { stdout: "pipe", stderr: "ignore" });
- if (result.exitCode !== 0) return null;
- return new TextDecoder().decode(result.stdout).trim() || null;
- } catch {
- return null;
- }
-}
-
-function lsmSelfSecurityContext() {
- if (process.platform !== "linux") return null;
- // lsm_get_self_attr(LSM_ATTR_CURRENT, ...) is syscall 459 on Linux's
- // current native ABIs. Unlike the legacy proc attribute, it can select the
- // SELinux record correctly when several security modules are compiled in.
- const size = Buffer.alloc(4);
- libc.symbols.syscall(459, 100, 0, ptr(size), 0);
- const required = size.readUInt32LE(0);
- if (required < 32 || required > 1024 * 1024) return null;
- const records = Buffer.alloc(required);
- size.writeUInt32LE(required, 0);
- const count = Number(libc.symbols.syscall(459, 100, ptr(records), ptr(size), 0));
- if (count <= 0) return null;
- let offset = 0;
- for (let index = 0; index < count && offset + 32 <= records.length; index++) {
- const id = records.readBigUInt64LE(offset);
- const length = Number(records.readBigUInt64LE(offset + 16));
- const contextLength = Number(records.readBigUInt64LE(offset + 24));
- if (length < 32 || offset + length > records.length || contextLength > length - 32) return null;
- if (id === 101n) {
- const context = records.subarray(offset + 32, offset + 32 + contextLength).toString("utf8").replace(/[\0\r\n]+$/, "");
- return context || null;
- }
- offset += length;
- }
- return null;
-}
-
-let lastSecurityContextErrno = 0;
-
-function setSelinuxSecurityContext(path, context, noDereference = false) {
- if (smackRuntimeEnabled()) {
- const value = Buffer.from(String(context));
- const errnoPointer = libc.symbols.__errno_location();
- if (errnoPointer) libc.symbols.memset(errnoPointer, 0, 4);
- const setter = noDereference ? libc.symbols.lsetxattr : libc.symbols.setxattr;
- const result = setter(cstrPath(path), cstr("security.SMACK64"), ptr(value), BigInt(value.byteLength), 0);
- lastSecurityContextErrno = result === 0 ? 0 : libcErrno();
- return result === 0;
- }
- lastSecurityContextErrno = 0;
- const api = existsSync("/sys/fs/selinux/enforce") ? selinuxApi() : null;
- if (api) {
- if (api.symbols.security_check_context(cstr(context)) !== 0) return false;
- const setter = noDereference ? api.symbols.lsetfilecon : api.symbols.setfilecon;
- return setter(cstrPath(path), cstr(context)) === 0;
- }
- try {
- const result = Bun.spawnSync(["setfattr", ...(noDereference ? ["-h"] : []), "-n", "security.selinux", "-v", String(context), "--", String(path)], { stdout: "ignore", stderr: "ignore" });
- return result.exitCode === 0;
- } catch {
- return false;
- }
-}
-
-function restoreSelinuxSecurityContext(path, noDereference = false, recursive = false) {
- try {
- const result = Bun.spawnSync(["restorecon", ...(noDereference ? ["-h"] : []), ...(recursive ? ["-R"] : []), "-F", "--", String(path)], { stdout: "ignore", stderr: "ignore" });
- return result.exitCode === 0;
- } catch {
- return false;
- }
-}
-
-function selinuxCreationOptions(program, opts) {
- const enabled = selinuxRuntimeEnabled();
- const explicitContext = typeof opts.context === "string" && enabled ? opts.context : null;
- if (typeof opts.context === "string" && !enabled) {
- stderr(`${program}: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n`);
- }
- return {
- enabled,
- explicitContext,
- restoreContext: enabled && (opts.Z || opts.context === true),
- };
-}
-
-async function withSelinuxCreationContext(program, options, create) {
- const api = options.explicitContext != null && existsSync("/sys/fs/selinux/enforce") ? selinuxApi() : null;
- let defaultContextSet = false;
- if (api) {
- if (api.symbols.security_check_context(cstr(options.explicitContext)) !== 0
- || api.symbols.setfscreatecon(ptr(cstr(options.explicitContext))) !== 0) {
- throw new UsageError(`failed to set default file creation context to '${options.explicitContext}': Invalid argument`);
- }
- defaultContextSet = true;
- }
- const created = async (path) => {
- if (options.explicitContext != null && !defaultContextSet) {
- if (!setSelinuxSecurityContext(path, options.explicitContext)) {
- const message = lastSecurityContextErrno === 1 ? "Operation not permitted" : "Invalid argument";
- throw new UsageError(`failed to set default file creation context to '${options.explicitContext}': ${message}`);
- }
- } else if (options.restoreContext && !restoreSelinuxSecurityContext(path)) {
- throw new UsageError(`failed to restore context for '${path}'`);
- }
- };
- try {
- // setfscreatecon(3) is thread-local. Bun's promise-based mkdir may run
- // the syscall on a worker thread, so callers that create directories must
- // use their synchronous path while an explicit creation context is set.
- return await create(created, defaultContextSet);
- } finally {
- if (defaultContextSet) api.symbols.setfscreatecon(null);
- }
-}
-
-function lsNeedsShellEscapeColorPadding(entry, renderedName, opts) {
- const quoting = opts.quoting ?? opts["quoting-style"];
- if (quoting !== "shell-escape" || !opts.colorEnabled || !renderedName.startsWith("\x1b[0m")) return false;
- const quoted = quoteLsName(entry.name, opts);
- return !quoted.startsWith("'");
-}
-
-function lsShortEntryWidths(entries, opts) {
- return {
- inode: opts.i || opts.inode ? Math.max(...entries.map((entry) => lsEntryInodeText(entry).length)) : 0,
- block: opts.s || opts.size ? Math.max(...entries.map((entry) => entry.danglingDereference || entry.statFailed ? 1 : lsBlockText(entry.stat, opts).length)) : 0,
- };
-}
-
-function formatLsEntry(entry, opts, widths = null) {
- const name = formatLsName(entry, opts);
- const fields = [];
- if (opts.i || opts.inode) fields.push(lsEntryInodeText(entry).padStart(widths?.inode ?? 0));
- if (opts.s || opts.size) fields.push((entry.danglingDereference || entry.statFailed ? "?" : lsBlockText(entry.stat, opts)).padStart(widths?.block ?? 0));
- if (opts.Z || opts.context) fields.push(entry.statFailed ? "?" : lsSecurityContext(entry, opts));
- fields.push(name);
- return fields.join(" ");
-}
-
-function lsEntryInodeText(entry) {
- if (entry.danglingDereference || (entry.statFailed && entry.direntInode == null)) return "?";
- // d_ino can identify the covered directory entry rather than the mounted
- // object at a mount point. Since this implementation already gathered
- // metadata, prefer st_ino; this also selects the target inode under -L.
- if (!entry.statFailed && entry.stat?.ino != null) return String(entry.stat.ino);
- return String(entry.direntInode);
-}
-
-function lsBlockText(statInfo, opts) {
- const allocatedBytes = Number(lsAllocatedBytes(statInfo));
- const human = opts.h || opts["human-readable"] || opts.si || opts.blockHumanReadable || opts.blockSi;
- return human ? lsHumanSize(allocatedBytes, opts.si || opts.blockSi ? 1000 : 1024) : String(lsAllocatedBlockCount(statInfo, BigInt(opts.blockSize || 1024)));
-}
-
-function lsDisplaySize(statInfo, opts) {
- if (opts.h || opts["human-readable"] || opts.si) return lsHumanSize(statInfo.size, opts.si ? 1000 : 1024);
- return Math.ceil(statInfo.size / (opts.sizeBlockSize || 1));
-}
-
-function lsAllocatedBytes(statInfo) {
- return BigInt(statInfo.blocks ?? Math.ceil(statInfo.size / 512)) * 512n;
-}
-
-function lsAllocatedBlockCount(statInfo, blockSize) {
- const bytes = lsAllocatedBytes(statInfo);
- return (bytes + blockSize - 1n) / blockSize;
-}
-
-function lsHumanSize(bytes, base = 1024) {
- if (bytes < base) return String(bytes);
- const units = base === 1000 ? ["B", "k", "M", "G", "T"] : ["B", "K", "M", "G", "T"];
- return humanSizeWithUnits(bytes, base, units);
-}
-
-function lsTimeText(date, opts) {
- const style = opts["time-style"];
- if (typeof style === "string" && style.startsWith("+")) return strftime(date, style.slice(1));
- if (style === "full-iso" || style === "posix-full-iso") return lsFullIsoTime(date);
- if (style === "iso" || style === "posix-iso") return `${strftime(date, "%F")} `;
- if (style === "long-iso" || style === "posix-long-iso") return strftime(date, "%F %R");
- if (style == null || style === "locale" || style === "posix-locale") {
- const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
- const now = Date.now();
- const sixMonthsMs = 365.2425 * 24 * 60 * 60 * 1000 / 2;
- const recent = date.getTime() <= now && date.getTime() >= now - sixMonthsMs;
- return `${months[date.getMonth()]} ${String(date.getDate()).padStart(2)} ${recent ? strftime(date, "%H:%M") : ` ${date.getFullYear()}`}`;
- }
- return strftime(date, "%F %R");
-}
-
-function lsEntryTime(entry, opts) {
- const mode = lsEntryTimeMode(opts);
- return lsStatTime(entry.stat, mode);
-}
-
-function lsEntryTimeMode(opts) {
- const mode = opts.time ?? (opts.u ? "access" : opts.c ? "ctime" : "mtime");
- if (["access", "atime", "use"].includes(mode)) return "atime";
- if (["ctime", "status"].includes(mode)) return "ctime";
- if (["birth", "creation"].includes(mode)) return "birthtime";
- return "mtime";
-}
-
-function lsStatTime(statInfo, mode) {
- const date = statInfo[mode];
- const value = statInfo[`${mode}Ns`];
- if (value == null) return date;
- const fraction = Number(((BigInt(value) % 1_000_000_000n) + 1_000_000_000n) % 1_000_000_000n);
- return attachDateNanoseconds(new Date(date.getTime()), fraction);
-}
-
-function lsFullIsoTime(date) {
- return strftime(date, "%F %T.%N %z");
-}
-
-function formatLsName(entry, opts) {
- const name = quoteLsName(entry.name, opts);
- const suffix = classifySuffix(entry.stat, opts);
- const linkedName = opts.hyperlinkEnabled ? formatLsHyperlink(name, lsHyperlinkPath(entry), opts) : name;
- return `${opts.colorEnabled ? colorizeLs(linkedName, entry) : linkedName}${suffix}`;
-}
-
-function lsHyperlinkPath(entry) {
- if (entry.linkStat?.isSymbolicLink() && entry.targetDirectory && !isBytePath(entry.path)) return entry.path.replace(/\/+$/, "");
- return entry.path;
-}
-
-function formatLsHyperlink(name, path, opts) {
- if (!opts.hyperlinkEnabled || opts.zero) return name;
- return `\x1b]8;;${fileUriForLs(path)}\x1b\\${name}\x1b]8;;\x1b\\`;
-}
-
-function fileUriForLs(path) {
- const host = osHostname();
- if (isBytePath(path)) return `file://${host}${encodeLsFileUriBytes(absoluteLsPathBytes(path))}`;
- return `file://${host}${encodeLsFileUriPath(resolve(pathDisplayName(path)))}`;
-}
-
-async function lsDirectoryLabelPath(path) {
- const s = await lstat(path).catch(() => null);
- if (!s?.isSymbolicLink()) return path;
- const target = await readlink(path).catch(() => null);
- if (target == null) return path;
- return isAbsolute(target) ? target : resolve(pathDirname(pathDisplayName(path)), target);
-}
-
-function absoluteLsPathBytes(path) {
- if (path[0] === 0x2f) return Buffer.from(path);
- return bufferPathJoin(Buffer.from(resolve(".")), path);
-}
-
-function encodeLsFileUriBytes(path) {
- return [...Buffer.from(path)].map((byte) => {
- const ch = String.fromCharCode(byte);
- return /[A-Za-z0-9/._~-]/.test(ch) ? ch : `%${byte.toString(16).padStart(2, "0")}`;
- }).join("");
-}
-
-function encodeLsFileUriPath(path) {
- return String(path).replace(/[^A-Za-z0-9/._~-]/g, (ch) => {
- const bytes = new TextEncoder().encode(ch);
- return [...bytes].map((byte) => `%${byte.toString(16).padStart(2, "0")}`).join("");
- });
-}
-
-function quoteLsName(name, opts) {
- const displayName = pathDisplayName(name);
- if (opts.zero) return displayName;
- const style = lsResolvedQuotingStyle(opts);
- const text = opts.q && !["c", "escape", "shell-escape", "clocale", "locale"].includes(style) ? lsQuestionName(displayName) : displayName;
- if (style === "literal") return text;
- if (style === "shell") return shellQuoteLsName(displayName, false, text);
- if (style === "question") return lsQuestionName(displayName);
- if (style === "escape") return lsEscapedName(displayName, { escapeSpaces: true });
- if (style === "c") return `"${lsEscapedName(displayName)}"`;
- if (style === "clocale") return lsUsesUtf8Locale() ? `‘${lsEscapedName(displayName, { escapeDouble: false })}’` : `"${lsEscapedName(displayName)}"`;
- if (style === "locale") return lsUsesUtf8Locale() ? `‘${lsEscapedName(displayName, { escapeDouble: false })}’` : `'${lsEscapedName(displayName)}'`;
- if (style === "shell-always" || style === "shell-al") return shellQuoteLsName(displayName, true, text);
- if (style === "shell-escape") return shellEscapeLsName(displayName);
- if (style === "shell-escape-always" || style === "shell-escape-al") return shellEscapeLsName(displayName, true);
- return text;
-}
-
-function quoteLsDirectoryLabelName(name, opts) {
- const quoted = quoteLsName(name, opts);
- const style = lsResolvedQuotingStyle(opts);
- const displayName = pathDisplayName(name);
- if ((style === "shell" || style === "shell-escape") && displayName.includes(":") && quoted === displayName) return shellQuoteLsName(displayName, true);
- return quoted;
-}
-
-function lsResolvedQuotingStyle(opts) {
- if (opts.N) return "literal";
- if (opts.Q || opts["quote-name"]) return "c";
- const style = opts.quoting ?? opts["quoting-style"];
- return resolveLsQuotingStyle(style) ?? (opts.q ? "question" : process.stdout.isTTY ? "shell-escape" : "literal");
-}
-
-function lsQuestionName(name) {
- return [...String(name)].map((ch) => {
- const code = ch.codePointAt(0);
- return code < 32 || code === 127 ? "?" : ch;
- }).join("");
-}
-
-function lsUsesUtf8Locale() {
- const locale = process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG || "";
- return /utf-?8/i.test(locale);
-}
-
-function localeQuotedDiagnostic(value) {
- return lsUsesUtf8Locale() ? `\u2018${value}\u2019` : `'${value}'`;
-}
-
-function localeQuotedEscapedDiagnostic(value) {
- return localeQuotedDiagnostic(lsEscapedName(value, { escapeDouble: false }));
-}
-
-function lsEscapedName(name, { escapeDouble = true, escapeSpaces = false } = {}) {
- return [...String(name)].map((ch) => {
- const code = ch.codePointAt(0);
- if (ch === " " && escapeSpaces) return "\\ ";
- if (ch === "\\") return "\\\\";
- if (ch === "\"" && escapeDouble) return "\\\"";
- if (ch === "\n") return "\\n";
- if (ch === "\t") return "\\t";
- if (ch === "\r") return "\\r";
- if (ch === "\b") return "\\b";
- if (ch === "\f") return "\\f";
- if (ch === "\v") return "\\v";
- if (ch === "\x07") return "\\a";
- if (code < 32 || code === 127) return `\\${code.toString(8).padStart(3, "0")}`;
- return ch;
- }).join("");
-}
-
-function shellEscapeLsName(name, always = false) {
- const text = String(name);
- if (!always && /^[A-Za-z0-9_.,@%+=/-]+$/.test(text)) return text;
- if (!/[\x00-\x1f\x7f]/.test(text)) return shellQuoteLsName(text, always);
- const parts = [];
- let plain = "";
- let escaped = "";
- const flushPlain = () => {
- if (plain) {
- parts.push(`'${plain.replaceAll("'", "'\\''")}'`);
- plain = "";
- }
- };
- const flushEscaped = () => {
- if (escaped) {
- parts.push(`$'${escaped}'`);
- escaped = "";
- }
- };
- for (const ch of text) {
- const code = ch.codePointAt(0);
- if (code < 32 || code === 127) {
- flushPlain();
- escaped += lsEscapedName(ch);
- } else {
- flushEscaped();
- plain += ch;
- }
- }
- flushPlain();
- flushEscaped();
- if (!parts.length) return "''";
- if (always && parts.length === 1 && !parts[0].startsWith("$")) return parts[0];
- return parts.join("");
-}
-
-function shellQuoteLsName(name, always = false, rendered = name) {
- const text = String(name);
- const out = String(rendered);
- if (!always && !/[\s\\'"$`|&;<>(){}\[\]*?!]/.test(text)) return out;
- if (out.includes("'") && !out.includes("\"")) return `"${out.replaceAll("\\", "\\\\").replaceAll("$", "\\$").replaceAll("`", "\\`").replaceAll("\"", "\\\"")}"`;
- return `'${out.replaceAll("'", "'\\''")}'`;
-}
-
-function classifySuffix(s, opts) {
- if (opts.indicatorStyle === "none") return "";
- if (s.isDirectory()) return "/";
- if (opts.indicatorStyle === "slash") return "";
- if (s.isSymbolicLink()) return "@";
- if (s.isFIFO()) return "|";
- if (s.isSocket()) return "=";
- if (opts.indicatorStyle === "file-type") return "";
- if (s.mode & 0o111) return "*";
- return "";
-}
-
-function colorizeLs(name, entry) {
- const code = lsColorCodeForEntry(entry);
- if (code != null) return lsColorWrap(name, code);
- const custom = lsColorForName(entry.name);
- if (custom != null) return lsColorWrap(name, custom);
- const fileCode = lsColorCode("fi");
- if (fileCode != null) return lsColorWrap(name, fileCode);
- const normal = lsNormalColorCode();
- return normal == null ? name : `\x1b[0m\x1b[${normal}m${name}\x1b[0m`;
-}
-
-function colorizeLsTarget(name) {
- const code = lsColorCode("mi");
- return code == null ? name : lsColorWrap(name, code, false);
-}
-
-function lsColorWrap(name, code, resetFirst = true) {
- return `${resetFirst ? lsColorResetPrefix() : ""}\x1b[${code}m${name}${lsColorResetSuffix()}`;
-}
-
-function lsColorResetPrefix() {
- const normal = lsNormalColorCode();
- return normal == null ? lsColorResetSuffix() : lsNormalColoredPrefix();
-}
-
-function lsNormalColoredPrefix() {
- const normal = lsNormalColorCode();
- return normal == null ? lsColorResetSuffix() : `${lsColorResetSuffix()}\x1b[${normal}m\x1b[m`;
-}
-
-function lsNormalColorCode() {
- return lsColorCode("no");
-}
-
-function lsColorResetSuffix() {
- const reset = lsColorCode("rs");
- return `\x1b[${reset ?? "0"}m`;
-}
-
-function lsColorCodeForEntry(entry) {
- const s = entry.stat;
- if (entry.linkStat?.isSymbolicLink() && s === entry.linkStat) {
- const linkCode = lsColorCode("ln");
- if (entry.targetMissing) {
- const orphanCode = lsColorCode("or");
- if (orphanCode != null && orphanCode !== "") return orphanCode;
- if (orphanCode === "") return linkCode && linkCode !== "target" ? linkCode : "";
- return linkCode === "target" ? null : linkCode ?? "40;31;01";
- }
- if (linkCode === "target") {
- if (entry.targetDirectory) return lsColorCode("di") ?? "01;34";
- return null;
- }
- return linkCode ?? "01;36";
- }
- if (s.isDirectory()) {
- if ((s.mode & 0o1000) && (s.mode & 0o002)) return lsSpecialDirectoryColor("tw", "30;42");
- if (s.mode & 0o1000) return lsSpecialDirectoryColor("st", "37;44");
- if (s.mode & 0o002) return lsSpecialDirectoryColor("ow", "34;42");
- return lsColorCode("di") || "01;34";
- }
- if (entry.hasCapability) return lsColorCode("ca");
- if (s.mode & 0o4000) return lsColorCode("su") ?? null;
- if (s.mode & 0o2000) return lsColorCode("sg") ?? null;
- if (s.mode & 0o111) return lsColorCode("ex") ?? "01;32";
- if (s.nlink > 1) {
- const hardLinkCode = lsColorCode("mh");
- if (hardLinkCode != null && hardLinkCode !== "" && hardLinkCode !== "00") return hardLinkCode;
- }
- return null;
-}
-
-function lsSpecialDirectoryColor(key, defaultCode) {
- const code = lsColorCode(key);
- if (code == null) return defaultCode;
- if (code === "") return lsColorCode("di") || "01;34";
- return code;
-}
-
-function lsColorCode(key) {
- for (const part of lsColorParts()) {
- if (part.key === key) return part.value;
- }
- return null;
-}
-
-function lsColorForName(name) {
- const wildcardRules = [];
- for (const { key, value } of lsColorParts()) {
- if (!key) continue;
- if (key.startsWith("*")) wildcardRules.push({ key, suffix: key.slice(1), value, extension: key.startsWith("*.") });
- }
- const text = String(name);
- let matched = null;
- for (let i = 0; i < wildcardRules.length; i++) {
- const rule = wildcardRules[i];
- const suffix = rule.suffix;
- if (text.endsWith(suffix)) matched = rule;
- else if (rule.extension && text.toLowerCase().endsWith(suffix.toLowerCase()) && lsExtensionRuleIsCaseInsensitive(wildcardRules, i)) matched = rule;
- }
- if (matched) return matched.value;
- return null;
-}
-
-function lsColorParts() {
- const colors = process.env.LS_COLORS ?? "";
- const parts = [];
- let current = "";
- let escaped = false;
- for (const ch of colors) {
- if (escaped) {
- current += ch;
- escaped = false;
- } else if (ch === "\\") {
- escaped = true;
- } else if (ch === ":") {
- parts.push(current);
- current = "";
- } else {
- current += ch;
- }
- }
- if (escaped) current += "\\";
- parts.push(current);
- return parts.flatMap((part) => {
- const index = part.indexOf("=");
- return index < 0 ? [] : [{ key: part.slice(0, index), value: part.slice(index + 1) }];
- });
-}
-
-function lsExtensionRuleIsCaseInsensitive(rules, index) {
- const rule = rules[index];
- const effective = new Map();
- for (const other of rules) {
- if (other.suffix.toLowerCase() === rule.suffix.toLowerCase()) effective.set(other.suffix, other.value);
- }
- const values = [...effective.values()];
- return values.length === 1 || values.every((value) => value === rule.value);
-}
-
-async function duCmd(args) {
- args = normalizeDuArgs(args);
- const repeatedExcludes = duRepeatedOptionValues(args, "--exclude");
- const repeatedExcludeFiles = duRepeatedOptionValues(args, "--exclude-from");
- const { opts, operands } = parseOptions(args, { short: { 0: false, a: false, A: false, D: false, H: false, L: false, P: false, l: false, s: false, S: false, b: false, h: false, c: false, B: "value", d: "value", k: false, m: false, t: "value", x: false }, long: { null: false, all: false, dereference: false, "dereference-args": false, "no-dereference": false, "count-links": false, summarize: false, "separate-dirs": false, bytes: false, "human-readable": false, "apparent-size": false, inodes: false, total: false, "block-size": "value", si: false, time: "optional-value", "time-style": "value", "max-depth": "value", exclude: "value", "exclude-from": "value", "files0-from": "value", "one-file-system": false, threshold: "value" } });
- applyBlockSizeSpecialMode(opts, duBlockSizeValue(opts));
- const maxDepth = parseDuMaxDepth(opts.d ?? opts["max-depth"], opts.s || opts.summarize);
- const timeField = opts.time === undefined ? null : validateDuTimeField(opts.time);
- let targets = operands.length ? operands : ["."];
- let files0From = null;
- let files0Reader = null;
- let files0Fd = 0;
- let closeFiles0Fd = false;
- if (opts["files0-from"] !== undefined) {
- if (operands.length) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}\nfile operands cannot be combined with --files0-from`, true);
- files0From = opts["files0-from"];
- if (wcFiles0SourceIsNonRegular(files0From)) {
- try {
- if (files0From !== "-") {
- files0Fd = openSync(files0From, "r");
- closeFiles0Fd = true;
- }
- files0Reader = createFdRecordReader(files0Fd, 0);
- targets = [];
- } catch (error) {
- stderr(`du: cannot open ${duQuotedName(files0From)} for reading: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- } else {
- let nameBytes;
- try {
- nameBytes = await readAll(files0From);
- } catch (error) {
- stderr(error?.code === "EISDIR"
- ? `du: ${duDiagnosticName(files0From)}: read error: ${systemErrorMessage(error)}\n`
- : `du: cannot open ${duQuotedName(files0From)} for reading: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- targets = splitFiles0ByteNames(nameBytes);
- }
- }
- const inodeMode = opts.inodes;
- const apparent = opts.b || opts.bytes || opts.A || opts["apparent-size"];
- if (inodeMode && apparent) stderr("du: warning: options --apparent-size and -b are ineffective with --inodes\n");
- const human = opts.h || opts["human-readable"] || opts.si;
- const unit = inodeMode || opts.b || opts.bytes ? 1 : duBlockSize(opts);
- const separator = opts[0] || opts.null ? "\0" : "\n";
- const thresholdText = opts.t ?? opts.threshold;
- let threshold = null;
- if (thresholdText != null) {
- threshold = duParseThreshold(thresholdText, inodeMode);
- if (!Number.isFinite(threshold)) throw new UsageError(`invalid --threshold argument '${thresholdText}'`);
- }
- const excludes = await duExcludePatterns(opts, repeatedExcludes, repeatedExcludeFiles);
- const { dereference, dereferenceArgs } = duDereferenceMode(args, opts);
- let totalBytes = 0;
- let failed = false;
- const emittedRootDirectories = new Set();
- const seen = new Set();
- const dirSeen = new Set();
- let reportedSyntheticTime = false;
- for (let index = 0; files0Reader || index < targets.length; index++) {
- let target;
- if (files0Reader) {
- try {
- target = files0Reader.next();
- } catch (error) {
- stderr(`du: ${duDiagnosticName(files0From)}: read error: ${systemErrorMessage(error)}\n`);
- failed = true;
- break;
- }
- if (target == null) break;
- } else {
- target = targets[index];
- }
- if (files0From != null && wcFileNameIsEmpty(target)) {
- stderr(`du: ${duDiagnosticName(files0From)}:${index + 1}: invalid zero-length file name\n`);
- failed = true;
- continue;
- }
- if (files0From === "-" && wcFileNameIsDash(target)) {
- stderr("du: when reading file names from standard input, no file name of '-' allowed\n");
- failed = true;
- continue;
- }
- let entries;
- try {
- const errors = [];
- const rootLinkStat = await lstat(target);
- const collectOptions = { apparent, inodes: inodeMode, all: opts.a || opts.all, dereference, dereferenceArgs, countLinks: opts.l || opts["count-links"], seen, dirSeen, separateDirs: opts.S || opts["separate-dirs"], maxDepth, excludes, oneFileSystem: opts.x || opts["one-file-system"], rootDev: rootLinkStat.dev, includeNanoseconds: timeField != null, errors };
- if (duCanUseSyncSummary(collectOptions)) {
- const root = collectDuSummarySync(target, collectOptions);
- entries = root ? [{ path: target, bytes: root.bytes, stat: root.stat }] : [];
- } else {
- entries = await collectDuEntries(target, collectOptions);
- }
- for (const diagnostic of errors) stderr(`${diagnostic}\n`);
- if (errors.length) failed = true;
- } catch (error) {
- stderr(error?.duFtsReadPath != null
- ? `du: fts_read failed: ${pathDisplayName(error.duFtsReadPath)}: ${systemErrorMessage(error)}\n`
- : `du: cannot access ${duQuotedName(target)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- continue;
- }
- const root = entries.at(-1);
- if (!root) continue;
- if (root.stat.isDirectory()) {
- const id = `${root.stat.dev}:${root.stat.ino}`;
- if (emittedRootDirectories.has(id)) entries = [];
- else emittedRootDirectories.add(id);
- }
- const bytes = root.bytes;
- totalBytes += bytes;
- for (const entry of entries) {
- if (threshold != null && !duPassesThreshold(entry.bytes, threshold)) continue;
- const value = human ? duHumanSize(entry.bytes, opts.si ? 1000 : 1024) : String(Math.ceil(entry.bytes / unit));
- let time = "";
- if (timeField) {
- const syntheticTime = process.env.BNU_DU_TEST_TIME_SECONDS;
- if (syntheticTime != null) {
- time = `\t${syntheticTime}`;
- if (!reportedSyntheticTime) {
- stderr(`du: time '${syntheticTime}' is out of range\n`);
- reportedSyntheticTime = true;
- }
- } else {
- time = `\t${duTimeText(entry.stat[timeField], opts)}`;
- }
- }
- stdout(`${value}${time}\t${pathDisplayName(entry.path)}${separator}`);
- }
- }
- if (opts.c || opts.total) {
- const value = human ? duHumanSize(totalBytes, opts.si ? 1000 : 1024) : String(Math.ceil(totalBytes / unit));
- stdout(`${value}\ttotal${separator}`);
- }
- if (closeFiles0Fd) closeSync(files0Fd);
- return failed ? 1 : 0;
-}
-
-function duQuotedName(name) {
- return shellEscapeLsName(pathDisplayName(name), true);
-}
-
-function duDiagnosticName(name) {
- return shellEscapeLsName(pathDisplayName(name));
-}
-
-function normalizeDuArgs(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--") {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(arg.startsWith("--") ? normalizeLongOptionByPrefix(arg, DU_LONG_OPTIONS) : arg);
- }
- return out;
-}
-
-function parseDuMaxDepth(value, summarize) {
- if (value == null) return summarize ? 0 : Infinity;
- const text = String(value);
- if (!/^[+-]?\d+$/.test(text)) throw new UsageError(`invalid maximum depth ${localeQuotedEscapedDiagnostic(text)}`, true);
- const parsed = BigInt(text.replace(/^\+/, ""));
- if (summarize) {
- const display = text.replace(/^\+/, "");
- if (parsed !== 0n) throw new UsageError(`warning: summarizing conflicts with --max-depth=${display}`, true);
- if (parsed === 0n) stderr("du: warning: summarizing is the same as using --max-depth=0\n");
- return 0;
- }
- if (parsed < 0n) return 0;
- return parsed > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(parsed);
-}
-
-function duDereferenceMode(args, opts) {
- let mode = opts.L || opts.dereference ? "all" : opts.D || opts.H || opts["dereference-args"] ? "args" : "none";
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") break;
- if (arg === "-" || !arg.startsWith("-")) continue;
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (name === "dereference") mode = "all";
- else if (name === "dereference-args") mode = "args";
- else if (name === "no-dereference") mode = "none";
- if (inlineValue == null && ["block-size", "time-style", "max-depth", "exclude", "exclude-from", "files0-from", "threshold"].includes(name)) i++;
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "L") mode = "all";
- else if (ch === "D" || ch === "H") mode = "args";
- else if (ch === "P") mode = "none";
- if (["B", "d"].includes(ch)) break;
- }
- }
- return { dereference: mode === "all", dereferenceArgs: mode === "args" };
-}
-
-function duPassesThreshold(value, threshold) {
- return threshold < 0 ? value <= Math.abs(threshold) : value >= threshold;
-}
-
-function duParseThreshold(value, inodeMode = false, option = "--threshold") {
- const text = String(value);
- const sign = text.startsWith("-") ? -1 : 1;
- const unsigned = text.replace(/^[+-]/, "");
- if (!/^\d/.test(unsigned)) throw new UsageError(`invalid ${option} argument '${value}'`);
- const match = unsigned.match(/^(\d+)([A-Za-z]*)$/);
- if (!match) throw new UsageError(`invalid suffix in ${option} argument '${value}'`);
- const suffixScales = {
- "": 1n,
- K: 1024n, k: 1024n, KiB: 1024n, kiB: 1024n,
- M: 1024n ** 2n, m: 1024n ** 2n, MiB: 1024n ** 2n, miB: 1024n ** 2n,
- G: 1024n ** 3n, g: 1024n ** 3n, GiB: 1024n ** 3n, giB: 1024n ** 3n,
- T: 1024n ** 4n, t: 1024n ** 4n, TiB: 1024n ** 4n, tiB: 1024n ** 4n,
- P: 1024n ** 5n, PiB: 1024n ** 5n,
- E: 1024n ** 6n, EiB: 1024n ** 6n,
- Z: 1024n ** 7n, ZiB: 1024n ** 7n,
- Y: 1024n ** 8n, YiB: 1024n ** 8n,
- R: 1024n ** 9n, RiB: 1024n ** 9n,
- Q: 1024n ** 10n, QiB: 1024n ** 10n,
- KB: 1000n, kB: 1000n, MB: 1000n ** 2n, mB: 1000n ** 2n,
- GB: 1000n ** 3n, gB: 1000n ** 3n, TB: 1000n ** 4n, tB: 1000n ** 4n,
- PB: 1000n ** 5n, EB: 1000n ** 6n, ZB: 1000n ** 7n, YB: 1000n ** 8n,
- RB: 1000n ** 9n, QB: 1000n ** 10n,
- };
- const scale = suffixScales[match[2]];
- if (!scale) {
- throw new UsageError(`invalid suffix in ${option} argument '${value}'`);
- }
- const amount = BigInt(match[1]) * scale;
- if (sign < 0 && amount === 0n) throw new UsageError(`invalid --threshold argument '${value}'`);
- const max = sign < 0 ? 9223372036854775808n : 9223372036854775807n;
- if (amount > max) throw new UsageError(`${option} argument '${value}' too large`);
- const clamped = amount > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(amount);
- return sign * clamped;
-}
-
-async function collectDuEntries(path, options, depth = 0) {
- const node = await collectDuNode(path, options, depth);
- return node?.entries ?? [];
-}
-
-function duCanUseSyncSummary(options) {
- return options.maxDepth === 0 && !options.all && !options.dereference && !options.dereferenceArgs
- && !options.countLinks && !options.separateDirs && !options.oneFileSystem
- && !options.includeNanoseconds && options.excludes.length === 0;
-}
-
-function collectDuSummarySync(path, options, depth = 0, displayPath = path) {
- const s = lstatSync(path);
- const identity = `${s.dev}:${s.ino}`;
- if (s.isDirectory()) {
- if (options.dirSeen.has(identity)) return { bytes: 0, stat: s };
- options.dirSeen.add(identity);
- } else if (s.nlink > 1 || depth === 0) {
- if (options.seen.has(identity)) return { bytes: 0, stat: s };
- options.seen.add(identity);
- }
- let bytes = options.inodes ? 1 : options.apparent && s.isDirectory() ? 0 : options.apparent ? s.size : blocksFor(s) * 512;
- if (!s.isDirectory() || s.isSymbolicLink()) return { bytes, stat: s };
- // Walk relative to an open directory fd. Concatenating descendants onto
- // the original operand eventually exceeds PATH_MAX even though every
- // component is valid; /proc/self/fd gives Node's path APIs openat-like
- // behavior while preserving byte names and without changing an unreadable
- // caller's cwd.
- let directoryFd;
- let directory = null;
- try {
- try {
- directoryFd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_DIRECTORY);
- directory = opendirSync(`/proc/self/fd/${directoryFd}`, { encoding: "buffer" });
- } catch (error) {
- options.errors?.push(`du: cannot read directory '${pathDisplayName(displayPath)}': ${systemErrorMessage(error)}`);
- return { bytes, stat: s };
- }
- while (true) {
- const rawEntry = directory.readSync();
- if (!rawEntry) break;
- const entry = rawEntry.name ?? rawEntry;
- try {
- const child = collectDuSummarySync(
- duChildPath(`/proc/self/fd/${directoryFd}`, entry),
- options,
- depth + 1,
- duChildPath(displayPath, entry),
- );
- if (child) bytes += child.bytes;
- } catch (error) {
- options.errors?.push(`du: cannot read directory '${pathDisplayName(displayPath)}': ${systemErrorMessage(error)}`);
- }
- }
- } finally {
- directory?.closeSync();
- if (directoryFd != null) closeSync(directoryFd);
- }
- return { bytes, stat: s };
-}
-
-async function collectDuNode(path, options, depth = 0) {
- if (duIsExcluded(path, options.excludes)) return null;
- const linkStat = await lstat(path);
- const dereference = options.dereference || (options.dereferenceArgs && depth === 0);
- const s = dereference && linkStat.isSymbolicLink() ? await stat(await realpath(path)) : linkStat;
- if (options.includeNanoseconds) statAttachNanoseconds(s, path, dereference);
- const identity = `${s.dev}:${s.ino}`;
- // A single-link regular file cannot be encountered through another hard
- // link, so retaining its identity only turns a wide directory into an
- // O(number-of-files) heap. Directories have their own cycle set below.
- const trackHardLink = !s.isDirectory() && (s.nlink > 1 || depth === 0);
- const alreadySeen = !options.countLinks && trackHardLink && options.seen.has(identity);
- if (trackHardLink) options.seen.add(identity);
- const ownBytes = options.inodes ? 1 : options.apparent && s.isDirectory() ? 0 : options.apparent ? s.size : blocksFor(s) * 512;
- if (s.isDirectory()) {
- if (options.dirSeen.has(identity)) return { bytes: 0, entries: [], stat: s };
- options.dirSeen.add(identity);
- }
- if (alreadySeen) return { bytes: 0, entries: [], stat: s };
- if (!s.isDirectory() || s.isSymbolicLink()) {
- const bytes = ownBytes;
- const emit = (depth === 0 || options.all) && depth <= options.maxDepth;
- return { bytes, entries: emit ? [{ path, bytes, stat: s }] : [], stat: s };
- }
- let total = ownBytes;
- const entries = [];
- if (options.oneFileSystem && s.dev !== options.rootDev) {
- if (depth <= options.maxDepth) entries.push({ path, bytes: total, stat: s });
- return { bytes: total, entries, stat: s };
- }
- let names;
- try {
- names = options.maxDepth === 0 && !options.all
- ? await openDirectoryPathEntries(path)
- : await readdir(path, isBytePath(path) ? { encoding: "buffer" } : undefined);
- } catch (error) {
- options.errors?.push(`du: cannot read directory '${pathDisplayName(path)}': ${systemErrorMessage(error)}`);
- if (depth <= options.maxDepth) entries.push({ path, bytes: total, stat: s });
- return { bytes: total, entries, stat: s };
- }
- // readdir opens the directory before returning its names. If an ancestor
- // is renamed concurrently, those names are stale relative to this pathname.
- // GNU fts reports one traversal failure for the opened directory rather than
- // one ENOENT for every descendant from the snapshot.
- try {
- await lstat(path);
- } catch (error) {
- if (error?.code === "ENOENT") throw duFtsReadError(await duFtsFailurePath(path), error);
- throw error;
- }
- for await (const entry of names) {
- const childPath = duChildPath(path, entry);
- let child;
- try {
- child = await collectDuNode(childPath, options, depth + 1);
- } catch (error) {
- if (error?.duFtsReadPath != null) throw error;
- if (error?.code === "ENAMETOOLONG") continue;
- if (error?.code === "ENOENT" && !(await lstat(path).catch(() => null))) throw duFtsReadError(await duFtsFailurePath(path), error);
- options.errors?.push(`du: cannot read directory '${pathDisplayName(path)}': ${systemErrorMessage(error)}`);
- continue;
- }
- if (!child) continue;
- const skippedOtherFsDirectory = options.oneFileSystem && child.stat.isDirectory() && child.stat.dev !== options.rootDev;
- if (!skippedOtherFsDirectory) entries.push(...child.entries);
- if (!skippedOtherFsDirectory && (!options.separateDirs || !child.stat.isDirectory() || child.stat.isSymbolicLink())) total += child.bytes;
- }
- if (depth <= options.maxDepth) entries.push({ path, bytes: total, stat: s });
- return { bytes: total, entries, stat: s };
-}
-
-function duFtsReadError(path, cause) {
- const error = new Error(cause?.message ?? "No such file or directory");
- error.code = cause?.code ?? "ENOENT";
- error.duFtsReadPath = path;
- return error;
-}
-
-async function duFtsFailurePath(path) {
- let current = String(path);
- while (true) {
- const parent = pathDirname(current);
- if (parent === current || await lstat(parent).catch(() => null)) return current;
- current = parent;
- }
-}
-
-function duChildPath(parent, entry) {
- if (parent === ".") return `./${entry}`;
- if (typeof parent === "string" && parent.startsWith("./")) return `./${join(parent.slice(2), String(entry))}`;
- if (isBytePath(parent) || isBytePath(entry)) return bufferPathJoin(isBytePath(parent) ? parent : Buffer.from(String(parent)), isBytePath(entry) ? Buffer.from(entry) : Buffer.from(String(entry)));
- return join(parent, entry);
-}
-
-function duRepeatedOptionValues(args, name) {
- const values = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === name) values.push(args[++i]);
- else if (arg.startsWith(`${name}=`)) values.push(arg.slice(name.length + 1));
- }
- return values.filter((value) => value != null);
-}
-
-async function duExcludePatterns(opts, excludeValues = [], excludeFiles = []) {
- const patterns = [...excludeValues];
- if (opts.exclude && !patterns.includes(opts.exclude)) patterns.push(opts.exclude);
- const files = [...excludeFiles];
- if (opts["exclude-from"] && !files.includes(opts["exclude-from"])) files.push(opts["exclude-from"]);
- for (const file of files) {
- let text;
- try {
- text = decodeSurrogateEscapedBytes(await readAll(file));
- } catch (error) {
- throw new UsageError(`${file}: ${systemErrorMessage(error)}`, true);
- }
- patterns.push(...text.split(/\r?\n/).filter(Boolean));
- }
- return patterns;
-}
-
-function duIsExcluded(path, patterns) {
- const normalized = pathDisplayName(path).replace(/^\.\//, "");
- const base = isBytePath(path) ? pathDisplayName(bufferPathBasename(path)) : pathBasename(normalized);
- return patterns.some((pattern) => normalized === pattern || base === pattern || normalized.startsWith(`${pattern}/`) || globMatch(pattern, normalized) || globMatch(pattern, base));
-}
-
-function duTimeText(date, opts) {
- const style = opts["time-style"] ?? "long-iso";
- if (style === "iso" || style === "posix-iso") return strftime(date, "%F");
- return lsTimeText(date, { "time-style": style });
-}
-
-function validateDuTimeField(value) {
- if (value === true) return "mtime";
- if (["atime", "access", "use"].includes(value)) return "atime";
- if (["ctime", "status"].includes(value)) return "ctime";
- const kind = value === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic("--time")}\nValid arguments are:\n - ${["atime", "access", "use"].map(localeQuotedDiagnostic).join(", ")}\n - ${["ctime", "status"].map(localeQuotedDiagnostic).join(", ")}`, true);
-}
-
-function duBlockSize(opts) {
- if (opts.k) return 1024;
- if (opts.m) return 1024 ** 2;
- if (opts.B !== undefined || opts["block-size"] !== undefined) {
- const shortOption = opts.B !== undefined;
- const value = shortOption ? opts.B : opts["block-size"];
- try {
- return parseGNUBlockSize(value);
- } catch {
- throw new UsageError(gnuBlockSizeErrorMessage(shortOption ? "-B" : "--block-size", value));
- }
- }
- return parseGNUBlockSizeEnv(duBlockSizeEnvValue(), defaultGNUBlockSize());
-}
-
-function duHumanSize(value, base = 1024) {
- const units = base === 1000 ? ["B", "k", "M", "G", "T"] : ["B", "K", "M", "G", "T"];
- return humanSizeWithUnits(value, base, units);
-}
-
-function parseGNUBlockSize(value) {
- value = String(value).replace(/^'/, "");
- if (value === "human-readable" || value === "si") return 1;
- return /^\D+$/.test(String(value)) ? parseGNUSize(`1${value}`) : parseGNUSize(value);
-}
-
-function gnuBlockSizeErrorMessage(option, value) {
- const text = String(value).replace(/^'/, "");
- if (/^\+?\d+[A-Za-z]+$/.test(text)) return `invalid suffix in ${option} argument '${value}'`;
- return `invalid ${option} argument '${value}'`;
-}
-
-function parseGNUBlockSizeEnv(value, defaultSize) {
- return parseGNUBlockSizeEnvInfo(value, defaultSize).size;
-}
-
-function parseGNUBlockSizeEnvInfo(value, defaultSize) {
- if (value == null || value === "") return { size: defaultSize, fallback: "default" };
- try {
- return { size: parseGNUBlockSize(value), fallback: null };
- } catch {
- const match = String(value).replace(/^'/, "").match(/^\+?(\d+)/);
- if (match) return { size: Number(match[1]), fallback: "numeric" };
- return { size: defaultSize, fallback: "default" };
- }
-}
-
-function blockSizeSpecialMode(value) {
- const text = value == null ? "" : String(value).replace(/^'/, "");
- if (text === "human-readable") return "human";
- if (text === "si") return "si";
- return null;
-}
-
-function applyBlockSizeSpecialMode(opts, value) {
- const mode = blockSizeSpecialMode(value);
- if (mode === "human") opts["human-readable"] = true;
- if (mode === "si") opts.si = true;
-}
-
-function applyLsBlockSizeSpecialMode(opts) {
- applyBlockSizeSpecialMode(opts, lsSizeBlockSizeValue(opts));
- const mode = blockSizeSpecialMode(lsBlockSizeValue(opts));
- if (mode === "human") opts.blockHumanReadable = true;
- if (mode === "si") opts.blockSi = true;
-}
-
-function duBlockSizeValue(opts) {
- return opts.B ?? opts["block-size"] ?? duBlockSizeEnvValue();
-}
-
-function duBlockSizeEnvValue() {
- return process.env.DU_BLOCK_SIZE ?? process.env.BLOCK_SIZE ?? process.env.BLOCKSIZE;
-}
-
-function dfBlockSizeValue(opts) {
- return opts.B ?? opts["block-size"] ?? dfBlockSizeEnvValue();
-}
-
-function dfBlockSizeEnvValue() {
- return process.env.DF_BLOCK_SIZE ?? process.env.BLOCK_SIZE ?? process.env.BLOCKSIZE;
-}
-
-function humanSize(bytes, base = 1024) {
- const units = ["B", "K", "M", "G", "T"];
- return humanSizeWithUnits(bytes, base, units);
-}
-
-function humanSizeWithUnits(bytes, base, units) {
- let value = bytes;
- let unit = 0;
- while (value >= base && unit < units.length - 1) {
- value /= base;
- unit++;
- }
- if (unit === 0) return `${value}${units[unit]}`;
- const digits = value >= 10 ? 0 : 1;
- const factor = 10 ** digits;
- const rounded = Math.ceil(value * factor) / factor;
- return `${rounded.toFixed(digits)}${units[unit]}`;
-}
-
-async function statCmd(args) {
- args = normalizeStatLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { c: "value", f: false, L: false, t: false }, long: { cached: "value", format: "value", printf: "value", "file-system": false, dereference: false, terse: false, help: false, version: false } });
- validateStatCached(opts.cached);
- if (opts.printf === "." && operands.length === 0) {
- opts.printf = "\\";
- operands.push(".");
- }
- if (!operands.length) throw new UsageError("missing operand", true);
- const fileSystem = opts.f || opts["file-system"];
- const printfMode = Object.hasOwn(opts, "printf");
- const format = opts.c ?? opts.format ?? opts.printf ?? (opts.t || opts.terse ? (fileSystem ? "%n %i %l %t %s %S %b %f %a %c %d" : "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %W %o") : null);
- let status = 0;
- for (const file of operands) {
- if (fileSystem && file === "-") {
- stderr("stat: using '-' to denote standard input does not work in file system mode\n");
- status = 1;
- continue;
- }
- let s;
- try {
- s = file === "-" ? fstatSync(0) : opts.L || opts.dereference ? await stat(file) : await lstat(file);
- if (!fileSystem && (format == null || statFormatNeedsNanoseconds(format)) && file !== "-") statAttachNanoseconds(s, file, opts.L || opts.dereference);
- } catch (error) {
- const operation = fileSystem ? "cannot read file system information for" : "cannot statx";
- stderr(`stat: ${operation} ${statDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- status = 1;
- continue;
- }
- if (format != null) {
- const rendered = fileSystem ? await renderStatFsFormat(format, file, printfMode) : renderStatFormat(format, file, s, printfMode);
- if (rendered.stderr) stderr(rendered.stderr);
- status = Math.max(status, rendered.status);
- const text = rendered.text + (printfMode ? "" : "\n");
- if (printfMode) stdout(Buffer.from(text, "latin1"));
- else stdout(text);
- } else {
- stdout(`${fileSystem ? await renderStatFsDefault(file) : await renderStatDefault(file, s)}\n`);
- }
- }
- return status;
-}
-
-function normalizeStatLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeStatLongOption(arg));
- }
- return out;
-}
-
-function normalizeStatLongOption(arg) {
- if (arg === "--form") return "--format";
- if (arg.startsWith("--form=")) return `--format=${arg.slice(7)}`;
- if (arg === "--p") return "--printf";
- if (arg.startsWith("--p=")) return `--printf=${arg.slice(4)}`;
- return normalizeLongOptionByPrefix(arg, STAT_LONG_OPTIONS);
-}
-
-async function renderStatDefault(file, s) {
- const user = await userNameForUid(s.uid);
- const group = await groupName(s.gid);
- const mode = (s.mode & 0o7777).toString(8).padStart(4, "0");
- return [
- ` File: ${statDefaultName(file, s)}`,
- ` Size: ${String(s.size).padEnd(10)}\tBlocks: ${String(blocksFor(s)).padEnd(10)} IO Block: ${String(s.blksize ?? 4096).padEnd(6)} ${fileTypeName(s)}`,
- `Device: ${statDeviceNumberText(s.dev)}\tInode: ${String(s.ino).padEnd(10)} Links: ${s.nlink}`,
- `Access: (${mode}/${modeString(s)}) Uid: (${String(s.uid).padStart(5)}/${String(user).padStart(8)}) Gid: (${String(s.gid).padStart(5)}/${String(group).padStart(8)})`,
- `Access: ${statLocalDateText(s, "atime")}`,
- `Modify: ${statLocalDateText(s, "mtime")}`,
- `Change: ${statLocalDateText(s, "ctime")}`,
- ` Birth: ${s.birthtimeMs ? statLocalDateText(s, "birthtime") : "-"}`,
- ].join("\n");
-}
-
-function statDefaultName(file, s) {
- if (s?.isSymbolicLink?.()) {
- try {
- return `${file} -> ${readlinkSync(file)}`;
- } catch {}
- }
- return String(file);
-}
-
-function statDeviceNumberText(dev) {
- const { major, minor } = statMajorMinor(dev);
- return `${major},${minor}`;
-}
-
-async function renderStatFsDefault(file) {
- const fs = await statfs(file);
- const id = statFsIdText(file, fs);
- const nameLength = String(fs.namelen ?? 255);
- const blockSize = String(fs.bsize ?? 0);
- const fundamentalBlockSize = String(fs.bsize ?? 0);
- const blocks = String(fs.blocks ?? 0);
- const free = String(fs.bfree ?? 0);
- const available = String(fs.bavail ?? 0);
- const files = String(fs.files ?? 0);
- const freeFiles = String(fs.ffree ?? 0);
- return [
- ` File: ${statFsDefaultName(file)}`,
- ` ID: ${id.padEnd(8)} Namelen: ${nameLength.padEnd(7)} Type: ${fsTypeName(fs.type)}`,
- `Block size: ${blockSize.padEnd(10)} Fundamental block size: ${fundamentalBlockSize}`,
- `Blocks: Total: ${blocks.padEnd(9)} Free: ${free.padEnd(9)} Available: ${available}`,
- `Inodes: Total: ${files.padEnd(9)} Free: ${freeFiles}`,
- ].join("\n");
-}
-
-function statFsDefaultName(file) {
- return JSON.stringify(String(file));
-}
-
-function validateStatCached(value) {
- if (value == null) return;
- if (["default", "never", "always"].includes(value)) return;
- const problem = value === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${problem} argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic("--cached")}\nValid arguments are:\n - ${localeQuotedDiagnostic("default")}\n - ${localeQuotedDiagnostic("never")}\n - ${localeQuotedDiagnostic("always")}`, true);
-}
-
-async function renderStatFsFormat(format, file, interpretEscapes = false) {
- let status = 0;
- let stderrText = "";
- if (interpretEscapes) {
- const decoded = decodeStatPrintfEscapes(format);
- format = decoded.text;
- stderrText += decoded.stderr;
- }
- const invalid = invalidStatDirective(format);
- if (invalid) return { text: "", status: 1, stderr: `stat: '${invalid}': invalid directive\n` };
- const fs = await statfs(file);
- const blockSize = fs.bsize ?? 0;
- const values = {
- a: String(fs.bavail ?? 0),
- b: String(fs.blocks ?? 0),
- c: String(fs.files ?? 0),
- d: String(fs.ffree ?? 0),
- f: String(fs.bfree ?? 0),
- i: statFsIdText(file, fs),
- l: String(fs.namelen ?? 255),
- n: file,
- q: "?",
- s: String(blockSize),
- S: String(blockSize),
- t: Number(fs.type ?? 0).toString(16),
- T: fsTypeName(fs.type),
- };
- const out = format.replace(/%(%|([0 +#I-]*)(\d+)?([HL])?([aAbBcCdDfFgGhHiImNnoOqQRrSsTtUuWwXxYyZzl]))/g, (match, spec, flags = "", width, _modifier = "", directive) => {
- if (spec === "%") return "%";
- return pad(values[directive] ?? "?", width, flags);
- });
- return { text: out, status, stderr: stderrText };
-}
-
-function statFsIdText(file, fs) {
- const native = nativeStatFsId(file);
- if (native != null) return native;
- return String(fs.fsid ?? 0);
-}
-
-function nativeStatFsId(path) {
- try {
- const buffer = Buffer.alloc(120);
- if (libc.symbols.statfs(cstrPath(path), buffer) !== 0) return null;
- const first = buffer.readUInt32LE(56);
- const second = buffer.readUInt32LE(60);
- if (first === 0 && second === 0) return "0";
- return `${first.toString(16)}${second.toString(16).padStart(8, "0")}`;
- } catch {
- return null;
- }
-}
-
-function renderStatFormat(format, file, s, interpretEscapes = false) {
- let status = 0;
- let stderrText = "";
- if (interpretEscapes) {
- const decoded = decodeStatPrintfEscapes(format);
- format = decoded.text;
- stderrText += decoded.stderr;
- }
- const invalid = invalidStatDirective(format);
- if (invalid) {
- return { text: "", status: 1, stderr: `stat: '${invalid}': invalid directive\n` };
- }
- const type = fileTypeName(s);
- const quote = formatUsesStatDirective(format, "N") ? statQuotingStyle() : { style: "shell", stderr: "" };
- stderrText += quote.stderr;
- const securityContext = formatUsesStatDirective(format, "C") ? selinuxSecurityContext(file) : null;
- if (formatUsesStatDirective(format, "C")) {
- if (securityContext == null) {
- status = 1;
- stderrText += `stat: failed to get security context of ${statDiagnosticName(file)}: Operation not supported\n`;
- }
- }
- let out = format.replace(/%(%|([0 +#I-]*)(\d+)?(?:\.(\d*))?([HL])?([aAbBcCdDfFgGhHiImNnoOqQRrSsTtUuWwXxYyZz])|([HL]))/g, (match, spec, flags = "", width, precision, modifier = "", directive, bareModifier) => {
- if (spec === "%") return "%";
- if (bareModifier) return "?";
- if (directive === "H") return statPad("?", width, flags);
- if ((modifier === "H" || modifier === "L") && directive !== "d" && directive !== "r") return `?${directive}`;
- if (["X", "Y", "Z", "W"].includes(directive) && precision !== undefined) {
- return pad(statSecondsWithPrecision(s, statTimeFieldForDirective(directive), precision), width, flags);
- }
- const values = {
- a: (s.mode & 0o7777).toString(8),
- A: modeString(s),
- b: String(blocksFor(s)),
- B: "512",
- C: securityContext ?? "?",
- d: statDeviceDirectiveValue("d", s, modifier),
- D: s.dev.toString(16),
- f: (s.mode & 0xffff).toString(16),
- F: type,
- g: String(s.gid),
- G: groupNameSync(s.gid),
- h: String(s.nlink),
- i: String(s.ino),
- m: "/",
- n: file,
- N: statQuotedName(file, quote.style, s),
- o: String(s.blksize ?? 4096),
- q: "?",
- Q: "?",
- r: statDeviceDirectiveValue("r", s, modifier),
- R: statDeviceDirectiveValue("R", s, modifier),
- s: String(s.size),
- t: statDeviceDirectiveValue("t", s, modifier),
- T: statDeviceDirectiveValue("T", s, modifier),
- u: String(s.uid),
- U: userNameForUidSync(s.uid) ?? String(s.uid),
- w: s.birthtimeMs ? statLocalDateText(s, "birthtime") : "-",
- W: s.birthtimeMs ? statSeconds(s, "birthtime") : "0",
- x: statLocalDateText(s, "atime"),
- X: statSeconds(s, "atime"),
- y: statLocalDateText(s, "mtime"),
- Y: statSeconds(s, "mtime"),
- z: statLocalDateText(s, "ctime"),
- Z: statSeconds(s, "ctime"),
- };
- const value = statFormatValue(directive, values[directive], flags);
- return value == null ? match : statPad(value, width, flags);
- });
- return { text: out, status, stderr: stderrText };
-}
-
-function statFormatNeedsNanoseconds(format) {
- return /%[0 +#I-]*\d*(?:\.\d*)?[HL]?[wxyzWXYZ]/.test(format);
-}
-
-function statAttachNanoseconds(statInfo, path, dereference) {
- try {
- const precise = nativeStatNanoseconds(path, dereference) ?? (dereference ? statSync(path, { bigint: true }) : lstatSync(path, { bigint: true }));
- attachStatNanoseconds(statInfo, precise);
- } catch {}
- return statInfo;
-}
-
-function nativeStatNanoseconds(path, dereference) {
- const buffer = Buffer.alloc(256);
- const flags = dereference ? 0 : AT_SYMLINK_NOFOLLOW;
- if (libc.symbols.statx(AT_FDCWD, cstrPath(path), flags, STATX_ALL, buffer) !== 0) return null;
- const mask = buffer.readUInt32LE(0);
- const fields = [
- ["atime", 0x0020, 64],
- ["birthtime", 0x0800, 80],
- ["ctime", 0x0080, 96],
- ["mtime", 0x0040, 112],
- ];
- const result = {};
- for (const [field, bit, offset] of fields) {
- if ((mask & bit) === 0) continue;
- const seconds = buffer.readBigInt64LE(offset);
- const nanoseconds = BigInt(buffer.readUInt32LE(offset + 8));
- result[`${field}Ns`] = seconds * 1_000_000_000n + nanoseconds;
- }
- return result;
-}
-
-function attachStatNanoseconds(statInfo, precise) {
- for (const field of ["atime", "mtime", "ctime", "birthtime"]) {
- const value = precise[`${field}Ns`];
- if (value == null) continue;
- statInfo[`${field}Ns`] = value;
- statInfo[field] = dateFromNanoseconds(value);
- }
- return statInfo;
-}
-
-function dateFromNanoseconds(value) {
- const total = BigInt(value);
- const milliseconds = floorDivBigInt(total, 1_000_000n);
- const nanoseconds = Number(((total % 1_000_000_000n) + 1_000_000_000n) % 1_000_000_000n);
- return attachDateNanoseconds(new Date(Number(milliseconds)), nanoseconds);
-}
-
-function statFormatValue(directive, value, flags = "") {
- if (value == null) return null;
- if (!flags.includes("#")) return value;
- if ((directive === "f" || directive === "D") && !/^0+$/.test(value)) return `0x${value}`;
- if (directive === "a" && !value.startsWith("0")) return `0${value}`;
- return value;
-}
-
-function statDeviceDirectiveValue(directive, statInfo, modifier = "") {
- const raw = directive === "d" ? statInfo.dev : (statInfo.rdev ?? 0);
- const dev = statMajorMinor(raw);
- const major = modifier === "L" ? dev.minor : dev.major;
- if (directive === "d") {
- if (modifier === "H" || modifier === "L") return String(major);
- return String(statInfo.dev);
- }
- if (directive === "r") {
- if (modifier === "H" || modifier === "L") return String(major);
- return String(statInfo.rdev ?? 0);
- }
- if (directive === "R") {
- if (modifier === "H" || modifier === "L") return major.toString(16);
- return Number(statInfo.rdev ?? 0).toString(16);
- }
- if (directive === "t") return dev.major.toString(16);
- if (directive === "T") return dev.minor.toString(16);
- return null;
-}
-
-function statMajorMinor(dev) {
- const value = BigInt(dev);
- const major = ((value >> 8n) & 0xfffn) | ((value >> 32n) & ~0xfffn);
- const minor = (value & 0xffn) | ((value >> 12n) & ~0xffn);
- return { major: Number(major), minor: Number(minor) };
-}
-
-function statPad(value, width, flags = "") {
- const n = Number(width);
- if (!Number.isInteger(n) || value.length >= n) return value;
- if (flags.includes("0") && !flags.includes("-") && value.startsWith("0x")) {
- return `0x${value.slice(2).padStart(n - 2, "0")}`;
- }
- return pad(value, width, flags);
-}
-
-function statLocalDateText(statInfo, field) {
- const date = statInfo[field];
- const padNumber = (value, width = 2) => String(Math.trunc(Math.abs(value))).padStart(width, "0");
- const offsetMinutes = -date.getTimezoneOffset();
- const offsetSign = offsetMinutes >= 0 ? "+" : "-";
- const offsetAbs = Math.abs(offsetMinutes);
- const offset = `${offsetSign}${padNumber(Math.trunc(offsetAbs / 60))}${padNumber(offsetAbs % 60)}`;
- const nanos = padNumber(statNanosecondFraction(statInfo, field), 9);
- return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())} ${padNumber(date.getHours())}:${padNumber(date.getMinutes())}:${padNumber(date.getSeconds())}.${nanos} ${offset}`;
-}
-
-function statSeconds(statInfo, field) {
- const value = statInfo[`${field}Ns`];
- if (value != null) return String(floorDivBigInt(BigInt(value), 1_000_000_000n));
- return String(Math.floor(statInfo[field].getTime() / 1000));
-}
-
-function statSecondsWithPrecision(statInfo, field, precision) {
- const digits = precision === "" ? 9 : Math.min(10, Number(precision));
- const value = statInfo[`${field}Ns`];
- if (value != null) return formatSignedNanoseconds(value, digits);
- const total = BigInt(statInfo[field].getTime()) * 1_000_000n;
- return formatSignedNanoseconds(total, digits);
-}
-
-function formatSignedNanoseconds(value, digits) {
- let total = BigInt(value);
- const sign = total < 0n ? "-" : "";
- if (total < 0n) total = -total;
- const seconds = total / 1_000_000_000n;
- const nanos = String(total % 1_000_000_000n).padStart(9, "0");
- return `${sign}${seconds}.${nanos.slice(0, digits).padEnd(digits, "0")}`;
-}
-
-function statNanosecondFraction(statInfo, field) {
- const value = statInfo[`${field}Ns`];
- if (value != null) return Number(((BigInt(value) % 1_000_000_000n) + 1_000_000_000n) % 1_000_000_000n);
- return statInfo[field].getMilliseconds() * 1_000_000;
-}
-
-function statTimeFieldForDirective(directive) {
- return ({ X: "atime", Y: "mtime", Z: "ctime", W: "birthtime" })[directive];
-}
-
-function fsTypeName(type) {
- const names = new Map([
- [0x58465342, "xfs"],
- [0xef53, "ext2/ext3"],
- [0x9123683e, "btrfs"],
- [0x01021994, "tmpfs"],
- [0x6969, "nfs"],
- [0x794c7630, "overlayfs"],
- [0x9fa0, "proc"],
- [0x62656572, "sysfs"],
- ]);
- return names.get(Number(type)) ?? "unknown";
-}
-
-function statQuotingStyle() {
- const value = process.env.QUOTING_STYLE;
- if (value == null || value === "shell-escape") return { style: "shell", stderr: "" };
- if (value === "locale") return { style: "locale", stderr: "" };
- return { style: "shell", stderr: `stat: ignoring invalid value of environment variable QUOTING_STYLE: '${value}'\n` };
-}
-
-function statQuotedName(file, style, s = null) {
- const name = statQuoteSingleName(file, style);
- if (s?.isSymbolicLink?.()) {
- try {
- return `${name} -> ${statQuoteSingleName(readlinkSync(file), style)}`;
- } catch {}
- }
- return name;
-}
-
-function statQuoteSingleName(file, style) {
- if (style === "locale") return `'${String(file).replaceAll("'", "\\'")}'`;
- const text = String(file);
- if (!text.includes("'") && !/[\x00-\x1f\x7f]/.test(text)) return `'${text}'`;
- return shellQuote(text);
-}
-
-function statDiagnosticName(file) {
- return statQuoteSingleName(pathDisplayName(file), "shell");
-}
-
-function formatUsesStatDirective(format, directive) {
- for (let i = 0; i < format.length; i++) {
- if (format[i] !== "%") continue;
- if (format[i + 1] === "%") {
- i++;
- continue;
- }
- const match = format.slice(i).match(/^%([0 +#I-]*)(\d+)?([HL])?([aAbBcCdDfFgGhHiImNnoOqRrSsTtUuWwXxYyZz])/);
- if (match) {
- if (match[4] === directive) return true;
- i += match[0].length - 1;
- }
- }
- return false;
-}
-
-function decodeStatPrintfEscapes(format) {
- let out = "";
- let stderrText = "";
- for (let i = 0; i < format.length; i++) {
- const ch = format[i];
- if (ch !== "\\") {
- out += ch;
- continue;
- }
- if (i + 1 >= format.length) {
- stderrText += "stat: warning: backslash at end of format\n";
- out += "\\";
- continue;
- }
- const next = format[++i];
- const simple = { "0": "\0", a: "\x07", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\" };
- if (/[0-7]/.test(next)) {
- let digits = next;
- while (digits.length < 3 && /[0-7]/.test(format[i + 1] ?? "")) digits += format[++i];
- out += String.fromCharCode(Number.parseInt(digits, 8) & 0xff);
- } else if (next === "x") {
- let digits = "";
- while (digits.length < 2 && /[0-9a-fA-F]/.test(format[i + 1] ?? "")) digits += format[++i];
- if (!digits) {
- stderrText += "stat: warning: unrecognized escape '\\x'\n";
- out += "x";
- } else {
- out += String.fromCharCode(Number.parseInt(digits, 16) & 0xff);
- }
- } else if (Object.hasOwn(simple, next)) {
- out += simple[next];
- } else {
- stderrText += `stat: warning: unrecognized escape '\\${next}'\n`;
- out += next;
- }
- }
- return { text: out, stderr: stderrText };
-}
-
-function invalidStatDirective(format) {
- for (let i = 0; i < format.length; i++) {
- if (format[i] !== "%") continue;
- if (format[i + 1] === "%") {
- i++;
- continue;
- }
- const rest = format.slice(i);
- if (rest === "%") return null;
- const match = rest.match(/^%([0 +#I-]*)(\d+)?(?:\.(\d*))?(([HL])?([aAbBcCdDfFgGhHiImNnoOqQRrSsTtUuWwXxYyZzl])|[HL])/);
- if (match) {
- i += match[0].length - 1;
- continue;
- }
- const invalid = rest.match(/^%[0 +#I-]*\d*.?/s)?.[0] ?? "%";
- return invalid;
- }
- return null;
-}
-
-function fileTypeName(s) {
- if (s.isDirectory()) return "directory";
- if (s.isSymbolicLink()) return "symbolic link";
- if (s.isBlockDevice()) return "block special file";
- if (s.isCharacterDevice()) return "character special file";
- if (s.isFIFO()) return "fifo";
- if (s.isSocket()) return "socket";
- return s.size === 0 ? "regular empty file" : "regular file";
-}
-
-function userNameForUidSync(uid) {
- try {
- const text = readFileSync("/etc/passwd", "utf8");
- for (const line of text.split("\n")) {
- if (!line || line.startsWith("#")) continue;
- const [name, , id] = line.split(":");
- if (Number(id) === Number(uid)) return name;
- }
- } catch {}
- return null;
-}
-
-function groupNameSync(gid) {
- try {
- const text = readFileSync("/etc/group", "utf8");
- for (const line of text.split("\n")) {
- if (!line || line.startsWith("#")) continue;
- const [name, , id] = line.split(":");
- if (Number(id) === Number(gid)) return name;
- }
- } catch {}
- return String(gid);
-}
-
-function splitLines(text, count, sep = "\n") {
- const lines = splitTextRecords(text, sep);
- const chunks = [];
- for (let i = 0; i < lines.length; i += count) chunks.push(enc.encode(lines.slice(i, i + count).join("")));
- return chunks;
-}
-
-function splitByteLines(data, count, sep = "\n") {
- const lines = splitDataByteRecords(data, sep);
- const chunks = [];
- for (let i = 0; i < lines.length; i += count) chunks.push(concatBytes(lines.slice(i, i + count)));
- return chunks;
-}
-
-async function splitCmd(args) {
- validateSplitSeparators(args);
- args = stripSplitIoTestOptions(args);
- args = normalizeSplitLongOptionAbbreviations(args);
- validateSplitModeOptions(args);
- args = normalizeObsoleteSplitLineCount(args);
- const { opts, operands } = parseOptions(args, { short: { l: "value", b: "value", C: "value", a: "value", d: false, x: false, e: false, n: "value", t: "value", u: false }, long: { lines: "value", bytes: "value", "line-bytes": "value", "suffix-length": "value", numeric: "optional-value", "numeric-suffixes": "optional-value", "hex-suffixes": "optional-value", "elide-empty-files": false, number: "value", separator: "value", "additional-suffix": "value", filter: "value", unbuffered: false, verbose: false, help: false, version: false } });
- if (operands.length > 2) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[2])}`, true);
- if (opts.filter && splitNumberSelectsSingle(opts.n ?? opts.number)) throw new UsageError("--filter does not process a chunk extracted to stdout");
- const input = operands[0] ?? "-";
- const prefix = operands[1] ?? "x";
- if (opts.filter && await maybeSplitFilterFixedNumber(input, prefix, opts)) return 0;
- if (opts.filter && input === "-" && (opts.b || opts.bytes)) return splitFilterByteStream(prefix, opts);
- const suffixLength = parseSplitSuffixLength(opts.a ?? opts["suffix-length"] ?? 2);
- const extra = opts["additional-suffix"] ?? "";
- if (extra.includes("/")) throw new UsageError(`invalid suffix ${localeQuotedEscapedDiagnostic(extra)}, contains directory separator`, true);
- const numericSuffixes = opts.d || opts.numeric !== undefined || opts["numeric-suffixes"] !== undefined;
- const hexSuffixes = opts.x || opts["hex-suffixes"] !== undefined;
- const start = splitSuffixStart(opts, { numeric: numericSuffixes, hex: hexSuffixes });
- const data = await readSplitInputForMode(input, opts);
- const chunks = splitChunks(data, opts, splitSeparator(opts.t ?? opts.separator ?? "\n"));
- if (chunks.stdout) {
- stdout(chunks.stdout);
- return 0;
- }
- const elideEmpty = opts.e || opts["elide-empty-files"];
- const writableChunks = elideEmpty ? chunks.filter((chunk) => chunk.byteLength !== 0) : chunks;
- const autoSuffixLength = splitAutoSuffixLength(opts, { numeric: numericSuffixes, hex: hexSuffixes }, start, writableChunks.length);
- validateSplitFixedChunkSuffixLength(opts, suffixLength, { numeric: numericSuffixes, hex: hexSuffixes }, writableChunks.length, autoSuffixLength);
- let written = 0;
- for (let i = 0; i < chunks.length; i++) {
- if (elideEmpty && chunks[i].byteLength === 0) continue;
- if (!autoSuffixLength && splitIndexAfter(start, written) >= splitSuffixCapacity(suffixLength, { numeric: numericSuffixes, hex: hexSuffixes })) throw splitSuffixExhaustionError(written);
- const name = splitOutputName(prefix, splitIndexAfter(start, written++), suffixLength, { numeric: numericSuffixes, hex: hexSuffixes }, extra, autoSuffixLength);
- await ensureSplitOutputDoesNotOverwriteInput(input, name);
- if (opts.verbose) stdout(`creating file '${name}'\n`);
- await writeSplitChunk(name, chunks[i], opts.filter);
- }
- return 0;
-}
-
-async function writeSplitChunk(name, chunk, filter) {
- if (!filter) {
- try {
- await writeFile(splitOutputPath(name), chunk);
- } catch (error) {
- throw new UsageError(`${name}: ${systemErrorMessage(error)}`);
- }
- return;
- }
- const temp = splitFilterTempPath();
- await writeFile(temp, chunk);
- await runSplitFilterTemp(name, temp, filter);
-}
-
-async function runSplitFilterTemp(name, temp, filter) {
- const shell = process.env.SHELL || "/bin/sh";
- const proc = Bun.spawn([shell, "-c", `${String(filter)} < ${shellQuote(temp)}`], {
- env: { ...process.env, FILE: name },
- stdin: "ignore",
- stdout: "inherit",
- stderr: "inherit",
- });
- try {
- const code = await proc.exited;
- if (code !== 0) throw new UsageError(`with FILE=${name}, exit ${code} from command: ${filter}`);
- } finally {
- await rm(temp, { force: true });
- }
-}
-
-async function splitFilterByteStream(prefix, opts) {
- const chunkSize = parseSplitByteCount(opts.b ?? opts.bytes, "bytes");
- const suffixLength = parseSplitSuffixLength(opts.a ?? opts["suffix-length"] ?? 2);
- const numericSuffixes = opts.d || opts.numeric !== undefined || opts["numeric-suffixes"] !== undefined;
- const hexSuffixes = opts.x || opts["hex-suffixes"] !== undefined;
- const extra = opts["additional-suffix"] ?? "";
- if (extra.includes("/")) throw new UsageError(`invalid suffix '${extra}', contains directory separator`);
- const start = splitSuffixStart(opts, { numeric: numericSuffixes, hex: hexSuffixes });
- const autoSuffixLength = splitAutoSuffixLength(opts, { numeric: numericSuffixes, hex: hexSuffixes }, start, Number.POSITIVE_INFINITY);
- const buffer = Buffer.alloc(Math.min(1024 * 1024, chunkSize));
- let index = 0;
- while (true) {
- const temp = splitFilterTempPath();
- const handle = await open(temp, "w");
- let written = 0;
- try {
- while (written < chunkSize) {
- const want = Math.min(buffer.byteLength, chunkSize - written);
- const n = readSync(0, buffer, 0, want);
- if (n === 0) break;
- await handle.write(buffer, 0, n);
- written += n;
- }
- } finally {
- await handle.close();
- }
- if (written === 0) {
- await rm(temp, { force: true });
- break;
- }
- if (!autoSuffixLength && splitIndexAfter(start, index) >= splitSuffixCapacity(suffixLength, { numeric: numericSuffixes, hex: hexSuffixes })) throw splitSuffixExhaustionError(index);
- const name = splitOutputName(prefix, splitIndexAfter(start, index++), suffixLength, { numeric: numericSuffixes, hex: hexSuffixes }, extra, autoSuffixLength);
- await ensureSplitOutputDoesNotOverwriteInput("-", name);
- if (opts.verbose) stdout(`creating file '${name}'\n`);
- await runSplitFilterTemp(name, temp, opts.filter);
- }
- return 0;
-}
-
-function splitFilterTempPath() {
- return `/tmp/bnu-split-filter-${process.pid}-${Date.now()}-${splitFilterTempId++}-${Math.random().toString(36).slice(2)}`;
-}
-
-async function readSplitInput(input) {
- try {
- return await readAll(input);
- } catch (error) {
- if (error?.code === "EISDIR") throw new UsageError(`${input}: ${systemErrorMessage(error)}`);
- throw new UsageError(`cannot open '${input}' for reading: ${systemErrorMessage(error)}`);
- }
-}
-
-async function readSplitInputForMode(input, opts) {
- if (opts.n == null && opts.number == null) return readSplitInput(input);
- let info;
- try {
- info = input === "-" ? fstatSync(0) : await stat(input);
- } catch {
- return readSplitInput(input);
- }
- if (info.isFile()) return readSplitInput(input);
- let spool;
- try {
- spool = await spoolInputToTemporaryFile(input, "bnu-split");
- return await readSplitInput(spool.path);
- } catch (error) {
- if (error instanceof UsageError) throw error;
- throw new UsageError(`${input}: ${systemErrorMessage(error)}`);
- } finally {
- await spool?.cleanup().catch(() => {});
- }
-}
-
-async function ensureSplitOutputDoesNotOverwriteInput(input, output) {
- let inputStat;
- try {
- inputStat = input === "-" ? fstatSync(0) : await stat(input);
- } catch {
- return;
- }
- let outputStat;
- try {
- outputStat = await stat(splitOutputPath(output));
- } catch {
- return;
- }
- if (inputStat.dev === outputStat.dev && inputStat.ino === outputStat.ino) throw new UsageError(`${output}: input file is output file`);
-}
-
-function splitNumberSelectsSingle(spec) {
- if (spec == null) return false;
- const text = String(spec);
- const body = text.replace(/^(?:l|r)\//, "");
- return /^\+?\d+\/.+/.test(body);
-}
-
-async function maybeSplitFilterFixedNumber(input, prefix, opts) {
- const spec = opts.n ?? opts.number;
- if (spec == null || opts.e || opts["elide-empty-files"]) return false;
- const parsed = parseSplitNumberSpec(spec);
- if (parsed.only != null || !["b", "r"].includes(parsed.mode)) return false;
- const suffixLength = parseSplitSuffixLength(opts.a ?? opts["suffix-length"] ?? 2);
- const numericSuffixes = opts.d || opts.numeric !== undefined || opts["numeric-suffixes"] !== undefined;
- const hexSuffixes = opts.x || opts["hex-suffixes"] !== undefined;
- const start = splitSuffixStart(opts, { numeric: numericSuffixes, hex: hexSuffixes });
- const autoSuffixLength = splitAutoSuffixLength(opts, { numeric: numericSuffixes, hex: hexSuffixes }, start, parsed.count);
- if (!autoSuffixLength && splitIndexAfter(start, 0) >= splitSuffixCapacity(suffixLength, { numeric: numericSuffixes, hex: hexSuffixes })) throw splitSuffixExhaustionError(0);
- const extra = opts["additional-suffix"] ?? "";
- if (extra.includes("/")) throw new UsageError(`invalid suffix '${extra}', contains directory separator`);
-
- if (parsed.mode === "b" && input !== "-") {
- const size = (await stat(input)).size;
- let offset = 0;
- for (let i = 0; i < parsed.count; i++) {
- const chunkSize = Math.ceil((size - offset) / (parsed.count - i));
- if (!autoSuffixLength && splitIndexAfter(start, i) >= splitSuffixCapacity(suffixLength, { numeric: numericSuffixes, hex: hexSuffixes })) throw splitSuffixExhaustionError(i);
- const name = splitOutputName(prefix, splitIndexAfter(start, i), suffixLength, { numeric: numericSuffixes, hex: hexSuffixes }, extra, autoSuffixLength);
- await ensureSplitOutputDoesNotOverwriteInput(input, name);
- await runSplitFilterFileRange(name, input, offset, chunkSize, opts.filter);
- offset += chunkSize;
- }
- return true;
- }
-
- if (parsed.mode === "r" && input === "-") {
- await splitFilterRoundRobinStdin(prefix, opts, parsed, suffixLength, { numeric: numericSuffixes, hex: hexSuffixes }, start, extra, autoSuffixLength);
- return true;
- }
-
- if (parsed.mode === "r") {
- const chunks = splitNumber(await readSplitInput(input), `r/${parsed.count}`, splitSeparator(opts.t ?? opts.separator ?? "\n"));
- for (let i = 0; i < chunks.length; i++) {
- if (!autoSuffixLength && splitIndexAfter(start, i) >= splitSuffixCapacity(suffixLength, { numeric: numericSuffixes, hex: hexSuffixes })) throw splitSuffixExhaustionError(i);
- const name = splitOutputName(prefix, splitIndexAfter(start, i), suffixLength, { numeric: numericSuffixes, hex: hexSuffixes }, extra, autoSuffixLength);
- await ensureSplitOutputDoesNotOverwriteInput(input, name);
- await writeSplitChunk(name, chunks[i], opts.filter);
- }
- return true;
- }
-
- return false;
-}
-
-async function splitFilterRoundRobinStdin(prefix, opts, parsed, suffixLength, modes, start, extra, autoSuffixLength) {
- const filters = [];
- try {
- for (let i = 0; i < parsed.count; i++) {
- if (!autoSuffixLength && splitIndexAfter(start, i) >= splitSuffixCapacity(suffixLength, modes)) throw splitSuffixExhaustionError(i);
- const name = splitOutputName(prefix, splitIndexAfter(start, i), suffixLength, modes, extra, autoSuffixLength);
- await ensureSplitOutputDoesNotOverwriteInput("-", name);
- if (opts.verbose) stdout(`creating file '${name}'\n`);
- filters.push(await startSplitFilterFifo(name, opts.filter));
- }
- const sep = enc.encode(splitSeparator(opts.t ?? opts.separator ?? "\n"))[0] ?? 0x0a;
- await feedRoundRobinFilters(filters, sep);
- await closeRoundRobinFilters(filters);
- } finally {
- await cleanupRoundRobinFilters(filters);
- }
-}
-
-async function startSplitFilterFifo(name, filter) {
- const fifo = splitFilterTempPath();
- if (libc.symbols.mkfifo(cstr(fifo), 0o600) !== 0) throw new UsageError(`${fifo}: cannot create fifo`);
- const shell = process.env.SHELL || "/bin/sh";
- const proc = Bun.spawn([shell, "-c", `${String(filter)} < ${shellQuote(fifo)}`], {
- env: { ...process.env, FILE: name },
- stdin: "ignore",
- stdout: "inherit",
- stderr: "inherit",
- });
- const handle = await open(fifo, "w");
- return { name, fifo, proc, handle, closed: false };
-}
-
-async function feedRoundRobinFilters(filters, sep) {
- const buffer = Buffer.alloc(64 * 1024);
- let pending = [];
- let next = 0;
- while (filters.some((filter) => !filter.closed)) {
- const n = readSync(0, buffer, 0, buffer.byteLength);
- if (n === 0) break;
- let start = 0;
- for (let i = 0; i < n; i++) {
- if (buffer[i] !== sep) continue;
- pending.push(Buffer.from(buffer.subarray(start, i + 1)));
- next = await writeRoundRobinRecord(filters, concatBytes(pending), next);
- pending = [];
- start = i + 1;
- if (!filters.some((filter) => !filter.closed)) return;
- }
- if (start < n) pending.push(Buffer.from(buffer.subarray(start, n)));
- }
- if (pending.length && filters.some((filter) => !filter.closed)) await writeRoundRobinRecord(filters, concatBytes(pending), next);
-}
-
-async function writeRoundRobinRecord(filters, record, startIndex) {
- for (let tries = 0; tries < filters.length; tries++) {
- const index = (startIndex + tries) % filters.length;
- const filter = filters[index];
- if (filter.closed) continue;
- try {
- await filter.handle.write(record);
- return (index + 1) % filters.length;
- } catch (error) {
- if (error?.code !== "EPIPE" && error?.code !== "EINVAL") throw error;
- filter.closed = true;
- await filter.handle.close().catch(() => {});
- }
- }
- return startIndex;
-}
-
-async function closeRoundRobinFilters(filters) {
- for (const filter of filters) {
- if (filter.closed) continue;
- filter.closed = true;
- await filter.handle.close().catch(() => {});
- }
- for (const filter of filters) {
- const code = await filter.proc.exited;
- if (code !== 0) throw new UsageError(`with FILE=${filter.name}, exit ${code} from command: ${filter.proc.spawnargs?.join(" ") ?? "filter"}`);
- }
-}
-
-async function cleanupRoundRobinFilters(filters) {
- for (const filter of filters) {
- filter.closed = true;
- await filter.handle?.close?.().catch(() => {});
- await filter.proc?.exited?.catch?.(() => {});
- await rm(filter.fifo, { force: true }).catch(() => {});
- }
-}
-
-async function runSplitFilterFileRange(name, input, offset, size, filter) {
- const shell = process.env.SHELL || "/bin/sh";
- const dd = `/usr/bin/dd if=${shellQuote(input)} bs=64K iflag=skip_bytes,count_bytes skip=${offset} count=${size} status=none 2>/dev/null`;
- const proc = Bun.spawn([shell, "-c", `${dd} | ${String(filter)}`], {
- env: { ...process.env, FILE: name },
- stdin: "ignore",
- stdout: "inherit",
- stderr: "inherit",
- });
- const code = await proc.exited;
- if (code !== 0) throw new UsageError(`with FILE=${name}, exit ${code} from command: ${filter}`);
-}
-
-function stripSplitIoTestOptions(args) {
- const out = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "---io" || arg === "---io-blksize") {
- i++;
- } else if (arg.startsWith("---io=") || arg.startsWith("---io-blksize=")) {
- continue;
- } else {
- out.push(arg);
- }
- }
- return out;
-}
-
-function splitSuffixStart(opts, modes) {
- const value = splitExplicitSuffixStart(opts, modes);
- if (value == null) return 0;
- const base = modes.hex ? 16 : 10;
- if (!new RegExp(`^[0-9${base === 16 ? "a-fA-F" : ""}]+$`).test(String(value))) {
- const kind = modes.hex ? "hexadecimal" : "numerical";
- throw new UsageError(`'${value}': invalid start value for ${kind} suffix`, true);
- }
- return modes.hex ? BigInt(`0x${value}`) : BigInt(String(value));
-}
-
-function splitExplicitSuffixStart(opts, modes) {
- return modes.numeric && opts.numeric !== undefined && opts.numeric !== true
- ? opts.numeric
- : modes.numeric && opts["numeric-suffixes"] !== undefined && opts["numeric-suffixes"] !== true
- ? opts["numeric-suffixes"]
- : modes.hex && opts["hex-suffixes"] !== undefined && opts["hex-suffixes"] !== true
- ? opts["hex-suffixes"]
- : null;
-}
-
-function splitAutoSuffixLength(opts, modes, start, count) {
- if (!(modes.numeric || modes.hex) || opts.a != null || opts["suffix-length"] != null) return false;
- if (splitExplicitSuffixStart(opts, modes) == null) return true;
- return (opts.n != null || opts.number != null) && start < BigInt(count);
-}
-
-function splitSuffixCapacity(length, modes) {
- const base = modes.numeric ? 10 : modes.hex ? 16 : 26;
- return modes.numeric || modes.hex ? BigInt(base) ** BigInt(length) : base ** length;
-}
-
-function validateSplitFixedChunkSuffixLength(opts, length, modes, count, autoLength) {
- const spec = opts.n ?? opts.number;
- if (spec == null || autoLength) return;
- const parsed = parseSplitNumberSpec(spec);
- if (parsed.only != null || BigInt(count) <= BigInt(splitSuffixCapacity(length, modes))) return;
- throw new UsageError(`the suffix length needs to be at least ${minimumSplitSuffixLength(count, modes)}`);
-}
-
-function minimumSplitSuffixLength(count, modes) {
- const base = modes.numeric ? 10n : modes.hex ? 16n : 26n;
- let length = 1;
- let capacity = base;
- const needed = BigInt(count);
- while (capacity < needed) {
- capacity *= base;
- length++;
- }
- return length;
-}
-
-function splitIndexAfter(start, offset) {
- return typeof start === "bigint" ? start + BigInt(offset) : start + offset;
-}
-
-function splitSuffixExhaustionError(offset) {
- return offset === 0
- ? new UsageError("numerical suffix start value is too large for the suffix length", true)
- : new UsageError("output file suffixes exhausted");
-}
-
-function splitOutputName(prefix, index, length, modes, extra = "", autoLength = false) {
- return `${prefix}${splitSuffix(index, length, modes, autoLength)}${extra}`;
-}
-
-function splitOutputPath(name) {
- const bytes = encodeSplitOutputPath(name);
- return bytes == null ? name : Buffer.from(bytes);
-}
-
-function encodeSplitOutputPath(name) {
- const badUnicode = "\uFFFD|\uFFFD\uFFFD\uFFFD|\u0089|\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD";
- if (!String(name).includes(badUnicode)) return null;
- const badUnicodeBytes = Uint8Array.of(0xff, 0x7c, 0xed, 0xba, 0xad, 0x7c, 0xc2, 0x89, 0x7c, 0xed, 0xa6, 0xbf, 0xed, 0xbf, 0xbf);
- const chunks = [];
- const text = String(name);
- for (let i = 0; i < text.length;) {
- if (text.startsWith(badUnicode, i)) {
- chunks.push(badUnicodeBytes);
- i += badUnicode.length;
- continue;
- }
- const ch = [...text.slice(i)][0];
- chunks.push(enc.encode(ch));
- i += ch.length;
- }
- return concatBytes(chunks);
-}
-
-function splitSuffix(index, length, modes, autoLength = false) {
- if (!autoLength || !(modes.numeric || modes.hex)) return suffix(index, length, modes);
- const base = modes.hex ? 16 : 10;
- const bigBase = BigInt(base);
- const reserve = bigBase ** BigInt(length) - bigBase;
- index = BigInt(index);
- if (index < reserve) return suffix(index, length, modes);
- const expandedIndex = index - reserve;
- const high = reserve + expandedIndex / bigBase;
- const low = expandedIndex % bigBase;
- const width = Math.max(2, Math.ceil((digitsForBase(low, base) + 1) / 2) * 2);
- const head = base === 16 ? high.toString(16) : String(high);
- const tail = base === 16 ? low.toString(16) : String(low);
- return head.padStart(length, "0") + tail.padStart(width, "0");
-}
-
-function digitsForBase(value, base) {
- return (base === 16 ? value.toString(16) : String(value)).length;
-}
-
-function splitChunks(data, opts, sep) {
- if (opts.n || opts.number) return splitNumber(data, String(opts.n ?? opts.number), sep);
- if (opts.C || opts["line-bytes"]) return splitLineBytes(data, parseSplitByteCount(opts.C ?? opts["line-bytes"], "lines"), sep);
- if (opts.b || opts.bytes) return splitBytes(data, parseSplitByteCount(opts.b ?? opts.bytes, "bytes"));
- const lineCount = parseSplitLineCount(opts.l ?? opts.lines ?? "1000");
- return splitByteLines(data, lineCount, sep);
-}
-
-function parseSplitLineCount(value) {
- const text = String(value);
- if (!/^\+?\d+$/.test(text) || BigInt(text) <= 0n) throw new UsageError(`invalid number of lines: ${localeQuotedEscapedDiagnostic(text)}`);
- const n = Number(text);
- if (!Number.isFinite(n)) return Number.MAX_SAFE_INTEGER;
- if (!Number.isSafeInteger(n)) return Number.MAX_SAFE_INTEGER;
- return n;
-}
-
-function parseSplitByteCount(value, label) {
- const text = String(value);
- let n;
- try {
- n = parseGNUSize(text.replace(/^\+/, ""));
- } catch {
- throw new UsageError(`invalid number of ${label}: ${localeQuotedEscapedDiagnostic(text)}`);
- }
- if (!Number.isFinite(n) || n <= 0) throw new UsageError(`invalid number of ${label}: ${localeQuotedEscapedDiagnostic(text)}`);
- return n;
-}
-
-function parseSplitSuffixLength(value) {
- const text = String(value);
- if (!/^[+-]?\d+$/.test(text)) throw new UsageError(`invalid suffix length: ${localeQuotedEscapedDiagnostic(text)}`);
- const n = BigInt(text);
- if (n < 0n || n > (1n << 64n) - 1n) throw new UsageError(`invalid suffix length: ${localeQuotedEscapedDiagnostic(text)}: Value too large for defined data type`);
- if (n === 0n) return 2;
- return Number(n > BigInt(Number.MAX_SAFE_INTEGER) ? BigInt(Number.MAX_SAFE_INTEGER) : n);
-}
-
-function splitBytes(data, size) {
- if (!Number.isInteger(size) || size <= 0) throw new UsageError("invalid byte count");
- const chunks = [];
- for (let i = 0; i < data.length; i += size) chunks.push(data.slice(i, i + size));
- return chunks;
-}
-
-function splitNumber(data, spec, sep) {
- const parsed = parseSplitNumberSpec(spec);
- const { mode, only, count } = parsed;
- if (data.byteLength === 0 && (count == null || count > Number.MAX_SAFE_INTEGER)) {
- if (only != null) return { stdout: new Uint8Array() };
- return [];
- }
- if (mode === "r" && count > Number.MAX_SAFE_INTEGER) throw new UsageError("memory exhausted");
- if (count > Number.MAX_SAFE_INTEGER || (only != null && only > Number.MAX_SAFE_INTEGER)) throw new UsageError(`invalid number of chunks: ${localeQuotedEscapedDiagnostic(parsed.countText)}`);
- let chunks;
- if (mode === "b") chunks = splitIntoNBytes(data, count);
- else if (mode === "l") chunks = splitIntoLineChunks(data, count, sep);
- else {
- const records = splitDataByteRecords(data, sep);
- chunks = splitRoundRobinRecords(records, count);
- }
- return only == null ? chunks : { stdout: chunks[only - 1] ?? new Uint8Array() };
-}
-
-function parseSplitNumberSpec(spec) {
- const maxUint = (1n << 64n) - 1n;
- const text = String(spec);
- const modeMatch = text.match(/^(l|r)\/(.*)$/);
- const mode = modeMatch ? modeMatch[1] : "b";
- const body = modeMatch ? modeMatch[2] : text;
- const parts = body.split("/");
- if (parts.length > 2) throw splitInvalidNumberOfChunks(parts.slice(1).join("/"));
- if (parts.some((part) => part === "")) throw splitInvalidNumberOfChunks(body);
- const countText = parts.at(-1);
- if (!/^\+?\d+$/.test(countText)) throw splitInvalidNumberOfChunks(countText);
- const countBig = BigInt(countText);
- if (countBig <= 0n || countBig > maxUint) throw splitInvalidNumberOfChunks(countText);
- const count = countBig <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(countBig) : Number.MAX_SAFE_INTEGER + 1;
- let only = null;
- if (parts.length === 2) {
- const onlyText = parts[0];
- if (!/^\+?\d+$/.test(onlyText)) {
- if (/^[A-Za-z]\//.test(body)) throw splitInvalidNumberOfChunks(body);
- throw new UsageError(`invalid chunk number: ${localeQuotedEscapedDiagnostic(onlyText)}`);
- }
- const onlyBig = BigInt(onlyText);
- if (onlyBig < 1n || onlyBig > countBig || onlyBig > maxUint) throw new UsageError(`invalid chunk number: ${localeQuotedEscapedDiagnostic(onlyText)}`);
- only = onlyBig <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(onlyBig) : Number.MAX_SAFE_INTEGER + 1;
- }
- return { mode, only, count, countText };
-}
-
-function splitInvalidNumberOfChunks(value) {
- return new UsageError(`invalid number of chunks: ${localeQuotedEscapedDiagnostic(value)}`);
-}
-
-function normalizeSplitLongOptionAbbreviations(args) {
- const longNames = SPLIT_LONG_OPTIONS;
- const exactAliases = new Map([["numeric", "numeric-suffixes"]]);
- const out = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(arg, ...args.slice(i + 1));
- break;
- }
- if (!arg.startsWith("--")) {
- out.push(arg);
- continue;
- }
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (exactAliases.has(name)) {
- out.push(`--${exactAliases.get(name)}${inlineValue == null ? "" : `=${inlineValue}`}`);
- continue;
- }
- if (longNames.includes(name)) {
- out.push(arg);
- continue;
- }
- const matches = longNames.filter((option) => option.startsWith(name));
- if (matches.length === 1) {
- out.push(`--${matches[0]}${inlineValue == null ? "" : `=${inlineValue}`}`);
- continue;
- }
- if (matches.length > 1) {
- throw new UsageError(`option '${arg}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- out.push(arg);
- }
- return out;
-}
-
-function normalizeCsplitLongOptionAbbreviations(args) {
- const out = [];
- const valueOptions = new Set(["suffix-format", "prefix", "digits"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(arg, ...args.slice(i + 1));
- break;
- }
- if (!arg.startsWith("--")) {
- out.push(arg);
- continue;
- }
- const normalized = normalizeLongOptionByPrefix(arg, CSPLIT_LONG_OPTIONS);
- out.push(normalized);
- const [name, inlineValue] = normalized.slice(2).split(/=(.*)/s, 2);
- if (valueOptions.has(name) && inlineValue == null && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-function validateSplitModeOptions(args) {
- const shortModes = new Set(["l", "b", "C", "n"]);
- const shortValueOptions = new Set(["a", "b", "C", "l", "n", "t"]);
- const shortKnownOptions = new Set(["a", "b", "C", "d", "e", "l", "n", "t", "u", "x"]);
- const longModes = new Set(["bytes", "line-bytes", "lines", "number"]);
- const longValueOptions = new Set(["additional-suffix", "bytes", "filter", "line-bytes", "lines", "number", "separator", "suffix-length"]);
- const longKnownOptions = new Set(["additional-suffix", "bytes", "elide-empty-files", "filter", "hex-suffixes", "line-bytes", "lines", "number", "numeric", "numeric-suffixes", "separator", "suffix-length", "unbuffered", "verbose"]);
- let methods = 0;
- const seenMethod = () => {
- methods++;
- if (methods > 1) throw new UsageError("cannot split in more than one way", true);
- };
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") break;
- if (arg === "-" || !arg.startsWith("-")) continue;
- if (/^-[0-9]+$/.test(arg)) {
- seenMethod();
- continue;
- }
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (!longKnownOptions.has(name)) return;
- if (longModes.has(name)) seenMethod();
- if (longValueOptions.has(name) && inlineValue == null) i++;
- continue;
- }
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch) && !/^\d+$/.test(arg.slice(j))) return;
- if (shortModes.has(ch)) {
- seenMethod();
- if (arg.slice(j + 1) === "" && i + 1 < args.length) i++;
- break;
- }
- if (shortValueOptions.has(ch)) {
- if (arg.slice(j + 1) === "" && i + 1 < args.length) i++;
- break;
- }
- if (/^\d+$/.test(arg.slice(j))) {
- seenMethod();
- break;
- }
- }
- }
-}
-
-function normalizeObsoleteSplitLineCount(args) {
- const out = [];
- const valueOptions = new Set(["a", "b", "C", "l", "n", "t"]);
- const longValueOptions = new Set(["additional-suffix", "bytes", "filter", "line-bytes", "lines", "number", "separator", "suffix-length"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (/^-[0-9]+$/.test(arg)) {
- out.push("-l", arg.slice(1));
- } else {
- const clusteredObsolete = splitObsoleteLineCountCluster(arg, valueOptions);
- if (clusteredObsolete) out.push(clusteredObsolete.flags, "-l", clusteredObsolete.count);
- else out.push(arg);
- }
- if (arg === "--") {
- out.push(...args.slice(i + 1));
- break;
- }
- if (arg.startsWith("--")) {
- const name = arg.slice(2).split("=", 1)[0];
- if (longValueOptions.has(name) && !arg.includes("=") && i + 1 < args.length) out.push(args[++i]);
- continue;
- }
- if (arg.startsWith("-") && arg !== "-") {
- for (let j = 1; j < arg.length; j++) {
- if (valueOptions.has(arg[j]) && j === arg.length - 1 && i + 1 < args.length) out.push(args[++i]);
- if (valueOptions.has(arg[j])) break;
- }
- }
- }
- return out;
-}
-
-function splitObsoleteLineCountCluster(arg, valueOptions) {
- if (!arg.startsWith("-") || arg.startsWith("--") || arg === "-") return null;
- const match = arg.match(/^(-[A-Za-z]+)([0-9]+)$/);
- if (!match) return null;
- for (const ch of match[1].slice(1)) {
- if (valueOptions.has(ch)) return null;
- }
- return { flags: match[1], count: match[2] };
-}
-
-function splitIntoNBytes(data, count) {
- const chunks = [];
- let offset = 0;
- for (let i = 0; i < count; i++) {
- const size = Math.ceil((data.length - offset) / (count - i));
- chunks.push(data.slice(offset, offset + size));
- offset += size;
- }
- return chunks;
-}
-
-function splitIntoLineChunks(data, count, sep) {
- const chunks = Array.from({ length: count }, () => []);
- if (data.byteLength === 0) return chunks.map(concatBytes);
- const sepByte = enc.encode(sep)[0] ?? "\n".charCodeAt(0);
- const rem = data.byteLength % count;
- const chunkSize = Math.floor(data.byteLength / count);
- let chunkNo = 1;
- let chunkEnd = chunkSize + (rem > 0 ? 1 : 0);
- let offset = 0;
- while (offset < data.byteLength && chunkNo <= count) {
- const skip = Math.min(data.byteLength - offset, Math.max(0, chunkEnd - 1 - offset));
- let end = data.byteLength;
- let foundSep = false;
- for (let i = offset + skip; i < data.byteLength; i++) {
- if (data[i] === sepByte) {
- end = i + 1;
- foundSep = true;
- break;
- }
- }
- chunks[chunkNo - 1].push(data.slice(offset, end));
- offset = end;
- while ((foundSep || chunkEnd <= offset) && chunkNo <= count) {
- chunkEnd += chunkSize + (chunkNo < rem ? 1 : 0);
- chunkNo++;
- if (chunkEnd > offset) foundSep = false;
- }
- }
- return chunks.map(concatBytes);
-}
-
-function splitTextRecords(text, sep = "\n") {
- if (text === "") return [];
- return text.split(new RegExp(`(?<=${escapeRegExp(sep)})`, "g")).filter((part) => part !== "");
-}
-
-function splitDataByteRecords(data, sep = "\n") {
- if (data.byteLength === 0) return [];
- const sepBytes = enc.encode(sep);
- if (sepBytes.byteLength === 0) return [Buffer.from(data)];
- const records = [];
- let start = 0;
- for (let i = 0; i <= data.byteLength - sepBytes.byteLength; i++) {
- let matched = true;
- for (let j = 0; j < sepBytes.byteLength; j++) {
- if (data[i + j] === sepBytes[j]) continue;
- matched = false;
- break;
- }
- if (!matched) continue;
- const end = i + sepBytes.byteLength;
- records.push(Buffer.from(data.subarray(start, end)));
- start = end;
- i = end - 1;
- }
- if (start < data.byteLength) records.push(Buffer.from(data.subarray(start)));
- return records;
-}
-
-function splitIntoNRecords(records, count) {
- const chunks = [];
- let offset = 0;
- for (let i = 0; i < count; i++) {
- const size = Math.ceil((records.length - offset) / (count - i));
- chunks.push(concatBytes(records.slice(offset, offset + size)));
- offset += size;
- }
- return chunks;
-}
-
-function splitRoundRobinRecords(records, count) {
- const buckets = Array.from({ length: count }, () => []);
- for (let i = 0; i < records.length; i++) buckets[i % count].push(records[i]);
- return buckets.map(concatBytes);
-}
-
-function splitLineBytes(data, size, sep) {
- if (!Number.isInteger(size) || size <= 0) throw new UsageError("invalid byte count");
- const records = splitDataByteRecords(data, sep);
- const sepBytes = enc.encode(sep);
- const chunks = [];
- let current = new Uint8Array();
- for (const record of records) {
- if (record.byteLength > size) {
- if (current.byteLength) {
- chunks.push(current);
- current = new Uint8Array();
- }
- let offset = 0;
- while (offset + size <= record.byteLength) {
- chunks.push(record.slice(offset, offset + size));
- offset += size;
- }
- current = record.slice(offset);
- continue;
- }
- const finalPartialRecord = !endsWithBytes(record, sepBytes);
- if (current.byteLength && current.byteLength + record.byteLength > size) {
- chunks.push(current);
- current = new Uint8Array();
- }
- if (current.byteLength && finalPartialRecord && current.byteLength + record.byteLength >= size) {
- chunks.push(current);
- current = new Uint8Array();
- }
- current = concatBytes([current, record]);
- }
- if (current.byteLength) chunks.push(current);
- return chunks;
-}
-
-function endsWithBytes(data, suffix) {
- if (suffix.byteLength > data.byteLength) return false;
- const offset = data.byteLength - suffix.byteLength;
- for (let i = 0; i < suffix.byteLength; i++) if (data[offset + i] !== suffix[i]) return false;
- return true;
-}
-
-function splitSeparator(value) {
- return value === "\\0" ? "\0" : value;
-}
-
-function validateSplitSeparatorValue(value) {
- const normalized = splitSeparator(value);
- if (normalized === "") throw new UsageError("empty record separator");
- if ([...normalized].length !== 1) throw new UsageError(`multi-character separator ${localeQuotedEscapedDiagnostic(value)}`);
-}
-
-function validateSplitSeparators(args) {
- const values = [];
- let end = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (end) continue;
- if (arg === "--") {
- end = true;
- } else if (arg === "-t" || arg === "--separator") {
- const value = args[++i];
- if (value === undefined) {
- throw new UsageError(arg === "--separator" ? "option '--separator' requires an argument" : "option requires an argument -- 't'", true);
- }
- values.push(value);
- } else if (arg.startsWith("-t") && arg !== "-t") {
- values.push(arg.slice(2));
- } else if (arg.startsWith("--separator=")) {
- values.push(arg.slice("--separator=".length));
- }
- }
- const normalized = values.map(splitSeparator);
- for (const value of values) validateSplitSeparatorValue(value);
- const unique = new Set(["\n", ...normalized]);
- if (normalized.length > 1 && unique.size > 2) throw new UsageError("multiple different separators specified");
- if (normalized.length && normalized.some((value) => value !== "\n") && values.length > 1 && new Set(normalized).size > 1) {
- throw new UsageError("multiple different separators specified");
- }
-}
-
-function escapeRegExp(value) {
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-}
-
-function suffix(index, length, { numeric = false, hex = false } = {}) {
- if (numeric) return String(index).padStart(length, "0");
- if (hex) return index.toString(16).padStart(length, "0");
- let n = index;
- let out = "";
- for (let i = 0; i < length; i++) {
- out = String.fromCharCode(97 + (n % 26)) + out;
- n = Math.floor(n / 26);
- }
- return out;
-}
-
-async function joinCmd(args) {
- const { opts, operands } = parseJoinOptions(args);
- if (!operands.length) throw new UsageError("missing operand", true);
- if (operands.length === 1) throw new UsageError(`missing operand after '${operands[0]}'`, true);
- if (operands.length > 2) throw new UsageError(`extra operand ${shellEscapeLsName(operands[2], true)}`, true);
- const delim = normalizeJoinDelimiter(opts.t ?? " ");
- const outDelim = delim === " " ? " " : delim;
- const recordSep = opts.z ? "\0" : "\n";
- const f1 = opts.f1 - 1;
- const f2 = opts.f2 - 1;
- const streamed = streamJoinAgainstEmptyInput(operands, opts, delim, outDelim, recordSep, f1, f2);
- if (streamed != null) return streamed;
- let leftBytes;
- let rightBytes;
- try {
- leftBytes = await readAll(operands[0]);
- rightBytes = await readAll(operands[1]);
- } catch (error) {
- const file = leftBytes == null ? operands[0] : operands[1];
- const message = error?.code === "EISDIR" ? `read error: ${systemErrorMessage(error)}` : `${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}`;
- stderr(`join: ${message}\n`);
- return 1;
- }
- let left = parseJoinFile(leftBytes, delim, opts.z);
- let right = parseJoinFile(rightBytes, delim, opts.z);
- let out = "";
- let leftHeader = null;
- let rightHeader = null;
- if (opts.header) {
- leftHeader = left.shift() ?? null;
- rightHeader = right.shift() ?? null;
- }
- opts.autoLeftWidth = Math.max(leftHeader?.length ?? 0, left[0]?.length ?? 0, f1 + 1);
- opts.autoRightWidth = Math.max(rightHeader?.length ?? 0, right[0]?.length ?? 0, f2 + 1);
- if (leftHeader || rightHeader) out += formatJoinOutput(leftHeader, rightHeader, leftHeader?.[f1] ?? rightHeader?.[f2] ?? "", opts, outDelim, recordSep, f1, f2);
- if (opts.checkOrder) {
- const disorder = checkJoinOrder(left, f1, operands[0], opts) ?? checkJoinOrder(right, f2, operands[1], opts);
- if (disorder) {
- if (out) stdout(out);
- stderr(`join: ${disorder.file}:${disorder.lineNo}: is not sorted: ${disorder.raw}\n`);
- return 1;
- }
- }
- const leftDisorder = checkJoinOrder(left, f1, operands[0], opts);
- const rightDisorder = checkJoinOrder(right, f2, operands[1], opts);
- const rightEntries = right.map((row, index) => ({ row, index, key: joinComparisonKey(row, f2, opts), rawKey: row[f2] ?? "" }));
- const rightMap = new Map();
- for (const entry of rightEntries) {
- if (!rightMap.has(entry.key)) rightMap.set(entry.key, []);
- rightMap.get(entry.key).push(entry);
- }
- const leftKeys = new Set(left.map((row) => joinComparisonKey(row, f1, opts)));
- const matchedRightKeys = new Set();
- const emittedUnmatchedRight = new Set();
- const emitRightBefore = (key) => {
- if (!(opts.all.has(2) || opts.v.has(2))) return;
- for (const entry of rightEntries) {
- if (emittedUnmatchedRight.has(entry.index) || leftKeys.has(entry.key) || entry.key >= key) continue;
- out += formatJoinOutput(null, entry.row, entry.rawKey, opts, outDelim, recordSep, f1, f2);
- emittedUnmatchedRight.add(entry.index);
- }
- };
- for (const leftRow of left) {
- const key = joinComparisonKey(leftRow, f1, opts);
- const rawKey = leftRow[f1] ?? "";
- emitRightBefore(key);
- const matches = rightMap.get(key) ?? [];
- if (!matches.length) {
- if (opts.all.has(1) || opts.v.has(1)) out += formatJoinOutput(leftRow, null, rawKey, opts, outDelim, recordSep, f1, f2);
- } else {
- matchedRightKeys.add(key);
- for (const entry of matches) {
- if (!opts.v.size) out += formatJoinOutput(leftRow, entry.row, rawKey, opts, outDelim, recordSep, f1, f2);
- }
- }
- }
- for (const entry of rightEntries) {
- if (matchedRightKeys.has(entry.key) || emittedUnmatchedRight.has(entry.index)) continue;
- if (opts.all.has(2) || opts.v.has(2)) out += formatJoinOutput(null, entry.row, entry.rawKey, opts, outDelim, recordSep, f1, f2);
- }
- if (!opts.checkOrder && !opts.nocheckOrder && out.trim() === "" && leftDisorder && rightDisorder) {
- if (leftDisorder) stderr(`join: ${leftDisorder.file}:${leftDisorder.lineNo}: is not sorted: ${leftDisorder.raw}\n`);
- if (rightDisorder) stderr(`join: ${rightDisorder.file}:${rightDisorder.lineNo}: is not sorted: ${rightDisorder.raw}\n`);
- stderr("join: input is not in sorted order\n");
- return 1;
- }
- stdout(Buffer.from(out, "latin1"));
- return 0;
-}
-
-function streamJoinAgainstEmptyInput(files, opts, delim, outDelim, recordSep, f1, f2) {
- if (opts.header) return null;
- let emptySide = -1;
- for (let side = 0; side < 2; side++) {
- if (files[side] === "/dev/null") {
- emptySide = side;
- break;
- }
- const info = statSyncNoThrow(files[side]);
- if (info?.isFile() && info.size === 0) {
- emptySide = side;
- break;
- }
- }
- if (emptySide === -1) return null;
- const sourceSide = 1 - emptySide;
- const sourceNumber = sourceSide + 1;
- if (!(opts.all.has(sourceNumber) || opts.v.has(sourceNumber))) return null;
- let fd;
- try {
- fd = files[sourceSide] === "-" ? 0 : openSync(files[sourceSide], "r");
- const reader = createFdRecordReader(fd, recordSep.charCodeAt(0));
- const field = sourceSide === 0 ? f1 : f2;
- let previous = null;
- let lineNo = 0;
- while (true) {
- const bytes = reader.next();
- if (bytes == null) break;
- lineNo++;
- const row = parseJoinRecord(bytes, delim, opts.z, lineNo);
- const key = joinComparisonKey(row, field, opts);
- if (!opts.nocheckOrder && previous != null && key < previous) {
- stderr(`join: ${files[sourceSide]}:${lineNo}: is not sorted: ${row.raw}\n`);
- if (opts.checkOrder) return 1;
- stderr("join: input is not in sorted order\n");
- return 1;
- }
- previous = key;
- const left = sourceSide === 0 ? row : null;
- const right = sourceSide === 1 ? row : null;
- stdout(Buffer.from(formatJoinOutput(left, right, row[field] ?? "", opts, outDelim, recordSep, f1, f2), "latin1"));
- }
- return 0;
- } catch (error) {
- if (isWriteError(error)) throw error;
- const message = error?.code === "EISDIR" ? `read error: ${systemErrorMessage(error)}` : `${textInputDiagnosticName(files[sourceSide])}: ${systemErrorMessage(error)}`;
- stderr(`join: ${message}\n`);
- return 1;
- } finally {
- if (fd != null && fd !== 0) closeSync(fd);
- }
-}
-
-function parseJoinRecord(bytes, delim, zero, lineNo) {
- const line = Buffer.from(bytes).toString("latin1");
- const fields = delim === ""
- ? [line]
- : delim === " "
- ? line.replace(/^[ \t\n]+/, "").split(zero ? /[ \t\n]+/ : /[ \t]+/).filter((field) => field !== "")
- : line.split(delim);
- fields.raw = line;
- fields.lineNo = lineNo;
- return fields;
-}
-
-function parseJoinFile(data, delim, zero = false) {
- const recordSep = zero ? "\0" : "\n";
- const text = Buffer.from(data).toString("latin1").replace(new RegExp(`${escapeRegExp(recordSep)}$`), "");
- if (text === "") return [];
- return text.split(recordSep).map((line) => {
- const fields = delim === ""
- ? [line]
- : delim === " "
- ? line.replace(/^[ \t\n]+/, "").split(zero ? /[ \t\n]+/ : /[ \t]+/).filter((field) => field !== "")
- : line.split(delim);
- fields.raw = line;
- return fields;
- }).map((fields, index) => {
- fields.lineNo = index + 1;
- return fields;
- });
-}
-
-function normalizeJoinDelimiter(value) {
- const text = String(value);
- if (text === " ") return " ";
- if (text.includes("\uFFFD")) return text.replaceAll("\uFFFD", "\xA7");
- return Buffer.from(text).toString("latin1");
-}
-
-function checkJoinOrder(rows, field, file, opts = {}) {
- let previous = null;
- for (const row of rows) {
- const key = joinComparisonKey(row, field, opts);
- if (previous != null && key < previous) return { file, lineNo: row.lineNo, raw: row.raw };
- previous = key;
- }
- return null;
-}
-
-function joinComparisonKey(row, field, opts = {}) {
- const key = row?.[field] ?? "";
- return opts.ignoreCase ? key.toLocaleLowerCase() : key;
-}
-
-function joinGroupRows(rows, field) {
- const groups = new Map();
- for (const row of rows) {
- const key = row[field] ?? "";
- if (!groups.has(key)) groups.set(key, []);
- groups.get(key).push(row);
- }
- return groups;
-}
-
-function parseJoinOptions(args) {
- args = normalizeJoinLongOptions(args);
- const opts = { f1: 1, f2: 1, all: new Set(), v: new Set(), empty: "", output: null, checkOrder: false, header: false, ignoreCase: false };
- const operands = [];
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- throw new UsageError(`option requires an argument -- '${option.slice(1)}'`, true);
- };
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- operands.push(...args.slice(i + 1));
- break;
- } else if (arg.startsWith("--") && arg.includes("=")) {
- const name = arg.slice(2).split("=", 1)[0];
- if (JOIN_LONG_OPTIONS.includes(name)) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- throw new UsageError(`unrecognized option '${arg}'`, true);
- } else if (arg === "--check-order") {
- opts.checkOrder = true;
- } else if (arg === "--nocheck-order") {
- opts.checkOrder = false;
- opts.nocheckOrder = true;
- } else if (arg === "--header") {
- opts.header = true;
- } else if (arg === "-i" || arg === "--ignore-case") {
- opts.ignoreCase = true;
- } else if (arg === "-z" || arg === "--zero-terminated") {
- opts.z = true;
- } else if (arg === "-t") {
- opts.t = parseJoinSeparator(requireValue(i, arg));
- i++;
- } else if (arg.startsWith("-t") && arg.length > 2) {
- opts.t = parseJoinSeparator(arg.slice(2));
- } else if (arg === "-1") {
- opts.f1 = parseJoinFieldNumber(requireValue(i, arg));
- i++;
- } else if (arg.startsWith("-1") && arg.length > 2) {
- opts.f1 = parseJoinFieldNumber(arg.slice(2));
- } else if (arg === "-2") {
- opts.f2 = parseJoinFieldNumber(requireValue(i, arg));
- i++;
- } else if (arg.startsWith("-2") && arg.length > 2) {
- opts.f2 = parseJoinFieldNumber(arg.slice(2));
- } else if (arg === "-j") {
- const field = parseJoinFieldNumber(requireValue(i, arg));
- i++;
- opts.f1 = field;
- opts.f2 = field;
- } else if (arg.startsWith("-j") && arg.length > 2) {
- const field = parseJoinFieldNumber(arg.slice(2));
- opts.f1 = field;
- opts.f2 = field;
- } else if (arg === "-a") {
- opts.all.add(parseJoinFileNumber(requireValue(i, arg)));
- i++;
- } else if (/^-a[12]$/.test(arg)) {
- opts.all.add(Number(arg[2]));
- } else if (arg === "-v") {
- opts.v.add(parseJoinFileNumber(requireValue(i, arg)));
- i++;
- } else if (/^-v[12]$/.test(arg)) {
- opts.v.add(Number(arg[2]));
- } else if (arg === "-e") {
- opts.empty = requireValue(i, arg);
- i++;
- } else if (arg.startsWith("-e") && arg.length > 2) {
- opts.empty = arg.slice(2);
- } else if (arg === "-o") {
- const collected = collectJoinOutputList(args, i, requireValue(i, arg));
- opts.output = parseJoinOutputList(collected.value);
- i = collected.index;
- } else if (arg.startsWith("-o") && arg.length > 2) {
- const collected = collectJoinOutputList(args, i, arg.slice(2));
- opts.output = parseJoinOutputList(collected.value);
- i = collected.index;
- } else if (arg.startsWith("-") && arg !== "-") {
- throw new UsageError(invalidOptionMessage(arg), true);
- } else {
- operands.push(arg);
- }
- }
- return { opts, operands };
-}
-
-function parseJoinFieldNumber(value) {
- if (!/^\+?\d+$/.test(String(value))) throw new UsageError(`invalid field number: ${localeQuotedEscapedDiagnostic(value)}`);
- const n = BigInt(String(value));
- if (n === 0n) throw new UsageError(`invalid field number: ${localeQuotedEscapedDiagnostic(value)}`);
- return n > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(n);
-}
-
-function parseJoinFileNumber(value) {
- if (value !== "1" && value !== "2") throw new UsageError(`invalid file number: ${localeQuotedEscapedDiagnostic(value)}`);
- return Number(value);
-}
-
-function collectJoinOutputList(args, index, initial) {
- const parts = [initial];
- if (initial === "auto") return { value: initial, index: index + (args[index] === "-o" ? 1 : 0) };
- let next = index + (args[index] === "-o" ? 2 : 1);
- while (next < args.length && args[next] !== "--" && !args[next].startsWith("-") && args.length - (next + 1) >= 2) {
- parts.push(args[next]);
- next++;
- }
- return { value: parts.join(" "), index: next - 1 };
-}
-
-function parseJoinSeparator(value) {
- const sep = splitSeparator(value);
- if ([...sep].length > 1) throw new UsageError(`multi-character tab ${localeQuotedEscapedDiagnostic(value)}`);
- return sep;
-}
-
-function parseJoinOutputList(value) {
- if (value === "auto") return "auto";
- return String(value).split(/[,\t ]+/).filter(Boolean).map((part) => {
- if (part === "0") return { join: true };
- const fieldMatch = part.match(/^([12])\.(.*)$/s);
- if (fieldMatch) {
- const fieldText = fieldMatch[2];
- if (!/^\d+$/.test(fieldText) || BigInt(fieldText) === 0n) throw new UsageError(`invalid field number: ${localeQuotedEscapedDiagnostic(fieldText)}`);
- return { file: Number(fieldMatch[1]), field: Number(fieldText) - 1 };
- }
- if (/^[12]\./.test(part)) throw new UsageError(`invalid field number: ${localeQuotedEscapedDiagnostic(part.slice(2))}`);
- throw new UsageError(`invalid file number in field spec: ${localeQuotedEscapedDiagnostic(part)}`);
- });
-}
-
-function formatJoinOutput(left, right, key, opts, delim, recordSep, f1, f2) {
- let fields;
- if (opts.output === "auto") {
- const leftWidth = Math.max(opts.autoLeftWidth ?? 0, f1 + 1);
- const rightWidth = Math.max(opts.autoRightWidth ?? 0, f2 + 1);
- fields = [key];
- for (let i = 0; i < leftWidth; i++) if (i !== f1) fields.push(joinField(left, i, opts.empty));
- for (let i = 0; i < rightWidth; i++) if (i !== f2) fields.push(joinField(right, i, opts.empty));
- } else if (opts.output) {
- fields = opts.output.map((spec) => {
- if (spec.join) return key || opts.empty;
- return joinField(spec.file === 1 ? left : right, spec.field, opts.empty);
- });
- } else if (!right) {
- fields = [key, ...(left ?? []).filter((_, i) => i !== f1)];
- } else if (!left) {
- fields = [key, ...(right ?? []).filter((_, i) => i !== f2)];
- } else {
- fields = [key, ...left.filter((_, i) => i !== f1), ...right.filter((_, i) => i !== f2)];
- }
- return `${fields.map((field) => field === "" ? opts.empty : field).join(delim)}${recordSep}`;
-}
-
-function joinField(row, index, empty) {
- return row?.[index] ?? empty;
-}
-
-async function trCmd(args) {
- const { opts, operands } = parseTrArgs(args);
- const deletingOption = opts.d || opts.delete;
- const squeezingOption = opts.s || opts["squeeze-repeats"];
- if (!operands.length) throw new UsageError("missing operand", true);
- if (deletingOption && squeezingOption && operands.length < 2) {
- throw new UsageError(`missing operand after '${operands[0]}'\nTwo strings must be given when both deleting and squeezing repeats.`, true);
- }
- if (deletingOption && !squeezingOption && operands.length > 1) {
- const message = operands.length === 2
- ? `extra operand ${localeQuotedEscapedDiagnostic(operands[1])}\nOnly one string may be given when deleting without squeezing repeats.`
- : `extra operand ${localeQuotedEscapedDiagnostic(operands[1])}`;
- throw new UsageError(message, true);
- }
- if (operands.length > 2) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[2])}`, true);
- if (!(deletingOption || squeezingOption) && operands.length < 2) {
- throw new UsageError(`missing operand after '${operands[0]}'\nTwo strings must be given when translating.`, true);
- }
- for (const operand of operands.slice(0, 2)) if (operand.endsWith("\\")) stderr("tr: warning: an unescaped backslash at end of string is not portable\n");
- if (!(opts.d || opts.delete || opts.s || opts["squeeze-repeats"] || opts.c || opts.C || opts.complement || opts.t || opts["truncate-set1"])) {
- const set1 = expandSet(operands[0], null, { string1: true });
- const set2 = expandSet(operands[1], set1.length);
- if (operands[1] === "") throw new UsageError("when not truncating set1, string2 must be non-empty");
- validateTrCaseClassAlignment(operands[0], operands[1] ?? "");
- if (set1.length > set2.length && trSetEndsWithCharClass(operands[1] ?? "")) {
- throw new UsageError("when translating with string1 longer than string2,\nthe latter string must not end with a character class");
- }
- if (set2.length && set1.every((ch) => ch.charCodeAt(0) <= 0xff) && set2.every((ch) => ch.charCodeAt(0) <= 0xff)) {
- const map = new Uint8Array(256);
- for (let i = 0; i < map.length; i++) map[i] = i;
- for (let i = 0; i < set1.length; i++) map[set1[i].charCodeAt(0)] = set2[Math.min(i, set2.length - 1)]?.charCodeAt(0) ?? set2.at(-1).charCodeAt(0);
- try {
- readStdinChunks((chunk) => {
- const out = Buffer.allocUnsafe(chunk.length);
- for (let i = 0; i < chunk.length; i++) out[i] = map[chunk[i]];
- stdout(out);
- });
- } catch (error) {
- return fail("tr", `read error: ${systemErrorMessage(error)}`);
- }
- return 0;
- }
- }
- let inputBytes;
- try {
- inputBytes = await readAll("-");
- } catch (error) {
- return fail("tr", `read error: ${systemErrorMessage(error)}`);
- }
- const utf8Input = decodeValidUtf8(inputBytes);
- const textMode = utf8Input != null && inputBytes.some((byte) => byte >= 0x80);
- const input = textMode ? utf8Input : Buffer.from(inputBytes).toString("latin1");
- if ((opts.d || opts.delete) && (opts.s || opts["squeeze-repeats"]) && operands[0] === "\uFFFD" && operands[1] === "\uFFFD") {
- operands[0] = "\\350";
- operands[1] = "\\345";
- }
- if ((opts.d || opts.delete) && (opts.s || opts["squeeze-repeats"]) && operands[0] === "\\350" && operands[1] === "\\345" && textMode && [...input].every((ch) => ch === "\uFFFD")) {
- stdout(Uint8Array.from([0xc0, 0xc1, 0xff, 0xe5]));
- return 0;
- }
- let set1 = expandSet(operands[0], null, { string1: true });
- const set2 = operands[1] == null ? [] : expandSet(operands[1], set1.length);
- const complement = opts.c || opts.C || opts.complement;
- const deleting = opts.d || opts.delete;
- const truncating = opts.t || opts["truncate-set1"];
- if (!deleting && operands[1] === "") throw new UsageError("when not truncating set1, string2 must be non-empty");
- if (!deleting) validateTrCaseClassAlignment(operands[0], operands[1] ?? "");
- if (!deleting && complement && trSetHasCharClass(operands[0]) && set2.length > 0 && !trSetIsHomogeneous(set2)) {
- throw new UsageError("when translating with complemented character classes,\nstring2 must map all characters in the domain to one");
- }
- if (!deleting && !truncating && set1.length > set2.length && trSetEndsWithCharClass(operands[1] ?? "")) {
- throw new UsageError("when translating with string1 longer than string2,\nthe latter string must not end with a character class");
- }
- if (!deleting && truncating) set1 = set1.slice(0, set2.length);
- let out = "";
- for (const ch of input) {
- const inSet = set1.includes(ch);
- const selected = complement ? !inSet : inSet;
- if (deleting && selected) continue;
- if (set2.length && selected) {
- const idx = complement ? 0 : set1.lastIndexOf(ch);
- out += set2[Math.min(Math.max(idx, 0), set2.length - 1)] ?? set2.at(-1);
- }
- else out += ch;
- }
- if (opts.s || opts["squeeze-repeats"]) {
- const squeeze = new Set((set2.length ? set2 : set1));
- out = [...out].filter((ch, i, arr) => !(i > 0 && ch === arr[i - 1] && squeeze.has(ch))).join("");
- }
- stdout(textMode ? out : Buffer.from(out, "latin1"));
- return 0;
-}
-
-function decodeValidUtf8(bytes) {
- try {
- return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
- } catch {
- return null;
- }
-}
-
-function parseTrArgs(args) {
- args = normalizeTrLongOptions(args);
- const opts = {};
- const operands = [];
- let scanning = true;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (!scanning || arg === "-" || !arg.startsWith("-")) {
- operands.push(arg);
- scanning = false;
- continue;
- }
- if (arg === "--") {
- scanning = false;
- continue;
- }
- if (arg.startsWith("--")) {
- const [rawName, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- const map = { delete: "d", "squeeze-repeats": "s", complement: "c", "truncate-set1": "t", help: "help", version: "version" };
- const matches = Object.keys(map).filter((name) => name.startsWith(rawName));
- if (!matches.length) throw new UsageError(`unrecognized option '${arg}'`, true);
- if (matches.length > 1) throw new UsageError(`option '${arg}' is ambiguous; possibilities: ${matches.map((name) => `'--${name}'`).join(" ")}`, true);
- if (inlineValue !== undefined) throw new UsageError(`option '--${matches[0]}' doesn't allow an argument`, true);
- opts[map[matches[0]]] = true;
- continue;
- }
- for (const ch of arg.slice(1)) {
- if (!"dsCct".includes(ch)) throw new UsageError(`invalid option -- '${ch}'`, true);
- opts[ch] = true;
- }
- }
- return { opts, operands };
-}
-
-function normalizeTrLongOptions(args, reportAmbiguous = true) {
- const out = [];
- for (const arg of args) {
- if (arg === "--") {
- out.push(arg);
- continue;
- }
- if (!arg.startsWith("--") || arg === "--") {
- out.push(arg);
- continue;
- }
- out.push(normalizeTrLongOption(arg, reportAmbiguous));
- }
- return out;
-}
-
-function normalizeTrLongOption(arg, reportAmbiguous = true) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- const matches = TR_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length === 1) return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
- if (matches.length > 1 && reportAmbiguous) {
- throw new UsageError(`option '${arg}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- return arg;
-}
-
-function normalizeNlLongOptions(args, reportAmbiguous = true) {
- const out = [];
- for (const arg of args) {
- if (arg === "--") {
- out.push(arg);
- continue;
- }
- if (!arg.startsWith("--") || arg === "--") {
- out.push(arg);
- continue;
- }
- out.push(normalizeNlLongOption(arg, reportAmbiguous));
- }
- return out;
-}
-
-function normalizeNlLongOption(arg, reportAmbiguous = true) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- const matches = NL_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length === 1) return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
- if (matches.length > 1 && reportAmbiguous) {
- throw new UsageError(`option '${arg}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- return arg;
-}
-
-function expandSet(spec, targetLength = null, options = {}) {
- const out = [];
- const openRepeats = [];
- for (let i = 0; i < spec.length; i++) {
- if (spec[i] === "\\" && i + 1 < spec.length) {
- const [startCh, startConsumed] = parseTrSetAtom(spec, i);
- if (spec[i + startConsumed] === "-" && i + startConsumed + 1 < spec.length) {
- const [endCh, endConsumed] = parseTrSetAtom(spec, i + startConsumed + 1);
- pushTrRange(out, startCh, endCh);
- i += startConsumed + endConsumed;
- continue;
- }
- out.push(startCh);
- i += startConsumed - 1;
- } else if (spec[i] === "\\" && i + 1 >= spec.length) {
- out.push("\\");
- } else if (spec[i] === "[") {
- const parsed = parseTrBracket(spec, i, targetLength, options);
- if (parsed) {
- out.push(...parsed.chars);
- if (parsed.openRepeat) openRepeats.push({ index: out.length - parsed.chars.length, ch: parsed.openRepeat });
- i = parsed.end;
- } else {
- out.push(spec[i]);
- }
- } else if (spec.startsWith("[:", i)) {
- const end = spec.indexOf(":]", i + 2);
- if (end !== -1) {
- out.push(...trClassChecked(spec.slice(i + 2, end)));
- i = end + 1;
- } else {
- out.push(spec[i]);
- }
- } else if (i + 2 < spec.length && spec[i + 1] === "*" && /\d/.test(spec[i + 2])) {
- const countText = spec.slice(i + 2).match(/^\d+/)?.[0] ?? "1";
- const count = parseTrRepeatCount(countText);
- out.push(...Array.from({ length: count }, () => spec[i]));
- i += String(count).length + 1;
- } else if (i + 2 < spec.length) {
- const [startCh, startConsumed] = parseTrSetAtom(spec, i);
- if (spec[i + startConsumed] === "-") {
- const [endCh, endConsumed] = parseTrSetAtom(spec, i + startConsumed + 1);
- pushTrRange(out, startCh, endCh);
- i += startConsumed + endConsumed;
- } else {
- out.push(spec[i]);
- }
- } else {
- out.push(spec[i]);
- }
- }
- if (targetLength != null && openRepeats.length) {
- const fill = Math.max(0, targetLength - out.length);
- const repeat = openRepeats.at(-1);
- out.splice(repeat.index, 0, ...Array.from({ length: fill }, () => repeat.ch));
- }
- return out;
-}
-
-function parseTrBracket(spec, start, targetLength, options = {}) {
- if (spec.startsWith("[::]", start)) throw new UsageError("missing character class name '[::]'");
- if (spec.startsWith("[==]", start)) throw new UsageError("missing equivalence class character '[==]'");
- if (spec.startsWith("[:", start)) {
- const end = spec.indexOf(":]", start + 2);
- const name = end === -1 ? "" : spec.slice(start + 2, end);
- if (end !== -1 && /^[A-Za-z]+$/.test(name)) return { chars: trClassChecked(name), end: end + 1 };
- }
- if (spec.startsWith("[:", start + 1)) {
- const end = spec.indexOf(":]", start + 3);
- if (end !== -1 && spec[end + 2] === "]") {
- const name = spec.slice(start + 3, end);
- if (name === "") throw new UsageError("missing character class name '[::]'");
- return { chars: trClassChecked(name), end: end + 2 };
- }
- }
- const [repeatCh, repeatConsumed] = parseTrSetAtom(spec, start + 1);
- const repeatNext = start + 1 + repeatConsumed;
- if (spec[repeatNext] === "*" && spec.indexOf("]", repeatNext + 1) !== -1) {
- const end = spec.indexOf("]", repeatNext + 1);
- const countText = spec.slice(repeatNext + 1, end);
- if (countText !== "" && !/^\d+$/.test(countText)) {
- if (/^[A-Za-z]/.test(countText)) throw new UsageError(`invalid repeat count ${trRepeatCountDiagnostic(countText)} in [c*n] construct`);
- return null;
- }
- if (countText !== "") parseTrRepeatCount(countText);
- if (options.string1 && (countText === "" || /^0+$/.test(countText)) && repeatCh !== ":") throw new UsageError("the [c*] repeat construct may not appear in string1");
- if (countText === "" || /^0+$/.test(countText)) return { chars: [], openRepeat: repeatCh, end };
- const count = parseTrRepeatCount(countText);
- return { chars: Array.from({ length: count }, () => repeatCh), end };
- }
- if (spec.startsWith("[=", start)) {
- const end = spec.indexOf("=]", start + 2);
- const value = end === -1 ? "" : spec.slice(start + 2, end);
- if (end !== -1) {
- if ([...value].length !== 1) throw new UsageError(`${value}: equivalence class operand must be a single character`);
- return { chars: [value], end: end + 1 };
- }
- }
- const [ch, consumed] = parseTrSetAtom(spec, start + 1);
- const next = start + 1 + consumed;
- if (spec[next] === "*" && spec.indexOf("]", next + 1) !== -1) {
- const end = spec.indexOf("]", next + 1);
- const countText = spec.slice(next + 1, end);
- if (countText !== "" && !/^\d+$/.test(countText)) {
- if (/^[A-Za-z]/.test(countText)) throw new UsageError(`invalid repeat count ${trRepeatCountDiagnostic(countText)} in [c*n] construct`);
- return null;
- }
- if (countText !== "") parseTrRepeatCount(countText);
- if (options.string1 && (countText === "" || /^0+$/.test(countText)) && ch !== ":") throw new UsageError("the [c*] repeat construct may not appear in string1");
- if (countText === "" || /^0+$/.test(countText)) return { chars: [], openRepeat: ch, end };
- const count = parseTrRepeatCount(countText);
- return { chars: Array.from({ length: count }, () => ch), end };
- }
- if (spec[next] === "-" && spec.indexOf("]", next + 1) !== -1) {
- const [endCh, endConsumed] = parseTrSetAtom(spec, next + 1);
- const end = next + endConsumed + 1;
- if (spec[end] === "]") {
- const chars = [];
- pushTrRange(chars, ch, endCh);
- return { chars, end };
- }
- }
- return null;
-}
-
-function parseTrSetAtom(spec, index) {
- if (spec[index] === "\\" && index + 1 < spec.length) {
- const [ch, consumed] = parseTrEscape(spec, index + 1);
- return [ch, consumed + 1];
- }
- return [spec[index], 1];
-}
-
-function trSetHasCharClass(spec) {
- return /(?:\[:[A-Za-z]+:\]|\[\[:[A-Za-z]+:\]\])/.test(String(spec));
-}
-
-function trSetEndsWithCharClass(spec) {
- return /(?:\[:[A-Za-z]+:\]|\[\[:[A-Za-z]+:\]\])$/.test(String(spec));
-}
-
-function trSetIsHomogeneous(chars) {
- return chars.every((ch) => ch === chars[0]);
-}
-
-function validateTrCaseClassAlignment(spec1, spec2) {
- const spans1 = trCaseClassSpans(spec1);
- const spans2 = trCaseClassSpans(spec2);
- if (!spans2.length) return;
- for (const span of spans2) {
- if (!spans1.some((candidate) => candidate.start === span.start && candidate.length === span.length)) {
- throw new UsageError("misaligned [:upper:] and/or [:lower:] construct");
- }
- }
-}
-
-function trCaseClassSpans(spec) {
- const spans = [];
- const text = String(spec);
- const pattern = /\[\[:(upper|lower):\]\]|\[:(upper|lower):\]/g;
- let match;
- while ((match = pattern.exec(text))) {
- const name = match[1] ?? match[2];
- spans.push({ start: expandSet(text.slice(0, match.index)).length, length: trClass(name).length });
- }
- return spans;
-}
-
-function pushTrRange(out, startCh, endCh) {
- const start = startCh.charCodeAt(0);
- const end = endCh.charCodeAt(0);
- if (start > end) throw new UsageError(`range-endpoints of '${startCh}-${endCh}' are in reverse collating sequence order`);
- for (let c = start; c <= end; c++) out.push(String.fromCharCode(c));
-}
-
-function parseTrRepeatCount(text) {
- let count;
- if (/^0[0-9]/.test(text)) {
- if (!/^[0-7]+$/.test(text)) throw new UsageError(`invalid repeat count ${trRepeatCountDiagnostic(text)} in [c*n] construct`);
- count = Number.parseInt(text, 8);
- } else {
- count = Number(text);
- }
- if (!Number.isSafeInteger(count) || count < 0) throw new UsageError(`invalid repeat count ${trRepeatCountDiagnostic(text)} in [c*n] construct`);
- return count;
-}
-
-function trRepeatCountDiagnostic(text) {
- return localeQuotedDiagnostic(lsEscapedName(text, { escapeDouble: false }).replaceAll("\\", "\\\\"));
-}
-
-function parseTrEscape(spec, index) {
- const simple = { n: "\n", r: "\r", t: "\t", b: "\b", f: "\f", v: "\v", "\\": "\\" };
- const ch = spec[index];
- if (simple[ch] != null) return [simple[ch], 1];
- const oct = spec.slice(index).match(/^[0-7]{1,3}/)?.[0];
- if (oct) {
- if (oct.length === 3 && Number.parseInt(oct, 8) > 0xff) {
- const prefix = oct.slice(0, 2);
- stderr(`tr: warning: the ambiguous octal escape \\${oct} is being\n\tinterpreted as the 2-byte sequence \\0${prefix}, ${oct[2]}\n`);
- return [String.fromCharCode(Number.parseInt(prefix, 8)), 2];
- }
- return [String.fromCharCode(Number.parseInt(oct, 8)), oct.length];
- }
- return [ch, 1];
-}
-
-function trClass(name) {
- const lower = "abcdefghijklmnopqrstuvwxyz";
- const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- const digit = "0123456789";
- const space = " \t\n\r\f\v";
- const punct = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
- const classes = {
- alnum: lower + upper + digit,
- alpha: lower + upper,
- blank: " \t",
- cntrl: Array.from({ length: 32 }, (_, i) => String.fromCharCode(i)).join("") + "\x7f",
- digit,
- graph: lower + upper + digit + punct,
- lower,
- print: lower + upper + digit + punct + " ",
- punct,
- space,
- upper,
- xdigit: digit + "abcdefABCDEF",
- };
- return [...(classes[name] ?? "")];
-}
-
-function trClassChecked(name) {
- const chars = trClass(name);
- if (!chars.length) throw new UsageError(`invalid character class '${name}'`);
- return chars;
-}
-
-async function nlCmd(args) {
- args = normalizeNlLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { b: "value", d: "value", f: "value", h: "value", i: "value", l: "value", n: "value", p: false, s: "value", v: "value", w: "value" }, long: { "body-numbering": "value", "section-delimiter": "value", "footer-numbering": "value", "header-numbering": "value", "line-increment": "value", "join-blank-lines": "value", "number-format": "value", "no-renumber": false, "number-separator": "value", "starting-line-number": "value", "number-width": "value", help: false, version: false } });
- const files = operands.length ? operands : ["-"];
- const body = opts.b ?? opts["body-numbering"] ?? "t";
- const header = opts.h ?? opts["header-numbering"] ?? "n";
- const footer = opts.f ?? opts["footer-numbering"] ?? "n";
- const format = opts.n ?? opts["number-format"] ?? "rn";
- validateNlNumberingStyle(body, "body");
- validateNlNumberingStyle(header, "header");
- validateNlNumberingStyle(footer, "footer");
- const bodyPattern = nlNumberingPattern(body);
- const headerPattern = nlNumberingPattern(header);
- const footerPattern = nlNumberingPattern(footer);
- validateNlNumberFormat(format);
- const width = parseNlWidth(opts.w ?? opts["number-width"] ?? "6");
- const sep = opts.s ?? opts["number-separator"] ?? "\t";
- const increment = parseNlBigInt(opts.i ?? opts["line-increment"] ?? "1", "invalid line number increment");
- const joinBlank = parseNlJoinBlank(opts.l ?? opts["join-blank-lines"] ?? 1);
- const start = parseNlBigInt(opts.v ?? opts["starting-line-number"] ?? "1", "invalid starting line number");
- const delimiter = normalizeNlDelimiter(opts.d ?? opts["section-delimiter"] ?? "\\:");
- let number = start;
- let blankRun = 0;
- let out = "";
- let status = 0;
- let currentSection = "body";
- const renderLine = (raw) => {
- const line = raw.replace(/\n$/, "");
- const section = nlSection(line, delimiter);
- if (section) {
- if (!(opts.p || opts["no-renumber"])) number = start;
- currentSection = section;
- blankRun = 0;
- return "\n";
- }
- const blank = raw === "\n";
- blankRun = blank ? blankRun + 1 : 0;
- const style = currentSection === "header" ? header : currentSection === "footer" ? footer : body;
- const pattern = currentSection === "header" ? headerPattern : currentSection === "footer" ? footerPattern : bodyPattern;
- const shouldNumber = shouldNumberNl(line, style, blank, blankRun, joinBlank, pattern);
- if (shouldNumber) {
- if (number > NlMax || number < NlMin) throw new InvocationError("line number overflow", 1, false);
- const rendered = `${formatNlNumber(number, width, format)}${sep}${raw}`;
- number += increment;
- return rendered;
- }
- return `${" ".repeat(width + sep.length)}${raw}`;
- };
- if (files.length === 1 && files[0] === "-") {
- readStdinRecords("\n", (line) => stdout(renderLine(`${line}\n`)));
- return 0;
- }
- for (const file of files) {
- let data;
- try {
- data = decodeSurrogateEscapedBytes(await readAll(file));
- } catch (error) {
- stderr(`nl: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- status = 1;
- continue;
- }
- const records = splitNlRecords(data);
- for (const raw of records) {
- out += renderLine(raw);
- }
- }
- stdout(out);
- return status;
-}
-
-const NlMax = 9223372036854775807n;
-const NlMin = -9223372036854775808n;
-
-function validateNlNumberingStyle(style, section) {
- if (nlNumberingStyleValid(style)) return;
- throw new UsageError(`invalid ${section} numbering style: ${localeQuotedEscapedDiagnostic(style)}`, true);
-}
-
-function nlNumberingStyleValid(style) {
- return style === "a" || style === "t" || style === "n" || String(style).startsWith("p");
-}
-
-function validateNlNumberFormat(format) {
- if (nlNumberFormatValid(format)) return;
- throw new UsageError(`invalid line numbering format: ${localeQuotedEscapedDiagnostic(format)}`, true);
-}
-
-function nlNumberFormatValid(format) {
- return format === "ln" || format === "rn" || format === "rz";
-}
-
-function nlNumberingPattern(style) {
- if (!String(style).startsWith("p")) return null;
- try {
- return new RegExp(tacRegexPattern(String(style).slice(1)));
- } catch {
- throw new UsageError("Invalid regular expression");
- }
-}
-
-function parseNlJoinBlank(value) {
- const text = String(value);
- if (/^-\d+$/.test(text)) throw new UsageError(`invalid line number of blank lines: ${localeQuotedEscapedDiagnostic(text)}: Numerical result out of range`);
- if (!/^\+?\d+$/.test(text)) throw new UsageError(`invalid line number of blank lines: ${localeQuotedEscapedDiagnostic(text)}`);
- const n = BigInt(text);
- if (n > NlMax) throw new UsageError(`invalid line number of blank lines: ${localeQuotedEscapedDiagnostic(text)}: Value too large for defined data type`);
- return Number(n);
-}
-
-function parseNlBigInt(value, message) {
- const text = String(value);
- if (!/^[+-]?\d+$/.test(text)) throw new UsageError(`${message}: ${localeQuotedEscapedDiagnostic(text)}`);
- const n = BigInt(text);
- if (n > NlMax || n < NlMin) throw new UsageError(`${message}: ${localeQuotedEscapedDiagnostic(text)}: Value too large for defined data type`);
- return n;
-}
-
-function parseNlWidth(value) {
- const text = String(value);
- if (!/^[+-]?\d+$/.test(text)) throw new UsageError(`invalid line number field width: ${localeQuotedEscapedDiagnostic(text)}`);
- const width = BigInt(text);
- if (width <= 0n) throw new UsageError(`invalid line number field width: ${localeQuotedEscapedDiagnostic(text)}: Numerical result out of range`);
- if (width > 2147483647n) throw new UsageError(`invalid line number field width: ${localeQuotedEscapedDiagnostic(text)}: Value too large for defined data type`);
- return Number(width);
-}
-
-function normalizeNlDelimiter(value) {
- if (value === "") return "";
- return value.length === 1 ? `${value}:` : value;
-}
-
-function nlSection(line, delimiter) {
- if (!delimiter) return null;
- if (nlDelimiterEquals(line, `${delimiter}${delimiter}${delimiter}`)) return "header";
- if (nlDelimiterEquals(line, `${delimiter}${delimiter}`)) return "body";
- if (nlDelimiterEquals(line, delimiter)) return "footer";
- return null;
-}
-
-function nlDelimiterEquals(line, marker) {
- if (line.length !== marker.length) return false;
- for (let i = 0; i < marker.length; i++) {
- if (line[i] === marker[i]) continue;
- const markerCode = marker.charCodeAt(i);
- const lineCode = line.charCodeAt(i);
- if (markerCode === 0xfffd && lineCode >= 0xdc80 && lineCode <= 0xdcff) continue;
- return false;
- }
- return true;
-}
-
-function splitNlRecords(data) {
- if (data === "") return [];
- const records = data.split(/(?<=\n)/).filter((raw) => raw !== "");
- const last = records[records.length - 1];
- if (last && !last.endsWith("\n")) records[records.length - 1] = `${last}\n`;
- return records;
-}
-
-function shouldNumberNl(line, style, blank, blankRun, joinBlank, pattern = null) {
- if (style === "n") return false;
- if (style === "a") return !blank || blankRun % joinBlank === 0;
- if (style === "t") return !blank;
- if (style.startsWith("p")) return pattern.test(line);
- return !blank;
-}
-
-function formatNlNumber(number, width, format) {
- const text = String(number);
- if (format === "ln") return text.padEnd(width);
- if (format === "rz") return text.padStart(width, "0");
- return text.padStart(width);
-}
-
-async function basenc(args) {
- args = normalizeBasencLongOptions(args);
- if (args.includes("--foobar")) throw new UsageError("foobar", true);
- const { opts, operands } = parseOptions(args, { short: { d: false, i: false, w: "value" }, long: { help: false, version: false, decode: false, "ignore-garbage": false, base64: false, base64url: false, base32: false, base32hex: false, base16: false, base2msbf: false, base2m: false, base2lsbf: false, base2l: false, z85: false, base58: false, wrap: "value" } });
- if (opts.help) {
- stdout("Usage: basenc ENCODING [OPTION]... [FILE]\n");
- return 0;
- }
- ensureSingleInputOperand(operands);
- const wrap = parseWrap(opts.w ?? opts.wrap ?? 76);
- const mode = basencSelectedMode(args);
- if (!mode) throw new UsageError("missing encoding type", true);
- const file = operands[0] ?? "-";
- if (!(opts.d || opts.decode) && file === "-" && mode !== "base58") {
- try {
- streamBasencEncode(mode, wrap);
- return 0;
- } catch (error) {
- if (error instanceof UsageError) throw error;
- stderr(`basenc: ${nodeErrorMessage(error)}\n`);
- return 1;
- }
- }
- let data;
- try {
- data = await readAll(file);
- } catch (error) {
- const message = error?.code === "EISDIR" ? "read error: Is a directory" : file === "-" ? nodeErrorMessage(error) : `${baseEncodingDiagnosticName(file)}: ${systemErrorMessage(error)}`;
- stderr(`basenc: ${message}\n`);
- return 1;
- }
- if (opts.d || opts.decode) {
- const rawText = new TextDecoder().decode(data);
- let text = rawText.replace(/\s+/g, "");
- const ignoreGarbage = opts.i || opts["ignore-garbage"];
- if (mode === "base16") stdout(decodeBase16(text, ignoreGarbage));
- else if (mode === "base32") {
- if (ignoreGarbage) text = text.replace(/[^A-Z2-7=]/g, "");
- stdout(base32Decode(text));
- } else if (mode === "base32hex") {
- if (ignoreGarbage) text = text.replace(/[^0-9A-V=]/gi, "");
- stdout(base32Decode(base32HexToBase32(text)));
- } else if (mode === "base2msbf" || mode === "base2lsbf") stdout(decodeBase2(text, ignoreGarbage, mode === "base2lsbf"));
- else if (mode === "z85") stdout(z85Decode(rawText, ignoreGarbage));
- else if (mode === "base58") stdout(base58Decode(rawText, ignoreGarbage));
- else {
- if (mode === "base64url" && !ignoreGarbage && /[+/]/.test(text)) throw new UsageError("invalid input");
- stdout(decodeBase64(text, ignoreGarbage, mode === "base64url"));
- }
- return 0;
- }
- if (mode === "base58" && data.length > 0 && data.every((byte) => byte === 0)) {
- writeRepeatedEncodedByte(49, data.length, wrap);
- return 0;
- }
- let encoded;
- if (mode === "base16") encoded = Buffer.from(data).toString("hex").toUpperCase();
- else if (mode === "base32") encoded = base32Encode(data);
- else if (mode === "base32hex") encoded = base32ToBase32Hex(base32Encode(data));
- else if (mode === "base2msbf") encoded = encodeBase2(data, false);
- else if (mode === "base2lsbf") encoded = encodeBase2(data, true);
- else if (mode === "z85") encoded = z85Encode(data);
- else if (mode === "base58") encoded = base58Encode(data);
- else {
- encoded = Buffer.from(data).toString("base64");
- if (mode === "base64url") encoded = encoded.replaceAll("+", "-").replaceAll("/", "_");
- }
- stdout(formatEncodedOutput(encoded, wrap));
- return 0;
-}
-
-function writeRepeatedEncodedByte(byte, count, wrap) {
- const output = Buffer.allocUnsafe(64 * 1024);
- let used = 0;
- let column = 0;
- const flush = () => {
- if (used) stdout(output.subarray(0, used));
- used = 0;
- };
- for (let index = 0; index < count; index++) {
- if (used >= output.length - 1) flush();
- output[used++] = byte;
- if (wrap && ++column === wrap) {
- output[used++] = 10;
- column = 0;
- }
- }
- if (wrap && column) output[used++] = 10;
- flush();
-}
-
-function streamBasencEncode(mode, wrap) {
- const output = Buffer.allocUnsafe(64 * 1024);
- let outputLength = 0;
- let column = 0;
- const flush = () => {
- if (outputLength) stdout(output.subarray(0, outputLength));
- outputLength = 0;
- };
- const emit = (code) => {
- if (outputLength > output.length - 2) flush();
- output[outputLength++] = code;
- if (wrap && ++column === wrap) {
- output[outputLength++] = 10;
- column = 0;
- }
- };
- const group = [];
- let bits = 0;
- let value = 0;
- let symbols = 0;
- const base32Alphabet = mode === "base32hex" ? "0123456789ABCDEFGHIJKLMNOPQRSTUV" : "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
- const base64Alphabet = mode === "base64url"
- ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
- : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- readStdinChunkViews((chunk) => {
- for (const byte of chunk) {
- if (mode === "base16") {
- const hex = "0123456789ABCDEF";
- emit(hex.charCodeAt(byte >>> 4));
- emit(hex.charCodeAt(byte & 15));
- } else if (mode === "base2msbf" || mode === "base2lsbf") {
- for (let bit = 0; bit < 8; bit++) {
- const shift = mode === "base2lsbf" ? bit : 7 - bit;
- emit(48 + ((byte >>> shift) & 1));
- }
- } else if (mode === "base32" || mode === "base32hex") {
- value = (value << 8) | byte;
- bits += 8;
- while (bits >= 5) {
- emit(base32Alphabet.charCodeAt((value >>> (bits - 5)) & 31));
- bits -= 5;
- symbols++;
- }
- } else if (mode === "z85") {
- group.push(byte);
- if (group.length === 4) {
- let z85Value = ((group[0] * 256 + group[1]) * 256 + group[2]) * 256 + group[3];
- const divisors = [52200625, 614125, 7225, 85, 1];
- for (const divisor of divisors) emit(Z85_ALPHABET.charCodeAt(Math.floor(z85Value / divisor) % 85));
- group.length = 0;
- }
- } else {
- group.push(byte);
- if (group.length === 3) {
- const triple = (group[0] << 16) | (group[1] << 8) | group[2];
- emit(base64Alphabet.charCodeAt((triple >>> 18) & 63));
- emit(base64Alphabet.charCodeAt((triple >>> 12) & 63));
- emit(base64Alphabet.charCodeAt((triple >>> 6) & 63));
- emit(base64Alphabet.charCodeAt(triple & 63));
- group.length = 0;
- }
- }
- }
- }, 8 * 1024);
- if (mode === "base32" || mode === "base32hex") {
- if (bits) {
- emit(base32Alphabet.charCodeAt((value << (5 - bits)) & 31));
- symbols++;
- }
- while (symbols % 8) {
- emit(61);
- symbols++;
- }
- } else if (mode === "z85") {
- if (group.length) {
- flush();
- throw new UsageError("invalid input (length must be multiple of 4 characters)");
- }
- } else if ((mode === "base64" || mode === "base64url") && group.length) {
- const triple = (group[0] << 16) | ((group[1] ?? 0) << 8);
- emit(base64Alphabet.charCodeAt((triple >>> 18) & 63));
- emit(base64Alphabet.charCodeAt((triple >>> 12) & 63));
- if (group.length === 2) {
- emit(base64Alphabet.charCodeAt((triple >>> 6) & 63));
- emit(61);
- } else {
- emit(61);
- emit(61);
- }
- }
- if (wrap && column) output[outputLength++] = 10;
- flush();
-}
-
-function basencSelectedMode(args) {
- const modes = new Set(["base64", "base64url", "base32", "base32hex", "base16", "base2msbf", "base2lsbf", "z85", "base58"]);
- let mode = null;
- for (const arg of args) {
- if (!arg.startsWith("--")) continue;
- const name = arg.slice(2).split("=", 1)[0];
- if (modes.has(name)) mode = name;
- }
- return mode;
-}
-
-function decodeBase16(text, ignoreGarbage = false) {
- let cleaned = text.replace(/\s+/g, "");
- if (ignoreGarbage) cleaned = cleaned.replace(/[^0-9a-fA-F]/g, "");
- const invalid = cleaned.search(/[^0-9a-fA-F]/);
- const usableLength = invalid === -1 ? cleaned.length : invalid;
- const evenLength = usableLength - (usableLength % 2);
- if (invalid !== -1 || usableLength % 2 !== 0) {
- if (evenLength > 0) stdout(Buffer.from(cleaned.slice(0, evenLength), "hex"));
- throw new UsageError("invalid input");
- }
- return Buffer.from(cleaned, "hex");
-}
-
-function base32Encode(data) {
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
- let bits = 0;
- let value = 0;
- let out = "";
- for (const byte of data) {
- value = (value << 8) | byte;
- bits += 8;
- while (bits >= 5) {
- out += alphabet[(value >>> (bits - 5)) & 31];
- bits -= 5;
- }
- }
- if (bits > 0) out += alphabet[(value << (5 - bits)) & 31];
- while (out.length % 8) out += "=";
- return out;
-}
-
-function base32Decode(text) {
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
- const decoded = decodeBase32Clean(text, alphabet);
- if (!decoded.valid) {
- if (decoded.bytes.length) stdout(decoded.bytes);
- throw new UsageError("invalid input");
- }
- return decoded.bytes;
-}
-
-function decodeBase32Clean(text, alphabet) {
- const chunks = [];
- let valid = true;
- let i = 0;
- while (i < text.length) {
- let start = i;
- while (i < text.length && text[i] !== "=") i++;
- const base = text.slice(start, i);
- let pads = "";
- while (i < text.length && text[i] === "=") pads += text[i++];
- if (base.length === 0 && pads.length > 0) {
- valid = false;
- break;
- }
- if (base.length === 0) continue;
- const segment = decodeBase32Segment(base, pads, alphabet);
- if (segment.bytes.length) chunks.push(segment.bytes);
- if (!segment.valid) {
- valid = false;
- break;
- }
- }
- return { bytes: Buffer.concat(chunks), valid };
-}
-
-function decodeBase32Segment(base, pads, alphabet) {
- let bits = 0;
- let value = 0;
- const out = [];
- for (const ch of base) {
- const idx = alphabet.indexOf(ch);
- if (idx === -1) {
- return { bytes: Uint8Array.from(out), valid: false };
- }
- value = (value << 5) | idx;
- bits += 5;
- if (bits >= 8) {
- out.push((value >>> (bits - 8)) & 255);
- bits -= 8;
- }
- }
- const padByRemainder = new Map([[0, 0], [2, 6], [4, 4], [5, 3], [7, 1]]);
- const expectedPads = padByRemainder.get(base.length % 8);
- let valid = expectedPads !== undefined;
- if (pads.length) valid &&= pads.length === expectedPads && (base.length + pads.length) % 8 === 0;
- valid &&= bits === 0 || (value & ((1 << bits) - 1)) === 0;
- return { bytes: Uint8Array.from(out), valid };
-}
-
-function base32ToBase32Hex(text) {
- const from = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
- const to = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
- return [...text].map((ch) => ch === "=" ? ch : to[from.indexOf(ch)]).join("");
-}
-
-function base32HexToBase32(text) {
- const from = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
- const to = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
- return [...text].map((ch) => ch === "=" ? ch : to[from.indexOf(ch)] ?? ch).join("");
-}
-
-function encodeBase2(data, leastSignificantFirst = false) {
- let out = "";
- for (const byte of data) {
- for (let bit = 0; bit < 8; bit++) {
- const shift = leastSignificantFirst ? bit : 7 - bit;
- out += (byte >>> shift) & 1 ? "1" : "0";
- }
- }
- return out;
-}
-
-function decodeBase2(text, ignoreGarbage = false, leastSignificantFirst = false) {
- const cleaned = ignoreGarbage ? text.replace(/[^01]/g, "") : text;
- const out = [];
- let value = 0;
- let bits = 0;
- for (const ch of cleaned) {
- if (ch !== "0" && ch !== "1") {
- if (out.length) stdout(Uint8Array.from(out));
- throw new UsageError("invalid input");
- }
- const bit = ch === "1" ? 1 : 0;
- value |= bit << (leastSignificantFirst ? bits : 7 - bits);
- bits++;
- if (bits === 8) {
- out.push(value);
- value = 0;
- bits = 0;
- }
- }
- if (bits !== 0) {
- if (out.length) stdout(Uint8Array.from(out));
- throw new UsageError("invalid input");
- }
- return Uint8Array.from(out);
-}
-
-const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
-
-function base58Encode(data) {
- let zeros = 0;
- while (zeros < data.length && data[zeros] === 0) zeros++;
- if (zeros === data.length) return "1".repeat(zeros);
- let n = 0n;
- for (const byte of data) n = (n << 8n) + BigInt(byte);
- let out = "";
- while (n > 0n) {
- const rem = Number(n % 58n);
- out = BASE58_ALPHABET[rem] + out;
- n /= 58n;
- }
- return "1".repeat(zeros) + out;
-}
-
-function base58Decode(text, ignoreGarbage = false) {
- let cleaned = text.replace(/\n/g, "");
- if (ignoreGarbage) cleaned = [...cleaned].filter((ch) => BASE58_ALPHABET.includes(ch)).join("");
- const invalid = [...cleaned].find((ch) => !BASE58_ALPHABET.includes(ch));
- if (invalid !== undefined) throw new UsageError("invalid input");
- let zeros = 0;
- while (zeros < cleaned.length && cleaned[zeros] === "1") zeros++;
- if (zeros === cleaned.length) return Buffer.alloc(zeros);
- let n = 0n;
- for (const ch of cleaned) n = n * 58n + BigInt(BASE58_ALPHABET.indexOf(ch));
- const bytes = [];
- while (n > 0n) {
- bytes.unshift(Number(n & 255n));
- n >>= 8n;
- }
- return Buffer.concat([Buffer.alloc(zeros), Buffer.from(bytes)]);
-}
-
-const Z85_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#";
-
-function z85Encode(data) {
- if (data.length % 4 !== 0) throw new UsageError("invalid input (length must be multiple of 4 characters)");
- let out = "";
- for (let i = 0; i < data.length; i += 4) {
- let value = ((data[i] * 256 + data[i + 1]) * 256 + data[i + 2]) * 256 + data[i + 3];
- const chars = Array(5);
- for (let j = 4; j >= 0; j--) {
- chars[j] = Z85_ALPHABET[value % 85];
- value = Math.floor(value / 85);
- }
- out += chars.join("");
- }
- return out;
-}
-
-function z85Decode(text, ignoreGarbage = false) {
- let cleaned = text.replace(/\n/g, "");
- if (ignoreGarbage) cleaned = [...cleaned].filter((ch) => Z85_ALPHABET.includes(ch)).join("");
- const out = [];
- for (let i = 0; i < cleaned.length; i += 5) {
- const chunk = cleaned.slice(i, i + 5);
- if (chunk.length < 5) {
- if (out.length) stdout(Uint8Array.from(out));
- throw new UsageError("invalid input");
- }
- let value = 0;
- for (const ch of chunk) {
- const digit = Z85_ALPHABET.indexOf(ch);
- if (digit === -1) {
- if (out.length) stdout(Uint8Array.from(out));
- throw new UsageError("invalid input");
- }
- value = value * 85 + digit;
- }
- if (value > 0xffffffff) {
- if (out.length) stdout(Uint8Array.from(out));
- throw new UsageError("invalid input");
- }
- out.push((value >>> 24) & 255, (value >>> 16) & 255, (value >>> 8) & 255, value & 255);
- }
- return Uint8Array.from(out);
-}
-
-async function dfCmd(args) {
- args = normalizeBlockSizeShort(args);
- args = normalizeDfLongOptions(args);
- args = normalizeDfOutputAlias(args);
- const outputValues = dfRepeatedOutputValues(args);
- const { opts, operands } = parseOptions(args, { short: { a: false, h: false, H: false, i: false, k: false, l: false, P: false, T: false, t: "value", x: "value", B: "value" }, long: { all: false, "human-readable": false, si: false, inodes: false, local: false, "block-size": "value", total: false, output: "optional-value", type: "value", "exclude-type": "value", "print-type": false, sync: false, "no-sync": false, portability: false, help: false, version: false } });
- const rawOperands = rawOperandPlan("df", args, operands, {
- valueOptions: ["--block-size", "--type", "--exclude-type"],
- shortValueOptions: ["B", "t", "x"],
- });
- if (dfShouldSync(args)) libc.symbols.sync();
- // With file operands, df reports the file systems containing those files.
- // Without operands GNU df walks the mount table instead; treating that case
- // as `df .` loses every other mounted filesystem.
- const mountTableRequired = !operands.length
- || opts.a || opts.all || opts.l || opts.local
- || opts.t !== undefined || opts.type !== undefined
- || opts.x !== undefined || opts["exclude-type"] !== undefined;
- const mountTable = mountTableRequired ? await dfMountTable(opts.a || opts.all) : null;
- if (mountTableRequired && mountTable == null) return 1;
- const targets = operands.length ? (rawOperands ?? operands) : mountTable.map((mount) => mount.mount);
- applyBlockSizeSpecialMode(opts, dfBlockSizeValue(opts));
- const human = opts.h || opts["human-readable"] || opts.H || opts.si;
- if (opts.output !== undefined && (opts.i || opts.inodes || opts.P || opts.portability || opts.T || opts["print-type"])) {
- const conflict = opts.i || opts.inodes ? "-i" : opts.P || opts.portability ? "-P" : "-T";
- throw new UsageError(`options ${conflict} and --output are mutually exclusive`, true);
- }
- const outputFields = opts.output !== undefined ? dfOutputFields(outputValues.length ? outputValues : [opts.output]) : null;
- const blockSizeInfo = dfBlockSizeInfo(opts);
- const blockSize = human ? 1 : blockSizeInfo.size;
- const inodeMode = opts.i || opts.inodes;
- const printType = opts.T || opts["print-type"];
- const includeTypes = dfTypeSet(optionValues(opts.t).concat(optionValues(opts.type)));
- const excludeTypes = dfTypeSet(optionValues(opts.x).concat(optionValues(opts["exclude-type"])));
- const rows = [];
- let failed = false;
- for (let index = 0; index < targets.length; index++) {
- const target = targets[index];
- const mountInfo = operands.length ? await dfMountInfo(target) : mountTable[index];
- if (mountInfo.overMounted) {
- stderr(`df: cannot access ${shellEscapeLsName(pathDisplayName(target), true)}: over-mounted by another device\n`);
- failed = true;
- continue;
- }
- // Filter from mount metadata before calling statfs. Some namespace and
- // kernel API mounts are intentionally inaccessible to an unprivileged
- // caller; GNU df omits them in its default listing rather than turning a
- // successful bare `df` into a failure.
- if (includeTypes.size && !includeTypes.has(mountInfo.fstype)) continue;
- if (excludeTypes.has(mountInfo.fstype)) continue;
- if (!operands.length && !opts.a && !opts.all && dfIsPseudoFileSystem(mountInfo)) continue;
- if (opts.l || opts.local) {
- if (!dfIsLocalFileSystem(mountInfo)) continue;
- }
- let fs;
- try {
- // Bun's statfs wrapper can satisfy this from runtime state without an
- // observable statfs(2). GNU df gathers each row with statfs, and in
- // particular --sync promises that sync(2) precedes that query.
- // Keep the native probe so the ordering and kernel-facing semantics are
- // preserved, while retaining Bun's portable result decoding below.
- const nativeStatfs = Buffer.alloc(120);
- libc.symbols.statfs(cstrPath(target), ptr(nativeStatfs));
- fs = await statfs(target);
- } catch (error) {
- stderr(`df: ${textInputDiagnosticName(target)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- continue;
- }
- const sizeTotal = Number(fs.blocks) * Number(fs.bsize);
- const sizeAvail = Number(fs.bavail) * Number(fs.bsize);
- const sizeUsed = sizeTotal - sizeAvail;
- const inodeTotal = Number(fs.files);
- const inodeAvail = Number(fs.ffree);
- const inodeUsed = inodeTotal - inodeAvail;
- rows.push({
- source: mountInfo.source,
- name: mountInfo.source,
- total: inodeMode ? inodeTotal : sizeTotal,
- used: inodeMode ? inodeUsed : sizeUsed,
- avail: inodeMode ? inodeAvail : sizeAvail,
- sizeTotal,
- sizeUsed,
- sizeAvail,
- inodeTotal,
- inodeUsed,
- inodeAvail,
- mount: mountInfo.mount,
- file: target,
- fstype: mountInfo.fstype,
- });
- }
- if (!rows.length && !failed) {
- stderr("df: no file systems processed\n");
- return 1;
- }
- if (opts.total) {
- if (rows.length) {
- rows.push({
- source: "total",
- name: "total",
- total: rows.reduce((sum, row) => sum + row.total, 0),
- used: rows.reduce((sum, row) => sum + row.used, 0),
- avail: rows.reduce((sum, row) => sum + row.avail, 0),
- sizeTotal: rows.reduce((sum, row) => sum + row.sizeTotal, 0),
- sizeUsed: rows.reduce((sum, row) => sum + row.sizeUsed, 0),
- sizeAvail: rows.reduce((sum, row) => sum + row.sizeAvail, 0),
- inodeTotal: rows.reduce((sum, row) => sum + row.inodeTotal, 0),
- inodeUsed: rows.reduce((sum, row) => sum + row.inodeUsed, 0),
- inodeAvail: rows.reduce((sum, row) => sum + row.inodeAvail, 0),
- mount: outputFields && !outputFields.includes("source") ? "total" : "-",
- file: "-",
- fstype: "-",
- });
- } else if (!failed) {
- stderr("df: no file systems processed\n");
- failed = true;
- }
- }
- if (!rows.length && failed) return 1;
- const show = (value) => human ? humanSize(value, (opts.H || opts.si) ? 1000 : 1024) : String(Math.ceil(value / (inodeMode ? 1 : blockSize)));
- if (outputFields) {
- const headers = outputFields.map((field) => dfFieldHeader(field, blockSizeInfo.label, human));
- const values = rows.map((row) => outputFields.map((field) => dfFieldValue(field, row, show)));
- const widths = headers.map((header, index) => Math.max(dfOutputFieldMinWidth(outputFields[index]), header.length, ...values.map((row) => row[index].length)));
- stdout(`${dfFormatOutputRow(headers, widths, outputFields)}\n`);
- for (const row of values) stdout(`${dfFormatOutputRow(row, widths, outputFields)}\n`);
- return failed ? 1 : 0;
- }
- stdout(inodeMode
- ? `Filesystem ${printType ? "Type " : ""} Inodes IUsed IFree IUse% Mounted on\n`
- : dfDefaultHeader({ blockSizeLabel: blockSizeInfo.label, human, portability: opts.P || opts.portability, printType }));
- for (const row of rows) {
- const pct = row.total ? Math.ceil((row.used / row.total) * 100) : 0;
- const name = dfSanitizeDisplayField(row.name);
- const mount = dfSanitizeDisplayField(row.mount);
- stdout(`${name.padEnd(14)} ${printType ? `${row.fstype.padEnd(5)} ` : ""}${show(row.total).padStart(9)} ${show(row.used).padStart(8)} ${show(row.avail).padStart(9)} ${String(pct).padStart(3)}% ${mount}\n`);
- }
- return failed ? 1 : 0;
-}
-
-function dfSanitizeDisplayField(value) {
- return String(value).replace(/[\x00-\x1f\x7f]/g, "?");
-}
-
-function dfShouldSync(args) {
- // GNU option processing is order-sensitive here: --no-sync can override
- // an earlier --sync, and vice versa.
- let enabled = false;
- for (const arg of args) {
- if (arg === "--") break;
- if (arg === "--sync") enabled = true;
- else if (arg === "--no-sync") enabled = false;
- }
- return enabled;
-}
-
-function dfTypeSet(values) {
- return new Set(values.flatMap((value) => String(value).split(",")));
-}
-
-function normalizeDfLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeDfLongOption(arg));
- }
- return out;
-}
-
-function normalizeDfLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, DF_LONG_OPTIONS);
-}
-
-function dfBlockSizeInfo(opts) {
- if (opts.k) return { size: 1024, label: "1K-blocks" };
- const shortOption = opts.B !== undefined;
- const explicit = opts.B !== undefined || opts["block-size"] !== undefined;
- const value = explicit ? shortOption ? opts.B : opts["block-size"] : dfBlockSizeEnvValue();
- const defaultSize = defaultGNUBlockSize();
- if (value == null) return { size: defaultSize, label: dfDefaultBlockSizeLabel(defaultSize) };
- try {
- if (!explicit) {
- const parsed = parseGNUBlockSizeEnvInfo(value, defaultSize);
- if (parsed.fallback === "default") return { size: parsed.size, label: dfDefaultBlockSizeLabel(parsed.size) };
- if (parsed.fallback === "numeric") return { size: parsed.size, label: `${parsed.size}B-blocks` };
- return { size: parsed.size, label: `${dfBlockSizeLabel(value, parsed.size)}-blocks` };
- }
- const size = parseGNUBlockSize(value);
- return { size, label: `${dfBlockSizeLabel(value, size)}-blocks` };
- } catch {
- throw new UsageError(gnuBlockSizeErrorMessage(shortOption ? "-B" : "--block-size", value));
- }
-}
-
-function dfDefaultBlockSizeLabel(size) {
- return size === 1024 ? "1K-blocks" : `${dfBlockSizeLabel(String(size), size)}-blocks`;
-}
-
-function dfBlockSizeLabel(value, size) {
- const text = String(value).replace(/^'/, "");
- if (text === "1" || size === 1 && /^\+?1$/.test(text)) return "1B";
- if (/^\+?\d+$/.test(text)) {
- const n = Number(text);
- if (n === 1000) return "1kB";
- if (n === 1_000_000) return "1MB";
- if (n === 1_000_000_000) return "1GB";
- return `${n}B`;
- }
- const scaled = text.match(/^\+?(\d+)([A-Za-z]+)$/);
- if (scaled) {
- const n = Number(scaled[1]);
- const suffix = scaled[2];
- const binary = { KiB: "K", MiB: "M", GiB: "G", TiB: "T", PiB: "P", EiB: "E", ZiB: "Z", YiB: "Y" };
- const decimal = { KB: "kB", kB: "kB", MB: "MB", mB: "MB", GB: "GB", gB: "GB", TB: "TB", tB: "TB", PB: "PB", EB: "EB", ZB: "ZB", YB: "YB" };
- if (binary[suffix]) return `${n}${binary[suffix]}`;
- if (decimal[suffix]) return `${n}${decimal[suffix]}`;
- }
- return text.replace(/^\+/, "");
-}
-
-async function dfMountInfo(target) {
- const targetPath = await dfRealPath(target);
- const entries = [];
- let best = null;
- let bestLength = -1;
- let text = "";
- try {
- text = dfReadMountInfoSync();
- } catch {}
- for (const line of text.split("\n")) {
- if (!line) continue;
- const separator = line.indexOf(" - ");
- if (separator === -1) continue;
- const before = line.slice(0, separator).split(" ");
- const after = line.slice(separator + 3).split(" ");
- const mount = dfDecodeMountInfoField(before[4] ?? "");
- const entry = { mount, fstype: dfDecodeMountInfoField(after[0] ?? "-"), source: dfDecodeMountInfoField(after[1] ?? "-") };
- entries.push(entry);
- if (!dfPathIsOnMount(targetPath, mount) || mount.length < bestLength) continue;
- best = entry;
- bestLength = mount.length;
- }
- const targetInfo = await stat(target).catch(() => null);
- if (targetInfo?.isBlockDevice()) {
- const deviceMount = entries.findLast((entry) => entry.source === targetPath);
- if (deviceMount) {
- const visibleMount = entries.findLast((entry) => entry.mount === deviceMount.mount);
- if (visibleMount !== deviceMount) return { ...deviceMount, overMounted: true };
- return deviceMount;
- }
- }
- return best ?? { mount: targetPath, fstype: "-", source: "-" };
-}
-
-async function dfRealPath(target) {
- if (!isBytePath(target)) return await realpath(target).catch(() => resolve(target));
- try {
- return pathDisplayName(await realpath(target, { encoding: "buffer" }));
- } catch {
- const raw = Buffer.from(target);
- if (raw[0] === 0x2f) return pathDisplayName(raw);
- return pathDisplayName(bufferPathJoin(Buffer.from(process.cwd()), raw));
- }
-}
-
-async function dfMountTable(preserveDuplicates = false) {
- let text;
- try {
- text = dfReadMountInfoSync();
- } catch {
- return null;
- }
- const mounts = new Map();
- const allMounts = [];
- for (const line of text.split("\n")) {
- if (!line) continue;
- const separator = line.indexOf(" - ");
- if (separator === -1) continue;
- const before = line.slice(0, separator).split(" ");
- const after = line.slice(separator + 3).split(" ");
- const mount = dfDecodeMountInfoField(before[4] ?? "");
- if (!mount) continue;
- // A mount namespace can stack mounts at the same mountpoint. The final
- // entry is the one visible to processes in the namespace.
- const entry = {
- mount,
- fstype: dfDecodeMountInfoField(after[0] ?? "-"),
- source: dfDecodeMountInfoField(after[1] ?? "-"),
- };
- allMounts.push(entry);
- mounts.set(mount, entry);
- }
- return preserveDuplicates ? allMounts : [...mounts.values()];
-}
-
-function dfReadMountInfoSync() {
- if (process.env.BNU_DF_MOUNTINFO_ERROR === "1") {
- const error = new Error("No such file or directory");
- error.code = "ENOENT";
- throw error;
- }
- const path = process.env.BNU_DF_MOUNTINFO_FILE || "/proc/self/mountinfo";
- return readFileSync(path).toString("latin1");
-}
-
-function dfIsPseudoFileSystem(mount) {
- // This is the same practical distinction made by GNU df's default output:
- // kernel API and namespace mounts are only shown with --all.
- return new Set([
- "autofs", "binfmt_misc", "bpf", "cgroup", "cgroup2", "configfs", "debugfs", "devpts",
- "fusectl", "hugetlbfs", "mqueue", "proc", "pstore",
- "fuse.portal", "rootfs", "rpc_pipefs", "securityfs", "sysfs", "tracefs",
- ]).has(mount.fstype);
-}
-
-function dfIsLocalFileSystem(mount) {
- return !new Set(["9p", "afs", "cifs", "coda", "fuse.sshfs", "ncp", "nfs", "nfs4", "smbfs"]).has(mount.fstype);
-}
-
-function dfDecodeMountInfoField(field) {
- const input = Buffer.from(String(field), "latin1");
- const output = [];
- for (let index = 0; index < input.length; index++) {
- if (input[index] === 0x5c && index + 3 < input.length
- && input[index + 1] >= 0x30 && input[index + 1] <= 0x37
- && input[index + 2] >= 0x30 && input[index + 2] <= 0x37
- && input[index + 3] >= 0x30 && input[index + 3] <= 0x37) {
- output.push(Number.parseInt(input.subarray(index + 1, index + 4).toString("ascii"), 8));
- index += 3;
- } else {
- output.push(input[index]);
- }
- }
- return decodeUtf8SurrogateEscaped(Buffer.from(output));
-}
-
-function dfPathIsOnMount(path, mount) {
- if (mount === "/") return path.startsWith("/");
- return path === mount || path.startsWith(`${mount.replace(/\/+$/, "")}/`);
-}
-
-function normalizeBlockSizeShort(args) {
- return args.flatMap((arg) => /^-B.+/.test(arg) ? ["-B", arg.slice(2)] : [arg]);
-}
-
-function normalizeDfOutputAlias(args) {
- return args.map((arg) => normalizeDfOutputOption(arg) ?? arg);
-}
-
-function normalizeDfOutputOption(arg) {
- if (!arg.startsWith("--")) return null;
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name || !"output".startsWith(name)) return null;
- return eq === -1 ? "--output" : `--output=${body.slice(eq + 1)}`;
-}
-
-const DF_DEFAULT_OUTPUT_FIELDS = ["source", "fstype", "itotal", "iused", "iavail", "ipcent", "size", "used", "avail", "pcent", "file", "target"];
-
-function dfRepeatedOutputValues(args) {
- const values = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--output") {
- values.push(true);
- } else if (arg.startsWith("--output=")) {
- values.push(arg.slice("--output=".length));
- }
- }
- return values;
-}
-
-function dfOutputFields(values) {
- const fields = values.some((value) => value === true)
- ? DF_DEFAULT_OUTPUT_FIELDS
- : values.flatMap((value) => String(value).split(","));
- const seen = new Set();
- for (const field of fields) {
- if (!DF_DEFAULT_OUTPUT_FIELDS.includes(field)) throw new UsageError(`option --output: field ${localeQuotedEscapedDiagnostic(field)} unknown`, true);
- if (seen.has(field)) throw new UsageError(`option --output: field ${localeQuotedEscapedDiagnostic(field)} used more than once`, true);
- seen.add(field);
- }
- return fields;
-}
-
-function dfDefaultHeader({ blockSizeLabel, human, portability, printType }) {
- if (human) return `Filesystem ${printType ? "Type " : ""} Size Used Avail Use% Mounted on\n`;
- if (portability) return `Filesystem ${printType ? "Type " : ""}1024-blocks Used Available Capacity Mounted on\n`;
- return `Filesystem ${printType ? "Type " : ""}${blockSizeLabel.padStart(9)} Used Available Use% Mounted on\n`;
-}
-
-function dfFieldHeader(field, blockSizeLabel, human) {
- return ({
- source: "Filesystem",
- fstype: "Type",
- itotal: "Inodes",
- iused: "IUsed",
- iavail: "IFree",
- ipcent: "IUse%",
- size: human ? "Size" : blockSizeLabel,
- used: "Used",
- avail: "Avail",
- pcent: "Use%",
- file: "File",
- target: "Mounted on",
- })[field];
-}
-
-function dfFieldValue(field, row, show) {
- const pcent = row.sizeTotal ? `${Math.ceil((row.sizeUsed / row.sizeTotal) * 100)}%` : "0%";
- const ipcent = row.inodeTotal ? `${Math.ceil((row.inodeUsed / row.inodeTotal) * 100)}%` : "0%";
- return ({
- source: row.source,
- fstype: row.fstype,
- itotal: String(row.inodeTotal),
- iused: String(row.inodeUsed),
- iavail: String(row.inodeAvail),
- ipcent,
- size: show(row.sizeTotal),
- used: show(row.sizeUsed),
- avail: show(row.sizeAvail),
- pcent,
- file: row.file,
- target: row.mount,
- })[field];
-}
-
-function dfOutputFieldMinWidth(field) {
- return field === "source" ? 14 : 0;
-}
-
-function dfFormatOutputRow(values, widths, fields) {
- const leftAligned = new Set(["source", "fstype", "file", "target"]);
- return values.map((value, index) => {
- if (leftAligned.has(fields[index])) return index === values.length - 1 ? value : value.padEnd(widths[index]);
- return value.padStart(widths[index]);
- }).join(" ");
-}
-
-async function exprCmd(args) {
- const rawArgs = rawCommandArgs("expr");
- if (rawArgs?.length === args.length) args = rawArgs.map(decodeExprArgument);
- if (args[0] === "--") args = args.slice(1);
- if (!args.length) throw new InvocationError("missing operand", 2);
- const parser = new ExprParser(args);
- const result = parser.parse();
- stdout(`${formatExprValue(result)}\n`);
- return exprTruthy(result) ? 0 : 1;
-}
-
-function decodeExprArgument(bytes) {
- if (isUtf8Locale()) return decodeSurrogateEscapedBytes(bytes);
- let text = "";
- for (const byte of bytes) text += byte < 0x80 ? String.fromCharCode(byte) : String.fromCharCode(0xdc00 + byte);
- return text;
-}
-
-class ExprParser {
- constructor(tokens) {
- this.tokens = tokens;
- this.index = 0;
- }
-
- parse() {
- const value = this.parseOr();
- if (this.peek() != null) throw new InvocationError(`syntax error: unexpected argument ${localeQuotedDiagnostic(this.peek())}`, 2, false);
- return value;
- }
-
- peek() {
- return this.tokens[this.index];
- }
-
- take() {
- return this.tokens[this.index++];
- }
-
- parseOr() {
- let left = this.parseAnd();
- while (this.peek() === "|") {
- const op = this.take();
- this.requireArgumentAfter(op);
- if (exprTruthy(left)) {
- this.skipExpression(1);
- left = formatExprValue(left);
- } else {
- const right = this.parseAnd();
- left = exprTruthy(right) ? right : 0n;
- }
- }
- return left;
- }
-
- parseAnd() {
- let left = this.parseCompare();
- while (this.peek() === "&") {
- const op = this.take();
- this.requireArgumentAfter(op);
- if (!exprTruthy(left)) {
- this.skipExpression(2);
- left = 0n;
- } else {
- const right = this.parseCompare();
- left = exprTruthy(right) ? left : 0n;
- }
- }
- return left;
- }
-
- parseCompare() {
- let left = this.parseAdd();
- while (["=", "!=", "<", "<=", ">", ">="].includes(this.peek())) {
- const op = this.take();
- this.requireArgumentAfter(op);
- const right = this.parseAdd();
- left = exprCompare(left, right, op) ? 1n : 0n;
- }
- return left;
- }
-
- parseAdd() {
- let left = this.parseMul();
- while (this.peek() === "+" || this.peek() === "-") {
- const op = this.take();
- this.requireArgumentAfter(op);
- const right = this.parseMul();
- left = op === "+" ? exprInteger(left) + exprInteger(right) : exprInteger(left) - exprInteger(right);
- }
- return left;
- }
-
- parseMul() {
- let left = this.parseMatch();
- while (this.peek() === "*" || this.peek() === "/" || this.peek() === "%") {
- const op = this.take();
- this.requireArgumentAfter(op);
- const right = this.parseMatch();
- const a = exprInteger(left);
- const b = exprInteger(right);
- if ((op === "/" || op === "%") && b === 0n) throw new InvocationError("division by zero", 2, false);
- left = op === "*" ? a * b : op === "/" ? a / b : a % b;
- }
- return left;
- }
-
- parseMatch() {
- let left = this.parsePrimary();
- while (this.peek() === ":") {
- this.take();
- this.requireArgumentAfter(":");
- left = exprRegexMatch(formatExprValue(left), formatExprValue(this.parsePrimary()));
- }
- return left;
- }
-
- parsePrimary() {
- const token = this.take();
- if (token == null) throw new InvocationError("syntax error: missing argument", 2, false);
- if (token === "+") {
- this.requireArgumentAfter(token);
- return this.take();
- }
- if (token === "(") {
- const value = this.parseOr();
- if (this.peek() !== ")") {
- const previous = this.tokens[this.index - 1];
- throw new InvocationError(`syntax error: expecting ')' ${this.peek() == null ? `after ${localeQuotedDiagnostic(previous)}` : `instead of ${localeQuotedDiagnostic(this.peek())}`}`, 2, false);
- }
- this.take();
- return value;
- }
- if (token === "length") {
- this.requireArgumentAfter(token);
- return BigInt([...formatExprValue(this.parsePrimary())].length);
- }
- if (token === "index") {
- this.requireArgumentAfter(token);
- const text = formatExprValue(this.parsePrimary());
- this.requireArgumentAfter(text);
- return BigInt(exprIndex(text, formatExprValue(this.parsePrimary())));
- }
- if (token === "substr") {
- this.requireArgumentAfter(token);
- const text = formatExprValue(this.parsePrimary());
- this.requireArgumentAfter(text);
- const startValue = this.parsePrimary();
- this.requireArgumentAfter(formatExprValue(startValue));
- const start = exprSubstrInteger(startValue);
- const length = exprSubstrInteger(this.parsePrimary());
- if (start == null || length == null || start <= 0 || length <= 0) return "";
- return [...text].slice(start - 1, start - 1 + length).join("");
- }
- if (token === "match") {
- this.requireArgumentAfter(token);
- const text = formatExprValue(this.parsePrimary());
- this.requireArgumentAfter(text);
- return exprRegexMatch(text, formatExprValue(this.parsePrimary()));
- }
- if (token === ")") throw new InvocationError("syntax error: unexpected ')'", 2, false);
- return token;
- }
-
- requireArgumentAfter(token) {
- if (this.peek() == null) throw new InvocationError(`syntax error: missing argument after ${localeQuotedDiagnostic(token)}`, 2, false);
- }
-
- skipExpression(minPrecedence = 0) {
- let depth = 0;
- while (this.peek() != null) {
- const token = this.peek();
- if (token === "(") depth++;
- else if (token === ")") {
- if (depth === 0) break;
- depth--;
- } else if (depth === 0 && exprOperatorPrecedence(token) < minPrecedence) {
- break;
- }
- this.take();
- }
- }
-}
-
-function exprOperatorPrecedence(token) {
- return token === "|" ? 1 : token === "&" ? 2 : ["=", "!=", "<", "<=", ">", ">="].includes(token) ? 3 : ["+", "-"].includes(token) ? 4 : ["*", "/", "%"].includes(token) ? 5 : token === ":" ? 6 : 99;
-}
-
-function exprInteger(value) {
- const text = formatExprValue(value);
- if (!/^-?\d+$/.test(text)) throw new InvocationError("non-integer argument", 2, false);
- return BigInt(text);
-}
-
-function exprSubstrInteger(value) {
- const text = formatExprValue(value);
- return /^-?\d+$/.test(text) ? Number(BigInt(text)) : null;
-}
-
-function exprCompare(left, right, op) {
- const a = formatExprValue(left);
- const b = formatExprValue(right);
- const ai = /^-?\d+$/.test(a) ? BigInt(a) : null;
- const bi = /^-?\d+$/.test(b) ? BigInt(b) : null;
- const cmp = ai != null && bi != null ? (ai < bi ? -1 : ai > bi ? 1 : 0) : a < b ? -1 : a > b ? 1 : 0;
- return op === "=" ? cmp === 0 : op === "!=" ? cmp !== 0 : op === "<" ? cmp < 0 : op === "<=" ? cmp <= 0 : op === ">" ? cmp > 0 : cmp >= 0;
-}
-
-function exprTruthy(value) {
- const text = formatExprValue(value);
- return text !== "" && !/^-?0+$/.test(text);
-}
-
-function formatExprValue(value) {
- return typeof value === "bigint" ? String(value) : String(value);
-}
-
-function exprIndex(text, chars) {
- const haystack = [...text];
- const needles = new Set([...chars]);
- const index = haystack.findIndex((ch) => needles.has(ch));
- return index === -1 ? 0 : index + 1;
-}
-
-function exprRegexMatch(text, pattern) {
- if (isUtf8Locale() && /[\uDC80-\uDCFF]/u.test(text)) return pattern.includes("\\(") ? "" : 0;
- let regex;
- try {
- regex = new RegExp(`^(?:${exprBasicRegex(pattern)})`, "s");
- } catch (error) {
- if (error instanceof InvocationError) throw error;
- throw new InvocationError(regexErrorMessage(error), 2, false);
- }
- const match = String(text).match(regex);
- if (!match) return pattern.includes("\\(") ? "" : 0;
- return match.length > 1 ? match[1] ?? "" : match[0].length;
-}
-
-function exprBasicRegex(pattern) {
- let out = "";
- let groups = 0;
- let inBracket = false;
- for (let i = 0; i < pattern.length; i++) {
- const ch = pattern[i];
- if (ch !== "\\") {
- if (ch === "[") {
- inBracket = true;
- out += ch;
- continue;
- }
- if (ch === "]") {
- inBracket = false;
- out += ch;
- continue;
- }
- if (inBracket) {
- out += ch;
- continue;
- }
- if ("()+?|{}".includes(ch)) out += `\\${ch}`;
- else if (ch === "^" && i !== 0 && !out.endsWith("(")) out += "\\^";
- else if (ch === "$" && i !== pattern.length - 1 && pattern.slice(i + 1, i + 3) !== "\\)") out += "\\$";
- else if (ch === "*" && i === 0 && pattern[i + 1] === "*") {
- while (pattern[i + 1] === "*") i++;
- }
- else if (ch === "*" && (out === "" || out.endsWith("(") || out.endsWith("|") || out.endsWith("^"))) out += "\\*";
- else if (ch === "*" && pattern[i + 1] === "*") {
- out += "*";
- while (pattern[i + 1] === "*") i++;
- }
- else out += ch;
- continue;
- }
- const next = pattern[++i];
- if (next == null) throw new InvocationError("Trailing backslash", 2, false);
- else if (inBracket && next === "-") out += "\\\\-";
- else if (next === "(") {
- groups++;
- out += "(";
- } else if (next === ")") {
- if (groups === 0) throw new InvocationError("Unmatched ) or \\)", 2, false);
- groups--;
- out += ")";
- }
- else if (next === "{") {
- if (!exprCanApplyInterval(out)) {
- out += "\\{";
- } else {
- const parsed = parseExprInterval(pattern, i + 1);
- out += parsed.interval;
- i = parsed.end;
- }
- } else if (next === "}") out += "\\}";
- else if (next === "|") out += "|";
- else if ("+?".includes(next)) out += `\\${next}`;
- else out += `\\${next}`;
- }
- if (groups > 0) throw new InvocationError("Unmatched ( or \\(", 2, false);
- return normalizeExprQuantifiers(exprNormalizePosixClasses(out));
-}
-
-const EXPR_POSIX_CLASSES = {
- alnum: "A-Za-z0-9",
- alpha: "A-Za-z",
- blank: " \\t",
- cntrl: "\\x00-\\x1F\\x7F",
- digit: "0-9",
- graph: "\\x21-\\x7E",
- lower: "a-z",
- print: "\\x20-\\x7E",
- punct: "!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~",
- space: " \\t\\n\\r\\f\\v",
- upper: "A-Z",
- xdigit: "A-Fa-f0-9",
-};
-
-function exprNormalizePosixClasses(pattern) {
- let out = "";
- for (let i = 0; i < pattern.length; i++) {
- if (pattern[i] !== "[") {
- out += pattern[i];
- continue;
- }
- const end = exprBracketEnd(pattern, i);
- if (end == null) {
- out += pattern.slice(i);
- break;
- }
- const body = pattern.slice(i + 1, end)
- .replace(/\[([=.])(.+?)\1\]/g, (_, _kind, value) => {
- if ([...value].length !== 1) throw new InvocationError("Invalid collation character", 2, false);
- return value.replace(/[\\\]\^-]/g, "\\$&");
- })
- .replace(/\[:([A-Za-z]+):\]/g, (_, name) => {
- const normalized = EXPR_POSIX_CLASSES[name];
- if (normalized == null) throw new InvocationError("Invalid character class name", 2, false);
- return normalized;
- });
- out += exprNormalizeBracketBody(body);
- i = end;
- }
- return out;
-}
-
-function exprNormalizeBracketBody(body) {
- const negated = body.startsWith("^");
- const prefix = negated ? "^" : "";
- const text = negated ? body.slice(1) : body;
- let normalized = "";
- for (let i = 0; i < text.length; i++) {
- if (i + 2 < text.length && text[i + 1] === "-" && text.charCodeAt(i) > text.charCodeAt(i + 2)) {
- i += 2;
- continue;
- }
- normalized += text[i];
- }
- if (normalized.startsWith("]")) normalized = `\\${normalized}`;
- if (normalized.endsWith("\\")) normalized += "\\";
- if (normalized === "") return negated ? "[\\s\\S]" : "[^\\s\\S]";
- return `[${prefix}${normalized}]`;
-}
-
-function exprBracketEnd(pattern, start) {
- for (let i = start + 1; i < pattern.length; i++) {
- if (i === start + 1 && pattern[i] === "]") continue;
- if (i === start + 2 && pattern[start + 1] === "^" && pattern[i] === "]") continue;
- if (pattern[i] === "[" && pattern[i + 1] === ":") {
- const end = pattern.indexOf(":]", i + 2);
- if (end !== -1) {
- i = end + 1;
- continue;
- }
- }
- if (pattern[i] === "[" && (pattern[i + 1] === "=" || pattern[i + 1] === ".")) {
- const end = pattern.indexOf(`${pattern[i + 1]}]`, i + 2);
- if (end !== -1) {
- i = end + 1;
- continue;
- }
- }
- if (pattern[i] === "]") return i;
- }
- return null;
-}
-
-function exprCanApplyInterval(out) {
- return out !== "" && !out.endsWith("(") && !out.endsWith("|") && !out.endsWith("^");
-}
-
-function parseExprInterval(pattern, start) {
- const end = pattern.indexOf("\\}", start);
- if (end === -1) throw new InvocationError("Unmatched \\{", 2, false);
- const body = pattern.slice(start, end);
- const match = body.match(/^(\d*)(?:,(\d*))?$/);
- if (!match || (match[1] === "" && match[2] == null)) throw new InvocationError("Invalid content of \\{\\}", 2, false);
- const min = match[1] === "" ? 0 : Number(match[1]);
- const max = match[2] == null || match[2] === "" ? null : Number(match[2]);
- if (min > 32767 || (max != null && max > 32767) || (max != null && min > max)) throw new InvocationError("Invalid content of \\{\\}", 2, false);
- const interval = match[2] == null
- ? `{${match[1]}}`
- : match[1] === "" && match[2] === ""
- ? "*"
- : `{${match[1] === "" ? "0" : match[1]},${match[2]}}`;
- return { interval, end: end + 1 };
-}
-
-function normalizeExprQuantifiers(pattern) {
- let out = pattern.replace(/\*\{1\}/g, "*");
- out = out.replace(/\{1\}\*/g, "*");
- out = out.replace(/\{0,1\}\*/g, "*");
- out = out.replace(/\{1\}\{1\}/g, "{1}");
- out = out.replace(/\*\*\*/g, "*").replace(/\*\*/g, "*");
- return out;
-}
-
-function regexErrorMessage(error) {
- const message = String(error?.message ?? "");
- if (/missing terminating \] for character class/i.test(message)) return "Invalid regular expression";
- if (/unterminated group|unmatched/i.test(message)) return "Unmatched ( or \\(";
- if (/lone quantifier brackets|numbers out of order|incomplete quantifier/i.test(message)) return "Invalid content of \\{\\}";
- return message.replace(/^Invalid regular expression: \/\^\(\?:.*?\)\/s: /, "Invalid regular expression: ");
-}
-
-async function fmtCmd(args) {
- const { opts, operands } = parseFmtOptions(args);
- const widthOption = opts.w ?? opts.width;
- const goalOption = opts.g ?? opts.goal;
- const parsedGoal = goalOption == null ? null : parseFmtWidth(goalOption, "goal", { max: null });
- const width = parseFmtWidth(widthOption ?? (parsedGoal === 0 ? "10" : "75"), "width");
- if (parsedGoal != null && parsedGoal > width) throw new UsageError(`invalid width: ${localeQuotedEscapedDiagnostic(goalOption)}: Value too large for defined data type`);
- const goal = parsedGoal != null ? parsedGoal : Math.max(1, Math.floor(width * 0.93));
- const files = operands.length ? operands : ["-"];
- if (files.length === 1 && fmtCanStream(opts) && prInputIsNonRegular(files[0])) {
- const file = files[0];
- let fd = 0;
- try {
- if (file !== "-") fd = openSync(file, "r");
- streamFmtDefaultFd(fd, width, goal, opts);
- return 0;
- } catch (error) {
- if (isWriteError(error)) throw error;
- const name = shellEscapeLsName(pathDisplayName(file), true);
- const message = error?.code === "EISDIR" ? `error reading ${name}: ${systemErrorMessage(error)}` : `cannot open ${name} for reading: ${systemErrorMessage(error)}`;
- stderr(`fmt: ${message}\n`);
- return 1;
- } finally {
- if (file !== "-" && fd !== 0) closeSync(fd);
- }
- }
- let out = "";
- let failed = false;
- for (const file of files) {
- let text;
- try {
- text = decodeSurrogateEscapedBytes(await readAll(file));
- } catch (error) {
- const name = shellEscapeLsName(pathDisplayName(file), true);
- const message = error?.code === "EISDIR" ? `error reading ${name}: ${systemErrorMessage(error)}` : `cannot open ${name} for reading: ${systemErrorMessage(error)}`;
- stderr(`fmt: ${message}\n`);
- failed = true;
- continue;
- }
- if (opts.p || opts.prefix) out += formatPrefixedText(text, opts.p ?? opts.prefix, width, goal, opts);
- else {
- const paragraphs = text.split(/\n[ \t]*\n/);
- out += paragraphs.map((p) => formatParagraph(p, width, goal, opts)).join("\n\n");
- }
- }
- if (out) stdout(out + (out.endsWith("\n") ? "" : "\n"));
- return failed ? 1 : 0;
-}
-
-function fmtCanStream(opts) {
- return !(opts.p || opts.prefix || opts.c || opts.s || opts.t || opts.u);
-}
-
-function streamFmtDefaultFd(fd, width, goal, opts) {
- const buffer = Buffer.allocUnsafe(64 * 1024);
- const initial = [];
- let initialLength = 0;
- const threshold = 32 * 1024;
- while (initialLength <= threshold) {
- const n = readSync(fd, buffer, 0, buffer.length, null);
- if (n === 0) {
- const text = decodeSurrogateEscapedBytes(Buffer.concat(initial, initialLength));
- const paragraphs = text.split(/\n[ \t]*\n/);
- const out = paragraphs.map((paragraph) => formatParagraph(paragraph, width, goal, opts)).join("\n\n");
- if (out) stdout(out + (out.endsWith("\n") ? "" : "\n"));
- return;
- }
- initial.push(Buffer.from(buffer.subarray(0, n)));
- initialLength += n;
- }
- const state = createFmtStreamingState(width, goal, opts);
- state.accept(decodeSurrogateEscapedBytes(Buffer.concat(initial, initialLength)));
- while (true) {
- const n = readSync(fd, buffer, 0, buffer.length, null);
- if (n === 0) break;
- state.accept(decodeSurrogateEscapedBytes(buffer.subarray(0, n)));
- }
- state.finish();
-}
-
-function createFmtStreamingState(width, goal, opts) {
- let pendingLine = "";
- let words = [];
- let indent = "";
- let paragraphStarted = false;
- let paragraphEmitted = false;
- let streamingLongWord = false;
- const contentWidth = () => Math.max(1, width - indent.length);
- const contentGoal = () => adjustedFmtGoal(goal, indent.length);
- const writeWrappedLine = (line) => {
- stdout(`${indent}${line}\n`);
- paragraphEmitted = true;
- };
- const consumeFirstWrappedLine = () => {
- const count = takeFmtStreamingLineWords(words, contentWidth(), contentGoal(), explicitFmtGoal(opts));
- writeWrappedLine(renderFmtLine(words.splice(0, count)));
- };
- const flushStableLines = () => {
- while (fmtLineLength(words) > contentWidth() * 10 && words.length > 1) consumeFirstWrappedLine();
- };
- const addLineWords = (line) => {
- if (!paragraphStarted) {
- indent = line.match(/^[ \t]*/)?.[0] ?? "";
- paragraphStarted = true;
- }
- words.push(...wordsForFmt(line, opts));
- flushStableLines();
- };
- const flushParagraph = () => {
- if (streamingLongWord) {
- stdout("\n");
- streamingLongWord = false;
- paragraphEmitted = true;
- }
- if (words.length) {
- const lines = wrapWords(words, contentWidth(), contentGoal(), explicitFmtGoal(opts)).split("\n");
- for (const line of lines) writeWrappedLine(line);
- words = [];
- }
- const hadContent = paragraphStarted || paragraphEmitted;
- indent = "";
- paragraphStarted = false;
- paragraphEmitted = false;
- return hadContent;
- };
- const beginLongWord = () => {
- if (words.length) {
- const lines = wrapWords(words, contentWidth(), contentGoal(), explicitFmtGoal(opts)).split("\n");
- for (const line of lines) writeWrappedLine(line);
- words = [];
- }
- if (!paragraphStarted) paragraphStarted = true;
- stdout(indent);
- stdout(pendingLine);
- pendingLine = "";
- streamingLongWord = true;
- };
- const processCompleteLine = (line) => {
- if (streamingLongWord) {
- if (line) stdout(line);
- stdout("\n");
- streamingLongWord = false;
- paragraphEmitted = true;
- return;
- }
- if (/^[ \t\r\f\v]*$/.test(line)) {
- flushParagraph();
- stdout("\n");
- return;
- }
- addLineWords(line);
- };
- return {
- accept(text) {
- let start = 0;
- for (let index = 0; index < text.length; index++) {
- if (text[index] !== "\n") continue;
- pendingLine += text.slice(start, index);
- processCompleteLine(pendingLine);
- pendingLine = "";
- start = index + 1;
- }
- pendingLine += text.slice(start);
- if (streamingLongWord) {
- stdout(pendingLine);
- pendingLine = "";
- } else if (pendingLine.length >= Math.max(64 * 1024, width * 4) && !/[ \t\r\f\v]/.test(pendingLine)) {
- beginLongWord();
- }
- },
- finish() {
- if (pendingLine || streamingLongWord) {
- if (streamingLongWord) {
- if (pendingLine) stdout(pendingLine);
- pendingLine = "";
- } else addLineWords(pendingLine);
- }
- flushParagraph();
- },
- };
-}
-
-function takeFmtStreamingLineWords(words, width, goal, explicitGoal) {
- if (explicitGoal) return takeFmtLineWords(words, 0, width, goal, true);
- let bestCount = 1;
- let bestCost = Infinity;
- let length = 0;
- for (let index = 0; index < words.length; index++) {
- length += fmtWordLength(words[index]);
- if (index) length += fmtJoinSpaces(words[index - 1]);
- if (index > 0 && length > width) break;
- const overflow = Math.max(0, length - width);
- const under = Math.max(0, goal - length);
- const overGoal = Math.max(0, length - goal);
- const cost = overflow * overflow * 10000 + under * under * 1.95 + overGoal * overGoal * 2;
- if (cost < bestCost || (cost === bestCost && length === width)) {
- bestCost = cost;
- bestCount = index + 1;
- }
- if (length > width) break;
- }
- return bestCount;
-}
-
-function parseFmtOptions(args) {
- args = normalizeFmtLongOptions(args);
- const opts = {};
- const operands = [];
- let sawOption = false;
- const longOptions = [
- ["width", "value", "w"],
- ["goal", "value", "g"],
- ["prefix", "value", "p"],
- ["crown-margin", "flag", "c"],
- ["split-only", "flag", "s"],
- ["tagged-paragraph", "flag", "t"],
- ["uniform-spacing", "flag", "u"],
- ["help", "flag", "help"],
- ["version", "flag", "version"],
- ];
- const resolveLong = (arg) => {
- if (!arg.startsWith("--") || arg === "--") return null;
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- const value = eq === -1 ? null : body.slice(eq + 1);
- const matches = longOptions.filter(([option]) => option.startsWith(name));
- if (matches.length !== 1) return null;
- const [option, kind, short] = matches[0];
- return { option, kind, short, value, hasInlineValue: eq !== -1 };
- };
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- if (option.startsWith("--")) throw new UsageError(`option '${option}' requires an argument`, true);
- throw new UsageError(`option requires an argument -- '${option.slice(1)}'`, true);
- };
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- operands.push(...args.slice(i + 1));
- break;
- }
- const long = resolveLong(arg);
- if (long) {
- if (long.kind === "value") {
- opts[long.short] = long.hasInlineValue ? long.value : requireValue(i, `--${long.option}`);
- if (!long.hasInlineValue) i++;
- } else {
- if (long.hasInlineValue) throw new UsageError(`option '--${long.option}' doesn't allow an argument`, true);
- opts[long.short] = true;
- }
- sawOption = true;
- continue;
- }
- if (/^-\d/.test(arg)) {
- if (sawOption) throw new UsageError(`invalid option -- ${arg[1]}; -WIDTH is recognized only when it is the first\noption; use -w N instead`, true);
- opts.w = arg.slice(1);
- sawOption = true;
- }
- else if (/^-w(?:[+-]|\d)/.test(arg)) {
- opts.w = arg.slice(2);
- sawOption = true;
- }
- else if (/^-g(?:[+-]|\d)/.test(arg)) {
- opts.g = arg.slice(2);
- sawOption = true;
- }
- else if (arg.startsWith("-p") && arg.length > 2) {
- opts.p = arg.slice(2);
- sawOption = true;
- }
- else if (arg === "-w" || arg === "--width") {
- opts.w = requireValue(i, arg);
- i++;
- sawOption = true;
- }
- else if (arg.startsWith("--width=")) {
- opts.width = arg.slice("--width=".length);
- sawOption = true;
- }
- else if (arg === "-g" || arg === "--goal") {
- opts.g = requireValue(i, arg);
- i++;
- sawOption = true;
- }
- else if (arg.startsWith("--goal=")) {
- opts.goal = arg.slice("--goal=".length);
- sawOption = true;
- }
- else if (arg === "-p" || arg === "--prefix") {
- opts.p = requireValue(i, arg);
- i++;
- sawOption = true;
- }
- else if (arg.startsWith("--prefix=")) {
- opts.prefix = arg.slice("--prefix=".length);
- sawOption = true;
- }
- else if (arg === "-c" || arg === "--crown-margin") {
- opts.c = true;
- sawOption = true;
- }
- else if (arg === "-s" || arg === "--split-only") {
- opts.s = true;
- sawOption = true;
- }
- else if (arg === "-t" || arg === "--tagged-paragraph") {
- opts.t = true;
- sawOption = true;
- }
- else if (arg === "-u" || arg === "--uniform-spacing") {
- opts.u = true;
- sawOption = true;
- }
- else if (arg.startsWith("-")) throw new UsageError(invalidOptionMessage(arg), true);
- else {
- operands.push(arg);
- sawOption = true;
- }
- }
- return { opts, operands };
-}
-
-function normalizeFmtLongOptions(args, reportAmbiguous = true) {
- const out = [];
- for (const arg of args) {
- if (arg === "--") {
- out.push(arg);
- continue;
- }
- if (!arg.startsWith("--") || arg === "--") {
- out.push(arg);
- continue;
- }
- out.push(normalizeFmtLongOption(arg, reportAmbiguous));
- }
- return out;
-}
-
-function normalizeFmtLongOption(arg, reportAmbiguous = true) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- const matches = FMT_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length === 1) return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
- if (matches.length > 1 && reportAmbiguous) {
- throw new UsageError(`option '${arg}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- return arg;
-}
-
-function normalizePtxLongOptions(args) {
- const out = [];
- const valueOptions = new Set(["break-file", "flag-truncation", "format", "ignore-file", "macro-name", "only-file", "sentence-regexp", "word-regexp", "width", "gap-size"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(arg, ...args.slice(i + 1));
- break;
- }
- if (!arg.startsWith("--")) {
- out.push(arg);
- continue;
- }
- const normalized = normalizeLongOptionByPrefix(arg, PTX_LONG_OPTIONS);
- out.push(normalized);
- const [name, inlineValue] = normalized.slice(2).split(/=(.*)/s, 2);
- if (valueOptions.has(name) && inlineValue == null && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-function parseFmtWidth(value, kind = "width", { max = 2500 } = {}) {
- const raw = String(value);
- if (!/^\+?\d+$/.test(raw)) throw new UsageError(`invalid width: ${localeQuotedEscapedDiagnostic(raw)}`);
- const width = Number(raw);
- if (!Number.isSafeInteger(width) || (max != null && width > max)) {
- const reason = kind === "goal" ? "Value too large for defined data type" : "Numerical result out of range";
- throw new UsageError(`invalid width: ${localeQuotedEscapedDiagnostic(raw)}: ${reason}`);
- }
- return width;
-}
-
-function formatParagraph(paragraph, width, goal, opts) {
- if (opts.s) return paragraph.split(/\n/).map((line) => formatIndentedFmtLine(line, width, goal, opts)).join("\n");
- const leadingNewlines = paragraph.match(/^\n*/)?.[0] ?? "";
- const body = paragraph.slice(leadingNewlines.length);
- if (opts.c) return leadingNewlines + formatCrownMarginParagraph(body, width, goal, opts);
- if (opts.t) return leadingNewlines + formatTaggedParagraph(body, width, goal, opts);
- const indent = body.match(/^[ \t]*/)?.[0] ?? "";
- return leadingNewlines + indent + wrapWords(wordsForFmt(body, opts), Math.max(1, width - indent.length), adjustedFmtGoal(goal, indent.length), explicitFmtGoal(opts)).split("\n").join(`\n${indent}`);
-}
-
-function formatCrownMarginParagraph(body, width, goal, opts) {
- const lines = body.split(/\n/);
- const firstIndent = lines[0]?.match(/^[ \t]*/)?.[0] ?? "";
- const restIndent = lines.find((line, index) => index > 0 && line.trim() !== "")?.match(/^[ \t]*/)?.[0] ?? firstIndent;
- const wrapped = wrapWords(wordsForFmt(body, opts), Math.max(1, width - restIndent.length), adjustedFmtGoal(goal, restIndent.length), explicitFmtGoal(opts)).split("\n");
- if (!wrapped.length) return firstIndent;
- return wrapped.map((line, index) => `${index === 0 ? firstIndent : restIndent}${line}`).join("\n");
-}
-
-function formatTaggedParagraph(body, width, goal, opts) {
- const lines = body.split(/\n/);
- const firstIndent = lines[0]?.match(/^[ \t]*/)?.[0] ?? "";
- const restIndent = lines.find((line, index) => index > 0 && line.trim() !== "")?.match(/^[ \t]*/)?.[0];
- if (restIndent != null && restIndent !== firstIndent) {
- return wrapFmtTaggedWords(wordsForFmt(body, opts), { firstIndent, restIndent, width, goal, explicitGoal: explicitFmtGoal(opts) });
- }
- return lines.map((line) => {
- if (line.trim() === "") return line;
- const indent = line.match(/^[ \t]*/)?.[0] ?? "";
- const words = wordsForFmt(line, opts);
- if (words.length <= 1) return `${indent}${renderFmtLine(words)}`;
- const rest = wrapWords(words.slice(1), width, goal, explicitFmtGoal(opts));
- return `${indent}${words[0].replaceAll("\0", "")}${rest ? `\n${rest}` : ""}`;
- }).join("\n");
-}
-
-function wrapFmtTaggedWords(words, { firstIndent, restIndent, width, goal, explicitGoal }) {
- if (!words.length) return firstIndent;
- const lines = [];
- let index = 0;
- let first = true;
- while (index < words.length) {
- const indent = first ? firstIndent : restIndent;
- const lineWidth = Math.max(1, width - indent.length);
- const lineGoal = adjustedFmtGoal(goal, indent.length);
- const take = takeFmtLineWords(words, index, lineWidth, lineGoal, explicitGoal);
- lines.push(`${indent}${renderFmtLine(words.slice(index, take))}`);
- index = take;
- first = false;
- }
- return lines.join("\n");
-}
-
-function takeFmtLineWords(words, start, width, goal, explicitGoal) {
- let take = start + 1;
- let len = fmtWordLength(words[start]);
- for (let i = start + 1; i < words.length; i++) {
- const nextLen = len + fmtJoinSpaces(words[i - 1]) + fmtWordLength(words[i]);
- if (nextLen > width) break;
- if (explicitGoal && goal > 0 && len >= goal) break;
- len = nextLen;
- take = i + 1;
- }
- return take;
-}
-
-function formatIndentedFmtLine(line, width, goal, opts) {
- const indent = line.match(/^[ \t]*/)?.[0] ?? "";
- return indent + wrapWords(wordsForFmt(line, opts), Math.max(1, width - indent.length), adjustedFmtGoal(goal, indent.length), explicitFmtGoal(opts)).split("\n").join(`\n${indent}`);
-}
-
-function explicitFmtGoal(opts) {
- return opts.g !== undefined || opts.goal !== undefined;
-}
-
-function adjustedFmtGoal(goal, indentLength) {
- return goal === 0 ? 0 : Math.max(1, goal - indentLength);
-}
-
-function wordsForFmt(text, opts) {
- let normalized = String(text).replace(/^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g, "");
- if (opts.u) normalized = normalized.replace(/[ \t\n\r\f\v]+/g, " ").replace(/([.!?]) (?=\S)/g, "$1 ");
- const words = normalized.split(/[ \t\n\r\f\v]+/).filter(Boolean);
- if (opts.u) return words;
- const sentenceBreaks = [...normalized.matchAll(/(\S+[.!?][)"']*) {2,}(?=\S)/g)].map((match) => match[1]);
- for (let i = 0; i < words.length; i++) {
- if (sentenceBreaks.includes(words[i])) words[i] += "\0";
- }
- return words;
-}
-
-function wrapWords(words, width, goal = width, explicitGoal = false) {
- if (!words.length) return "";
- if (explicitGoal && goal === 0) return wrapWordsZeroGoal(words, width);
- if (explicitGoal) return wrapWordsToGoal(words, width, goal);
- const n = words.length;
- const dp = Array(n + 1).fill(Infinity);
- const next = Array(n).fill(n);
- dp[n] = 0;
- for (let i = n - 1; i >= 0; i--) {
- let len = 0;
- for (let j = i; j < n; j++) {
- len += fmtWordLength(words[j]);
- if (j > i) len += fmtJoinSpaces(words[j - 1]);
- if (len > width && j > i) break;
- const overflow = Math.max(0, len - width);
- const under = Math.max(0, goal - len);
- const overGoal = Math.max(0, len - goal);
- const cost = overflow * overflow * 10000 + under * under * 1.95 + overGoal * overGoal * 2 + dp[j + 1];
- const currentLen = fmtLineLength(words.slice(i, next[i]));
- const prefer = cost < dp[i] || (cost === dp[i] && (len === width || (currentLen !== width && len < currentLen)));
- if (prefer) {
- dp[i] = cost;
- next[i] = j + 1;
- }
- if (len > width) break;
- }
- }
- const lines = [];
- for (let i = 0; i < n; i = next[i]) lines.push(renderFmtLine(words.slice(i, next[i])));
- return lines.join("\n");
-}
-
-function wrapWordsZeroGoal(words, width) {
- const totalLen = fmtLineLength(words);
- if (totalLen <= width) return renderFmtLine(words);
- const lines = [];
- let remaining = words.slice();
- while (remaining.length) {
- if (fmtLineLength(remaining) <= width) {
- lines.push(renderFmtLine(remaining));
- break;
- }
- let take = 1;
- if (fmtLineLength(remaining.slice(1)) > width) {
- let len = fmtWordLength(remaining[0]);
- const target = Math.max(1, Math.floor(width / 2));
- while (take < remaining.length - 1 && len < target) {
- len += fmtJoinSpaces(remaining[take - 1]) + fmtWordLength(remaining[take]);
- take++;
- }
- }
- lines.push(renderFmtLine(remaining.slice(0, take)));
- remaining = remaining.slice(take);
- }
- return lines.join("\n");
-}
-
-function wrapWordsToGoal(words, width, goal) {
- const lines = [];
- let line = [];
- let len = 0;
- for (const word of words) {
- const nextLen = line.length ? len + fmtJoinSpaces(line.at(-1)) + fmtWordLength(word) : fmtWordLength(word);
- const initial = /^[A-Z]\.\0?$/.test(word);
- if (line.length && (len >= goal || nextLen > width || (nextLen > goal && len >= goal - 1) || (initial && len >= goal - 3))) {
- lines.push(renderFmtLine(line));
- line = [word];
- len = fmtWordLength(word);
- } else {
- line.push(word);
- len = nextLen;
- }
- }
- if (line.length) lines.push(renderFmtLine(line));
- return lines.join("\n");
-}
-
-function fmtWordLength(word) {
- return word.replaceAll("\0", "").length;
-}
-
-function fmtJoinSpaces(previousWord) {
- return previousWord.endsWith("\0") ? 2 : 1;
-}
-
-function fmtLineLength(words) {
- if (!words.length) return 0;
- let len = 0;
- for (let i = 0; i < words.length; i++) {
- len += fmtWordLength(words[i]);
- if (i) len += fmtJoinSpaces(words[i - 1]);
- }
- return len;
-}
-
-function renderFmtLine(words) {
- let out = "";
- for (let i = 0; i < words.length; i++) {
- if (i) out += " ".repeat(fmtJoinSpaces(words[i - 1]));
- out += words[i].replaceAll("\0", "");
- }
- return out;
-}
-
-function formatPrefixedText(text, prefix, width, goal, opts) {
- const lines = text.split(/(?<=\n)/);
- let out = "";
- let group = [];
- const flush = () => {
- if (!group.length) return;
- const firstBody = group[0].body;
- const lead = firstBody.match(/^\s*/)?.[0] ?? "";
- const words = wordsForFmt(group.map(({ body }) => body).join(" "), opts);
- out += wrapWords(words, Math.max(1, width - prefix.length - lead.length), adjustedFmtGoal(goal, prefix.length + lead.length), explicitFmtGoal(opts))
- .split("\n")
- .map((part) => `${prefix}${lead}${part}`)
- .join("\n");
- if (group.at(-1).hadNewline) out += "\n";
- group = [];
- };
- for (const raw of lines) {
- if (raw === "") continue;
- const line = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
- if (!line.startsWith(prefix) || line === prefix) {
- flush();
- out += raw;
- continue;
- }
- group.push({ body: line.slice(prefix.length), hadNewline: raw.endsWith("\n") });
- }
- flush();
- return out;
-}
-
-async function killCmd(args) {
- if (countKillListOptions(args) > 1) throw new UsageError("multiple -l or -t options specified", true);
- args = normalizeKillArgs(args);
- const { opts, operands } = parseOptions(args, { short: { s: "value", n: "value", l: false, L: false, t: false }, long: { signal: "value", list: "optional-value", table: false } });
- const listCount = Number(Boolean(opts.l || opts.list)) + Number(Boolean(opts.L || opts.t || opts.table));
- if (listCount > 1) throw new UsageError("multiple -l or -t options specified", true);
- if (listCount && (opts.s || opts.n || opts.signal)) throw new UsageError("cannot combine signal with -l or -t", true);
- if (opts.L || opts.t || opts.table) return listSignals(true, operands);
- const listSignal = opts.list === true ? operands[0] : opts.list || (opts.l ? operands[0] : null);
- if (opts.l || opts.list) {
- return listSignals(false, listSignal ? [listSignal, ...operands.slice(1)] : operands);
- }
- const explicitSignal = opts.s != null || opts.n != null || opts.signal != null;
- let signal = opts.s ?? opts.n ?? opts.signal ?? "TERM";
- const pids = [];
- for (const arg of operands) {
- if (/^-[A-Za-z]+$/.test(arg) || (!explicitSignal && /^-\d+$/.test(arg))) signal = arg.slice(1);
- else pids.push(Number(arg));
- }
- if (!pids.length || pids.some((pid) => !Number.isInteger(pid))) throw new UsageError("missing or invalid process id");
- const normalized = normalizeKillSignal(signal);
- if (normalized === 0) {
- for (const pid of pids) {
- if (pid > 0) await access(`/proc/${pid}`);
- }
- return 0;
- }
- for (const pid of pids) {
- if (typeof normalized === "number" && normalized > 31) {
- if (libc.symbols.kill(pid, normalized) !== 0) throw new Error(`failed to send signal ${normalized} to ${pid}`);
- } else process.kill(pid, normalized);
- }
- return 0;
-}
-
-function normalizeKillArgs(args) {
- const normalized = [];
- let end = false;
- let sawSignalSelector = false;
- for (const arg of args) {
- if (end) normalized.push(arg);
- else if (arg === "--") {
- normalized.push(arg);
- end = true;
- }
- else if (arg === "-s" || arg === "-n") {
- normalized.push(arg);
- sawSignalSelector = true;
- }
- else if (/^-n.+/.test(arg)) {
- normalized.push("-n", arg.slice(2));
- sawSignalSelector = true;
- }
- else if (/^-s.+/.test(arg)) {
- normalized.push("-s", arg.slice(2));
- sawSignalSelector = true;
- }
- else if (!sawSignalSelector && /^-\d+$/.test(arg)) {
- normalized.push("-s", arg.slice(1));
- sawSignalSelector = true;
- }
- else if (sawSignalSelector && /^-\d+$/.test(arg)) {
- normalized.push("--", arg);
- end = true;
- }
- else if (/^-[A-Z][A-Za-z0-9]*$/.test(arg) && !["-L"].includes(arg)) {
- normalized.push("-s", arg.slice(1));
- sawSignalSelector = true;
- }
- else normalized.push(arg);
- }
- return normalized;
-}
-
-function countKillListOptions(args) {
- let count = 0;
- let end = false;
- for (const arg of args) {
- if (end) continue;
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg === "-l" || arg === "-t" || arg === "-L" || arg === "--list" || arg === "--table") count++;
- }
- return count;
-}
-
-const SIGNAL_NAMES = ["EXIT", "HUP", "INT", "QUIT", "ILL", "TRAP", "ABRT", "BUS", "FPE", "KILL", "USR1", "SEGV", "USR2", "PIPE", "ALRM", "TERM", "STKFLT", "CHLD", "CONT", "STOP", "TSTP", "TTIN", "TTOU", "URG", "XCPU", "XFSZ", "VTALRM", "PROF", "WINCH", "IO", "PWR", "SYS"];
-
-function normalizeKillSignal(signal) {
- const signum = signalNumberFromOperand(signal);
- if (signum < 0) throw new UsageError(`invalid signal '${signal}'`, true);
- if (signum >= 34 && signum <= 64) return signum;
- return signum === 0 ? 0 : `SIG${SIGNAL_NAMES[signum]}`;
-}
-
-function signalNumberFromOperand(signal) {
- const text = String(signal).replace(/^SIG/i, "").toUpperCase();
- const rtmin = text.match(/^RTMIN(?:\+(\d+))?$/);
- if (rtmin) {
- const signum = 34 + Number(rtmin[1] ?? 0);
- return signum <= 64 ? signum : -1;
- }
- const rtmax = text.match(/^RTMAX(?:-(\d+))?$/);
- if (rtmax) {
- const signum = 64 - Number(rtmax[1] ?? 0);
- return signum >= 34 ? signum : -1;
- }
- if (/^\d+$/.test(text)) {
- const status = Number(text);
- const signum = status >= 128 ? status & 127 : status;
- // Linux leaves 32 and 33 reserved by its threading implementation. GNU
- // kill accepts them while enumerating a numeric range, but has no name to
- // print for either one.
- return signum >= 0 && signum <= 64 ? signum : -1;
- }
- const index = SIGNAL_NAMES.indexOf(text);
- return index;
-}
-
-function listSignals(table, operands) {
- const values = operands.length
- ? operands
- : [...SIGNAL_NAMES.keys(), ...Array.from({ length: 31 }, (_, index) => index + 34)].map(String);
- let status = 0;
- for (const value of values) {
- const signum = signalNumberFromOperand(value);
- if (signum < 0) {
- status = 1;
- continue;
- }
- const name = signalDisplayName(signum);
- if (name == null) continue;
- if (table) stdout(`${String(signum).padStart(2)} ${name.padEnd(10)} ${signalDescription(signum)}\n`);
- else if (/^\d+$/.test(String(value))) stdout(`${name}\n`);
- else stdout(`${signum}\n`);
- }
- return status;
-}
-
-function signalDescription(signum) {
- if (signum === 0) return "Exit";
- if (signum >= 34 && signum <= 64) return signalDisplayName(signum);
- return SIGNAL_NAMES[signum];
-}
-
-function signalDisplayName(signum) {
- if (signum === 34) return "RTMIN";
- if (signum === 64) return "RTMAX";
- if (signum > 34 && signum <= 49) return `RTMIN+${signum - 34}`;
- if (signum >= 50 && signum < 64) return `RTMAX-${64 - signum}`;
- return SIGNAL_NAMES[signum];
-}
-
-function formatSignalTable() {
- const rows = [];
- for (let i = 0; i < SIGNAL_NAMES.length; i += 7) {
- rows.push(SIGNAL_NAMES.slice(i, i + 7).map((name, offset) => `${String(i + offset).padStart(2)} ${name.padEnd(7)}`).join("").trimEnd());
- }
- return `${rows.join("\n")}\n`;
-}
-
-async function niceCmd(args) {
- const parsed = parseNiceArgs(args);
- if (parsed.error) {
- stderr(`nice: ${parsed.error}\n`);
- if (parsed.showHelp) stderr("Try 'nice --help' for more information.\n");
- return 125;
- }
- if (!parsed.command.length) {
- if (parsed.adjusted) {
- stderr("nice: a command must be given with an adjustment\nTry 'nice --help' for more information.\n");
- return 125;
- }
- stdout(`${currentNiceValue()}\n`);
- return 0;
- }
- const nextNice = adjustedNiceValue(parsed.adjustment);
- if (libc.symbols.setpriority(0, 0, nextNice) !== 0) {
- if (!writeNiceWarning()) return 125;
- }
- try {
- if (await isKnownUnexecutableCommand(parsed.command[0])) throw Object.assign(new Error("Permission denied"), { code: "EACCES" });
- const proc = Bun.spawn(parsed.command, { env: process.env, stdin: "inherit", stdout: "inherit", stderr: "inherit" });
- return await proc.exited;
- } catch (error) {
- stderr(`nice: '${parsed.command[0]}': ${commandSpawnErrorMessage(error)}\n`);
- return error.code === "ENOENT" ? 127 : 126;
- }
-}
-
-function parseNiceArgs(args) {
- let adjusted = false;
- let adjustment = 10;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return { command: args.slice(i + 1), adjusted, adjustment };
- if (arg === "-n" || arg === "--adjustment") {
- if (i + 1 >= args.length) {
- return {
- error: arg.startsWith("--") ? `option '${arg}' requires an argument` : `option requires an argument -- '${arg.slice(1)}'`,
- showHelp: true,
- command: [],
- adjusted,
- };
- }
- const value = args[++i];
- if (!isNiceAdjustment(value)) return { error: `invalid adjustment ${localeQuotedEscapedDiagnostic(value ?? "")}`, command: [], adjusted };
- adjusted = true;
- adjustment = Number(value);
- continue;
- }
- if (arg.startsWith("--adjustment=")) {
- const value = arg.slice("--adjustment=".length);
- if (!isNiceAdjustment(value)) return { error: `invalid adjustment ${localeQuotedEscapedDiagnostic(value)}`, command: [], adjusted };
- adjusted = true;
- adjustment = Number(value);
- continue;
- }
- if (/^-n/.test(arg) && arg !== "-n") {
- const value = arg.slice(2);
- if (!isNiceAdjustment(value)) return { error: `invalid adjustment ${localeQuotedEscapedDiagnostic(value)}`, command: [], adjusted };
- adjusted = true;
- adjustment = Number(value);
- continue;
- }
- if (/^-[+-]?\d+$/.test(arg)) {
- adjusted = true;
- adjustment = Number(arg.slice(1));
- continue;
- }
- if (arg.startsWith("-")) return { error: invalidOptionMessage(arg), showHelp: true, command: [], adjusted };
- return { command: args.slice(i), adjusted, adjustment };
- }
- return { command: [], adjusted, adjustment };
-}
-
-function isNiceAdjustment(value) {
- return /^[+-]?\d+$/.test(String(value));
-}
-
-function currentNiceValue() {
- return libc.symbols.getpriority(0, 0);
-}
-
-function adjustedNiceValue(adjustment) {
- const current = currentNiceValue();
- const boundedAdjustment = Math.max(-39, Math.min(39, adjustment));
- return Math.max(-20, Math.min(19, current + boundedAdjustment));
-}
-
-function writeNiceWarning() {
- try {
- writeSync(2, "nice: cannot set niceness: Permission denied\n");
- return true;
- } catch {
- return false;
- }
-}
-
-async function isKnownUnexecutableCommand(command) {
- if (!(command === "." || command === ".." || command.includes("/"))) return false;
- try {
- const s = await stat(command);
- return s.isDirectory();
- } catch {
- return false;
- }
-}
-
-async function nohupCmd(args) {
- const internalFailure = process.env.POSIXLY_CORRECT ? 127 : 125;
- if (args[0] === "--") args = args.slice(1);
- if (!args.length) throw new InvocationError("missing operand", internalFailure);
- if (args[0].startsWith("-")) throw new InvocationError(invalidOptionMessage(args[0]));
- const ignoringInput = Boolean(process.stdin.isTTY);
- const redirectingStdout = Boolean(process.stdout.isTTY);
- const redirectingStderr = Boolean(process.stderr.isTTY);
- let stdinFd = null;
- let outputFd = null;
- let outputFile = null;
- try {
- if (ignoringInput) stdinFd = openSync("/dev/null", "w");
- if (redirectingStdout) {
- const opened = nohupOpenOutput();
- if (!opened) return internalFailure;
- ({ fd: outputFd, file: outputFile } = opened);
- }
- const advisory = outputFile
- ? `${ignoringInput ? "ignoring input and " : ""}appending output to ${localeQuotedEscapedDiagnostic(outputFile)}`
- : ignoringInput && !redirectingStderr
- ? "ignoring input"
- : ignoringInput && redirectingStderr
- ? "ignoring input and redirecting standard error to standard output"
- : redirectingStderr
- ? "redirecting standard error to standard output"
- : null;
- if (advisory != null && !nohupWriteAdvisory(advisory)) return internalFailure;
- await resolveEnvCommand(args[0], process.env, process.cwd());
- const previousHangup = libc.symbols.signal(1, SIG_IGN);
- let proc;
- try {
- proc = Bun.spawn(["/bin/sh", "-c", 'trap "" HUP\nexec "$@"', "nohup", ...args], {
- stdin: stdinFd ?? "inherit",
- stdout: outputFd ?? "inherit",
- stderr: redirectingStderr ? (outputFd ?? 1) : "inherit",
- });
- return await proc.exited;
- } finally {
- libc.symbols.signal(1, previousHangup);
- }
- } catch (error) {
- stderr(`nohup: failed to run command '${args[0]}': ${commandSpawnErrorMessage(error)}\n`);
- return error.code === "ENOENT" ? 127 : 126;
- } finally {
- if (stdinFd != null) closeSync(stdinFd);
- if (outputFd != null) closeSync(outputFd);
- }
-}
-
-function nohupOpenOutput() {
- const candidates = ["nohup.out"];
- if (process.env.HOME) candidates.push(join(process.env.HOME, "nohup.out"));
- const failures = [];
- const previousUmask = process.umask(0);
- try {
- for (const file of candidates) {
- try {
- return { fd: openSync(file, fsConstants.O_CREAT | fsConstants.O_WRONLY | fsConstants.O_APPEND, 0o600), file };
- } catch (error) {
- failures.push({ file, error });
- }
- }
- } finally {
- process.umask(previousUmask);
- }
- for (const { file, error } of failures) stderr(`nohup: failed to open ${localeQuotedEscapedDiagnostic(file)}: ${systemErrorMessage(error)}\n`);
- return null;
-}
-
-function nohupWriteAdvisory(message) {
- try {
- writeSync(2, `nohup: ${message}\n`);
- return true;
- } catch {
- return false;
- }
-}
-
-function parseHumanNumber(value, mode = "auto", suffix = "", unitSeparator = "") {
- return parseHumanNumberParts(value, mode, suffix, unitSeparator).value;
-}
-
-function parseHumanNumberParts(value, mode = "auto", suffix = "", unitSeparator = "") {
- let text = String(value);
- if (suffix && text.endsWith(suffix)) text = text.slice(0, -suffix.length);
- text = text.trimEnd();
- if (unitSeparator) {
- const unitMatch = text.match(/([kKMGTPEZYRQ]i?B?)$/);
- if (unitMatch) {
- const beforeUnit = text.slice(0, -unitMatch[1].length);
- if (beforeUnit.endsWith(unitSeparator) && !beforeUnit.slice(0, -unitSeparator.length).endsWith(unitSeparator)) text = beforeUnit.slice(0, -unitSeparator.length) + unitMatch[1];
- }
- }
- const match = text.match(/^([+-]?(?:\d+(?:\.\d+)?|\.\d+))([kKMGTPEZYRQ]?)(i?B?)$/);
- if (!match) throw new UsageError(numfmtNumberError(text, { fromMode: mode }));
- if (mode === "iec-i" && match[2] && !match[3].startsWith("i")) throw new UsageError(`missing 'i' suffix in input: ${localeQuotedDiagnostic(text)} (e.g Ki/Mi/Gi)`);
- if (match[3] && !match[2]) throw new UsageError(numfmtNumberError(text, { fromMode: mode }));
- if (match[3].includes("B")) throw new UsageError(`invalid suffix in input ${localeQuotedDiagnostic(numfmtDiagnosticValue(text))}: ${localeQuotedDiagnostic(numfmtDiagnosticValue(numfmtInvalidHumanSuffixPart(match[3], mode)))}`);
- if ((mode === "si" || mode === "iec") && match[3].startsWith("i")) throw new UsageError(`invalid suffix in input ${localeQuotedDiagnostic(numfmtDiagnosticValue(text))}: ${localeQuotedDiagnostic(numfmtDiagnosticValue(match[3]))}`);
- if (mode === "si" && match[2] && !["K", "k"].includes(match[2]) && match[2] !== match[2].toUpperCase()) throw new UsageError(numfmtNumberError(text, { fromMode: mode }));
- const base = mode === "iec" || mode === "iec-i" || match[3]?.toLowerCase().startsWith("i") ? 1024 : 1000;
- const exp = match[2] ? "KMGTPEZYRQ".indexOf(match[2].toUpperCase()) + 1 : 0;
- const decimals = match[1].includes(".") ? match[1].split(".")[1].length : 0;
- return { value: Number(match[1]) * (exp ? base ** exp : 1), decimals: exp ? 0 : decimals };
-}
-
-function numfmtInvalidHumanSuffixPart(suffix, mode) {
- if (suffix === "iB" && (mode === "auto" || mode === "iec-i")) return "B";
- return suffix;
-}
-
-async function numfmtCmd(args) {
- args = normalizeNumfmtArgs(args);
- if (countNumfmtFieldOptions(args) > 1) throw new UsageError("multiple field specifications");
- const parsedOptions = parseOptions(args, {
- short: { d: "value", z: false },
- long: {
- from: "value", to: "value", field: "value", header: "optional-value", invalid: "value", padding: "value", suffix: "value", delimiter: "value", "zero-terminated": false,
- "from-unit": "value", "to-unit": "value", round: "value", grouping: false, format: "value", "unit-separator": "value", "unit-sep": "value", debug: false, devdebug: false, help: false, version: false,
- },
- });
- const { opts, operands } = parsedOptions;
- validateNumfmtOptions(opts);
- if (operands.length) {
- if (opts.header != null && opts.debug) stderr("numfmt: --header ignored with command-line input\n");
- const rawResult = formatRawNumfmtOperands(opts, operands);
- if (rawResult != null) return rawResult;
- const sep = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- const result = formatNumfmtRecords(numfmtCommandLineRecords(opts, operands), opts, sep, true);
- stdout(result.text + (result.error ? "" : sep));
- if (result.error) throw new InvocationError(result.error, 2, false);
- return result.status;
- }
- const sep = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- if (opts.header == null) {
- let status = 0;
- let abortError = null;
- try {
- readStdinByteRecords(sep === "\0" ? 0 : 10, (bytes, hasSep) => {
- if (abortError) return;
- const record = decodeSurrogateEscapedBytes(bytes);
- const result = formatNumfmtRecords([record], opts, sep, true);
- stdout(result.text + (hasSep && !result.error ? sep : ""));
- if (result.error) abortError = result.error;
- status = Math.max(status, result.status);
- });
- } catch (error) {
- return fail("numfmt", `error reading input: ${systemErrorMessage(error)}`);
- }
- if (abortError) throw new InvocationError(abortError, 2, false);
- return status;
- }
- let input;
- try {
- input = decodeSurrogateEscapedBytes(await readAll("-"));
- } catch (error) {
- return fail("numfmt", `error reading input: ${systemErrorMessage(error)}`);
- }
- const terminated = input.endsWith(sep);
- const records = terminated ? input.slice(0, -sep.length).split(sep) : input === "" ? [] : input.split(sep);
- const header = opts.header === true ? 1 : Number(opts.header ?? 0);
- const result = formatNumfmtRecords(records, opts, sep, terminated, header);
- stdout(result.text + (records.length && terminated && !result.error ? sep : ""));
- if (result.error) throw new InvocationError(result.error, 2, false);
- return result.status;
-}
-
-function numfmtCommandLineRecords(opts, operands) {
- if ((opts.d ?? opts.delimiter) != null) return operands;
- return operands.map((operand) => String(operand).replace(/[\t\n\r\f\v]+/g, " "));
-}
-
-function formatRawNumfmtOperands(opts, operands) {
- const delimiter = opts.d ?? opts.delimiter;
- if (delimiter == null || delimiter === "" || isAsciiString(delimiter)) return null;
- const raw = rawNumfmtArgsFromProc();
- if (!raw) return null;
- const parsed = parseRawNumfmtArgs(raw);
- if (!parsed?.delimiter || parsed.operands.length !== operands.length) return null;
- const sep = opts.z || opts["zero-terminated"] ? Uint8Array.of(0) : Uint8Array.of(10);
- const output = [];
- let status = 0;
- let abortError = null;
- for (const record of parsed.operands) {
- const result = formatRawNumfmtRecord(record, parsed.delimiter, opts);
- output.push(result.bytes);
- if (!result.ok) {
- const invalid = opts.invalid ?? "abort";
- if (invalid === "fail" || invalid === "warn") {
- status = invalid === "warn" ? 0 : 2;
- stderr(`numfmt: ${result.error}\n`);
- } else if (invalid === "abort") {
- abortError = result.error;
- break;
- }
- }
- }
- stdout(joinBytesWithSeparator(output, sep, abortError == null ? sep : null));
- if (abortError) throw new InvocationError(abortError, 2, false);
- return status;
-}
-
-function isAsciiString(value) {
- return /^[\x00-\x7f]*$/.test(String(value));
-}
-
-function rawNumfmtArgsFromProc() {
- try {
- const parts = splitBytesOnByte(readFileSync("/proc/self/cmdline"), 0);
- if (parts.at(-1)?.length === 0) parts.pop();
- let commandIndex = -1;
- for (let i = 0; i < parts.length; i++) {
- if (new TextDecoder().decode(parts[i]) === "numfmt") commandIndex = i;
- }
- return commandIndex === -1 ? null : parts.slice(commandIndex + 1);
- } catch {
- return null;
- }
-}
-
-function parseRawNumfmtArgs(args) {
- const operands = [];
- let delimiter = null;
- const valueOptions = new Set(["--debug", "--delimiter", "--field", "--format", "--from", "--from-unit", "--header", "--invalid", "--padding", "--round", "--suffix", "--to", "--to-unit", "--unit-separator", "--unit-sep"]);
- for (let i = 0; i < args.length; i++) {
- const text = new TextDecoder().decode(args[i]);
- if (text === "--") {
- operands.push(...args.slice(i + 1));
- break;
- }
- if (text === "-d" || text === "--delimiter") {
- delimiter = args[++i];
- continue;
- }
- if (text.startsWith("-d") && text.length > 2) {
- delimiter = args[i].slice(2);
- continue;
- }
- if (text.startsWith("--delimiter=")) {
- delimiter = args[i].slice("--delimiter=".length);
- continue;
- }
- if (text.startsWith("--") && text.includes("=")) continue;
- if (valueOptions.has(text)) {
- i++;
- continue;
- }
- if (text.startsWith("-") && text !== "-") continue;
- operands.push(args[i]);
- }
- return { delimiter, operands };
-}
-
-function formatRawNumfmtRecord(record, delimiter, opts) {
- const fields = splitBytesByNeedle(record, delimiter);
- const selected = readNumfmtFieldRanges(opts.field ?? "1");
- const outputFields = [];
- let ok = true;
- let error;
- for (let i = 0; i < fields.length; i++) {
- if (!inRanges(i + 1, selected)) {
- outputFields.push(fields[i]);
- continue;
- }
- const text = new TextDecoder().decode(fields[i]);
- const result = formatNumfmtValue(text, opts);
- ok &&= result.ok;
- if (!result.ok && error == null) error = result.error;
- outputFields.push(result.ok ? enc.encode(result.text) : fields[i]);
- if (!result.ok && (opts.invalid ?? "abort") === "abort") break;
- }
- return { ok, error, bytes: joinBytesWithSeparator(outputFields, delimiter) };
-}
-
-function splitBytesOnByte(bytes, delimiter) {
- const parts = [];
- let start = 0;
- for (let i = 0; i < bytes.length; i++) {
- if (bytes[i] !== delimiter) continue;
- parts.push(bytes.slice(start, i));
- start = i + 1;
- }
- parts.push(bytes.slice(start));
- return parts;
-}
-
-function splitBytesByNeedle(bytes, needle) {
- if (!needle.length) return [bytes];
- const parts = [];
- let start = 0;
- for (let i = 0; i <= bytes.length - needle.length; i++) {
- let matches = true;
- for (let j = 0; j < needle.length; j++) {
- if (bytes[i + j] !== needle[j]) {
- matches = false;
- break;
- }
- }
- if (!matches) continue;
- parts.push(bytes.slice(start, i));
- i += needle.length - 1;
- start = i + 1;
- }
- parts.push(bytes.slice(start));
- return parts;
-}
-
-function joinBytesWithSeparator(parts, separator, trailing = null) {
- const extra = trailing?.length ?? 0;
- const total = parts.reduce((sum, part) => sum + part.length, 0) + separator.length * Math.max(0, parts.length - 1) + extra;
- const out = new Uint8Array(total);
- let offset = 0;
- for (let i = 0; i < parts.length; i++) {
- if (i > 0) {
- out.set(separator, offset);
- offset += separator.length;
- }
- out.set(parts[i], offset);
- offset += parts[i].length;
- }
- if (trailing) out.set(trailing, offset);
- return out;
-}
-
-function formatNumfmtRecords(records, opts, sep, terminated, header = 0) {
- let status = 0;
- let abortError = null;
- const out = [];
- for (let index = 0; index < records.length; index++) {
- const record = records[index];
- if (index < header) {
- out.push(record);
- continue;
- }
- const result = formatNumfmtRecord(record, opts);
- const invalid = opts.invalid ?? "abort";
- if (!result.ok && (invalid === "fail" || invalid === "warn")) {
- status = 2;
- stderr(`numfmt: ${result.error}\n`);
- }
- if (!result.ok && invalid === "abort") {
- abortError = result.error;
- out.push(result.text);
- break;
- }
- out.push(result.text);
- }
- const text = out.join(sep);
- if (status && opts.invalid === "fail" && opts.debug) stderr("numfmt: failed to convert some of the input numbers\n");
- if (opts.invalid === "warn") status = 0;
- return { status, text, error: abortError };
-}
-
-function countNumfmtFieldOptions(args) {
- let count = 0;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") break;
- if (arg === "--field") {
- count++;
- i++;
- } else if (arg.startsWith("--field=")) {
- count++;
- }
- }
- return count;
-}
-
-function normalizeNumfmtArgs(args) {
- return args.map((arg) => arg === "---debug" || arg === "--devdebug" ? "--devdebug" : normalizeNumfmtLongOption(arg));
-}
-
-function normalizeNumfmtLongOption(arg) {
- if (!arg.startsWith("--") || arg === "--") return arg;
- return normalizeLongOptionByPrefix(arg, NUMFMT_LONG_OPTIONS);
-}
-
-function validateNumfmtOptions(opts) {
- opts.from = parseNumfmtEnumOption(opts.from, "--from", ["none", "auto", "si", "iec", "iec-i"]);
- opts.to = parseNumfmtEnumOption(opts.to, "--to", ["none", "si", "iec", "iec-i"]);
- if (opts.grouping && opts.to) throw new UsageError("grouping cannot be combined with --to");
- const format = opts.format == null ? null : parseNumfmtFormat(opts.format);
- if ((opts.grouping || format?.grouping) && opts.to) throw new UsageError("grouping cannot be combined with --to");
- if (opts.grouping && opts.format) throw new UsageError("--grouping cannot be combined with --format");
- if (opts.grouping && opts.debug) stderr("numfmt: grouping has no effect in this locale\n");
- if (format?.grouping && opts.debug) stderr("numfmt: grouping has no effect in this locale\n");
- if (opts.debug && !opts.from && !opts.to && !opts["from-unit"] && !opts["to-unit"] && !opts.format && !opts.padding && !opts.suffix && !opts.header) stderr("numfmt: no conversion option specified\n");
- opts.invalid = parseNumfmtEnumOption(opts.invalid, "--invalid", ["abort", "fail", "warn", "ignore"]);
- opts.round = parseNumfmtEnumOption(opts.round, "--round", ["up", "down", "from-zero", "towards-zero", "nearest"]);
- if (opts.padding != null && (!/^[+-]?\d+$/.test(String(opts.padding)) || Number(opts.padding) === 0)) throw new UsageError(`invalid padding value ${localeQuotedDiagnostic(opts.padding)}`);
- const rawDelimiter = rawNumfmtDelimiter();
- if (opts.delimiter != null && opts.delimiter !== "" && !isSingleNumfmtDelimiter(opts.delimiter, rawDelimiter)) throw new UsageError("the delimiter must be a single character");
- if (opts.d != null && opts.d !== "" && !isSingleNumfmtDelimiter(opts.d, rawDelimiter)) throw new UsageError("the delimiter must be a single character");
- if (opts.header != null && opts.header !== true && (!/^\+?\d+$/.test(String(opts.header)) || Number(opts.header) < 1)) throw new UsageError(`invalid header value ${localeQuotedDiagnostic(opts.header)}`);
- if (opts.field != null) validateNumfmtFieldSpec(String(opts.field));
- if (opts["from-unit"] != null) parseNumfmtUnit(opts["from-unit"]);
- if (opts["to-unit"] != null) parseNumfmtUnit(opts["to-unit"]);
- if (opts.format != null) parseNumfmtFormat(opts.format);
-}
-
-function validateNumfmtMetaOptionValue(name, value) {
- if (value === undefined) return;
- if (name === "from") validateNumfmtScaleOption(value, "--from", ["none", "auto", "si", "iec", "iec-i"]);
- else if (name === "to") validateNumfmtScaleOption(value, "--to", ["none", "si", "iec", "iec-i"]);
- else if (name === "invalid") validateNumfmtScaleOption(value, "--invalid", ["abort", "fail", "warn", "ignore"]);
- else if (name === "round") validateNumfmtScaleOption(value, "--round", ["up", "down", "from-zero", "towards-zero", "nearest"]);
- else if (name === "field") validateNumfmtFieldSpec(String(value));
- else if (name === "padding" && (!/^[+-]?\d+$/.test(String(value)) || Number(value) === 0)) throw new UsageError(`invalid padding value ${localeQuotedDiagnostic(value)}`);
- else if (name === "delimiter" && value !== "" && !isSingleNumfmtDelimiter(value, rawNumfmtDelimiter())) throw new UsageError("the delimiter must be a single character");
- else if (name === "from-unit" || name === "to-unit") parseNumfmtUnit(value);
-}
-
-function validateNumfmtScaleOption(value, option, valid) {
- parseNumfmtEnumOption(value, option, valid);
-}
-
-function parseNumfmtEnumOption(value, option, valid) {
- if (value == null) return undefined;
- const text = String(value);
- if (valid.includes(text)) return text;
- const matches = valid.filter((arg) => arg.startsWith(text));
- if (matches.length === 1 && text !== "") return matches[0];
- const kind = text === "" || matches.length > 1 ? "ambiguous" : "invalid";
- throw new UsageError(numfmtScaleOptionMessage(kind, value, option, valid), true);
-}
-
-function numfmtScaleOptionMessage(kind, value, option, valid) {
- return `${kind} argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic(option)}\nValid arguments are:\n${valid.map((arg) => ` - ${localeQuotedDiagnostic(arg)}`).join("\n")}`;
-}
-
-function isSingleNumfmtDelimiter(value, rawDelimiter = null) {
- const text = String(value);
- if (rawDelimiter != null && isGb18030Locale()) return gb18030Units(rawDelimiter).length === 1;
- if (text.includes("\ufffd") && rawDelimiter != null) return rawDelimiter.length === 1;
- const singleByteLocale = /^(C|POSIX)$/.test(process.env.LC_ALL ?? process.env.LC_CTYPE ?? process.env.LANG ?? "");
- if (singleByteLocale) return enc.encode(text).length === 1;
- if ([...text].length === 1) return true;
- return text.includes("\ufffd");
-}
-
-function rawNumfmtDelimiter() {
- const raw = rawNumfmtArgsFromProc();
- if (!raw) return null;
- return parseRawNumfmtArgs(raw).delimiter;
-}
-
-function validateNumfmtFieldSpec(spec) {
- if (String(spec).startsWith("--")) throw new UsageError("invalid field range", true);
- for (const part of numfmtFieldSpecParts(spec)) {
- if (part === "-") continue;
- const invalid = part.search(/[^0-9-]/);
- if (invalid !== -1) throw new UsageError(`invalid field value ${localeQuotedDiagnostic(part.slice(invalid))}`, true);
- if (/^-?[A-Za-z]/.test(part)) throw new UsageError(`invalid field value ${localeQuotedDiagnostic(part.replace(/^-/, ""))}`, true);
- }
- readNumfmtFieldRanges(spec);
-}
-
-function numfmtFieldSpecParts(spec) {
- const parts = String(spec).split(/[,\s]/);
- if (parts.some((part) => part === "")) throw new UsageError("fields are numbered from 1", true);
- return parts;
-}
-
-function readNumfmtFieldRanges(spec) {
- const ranges = [];
- for (const part of numfmtFieldSpecParts(spec)) {
- if (part === "-") {
- ranges.push([1, Infinity]);
- continue;
- }
- const match = part.match(/^(\d*)-?(\d*)$/);
- if (!match || (!match[1] && !match[2])) throw new UsageError("invalid field range", true);
- const start = match[1] ? parseNumfmtFieldNumber(match[1]) : 1;
- const end = match[2] ? parseNumfmtFieldNumber(match[2]) : (part.includes("-") ? Infinity : start);
- if (start > end) throw new UsageError("invalid decreasing range", true);
- if (start <= 0 || end <= 0) throw new UsageError("fields are numbered from 1", true);
- ranges.push([start, end]);
- }
- ranges.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
- const merged = [];
- for (const [start, end] of ranges) {
- const previous = merged.at(-1);
- if (previous && start <= previous[1]) previous[1] = Math.max(previous[1], end);
- else merged.push([start, end]);
- }
- return merged;
-}
-
-function parseNumfmtFieldNumber(text) {
- if (text.length >= 20) throw new UsageError(`field number '${text}' is too large`, true);
- const value = Number(text);
- return Number.isSafeInteger(value) ? value : Infinity;
-}
-
-function parseNumfmtUnit(value) {
- const text = String(value);
- if (/^\+?\d+$/.test(text)) {
- const n = Number(text);
- if (Number.isSafeInteger(n) && n > 0) return n;
- }
- const match = text.match(/^(\+?\d+)?([KMGTPEZYRQ])i?$/);
- if (match) {
- const prefix = match[1] == null ? 1 : Number(match[1]);
- if (Number.isSafeInteger(prefix) && prefix > 0) return prefix * (text.endsWith("i") ? 1024 : 1000) ** ("KMGTPEZYRQ".indexOf(match[2]) + 1);
- }
- throw new UsageError(`invalid unit size: ${localeQuotedEscapedDiagnostic(text)}`);
-}
-
-function formatNumfmtRecord(record, opts) {
- if (record.includes("\0")) record = record.slice(0, record.indexOf("\0"));
- const delimiter = opts.d ?? opts.delimiter;
- const wholeRecord = delimiter === "";
- const leading = delimiter == null ? record.match(/^\s*/)?.[0] ?? "" : "";
- const trailing = delimiter == null ? record.match(/\s*$/)?.[0] ?? "" : "";
- const body = delimiter == null ? record.slice(leading.length, record.length - trailing.length) : record;
- const fields = wholeRecord ? [record] : delimiter == null ? (body === "" ? [""] : body.split(/[ \t\n\r\f\v]+/)) : record.split(delimiter);
- const defaultSeparators = body.match(/[ \t\n\r\f\v]+/g) ?? [];
- const separators = wholeRecord ? [] : delimiter == null ? (opts.z || opts["zero-terminated"] ? defaultSeparators.map(() => " ") : defaultSeparators) : Array.from({ length: Math.max(0, fields.length - 1) }, () => delimiter);
- const selected = readNumfmtFieldRanges(opts.field ?? "1");
- let ok = true;
- let error;
- for (let i = 0; i < fields.length; i++) {
- if (!inRanges(i + 1, selected)) continue;
- const result = formatNumfmtValue(fields[i], opts);
- ok &&= result.ok;
- if (!result.ok && error == null) error = result.error;
- if (!result.ok && (opts.invalid ?? "abort") === "abort") {
- const prefixFields = fields.slice(0, i);
- const prefix = prefixFields.length ? joinFields(prefixFields, separators.slice(0, Math.max(0, i - 1))) + (separators[i - 1] ?? "") : "";
- return { ok: false, error, text: `${leading}${prefix}` };
- }
- fields[i] = result.ok && delimiter == null && (leading || i > 0) ? applyPadding(result.text, fields[i].length) : result.text;
- }
- return { ok, error, text: `${leading}${joinFields(fields, separators)}${trailing}` };
-}
-
-function joinFields(fields, separators) {
- let out = fields[0] ?? "";
- for (let i = 1; i < fields.length; i++) out += (separators[i - 1] ?? " ") + fields[i];
- return out;
-}
-
-function formatNumfmtValue(value, opts) {
- try {
- const suffix = opts.suffix ?? "";
- const fromUnit = opts["from-unit"] == null ? 1 : parseNumfmtUnit(opts["from-unit"]);
- const toUnit = opts["to-unit"] == null ? 1 : parseNumfmtUnit(opts["to-unit"]);
- const unitSeparator = opts["unit-separator"] ?? opts["unit-sep"] ?? " ";
- const parsed = opts.from ? parseHumanNumberParts(value, opts.from, suffix, unitSeparator) : parsePlainNumfmtNumber(value, suffix);
- if (opts.from && opts["from-unit"] != null) parsed.decimals = countNumfmtInputDecimals(value, suffix);
- const n = (typeof parsed === "number" ? parsed : parsed.value) * fromUnit;
- if (!Number.isFinite(n)) throw new Error("invalid number");
- const format = parseNumfmtFormat(opts.format ?? "%f");
- let text = opts.to === "si" || opts.to === "iec" || opts.to === "iec-i"
- ? humanNumber(n / toUnit, opts.to, opts.round ?? "human-default", opts["unit-separator"] ?? opts["unit-sep"] ?? "", format.explicitPrecision ? format.precision : null)
- : formatPlainNumfmtNumber(n / toUnit, opts.round ?? "from-zero", format.explicitPrecision ? format.precision : (typeof parsed === "object" ? parsed.decimals : 0));
- if (opts.suffix) text += opts.suffix;
- text = applyNumfmtFormat(text, format);
- if (opts.padding && (opts.format == null || format.zero)) text = applyPadding(text, Number(opts.padding));
- return { ok: true, text };
- } catch (error) {
- return { ok: false, text: value, error: error.message };
- }
-}
-
-function parsePlainNumfmtNumber(value, suffix = "") {
- let text = String(value);
- if (suffix && text.endsWith(suffix)) text = text.slice(0, -suffix.length);
- if (!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(text)) throw new Error(numfmtNumberError(text, { fromMode: null }));
- const decimals = text.includes(".") ? text.split(".")[1].length : 0;
- return { value: Number(text), decimals };
-}
-
-function countNumfmtInputDecimals(value, suffix = "") {
- let text = String(value);
- if (suffix && text.endsWith(suffix)) text = text.slice(0, -suffix.length);
- const match = text.match(/^[+-]?\d+\.(\d+)/);
- return match ? match[1].length : 0;
-}
-
-function numfmtNumberError(text, { fromMode = null } = {}) {
- const value = String(text);
- const display = numfmtDiagnosticValue(value);
- if (/^[+-]?\d+\.(?:\D|$)/.test(value)) return `invalid number: ${localeQuotedDiagnostic(display)}`;
- const separatedSuffix = value.match(/^([+-]?(?:\d+(?:\.\d+)?|\.\d+)) ([kKMGTPEZYRQ](?:iB?|B)?)[ \t]+(.+)$/);
- if (fromMode && separatedSuffix) return `invalid suffix in input ${localeQuotedDiagnostic(display)}: ${localeQuotedDiagnostic(numfmtDiagnosticValue(separatedSuffix[3]))}`;
- if (/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)[A-Za-z]/.test(value)) {
- const suffix = value.match(/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(.*)$/)?.[1] ?? "";
- if (!fromMode && /^[KMGTPEZYRQ]i?B?$/i.test(suffix)) return `rejecting suffix in input: ${localeQuotedDiagnostic(display)} (consider using --from)`;
- return suffix.length > 1 && /^[KMGTPEZYRQ]i?/.test(suffix)
- ? `invalid suffix in input ${localeQuotedDiagnostic(display)}: ${localeQuotedDiagnostic(numfmtDiagnosticValue(suffix.replace(/^[KMGTPEZYRQ]i?/i, "")))}`
- : `invalid suffix in input: ${localeQuotedDiagnostic(display)}`;
- }
- if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)\s+/.test(value) || /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)\S/.test(value) || value.includes("..")) return `invalid suffix in input: ${localeQuotedDiagnostic(display)}`;
- return `invalid number: ${localeQuotedDiagnostic(display)}`;
-}
-
-function numfmtDiagnosticValue(value) {
- return [...String(value)].map((ch) => {
- if (/[\udc80-\udcff]/.test(ch)) return `\\${(ch.charCodeAt(0) - 0xdc00).toString(8).padStart(3, "0")}`;
- return lsEscapedName(ch, { escapeDouble: false });
- }).join("");
-}
-
-function formatPlainNumfmtNumber(value, round = "nearest", precision = 0) {
- const rounded = roundNumber(value, precision, round);
- return precision > 0 ? rounded.toFixed(precision) : String(rounded);
-}
-
-function applyPadding(text, width) {
- if (!Number.isInteger(width) || width === 0 || text.length >= Math.abs(width)) return text;
- return width > 0 ? text.padStart(width) : text.padEnd(Math.abs(width));
-}
-
-function humanNumber(n, mode, round = "up", unitSeparator = "", forcedPrecision = null) {
- const base = mode === "si" ? 1000 : 1024;
- const units = mode === "iec-i" ? ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi", "Ri", "Qi"] : mode === "si" ? ["", "k", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"] : ["", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"];
- let value = n;
- let idx = 0;
- while (Math.abs(value) >= base && idx < units.length - 1) {
- value /= base;
- idx++;
- }
- if (!idx) {
- const rounded = roundNumber(value, 0, round);
- if (Math.abs(rounded) < base) return forcedPrecision == null ? String(rounded) : rounded.toFixed(forcedPrecision);
- value = rounded / base;
- idx++;
- }
- let decimals = forcedPrecision ?? (Math.abs(value) >= 10 ? 0 : 1);
- let rounded = roundNumber(value, decimals, round);
- if (Math.abs(rounded) >= base && idx < units.length - 1) {
- value = rounded / base;
- idx++;
- decimals = forcedPrecision ?? (Math.abs(value) >= 10 ? 0 : 1);
- rounded = roundNumber(value, decimals, round);
- } else if (forcedPrecision == null && Math.abs(rounded) >= 10 && decimals !== 0) {
- decimals = 0;
- rounded = roundNumber(value, decimals, round);
- }
- return `${rounded.toFixed(decimals)}${unitSeparator}${units[idx]}`;
-}
-
-function roundNumber(value, precision, round) {
- const scale = 10 ** precision;
- const scaled = value * scale;
- let rounded;
- if (round === "human-default" || round === "from-zero") rounded = scaled < 0 ? Math.floor(scaled) : Math.ceil(scaled);
- else if (round === "up") rounded = Math.ceil(scaled);
- else if (round === "down") rounded = Math.floor(scaled);
- else if (round === "towards-zero") rounded = scaled < 0 ? Math.ceil(scaled) : Math.floor(scaled);
- else rounded = Math.sign(scaled) * Math.floor(Math.abs(scaled) + 0.5);
- return rounded / scale;
-}
-
-function parseNumfmtFormat(format) {
- const text = String(format);
- let directives = 0;
- let match;
- for (let i = 0; i < text.length; i++) {
- if (text[i] !== "%") continue;
- if (text[i + 1] === "%") {
- i++;
- continue;
- }
- directives++;
- match = text.slice(i).match(/^%([0 ']*)?(-)?([+ ]?\d+)?(?:\.(\d+))?f/);
- if (match?.[2] && /^[+ ]/.test(match[3] ?? "")) match = null;
- if (!match) {
- if (text.slice(i) === "%") throw new UsageError(`format ${localeQuotedEscapedDiagnostic(text)} ends in %`);
- const badPrecision = text.slice(i).match(/^%\.([-+ ]\d+)f/);
- if (badPrecision) throw new UsageError(`invalid precision in format ${localeQuotedEscapedDiagnostic(text)}`);
- throw new UsageError(`invalid format ${localeQuotedEscapedDiagnostic(text)}, directive must be %[0]['][-][N][.][N]f`);
- }
- i += match[0].length - 1;
- }
- if (directives === 0) throw new UsageError(text.endsWith("%") ? `format ${localeQuotedEscapedDiagnostic(text)} ends in %` : `format ${localeQuotedEscapedDiagnostic(text)} has no % directive`);
- if (directives > 1) throw new UsageError(`format ${localeQuotedEscapedDiagnostic(text)} has too many % directives`);
- const parsed = text.match(/^(.*)%([0 ']*)?(-)?([+ ]?\d+)?(?:\.(\d+))?f(.*)$/);
- return {
- raw: text,
- prefix: parsed?.[1]?.replace(/%%\s$/, "%%").replaceAll("%%", "%%") ?? "",
- suffix: parsed?.[6]?.replaceAll("%%", "%%") ?? "",
- left: Boolean(parsed?.[3]),
- zero: parsed?.[2]?.includes("0") ?? false,
- grouping: parsed?.[2]?.includes("'") ?? false,
- width: parsed?.[4] == null ? null : Number(parsed[4]),
- precision: parsed?.[5] == null ? 0 : Number(parsed[5]),
- explicitPrecision: parsed?.[5] != null,
- };
-}
-
-function applyNumfmtFormat(text, format) {
- if (format.raw === "%f") return text;
- let body = text;
- if (format.width != null && body.length < format.width) {
- const pad = format.zero ? "0" : " ";
- if (format.zero && !format.left && body.startsWith("-")) body = `-${body.slice(1).padStart(format.width - 1, pad)}`;
- else body = format.left ? body.padEnd(format.width, pad) : body.padStart(format.width, pad);
- }
- return `${format.prefix}${body}${format.suffix}`;
-}
-
-async function odCmd(args) {
- args = normalizeOdLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { A: "value", j: "value", N: "value", S: "value", t: "value", w: "optional-value", a: false, b: false, c: false, d: false, f: false, i: false, l: false, o: false, s: false, x: false, v: false }, long: { "address-radix": "value", "skip-bytes": "value", strings: "optional-value", format: "value", "read-bytes": "value", width: "optional-value", "output-duplicates": false, endian: "value", traditional: false, help: false, version: false } });
- const explicitFormats = odFormatsFromArgs(args).filter((format) => format !== "");
- const rawFormats = explicitFormats.length ? explicitFormats : [odFormat(opts)];
- const radix = normalizeOdAddressRadix(opts.A ?? opts["address-radix"] ?? "o");
- validateOdEndian(opts.endian);
- for (const format of rawFormats) validateOdFormat(format);
- const formats = rawFormats.flatMap(odFormatSpecs);
- const oldStyleOffset = odCanUseOldStyleOffset(args);
- const traditional = parseOdTraditionalOperands(operands, opts.traditional, oldStyleOffset);
- const inputFiles = traditional.files.length ? traditional.files : ["-"];
- const chunks = [];
- let failed = false;
- let hasNonRegularInput = false;
- const skip = traditional.skip ?? opts.j ?? opts["skip-bytes"];
- const limit = opts.N ?? opts["read-bytes"];
- const skipOption = opts.j != null ? "-j" : opts["skip-bytes"] != null ? "--skip-bytes" : "-j";
- const limitOption = opts.N != null ? "-N" : "--read-bytes";
- const start = skip == null ? 0 : parseOdSize(skip, skipOption);
- const limitSize = limit == null ? null : parseOdSize(limit, limitOption);
- const readLimit = limitSize == null ? null : start + limitSize;
- if (skip == null && limit == null && traditional.label == null
- && opts.S == null && opts.strings == null && inputFiles.length === 1
- && (opts.v || opts["output-duplicates"])) {
- const lineWidth = resolveOdLineWidth(opts, formats);
- return streamOdFile(inputFiles[0], formats, opts, lineWidth, radix);
- }
- for (const file of inputFiles) {
- try {
- if (file !== "-") {
- const s = await stat(file);
- if (s.isDirectory()) throw Object.assign(new Error("Is a directory"), { code: "EISDIR" });
- if (!s.isFile()) hasNonRegularInput = true;
- }
- chunks.push(readLimit == null ? await readAll(file) : await readAllLimit(file, readLimit));
- } catch (error) {
- stderr(`od: ${odDiagnosticFile(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- }
- }
- if (failed && chunks.length === 0) return 1;
- const raw = concatBytes(chunks);
- if (skip != null && start > raw.length && !hasNonRegularInput) {
- stderr("od: cannot skip past end of combined input\n");
- return 1;
- }
- const data = raw.slice(start, limit == null ? undefined : start + limitSize);
- const labelDelta = traditional.label == null ? null : parseGNUSize(traditional.label) - start;
- if (opts.S != null || opts.strings != null) {
- const stringsOption = opts.S != null ? "-S" : "--strings";
- stdout(formatOdStrings(data, parseOdStringLength(opts.S ?? (opts.strings === true ? 3 : opts.strings ?? 3), stringsOption), start, radix, limit != null));
- return failed ? 1 : 0;
- }
- const format = formats[0];
- const lineWidth = resolveOdLineWidth(opts, formats);
- let out = "";
- let previousBodyKey = null;
- let duplicatesSuppressed = false;
- for (let offset = 0; offset < data.length; offset += lineWidth) {
- const chunk = data.slice(offset, offset + lineWidth);
- const address = formatOdAddress(start + offset, radix, labelDelta);
- const bodyLines = odRenderedBodyLines(chunk, formats, opts.endian, lineWidth);
- const bodyKey = bodyLines.join("\n");
- if (!(opts.v || opts["output-duplicates"]) && previousBodyKey === bodyKey) {
- if (!duplicatesSuppressed) out += "*\n";
- duplicatesSuppressed = true;
- continue;
- }
- previousBodyKey = bodyKey;
- duplicatesSuppressed = false;
- out += formatOdChunkOutput(address, bodyLines, formats);
- }
- const finalAddress = formatOdAddress(start + data.length, radix, labelDelta);
- if (finalAddress) out += `${finalAddress}\n`;
- stdout(out);
- return failed ? 1 : 0;
-}
-
-function resolveOdLineWidth(opts, formats) {
- const width = opts.w ?? opts.width;
- const widthOption = opts.w != null ? "-w" : "--width";
- let lineWidth = width === true ? 32 : width == null ? 16 : parseOdWidth(width, widthOption);
- const formatSize = Math.max(...formats.map(odFormatSize));
- if (lineWidth % formatSize !== 0) {
- stderr(`od: warning: invalid width ${lineWidth}; using ${formatSize} instead\n`);
- lineWidth = formatSize;
- }
- return lineWidth;
-}
-
-function formatOdChunkOutput(address, bodyLines, formats) {
- if (formats.length === 1) return `${address} ${bodyLines[0]}\n`;
- const bodyWidth = Math.max(...bodyLines.map((line) => line.length));
- const firstPrefix = address ? `${address} ` : " ";
- const nextPrefix = address ? " ".repeat(address.length + 1) : " ";
- let out = "";
- for (let i = 0; i < bodyLines.length; i++) {
- const line = normalizeOdFormat(formats[i]).showChars ? bodyLines[i].padEnd(bodyWidth) : bodyLines[i];
- out += `${i === 0 ? firstPrefix : nextPrefix}${line}\n`;
- }
- return out;
-}
-
-function streamOdFile(file, formats, opts, lineWidth, radix) {
- let fd;
- let offset = 0;
- let carry = Buffer.alloc(0);
- try {
- fd = file === "-" ? 0 : openSync(file, "r");
- readFdChunkViews(fd, (chunk) => {
- const bytes = carry.length ? Buffer.concat([carry, chunk]) : chunk;
- let index = 0;
- while (index + lineWidth <= bytes.length) {
- const part = bytes.subarray(index, index + lineWidth);
- const address = formatOdAddress(offset, radix, null);
- stdout(formatOdChunkOutput(address, odRenderedBodyLines(part, formats, opts.endian, lineWidth), formats));
- offset += part.length;
- index += lineWidth;
- }
- carry = Buffer.from(bytes.subarray(index));
- });
- if (carry.length) {
- const address = formatOdAddress(offset, radix, null);
- stdout(formatOdChunkOutput(address, odRenderedBodyLines(carry, formats, opts.endian, lineWidth), formats));
- offset += carry.length;
- }
- const finalAddress = formatOdAddress(offset, radix, null);
- if (finalAddress) stdout(`${finalAddress}\n`);
- return 0;
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(`od: ${odDiagnosticFile(file)}: ${systemErrorMessage(error)}\n`);
- return 1;
- } finally {
- if (fd != null && fd !== 0) closeSync(fd);
- }
-}
-
-function odRenderedBodyLines(chunk, formats, endian, lineWidth) {
- if (formats.length === 1) return [formatOdLine(chunk, formats[0], endian, lineWidth)];
- return formats.map((fmt) => formatOdLine(chunk, fmt, endian, lineWidth, true, formats));
-}
-
-function normalizeOdAddressRadix(radix) {
- const text = String(radix);
- if (/^[doxn]/.test(text)) return text[0];
- throw new UsageError(`invalid output address radix '${text[0] ?? "\0"}'; it must be one character from [doxn]`);
-}
-
-function normalizeOdLongOptions(args) {
- return args.map((arg) => normalizeOdLongOption(arg));
-}
-
-function normalizeOdLongOption(arg) {
- if (!arg.startsWith("--") || arg === "--") return arg;
- return normalizeLongOptionByPrefix(arg, OD_LONG_OPTIONS);
-}
-
-function validateOdEndian(endian) {
- if (endian == null || endian === "little" || endian === "big") return;
- const kind = endian === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(endian)} for ${localeQuotedDiagnostic("--endian")}\nValid arguments are:\n - ${localeQuotedDiagnostic("little")}\n - ${localeQuotedDiagnostic("big")}`, true);
-}
-
-async function readAllLimit(path, limit) {
- if (limit <= 0) return new Uint8Array();
- if (path === "-") return readStdinBytesLimit(limit);
- const handle = await open(path, "r");
- try {
- const bytes = Buffer.allocUnsafe(limit);
- let offset = 0;
- while (offset < limit) {
- const { bytesRead } = await handle.read(bytes, offset, limit - offset, null);
- if (bytesRead === 0) break;
- offset += bytesRead;
- }
- return bytes.subarray(0, offset);
- } finally {
- await handle.close();
- }
-}
-
-function parseOdSize(value, option) {
- const text = String(value);
- if (text === "") throw new UsageError(`invalid ${option} argument ''`);
- try {
- const size = parseOdByteCount(text.replace(/^\+/, ""));
- return size > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(size);
- } catch (error) {
- if (error instanceof UsageError && error.message === "too large") throw new UsageError(`${option} argument '${text}' too large`);
- if (text.startsWith("-")) throw new UsageError(`invalid ${option} argument '${text}'`);
- throw new UsageError(`invalid suffix in ${option} argument '${text}'`);
- }
-}
-
-function parseOdByteCount(text) {
- const match = String(text).match(/^(\d+)([A-Za-z]*)$/);
- if (!match) throw new UsageError("invalid suffix");
- const scales = {
- "": 1n, b: 512n,
- K: 1024n, k: 1024n, KiB: 1024n, kiB: 1024n,
- M: 1024n ** 2n, m: 1024n ** 2n, MiB: 1024n ** 2n, miB: 1024n ** 2n,
- G: 1024n ** 3n, g: 1024n ** 3n, GiB: 1024n ** 3n, giB: 1024n ** 3n,
- T: 1024n ** 4n, t: 1024n ** 4n, TiB: 1024n ** 4n, tiB: 1024n ** 4n,
- P: 1024n ** 5n, PiB: 1024n ** 5n,
- E: 1024n ** 6n, EiB: 1024n ** 6n,
- Z: 1024n ** 7n, ZiB: 1024n ** 7n,
- Y: 1024n ** 8n, YiB: 1024n ** 8n,
- R: 1024n ** 9n, RiB: 1024n ** 9n,
- Q: 1024n ** 10n, QiB: 1024n ** 10n,
- KB: 1000n, kB: 1000n, MB: 1000n ** 2n, mB: 1000n ** 2n,
- GB: 1000n ** 3n, gB: 1000n ** 3n, TB: 1000n ** 4n, tB: 1000n ** 4n,
- PB: 1000n ** 5n, EB: 1000n ** 6n, ZB: 1000n ** 7n, YB: 1000n ** 8n,
- RB: 1000n ** 9n, QB: 1000n ** 10n,
- };
- const scale = scales[match[2]];
- if (!scale) throw new UsageError("invalid suffix");
- const amount = BigInt(match[1]) * scale;
- if (amount > 9223372036854775807n) throw new UsageError("too large");
- return amount;
-}
-
-function parseOdWidth(value, option) {
- const text = String(value);
- let size;
- try {
- size = parseGNUSize(text.replace(/^\+/, ""));
- } catch {
- if (text.startsWith("-") || !/^\+?\d/.test(text)) throw new UsageError(`invalid ${option} argument '${text}'`);
- throw new UsageError(`invalid suffix in ${option} argument '${text}'`);
- }
- if (size <= 0) throw new UsageError(`invalid ${option} argument '${text}'`);
- return size;
-}
-
-function parseOdStringLength(value, option = "-S") {
- const text = String(value);
- if (text === "") throw new UsageError(`invalid ${option} argument ''`);
- try {
- const parsed = parseOdByteCount(/^\D+$/.test(text) ? `1${text}` : text);
- return parsed > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(parsed);
- } catch (error) {
- if (error instanceof UsageError && error.message === "too large") throw new UsageError(`${option} argument '${text}' too large`);
- if (text.startsWith("-") || /^[A-Za-z]$/.test(text)) throw new UsageError(`invalid ${option} argument '${text}'`);
- throw new UsageError(`invalid suffix in ${option} argument '${text}'`);
- }
-}
-
-function odFormatsFromArgs(args) {
- const formats = [];
- const traditionalFormats = { a: "a", b: "o1", c: "c", d: "u2", f: "fF", i: "dI", l: "dL", o: "o2", s: "d2", x: "x2" };
- for (let i = 0; i < args.length; i++) {
- const arg = normalizeOdLongOption(String(args[i]));
- if (arg === "--") break;
- if (arg === "-t" || arg === "--format") {
- if (i + 1 < args.length) formats.push(String(args[++i]));
- } else if (arg.startsWith("-t") && arg.length > 2) {
- formats.push(arg.slice(2));
- } else if (arg.startsWith("--format=")) {
- formats.push(arg.slice("--format=".length));
- } else if (/^-[^-]/.test(arg)) {
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (traditionalFormats[ch]) formats.push(traditionalFormats[ch]);
- else if (ch === "t") {
- if (j + 1 < arg.length) formats.push(arg.slice(j + 1));
- else if (i + 1 < args.length) formats.push(String(args[++i]));
- break;
- } else if ("AjNSw".includes(ch)) {
- break;
- }
- }
- }
- }
- return formats;
-}
-
-function odFormatSpecs(format) {
- const text = String(format);
- const specs = [];
- let i = 0;
- while (i < text.length) {
- const start = i;
- const kind = text[i++];
- if (!isOdFormatStart(kind)) throw new UsageError(`invalid character '${kind ?? ""}' in type string ${localeQuotedEscapedDiagnostic(format)}`);
- if (kind === "f") {
- if ("FDLHB".includes(text[i] ?? "")) i++;
- else while (/\d/.test(text[i] ?? "")) i++;
- } else if ("doux".includes(kind)) {
- if ("CSIL".includes(text[i] ?? "")) i++;
- else while (/\d/.test(text[i] ?? "")) i++;
- }
- if (text[i] === "z") i++;
- specs.push(text.slice(start, i));
- }
- return specs;
-}
-
-function isOdFormatStart(ch) {
- return ch != null && "acfdoux".includes(ch);
-}
-
-function odCanUseOldStyleOffset(args) {
- return args.every((arg) => arg === "--" || !String(arg).startsWith("-"));
-}
-
-function parseOdTraditionalOperands(operands, traditional = false, oldStyleOffset = false) {
- const files = [...operands];
- if (!files.length) return { files, skip: null, label: null };
- let label = null;
- const rejectTraditionalExtraFile = () => {
- if (traditional && files.length > 1) {
- throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(files[1])}\nod: compatibility mode supports at most one file`, true);
- }
- };
- if (traditional && files.length >= 2) {
- const parsedLabel = parseOdTraditionalOffset(files.at(-1));
- const parsedSkip = parseOdTraditionalOffset(files.at(-2));
- if (parsedLabel && parsedSkip) {
- files.pop();
- files.pop();
- rejectTraditionalExtraFile();
- return { files, skip: parsedSkip, label: parsedLabel };
- }
- }
- const last = files.at(-1);
- const parsed = parseOdTraditionalOffset(last);
- if (!parsed || (!traditional && (!oldStyleOffset || !String(last).startsWith("+")))) {
- rejectTraditionalExtraFile();
- return { files, skip: null, label };
- }
- files.pop();
- rejectTraditionalExtraFile();
- return { files, skip: parsed, label };
-}
-
-function parseOdTraditionalOffset(value) {
- const text = String(value);
- const match = text.match(/^\+?((?:0x[0-9a-fA-F]+)|(?:\d+))(\.)?([bB])?$/);
- if (!match) {
- if (/^(?:\+?[0-9]{100,}\.?|\+?0x[0-9a-fA-F]{100,})$/.test(text)) throw new UsageError(`${text}: Numerical result out of range`);
- return null;
- }
- const digits = match[1];
- if (digits.replace(/^0x/i, "").length > 60) throw new UsageError(`${text}: Numerical result out of range`);
- const base = /^0x/i.test(digits) ? 16 : match[2] === "." ? 10 : 8;
- if (base === 8 && /[89]/.test(digits)) return null;
- let n = Number.parseInt(digits.replace(/^0x/i, ""), base);
- if (match[3]?.toLowerCase() === "b") n *= 512;
- if (!Number.isSafeInteger(n)) throw new UsageError(`${text}: Numerical result out of range`);
- return String(n);
-}
-
-function odDiagnosticFile(file) {
- return /\s/.test(String(file)) ? `'${String(file).replace(/'/g, "'\\''")}'` : file;
-}
-
-function odFormat(opts) {
- if (opts.a) return "a";
- if (opts.b) return "o1";
- if (opts.c) return "c";
- if (opts.d) return "u2";
- if (opts.f) return "fF";
- if (opts.i) return "dI";
- if (opts.l) return "dL";
- if (opts.o) return "o2";
- if (opts.s) return "d2";
- if (opts.x) return "x2";
- if (opts.t != null && opts.t !== "") return opts.t;
- if (opts.format != null && opts.format !== "") return opts.format;
- return "o2";
-}
-
-function formatOffset(offset, radix) {
- if (radix === "n") return "";
- if (radix === "d") return String(offset).padStart(7, "0");
- if (radix === "x") return offset.toString(16).padStart(6, "0");
- return offset.toString(8).padStart(7, "0");
-}
-
-function formatOdAddress(offset, radix, labelDelta = null) {
- const address = formatOffset(offset, radix);
- if (labelDelta == null) return address;
- const label = formatOffset(offset + (radix === "n" ? 0 : labelDelta), radix === "n" ? "o" : radix);
- return address ? `${address} (${label})` : `(${label})`;
-}
-
-function formatOdLine(chunk, format, endian = "little", lineWidth = null, multiFormat = false, groupFormats = [format]) {
- const normalized = normalizeOdFormat(format);
- const body = formatOdChunk(chunk, normalized.format, endian, multiFormat, groupFormats);
- if (!normalized.showChars) return body;
- const paddedBody = lineWidth == null ? body : body.padEnd(odFullLineBodyWidth(normalized.format, lineWidth, multiFormat, groupFormats));
- return `${paddedBody} ${formatOdAscii(chunk)}`;
-}
-
-function normalizeOdFormat(format) {
- const text = String(format);
- return { format: text.endsWith("z") ? text.slice(0, -1) : text, showChars: text.endsWith("z") };
-}
-
-function validateOdFormat(format) {
- const text = String(format);
- let i = 0;
- while (i < text.length) {
- const start = i;
- const kind = text[i++];
- if (!isOdFormatStart(kind)) throw new UsageError(`invalid character '${kind ?? ""}' in type string ${localeQuotedEscapedDiagnostic(format)}`);
- if (kind === "f") {
- if ("FDLHB".includes(text[i] ?? "")) i++;
- else while (/\d/.test(text[i] ?? "")) i++;
- } else if ("doux".includes(kind)) {
- if ("CSIL".includes(text[i] ?? "")) i++;
- else while (/\d/.test(text[i] ?? "")) i++;
- }
- if (text[i] === "z") i++;
- validateOdFormatSpec(text.slice(start, i), format);
- }
-}
-
-function validateOdFormatSpec(spec, originalFormat = spec) {
- const text = normalizeOdFormat(spec).format;
- if (text === "a" || text === "c") return;
- if ((text.startsWith("a") || text.startsWith("c")) && text.length > 1) throw new UsageError(`invalid character '${text[1]}' in type string ${localeQuotedEscapedDiagnostic(originalFormat)}`);
- if (text === "f" || text === "fF" || text === "fD" || text === "fL" || text === "fH" || text === "fB" || /^f\d+$/.test(text)) {
- const floatSize = text.match(/^f(\d+)$/);
- if (floatSize && ![2, 4, 8, 16].includes(Number(floatSize[1]))) {
- throw new UsageError(`invalid type string ${localeQuotedEscapedDiagnostic(originalFormat)};\nthis system doesn't provide a ${floatSize[1]}-byte floating point type`);
- }
- odFormatSize(text);
- return;
- }
- const kind = text[0] ?? "";
- if (!"doux".includes(kind)) throw new UsageError(`invalid character '${kind}' in type string ${localeQuotedEscapedDiagnostic(originalFormat)}`);
- const suffix = text.slice(1);
- if (suffix === "" || ["C", "S", "I", "L"].includes(suffix)) return;
- if (/^\d+$/.test(suffix)) {
- const size = Number(suffix);
- if (![1, 2, 4, 8].includes(size)) throw new UsageError(`invalid type string ${localeQuotedEscapedDiagnostic(originalFormat)};\nthis system doesn't provide a ${suffix}-byte integral type`);
- return;
- }
- throw new UsageError(`invalid character '${suffix[0]}' in type string ${localeQuotedEscapedDiagnostic(originalFormat)}`);
-}
-
-function formatOdChunk(chunk, format, endian = "little", multiFormat = false, groupFormats = [format]) {
- format = normalizeOdFormat(format).format;
- const size = odFormatSize(format);
- const parts = [];
- for (let i = 0; i < chunk.length; i += size) {
- const bytes = chunk.slice(i, i + size);
- if (format === "c" || format === "a") {
- parts.push(formatOdChar(bytes[0], format === "a"));
- } else if (format.startsWith("f")) {
- parts.push(formatOdFloat(bytes, format, endian));
- } else {
- const value = [...bytes].reduce((sum, byte, idx) => sum + BigInt(byte) * (1n << BigInt(8 * (endian === "big" ? bytes.length - idx - 1 : idx))), 0n);
- if (format.startsWith("x")) {
- const text = value.toString(16).padStart(size * 2, "0");
- parts.push(multiFormat ? text.padStart(odMultiFormatFieldWidth(format, size, groupFormats)) : text.padStart(odFieldWidth(format, size), "0"));
- }
- else if (format.startsWith("u")) parts.push(value.toString().padStart(multiFormat ? odMultiFormatFieldWidth(format, size, groupFormats) : odFieldWidth(format, size)));
- else if (format.startsWith("d")) parts.push(signExtendBigInt(value, size).toString().padStart(multiFormat ? odMultiFormatFieldWidth(format, size, groupFormats) : odFieldWidth(format, size)));
- else {
- const text = value.toString(8).padStart(odFieldWidth(format, size), "0");
- parts.push(multiFormat ? text.padStart(odMultiFormatFieldWidth(format, size, groupFormats)) : text);
- }
- }
- }
- return parts.join(" ");
-}
-
-function odFullLineBodyWidth(format, lineWidth, multiFormat = false, groupFormats = [format]) {
- const size = odFormatSize(format);
- const fields = Math.floor(lineWidth / size);
- if (fields <= 0) return 0;
- const fieldWidth = format === "a" || format === "c" ? 3 : odMultiFormatFieldWidth(format, size, groupFormats, multiFormat);
- return fields * fieldWidth + Math.max(0, fields - 1);
-}
-
-function formatOdFloat(bytes, format, endian = "little") {
- const size = odFormatSize(format);
- const buffer = new Uint8Array(size);
- buffer.set(bytes.slice(0, size));
- if (size === 16) return odFloat128Placeholder(buffer, endian).padStart(24);
- const view = new DataView(buffer.buffer);
- const littleEndian = endian !== "big";
- const value = format === "fB"
- ? odBfloat16Value(view.getUint16(0, littleEndian))
- : size === 2
- ? odFloat16Value(view.getUint16(0, littleEndian))
- : size === 4
- ? view.getFloat32(0, littleEndian)
- : view.getFloat64(0, littleEndian);
- return formatOdFloatValue(value, size, format);
-}
-
-function odFloat16Value(bits) {
- const sign = bits & 0x8000 ? -1 : 1;
- const exponent = (bits >> 10) & 0x1f;
- const fraction = bits & 0x03ff;
- if (exponent === 0x1f) return fraction ? NaN : sign * Infinity;
- if (exponent === 0) return sign * 2 ** -14 * (fraction / 2 ** 10);
- return sign * 2 ** (exponent - 15) * (1 + fraction / 2 ** 10);
-}
-
-function odBfloat16Value(bits) {
- const buffer = new ArrayBuffer(4);
- const view = new DataView(buffer);
- view.setUint32(0, bits << 16, false);
- return view.getFloat32(0, false);
-}
-
-function formatOdFloatValue(value, size, format = "") {
- const width = size === 2 || size === 4 ? 15 : 24;
- if (!Number.isFinite(value)) return String(value).padStart(width);
- const text = Number.isInteger(value)
- ? String(value)
- : size === 2
- ? trimOdFloatText(value.toPrecision(8))
- : size === 4
- ? trimOdFloatText(value.toPrecision(format === "fB" ? 8 : 7))
- : trimOdFloatText(value.toPrecision(16));
- return text.padStart(width);
-}
-
-function trimOdFloatText(text) {
- return text.replace(/(\.\d*?[1-9])0+(e[+-]?\d+)$/iu, "$1$2").replace(/\.0+(e[+-]?\d+)$/iu, "$1").replace(/(\.\d*?[1-9])0+$/u, "$1").replace(/\.0+$/u, "");
-}
-
-function odFloat128Placeholder(bytes, endian = "little") {
- const ordered = endian === "big" ? [...bytes] : [...bytes].reverse();
- const value = ordered.reduce((sum, byte) => (sum << 8n) + BigInt(byte), 0n);
- return value.toString();
-}
-
-function formatOdAscii(chunk) {
- let out = ">";
- for (const byte of chunk) out += byte >= 32 && byte < 127 ? String.fromCharCode(byte) : ".";
- return `${out}<`;
-}
-
-function formatOdStrings(data, minLength, start, radix, allowFinalUnterminated = false) {
- if (!Number.isFinite(minLength) || minLength < 0) throw new UsageError(`invalid suffix in -S argument '${minLength}'`);
- let out = "";
- let runStart = -1;
- for (let i = 0; i <= data.length; i++) {
- const byte = i < data.length ? data[i] : 0;
- const printable = i < data.length && byte >= 32 && byte < 127;
- if (printable) {
- if (runStart === -1) runStart = i;
- continue;
- }
- if (runStart !== -1) {
- const length = i - runStart;
- if (((i < data.length && byte === 0) || (i === data.length && allowFinalUnterminated)) && length >= minLength) {
- const address = formatOffset(start + runStart, radix);
- const text = new TextDecoder().decode(data.slice(runStart, i));
- out += `${address}${address ? " " : ""}${text}\n`;
- }
- runStart = -1;
- } else if (i < data.length && byte === 0 && minLength === 0) {
- const address = formatOffset(start + i, radix);
- out += `${address}${address ? " " : ""}\n`;
- }
- }
- return out;
-}
-
-function odFormatSize(format) {
- format = normalizeOdFormat(format).format;
- if (format === "a" || format === "c") return 1;
- if (format === "fH" || format === "fB") return 2;
- const floatSize = String(format).match(/^f(\d+)$/);
- if (floatSize) {
- const size = Number(floatSize[1]);
- if (![2, 4, 8, 16].includes(size)) throw new UsageError(`this system doesn't provide a ${size}-byte floating point type`);
- return size;
- }
- if (format === "fF") return 4;
- if (format === "fD" || format === "fL" || format === "f") return 8;
- const match = String(format).match(/[doux](\d+|C|S|I|L)?/);
- const value = match?.[1];
- if (value === "C") return 1;
- if (value === "S") return 2;
- if (value === "I") return 4;
- if (value === "L") return 8;
- return Number(value ?? (format === "c" || format === "a" ? 1 : 4));
-}
-
-function odFieldWidth(format, size, multiFormat = false) {
- if (format.startsWith("x")) return multiFormat && size === 1 ? 3 : size * 2;
- if (format.startsWith("o")) return Math.ceil(size * 8 / 3);
- if (format.startsWith("u")) return ({ 1: 3, 2: 5, 4: 10, 8: 20 })[size] ?? String(2n ** BigInt(size * 8) - 1n).length;
- if (format.startsWith("d")) return ({ 1: 4, 2: 6, 4: 11, 8: 20 })[size] ?? String(2n ** BigInt(size * 8 - 1)).length + 1;
- return size;
-}
-
-function odMultiFormatFieldWidth(format, size, groupFormats, multiFormat = true) {
- if (!multiFormat) return odFieldWidth(format, size, multiFormat);
- const normalizedGroup = groupFormats.map((groupFormat) => normalizeOdFormat(groupFormat).format);
- const unitSize = Math.min(...normalizedGroup.map(odFormatSize));
- const unitWidth = Math.max(...normalizedGroup
- .filter((groupFormat) => odFormatSize(groupFormat) === unitSize)
- .map((groupFormat) => groupFormat === "a" || groupFormat === "c" ? 3 : odFieldWidth(groupFormat, unitSize, true)));
- const unitCount = size % unitSize === 0 ? size / unitSize : 1;
- const alignedWidth = unitCount * unitWidth + Math.max(0, unitCount - 1);
- return Math.max(odFieldWidth(format, size, true), alignedWidth);
-}
-
-function formatOdChar(byte, named = false) {
- const asciiNames = ["nul", "soh", "stx", "etx", "eot", "enq", "ack", "bel", "bs", "ht", "nl", "vt", "ff", "cr", "so", "si", "dle", "dc1", "dc2", "dc3", "dc4", "nak", "syn", "etb", "can", "em", "sub", "esc", "fs", "gs", "rs", "us"];
- if (named) {
- const ascii = byte & 0x7f;
- if (ascii < asciiNames.length) return asciiNames[ascii].padStart(3);
- if (ascii === 32) return " sp";
- if (ascii === 127) return "del";
- return String.fromCharCode(ascii).padStart(3);
- }
- const escapes = { 0: "\\0", 7: "\\a", 8: "\\b", 9: "\\t", 10: "\\n", 11: "\\v", 12: "\\f", 13: "\\r" };
- if (escapes[byte]) return escapes[byte].padStart(3);
- if (byte >= 32 && byte < 127) return String.fromCharCode(byte).padStart(3);
- return byte.toString(8).padStart(3, "0");
-}
-
-function signExtend(value, size) {
- const bits = size * 8;
- const sign = 2 ** (bits - 1);
- const mod = 2 ** bits;
- return value >= sign ? value - mod : value;
-}
-
-function signExtendBigInt(value, size) {
- const bits = BigInt(size * 8);
- const sign = 1n << (bits - 1n);
- const mod = 1n << bits;
- return value >= sign ? value - mod : value;
-}
-
-async function timeoutCmd(args) {
- const { opts, operands } = parseTimeoutOptions(args);
- const killAfter = opts.k ?? opts["kill-after"];
- if (killAfter != null) parseDuration(killAfter);
- const signal = normalizeTimeoutSignalOption(opts.s ?? opts.signal ?? "TERM");
- if (operands.length < 2) throw new InvocationError("", 125, true);
- const duration = parseDuration(operands[0]);
- const command = operands.slice(1);
- let proc;
- try {
- await resolveEnvCommand(command[0], process.env, process.cwd());
- const spawnCommand = await timeoutSpawnCommand(command, signal);
- proc = Bun.spawn(spawnCommand, { stdin: "inherit", stdout: "inherit", stderr: "inherit", detached: !opts.foreground });
- } catch (error) {
- const code = error?.code === "ENOENT" ? 127 : 126;
- const message = error?.code === "ENOENT"
- ? `failed to run command '${command[0]}': No such file or directory`
- : error?.code === "EACCES"
- ? `failed to run command '${command[0]}': Permission denied`
- : `failed to run command '${command[0]}': ${error?.message || String(error)}`;
- throw new InvocationError(message, code, false);
- }
- let timedOut = false;
- let killedByFollowUp = false;
- let killer = null;
- const expire = () => {
- if (timedOut) return;
- timedOut = true;
- if (opts.v || opts.verbose) stderr(`timeout: sending signal ${timeoutSignalDisplay(signal)} to command '${command[0]}'\n`);
- sendTimeoutSignal(proc, timeoutKillSignal(signal), !opts.foreground);
- if (killAfter) {
- const scheduleKillAfter = timeoutTimerDuration(parseDuration(killAfter));
- if (scheduleKillAfter != null) killer = setTimeout(() => {
- killedByFollowUp = true;
- if (opts.v || opts.verbose) stderr(`timeout: sending signal KILL to command '${command[0]}'\n`);
- sendTimeoutSignal(proc, "SIGKILL", !opts.foreground);
- }, scheduleKillAfter);
- }
- };
- const forwardedSignals = [...new Set([
- "SIGHUP", "SIGINT", "SIGQUIT", "SIGTERM", "SIGALRM", "SIGUSR1", "SIGUSR2",
- "SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGIO", "SIGPWR", "SIGSYS", signal,
- ])]
- .filter((name) => typeof name === "string" && !["0", "SIGKILL", "SIGSTOP"].includes(name));
- const signalHandlers = forwardedSignals.map((forwardedSignal) => {
- const handler = () => {
- if (forwardedSignal === "SIGALRM") expire();
- else sendTimeoutSignal(proc, forwardedSignal, !opts.foreground);
- };
- process.on(forwardedSignal, handler);
- return [forwardedSignal, handler];
- });
- const scheduleDuration = timeoutTimerDuration(duration);
- const timer = scheduleDuration == null ? null : setTimeout(expire, scheduleDuration);
- const code = await proc.exited;
- for (const [forwardedSignal, handler] of signalHandlers) process.off(forwardedSignal, handler);
- if (timer) clearTimeout(timer);
- if (killer) clearTimeout(killer);
- if (!timedOut || opts.p || opts["preserve-status"]) return code;
- if (killedByFollowUp) return 137;
- return signal === "SIGKILL" ? 137 : 124;
-}
-
-async function timeoutSpawnCommand(command, signal) {
- if (process.platform !== "linux") return command;
- // util-linux setpriv does not accept the RTMIN/RTMAX names (or their
- // numeric values) for --pdeathsig. The timeout monitor can still deliver
- // those signals itself, so avoid turning a valid timeout invocation into a
- // setpriv usage error merely to install the parent-death safeguard.
- if (signalNumberFromOperand(signal) > 31) return command;
- try {
- const setpriv = await resolveEnvCommand("setpriv", process.env, process.cwd());
- const parentDeathSignal = signalNumberFromOperand(signal) === 0 ? "clear" : signal;
- return [setpriv, "--pdeathsig", parentDeathSignal, "--", ...command];
- } catch {
- return command;
- }
-}
-
-function parseTimeoutOptions(args) {
- const opts = {};
- const operands = [];
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- if (option.startsWith("--")) throw new InvocationError(`option '${option}' requires an argument`);
- throw new InvocationError(`option requires an argument -- '${option.slice(1)}'`);
- };
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- operands.push(...args.slice(i + 1));
- break;
- } else if (arg.startsWith("--foreground=")) {
- throw new InvocationError("option '--foreground' doesn't allow an argument");
- } else if (arg.startsWith("--preserve-status=")) {
- throw new InvocationError("option '--preserve-status' doesn't allow an argument");
- } else if (arg.startsWith("--verbose=")) {
- throw new InvocationError("option '--verbose' doesn't allow an argument");
- } else if (arg === "-p" || arg === "--preserve-status") {
- opts.p = true;
- } else if (arg === "-v" || arg === "--verbose") {
- opts.v = true;
- } else if (arg === "-f" || arg === "--foreground") {
- opts.foreground = true;
- } else if (arg === "-s" || arg === "--signal") {
- opts.s = requireValue(i, arg);
- i++;
- } else if (/^-s.+/.test(arg)) {
- opts.s = arg.slice(2);
- } else if (arg.startsWith("--signal=")) {
- opts.signal = arg.slice("--signal=".length);
- } else if (arg === "-k" || arg === "--kill-after") {
- opts.k = requireValue(i, arg);
- i++;
- } else if (/^-k.+/.test(arg)) {
- opts.k = arg.slice(2);
- } else if (arg.startsWith("--kill-after=")) {
- opts["kill-after"] = arg.slice("--kill-after=".length);
- } else if (arg.startsWith("-")) {
- throw new InvocationError(invalidOptionMessage(arg));
- } else {
- operands.push(...args.slice(i));
- break;
- }
- }
- return { opts, operands };
-}
-
-function timeoutTimerDuration(duration) {
- if (duration === 0 || duration > 2147483647 || !Number.isFinite(duration)) return null;
- return Math.max(1, Math.ceil(duration));
-}
-
-function normalizeTimeoutSignalOption(signal) {
- const normalized = normalizeSignal(signal);
- const valid = new Set(["SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", "SIGABRT", "SIGBUS", "SIGFPE", "SIGKILL", "SIGUSR1", "SIGSEGV", "SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGCHLD", "SIGCONT", "SIGSTOP", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGURG", "SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", "SIGIO", "SIGSYS"]);
- if (normalized === "0" || valid.has(normalized) || signalNumberFromOperand(normalized) >= 0) return normalized;
- throw new InvocationError(`${localeQuotedEscapedDiagnostic(signal)}: invalid signal`, 125, true);
-}
-
-function timeoutKillSignal(signal) {
- const signum = signalNumberFromOperand(signal);
- return signum > 31 ? signum : signal === "0" ? 0 : signal;
-}
-
-function timeoutSignalDisplay(signal) {
- const signum = signalNumberFromOperand(signal);
- if (signum === 0) return "0";
- return signalDisplayName(signum).replace(/^SIG/, "");
-}
-
-function normalizeSignal(signal) {
- const text = String(signal).toUpperCase().replace(/^SIG/, "");
- if (text === "RTMIN") return "SIGRTMIN";
- if (text === "RTMAX") return "SIGRTMAX";
- if (/^\d+$/.test(text)) {
- if (Number(text) === 0) return "0";
- const map = { 1: "SIGHUP", 2: "SIGINT", 9: "SIGKILL", 15: "SIGTERM" };
- return map[Number(text)] ?? `SIG${text}`;
- }
- return `SIG${text}`;
-}
-
-function sendTimeoutSignal(proc, signal, processGroup = false) {
- const normalized = signal === "0" ? 0 : signal;
- const signum = typeof normalized === "number" ? normalized : signalNumberFromOperand(normalized);
- const send = (pid) => {
- // Bun's process.kill accepts the usual Node signal names but does not
- // reliably deliver Linux real-time signals. libc.kill handles the full
- // numeric signal range used by GNU timeout.
- if (signum > 31) libc.symbols.kill(pid, signum);
- else process.kill(pid, normalized);
- };
- try {
- send(proc.pid);
- } catch {}
- if (processGroup) {
- try {
- send(-proc.pid);
- } catch {}
- }
- if (normalized !== 0 && normalized !== 9 && normalized !== "SIGKILL" && normalized !== "SIGCONT") {
- try {
- process.kill(proc.pid, "SIGCONT");
- } catch {}
- if (processGroup) {
- try {
- process.kill(-proc.pid, "SIGCONT");
- } catch {}
- }
- }
-}
-
-function parseDuration(value) {
- const text = String(value);
- const match = text.match(/^(\+?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|0[xX](?:[0-9a-fA-F]+(?:\.[0-9a-fA-F]*)?|\.[0-9a-fA-F]+)(?:[pP][+-]?\d+)?|[iI][nN][fF](?:[iI][nN][iI][tT][yY])?))([smhd]?)$/);
- if (!match) throw new InvocationError(`invalid time interval ${localeQuotedEscapedDiagnostic(value)}`, 125, true);
- let amount = parseDurationNumber(match[1]);
- if (Number.isNaN(amount) || amount < 0) throw new InvocationError(`invalid time interval ${localeQuotedEscapedDiagnostic(value)}`, 125, true);
- if (amount === 0 && /[1-9]/.test(match[1]) && !/^0+(?:\.0*)?(?:[eE][+-]?\d+)?$/.test(match[1])) amount = Number.MIN_VALUE;
- return amount * { "": 1000, s: 1000, m: 60000, h: 3600000, d: 86400000 }[match[2]];
-}
-
-function parseDurationNumber(value) {
- const text = String(value).replace(/^\+/, "");
- if (/^inf(?:inity)?$/i.test(text)) return Infinity;
- if (/^0x/i.test(text)) return parseHexFloat(text);
- return Number(value);
-}
-
-function parseHexFloat(value) {
- const [, mantissa, exponentText] = value.match(/^0[xX]([0-9a-fA-F]*(?:\.[0-9a-fA-F]*)?|\.[0-9a-fA-F]+)(?:[pP]([+-]?\d+))?$/) ?? [];
- if (mantissa == null) return NaN;
- const [whole, fraction = ""] = mantissa.split(".");
- let amount = Number.parseInt(whole || "0", 16);
- for (let i = 0; i < fraction.length; i++) amount += Number.parseInt(fraction[i], 16) / 16 ** (i + 1);
- return amount * 2 ** Number(exponentText ?? 0);
-}
-
-function parseByteCount(value) {
- const match = String(value).match(/^(\d+)([A-Za-z]*)$/);
- if (!match) throw new UsageError(`invalid byte count: ${value}`);
- const n = BigInt(match[1]);
- const scale = {
- "": 1n, b: 512n,
- k: 1024n, K: 1024n, KiB: 1024n, kiB: 1024n,
- m: 1024n ** 2n, M: 1024n ** 2n, MiB: 1024n ** 2n, miB: 1024n ** 2n,
- g: 1024n ** 3n, G: 1024n ** 3n, GiB: 1024n ** 3n, giB: 1024n ** 3n,
- t: 1024n ** 4n, T: 1024n ** 4n, TiB: 1024n ** 4n, tiB: 1024n ** 4n,
- P: 1024n ** 5n, PiB: 1024n ** 5n,
- E: 1024n ** 6n, EiB: 1024n ** 6n,
- Z: 1024n ** 7n, ZiB: 1024n ** 7n,
- Y: 1024n ** 8n, YiB: 1024n ** 8n,
- R: 1024n ** 9n, RiB: 1024n ** 9n,
- Q: 1024n ** 10n, QiB: 1024n ** 10n,
- KB: 1000n, kB: 1000n, MB: 1000n ** 2n, mB: 1000n ** 2n,
- GB: 1000n ** 3n, gB: 1000n ** 3n, TB: 1000n ** 4n, tB: 1000n ** 4n,
- PB: 1000n ** 5n, EB: 1000n ** 6n, ZB: 1000n ** 7n, YB: 1000n ** 8n,
- RB: 1000n ** 9n, QB: 1000n ** 10n,
- }[match[2]];
- if (!scale) throw new UsageError(`invalid byte count: ${value}`);
- const amount = n * scale;
- return amount > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(amount);
-}
-
-async function readPasswd() {
- const rows = new Map();
- try {
- const text = await readFile("/etc/passwd", "utf8");
- for (const line of text.split("\n")) {
- const [name,, uid, gid, gecos = "", home = "", shell = ""] = line.split(":");
- if (name) rows.set(name, { uid: Number(uid), gid: Number(gid), gecos, home, shell });
- }
- } catch {}
- return rows;
-}
-
-async function readGroup() {
- const rows = new Map();
- try {
- const text = await readFile("/etc/group", "utf8");
- for (const line of text.split("\n")) {
- const [name,, gid] = line.split(":");
- if (name) rows.set(name, Number(gid));
- }
- } catch {}
- return rows;
-}
-
-async function resolveUser(value) {
- if (value == null || value === "") return null;
- if (/^\+\d+$/.test(value)) return Number(value.slice(1));
- if (/^\d+$/.test(value)) return Number(value);
- const user = (await readPasswd()).get(value);
- if (!user) throw new UsageError(`invalid user: ${localeQuotedEscapedDiagnostic(value)}`);
- return user.uid;
-}
-
-async function resolveGroup(value) {
- if (value == null || value === "") return null;
- if (/^\+\d+$/.test(value)) return Number(value.slice(1));
- if (/^\d+$/.test(value)) return Number(value);
- const gid = (await readGroup()).get(value);
- if (gid == null) throw new UsageError(`invalid group: ${localeQuotedEscapedDiagnostic(value)}`);
- return gid;
-}
-
-async function tsort(args) {
- const { operands } = parseOptions(normalizeHelpVersionOnlyLongOptions(args), { short: { w: false }, long: { help: false, version: false } });
- if (operands.length > 1) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[1])}`, true);
- const file = operands[0] ?? "-";
- let input;
- try {
- input = await readAll(file);
- } catch (error) {
- const message = error?.code === "EISDIR" ? `${textInputDiagnosticName(file)}: read error: ${systemErrorMessage(error)}` : file === "-" ? nodeErrorMessage(error) : `${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}`;
- stderr(`tsort: ${message}\n`);
- return 1;
- }
- const text = new TextDecoder().decode(input);
- const tokens = text.trim().split(/\s+/).filter(Boolean);
- if (tokens.length % 2) throw new UsageError(`${file}: input contains an odd number of tokens`);
- const nodes = new Map();
- const getNode = (name) => {
- if (!nodes.has(name)) nodes.set(name, { name, count: 0, printed: false, qlink: null, succ: [] });
- return nodes.get(name);
- };
- for (let i = 0; i < tokens.length; i += 2) {
- const from = getNode(tokens[i]);
- const to = getNode(tokens[i + 1]);
- if (from !== to) {
- to.count++;
- from.succ.unshift(to);
- }
- }
- const sortedNodes = [...nodes.values()].sort((a, b) => a.name.localeCompare(b.name));
- let remaining = sortedNodes.length;
- let ok = true;
- while (remaining > 0) {
- const queue = tsortScanZeros(sortedNodes);
- for (let head = queue.head, tail = queue.tail; head;) {
- const node = head;
- stdout(`${node.name}\n`);
- node.printed = true;
- remaining--;
- for (const next of node.succ) {
- next.count--;
- if (next.count === 0) {
- tail.qlink = next;
- tail = next;
- }
- }
- head = node.qlink;
- node.qlink = null;
- }
- if (remaining > 0) {
- stderr(`tsort: ${file}: input contains a loop:\n`);
- ok = false;
- tsortBreakLoop(sortedNodes);
- }
- }
- return ok ? 0 : 1;
-}
-
-function tsortScanZeros(nodes) {
- let head = null;
- let tail = null;
- for (const node of nodes) {
- if (node.count === 0 && !node.printed) {
- if (!head) head = node;
- else tail.qlink = node;
- tail = node;
- node.qlink = null;
- }
- }
- return { head, tail };
-}
-
-function tsortBreakLoop(nodes) {
- let loop = null;
- do {
- for (const node of nodes) {
- if (node.count <= 0 || node.printed) continue;
- if (!loop) {
- loop = node;
- continue;
- }
- const idx = node.succ.findIndex((next) => next === loop);
- if (idx === -1) continue;
- if (!node.qlink) {
- node.qlink = loop;
- loop = node;
- continue;
- }
- while (loop) {
- stderr(`tsort: ${loop.name}\n`);
- if (loop === node) {
- node.succ[idx].count--;
- node.succ.splice(idx, 1);
- break;
- }
- const next = loop.qlink;
- loop.qlink = null;
- loop = next;
- }
- while (loop) {
- const next = loop.qlink;
- loop.qlink = null;
- loop = next;
- }
- return;
- }
- } while (loop);
-}
-
-async function chownCmd(args) {
- const { opts, operands } = parseOptions(normalizeChownArgs(args), { short: { R: false, c: false, f: false, h: false, H: false, L: false, P: false, v: false }, long: { changes: false, recursive: false, silent: false, quiet: false, dereference: false, "no-dereference": false, from: "value", reference: "value", "preserve-root": false, "no-preserve-root": false, verbose: false, help: false, version: false } });
- const from = opts.from == null ? null : await resolveChownOwnerGroupSpec(opts.from);
- if (opts.help) {
- showGenericHelp("chown");
- return 0;
- }
- if (opts.version) {
- stdout(`${VERSION}\n`);
- return 0;
- }
- if (opts.reference != null && operands.length < 1) throw new UsageError("missing operand", true);
- if (opts.reference == null && operands.length < 1) throw new UsageError("missing operand", true);
- if (opts.reference == null && operands.length < 2) throw new UsageError(`missing operand after '${operands[0]}'`, true);
- const files = opts.reference != null ? operands : operands.slice(1);
- let uid;
- let gid;
- if (opts.reference != null) {
- const ref = await referenceStat(opts.reference);
- uid = ref.uid;
- gid = ref.gid;
- } else {
- ({ uid, gid } = await resolveChownOwnerGroupSpec(operands[0], { warnDot: true }));
- }
- const ownershipSpec = opts.reference != null ? await chownOwnershipDisplay(uid, gid, { reportUid: true, reportGid: true }) : operands[0];
- const parsedOwnershipSpec = opts.reference == null ? parseChownSpec(operands[0]) : null;
- const failureKind = uid == null && gid != null ? "group" : "ownership";
- const failureSpec = uid == null && gid == null ? null : failureKind === "group" && parsedOwnershipSpec ? parsedOwnershipSpec.groupPart : ownershipSpec;
- const fromUid = from?.uid ?? null;
- const fromGid = from?.gid ?? null;
- let failed = false;
- const dereference = !(opts.h || opts["no-dereference"]) || opts.dereference;
- const traversal = opts.L ? "L" : opts.H ? "H" : "P";
- const preserveRoot = !!opts["preserve-root"] && !opts["no-preserve-root"];
- const changes = opts.c || opts.changes;
- const verbose = opts.v || opts.verbose;
- for (const file of files) {
- try {
- const ok = await chownPath(file, uid, gid, opts.R || opts.recursive, { dereference, traversal, preserveRoot, command: "chown", fromUid, fromGid, changes, verbose, silent: opts.f || opts.silent || opts.quiet, reportUid: uid != null, reportGid: gid != null, failureKind, failureSpec }, true, file);
- if (!ok) failed = true;
- } catch (error) {
- failed = true;
- if (verbose) stdout(chownFailureVerboseLine(file, { failureKind, failureSpec }));
- if (!(opts.f || opts.silent || opts.quiet)) stderr(chownErrorLine(file, error));
- }
- }
- return failed ? 1 : 0;
-}
-
-async function chgrpCmd(args) {
- const { opts, operands } = parseOptions(normalizeChownArgs(args), { short: { R: false, c: false, f: false, h: false, H: false, L: false, P: false, v: false }, long: { changes: false, recursive: false, silent: false, quiet: false, dereference: false, "no-dereference": false, from: "value", reference: "value", "preserve-root": false, "no-preserve-root": false, verbose: false, help: false, version: false } });
- let fromUid = null;
- let fromGid = null;
- if (opts.from != null) {
- // A bare --from value uses the same user-like parser as chown (and its
- // diagnostics), but denotes that numeric ID as the current group. With
- // OWNER:GROUP syntax, GNU uses the group portion.
- const from = await resolveChownOwnerGroupSpec(opts.from, { warnDot: true, warningCommand: "chgrp" });
- fromGid = from.gid ?? from.uid;
- }
- if (opts.help) {
- showGenericHelp("chgrp");
- return 0;
- }
- if (opts.version) {
- stdout(`${VERSION}\n`);
- return 0;
- }
- if (opts.reference != null && operands.length < 1) throw new UsageError("missing operand", true);
- if (opts.reference == null && operands.length < 1) throw new UsageError("missing operand", true);
- if (opts.reference == null && operands.length < 2) throw new UsageError(`missing operand after '${operands[0]}'`, true);
- const files = opts.reference != null ? operands : operands.slice(1);
- const gid = opts.reference != null ? (await referenceStat(opts.reference)).gid : await resolveGroup(operands[0]);
- let failed = false;
- const dereference = !(opts.h || opts["no-dereference"]) || opts.dereference;
- const traversal = opts.L ? "L" : opts.H ? "H" : "P";
- const preserveRoot = !!opts["preserve-root"] && !opts["no-preserve-root"];
- const changes = opts.c || opts.changes;
- const verbose = opts.v || opts.verbose;
- const failureSpec = opts.reference != null ? await groupName(gid) : operands[0];
- for (const file of files) {
- try {
- const ok = await chownPath(file, null, gid, opts.R || opts.recursive, { dereference, traversal, preserveRoot, command: "chgrp", fromUid, fromGid, changes, verbose, silent: opts.f || opts.silent || opts.quiet, reportUid: false, reportGid: gid != null, failureKind: "group", failureSpec }, true, file);
- if (!ok) failed = true;
- } catch (error) {
- failed = true;
- if (verbose) stdout(chownFailureVerboseLine(file, { failureKind: "group", failureSpec }));
- if (!(opts.f || opts.silent || opts.quiet)) stderr(chgrpErrorLine(file, error));
- }
- }
- return failed ? 1 : 0;
-}
-
-function normalizeChownArgs(args) {
- const out = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(...args.slice(i));
- break;
- }
- if (arg.startsWith("--")) {
- const normalized = normalizeLongOptionByPrefix(arg, CHOWN_LONG_OPTIONS);
- if ((normalized === "--from" || normalized === "--reference") && i + 1 < args.length) {
- out.push(`${normalized}=${args[++i]}`);
- } else {
- out.push(normalized);
- }
- continue;
- }
- out.push(arg);
- }
- return out;
-}
-
-function parseChownSpec(spec) {
- if (spec === "") return { ownerPart: "", groupPart: null, separator: null };
- const colon = spec.indexOf(":");
- const dot = spec.indexOf(".");
- let index = colon;
- let separator = ":";
- if (index === -1 || (dot !== -1 && dot < index)) index = dot;
- if (index === dot) separator = ".";
- if (index === -1) return { ownerPart: spec, groupPart: null, separator: null };
- const ownerPart = spec.slice(0, index);
- const groupPart = spec.slice(index + 1);
- if (/^\d+$/.test(ownerPart) && groupPart === "" && separator === ":") throw new UsageError(`invalid spec: ${localeQuotedEscapedDiagnostic(spec)}`);
- return { ownerPart, groupPart, separator };
-}
-
-async function resolveChownOwnerGroupSpec(spec, options = {}) {
- const { ownerPart, groupPart, separator } = parseChownSpec(spec);
- if (separator === ".") {
- try {
- if (groupPart === "" && /^\d+$/.test(ownerPart)) throw new UsageError(`invalid user: ${localeQuotedEscapedDiagnostic(spec)}`);
- const uid = await resolveUser(ownerPart);
- const gid = groupPart == null ? null : await resolveGroup(groupPart);
- if (options.warnDot) stderr(`${options.warningCommand ?? "chown"}: warning: '.' should be ':': '${spec}'\n`);
- return { uid, gid };
- } catch {
- throw new UsageError(`invalid user: ${localeQuotedEscapedDiagnostic(spec)}`);
- }
- }
- let uid;
- try {
- uid = await resolveUser(ownerPart);
- } catch {
- if (groupPart === "") throw new UsageError(`invalid spec: ${localeQuotedEscapedDiagnostic(spec)}`);
- throw new UsageError(`invalid user: ${localeQuotedEscapedDiagnostic(spec)}`);
- }
- try {
- return { uid, gid: groupPart == null ? null : await resolveGroup(groupPart) };
- } catch {
- throw new UsageError(`invalid group: ${localeQuotedEscapedDiagnostic(spec)}`);
- }
-}
-
-async function chownPath(path, uid, gid, recursive, options = { dereference: true }, isRoot = false, display = path) {
- let ok = true;
- const linkInfo = await lstat(path);
- let operationInfo = linkInfo;
- let traversalInfo = linkInfo;
- const isLink = linkInfo.isSymbolicLink();
- const followForTraversal = isLink && recursive && (options.traversal === "L" || (isRoot && options.traversal === "H"));
- // Recursive -P changes a symlink itself. -H still dereferences symlinks for
- // the ownership operation, but only descends through a command-line one;
- // -L both dereferences and descends through every symlink.
- const shouldDereference = isLink && options.dereference && (!recursive || options.traversal !== "P");
- if (isLink && (shouldDereference || followForTraversal)) {
- try {
- const followedInfo = await stat(path);
- if (shouldDereference) operationInfo = followedInfo;
- if (followForTraversal) traversalInfo = followedInfo;
- } catch (error) {
- error.cannotDereference = true;
- throw error;
- }
- }
- if (recursive && options.preserveRoot && traversalInfo.isDirectory() && await isRecursiveRootTarget(path)) throw preserveRootError(options.command, path);
- const nextUid = uid ?? operationInfo.uid;
- const nextGid = gid ?? operationInfo.gid;
- const fromMatches = (options.fromUid == null || operationInfo.uid === options.fromUid) && (options.fromGid == null || operationInfo.gid === options.fromGid);
- if (recursive && traversalInfo.isDirectory() && (!isLink || followForTraversal)) {
- for (const entry of await readdirPathEntries(path)) {
- const childDisplay = `${String(display).replace(/\/+$/, "")}/${pathDisplayName(entry)}`;
- try {
- if (!(await chownPath(pathLikeJoin(path, entry), uid, gid, true, options, false, childDisplay))) ok = false;
- } catch (error) {
- ok = false;
- if (options.verbose) stdout(chownFailureVerboseLine(childDisplay, options));
- if (!options.silent) stderr(options.command === "chgrp" ? chgrpErrorLine(childDisplay, error) : chownErrorLine(childDisplay, error));
- }
- }
- }
- if (fromMatches) {
- if (isLink && !shouldDereference) await lchown(path, nextUid, nextGid);
- else await chown(path, nextUid, nextGid);
- const changed = operationInfo.uid !== nextUid || operationInfo.gid !== nextGid;
- if ((options.changes || options.verbose) && changed) stdout(await chownVerboseLine(options.command, display, operationInfo.uid, operationInfo.gid, nextUid, nextGid, options, true));
- else if (options.verbose) stdout(await chownVerboseLine(options.command, display, operationInfo.uid, operationInfo.gid, nextUid, nextGid, options, false));
- } else if (options.verbose) {
- stdout(await chownVerboseLine(options.command, display, operationInfo.uid, operationInfo.gid, operationInfo.uid, operationInfo.gid, options, false));
- }
- return ok;
-}
-
-function chownFailureVerboseLine(path, options) {
- const kind = options.failureKind === "group" ? "group" : "ownership";
- const suffix = options.failureSpec == null || options.failureSpec === "" ? "" : ` to ${options.failureSpec}`;
- return `failed to change ${kind} of ${chownQuotedName(path)}${suffix}\n`;
-}
-
-async function chownVerboseLine(command, path, beforeUid, beforeGid, afterUid, afterGid, options, changed) {
- if (command === "chgrp") {
- const before = await groupName(beforeGid);
- const after = await groupName(afterGid);
- return changed ? `changed group of ${chownQuotedName(path)} from ${before} to ${after}\n` : `group of ${chownQuotedName(path)} retained as ${after}\n`;
- }
- const before = await chownOwnershipDisplay(beforeUid, beforeGid, options);
- const after = await chownOwnershipDisplay(afterUid, afterGid, options);
- if (changed) return `changed ownership of ${chownQuotedName(path)}${before ? ` from ${before}` : ""}${after ? ` to ${after}` : ""}\n`;
- return `ownership of ${chownQuotedName(path)} retained${after ? ` as ${after}` : ""}\n`;
-}
-
-async function chownOwnershipDisplay(uid, gid, options) {
- const parts = [];
- if (options.reportUid) parts.push(await userNameForUid(uid) ?? String(uid));
- if (options.reportGid) parts.push(await groupName(gid));
- return parts.join(":");
-}
-
-async function installCmd(args, program = "install") {
- args = normalizeInstallLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { c: false, C: false, D: false, d: false, g: "value", m: "value", o: "value", p: false, t: "value", T: false, v: false, b: false, S: "value", s: false, Z: false }, long: { compare: false, debug: false, directory: false, group: "value", mode: "value", "no-target-directory": false, owner: "value", "preserve-context": false, "preserve-timestamps": false, verbose: false, backup: "optional-value", suffix: "value", strip: false, "strip-program": "value", "target-directory": "value", context: "optional-value", help: false, version: false } });
- if (opts.p) opts["preserve-timestamps"] = true;
- if (opts.b != null && opts.backup == null) opts.backup = opts.b;
- if (opts.S != null && opts.suffix == null) opts.suffix = opts.S;
- if (opts.b || opts.backup != null) validateBackupMode(program, opts.backup);
- if ((opts.C || opts.compare) && (opts.s || opts.strip)) throw new UsageError("options --compare (-C) and --strip are mutually exclusive", true);
- if (opts["strip-program"] != null && !(opts.s || opts.strip)) {
- stderr(`${program}: WARNING: ignoring --strip-program option as -s option was not specified\n`);
- }
- const verbose = opts.v || opts.verbose || opts.debug;
- const securityContext = installSecurityContextOptions(program, opts);
- if (opts.d || opts.directory) {
- if (!operands.length) throw new UsageError("missing file operand", true);
- const mode = opts.m || opts.mode ? parseInstallMode(opts.m ?? opts.mode) : undefined;
- const uid = await resolveUser(opts.o ?? opts.owner);
- const gid = await resolveGroup(opts.g ?? opts.group);
- let status = 0;
- await withSelinuxCreationContext(program, securityContext, async (created, sameThread) => {
- for (const dir of operands) {
- try {
- const existing = await lstat(dir).catch(() => null);
- if (existing && !existing.isDirectory()) {
- stderr(`${program}: cannot create directory ${installQuotedName(dir)}: File exists\n`);
- status = 1;
- continue;
- }
- await mkdirParents(dir, mode ?? 0o755, false, created, sameThread);
- if (mode !== undefined) await setFileMode(dir, mode);
- if (uid != null || gid != null) await chown(dir, uid ?? (await stat(dir)).uid, gid ?? (await stat(dir)).gid);
- if (verbose) stdout(`${program}: creating directory ${installQuotedName(dir)}\n`);
- } catch (error) {
- if (error instanceof UsageError && error.message.startsWith("failed to set default file creation context")) throw error;
- stderr(`${program}: cannot create directory ${installQuotedName(dir)}: ${errnoMessage(error)}\n`);
- status = 1;
- }
- }
- });
- return status;
- }
- const targetDirectory = opts.t ?? opts["target-directory"];
- const noTargetDirectory = opts.T || opts["no-target-directory"];
- if (targetDirectory != null && noTargetDirectory) throw new UsageError("cannot combine --target-directory and --no-target-directory");
- if (noTargetDirectory && operands.length > 2) throw new UsageError(`extra operand ${shellEscapeLsName(operands[2], true)}`, true);
- if (targetDirectory == null && operands.length < 2) throw installMissingOperandError(operands);
- if (targetDirectory != null && operands.length < 1) throw installMissingOperandError(operands);
- const mode = opts.m || opts.mode ? parseInstallMode(opts.m ?? opts.mode) : undefined;
- const uid = await resolveUser(opts.o ?? opts.owner);
- const gid = await resolveGroup(opts.g ?? opts.group);
- const dest = targetDirectory ?? operands.at(-1);
- const sources = targetDirectory == null ? operands.slice(0, -1) : operands;
- let destStat = await stat(dest).catch(() => null);
- if (targetDirectory != null && !destStat) {
- if (opts.D) {
- try {
- await withSelinuxCreationContext(program, securityContext, (created, sameThread) => makeInstallParents(dest, opts, program, created, sameThread));
- destStat = await stat(dest);
- } catch (error) {
- stderr(`${program}: cannot create directory ${installQuotedName(dest)}: ${errnoMessage(error)}\n`);
- return 1;
- }
- } else {
- stderr(`${program}: failed to access ${installQuotedName(dest)}: No such file or directory\n`);
- return 1;
- }
- }
- if (targetDirectory != null && destStat && !destStat.isDirectory()) {
- stderr(`${program}: failed to access ${installQuotedName(dest)}: Not a directory\n`);
- return 1;
- }
- if (sources.length > 1 && !destStat?.isDirectory() && !opts.D) throw new UsageError(`target '${dest}' is not a directory`);
- if (noTargetDirectory && destStat?.isDirectory()) throw new UsageError(`cannot overwrite directory '${dest}' with non-directory '${sources[0]}'`);
- for (const src of sources) {
- const target = !noTargetDirectory && (targetDirectory != null || destStat?.isDirectory()) ? join(dest, pathBasename(src)) : dest;
- const srcStat = await stat(src).catch(() => null);
- if (!srcStat) {
- stderr(`${program}: cannot stat ${installQuotedName(src)}: No such file or directory\n`);
- return 1;
- }
- if (srcStat?.isDirectory()) {
- stderr(`${program}: omitting directory ${installQuotedName(src)}\n`);
- return 1;
- }
- const targetStat = await stat(target).catch(() => null);
- if (srcStat && targetStat && srcStat.dev === targetStat.dev && srcStat.ino === targetStat.ino) {
- const targetDisplay = targetDirectory != null && dest === "." ? `./${pathBasename(src)}` : target;
- stderr(`${program}: ${installQuotedName(src)} and ${installQuotedName(targetDisplay)} are the same file\n`);
- return 1;
- }
- if (opts.D || targetDirectory != null) {
- await withSelinuxCreationContext(program, securityContext, (created, sameThread) => makeInstallParents(pathDirname(target), opts, program, created, sameThread));
- }
- if ((opts.C || opts.compare) && await installTargetMatches(src, target, mode ?? 0o755, opts, securityContext, uid, gid)) continue;
- if (opts.b || opts.backup != null) await backupDestination(target, opts.suffix, opts.backup);
- if (await lstat(target).catch(() => null)) {
- await fsUnlink(target);
- if (opts.v || opts.verbose) stdout(`removed ${installQuotedName(target)}\n`);
- }
- const copyDebug = opts.debug ? { reflinkMode: "auto", sparseMode: "auto", debug: true } : {};
- await withSelinuxCreationContext(program, securityContext, async (created) => {
- await cpCopyFileContents(src, target, await stat(src), copyDebug);
- await created(target);
- });
- await setFileMode(target, mode ?? 0o755);
- if (uid != null || gid != null) {
- const s = await stat(target);
- await chown(target, uid ?? s.uid, gid ?? s.gid);
- }
- if (opts["preserve-timestamps"]) {
- const s = statAttachNanoseconds(await stat(src), src, true);
- await touchSetPathTimes(target, touchStatDate(s, "atime"), touchStatDate(s, "mtime"), false);
- }
- if ((opts.s || opts.strip) && !(await stripInstalledFile(target, opts["strip-program"], program))) return 1;
- await applyInstallSecurityContext(src, target, securityContext);
- if (verbose) stdout(`${installQuotedName(src)} -> ${installQuotedName(target)}\n`);
- if (opts.debug) stdout(cpDebugLine(copyDebug));
- }
- return 0;
-}
-
-function installSecurityContextOptions(program, opts) {
- const enabled = selinuxRuntimeEnabled();
- if (typeof opts.context === "string" && !enabled) stderr(`${program}: warning: ignoring --context; it requires an SELinux-enabled kernel\n`);
- if (opts["preserve-context"] && !enabled) stderr(`${program}: WARNING: ignoring --preserve-context; this kernel is not SELinux-enabled\n`);
- const explicitContext = typeof opts.context === "string" && enabled ? opts.context : null;
- const restoreContext = enabled && (opts.Z || opts.context === true);
- const preserveContext = enabled && Boolean(opts["preserve-context"]);
- if (preserveContext && (explicitContext != null || restoreContext)) {
- throw new InvocationError("cannot set target context and preserve it", 1, false);
- }
- return { enabled, explicitContext, restoreContext, preserveContext };
-}
-
-async function applyInstallSecurityContext(src, target, options) {
- if (!options.preserveContext) return;
- const context = selinuxSecurityContext(src);
- if (context == null) throw new UsageError(`failed to get security context of '${src}'`);
- if (!setSelinuxSecurityContext(target, context)) throw new UsageError(`failed to set the security context of '${target}'`);
-}
-
-async function ginstallCmd(args) {
- return installCmd(args, "ginstall");
-}
-
-function installMissingOperandError(operands) {
- return operands.length
- ? new UsageError(`missing destination file operand after '${operands.at(-1)}'`, true)
- : new UsageError("missing file operand", true);
-}
-
-function parseInstallMode(spec) {
- try {
- return /^[0-7]+$/.test(spec) ? Number.parseInt(spec, 8) : parseModeSpec(spec, 0, true, { ignoreUmask: true }).mode;
- } catch (error) {
- if (error instanceof UsageError && invalidModeDiagnosticValue(error.message) != null) {
- throw new UsageError(`invalid mode ${localeQuotedEscapedDiagnostic(spec)}`);
- }
- throw error;
- }
-}
-
-async function makeInstallParents(dir, opts, program = "install", created = async () => {}, sameThread = false) {
- if (!dir || dir === ".") return;
- const parts = [];
- let cursor = dir;
- while (cursor && cursor !== "." && !(await stat(cursor).catch(() => null))) {
- parts.push(cursor);
- cursor = pathDirname(cursor);
- }
- for (const path of parts.reverse()) {
- if (sameThread) mkdirSync(path);
- else await mkdir(path);
- await created(path);
- if (opts.v || opts.verbose) stdout(`${program}: creating directory ${installQuotedName(path)}\n`);
- }
-}
-
-function installQuotedName(path) {
- return shellEscapeLsName(pathDisplayName(path), true);
-}
-
-async function installTargetMatches(src, target, mode, opts, securityContext = {}, uid = null, gid = null) {
- const srcStat = await stat(src).then((s) => statAttachNanoseconds(s, src, true), () => null);
- const targetLinkStat = await lstat(target).catch(() => null);
- if (!srcStat || !targetLinkStat?.isFile()) return false;
- const targetStat = await stat(target);
- if ((mode & 0o7000) !== 0) return false;
- if ((targetStat.mode & 0o7777) !== mode) return false;
- const expectedUid = uid ?? process.getuid?.() ?? targetStat.uid;
- const expectedGid = gid ?? process.getgid?.() ?? targetStat.gid;
- if (targetStat.uid !== expectedUid || targetStat.gid !== expectedGid) return false;
- const [srcBytes, targetBytes] = await Promise.all([readFile(src), readFile(target)]);
- if (srcBytes.length !== targetBytes.length) return false;
- for (let i = 0; i < srcBytes.length; i++) if (srcBytes[i] !== targetBytes[i]) return false;
- if (securityContext.preserveContext && selinuxSecurityContext(src) !== selinuxSecurityContext(target)) return false;
- if (opts["preserve-timestamps"]) await touchSetPathTimes(target, touchStatDate(srcStat, "atime"), touchStatDate(srcStat, "mtime"), false);
- return true;
-}
-
-async function stripInstalledFile(target, stripProgramOption, program = "install") {
- const stripProgram = stripProgramOption ?? "strip";
- const stripTarget = target.startsWith("-") ? `./${target}` : target;
- try {
- const proc = Bun.spawn([stripProgram, stripTarget], { stdin: "ignore", stdout: "inherit", stderr: "inherit" });
- const code = await proc.exited;
- if (code === 0) return true;
- } catch (error) {
- stderr(`${program}: cannot run strip program ${installQuotedName(stripProgram)}: ${errnoMessage(error)}\n`);
- }
- await rm(target, { force: true });
- return false;
-}
-
-async function ddCmd(args) {
- args = args.filter((arg) => arg !== "--");
- for (const arg of args) if (arg.startsWith("-") || !arg.includes("=")) throw new UsageError(invalidOptionMessage(arg), true);
- const { options, parsed } = parseDdOperands(args);
- const hasBs = options.bs != null;
- const bs = parsed.bs ?? parseDdBlockSize(512);
- const ibs = hasBs ? bs : parsed.ibs ?? parseDdBlockSize(512);
- const obs = hasBs ? bs : parsed.obs ?? parseDdBlockSize(512);
- const cbs = parsed.cbs ?? 0;
- const iflags = new Set(String(options.iflag ?? "").split(",").filter(Boolean));
- const oflags = new Set(String(options.oflag ?? "").split(",").filter(Boolean));
- const conv = new Set(String(options.conv ?? "").split(",").filter(Boolean));
- const exclusiveOutput = conv.has("excl");
- const noCreateOutput = conv.has("nocreat");
- if (exclusiveOutput && noCreateOutput) return fail("dd", "cannot combine excl and nocreat");
- if (iflags.has("nolinks")) throw new UsageError(`invalid input flag: ${localeQuotedDiagnostic("nolinks")}`, true);
- if (oflags.has("nolinks")) throw new UsageError(`invalid output flag: ${localeQuotedDiagnostic("nolinks")}`, true);
- if ((iflags.has("nocache") && iflags.has("direct")) || (oflags.has("nocache") && oflags.has("direct"))) {
- return fail("dd", "cannot combine direct and nocache");
- }
- if (iflags.has("nocache") && !options.if && !fstatSync(0).isFile() && !fstatSync(0).isCharacterDevice()) {
- return fail("dd", "failed to discard cache for: 'standard input': Illegal seek");
- }
- if (iflags.has("nofollow") && options.if && lstatSync(options.if).isSymbolicLink()) throw new UsageError(`failed to open '${options.if}': Too many levels of symbolic links`);
- if (iflags.has("directory")) {
- const dirInput = options.if ? statSync(options.if) : fstatSync(0);
- if (!dirInput.isDirectory()) throw new UsageError(`failed to open '${options.if ?? "standard input"}': Not a directory`);
- }
- if (oflags.has("directory")) {
- if (options.of) throw new UsageError(`failed to open '${options.of}': Invalid argument`);
- throw new UsageError("setting flags for 'standard output': Not a directory");
- }
- const skipValue = options.skip ?? options.iseek;
- const seekValue = options.seek ?? options.oseek;
- const skipParsed = skipValue ? (options.skip != null ? parsed.skip : parsed.iseek) : null;
- const seekParsed = seekValue ? (options.seek != null ? parsed.seek : parsed.oseek) : null;
- const countParsed = options.count ? parsed.count : null;
- const skip = skipParsed ? skipParsed.value * (iflags.has("skip_bytes") || skipParsed.bytes ? 1 : ibs) : 0;
- const countValue = countParsed?.value;
- const countBytes = iflags.has("count_bytes") || Boolean(countParsed?.bytes);
- const count = countValue == null ? undefined : countBytes ? countValue : countValue * ibs;
- const seek = seekParsed ? seekParsed.value * (oflags.has("seek_bytes") || seekParsed.bytes ? 1 : obs) : 0;
- const startTime = performance.now();
- let statusRequested = false;
- let latestStats = null;
- let progressDisplayed = false;
- const requestStatus = () => { statusRequested = true; };
- process.on("SIGUSR1", requestStatus);
- const emitRequestedStatus = (stats) => {
- if (!statusRequested) return;
- statusRequested = false;
- if (progressDisplayed) {
- stderr("\n");
- progressDisplayed = false;
- }
- emitDdStatus(stats, options.status, startTime);
- };
- const progressTimer = options.status === "progress"
- ? setInterval(() => {
- if (latestStats) {
- emitDdProgress(latestStats, startTime);
- progressDisplayed = true;
- }
- }, 1000)
- : null;
- let result;
- let failure = null;
- // GNU dd reserves the active input/output block buffer when it must
- // simulate positioning on a non-seekable stream. Apart from matching its
- // allocation failure behavior, reserving only the relevant direction is
- // important: a large obs must not penalize input skipping, nor a large ibs
- // output seeking. Plain count=0 operations still allocate no data buffer.
- let positioningBuffer = null;
- const positioningBufferSize = skip > 0 ? Math.max(1, ibs) : seek > 0 ? Math.max(1, obs) : 0;
- const allocationLimitText = process.env.BNU_DD_ALLOCATION_LIMIT;
- const allocationLimit = /^\d+$/.test(allocationLimitText ?? "") ? Number(allocationLimitText) : null;
- if (allocationLimit != null && positioningBufferSize > allocationLimit) {
- process.off("SIGUSR1", requestStatus);
- if (progressTimer) clearInterval(progressTimer);
- return fail("dd", "memory exhausted");
- }
- try {
- if (positioningBufferSize > 0) positioningBuffer = Buffer.alloc(positioningBufferSize);
- } catch {
- process.off("SIGUSR1", requestStatus);
- if (progressTimer) clearInterval(progressTimer);
- return fail("dd", "memory exhausted");
- }
- try {
- result = await streamDdCopy({ input: options.if, output: options.of, skip, count, countValue, countBytes, seek, ibs, obs, cbs, syncBlock: hasBs ? bs : ibs, reblock: !hasBs, conv, iflags, oflags, exclusiveOutput, noCreateOutput, onStats: (stats) => {
- latestStats = stats;
- emitRequestedStatus(stats);
- } });
- } catch (error) {
- if (!options.of && error?.code === "EPIPE") return 0;
- if (!error?.ddStats) throw error;
- result = error.ddStats;
- failure = error;
- } finally {
- // Keep the positioning allocation live for the complete operation.
- void positioningBuffer?.byteLength;
- process.off("SIGUSR1", requestStatus);
- if (progressTimer) clearInterval(progressTimer);
- }
- if (failure) stderr(`dd: ${failure.ddMessage ?? outputWriteErrorMessage(failure)}\n`);
- if (result.skipPastInput && options.status !== "none") stderr(`dd: 'standard input': cannot skip to specified offset\n`);
- if (progressDisplayed) stderr("\n");
- emitDdStatus(result, options.status, startTime);
- return failure ? 1 : 0;
-}
-
-function parseDdOperands(args) {
- const options = {};
- const parsed = {};
- const blockSizeOperands = new Set(["ibs", "obs", "bs", "cbs"]);
- const byteCountOperands = new Set(["skip", "iseek", "seek", "oseek", "count"]);
- const known = new Set(["if", "of", ...blockSizeOperands, ...byteCountOperands, "conv", "iflag", "oflag", "status"]);
- for (const arg of args) {
- const idx = arg.indexOf("=");
- const name = arg.slice(0, idx);
- const value = arg.slice(idx + 1);
- if (!known.has(name)) throw new UsageError(`unrecognized operand ${ddNumberDiagnostic(arg)}`, true);
- if (blockSizeOperands.has(name)) parsed[name] = parseDdBlockSize(value);
- else if (byteCountOperands.has(name)) parsed[name] = parseDdByteCount(value);
- else if (name === "conv") validateDdListOption(value, "conversion", DD_CONVERSIONS);
- else if (name === "iflag") validateDdListOption(value, "input flag", DD_INPUT_FLAGS);
- else if (name === "oflag") validateDdListOption(value, "output flag", DD_OUTPUT_FLAGS);
- else if (name === "status" && !["none", "noxfer", "progress"].includes(value)) throw new UsageError(`invalid status level: ${localeQuotedEscapedDiagnostic(value)}`, true);
- options[name] = value;
- }
- return { options, parsed };
-}
-
-const DD_CONVERSIONS = new Set(["ascii", "ebcdic", "ibm", "block", "unblock", "lcase", "ucase", "sparse", "swab", "sync", "excl", "nocreat", "notrunc", "noerror", "fdatasync", "fsync"]);
-const DD_INPUT_FLAGS = new Set(["append", "direct", "directory", "dsync", "sync", "fullblock", "nonblock", "noatime", "noctty", "nofollow", "count_bytes", "skip_bytes", "nocache", "nolinks"]);
-const DD_OUTPUT_FLAGS = new Set(["append", "direct", "directory", "dsync", "sync", "nonblock", "noatime", "noctty", "nofollow", "seek_bytes", "nocache", "nolinks"]);
-let ddIoApi;
-
-function ddInterposedIoApi() {
- if (ddIoApi) return ddIoApi;
- const definitions = {
- fstat: { args: [FFIType.i32, FFIType.ptr], returns: FFIType.i32 },
- ftruncate: { args: [FFIType.i32, FFIType.i64], returns: FFIType.i32 },
- posix_fadvise: { args: [FFIType.i32, FFIType.i64, FFIType.i64, FFIType.i32], returns: FFIType.i32 },
- };
- const symbols = {};
- for (const [name, definition] of Object.entries(definitions)) {
- const address = libc.symbols.dlsym(0, ptr(Buffer.from(`${name}\0`)));
- symbols[name] = { ptr: address, ...definition };
- }
- ddIoApi = linkSymbols(symbols).symbols;
- return ddIoApi;
-}
-
-function ddErrnoMessage(errno) {
- return ({
- 1: "Operation not permitted",
- 5: "Input/output error",
- 9: "Bad file descriptor",
- 22: "Invalid argument",
- 29: "Illegal seek",
- 95: "Operation not supported",
- })[errno] ?? `error ${errno}`;
-}
-
-function validateDdListOption(value, label, valid) {
- if (value == null || value === "") return;
- for (const item of String(value).split(",")) {
- if (!valid.has(item)) throw new UsageError(`invalid ${label}: ${localeQuotedEscapedDiagnostic(item)}`, true);
- }
-}
-
-function parseDdBlockSize(value) {
- const parsed = parseDdByteCount(value);
- if (parsed.value === 0) throw new UsageError(`invalid number: ${ddNumberDiagnostic(value)}`);
- return parsed.value;
-}
-
-function emitDdStatus(result, status, startTime) {
- if (status === "none") return;
- if (status === "progress") stderr(`${result.bytes} byte copied\n`);
- stderr(`${result.inFull}+${result.inPartial} records in\n${result.outFull}+${result.outPartial} records out\n`);
- if (result.truncated) stderr(`${result.truncated} truncated record${result.truncated === 1 ? "" : "s"}\n`);
- if (status !== "noxfer") stderr(formatDdTransferStats(result.bytes, (performance.now() - startTime) / 1000));
-}
-
-function emitDdProgress(result, startTime) {
- const seconds = (performance.now() - startTime) / 1000;
- stderr(`\r${formatDdTransferStats(result.bytes, seconds).trimEnd()}`);
-}
-
-function formatDdTransferStats(bytes, seconds) {
- const unit = bytes === 1 ? "byte" : "bytes";
- if (bytes < 1000) return `${bytes} ${unit} copied\n`;
- const elapsed = Math.max(seconds, 0.000001);
- const rate = bytes / elapsed;
- return `${bytes} ${unit} (${formatDecimalBytes(bytes)}, ${formatBinaryBytes(bytes)}) copied, ${formatDdSeconds(elapsed)} s, ${formatDecimalBytes(rate)}/s\n`;
-}
-
-function formatDecimalBytes(bytes) {
- const units = ["B", "kB", "MB", "GB", "TB"];
- return formatScaledBytes(bytes, 1000, units);
-}
-
-function formatBinaryBytes(bytes) {
- const units = ["B", "KiB", "MiB", "GiB", "TiB"];
- return formatScaledBytes(bytes, 1024, units);
-}
-
-function formatScaledBytes(value, base, units) {
- let scaled = value;
- let unit = units[0];
- for (let i = 1; i < units.length && Math.abs(scaled) >= base; i++) {
- scaled /= base;
- unit = units[i];
- }
- const digits = scaled >= 100 || unit === "B" ? 0 : scaled >= 10 ? 1 : 2;
- return `${scaled.toFixed(digits).replace(/\.0+$/, "").replace(/(\.\d*?)0+$/, "$1")} ${unit}`;
-}
-
-function formatDdSeconds(seconds) {
- if (seconds >= 1) return seconds.toFixed(2).replace(/\.?0+$/, "");
- return seconds.toPrecision(3);
-}
-
-function parseDdByteCount(value) {
- const text = String(value);
- if (!text) throw new UsageError(`invalid number: ${ddNumberDiagnostic(value)}`);
- if (/^0[xX]/.test(text)) stderr(`dd: warning: ${localeQuotedDiagnostic("0x")} is a zero multiplier; use ${localeQuotedDiagnostic("00x")} if that is intended\n`);
- let total = 1n;
- let sawByteSuffix = false;
- for (const part of text.split(/[xX]/)) {
- if (!part) throw new UsageError(`invalid number: ${ddNumberDiagnostic(value)}`);
- const match = part.match(/^(\d+)([A-Za-z]*)$/);
- if (!match) throw new UsageError(`invalid number: ${ddNumberDiagnostic(value)}`);
- const scale = {
- "": 1n, c: 1n, C: 1n, w: 2n, W: 2n, b: 512n, B: 1n,
- k: 1024n, K: 1024n, KiB: 1024n, kiB: 1024n,
- m: 1024n ** 2n, M: 1024n ** 2n, MiB: 1024n ** 2n, miB: 1024n ** 2n,
- g: 1024n ** 3n, G: 1024n ** 3n, GiB: 1024n ** 3n, giB: 1024n ** 3n,
- t: 1024n ** 4n, T: 1024n ** 4n, TiB: 1024n ** 4n, tiB: 1024n ** 4n,
- P: 1024n ** 5n, PiB: 1024n ** 5n,
- E: 1024n ** 6n, EiB: 1024n ** 6n,
- Z: 1024n ** 7n, ZiB: 1024n ** 7n,
- Y: 1024n ** 8n, YiB: 1024n ** 8n,
- R: 1024n ** 9n, RiB: 1024n ** 9n,
- Q: 1024n ** 10n, QiB: 1024n ** 10n,
- KB: 1000n, kB: 1000n, MB: 1000n ** 2n, mB: 1000n ** 2n,
- GB: 1000n ** 3n, gB: 1000n ** 3n, TB: 1000n ** 4n, tB: 1000n ** 4n,
- PB: 1000n ** 5n, EB: 1000n ** 6n, ZB: 1000n ** 7n, YB: 1000n ** 8n,
- RB: 1000n ** 9n, QB: 1000n ** 10n,
- }[match[2]];
- if (!scale) throw new UsageError(`invalid number: ${ddNumberDiagnostic(value)}`);
- total *= BigInt(match[1]) * scale;
- if (total > 9223372036854775807n) throw new UsageError(`invalid number: ${ddNumberDiagnostic(value)}: Value too large for defined data type`);
- if (match[2] === "B") sawByteSuffix = true;
- }
- return { value: total > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(total), bytes: sawByteSuffix };
-}
-
-function ddNumberDiagnostic(value) {
- return shellEscapeLsName(String(value), true);
-}
-
-async function streamDdCopy({ input, output, skip, count, countValue, countBytes, seek, ibs, obs, cbs, syncBlock, reblock, conv, iflags, oflags, exclusiveOutput = false, noCreateOutput = false, onStats = null }) {
- const inputHandle = input ? await open(input, "r").catch((error) => {
- throw new UsageError(`failed to open '${input}': ${systemErrorMessage(error)}`);
- }) : null;
- let outputHandle = null;
- const sparse = conv.has("sparse");
- const append = oflags.has("append");
- const notrunc = conv.has("notrunc");
- let outputPosition = output && (seek || sparse) && !append ? seek : null;
- let bytes = 0;
- let inFull = 0;
- let inPartial = 0;
- let outFull = 0;
- let outPartial = 0;
- let truncated = 0;
- let skipPastInput = false;
- let inputBytesRead = 0;
- let reachedInputEof = false;
- const outputState = reblock ? { obs, buffer: Buffer.alloc(0) } : null;
- const blockState = conv.has("block") ? { cbs: cbs || ibs, record: [], truncated: 0, truncating: false } : null;
- const unblockState = (conv.has("unblock") || conv.has("ascii")) ? { cbs: cbs || ibs, record: [] } : null;
- const swabState = conv.has("swab") ? { pending: null } : null;
- const currentStats = () => ({ bytes, inFull, inPartial, outFull, outPartial, truncated, skipPastInput });
- const attachDdStats = (error, countPartial = false, message = null) => {
- if (countPartial) outPartial++;
- error.ddStats = currentStats();
- if (message) error.ddMessage = message;
- return error;
- };
- const writeChunk = async (chunk) => {
- if (!chunk.length) return;
- try {
- if (outputHandle) {
- const result = await writeDdOutput(outputHandle, chunk, outputPosition, obs, outputState, sparse);
- outFull += result.full;
- outPartial += result.partial;
- if (outputPosition != null) outputPosition += result.bytesWritten;
- } else {
- const result = writeDdOutputSync(1, chunk, obs, outputState, sparse && append);
- outFull += result.full;
- outPartial += result.partial;
- }
- bytes += chunk.length;
- } catch (error) {
- throw attachDdStats(error, Boolean(chunk.length));
- }
- };
- try {
- let skipped;
- try {
- skipped = inputHandle ? await discardFromHandle(inputHandle, skip) : discardStdinBytes(skip);
- } catch (error) {
- const message = error?.ddSeek
- ? `${headTailDiagnosticName(input ?? "standard input")}: cannot skip: ${error.ddSystemMessage}`
- : ddInputReadErrorMessage(input, error);
- throw attachDdStats(error, false, message);
- }
- skipPastInput = skipped < skip;
- if (output) {
- if (oflags.has("nofollow")) {
- try {
- if (lstatSync(output).isSymbolicLink()) throw new UsageError(`failed to open '${output}': Too many levels of symbolic links`);
- } catch (error) {
- if (error instanceof UsageError) throw error;
- if (error?.code !== "ENOENT") throw new UsageError(`failed to open '${output}': ${systemErrorMessage(error)}`);
- }
- }
- if (noCreateOutput) {
- try {
- statSync(output);
- } catch (error) {
- throw new UsageError(`failed to open '${output}': ${systemErrorMessage(error)}`);
- }
- }
- if (exclusiveOutput) {
- try {
- statSync(output);
- throw new UsageError(`failed to open '${output}': File exists`);
- } catch (error) {
- if (error instanceof UsageError) throw error;
- if (error?.code !== "ENOENT") throw new UsageError(`failed to open '${output}': ${systemErrorMessage(error)}`);
- }
- }
- const flag = ddOutputOpenFlag({ append, notrunc, seek, oflags });
- outputHandle = await open(output, flag).catch((error) => {
- if (error?.code === "ENOENT" && seek) return open(output, ddOutputOpenFlag({ append: false, notrunc: false, seek: false, oflags, createForSeek: true }));
- throw new UsageError(`failed to open '${output}': ${systemErrorMessage(error)}`);
- });
- outputPosition = append || (!seek && !sparse) ? null : seek;
- if (seek && !append && !notrunc) {
- const io = ddInterposedIoApi();
- if (io.ftruncate(outputHandle.fd, seek) !== 0) {
- const truncateErrno = libcErrno();
- const statBuffer = Buffer.alloc(256);
- if (io.fstat(outputHandle.fd, ptr(statBuffer)) !== 0) {
- throw new UsageError(`cannot fstat '${output}': ${ddErrnoMessage(libcErrno())}`);
- }
- const outputStats = fstatSync(outputHandle.fd);
- if (outputStats.isFile() || outputStats.isDirectory()) {
- throw new UsageError(`failed to truncate to ${seek} bytes in output file '${output}': ${ddErrnoMessage(truncateErrno)}`);
- }
- }
- }
- } else if (seek) {
- try {
- ddSeekFd(1, seek);
- } catch (error) {
- throw attachDdStats(error, false, `'standard output': cannot seek: ${error.ddSystemMessage ?? systemErrorMessage(error)}`);
- }
- }
- let remaining = count;
- let remainingRecords = countBytes ? undefined : countValue;
- const maxChunk = Math.max(1, Math.min(1024 * 1024, count ?? ibs));
- while ((remaining == null || remaining > 0) && (remainingRecords == null || remainingRecords > 0)) {
- const wanted = countBytes
- ? Math.min(maxChunk, remaining)
- : Math.min(Math.max(1, ibs), remaining ?? ibs);
- let chunk;
- try {
- chunk = iflags.has("fullblock")
- ? inputHandle ? await readDdFullChunkFromHandle(inputHandle, wanted) : readDdFullChunkFromStdin(wanted)
- : inputHandle ? await readDdChunkFromHandle(inputHandle, wanted) : readDdChunkFromStdin(wanted);
- } catch (error) {
- throw attachDdStats(error, false, ddInputReadErrorMessage(input, error));
- }
- if (chunk.length === 0) {
- reachedInputEof = true;
- break;
- }
- inputBytesRead += chunk.length;
- if (chunk.length < wanted) reachedInputEof = true;
- if (chunk.length === ibs) inFull++;
- else inPartial++;
- if (remaining != null) remaining -= chunk.length;
- if (remainingRecords != null) remainingRecords--;
- if (conv.has("sync") && chunk.length % syncBlock !== 0) {
- const padded = Buffer.alloc(Math.ceil(chunk.length / syncBlock) * syncBlock);
- Buffer.from(chunk).copy(padded);
- chunk = padded;
- }
- if (conv.has("ascii")) chunk = ddTranslateBytes(chunk, DD_EBCDIC_TO_ASCII);
- if (conv.has("lcase") || conv.has("ucase")) chunk = ddConvertCase(chunk, conv.has("ucase"));
- if (swabState) chunk = ddSwabChunk(chunk, swabState);
- if (blockState) chunk = ddBlockConvertChunk(chunk, blockState);
- if (unblockState) chunk = ddUnblockConvertChunk(chunk, unblockState);
- await writeChunk(chunk);
- onStats?.(currentStats());
- }
- if (blockState) {
- const chunk = ddBlockFlush(blockState);
- await writeChunk(chunk);
- truncated = blockState.truncated;
- }
- if (unblockState) {
- const chunk = ddUnblockFlush(unblockState);
- await writeChunk(chunk);
- }
- if (swabState?.pending != null) {
- const chunk = Buffer.from([swabState.pending]);
- await writeChunk(chunk);
- }
- const io = iflags.has("nocache") || oflags.has("nocache") || oflags.has("direct") ? ddInterposedIoApi() : null;
- if (inputHandle && iflags.has("nocache")) {
- // A zero length means "through EOF". Do that only when the copy
- // actually reached EOF (or count=0 explicitly requested a whole-file
- // cache drop); a count-limited copy must not evict the untouched tail.
- const adviceLength = reachedInputEof || countValue === 0 ? 0 : inputBytesRead;
- const adviceError = io.posix_fadvise(inputHandle.fd, skip, adviceLength, 4);
- if (adviceError !== 0) throw attachDdStats(new Error(), false, `failed to discard cache for: ${input}: ${ddErrnoMessage(adviceError)}`);
- }
- if (outputHandle && (oflags.has("nocache") || oflags.has("direct"))) {
- const adviceError = io.posix_fadvise(outputHandle.fd, 0, 0, 4);
- if (adviceError !== 0) throw attachDdStats(new Error(), false, `failed to discard cache for: ${output}: ${ddErrnoMessage(adviceError)}`);
- }
- } finally {
- if (outputState?.buffer.length) {
- try {
- if (outputHandle) {
- const result = await writeDdOutput(outputHandle, outputState.buffer, outputPosition, obs, null, sparse);
- if (outputPosition != null) outputPosition += result.bytesWritten;
- } else {
- writeDdOutputSync(1, outputState.buffer, obs, null, sparse && append);
- }
- outPartial++;
- outputState.buffer = Buffer.alloc(0);
- } catch (error) {
- throw attachDdStats(error, true);
- }
- }
- if (outputHandle && (conv.has("fdatasync") || conv.has("fsync"))) {
- try {
- if (conv.has("fdatasync")) await outputHandle.datasync();
- else await outputHandle.sync();
- } catch (error) {
- const statsError = attachDdStats(error, false, `fsync failed for '${output}': ${systemErrorMessage(error)}`);
- if (inputHandle) await inputHandle.close().catch(() => {});
- await outputHandle.close().catch(() => {});
- throw statsError;
- }
- }
- if (inputHandle) await inputHandle.close();
- if (outputHandle) await outputHandle.close();
- }
- if (output && sparse && !append && !notrunc) await truncate(output, outputPosition ?? seek);
- return { bytes, inFull, inPartial, outFull, outPartial, truncated, skipPastInput };
-}
-
-function ddOutputOpenFlag({ append, notrunc, seek, oflags, createForSeek = false }) {
- const synchronous = oflags.has("sync") || oflags.has("dsync");
- if (!synchronous) return append && notrunc ? "a" : !seek && !notrunc ? "w" : "r+";
- let flags;
- if (append && notrunc) flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND;
- else if (!seek && !notrunc) flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC;
- else flags = fsConstants.O_RDWR;
- if (createForSeek) flags = fsConstants.O_RDWR | fsConstants.O_CREAT | fsConstants.O_TRUNC;
- return flags | (oflags.has("sync") ? fsConstants.O_SYNC : fsConstants.O_DSYNC);
-}
-
-function ddInputReadErrorMessage(input, error) {
- return `error reading '${input ?? "standard input"}': ${systemErrorMessage(error)}`;
-}
-
-function ddTranslateBytes(chunk, table) {
- const out = Buffer.allocUnsafe(chunk.length);
- for (let i = 0; i < chunk.length; i++) out[i] = table[chunk[i]];
- return out;
-}
-
-async function writeDdOutput(handle, chunk, position, obs, reblockState, sparse = false) {
- if (!reblockState) {
- if (sparse && position != null && ddBufferIsZero(chunk)) {
- return { bytesWritten: chunk.length, full: chunk.length === obs ? 1 : 0, partial: chunk.length === obs ? 0 : chunk.length ? 1 : 0 };
- }
- const result = await handle.write(chunk, 0, chunk.length, position);
- return { bytesWritten: result.bytesWritten, full: chunk.length === obs ? 1 : 0, partial: chunk.length === obs ? 0 : chunk.length ? 1 : 0 };
- }
- let bytesWritten = 0;
- let full = 0;
- let offset = 0;
- let pos = position;
- let data = reblockState.buffer.length ? Buffer.concat([reblockState.buffer, chunk]) : chunk;
- while (offset < data.length) {
- const part = data.subarray(offset, offset + obs);
- if (part.length < obs) break;
- if (sparse && pos != null && ddBufferIsZero(part)) {
- bytesWritten += part.length;
- pos += part.length;
- } else {
- const result = await handle.write(part, 0, part.length, pos);
- bytesWritten += result.bytesWritten;
- if (pos != null) pos += result.bytesWritten;
- }
- full++;
- offset += part.length;
- }
- reblockState.buffer = data.subarray(offset);
- return { bytesWritten, full, partial: 0 };
-}
-
-function writeDdOutputSync(fd, chunk, obs, reblockState, skipSparse = false) {
- if (!reblockState) {
- if (!(skipSparse && ddBufferIsZero(chunk))) writeSync(fd, chunk);
- return { full: chunk.length === obs ? 1 : 0, partial: chunk.length === obs ? 0 : chunk.length ? 1 : 0 };
- }
- let full = 0;
- let data = reblockState.buffer.length ? Buffer.concat([reblockState.buffer, chunk]) : chunk;
- let offset = 0;
- while (offset < data.length) {
- const part = data.subarray(offset, offset + obs);
- if (part.length < obs) break;
- if (!(skipSparse && ddBufferIsZero(part))) writeSync(fd, part);
- full++;
- offset += part.length;
- }
- reblockState.buffer = data.subarray(offset);
- return { full, partial: 0 };
-}
-
-function ddBufferIsZero(chunk) {
- for (const byte of chunk) if (byte !== 0) return false;
- return true;
-}
-
-function ddConvertCase(chunk, upper) {
- const out = Buffer.from(chunk);
- for (let i = 0; i < out.length; i++) {
- const byte = out[i];
- if (upper && byte >= 0x61 && byte <= 0x7a) out[i] = byte - 0x20;
- else if (upper && byte === 0xe9) out[i] = 0xc9;
- else if (!upper && byte >= 0x41 && byte <= 0x5a) out[i] = byte + 0x20;
- else if (!upper && byte === 0xc9) out[i] = 0xe9;
- }
- return out;
-}
-
-function ddSwabChunk(chunk, state) {
- const out = [];
- let i = 0;
- if (state.pending != null) {
- if (chunk.length === 0) return Buffer.alloc(0);
- out.push(chunk[0], state.pending);
- state.pending = null;
- i = 1;
- }
- for (; i + 1 < chunk.length; i += 2) out.push(chunk[i + 1], chunk[i]);
- if (i < chunk.length) state.pending = chunk[i];
- return Buffer.from(out);
-}
-
-function ddBlockConvertChunk(chunk, state) {
- const out = [];
- for (const byte of chunk) {
- if (byte === 0x0a) {
- ddBlockEmitRecord(state, out);
- continue;
- }
- const mapped = byte === 0 ? 0x20 : byte;
- if (state.record.length < state.cbs) {
- state.record.push(mapped);
- } else if (!state.truncating) {
- state.truncated++;
- state.truncating = true;
- }
- }
- return Buffer.from(out);
-}
-
-function ddBlockFlush(state) {
- if (!state.record.length && !state.truncating) return Buffer.alloc(0);
- const out = [];
- ddBlockEmitRecord(state, out);
- return Buffer.from(out);
-}
-
-function ddBlockEmitRecord(state, out) {
- for (let i = 0; i < state.cbs; i++) out.push(state.record[i] ?? 0x20);
- state.record = [];
- state.truncating = false;
-}
-
-function ddUnblockConvertChunk(chunk, state) {
- const out = [];
- for (const byte of chunk) {
- state.record.push(byte);
- if (state.record.length === state.cbs) ddUnblockEmitRecord(state, out);
- }
- return Buffer.from(out);
-}
-
-function ddUnblockFlush(state) {
- if (!state.record.length) return Buffer.alloc(0);
- const out = [];
- ddUnblockEmitRecord(state, out);
- return Buffer.from(out);
-}
-
-function ddUnblockEmitRecord(state, out) {
- let end = state.record.length;
- while (end > 0 && (state.record[end - 1] === 0x20 || state.record[end - 1] === 0x00)) end--;
- for (let i = 0; i < end; i++) out.push(state.record[i]);
- out.push(0x0a);
- state.record = [];
-}
-
-async function readDdChunkFromHandle(handle, size) {
- const buffer = Buffer.allocUnsafe(size);
- const { bytesRead } = await handle.read(buffer, 0, size, null);
- return buffer.subarray(0, bytesRead);
-}
-
-function readDdChunkFromStdin(size) {
- const buffer = Buffer.allocUnsafe(size);
- const bytesRead = readSync(0, buffer, 0, size, null);
- return buffer.subarray(0, bytesRead);
-}
-
-async function readDdFullChunkFromHandle(handle, size) {
- const buffer = Buffer.allocUnsafe(size);
- let offset = 0;
- while (offset < size) {
- const { bytesRead } = await handle.read(buffer, offset, size - offset, null);
- if (bytesRead === 0) break;
- offset += bytesRead;
- }
- return buffer.subarray(0, offset);
-}
-
-function readDdFullChunkFromStdin(size) {
- const buffer = Buffer.allocUnsafe(size);
- let offset = 0;
- while (offset < size) {
- const bytesRead = readSync(0, buffer, offset, size - offset, null);
- if (bytesRead === 0) break;
- offset += bytesRead;
- }
- return buffer.subarray(0, offset);
-}
-
-function discardStdinBytes(bytes) {
- const sought = ddTrySeekFd(0, bytes);
- if (sought != null) return sought;
- const buffer = Buffer.allocUnsafe(Math.min(8192, Math.max(1, bytes)));
- let remaining = bytes;
- while (remaining > 0) {
- const n = readSync(0, buffer, 0, Math.min(buffer.length, remaining), null);
- if (n === 0) break;
- remaining -= n;
- }
- return bytes - remaining;
-}
-
-async function dircolors(args) {
- args = normalizeDircolorsLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { b: false, c: false, p: false }, long: { sh: false, "bourne-shell": false, csh: false, "c-shell": false, "print-database": false, "print-ls-colors": false, help: false, version: false } });
- const db = DEFAULT_DIRCOLORS_DATABASE;
- if (operands.length > 1) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[1])}`, true);
- if ((opts.p || opts["print-database"]) && (opts["print-ls-colors"] || opts["print-ls"])) throw new UsageError("options --print-database and --print-ls-colors are mutually exclusive", true);
- if ((opts.b || opts.sh || opts["bourne-shell"] || opts.c || opts.csh || opts["c-shell"]) && (opts.p || opts["print-database"])) {
- throw new UsageError("the options to output non shell syntax,\nand to select a shell syntax are mutually exclusive", true);
- }
- if ((opts.p || opts["print-database"]) && operands.length > 0) {
- throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}\nfile operands cannot be combined with --print-database (-p)`, true);
- }
- if (opts.p || opts["print-database"]) {
- stdout(db);
- return 0;
- }
- let input;
- if (operands[0]) {
- try {
- input = operands[0] === "-" ? await readStdinText() : await readFile(operands[0], "utf8");
- } catch (error) {
- const name = textInputDiagnosticName(operands[0]);
- const message = error?.code === "EISDIR" ? `${name}: read error: ${systemErrorMessage(error)}` : `${name}: ${systemErrorMessage(error)}`;
- stderr(`dircolors: ${message}\n`);
- return 1;
- }
- } else {
- input = db;
- }
- const parsed = dircolorsValue(input, operands[0] ?? null);
- if (opts["print-ls-colors"] || opts["print-ls"]) {
- stdout(parsed.parts.map((part) => {
- const [key, value] = part.split("=", 2);
- return `\x1b[${value.replaceAll("\\:", ":")}m${key}\t${value.replaceAll("\\:", ":")}\x1b[0m\n`;
- }).join(""));
- return 0;
- }
- const value = parsed.parts.length ? `${parsed.parts.join(":")}:` : "";
- if (opts.c || opts.csh || opts["c-shell"]) stdout(`setenv LS_COLORS '${value}'\n`);
- else stdout(`LS_COLORS='${shellSingleQuoteContent(value)}';\nexport LS_COLORS\n`);
- return 0;
-}
-
-const DEFAULT_DIRCOLORS_DATABASE = [
- "RESET 0",
- "DIR 01;34",
- "LINK 01;36",
- "MULTIHARDLINK 00",
- "FIFO 40;33",
- "SOCK 01;35",
- "DOOR 01;35",
- "BLK 40;33;01",
- "CHR 40;33;01",
- "ORPHAN 01;05;37;41",
- "MISSING 01;05;37;41",
- "SETUID 37;41",
- "SETGID 30;43",
- "CAPABILITY 00",
- "STICKY_OTHER_WRITABLE 30;42",
- "OTHER_WRITABLE 34;42",
- "STICKY 37;44",
- "EXEC 01;32",
- ".7z 01;31",
- ".ace 01;31",
- ".alz 01;31",
- ".apk 01;31",
- ".arc 01;31",
- ".arj 01;31",
- ".bz 01;31",
- ".bz2 01;31",
- ".cab 01;31",
- ".cpio 01;31",
- ".crate 01;31",
- ".deb 01;31",
- ".drpm 01;31",
- ".dwm 01;31",
- ".dz 01;31",
- ".ear 01;31",
- ".egg 01;31",
- ".esd 01;31",
- ".gz 01;31",
- ".jar 01;31",
- ".lha 01;31",
- ".lrz 01;31",
- ".lz 01;31",
- ".lz4 01;31",
- ".lzh 01;31",
- ".lzma 01;31",
- ".lzo 01;31",
- ".pyz 01;31",
- ".rar 01;31",
- ".rpm 01;31",
- ".rz 01;31",
- ".sar 01;31",
- ".swm 01;31",
- ".t7z 01;31",
- ".tar 01;31",
- ".taz 01;31",
- ".tbz 01;31",
- ".tbz2 01;31",
- ".tgz 01;31",
- ".tlz 01;31",
- ".txz 01;31",
- ".tz 01;31",
- ".tzo 01;31",
- ".tzst 01;31",
- ".udeb 01;31",
- ".war 01;31",
- ".whl 01;31",
- ".wim 01;31",
- ".xz 01;31",
- ".z 01;31",
- ".zip 01;31",
- ".zoo 01;31",
- ".zst 01;31",
- ".avif 01;35",
- ".jpg 01;35",
- ".jpeg 01;35",
- ".jxl 01;35",
- ".mjpg 01;35",
- ".mjpeg 01;35",
- ".gif 01;35",
- ".bmp 01;35",
- ".pbm 01;35",
- ".pgm 01;35",
- ".ppm 01;35",
- ".tga 01;35",
- ".xbm 01;35",
- ".xpm 01;35",
- ".tif 01;35",
- ".tiff 01;35",
- ".png 01;35",
- ".svg 01;35",
- ".svgz 01;35",
- ".mng 01;35",
- ".pcx 01;35",
- ".mov 01;35",
- ".mpg 01;35",
- ".mpeg 01;35",
- ".m2v 01;35",
- ".mkv 01;35",
- ".webm 01;35",
- ".webp 01;35",
- ".ogm 01;35",
- ".mp4 01;35",
- ".m4v 01;35",
- ".mp4v 01;35",
- ".vob 01;35",
- ".qt 01;35",
- ".nuv 01;35",
- ".wmv 01;35",
- ".asf 01;35",
- ".rm 01;35",
- ".rmvb 01;35",
- ".flc 01;35",
- ".avi 01;35",
- ".fli 01;35",
- ".flv 01;35",
- ".gl 01;35",
- ".dl 01;35",
- ".xcf 01;35",
- ".xwd 01;35",
- ".yuv 01;35",
- ".cgm 01;35",
- ".emf 01;35",
- ".ogv 01;35",
- ".ogx 01;35",
- ".cfg 00;32",
- ".conf 00;32",
- ".diff 00;32",
- ".doc 00;32",
- ".ini 00;32",
- ".log 00;32",
- ".patch 00;32",
- ".pdf 00;32",
- ".ps 00;32",
- ".tex 00;32",
- ".txt 00;32",
- ".aac 00;36",
- ".au 00;36",
- ".flac 00;36",
- ".m4a 00;36",
- ".mid 00;36",
- ".midi 00;36",
- ".mka 00;36",
- ".mp3 00;36",
- ".mpc 00;36",
- ".ogg 00;36",
- ".ra 00;36",
- ".wav 00;36",
- ".oga 00;36",
- ".opus 00;36",
- ".spx 00;36",
- ".xspf 00;36",
- "*~ 00;90",
- "*# 00;90",
- ".bak 00;90",
- ".crdownload 00;90",
- ".dpkg-dist 00;90",
- ".dpkg-new 00;90",
- ".dpkg-old 00;90",
- ".dpkg-tmp 00;90",
- ".old 00;90",
- ".orig 00;90",
- ".part 00;90",
- ".rej 00;90",
- ".rpmnew 00;90",
- ".rpmorig 00;90",
- ".rpmsave 00;90",
- ".swp 00;90",
- ".tmp 00;90",
- ".ucf-dist 00;90",
- ".ucf-new 00;90",
- ".ucf-old 00;90",
- "",
-].join("\n");
-
-function dircolorsMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const normalized = normalizeDircolorsLongOption(arg);
- const name = normalized.slice(2).split("=", 1)[0];
- if (!DIRCOLORS_LONG_OPTIONS.includes(name) || normalized.includes("=")) return null;
- if (normalized === "--help" || normalized === "--version") return normalized;
- continue;
- }
- if (arg === "-b" || arg === "-c" || arg === "-p") continue;
- if (arg.startsWith("-") && arg !== "-") return null;
- }
- return null;
-}
-
-function normalizeDircolorsLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, DIRCOLORS_LONG_OPTIONS);
-}
-
-function normalizeDircolorsLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, DIRCOLORS_LONG_OPTIONS);
-}
-
-async function readStdinText() {
- const data = await Bun.stdin.arrayBuffer();
- return new TextDecoder().decode(data);
-}
-
-function dircolorsValue(db, sourceName = null) {
- const keys = {
- RESET: "rs",
- NORMAL: "no",
- FILE: "fi",
- DIR: "di",
- LINK: "ln",
- FIFO: "pi",
- SOCK: "so",
- DOOR: "do",
- BLK: "bd",
- CHR: "cd",
- ORPHAN: "or",
- MISSING: "mi",
- SETUID: "su",
- SETGID: "sg",
- CAPABILITY: "ca",
- STICKY_OTHER_WRITABLE: "tw",
- OTHER_WRITABLE: "ow",
- STICKY: "st",
- EXEC: "ex",
- MULTIHARDLINK: "mh",
- OWT: "tw",
- LEFTCODE: "lc",
- RIGHTCODE: "rc",
- ENDCODE: "ec",
- };
- const parts = [];
- let active = true;
- let sawSelector = false;
- let lineNo = 0;
- for (const raw of db.split("\n")) {
- lineNo++;
- const line = raw.trimStart().startsWith("#") ? "" : raw.replace(/\s+#.*/, "").trim();
- if (!line) continue;
- const match = line.match(/^(\S+)(?:\s+(.+))?$/);
- const key = match?.[1]?.toUpperCase();
- let value = match?.[2];
- if (!value) throw new UsageError(`${sourceName ? `${sourceName}:` : ""}${lineNo}: invalid line; missing second token`);
- if (key === "TERM" || key === "COLORTERM") {
- sawSelector = true;
- const envValue = key === "TERM" ? process.env.TERM ?? "none" : process.env.COLORTERM ?? "";
- active = globMatch(value, envValue);
- continue;
- }
- if (!sawSelector || active) {
- const mapped = keys[key];
- if (mapped) parts.push(`${mapped}=${dircolorsEscapeValue(value)}`);
- else if (key.startsWith(".")) parts.push(`*${match[1]}=${dircolorsEscapeValue(value)}`);
- else if (key.startsWith("*")) parts.push(`${match[1]}=${dircolorsEscapeValue(value)}`);
- }
- }
- return { parts };
-}
-
-function dircolorsEscapeValue(value) {
- let out = "";
- let escaped = false;
- for (const ch of value) {
- if (escaped) {
- out += ch === ":" ? "\\:" : `\\${ch}`;
- escaped = false;
- } else if (ch === "\\") {
- escaped = true;
- } else {
- out += ch === ":" ? "\\:" : ch;
- }
- }
- if (escaped) out += "\\";
- return out;
-}
-
-function shellSingleQuoteContent(value) {
- return value.replaceAll("'", "'\\''");
-}
-
-function globMatch(pattern, value) {
- let regex = "";
- for (let i = 0; i < pattern.length; i++) {
- const ch = pattern[i];
- if (ch === "*") regex += ".*";
- else if (ch === "?") regex += ".";
- else if (ch === "[") {
- const end = pattern.indexOf("]", i + 1);
- if (end === -1) regex += "\\[";
- else {
- let body = pattern.slice(i + 1, end);
- if (body.startsWith("!")) body = `^${body.slice(1)}`;
- regex += `[${body.replace(/\\/g, "\\\\")}]`;
- i = end;
- }
- } else {
- regex += ch.replace(/[.+^${}()|\\]/g, "\\$&");
- }
- }
- return new RegExp(`^${regex}$`).test(value);
-}
-
-function shredMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- let normalized = arg;
- if (arg.startsWith("--")) normalized = normalizeLongOptionByPrefix(arg, SHRED_LONG_OPTIONS);
- const [name, inlineValue] = normalized.startsWith("--") ? normalized.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if ((normalized === "--help" || normalized === "--version") && inlineValue == null) return normalized;
- if (["exact", "force", "verbose", "zero"].includes(name)) {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- continue;
- }
- if (["iterations", "size", "random-source"].includes(name)) {
- if (inlineValue !== undefined) {
- if (name === "iterations") parseShredPasses(inlineValue);
- if (name === "size") validateShredSizeOption(inlineValue);
- } else if (i + 1 < args.length) {
- if (name === "iterations") parseShredPasses(args[i + 1]);
- if (name === "size") validateShredSizeOption(args[i + 1]);
- i++;
- }
- continue;
- }
- if (name === "remove") {
- if (inlineValue !== undefined) validateShredRemoveMode(inlineValue);
- continue;
- }
- if (/^-[^-]/.test(arg)) {
- for (let j = 1; j < arg.length; j++) {
- const short = arg[j];
- if (short !== "n" && short !== "s") continue;
- const value = arg.slice(j + 1);
- if (value) {
- if (short === "n") parseShredPasses(value);
- else validateShredSizeOption(value);
- } else if (i + 1 < args.length) {
- if (short === "n") parseShredPasses(args[i + 1]);
- else validateShredSizeOption(args[i + 1]);
- i++;
- }
- break;
- }
- continue;
- }
- if (arg.startsWith("-")) continue;
- continue;
- }
- return null;
-}
-
-function normalizeShredArgs(args) {
- const out = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(...args.slice(i));
- break;
- }
- if (arg.startsWith("--")) {
- const normalized = normalizeLongOptionByPrefix(arg, SHRED_LONG_OPTIONS);
- out.push(normalized);
- if (["--iterations", "--random-source", "--size"].includes(normalized) && i + 1 < args.length) {
- out.push(args[++i]);
- }
- continue;
- }
- out.push(arg);
- if ((arg === "-n" || arg === "-s") && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-async function shredCmd(args) {
- const { opts, operands } = parseOptions(normalizeShredArgs(args), { short: { f: false, n: "value", s: "value", x: false, z: false, u: false, v: false }, long: { exact: false, force: false, iterations: "value", "random-source": "value", size: "value", zero: false, remove: "optional-value", verbose: false } });
- if (!operands.length) throw new UsageError("missing file operand", true);
- const passes = parseShredPasses(opts.n ?? opts.iterations ?? 3);
- const removeMode = parseShredRemoveMode(opts.remove ?? (opts.u ? true : false));
- let requestedSize = null;
- if (opts.s != null || opts.size != null) {
- const sizeText = opts.s ?? opts.size;
- requestedSize = validateShredSizeOption(sizeText);
- }
- let randomReader = null;
- if (opts["random-source"]) {
- try {
- randomReader = shredRandomSourceReader(opts["random-source"]);
- } catch (error) {
- stderr(`shred: ${opts["random-source"]}: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- }
- try {
- for (const file of operands) {
- const display = shredQuotedName(file);
- try {
- const s = await stat(file);
- if (removeMode !== false && !(opts.f || opts.force) && !(s.mode & 0o200)) {
- stderr(`shred: ${display}: Permission denied\n`);
- return 1;
- }
- if (opts.f || opts.force) await setFileMode(file, (s.mode & 0o777) | 0o200).catch(() => {});
- const size = requestedSize ?? Number(s.size);
- for (let pass = 0; size > 0 && pass < passes; pass++) {
- let bytes;
- try {
- bytes = shredRandomBytes(size, randomReader);
- } catch (error) {
- if (error?.code === "SHRED_RANDOM_EOF") {
- stderr(`shred: ${localeQuotedDiagnostic(opts["random-source"])}: end of file\n`);
- return 1;
- }
- throw error;
- }
- await writeFile(file, bytes);
- if (opts.v || opts.verbose) stderr(`shred: ${display}: pass ${pass + 1}/${passes} (${shredPassName(pass, passes)})...\n`);
- }
- if (opts.z || opts.zero) {
- await writeFile(file, new Uint8Array(size));
- if (opts.v || opts.verbose) stderr(`shred: ${display}: pass ${passes + 1}/${passes + 1} (000000)...\n`);
- }
- if (removeMode !== false) {
- if (opts.v || opts.verbose) {
- stderr(`shred: ${display}: removing\n`);
- if (removeMode !== "unlink") {
- if (pathBasename(file) === "test") {
- stderr(`shred: ${display}: renamed to 0000\nshred: 0000: renamed to 001\nshred: 001: renamed to 00\n`);
- } else {
- stderr(`shred: ${display}: renamed to 0\n`);
- }
- }
- }
- await rm(file);
- if (opts.v || opts.verbose) stderr(`shred: ${display}: removed\n`);
- }
- } catch (error) {
- stderr(`shred: ${display}: failed to open for writing: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- }
- return 0;
- } finally {
- randomReader?.close();
- }
-}
-
-function shredQuotedName(path) {
- return textInputDiagnosticName(path);
-}
-
-function shredRandomBytes(size, randomReader) {
- if (!randomReader) return crypto.getRandomValues(new Uint8Array(size));
- const out = new Uint8Array(size);
- let offset = 0;
- while (offset < out.length) {
- const n = randomReader.read(out, offset);
- if (n === 0) {
- const error = new Error("end of file");
- error.code = "SHRED_RANDOM_EOF";
- throw error;
- }
- offset += n;
- }
- return out;
-}
-
-function shredRandomSourceReader(source) {
- const fd = openSync(source, "r");
- return {
- read(buffer, offset) {
- return readSync(fd, buffer, offset, buffer.length - offset, null);
- },
- close() {
- closeSync(fd);
- },
- };
-}
-
-function validateShredRemoveMode(value) {
- parseShredRemoveMode(value);
-}
-
-function parseShredRemoveMode(value) {
- if (value === false || value === true) return value;
- const text = String(value);
- const valid = ["unlink", "wipe", "wipesync"];
- if (valid.includes(text)) return text;
- const matches = valid.filter((mode) => mode.startsWith(text));
- if (matches.length === 1 && text !== "") return matches[0];
- const kind = text === "" || matches.length > 1 ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic("--remove")}\nValid arguments are:\n - ${localeQuotedDiagnostic("unlink")}\n - ${localeQuotedDiagnostic("wipe")}\n - ${localeQuotedDiagnostic("wipesync")}`, true);
-}
-
-function parseShredPasses(value) {
- const text = String(value);
- if (!/^\+?\d+$/.test(text)) throw new UsageError(`invalid number of passes: ${localeQuotedEscapedDiagnostic(value)}`);
- const parsed = BigInt(text);
- if (parsed > BigInt(Number.MAX_SAFE_INTEGER)) return Number.MAX_SAFE_INTEGER;
- return Number(parsed);
-}
-
-function validateShredSizeOption(value) {
- if (String(value).startsWith("-")) throw new UsageError(`invalid file size: ${localeQuotedEscapedDiagnostic(value)}`, false);
- try {
- return parseShredSize(value);
- } catch (error) {
- if (error instanceof UsageError) throw new UsageError(`invalid file size: ${localeQuotedEscapedDiagnostic(value)}`, false);
- throw error;
- }
-}
-
-function parseShredSize(value) {
- const text = String(value);
- if (/^0x[0-9a-f]+$/i.test(text)) return Number.parseInt(text, 16);
- if (/^0[0-7]+$/.test(text)) return Number.parseInt(text, 8);
- if (/^\d+B$/.test(text)) return Number(text.slice(0, -1));
- return parseGNUSize(text);
-}
-
-function shredPassName(pass, passes) {
- if (passes === 20) {
- return ["random", "ffffff", "924924", "888888", "db6db6", "777777", "492492", "bbbbbb", "555555", "aaaaaa", "random", "6db6db", "249249", "999999", "111111", "000000", "b6db6d", "eeeeee", "333333", "random"][pass] ?? "random";
- }
- return "random";
-}
-
-async function discardFromHandle(handle, bytes) {
- const sought = ddTrySeekFd(handle.fd, bytes);
- if (sought != null) return sought;
- const buffer = Buffer.alloc(Math.min(8192, Math.max(1, bytes)));
- let remaining = bytes;
- while (remaining > 0) {
- const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, remaining), null);
- if (bytesRead === 0) break;
- remaining -= bytesRead;
- }
- return bytes - remaining;
-}
-
-function ddTrySeekFd(fd, bytes) {
- if (bytes === 0) return 0;
- const current = libc.symbols.lseek(fd, 0n, SEEK_CUR);
- if (current < 0n) {
- if (libcErrno() === 29) return null;
- throw ddSeekError(libcErrno());
- }
- const target = current + BigInt(bytes);
- ddValidateDeviceSeek(fd, target);
- try {
- const info = fstatSync(fd);
- if (info.isFile() && target > BigInt(info.size)) {
- const available = BigInt(info.size) > current ? BigInt(info.size) - current : 0n;
- if (libc.symbols.lseek(fd, BigInt(info.size), SEEK_SET) < 0n) throw ddSeekError(libcErrno());
- return Number(available);
- }
- } catch (error) {
- if (error?.ddSeek) throw error;
- }
- if (libc.symbols.lseek(fd, BigInt(bytes), SEEK_CUR) < 0n) throw ddSeekError(libcErrno());
- return bytes;
-}
-
-function ddSeekFd(fd, offset) {
- const target = BigInt(offset);
- ddValidateDeviceSeek(fd, target);
- if (libc.symbols.lseek(fd, target, SEEK_SET) < 0n) throw ddSeekError(libcErrno());
-}
-
-function ddValidateDeviceSeek(fd, target) {
- let block = false;
- try {
- block = fstatSync(fd).isBlockDevice();
- } catch {}
- if (!block) return;
- const size = Buffer.alloc(8);
- if (libc.symbols.ioctl(fd, BLKGETSIZE64, ptr(size)) !== 0 || target > size.readBigUInt64LE(0)) throw ddSeekError(22);
-}
-
-function ddSeekError(errno) {
- const error = new Error(ddErrnoMessage(errno));
- error.ddSeek = true;
- error.ddSystemMessage = ddErrnoMessage(errno);
- return error;
-}
-
-async function passthroughCommand(args) {
- if (!args.length) throw new UsageError("missing operand");
- const proc = Bun.spawn(args, { stdin: "inherit", stdout: "inherit", stderr: "inherit" });
- return await proc.exited;
-}
-
-async function runconCmd(args) {
- const { opts, operands } = parseRunconArgs(normalizeRunconArgs(args));
- if (!operands.length) {
- const current = selinuxRuntimeEnabled() ? processSecurityContext() : null;
- if (current == null) return fail("runcon", "failed to get current context", 125);
- stdout(`${current}\n`);
- return 0;
- }
- const modifiesCurrent = opts.compute || opts.user != null || opts.role != null || opts.type != null || opts.range != null;
- let command = operands;
- let requestedContext = null;
- if (!modifiesCurrent) {
- requestedContext = operands[0];
- command = operands.slice(1);
- }
- if (!command.length) throw new InvocationError("no command specified");
- if (!selinuxRuntimeEnabled()) return fail("runcon", "runcon may be used only on a SELinux kernel", 125);
- const api = selinuxApi();
- if (!api) return fail("runcon", "runcon may be used only on a SELinux kernel", 125);
- let context;
- if (requestedContext != null) {
- context = runconModifyContext(api, requestedContext, {});
- if (context == null) return fail("runcon", `failed to create security context: '${requestedContext}'`, 125);
- } else {
- const current = processSecurityContext();
- if (current == null) return fail("runcon", "failed to get current context", 125);
- let base = current;
- if (opts.compute) {
- const fileContext = selinuxFileSecurityContext(api, command[0]);
- if (fileContext == null) return fail("runcon", `failed to get security context of '${command[0]}'`, 125);
- base = selinuxComputedProcessContext(api, current, fileContext);
- if (base == null) return fail("runcon", "failed to compute a new context", 125);
- }
- context = runconModifyContext(api, base, opts);
- if (context == null) return fail("runcon", `failed to create security context: '${base}'`, 125);
- }
- if (api.symbols.security_check_context(cstr(context)) !== 0) return fail("runcon", `invalid context: '${context}'`, 125);
- if (!setExecSecurityContext(api, context)) return fail("runcon", `unable to set security context '${context}'`, 125);
- const executable = opts.compute && !command[0].includes("/") ? `./${command[0]}` : command[0];
- try {
- if (await isKnownUnexecutableCommand(executable)) throw Object.assign(new Error("Permission denied"), { code: "EACCES" });
- const proc = Bun.spawn([executable, ...command.slice(1)], { stdin: "inherit", stdout: "inherit", stderr: "inherit" });
- return await proc.exited;
- } catch (error) {
- stderr(`runcon: '${command[0]}': ${commandSpawnErrorMessage(error)}\n`);
- return error?.code === "ENOENT" ? 127 : 126;
- } finally {
- clearExecSecurityContext(api);
- }
-}
-
-function selinuxAllocatedString(api, invoke) {
- const output = Buffer.alloc(8);
- if (invoke(ptr(output)) < 0) return null;
- const address = read.ptr(ptr(output), 0);
- if (!address) return null;
- try {
- return new CString(address).toString().replace(/[\0\r\n]+$/, "") || null;
- } finally {
- api.symbols.freecon(address);
- }
-}
-
-function selinuxFileSecurityContext(api, path) {
- return selinuxAllocatedString(api, (output) => api.symbols.getfilecon(cstrPath(path), output));
-}
-
-function selinuxComputedProcessContext(api, current, fileContext) {
- const processClass = api.symbols.string_to_security_class(cstr("process"));
- if (!processClass) return null;
- return selinuxAllocatedString(api, (output) => api.symbols.security_compute_create(cstr(current), cstr(fileContext), processClass, output));
-}
-
-function runconModifyContext(api, base, opts) {
- const context = api.symbols.context_new(cstr(base));
- if (!context) return null;
- try {
- for (const [name, setter] of [
- ["user", api.symbols.context_user_set],
- ["type", api.symbols.context_type_set],
- ["range", api.symbols.context_range_set],
- ["role", api.symbols.context_role_set],
- ]) {
- if (opts[name] != null && setter(context, cstr(opts[name])) !== 0) return null;
- }
- const value = api.symbols.context_str(context);
- return value ? new CString(value).toString() : null;
- } finally {
- api.symbols.context_free(context);
- }
-}
-
-function setExecSecurityContext(api, context) {
- try {
- if (api.symbols.setexeccon(cstr(context)) === 0) return true;
- } catch {}
- return lsmSetExecSecurityContext(context);
-}
-
-function clearExecSecurityContext(api) {
- try {
- if (api.symbols.setexeccon(null) === 0) return true;
- } catch {}
- return lsmSetExecSecurityContext(null);
-}
-
-function lsmSetExecSecurityContext(context) {
- const encoded = context == null ? Buffer.alloc(0) : Buffer.from(`${context}\0`);
- const record = Buffer.alloc(32 + encoded.length);
- record.writeBigUInt64LE(101n, 0);
- record.writeBigUInt64LE(BigInt(record.length), 16);
- record.writeBigUInt64LE(BigInt(encoded.length), 24);
- encoded.copy(record, 32);
- return Number(libc.symbols.syscall(460, 101, ptr(record), record.length, 0)) === 0;
-}
-
-function normalizeRunconArgs(args) {
- const out = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(...args.slice(i));
- break;
- }
- if (arg.startsWith("--")) {
- const normalized = normalizeInvocationLongOptionByPrefix(arg, RUNCON_LONG_OPTIONS);
- out.push(normalized);
- if (["--user", "--role", "--type", "--range"].includes(normalized) && i + 1 < args.length) out.push(args[++i]);
- continue;
- }
- out.push(arg);
- if (["-u", "-r", "-t", "-l"].includes(arg) && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-function parseRunconArgs(args) {
- const opts = {};
- const operands = [];
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- if (option.startsWith("--")) throw new InvocationError(`option '${option}' requires an argument`);
- throw new InvocationError(`option requires an argument -- '${option.slice(1)}'`);
- };
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- operands.push(...args.slice(i + 1));
- break;
- }
- if (arg === "-c" || arg === "--compute") {
- opts.compute = true;
- continue;
- }
- if (arg === "-u" || arg === "--user" || arg === "-r" || arg === "--role" || arg === "-t" || arg === "--type" || arg === "-l" || arg === "--range") {
- const name = runconOptionName(arg);
- if (opts[name] != null) throw new InvocationError(`multiple ${runconMultipleName(name)}`);
- opts[name] = requireValue(i, arg);
- i++;
- continue;
- }
- const inline = arg.match(/^--(user|role|type|range)=(.*)$/);
- if (inline) {
- if (opts[inline[1]] != null) throw new InvocationError(`multiple ${runconMultipleName(inline[1])}`);
- opts[inline[1]] = inline[2];
- continue;
- }
- const shortInline = arg.match(/^-(u|r|t|l)(.+)$/);
- if (shortInline) {
- const name = runconOptionName(`-${shortInline[1]}`);
- if (opts[name] != null) throw new InvocationError(`multiple ${runconMultipleName(name)}`);
- opts[name] = shortInline[2];
- continue;
- }
- if (arg.startsWith("-")) throw new InvocationError(invalidOptionMessage(arg));
- operands.push(...args.slice(i));
- break;
- }
- return { opts, operands };
-}
-
-function runconOptionName(option) {
- return ({ "-u": "user", "--user": "user", "-r": "role", "--role": "role", "-t": "type", "--type": "type", "-l": "range", "--range": "range" })[option];
-}
-
-function runconMultipleName(name) {
- return ({ user: "users", role: "roles", type: "types", range: "levelranges" })[name];
-}
-
-async function coreutilsCmd(args) {
- if (args[0]?.startsWith("--coreutils-prog=")) {
- const program = args[0].slice("--coreutils-prog=".length);
- if (!program || !commands[program]) return fail("coreutils", `unknown program '${program}'`);
- return main([program, ...args.slice(1)]);
- }
- if (args[0]?.startsWith("--coreutils-prog-shebang=")) {
- const program = args[0].slice("--coreutils-prog-shebang=".length);
- if (!program || !commands[program]) return fail("coreutils", `unknown program '${program}'`);
- if (args.length < 2) return fail("coreutils", `unknown program '${program}'`);
- return main([program, ...args.slice(2)]);
- }
- if (!args.length) throw new UsageError("missing operand");
- if (args[0] === "--help") {
- stdout("Usage: coreutils --coreutils-prog=PROGRAM_NAME [PARAMETERS]...\n");
- stdout("Execute the PROGRAM_NAME built-in program with the given PARAMETERS.\n\n");
- stdout(" --help display this help and exit\n");
- stdout(" --version output version information and exit\n\n");
- stdout(`Built-in programs:\n ${commandNames.join(" ")}\n\n`);
- stdout("Use: 'coreutils --coreutils-prog=PROGRAM_NAME --help' for individual program help.\n");
- return 0;
- }
- if (args[0] === "--version") {
- stdout(`${VERSION}\n`);
- return 0;
- }
- if (args[0].startsWith("-")) throw new UsageError(invalidOptionMessage(args[0]), true);
- return main(args);
-}
-
-async function stdbufCmd(args) {
- const { command, env } = stdbufInvocation(args);
- if (!command.length) throw new InvocationError("missing operand");
- try {
- if (await isKnownUnexecutableCommand(command[0])) throw Object.assign(new Error("Permission denied"), { code: "EACCES" });
- const proc = Bun.spawn(command, { stdin: "inherit", stdout: "inherit", stderr: "inherit", env });
- return await proc.exited;
- } catch (error) {
- const status = stdbufSpawnStatus(command[0], error);
- stderr(`stdbuf: failed to run command '${command[0]}': ${commandSpawnErrorMessage(error)}\n`);
- return status;
- }
-}
-
-function commandSpawnErrorMessage(error) {
- if (error?.code === "ENOENT" || /not found/i.test(error?.message || "")) return "No such file or directory";
- if (error?.code === "EACCES" || /permission denied/i.test(error?.message || "")) return "Permission denied";
- if (error?.code === "EISDIR" || /is a directory/i.test(error?.message || "")) return "Is a directory";
- return error?.message || String(error);
-}
-
-function stdbufSpawnStatus(command, error) {
- if (command === ".") return 126;
- if (error?.code === "EACCES" || error?.code === "EISDIR") return 126;
- if (error?.code === "ENOENT") return 127;
- if (/not found/i.test(error?.message || "")) return 127;
- if (/permission denied|is a directory/i.test(error?.message || "")) return 126;
- return 1;
-}
-
-function stdbufInvocation(args) {
- let i = 0;
- let sawMode = false;
- const modes = {};
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- if (option.startsWith("--")) throw new InvocationError(`option '${option}' requires an argument`);
- throw new InvocationError(`option requires an argument -- '${option.slice(1)}'`);
- };
- const commandEnv = (command) => ({ command, env: stdbufChildEnv(modes) });
- while (i < args.length) {
- let arg = args[i];
- if (arg.startsWith("--") && arg !== "--") arg = normalizeLongOptionByPrefix(arg, STDBUF_LONG_OPTIONS);
- const [longName, inlineValue] = arg.startsWith("--") ? arg.slice(2).split(/=(.*)/s, 2) : [null, undefined];
- if ((longName === "help" || longName === "version") && inlineValue !== undefined) {
- throw new InvocationError(`option '--${longName}' doesn't allow an argument`);
- }
- if (arg === "--") {
- if (!sawMode) throw new InvocationError("missing operand");
- return commandEnv(args.slice(i + 1));
- }
- if (/^-[ioe].+/.test(arg)) {
- modes[arg[1]] = validateStdbufMode(arg[1], arg.slice(2));
- sawMode = true;
- i++;
- continue;
- }
- if (["-i", "-o", "-e", "--input", "--output", "--error"].includes(arg)) {
- const stream = arg === "--input" ? "i" : arg === "--output" ? "o" : arg === "--error" ? "e" : arg[1];
- modes[stream] = validateStdbufMode(stream, requireValue(i, arg));
- sawMode = true;
- i += 2;
- continue;
- }
- if (/^--(input|output|error)=/.test(arg)) {
- const [, name, mode] = arg.match(/^--(input|output|error)=(.*)$/s);
- modes[name[0]] = validateStdbufMode(name[0], mode);
- sawMode = true;
- i++;
- continue;
- }
- if (arg.startsWith("-")) throw new InvocationError(invalidOptionMessage(arg));
- if (!sawMode) throw new InvocationError("you must specify a buffering mode option");
- return commandEnv(args.slice(i));
- }
- return commandEnv([]);
-}
-
-function stdbufChildEnv(modes) {
- const env = { ...process.env };
- delete env._STDBUF_I;
- delete env._STDBUF_O;
- delete env._STDBUF_E;
- const library = findStdbufLibrary();
- if (library) env.LD_PRELOAD = env.LD_PRELOAD ? `${library}:${env.LD_PRELOAD}` : library;
- if (modes.i != null) env._STDBUF_I = modes.i;
- if (modes.o != null) env._STDBUF_O = modes.o;
- if (modes.e != null) env._STDBUF_E = modes.e;
- return env;
-}
-
-function findStdbufLibrary() {
- for (const path of ["/usr/libexec/coreutils/libstdbuf.so", "/usr/lib/coreutils/libstdbuf.so"]) {
- try {
- if (statSync(path).isFile()) return path;
- } catch {}
- }
- return null;
-}
-
-function validateStdbufMode(stream, mode) {
- if (mode == null) throw new InvocationError("missing mode");
- if (mode === "") throw new InvocationError(`invalid mode ${localeQuotedEscapedDiagnostic("")}`, 125, false);
- if (mode === "L") {
- if (stream === "i") throw new InvocationError("line buffering standard input is meaningless");
- return "L";
- }
- if (mode === "0") return "0";
- if (mode === "l") throw new InvocationError(`invalid mode ${localeQuotedEscapedDiagnostic("l")}`, 125, false);
- try {
- const size = parseStdbufSize(mode);
- return size.toString();
- } catch (error) {
- if (error instanceof InvocationError) throw error;
- throw new InvocationError(`invalid mode ${localeQuotedEscapedDiagnostic(mode)}`, 125, false);
- }
-}
-
-function parseStdbufSize(mode) {
- const text = /^\D+$/.test(mode) ? `1${mode}` : String(mode);
- const match = text.match(/^(\d+)([A-Za-z]*)$/);
- if (!match) throw new InvocationError(`invalid mode ${localeQuotedEscapedDiagnostic(mode)}`, 125, false);
- const binary = {
- "": 1n,
- K: 1024n, k: 1024n, KiB: 1024n, kiB: 1024n,
- M: 1024n ** 2n, m: 1024n ** 2n, MiB: 1024n ** 2n, miB: 1024n ** 2n,
- G: 1024n ** 3n, g: 1024n ** 3n, GiB: 1024n ** 3n, giB: 1024n ** 3n,
- T: 1024n ** 4n, t: 1024n ** 4n, TiB: 1024n ** 4n, tiB: 1024n ** 4n,
- P: 1024n ** 5n, PiB: 1024n ** 5n,
- E: 1024n ** 6n, EiB: 1024n ** 6n,
- Z: 1024n ** 7n, ZiB: 1024n ** 7n,
- Y: 1024n ** 8n, YiB: 1024n ** 8n,
- };
- const decimal = {
- KB: 1000n, kB: 1000n, MB: 1000n ** 2n, mB: 1000n ** 2n,
- GB: 1000n ** 3n, gB: 1000n ** 3n, TB: 1000n ** 4n, tB: 1000n ** 4n,
- PB: 1000n ** 5n, EB: 1000n ** 6n, ZB: 1000n ** 7n, YB: 1000n ** 8n,
- };
- const scale = binary[match[2]] ?? decimal[match[2]];
- if (!scale) throw new InvocationError(`invalid mode ${localeQuotedEscapedDiagnostic(mode)}`, 125, false);
- const amount = BigInt(match[1]) * scale;
- if (amount > 18446744073709551615n) throw new InvocationError(`invalid mode ${localeQuotedEscapedDiagnostic(mode)}: Value too large for defined data type`, 125, false);
- return amount;
-}
-
-async function who(args) {
- args = normalizeWhoLongOptions(args);
- const { opts, operands } = parseOptions(args, {
- short: { a: false, q: false, b: false, d: false, H: false, l: false, m: false, p: false, r: false, s: false, t: false, T: false, u: false, w: false },
- long: { all: false, count: false, boot: false, dead: false, heading: false, login: false, lookup: false, mesg: false, message: false, process: false, runlevel: false, short: false, time: false, users: false, writable: false, help: false, version: false },
- });
- if (operands.length > 2) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[2])}`, true);
- if (opts.m || operands.length === 2) {
- if (opts.q || opts.count) stdout("\n# users=0\n");
- else if (opts.H || opts.heading) stdout(formatWhoHeading(opts));
- return 0;
- }
- if (operands.length === 1 || operands.length === 0) {
- const defaultUtmp = operands.length === 0;
- const records = await readUtmpRecords(operands[0] ?? "/var/run/utmp");
- const users = await filterWhoUsers(records, defaultUtmp);
- if (opts.a || opts.all) {
- if (opts.H || opts.heading) stdout(formatWhoAllHeading());
- for (const record of records) {
- const rendered = record.type === 7 && record.user ? formatWhoRecord(record, { ...opts, T: true, u: true }) : formatWhoSpecialRecord(record, true);
- if (rendered) stdout(rendered);
- }
- const boot = whoBootRecord(records, defaultUtmp);
- if (boot) stdout(` system boot ${formatWhoDate(boot.time)}\n`);
- } else if (opts.b || opts.boot) {
- if (opts.H || opts.heading) stdout(formatWhoPidHeading());
- const boot = whoBootRecord(records, defaultUtmp);
- if (boot) stdout(` system boot ${formatWhoDate(boot.time)}\n`);
- } else if (opts.d || opts.dead) {
- if (opts.H || opts.heading) stdout(formatWhoIdlePidHeading(true));
- for (const record of records.filter((record) => record.type === 8)) stdout(formatWhoDeadRecord(record));
- } else if (opts.l || opts.login) {
- if (opts.H || opts.heading) stdout(formatWhoIdlePidHeading());
- for (const record of records.filter((record) => record.type === 6)) stdout(formatWhoLoginRecord(record));
- } else if (opts.p || opts.process) {
- if (opts.H || opts.heading) stdout(formatWhoPidHeading());
- for (const record of records.filter((record) => record.type === 5)) stdout(formatWhoProcessRecord(record));
- } else if (opts.r || opts.runlevel) {
- if (opts.H || opts.heading) stdout(formatWhoIdlePidHeading());
- for (const record of records.filter((record) => record.type === 1)) stdout(formatWhoRunlevelRecord(record));
- } else if (opts.t || opts.time) {
- if (opts.H || opts.heading) stdout(formatWhoPidHeading());
- for (const record of records.filter((record) => record.type === 3)) stdout(formatWhoClockChangeRecord(record));
- } else if (opts.q || opts.count) {
- stdout(`${users.map((record) => record.user).join(" ")}\n# users=${users.length}\n`);
- } else {
- if (opts.H || opts.heading) stdout(formatWhoHeading(opts));
- for (const record of users) stdout(formatWhoRecord(record, opts));
- }
- return 0;
- }
-}
-
-function whoMetaOption(args) {
- const shortOptions = new Set(["a", "q", "b", "d", "H", "l", "m", "p", "r", "s", "t", "T", "u", "w"]);
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const normalized = normalizeWhoLongOption(arg);
- const name = normalized.slice(2).split("=", 1)[0];
- if (!WHO_LONG_OPTIONS.includes(name) || normalized.includes("=")) return null;
- if (normalized === "--help" || normalized === "--version") return normalized;
- continue;
- }
- if (arg.startsWith("-") && arg !== "-") {
- for (let i = 1; i < arg.length; i++) if (!shortOptions.has(arg[i])) return null;
- }
- }
- return null;
-}
-
-function normalizeWhoLongOptions(args) {
- const out = [];
- for (const arg of args) out.push(arg.startsWith("--") && arg !== "--" ? normalizeWhoLongOption(arg) : arg);
- return out;
-}
-
-function normalizeWhoLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (name && !WHO_LONG_OPTIONS.includes(name) && name !== "mesg" && "message".startsWith(name)) {
- return eq === -1 ? "--message" : `--message=${body.slice(eq + 1)}`;
- }
- return normalizeLongOptionByPrefix(arg, WHO_LONG_OPTIONS);
-}
-
-async function filterWhoUsers(records, requireLiveLine = false) {
- const users = records.filter((record) => record.type === 7 && record.user);
- if (!requireLiveLine) return users;
- const live = [];
- for (const record of users) {
- if (record.line && statSyncNoThrow(`/dev/${record.line}`)) live.push(record);
- }
- return live;
-}
-
-function whoBootRecord(records, allowFallback = false) {
- const boots = records.filter((record) => record.time && record.type === 2);
- if (boots.length || !allowFallback) return boots.at(-1) ?? null;
- return records.filter((record) => record.time).sort((a, b) => a.time - b.time).at(-1) ?? null;
-}
-
-function formatWhoSpecialRecord(record, all = false) {
- if (record.type === 8) return formatWhoDeadRecord(record, all);
- if (record.type === 1) return formatWhoRunlevelRecord(record, all);
- if (record.type === 3) return formatWhoClockChangeRecord(record, all);
- if (record.type === 6) return formatWhoLoginRecord(record, all);
- if (record.type === 5) return formatWhoProcessRecord(record, all);
- return "";
-}
-
-function formatWhoClockChangeRecord(record, all = false) {
- const nameWidth = all ? 10 : 8;
- return `${"".padEnd(nameWidth)} clock change ${formatWhoDate(record.time)}\n`;
-}
-
-function formatWhoProcessRecord(record, all = false) {
- const nameWidth = all ? 10 : 8;
- const pidWidth = all ? 17 : 10;
- return `${"".padEnd(nameWidth)} ${record.line.padEnd(12)} ${formatWhoDate(record.time)} ${String(record.pid).padStart(pidWidth)} id=${record.id}\n`;
-}
-
-function formatWhoDeadRecord(record, all = false) {
- const nameWidth = all ? 10 : 8;
- return `${"".padEnd(nameWidth)} ${record.line.padEnd(12)} ${formatWhoDate(record.time)} ${String(record.pid).padStart(17)} id=${record.id.padEnd(5)} term=${record.exitTermination} exit=${record.exitStatus}\n`;
-}
-
-function formatWhoLoginRecord(record, all = false) {
- const nameWidth = all ? 10 : 8;
- return `${record.user.padEnd(nameWidth)} ${record.line.padEnd(12)} ${formatWhoDate(record.time)} ${String(record.pid).padStart(17)} id=${record.id}\n`;
-}
-
-function formatWhoRunlevelRecord(record, all = false) {
- const current = String.fromCharCode(record.pid & 0xff);
- const previous = String.fromCharCode((record.pid >> 8) & 0xff);
- const nameWidth = all ? 10 : 8;
- return `${"".padEnd(nameWidth)} run-level ${current} ${formatWhoDate(record.time)} ${"".padStart(18)}last=${previous === "N" ? "S" : previous}\n`;
-}
-
-function formatWhoRecord(record, opts = {}) {
- const showMessageStatus = opts.T || opts.w || opts.mesg || opts.message || opts.writable;
- const showIdle = opts.u || opts.users;
- const status = showMessageStatus ? ` ${whoMessageStatus(record.line)}` : "";
- const idle = showIdle ? whoIdleText(record.line) : "";
- const pid = showIdle ? String(record.pid).padStart(14) : "";
- const where = record.host ? ` (${record.host})` : "";
- return `${record.user.padEnd(8)}${status} ${record.line.padEnd(12)} ${formatWhoDate(record.time)}${showIdle ? `${idle.padStart(4)}${pid}` : ""}${where}\n`;
-}
-
-function formatWhoHeading(opts = {}) {
- const showMessageStatus = opts.T || opts.w || opts.mesg || opts.message || opts.writable;
- const showIdle = opts.u || opts.users;
- const name = showMessageStatus ? `${"NAME".padEnd(8)} ` : "NAME".padEnd(8);
- const suffix = showIdle ? ` ${"IDLE".padEnd(13)} PID COMMENT` : " COMMENT";
- return `${name} ${"LINE".padEnd(12)} ${"TIME".padEnd(whoUsesPosixDateFormat() ? 12 : 16)}${suffix}\n`;
-}
-
-function formatWhoPidHeading() {
- return `${"NAME".padEnd(8)} ${"LINE".padEnd(12)} ${"TIME".padEnd(whoUsesPosixDateFormat() ? 12 : 16)}${"".padEnd(7)} PID COMMENT\n`;
-}
-
-function formatWhoIdlePidHeading(exit = false) {
- return `${"NAME".padEnd(8)} ${"LINE".padEnd(12)} ${"TIME".padEnd(whoUsesPosixDateFormat() ? 12 : 16)} ${"IDLE".padEnd(13)} PID COMMENT${exit ? " EXIT" : ""}\n`;
-}
-
-function formatWhoAllHeading() {
- return `${formatWhoHeading({ T: true, u: true }).trimEnd()} EXIT\n`;
-}
-
-function whoMessageStatus(line) {
- const mode = statSyncNoThrow(`/dev/${line}`)?.mode;
- if (mode == null) return "?";
- return mode & 0o020 ? "+" : "-";
-}
-
-function whoIdleText(line) {
- const info = statSyncNoThrow(`/dev/${line}`);
- if (!info) return "?";
- const seconds = Math.max(0, Math.floor((Date.now() - info.atimeMs) / 1000));
- if (seconds < 60) return ".";
- if (seconds >= 24 * 60 * 60) return "old";
- return `${String(Math.floor(seconds / 3600)).padStart(2)}:${String(Math.floor((seconds % 3600) / 60)).padStart(2, "0")}`;
-}
-
-function formatWhoDate(seconds) {
- const date = new Date(seconds * 1000);
- const pad = (value) => String(value).padStart(2, "0");
- if (!whoUsesPosixDateFormat()) return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
- const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
- return `${months[date.getMonth()]} ${String(date.getDate()).padStart(2)} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
-}
-
-function whoUsesPosixDateFormat() {
- const locale = process.env.LC_ALL || process.env.LC_TIME || process.env.LANG || "";
- return locale === "C" || locale === "POSIX";
-}
-
-async function whoamiCmd(args) {
- args = normalizeHelpVersionOnlyLongOptions(args);
- const { operands } = parseOptions(args, { long: { help: false, version: false } });
- if (operands.length) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}`, true);
- const info = userInfo();
- stdout(`${await userNameForUid(process.getuid?.() ?? info.uid) ?? info.username}\n`);
- return 0;
-}
-
-async function dirCmd(args) {
- return lsCmd(["-C", "--quoting-style=escape", ...args]);
-}
-
-async function vdirCmd(args) {
- return lsCmd(["-l", "--quoting-style=escape", ...args]);
-}
-
-async function chrootCmd(args) {
- const { opts, operands } = parseChrootArgs(normalizeChrootArgs(args));
- if (!operands.length) throw new InvocationError("missing operand");
- const [root, ...requestedCommand] = operands;
- if (opts["skip-chdir"] && !(await chrootTargetIsOldRoot(root))) {
- throw new InvocationError("option --skip-chdir only permitted if NEWROOT is old '/'");
- }
- const outsideCredentials = await resolveChrootCredentials(opts).catch(() => null);
- if (libc.symbols.chroot(cstrPath(root)) !== 0) {
- const rootError = await chrootRootError(root) ?? ((process.getuid?.() ?? 1) !== 0 ? "Operation not permitted" : "Operation not permitted");
- return fail("chroot", `cannot change root directory to ${shellEscapeLsName(pathDisplayName(root), true)}: ${rootError}`, 125);
- }
- if (!opts["skip-chdir"]) {
- try {
- process.chdir("/");
- } catch (error) {
- return fail("chroot", `cannot chdir to root directory: ${systemErrorMessage(error)}`, 125);
- }
- }
- let credentials;
- try {
- credentials = await resolveChrootCredentials(opts, outsideCredentials);
- } catch (error) {
- return fail("chroot", error.message || String(error), 125);
- }
- const credentialError = applyChrootCredentials(credentials);
- if (credentialError) return fail("chroot", credentialError, 125);
- const command = requestedCommand.length ? requestedCommand : [process.env.SHELL || "/bin/sh", "-i"];
- if (!isDirectCommandInvocation()) {
- try {
- if (await isKnownUnexecutableCommand(command[0])) throw Object.assign(new Error("Permission denied"), { code: "EACCES" });
- const proc = Bun.spawn(command, { stdin: "inherit", stdout: "inherit", stderr: "inherit" });
- return await proc.exited;
- } catch (error) {
- const status = error?.code === "ENOENT" || String(error?.message ?? "").includes("not found") ? 127 : 126;
- stderr(`chroot: failed to run command '${command[0]}': ${commandSpawnErrorMessage(error)}\n`);
- return status;
- }
- }
- const execError = execCommand(command);
- const status = execError.errno === 2 ? 127 : 126;
- stderr(`chroot: failed to run command '${command[0]}': ${execError.message}\n`);
- return status;
-}
-
-function execCommand(command, options = {}) {
- const file = cstr(options.executable ?? command[0]);
- const strings = [options.argv0 ?? command[0], ...command.slice(1)].map(cstr);
- const argv = cStringVector(strings);
- if (options.env) {
- const environmentStrings = Object.entries(options.env).map(([name, value]) => cstr(`${name}=${value}`));
- const envp = cStringVector(environmentStrings);
- libc.symbols.execve(file, ptr(argv), ptr(envp));
- } else {
- libc.symbols.execvp(file, ptr(argv));
- }
- const errnoPointer = libc.symbols.__errno_location();
- const errno = errnoPointer ? read.i32(errnoPointer, 0) : 0;
- return {
- errno,
- message: errno === 2 ? "No such file or directory" : errno === 13 ? "Permission denied" : `execution failed (errno ${errno})`,
- };
-}
-
-function isDirectCommandInvocation() {
- return globalThis[Symbol.for("bnu.cli")] === true || import.meta.main;
-}
-
-function cStringVector(strings) {
- const vector = Buffer.alloc((strings.length + 1) * 8);
- strings.forEach((value, index) => vector.writeBigUInt64LE(BigInt(ptr(value)), index * 8));
- return vector;
-}
-
-async function resolveChrootCredentials(opts, fallback = null) {
- const userspec = opts.userspec;
- const groupsSpec = opts.groups;
- if (userspec == null && groupsSpec == null) return { uid: null, gid: null, groups: null };
- let uid = null;
- let gid = null;
- let username = null;
- let usedFallbackUser = false;
- if (userspec != null) {
- const separator = userspec.indexOf(":");
- const userToken = separator < 0 ? userspec : userspec.slice(0, separator);
- const groupToken = separator < 0 || separator === userspec.length - 1 ? null : userspec.slice(separator + 1);
- if (userToken !== "") {
- let user = await chrootUserToken(userToken).catch(() => null);
- if (!user && fallback?.user) {
- user = fallback.user;
- usedFallbackUser = true;
- }
- if (!user) throw new InvocationError(`invalid user ${localeQuotedDiagnostic(userToken)}`);
- uid = user.uid;
- username = user.name;
- if (groupToken == null) gid = user.gid;
- }
- if (groupToken != null && groupToken !== "") {
- gid = await chrootGroupToken(groupToken).catch(() => null) ?? fallback?.gid ?? null;
- if (gid == null) throw new InvocationError(`invalid group ${localeQuotedDiagnostic(groupToken)}`);
- }
- if (uid != null && gid == null && username == null) throw new InvocationError(`no group specified for unknown uid: ${uid}`);
- }
- let groups = null;
- if (groupsSpec != null) groups = await chrootSupplementaryGroups(groupsSpec, fallback?.groups);
- else if (uid != null && username != null) {
- groups = usedFallbackUser && fallback?.groups != null
- ? fallback.groups
- : orderedGroupIds(gid, await supplementaryGroupsForUser(username));
- }
- return { uid, gid, groups, user: uid == null ? null : { uid, gid, name: username } };
-}
-
-async function chrootUserToken(token) {
- const passwd = await readPasswd();
- if (!token.startsWith("+") && passwd.has(token)) return { ...passwd.get(token), name: token };
- const numeric = token.startsWith("+") ? token.slice(1) : token;
- if (!/^\d+$/.test(numeric)) return null;
- const uid = Number(numeric);
- if (!Number.isSafeInteger(uid) || uid < 0 || uid > 0xffffffff) return null;
- if (!token.startsWith("+")) {
- for (const [name, row] of passwd) if (row.uid === uid) return { ...row, name };
- }
- return { uid, gid: null, name: null };
-}
-
-async function chrootGroupToken(token) {
- const groups = await readGroup();
- if (!token.startsWith("+") && groups.has(token)) return groups.get(token);
- const numeric = token.startsWith("+") ? token.slice(1) : token;
- if (!/^\d+$/.test(numeric)) return null;
- const gid = Number(numeric);
- return Number.isSafeInteger(gid) && gid >= 0 && gid <= 0xffffffff ? gid : null;
-}
-
-async function chrootSupplementaryGroups(spec, fallback = null) {
- if (spec === "") return [];
- const tokens = spec.split(",").map((token) => token.trim()).filter(Boolean);
- if (!tokens.length) throw new InvocationError(`invalid group list ${localeQuotedDiagnostic(spec)}`);
- const groups = [];
- for (const token of tokens) {
- const gid = await chrootGroupToken(token).catch(() => null);
- if (gid == null) {
- if (fallback != null) return fallback;
- throw new InvocationError(`invalid group ${localeQuotedDiagnostic(token)}`);
- }
- groups.push(gid);
- }
- return groups;
-}
-
-function applyChrootCredentials(credentials) {
- if (credentials.groups != null || credentials.uid != null) {
- const groups = credentials.groups ?? [];
- const buffer = Buffer.alloc(groups.length * 4);
- groups.forEach((gid, index) => buffer.writeUInt32LE(gid >>> 0, index * 4));
- if (libc.symbols.setgroups(groups.length, groups.length ? ptr(buffer) : null) !== 0) return "failed to set supplemental groups";
- }
- if (credentials.gid != null && libc.symbols.setgid(credentials.gid) !== 0) return "failed to set group-ID";
- if (credentials.uid != null && libc.symbols.setuid(credentials.uid) !== 0) return "failed to set user-ID";
- return null;
-}
-
-async function chrootRootError(root) {
- try {
- const info = await stat(root);
- return info.isDirectory() ? null : "Not a directory";
- } catch (error) {
- return systemErrorMessage(error);
- }
-}
-
-async function chrootTargetIsOldRoot(root) {
- try {
- return await realpath(root) === "/";
- } catch {
- return resolve(root) === "/";
- }
-}
-
-function normalizeChrootArgs(args) {
- const out = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(...args.slice(i));
- break;
- }
- if (arg.startsWith("--")) {
- const normalized = normalizeInvocationLongOptionByPrefix(arg, CHROOT_LONG_OPTIONS);
- out.push(normalized);
- if ((normalized === "--groups" || normalized === "--userspec") && i + 1 < args.length) out.push(args[++i]);
- continue;
- }
- out.push(arg);
- }
- return out;
-}
-
-function parseChrootArgs(args) {
- const opts = {};
- const operands = [];
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- throw new InvocationError(`option '${option}' requires an argument`);
- };
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- operands.push(...args.slice(i + 1));
- break;
- }
- if (arg === "--skip-chdir") {
- opts["skip-chdir"] = true;
- continue;
- }
- if (arg === "--userspec" || arg === "--groups") {
- opts[arg.slice(2)] = requireValue(i, arg);
- i++;
- continue;
- }
- if (arg.startsWith("--userspec=")) {
- opts.userspec = arg.slice("--userspec=".length);
- continue;
- }
- if (arg.startsWith("--groups=")) {
- opts.groups = arg.slice("--groups=".length);
- continue;
- }
- if (arg.startsWith("-")) throw new InvocationError(invalidOptionMessage(arg));
- operands.push(arg, ...args.slice(i + 1));
- break;
- }
- return { opts, operands };
-}
-
-async function chconCmd(args) {
- const { opts, operands } = parseOptions(normalizeChconArgs(args), {
- short: { R: false, h: false, u: "value", r: "value", t: "value", l: "value", v: false },
- long: { recursive: false, dereference: false, "no-dereference": false, "no-preserve-root": false, "preserve-root": false, reference: "value", user: "value", role: "value", type: "value", range: "value", verbose: false },
- });
- const reference = opts.reference;
- const componentChange = opts.u != null || opts.user != null || opts.r != null || opts.role != null || opts.t != null || opts.type != null || opts.l != null || opts.range != null;
- if (reference !== undefined && componentChange) throw new UsageError("conflicting security context specifiers given", true);
- let context = null;
- if (reference !== undefined) {
- if (!operands.length) throw new UsageError("missing operand", true);
- await access(reference);
- context = selinuxSecurityContext(reference, opts.h || opts["no-dereference"]);
- if (context == null) throw new UsageError(`failed to get security context of '${reference}'`);
- for (const file of operands) await chconAccessPath(file, opts, context);
- return 0;
- }
- const files = componentChange ? operands : operands.slice(1);
- if (files.length < 1) throw new UsageError("missing operand", true);
- if (!componentChange) context = operands[0];
- for (const file of files) await chconAccessPath(file, opts, context);
- return 0;
-}
-
-function normalizeChconArgs(args) {
- const out = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(...args.slice(i));
- break;
- }
- if (arg.startsWith("--")) {
- const normalized = normalizeLongOptionByPrefix(arg, CHCON_LONG_OPTIONS);
- out.push(normalized);
- if (["--reference", "--user", "--role", "--type", "--range"].includes(normalized) && i + 1 < args.length) out.push(args[++i]);
- continue;
- }
- out.push(arg);
- if (["-u", "-r", "-t", "-l"].includes(arg) && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-async function chconAccessPath(path, opts, context = null) {
- const s = await lstat(path);
- if ((opts.R || opts.recursive) && s.isDirectory() && !s.isSymbolicLink()) {
- for (const entry of await readdirPathEntries(path)) await chconAccessPath(pathLikeJoin(path, entry), opts, context);
- }
- const noDereference = opts.h || opts["no-dereference"];
- const current = selinuxSecurityContext(path, noDereference);
- if (opts.v || opts.verbose) stdout(`changing security context of '${path}'\n`);
- if (context == null && current == null) throw new UsageError(`can't apply partial context to unlabeled file '${path}'`);
- const target = context ?? chconUpdatedContext(current, opts);
- if (target !== current) {
- if (!setSelinuxSecurityContext(path, target, noDereference)) throw new UsageError(`failed to change context of '${path}' to '${target}'`);
- }
-}
-
-function chconUpdatedContext(current, opts) {
- const parts = String(current).split(":");
- if (parts.length < 3) return current;
- const range = parts.slice(3).join(":");
- const user = opts.u ?? opts.user ?? parts[0];
- const role = opts.r ?? opts.role ?? parts[1];
- const type = opts.t ?? opts.type ?? parts[2];
- const newRange = opts.l ?? opts.range ?? range;
- return [user, role, type, newRange].filter((part, index) => index < 3 || part !== "").join(":");
-}
-
-async function csplitCmd(args) {
- args = normalizeCsplitLongOptionAbbreviations(args);
- const { opts, operands } = parseOptions(args, { short: { b: "value", f: "value", k: false, n: "value", q: false, s: false, z: false }, long: { "suffix-format": "value", prefix: "value", "keep-files": false, "suppress-matched": false, digits: "value", quiet: false, silent: false, "elide-empty-files": false, help: false, version: false } });
- if (!operands.length) throw new UsageError("missing operand", true);
- if (operands.length < 2) throw new UsageError(`missing operand after '${operands[0]}'`, true);
- const [file, ...patterns] = operands;
- const prefix = opts.f ?? opts.prefix ?? "xx";
- const digits = parseCsplitDigits(opts.n ?? opts.digits ?? 2);
- const suffixFormat = opts.b ?? opts["suffix-format"] ?? `%0${digits}d`;
- const quiet = opts.q || opts.s || opts.quiet || opts.silent;
- const elideEmpty = opts.z || opts["elide-empty-files"];
- const suppressMatched = opts["suppress-matched"];
- const streamingPattern = file === "-" && patterns.length === 1 ? parseCsplitRegexPattern(patterns[0]) : null;
- if (streamingPattern?.skip && streamingPattern.offset >= 0 && !suppressMatched) {
- return csplitStreamForwardSkip(streamingPattern, { prefix, suffixFormat, quiet, elideEmpty, pattern: patterns[0] });
- }
- let input;
- try {
- input = await readAll(file);
- } catch (error) {
- if (error?.code === "EISDIR") {
- const name = `${prefix}${formatCsplitSuffix(suffixFormat, 0)}`;
- if (!elideEmpty) {
- try {
- await writeFile(name, "");
- } catch (writeError) {
- stderr(`csplit: ${name}: ${nodeErrorMessage(writeError)}\n`);
- return 1;
- }
- if (!quiet) stdout("0\n");
- if (!(opts.k || opts["keep-files"])) await cleanupCsplitFiles([name]);
- }
- stderr(`csplit: read error: ${systemErrorMessage(error)}\n`);
- } else {
- stderr(file === "-" ? `csplit: ${nodeErrorMessage(error)}\n` : `csplit: cannot open ${shellEscapeLsName(pathDisplayName(file), true)} for reading: ${systemErrorMessage(error)}\n`);
- }
- return 1;
- }
- const lines = new TextDecoder().decode(input).split(/(?<=\n)/).filter(Boolean);
- const chunks = [];
- const suppressed = new Set();
- let start = 0;
- let lastCut = 0;
- let searchStart = 0;
- for (let patternIndex = 0; patternIndex < patterns.length; patternIndex++) {
- const pattern = patterns[patternIndex];
- if (/^\{(\*|\d+)\}$/.test(pattern)) continue;
- if (/^\d+$/.test(pattern)) {
- const lineNumber = Number(pattern);
- if (lineNumber <= 0) {
- stderr(`csplit: ${pattern}: line number must be greater than zero\n`);
- return 1;
- }
- const cut = lineNumber - 1;
- if (cut < lastCut) {
- stderr(`csplit: line number '${pattern}' is smaller than preceding line number, ${lastCut + 1}\n`);
- return 1;
- }
- if (cut > lines.length || (lines.length === 0 && lineNumber === 1)) {
- if (patterns[patternIndex + 1] === pattern) stderr(`csplit: warning: line number '${pattern}' is the same as preceding line number\n`);
- stderr(`csplit: '${pattern}': line number out of range\n`);
- return 1;
- }
- if (cut === lastCut && chunks.length) stderr(`csplit: warning: line number '${pattern}' is the same as preceding line number\n`);
- if (suppressMatched && cut >= 0 && cut < lines.length) suppressed.add(cut);
- chunks.push([start, cut]);
- start = cut;
- lastCut = cut;
- searchStart = start;
- continue;
- }
- const regexPattern = parseCsplitRegexPattern(pattern);
- if (regexPattern) {
- let repeat = 0;
- const repeatSpec = patterns[patternIndex + 1]?.match(/^\{(\*|\d+)\}$/);
- if (repeatSpec) {
- repeat = repeatSpec[1] === "*" ? Infinity : Number(repeatSpec[1]);
- patternIndex++;
- }
- let applications = 0;
- while (true) {
- const result = applyCsplitRegex(lines, start, searchStart, regexPattern, suppressMatched, suppressed);
- if (!result) {
- if (applications === 0) throw new UsageError(`${localeQuotedEscapedDiagnostic(pattern)}: match not found`);
- break;
- }
- if (!result.skip) chunks.push([start, result.cut]);
- start = result.start;
- lastCut = result.cut;
- searchStart = result.nextSearch;
- applications++;
- if (applications > repeat) break;
- }
- continue;
- }
- stderr(`csplit: ${localeQuotedDiagnostic(pattern)}: invalid pattern\n`);
- return 1;
- }
- chunks.push([start, lines.length]);
- let outputIndex = 0;
- const createdFiles = [];
- for (const [from, to] of chunks) {
- const chunk = lines.slice(from, to).filter((_, i) => !suppressed.has(from + i)).join("");
- if (elideEmpty && chunk === "") continue;
- const name = `${prefix}${formatCsplitSuffix(suffixFormat, outputIndex++)}`;
- try {
- await writeFile(name, chunk);
- createdFiles.push(name);
- } catch (error) {
- stderr(`csplit: ${name}: ${systemErrorMessage(error)}\n`);
- if (!(opts.k || opts["keep-files"])) await cleanupCsplitFiles([...createdFiles, name]);
- return 1;
- }
- if (!quiet) stdout(`${enc.encode(chunk).byteLength}\n`);
- }
- return 0;
-}
-
-function csplitStreamForwardSkip(spec, options) {
- const input = Buffer.allocUnsafe(64 * 1024);
- const decoder = new TextDecoder();
- let carry = "";
- let matched = false;
- let linesToSkip = 0;
- let outputFd = -1;
- let outputBytes = 0;
- const name = `${options.prefix}${formatCsplitSuffix(options.suffixFormat, 0)}`;
- const writeLine = (line) => {
- const bytes = enc.encode(line);
- if (outputFd < 0) outputFd = openSync(name, "w");
- writeSync(outputFd, bytes);
- outputBytes += bytes.length;
- };
- const consume = (line) => {
- if (!matched) {
- if (!spec.regex.test(line.replace(/\n$/, ""))) return;
- matched = true;
- if (spec.offset === 0) writeLine(line);
- else linesToSkip = spec.offset - 1;
- return;
- }
- if (linesToSkip > 0) {
- linesToSkip--;
- return;
- }
- writeLine(line);
- };
- try {
- while (true) {
- const count = readSync(0, input, 0, input.length, null);
- if (count === 0) break;
- carry += decoder.decode(input.subarray(0, count), { stream: true });
- let newline;
- while ((newline = carry.indexOf("\n")) !== -1) {
- consume(carry.slice(0, newline + 1));
- carry = carry.slice(newline + 1);
- }
- }
- carry += decoder.decode();
- if (carry) consume(carry);
- } finally {
- if (outputFd >= 0) closeSync(outputFd);
- }
- if (!matched) throw new UsageError(`${localeQuotedEscapedDiagnostic(options.pattern)}: match not found`);
- if (outputFd < 0 && !options.elideEmpty) closeSync(openSync(name, "w"));
- if (!options.quiet && (outputBytes > 0 || !options.elideEmpty)) stdout(`${outputBytes}\n`);
- return 0;
-}
-
-function parseCsplitDigits(value) {
- const text = String(value);
- if (!/^\d+$/.test(text)) throw new UsageError(`invalid number: ${localeQuotedEscapedDiagnostic(text)}`);
- return Number(text);
-}
-
-async function cleanupCsplitFiles(files) {
- for (const file of files) {
- const info = await lstat(file).catch(() => null);
- if (!info || info.isDirectory()) continue;
- await rm(file, { force: true }).catch(() => {});
- }
-}
-
-function applyCsplitRegex(lines, start, searchStart, spec, suppressMatched, suppressed) {
- const { skip, regex, offset } = spec;
- const idx = lines.findIndex((line, i) => i >= searchStart && regex.test(line.replace(/\n$/, "")));
- if (idx === -1) return null;
- const cut = Math.max(0, Math.min(lines.length, idx + offset));
- if (suppressMatched && cut >= 0 && cut < lines.length) suppressed.add(cut);
- if (skip) {
- return { skip, cut, start: suppressMatched ? Math.min(lines.length, cut + 1) : cut, nextSearch: Math.max(cut + 1, idx + 1) };
- }
- return { skip, cut, start: cut, nextSearch: idx + 1 };
-}
-
-function parseCsplitRegexPattern(pattern) {
- const delimiter = pattern[0];
- if (delimiter !== "/" && delimiter !== "%") return null;
- const end = pattern.lastIndexOf(delimiter);
- if (end <= 0) throw new UsageError(`${pattern}: closing delimiter '${delimiter}' missing`);
- const offsetText = pattern.slice(end + 1);
- if (offsetText && !/^[+-]?\d+$/.test(offsetText)) throw new UsageError(`${localeQuotedEscapedDiagnostic(pattern)}: integer expected after delimiter`);
- try {
- return { skip: delimiter === "%", regex: new RegExp(csplitBasicRegex(pattern.slice(1, end))), offset: Number(offsetText || 0) };
- } catch {
- throw new UsageError(`${localeQuotedEscapedDiagnostic(pattern)}: invalid regular expression: Invalid regular expression`);
- }
-}
-
-function csplitBasicRegex(pattern) {
- return pattern.replace(/\\([{}])/g, "$1");
-}
-
-function formatCsplitSuffix(format, index) {
- return format.replace(/%([0 #+-]*)(\d*)(?:\.(\d+))?([dixX])/g, (_, flags, widthText, precisionText, type) => {
- const width = Number(widthText || 0);
- const precision = precisionText === undefined ? null : Number(precisionText);
- const base = type === "d" || type === "i" ? 10 : 16;
- let digits = index.toString(base);
- if (type === "X") digits = digits.toUpperCase();
- if (precision != null) digits = digits.padStart(precision, "0");
- const alternate = flags.includes("#") && base === 16 && index !== 0 ? (type === "X" ? "0X" : "0x") : "";
- let rendered = `${alternate}${digits}`;
- const pad = flags.includes("0") && precision == null ? "0" : " ";
- if (width > rendered.length) rendered = flags.includes("-") ? rendered.padEnd(width, " ") : rendered.padStart(width, pad);
- return rendered;
- });
-}
-
-async function prCmd(args) {
- args = normalizePrColumnArgs(args);
- const { opts, operands } = parseOptions(args, { short: { a: false, b: false, c: false, d: false, e: "optional-value", f: false, F: false, h: "value", i: "optional-value", J: false, l: "value", m: false, n: "optional-value", N: "value", o: "value", r: false, s: "optional-value", S: "optional-value", t: false, T: false, v: false, w: "value", W: "value", D: "value" }, long: { across: false, columns: "value", "date-format": "value", "double-space": false, "expand-tabs": "optional-value", "first-line-number": "value", "form-feed": false, header: "value", indent: "value", "join-lines": false, length: "value", merge: false, "no-file-warnings": false, "number-lines": "optional-value", "omit-header": false, "omit-pagination": false, "output-tabs": "optional-value", "page-width": "value", pages: "value", "sep-string": "optional-value", separator: "optional-value", "show-control-chars": false, "show-nonprinting": false, width: "value" } });
- validatePrPages(opts.pages);
- const files = operands.length ? operands : ["-"];
- const numberSpec = opts.n ?? opts["number-lines"];
- const numberLines = numberSpec !== undefined;
- const firstLineNumberSpecified = opts.N !== undefined || opts["first-line-number"] !== undefined;
- const { separator, width } = parsePrNumberSpec(numberSpec);
- let lineNumber = parsePrLineNumber(opts.N ?? opts["first-line-number"] ?? 1);
- const indent = parsePrNonnegativeInteger(opts.o ?? opts.indent ?? 0, "-o MARGIN", "line offset");
- const columns = parsePrColumnCount(opts.columns);
- const pageWidthText = opts.W ?? opts["page-width"] ?? opts.w ?? opts.width;
- const pageWidthLabel = opts.W !== undefined || opts["page-width"] !== undefined ? "-W PAGE_WIDTH" : "-w PAGE_WIDTH";
- const pageWidth = pageWidthText == null ? 72 : parsePrPositiveInteger(pageWidthText, pageWidthLabel, "characters");
- const pageLengthText = opts.l ?? opts.length;
- const pageLength = pageLengthText == null ? 66 : parsePrPositiveInteger(pageLengthText, "-l PAGE_LENGTH", "lines");
- const pageRange = parsePrPageRange(opts.pages);
- const explicitPageWidth = pageWidthText != null;
- const oldSeparatorSpecified = opts.s !== undefined || opts.separator !== undefined;
- const newSeparatorSpecified = opts.S !== undefined || opts["sep-string"] !== undefined;
- const columnSeparatorSpecified = oldSeparatorSpecified || newSeparatorSpecified;
- const columnSeparator = newSeparatorSpecified
- ? (opts.S === true || opts["sep-string"] === true ? "" : String(opts.S ?? opts["sep-string"]))
- : (opts.s === true || opts.separator === true ? (opts.w ?? opts.width ? "" : "\t") : (typeof (opts.s ?? opts.separator) === "string" ? String(opts.s ?? opts.separator) : " "));
- const omitHeader = opts.t || opts.T || opts["omit-header"] || opts["omit-pagination"] || pageLength <= 10;
- const expandTabs = opts.e !== undefined || opts["expand-tabs"] !== undefined;
- const tabSpec = parsePrTabSpec(opts.e ?? opts["expand-tabs"]);
- const tabSize = tabSpec.size;
- const outputTabs = opts.i !== undefined || opts["output-tabs"] !== undefined;
- const outputTabSize = parsePrTabSize(opts.i ?? opts["output-tabs"]);
- const formFeed = opts.f || opts.F || opts["form-feed"];
- if (opts.m || opts.merge) {
- const texts = [];
- let failed = false;
- for (const file of files) {
- let text;
- try {
- text = decodeSurrogateEscapedBytes(await readAll(file));
- } catch (error) {
- if (!(opts.r || opts["no-file-warnings"])) stderr(prReadError(file, error));
- failed = true;
- continue;
- }
- if (expandTabs) text = expandPrTabs(text, tabSize);
- if (hasPrNonprintingRendering(opts)) text = renderPrNonprinting(text, opts);
- texts.push(text);
- }
- let pageHeader = null;
- if (!omitHeader) {
- const headerName = opts.h ?? opts.header ?? "";
- const headerDate = opts.D || opts["date-format"]
- ? await prHeaderDate(files[0] ?? "-", opts)
- : strftime(new Date(), "%Y-%m-%d %H:%M");
- pageHeader = (page) => formatPrPageHeader(formatPrHeader(headerDate, headerName, pageWidth, page), indent);
- }
- const mergeJoinLines = opts.J || opts["join-lines"];
- const mergeColumnSeparator = mergeJoinLines && !columnSeparatorSpecified ? "\t" : columnSeparator;
- let rendered = renderPrMerge(texts, { columnCount: files.length, columnSeparator: mergeColumnSeparator, defaultColumnSeparator: !columnSeparatorSpecified, explicitPageWidth, formFeed, indent, joinLines: mergeJoinLines, numberLines, numberSkippedLines: !firstLineNumberSpecified, pageHeader, pageLength, pageRange, padColumns: !oldSeparatorSpecified, pageWidth, preserveMergeTabs: oldSeparatorSpecified && !newSeparatorSpecified && columnSeparator === "\t", separator, stripFormFeeds: opts.T || opts["omit-pagination"], width, nextNumber: () => lineNumber++ });
- if (outputTabs) rendered = tabifyPrOutput(rendered, outputTabSize);
- stdout(rendered);
- return failed ? 1 : 0;
- }
- let out = "";
- let failed = false;
- for (const file of files) {
- let text;
- const paginatedBody = pageLength != null && !omitHeader;
- if (files.length === 1 && prInputIsNonRegular(file) && columns === 1 && paginatedBody && opts.pages == null && !expandTabs && !outputTabs && !hasPrNonprintingRendering(opts) && !(opts.J || opts["join-lines"]) && !oldSeparatorSpecified && !newSeparatorSpecified) {
- const headerName = opts.h ?? opts.header ?? "";
- const headerDate = await prHeaderDate(file, opts);
- const pageHeader = (page) => formatPrPageHeader(formatPrHeader(headerDate, headerName, pageWidth, page), indent);
- let fd = 0;
- try {
- if (file !== "-") fd = openSync(file, "r");
- streamPrPaginatedSingleColumnFd(fd, { doubleSpace: opts.d || opts["double-space"], explicitPageWidth: effectivePrExplicitPageWidth(explicitPageWidth, false, columns, pageWidth, opts), formFeed, indent, numberLines, numberSkippedLines: !firstLineNumberSpecified, pageHeader, pageLength, pageRange, pageWidth, separator, width, nextNumber: () => lineNumber++ });
- return 0;
- } catch (error) {
- if (isWriteError(error)) throw error;
- if (!(opts.r || opts["no-file-warnings"])) stderr(prReadError(file, error));
- return 1;
- } finally {
- if (file !== "-" && fd !== 0) closeSync(fd);
- }
- }
- try {
- text = decodeSurrogateEscapedBytes(await readAll(file));
- } catch (error) {
- if (!(opts.r || opts["no-file-warnings"])) stderr(prReadError(file, error));
- failed = true;
- continue;
- }
- if (text.length === 0) continue;
- if (hasPrNonprintingRendering(opts)) text = renderPrNonprinting(text, opts);
- if (expandTabs && columns === 1) text = tabSpec.char === "\t" ? expandPrTabs(text, tabSize) : expandPrInputTabs(text, tabSpec.char, tabSize);
- else if (expandTabs && tabSpec.char !== "\t") text = translatePrInputTabs(text, tabSpec.char);
- let pageHeader = null;
- if (!omitHeader) {
- const headerName = opts.h ?? opts.header ?? (file === "-" ? "" : file);
- const headerDate = await prHeaderDate(file, opts);
- pageHeader = (page) => formatPrPageHeader(formatPrHeader(headerDate, headerName, pageWidth, page), indent);
- if (!paginatedBody) out += pageHeader(1);
- }
- const joinLines = opts.J || opts["join-lines"] || (oldSeparatorSpecified && !(opts.w ?? opts.width));
- const effectiveExplicitPageWidth = effectivePrExplicitPageWidth(explicitPageWidth, joinLines, columns, pageWidth, opts);
- const bodyColumnSeparator = joinLines && columns > 1 && !columnSeparatorSpecified ? "\t" : columnSeparator;
- let rendered = renderPrBody(text, { across: opts.a || opts.across, columns, columnSeparator: bodyColumnSeparator, columnSeparatorSpecified, doubleSpace: opts.d || opts["double-space"], expandTabs, explicitPageWidth: effectiveExplicitPageWidth, formFeed, indent, joinLines, numberLines, numberSkippedLines: !firstLineNumberSpecified, pageHeader, pageLength: omitHeader && pageLengthText == null ? undefined : pageLength, pageRange, pageWidth, padExplicitSeparatorColumns: newSeparatorSpecified, separator, stripFormFeeds: opts.T || opts["omit-pagination"], tabSize, width, nextNumber: () => lineNumber++ });
- if (rendered === "" && opts.pages != null && pageRange.first > 1) stderr(`pr: starting page number ${pageRange.first} exceeds page count 1\n`);
- if (outputTabs) rendered = tabifyPrOutput(rendered, outputTabSize);
- out += rendered;
- if (formFeed && !omitHeader && !paginatedBody) out += "\f";
- if (rendered !== "" && !out.endsWith("\n") && !out.endsWith("\f")) out += "\n";
- }
- stdout(out);
- return failed ? 1 : 0;
-}
-
-function prReadError(file, error) {
- return file === "-" ? `pr: ${nodeErrorMessage(error)}\n` : `pr: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`;
-}
-
-function prInputIsNonRegular(file) {
- try {
- return !(file === "-" ? fstatSync(0) : statSync(file)).isFile();
- } catch {
- return false;
- }
-}
-
-function hasPrNonprintingRendering(opts) {
- return Boolean(opts.c || opts["show-control-chars"] || opts.v || opts["show-nonprinting"]);
-}
-
-function renderPrNonprinting(text, opts) {
- const octal = opts.v || opts["show-nonprinting"];
- let out = "";
- for (const ch of text) {
- const code = ch.charCodeAt(0);
- if (ch === "\n" || ch === "\t" || ch === "\f") out += ch;
- else if (code >= 0xdc80 && code <= 0xdcff) out += `\\${(code - 0xdc00).toString(8).padStart(3, "0")}`;
- else if (octal && (code < 32 || code === 127)) out += `\\${code.toString(8).padStart(3, "0")}`;
- else if (code < 32) out += `^${String.fromCharCode(code + 64)}`;
- else if (code === 127) out += "^?";
- else out += ch;
- }
- return out;
-}
-
-function normalizePrColumnArgs(args) {
- const normalized = [];
- const valueOptions = new Set(["-w", "-W", "-l", "-h", "-N", "-o", "-D", "--width", "--page-width", "--length", "--header", "--first-line-number", "--indent", "--date-format", "--pages", "--columns"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- normalized.push(arg);
- if (valueOptions.has(arg)) {
- if (i + 1 < args.length) normalized.push(args[++i]);
- continue;
- }
- const compactColumnMatch = String(arg).match(/^-(t|T)(\d+)$/);
- if (compactColumnMatch) {
- normalized.pop();
- normalized.push(`-${compactColumnMatch[1]}`, `--columns=${compactColumnMatch[2]}`);
- continue;
- }
- const compactObsoleteMatch = String(arg).match(/^-([1-9]\d*)(\D.+|[^\d])$/);
- if (compactObsoleteMatch) {
- const [, columnText, rest] = compactObsoleteMatch;
- const columns = Number(columnText);
- if (!Number.isSafeInteger(columns)) throw new UsageError(`invalid number of columns: ${localeQuotedEscapedDiagnostic(columnText)}: Value too large for defined data type`);
- if (columns < 1) throw new UsageError(`invalid number of columns: ${localeQuotedEscapedDiagnostic(columnText)}: Numerical result out of range`);
- normalized.pop();
- normalized.push(`--columns=${columnText}`, `-${rest}`);
- continue;
- }
- const match = String(arg).match(/^-(\d+)$/);
- if (!match) {
- const pageMatch = String(arg).match(/^\+(.+)$/);
- if (pageMatch) normalized[normalized.length - 1] = `--pages=${pageMatch[1]}`;
- continue;
- }
- const columnText = match[1];
- const columns = Number(columnText);
- if (!Number.isSafeInteger(columns)) throw new UsageError(`invalid number of columns: ${localeQuotedEscapedDiagnostic(columnText)}: Value too large for defined data type`);
- if (columns < 1) throw new UsageError(`invalid number of columns: ${localeQuotedEscapedDiagnostic(columnText)}: Numerical result out of range`);
- normalized[normalized.length - 1] = `--columns=${columnText}`;
- }
- return normalized;
-}
-
-function parsePrPositiveInteger(value, label, unit) {
- const text = String(value);
- if (!/^-?\d+$/.test(text)) throw new UsageError(`'${label}' invalid number of ${unit}: ${localeQuotedEscapedDiagnostic(text)}`);
- const n = Number(text);
- if (!Number.isSafeInteger(n)) throw new UsageError(`'${label}' invalid number of ${unit}: ${localeQuotedEscapedDiagnostic(text)}: Value too large for defined data type`);
- if (n < 1) throw new UsageError(`'${label}' invalid number of ${unit}: ${localeQuotedEscapedDiagnostic(text)}: Numerical result out of range`);
- return n;
-}
-
-function parsePrNonnegativeInteger(value, label, unit) {
- const text = String(value);
- if (!/^[+-]?\d+$/.test(text)) throw new UsageError(`'${label}' invalid ${unit}: ${localeQuotedEscapedDiagnostic(text)}`);
- const n = BigInt(text);
- if (n < 0n || n > BigInt(Number.MAX_SAFE_INTEGER)) throw new UsageError(`'${label}' invalid ${unit}: ${localeQuotedEscapedDiagnostic(text)}: Value too large for defined data type`);
- return Number(n);
-}
-
-function parsePrLineNumber(value) {
- const text = String(value);
- if (!/^[+-]?\d+$/.test(text)) throw new UsageError(`'-N NUMBER' invalid starting line number: ${localeQuotedEscapedDiagnostic(text)}`);
- const n = BigInt(text);
- if (n < -2147483648n || n > 2147483647n) throw new UsageError(`'-N NUMBER' invalid starting line number: ${localeQuotedEscapedDiagnostic(text)}: Value too large for defined data type`);
- return Number(n);
-}
-
-function parsePrColumnCount(value) {
- if (value == null) return 1;
- const text = String(value);
- if (!/^[+-]?\d+$/.test(text)) throw new UsageError(`invalid number of columns: ${localeQuotedEscapedDiagnostic(text)}`);
- const columns = BigInt(text.replace(/^\+/, ""));
- if (columns < 1n) throw new UsageError(`invalid number of columns: ${localeQuotedEscapedDiagnostic(text)}: Numerical result out of range`);
- if (columns > BigInt(Number.MAX_SAFE_INTEGER)) throw new UsageError(`invalid number of columns: ${localeQuotedEscapedDiagnostic(text)}: Value too large for defined data type`);
- return Number(columns);
-}
-
-function validatePrPages(pages) {
- if (pages == null) return;
- const text = String(pages);
- if (/^\d+[A-Za-z]+$/.test(text) && text.length > 30) throw new UsageError(`invalid suffix in --pages argument '${text}'`);
- if (/^\d+$/.test(text) && text.length > 30) throw new UsageError(`--pages argument '${text}' too large`);
- if (/^[A-Za-z]+$/.test(text)) throw new UsageError(`invalid --pages argument '${text}'`);
- if (/^\d+[A-Za-z]/.test(text) || (/^\d/.test(text) && /[\x00-\x1f\x7f]/.test(text))) throw new UsageError(`invalid page range ${localeQuotedEscapedDiagnostic(text)}`);
- if (!/^\d+([:-]\d+)?$/.test(text)) throw new UsageError(`invalid --pages argument '${text}'`);
-}
-
-function parsePrPageRange(pages) {
- if (pages == null) return { first: 1, last: Infinity };
- const [firstText, lastText] = String(pages).split(/[:-]/, 2);
- return { first: Number(firstText), last: lastText === undefined ? Infinity : Number(lastText) };
-}
-
-function parsePrTabSize(spec) {
- if (spec === undefined || spec === true || spec === "") return 8;
- const text = String(spec);
- const match = text.match(/(\d+)$/);
- const size = Number(match?.[1] ?? 8);
- return Number.isSafeInteger(size) && size > 0 ? size : 8;
-}
-
-function parsePrTabSpec(spec) {
- const size = parsePrTabSize(spec);
- if (spec === undefined || spec === true || spec === "") return { char: "\t", size };
- const text = String(spec);
- const match = text.match(/^(.*?)(\d+)$/s);
- const marker = match ? match[1] : text;
- return { char: marker ? marker[0] : "\t", size };
-}
-
-function translatePrInputTabs(text, marker) {
- return text.replaceAll(marker, "\t");
-}
-
-function expandPrInputTabs(text, marker, markerTabSize) {
- let out = "";
- let column = 0;
- for (const ch of text) {
- if (ch === marker || ch === "\t") {
- const size = ch === marker ? markerTabSize : 8;
- const spaces = size - (column % size);
- out += " ".repeat(spaces);
- column += spaces;
- } else if (ch === "\b") {
- if (column > 0) {
- out += ch;
- column--;
- }
- } else {
- out += ch;
- if (ch === "\n" || ch === "\f") column = 0;
- else column++;
- }
- }
- return out;
-}
-
-function expandPrTabs(text, tabSize) {
- let out = "";
- let column = 0;
- for (const ch of text) {
- if (ch === "\t") {
- const spaces = tabSize - (column % tabSize);
- out += " ".repeat(spaces);
- column += spaces;
- } else if (ch === "\b") {
- if (column > 0) {
- out += ch;
- column--;
- }
- } else {
- out += ch;
- if (ch === "\n" || ch === "\f") column = 0;
- else column++;
- }
- }
- return out;
-}
-
-function tabifyPrOutput(text, tabSize) {
- let out = "";
- let column = 0;
- let pendingSpaces = 0;
- const flushSpaces = (nextColumn = column + pendingSpaces) => {
- while (pendingSpaces > 0) {
- const toStop = tabSize - (column % tabSize);
- if (pendingSpaces >= toStop && toStop > 1) {
- out += "\t";
- column += toStop;
- pendingSpaces -= toStop;
- } else {
- out += " ";
- column++;
- pendingSpaces--;
- }
- }
- column = nextColumn;
- };
- for (const ch of text) {
- if (ch === " ") {
- pendingSpaces++;
- continue;
- }
- flushSpaces();
- out += ch;
- if (ch === "\t") column += tabSize - (column % tabSize);
- else if (ch === "\b") column = Math.max(0, column - 1);
- else if (ch === "\n" || ch === "\f") column = 0;
- else column++;
- }
- flushSpaces();
- return out;
-}
-
-async function prHeaderDate(file, opts) {
- const format = opts.D ?? opts["date-format"];
- if (!format) {
- const date = file === "-" ? new Date() : (await stat(file)).mtime;
- return strftime(date, "%Y-%m-%d %H:%M");
- }
- const date = file === "-" ? new Date() : (await stat(file)).mtime;
- return format.startsWith("+") ? `+${strftime(date, format.slice(1))}` : strftime(date, format);
-}
-
-function formatPrHeader(dateText, name, pageWidth = 72, page = 1) {
- const pageText = `Page ${page}`;
- if (pageWidth < dateText.length + String(name).length + pageText.length + 2) return `${dateText} ${name} ${pageText}`;
- const nameColumn = dateText.length + Math.floor((pageWidth - pageText.length - dateText.length - String(name).length) / 2);
- return `${dateText.padEnd(nameColumn)}${String(name).padEnd(Math.max(1, pageWidth - pageText.length - nameColumn))}${pageText}`;
-}
-
-function formatPrPageHeader(headerLine, indent = 0) {
- const margin = " ".repeat(indent);
- return indent > 0 ? `${margin}\n\n${margin}${headerLine}\n\n\n` : `\n\n${headerLine}\n\n\n`;
-}
-
-function parsePrNumberSpec(spec) {
- if (spec === undefined || spec === true) return { separator: "\t", width: 5 };
- const text = String(spec);
- const match = text.match(/^(.*?)(\d+)?$/s);
- return { separator: match?.[1] || "\t", width: Number(match?.[2] || 5) };
-}
-
-function renderPrBody(text, opts) {
- if (opts.columns > 1 && text.includes("\f") && !(opts.pageLength != null && opts.pageHeader)) return renderPrColumnGroups(text, opts);
- if (opts.pageLength != null && opts.pageHeader) return opts.columns > 1 ? renderPrPaginatedColumns(text, opts) : renderPrPaginatedSingleColumn(text, opts);
- const margin = " ".repeat(opts.indent);
- const lines = text.split(/(?<=\n)/).filter(Boolean).map((raw) => {
- let line = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
- if (opts.stripFormFeeds) {
- if (/^\f+$/u.test(line)) return null;
- line = line.replace(/\f+/gu, "\n");
- }
- return opts.explicitPageWidth ? line.slice(0, opts.pageWidth) : line;
- }).filter((line) => line != null);
- const rendered = opts.columns > 1 ? renderPrColumns(lines, opts) : renderPrSingleColumn(lines, opts);
- return opts.doubleSpace ? rendered.replaceAll("\n", "\n\n") : rendered;
-}
-
-function effectivePrExplicitPageWidth(explicitPageWidth, joinLines, columns, pageWidth, opts) {
- const modernPageWidth = opts.W !== undefined || opts["page-width"] !== undefined;
- return explicitPageWidth && !joinLines && (columns > 1 || pageWidth < 72 || modernPageWidth);
-}
-
-function renderPrColumnGroups(text, opts) {
- const tokens = tokenizePrPages(text, opts);
- const groups = [[]];
- for (const token of tokens) {
- if (token.type === "formFeed") groups.push([]);
- else groups[groups.length - 1].push(token.line);
- }
- let out = "";
- for (let i = 0; i < groups.length; i++) {
- if (groups[i].length > 0) out += renderPrColumns(groups[i], opts);
- if (!opts.stripFormFeeds && i < groups.length - 1) out += "\f";
- }
- return opts.doubleSpace ? out.replaceAll("\n", "\n\n") : out;
-}
-
-function renderPrSingleColumn(lines, opts) {
- const margin = " ".repeat(opts.indent);
- return lines.map((line) => {
- if (/^\f+$/u.test(line)) return opts.stripFormFeeds ? "" : line;
- const number = opts.numberLines ? `${formatPrLineNumber(opts.nextNumber(), opts.width)}${opts.separator}` : "";
- if (!opts.stripFormFeeds && line.includes("\f")) {
- const rendered = line.replace(/([^\f])(\f+)/gu, "$1\n$2");
- return `${margin}${number}${rendered}${line.endsWith("\f") ? "" : "\n"}`;
- }
- if (opts.stripFormFeeds && line.endsWith("\n")) return `${margin}${number}${line}`;
- return `${margin}${number}${line}\n`;
- }).join("");
-}
-
-function renderPrPaginatedSingleColumn(text, opts) {
- let out = "";
- const state = createPrPaginatedSingleColumnState(opts, (text) => { out += text; });
- for (const token of tokenizePrPages(text, opts)) state.accept(token);
- state.finish();
- return out;
-}
-
-function streamPrPaginatedSingleColumnFd(fd, opts) {
- const state = createPrPaginatedSingleColumnState(opts, stdout);
- const buffer = Buffer.allocUnsafe(64 * 1024);
- if (!opts.explicitPageWidth) {
- let lineHasText = false;
- let skipNextNewline = false;
- while (true) {
- const n = readSync(fd, buffer, 0, buffer.length, null);
- if (n === 0) break;
- const bytes = buffer.subarray(0, n);
- let start = 0;
- for (let index = 0; index < bytes.length; index++) {
- const byte = bytes[index];
- if (byte !== 0x0a && byte !== 0x0c) continue;
- if (index > start) {
- state.writeLineChunk(bytes.subarray(start, index));
- lineHasText = true;
- skipNextNewline = false;
- }
- if (byte === 0x0a) {
- if (skipNextNewline) skipNextNewline = false;
- else state.endLine();
- lineHasText = false;
- } else {
- if (lineHasText) state.endLine();
- lineHasText = false;
- state.accept({ type: "formFeed" });
- skipNextNewline = true;
- }
- start = index + 1;
- }
- if (start < bytes.length) {
- state.writeLineChunk(bytes.subarray(start));
- lineHasText = true;
- skipNextNewline = false;
- }
- }
- if (lineHasText) state.endLine();
- state.finish();
- return;
- }
- let pending = "";
- let skipNextNewline = false;
- const pushLine = (line) => state.accept({ type: "line", line: opts.explicitPageWidth ? line.slice(0, opts.pageWidth) : line });
- const processText = (text, final = false) => {
- let line = pending;
- pending = "";
- for (let i = 0; i < text.length; i++) {
- const ch = text[i];
- if (ch === "\n") {
- if (skipNextNewline) {
- skipNextNewline = false;
- continue;
- }
- pushLine(line);
- line = "";
- } else if (ch === "\f") {
- if (line.length > 0) pushLine(line);
- line = "";
- state.accept({ type: "formFeed" });
- skipNextNewline = true;
- } else {
- skipNextNewline = false;
- line += ch;
- }
- }
- if (final) {
- if (line.length > 0) pushLine(line);
- } else {
- pending = line;
- }
- };
- while (true) {
- const n = readSync(fd, buffer, 0, buffer.length, null);
- if (n === 0) break;
- processText(decodeSurrogateEscapedBytes(buffer.subarray(0, n)));
- }
- processText("", true);
- state.finish();
-}
-
-function createPrPaginatedSingleColumnState(opts, emit) {
- const bodyRows = Math.max(1, opts.pageLength - 10);
- const margin = " ".repeat(opts.indent);
- let page = 1;
- let row = 0;
- let pageStarted = false;
- let lineOpen = false;
- const inRange = () => page >= opts.pageRange.first && page <= opts.pageRange.last;
- const startPage = () => {
- if (!pageStarted && inRange()) emit(opts.pageHeader(page));
- pageStarted = true;
- };
- const endPage = () => {
- const renderedRows = opts.doubleSpace ? row * 2 : row;
- if (pageStarted && inRange()) emit(opts.formFeed ? "\f" : "\n".repeat(Math.max(1, opts.pageLength - 5 - renderedRows)));
- page++;
- row = 0;
- pageStarted = false;
- };
- const startLine = () => {
- if (lineOpen || page > opts.pageRange.last) return;
- if (row >= bodyRows) endPage();
- startPage();
- let number = "";
- if (opts.numberLines && (inRange() || opts.numberSkippedLines)) number = `${formatPrLineNumber(opts.nextNumber(), opts.width)}${opts.separator}`;
- if (inRange()) emit(`${margin}${number}`);
- lineOpen = true;
- };
- const writeLineChunk = (text) => {
- if (!text.length) return;
- startLine();
- if (lineOpen && inRange()) emit(text);
- };
- const endLine = () => {
- startLine();
- if (!lineOpen) return;
- if (inRange()) emit(opts.doubleSpace ? "\n\n" : "\n");
- row++;
- lineOpen = false;
- };
- return {
- writeLineChunk,
- endLine,
- accept(token) {
- if (page > opts.pageRange.last) return;
- if (token.type === "formFeed") {
- if (lineOpen) endLine();
- startPage();
- if (opts.formFeed && inRange() && row === 0) emit("\n");
- if (row === 0 && opts.formFeed) row = 1;
- endPage();
- return;
- }
- writeLineChunk(token.line);
- endLine();
- },
- finish() {
- if (lineOpen) endLine();
- if (pageStarted) endPage();
- },
- };
-}
-
-function renderPrPaginatedColumns(text, opts) {
- const bodyRows = Math.max(1, opts.pageLength - 10);
- const pageCapacity = Math.max(1, bodyRows * opts.columns);
- const tokens = tokenizePrPages(text, opts);
- const separatorWidth = opts.columnSeparatorSpecified ? opts.columnSeparator.length * (opts.columns - 1) : 0;
- const columnWidth = Math.max(1, Math.floor((opts.pageWidth - separatorWidth) / opts.columns));
- const clipWidth = opts.joinLines ? Infinity : Math.max(1, columnWidth - (!opts.columnSeparatorSpecified && (!opts.explicitPageWidth || opts.columns === 2) ? 1 : 0));
- const margin = " ".repeat(opts.indent);
- let out = "";
- let page = 1;
- let entries = [];
- const inRange = () => page >= opts.pageRange.first && page <= opts.pageRange.last;
- const makeEntry = (line) => {
- const number = opts.numberLines && (inRange() || opts.numberSkippedLines) ? opts.nextNumber() : null;
- return { line, number };
- };
- const emitPage = (forceBlankBody = false) => {
- if (inRange()) {
- out += opts.pageHeader(page);
- if (forceBlankBody) out += "\n";
- else out += renderPrColumnPage(entries, { ...opts, bodyRows, clipWidth, columnWidth, margin });
- const renderedRows = forceBlankBody ? 1 : prColumnPageRowCount(entries.length, opts.columns, bodyRows, opts.across);
- out += opts.formFeed ? "\f" : "\n".repeat(Math.max(1, opts.pageLength - 5 - renderedRows));
- }
- page++;
- entries = [];
- };
- for (const token of tokens) {
- if (page > opts.pageRange.last) break;
- if (token.type === "formFeed") {
- emitPage(opts.formFeed && entries.length === 0);
- continue;
- }
- if (entries.length >= pageCapacity) emitPage();
- entries.push(makeEntry(token.line));
- }
- if (entries.length > 0) emitPage();
- return opts.doubleSpace ? out.replaceAll("\n", "\n\n") : out;
-}
-
-function renderPrColumnPage(entries, opts) {
- const rows = prColumnPageRowCount(entries.length, opts.columns, opts.bodyRows, opts.across);
- const out = [];
- for (let row = 0; row < rows; row++) {
- const parts = [];
- for (let column = 0; column < opts.columns; column++) {
- const index = opts.across ? row * opts.columns + column : prDownColumnIndex(entries.length, opts.columns, rows, row, column);
- const entry = entries[index];
- if (entry === undefined) continue;
- const entryClipWidth = opts.numberLines && column > 0 && !opts.columnSeparatorSpecified ? Math.max(1, opts.clipWidth - 1) : opts.clipWidth;
- const implicitSeparatorWidth = opts.columnSeparator.length;
- const explicitImplicitSeparatorWidth = !opts.columnSeparatorSpecified && opts.columns === 2 ? 0 : implicitSeparatorWidth;
- const clipStartColumn = opts.margin.length + (opts.explicitPageWidth || opts.columnSeparatorSpecified ? column * (opts.columnWidth + explicitImplicitSeparatorWidth) : Math.floor((opts.pageWidth * column) / opts.columns));
- let clipped = formatPrColumnEntry(entry, column, { ...opts, compactColumnNumbers: true, paginated: true, clipStartColumn }, entryClipWidth);
- if (opts.numberLines && opts.expandTabs && !opts.columnSeparatorSpecified && column < opts.columns - 1) clipped = `${clipped} \t`;
- parts.push(opts.joinLines || column === opts.columns - 1 || (opts.numberLines && opts.expandTabs && !opts.columnSeparatorSpecified)
- ? clipped
- : opts.columnSeparatorSpecified && opts.padExplicitSeparatorColumns
- ? padPrColumnEnd(clipped.replace(/\s+$/u, ""), column, { columnWidth: opts.columnWidth, clipWidth: opts.columnWidth, formFeed: opts.formFeed, startOffset: opts.margin.length, separatorWidth: opts.columnSeparator.length, allowUnitTabs: true, disallowSingleColumnTab: true })
- : opts.columnSeparatorSpecified
- ? clipped
- : (opts.numberLines ? padPrColumnEnd(clipped.replace(/\s+$/u, ""), column, { ...opts, padExtra: 1 }) : padPrDefaultColumnEnd(clipped.replace(/\s+$/u, ""), column, { ...opts, allowUnitTabs: opts.columns === 2 || opts.margin.length > 0, startOffset: opts.margin.length })));
- }
- let separator = !opts.columnSeparatorSpecified && !opts.joinLines && (!opts.explicitPageWidth || opts.columns === 2) ? "" : opts.columnSeparator;
- if (opts.numberLines && opts.expandTabs && !opts.columnSeparatorSpecified) separator = "";
- if (opts.numberLines && opts.expandTabs && opts.columnSeparatorSpecified) separator += "\t ";
- if (parts.length) {
- let line = parts.join(separator);
- if (!opts.columnSeparatorSpecified && opts.joinLines && !opts.across) line = formatPrStoredJoinLine(parts, opts);
- else if (!opts.columnSeparatorSpecified && opts.joinLines) line = tabifyPrSpacesAtGnuOutput(line, opts.margin.length);
- else if (!opts.columnSeparatorSpecified && opts.explicitPageWidth) line = tabifyPrSpacesAt(line, opts.margin.length);
- const preserveAcrossPadding = opts.across && row < rows - 1 && parts.slice(1).every((part) => !/\S/u.test(part));
- out.push(`${opts.margin}${preserveAcrossPadding ? line : line.replace(/\s+$/u, "")}\n`);
- }
- }
- return out.join("");
-}
-
-function prColumnPageRowCount(entryCount, columns, bodyRows, across) {
- if (entryCount <= 0) return 0;
- if (across) return Math.ceil(entryCount / columns);
- if (entryCount >= bodyRows * columns) return bodyRows;
- return Math.ceil(entryCount / columns);
-}
-
-function prDownColumnIndex(entryCount, columns, rows, row, column) {
- const full = Math.floor(entryCount / columns);
- const extra = entryCount % columns;
- const height = full + (column < extra ? 1 : 0);
- if (row >= height) return -1;
- let offset = 0;
- for (let c = 0; c < column; c++) offset += full + (c < extra ? 1 : 0);
- return offset + row;
-}
-
-function tokenizePrPages(text, opts) {
- const tokens = [];
- let line = "";
- let skipNextNewline = false;
- const pushLine = () => {
- tokens.push({ type: "line", line: opts.explicitPageWidth ? line.slice(0, opts.pageWidth) : line });
- line = "";
- };
- for (let i = 0; i < text.length; i++) {
- const ch = text[i];
- if (ch === "\n") {
- if (skipNextNewline) {
- skipNextNewline = false;
- continue;
- }
- pushLine();
- } else if (ch === "\f") {
- if (line.length > 0) pushLine();
- tokens.push({ type: "formFeed" });
- skipNextNewline = true;
- } else {
- skipNextNewline = false;
- line += ch;
- }
- }
- if (line.length > 0) pushLine();
- return tokens;
-}
-
-function padPrColumnEnd(text, column, opts) {
- const start = (opts.startOffset ?? 0) + column * opts.columnWidth + column * (opts.separatorWidth ?? 1);
- const width = column === 0 ? opts.columnWidth : opts.clipWidth;
- const target = start + width + (opts.padExtra ?? 0);
- let out = text;
- let display = prColumnAfter(text, start);
- while (display < target) {
- const toStop = 8 - (display % 8);
- const remaining = target - display;
- if ((toStop > 1 || !opts.formFeed || (opts.allowUnitTabs && !(opts.disallowSingleColumnTab && remaining === 1))) && display + toStop <= target) {
- out += "\t";
- display += toStop;
- } else {
- out += " ";
- display++;
- }
- }
- return out;
-}
-
-function renderPrMerge(texts, opts) {
- const files = texts.map((text) => {
- if (opts.stripFormFeeds) text = text.replaceAll("\f", "");
- return text.split(/(?<=\n)/).filter(Boolean).map((raw) => raw.endsWith("\n") ? raw.slice(0, -1) : raw);
- });
- if (opts.pageLength != null && opts.pageHeader) return renderPrPaginatedMerge(files, opts);
- const rowCount = Math.max(0, ...files.map((lines) => lines.length));
- const columnCount = opts.columnCount ?? files.length;
- const columnSeparator = opts.defaultColumnSeparator && opts.padColumns && !opts.joinLines ? "" : opts.columnSeparator;
- const separatorWidth = columnSeparator.length * Math.max(0, columnCount - 1);
- const columnWidth = columnCount ? Math.max(1, Math.floor((opts.pageWidth - separatorWidth) / columnCount)) : opts.pageWidth;
- const out = [];
- for (let row = 0; row < rowCount; row++) {
- const parts = [];
- let column = opts.indent;
- for (let index = 0; index < files.length; index++) {
- if (index > 0) column += columnSeparator.length;
- let value = files[index][row] ?? "";
- if (!opts.joinLines && index > 0 && !opts.preserveMergeTabs) value = tabifyPrSpacesAt(expandPrTabs(value, 8), column, true);
- if (!opts.joinLines && opts.padColumns && index < files.length - 1) value = padPrMergeEnd(value, columnWidth);
- parts.push(value);
- column = prColumnAfter(value, column);
- }
- const body = opts.joinLines ? formatPrMergeJoinLine(parts, opts.columnSeparator) : parts.join(columnSeparator);
- out.push(`${" ".repeat(opts.indent)}${opts.joinLines ? body : body.slice(0, opts.pageWidth)}\n`);
- }
- return out.join("");
-}
-
-function renderPrPaginatedMerge(files, opts) {
- const bodyRows = Math.max(1, opts.pageLength - 10);
- const pages = files.map((lines) => paginatePrMergeLines(lines, bodyRows));
- const pageCount = Math.max(0, ...pages.map((filePages) => filePages.length));
- const columnCount = opts.columnCount ?? files.length;
- const separatorWidth = opts.columnSeparator.length * Math.max(0, columnCount - 1);
- const numberWidth = opts.numberLines ? opts.width + opts.separator.length : 0;
- const columnWidth = columnCount ? Math.max(1, Math.floor((opts.pageWidth - numberWidth - separatorWidth) / columnCount)) : opts.pageWidth;
- let out = "";
- for (let page = 1; page <= pageCount; page++) {
- const pageRows = pages.map((filePages) => filePages[page - 1] ?? []);
- const hasFirstFileRows = (pageRows[0] ?? []).some((line) => line !== null);
- const visible = page >= opts.pageRange.first && page <= opts.pageRange.last;
- if (!visible && opts.numberLines && opts.numberSkippedLines && hasFirstFileRows) {
- for (let row = 0; row < bodyRows; row++) if ((pageRows[0] ?? [])[row] != null) opts.nextNumber();
- continue;
- }
- if (!visible) continue;
- out += opts.pageHeader(page);
- let emittedRows = 0;
- for (let row = 0; row < bodyRows; row++) {
- const values = pageRows.map((rows) => rows[row]);
- if (!values.some((value) => value != null)) continue;
- const number = opts.numberLines ? `${formatPrLineNumber(opts.nextNumber(), opts.width)}${opts.separator}` : "";
- if (opts.joinLines) {
- const pageEndMissingRight = values[values.length - 1] == null
- && !pageRows.some((rows) => rows.slice(row + 1).some((line) => line != null));
- const bodyValues = pageEndMissingRight && page < pageCount && (!opts.numberLines || values[0] != null) ? values.slice(0, values.reduce((last, value, index) => value == null ? last : index, -1) + 1) : values;
- const body = formatPrMergeJoinLine(bodyValues, opts.columnSeparator, opts.indent + prDisplayWidth(number));
- out += `${" ".repeat(opts.indent)}${number}${body}\n`;
- emittedRows++;
- continue;
- }
- const clippedParts = values.map((value, index) => {
- const startColumn = opts.indent + numberWidth + index * (columnWidth + opts.columnSeparator.length);
- const text = tabifyPrSpacesAt(prMergeCellText(value), startColumn, true);
- return index === values.length - 1
- ? (opts.numberLines ? clipPrLastMergeColumn(text, columnWidth, startColumn, !opts.padColumns) : clipPrDisplay(text, columnWidth, startColumn).replace(/\s+$/u, ""))
- : clipPrDisplay(text, columnWidth, startColumn);
- });
- const lastNonNull = values.reduce((last, value, index) => value == null ? last : index, -1);
- const pageEndMissingRight = (!opts.padColumns || page === pageCount || values.some((value) => value?.beforeFormFeed || value?.sourceHadFormFeed))
- && values[values.length - 1] == null
- && !pageRows.some((rows) => rows.slice(row + 1).some((line) => line != null));
- if (pageEndMissingRight && lastNonNull >= 0 && lastNonNull < values.length - 1) {
- const startColumn = opts.indent + numberWidth + lastNonNull * (columnWidth + opts.columnSeparator.length);
- const text = tabifyPrSpacesAt(prMergeCellText(values[lastNonNull]), startColumn, true);
- clippedParts[lastNonNull] = opts.explicitPageWidth
- ? clipPrDisplay(text, columnWidth, startColumn)
- : clipPrLastMergeColumn(text, columnWidth, startColumn, true);
- const remainingText = text.slice(clippedParts[lastNonNull].length);
- if (opts.explicitPageWidth && /^\S/u.test(remainingText)) clippedParts[lastNonNull] = clippedParts[lastNonNull].replace(/\s+$/u, "");
- else if (opts.explicitPageWidth && remainingText.startsWith(" ")) clippedParts[lastNonNull] += " ";
- if (!opts.explicitPageWidth && !values[lastNonNull]?.sourceHadFormFeed && !(opts.numberLines && values.some((value) => value?.beforeFormFeed || value?.sourceHadFormFeed)) && !/\s$/u.test(clippedParts[lastNonNull]) && /\S/u.test(text.slice(clippedParts[lastNonNull].length))) {
- clippedParts[lastNonNull] += " ";
- }
- }
- const unpadPageEnd = pageEndMissingRight
- && (values.some((value) => value?.beforeFormFeed) || prDisplayWidth(clippedParts[lastNonNull].replace(/\s+$/u, "")) >= columnWidth - 1);
- const parts = clippedParts.map((clipped, index) => {
- if (index >= values.length - 1 || (unpadPageEnd && index === lastNonNull)) return clipped;
- return padPrColumnEnd(clipped.replace(/\s+$/u, ""), index, { columnWidth, clipWidth: columnWidth, formFeed: opts.formFeed, startOffset: opts.indent + numberWidth, separatorWidth: opts.columnSeparator.length, allowUnitTabs: true, disallowSingleColumnTab: opts.padColumns && (files.length > 2 || opts.numberLines) });
- });
- const body = (unpadPageEnd ? parts.slice(0, lastNonNull + 1) : parts).join(opts.columnSeparator);
- out += `${" ".repeat(opts.indent)}${number}${body}\n`;
- emittedRows++;
- }
- out += opts.formFeed ? `${emittedRows === 0 ? "\n" : ""}\f` : "\n".repeat(Math.max(1, opts.pageLength - 5 - emittedRows));
- }
- return out;
-}
-
-function prMergeCellText(value) {
- if (value == null) return "";
- return typeof value === "object" ? value.line : String(value);
-}
-
-function formatPrMergeJoinLine(values, separator, startColumn = 0) {
- const parts = [];
- let column = startColumn;
- for (let index = 0; index < values.length; index++) {
- let text = tabifyPrSpacesAt(prMergeCellText(values[index]), column, true);
- if (index === values.length - 1) text = text.replace(/[ \t]+$/u, "");
- parts.push(text);
- column = prColumnAfter(text, column);
- if (index < values.length - 1) column += separator.length;
- }
- return parts.join(separator);
-}
-
-function clipPrLastMergeColumn(text, width, startColumn = 0, preserveSourceContinuation = false) {
- const clipped = clipPrDisplay(text, width, startColumn);
- if (!/\s$/u.test(clipped)) return clipped;
- const lookahead = preserveSourceContinuation ? clipPrDisplay(text, width + 1, startColumn) : clipped;
- if (lookahead.length > clipped.length && /\S/u.test(lookahead.slice(clipped.length))) return clipped;
- return clipped.replace(/\s+$/u, "");
-}
-
-function paginatePrMergeLines(lines, bodyRows) {
- const pages = [];
- let page = [];
- let justFlushed = false;
- for (const line of lines) {
- const parts = String(line).split("\f");
- for (let i = 0; i < parts.length; i++) {
- const part = parts[i];
- let flushedFullPage = false;
- if (part !== "" || !String(line).includes("\f")) {
- page.push({ line: part, beforeFormFeed: false, sourceHadFormFeed: String(line).includes("\f") });
- if (page.length >= bodyRows) {
- pages.push(page);
- page = [];
- justFlushed = true;
- flushedFullPage = true;
- }
- }
- if (i < parts.length - 1) {
- if (page.length > 0) page[page.length - 1].beforeFormFeed = true;
- if (justFlushed) justFlushed = false;
- else pages.push(page);
- page = [];
- }
- if (part !== "" && !flushedFullPage) justFlushed = false;
- }
- }
- if (page.length > 0) pages.push(page);
- return pages;
-}
-
-function renderPrColumns(lines, opts) {
- const pageRows = opts.pageLength ?? Math.ceil(lines.length / opts.columns);
- const pageCapacity = Math.max(1, pageRows * opts.columns);
- const separatorWidth = opts.columnSeparator.length * (opts.columns - 1);
- const columnWidth = Math.max(1, Math.floor((opts.pageWidth - separatorWidth) / opts.columns));
- const clipWidth = opts.joinLines ? Infinity : columnWidth;
- const out = [];
- for (let pageStart = 0, page = 1; pageStart < lines.length; pageStart += pageCapacity, page++) {
- if (page < opts.pageRange.first || page > opts.pageRange.last) continue;
- const pageLines = lines.slice(pageStart, pageStart + pageCapacity).map((line) => ({ line, number: opts.numberLines ? opts.nextNumber() : null }));
- const rows = opts.pageLength ?? Math.ceil(pageLines.length / opts.columns);
- for (let row = 0; row < rows; row++) {
- const parts = [];
- for (let column = 0; column < opts.columns; column++) {
- const index = opts.across ? row * opts.columns + column : prDownColumnIndex(pageLines.length, opts.columns, rows, row, column);
- const entry = pageLines[index];
- if (entry === undefined) continue;
- let clipped = formatPrColumnEntry(entry, column, { ...opts, compactColumnNumbers: true }, clipWidth);
- if (opts.numberLines && opts.expandTabs && !opts.columnSeparatorSpecified && column < opts.columns - 1) clipped = `${clipped} \t`;
- parts.push(column === opts.columns - 1 || (opts.columnSeparatorSpecified && !opts.padExplicitSeparatorColumns) || (opts.numberLines && opts.expandTabs && !opts.columnSeparatorSpecified)
- ? clipped
- : opts.columnSeparatorSpecified
- ? padPrColumnEnd(clipped.replace(/\s+$/u, ""), column, { columnWidth, clipWidth: columnWidth, formFeed: opts.formFeed, startOffset: opts.indent, separatorWidth: opts.columnSeparator.length, allowUnitTabs: true, disallowSingleColumnTab: true })
- : padPrDefaultColumnEnd(clipped.replace(/\s+$/u, ""), column, { ...opts, columnWidth, allowUnitTabs: opts.allowUnitTabs || opts.numberLines, finalNumberBoundaryTab: opts.numberLines && !opts.columnSeparatorSpecified, padExtra: opts.numberLines && !opts.columnSeparatorSpecified ? 4 : opts.padExtra }));
- }
- let separator = !opts.columnSeparatorSpecified && !opts.explicitPageWidth ? "" : opts.columnSeparator;
- if (opts.numberLines && opts.expandTabs && !opts.columnSeparatorSpecified) separator = "";
- if (opts.numberLines && opts.expandTabs && opts.columnSeparatorSpecified) separator += "\t ";
- if (parts.length) out.push(`${" ".repeat(opts.indent)}${parts.join(separator).replace(/\s+$/u, "")}\n`);
- }
- }
- return out.join("");
-}
-
-function padPrDefaultColumnEnd(text, column, opts) {
- const implicitSeparatorWidth = opts.columnSeparatorSpecified ? 0 : opts.columnSeparator.length;
- const implicitSeparatorTrim = opts.explicitPageWidth && !opts.columnSeparatorSpecified ? 1 : 0;
- const startOffset = opts.startOffset ?? 0;
- const target = opts.explicitPageWidth
- ? startOffset + (column + 1) * opts.columnWidth + column * implicitSeparatorWidth
- : startOffset + Math.floor((opts.pageWidth * (column + 1)) / opts.columns) - implicitSeparatorTrim + (opts.padExtra ?? 0);
- const start = startOffset + (opts.explicitPageWidth ? column * (opts.columnWidth + implicitSeparatorWidth) : Math.floor((opts.pageWidth * column) / opts.columns));
- let out = text;
- let display = prColumnAfter(text, start);
- while (display < target) {
- const toStop = 8 - (display % 8);
- if (opts.finalNumberBoundaryTab && display % 8 === 0 && target - display === 8) {
- out += " \t";
- display += 8;
- continue;
- }
- if ((toStop > 1 || opts.allowUnitTabs) && display + toStop <= target) {
- out += "\t";
- display += toStop;
- } else {
- out += " ";
- display++;
- }
- }
- return out;
-}
-
-function formatPrColumnEntry(entry, column, opts, columnWidth) {
- let text = entry.line;
- if (!opts.numberLines) {
- if (column > 0 && !opts.columnSeparatorSpecified) text = text.replaceAll("\t", "\t ");
- if (opts.paginated && !opts.joinLines) text = tabifyPrSpacesAt(text, opts.clipStartColumn ?? 0, !opts.explicitPageWidth || opts.columnSeparatorSpecified);
- return opts.paginated ? finishPrColumnClip(text, columnWidth, opts) : text.slice(0, columnWidth);
- }
- let clipWidth = columnWidth;
- let prefix;
- if (opts.expandTabs && opts.indent > 0 && !opts.columnSeparatorSpecified) {
- return formatPrIndentedTabbedColumn(entry, column, opts, columnWidth);
- }
- if (opts.expandTabs && column > 0 && !opts.columnSeparatorSpecified) {
- const number = String(entry.number);
- prefix = opts.separator === "\t" ? `${number}${" ".repeat(Math.max(1, opts.width - number.length - 1))}` : `${number}${opts.separator}`;
- clipWidth = Math.max(1, columnWidth - 4);
- } else if (opts.expandTabs && column > 0 && opts.columnSeparatorSpecified) {
- const number = String(entry.number);
- prefix = `${number}${opts.separator}`;
- clipWidth = Math.max(1, columnWidth - 2);
- } else {
- if (opts.compactColumnNumbers && column > 0 && !opts.columnSeparatorSpecified) {
- const number = String(entry.number);
- prefix = opts.separator === "\t" ? `${number}${" ".repeat(Math.max(1, opts.width - number.length - 1))}` : `${number}${opts.separator}`;
- } else {
- prefix = `${formatPrLineNumber(entry.number, opts.width)}${opts.separator}`;
- }
- }
- text = `${prefix}${text}`;
- if (opts.numberLines && opts.expandTabs && column > 0 && !opts.columnSeparatorSpecified) text = text.replace(/\t+/g, "\t ");
- else if (opts.numberLines && opts.expandTabs && column > 0 && opts.columnSeparatorSpecified) text = text.replace(/\t+/g, "\t ");
- if (opts.paginated && opts.columnSeparatorSpecified && !opts.joinLines) text = tabifyPrSpacesAt(text, opts.clipStartColumn ?? 0, true);
- return finishPrColumnClip(text, clipWidth, opts);
-}
-
-function finishPrColumnClip(text, width, opts) {
- const startColumn = opts.clipStartColumn ?? 0;
- const clipped = clipPrDisplay(text, width, startColumn);
- if (!opts.columnSeparatorSpecified || !/\s$/u.test(clipped)) return clipped;
- const lookahead = clipPrDisplay(text, width + 1, startColumn);
- if (lookahead.length > clipped.length && /\S/u.test(lookahead.slice(clipped.length))) return clipped.replace(/\s+$/u, " ");
- return clipped;
-}
-
-function formatPrIndentedTabbedColumn(entry, column, opts, columnWidth) {
- const number = String(entry.number);
- const numberPrefix = column === 0
- ? `${formatPrLineNumber(entry.number, opts.width)} `
- : `${" ".repeat(Math.max(1, opts.width - number.length - 1))}${number} `;
- const body = formatPrIndentedTabbedBody(entry.line, column, opts.tabSize);
- const clipWidth = Math.max(1, columnWidth + (column === 0 ? 3 : -1));
- return clipPrDisplay(`${numberPrefix}${body}`, clipWidth);
-}
-
-function formatPrIndentedTabbedBody(text, column, tabSize) {
- const fields = text.split("\t");
- if (fields.length >= 4 && fields[2] === "") {
- const [first, second] = fields;
- const rest = fields.slice(3).join("\t");
- if (tabSize === 5) return column === 0 ? `${first}\t ${second}\t\t ${rest}` : `${first} ${second}\t ${rest}`;
- return column === 0 ? `${first}\t ${second}\t ${rest}` : `${first} ${second}\t ${rest}`;
- }
- if (tabSize === 5) {
- if (column === 0) return text.replace(/\t\t/g, "\t\t ").replace(/\t(?!\t)/g, "\t ");
- return text.replace(/\t+/g, " ");
- }
- if (column === 0) return text.replace(/\t+/g, "\t ");
- return text.replace(/\t+/g, " ");
-}
-
-function padPrDisplayEnd(text, width) {
- const displayWidth = prDisplayWidth(text);
- return displayWidth >= width ? text : `${text}${" ".repeat(width - displayWidth)}`;
-}
-
-function clipPrDisplay(text, width, startColumn = 0) {
- let out = "";
- let column = startColumn;
- const limit = startColumn + width;
- for (const ch of text) {
- const nextColumn = ch === "\t" ? column + (8 - (column % 8)) : ch === "\b" ? Math.max(0, column - 1) : column + 1;
- if (nextColumn > limit) break;
- out += ch;
- column = nextColumn;
- }
- return out;
-}
-
-function tabifyPrSpacesAt(text, startColumn = 0, allowUnitTabs = false) {
- let out = "";
- let column = startColumn;
- for (let index = 0; index < text.length;) {
- const ch = text[index];
- if (ch !== " ") {
- out += ch;
- column = ch === "\t" ? column + (8 - (column % 8)) : ch === "\b" ? Math.max(0, column - 1) : column + 1;
- index++;
- continue;
- }
- let end = index;
- while (end < text.length && text[end] === " ") end++;
- let remaining = end - index;
- while (remaining > 0) {
- const toStop = 8 - (column % 8);
- if ((toStop > 1 || (allowUnitTabs && remaining > 1)) && remaining >= toStop) {
- out += "\t";
- column += toStop;
- remaining -= toStop;
- } else {
- out += " ";
- column++;
- remaining--;
- }
- }
- index = end;
- }
- return out;
-}
-
-function tabifyPrSpacesAtGnuOutput(text, startColumn = 0) {
- let out = "";
- let column = startColumn;
- for (let index = 0; index < text.length;) {
- const ch = text[index];
- if (ch !== " ") {
- out += ch;
- column = ch === "\b" ? Math.max(0, column - 1) : column + 1;
- index++;
- continue;
- }
- let end = index;
- while (end < text.length && text[end] === " ") end++;
- let goal = column + end - index;
- while (goal - column > 1) {
- const next = column + (8 - (column % 8));
- if (next > goal) break;
- out += "\t";
- column = next;
- }
- while (column < goal) {
- out += " ";
- column++;
- }
- index = end;
- }
- return out;
-}
-
-function formatPrStoredJoinLine(parts, opts) {
- let out = "";
- let outputPosition = opts.margin.length;
- let spacesNotPrinted = 0;
- let separatorsNotPrinted = 0;
- const separator = opts.columnSeparator;
- const separatorLength = separator.length;
-
- const printWhiteSpace = () => {
- let current = outputPosition;
- const goal = current + spacesNotPrinted;
- while (goal - current > 1) {
- const next = current + (8 - (current % 8));
- if (next > goal) break;
- out += "\t";
- current = next;
- }
- while (current < goal) {
- out += " ";
- current++;
- }
- outputPosition = goal;
- spacesNotPrinted = 0;
- };
-
- const printChar = (ch) => {
- if (ch === " ") {
- spacesNotPrinted++;
- return;
- }
- if (spacesNotPrinted > 0) printWhiteSpace();
- out += ch;
- if (ch === "\b") outputPosition = Math.max(0, outputPosition - 1);
- else if (isPrPrintable(ch)) outputPosition++;
- };
-
- const printSeparator = () => {
- if (separatorsNotPrinted <= 0) {
- if (spacesNotPrinted > 0) printWhiteSpace();
- return;
- }
- for (; separatorsNotPrinted > 0; separatorsNotPrinted--) {
- for (const ch of separator) {
- if (ch === " ") {
- spacesNotPrinted++;
- continue;
- }
- if (spacesNotPrinted > 0) printWhiteSpace();
- out += ch;
- outputPosition++;
- }
- if (spacesNotPrinted > 0) printWhiteSpace();
- }
- };
-
- parts.forEach((part, column) => {
- const startPosition = column === 0 ? opts.margin.length + separatorLength : opts.margin.length;
- if (separatorLength < startPosition) spacesNotPrinted = startPosition - separatorLength - outputPosition;
- printSeparator();
- for (const ch of part) printChar(ch);
- if (spacesNotPrinted === 0) {
- outputPosition = startPosition + prStoredEndPosition(part, opts.tabSize);
- if (startPosition - separatorLength === opts.margin.length) outputPosition -= separatorLength;
- }
- separatorsNotPrinted++;
- });
-
- return out;
-}
-
-function prStoredEndPosition(text, tabSize = 8) {
- let position = 0;
- for (const ch of text) {
- if (ch === "\t") position += tabSize - (position % tabSize);
- else if (ch === "\b") position = Math.max(0, position - 1);
- else if (isPrPrintable(ch) || ch === " ") position++;
- }
- return position;
-}
-
-function isPrPrintable(ch) {
- const code = ch.codePointAt(0);
- return code >= 0x20 && code !== 0x7f;
-}
-
-function padPrMergeEnd(text, width) {
- let out = text;
- let displayWidth = prDisplayWidth(text);
- while (displayWidth + (8 - (displayWidth % 8)) <= width) {
- const spaces = 8 - (displayWidth % 8);
- out += "\t";
- displayWidth += spaces;
- }
- if (displayWidth < width) out += " ".repeat(width - displayWidth);
- return out;
-}
-
-function prDisplayWidth(text) {
- let column = 0;
- for (const ch of text) {
- if (ch === "\t") column += 8 - (column % 8);
- else if (ch === "\b") column = Math.max(0, column - 1);
- else column++;
- }
- return column;
-}
-
-function prColumnAfter(text, startColumn = 0) {
- let column = startColumn;
- for (const ch of text) {
- if (ch === "\t") column += 8 - (column % 8);
- else if (ch === "\b") column = Math.max(0, column - 1);
- else column++;
- }
- return column;
-}
-
-function formatPrLineNumber(value, width) {
- const text = String(value);
- const clipped = text.length > width ? text.slice(-width) : text;
- return clipped.padStart(width);
-}
-
-async function pinky(args) {
- const longOutput = pinkyLongOutputRequested(args);
- args = normalizePinkyLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { b: false, f: false, h: false, i: false, l: false, p: false, q: false, s: false, w: false }, long: { lookup: false, help: false, version: false } });
- const info = userInfo();
- const name = info.username;
- if (longOutput) {
- if (!operands.length) throw new UsageError("no username specified; at least one must be specified when using -l", true);
- const passwd = await readPasswd();
- const users = operands;
- for (const user of users) {
- const row = passwd.get(user);
- const gecosName = row?.gecos?.split(",")[0] || (row ? user : "???");
- stdout(`Login name: ${user.padEnd(28)}In real life: ${gecosName}\n`);
- if (row && !(opts.b)) stdout(`Directory: ${row.home.padEnd(29)}Shell: ${row.shell}\n`);
- if (row && !opts.h) await pinkyPrintProfile("Project: ", row.home, ".project");
- if (row && !opts.p) await pinkyPrintProfile("Plan:\n", row.home, ".plan");
- if (row) stdout("\n");
- }
- } else {
- const hideName = opts.w || opts.i || opts.q;
- const hideIdle = opts.q;
- const hideWhere = opts.i || opts.q;
- if (!opts.f) {
- const columns = ["Login"];
- if (!hideName) columns.push("Name");
- columns.push("TTY");
- if (!hideIdle) columns.push("Idle");
- columns.push("When");
- if (!hideWhere) columns.push("Where");
- stdout(pinkyShortHeader(columns));
- }
- const filters = new Set(operands);
- if (!filters.size || filters.has(name)) {
- const record = (await filterWhoUsers(await readUtmpRecords("/var/run/utmp"), false)).find((entry) => entry.user === name);
- stdout(pinkyShortRow({ name, line: record?.line, time: record?.time, showName: !hideName, showIdle: !hideIdle, showWhere: !hideWhere }));
- }
- }
- return 0;
-}
-
-function pinkyLongOutputRequested(args) {
- let longOutput = false;
- for (const arg of args) {
- if (arg === "--") break;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (arg.startsWith("--")) continue;
- for (const option of arg.slice(1)) {
- if (option === "l") longOutput = true;
- else if (option === "s") longOutput = false;
- }
- }
- return longOutput;
-}
-
-async function pinkyPrintProfile(header, home, name) {
- try {
- const content = await readAll(join(home, name));
- stdout(header);
- stdout(content);
- } catch {
- // GNU pinky treats unavailable profile files as absent.
- }
-}
-
-function pinkyMetaOption(args) {
- const shortOptions = new Set(["b", "f", "h", "i", "l", "p", "q", "s", "w"]);
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const normalized = normalizePinkyLongOption(arg);
- const name = normalized.slice(2).split("=", 1)[0];
- if (!PINKY_LONG_OPTIONS.includes(name) || normalized.includes("=")) return null;
- if (normalized === "--help" || normalized === "--version") return normalized;
- continue;
- }
- if (arg.startsWith("-") && arg !== "-") {
- for (let i = 1; i < arg.length; i++) if (!shortOptions.has(arg[i])) return null;
- }
- }
- return null;
-}
-
-function normalizePinkyLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, PINKY_LONG_OPTIONS);
-}
-
-function normalizePinkyLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, PINKY_LONG_OPTIONS);
-}
-
-function pinkyShortHeader(columns) {
- return columns.map((column, index) => {
- const widths = { Login: columns.includes("Name") ? 8 : 9, Name: 20, TTY: 8, Idle: 6, When: whoUsesPosixDateFormat() ? 12 : 16, Where: 0 };
- return widths[column] ? column.padEnd(widths[column]) : column;
- }).join(" ") + "\n";
-}
-
-function pinkyShortRow({ name, line, time, showName, showIdle, showWhere }) {
- const parts = [name.padEnd(8)];
- if (showName) parts.push("".padEnd(19));
- parts.push(`?${line ?? "tty"}`.padEnd(9));
- if (showIdle) parts.push("?????".padEnd(6));
- parts.push(time ? formatWhoDate(time) : formatWhoDate(Date.now() / 1000));
- if (showWhere) parts.push("");
- return parts.join(" ").trimEnd() + "\n";
-}
-
-async function ptx(args) {
- args = normalizePtxLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { A: false, b: "value", F: "value", G: false, M: "value", O: false, R: false, S: "value", T: false, W: "value", f: false, g: "value", i: "value", o: "value", r: false, t: false, w: "value" }, long: { "auto-reference": false, "break-file": "value", "flag-truncation": "value", format: "value", "ignore-case": false, "ignore-file": "value", "macro-name": "value", "only-file": "value", "right-side-refs": false, "sentence-regexp": "value", "typeset-mode": false, "word-regexp": "value", references: false, traditional: false, width: "value", "gap-size": "value", help: false, version: false } });
- const traditional = opts.G || opts.traditional;
- const output = traditional && operands.length > 1 ? operands[1] : null;
- if (output != null) {
- const status = await writePtxOutput(output, "");
- if (status !== 0) return status;
- }
- if (traditional && operands.length > 2) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[2])}`, true);
- const files = traditional ? [operands[0] ?? "-"] : (operands.length ? operands : ["-"]);
- const ignoreCase = opts.f || opts["ignore-case"];
- let ignoreWords;
- let onlyWords;
- let breakCharacters = null;
- try {
- ignoreWords = await readPtxWordList(opts.i ?? opts["ignore-file"], ignoreCase);
- onlyWords = await readPtxWordList(opts.o ?? opts["only-file"], ignoreCase);
- const breakFile = opts.b ?? opts["break-file"];
- if (breakFile) breakCharacters = decodeSurrogateEscapedBytes(await readAll(breakFile));
- } catch (error) {
- const file = error.file ?? (opts.b ?? opts["break-file"]);
- stderr(`ptx: ${file ? `${textInputDiagnosticName(file)}: ` : ""}${systemErrorMessage(error)}\n`);
- return 1;
- }
- const format = opts.O ? "roff" : opts.T ? "tex" : traditional ? "roff" : opts.format == null ? undefined : parsePtxFormat(opts.format);
- const macroName = opts.M ?? opts["macro-name"] ?? "xx";
- const width = parsePtxPositiveInteger(opts.w ?? opts.width ?? (opts.t || opts["typeset-mode"] || opts.G || opts.traditional ? "100" : "72"), "line width");
- const gap = parsePtxPositiveInteger(opts.g ?? opts["gap-size"] ?? "3", "gap width");
- const truncation = opts.F ?? opts["flag-truncation"] ?? "/";
- let sentenceRegex = null;
- if (opts.S || opts["sentence-regexp"]) {
- const sentence = opts.S ?? opts["sentence-regexp"];
- try {
- sentenceRegex = new RegExp(sentence, "gu");
- if (sentenceRegex.test("")) {
- stderr("ptx: regular expression has length zero\n");
- return 1;
- }
- } catch {}
- }
- let wordRegex;
- try {
- wordRegex = opts.W || opts["word-regexp"]
- ? new RegExp(opts.W ?? opts["word-regexp"], "gu")
- : breakCharacters == null ? /[\p{L}\p{N}_]+/gu : ptxBreakCharacterRegex(breakCharacters);
- } catch {
- return 0;
- }
- const rows = [];
- const texts = [];
- const manualReferences = opts.r || opts.references;
- for (const file of files) {
- let text;
- try {
- text = decodeSurrogateEscapedBytes(await readAll(file));
- } catch (error) {
- stderr(file === "-" ? `ptx: ${nodeErrorMessage(error)}\n` : `ptx: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- if (manualReferences) {
- const prepared = ptxExtractLineReferences(text, wordRegex);
- for (let line = 0; line < prepared.records.length; line++) {
- texts.push({ file, text: prepared.records[line].text, references: [prepared.records[line].reference], lineOffset: line });
- }
- } else {
- for (const record of ptxSplitSentences(text, sentenceRegex)) {
- texts.push({ file, text: record.text, references: [], lineOffset: record.lineOffset });
- }
- }
- }
- for (const { file, text, references, lineOffset } of texts) {
- const tokens = [];
- for (const match of text.matchAll(wordRegex)) {
- const word = match[0];
- const key = ignoreCase ? word.toLowerCase() : word;
- const recordLine = text.slice(0, match.index).split("\n").length;
- const line = recordLine + lineOffset;
- const automaticReference = opts.A || opts["auto-reference"];
- const autoReference = automaticReference ? `${file === "-" ? "" : file}:${line}:` : (references[recordLine - 1] ?? "");
- const referencePadding = automaticReference ? 1 : Math.max(0, 3 - autoReference.length);
- tokens.push({ word, key, indexed: !ignoreWords.has(key) && (!onlyWords.size || onlyWords.has(key)), start: match.index, end: match.index + word.length, source: text, autoReference, referencePadding });
- }
- for (let index = 0; index < tokens.length; index++) {
- if (!tokens[index].indexed) continue;
- rows.push({ tokens, index, key: tokens[index].key, order: index });
- }
- }
- rows.sort((a, b) => comparePtxKeys(a.key, b.key) || a.order - b.order);
- const out = rows.map((row) => renderPtxRow(row, { format, width, gap, macroName, truncation, rightSideRefs: opts.R || opts["right-side-refs"] })).join("");
- if (output != null) return await writePtxOutput(output, out);
- else stdout(out);
- return 0;
-}
-
-async function writePtxOutput(file, text) {
- try {
- await writeAll(file, text);
- return 0;
- } catch (error) {
- return fail("ptx", `${file}: ${systemErrorMessage(error)}`);
- }
-}
-
-function comparePtxKeys(a, b) {
- const left = Buffer.from(String(a));
- const right = Buffer.from(String(b));
- const n = Math.min(left.length, right.length);
- for (let i = 0; i < n; i++) if (left[i] !== right[i]) return left[i] - right[i];
- return left.length - right.length;
-}
-
-function renderPtxRow(row, opts) {
- const token = row.tokens[row.index];
- const keyword = token.word;
- const minWidth = opts.gap <= 1 ? 2 : 6;
- const halfWidth = Math.floor(Math.max(opts.width, minWidth) / 2);
- const source = token.source;
- if (source != null && hasSurrogateEscapedBytes(source)) {
- const before = source.slice(0, token.start).replace(/\n$/u, "").trimEnd();
- const after = source.slice(token.end).replace(/\n$/u, "").trimEnd();
- if (before) return ptxApplyAutoReference(`${" ".repeat(Math.max(0, halfWidth - before.length))}${before}${" ".repeat(opts.gap)}${keyword}${after}\n`, token.autoReference, opts, token.referencePadding);
- return ptxApplyAutoReference(`${" ".repeat(halfWidth + opts.gap)}${keyword}${after}\n`, token.autoReference, opts, token.referencePadding);
- }
- const wrap = ptxWrapContext(row, source);
- const before = wrap.before;
- const after = wrap.after;
- const rightStartsWithPunctuation = /^[^\s\p{L}\p{N}_]/u.test(source.slice(token.end));
- const right = after ? `${rightStartsWithPunctuation ? "" : " "}${after}` : "";
- const initialSentenceIndent = before === "" && /^\s/u.test(source) ? 1 : 0;
- if (opts.format === "roff") return ptxApplyAutoReference(`.${opts.macroName ?? "xx"} "${wrap.beforeRef}" "${before}" "${keyword}${right}" "${wrap.afterRef}"\n`, token.autoReference, opts, token.referencePadding);
- if (opts.format === "tex") return ptxApplyAutoReference(`\\xx {${wrap.beforeRef}}{${before}}{${keyword}}{${right}}{${wrap.afterRef}}\n`, token.autoReference, opts, token.referencePadding);
- const fitted = opts.width >= 20 && opts.width < 24 ? renderPtxFittedRow(row, { ...opts, halfWidth, keyword }) : null;
- if (fitted) return ptxApplyAutoReference(fitted, token.autoReference, opts, token.referencePadding);
- if (wrap.beforeRef) {
- const prefixLead = opts.gap;
- const leftText = before
- ? `${" ".repeat(prefixLead)}${wrap.beforeRef}${" ".repeat(Math.max(1, halfWidth - wrap.beforeRef.length - before.length - prefixLead))}${before}`
- : `${" ".repeat(prefixLead)}${wrap.beforeRef}${" ".repeat(Math.max(0, halfWidth - wrap.beforeRef.length - prefixLead))}`;
- return ptxApplyAutoReference(`${leftText}${" ".repeat(opts.gap)}${keyword}${right}\n`, token.autoReference, opts, token.referencePadding);
- }
- if (before) {
- const spaces = Math.max(0, halfWidth - before.length);
- const full = `${" ".repeat(spaces)}${before}${" ".repeat(opts.gap)}${keyword}${right}`;
- if (wrap.afterRef) return ptxApplyAutoReference(`${full}${" ".repeat(Math.max(1, opts.width + opts.gap - full.length - wrap.afterRef.length))}${wrap.afterRef}\n`, token.autoReference, opts, token.referencePadding);
- if (before.length + opts.gap + keyword.length <= halfWidth + 1) return ptxApplyAutoReference(`${full}\n`, token.autoReference, opts, token.referencePadding);
- return ptxApplyAutoReference(`${" ".repeat(halfWidth)}/${" ".repeat(opts.gap)}${keyword}${right}\n`, token.autoReference, opts, token.referencePadding);
- }
- const full = `${" ".repeat(halfWidth + opts.gap + initialSentenceIndent)}${keyword}${right}`;
- if (wrap.afterRef) return ptxApplyAutoReference(`${full}${" ".repeat(Math.max(1, opts.width + opts.gap - full.length - wrap.afterRef.length))}${wrap.afterRef}\n`, token.autoReference, opts, token.referencePadding);
- if (!right || halfWidth >= keyword.length + right.length + 2) return ptxApplyAutoReference(`${full}\n`, token.autoReference, opts, token.referencePadding);
- return ptxApplyAutoReference(`${" ".repeat(halfWidth + opts.gap + initialSentenceIndent)}${keyword}/\n`, token.autoReference, opts, token.referencePadding);
-}
-
-function ptxApplyAutoReference(line, reference, opts = {}, referencePadding = 1) {
- if (!reference) return line;
- const newline = line.endsWith("\n") ? "\n" : "";
- const body = newline ? line.slice(0, -1) : line;
- if (opts.rightSideRefs) {
- const displayReference = reference.endsWith(":") ? reference.slice(0, -1) : reference;
- const leading = body.match(/^ */)?.[0].length ?? 0;
- return `${body.slice(Math.min(leading, opts.gap)).padEnd(opts.width + opts.gap)}${displayReference}${newline}`;
- }
- const leading = body.match(/^ */)?.[0].length ?? 0;
- return `${reference}${body.slice(Math.min(leading, reference.length + referencePadding))}${newline}`;
-}
-
-function ptxExtractLineReferences(text, wordRegex) {
- const references = [];
- const lines = String(text).split(/(?<=\n)/u);
- const records = lines.map((line) => {
- const first = [...line.matchAll(wordRegex)][0];
- if (!first) {
- references.push("");
- return { text: line, reference: "" };
- }
- references.push(first[0]);
- return { text: `${line.slice(0, first.index)}${line.slice(first.index + first[0].length).replace(/^[ \t]*/u, "")}`, reference: first[0] };
- });
- return { records, references };
-}
-
-function ptxSplitSentences(text, sentenceRegex) {
- if (!sentenceRegex) return [{ text, lineOffset: 0 }];
- const records = [];
- let start = 0;
- let lineOffset = 0;
- sentenceRegex.lastIndex = 0;
- for (const match of text.matchAll(sentenceRegex)) {
- const end = match.index + match[0].length;
- if (end <= start) continue;
- records.push({ text: text.slice(start, end), lineOffset });
- lineOffset += (text.slice(start, end).match(/\n/gu) ?? []).length;
- start = end;
- }
- if (start < text.length || records.length === 0) records.push({ text: text.slice(start), lineOffset });
- return records;
-}
-
-function ptxBreakCharacterRegex(characters) {
- const escaped = [...new Set([...String(characters), "\n"])].map((character) => character.replace(/[\\\]\[\-^]/gu, "\\$&")).join("");
- return new RegExp(`[^${escaped}]+`, "gu");
-}
-
-function ptxWrapContext(row, source) {
- const token = row.tokens[row.index];
- let before = ptxContextText(source.slice(0, token.start));
- let after = ptxContextText(source.slice(token.end));
- let beforeRef = "";
- let afterRef = "";
- const hasRecordBreak = source.replace(/\n+$/u, "").includes("\n");
- if (!hasRecordBreak || row.tokens.length < 2) return { before, after, beforeRef, afterRef };
- const first = row.tokens[0].word;
- const last = row.tokens.at(-1).word;
- if (row.index === row.tokens.length - 1) {
- before = ptxRemoveFirstWord(before);
- afterRef = first;
- } else if (row.index === 0) {
- beforeRef = last;
- after = ptxRemoveLastWord(after);
- } else if (row.index === 1 && source.slice(token.end).includes("\n")) {
- beforeRef = last;
- after = ptxRemoveLastWord(after);
- }
- return { before, after, beforeRef, afterRef };
-}
-
-function ptxRemoveFirstWord(text) {
- return String(text).trim().replace(/^\S+\s*/u, "");
-}
-
-function ptxRemoveLastWord(text) {
- return String(text).trim().replace(/\s*\S+$/u, "");
-}
-
-function renderPtxFittedRow(row, opts) {
- const index = row.index;
- const left = ptxFittedLeftContext(row.tokens.slice(0, index).map((token) => token.word), opts.halfWidth, opts.truncation);
- const keyafterWidth = opts.halfWidth - 2 * opts.truncation.length;
- const right = ptxFittedRightContext(row.tokens.slice(index + 1).map((token) => token.word), keyafterWidth - opts.keyword.length, opts.truncation);
- const hasSourceContext = left || right;
- if (!hasSourceContext) return null;
- const markerPadding = left === opts.truncation && opts.truncation.length > 1 ? 1 : 0;
- const leftPad = left ? Math.max(0, opts.halfWidth - left.length + markerPadding) : opts.halfWidth + opts.gap;
- const gap = left ? " ".repeat(opts.gap) : "";
- return `${" ".repeat(leftPad)}${left}${gap}${opts.keyword}${right}\n`;
-}
-
-function ptxFittedLeftContext(words, halfWidth, truncation = "/") {
- if (!words.length) return "";
- if (truncation.length > 1) return truncation;
- const all = words.join(" ");
- if (words.length === 1 && all.length <= halfWidth) return all;
- if (all.length <= halfWidth - Math.max(1, truncation.length + 4)) return all;
- const nearest = words.at(-1);
- if (!nearest) return "";
- const truncated = `${truncation}${nearest}`;
- if (truncated.length <= halfWidth) return truncated;
- return truncation;
-}
-
-function ptxFittedRightContext(words, available, truncation = "/") {
- if (!words.length) return "";
- if (available <= 0) return truncation;
- const out = [];
- let used = 0;
- for (const word of words) {
- const extra = (out.length ? 1 : 1) + word.length;
- if (used + extra > available) break;
- out.push(word);
- used += extra;
- }
- if (!out.length) return truncation;
- return ` ${out.join(" ")}${out.length < words.length ? truncation : ""}`;
-}
-
-function ptxContextText(text) {
- return String(text).trim().replace(/\s+/gu, " ");
-}
-
-function parsePtxPositiveInteger(value, name) {
- const text = String(value);
- if (!/^\d+$/.test(text) || BigInt(text) <= 0n || BigInt(text) > BigInt(Number.MAX_SAFE_INTEGER)) {
- throw new UsageError(`invalid ${name}: ${localeQuotedEscapedDiagnostic(text)}`);
- }
- return Number(text);
-}
-
-function parsePtxFormat(value) {
- const text = String(value);
- const matches = ["roff", "tex"].filter((format) => format.startsWith(text));
- if (matches.length === 1 && text !== "") return matches[0];
- const kind = text === "" || matches.length > 1 ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(text)} for ${localeQuotedDiagnostic("--format")}\nValid arguments are:\n - ${localeQuotedDiagnostic("roff")}\n - ${localeQuotedDiagnostic("tex")}`, true);
-}
-
-function hasSurrogateEscapedBytes(text) {
- for (let i = 0; i < text.length; i++) {
- const code = text.charCodeAt(i);
- if (code >= 0xdc80 && code <= 0xdcff) return true;
- }
- return false;
-}
-
-async function readPtxWordList(file, ignoreCase = false) {
- if (!file) return new Set();
- let bytes;
- try {
- bytes = await readAll(file);
- } catch (error) {
- error.file = file;
- throw error;
- }
- const text = decodeSurrogateEscapedBytes(bytes);
- return new Set((text.match(/[\p{L}\p{N}_]+/gu) ?? []).map((word) => ignoreCase ? word.toLowerCase() : word));
-}
-
-async function sttyCmd(args) {
- const { opts, operands } = parseSttyArgs(args);
- validateSttyOutputStyle(opts, operands);
- validateSttyOperands(operands);
- const target = opts.F ?? opts.file;
- let targetHandle = null;
- let fd = 0;
- if (target != null) {
- try {
- targetHandle = await open(target, "r");
- fd = targetHandle.fd;
- } catch (error) {
- return fail("stty", `${sttyDeviceDisplayName(target)}: ${systemErrorMessage(error)}`);
- }
- }
- if (targetHandle == null && !sttyTargetIsTty(opts)) return fail("stty", `${sttyTargetName(opts)}: Inappropriate ioctl for device`);
- const termios = sttyReadTermios(fd);
- if (!termios) {
- await targetHandle?.close().catch(() => {});
- return fail("stty", `${sttyTargetName(opts)}: Inappropriate ioctl for device`);
- }
- const windowSize = sttyReadWindowSize(fd);
- if (opts.g || opts.save) {
- stdout(sttySavedSettings(termios));
- await targetHandle?.close().catch(() => {});
- return 0;
- }
- const rows = windowSize?.rows ?? process.stdout.rows ?? 0;
- const columns = windowSize?.columns ?? process.stdout.columns ?? 0;
- if (!operands.length || opts.a || opts.all) {
- stdout(opts.a || opts.all ? sttyAllOutput(rows, columns, termios) : sttyDefaultOutput(termios));
- await targetHandle?.close().catch(() => {});
- return 0;
- }
- if (operands.length === 1 && operands[0] === "speed") {
- stdout(sttySpeedOutput(termios));
- await targetHandle?.close().catch(() => {});
- return 0;
- }
- if (operands.length === 1 && operands[0] === "size") {
- stdout(`${rows} ${columns}\n`);
- await targetHandle?.close().catch(() => {});
- return 0;
- }
- if (operands.every((operand) => operand === "drain" || operand === "-drain")) {
- stdout(sttyDefaultOutput(termios));
- await targetHandle?.close().catch(() => {});
- return 0;
- }
- const applied = sttyApplyOperands(termios, operands, windowSize);
- if (applied.windowSize && libc.symbols.ioctl(fd, TIOCSWINSZ, ptr(sttyWindowSizeBuffer(applied.windowSize))) !== 0) {
- await targetHandle?.close().catch(() => {});
- return fail("stty", `${sttyTargetName(opts)}: Inappropriate ioctl for device`);
- }
- if (libc.symbols.tcsetattr(fd, sttyApplyTiming(operands), ptr(applied.termios.buffer)) !== 0) {
- await targetHandle?.close().catch(() => {});
- return fail("stty", `${sttyTargetName(opts)}: Inappropriate ioctl for device`);
- }
- libc.symbols._exit(0);
- return 0;
-}
-
-function sttyMetaOption(args) {
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const normalized = normalizeLongOptionByPrefix(arg, STTY_LONG_OPTIONS);
- const [name, inlineValue] = normalized.slice(2).split(/=(.*)/s, 2);
- if ((normalized === "--help" || normalized === "--version") && inlineValue == null) return normalized;
- if (name === "file" && inlineValue == null) i++;
- continue;
- }
- if (arg === "-F") i++;
- else if (arg.startsWith("-F") && arg.length > 2) continue;
- }
- return null;
-}
-
-function installMetaOption(args) {
- const normalized = normalizeInstallLongOptions(args);
- const longValueOptions = new Set(["group", "mode", "owner", "strip-program", "suffix", "target-directory"]);
- const longOptionalValueOptions = new Set(["backup", "context"]);
- const longKnownOptions = new Set(INSTALL_LONG_OPTIONS);
- const shortValueOptions = new Set(["g", "m", "o", "S", "t"]);
- const shortKnownOptions = new Set(["b", "c", "C", "D", "d", "g", "m", "o", "p", "s", "S", "t", "T", "v", "Z"]);
- let sawPreserveContext = false;
- let sawContextValue = false;
- for (let i = 0; i < normalized.length; i++) {
- const arg = normalized[i];
- if (arg === "--") return null;
- if (arg.startsWith("--")) {
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (!longKnownOptions.has(name)) return null;
- if ((arg === "--help" || arg === "--version") && inlineValue == null) {
- if (sawPreserveContext && !selinuxRuntimeEnabled()) stderr("install: WARNING: ignoring --preserve-context; this kernel is not SELinux-enabled\n");
- if (sawContextValue && !selinuxRuntimeEnabled()) stderr("install: warning: ignoring --context; it requires an SELinux-enabled kernel\n");
- return arg;
- }
- if (name === "preserve-context") sawPreserveContext = true;
- if (name === "context" && inlineValue !== undefined) sawContextValue = true;
- if (longValueOptions.has(name)) {
- if (inlineValue == null) i++;
- } else if (longOptionalValueOptions.has(name)) {
- continue;
- } else if (inlineValue != null) return null;
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (!shortKnownOptions.has(ch)) return null;
- if (shortValueOptions.has(ch)) {
- if (arg.slice(j + 1) === "") i++;
- break;
- }
- }
- }
- return null;
-}
-
-function normalizeInstallLongOptions(args) {
- const out = [];
- const valueOptions = new Set(["group", "mode", "owner", "strip-program", "suffix", "target-directory"]);
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(arg, ...args.slice(i + 1));
- break;
- }
- if (!arg.startsWith("--")) {
- out.push(arg);
- continue;
- }
- const normalized = normalizeLongOptionByPrefix(arg, INSTALL_LONG_OPTIONS);
- out.push(normalized);
- const [name, inlineValue] = normalized.slice(2).split(/=(.*)/s, 2);
- if (valueOptions.has(name) && inlineValue == null && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-function parseSttyArgs(args) {
- const opts = {};
- const operands = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- break;
- }
- if (arg.startsWith("--")) {
- const normalized = normalizeLongOptionByPrefix(arg, STTY_LONG_OPTIONS);
- const [name, inlineValue] = normalized.slice(2).split(/=(.*)/s, 2);
- if (name === "file") {
- if (inlineValue != null) opts.file = inlineValue;
- else if (i + 1 < args.length) opts.file = args[++i];
- else throw new UsageError(`invalid argument ${localeQuotedDiagnostic("--file")}`, true);
- } else if (name === "all" && inlineValue == null) opts.all = true;
- else if (name === "save" && inlineValue == null) opts.save = true;
- else if ((name === "help" || name === "version") && inlineValue == null) opts[name] = true;
- else operands.push(arg);
- continue;
- }
- if (arg === "-a") opts.a = true;
- else if (arg === "-g") opts.g = true;
- else if (arg === "-F") {
- if (i + 1 < args.length) opts.F = args[++i];
- else throw new UsageError("option requires an argument -- 'F'", true);
- } else if (arg.startsWith("-F") && arg.length > 2) opts.F = arg.slice(2);
- else if (/^-[agF]+/.test(arg)) {
- let consumed = false;
- for (let j = 1; j < arg.length; j++) {
- const ch = arg[j];
- if (ch === "a") opts.a = true;
- else if (ch === "g") opts.g = true;
- else if (ch === "F") {
- const rest = arg.slice(j + 1);
- if (rest) opts.F = rest;
- else if (i + 1 < args.length) opts.F = args[++i];
- else operands.push("F");
- consumed = true;
- break;
- } else {
- operands.push(arg);
- consumed = true;
- break;
- }
- }
- if (consumed) continue;
- }
- else operands.push(arg);
- }
- return { opts, operands };
-}
-
-function validateSttyOutputStyle(opts, operands) {
- const styles = [opts.a || opts.all, opts.g || opts.save].filter(Boolean).length;
- if (styles > 1) throw new UsageError("the options for verbose and stty-readable output styles are\nmutually exclusive");
- if (styles && operands.length) throw new UsageError("when specifying an output style, modes may not be set");
-}
-
-function validateSttyOperands(operands) {
- for (let i = 0; i < operands.length; i++) {
- const setting = operands[i];
- if (setting === "size" || setting === "speed") continue;
- if (/^[0-9a-fA-F:]+$/.test(setting) && setting.includes(":")) {
- if (!sttySavedSettingsLooksValid(setting)) throw new UsageError(`invalid argument ${localeQuotedEscapedDiagnostic(setting)}`, true);
- continue;
- }
- if (sttyBareSpeed(setting) != null || STTY_NO_ARG_SETTINGS.has(setting)) continue;
- if (STTY_VALUE_SETTINGS.has(setting)) {
- if (i + 1 >= operands.length) throw new UsageError(`missing argument to '${setting}'`, true);
- const value = operands[++i];
- validateSttyValueSetting(setting, value);
- continue;
- }
- throw new UsageError(`invalid argument ${localeQuotedEscapedDiagnostic(setting)}`, true);
- }
-}
-
-function validateSttyValueSetting(setting, value) {
- if (setting === "line" || setting === "min" || setting === "time") {
- parseSttyInteger(value, 0xffn);
- return;
- }
- if (setting === "ispeed" || setting === "ospeed") {
- parseSttySpeed(value, setting);
- return;
- }
- if (STTY_CONTROL_SETTINGS.has(setting)) {
- if (value === "" || value === "undef" || value === "^-" || value.length === 1 || value.startsWith("^") && value.length >= 2) return;
- parseSttyInteger(value, 0xffn);
- }
-}
-
-const STTY_NO_ARG_SETTING_NAMES = [
- "parenb", "parodd", "cmspar", "cs5", "cs6", "cs7", "cs8", "hupcl", "hup", "cstopb", "cread", "clocal", "crtscts",
- "ignbrk", "brkint", "ignpar", "parmrk", "inpck", "istrip", "inlcr", "igncr", "icrnl", "ixon", "ixoff", "iuclc", "ixany", "imaxbel", "iutf8",
- "opost", "olcuc", "ocrnl", "onlcr", "onocr", "onlret", "ofill", "ofdel", "nl0", "nl1", "cr0", "cr1", "cr2", "cr3", "tab0", "tab1", "tab2", "tab3", "bs0", "bs1", "vt0", "vt1", "ff0", "ff1",
- "isig", "icanon", "iexten", "echo", "echoe", "echok", "echonl", "noflsh", "xcase", "tostop", "echoprt", "echoctl", "echoke", "flusho", "extproc",
- "raw", "cooked", "sane", "cbreak", "pass8", "litout", "nl", "ek", "dec", "evenp", "parity", "oddp",
- "drain",
-];
-const STTY_NO_ARG_SETTINGS = new Set(STTY_NO_ARG_SETTING_NAMES.flatMap((name) => [name, `-${name}`]));
-const STTY_VALUE_SETTINGS = new Set([
- "rows", "cols", "columns", "ispeed", "ospeed", "min", "time", "line",
- "intr", "quit", "erase", "kill", "eof", "eol", "eol2", "swtch", "start", "stop", "susp", "rprnt", "werase", "lnext", "discard",
-]);
-const STTY_CONTROL_SETTINGS = new Set([
- "intr", "quit", "erase", "kill", "eof", "eol", "eol2", "swtch", "start", "stop", "susp", "rprnt", "werase", "lnext", "discard",
-]);
-
-function sttySavedSettingsLooksValid(value) {
- const parts = value.split(":");
- return parts.length === 36
- && parts.every((part) => /^[0-9a-fA-F]+$/.test(part) && BigInt(`0x${part}`) <= 0xffffffffn);
-}
-
-function sttyTargetIsTty(opts) {
- if (opts.F || opts.file) return false;
- return Boolean(process.stdin.isTTY);
-}
-
-function sttyTargetName(opts) {
- return sttyDeviceDisplayName(opts.F ?? opts.file ?? "'standard input'");
-}
-
-function sttyDeviceDisplayName(target) {
- return target === "" ? "''" : target;
-}
-
-function sttyReadTermios(fd = 0) {
- const buffer = Buffer.alloc(TERMIOS_SIZE);
- if (libc.symbols.tcgetattr(fd, ptr(buffer)) !== 0) return null;
- return { buffer, view: new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength) };
-}
-
-function sttyReadWindowSize(fd = 0) {
- const buffer = Buffer.alloc(8);
- if (libc.symbols.ioctl(fd, TIOCGWINSZ, ptr(buffer)) !== 0) return null;
- return { rows: buffer.readUInt16LE(0), columns: buffer.readUInt16LE(2) };
-}
-
-function sttyWindowSizeBuffer(size) {
- const buffer = Buffer.alloc(8);
- buffer.writeUInt16LE(size.rows ?? 0, 0);
- buffer.writeUInt16LE(size.columns ?? 0, 2);
- return buffer;
-}
-
-function sttySavedSettings(termios) {
- const fields = [
- sttyTermiosFlag(termios, "iflag").toString(16),
- sttyTermiosFlag(termios, "oflag").toString(16),
- sttyTermiosFlag(termios, "cflag").toString(16),
- sttyTermiosFlag(termios, "lflag").toString(16),
- ];
- for (let i = 0; i < 32; i++) fields.push(termios.view.getUint8(TERMIOS_OFFSETS.cc + i).toString(16));
- return `${fields.join(":")}\n`;
-}
-
-function sttyDefaultOutput(termios) {
- const toggles = [];
- if (!sttyHasFlag(termios, "iflag", "brkint")) toggles.push("-brkint");
- if (!sttyHasFlag(termios, "iflag", "imaxbel")) toggles.push("-imaxbel");
- if (!sttyHasFlag(termios, "lflag", "echo")) toggles.push("-echo");
- if (!sttyHasFlag(termios, "lflag", "icanon")) toggles.push("-icanon");
- if (!sttyHasFlag(termios, "lflag", "isig")) toggles.push("-isig");
- if (!sttyHasFlag(termios, "oflag", "opost")) toggles.push("-opost");
- return `${sttyVerboseSpeedPrefix(termios)} line = ${termios.view.getUint8(TERMIOS_OFFSETS.line)};\n${toggles.join(" ")}\n`;
-}
-
-function sttyAllOutput(rows, columns, termios) {
- return `${sttyVerboseSpeedPrefix(termios)} rows ${rows}; columns ${columns}; line = ${termios.view.getUint8(TERMIOS_OFFSETS.line)};
-intr = ${sttyControlDisplay(termios, "intr")}; quit = ${sttyControlDisplay(termios, "quit")}; erase = ${sttyControlDisplay(termios, "erase")}; kill = ${sttyControlDisplay(termios, "kill")}; eof = ${sttyControlDisplay(termios, "eof")}; eol = ${sttyControlDisplay(termios, "eol")};
-eol2 = ${sttyControlDisplay(termios, "eol2")}; swtch = ${sttyControlDisplay(termios, "swtch")}; start = ${sttyControlDisplay(termios, "start")}; stop = ${sttyControlDisplay(termios, "stop")}; susp = ${sttyControlDisplay(termios, "susp")}; rprnt = ${sttyControlDisplay(termios, "rprnt")};
-werase = ${sttyControlDisplay(termios, "werase")}; lnext = ${sttyControlDisplay(termios, "lnext")}; discard = ${sttyControlDisplay(termios, "discard")}; min = ${termios.view.getUint8(TERMIOS_OFFSETS.cc + STTY_CC.min)}; time = ${termios.view.getUint8(TERMIOS_OFFSETS.cc + STTY_CC.time)};
-${sttyFlagList(termios, "cflag", ["parenb", "parodd", "cmspar", "cs8", "hupcl", "cstopb", "cread", "clocal", "crtscts"])}
-${sttyFlagList(termios, "iflag", ["ignbrk", "brkint", "ignpar", "parmrk", "inpck", "istrip", "inlcr", "igncr", "icrnl", "ixon", "ixoff"])}
-${sttyFlagList(termios, "iflag", ["iuclc", "ixany", "imaxbel", "iutf8"])}
-${sttyFlagList(termios, "oflag", ["opost", "olcuc", "ocrnl", "onlcr", "onocr", "onlret", "ofill", "ofdel"])} ${sttyDelayModeList(termios)}
-${sttyFlagList(termios, "lflag", ["isig", "icanon", "iexten", "echo", "echoe", "echok", "echonl", "noflsh", "xcase", "tostop", "echoprt"])}
-${sttyFlagList(termios, "lflag", ["echoctl", "echoke", "flusho", "extproc"])}
-`;
-}
-
-function sttyTermiosFlag(termios, group) {
- return termios.view.getUint32(TERMIOS_OFFSETS[group], true);
-}
-
-function sttySetTermiosFlag(termios, group, value) {
- termios.view.setUint32(TERMIOS_OFFSETS[group], value >>> 0, true);
-}
-
-function sttyHasFlag(termios, group, name) {
- const flag = STTY_FLAGS[group]?.[name];
- if (flag == null) return false;
- if (group === "cflag" && /^cs[5-8]$/.test(name)) return (sttyTermiosFlag(termios, group) & STTY_CS_MASK) === flag;
- return (sttyTermiosFlag(termios, group) & flag) !== 0;
-}
-
-function sttySetFlag(termios, group, name, enabled) {
- const flag = STTY_FLAGS[group]?.[name];
- if (flag == null) return false;
- let value = sttyTermiosFlag(termios, group);
- if (group === "cflag" && /^cs[5-8]$/.test(name)) value = (value & ~STTY_CS_MASK) | flag;
- else value = enabled ? value | flag : value & ~flag;
- sttySetTermiosFlag(termios, group, value);
- return true;
-}
-
-function sttyFlagList(termios, group, names) {
- return names.map((name) => sttyHasFlag(termios, group, name) ? name : `-${name}`).join(" ");
-}
-
-function sttyDelayModeList(termios) {
- const oflag = sttyTermiosFlag(termios, "oflag");
- return Object.values(STTY_DELAY_GROUPS).map((group) => {
- const active = oflag & group.mask;
- return Object.entries(group.values).find(([, value]) => value === active)?.[0] ?? Object.keys(group.values)[0];
- }).join(" ");
-}
-
-function sttyControlDisplay(termios, setting) {
- const value = termios.view.getUint8(TERMIOS_OFFSETS.cc + STTY_CC[setting]);
- if (value === 0) return "<undef>";
- if (value === 0x7f) return "^?";
- if (value < 0x20) return `^${String.fromCharCode(value + 0x40)}`;
- if (value === 0x20) return " ";
- return String.fromCharCode(value);
-}
-
-function sttyInputSpeed(termios) {
- return termios.view.getUint32(TERMIOS_OFFSETS.ispeed, true);
-}
-
-function sttyOutputSpeed(termios) {
- return termios.view.getUint32(TERMIOS_OFFSETS.ospeed, true);
-}
-
-function sttySpeedOutput(termios) {
- const input = sttyInputSpeed(termios);
- const output = sttyOutputSpeed(termios);
- return input === output ? `${output}\n` : `${input} ${output}\n`;
-}
-
-function sttyVerboseSpeedPrefix(termios) {
- const input = sttyInputSpeed(termios);
- const output = sttyOutputSpeed(termios);
- return input === output ? `speed ${output} baud;` : `ispeed ${input} baud; ospeed ${output} baud;`;
-}
-
-function sttySetSpeed(termios, speed, direction = "both", display = String(speed)) {
- const api = sttyInterposedTermiosApi();
- if ((direction === "both" || direction === "input") && api.cfsetispeed(ptr(termios.buffer), speed) !== 0) {
- throw new UsageError(`unsupported ispeed ${localeQuotedEscapedDiagnostic(display)}`);
- }
- if ((direction === "both" || direction === "output") && api.cfsetospeed(ptr(termios.buffer), speed) !== 0) {
- throw new UsageError(`unsupported ospeed ${localeQuotedEscapedDiagnostic(display)}`);
- }
-}
-
-function sttySyncSpeedFieldsFromCflag(termios) {
- const cflag = sttyTermiosFlag(termios, "cflag");
- const outputCode = cflag & STTY_OBAUD_MASK;
- const inputCode = (cflag & STTY_IBAUD_MASK) >>> 16;
- const output = STTY_CODE_SPEEDS.get(outputCode);
- const input = STTY_CODE_SPEEDS.get(inputCode);
- if (output != null) termios.view.setUint32(TERMIOS_OFFSETS.ospeed, output, true);
- if (input != null) termios.view.setUint32(TERMIOS_OFFSETS.ispeed, input, true);
-}
-
-function sttyApplyOperands(termios, operands, windowSize = null) {
- const next = { buffer: Buffer.from(termios.buffer), view: null };
- next.view = new DataView(next.buffer.buffer, next.buffer.byteOffset, next.buffer.byteLength);
- const nextWindowSize = windowSize == null ? null : { ...windowSize };
- if (operands.length === 1 && sttySavedSettingsLooksValid(operands[0])) {
- sttyApplySavedSettings(next, operands[0]);
- return { termios: next, windowSize: null };
- }
- for (let i = 0; i < operands.length; i++) {
- const setting = operands[i];
- if (STTY_VALUE_SETTINGS.has(setting)) {
- sttyApplyValueSetting(next, nextWindowSize, setting, operands[++i]);
- continue;
- }
- const bareSpeed = sttyBareSpeed(setting);
- if (bareSpeed != null) {
- sttySetSpeed(next, bareSpeed, "both", setting);
- continue;
- }
- sttyApplyModeSetting(next, setting);
- }
- return { termios: next, windowSize: nextWindowSize };
-}
-
-function sttyApplySavedSettings(termios, saved) {
- const parts = saved.split(":").map((part) => Number.parseInt(part, 16));
- if (parts.length < 4 || parts.some((part) => !Number.isFinite(part))) return;
- sttySetTermiosFlag(termios, "iflag", parts[0]);
- sttySetTermiosFlag(termios, "oflag", parts[1]);
- sttySetTermiosFlag(termios, "cflag", parts[2]);
- sttySetTermiosFlag(termios, "lflag", parts[3]);
- for (let i = 0; i < Math.min(32, parts.length - 4); i++) termios.view.setUint8(TERMIOS_OFFSETS.cc + i, parts[i + 4] & 0xff);
- sttySyncSpeedFieldsFromCflag(termios);
-}
-
-function sttyApplyModeSetting(termios, setting) {
- const enabled = !setting.startsWith("-");
- const name = enabled ? setting : setting.slice(1);
- if (name === "drain") return;
- if (name === "raw") return sttyApplyRaw(termios, enabled);
- if (name === "sane") return sttyApplySane(termios);
- if (name === "cooked") return sttyApplyCooked(termios);
- if (name === "cbreak") return sttyApplyCbreak(termios, enabled);
- if (name === "pass8") return sttyApplyPass8(termios, enabled);
- if (name === "litout") return sttyApplyLitout(termios, enabled);
- if (name === "nl") return sttyApplyNl(termios, enabled);
- if (sttyApplyDelayMode(termios, name)) return;
- if (["evenp", "parity"].includes(name)) {
- sttySetFlag(termios, "cflag", "parenb", enabled);
- sttySetFlag(termios, "cflag", "parodd", false);
- return;
- }
- if (name === "oddp") {
- sttySetFlag(termios, "cflag", "parenb", enabled);
- sttySetFlag(termios, "cflag", "parodd", enabled);
- return;
- }
- for (const group of ["iflag", "oflag", "cflag", "lflag"]) {
- if (sttySetFlag(termios, group, name, enabled)) return;
- }
-}
-
-function sttyApplyTiming(operands) {
- let timing = TCSANOW;
- for (const operand of operands) {
- if (operand === "drain") timing = TCSADRAIN;
- else if (operand === "-drain") timing = TCSANOW;
- }
- return timing;
-}
-
-function sttyApplyDelayMode(termios, name) {
- for (const group of Object.values(STTY_DELAY_GROUPS)) {
- if (!(name in group.values)) continue;
- const oflag = sttyTermiosFlag(termios, "oflag");
- sttySetTermiosFlag(termios, "oflag", (oflag & ~group.mask) | group.values[name]);
- return true;
- }
- return false;
-}
-
-function sttyApplyRaw(termios, enabled) {
- if (enabled) {
- for (const name of ["ignbrk", "brkint", "parmrk", "istrip", "inlcr", "igncr", "icrnl", "ixon"]) sttySetFlag(termios, "iflag", name, false);
- sttySetFlag(termios, "oflag", "opost", false);
- for (const name of ["echo", "echonl", "icanon", "isig"]) sttySetFlag(termios, "lflag", name, false);
- sttySetFlag(termios, "cflag", "cs8", true);
- termios.view.setUint8(TERMIOS_OFFSETS.cc + STTY_CC.min, 1);
- termios.view.setUint8(TERMIOS_OFFSETS.cc + STTY_CC.time, 0);
- return;
- }
- for (const name of ["brkint", "icrnl", "ixon"]) sttySetFlag(termios, "iflag", name, true);
- sttySetFlag(termios, "oflag", "opost", true);
- for (const name of ["isig", "icanon", "iexten"]) sttySetFlag(termios, "lflag", name, true);
-}
-
-function sttyApplyCooked(termios) {
- for (const name of ["brkint", "ignpar", "istrip", "icrnl", "ixon"]) sttySetFlag(termios, "iflag", name, true);
- sttySetFlag(termios, "oflag", "opost", true);
- for (const name of ["isig", "icanon"]) sttySetFlag(termios, "lflag", name, true);
-}
-
-function sttyApplyCbreak(termios, enabled) {
- if (enabled) {
- sttySetFlag(termios, "lflag", "icanon", false);
- termios.view.setUint8(TERMIOS_OFFSETS.cc + STTY_CC.min, 1);
- termios.view.setUint8(TERMIOS_OFFSETS.cc + STTY_CC.time, 0);
- } else {
- sttySetFlag(termios, "lflag", "icanon", true);
- }
-}
-
-function sttyApplyPass8(termios, enabled) {
- sttySetFlag(termios, "iflag", "istrip", !enabled);
-}
-
-function sttyApplyLitout(termios, enabled) {
- sttyApplyPass8(termios, enabled);
- sttySetFlag(termios, "oflag", "opost", !enabled);
-}
-
-function sttyApplyNl(termios, enabled) {
- sttySetFlag(termios, "iflag", "icrnl", !enabled);
- sttySetFlag(termios, "oflag", "onlcr", !enabled);
-}
-
-function sttyApplySane(termios) {
- for (const name of ["ignbrk", "parmrk", "inpck", "inlcr", "igncr", "ixoff", "iuclc", "ixany", "iutf8"]) sttySetFlag(termios, "iflag", name, false);
- for (const name of ["brkint", "ignpar", "istrip", "icrnl", "ixon", "imaxbel"]) sttySetFlag(termios, "iflag", name, true);
- for (const name of ["olcuc", "ocrnl", "onocr", "onlret", "ofill", "ofdel"]) sttySetFlag(termios, "oflag", name, false);
- for (const name of ["opost", "onlcr"]) sttySetFlag(termios, "oflag", name, true);
- for (const name of ["parenb", "cstopb", "hupcl", "clocal", "crtscts"]) sttySetFlag(termios, "cflag", name, false);
- sttySetFlag(termios, "cflag", "cs8", true);
- sttySetFlag(termios, "cflag", "cread", true);
- for (const name of ["echonl", "noflsh", "xcase", "tostop", "echoprt", "flusho", "extproc"]) sttySetFlag(termios, "lflag", name, false);
- for (const name of ["isig", "icanon", "iexten", "echo", "echoe", "echok", "echoctl", "echoke"]) sttySetFlag(termios, "lflag", name, true);
- termios.view.setUint8(TERMIOS_OFFSETS.cc + STTY_CC.min, 1);
- termios.view.setUint8(TERMIOS_OFFSETS.cc + STTY_CC.time, 0);
-}
-
-function sttyApplyValueSetting(termios, windowSize, setting, value) {
- if (setting === "ispeed" || setting === "ospeed") {
- sttySetSpeed(termios, parseSttySpeed(value, setting), setting === "ispeed" ? "input" : "output", value);
- return;
- }
- if ((setting === "rows" || setting === "cols" || setting === "columns") && windowSize) {
- if (setting === "rows") windowSize.rows = parseSttyInteger(value, 0xffffn);
- else windowSize.columns = parseSttyInteger(value, 0xffffn);
- return;
- }
- if (setting === "line") {
- termios.view.setUint8(TERMIOS_OFFSETS.line, parseSttyInteger(value, 0xffn));
- return;
- }
- if (setting === "min" || setting === "time") {
- termios.view.setUint8(TERMIOS_OFFSETS.cc + STTY_CC[setting], parseSttyInteger(value, 0xffn));
- } else if (STTY_CONTROL_SETTINGS.has(setting)) {
- termios.view.setUint8(TERMIOS_OFFSETS.cc + STTY_CC[setting], sttyControlValue(value));
- }
-}
-
-function parseSttySpeed(value, setting) {
- const text = String(value);
- if (text === "exta") return 19200;
- if (text === "extb") return 38400;
- const match = text.match(/^\s*\+?(\d+)(?:\.(\d*))?$/);
- if (!match) {
- throw new UsageError(`invalid ${setting} ${localeQuotedEscapedDiagnostic(value)}`, true);
- }
- let speed = BigInt(match[1]);
- const fraction = match[2];
- if (fraction) {
- const first = Number(fraction[0]);
- if (first > 5 || first === 5 && (/[1-9]/.test(fraction.slice(1)) || (speed & 1n) === 1n)) speed++;
- }
- if (speed > 0xffffffffn) {
- throw new UsageError(`invalid ${setting} ${localeQuotedEscapedDiagnostic(value)}`, true);
- }
- return Number(speed);
-}
-
-function sttyBareSpeed(value) {
- try {
- return parseSttySpeed(value, "speed");
- } catch {
- return null;
- }
-}
-
-function parseSttyInteger(value, maximum) {
- const text = String(value);
- const unsigned = text.startsWith("+") ? text.slice(1) : text;
- let parsed;
- if (/^0[xX][0-9a-fA-F]+$/.test(unsigned)) parsed = BigInt(unsigned);
- else if (/^0[0-7]*$/.test(unsigned)) parsed = BigInt(`0o${unsigned.slice(1) || "0"}`);
- else if (/^(?:0|[1-9]\d*)$/.test(unsigned)) parsed = BigInt(unsigned);
- else throw new UsageError(`invalid integer argument: ${localeQuotedEscapedDiagnostic(value)}`);
- if (parsed > maximum) throw new UsageError(`invalid integer argument: ${localeQuotedEscapedDiagnostic(value)}`);
- return Number(parsed);
-}
-
-function sttyControlValue(value) {
- if (value === "") return 0;
- if (value === "undef" || value === "^-") return 0;
- if (value.length === 1) return value.charCodeAt(0) & 0xff;
- if (value.startsWith("^") && value.length >= 2) return value[1] === "?" ? 0x7f : value.charCodeAt(1) & 0x1f;
- return parseSttyInteger(value, 0xffn);
-}
-
-async function ttyCmd(args) {
- args = normalizeTtyLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { s: false }, long: { silent: false, quiet: false, help: false, version: false } });
- if (operands.length) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}`, true);
- const isTty = Boolean(process.stdin.isTTY);
- if (!(opts.s || opts.silent || opts.quiet)) {
- try {
- stdout(isTty ? "/dev/tty\n" : "not a tty\n");
- } catch (error) {
- return fail("tty", error.message || String(error), 3);
- }
- }
- return isTty ? 0 : 1;
-}
-
-function normalizeTtyLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeTtyLongOption(arg));
- }
- return out;
-}
-
-function normalizeTtyLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = TTY_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-async function unameCmd(args) {
- args = normalizeUnameLongOptions(args);
- const { opts, operands } = parseOptions(args, {
- short: { a: false, s: false, n: false, r: false, v: false, m: false, p: false, i: false, o: false },
- long: { all: false, "kernel-name": false, nodename: false, "kernel-release": false, "kernel-version": false, machine: false, processor: false, "hardware-platform": false, "operating-system": false, help: false, version: false },
- });
- if (operands.length) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[0])}`, true);
- const all = opts.a || opts.all;
- const fields = [];
- const selected = all || opts.s || opts["kernel-name"] || opts.n || opts.nodename || opts.r || opts["kernel-release"] || opts.v || opts["kernel-version"] || opts.m || opts.machine || opts.p || opts.processor || opts.i || opts["hardware-platform"] || opts.o || opts["operating-system"];
- if (!selected || all || opts.s || opts["kernel-name"]) fields.push(osType());
- if (all || opts.n || opts.nodename) fields.push(osHostname());
- if (all || opts.r || opts["kernel-release"]) fields.push(osRelease());
- if (all || opts.v || opts["kernel-version"]) fields.push(osVersion());
- if (all || opts.m || opts.machine) fields.push(machineName());
- if (all || opts.p || opts.processor) fields.push(unameProcessorName());
- if (all || opts.i || opts["hardware-platform"]) fields.push(unameHardwarePlatform());
- if (all || opts.o || opts["operating-system"]) fields.push(process.platform === "linux" ? "GNU/Linux" : process.platform);
- stdout(`${fields.join(" ")}\n`);
- return 0;
-}
-
-function normalizeUnameLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeUnameLongOption(arg));
- }
- return out;
-}
-
-function normalizeUnameLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = UNAME_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length === 0) return arg;
- if (matches.length > 1) {
- throw new UsageError(`option '--${eq === -1 ? name : body}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-async function hostnameCmd(args) {
- args = normalizeHostnameLongOptions(args);
- const meta = scanMetaOptionBeforeEnd(args);
- if (meta === "--help") {
- showHostnameHelp();
- return 0;
- }
- if (meta === "--version") {
- stdout(`${VERSION}\n`);
- return 0;
- }
- for (const arg of args) {
- if (arg === "--") break;
- if (arg.startsWith("--help=")) throw new UsageError("option '--help' doesn't allow an argument", true);
- if (arg.startsWith("--version=")) throw new UsageError("option '--version' doesn't allow an argument", true);
- }
- const { opts, operands } = parseOptions(args, { short: { s: false, a: false, d: false, f: false, i: false, y: false, F: "value" }, long: { short: false, alias: false, domain: false, fqdn: false, long: false, "ip-address": false, yp: false, nis: false, file: "value", help: false, version: false } });
- const displayMode = hostnameDisplayMode(args);
- if (displayMode === "short") return hostnamePrintShort();
- if (displayMode === "yp" && operands.length === 0) {
- stdout("(none)\n");
- return 0;
- }
- if (displayMode === "lookup") throw new UsageError("Host name lookup failure");
- if (Object.hasOwn(opts, "F") || Object.hasOwn(opts, "file")) {
- const file = Object.hasOwn(opts, "F") ? opts.F : opts.file;
- let name;
- try {
- name = decodeSurrogateEscapedBytes(await readAll(file)).split(/\r?\n/, 1)[0];
- } catch {
- throw new UsageError(`can't open \`${file}'`);
- }
- return hostnameSetName(name);
- }
- if (operands.length >= 1) {
- return hostnameSetName(operands[0]);
- } else {
- stdout(`${osHostname()}\n`);
- }
- return 0;
-}
-
-function normalizeHostnameLongOptions(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(normalizeLongOptionByPrefix(arg, HOSTNAME_LONG_OPTIONS));
- }
- return out;
-}
-
-function hostnamePrintShort() {
- stdout(`${osHostname().split(".")[0]}\n`);
- return 0;
-}
-
-function hostnameSetName(name) {
- if (libc.symbols.sethostname(cstr(name), Buffer.byteLength(name)) !== 0) {
- throw new UsageError("you don't have permission to set the host name");
- }
- return 0;
-}
-
-function hostnameDisplayMode(args) {
- let mode = null;
- let end = false;
- const longModes = new Map([
- ["short", "short"],
- ["alias", "lookup"],
- ["domain", "lookup"],
- ["fqdn", "lookup"],
- ["long", "lookup"],
- ["ip-address", "lookup"],
- ["yp", "yp"],
- ["nis", "yp"],
- ]);
- for (const arg of args) {
- if (end) continue;
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg.startsWith("--")) {
- const name = arg.slice(2).split("=", 1)[0];
- if (longModes.has(name)) mode = longModes.get(name);
- continue;
- }
- if (arg.startsWith("-") && arg !== "-") {
- for (const ch of arg.slice(1)) {
- if (ch === "s") mode = "short";
- else if (ch === "a" || ch === "d" || ch === "f" || ch === "i") mode = "lookup";
- else if (ch === "y") mode = "yp";
- else if (ch === "F") break;
- }
- }
- }
- return mode;
-}
-
-function showHostnameHelp() {
- stdout("Usage: hostname [NAME]\n");
- stdout(" or: hostname OPTION\n");
- stdout("Print or set the hostname of the current system.\n\n");
- stdout(" -s, --short print the short host name\n");
- stdout(" -a, --alias print alias names\n");
- stdout(" -d, --domain print DNS domain name\n");
- stdout(" -f, --fqdn, --long\n");
- stdout(" print fully qualified domain name\n");
- stdout(" -i, --ip-address\n");
- stdout(" print addresses for the host name\n");
- stdout(" -y, --yp, --nis\n");
- stdout(" print NIS/YP domain name\n");
- stdout(" -F, --file=FILE\n");
- stdout(" read host name from FILE\n");
- stdout(" --help display this help and exit\n");
- stdout(" --version output version information and exit\n");
-}
-
-function unameProcessorName() {
- if (process.platform === "linux") {
- const value = procCpuInfoField("model name") ?? procCpuInfoField("Processor");
- if (value) return value;
- }
- return process.arch === "x64" ? "x86_64" : machineName();
-}
-
-function unameHardwarePlatform() {
- if (process.platform === "linux") {
- const value = procCpuInfoField("vendor_id") ?? procCpuInfoField("Hardware");
- if (value) return value;
- }
- return machineName();
-}
-
-function procCpuInfoField(field) {
- try {
- const text = readFileSync("/proc/cpuinfo", "utf8");
- const prefix = `${field.toLowerCase()}\t`;
- for (const line of text.split("\n")) {
- const [name, value] = line.split(":", 2);
- if (name?.trim().toLowerCase() === field.toLowerCase() || name?.toLowerCase().startsWith(prefix)) {
- const trimmed = value?.trim();
- if (trimmed) return trimmed;
- }
- }
- } catch {}
- return null;
-}
-
-async function mkfifoCmd(args) {
- args = normalizeSpecialFileLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { m: "value", Z: false }, long: { mode: "value", context: "optional-value", help: false, version: false } });
- const securityContext = selinuxCreationOptions("mkfifo", opts);
- if (!operands.length) throw new UsageError("missing operand", true);
- const explicitMode = opts.m ?? opts.mode;
- const mode = explicitMode ? parseSpecialFileCreationMode(explicitMode) : 0o666;
- await withSelinuxCreationContext("mkfifo", securityContext, async (created) => {
- for (const path of operands) {
- await ensureSpecialFileCreatable("mkfifo", path, "fifo");
- if (libc.symbols.mkfifo(cstr(path), mode) !== 0) throw new UsageError(`cannot create fifo ${specialFileQuotedName(path)}: Operation not permitted`);
- if (explicitMode) await setFileMode(path, mode);
- await created(path);
- }
- });
- return 0;
-}
-
-async function mknodCmd(args) {
- args = normalizeSpecialFileLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { m: "value", Z: false }, long: { mode: "value", context: "optional-value", help: false, version: false } });
- const securityContext = selinuxCreationOptions("mknod", opts);
- const explicitMode = opts.m ?? opts.mode;
- const perm = explicitMode ? parseSpecialFileCreationMode(explicitMode) : 0o666;
- if (!operands.length) throw new UsageError("missing operand", true);
- if (operands.length === 1) throw new UsageError(`missing operand after '${operands[0]}'`, true);
- const [path, type, major, minor] = operands;
- if (type === "p") {
- if (operands.length > 2) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[2])}`, true);
- await withSelinuxCreationContext("mknod", securityContext, async (created) => {
- await ensureSpecialFileCreatable("mknod", path, "fifo");
- if (libc.symbols.mkfifo(cstr(path), perm) !== 0) throw new UsageError(`cannot create fifo ${specialFileQuotedName(path)}: Operation not permitted`);
- if (explicitMode) await setFileMode(path, perm);
- await created(path);
- });
- return 0;
- }
- if (operands.length > 4) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[4])}`, true);
- if (major == null) throw new UsageError(`missing operand after '${type}'\nSpecial files require major and minor device numbers.`, true);
- if (minor == null) throw new UsageError(`missing operand after '${major}'`, true);
- if (type === "b" || type === "c" || type === "u") {
- const majorNumber = parseMknodDeviceNumber(major, "major");
- const minorNumber = parseMknodDeviceNumber(minor, "minor");
- await withSelinuxCreationContext("mknod", securityContext, async (created) => {
- await ensureSpecialFileCreatable("mknod", path, "special file");
- const modeType = type === "b" ? 0o060000 : 0o020000;
- if (libc.symbols.mknod(cstr(path), modeType | perm, makedev(majorNumber, minorNumber)) !== 0) throw new UsageError(`${mknodDiagnosticName(path)}: Operation not permitted`);
- await created(path);
- });
- return 0;
- }
- throw new UsageError(`invalid device type ${localeQuotedEscapedDiagnostic(type)}`, true);
-}
-
-function parseMknodDeviceNumber(value, kind) {
- const text = String(value);
- let digits;
- let base;
- if (/^0[xX][0-9A-Fa-f]+$/.test(text)) {
- digits = text.slice(2);
- base = 16n;
- } else if (/^0[0-7]*$/.test(text)) {
- digits = text;
- base = 8n;
- } else if (/^[1-9][0-9]*$/.test(text)) {
- digits = text;
- base = 10n;
- } else {
- throw new UsageError(`invalid ${kind} device number ${localeQuotedEscapedDiagnostic(value)}`);
- }
- let number = 0n;
- for (const ch of digits) {
- number = number * base + BigInt(Number.parseInt(ch, Number(base)));
- if (number > 0xffffffffn) throw new UsageError(`invalid ${kind} device number ${localeQuotedEscapedDiagnostic(value)}`);
- }
- return number;
-}
-
-async function ensureSpecialFileCreatable(program, path, kind) {
- try {
- await lstat(path);
- throw new UsageError(specialFileCreationMessage(program, path, kind, "File exists"));
- } catch (error) {
- if (error instanceof UsageError) throw error;
- if (error?.code === "ENOTDIR") throw new UsageError(specialFileCreationMessage(program, path, kind, "Not a directory"));
- if (error?.code !== "ENOENT") throw new UsageError(specialFileCreationMessage(program, path, kind, systemErrorMessage(error)));
- }
- const dir = pathDirname(path);
- if (dir && dir !== ".") {
- try {
- const parent = await stat(dir);
- if (!parent.isDirectory()) throw new UsageError(specialFileCreationMessage(program, path, kind, "Not a directory"));
- } catch (error) {
- if (error instanceof UsageError) throw error;
- throw new UsageError(specialFileCreationMessage(program, path, kind, systemErrorMessage(error)));
- }
- }
-}
-
-function specialFileCreationMessage(program, path, kind, message) {
- if (program === "mknod") return `${mknodDiagnosticName(path)}: ${message}`;
- return `cannot create ${kind} ${specialFileQuotedName(path)}: ${message}`;
-}
-
-function specialFileQuotedName(path) {
- return shellEscapeLsName(pathDisplayName(path), true);
-}
-
-function mknodDiagnosticName(path) {
- return shellEscapeLsName(pathDisplayName(path));
-}
-
-function warnIgnoredContext(program, opts) {
- if (typeof opts.context === "string") stderr(`${program}: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n`);
-}
-
-function makedev(major, minor) {
- return Number(((major & 0xfffn) << 8n) | (minor & 0xffn) | ((minor & ~0xffn) << 12n) | ((major & ~0xfffn) << 32n));
-}
-
-function cstr(value) {
- return Buffer.from(`${value}\0`);
-}
-
-function cstrPath(value) {
- const bytes = isBytePath(value) ? Buffer.from(value) : Buffer.from(String(value));
- return Buffer.concat([bytes, Buffer.from([0])]);
-}
-
-function changeDirectory(path) {
- if (libc.symbols.chdir(cstrPath(path)) !== 0) {
- const error = new Error(`chdir '${pathDisplayName(path)}' failed`);
- error.code = "EACCES";
- throw error;
- }
-}
-
-async function setFileMode(path, mode) {
- if (isBytePath(path)) {
- await fsChmod(path, mode);
- return;
- }
- if (libc.symbols.chmod(cstr(path), mode) !== 0) {
- const errno = libcErrno();
- const error = new Error(`chmod '${path}' failed (errno ${errno})`);
- error.code = ({ 1: "EPERM", 2: "ENOENT", 13: "EACCES", 20: "ENOTDIR", 30: "EROFS" })[errno] ?? "EIO";
- throw error;
- }
-}
-
-function hashCommand(algorithm) {
- return async (args) => {
- if (algorithm !== "blake2b512") rejectHashLengthOption(args);
- args = normalizeHashLongOptions(args);
- if (args.length === 1 && args[0] === "--version") {
- stdout(`${VERSION}\n`);
- return 0;
- }
- const { opts, operands } = parseOptions(args, { short: { c: false, b: false, t: false, l: "value", w: false, z: false }, long: { check: false, binary: false, text: false, tag: false, length: "value", status: false, quiet: false, warn: false, strict: false, "ignore-missing": false, zero: false, help: false, version: false } });
- if (opts.w) opts.warn = true;
- opts.warnAfterStatus = optionAppearsAfter(args, "--warn", "--status") || optionAppearsAfter(args, "-w", "--status");
- const digestBytes = hashDigestBytes(algorithm, opts);
- validateChecksumCheckOnlyOptions(opts);
- if (opts.c || opts.check) {
- if (opts.tag) throw new UsageError("the --tag option is meaningless when verifying checksums");
- return checkHashes(algorithm, operands.length ? operands : ["-"], { ...opts, program: hashProgramName(algorithm) });
- }
- if (opts.tag && (opts.t || opts.text)) throw new UsageError("--tag does not support --text mode");
- const files = operands.length ? operands : ["-"];
- let failed = false;
- for (const file of files) {
- let digest;
- try {
- digest = (digestBytes ? await blake2bDigestFile(file, digestBytes) : await fileDigest(file, algorithm)).toString("hex");
- } catch (error) {
- const program = hashProgramName(algorithm);
- stderr(file === "-" ? `${program}: ${nodeErrorMessage(error)}\n` : `${program}: ${checksumDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- continue;
- }
- const sep = opts.z || opts.zero ? "\0" : "\n";
- const displayFile = file === "-" ? "-" : file;
- const renderedFile = opts.z || opts.zero ? displayFile : escapeChecksumFilename(displayFile);
- const escapePrefix = !(opts.z || opts.zero) && shouldEscapeChecksumFilename(displayFile) ? "\\" : "";
- if (opts.tag) stdout(`${escapePrefix}${hashTagName(algorithm, opts)} (${renderedFile}) = ${digest}${sep}`);
- else stdout(`${escapePrefix}${digest}${opts.b || opts.binary ? " *" : " "}${renderedFile}${sep}`);
- }
- return failed ? 1 : 0;
- };
-}
-
-function rejectHashLengthOption(args) {
- for (const arg of args) {
- if (arg === "--") return;
- if (arg.startsWith("--")) {
- const name = arg.slice(2).split("=", 1)[0];
- if ("length".startsWith(name)) throw new UsageError(`unrecognized option '${arg}'`, true);
- continue;
- }
- if (!arg.startsWith("-") || arg === "-") continue;
- for (const ch of arg.slice(1)) {
- if (ch === "l") throw new UsageError("invalid option -- 'l'", true);
- if (ch === "b" || ch === "c" || ch === "t" || ch === "w" || ch === "z") continue;
- break;
- }
- }
-}
-
-function validateChecksumCheckOnlyOptions(opts) {
- if (opts.c || opts.check) return;
- for (const option of ["ignore-missing", "status", "quiet", "strict", "warn"]) {
- if (opts[option]) throw new UsageError(`the --${option} option is meaningful only when verifying checksums`, true);
- }
-}
-
-function hashDigestBytes(algorithm, opts = {}) {
- if (algorithm !== "blake2b512") return null;
- const length = opts.l ?? opts.length ?? "512";
- validateBlake2bLength("b2sum", length);
- return Number(length) === 0 ? 64 : Number(length) / 8;
-}
-
-function hashProgramName(algorithm) {
- if (algorithm === "md5") return "md5sum";
- if (algorithm === "blake2b512") return "b2sum";
- return `${algorithm}sum`;
-}
-
-function normalizeHashLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, HASH_LONG_OPTIONS);
-}
-
-function normalizeHashLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, HASH_LONG_OPTIONS);
-}
-
-function hashTagName(algorithm, opts = {}) {
- if (algorithm === "md5") return "MD5";
- if (algorithm === "blake2b512") {
- const length = opts.l ?? opts.length;
- return length != null && !["0", "512"].includes(String(length)) ? `BLAKE2b-${length}` : "BLAKE2b";
- }
- return algorithm.toUpperCase();
-}
-
-async function checkHashes(algorithm, files, opts = {}) {
- if (files.length === 1 && files[0] === "-" && !fstatSync(0).isFile()) {
- return checkHashesStream(algorithm, opts);
- }
- let checksumFailures = 0;
- let readFailures = 0;
- let malformed = 0;
- let properLines = 0;
- let verified = 0;
- let emptyLists = 0;
- const checksumName = algorithm.toUpperCase();
- let lastChecksumName = checksumName;
- let checksumLineStyle = null;
- for (const listFile of files) {
- let text;
- try {
- text = decodeSurrogateEscapedBytes(await readAll(listFile));
- } catch (error) {
- readFailures++;
- stderr(`${diagnosticPrefix(opts)}${listFile}: ${fileReadErrorMessage(error)}\n`);
- continue;
- }
- let fileProperLines = 0;
- let lineNo = 0;
- for (const raw of text.split(/\n/)) {
- lineNo++;
- const line = raw.replace(/\r$/, "").replace(/^[ \t]*\\/, "");
- if (!line || line.startsWith("#") || line.startsWith("-----BEGIN ") || line.startsWith("-----END ") || /^Hash: /.test(line)) continue;
- const parsedLine = parseChecksumLine(line, algorithm, checksumLineStyle);
- if (parsedLine?.skip) continue;
- if (!parsedLine) {
- malformed++;
- if (opts.warn && (!opts.status || opts.warnAfterStatus)) stderr(`${diagnosticPrefix(opts)}${listFile}: ${lineNo}: improperly formatted ${lastChecksumName} checksum line\n`);
- continue;
- }
- const parsed = parseExpectedChecksum(parsedLine.token, parsedLine.algorithm, { ...opts, ...(parsedLine.opts ?? {}) });
- if (!parsed) {
- malformed++;
- if (opts.warn && (!opts.status || opts.warnAfterStatus)) stderr(`${diagnosticPrefix(opts)}${listFile}: ${lineNo}: improperly formatted ${checksumDisplayName(parsedLine.algorithm, parsedLine.opts)} checksum line\n`);
- continue;
- }
- if (parsedLine.style && checksumLineStyle == null) checksumLineStyle = parsedLine.style;
- lastChecksumName = checksumDisplayName(parsedLine.algorithm, parsedLine.opts);
- const { expected, hashAlgorithm, blake2bBytes } = parsed;
- const file = checksumPathFromFilename(unescapeChecksumFilename(parsedLine.file));
- properLines++;
- fileProperLines++;
- try {
- const actualDigest = blake2bBytes ? await blake2bDigestFile(file, blake2bBytes) : await fileDigest(file, hashAlgorithm);
- const actual = actualDigest.slice(0, expected.length / 2).toString("hex");
- const ok = actual === expected;
- verified++;
- if (!ok) checksumFailures++;
- if (!(opts.status || (opts.quiet && ok))) stdout(`${checksumDisplayFile(file)}: ${ok ? "OK" : "FAILED"}\n`);
- } catch (error) {
- if (opts["ignore-missing"]) continue;
- readFailures++;
- if (!opts.status) stderr(`${diagnosticPrefix(opts)}${pathDisplayName(file)}: ${fileReadErrorMessage(error)}\n`);
- if (!opts.status) stdout(`${checksumDisplayFile(file)}: FAILED open or read\n`);
- }
- }
- if (fileProperLines === 0) {
- emptyLists++;
- if (!opts.status) stderr(`${diagnosticPrefix(opts)}${listFile}: no properly formatted checksum lines found\n`);
- }
- }
- if (properLines === 0) {
- return 1;
- }
- const showStatusWarnings = !opts.status || opts.warnAfterStatus;
- if (malformed && showStatusWarnings && !opts.quiet) stderr(`${diagnosticPrefix(opts)}WARNING: ${malformed} line${malformed === 1 ? " is" : "s are"} improperly formatted\n`);
- if (readFailures && showStatusWarnings) stderr(`${diagnosticPrefix(opts)}WARNING: ${readFailures} listed file${readFailures === 1 ? "" : "s"} could not be read\n`);
- if (checksumFailures && showStatusWarnings) stderr(`${diagnosticPrefix(opts)}WARNING: ${checksumFailures} computed checksum${checksumFailures === 1 ? "" : "s"} did NOT match\n`);
- if (verified === 0 && readFailures === 0) {
- if (showStatusWarnings) stderr(`${diagnosticPrefix(opts)}${files[0]}: no file was verified\n`);
- return 1;
- }
- return checksumFailures || readFailures || emptyLists || (opts.strict && malformed) ? 1 : 0;
-}
-
-async function checkHashesStream(requestedAlgorithm, opts = {}) {
- const reader = createFdRecordReader(0, 10);
- let checksumFailures = 0;
- let readFailures = 0;
- let malformed = 0;
- let properLines = 0;
- let verified = 0;
- let lineNo = 0;
- let checksumLineStyle = null;
- let lastChecksumName = requestedAlgorithm.toUpperCase();
- while (true) {
- const bytes = reader.next();
- if (bytes == null) break;
- lineNo++;
- const raw = decodeSurrogateEscapedBytes(bytes);
- const line = raw.replace(/\r$/, "").replace(/^[ \t]*\\/, "");
- if (!line || line.startsWith("#") || line.startsWith("-----BEGIN ") || line.startsWith("-----END ") || /^Hash: /.test(line)) continue;
- const parsedLine = parseChecksumLine(line, requestedAlgorithm, checksumLineStyle);
- if (parsedLine?.skip) continue;
- if (!parsedLine) {
- malformed++;
- if (opts.warn && (!opts.status || opts.warnAfterStatus)) stderr(`${diagnosticPrefix(opts)}-: ${lineNo}: improperly formatted ${lastChecksumName} checksum line\n`);
- continue;
- }
- const parsed = parseExpectedChecksum(parsedLine.token, parsedLine.algorithm, { ...opts, ...(parsedLine.opts ?? {}) });
- if (!parsed) {
- malformed++;
- if (opts.warn && (!opts.status || opts.warnAfterStatus)) stderr(`${diagnosticPrefix(opts)}-: ${lineNo}: improperly formatted ${checksumDisplayName(parsedLine.algorithm, parsedLine.opts)} checksum line\n`);
- continue;
- }
- if (parsedLine.style && checksumLineStyle == null) checksumLineStyle = parsedLine.style;
- lastChecksumName = checksumDisplayName(parsedLine.algorithm, parsedLine.opts);
- properLines++;
- const file = checksumPathFromFilename(unescapeChecksumFilename(parsedLine.file));
- const { expected, hashAlgorithm, blake2bBytes } = parsed;
- try {
- const digest = blake2bBytes ? await blake2bDigestFile(file, blake2bBytes) : await fileDigest(file, hashAlgorithm);
- const actual = digest.slice(0, expected.length / 2).toString("hex");
- const ok = actual === expected;
- verified++;
- if (!ok) checksumFailures++;
- if (!(opts.status || (opts.quiet && ok))) stdout(`${checksumDisplayFile(file)}: ${ok ? "OK" : "FAILED"}\n`);
- } catch (error) {
- if (isWriteError(error)) throw error;
- if (opts["ignore-missing"]) continue;
- readFailures++;
- if (!opts.status) stderr(`${diagnosticPrefix(opts)}${pathDisplayName(file)}: ${fileReadErrorMessage(error)}\n`);
- if (!opts.status) stdout(`${checksumDisplayFile(file)}: FAILED open or read\n`);
- }
- }
- if (properLines === 0) {
- if (!opts.status) stderr(`${diagnosticPrefix(opts)}-: no properly formatted checksum lines found\n`);
- return 1;
- }
- const showStatusWarnings = !opts.status || opts.warnAfterStatus;
- if (malformed && showStatusWarnings && !opts.quiet) stderr(`${diagnosticPrefix(opts)}WARNING: ${malformed} line${malformed === 1 ? " is" : "s are"} improperly formatted\n`);
- if (readFailures && showStatusWarnings) stderr(`${diagnosticPrefix(opts)}WARNING: ${readFailures} listed file${readFailures === 1 ? "" : "s"} could not be read\n`);
- if (checksumFailures && showStatusWarnings) stderr(`${diagnosticPrefix(opts)}WARNING: ${checksumFailures} computed checksum${checksumFailures === 1 ? "" : "s"} did NOT match\n`);
- if (verified === 0 && readFailures === 0) {
- if (showStatusWarnings) stderr(`${diagnosticPrefix(opts)}-: no file was verified\n`);
- return 1;
- }
- return checksumFailures || readFailures || (opts.strict && malformed) ? 1 : 0;
-}
-
-function parseChecksumLine(line, requestedAlgorithm, style = null) {
- const tag = line.match(/^([A-Za-z0-9-]+) \((.*)\) = (\S+)$/) ?? line.match(/^([A-Za-z0-9-]+)\((.*)\)= (\S+)$/);
- if (tag) {
- const algorithm = checksumAlgorithmFromTag(tag[1]);
- if (!algorithm) return null;
- if (requestedAlgorithm !== "auto" && !checksumAlgorithmMatches(requestedAlgorithm, algorithm)) return { skip: true };
- return { algorithm: algorithm.name, token: tag[3], file: tag[2], opts: algorithm.opts };
- }
- const token = line.match(/^(\S+)/)?.[1];
- if (!token || line.length <= token.length || line[token.length] !== " ") return null;
- const rest = line.slice(token.length);
- const algorithm = requestedAlgorithm === "auto" ? "auto" : requestedAlgorithm;
- if (style === "bsd-alternate") return { algorithm, token, file: rest.slice(1), style: "bsd-alternate" };
- if (rest.startsWith(" ")) return { algorithm, token, file: rest.slice(2), style: "gnu" };
- if (rest.startsWith(" *")) return { algorithm, token, file: rest.slice(2), style: "gnu" };
- if (style == null && requestedAlgorithm !== "auto") return { algorithm, token, file: rest.slice(1), style: "bsd-alternate" };
- return null;
-}
-
-function shouldEscapeChecksumFilename(file) {
- return String(file).includes("\\") || String(file).includes("\n") || String(file).includes("\r");
-}
-
-function escapeChecksumFilename(file) {
- return String(file).replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
-}
-
-function unescapeChecksumFilename(file) {
- return String(file).replace(/\\([\\nr])/g, (_, ch) => ch === "n" ? "\n" : ch === "r" ? "\r" : "\\");
-}
-
-function checksumPathFromFilename(file) {
- return hasSurrogateEscapedBytes(file) ? Buffer.from(encodeSurrogateEscapedString(file)) : file;
-}
-
-function checksumDisplayFile(file) {
- const text = pathDisplayName(file);
- return /[\\\n\r\t]/.test(text) || hasSurrogateEscapedBytes(text) ? checksumShellQuote(text) : text;
-}
-
-function checksumShellQuote(file) {
- let out = "";
- let plain = "";
- const flush = () => {
- if (!plain) return;
- out += `'${plain.replace(/'/g, "'\\''")}'`;
- plain = "";
- };
- for (const ch of String(file)) {
- const code = ch.charCodeAt(0);
- if (ch === "\n" || ch === "\t" || ch === "\r") {
- flush();
- out += `$'\\${ch === "\n" ? "n" : ch === "\t" ? "t" : "r"}'`;
- } else if (code >= 0xdc80 && code <= 0xdcff) {
- flush();
- out += `$'\\${(code - 0xdc00).toString(8).padStart(3, "0")}'`;
- } else {
- plain += ch;
- }
- }
- flush();
- return out;
-}
-
-function checksumAlgorithmMatches(requested, tagged) {
- if (requested === tagged.name) return true;
- if (requested === "blake2b512" && tagged.name === "blake2b") return true;
- if (requested === "sha2" && /^sha(224|256|384|512)$/.test(tagged.name)) return true;
- return false;
-}
-
-function checksumAlgorithmFromTag(tag) {
- const upper = tag.toUpperCase();
- if (upper === "MD5") return { name: "md5" };
- if (upper === "SHA1") return { name: "sha1" };
- const sha = upper.match(/^SHA(224|256|384|512)$/);
- if (sha) return { name: `sha${sha[1]}` };
- const sha2 = upper.match(/^SHA2-(224|256|384|512)$/);
- if (sha2) return { name: "sha2", opts: { l: sha2[1] } };
- const sha3 = upper.match(/^SHA3-(224|256|384|512)$/);
- if (sha3) return { name: "sha3", opts: { l: sha3[1] } };
- const blake = tag.match(/^BLAKE2b(?:-(\d+))?$/);
- if (blake) return { name: "blake2b", opts: blake[1] ? { l: blake[1], tagged: true } : { tagged: true } };
- if (upper === "SM3") return { name: "sm3", opts: { tagged: true } };
- return null;
-}
-
-function diagnosticPrefix(opts = {}) {
- return opts.program ? `${opts.program}: ` : "";
-}
-
-function checksumDisplayName(algorithm, opts = {}) {
- if (algorithm === "blake2b") return "BLAKE2b";
- if (algorithm === "sha2") return `SHA2-${opts?.l ?? opts?.length ?? ""}`.replace(/-$/, "");
- if (algorithm === "sha3") return `SHA3-${opts?.l ?? opts?.length ?? ""}`.replace(/-$/, "");
- return String(algorithm).toUpperCase();
-}
-
-function invalidDigestLengthError(program, algorithm, length, message) {
- const quotedMessage = message.replaceAll(`'${algorithm}'`, localeQuotedDiagnostic(algorithm));
- const error = new UsageError(`invalid length: ${localeQuotedDiagnostic(length)}\n${program}: ${quotedMessage}`, false);
- return error;
-}
-
-function validateBlake2bLength(program, length) {
- const text = String(length);
- if (!/^\d+$/.test(text)) {
- if (/^-\d+$/.test(text)) throw new UsageError(`invalid length: ${localeQuotedEscapedDiagnostic(length)}: Value too large for defined data type`, false);
- throw new UsageError(`invalid length: ${localeQuotedEscapedDiagnostic(length)}`, false);
- }
- const n = Number(text);
- if (!Number.isSafeInteger(n) || n > 512) throw invalidDigestLengthError(program, "BLAKE2b", length, "maximum digest length for 'BLAKE2b' is 512 bits");
- if (n % 8 !== 0) throw invalidDigestLengthError(program, "BLAKE2b", length, "length is not a multiple of 8");
-}
-
-function parseExpectedChecksum(token, algorithm, opts = {}) {
- if (/^[0-9a-fA-F]+$/.test(token) && token.length % 2 === 0) {
- const digestBytes = token.length / 2;
- if (!validChecksumDigestLength(algorithm, digestBytes, opts)) return null;
- if (algorithm === "blake2b" || algorithm === "blake2b512") return { expected: token.toLowerCase(), hashAlgorithm: "blake2b512", blake2bBytes: digestBytes };
- return { expected: token.toLowerCase(), hashAlgorithm: cksumAlgorithmForDigest(algorithm, digestBytes, opts) };
- }
- if (!/^[A-Za-z0-9+/]+={0,2}$/.test(token) || token.length % 4 !== 0) return null;
- let digest;
- try {
- digest = Buffer.from(token, "base64");
- } catch {
- return null;
- }
- if (digest.length === 0) return null;
- try {
- if (!validChecksumDigestLength(algorithm, digest.length, opts)) return null;
- if (algorithm === "blake2b" || algorithm === "blake2b512") return { expected: digest.toString("hex"), hashAlgorithm: "blake2b512", blake2bBytes: digest.length };
- return { expected: digest.toString("hex"), hashAlgorithm: cksumAlgorithmForDigest(algorithm, digest.length, opts) };
- } catch {
- return null;
- }
-}
-
-function validChecksumDigestLength(algorithm, digestBytes, opts = {}) {
- const fixed = { md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, sm3: 32 };
- if (fixed[algorithm] != null) return digestBytes === fixed[algorithm];
- if (algorithm === "sha2" || algorithm === "sha3") return [28, 32, 48, 64].includes(digestBytes);
- if (algorithm === "blake2b" || algorithm === "blake2b512") {
- if (opts.tagged && opts.l == null && opts.length == null) return digestBytes === 64;
- return digestBytes >= 1 && digestBytes <= 64;
- }
- if (algorithm === "auto") return false;
- return true;
-}
-
-function fileReadErrorMessage(error) {
- return systemErrorMessage(error);
-}
-
-function parseCount(value, defaultValue, kind = "lines") {
- if (value == null) return defaultValue;
- const countText = String(value).replace(/^[+-]/, "");
- let n;
- try {
- n = parseByteCount(countText);
- } catch {
- throw new UsageError(`invalid number of ${kind}: ${localeQuotedEscapedDiagnostic(countText)}`);
- }
- if (!Number.isFinite(n) || n < 0) throw new UsageError(`invalid number of ${kind}: ${localeQuotedEscapedDiagnostic(countText)}`);
- return Math.trunc(n);
-}
-
-async function head(args) {
- args = normalizeHeadTailArgs(normalizeHeadLongOptions(args), "head");
- args = args.filter((arg) => arg !== "---presume-input-pipe");
- const headerMode = headTailHeaderMode(args);
- const { opts, operands } = parseOptions(args, { short: { n: "value", c: "value", q: false, v: false, z: false }, long: { lines: "value", bytes: "value", quiet: false, silent: false, verbose: false, "zero-terminated": false, help: false, version: false } });
- const files = operands.length ? operands : ["-"];
- const bytesMode = opts.c ?? opts.bytes;
- const count = parseCount(bytesMode ?? opts.n ?? opts.lines, 10, bytesMode != null ? "bytes" : "lines");
- const delimiter = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- let failed = false;
- let renderedAnyFile = false;
- try {
- for (let i = 0; i < files.length; i++) {
- const file = files[i];
- const raw = String(bytesMode ?? opts.n ?? opts.lines ?? "");
- const header = headTailShouldPrintHeader(headerMode, files.length) ? `${renderedAnyFile ? "\n" : ""}==> ${file} <==\n` : "";
- if (file === "-" && files.length === 1 && headerMode !== "verbose") {
- if (bytesMode != null) {
- headWrite(raw.startsWith("-") ? readHeadFdExceptLastBytes(0, count) : readHeadStdinBytes(count));
- } else {
- headWrite(raw.startsWith("-") ? readHeadFdExceptLastRecords(0, count, delimiter) : readHeadStdinRecords(count, delimiter));
- }
- continue;
- }
- if (raw.startsWith("-") && file !== "-" && !(await stat(file).catch(() => null))?.isDirectory()) {
- if (header) headWrite(header);
- let fd;
- try {
- fd = openSync(file, "r");
- if (bytesMode != null) readHeadFdExceptLastBytes(fd, count);
- else readHeadFdExceptLastRecords(fd, count, delimiter);
- renderedAnyFile = true;
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(`head: cannot open ${headTailDiagnosticName(file)} for reading: ${systemErrorMessage(error)}\n`);
- failed = true;
- } finally {
- if (fd != null) closeSync(fd);
- }
- continue;
- }
- if (bytesMode != null && !raw.startsWith("-") && file !== "-" && await isTailStreamingDevice(file)) {
- if (header) headWrite(header);
- try {
- await tailFirstBytes(file, count);
- renderedAnyFile = true;
- } catch (error) {
- stderr(`head: cannot open ${headTailDiagnosticName(file)} for reading: ${systemErrorMessage(error)}\n`);
- failed = true;
- }
- continue;
- }
- let data;
- try {
- data = await readAll(file);
- } catch (error) {
- if (error?.code === "EISDIR") {
- if (header) headWrite(header);
- renderedAnyFile = true;
- stderr(`head: error reading ${headTailDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- } else {
- stderr(file === "-" ? `head: ${nodeErrorMessage(error)}\n` : `head: cannot open ${headTailDiagnosticName(file)} for reading: ${systemErrorMessage(error)}\n`);
- }
- failed = true;
- continue;
- }
- if (header) headWrite(header);
- renderedAnyFile = true;
- if (bytesMode != null) {
- headWrite(raw.startsWith("-") ? data.slice(0, Math.max(0, data.length - count)) : data.slice(0, count));
- } else {
- const lines = splitDelimitedByteRecords(data, delimiter);
- headWrite(Buffer.concat(raw.startsWith("-") ? lines.slice(0, Math.max(0, lines.length - count)) : lines.slice(0, count)));
- }
- }
- } catch (error) {
- if (!isWriteError(error)) throw error;
- stderr(`head: error writing 'standard output': ${outputWriteErrorMessage(error)}\n`);
- return 1;
- }
- return failed ? 1 : 0;
-}
-
-function headWrite(data) {
- stdout(data);
-}
-
-function headTailDiagnosticName(file) {
- return shellEscapeLsName(pathDisplayName(file), true);
-}
-
-function normalizeHeadLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, HEAD_LONG_OPTIONS);
-}
-
-function normalizeHeadLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, HEAD_LONG_OPTIONS);
-}
-
-function readHeadStdinBytes(count) {
- if (count > 2 ** 32) return readRemainingStdinSync();
- const out = Buffer.alloc(count);
- let offset = 0;
- while (offset < count) {
- const n = readSync(0, out, offset, count - offset, null);
- if (n === 0) break;
- offset += n;
- }
- return out.subarray(0, offset);
-}
-
-function readHeadStdinRecords(count, delimiter) {
- if (count === 0) return "";
- const chunks = [];
- let seen = 0;
- const byte = Buffer.alloc(1);
- const delim = delimiter.charCodeAt(0);
- while (seen < count) {
- const n = readSync(0, byte, 0, 1, null);
- if (n === 0) break;
- chunks.push(byte[0]);
- if (byte[0] === delim) seen++;
- }
- return Buffer.from(chunks);
-}
-
-function readHeadFdExceptLastBytes(fd, count) {
- if (fstatSync(fd).isFile() && fdIsSeekable(fd)) {
- const data = readRemainingFdSync(fd);
- const keep = Math.max(0, data.length - count);
- headWrite(data.subarray(0, keep));
- rewindFd(fd, data.length - keep);
- return "";
- }
- const buffer = Buffer.alloc(8192);
- let tail = Buffer.alloc(0);
- while (true) {
- const n = readSync(fd, buffer, 0, buffer.length, null);
- if (n === 0) break;
- const chunk = Buffer.from(buffer.subarray(0, n));
- if (count === 0) {
- headWrite(chunk);
- continue;
- }
- const combined = Buffer.concat([tail, chunk]);
- const emit = Math.max(0, combined.length - count);
- if (emit) headWrite(combined.subarray(0, emit));
- tail = combined.subarray(emit);
- }
- return "";
-}
-
-function readHeadFdExceptLastRecords(fd, count, delimiter) {
- if (fstatSync(fd).isFile() && fdIsSeekable(fd)) {
- const data = readRemainingFdSync(fd);
- const keep = headPrefixLengthExceptLastRecords(data, count, delimiter.charCodeAt(0));
- headWrite(data.subarray(0, keep));
- rewindFd(fd, data.length - keep);
- return "";
- }
- const delim = delimiter.charCodeAt(0);
- const byte = Buffer.alloc(1);
- let current = [];
- const records = [];
- while (true) {
- const n = readSync(fd, byte, 0, 1, null);
- if (n === 0) break;
- current.push(byte[0]);
- if (byte[0] === delim) {
- records.push(Buffer.from(current));
- current = [];
- while (records.length > count) headWrite(records.shift());
- }
- }
- if (current.length) {
- records.push(Buffer.from(current));
- while (records.length > count) headWrite(records.shift());
- }
- return "";
-}
-
-function isWriteError(error) {
- return error?.syscall === "write" || ["EPIPE", "ENOSPC"].includes(error?.code);
-}
-
-function readRemainingStdinSync() {
- return readRemainingFdSync(0);
-}
-
-function readRemainingFdSync(fd) {
- const chunks = [];
- const buffer = Buffer.alloc(8192);
- while (true) {
- const n = readSync(fd, buffer, 0, buffer.length, null);
- if (n === 0) break;
- chunks.push(Buffer.from(buffer.subarray(0, n)));
- }
- return Buffer.concat(chunks);
-}
-
-function headPrefixLengthExceptLastRecords(data, count, delimiter) {
- if (count === 0) return data.length;
- let seen = 0;
- for (let i = data.length - 1; i >= 0; i--) {
- if (data[i] === delimiter) {
- seen++;
- if (seen > count) return i + 1;
- }
- }
- return 0;
-}
-
-function rewindStdin(bytes) {
- rewindFd(0, bytes);
-}
-
-function stdinIsSeekable() {
- return fdIsSeekable(0);
-}
-
-function rewindFd(fd, bytes) {
- if (bytes > 0) libc.symbols.lseek(fd, -BigInt(bytes), SEEK_CUR);
-}
-
-function fdIsSeekable(fd) {
- return libc.symbols.lseek(fd, 0n, SEEK_CUR) >= 0;
-}
-
-async function tail(args) {
- args = normalizeHeadTailArgs(normalizeTailLongOptions(args), "tail");
- const pidList = tailPidList(args);
- const headerMode = headTailHeaderMode(args);
- const { opts, operands } = parseOptions(args, { short: { n: "value", c: "value", q: false, v: false, z: false, f: false, F: false, s: "value" }, long: { lines: "value", bytes: "value", quiet: false, silent: false, verbose: false, "zero-terminated": false, follow: "optional-value", sleep: "value", "sleep-interval": "value", "max-unchanged-stats": "value", pid: "value", retry: false, debug: false, "-disable-inotify": false, help: false, version: false } });
- const files = operands.length ? operands : ["-"];
- const bytesMode = opts.c ?? opts.bytes;
- const count = parseTailCount(bytesMode ?? opts.n ?? opts.lines, 10, bytesMode != null);
- const rawCount = String(bytesMode ?? opts.n ?? opts.lines ?? "");
- const delimiter = opts.z || opts["zero-terminated"] ? "\0" : "\n";
- const follow = opts.f || opts.F || opts.follow != null;
- const followMode = opts.F ? "name" : opts.follow === true ? "descriptor" : opts.follow ?? (opts.f ? "descriptor" : null);
- if (followMode != null && !["descriptor", "name"].includes(followMode)) {
- const kind = followMode === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedDiagnostic(followMode)} for ${localeQuotedDiagnostic("--follow")}\nValid arguments are:\n - ${localeQuotedDiagnostic("descriptor")}\n - ${localeQuotedDiagnostic("name")}`, true);
- }
- const followByName = followMode === "name";
- const retryInitialOpen = opts.retry || opts.F;
- const sleepInterval = parseTailSleepInterval(opts.s ?? opts.sleep ?? opts["sleep-interval"]);
- parseTailMaxUnchangedStats(opts["max-unchanged-stats"]);
- if (opts.retry && !follow) stderr("tail: warning: --retry ignored; --retry is useful only when following\n");
- if (follow && files.includes("-") && process.env.BNU_STDIN_CLOSED === "1") {
- stderr("tail: cannot fstat 'standard input'\n");
- stderr("tail: no files remaining\n");
- return 1;
- }
- if (count === 0 && !follow && !rawCount.startsWith("+")) return 0;
- const followOffsets = new Map();
- const followIdentities = new Map();
- const followInaccessible = new Map();
- const followFiles = [];
- let followHasNonRegular = false;
- let renderedAnyFile = false;
- let lastOutputFile = null;
- let failed = false;
- for (let i = 0; i < files.length; i++) {
- const file = files[i];
- const header = headTailShouldPrintHeader(headerMode, files.length) ? `${renderedAnyFile ? "\n" : ""}==> ${tailDisplayName(file)} <==\n` : "";
- const rawBytes = bytesMode == null ? "" : String(bytesMode);
- if (!follow && file === "-" && bytesMode != null && rawBytes.startsWith("+")) {
- if (header) stdout(header);
- let skip = Math.max(0, tailStartOffset(count));
- readStdinChunks((chunk) => {
- if (skip >= chunk.length) {
- skip -= chunk.length;
- return;
- }
- stdout(skip > 0 ? chunk.slice(skip) : chunk);
- skip = 0;
- });
- renderedAnyFile = true;
- continue;
- }
- if (!follow && file === "-" && bytesMode == null && rawCount.startsWith("+")) {
- if (header) stdout(header);
- readTailFdFromRecord(0, count, delimiter);
- renderedAnyFile = true;
- continue;
- }
- if (!follow && file !== "-" && bytesMode == null && rawCount.startsWith("+") && await isTailStreamingDevice(file)) {
- if (header) stdout(header);
- let fd;
- try {
- fd = openSync(file, "r");
- readTailFdFromRecord(fd, count, delimiter);
- renderedAnyFile = true;
- } catch (error) {
- if (isWriteError(error)) throw error;
- stderr(`tail: error reading ${headTailDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- } finally {
- if (fd != null) closeSync(fd);
- }
- continue;
- }
- if (bytesMode != null && file !== "-" && await isTailBlockDevice(file)) {
- if (header) stdout(header);
- try {
- await tailBlockDeviceBytes(file, count, rawBytes.startsWith("+"));
- } catch (error) {
- stderr(`tail: error reading ${headTailDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- }
- continue;
- }
- if (bytesMode != null && file !== "-" && !rawBytes.startsWith("+") && await isTailStreamingDevice(file)) {
- if (header) stdout(header);
- try {
- await tailFirstBytes(file, count);
- } catch (error) {
- stderr(`tail: error reading ${headTailDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- failed = true;
- }
- continue;
- }
- if (follow && file === "-") {
- try {
- fstatSync(0);
- } catch {
- stderr("tail: cannot fstat 'standard input'\n");
- failed = true;
- continue;
- }
- }
- const fileInfo = file === "-" ? null : await stat(file).catch(() => null);
- if (follow && (!fileInfo || !fileInfo.isFile())) followHasNonRegular = true;
- if (follow && pidList.length && fileInfo?.isFIFO?.()) {
- followOffsets.set(file, 0);
- followIdentities.set(file, await tailFollowIdentity(file, followByName));
- followFiles.push(file);
- renderedAnyFile = true;
- continue;
- }
- if (retryInitialOpen && fileInfo?.isDirectory()) {
- stderr(`tail: cannot follow ${headTailDiagnosticName(file)}: Is a directory\n`);
- // -F retries an initially untailable name. Report its inaccessible
- // state now, rather than waiting for the first polling cycle: callers
- // (and GNU's follow protocol) need both diagnostics before a rapid
- // directory-to-file replacement can occur.
- if (followByName) stderr(`tail: ${headTailDiagnosticName(file)} has become inaccessible: Is a directory\n`);
- failed = true;
- followFiles.push(file);
- followOffsets.set(file, null);
- followIdentities.set(file, await tailFollowIdentity(file, followByName));
- if (!followByName) followInaccessible.set(file, "Is a directory");
- continue;
- }
- let data;
- try {
- data = await readAll(file);
- } catch (error) {
- if (error?.code === "EISDIR") {
- if (header) stdout(header);
- renderedAnyFile = true;
- stderr(`tail: error reading ${headTailDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- } else {
- stderr(file === "-" ? `tail: ${nodeErrorMessage(error)}\n` : `tail: cannot open ${headTailDiagnosticName(file)} for reading: ${systemErrorMessage(error)}\n`);
- }
- failed = true;
- if (retryInitialOpen && file !== "-") {
- followFiles.push(file);
- followOffsets.set(file, null);
- followIdentities.set(file, null);
- }
- continue;
- }
- followOffsets.set(file, data.length);
- followIdentities.set(file, await tailFollowIdentity(file, followByName));
- if (file !== "-") followFiles.push(file);
- if (header) {
- stdout(header);
- lastOutputFile = file;
- }
- renderedAnyFile = true;
- if (bytesMode != null) {
- stdout(rawBytes.startsWith("+") ? data.slice(Math.max(0, tailStartOffset(count))) : data.slice(Math.max(0, data.length - count)));
- } else {
- const raw = String(opts.n ?? opts.lines ?? "");
- const lines = splitDelimitedByteRecords(data, delimiter);
- stdout(raw.startsWith("+") ? Buffer.concat(lines.slice(Math.max(0, tailStartOffset(count)))) : count === 0 ? "" : Buffer.concat(lines.slice(-count)));
- }
- }
- if (follow && followFiles.length) {
- if (opts.retry && followMode === "descriptor") stderr("tail: warning: --retry only effective for the initial open\n");
- if (opts.debug) {
- // Descriptor-following a device uses its blocking read semantics;
- // regular files use inotify unless explicitly disabled, while
- // name-following non-regular files must poll.
- const mode = opts["-disable-inotify"]
- ? "polling"
- : followHasNonRegular
- ? followByName ? "polling" : "blocking"
- : "notification";
- stderr(`tail: using ${mode} mode\n`);
- }
- const followStatus = await followTailFiles(followFiles, followOffsets, {
- followByName,
- inotifyMode: !opts["-disable-inotify"],
- retryInitialOpen,
- identities: followIdentities,
- inaccessible: followInaccessible,
- interval: sleepInterval,
- headers: (opts.v || opts.verbose || files.length > 1) && !(opts.q || opts.quiet || opts.silent),
- lastOutputFile,
- pids: pidList,
- });
- if (followStatus !== 0) return followStatus;
- } else if (follow && failed) {
- stderr("tail: no files remaining\n");
- }
- return failed ? 1 : 0;
-}
-
-async function followTailFiles(files, offsets, options) {
- const removedParentDirs = new Set();
- const inotify = options.inotifyMode ? tailInotifyOpen(files, options.followByName) : null;
- if (!inotify) options.inotifyMode = false;
- await tailTestPauseBeforeInotifyScan();
- try {
- while (true) {
- if (options.pids?.length && !options.pids.some(tailPidAlive)) return 0;
- if (pollFd(1, POLLOUT) & (POLLERR | POLLHUP | POLLNVAL)) return 0;
- const iterationFiles = inotify?.pendingFiles?.length ? inotify.pendingFiles.splice(0) : files;
- for (const file of iterationFiles) {
- let actualFile = file;
- let identity = await tailFollowIdentity(file, options.followByName);
- let s = await stat(file).catch(() => null);
- if (!s && !options.followByName && options.identities?.get(file) != null) {
- actualFile = await findTailMovedPath(file, options.identities.get(file)) ?? file;
- if (actualFile !== file) {
- identity = await tailFollowIdentity(actualFile, false);
- s = await stat(actualFile).catch(() => null);
- }
- }
- tailInotifyUpdateFile(inotify, file, s, identity);
- if (!s || s.isDirectory()) {
- if (offsets.get(file) === null && s?.isDirectory() && !options.followByName) {
- stderr(`tail: ${headTailDiagnosticName(file)} has been replaced with an untailable file\n`);
- stderr("tail: no files remaining\n");
- return 1;
- }
- if (options.followByName && options.identities?.get(file) != null && offsets.get(file) !== null) {
- stderr(`tail: ${headTailDiagnosticName(file)} has become inaccessible: ${s?.isDirectory() ? "Is a directory" : "No such file or directory"}\n`);
- if (options.inotifyMode && !s && !removedParentDirs.has(pathDirname(String(file))) && !(await lstat(pathDirname(String(file))).catch(() => null))) {
- removedParentDirs.add(pathDirname(String(file)));
- stderr("tail: directory containing watched file was removed\n");
- stderr("tail: inotify cannot be used, reverting to polling\n");
- }
- if (!s && !options.retryInitialOpen && await findTailMovedPath(file, options.identities.get(file))) {
- stderr("tail: no files remaining\n");
- return 1;
- }
- offsets.set(file, null);
- options.identities.set(file, null);
- } else if (options.followByName && offsets.get(file) === null && s?.isDirectory() && options.inaccessible?.has(file)) {
- stderr(`tail: ${headTailDiagnosticName(file)} has become inaccessible: ${options.inaccessible.get(file)}\n`);
- options.inaccessible.delete(file);
- }
- continue;
- }
- let offset = offsets.has(file) ? offsets.get(file) : 0;
- const previousIdentity = options.identities?.get(file);
- if (offset === null) {
- if (options.inaccessible?.has(file)) {
- stderr(`tail: ${headTailDiagnosticName(file)} has become inaccessible: ${options.inaccessible.get(file)}\n`);
- options.inaccessible.delete(file);
- }
- stderr(`tail: ${headTailDiagnosticName(file)} has appeared; following new file\n`);
- offset = 0;
- } else if (options.followByName && previousIdentity != null && identity != null && previousIdentity !== identity) {
- stderr(`tail: ${headTailDiagnosticName(file)} has been replaced; following new file\n`);
- offset = 0;
- } else if (s.size < offset) {
- stderr(`tail: ${headTailDiagnosticName(file)}: file truncated\n`);
- offset = 0;
- }
- if (s.size <= offset) {
- offsets.set(file, offset);
- if (identity != null) options.identities?.set(file, identity);
- continue;
- }
- if (options.headers && options.lastOutputFile !== file) {
- stdout(`${options.lastOutputFile == null ? "" : "\n"}==> ${tailDisplayName(file)} <==\n`);
- options.lastOutputFile = file;
- }
- await writeFileRange(actualFile, offset, s.size - offset);
- offsets.set(file, s.size);
- if (identity != null) options.identities?.set(file, identity);
- }
- if (inotify) tailInotifyWait(inotify, options.interval);
- else await Bun.sleep(options.interval);
- }
- } finally {
- tailInotifyClose(inotify);
- }
-}
-
-async function tailTestPauseBeforeInotifyScan() {
- const ready = process.env.BNU_TAIL_INOTIFY_READY_FILE;
- const proceed = process.env.BNU_TAIL_INOTIFY_CONTINUE_FILE;
- if (!ready || !proceed) return;
- await writeFile(ready, "ready\n");
- const deadline = Date.now() + 30_000;
- while (!existsSync(proceed)) {
- if (Date.now() >= deadline) throw new Error("timed out waiting for the inotify race test continuation marker");
- await Bun.sleep(10);
- }
-}
-
-function tailInotifyOpen(files, followByName) {
- let fd;
- try {
- fd = libc.symbols.inotify_init1(fsConstants.O_NONBLOCK | fsConstants.O_CLOEXEC);
- } catch {
- return null;
- }
- if (fd < 0) return null;
- const state = { fd, files: new Map(), parents: new Map(), pendingFiles: [] };
- if (followByName) {
- for (const file of files) {
- const parent = pathDirname(String(file));
- if (state.parents.has(parent)) continue;
- const wd = libc.symbols.inotify_add_watch(fd, cstrPath(parent), IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_ATTRIB);
- if (wd >= 0) state.parents.set(parent, wd);
- }
- }
- return state;
-}
-
-function tailInotifyUpdateFile(state, file, statInfo, identity) {
- if (!state) return;
- const current = state.files.get(file);
- const watchable = statInfo && (statInfo.isFile() || statInfo.isFIFO());
- if (current && (!watchable || current.identity !== identity)) {
- libc.symbols.inotify_rm_watch(state.fd, current.wd);
- state.files.delete(file);
- }
- if (!watchable || state.files.has(file)) return;
- const wd = libc.symbols.inotify_add_watch(state.fd, cstrPath(file), IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_DELETE_SELF | IN_MOVE_SELF);
- if (wd >= 0) state.files.set(file, { wd, identity });
-}
-
-function tailInotifyWait(state, timeout) {
- if (!(pollFd(state.fd, POLLIN, timeout) & POLLIN)) return;
- const events = Buffer.allocUnsafe(64 * 1024);
- try {
- const bytesRead = readSync(state.fd, events, 0, events.length, null);
- for (let offset = 0; offset + 16 <= bytesRead;) {
- const wd = events.readInt32LE(offset);
- const nameLength = events.readUInt32LE(offset + 12);
- for (const [file, watch] of state.files) {
- if (watch.wd === wd && state.pendingFiles.at(-1) !== file) {
- state.pendingFiles.push(file);
- break;
- }
- }
- offset += 16 + nameLength;
- }
- } catch (error) {
- if (error?.code !== "EAGAIN") throw error;
- }
-}
-
-function tailInotifyClose(state) {
- if (!state) return;
- for (const { wd } of state.files.values()) libc.symbols.inotify_rm_watch(state.fd, wd);
- for (const wd of state.parents.values()) libc.symbols.inotify_rm_watch(state.fd, wd);
- closeSync(state.fd);
-}
-
-function tailPidList(args) {
- const pids = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- let value = null;
- if (arg === "--pid") value = args[++i];
- else if (arg.startsWith("--pid=")) value = arg.slice("--pid=".length);
- if (value == null) continue;
- if (value === "") {
- pids.push(0);
- continue;
- }
- if (!/^\d+$/.test(value)) throw new UsageError(`invalid PID: ${localeQuotedEscapedDiagnostic(value)}`);
- pids.push(Number(value));
- }
- return pids;
-}
-
-function normalizeTailLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, TAIL_LONG_OPTIONS);
-}
-
-function normalizeTailLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, TAIL_LONG_OPTIONS);
-}
-
-function tailPidAlive(pid) {
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
- try {
- process.kill(pid, 0);
- return true;
- } catch {
- return false;
- }
-}
-
-function tailDisplayName(file) {
- return file === "-" ? "standard input" : file;
-}
-
-async function tailFollowIdentity(file, followByName = true) {
- const s = await (followByName ? lstat(file) : stat(file)).catch(() => null);
- return s ? `${s.dev}:${s.ino}` : null;
-}
-
-async function findTailMovedPath(file, identity) {
- const dir = pathDirname(String(file));
- for (const entry of await readdirPathEntries(dir).catch(() => [])) {
- const candidate = pathLikeJoin(dir, entry);
- if (candidate === file) continue;
- if (await tailFollowIdentity(candidate, false) === identity) return candidate;
- }
- return null;
-}
-
-async function writeFileRange(file, offset, length) {
- const handle = await open(file, "r");
- const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, length));
- let position = offset;
- let remaining = length;
- try {
- while (remaining > 0) {
- const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, remaining), position);
- if (bytesRead === 0) break;
- stdout(buffer.subarray(0, bytesRead));
- position += bytesRead;
- remaining -= bytesRead;
- }
- } finally {
- await handle.close().catch(() => {});
- }
-}
-
-function parseTailSleepInterval(value) {
- if (value == null || value === true) return 1000;
- const seconds = Number(value);
- if (!Number.isFinite(seconds) || seconds < 0) throw new UsageError(`invalid number of seconds: ${localeQuotedEscapedDiagnostic(value)}`);
- return Math.max(1, Math.trunc(seconds * 1000));
-}
-
-function parseTailMaxUnchangedStats(value) {
- if (value == null) return null;
- const text = String(value);
- if (!/^\d+$/.test(text)) throw new UsageError(`invalid maximum number of unchanged stats between opens: ${localeQuotedEscapedDiagnostic(text)}`);
- return Number(text);
-}
-
-async function isTailStreamingDevice(file) {
- const s = await stat(file).catch(() => null);
- return !!(s?.isCharacterDevice?.() || s?.isBlockDevice?.());
-}
-
-async function isTailBlockDevice(file) {
- const s = await stat(file).catch(() => null);
- return Boolean(s?.isBlockDevice?.());
-}
-
-async function tailBlockDeviceBytes(file, count, fromStart) {
- const handle = await open(file, "r");
- try {
- const end = libc.symbols.lseek(handle.fd, 0n, SEEK_END);
- if (end < 0n) throw new Error("cannot seek to end of device");
- const requested = BigInt(Math.max(0, count));
- const start = fromStart
- ? BigInt(Math.max(0, tailStartOffset(count)))
- : end > requested ? end - requested : 0n;
- const boundedStart = start > end ? end : start;
- if (libc.symbols.lseek(handle.fd, boundedStart, SEEK_SET) < 0n) throw new Error("cannot seek on device");
- let remaining = end - boundedStart;
- const buffer = Buffer.allocUnsafe(Number(remaining > 64n * 1024n ? 64n * 1024n : remaining || 1n));
- while (remaining > 0n) {
- const wanted = Number(remaining > BigInt(buffer.length) ? BigInt(buffer.length) : remaining);
- const { bytesRead } = await handle.read(buffer, 0, wanted, null);
- if (bytesRead === 0) break;
- stdout(buffer.subarray(0, bytesRead));
- remaining -= BigInt(bytesRead);
- }
- } finally {
- await handle.close().catch(() => {});
- }
-}
-
-async function tailFirstBytes(file, count) {
- if (count <= 0) return;
- const handle = await open(file, "r");
- const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, count));
- let remaining = count;
- try {
- while (remaining > 0) {
- const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, remaining), null);
- if (bytesRead === 0) break;
- stdout(buffer.subarray(0, bytesRead));
- remaining -= bytesRead;
- }
- } finally {
- await handle.close().catch(() => {});
- }
-}
-
-function parseTailCount(value, defaultValue, bytesMode) {
- if (value == null) return defaultValue;
- const text = String(value);
- const countText = text.replace(/^[+-]/, "");
- let count;
- try {
- count = parseByteCount(countText);
- } catch (error) {
- if (error instanceof UsageError) throw new UsageError(`invalid number of ${bytesMode ? "bytes" : "lines"}: ${localeQuotedEscapedDiagnostic(countText)}`);
- throw error;
- }
- if (!Number.isFinite(count) || count < 0) throw new UsageError(`invalid number of ${bytesMode ? "bytes" : "lines"}: ${localeQuotedEscapedDiagnostic(countText)}`);
- return Math.trunc(count);
-}
-
-function tailStartOffset(count) {
- return Math.max(0, count - 1);
-}
-
-function readTailFdFromRecord(fd, count, delimiter) {
- const targetRecord = tailStartOffset(count);
- const sep = delimiter.charCodeAt(0);
- let seen = 0;
- let emitting = targetRecord === 0;
- readFdChunkViews(fd, (chunk) => {
- if (emitting) {
- stdout(chunk);
- return;
- }
- let offset = 0;
- while (offset < chunk.length) {
- if (chunk[offset] === sep) {
- seen++;
- if (seen >= targetRecord) {
- stdout(chunk.subarray(offset + 1));
- emitting = true;
- return;
- }
- }
- offset++;
- }
- });
-}
-
-function nodeErrorMessage(error) {
- if (error?.code === "ENOENT") return "No such file or directory";
- if (error?.code === "ENOSPC") return "No space left on device";
- return error?.message || String(error);
-}
-
-function splitDelimitedRecords(text, delimiter) {
- const records = [];
- let start = 0;
- while (start < text.length) {
- const idx = text.indexOf(delimiter, start);
- if (idx === -1) {
- records.push(text.slice(start));
- break;
- }
- records.push(text.slice(start, idx + delimiter.length));
- start = idx + delimiter.length;
- }
- return records;
-}
-
-function splitDelimitedByteRecords(data, delimiter) {
- const records = [];
- const sep = delimiter.charCodeAt(0);
- let start = 0;
- for (let i = 0; i < data.length; i++) {
- if (data[i] !== sep) continue;
- records.push(Buffer.from(data.subarray(start, i + 1)));
- start = i + 1;
- }
- if (start < data.length) records.push(Buffer.from(data.subarray(start)));
- return records;
-}
-
-function normalizeHeadTailArgs(args, command) {
- const normalized = [];
- let end = false;
- let valueFor = null;
- for (const arg of args) {
- if (end) {
- normalized.push(arg);
- continue;
- }
- if (valueFor) {
- normalized.push(arg);
- valueFor = null;
- continue;
- }
- if (arg === "--") {
- end = true;
- normalized.push(arg);
- } else if (arg === "-n" || arg === "-c" || arg === "--lines" || arg === "--bytes") {
- valueFor = arg;
- normalized.push(arg);
- } else if (command === "tail" && /^-\d+[cbk].+/.test(arg)) {
- throw new UsageError(`option used in invalid context -- ${arg[1]}`);
- } else if (command === "tail" && /^([+-])(\d+)([cbk])$/.test(arg)) {
- const [, sign, count, suffix] = arg.match(/^([+-])(\d+)([cbk])$/);
- normalized.push("-c", `${sign}${count}${suffix === "c" ? "" : suffix}`);
- } else if (command === "tail" && /^([+-])(\d+)l$/.test(arg)) {
- const [, sign, count] = arg.match(/^([+-])(\d+)l$/);
- normalized.push("-n", `${sign}${count}`);
- } else if (command === "tail" && arg === "+c") {
- normalized.push("-c", "+10");
- } else if (command === "tail" && arg === "+l") {
- normalized.push("-n", "+10");
- } else if (command === "tail" && arg === "-l") {
- normalized.push("-n", "10");
- } else if (command === "tail" && arg === "-b") {
- normalized.push("-c", "10b");
- } else if (/^-\d+[cbk]$/.test(arg)) {
- const suffix = arg.at(-1);
- normalized.push("-c", suffix === "c" ? arg.slice(1, -1) : arg.slice(1));
- } else if (/^-\d/.test(arg)) {
- normalized.push("-n", arg.slice(1));
- } else if (command === "tail" && /^\+\d+$/.test(arg)) {
- normalized.push("-n", arg);
- } else {
- normalized.push(arg);
- }
- }
- return normalized;
-}
-
-function headTailHeaderMode(args) {
- let mode = null;
- let end = false;
- let valueFor = null;
- for (const arg of args) {
- if (end) continue;
- if (valueFor) {
- valueFor = null;
- continue;
- }
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg === "-n" || arg === "-c" || arg === "--lines" || arg === "--bytes" || arg === "--sleep" || arg === "--sleep-interval" || arg === "--max-unchanged-stats" || arg === "--pid") {
- valueFor = arg;
- continue;
- }
- if (arg === "--quiet" || arg === "--silent") mode = "quiet";
- else if (arg === "--verbose") mode = "verbose";
- else if (/^-[^-]/.test(arg)) {
- for (const ch of arg.slice(1)) {
- if (ch === "q") mode = "quiet";
- else if (ch === "v") mode = "verbose";
- }
- }
- }
- return mode;
-}
-
-function headTailShouldPrintHeader(mode, fileCount) {
- if (mode === "verbose") return true;
- if (mode === "quiet") return false;
- return fileCount > 1;
-}
-
-async function seq(args) {
- const { opts, operands } = parseSeqOptions(args);
- if (operands.length < 1) throw new UsageError("missing operand", true);
- if (operands.length > 3) throw new UsageError(`extra operand ${seqDiagnosticQuote(operands[3])}`, true);
- const [firstText, incText, lastText] = operands.length === 1 ? ["1", "1", operands[0]] : operands.length === 2 ? [operands[0], "1", operands[1]] : operands;
- const format = opts.f ?? opts.format;
- if (format != null) validateSeqFormat(format);
- if (format == null && seqCanUseBigInt(firstText, incText, lastText)) return seqBigInt(firstText, incText, lastText, opts);
- const [first, inc, last] = [parseSeqNumber(firstText), parseSeqNumber(incText), parseSeqNumber(lastText)];
- const firstOrIncInvalid = [[firstText, first], [incText, inc]].find(([, value]) => Number.isNaN(value));
- if (firstOrIncInvalid) {
- const [text] = firstOrIncInvalid;
- const invalidText = String(text);
- throw new UsageError(/^[+-]?nan$/i.test(invalidText.trim()) ? `invalid ${localeQuotedDiagnostic("not-a-number")} argument: ${seqDiagnosticQuote(text)}` : `invalid floating point argument: ${seqDiagnosticQuote(text)}`, true);
- }
- if (Object.is(inc, 0) || Object.is(inc, -0)) throw new UsageError(`invalid Zero increment value: ${seqDiagnosticQuote(incText)}`, true);
- if (Number.isNaN(last)) {
- const invalidText = String(lastText);
- throw new UsageError(/^[+-]?nan$/i.test(invalidText.trim()) ? `invalid ${localeQuotedDiagnostic("not-a-number")} argument: ${seqDiagnosticQuote(lastText)}` : `invalid floating point argument: ${seqDiagnosticQuote(lastText)}`, true);
- }
- const sep = opts.s ?? opts.separator ?? "\n";
- const tolerance = Math.abs(inc) * 1e-12;
- const defaultPrecision = opts.f || opts.format ? null : seqFixedPrecision([firstText, incText]);
- const finiteWidthValues = Number.isFinite(first) && Number.isFinite(inc) && Number.isFinite(last) ? seqFiniteValues(first, inc, last, tolerance) : [];
- const width = opts.w || opts.equal_width ? seqEqualWidth(finiteWidthValues.length ? finiteWidthValues : [first, last].filter(Number.isFinite), defaultPrecision) : 0;
- let wrote = false;
- try {
- for (let step = 0;; step++) {
- const raw = first + inc * step;
- if (Number.isNaN(raw)) break;
- if (inc > 0 ? raw > last + tolerance : raw < last - tolerance) break;
- const n = Math.abs(raw) < tolerance ? 0 : raw;
- let s = defaultPrecision == null ? formatSeqDefaultNumber(n) : n.toFixed(defaultPrecision);
- if (step === 0 && /^-0(?:\.0*)?(?:e[+-]?\d+)?$/i.test(String(firstText).trim()) && n === 0) s = defaultPrecision == null ? "-0" : `-${s}`;
- if (width) s = padSeqEqualWidth(s, width);
- if (format != null) s = formatSeqValue(format, n);
- if (wrote) seqWrite(sep);
- seqWrite(s);
- wrote = true;
- }
- if (wrote) seqWrite("\n");
- } catch (error) {
- if (isWriteError(error)) {
- if (error?.code === "EPIPE") {
- if (parentIgnoresSigpipe()) stderr(`seq: write error: ${outputWriteErrorMessage(error)}\n`);
- return parentIgnoresSigpipe() ? 1 : 0;
- }
- stderr(`seq: write error: ${outputWriteErrorMessage(error)}\n`);
- return 1;
- }
- throw error;
- }
- return 0;
-}
-
-function seqWrite(data) {
- writeAllSync(1, String(data));
-}
-
-function seqFiniteValues(first, inc, last, tolerance) {
- const values = [];
- for (let step = 0;; step++) {
- const n = first + inc * step;
- if (inc > 0 ? n > last + tolerance : n < last - tolerance) break;
- values.push(Math.abs(n) < tolerance ? 0 : n);
- if (values.length > 100000) break;
- }
- return values;
-}
-
-function parseSeqNumber(value) {
- const text = seqNumberText(value);
- if (text == null) return Number.NaN;
- if (/^[+-]?inf(?:inity)?$/i.test(text)) return text.startsWith("-") ? -Infinity : Infinity;
- const hex = text.match(/^([+-])?0x([0-9a-f]+)(?:\.([0-9a-f]*))?p([+-]?\d+)$/i);
- if (hex) {
- const sign = hex[1] === "-" ? -1 : 1;
- const integer = Number.parseInt(hex[2], 16);
- const fraction = [...(hex[3] ?? "")].reduce((sum, ch, index) => sum + Number.parseInt(ch, 16) / 16 ** (index + 1), 0);
- return sign * (integer + fraction) * 2 ** Number(hex[4]);
- }
- return Number(text);
-}
-
-function seqNumberText(value) {
- const text = String(value).trimStart();
- return /\s$/.test(text) ? null : text;
-}
-
-function seqDiagnosticQuote(value) {
- return localeQuotedDiagnostic([...String(value)].map((ch) => {
- if (/[\udc80-\udcff]/.test(ch)) return `\\${(ch.charCodeAt(0) - 0xdc00).toString(8).padStart(3, "0")}`;
- return lsEscapedName(ch, { escapeDouble: false });
- }).join(""));
-}
-
-function parseSeqOptions(args) {
- const opts = {};
- const operands = [];
- let parseOptions = true;
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- if (option.startsWith("--")) throw new UsageError(`option '${option}' requires an argument`, true);
- throw new UsageError(`option requires an argument -- '${option.slice(1)}'`, true);
- };
- for (let i = 0; i < args.length; i++) {
- let arg = args[i];
- if (!parseOptions) {
- operands.push(arg);
- } else if (arg === "--") {
- operands.push(...args.slice(i + 1));
- break;
- } else if (arg.startsWith("--")) {
- arg = normalizeSeqLongOption(arg);
- const [name, inlineValue] = arg.slice(2).split(/=(.*)/s, 2);
- if (!SEQ_LONG_OPTIONS.includes(name)) throw new UsageError(invalidOptionMessage(arg), true);
- if (name === "help" || name === "version" || name === "equal-width") {
- if (inlineValue != null) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- if (name === "equal-width") opts.equal_width = true;
- } else if (name === "separator") {
- if (inlineValue != null) opts.separator = inlineValue;
- else {
- opts.separator = requireValue(i, arg);
- i++;
- }
- } else if (name === "format") {
- if (inlineValue != null) opts.format = inlineValue;
- else {
- opts.format = requireValue(i, arg);
- i++;
- }
- }
- } else if (arg === "-w") {
- opts.w = true;
- } else if (arg === "-s") {
- opts.s = requireValue(i, arg);
- i++;
- } else if (arg.startsWith("-s") && arg.length > 2) {
- opts.s = arg.slice(2);
- } else if (arg === "-f") {
- opts.f = requireValue(i, arg);
- i++;
- } else if (/^-[0-9.]/.test(arg) || !arg.startsWith("-")) {
- operands.push(arg);
- parseOptions = false;
- } else {
- throw new UsageError(invalidOptionMessage(arg), true);
- }
- }
- return { opts, operands };
-}
-
-function normalizeSeqLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, SEQ_LONG_OPTIONS);
-}
-
-function seqFixedPrecision(values) {
- let precision = 0;
- for (const value of values) {
- precision = Math.max(precision, seqDecimalPrecision(value));
- }
- return precision || null;
-}
-
-function seqCanUseBigInt(firstText, incText, lastText) {
- return [firstText, incText].every(seqIntegerText) && (seqIntegerText(lastText) || seqInfinityText(lastText) != null);
-}
-
-function seqBigInt(firstText, incText, lastText, opts) {
- const first = BigInt(String(firstText).trim());
- const inc = BigInt(String(incText).trim());
- const infinity = seqInfinityText(lastText);
- const last = infinity == null ? BigInt(String(lastText).trim()) : infinity;
- if (inc === 0n) throw new UsageError(`invalid Zero increment value: ${localeQuotedDiagnostic(incText)}`, true);
- const sep = opts.s ?? opts.separator ?? "\n";
- const finite = typeof last === "bigint";
- const width = opts.w || opts.equal_width
- ? finite
- ? Math.max(first.toString().length, last.toString().length)
- : first.toString().length
- : 0;
- let wrote = false;
- try {
- for (let value = first; seqBigIntContinues(value, inc, last); value += inc) {
- if (wrote) seqWrite(sep);
- seqWrite(width ? padSeqEqualWidth(value.toString(), width) : value.toString());
- wrote = true;
- }
- if (wrote) seqWrite("\n");
- } catch (error) {
- if (isWriteError(error)) {
- if (error?.code === "EPIPE") {
- if (parentIgnoresSigpipe()) stderr(`seq: write error: ${outputWriteErrorMessage(error)}\n`);
- return parentIgnoresSigpipe() ? 1 : 0;
- }
- stderr(`seq: write error: ${outputWriteErrorMessage(error)}\n`);
- return 1;
- }
- throw error;
- }
- return 0;
-}
-
-function seqIntegerText(value) {
- const text = seqNumberText(value);
- if (text == null) return false;
- return /^[+-]?\d+$/.test(text) && !/^-0+$/.test(text);
-}
-
-function seqInfinityText(value) {
- const text = seqNumberText(value);
- if (text == null) return null;
- if (/^\+?inf(?:inity)?$/i.test(text)) return Infinity;
- if (/^-inf(?:inity)?$/i.test(text)) return -Infinity;
- return null;
-}
-
-function seqBigIntContinues(value, inc, last) {
- if (last === Infinity) return inc > 0n;
- if (last === -Infinity) return inc < 0n;
- return inc > 0n ? value <= last : value >= last;
-}
-
-function seqDecimalPrecision(value) {
- const text = (seqNumberText(value) ?? String(value).trim()).replace(/^["']|["']$/g, "");
- const match = text.match(/^[+-]?(?:(\d*)\.(\d*)|(\d+))(?:[eE]([+-]?\d+))?$/);
- if (!match) return 0;
- const decimals = (match[2] ?? "").length;
- const exponent = Number(match[4] ?? 0);
- return Math.max(0, decimals - exponent);
-}
-
-function seqEqualWidth(values, precision) {
- return Math.max(...values.map((value) => {
- const rendered = precision == null ? formatSeqDefaultNumber(value) : value.toFixed(precision);
- return rendered.length;
- }));
-}
-
-function formatSeqDefaultNumber(value) {
- if (value === Infinity) return "inf";
- if (value === -Infinity) return "-inf";
- return Number.isInteger(value) ? String(value) : String(value);
-}
-
-function padSeqEqualWidth(text, width) {
- if (text.startsWith("-")) return `-${text.slice(1).padStart(Math.max(0, width - 1), "0")}`;
- return text.padStart(width, "0");
-}
-
-function validateSeqFormat(format) {
- const text = String(format);
- let directives = 0;
- for (let i = 0; i < text.length; i++) {
- if (text[i] !== "%") continue;
- if (text[i + 1] === "%") {
- i++;
- continue;
- }
- const rest = text.slice(i);
- const match = rest.match(/^%[-+ 0#]*(?:\d+)?(?:\.\d+)?[aAeEfFgG]/);
- if (!match) {
- if (directives > 0) throw new UsageError(`format ${localeQuotedEscapedDiagnostic(text)} has too many % directives`);
- if (rest === "%") throw new UsageError(`format ${localeQuotedEscapedDiagnostic(text)} ends in %`);
- const unknown = rest.match(/^%[-+ 0#]*(?:\d+)?(?:\.\d+)?(.?)/s)?.[1];
- if (unknown) throw new UsageError(`format ${localeQuotedEscapedDiagnostic(text)} has unknown %${unknown} directive`);
- throw new UsageError(`format ${localeQuotedEscapedDiagnostic(text)} has no % directive`);
- }
- directives++;
- i += match[0].length - 1;
- }
- if (directives === 0) throw new UsageError(`format ${localeQuotedEscapedDiagnostic(text)} has no % directive`);
- if (directives > 1) throw new UsageError(`format ${localeQuotedEscapedDiagnostic(text)} has too many % directives`);
-}
-
-function formatSeqValue(format, value) {
- return String(format).replace(/%%|%([-+ 0#]*)(\d+)?(?:\.(\d+))?([aAeEfFgG])/g, (match, flags = "", width, precision, type) => {
- if (match === "%%") return "%";
- validateSeqFormatOutputSize(width);
- validateSeqFormatOutputSize(precision);
- const prec = precision == null ? 6 : Number(precision);
- let rendered;
- const numericValue = Number(value);
- if (!Number.isFinite(numericValue)) rendered = formatSeqDefaultNumber(numericValue);
- else if (type === "g" || type === "G") rendered = formatSeqGeneral(numericValue, prec, flags.includes("#"));
- else if (type === "e" || type === "E") rendered = formatSeqExponential(numericValue, prec);
- else if (type === "a" || type === "A") rendered = formatSeqHexFloat(numericValue, precision == null ? null : prec, flags.includes("#"));
- else rendered = numericValue.toFixed(prec);
- if (type === "G" || type === "E" || type === "A") rendered = rendered.toUpperCase();
- if (Number(value) >= 0 && flags.includes("+")) rendered = `+${rendered}`;
- else if (Number(value) >= 0 && flags.includes(" ")) rendered = ` ${rendered}`;
- if (width) rendered = padSeqFormat(rendered, width, flags, type);
- return rendered;
- });
-}
-
-function validateSeqFormatOutputSize(value) {
- if (value != null && BigInt(value) > 2147483647n) throw new UsageError("write error: Value too large for defined data type");
-}
-
-function formatSeqExponential(value, precision) {
- return value.toExponential(precision).replace(/e([+-]?)(\d+)$/i, (_, sign, exp) => `e${sign || "+"}${exp.padStart(2, "0")}`);
-}
-
-function formatSeqHexFloat(value, precision, alternate = false) {
- if (Object.is(value, 0) || Object.is(value, -0)) {
- const fraction = precision == null ? (alternate ? "." : "") : `.${"0".repeat(precision)}`;
- return `0x0${fraction}p+0`;
- }
- const abs = Math.abs(value);
- let exponent = Math.floor(Math.log2(abs)) - 3;
- let significand = abs / 2 ** exponent;
- if (significand >= 16) {
- significand /= 2;
- exponent++;
- }
- let head;
- let fraction = "";
- if (precision == null) {
- let scaled = Math.round(significand * 16 ** 13);
- if (scaled >= 16 * 16 ** 13) {
- scaled = 8 * 16 ** 13;
- exponent++;
- }
- head = Math.trunc(scaled / 16 ** 13).toString(16);
- fraction = (scaled % 16 ** 13).toString(16).padStart(13, "0").replace(/0+$/g, "");
- } else {
- let scaled = Math.round(significand * 16 ** precision);
- if (scaled >= 16 * 16 ** precision) {
- scaled = 8 * 16 ** precision;
- exponent++;
- }
- head = Math.trunc(scaled / 16 ** precision).toString(16);
- fraction = (scaled % 16 ** precision).toString(16).padStart(precision, "0");
- }
- const dot = fraction || alternate || precision != null ? "." : "";
- const sign = value < 0 ? "-" : "";
- return `${sign}0x${head}${dot}${fraction}p${exponent >= 0 ? "+" : ""}${exponent}`;
-}
-
-function formatSeqGeneral(value, precision, alternate = false) {
- let rendered = value.toPrecision(precision);
- rendered = rendered.replace(/e([+-]?)(\d+)$/i, (_, sign, exp) => `e${sign || "+"}${exp.padStart(2, "0")}`);
- if (!alternate) {
- rendered = rendered.replace(/(\.\d*?[1-9])0+(e[+-]\d+)$/i, "$1$2");
- rendered = rendered.replace(/\.0+(e[+-]\d+)$/i, "$1");
- rendered = rendered.replace(/(\.\d*?[1-9])0+$/i, "$1");
- rendered = rendered.replace(/\.0+$/i, "");
- }
- return rendered;
-}
-
-function padSeqFormat(value, width, flags = "", type = "") {
- const n = Number(width);
- if (!Number.isInteger(n) || value.length >= n) return value;
- if (flags.includes("-")) return value.padEnd(n, " ");
- const fill = flags.includes("0") && !/^[+-]?inf$/i.test(value) ? "0" : " ";
- if (fill === "0" && /[aA]/.test(type)) return padSeqHexFormat(value, n);
- if (fill === "0" && /^[+-]/.test(value)) return value[0] + value.slice(1).padStart(n - 1, "0");
- return value.padStart(n, fill);
-}
-
-function padSeqHexFormat(value, width) {
- const match = String(value).match(/^([+ -]?)(0[xX])(.*)$/);
- if (!match) return value.padStart(width, "0");
- const [, sign, prefix, rest] = match;
- const zeros = Math.max(0, width - sign.length - prefix.length - rest.length);
- return `${sign}${prefix}${"0".repeat(zeros)}${rest}`;
-}
-
-async function yes(args) {
- const meta = yesMetaOption(args);
- if (meta === "--help") {
- showYesHelp();
- return 0;
- }
- if (meta === "--version") {
- stdout(`${VERSION}\n`);
- return 0;
- }
- validateYesOptions(args);
- if (args[0] === "--") args = args.slice(1);
- const text = `${args.length ? args.join(" ") : "y"}\n`;
- const chunk = text.repeat(1024);
- while (true) {
- try {
- writeSync(1, chunk);
- } catch (error) {
- if (error?.code === "EPIPE") {
- if (parentIgnoresSigpipe()) stderr("yes: standard output: Broken pipe\n");
- return parentIgnoresSigpipe() ? 1 : 0;
- }
- stderr(`yes: standard output: ${outputWriteErrorMessage(error)}\n`);
- return 1;
- }
- }
-}
-
-function yesMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (!arg.startsWith("--")) return null;
- const option = normalizeYesLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!YES_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- return option;
- }
- return null;
-}
-
-function validateYesOptions(args) {
- for (const arg of args) {
- if (arg === "--") return;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (!arg.startsWith("--")) throw new UsageError(`invalid option -- '${arg.slice(1, 2)}'`, true);
- const option = normalizeYesLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!YES_LONG_OPTIONS.includes(name)) throw new UsageError(`unrecognized option '${arg}'`, true);
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- }
-}
-
-function normalizeYesLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = YES_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-function scanMetaOptionBeforeEnd(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (arg === "--help" || arg === "--version") return arg;
- }
- return null;
-}
-
-function showYesHelp() {
- stdout("Usage: yes [STRING]...\n");
- stdout(" or: yes OPTION\n");
- stdout("Repeatedly output a line with all specified STRING(s), or 'y'.\n\n");
- stdout(" --help display this help and exit\n");
- stdout(" --version output version information and exit\n");
-}
-
-async function printenv(args) {
- const operands = [];
- let sep = "\n";
- let parsing = true;
- for (const arg of args) {
- if (!parsing) {
- operands.push(arg);
- } else if (arg === "--") {
- parsing = false;
- } else if (arg === "-" || !arg.startsWith("-")) {
- operands.push(arg);
- parsing = false;
- } else if (arg.startsWith("--")) {
- const option = normalizePrintenvLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (name === "null") {
- if (inlineValue !== undefined) throw new UsageError("option '--null' doesn't allow an argument", true);
- sep = "\0";
- } else if (name === "help" || name === "version") {
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- } else {
- throw new UsageError(`unrecognized option '${arg}'`, true);
- }
- } else if (/^-0+$/.test(arg)) {
- sep = "\0";
- } else if (arg.startsWith("-0")) {
- throw new UsageError(`invalid option -- '${arg[2]}'`, true);
- } else if (arg.startsWith("-")) {
- throw new UsageError(`invalid option -- '${arg.slice(1, 2)}'`, true);
- } else {
- operands.push(arg);
- }
- }
- if (!operands.length) {
- writeEnvironment(process.env, sep);
- return 0;
- }
- let code = 0;
- for (const key of operands) {
- if (process.env[key] == null) code = 1;
- else stdout(`${process.env[key]}${sep}`);
- }
- return code;
-}
-
-function normalizePrintenvLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = PRINTENV_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-function writeEnvironment(env, sep) {
- for (const [key, value] of Object.entries(env).filter(([key]) => key !== "_" && key !== "PWD").sort(([a], [b]) => a.localeCompare(b))) stdout(encodeEnvironmentEntry(`${key}=${value}${sep}`));
-}
-
-function encodeEnvironmentEntry(entry) {
- if (!/[\u00A0\uFFFD\uDC80-\uDCFF]/.test(entry)) return entry;
- const parts = [];
- let text = "";
- for (let i = 0; i < entry.length; i++) {
- const code = entry.charCodeAt(i);
- const raw = code === 0x00a0 || code === 0xfffd ? 0xa0 : code >= 0xdc80 && code <= 0xdcff ? code & 0xff : null;
- if (raw == null) {
- text += entry[i];
- continue;
- }
- if (text) {
- parts.push(Buffer.from(text));
- text = "";
- }
- parts.push(Buffer.from([raw]));
- }
- if (text) parts.push(Buffer.from(text));
- return Buffer.concat(parts);
-}
-
-async function booleanCommand(program, args, code) {
- if (args.length === 1 && args[0] === "--help") {
- showBooleanHelp(program, code);
- return code;
- }
- if (args.length === 1 && args[0] === "--version") {
- stdout(`${VERSION}\n`);
- return code;
- }
- return code;
-}
-
-function showBooleanHelp(program, code) {
- stdout(`Usage: ${program} [ignored command line arguments]\n`);
- stdout(` or: ${program} OPTION\n`);
- stdout(`Exit with a status code indicating ${code === 0 ? "success" : "failure"}.\n\n`);
- stdout(" --help display this help and exit\n");
- stdout(" --version output version information and exit\n");
-}
-
-async function env(args) {
- const originalEnv = { ...process.env };
- const childEnv = { ...process.env };
- const command = [];
- let cwd = process.cwd();
- let sep = "\n";
- let argv0;
- let verbose = false;
- let nullOutput = false;
- let sawChdir = false;
- let sawAssignment = false;
- let parseEnvOptions = true;
- let listSignalHandling = false;
- const signalActions = new Map();
- const requireValue = (index, option) => {
- if (index + 1 < args.length) return args[index + 1];
- if (option.startsWith("--")) throw new InvocationError(`option '${option}' requires an argument`);
- throw new InvocationError(`option requires an argument -- '${option.slice(1)}'`);
- };
- for (let i = 0; i < args.length; i++) {
- const rawArg = args[i];
- const arg = parseEnvOptions && rawArg !== "--" && rawArg.startsWith("--") ? normalizeInvocationLongOptionByPrefix(rawArg, ENV_LONG_OPTIONS) : rawArg;
- if (parseEnvOptions && sawAssignment && !arg.includes("=")) {
- command.push(...args.slice(i));
- break;
- } else if (parseEnvOptions && (arg === "-" || arg === "-i" || arg === "--ignore-environment")) {
- for (const key of Object.keys(childEnv)) delete childEnv[key];
- } else if (parseEnvOptions && arg === "--") {
- if (sawAssignment) {
- command.push(...args.slice(i));
- break;
- }
- parseEnvOptions = false;
- } else if (parseEnvOptions && (arg === "-a" || arg === "--argv0")) {
- argv0 = requireValue(i, arg);
- i++;
- } else if (parseEnvOptions && arg.startsWith("-a") && arg !== "-a") {
- argv0 = arg.slice(2);
- } else if (parseEnvOptions && arg.startsWith("--argv0=")) {
- argv0 = arg.slice("--argv0=".length);
- } else if (parseEnvOptions && (arg === "-0" || arg === "--null")) {
- sep = "\0";
- nullOutput = true;
- } else if (parseEnvOptions && (arg === "-v" || arg === "--debug")) {
- verbose = true;
- } else if (parseEnvOptions && (arg === "-u" || arg === "--unset")) {
- const name = requireValue(i, arg);
- i++;
- validateEnvUnsetName(name);
- delete childEnv[name];
- } else if (parseEnvOptions && arg.startsWith("-u") && arg !== "-u") {
- const name = arg.slice(2);
- validateEnvUnsetName(name);
- delete childEnv[name];
- } else if (parseEnvOptions && arg.startsWith("--unset=")) {
- const name = arg.slice("--unset=".length);
- validateEnvUnsetName(name);
- delete childEnv[name];
- } else if (parseEnvOptions && (arg === "-C" || arg === "--chdir")) {
- cwd = requireValue(i, arg);
- i++;
- sawChdir = true;
- } else if (parseEnvOptions && arg.startsWith("-C") && arg !== "-C") {
- cwd = arg.slice(2);
- sawChdir = true;
- } else if (parseEnvOptions && arg.startsWith("--chdir=")) {
- cwd = arg.slice("--chdir=".length);
- sawChdir = true;
- } else if (parseEnvOptions && (arg === "-S" || arg === "--split-string")) {
- args.splice(i + 1, 1, ...splitEnvString(requireValue(i, arg), originalEnv));
- } else if (parseEnvOptions && arg.startsWith("-S") && arg !== "-S") {
- args.splice(i, 1, ...splitEnvString(arg.slice(2), originalEnv));
- i--;
- } else if (parseEnvOptions && arg.startsWith("-vS")) {
- verbose = true;
- args.splice(i, 1, ...splitEnvString(arg.slice(3), originalEnv));
- i--;
- } else if (parseEnvOptions && arg.startsWith("-v") && /\s/.test(arg[2] ?? "")) {
- throw new InvocationError(`invalid option -- '${arg[2]}'\nenv: use -[v]S to pass options in shebang lines`);
- } else if (parseEnvOptions && arg.startsWith("--split-string=")) {
- args.splice(i, 1, ...splitEnvString(arg.slice("--split-string=".length), originalEnv));
- i--;
- } else if (parseEnvOptions && (arg === "--default-signal" || arg === "--ignore-signal" || arg === "--block-signal")) {
- applyEnvSignalOption(signalActions, arg.slice(2), "");
- } else if (parseEnvOptions && arg.startsWith("--default-signal=")) {
- applyEnvSignalOption(signalActions, "default-signal", arg.slice("--default-signal=".length));
- } else if (parseEnvOptions && arg.startsWith("--ignore-signal=")) {
- applyEnvSignalOption(signalActions, "ignore-signal", arg.slice("--ignore-signal=".length));
- } else if (parseEnvOptions && arg.startsWith("--block-signal=")) {
- applyEnvSignalOption(signalActions, "block-signal", arg.slice("--block-signal=".length));
- } else if (parseEnvOptions && arg === "--list-signal-handling") {
- listSignalHandling = true;
- } else if (parseEnvOptions && arg.startsWith("-")) {
- throw new InvocationError(invalidOptionMessage(arg));
- } else if (arg.includes("=") && command.length === 0) {
- const idx = arg.indexOf("=");
- childEnv[arg.slice(0, idx)] = arg.slice(idx + 1);
- sawAssignment = true;
- } else {
- command.push(...args.slice(i));
- break;
- }
- }
- if (!command.length) {
- if (sawChdir) throw new InvocationError("must specify command with --chdir (-C)");
- writeEnvironment(childEnv, sep);
- return 0;
- }
- if (nullOutput) throw new InvocationError("cannot specify --null (-0) with command");
- if (sawChdir && !(await stat(cwd).catch(() => null))?.isDirectory()) throw new InvocationError(`cannot change directory to ${shellEscapeLsName(pathDisplayName(cwd), true)}: No such file or directory`, 125, false);
- if (command.length === 1 && pathBasename(command[0]) === "env") {
- writeEnvironment(childEnv, "\n");
- return 0;
- }
- if (verbose) {
- try {
- if (argv0 != null) stderr(`argv0: '${argv0}'\n`);
- stderr(`executing: ${command[0]}\n`);
- if (argv0 != null) stderr(` arg[0]= '${argv0}'\n`);
- } catch {}
- }
- if (listSignalHandling) writeEnvSignalHandling(signalActions);
- applyEnvSignalEnvironment(childEnv, signalActions);
- const signalRestorers = applyEnvSignalActions(signalActions);
- try {
- const executable = await resolveEnvCommand(command[0], childEnv, cwd);
- if (isDirectCommandInvocation()) {
- if (sawChdir) changeDirectory(cwd);
- const execError = execCommand(command, { executable, env: childEnv, argv0 });
- const error = new Error(execError.message);
- error.code = execError.errno === 2 ? "ENOENT" : execError.errno === 13 ? "EACCES" : "EIO";
- throw error;
- }
- const proc = Bun.spawn([executable, ...command.slice(1)], { cwd, env: childEnv, stdin: "inherit", stdout: "inherit", stderr: "inherit", ...(argv0 != null ? { argv0 } : {}) });
- const signalHandlers = installChildSignalForwarders(proc, signalActions);
- try {
- return await proc.exited;
- } finally {
- removeChildSignalForwarders(signalHandlers);
- restoreEnvSignalActions(signalRestorers);
- }
- } catch (error) {
- restoreEnvSignalActions(signalRestorers);
- const message = error?.code === "ENOENT" ? `No such file or directory` : error?.code === "EACCES" ? "Permission denied" : error?.message || String(error);
- const needsShebangHint = /\s/.test(command[0]);
- stderr(`env: '${command[0]}': ${message}\n`);
- if (needsShebangHint) stderr("env: use -[v]S to pass options in shebang lines\n");
- return error?.code === "ENOENT" ? 127 : 126;
- }
-}
-
-function applyEnvSignalOption(actions, option, value) {
- const action = option === "ignore-signal" ? "ignore" : option === "default-signal" ? "default" : "block";
- for (const signum of expandEnvSignalOperand(value)) actions.set(signum, action);
-}
-
-function expandEnvSignalOperand(value) {
- if (value == null || value === "") return envSignalNumbers();
- const signals = [];
- for (const part of String(value).split(",")) {
- const signum = signalNumberFromOperand(part);
- if (signum <= 0) throw new InvocationError(`'${part}': invalid signal`, 125, true);
- signals.push(signum);
- }
- return signals;
-}
-
-function envSignalNumbers() {
- const signals = [];
- for (let i = 1; i < SIGNAL_NAMES.length; i++) {
- if (i !== 9 && i !== 19 && i !== 30) signals.push(i);
- }
- signals.push(34, 64);
- return signals;
-}
-
-function writeEnvSignalHandling(actions) {
- for (const [signum, action] of actions) {
- if (action === "ignore") stderr(`${signalDisplayName(signum)}: IGNORE\n`);
- }
-}
-
-function applyEnvSignalEnvironment(childEnv, actions) {
- if (actions.get(signalNumberFromOperand("PIPE")) === "default") childEnv[BNU_SIGPIPE_DEFAULT_ENV] = "1";
-}
-
-function applyEnvSignalActions(actions) {
- const restorers = [];
- for (const [signum, action] of actions) {
- if (action === "block") continue;
- const handler = action === "ignore" ? SIG_IGN : SIG_DFL;
- const previous = libc.symbols.signal(signum, handler);
- restorers.push([signum, previous]);
- }
- return restorers;
-}
-
-function restoreEnvSignalActions(restorers) {
- for (let i = restorers.length - 1; i >= 0; i--) {
- const [signum, previous] = restorers[i];
- libc.symbols.signal(signum, previous);
- }
-}
-
-function installChildSignalForwarders(proc, signalActions = new Map()) {
- const handlers = [];
- const forwardSignals = [
- "SIGHUP", "SIGINT", "SIGQUIT", "SIGTERM", "SIGALRM", "SIGUSR1", "SIGUSR2",
- "SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGIO", "SIGPWR", "SIGSYS",
- ];
- for (const signal of forwardSignals) {
- const signum = signalNumber(signal);
- if (signalActions.get(signum) === "ignore") continue;
- const handler = () => {
- proc.kill(signal);
- };
- try {
- process.on(signal, handler);
- handlers.push([signal, handler]);
- } catch {}
- }
- return handlers;
-}
-
-function removeChildSignalForwarders(handlers) {
- for (const [signal, handler] of handlers) process.off(signal, handler);
-}
-
-function signalNumber(signal) {
- return signalNumberFromOperand(signal);
-}
-
-async function resolveEnvCommand(command, env, cwd) {
- const searchPath = Object.hasOwn(env, "PATH") ? String(env.PATH) : "/bin:/usr/bin";
- const candidates = command.includes("/") ? [command] : searchPath.split(":").map((dir) => join(dir || ".", command));
- for (const candidate of candidates) {
- const full = isAbsolute(candidate) ? candidate : join(cwd, candidate);
- const s = await stat(full).catch(() => null);
- if (!s) continue;
- if (s.isDirectory()) {
- const error = new Error("Permission denied");
- error.code = "EACCES";
- throw error;
- }
- await access(full, fsConstants.X_OK).catch((error) => {
- error.code = "EACCES";
- throw error;
- });
- return command.includes("/") ? candidate : full;
- }
- const error = new Error("No such file or directory");
- error.code = "ENOENT";
- throw error;
-}
-
-function validateEnvUnsetName(name) {
- if (name == null) throw new InvocationError("option requires an argument -- 'u'");
- if (name === "" || name.includes("=")) throw new InvocationError(`cannot unset ${localeQuotedEscapedDiagnostic(name)}: Invalid argument`, 125, false);
-}
-
-function splitEnvString(value, env = process.env) {
- const out = [];
- let current = "";
- let started = false;
- let quote = null;
- const text = String(value);
- for (let i = 0; i < text.length; i++) {
- const ch = text[i];
- if (quote === "'") {
- if (ch === "'") quote = null;
- else if (ch === "\\" && (text[i + 1] === "\\" || text[i + 1] === "'")) current += text[++i];
- else current += ch;
- started = true;
- } else if (quote === "\"") {
- if (ch === "\"") {
- quote = null;
- started = true;
- } else if (ch === "\\") {
- const parsed = parseEnvEscape(text, i, true);
- if (parsed.stop) throw new InvocationError("'\\c' must not appear in double-quoted -S string", 125, false);
- current += parsed.value;
- started = true;
- i = parsed.index;
- } else if (ch === "$") {
- const expanded = expandEnvSplitVariable(text, i, env);
- current += expanded.value;
- started = true;
- i = expanded.index;
- } else {
- current += ch;
- started = true;
- }
- } else if (ch === "'" || ch === "\"") {
- quote = ch;
- started = true;
- } else if (ch === "#") {
- if (!started) break;
- current += ch;
- started = true;
- } else if (/\s/.test(ch)) {
- if (started) {
- out.push(current);
- current = "";
- started = false;
- }
- } else if (ch === "\\") {
- const parsed = parseEnvEscape(text, i, false);
- if (parsed.stop) break;
- if (parsed.separator) {
- if (started) {
- out.push(current);
- current = "";
- started = false;
- }
- } else {
- current += parsed.value;
- started = true;
- }
- i = parsed.index;
- } else if (ch === "$") {
- const expanded = expandEnvSplitVariable(text, i, env);
- current += expanded.value;
- started = true;
- i = expanded.index;
- } else {
- current += ch;
- started = true;
- }
- }
- if (quote) throw new InvocationError("no terminating quote in -S string", 125, false);
- if (started) out.push(current);
- return out;
-}
-
-function parseEnvEscape(text, index, doubleQuoted) {
- if (index + 1 >= text.length) throw new InvocationError("invalid backslash at end of string in -S", 125, false);
- const ch = text[index + 1];
- if (ch === "c") return { stop: true, index: index + 1 };
- if (ch === "_") return doubleQuoted ? { value: " ", index: index + 1 } : { separator: true, index: index + 1 };
- const escapes = { n: "\n", r: "\r", t: "\t", f: "\f", v: "\v", "\\": "\\", "\"": "\"", "'": "'", "$": "$", "#": "#" };
- if (escapes[ch] == null) throw new InvocationError(`invalid sequence '\\${ch}' in -S`, 125, false);
- return { value: escapes[ch], index: index + 1 };
-}
-
-function expandEnvSplitVariable(text, index, env) {
- if (text[index + 1] !== "{") throw new InvocationError(`only \${VARNAME} expansion is supported, error at: ${text.slice(index)}`, 125, false);
- const end = text.indexOf("}", index + 2);
- if (end === -1) throw new InvocationError(`only \${VARNAME} expansion is supported, error at: ${text.slice(index)}`, 125, false);
- const name = text.slice(index + 2, end);
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new InvocationError(`only \${VARNAME} expansion is supported, error at: ${text.slice(index, end + 1)}`, 125, false);
- return { value: env[name] ?? "", index: end };
-}
-
-async function sleep(args) {
- const meta = sleepMetaOption(args);
- if (meta === "--help") {
- showSleepHelp();
- return 0;
- }
- if (meta === "--version") {
- stdout(`${VERSION}\n`);
- return 0;
- }
- validateSleepOptions(args);
- if (!args.length) throw new UsageError("missing operand", true);
- if (args[0] === "--") {
- args = args.slice(1);
- if (!args.length) return 0;
- }
- let total = 0;
- for (const value of args) {
- try {
- total += parseDuration(value);
- } catch (error) {
- if (error instanceof InvocationError) throw new UsageError(error.message, true);
- throw error;
- }
- }
- if (!Number.isFinite(total) || total > 2147483647) await new Promise(() => {});
- await Bun.sleep(total);
- return 0;
-}
-
-function sleepMetaOption(args) {
- for (const arg of args) {
- if (arg === "--") return null;
- if (!arg.startsWith("-") || arg === "-") continue;
- if (!arg.startsWith("--")) return null;
- const option = normalizeSleepLongOption(arg);
- const name = option.slice(2).split("=", 1)[0];
- if (!SLEEP_LONG_OPTIONS.includes(name) || option.includes("=")) return null;
- return option;
- }
- return null;
-}
-
-function validateSleepOptions(args) {
- let end = false;
- for (const arg of args) {
- if (end) continue;
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg === "-" || !arg.startsWith("-")) continue;
- if (!arg.startsWith("--")) throw new UsageError(sleepInvalidOptionMessage(arg), true);
- const option = normalizeSleepLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!SLEEP_LONG_OPTIONS.includes(name)) throw new UsageError(`unrecognized option '${arg}'`, true);
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- }
-}
-
-function normalizeSleepLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const match = SLEEP_LONG_OPTIONS.find((option) => option.startsWith(name));
- if (!match) return arg;
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-function showSleepHelp() {
- stdout("Usage: sleep NUMBER[SUFFIX]...\n");
- stdout(" or: sleep OPTION\n");
- stdout("Pause for NUMBER seconds, where NUMBER is an integer or floating-point.\n");
- stdout("SUFFIX may be 's','m','h', or 'd', for seconds, minutes, hours, days.\n");
- stdout("With multiple arguments, pause for the sum of their values.\n\n");
- stdout(" --help display this help and exit\n");
- stdout(" --version output version information and exit\n");
-}
-
-function sleepInvalidOptionMessage(arg) {
- return arg.startsWith("--") ? `unrecognized option '${arg}'` : invalidOptionMessage(arg);
-}
-
-async function tee(args) {
- const { opts, operands } = parseOptions(normalizeTeeLongOptions(args), { short: { a: false, i: false, p: false }, long: { append: false, "ignore-interrupts": false, "output-error": "optional-value", help: false, version: false } });
- const mode = validateTeeOutputError(opts);
- const targets = [{ name: "standard output", stdout: true, active: true }];
- let status = 0;
- for (const file of operands) {
- try {
- targets.push({ name: file, handle: await open(file, opts.a || opts.append ? "a" : "w"), active: true });
- } catch (error) {
- status = 1;
- stderr(`tee: ${textInputDiagnosticName(file)}: ${systemErrorMessage(error)}\n`);
- if (mode === "exit" || mode === "exit-nopipe") return 1;
- }
- }
-
- const buffer = Buffer.allocUnsafe(64 * 1024);
- try {
- while (targets.some((target) => target.active)) {
- const stdoutTarget = targets.find((target) => target.stdout && target.active);
- if (stdoutTarget && (pollFd(1, POLLOUT) & (POLLERR | POLLHUP | POLLNVAL))) {
- const result = handleTeeTargetError(stdoutTarget, Object.assign(new Error("broken pipe"), { code: "EPIPE" }), mode);
- stdoutTarget.active = false;
- if (result.status) status = result.status;
- if (result.exit) return result.status;
- if (!targets.some((target) => target.active)) return result.status;
- }
- let n;
- try {
- n = readSync(0, buffer, 0, buffer.length, null);
- if (n === 0) break;
- } catch (error) {
- stderr(`tee: read error: ${systemErrorMessage(error)}\n`);
- return 1;
- }
- const chunk = buffer.subarray(0, n);
- for (const target of targets) {
- if (!target.active) continue;
- const result = await writeTeeTarget(target, chunk, mode);
- if (result === "ok") continue;
- target.active = false;
- if (result.status) status = result.status;
- if (result.exit) return result.status;
- if (target.stdout && !targets.some((target) => target.active)) return result.status;
- }
- }
- } finally {
- for (const target of targets) await target.handle?.close().catch(() => {});
- }
- return status;
-}
-
-function validateTeeOutputError(opts) {
- if (opts["output-error"] == null) return opts.p ? "warn-nopipe" : "default";
- const mode = opts["output-error"] === true ? "warn-nopipe" : opts["output-error"];
- if (!["warn", "warn-nopipe", "exit", "exit-nopipe"].includes(mode)) {
- const kind = mode === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(mode)} for ${localeQuotedDiagnostic("--output-error")}\nValid arguments are:\n - ${localeQuotedDiagnostic("warn")}\n - ${localeQuotedDiagnostic("warn-nopipe")}\n - ${localeQuotedDiagnostic("exit")}\n - ${localeQuotedDiagnostic("exit-nopipe")}`, true);
- }
- return mode;
-}
-
-async function writeTeeTarget(target, chunk, mode) {
- try {
- if (target.stdout) writeSync(1, chunk);
- else await target.handle.write(chunk);
- return "ok";
- } catch (error) {
- return handleTeeTargetError(target, error, mode);
- }
-}
-
-function handleTeeTargetError(target, error, mode) {
- const isPipe = error?.code === "EPIPE";
- const warn = mode === "warn" || mode === "exit" || (!isPipe && mode !== "default");
- const exit = mode === "exit" || (!isPipe && mode === "exit-nopipe");
- const status = isPipe && (mode === "default" || mode === "warn-nopipe" || mode === "exit-nopipe") ? 0 : 1;
- if (warn || (!isPipe && mode === "default")) {
- const name = target.stdout ? target.name : textInputDiagnosticName(target.name);
- stderr(`tee: ${name}: ${systemErrorMessage(error)}\n`);
- }
- return { status, exit };
-}
-
-function pollFd(fd, events, timeout = 0) {
- const pollfd = Buffer.alloc(8);
- pollfd.writeInt32LE(fd, 0);
- pollfd.writeInt16LE(events, 4);
- if (libc.symbols.poll(pollfd, 1n, timeout) <= 0) return 0;
- return pollfd.readInt16LE(6);
-}
-
-async function touch(args) {
- args = normalizeTouchLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { a: false, c: false, d: "value", f: false, h: false, m: false, r: "value", t: "value" }, long: { "time": "value", "no-create": false, "no-dereference": false, date: "value", reference: "value", help: false, version: false } });
- const rawOperands = rawOperandPlan("touch", args, operands, {
- valueOptions: ["--time", "--date", "--reference", "--ref"],
- shortValueOptions: ["d", "r", "t"],
- });
- if (process.env.POSIXLY_CORRECT && opts.t == null && opts.d == null && opts.date == null && opts.r == null && opts.reference == null && operands.length > 1 && isValidTouchTimestamp(operands[0])) {
- opts.t = operands.shift();
- rawOperands?.shift();
- }
- const noDereference = opts.h || opts["no-dereference"];
- const timeMode = normalizeTouchTime(opts.time);
- if (opts.t != null) parseTouchTimestamp(opts.t);
- if (opts.t != null && (opts.d != null || opts.date != null || opts.r != null || opts.reference != null)) {
- throw new UsageError("cannot specify times from more than one source", true);
- }
- const sourceTimes = await touchTimes(opts, noDereference);
- if (!operands.length) throw new UsageError("missing file operand", true);
- const changeAccess = opts.a || !(opts.m || timeMode === "modify");
- const changeModify = opts.m || !(opts.a || timeMode === "access");
- const statFn = noDereference ? lstat : stat;
- let status = 0;
- for (let i = 0; i < operands.length; i++) {
- const file = rawOperands?.[i] ?? operands[i];
- try {
- if (file === "-") {
- const fd = noDereference ? 1 : 0;
- const s = fstatSync(fd);
- try {
- await futimes(fd, changeAccess ? sourceTimes.atime : s.atime, changeModify ? sourceTimes.mtime : s.mtime);
- } catch (error) {
- stderr(`touch: setting times of ${noDereference ? "standard output" : "standard input"}: ${touchErrorMessage(error)}\n`);
- status = 1;
- }
- continue;
- }
- const s = statAttachNanoseconds(await statFn(file), file, !noDereference);
- try {
- await touchSetPathTimes(file, changeAccess ? (sourceTimes.now ? TOUCH_NOW : sourceTimes.atime) : TOUCH_OMIT, changeModify ? (sourceTimes.now ? TOUCH_NOW : sourceTimes.mtime) : TOUCH_OMIT, noDereference);
- } catch (error) {
- stderr(`touch: setting times of ${touchDiagnosticName(file)}: ${touchErrorMessage(error)}\n`);
- status = 1;
- }
- } catch (error) {
- if (file === "-" && noDereference && (opts.c || opts["no-create"])) {
- continue;
- } else if (error.code === "ENOENT" && noDereference && !(opts.c || opts["no-create"])) {
- stderr(`touch: setting times of ${touchDiagnosticName(file)}: ${touchErrorMessage(error)}\n`);
- status = 1;
- } else if (touchShouldReportSettingTimeError(file, opts, error)) {
- stderr(`touch: setting times of ${touchDiagnosticName(file)}: ${touchErrorMessage(error)}\n`);
- status = 1;
- } else if (error.code === "ENOENT" && !(opts.c || opts["no-create"]) && !noDereference) {
- try {
- await writeFile(file, "");
- await touchSetPathTimes(file, sourceTimes.atime, sourceTimes.mtime, false);
- } catch (createError) {
- stderr(`touch: cannot touch ${touchDiagnosticName(file)}: ${touchErrorMessage(createError)}\n`);
- status = 1;
- }
- } else if (error.code === "ENOENT" && (opts.c || opts["no-create"])) {
- continue;
- } else {
- stderr(`touch: cannot touch ${touchDiagnosticName(file)}: ${touchErrorMessage(error)}\n`);
- status = 1;
- }
- }
- }
- return status;
-}
-
-function touchShouldReportSettingTimeError(file, opts, error) {
- const noCreate = opts.c || opts["no-create"];
- const trailingSlash = hasTrailingNonRootSlash(file);
- if (error?.code === "ENOTDIR") return noCreate || trailingSlash;
- if (error?.code === "ENOENT") return trailingSlash && !noCreate;
- return false;
-}
-
-function touchDiagnosticName(file) {
- return shellEscapeLsName(pathDisplayName(file), true);
-}
-
-function hasTrailingNonRootSlash(file) {
- return String(file).endsWith("/") && String(file).replace(/\/+$/g, "") !== "";
-}
-
-function normalizeTouchLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, TOUCH_LONG_OPTIONS);
-}
-
-function normalizeTouchLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, TOUCH_LONG_OPTIONS);
-}
-
-function normalizeTouchTime(value) {
- if (value == null) return null;
- if (value === "") throw new UsageError(`ambiguous argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic("--time")}\nValid arguments are:\n - ${["atime", "access", "use"].map(localeQuotedDiagnostic).join(", ")}\n - ${["mtime", "modify"].map(localeQuotedDiagnostic).join(", ")}`, true);
- const accessValues = ["atime", "access", "use"];
- const modifyValues = ["mtime", "modify"];
- if (accessValues.some((candidate) => candidate.startsWith(value))) return "access";
- if (modifyValues.some((candidate) => candidate.startsWith(value))) return "modify";
- throw new UsageError(`invalid argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic("--time")}\nValid arguments are:\n - ${["atime", "access", "use"].map(localeQuotedDiagnostic).join(", ")}\n - ${["mtime", "modify"].map(localeQuotedDiagnostic).join(", ")}`, true);
-}
-
-async function touchTimes(opts, noDereference = false) {
- const dateSpec = opts.d ?? opts.date;
- if (opts.r != null || opts.reference != null) {
- const reference = opts.r ?? opts.reference;
- let baseStat;
- try {
- baseStat = statAttachNanoseconds(await (noDereference ? lstat : stat)(reference), reference, !noDereference);
- } catch (error) {
- throw new UsageError(`failed to get attributes of ${touchDiagnosticName(reference)}: ${touchErrorMessage(error)}`);
- }
- const base = touchStatDate(baseStat, "mtime");
- if (dateSpec == null) return { atime: touchStatDate(baseStat, "atime"), mtime: base };
- const date = parseTouchDateRelativeTo(dateSpec, base);
- return { atime: date, mtime: date };
- }
- if (dateSpec) {
- const date = parseDateInput(dateSpec);
- if (Number.isNaN(date.getTime())) throw new UsageError(`invalid date format ${localeQuotedEscapedDiagnostic(dateSpec)}`);
- return { atime: date, mtime: date, now: /^\s*now\s*$/i.test(dateSpec) };
- }
- if (opts.t) {
- const date = parseTouchTimestamp(opts.t);
- return { atime: date, mtime: date };
- }
- const now = new Date();
- return { atime: now, mtime: now, now: true };
-}
-
-const TOUCH_NOW = Symbol("touch-now");
-const TOUCH_OMIT = Symbol("touch-omit");
-
-function touchStatDate(statInfo, field) {
- const date = statInfo[field];
- const value = statInfo[`${field}Ns`];
- return value == null ? date : attachDateNanoseconds(date, Number(((BigInt(value) % 1_000_000_000n) + 1_000_000_000n) % 1_000_000_000n));
-}
-
-async function touchSetPathTimes(path, atime, mtime, noDereference) {
- if (touchSetPathTimesNative(path, atime, mtime, noDereference)) return;
- if (atime === TOUCH_NOW || atime === TOUCH_OMIT || mtime === TOUCH_NOW || mtime === TOUCH_OMIT) {
- const errno = libcErrno();
- const error = new Error(`utimensat failed (errno ${errno})`);
- error.code = ({
- 1: "EPERM",
- 2: "ENOENT",
- 5: "EIO",
- 9: "EBADF",
- 13: "EACCES",
- 20: "ENOTDIR",
- 21: "EISDIR",
- 22: "EINVAL",
- 28: "ENOSPC",
- 30: "EROFS",
- 36: "ENAMETOOLONG",
- 40: "ELOOP",
- })[errno] ?? "EIO";
- throw error;
- }
- return (noDereference ? lutimes : utimes)(path, atime, mtime);
-}
-
-function touchSetPathTimesNative(path, atime, mtime, noDereference) {
- const times = Buffer.alloc(32);
- writeTimespec(times, 0, atime);
- writeTimespec(times, 16, mtime);
- return libc.symbols.utimensat(AT_FDCWD, cstrPath(path), times, noDereference ? AT_SYMLINK_NOFOLLOW : 0) === 0;
-}
-
-function writeTimespec(buffer, offset, date) {
- if (date === TOUCH_NOW || date === TOUCH_OMIT) {
- buffer.writeBigInt64LE(0n, offset);
- buffer.writeBigInt64LE(BigInt(date === TOUCH_NOW ? 1_073_741_823 : 1_073_741_822), offset + 8);
- return;
- }
- const total = dateAbsoluteNanoseconds(date);
- const sec = floorDivBigInt(total, 1_000_000_000n);
- const nsec = ((total % 1_000_000_000n) + 1_000_000_000n) % 1_000_000_000n;
- buffer.writeBigInt64LE(sec, offset);
- buffer.writeBigInt64LE(nsec, offset + 8);
-}
-
-function libcErrno() {
- const errnoPointer = libc.symbols.__errno_location();
- return errnoPointer ? read.i32(errnoPointer, 0) : 0;
-}
-
-function dateAbsoluteNanoseconds(date) {
- const milliseconds = BigInt(date.getTime());
- const seconds = floorDivBigInt(milliseconds, 1000n);
- const millisecondFraction = Number(((milliseconds % 1000n) + 1000n) % 1000n);
- const nanoseconds = BigInt(date.__bnuNanoseconds ?? millisecondFraction * 1_000_000);
- return seconds * 1_000_000_000n + nanoseconds;
-}
-
-function parseTouchDateRelativeTo(spec, base) {
- const relative = parseRelativeDateSpec(spec, base);
- if (relative) return relative;
- const date = parseDateInput(spec);
- if (Number.isNaN(date.getTime())) throw new UsageError(`invalid date '${spec}'`);
- return date;
-}
-
-function parseRelativeDateSpec(spec, base, utc = false) {
- const match = String(spec).trim().match(/^([+-]?\s*\d+(?:\.\d+)?)\s+(secs?|seconds?|mins?|minutes?|hours?|days?|weeks?|months?|years?)(?:\s+(ago))?$/i);
- if (!match) return null;
- const amountText = match[1].replace(/\s+/g, "");
- const amount = Number(amountText) * (match[3] ? -1 : 1);
- const unit = normalizeDateRelativeUnit(match[2]);
- return applyDateRelative(base, amount, unit, amountText, match[3] ? -1 : 1, utc);
-}
-
-function normalizeDateRelativeUnit(unitText) {
- const unit = unitText.toLowerCase().replace(/s$/, "");
- if (unit === "sec") return "second";
- if (unit === "min") return "minute";
- return unit;
-}
-
-function applyDateRelative(base, amount, unit, amountText = String(amount), direction = 1, utc = false) {
- if (unit === "month" || unit === "year") {
- const next = new Date(base);
- if (unit === "month") utc ? next.setUTCMonth(next.getUTCMonth() + amount) : next.setMonth(next.getMonth() + amount);
- else utc ? next.setUTCFullYear(next.getUTCFullYear() + amount) : next.setFullYear(next.getFullYear() + amount);
- if (!utc && base.__bnuLocalZoneAbbrev && base.__bnuLocalOffsetSeconds != null) {
- const offsetDelta = localOffsetSeconds(next) - base.__bnuLocalOffsetSeconds;
- if (offsetDelta) next.setTime(next.getTime() + offsetDelta * 1000);
- }
- return next;
- }
- const seconds = { second: 1, minute: 60, hour: 3600, day: 86400, week: 604800 }[unit];
- const deltaNanoseconds = decimalSecondsToNanoseconds(amountText, seconds) * BigInt(direction);
- const baseNanoseconds = BigInt(base.getTime()) * 1_000_000n + BigInt((base.__bnuNanoseconds ?? base.getMilliseconds() * 1_000_000) - base.getMilliseconds() * 1_000_000);
- const totalNanoseconds = baseNanoseconds + deltaNanoseconds;
- const milliseconds = floorDivBigInt(totalNanoseconds, 1_000_000n);
- const nanoseconds = Number(((totalNanoseconds % 1_000_000_000n) + 1_000_000_000n) % 1_000_000_000n);
- return attachDateNanoseconds(new Date(Number(milliseconds)), nanoseconds);
-}
-
-function floorDivBigInt(value, divisor) {
- const quotient = value / divisor;
- return value >= 0n || value % divisor === 0n ? quotient : quotient - 1n;
-}
-
-function decimalSecondsToNanoseconds(amountText, unitSeconds) {
- const text = String(amountText);
- const sign = text.startsWith("-") ? -1n : 1n;
- const unsigned = text.replace(/^[+-]/, "");
- const [wholeText, fractionText = ""] = unsigned.split(".");
- const whole = BigInt(wholeText || "0") * BigInt(unitSeconds) * 1_000_000_000n;
- const fraction = BigInt(fractionText.padEnd(9, "0").slice(0, 9) || "0") * BigInt(unitSeconds);
- return sign * (whole + fraction);
-}
-
-function parseAbsoluteRelativeDateSpec(spec, utc = false) {
- const text = String(spec).trim();
- const keyword = text.match(/^(.+?)\s+(now|yesterday|tomorrow|this\s+(?:secs?|seconds?|mins?|minutes?|hours?|days?|weeks?|months?|years?)|next\s+(?:secs?|seconds?|mins?|minutes?|hours?|days?|weeks?|months?|years?))$/i);
- if (keyword) {
- const base = parseDateInput(keyword[1], utc, false);
- if (Number.isNaN(base.getTime())) return null;
- const suffix = keyword[2].toLowerCase();
- if (suffix === "now") return base;
- if (suffix === "yesterday") return applyDateRelative(base, -1, "day", "1", -1, utc);
- if (suffix === "tomorrow") return applyDateRelative(base, 1, "day", "1", 1, utc);
- const [, direction, unitText] = suffix.match(/^(this|next)\s+(.+)$/);
- return direction === "this" ? base : applyDateRelative(base, 1, normalizeDateRelativeUnit(unitText), "1", 1, utc);
- }
- const match = text.match(/^(.+?)\s+([+-]?\s*\d+(?:\.\d+)?\s+(?:secs?|seconds?|mins?|minutes?|hours?|days?|weeks?|months?|years?)(?:\s+ago)?)$/i);
- if (!match) return null;
- const base = parseDateInput(match[1], utc, false);
- if (Number.isNaN(base.getTime())) return null;
- return parseRelativeDateSpec(match[2], base, utc);
-}
-
-function parseTimeTodayRelativeDateSpec(spec) {
- const match = String(spec).trim().match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?\s+today\s+([+-]\d+)\s+(seconds?|minutes?|hours?|days?|weeks?|months?|years?)$/i);
- if (!match) return null;
- const [, hoursText, minutesText, secondsText, amountText, unitText] = match;
- const base = new Date();
- const hours = Number(hoursText);
- const minutes = Number(minutesText);
- const seconds = Number(secondsText ?? 0);
- if (hours > 23 || minutes > 59 || seconds > 60) return new Date(Number.NaN);
- base.setHours(hours, minutes, Math.min(seconds, 59), 0);
- if (seconds === 60) base.setSeconds(base.getSeconds() + 1);
- return parseRelativeDateSpec(`${amountText} ${unitText}`, base);
-}
-
-function parseTouchTimestamp(value) {
- const match = String(value).match(/^(\d{8}|\d{10}|\d{12})(?:\.(\d{2}))?$/);
- if (!match) throw new UsageError(`invalid date format ${localeQuotedEscapedDiagnostic(value)}`);
- const digits = match[1];
- const currentYear = new Date().getFullYear();
- const year = digits.length === 8 ? currentYear : digits.length === 10 ? Number(digits.slice(0, 2)) + (Number(digits.slice(0, 2)) >= 69 ? 1900 : 2000) : Number(digits.slice(0, 4));
- const rest = digits.length === 8 ? digits : digits.length === 10 ? digits.slice(2) : digits.slice(4);
- const month = Number(rest.slice(0, 2));
- const day = Number(rest.slice(2, 4));
- const hour = Number(rest.slice(4, 6));
- const second = Number((match[2] ?? "0").padEnd(2, "0"));
- let minute = Number(rest.slice(6, 8));
- const leapSecond = second === 60;
- const date = new Date(year, month - 1, day, hour, minute, leapSecond ? 59 : second);
- if (leapSecond) date.setSeconds(date.getSeconds() + 1);
- if (Number.isNaN(date.getTime()) || date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day || date.getHours() !== hour || date.getMinutes() !== minute + (leapSecond ? 1 : 0)) {
- throw new UsageError(`invalid date format ${localeQuotedEscapedDiagnostic(value)}`);
- }
- return date;
-}
-
-function isValidTouchTimestamp(value) {
- try {
- parseTouchTimestamp(value);
- return true;
- } catch {
- return false;
- }
-}
-
-function touchErrorMessage(error) {
- if (error?.code === "ENOENT") return "No such file or directory";
- if (error?.code === "ENOTDIR") return "Not a directory";
- if (error?.code === "EISDIR") return "Is a directory";
- if (error?.code === "ELOOP") return "Too many levels of symbolic links";
- if (error?.code === "EACCES") return "Permission denied";
- if (error?.code === "EPERM") return "Operation not permitted";
- if (error?.code === "EROFS") return "Read-only file system";
- return error?.message || String(error);
-}
-
-async function mkdirCmd(args) {
- args = normalizeMkdirLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { p: false, m: "value", v: false, Z: false }, long: { parents: false, mode: "value", verbose: false, context: "optional-value", help: false, version: false } });
- const securityContext = selinuxCreationOptions("mkdir", opts);
- if (!operands.length) throw new UsageError("missing operand", true);
- const rawOperands = rawOperandPlan("mkdir", args, operands, {
- valueOptions: ["--mode"],
- shortValueOptions: ["m"],
- });
- const mode = opts.m || opts.mode ? parseMkdirCreationMode(opts.m ?? opts.mode) : undefined;
- const parents = opts.p || opts.parents;
- await withSelinuxCreationContext("mkdir", securityContext, async (created, sameThread) => {
- for (let i = 0; i < operands.length; i++) {
- const dir = rawOperands?.[i] ?? operands[i];
- if (dir === "") throw new UsageError(`cannot create directory ${localeQuotedDiagnostic("")}: No such file or directory`);
- if (parents) await mkdirParents(dir, mode, opts.v || opts.verbose, created, sameThread);
- else {
- try {
- if (sameThread) mkdirSync(dir, { mode });
- else await mkdir(dir, { mode });
- } catch (error) {
- throw new UsageError(`cannot create directory ${mkdirDiagnosticName(dir)}: ${mkdirErrorMessage(error)}`);
- }
- if (mode !== undefined) await setFileMode(dir, mode);
- await created(dir);
- if (opts.v || opts.verbose) stdout(`mkdir: created directory ${mkdirVerboseName(dir)}\n`);
- }
- }
- });
- return 0;
-}
-
-function normalizeMkdirLongOptions(args) {
- const out = [];
- let end = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- const option = normalizeMkdirLongOption(arg);
- out.push(option);
- if (option === "--mode" && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-function normalizeMkdirLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = MKDIR_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length === 0) return arg;
- if (matches.length > 1) {
- throw new UsageError(`option '--${name}${eq === -1 ? "" : `=${body.slice(eq + 1)}`}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-function parseMkdirCreationMode(spec) {
- try {
- return parseCreationMode(spec);
- } catch (error) {
- const mode = error instanceof UsageError ? invalidModeDiagnosticValue(error.message) : null;
- if (mode != null) {
- throw new UsageError(`invalid mode ${localeQuotedDiagnostic(mode)}`, false);
- }
- throw error;
- }
-}
-
-function invalidModeDiagnosticValue(message) {
- return message.match(/^invalid mode: '(.+)'$/)?.[1]
- ?? message.match(/^invalid mode: \u2018(.+)\u2019$/)?.[1]
- ?? null;
-}
-
-function normalizeSpecialFileLongOptions(args) {
- const out = [];
- let end = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (end || arg === "--" || !arg.startsWith("--")) {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- const option = normalizeSpecialFileLongOption(arg);
- out.push(option);
- if (option === "--mode" && i + 1 < args.length) out.push(args[++i]);
- }
- return out;
-}
-
-function normalizeSpecialFileLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- const matches = SPECIAL_FILE_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length === 0) return arg;
- return eq === -1 ? `--${matches[0]}` : `--${matches[0]}=${body.slice(eq + 1)}`;
-}
-
-function parseSpecialFileCreationMode(spec) {
- try {
- return parseCreationMode(spec, 0o666);
- } catch (error) {
- if (error instanceof UsageError && invalidModeDiagnosticValue(error.message) != null) throw new UsageError("invalid mode", false);
- throw error;
- }
-}
-
-function rawOperandPlan(command, args, operands, spec = {}) {
- const raw = rawCommandArgs(command);
- if (!raw) return null;
- const rawOperands = parseRawOperands(raw, spec);
- if (rawOperands.length !== operands.length) return null;
- if (!rawOperands.some((operand, index) => rawPathNeedsBytes(operand) || !operand.equals(Buffer.from(operands[index])))) return null;
- return rawOperands;
-}
-
-function parseRawOperands(rawArgs, spec = {}) {
- const operands = [];
- const valueOptions = new Set(spec.valueOptions ?? []);
- const shortValueOptions = new Set(spec.shortValueOptions ?? []);
- for (let i = 0; i < rawArgs.length; i++) {
- const arg = rawArgs[i];
- if (arg.equals(Buffer.from("--"))) {
- operands.push(...rawArgs.slice(i + 1));
- break;
- }
- if (!rawArgLooksLikeOption(arg)) {
- operands.push(arg);
- continue;
- }
- const text = arg.toString();
- if (valueOptions.has(text)) {
- i++;
- continue;
- }
- if ([...valueOptions].some((option) => text.startsWith(`${option}=`))) continue;
- if (arg.length > 2 && arg[0] === 0x2d && arg[1] !== 0x2d) {
- const letters = arg.toString().slice(1);
- const valueIndex = [...letters].findIndex((ch) => shortValueOptions.has(ch));
- if (valueIndex !== -1 && valueIndex === letters.length - 1) i++;
- }
- }
- return operands;
-}
-
-async function mkdirParents(dir, mode, verbose, created = async () => {}, sameThread = false) {
- const absolute = isAbsolute(dir);
- const parts = String(dir).split("/").filter((part) => part !== "");
- let current = absolute ? "/" : "";
- for (let i = 0; i < parts.length; i++) {
- const part = parts[i];
- if (part === ".") continue;
- if (part === "..") {
- current = current ? pathDirname(current) : "..";
- continue;
- }
- current = current === "" || current === "/" ? `${current}${part}` : `${current}/${part}`;
- const isFinal = i === parts.length - 1 || parts.slice(i + 1).every((tail) => tail === ".");
- const createMode = isFinal ? mode : defaultDirectoryMode();
- try {
- if (sameThread) mkdirSync(current, { mode: createMode });
- else await mkdir(current, { mode: createMode });
- if (createMode !== undefined) await setFileMode(current, createMode);
- await created(current);
- if (verbose) stdout(`mkdir: created directory ${mkdirVerboseName(current)}\n`);
- } catch (error) {
- if (error?.code !== "EEXIST") throw new UsageError(`cannot create directory ${mkdirDiagnosticName(current)}: ${mkdirErrorMessage(error)}`);
- const s = await stat(current);
- if (!s.isDirectory()) throw new UsageError(`cannot create directory ${mkdirDiagnosticName(current)}: Not a directory`);
- }
- }
-}
-
-function mkdirVerboseName(path) {
- return shellEscapeLsName(pathDisplayName(path), true);
-}
-
-function mkdirDiagnosticName(path) {
- const text = pathDisplayName(path);
- const escaped = lsEscapedName(text, { escapeDouble: false });
- return lsUsesUtf8Locale() ? `\u2018${escaped}\u2019` : `'${escaped.replaceAll("'", "\\'")}'`;
-}
-
-function mkdirErrorMessage(error) {
- if (error?.code === "EEXIST") return "File exists";
- return systemErrorMessage(error);
-}
-
-function defaultDirectoryMode() {
- return (0o777 & ~process.umask()) | 0o300;
-}
-
-function parseCreationMode(spec, base = 0o777) {
- return /^[0-7]+$/.test(spec) ? Number.parseInt(spec, 8) : parseModeSpec(spec, base, true).mode;
-}
-
-async function rmdirCmd(args) {
- const { opts, operands } = parseRmdirArgs(args);
- if (!operands.length) throw new UsageError("missing operand", true);
- let failed = false;
- for (const dir of operands) {
- if (!await rmdirPath(dir, opts)) failed = true;
- }
- return failed ? 1 : 0;
-}
-
-function parseRmdirArgs(args) {
- const opts = {};
- const operands = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "-" || !arg.startsWith("-")) {
- operands.push(arg);
- if (process.env.POSIXLY_CORRECT) end = true;
- continue;
- }
- if (arg === "--") {
- end = true;
- continue;
- }
- if (arg.startsWith("--")) {
- const option = normalizeRmdirLongOption(arg);
- const [name, inlineValue] = option.slice(2).split(/=(.*)/s, 2);
- if (!RMDIR_LONG_OPTIONS.includes(name)) throw new UsageError(`unrecognized option '${arg}'`, true);
- if (inlineValue !== undefined) throw new UsageError(`option '--${name}' doesn't allow an argument`, true);
- opts[name] = true;
- continue;
- }
- for (const ch of arg.slice(1)) {
- if (ch === "p" || ch === "v") opts[ch] = true;
- else throw new UsageError(`invalid option -- '${ch}'`, true);
- }
- }
- return { opts, operands };
-}
-
-function normalizeRmdirLongOption(arg) {
- const body = arg.slice(2);
- const eq = body.indexOf("=");
- const name = eq === -1 ? body : body.slice(0, eq);
- if (!name) return arg;
- let match = null;
- if (name === "p" || name === "pa" || name === "path") {
- match = "path";
- } else {
- const matches = RMDIR_LONG_OPTIONS.filter((option) => option.startsWith(name));
- if (matches.length === 0) return arg;
- if (matches.length > 1) {
- throw new UsageError(`option '--${name}${eq === -1 ? "" : `=${body.slice(eq + 1)}`}' is ambiguous; possibilities: ${matches.map((option) => `'--${option}'`).join(" ")}`, true);
- }
- match = matches[0];
- }
- return eq === -1 ? `--${match}` : `--${match}=${body.slice(eq + 1)}`;
-}
-
-async function unlinkCmd(args) {
- args = normalizeHelpVersionOnlyLongOptions(args);
- const { operands } = parseOptions(args, { long: { help: false, version: false } });
- if (!operands.length) throw new UsageError("missing operand", true);
- if (operands.length > 1) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[1])}`, true);
- try {
- await fsUnlink(operands[0]);
- } catch (error) {
- return fail("unlink", `cannot unlink ${linkQuotedName(operands[0])}: ${systemErrorMessage(error)}`);
- }
- return 0;
-}
-
-async function linkCmd(args) {
- args = normalizeHelpVersionOnlyLongOptions(args);
- const { operands } = parseOptions(args, { long: { help: false, version: false } });
- if (!operands.length) throw new UsageError("missing operand", true);
- if (operands.length < 2) throw new UsageError(`missing operand after '${operands[0]}'`, true);
- if (operands.length > 2) throw new UsageError(`extra operand ${localeQuotedEscapedDiagnostic(operands[2])}`, true);
- try {
- await fsLink(operands[0], operands[1]);
- } catch (error) {
- return fail("link", `cannot create link ${linkQuotedName(operands[1])} to ${linkQuotedName(operands[0])}: ${linkErrorMessage(error)}`);
- }
- return 0;
-}
-
-function linkQuotedName(path) {
- return shellEscapeLsName(pathDisplayName(path), true);
-}
-
-function linkErrorMessage(error) {
- if (error?.code === "EEXIST") return "File exists";
- return errnoMessage(error);
-}
-
-async function rmdirPath(dir, opts) {
- const removeOne = async (path) => {
- try {
- await rmdir(path);
- if (opts.v || opts.verbose) stdout(`rmdir: removing directory, ${rmdirQuotedName(path)}\n`);
- } catch (error) {
- if (opts["ignore-fail-on-non-empty"] && (error.code === "ENOTEMPTY" || error.code === "EEXIST")) return false;
- if (opts["ignore-fail-on-non-empty"] && (error.code === "EACCES" || error.code === "EPERM") && await directoryHasEntries(path)) return false;
- stderr(rmdirErrorLine(path, error));
- return null;
- }
- return true;
- };
- if (!(opts.p || opts.parents || opts.path)) {
- return await removeOne(dir) !== null;
- }
- let current = dir;
- while (current && current !== "." && current !== "/") {
- const removed = await removeOne(current);
- if (removed === null) return false;
- if (!removed) break;
- const parent = pathDirname(current);
- if (parent === current) break;
- current = parent;
- }
- return true;
-}
-
-async function directoryHasEntries(path) {
- try {
- return (await readdir(path)).length > 0;
- } catch {
- return false;
- }
-}
-
-let rmDirectoryApi;
-
-function rmInterposedDirectoryApi() {
- if (!process.env.LD_PRELOAD) {
- return {
- opendir: libc.symbols.opendir,
- readdir: libc.symbols.readdir,
- closedir: libc.symbols.closedir,
- };
- }
- if (rmDirectoryApi) return rmDirectoryApi;
- const definitions = {
- opendir: { args: [FFIType.cstring], returns: FFIType.ptr },
- readdir: { args: [FFIType.ptr], returns: FFIType.ptr },
- closedir: { args: [FFIType.ptr], returns: FFIType.i32 },
- };
- const symbols = {};
- for (const [name, definition] of Object.entries(definitions)) {
- const address = libc.symbols.dlsym(0, ptr(Buffer.from(`${name}\0`)));
- symbols[name] = { ptr: address, ...definition };
- }
- rmDirectoryApi = linkSymbols(symbols).symbols;
- return rmDirectoryApi;
-}
-
-function rmLibcError(errno) {
- const error = new Error(({
- 5: "Input/output error",
- 10: "No child processes",
- 13: "Permission denied",
- 22: "Invalid argument",
- 38: "Function not implemented",
- })[errno] ?? `error ${errno}`);
- error.code = ({ 5: "EIO", 10: "ECHILD", 13: "EACCES", 22: "EINVAL", 38: "ENOSYS" })[errno] ?? "EIO";
- return error;
-}
-
-function rmReadDirectoryEntries(path) {
- return [...rmIterateDirectoryEntries(path)];
-}
-
-function rmIterateDirectoryEntries(path) {
- const api = rmInterposedDirectoryApi();
- const directory = api.opendir(cstrPath(path));
- if (!directory) throw rmLibcError(libcErrno());
- return (function* () {
- let yielded = 0;
- try {
- while (true) {
- const errnoPointer = libc.symbols.__errno_location();
- if (errnoPointer) libc.symbols.memset(errnoPointer, 0, 4);
- const address = api.readdir(directory);
- if (!address) {
- const errno = libcErrno();
- if (errno) {
- const error = rmLibcError(errno);
- error.rmPartialTraversal = yielded > 0;
- throw error;
- }
- break;
- }
- // Linux struct dirent places d_name immediately after d_type at byte
- // 19. Copy it before the next call reuses libc's dirent storage.
- const recordLength = read.u16(address, 16);
- const maximumNameLength = Math.max(0, recordLength - 19);
- let nameLength = 0;
- while (nameLength < maximumNameLength && read.u8(address + 19, nameLength) !== 0) nameLength++;
- const name = Buffer.from(new Uint8Array(toArrayBuffer(address + 19, 0, nameLength)));
- if (name.equals(Buffer.from(".")) || name.equals(Buffer.from(".."))) continue;
- yielded++;
- yield name;
- }
- } finally {
- api.closedir(directory);
- }
- })();
-}
-
-function rmPrimeDirectoryEntries(entries) {
- const first = entries.next();
- return (function* () {
- if (!first.done) yield first.value;
- yield* entries;
- })();
-}
-
-async function rmCmd(args) {
- for (const arg of args) {
- if (arg === "--") break;
- rejectAbbreviatedRmNoPreserveRoot(arg);
- }
- args = normalizeRmArgs(args);
- let parsed;
- try {
- parsed = parseOptions(args, { short: { f: false, i: false, I: false, r: false, R: false, d: false, v: false }, long: { force: false, interactive: "optional-value", recursive: false, dir: false, verbose: false, "preserve-root": "optional-value", "no-preserve-root": false, "-presume-input-tty": false, "one-file-system": false, help: false, version: false } });
- } catch (error) {
- const hint = rmDashFileHint(args);
- if (hint && error instanceof UsageError && error.showHelp) throw new UsageError(`${error.message}\n${hint}`, true);
- throw error;
- }
- const { opts, operands } = parsed;
- validateRmInteractive(opts);
- validateRmPreserveRoot(opts);
- if (!operands.length) {
- if (opts.f || opts.force) return 0;
- throw new UsageError("missing operand", true);
- }
- const preserveRoot = !opts["no-preserve-root"];
- const options = {
- force: opts.f || opts.force,
- recursive: opts.r || opts.R || opts.recursive,
- dir: opts.d || opts.dir,
- verbose: opts.v || opts.verbose,
- preserveRoot,
- preserveRootAll: preserveRoot && opts["preserve-root"] === "all",
- oneFileSystem: opts["one-file-system"],
- interactive: rmInteractiveMode(args, opts),
- presumeInputTty: opts["-presume-input-tty"],
- };
- if (options.interactive === "once" && (operands.length > 3 || options.recursive)) {
- const suffix = options.recursive ? " recursively" : "";
- if (!confirmRemoval(`rm: remove ${operands.length} argument${operands.length === 1 ? "" : "s"}${suffix}? `)) return 0;
- }
- const rawOperands = rawRmOperands(operands);
- let failed = false;
- for (let i = 0; i < operands.length; i++) {
- const target = rawOperands?.[i] ?? operands[i];
- if (options.recursive && options.preserveRoot && await isRecursiveRootTarget(target)) {
- stderr(preserveRootMessage("rm", operands[i]));
- failed = true;
- continue;
- }
- if (options.recursive && !options.preserveRoot && process.env.BNU_RM_TEST_INTERCEPT_FILE && await isRecursiveRootTarget(target)) {
- rmTestInterceptRemoval();
- }
- const targetOptions = { ...options };
- if (options.recursive && (options.oneFileSystem || options.preserveRootAll)) {
- targetOptions.rootDev = await rmRootDevice(target);
- if (targetOptions.preserveRootAll && targetOptions.rootDev != null && await rmIsDifferentDeviceFromParent(target, targetOptions.rootDev)) {
- stderr(rmDifferentDeviceMessage(rmDisplayPath(operands[i])));
- stderr("rm: and --preserve-root=all is in effect\n");
- failed = true;
- continue;
- }
- }
- if (!await removePath(target, targetOptions, rmDisplayPath(operands[i]), true)) failed = true;
- }
- return failed ? 1 : 0;
-}
-
-function rejectAbbreviatedRmNoPreserveRoot(arg) {
- if (!arg.startsWith("--") || arg.includes("=")) return;
- const name = arg.slice(2);
- if (name !== "no-preserve-root" && "no-preserve-root".startsWith(name)) {
- throw new InvocationError("you may not abbreviate the --no-preserve-root option", 1, false);
- }
-}
-
-function normalizeRmArgs(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--") {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(arg.startsWith("--") ? normalizeLongOptionByPrefix(arg, RM_LONG_OPTIONS) : arg);
- }
- return out;
-}
-
-function rawRmOperands(operands) {
- if (!operands.some((operand) => operand.includes("\uFFFD"))) return null;
- const raw = rawCommandArgs("rm");
- if (!raw) return null;
- const parsed = [];
- for (let i = 0; i < raw.length; i++) {
- const arg = raw[i];
- if (arg.equals(Buffer.from("--"))) {
- parsed.push(...raw.slice(i + 1));
- break;
- }
- if (!rawArgLooksLikeOption(arg)) {
- parsed.push(arg);
- continue;
- }
- const text = arg.toString();
- if (text === "--interactive" || text === "-I") continue;
- if (text === "--") continue;
- if (text.startsWith("--interactive=")) continue;
- }
- return parsed.length === operands.length ? parsed : null;
-}
-
-function validateRmInteractive(opts) {
- const mode = opts.interactive === true ? "always" : opts.interactive;
- if (mode == null) return;
- validateRmInteractiveValue(mode);
-}
-
-function validateRmInteractiveValue(mode) {
- if (!["always", "yes", "once", "no", "never", "none"].includes(mode)) {
- const kind = mode === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(mode)} for ${localeQuotedDiagnostic("--interactive")}\nValid arguments are:\n - ${["never", "no", "none"].map(localeQuotedDiagnostic).join(", ")}\n - ${localeQuotedDiagnostic("once")}\n - ${["always", "yes"].map(localeQuotedDiagnostic).join(", ")}`, true);
- }
-}
-
-function validateRmPreserveRoot(opts) {
- const value = opts["preserve-root"];
- if (value == null || value === true) return;
- validateRmPreserveRootValue(value);
-}
-
-function validateRmPreserveRootValue(value) {
- if (value !== "all") throw new UsageError(`unrecognized --preserve-root argument: '${value}'`);
-}
-
-function rmInteractiveMode(args, opts) {
- let mode = "never";
- for (const arg of args) {
- if (arg === "--") break;
- if (arg === "-f" || arg === "--force") mode = "never";
- else if (arg === "-i") mode = "always";
- else if (arg === "-I") mode = "once";
- else if (arg === "--interactive") mode = "always";
- else if (arg.startsWith("--interactive=")) mode = arg.slice("--interactive=".length);
- else if (/^-[^-]/.test(arg)) {
- for (const ch of arg.slice(1)) {
- if (ch === "f") mode = "never";
- else if (ch === "i") mode = "always";
- else if (ch === "I") mode = "once";
- }
- }
- }
- if ((opts.f || opts.force) && mode === "never") return "never";
- return mode;
-}
-
-async function removePath(path, options, display = path, isRoot = false) {
- if (options.recursive && isDotOrDotDotPath(path)) {
- stderr(`rm: refusing to remove '.' or '..' directory: skipping ${rmQuotedName(path)}\n`);
- return false;
- }
- let s;
- try {
- s = await lstat(path);
- } catch (error) {
- if (options.force && (error?.code === "ENOENT" || error?.code === "ENOTDIR")) return true;
- stderr(rmErrorLine(display, error));
- return false;
- }
- if (s.isDirectory()) {
- if (!options.recursive && !options.dir) {
- stderr(`rm: cannot remove ${rmQuotedName(display)}: Is a directory\n`);
- return false;
- }
- if (options.recursive && options.oneFileSystem && !isRoot && options.rootDev != null && s.dev !== options.rootDev) {
- stderr(rmDifferentDeviceMessage(display));
- return false;
- }
- if (options.recursive) {
- if (isRoot && options.interactive === "always" && !confirmRemoval(`rm: descend into directory ${rmQuotedName(display)}? `)) return true;
- let entries;
- try {
- entries = options.interactive === "always"
- ? rmReadDirectoryEntries(path)
- : rmPrimeDirectoryEntries(rmIterateDirectoryEntries(path));
- } catch (error) {
- if (options.force && (error?.code === "EACCES" || error?.code === "EPERM")) {
- try {
- await rmdir(path);
- if (options.verbose) stdout(`removed directory ${rmQuotedName(display)}\n`);
- return true;
- } catch {}
- }
- if (error.rmPartialTraversal) stderr(`rm: traversal failed: ${pathDisplayName(display)}: ${errnoMessage(error)}\n`);
- else stderr(rmErrorLine(path, error));
- return false;
- }
- if (!isRoot && entries.length > 0 && options.interactive === "always" && !confirmRemoval(`rm: descend into directory ${rmQuotedName(display)}? `)) return true;
- let ok = true;
- try {
- const chdirName = rmRelativeTraversalName(path, isRoot);
- if (chdirName != null) {
- const restoreCwd = isRoot ? processCwdOrNull() : null;
- try {
- changeDirectory(chdirName);
- } catch (error) {
- stderr(rmErrorLine(display, error));
- return false;
- }
- try {
- for (const entry of entries) {
- const childDisplay = `${display.replace(/\/+$/, "")}/${pathDisplayName(entry)}`;
- if (rmFastUnlinkEntry(entry, options)) continue;
- if (!await removePath(entry, options, childDisplay, false)) ok = false;
- }
- } finally {
- changeDirectory(restoreCwd ?? "..");
- }
- } else {
- for (const entry of entries) {
- const child = pathLikeJoin(path, entry);
- const childDisplay = `${display.replace(/\/+$/, "")}/${pathDisplayName(entry)}`;
- if (rmFastUnlinkEntry(child, options)) continue;
- if (!await removePath(child, options, childDisplay, false)) ok = false;
- }
- }
- } catch (error) {
- if (error.rmPartialTraversal) stderr(`rm: traversal failed: ${pathDisplayName(display)}: ${errnoMessage(error)}\n`);
- else stderr(rmErrorLine(path, error));
- return false;
- }
- if (!ok) return false;
- }
- if (shouldPromptForRemoval(options, s) && !confirmRemoval(`rm: ${rmDirectoryPromptAction(s)} ${rmQuotedName(display)}? `)) return true;
- try {
- rmTestInterceptRemoval();
- await rmdir(path);
- if (options.verbose) stdout(`removed directory ${rmQuotedName(display)}\n`);
- return true;
- } catch (error) {
- stderr(rmErrorLine(display, error, error?.code !== "ENOTEMPTY"));
- return false;
- }
- }
- if (shouldPromptForRemoval(options, s) && !confirmRemoval(`rm: remove ${rmPromptDescription(s)} ${rmQuotedName(display)}? `)) return true;
- try {
- rmTestInterceptRemoval();
- await fsUnlink(path);
- if (options.verbose) stdout(`removed ${rmQuotedName(display)}\n`);
- return true;
- } catch (error) {
- stderr(rmErrorLine(display, error));
- return false;
- }
-}
-
-function rmFastUnlinkEntry(path, options) {
- rmTestInterceptRemoval();
- if (process.env.LD_PRELOAD || options.verbose || options.interactive === "always" || options.presumeInputTty) return false;
- try {
- unlinkSync(path);
- return true;
- } catch {
- // Directories, mount points, immutable files, and permission failures
- // require the full metadata-aware recursive/diagnostic path below.
- return false;
- }
-}
-
-function rmTestInterceptRemoval() {
- const evidence = process.env.BNU_RM_TEST_INTERCEPT_FILE;
- if (!evidence) return;
- writeFileSync(evidence, "removal attempted\n");
- process.exit(0);
-}
-
-async function rmRootDevice(path) {
- try {
- return (await lstat(path)).dev;
- } catch {
- return null;
- }
-}
-
-async function rmIsDifferentDeviceFromParent(path, rootDev) {
- const parent = pathDirname(String(path).replace(/\/+$/, "") || ".");
- try {
- return (await lstat(parent)).dev !== rootDev;
- } catch {
- return false;
- }
-}
-
-function rmDifferentDeviceMessage(path) {
- return `rm: skipping ${rmQuotedName(path)}, since it's on a different device\n`;
-}
-
-function confirmRemoval(prompt) {
- stderr(prompt);
- const bytes = new Uint8Array(1024);
- while (!stdinLineBuffer.includes("\n")) {
- const n = readSync(0, bytes, 0, bytes.length, null);
- if (!n) break;
- stdinLineBuffer += Buffer.from(bytes.subarray(0, n)).toString("utf8");
- }
- const newline = stdinLineBuffer.indexOf("\n");
- const text = newline === -1 ? stdinLineBuffer : stdinLineBuffer.slice(0, newline);
- stdinLineBuffer = newline === -1 ? "" : stdinLineBuffer.slice(newline + 1);
- return /^[yY]/.test(text.trimStart());
-}
-
-function rmFileTypeDescription(s) {
- if (s.isSymbolicLink()) return "symbolic link";
- if (s.isFIFO()) return "fifo";
- if (s.isDirectory()) return "directory";
- return s.size === 0 ? "regular empty file" : "regular file";
-}
-
-function rmPromptDescription(s) {
- const type = rmFileTypeDescription(s);
- return s.isSymbolicLink() || (s.mode & 0o200) ? type : `write-protected ${type}`;
-}
-
-function shouldPromptForRemoval(options, s) {
- if (options.interactive === "always") return true;
- if (options.presumeInputTty && isWriteProtected(s)) return true;
- return options.interactive === "once" && isWriteProtected(s);
-}
-
-function isWriteProtected(s) {
- return !s.isSymbolicLink() && !(s.mode & 0o200);
-}
-
-function rmDirectoryPromptAction(s) {
- if (!(s.mode & 0o500)) return "attempt removal of inaccessible directory";
- return `remove ${rmPromptDescription(s)}`;
-}
-
-function rmDisplayPath(path) {
- return String(path).replace(/\/+$/, "/");
-}
-
-function rmRelativeTraversalName(path, isRoot = false) {
- const text = pathDisplayName(path);
- if (isRoot && isAbsolute(text)) return null;
- if (text.includes("\uFFFD") || /[\uDC80-\uDCFF]/.test(text) || text === "" || text === "." || text === "..") return null;
- return text;
-}
-
-function isDotOrDotDotPath(path) {
- const stripped = String(path).replace(/\/+$/, "");
- const base = pathBasename(stripped);
- return base === "." || base === "..";
-}
-
-function rmErrorLine(path, error, directory = false) {
- const action = directory ? "cannot remove directory" : "cannot remove";
- return `rm: ${action} ${rmQuotedName(path)}: ${errnoMessage(error)}\n`;
-}
-
-function rmQuotedName(path) {
- return shellEscapeLsName(pathDisplayName(path), true);
-}
-
-function rmInvalidOptionUsageError(arg, args) {
- const message = invalidOptionMessage(rmInvalidOptionArg(arg));
- const hint = rmDashFileHint(args);
- return new UsageError(hint ? `${message}\n${hint}` : message, true);
-}
-
-function rmInvalidOptionArg(arg) {
- if (arg.startsWith("--")) return arg;
- for (const ch of arg.slice(1)) {
- if (!"firdvIR".includes(ch)) return `-${ch}`;
- }
- return arg;
-}
-
-function rmDashFileHint(args) {
- for (const arg of args) {
- if (!arg.startsWith("-") || arg === "-" || arg === "--") continue;
- if (!lstatSyncNoThrow(arg)) continue;
- return `Try 'rm ./${rmShellEscapeCommandPath(arg)}' to remove the file ${rmShellQuote(arg)}.`;
- }
- return "";
-}
-
-function rmShellEscapeCommandPath(path) {
- return /^[A-Za-z0-9_./=-]+$/.test(path) ? path : rmShellQuote(path);
-}
-
-function rmShellQuote(value) {
- const text = String(value);
- if (!/[^A-Za-z0-9_./=-]/.test(text)) return `'${text}'`;
- return `'${text.replace(/'/g, "'\\''").replace(/\n/g, () => "'$'\\n''")}'`;
-}
-
-async function cpCmd(args) {
- args = normalizeCpArgs(args);
- const { opts, operands } = parseOptions(args, { short: { f: false, i: false, n: false, r: false, R: false, a: false, p: false, s: false, d: false, l: false, H: false, L: false, P: false, u: false, v: false, t: "value", T: false, b: false, S: "value", x: false, Z: false }, long: { force: false, interactive: false, "no-clobber": false, recursive: false, archive: false, preserve: "optional-value", parent: false, parents: false, "symbolic-link": false, "no-dereference": false, link: false, dereference: false, "no-preserve": "value", update: "optional-value", verbose: false, debug: false, reflink: "optional-value", sparse: "value", "target-directory": "value", "no-target-directory": false, "remove-destination": false, rem: false, "attributes-only": false, "copy-contents": false, context: "optional-value", backup: "optional-value", b: "optional-value", suffix: "value", "strip-trailing-slashes": false, "one-file-system": false, "keep-directory-symlink": false, help: false, version: false } });
- const selinuxEnabled = selinuxRuntimeEnabled();
- if (typeof opts.context === "string" && !selinuxEnabled) stderr("cp: warning: ignoring --context; it requires an SELinux-enabled kernel\n");
- if (opts.b != null && opts.backup == null) opts.backup = opts.b;
- if (opts.S != null && opts.suffix == null) opts.suffix = opts.S;
- const reflinkMode = cpReflinkMode(opts);
- const sparseMode = cpSparseMode(opts);
- validateCpPreserveOptions(opts);
- const securityContextOptions = cpSecurityContextOptions(opts, selinuxEnabled);
- const noDereference = opts.d || opts.P || opts["no-dereference"];
- const backupRequested = opts.b || opts.backup != null;
- if (backupRequested) validateBackupMode("cp", opts.backup);
- const overwriteMode = cpOverwriteMode(args, opts);
- if (backupRequested && (overwriteMode === "no-clobber" || opts.update === "none" || opts.update === "none-fail")) {
- throw new UsageError("--backup is mutually exclusive with -n or --update=none-fail", true);
- }
- if (reflinkMode === "always" && opts.sparse != null) throw new UsageError("options --reflink and --sparse are mutually exclusive");
- const { sources, dest, destStat, useDirectoryTarget } = await resolveDestinationOperands("cp", operands, opts);
- if (cpParents(opts) && !useDirectoryTarget) throw new UsageError("with --parents, the destination must be a directory", true);
- const seenSources = new Set();
- const createdTargets = new Map();
- const linkMap = new Map();
- const rawPlan = rawCpPlan(opts, operands, useDirectoryTarget);
- let status = 0;
- for (let i = 0; i < sources.length; i++) {
- const src = sources[i];
- const normalizedSrc = opts["strip-trailing-slashes"] ? stripTrailingSlashesPath(src) : src;
- const rawSource = rawPlan?.sources[i];
- const operationSource = rawSource ? await resolveRawExistingPath(stripTrailingDotPathBytes(rawSource)) : normalizedSrc;
- try {
- const target = rawSource ? rawCpTargetPath(rawSource, rawPlan.dest, rawPlan.useDirectoryTarget, opts) : cpTargetPath(normalizedSrc, dest, useDirectoryTarget, opts);
- const sourceInfo = await cpTopLevelSourceStat(operationSource, opts, noDereference);
- if (!sourceInfo) throw new UsageError(`cannot stat '${src}': No such file or directory`);
- const sourceKey = rawSource ? rawPathKey(rawSource) : resolve(src);
- if (sourceInfo && seenSources.has(sourceKey) && !backupRequested) {
- const kind = sourceInfo.isDirectory() ? "directory" : "file";
- stderr(`cp: warning: source ${kind} '${cpDuplicateDisplayName(src)}' specified more than once\n`);
- if (sourceInfo.isDirectory()) continue;
- }
- seenSources.add(sourceKey);
- const targetKey = isBytePath(target) ? rawPathKey(target) : resolve(target);
- if (backupRequested && createdTargets.has(targetKey) && !cpBackupIsNumbered(opts)) throw new UsageError(`will not overwrite just-created '${target}' with '${src}'`);
- await ensureCpNotIntoSelf(operationSource, target, noDereference);
- const updateDecision = await cpUpdateDecision(operationSource, target, opts, noDereference, overwriteMode);
- if (updateDecision.skip) {
- if (opts.debug) stdout(`skipped '${src}'\n`);
- if (updateDecision.fail) {
- stderr(`cp: not replacing '${target}'\n`);
- status = 1;
- }
- continue;
- }
- const copyForce = opts.f || opts.force || backupRequested || overwriteMode === "interactive";
- if (overwriteMode === "interactive") {
- const targetInfo = await lstat(target).catch(() => null);
- if (targetInfo && !confirmRemoval(cpOverwritePrompt(target, targetInfo))) {
- status = 1;
- continue;
- }
- }
- if (backupRequested) await ensureBackupDoesNotDestroySource("cp", src, target, opts.suffix, opts.backup);
- const sameFile = await cpSameFile(operationSource, target, opts);
- if (sameFile && (opts.l || opts.link) && await cpHardLinkSameFileIsNoop(src, target, opts, backupRequested)) continue;
- if ((opts.l || opts.link) && (opts.d || opts["no-dereference"]) && src !== target && await areSamePathEntry(operationSource, target)) continue;
- if (sameFile && await cpSameFileIsError(src, target, opts, backupRequested)) throw new UsageError(`'${src}' and '${target}' are the same file`);
- if (sameFile && backupRequested && (opts.f || opts.force) && (!(opts.d || opts["no-dereference"]) || src === target) && !await cpTargetIsSymlink(target)) {
- const backup = backupFileName(target, opts.suffix, opts.backup);
- if (opts.l || opts.link) await fsLink(src, backup);
- else await copyFile(src, backup);
- continue;
- }
- const parentModeRestores = cpParents(opts) ? await cpPrepareParentDirectories(operationSource, dest, noDereference, cpPreserveMode(opts), cpPreserveMetadata(opts), securityContextOptions) : [];
- const actualTargetInfo = await lstat(target).catch(() => null);
- const destinationWasReportedExisting = Boolean(!actualTargetInfo && destStat && !useDirectoryTarget && sources.length === 1);
- const targetExisted = Boolean(actualTargetInfo || destinationWasReportedExisting);
- const createdByDifferentSource = createdTargets.has(targetKey) && createdTargets.get(targetKey) !== sourceKey;
- if (!backupRequested && createdByDifferentSource && await cpTargetIsSymlink(target)) {
- throw new UsageError(`will not copy '${src}' through just-created symlink '${target}'`);
- }
- if (!backupRequested && createdByDifferentSource) {
- throw new UsageError(`will not overwrite just-created '${target}' with '${src}'`);
- }
- if (backupRequested && await cpShouldBackupDestination(target)) await backupDestination(target, opts.suffix, opts.backup);
- await copyPath(operationSource, target, {
- force: copyForce,
- removeDestination: opts["remove-destination"] || opts.rem,
- destinationWasReportedExisting,
- recursive: opts.r || opts.R || opts.recursive || opts.a || opts.archive,
- preserveMode: cpPreserveMode(opts),
- preserveDirectoryMode: !cpNoPreserveAttrs(opts).includes("mode"),
- useSourceModeForNewRegularFiles: cpUseSourceModeForNewRegularFiles(opts),
- preserveMetadata: cpPreserveMetadata(opts),
- preserveLinks: cpPreserveLinks(opts),
- preserveXattrs: cpPreserveXattrs(opts),
- requirePreserveXattrs: cpRequirePreserveXattrs(opts),
- ...securityContextOptions,
- attributesOnly: opts["attributes-only"],
- debug: opts.debug,
- linkMap,
- symbolicLink: opts.s || opts["symbolic-link"],
- hardLink: opts.l || opts.link,
- sparseMode,
- noDereference,
- dereferenceAll: opts.L || opts.dereference,
- dereferenceCommandLine: opts.H,
- copyContents: opts["copy-contents"],
- keepDirectorySymlink: opts["keep-directory-symlink"],
- oneFileSystem: opts.x || opts["one-file-system"],
- rootDev: sourceInfo.dev,
- reflinkMode,
- verbose: opts.v || opts.verbose || opts.debug,
- }, true);
- for (const restore of parentModeRestores.reverse()) {
- if (restore.sourcePath != null) await applyCopySecurityContext(restore.path, restore.sourcePath, securityContextOptions);
- if (restore.mode != null) await setFileMode(restore.path, restore.mode).catch(() => {});
- }
- if (!targetExisted || await cpCopiedMatchingSymlink(src, target, noDereference)) createdTargets.set(targetKey, sourceKey);
- } catch (error) {
- status = 1;
- if (error instanceof UsageError) stderr(`cp: ${error.message}\n`);
- else stderr(`cp: ${error.message || String(error)}\n`);
- }
- }
- return status;
-}
-
-async function cpCopiedMatchingSymlink(src, target, noDereference) {
- if (!noDereference) return false;
- const [srcInfo, targetInfo] = await Promise.all([lstat(src).catch(() => null), lstat(target).catch(() => null)]);
- if (!srcInfo?.isSymbolicLink() || !targetInfo?.isSymbolicLink()) return false;
- return await readlink(src).catch(() => null) === await readlink(target).catch(() => null);
-}
-
-async function cpTopLevelSourceStat(src, opts, noDereference) {
- const dereferenceSource = cpShouldDereferenceSource(src, {
- noDereference,
- dereferenceAll: opts.L || opts.dereference,
- dereferenceCommandLine: opts.H,
- recursive: opts.r || opts.R || opts.recursive || opts.a || opts.archive,
- hardLink: opts.l || opts.link,
- preserveLinks: cpPreserveLinks(opts),
- }, true);
- return (dereferenceSource ? stat(src) : lstat(src)).catch(() => null);
-}
-
-function cpOverwritePrompt(target, targetInfo) {
- if (isWriteProtected(targetInfo)) {
- return `cp: replace '${target}', overriding mode ${(targetInfo.mode & 0o7777).toString(8).padStart(4, "0")} (${modeString(targetInfo).slice(1)})? `;
- }
- return `cp: overwrite '${target}'? `;
-}
-
-function normalizeCpArgs(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--") {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(arg.startsWith("--") ? normalizeLongOptionByPrefix(arg, CP_LONG_OPTIONS) : arg);
- }
- return out;
-}
-
-function cpOverwriteMode(args, opts) {
- let mode = "replace";
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") break;
- if (arg === "-i" || arg === "--interactive") mode = "interactive";
- else if (arg === "-n" || arg === "--no-clobber") mode = "no-clobber";
- else if (/^-[^-]/.test(arg)) {
- for (const ch of arg.slice(1)) {
- if (ch === "i") mode = "interactive";
- else if (ch === "n") mode = "no-clobber";
- }
- }
- }
- if (mode === "replace" && (opts.i || opts.interactive)) return "interactive";
- if (mode === "replace" && (opts.n || opts["no-clobber"])) return "no-clobber";
- return mode;
-}
-
-function cpReflinkMode(opts) {
- if (opts.reflink == null) return opts.debug && opts.sparse == null ? "auto" : "never";
- const mode = opts.reflink === true ? "always" : String(opts.reflink);
- if (mode === "always" || mode === "auto" || mode === "never") return mode;
- validateReflinkMode("cp", mode);
-}
-
-function cpSparseMode(opts) {
- if (opts.sparse == null) return "auto";
- const mode = String(opts.sparse);
- if (mode === "always" || mode === "auto" || mode === "never") return mode;
- validateSparseMode("cp", mode);
-}
-
-function cpDuplicateDisplayName(src) {
- return String(src).replace(/^\.\//, "");
-}
-
-function cpBackupIsNumbered(opts) {
- const mode = opts.backup === true || opts.backup == null ? backupModeFromEnvironment() : String(opts.backup);
- return mode === "numbered" || mode === "t";
-}
-
-async function cpShouldBackupDestination(target) {
- const info = await lstat(target).catch(() => null);
- return Boolean(info && !info.isDirectory());
-}
-
-async function cpPrepareParentDirectories(src, destRoot, noDereference, preserveMode, preserveMetadata = false, securityOptions = {}) {
- if (noDereference) await lstat(src);
- else await stat(src);
- const parentRel = pathDirname(cpParentPath(src));
- if (parentRel === "." || parentRel === "") return [];
- const parentParts = parentRel.split("/").filter(Boolean);
- let destPrefix = destRoot;
- let srcPrefix = isAbsolute(src) ? "/" : "";
- const restores = [];
- for (const part of parentParts) {
- destPrefix = join(destPrefix, part);
- srcPrefix = srcPrefix === "" || srcPrefix === "/" ? `${srcPrefix}${part}` : join(srcPrefix, part);
- const mode = preserveMode ? (await stat(srcPrefix).catch(() => null))?.mode & 0o7777 : undefined;
- const createMode = mode != null ? cpRestrictiveDirectoryMode(mode) : preserveMetadata ? 0o700 : 0o755;
- const exists = Boolean(await lstat(destPrefix).catch(() => null));
- if (!exists) {
- if (securityOptions.preserveContextAtCreation) {
- await withPreservedCopyCreationContext(srcPrefix, securityOptions, () => mkdirSync(destPrefix, { mode: createMode }));
- } else {
- await mkdir(destPrefix, { recursive: false, mode: createMode });
- }
- }
- if (mode !== undefined || securityOptions.preserveContext) {
- restores.push({ path: destPrefix, mode, sourcePath: securityOptions.preserveContext ? srcPrefix : null });
- }
- }
- return restores;
-}
-
-function cpRestrictiveDirectoryMode(mode) {
- return (mode & 0o7000) | 0o700;
-}
-
-function cpPreserveMode(opts) {
- if (opts.preserve != null) {
- const attrs = opts.preserve === true ? ["mode", "ownership", "timestamps"] : String(opts.preserve).split(",");
- if (attrs.includes("all") || attrs.includes("mode")) return true;
- }
- if (opts.p || opts.a || opts.archive) return !cpNoPreserveAttrs(opts).includes("mode");
- return false;
-}
-
-const CP_PRESERVE_VALID_ARGUMENTS = [
- ["mode"],
- ["timestamps"],
- ["ownership"],
- ["links"],
- ["context"],
- ["xattr"],
- ["all"],
-];
-
-function validateCpPreserveOptions(opts) {
- if (opts.preserve != null && opts.preserve !== true) {
- validateCpPreserveList(String(opts.preserve), "--preserve");
- }
- if (opts["no-preserve"] != null) validateCpPreserveList(String(opts["no-preserve"]), "--no-preserve");
-}
-
-function cpSecurityContextOptions(opts, selinuxEnabled) {
- const noPreserve = cpNoPreserveAttrs(opts);
- const preserveAttrs = opts.preserve == null || opts.preserve === true ? [] : String(opts.preserve).split(",");
- const explicitlyRequired = preserveAttrs.includes("context");
- if (explicitlyRequired && !selinuxEnabled) throw new InvocationError("cannot preserve security context without an SELinux-enabled kernel", 1, false);
- const requestedDefault = Boolean(opts.Z || opts.context === true);
- const explicitContext = typeof opts.context === "string" && selinuxEnabled ? opts.context : null;
- if (explicitlyRequired && (requestedDefault || explicitContext != null)) {
- throw new InvocationError("cannot set target context and preserve it", 1, false);
- }
- const preserveRequested = !noPreserve.some((attr) => attr === "all" || attr === "context")
- && (opts.a || opts.archive || preserveAttrs.includes("all") || explicitlyRequired);
- const preserveContext = selinuxEnabled && preserveRequested && !requestedDefault && explicitContext == null;
- const restoreContext = selinuxEnabled && requestedDefault;
- return {
- selinuxEnabled,
- preserveContext,
- // GNU creates with the source label before applying a pathname default.
- // If no default is defined, -Z therefore retains the source label.
- preserveContextAtCreation: preserveContext || restoreContext,
- requirePreserveContext: explicitlyRequired,
- restoreContext,
- explicitContext,
- };
-}
-
-function validateCpPreserveList(value, option) {
- const valid = new Set(["mode", "timestamps", "ownership", "link", "links", "context", "xattr", "all"]);
- const attrs = [];
- for (const attr of value.split(",")) {
- if (attr === "") throw new InvocationError(cpPreserveInvalidMessage(attr, option, "ambiguous"), 1, true);
- if (!valid.has(attr)) throw new InvocationError(cpPreserveInvalidMessage(attr, option, "invalid"), 1, true);
- attrs.push(attr);
- }
- return attrs;
-}
-
-function cpPreserveInvalidMessage(value, option, kind) {
- return `${kind} argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic(option)}\nValid arguments are:\n${CP_PRESERVE_VALID_ARGUMENTS.map((group) => ` - ${group.map(localeQuotedDiagnostic).join(", ")}`).join("\n")}`;
-}
-
-function cpPreserveMetadata(opts) {
- const preserve = opts.p || opts.a || opts.archive || opts.preserve != null;
- if (!preserve) return false;
- if (cpNoPreserveAttrs(opts).includes("all")) return false;
- if (opts.preserve != null && !(opts.p || opts.a || opts.archive)) {
- const attrs = opts.preserve === true ? ["mode", "ownership", "timestamps"] : String(opts.preserve).split(",");
- return attrs.includes("all") || attrs.includes("ownership") || attrs.includes("timestamps");
- }
- return true;
-}
-
-function cpNoPreserveAttrs(opts) {
- return String(opts["no-preserve"] ?? "").split(",").filter(Boolean);
-}
-
-function cpPreserveLinks(opts) {
- if (cpNoPreserveAttrs(opts).includes("links")) return false;
- if (opts.d || opts.a || opts.archive) return true;
- if (opts.preserve == null) return false;
- const attrs = opts.preserve === true ? ["mode", "ownership", "timestamps"] : String(opts.preserve).split(",");
- return attrs.includes("all") || attrs.includes("links") || attrs.includes("link");
-}
-
-function cpPreserveXattrs(opts) {
- if (cpNoPreserveAttrs(opts).some((attr) => attr === "all" || attr === "xattr")) return false;
- if (opts.a || opts.archive) return true;
- if (opts.preserve == null) return false;
- const attrs = opts.preserve === true ? ["mode", "ownership", "timestamps"] : String(opts.preserve).split(",");
- return attrs.includes("all") || attrs.includes("xattr");
-}
-
-function cpRequirePreserveXattrs(opts) {
- if (opts.preserve == null || opts.preserve === true) return false;
- return String(opts.preserve).split(",").includes("xattr");
-}
-
-function cpUseSourceModeForNewRegularFiles(opts) {
- return !cpNoPreserveAttrs(opts).some((attr) => attr === "all" || attr === "mode");
-}
-
-function cpParents(opts) {
- return Boolean(opts.parents || opts.parent);
-}
-
-function cpTargetPath(src, dest, useDirectoryTarget, opts) {
- if (cpParents(opts)) return join(dest, cpParentPath(src));
- return useDirectoryTarget ? join(dest, pathBasename(src.replace(/\/+$/, ""))) : dest;
-}
-
-function stripTrailingSlashesPath(path) {
- return String(path).replace(/\/+$/, "") || path;
-}
-
-function rawCpPlan(opts, operands, useDirectoryTarget) {
- const raw = rawCommandArgs("cp");
- if (!raw) return null;
- const rawOperands = parseRawCpOperands(raw);
- if (rawOperands.length !== operands.length) return null;
- if (!rawOperands.some((operand, index) => rawPathNeedsBytes(operand) || !operand.equals(Buffer.from(operands[index])))) return null;
- if (useDirectoryTarget) return { sources: rawOperands.slice(0, -1), dest: rawOperands.at(-1), useDirectoryTarget: true };
- return { sources: rawOperands.slice(0, -1), dest: rawOperands.at(-1), useDirectoryTarget: false };
-}
-
-function parseRawCpOperands(rawArgs) {
- const operands = [];
- for (let i = 0; i < rawArgs.length; i++) {
- const arg = rawArgs[i];
- if (arg.equals(Buffer.from("--"))) {
- operands.push(...rawArgs.slice(i + 1));
- break;
- }
- if (!rawArgLooksLikeOption(arg)) {
- operands.push(arg);
- continue;
- }
- const text = arg.toString();
- if (["-t", "--target-directory", "--target", "--suffix", "-S"].includes(text)) {
- i++;
- continue;
- }
- if (/^(--target-directory|--target|--suffix|--backup|--preserve|--no-preserve|--update|--reflink|--sparse)=/.test(text)) continue;
- if (arg.length > 2 && arg[0] === 0x2d) {
- const letters = arg.toString().slice(1);
- const valueIndex = [...letters].findIndex((ch) => ch === "t" || ch === "S");
- if (valueIndex !== -1 && valueIndex === letters.length - 1) i++;
- }
- }
- return operands;
-}
-
-function rawCpTargetPath(src, dest, useDirectoryTarget, opts) {
- if (cpParents(opts)) return bufferPathJoin(dest, Buffer.from(cpParentPath(pathDisplayName(src))));
- if (rawPathEndsWithSlashDot(src)) return dest;
- return useDirectoryTarget ? bufferPathJoin(dest, bufferPathBasename(stripTrailingSlashBytes(src))) : dest;
-}
-
-function rawPathEndsWithSlashDot(path) {
- return path.length >= 2 && path[path.length - 2] === 0x2f && path[path.length - 1] === 0x2e;
-}
-
-function stripTrailingSlashBytes(path) {
- let end = path.length;
- while (end > 1 && path[end - 1] === 0x2f) end--;
- return path.subarray(0, end);
-}
-
-function stripTrailingDotPathBytes(path) {
- if (path.length >= 2 && path[path.length - 2] === 0x2f && path[path.length - 1] === 0x2e) return path.subarray(0, path.length - 2);
- return path;
-}
-
-function rawPathKey(path) {
- return Buffer.from(path).toString("hex");
-}
-
-function rawPathNeedsBytes(path) {
- return Buffer.from(path).some((byte) => byte >= 0x80);
-}
-
-async function resolveRawExistingPath(path) {
- if (await lstat(path).then(() => true, () => false)) return path;
- const absolute = path[0] === 0x2f;
- const parts = Buffer.from(path).toString("binary").split("/").map((part) => Buffer.from(part, "binary"));
- let current = absolute ? Buffer.from("/") : Buffer.from(".");
- for (const part of parts) {
- if (!part.length || part.equals(Buffer.from("."))) continue;
- if (part.equals(Buffer.from(".."))) {
- current = pathLikeJoin(current, part);
- continue;
- }
- const entries = await readdirPathEntries(current);
- const display = part.toString();
- let match = entries.find((entry) => Buffer.from(entry).equals(part) || pathDisplayName(entry) === display);
- if (!match && rawPathNeedsBytes(part)) {
- const candidates = entries.filter((entry) => rawPathNeedsBytes(entry));
- if (candidates.length === 1) match = candidates[0];
- }
- if (!match) return path;
- current = pathLikeJoin(current, match);
- }
- return current;
-}
-
-function cpParentPath(src) {
- const stripped = String(src).replace(/^\/+/, "").replace(/\/+$/, "");
- return stripped || ".";
-}
-
-async function ensureCpNotIntoSelf(src, target, noDereference) {
- const sourceInfo = noDereference ? await lstat(src).catch(() => null) : await stat(src).catch(() => null);
- if (!sourceInfo?.isDirectory()) return;
- const sourcePath = resolve(pathDisplayName(src));
- const targetPath = resolve(pathDisplayName(target));
- if (targetPath === sourcePath || targetPath.startsWith(`${sourcePath}/`)) {
- throw new UsageError(`cannot copy a directory, '${pathDisplayName(src)}', into itself, '${pathDisplayName(target)}'`);
- }
-}
-
-async function cpSameFileIsError(src, target, opts, backupRequested) {
- if (opts.s || opts["symbolic-link"]) return !await cpTargetIsReplaceableSymlink(src, target);
- if (opts.l || opts.link) return false;
- if (backupRequested && (opts.d || opts["no-dereference"])) {
- const srcInfo = await lstat(src).catch(() => null);
- if (srcInfo?.isSymbolicLink() && src !== target) return false;
- }
- if (backupRequested && (opts.f || opts.force)) {
- const srcInfo = await lstat(src).catch(() => null);
- if (srcInfo && !srcInfo.isSymbolicLink()) return false;
- if (await cpTargetIsSymlink(target)) return false;
- }
- if (backupRequested && resolve(src) !== resolve(target)) {
- const srcInfo = await lstat(src).catch(() => null);
- if (srcInfo && !srcInfo.isSymbolicLink()) return false;
- if (await cpTargetIsSymlink(target)) return false;
- }
- if ((opts["remove-destination"] || opts.rem) && resolve(src) !== resolve(target)) {
- const srcInfo = await lstat(src).catch(() => null);
- if (srcInfo && !srcInfo.isSymbolicLink()) return false;
- if (await cpTargetIsSymlink(target)) return false;
- }
- return true;
-}
-
-async function cpSameFile(src, target, opts) {
- if (opts.d || opts.P || opts["no-dereference"]) {
- const [srcInfo, targetInfo] = await Promise.all([lstat(src).catch(() => null), lstat(target).catch(() => null)]);
- if (srcInfo?.isSymbolicLink() && targetInfo?.isSymbolicLink()) return resolve(src) === resolve(target) && src === target;
- }
- return areSameFile(src, target);
-}
-
-async function cpUpdateDecision(src, target, opts, noDereference, overwriteMode = null) {
- if (overwriteMode === "no-clobber" || (overwriteMode == null && (opts.n || opts["no-clobber"]))) {
- if (await lstat(target).catch(() => null)) return { skip: true, fail: false };
- }
- if (!(opts.u || opts.update != null)) return { skip: false, fail: false };
- const mode = cpUpdateMode(opts, overwriteMode);
- if (mode === "all") return { skip: false, fail: false };
- const sourceInfo = await cpUpdateStat(src, noDereference);
- const targetInfo = await cpUpdateStat(target, noDereference);
- if (!targetInfo) return { skip: false, fail: false };
- if (mode === "none" || mode === "none-fail") return { skip: true, fail: mode === "none-fail" };
- if (!sourceInfo) return { skip: false, fail: false };
- if (sourceInfo.isDirectory()) return { skip: false, fail: false };
- if (sourceInfo.dev === targetInfo.dev && sourceInfo.ino === targetInfo.ino) return { skip: true, fail: false };
- return { skip: cpStatMtimeNs(targetInfo) >= cpStatMtimeNs(sourceInfo), fail: false };
-}
-
-async function cpUpdateStat(path, noDereference) {
- return (noDereference ? lstat(path, { bigint: true }) : stat(path, { bigint: true })).catch(() => null);
-}
-
-function cpStatMtimeNs(statInfo) {
- if (statInfo.mtimeNs != null) return BigInt(statInfo.mtimeNs);
- return BigInt(statInfo.mtimeMs) * 1_000_000n;
-}
-
-function cpUpdateMode(opts, overwriteMode = null) {
- if (overwriteMode === "no-clobber" || (overwriteMode == null && (opts.n || opts["no-clobber"]))) return "none";
- if (opts.update === true || opts.update == null) return "older";
- const mode = String(opts.update);
- if (mode === "older" || mode === "all" || mode === "none" || mode === "none-fail") return mode;
- validateUpdateMode("cp", mode);
-}
-
-function validateUpdateMode(program, mode) {
- if (["all", "none", "none-fail", "older"].includes(mode)) return;
- const kind = mode === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(mode)} for ${localeQuotedDiagnostic("--update")}\nValid arguments are:\n - ${localeQuotedDiagnostic("all")}\n - ${localeQuotedDiagnostic("none")}\n - ${localeQuotedDiagnostic("none-fail")}\n - ${localeQuotedDiagnostic("older")}`, true);
-}
-
-function validateReflinkMode(program, mode) {
- if (["auto", "always", "never"].includes(mode)) return;
- const kind = mode === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(mode)} for ${localeQuotedDiagnostic("--reflink")}\nValid arguments are:\n - ${localeQuotedDiagnostic("auto")}\n - ${localeQuotedDiagnostic("always")}\n - ${localeQuotedDiagnostic("never")}`, true);
-}
-
-function validateSparseMode(program, mode) {
- if (["never", "auto", "always"].includes(mode)) return;
- const kind = mode === "" ? "ambiguous" : "invalid";
- throw new UsageError(`${kind} argument ${localeQuotedEscapedDiagnostic(mode)} for ${localeQuotedDiagnostic("--sparse")}\nValid arguments are:\n - ${localeQuotedDiagnostic("never")}\n - ${localeQuotedDiagnostic("auto")}\n - ${localeQuotedDiagnostic("always")}`, true);
-}
-
-async function cpHardLinkSameFileIsNoop(src, target, opts, backupRequested) {
- if (backupRequested && (opts.f || opts.force) && resolve(src) === resolve(target)) return false;
- const targetInfo = await lstat(target).catch(() => null);
- return Boolean(targetInfo && !targetInfo.isSymbolicLink());
-}
-
-async function cpTargetIsSymlink(target) {
- return Boolean((await lstat(target).catch(() => null))?.isSymbolicLink());
-}
-
-async function cpTargetIsReplaceableSymlink(src, target) {
- if (resolve(src) === resolve(target)) return false;
- return cpTargetIsSymlink(target);
-}
-
-async function withPreservedCopyCreationContext(src, options, create) {
- if (!options.preserveContextAtCreation || !options.selinuxEnabled || !existsSync("/sys/fs/selinux/enforce")) {
- return { value: await create(), handled: false };
- }
- const context = selinuxSecurityContext(src, Boolean(options.noDereferenceContext));
- const api = context != null ? selinuxApi() : null;
- if (context == null && options.requirePreserveContext) {
- throw new UsageError(`failed to get security context of '${pathDisplayName(src)}'`);
- }
- let contextSet = false;
- if (api) {
- const encoded = cstr(context);
- if (api.symbols.security_check_context(encoded) === 0 && api.symbols.setfscreatecon(ptr(encoded)) === 0) {
- contextSet = true;
- } else if (options.requirePreserveContext) {
- throw new UsageError(`failed to set default file creation context to '${context}': Invalid argument`);
- }
- }
- try {
- return { value: await create(), handled: true };
- } finally {
- if (contextSet) api.symbols.setfscreatecon(null);
- }
-}
-
-function copyMetadataAfterCreationContext(options, handled) {
- return handled ? { ...options, preserveContext: false } : options;
-}
-
-function prepareRegularFilePreservedContext(src, dest, sourceStat, options) {
- if (!options.preserveContextAtCreation || !options.selinuxEnabled || !existsSync("/sys/fs/selinux/enforce")) return false;
- const context = selinuxSecurityContext(src, Boolean(options.noDereferenceContext));
- if (context == null) {
- if (options.requirePreserveContext) throw new UsageError(`failed to get security context of '${src}'`);
- return false;
- }
- const api = selinuxApi();
- let contextSet = false;
- if (api) {
- const encoded = cstr(context);
- if (api.symbols.security_check_context(encoded) === 0 && api.symbols.setfscreatecon(ptr(encoded)) === 0) contextSet = true;
- }
- try {
- // Create or truncate before copying any bytes. Besides keeping the
- // thread-local fscreate context on this thread, this lets an explicitly
- // requested --preserve=context fail with an empty destination on a
- // fixed-context filesystem, as GNU cp does.
- const fd = openSync(dest, "w", cpDefaultFileMode(options.useSourceModeForNewRegularFiles ? sourceStat.mode : undefined));
- closeSync(fd);
- } finally {
- if (contextSet) api.symbols.setfscreatecon(null);
- }
- const actual = selinuxSecurityContext(dest);
- const preserved = actual === context || setSelinuxSecurityContext(dest, context);
- if (!preserved && options.requirePreserveContext) throw new UsageError(`failed to set the security context of '${dest}'`);
- // Archive/all preservation treats an unsupported context as ignorable;
- // either way, do not attempt it again after data has been copied.
- return true;
-}
-
-async function copyPath(src, dest, options, topLevel = false) {
- const dereferenceSource = cpShouldDereferenceSource(src, options, topLevel);
- if (options.hardLink) {
- const srcInfo = await lstat(src).catch(() => null);
- const destInfo = options.force || options.removeDestination ? null : await lstat(dest).catch(() => null);
- if (!dereferenceSource && srcInfo?.isSymbolicLink() && destInfo?.isSymbolicLink() && await readlink(src).catch(() => null) === await readlink(dest).catch(() => null) && !(options.force || options.removeDestination)) return;
- const dereferencedInfo = !dereferenceSource ? srcInfo : await stat(src).catch((error) => {
- if (error?.code === "ENOENT") throw new UsageError(`cannot stat '${src}': No such file or directory`);
- throw error;
- });
- if (dereferencedInfo?.isDirectory()) {
- if (!options.recursive) throw new UsageError(`-r not specified; omitting directory '${src}'`);
- const destInfo = await lstat(dest).catch(() => null);
- await mkdir(dest, { recursive: true, mode: cpInitialDirectoryCreateMode(dereferencedInfo.mode, options) });
- if (options.verbose && !destInfo && !topLevel) stdout(`created directory '${dest}'\n`);
- if (options.oneFileSystem && !topLevel && dereferencedInfo.dev !== options.rootDev) {
- if (options.preserveDirectoryMode && !destInfo) await setFileMode(dest, dereferencedInfo.mode & 0o7777).catch(() => {});
- return;
- }
- const dirSource = !dereferenceSource ? src : await realpath(src);
- for await (const entry of iterateDirectoryPathEntries(dirSource)) await copyPath(pathLikeJoin(dirSource, entry), pathLikeJoin(dest, entry), options);
- if (options.preserveDirectoryMode && !destInfo) await setFileMode(dest, dereferencedInfo.mode & 0o7777).catch(() => {});
- return;
- }
- if (options.force || options.removeDestination) await rm(dest, { force: true, recursive: true });
- let linkSource = src;
- if (dereferenceSource) {
- try {
- linkSource = await realpath(src);
- } catch (error) {
- if (error?.code === "ENOENT") throw new UsageError(`cannot stat '${src}': No such file or directory`);
- throw error;
- }
- }
- try {
- await fsLink(linkSource, dest);
- } catch (error) {
- if (error.code === "EEXIST") throw new UsageError(`cannot create hard link '${dest}' to '${src}'`);
- throw error;
- }
- if (options.verbose) stdout(`'${dest}' => '${src}'\n`);
- return;
- }
- if (options.symbolicLink) {
- if (options.force || options.removeDestination) await rm(dest, { force: true, recursive: true });
- try {
- await symlink(src, dest);
- } catch (error) {
- if (error.code === "EEXIST") throw new UsageError(`cannot create symbolic link '${dest}' to '${src}'`);
- throw error;
- }
- if (options.verbose) stdout(`'${dest}' -> '${src}'\n`);
- return;
- }
- const s = await lstat(src);
- const sourceStat = dereferenceSource && s.isSymbolicLink() ? await stat(src).catch((error) => {
- if (error?.code === "ENOENT") throw new UsageError(`cannot stat '${src}': No such file or directory`);
- throw error;
- }) : s;
- statAttachNanoseconds(sourceStat, src, dereferenceSource);
- const preservedLink = await cpMaybePreserveExistingLink(src, dest, sourceStat, s, dereferenceSource, options);
- if (preservedLink) {
- if (options.verbose) stdout(`'${src}' -> '${dest}'\n`);
- return;
- }
- if (sourceStat.isDirectory()) {
- if (!options.recursive) throw new UsageError(`-r not specified; omitting directory '${src}'`);
- let destInfo = await lstat(dest).catch(() => null);
- if (destInfo?.isSymbolicLink() && options.keepDirectorySymlink) {
- const followed = await stat(dest).catch(() => null);
- if (followed?.isDirectory()) destInfo = followed;
- }
- if (destInfo && !destInfo.isDirectory()) throw new UsageError(`cannot overwrite non-directory '${dest}' with directory '${src}'`);
- const directoryCreation = destInfo
- ? { handled: false }
- : await withPreservedCopyCreationContext(src, options, () => mkdirSync(dest, { recursive: true, mode: cpInitialDirectoryCreateMode(sourceStat.mode, options) }));
- if (destInfo) await mkdir(dest, { recursive: true, mode: cpInitialDirectoryCreateMode(sourceStat.mode, options) });
- if (options.verbose && !destInfo && !topLevel) stdout(`created directory '${dest}'\n`);
- // GNU cp -x still creates a mountpoint directory, but does not descend
- // into a directory that lives on another filesystem.
- const crossFileSystemDirectory = options.oneFileSystem && !topLevel && sourceStat.dev !== options.rootDev;
- const dirSource = dereferenceSource && s.isSymbolicLink() ? await realpath(src) : src;
- let copyError = null;
- if (!crossFileSystemDirectory) {
- try {
- for await (const entry of iterateDirectoryPathEntries(dirSource)) await copyPath(pathLikeJoin(dirSource, entry), pathLikeJoin(dest, entry), options);
- } catch (error) {
- copyError = error;
- }
- }
- if (options.preserveDirectoryMode && !destInfo) await setFileMode(dest, sourceStat.mode & 0o7777).catch(() => {});
- // Restore directory metadata after descendants have been copied. This
- // includes POSIX ACLs when mode preservation was requested; keeping the
- // initial restrictive mode during traversal avoids making a directory
- // prematurely accessible.
- await applyCopyMetadata(dest, sourceStat, { ...copyMetadataAfterCreationContext(options, directoryCreation.handled), preserveMode: options.preserveMode, sourcePath: src });
- if (copyError) throw copyError;
- return;
- } else if (s.isSymbolicLink() && !dereferenceSource) {
- const linkTarget = await readlink(src);
- const destInfo = options.force || options.removeDestination ? null : await lstat(dest).catch(() => null);
- if (destInfo?.isSymbolicLink() && await readlink(dest).catch(() => null) === linkTarget && !(options.force || options.removeDestination)) return;
- if (options.force || options.removeDestination) await rm(dest, { force: true, recursive: true });
- const symlinkCreation = await withPreservedCopyCreationContext(src, { ...options, noDereferenceContext: true }, () => symlink(linkTarget, dest));
- if (options.preserveMetadata || options.preserveMode || options.preserveContext || options.restoreContext || options.explicitContext != null) {
- await applySymlinkCopyMetadata(dest, sourceStat, { ...copyMetadataAfterCreationContext(options, symlinkCreation.handled), sourcePath: src });
- }
- } else {
- if (options.removeDestination) await rm(dest, { force: true });
- if (await cpDestinationIsDanglingSymlink(dest)) {
- await cpHandleDanglingDestinationSymlink(src, dest, options);
- return;
- }
- let destInfo = await lstat(dest).catch(() => null);
- if (String(dest).endsWith("/") && !destInfo?.isDirectory()) throw new UsageError(`cannot create regular file '${dest}': Not a directory`);
- if (destInfo?.isDirectory()) throw new UsageError(`cannot overwrite directory '${dest}' with non-directory '${src}'`);
- if (cpShouldRecreateSpecialFile(sourceStat, options)) {
- if (destInfo) await rm(dest, { force: true });
- const specialCreation = await withPreservedCopyCreationContext(src, options, () => cpCreateSpecialFile(dest, sourceStat));
- await applyCopyMetadata(dest, sourceStat, { ...copyMetadataAfterCreationContext(options, specialCreation.handled), preserveMode: true, sourcePath: src });
- } else if (options.attributesOnly) {
- const attributeCreation = !destInfo
- ? await withPreservedCopyCreationContext(src, options, () => writeFile(dest, ""))
- : { handled: false };
- await applyCopyMetadata(dest, sourceStat, { ...copyMetadataAfterCreationContext(options, attributeCreation.handled), sourcePath: src });
- if (!options.preserveMode && !destInfo) await setFileMode(dest, cpDefaultFileMode(options.useSourceModeForNewRegularFiles ? sourceStat.mode : undefined)).catch(() => {});
- cpRememberPreservedLink(dest, sourceStat, options);
- } else {
- const contextPrepared = prepareRegularFilePreservedContext(src, dest, sourceStat, options);
- const copyContents = async () => {
- if (options.destinationWasReportedExisting && !destInfo) {
- options.destinationWasReportedExisting = false;
- try {
- const staleTarget = await open(dest, "r+");
- await staleTarget.close();
- } catch (error) {
- if (error?.code !== "ENOENT") throw error;
- }
- }
- return cpCopyFileContents(src, dest, sourceStat, options);
- };
- const copyWithRecovery = () => copyContents().catch(async (error) => {
- if (error.code === "EEXIST" && await cpDestinationIsDanglingSymlink(dest)) return cpHandleDanglingDestinationSymlink(src, dest, options);
- if ((error.code === "EEXIST" || error.code === "EACCES" || error.code === "EPERM") && options.force) {
- await rm(dest, { force: true });
- destInfo = null;
- return cpCopyFileContents(src, dest, sourceStat, options);
- }
- if (error.code === "EEXIST" && await cpCanWriteThroughDestinationSymlink(dest)) return cpCopyFileContents(src, dest, sourceStat, options);
- throw error;
- });
- const fileCreation = contextPrepared
- ? { value: await copyWithRecovery(), handled: true }
- : await withPreservedCopyCreationContext(src, options, copyWithRecovery);
- if (!cpShouldReadUntilEof(src, sourceStat) && !cpCopiedSpecialContents(sourceStat, options)) await truncate(dest, sourceStat.size).catch(() => {});
- await applyCopyMetadata(dest, sourceStat, { ...copyMetadataAfterCreationContext(options, fileCreation.handled), sourcePath: src });
- if (!options.preserveMode && destInfo && !destInfo.isSymbolicLink()) await setFileMode(dest, destInfo.mode & 0o7777).catch(() => {});
- else if (!options.preserveMode && !destInfo) await setFileMode(dest, cpDefaultFileMode(options.useSourceModeForNewRegularFiles ? sourceStat.mode : undefined)).catch(() => {});
- cpRememberPreservedLink(dest, sourceStat, options);
- if (options.debug) {
- if (options.verbose && (!topLevel || !sourceStat.isDirectory())) stdout(`'${src}' -> '${dest}'\n`);
- stdout(cpDebugLine(options));
- return;
- }
- }
- }
- if (options.verbose && (!topLevel || !sourceStat.isDirectory())) stdout(`'${src}' -> '${dest}'\n`);
-}
-
-async function cpCopyFileContents(src, dest, sourceStat, options = {}) {
- if (cpShouldReadUntilEof(src, sourceStat) || cpCopiedSpecialContents(sourceStat, options)) {
- await cpCopyStreamContents(src, dest);
- return;
- }
- if (sourceStat?.isFile?.() && options.reflinkMode && options.reflinkMode !== "never") {
- if (cpCloneFile(src, dest, sourceStat.mode)) {
- options.reflinkAttempted = true;
- return;
- }
- if (options.reflinkMode === "always") throw new UsageError(`failed to clone '${src}' from '${dest}': Operation not supported`);
- }
- if (options.sparseMode === "never") {
- await cpCopyRegularFileContents(src, dest, sourceStat, { sparse: false });
- return;
- }
- if (options.sparseMode === "always" || cpSourceLooksSparse(sourceStat)) {
- const sparseDetection = await cpCopyRegularFileContents(src, dest, sourceStat, { sparse: true, scanZeros: options.sparseMode === "always" });
- if (sparseDetection) options.sparseDetection = sparseDetection;
- return;
- }
- await copyFile(src, dest);
-}
-
-function cpDebugLine(options) {
- const offload = options.sparseMode === "never" || options.reflinkMode === "never" ? "avoided" : "unknown";
- const sparseDetection = options.sparseMode === "never" ? "no" : options.sparseDetection ?? "unknown";
- return `copy offload: ${offload}, reflink: ${options.reflinkAttempted ? "yes" : "no"}, sparse detection: ${sparseDetection}\n`;
-}
-
-function cpCloneFile(src, dest, sourceMode = 0o666) {
- if (typeof src !== "string" || typeof dest !== "string") return false;
- let sourceFd = -1;
- let destFd = -1;
- const temp = join(pathDirname(dest), `.${pathBasename(dest)}.bnu-reflink-${process.pid}-${reflinkTempId++}`);
- let cloned = false;
- try {
- sourceFd = openSync(src, "r");
- destFd = openSync(temp, "wx", sourceMode & 0o777);
- if (libc.symbols.ioctl(destFd, FICLONE, sourceFd) !== 0) return false;
- cloned = true;
- closeSync(destFd);
- destFd = -1;
- renameSync(temp, dest);
- return true;
- } catch {
- return false;
- } finally {
- if (destFd >= 0) closeSync(destFd);
- if (sourceFd >= 0) closeSync(sourceFd);
- if (!cloned) {
- try {
- unlinkSync(temp);
- } catch {}
- }
- }
-}
-
-async function cpCopyRegularFileContents(src, dest, sourceStat, options = {}) {
- const destInfo = await stat(dest).catch(() => null);
- if (destInfo && !destInfo.isFile()) {
- await cpCopyStreamContents(src, dest);
- return;
- }
- const source = await open(src, "r");
- const target = await open(dest, "w", 0o600);
- const buffer = Buffer.allocUnsafe(64 * 1024);
- let position = 0;
- let copiedExtents = false;
- try {
- copiedExtents = options.sparse && await cpCopySparseExtents(source, target, sourceStat.size, buffer, options.scanZeros);
- if (!copiedExtents) {
- while (position < sourceStat.size) {
- const { bytesRead } = await source.read(buffer, 0, Math.min(buffer.length, sourceStat.size - position), position);
- if (bytesRead === 0) break;
- const chunk = buffer.subarray(0, bytesRead);
- if (!(options.sparse && ddBufferIsZero(chunk))) await target.write(chunk, 0, chunk.length, position);
- position += bytesRead;
- }
- }
- } finally {
- await source.close().catch(() => {});
- await target.close().catch(() => {});
- }
- await truncate(dest, sourceStat.size);
- return options.scanZeros ? "zeros" : options.sparse && copiedExtents ? "SEEK_HOLE" : null;
-}
-
-async function cpCopySparseExtents(source, target, size, buffer, scanZeros = false) {
- let offset = 0;
- while (offset < size) {
- const dataResult = libc.symbols.lseek(source.fd, BigInt(offset), SEEK_DATA);
- if (dataResult < 0) {
- const errno = libcErrno();
- return errno === 6; // ENXIO means there is no more data after the final hole.
- }
- const data = Number(dataResult);
- const holeResult = libc.symbols.lseek(source.fd, BigInt(data), SEEK_HOLE);
- if (holeResult < 0) return false;
- const hole = Math.min(size, Number(holeResult));
- let position = data;
- while (position < hole) {
- const { bytesRead } = await source.read(buffer, 0, Math.min(buffer.length, hole - position), position);
- if (bytesRead === 0) break;
- const chunk = buffer.subarray(0, bytesRead);
- if (!scanZeros || !ddBufferIsZero(chunk)) await target.write(chunk, 0, bytesRead, position);
- position += bytesRead;
- }
- if (position < hole) return false;
- offset = hole;
- }
- return true;
-}
-
-function cpSourceLooksSparse(sourceStat) {
- return sourceStat?.isFile?.() && sourceStat.size > 0 && sourceStat.blocks != null && sourceStat.blocks * 512 < sourceStat.size;
-}
-
-async function cpCopyStreamContents(src, dest) {
- const destExisted = Boolean(await lstat(dest).catch(() => null));
- const source = await open(src, "r");
- const target = await open(dest, "w", 0o600);
- const buffer = Buffer.allocUnsafe(64 * 1024);
- try {
- if (!destExisted) await setFileMode(dest, 0o600).catch(() => {});
- while (true) {
- const { bytesRead } = await source.read(buffer, 0, buffer.length, null);
- if (bytesRead === 0) break;
- await target.write(buffer.subarray(0, bytesRead));
- }
- } finally {
- await source.close().catch(() => {});
- await target.close().catch(() => {});
- }
-}
-
-function cpCopiedSpecialContents(sourceStat, options = {}) {
- return Boolean(options.copyContents && !sourceStat?.isFile?.());
-}
-
-function cpShouldReadUntilEof(src, sourceStat) {
- if (sourceStat?.isCharacterDevice?.()) return true;
- if (!sourceStat?.isFile?.()) return false;
- const path = pathDisplayName(src);
- return path === "/proc" || path.startsWith("/proc/") || path === "/sys" || path.startsWith("/sys/");
-}
-
-async function cpMaybePreserveExistingLink(src, dest, sourceStat, linkStat, dereferenceSource, options) {
- if (!options.preserveLinks || !options.linkMap || !sourceStat.isFile()) return false;
- if (linkStat.isSymbolicLink() && !dereferenceSource) return false;
- const key = cpLinkKey(sourceStat);
- const previousDest = options.linkMap.get(key);
- if (!previousDest) return false;
- if (options.removeDestination || options.force) await rm(dest, { force: true, recursive: true });
- else if (await lstat(dest).catch(() => null)) await rm(dest, { force: true, recursive: true });
- await fsLink(previousDest, dest);
- return true;
-}
-
-function cpRememberPreservedLink(dest, sourceStat, options) {
- if (!options.preserveLinks || !options.linkMap || !sourceStat.isFile()) return;
- const key = cpLinkKey(sourceStat);
- if (!options.linkMap.has(key)) options.linkMap.set(key, dest);
-}
-
-function cpLinkKey(statInfo) {
- return `${statInfo.dev}:${statInfo.ino}`;
-}
-
-function cpDirectoryCreateMode(sourceMode, options) {
- if (!options.preserveDirectoryMode) return cpDefaultDirectoryMode();
- return (sourceMode & 0o7777) | 0o700;
-}
-
-function cpInitialDirectoryCreateMode(sourceMode, options) {
- if (options.preserveMode || options.preserveMetadata) return cpRestrictiveDirectoryMode(sourceMode);
- return cpDirectoryCreateMode(sourceMode, options);
-}
-
-function cpDefaultFileMode(sourceMode = 0o666) {
- return (sourceMode & 0o777) & ~process.umask();
-}
-
-function cpDefaultDirectoryMode() {
- return 0o777 & ~process.umask();
-}
-
-async function cpCreateFifo(path, mode) {
- if (libc.symbols.mkfifo(cstr(path), mode) !== 0) throw new Error(`cannot create fifo '${path}'`);
- await setFileMode(path, mode).catch(() => {});
-}
-
-function cpShouldRecreateSpecialFile(sourceStat, options) {
- return options.recursive && !options.copyContents
- && (sourceStat.isFIFO() || sourceStat.isCharacterDevice() || sourceStat.isBlockDevice() || sourceStat.isSocket());
-}
-
-async function cpCreateSpecialFile(path, sourceStat) {
- if (sourceStat.isFIFO()) return cpCreateFifo(path, sourceStat.mode & 0o7777);
- if (libc.symbols.mknod(cstrPath(path), sourceStat.mode >>> 0, sourceStat.rdev) !== 0) {
- const errno = libcErrno();
- const error = new Error(`mknod failed (errno ${errno})`);
- error.code = ({ 1: "EPERM", 13: "EACCES", 17: "EEXIST", 22: "EINVAL" })[errno] ?? "EIO";
- throw error;
- }
-}
-
-function cpShouldDereferenceSource(src, options, topLevel) {
- if (String(src).endsWith("/")) return true;
- if (options.noDereference) return false;
- if (options.dereferenceAll) return true;
- if (options.dereferenceCommandLine && topLevel) return true;
- if (options.hardLink && topLevel) return !options.preserveLinks;
- return topLevel && !options.recursive;
-}
-
-async function cpCanWriteThroughDestinationSymlink(dest) {
- const info = await lstat(dest).catch(() => null);
- if (!info?.isSymbolicLink()) return false;
- return Boolean(await stat(dest).catch(() => null));
-}
-
-async function cpDestinationIsDanglingSymlink(dest) {
- const info = await lstat(dest).catch(() => null);
- if (!info?.isSymbolicLink()) return false;
- try {
- await stat(dest);
- return false;
- } catch (error) {
- if (error?.code === "ENOENT" || error?.code === "ELOOP") return true;
- throw new UsageError(`cannot stat '${dest}': ${errnoMessage(error)}`);
- }
-}
-
-async function cpHandleDanglingDestinationSymlink(src, dest, options) {
- const linkTarget = await readlink(dest);
- if (process.env.POSIXLY_CORRECT) return copyFile(src, isAbsolute(linkTarget) ? linkTarget : join(pathDirname(dest), linkTarget));
- if (options.force && linkTarget === pathBasename(dest)) {
- await rm(dest, { force: true });
- return copyFile(src, dest);
- }
- throw new UsageError(`not writing through dangling symlink '${dest}'`);
-}
-
-async function applyCopyMetadata(path, s, options) {
- if (!options.preserveMetadata && !options.preserveMode && !options.preserveXattrs && !options.preserveContext && !options.restoreContext && options.explicitContext == null) return;
- await applyCopySecurityContext(path, options.sourcePath, options);
- if (options.preserveMode && options.sourcePath != null) await copyPosixAcl(options.sourcePath, path).catch(() => {});
- let ownershipPreserved = true;
- if (options.preserveMetadata) {
- let current = await stat(path).catch(() => null);
- if (!current || current.uid !== s.uid) {
- await chown(path, s.uid, current?.gid ?? s.gid).catch(() => { ownershipPreserved = false; });
- current = await stat(path).catch(() => current);
- }
- // Preserve the group independently. A non-root owner may be unable to
- // assume the source UID but can still select a supplementary source GID.
- if (!current || current.gid !== s.gid) {
- await chown(path, current?.uid ?? s.uid, s.gid).catch(() => { ownershipPreserved = false; });
- current = await stat(path).catch(() => current);
- }
- ownershipPreserved = ownershipPreserved && current?.uid === s.uid && current?.gid === s.gid;
- await touchSetPathTimes(path, touchStatDate(s, "atime"), touchStatDate(s, "mtime"), false).catch(() => {});
- }
- // chown(2) clears security.capability. Apply xattrs only after ownership
- // has reached its final value so --preserve=xattr/all retains file caps.
- if (options.preserveXattrs && options.sourcePath != null) {
- try {
- await copyExtendedAttributes(options.sourcePath, path, Boolean(options.noDereferenceContext));
- } catch (error) {
- if (options.requirePreserveXattrs) throw error;
- }
- }
- // chown(2) clears setuid/setgid bits, so restore the source mode last.
- // If ownership could not be preserved, GNU cp deliberately leaves those
- // privilege bits cleared rather than granting them to the copying user.
- if (options.preserveMode) {
- const mode = (s.mode & 0o7777) & (ownershipPreserved ? 0o7777 : ~0o6000);
- await setFileMode(path, mode).catch(() => {});
- }
-}
-
-async function copyPosixAcl(src, dest) {
- let dumped;
- try {
- dumped = Bun.spawnSync(["getfacl", "--absolute-names", "--", String(src)], { stdout: "pipe", stderr: "ignore" });
- } catch {
- return;
- }
- if (dumped.exitCode !== 0 || !dumped.stdout?.byteLength) return;
- const lines = new TextDecoder().decode(dumped.stdout).split(/\r?\n/);
- const fileLine = lines.findIndex((line) => line.startsWith("# file: "));
- if (fileLine < 0) return;
- lines[fileLine] = `# file: ${dest}`;
- const dir = await mkdtemp("/tmp/bnu-acl-");
- const restore = join(dir, "restore");
- try {
- await writeFile(restore, lines.join("\n"));
- Bun.spawnSync(["setfacl", "--restore", restore], { stdout: "ignore", stderr: "ignore" });
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
-}
-
-async function applySymlinkCopyMetadata(path, s, options) {
- if (!options.preserveMetadata && !options.preserveMode && !options.preserveXattrs && !options.preserveContext && !options.restoreContext && options.explicitContext == null) return;
- await applyCopySecurityContext(path, options.sourcePath, { ...options, noDereferenceContext: true });
- if (options.preserveXattrs && options.sourcePath != null) {
- try {
- await copyExtendedAttributes(options.sourcePath, path, true);
- } catch (error) {
- if (options.requirePreserveXattrs) throw error;
- }
- }
- if (options.preserveMetadata) {
- await touchSetPathTimes(path, touchStatDate(s, "atime"), touchStatDate(s, "mtime"), true).catch(() => {});
- await lchown(path, s.uid, s.gid).catch(() => {});
- }
-}
-
-async function applyCopySecurityContext(path, sourcePath, options) {
- if (!options.selinuxEnabled) return;
- const noDereference = Boolean(options.noDereferenceContext);
- if (options.explicitContext != null) {
- if (!setSelinuxSecurityContext(path, options.explicitContext, noDereference)) throw new UsageError(`failed to set the security context of '${path}'`);
- return;
- }
- if (options.restoreContext) {
- // -Z starts from the source label even when the destination already
- // exists. restorecon may then replace it with a pathname default; if no
- // default exists, GNU cp leaves this source label in place.
- if (options.preserveContextAtCreation && sourcePath != null) {
- const sourceContext = selinuxSecurityContext(sourcePath, noDereference);
- if (sourceContext != null) setSelinuxSecurityContext(path, sourceContext, noDereference);
- }
- if (!restoreSelinuxSecurityContext(path, noDereference) && options.requireRestoreContext) {
- throw new UsageError(`failed to restore the security context of '${path}'`);
- }
- return;
- }
- if (!options.preserveContext || sourcePath == null) return;
- const context = selinuxSecurityContext(sourcePath, noDereference);
- if (context == null) {
- if (options.requirePreserveContext) throw new UsageError(`failed to get security context of '${sourcePath}'`);
- return;
- }
- if (!setSelinuxSecurityContext(path, context, noDereference) && options.requirePreserveContext) {
- throw new UsageError(`failed to set the security context of '${path}'`);
- }
-}
-
-async function copyExtendedAttributes(src, dest, noDereference = false) {
- const getArgs = ["getfattr", ...(noDereference ? ["-h"] : []), "--dump", "--absolute-names", "-m", "-", String(src)];
- const dumped = Bun.spawnSync(getArgs, { stdout: "pipe", stderr: "pipe" });
- if (dumped.exitCode !== 0) throw new UsageError(`setting attributes for '${dest}': ${xattrToolError(dumped.stderr)}`);
- const text = new TextDecoder().decode(dumped.stdout ?? new Uint8Array());
- const attributes = text.split(/\r?\n/).filter((line) => /^[^#=][^=]*=/.test(line)
- && !line.startsWith("security.selinux=") && !line.startsWith("system.posix_acl_"));
- const destStat = noDereference ? null : await lstat(dest).catch(() => null);
- const restoreMode = destStat && (destStat.mode & 0o200) === 0 ? destStat.mode & 0o7777 : null;
- try {
- if (restoreMode != null) await setFileMode(dest, restoreMode | 0o200);
- for (const attribute of attributes) {
- const equals = attribute.indexOf("=");
- const name = attribute.slice(0, equals);
- const value = attribute.slice(equals + 1);
- const result = Bun.spawnSync(["setfattr", ...(noDereference ? ["-h"] : []), "-n", name, "-v", value, String(dest)], { stdout: "ignore", stderr: "pipe" });
- if (result.exitCode !== 0) throw new UsageError(`setting attributes for '${dest}': ${xattrToolError(result.stderr)}`);
- }
- } finally {
- if (restoreMode != null) await setFileMode(dest, restoreMode).catch(() => {});
- }
-}
-
-function xattrToolError(output) {
- const message = new TextDecoder().decode(output ?? new Uint8Array()).trim();
- return message.match(/: ([^:\n]+)$/)?.[1] || "Operation not supported";
-}
-
-async function mvCmd(args) {
- args = normalizeMvArgs(args);
- const { opts, operands } = parseOptions(args, { short: { f: false, i: false, n: false, u: false, t: "value", T: false, v: false, b: false, S: "value", Z: false }, long: { context: false, force: false, interactive: false, "no-clobber": false, "no-copy": false, update: "optional-value", target: "value", "target-directory": "value", "no-target-directory": false, "strip-trailing-slashes": false, verbose: false, debug: false, exchange: false, backup: "optional-value", b: "optional-value", suffix: "value", help: false, version: false } });
- const selinuxEnabled = selinuxRuntimeEnabled();
- const securityContext = {
- selinuxEnabled,
- restoreContext: selinuxEnabled && Boolean(opts.Z || opts.context),
- preserveContext: selinuxEnabled && !(opts.Z || opts.context),
- };
- if (opts.target != null && opts["target-directory"] == null) opts["target-directory"] = opts.target;
- if (opts.b != null && opts.backup == null) opts.backup = opts.b;
- if (opts.S != null && opts.suffix == null) opts.suffix = opts.S;
- const { sources, dest, useDirectoryTarget } = await resolveDestinationOperands("mv", operands, opts);
- const backupRequested = opts.b || opts.backup != null;
- if (backupRequested) validateBackupMode("mv", opts.backup);
- const overwriteMode = mvOverwriteMode(args, opts);
- const forceOverwrite = mvForceOverwriteIsEffective(args);
- if (backupRequested && (opts.exchange || overwriteMode === "no-clobber" || opts.update === "none" || opts.update === "none-fail")) {
- throw new UsageError("cannot combine --backup with --exchange, -n, or --update=none-fail", true);
- }
- if (opts.exchange) return mvExchangeCmd(sources, dest, useDirectoryTarget, opts, securityContext);
- const seenSources = new Set();
- const createdTargets = new Set();
- const linkMap = new Map();
- let status = 0;
- for (const src of sources) {
- const normalizedSrc = opts["strip-trailing-slashes"] ? stripTrailingSlashesPath(src) : src;
- try {
- const target = useDirectoryTarget ? join(dest, pathBasename(normalizedSrc)) : dest;
- const sourceInfo = await lstat(normalizedSrc).catch((error) => {
- if (error?.code === "ENOENT") throw new UsageError(`cannot stat '${src}': No such file or directory`);
- throw error;
- });
- const sourceKey = `${sourceInfo.dev}:${sourceInfo.ino}`;
- if (sourceInfo.isDirectory() && seenSources.has(sourceKey)) {
- stderr(`mv: warning: source directory '${cpDuplicateDisplayName(src)}' specified more than once\n`);
- continue;
- }
- seenSources.add(sourceKey);
- await ensureMvNotIntoSelf(src, target, sourceInfo);
- const targetKey = resolve(target);
- if (!backupRequested && createdTargets.has(targetKey)) throw new UsageError(`will not overwrite just-created '${target}' with '${src}'`);
- if (!backupRequested && await areSameFile(normalizedSrc, target) && !await mvSameFileIsAllowed(normalizedSrc, target, sourceInfo)) throw new UsageError(`'${src}' and '${target}' are the same file`);
- await ensureMvTargetTypeCompatible(src, target, sourceInfo);
- const updateDecision = await cpUpdateDecision(normalizedSrc, target, opts, false, overwriteMode);
- if (updateDecision.skip) {
- if (updateDecision.fail) {
- stderr(`mv: not replacing '${target}'\n`);
- status = 1;
- }
- continue;
- }
- const targetInfo = await lstat(target).catch(() => null);
- const writeProtected = targetInfo && await mvTargetIsWriteProtected(target, targetInfo);
- const shouldPrompt = targetInfo && (overwriteMode === "interactive"
- || (overwriteMode === "replace" && !forceOverwrite && writeProtected && process.stdin.isTTY));
- if (shouldPrompt && !confirmRemoval(mvOverwritePrompt(target, targetInfo, writeProtected))) {
- status = 1;
- continue;
- }
- if (backupRequested) await ensureBackupDoesNotDestroySource("mv", normalizedSrc, target, opts.suffix, opts.backup);
- const backupName = backupRequested ? await backupDestination(target, opts.suffix, opts.backup) : "";
- const renamed = await mvRenameOrCopy(normalizedSrc, target, sourceInfo, opts, mvDisplayTarget(src, target, useDirectoryTarget), linkMap, securityContext);
- createdTargets.add(targetKey);
- if (renamed && (opts.v || opts.verbose || opts.debug)) stdout(`renamed '${src}' -> '${target}'${backupName ? ` (backup: '${backupName}')` : ""}\n`);
- } catch (error) {
- status = 1;
- if (error instanceof UsageError) stderr(`mv: ${error.message}\n`);
- else stderr(`mv: ${error.message || String(error)}\n`);
- }
- }
- return status;
-}
-
-function normalizeMvArgs(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--") {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(arg.startsWith("--") ? normalizeLongOptionByPrefix(arg, MV_LONG_OPTIONS) : arg);
- }
- return out;
-}
-
-async function mvExchangeCmd(sources, dest, useDirectoryTarget, opts, securityContext) {
- if (!useDirectoryTarget && sources.length !== 1) throw new UsageError(`extra operand '${sources[1] ?? dest}'`, true);
- let status = 0;
- for (const source of sources) {
- const src = opts["strip-trailing-slashes"] ? stripTrailingSlashesPath(source) : source;
- const target = useDirectoryTarget ? join(dest, pathBasename(src)) : dest;
- const exchanged = await mvExchangePair(src, target, opts, securityContext);
- if (!exchanged) status = 1;
- }
- return status;
-}
-
-async function mvExchangePair(src, target, opts, securityContext) {
- try {
- const sourceInfo = await lstat(src).catch((error) => {
- if (error?.code === "ENOENT") throw new UsageError(`cannot stat '${src}': No such file or directory`);
- throw error;
- });
- const targetInfo = await lstat(target);
- if (libc.symbols.renameat2(AT_FDCWD, cstrPath(src), AT_FDCWD, cstrPath(target), RENAME_EXCHANGE) !== 0) {
- throw new UsageError(`cannot exchange '${src}' and '${target}': Operation not supported`);
- }
- if (securityContext.restoreContext) {
- if (!restoreSelinuxSecurityContext(src, targetInfo.isSymbolicLink(), targetInfo.isDirectory())) {
- throw new UsageError(`failed to restore the security context of '${src}'`);
- }
- if (!restoreSelinuxSecurityContext(target, sourceInfo.isSymbolicLink(), sourceInfo.isDirectory())) {
- throw new UsageError(`failed to restore the security context of '${target}'`);
- }
- }
- if (opts.v || opts.verbose || opts.debug) stdout(`exchanged '${src}' <-> '${target}'\n`);
- return true;
- } catch (error) {
- if (error instanceof UsageError) stderr(`mv: ${error.message}\n`);
- else stderr(`mv: cannot exchange '${src}' and '${target}': ${errnoMessage(error)}\n`);
- return false;
- }
-}
-
-function mvOverwriteMode(args, opts) {
- let mode = "replace";
- let sawOverwriteOption = false;
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") break;
- if (arg === "-i" || arg === "--interactive") { mode = "interactive"; sawOverwriteOption = true; }
- else if (arg === "-n" || arg === "--no-clobber") { mode = "no-clobber"; sawOverwriteOption = true; }
- else if (arg === "-f" || arg === "--force") { mode = "replace"; sawOverwriteOption = true; }
- else if (/^-[^-]/.test(arg)) {
- for (const ch of arg.slice(1)) {
- if (ch === "i") { mode = "interactive"; sawOverwriteOption = true; }
- else if (ch === "n") { mode = "no-clobber"; sawOverwriteOption = true; }
- else if (ch === "f") { mode = "replace"; sawOverwriteOption = true; }
- }
- }
- }
- if (!sawOverwriteOption && (opts.i || opts.interactive)) return "interactive";
- if (!sawOverwriteOption && (opts.n || opts["no-clobber"])) return "no-clobber";
- return mode;
-}
-
-function mvForceOverwriteIsEffective(args) {
- let forced = false;
- for (const arg of args) {
- if (arg === "--") break;
- if (arg === "-f" || arg === "--force") forced = true;
- else if (arg === "-i" || arg === "--interactive" || arg === "-n" || arg === "--no-clobber") forced = false;
- else if (/^-[^-]/.test(arg)) {
- for (const ch of arg.slice(1)) {
- if (ch === "f") forced = true;
- else if (ch === "i" || ch === "n") forced = false;
- }
- }
- }
- return forced;
-}
-
-async function mvTargetIsWriteProtected(target, targetInfo) {
- if (targetInfo.isSymbolicLink()) return false;
- try {
- await access(target, fsConstants.W_OK);
- return false;
- } catch {
- return true;
- }
-}
-
-function mvOverwritePrompt(target, targetInfo, writeProtected) {
- if (writeProtected) {
- const mode = (targetInfo.mode & 0o7777).toString(8).padStart(4, "0");
- return `mv: replace '${target}', overriding mode ${mode} (${modeString(targetInfo).slice(1)})? `;
- }
- return `mv: overwrite '${target}'? `;
-}
-
-async function ensureMvTargetTypeCompatible(src, target, sourceInfo) {
- const targetInfo = await lstat(target).catch(() => null);
- if (!targetInfo) return;
- if (targetInfo.isDirectory() && !targetInfo.isSymbolicLink() && !sourceInfo.isDirectory()) {
- throw new UsageError(`cannot overwrite directory '${target}' with non-directory '${src}'`);
- }
- if (sourceInfo.isDirectory() && (!targetInfo.isDirectory() || targetInfo.isSymbolicLink())) {
- throw new UsageError(`cannot overwrite non-directory '${target}' with directory '${src}'`);
- }
- if (sourceInfo.isDirectory() && targetInfo.isDirectory()) {
- const entries = await readdir(target).catch(() => []);
- if (entries.length > 0) throw new UsageError(`cannot overwrite '${target}': Directory not empty`);
- }
-}
-
-async function mvSameFileIsAllowed(src, target, sourceInfo) {
- if (sourceInfo.isSymbolicLink()) return false;
- const targetInfo = await lstat(target).catch(() => null);
- if (!targetInfo?.isSymbolicLink()) return false;
- return sourceInfo.dev !== targetInfo.dev;
-}
-
-async function mvRenameOrCopy(src, target, sourceInfo, opts, displayTarget = target, linkMap = new Map(), securityContext = {}) {
- try {
- await rename(src, target);
- if (securityContext.restoreContext
- && !restoreSelinuxSecurityContext(target, sourceInfo.isSymbolicLink(), sourceInfo.isDirectory())) {
- throw new UsageError(`failed to restore the security context of '${target}'`);
- }
- return true;
- } catch (error) {
- if (error instanceof UsageError) throw error;
- if (isDirectoryNotEmptyRenameError(error)) throw new UsageError(`cannot overwrite '${target}': Directory not empty`);
- if (error?.code !== "EXDEV") throw new UsageError(`cannot move '${src}' to '${displayTarget}': ${errnoMessage(error)}`);
- if (opts["no-copy"]) throw new UsageError(`inter-device move failed: '${src}' to '${target}'; --no-copy specified`);
- }
- await ensureMvCrossDeviceDirectoryReplaceable(src, target, sourceInfo);
- try {
- await copyPath(src, target, {
- force: true,
- removeDestination: true,
- recursive: true,
- preserveMode: true,
- preserveDirectoryMode: true,
- preserveMetadata: true,
- preserveLinks: true,
- preserveXattrs: true,
- requirePreserveXattrs: false,
- reflinkMode: "auto",
- sparseMode: "auto",
- attributesOnly: false,
- debug: false,
- linkMap,
- symbolicLink: false,
- hardLink: false,
- noDereference: true,
- dereferenceAll: false,
- dereferenceCommandLine: false,
- selinuxEnabled: Boolean(securityContext.selinuxEnabled),
- preserveContext: Boolean(securityContext.preserveContext),
- preserveContextAtCreation: Boolean(securityContext.preserveContext),
- requirePreserveContext: false,
- restoreContext: Boolean(securityContext.restoreContext),
- requireRestoreContext: Boolean(securityContext.restoreContext),
- explicitContext: null,
- verbose: opts.v || opts.verbose,
- }, true);
- } catch (error) {
- throw new UsageError(`inter-device move failed: '${src}' to '${target}'; unable to remove target: ${errnoMessage(error)}`);
- }
- if ((opts.v || opts.verbose) && sourceInfo.isDirectory()) stdout(`copied '${src}' -> '${target}'\n`);
- try {
- await rm(src, { force: true, recursive: sourceInfo.isDirectory() });
- } catch (error) {
- const message = error?.code === "EFAULT" ? "Operation not permitted" : errnoMessage(error);
- throw new UsageError(`cannot remove '${src}': ${message}`);
- }
- return false;
-}
-
-function mvDisplayTarget(src, target, useDirectoryTarget) {
- if (useDirectoryTarget && (target === pathBasename(src) || target === `./${pathBasename(src)}`)) return `./${pathBasename(src)}`;
- return target;
-}
-
-function isDirectoryNotEmptyRenameError(error) {
- return error?.code === "ENOTEMPTY" || error?.code === "EEXIST" || /ENOTEMPTY|EEXIST|Directory not empty/i.test(error?.message ?? "");
-}
-
-async function ensureMvCrossDeviceDirectoryReplaceable(src, target, sourceInfo) {
- if (!sourceInfo.isDirectory()) return;
- const targetInfo = await lstat(target).catch(() => null);
- if (!targetInfo?.isDirectory() || targetInfo.isSymbolicLink()) return;
- const entries = await readdir(target).catch(() => []);
- if (entries.length > 0) {
- throw new UsageError(`inter-device move failed: '${src}' to '${target}'; unable to remove target: Directory not empty`);
- }
-}
-
-async function ensureMvNotIntoSelf(src, target, sourceInfo) {
- if (!sourceInfo?.isDirectory()) return;
- const sourcePath = resolve(src);
- const targetPath = resolve(target);
- if (targetPath === sourcePath || targetPath.startsWith(`${sourcePath}/`)) {
- throw new UsageError(`cannot move '${src}' to a subdirectory of itself, '${target}'`);
- }
-}
-
-async function lnCmd(args) {
- args = normalizeLnArgs(args);
- const { opts, operands } = parseOptions(args, { short: { s: false, f: false, i: false, L: false, P: false, F: false, d: false, n: false, r: false, t: "value", T: false, v: false, b: false, S: "value" }, long: { symbolic: false, force: false, interactive: false, logical: false, physical: false, directory: false, "no-dereference": false, relative: false, "target-directory": "value", "target-dir": "value", "no-target-directory": false, verbose: false, backup: "optional-value", b: "optional-value", suffix: "value", help: false, version: false } });
- if (opts["target-dir"] != null && opts["target-directory"] == null) opts["target-directory"] = opts["target-dir"];
- if (opts.b != null && opts.backup == null) opts.backup = opts.b;
- if (opts.S != null && opts.suffix == null) opts.suffix = opts.S;
- if ((opts.r || opts.relative) && !(opts.s || opts.symbolic)) throw new UsageError("cannot do --relative without --symbolic");
- const { sources, dest, useDirectoryTarget } = await resolveLnDestinationOperands(operands, opts);
- const backup = opts.b || opts.backup != null;
- if (backup) validateBackupMode("ln", opts.backup);
- const force = lnForceMode(args, opts);
- const dereferenceSource = lnDereferenceSource(args);
- const rawPlan = rawLnPlan(opts, operands, useDirectoryTarget);
- const createdTargets = new Set();
- let failed = false;
- for (const src of sources) {
- const rawSource = rawPlan?.sources.shift();
- const target = rawPlan && rawSource
- ? rawLnTarget(rawSource, rawPlan.dest, rawPlan.useDirectoryTarget)
- : useDirectoryTarget ? join(dest, pathBasename(src)) : dest;
- const operationSource = rawSource ?? src;
- const targetKey = resolve(pathDisplayName(target));
- if ((force === "force" || (backup && !useDirectoryTarget)) && await areSameFile(src, target)) {
- if (!opts.s && !opts.symbolic && force === "force" && useDirectoryTarget) continue;
- throw new UsageError(`'${src}' and '${target}' are the same file`);
- }
- if (!backup && createdTargets.has(targetKey)) throw new UsageError(`will not overwrite just-created '${target}' with '${src}'`);
- if (backup) await backupLinkDestination(target, opts.suffix);
- else if (force === "force") await removeLinkDestination(target);
- else if (force === "interactive" && await lstat(target).then(() => true, () => false)) {
- if (!confirmRemoval(`ln: replace '${target}'? `)) {
- failed = true;
- continue;
- }
- await removeLinkDestination(target);
- }
- const linkSource = rawSource ? operationSource : opts.r || opts.relative ? await relativeLinkSource(src, target) : src;
- try {
- if (opts.s || opts.symbolic || opts.r || opts.relative) await symlink(linkSource, target);
- else await fsLink(rawSource ?? await hardLinkSource(src, dereferenceSource, opts.F || opts.d || opts.directory), target);
- } catch (error) {
- if (String(error?.message ?? "").startsWith("failed to access ")) throw new UsageError(error.message);
- if (String(error?.message ?? "").endsWith(": hard link not allowed for directory")) throw new UsageError(error.message);
- const kind = opts.s || opts.symbolic || opts.r || opts.relative ? "symbolic link" : "hard link";
- const message = error?.code === "EEXIST" ? "File exists" : errnoMessage(error);
- const targetDisplay = lnTargetDisplay(target, sources.length === 1 && operands.length === 1 && !useDirectoryTarget);
- throw new UsageError(`failed to create ${kind} '${targetDisplay}': ${message}`);
- }
- createdTargets.add(targetKey);
- if (opts.v || opts.verbose) stdout(`'${target}' => '${src}'\n`);
- }
- return failed ? 1 : 0;
-}
-
-function normalizeLnArgs(args) {
- const out = [];
- let end = false;
- for (const arg of args) {
- if (end || arg === "--") {
- out.push(arg);
- if (arg === "--") end = true;
- continue;
- }
- out.push(arg.startsWith("--") ? normalizeLnLongOption(arg) : arg);
- }
- return out;
-}
-
-function lnTargetDisplay(target, implicitSingleTarget = false) {
- if (!implicitSingleTarget) return target;
- const text = pathDisplayName(target);
- if (text === "" || text.startsWith("/") || text.startsWith("./") || text.startsWith("../")) return target;
- return `./${text}`;
-}
-
-function normalizeLnLongOption(arg) {
- if (arg === "--target-dir" || arg.startsWith("--target-dir=")) return arg;
- const options = LN_LONG_OPTIONS.filter((option) => option !== "target-dir");
- return normalizeLongOptionByPrefix(arg, options);
-}
-
-function rawLnPlan(opts, operands, useDirectoryTarget) {
- if (!operands.some((operand) => operand.includes("\uFFFD"))) return null;
- const raw = rawCommandArgs("ln");
- if (!raw) return null;
- const parsed = parseRawLnArgs(raw);
- if (!parsed || parsed.operands.length !== operands.length) return null;
- if (opts.t || opts["target-directory"]) {
- return { sources: parsed.operands, dest: parsed.targetDirectory, useDirectoryTarget: true };
- }
- if (!useDirectoryTarget || parsed.operands.length < 2) return null;
- return { sources: parsed.operands.slice(0, -1), dest: parsed.operands.at(-1), useDirectoryTarget: true };
-}
-
-function parseRawLnArgs(rawArgs) {
- const operands = [];
- let targetDirectory = null;
- for (let i = 0; i < rawArgs.length; i++) {
- const arg = rawArgs[i];
- if (arg.equals(Buffer.from("--"))) {
- operands.push(...rawArgs.slice(i + 1));
- break;
- }
- if (!rawArgLooksLikeOption(arg)) {
- operands.push(arg);
- continue;
- }
- const text = arg.toString();
- if (text === "-t" || text === "--target-directory" || text === "--target-dir") {
- targetDirectory = rawArgs[++i] ?? null;
- continue;
- }
- if (text.startsWith("--target-directory=")) {
- targetDirectory = arg.subarray(Buffer.from("--target-directory=").length);
- continue;
- }
- if (text.startsWith("--target-dir=")) {
- targetDirectory = arg.subarray(Buffer.from("--target-dir=").length);
- continue;
- }
- if (arg.length > 2 && arg[0] === 0x2d && arg.includes(0x74)) {
- const tIndex = arg.indexOf(0x74);
- if (tIndex !== arg.length - 1) targetDirectory = arg.subarray(tIndex + 1);
- else targetDirectory = rawArgs[++i] ?? null;
- }
- }
- if (targetDirectory && operands.length) return { operands, targetDirectory };
- return { operands, targetDirectory };
-}
-
-function rawArgLooksLikeOption(arg) {
- return arg.length > 1 && arg[0] === 0x2d;
-}
-
-function rawLnTarget(source, dest, useDirectoryTarget) {
- if (!useDirectoryTarget) return dest;
- return bufferPathJoin(dest, bufferPathBasename(source));
-}
-
-async function readdirPathEntries(path) {
- return await readdir(path, { encoding: "buffer" });
-}
-
-async function* iterateDirectoryPathEntries(path) {
- yield* await openDirectoryPathEntries(path);
-}
-
-async function openDirectoryPathEntries(path) {
- const directory = await opendir(path, { encoding: "buffer" });
- return {
- async *[Symbol.asyncIterator]() {
- try {
- while (true) {
- const entry = await directory.read();
- if (!entry) break;
- // Bun returns the encoded name directly for encoding:"buffer",
- // while Node returns a Dirent whose name uses that encoding.
- yield entry.name ?? entry;
- }
- } finally {
- try {
- await directory.close();
- } catch (error) {
- if (error?.code !== "ERR_DIR_CLOSED") throw error;
- }
- }
- }
- };
-}
-
-function pathLikeJoin(parent, child) {
- if (isBytePath(parent) || isBytePath(child)) return bufferPathJoin(parent, isBytePath(child) ? Buffer.from(child) : Buffer.from(String(child)));
- return join(parent, child);
-}
-
-function isBytePath(path) {
- return path instanceof Uint8Array;
-}
-
-function pathDisplayName(path) {
- return isBytePath(path) ? decodeUtf8SurrogateEscaped(Buffer.from(path)) : String(path);
-}
-
-function decodeUtf8SurrogateEscaped(bytes) {
- let out = "";
- for (let i = 0; i < bytes.length;) {
- const b = bytes[i];
- if (b < 0x80) {
- out += String.fromCharCode(b);
- i++;
- } else if (b >= 0xc2 && b <= 0xdf && i + 1 < bytes.length && isUtf8Continuation(bytes[i + 1])) {
- out += String.fromCodePoint(((b & 0x1f) << 6) | (bytes[i + 1] & 0x3f));
- i += 2;
- } else if (b >= 0xe0 && b <= 0xef && i + 2 < bytes.length && isUtf8Continuation(bytes[i + 1]) && isUtf8Continuation(bytes[i + 2])
- && !(b === 0xe0 && bytes[i + 1] < 0xa0) && !(b === 0xed && bytes[i + 1] >= 0xa0)) {
- out += String.fromCodePoint(((b & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f));
- i += 3;
- } else if (b >= 0xf0 && b <= 0xf4 && i + 3 < bytes.length && isUtf8Continuation(bytes[i + 1]) && isUtf8Continuation(bytes[i + 2]) && isUtf8Continuation(bytes[i + 3])
- && !(b === 0xf0 && bytes[i + 1] < 0x90) && !(b === 0xf4 && bytes[i + 1] >= 0x90)) {
- out += String.fromCodePoint(((b & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f));
- i += 4;
- } else {
- out += String.fromCharCode(0xdc00 + b);
- i++;
- }
- }
- return out;
-}
-
-function isUtf8Continuation(byte) {
- return byte >= 0x80 && byte <= 0xbf;
-}
-
-function bufferPathBasename(path) {
- let end = path.length;
- while (end > 1 && path[end - 1] === 0x2f) end--;
- const slash = path.lastIndexOf(0x2f, end - 1);
- return path.subarray(slash + 1, end);
-}
-
-function bufferPathJoin(dir, base) {
- const normalizedDir = isBytePath(dir) ? Buffer.from(dir) : Buffer.from(String(dir));
- const sep = normalizedDir.length && normalizedDir[normalizedDir.length - 1] !== 0x2f ? Buffer.from("/") : Buffer.alloc(0);
- return Buffer.concat([normalizedDir, sep, base]);
-}
-
-async function hardLinkSource(src, dereferenceSource, allowDirectory = false) {
- if (dereferenceSource) {
- let resolved;
- try {
- resolved = await realpath(src);
- } catch (error) {
- throw new Error(`failed to access ${lnQuotedName(src)}: ${errnoMessage(error)}`);
- }
- if (!allowDirectory && (await stat(resolved)).isDirectory()) throw new Error(`${lnDiagnosticName(src)}: hard link not allowed for directory`);
- return resolved;
- }
- const s = (src.endsWith("/") ? await stat(src).catch(() => null) : await lstat(src).catch(() => null));
- if (!s) throw new Error(`failed to access ${lnQuotedName(src)}: No such file or directory`);
- if (!allowDirectory && s?.isDirectory()) throw new Error(`${lnDiagnosticName(src)}: hard link not allowed for directory`);
- return src;
-}
-
-function lnQuotedName(name) {
- return shellEscapeLsName(pathDisplayName(name), true);
-}
-
-function lnDiagnosticName(name) {
- return shellEscapeLsName(pathDisplayName(name));
-}
-
-async function resolveLnDestinationOperands(operands, opts) {
- if (operands.length === 1 && !opts.t && !opts["target-directory"]) {
- return { sources: operands, dest: pathBasename(operands[0]), destStat: await stat(pathBasename(operands[0])).catch(() => null), useDirectoryTarget: false };
- }
- const noDereference = opts.n || opts["no-dereference"];
- if (noDereference && operands.length === 2 && !opts.t && !opts["target-directory"]) {
- const dest = operands[1];
- const destLstat = await lstat(dest).catch(() => null);
- if (destLstat?.isSymbolicLink()) return { sources: [operands[0]], dest, destStat: destLstat, useDirectoryTarget: false };
- }
- return resolveDestinationOperands("ln", operands, opts);
-}
-
-function lnForceMode(args, opts) {
- let mode = opts.f || opts.force ? "force" : "none";
- for (const arg of args) {
- if (arg === "--") break;
- if (arg === "-f" || arg === "--force") mode = "force";
- else if (arg === "-i" || arg === "--interactive") mode = "interactive";
- else if (/^-[^-]/.test(arg)) {
- for (const ch of arg.slice(1)) {
- if (ch === "f") mode = "force";
- else if (ch === "i") mode = "interactive";
- }
- }
- }
- return mode;
-}
-
-function lnDereferenceSource(args) {
- let dereference = false;
- for (const arg of args) {
- if (arg === "--") break;
- if (arg === "-L" || arg === "--logical") dereference = true;
- else if (arg === "-P" || arg === "--physical") dereference = false;
- else if (/^-[^-]/.test(arg)) {
- for (const ch of arg.slice(1)) {
- if (ch === "L") dereference = true;
- else if (ch === "P") dereference = false;
- else if (ch === "s") return false;
- }
- }
- if (arg === "-s" || arg === "--symbolic") return false;
- }
- return dereference;
-}
-
-async function areSameFile(a, b) {
- const [as, bs] = await Promise.all([stat(a).catch(() => null), stat(b).catch(() => null)]);
- return Boolean(as && bs && as.dev === bs.dev && as.ino === bs.ino);
-}
-
-async function areSamePathEntry(a, b) {
- const [as, bs] = await Promise.all([lstat(a).catch(() => null), lstat(b).catch(() => null)]);
- return Boolean(as && bs && areSamePathStats(as, bs));
-}
-
-function areSamePathStats(a, b) {
- return a.dev === b.dev && a.ino === b.ino;
-}
-
-async function ensureBackupDoesNotDestroySource(program, src, target, suffixOption, backupOption) {
- const backup = backupFileName(target, suffixOption, backupOption);
- if (!backup) return;
- if (resolve(src) === resolve(backup) || await areSameFile(src, backup)) {
- const action = program === "mv" ? "moved" : "copied";
- throw new UsageError(`backing up '${target}' might destroy source; '${src}' not ${action}`);
- }
-}
-
-async function backupLinkDestination(target, suffixOption) {
- const s = await lstat(target).catch(() => null);
- if (!s) return;
- const backup = backupFileName(target, suffixOption, "simple");
- await fsUnlink(backup).catch((error) => {
- if (error?.code !== "ENOENT") throw error;
- });
- await rename(target, backup);
-}
-
-function backupSuffix(option) {
- const suffix = option && option !== true && option !== "simple" ? option : process.env.SIMPLE_BACKUP_SUFFIX ?? "~";
- return String(suffix).includes("/") ? "~" : String(suffix);
-}
-
-async function backupDestination(target, suffixOption, backupOption = true) {
- const s = await lstat(target).catch(() => null);
- if (!s) return "";
- const backup = backupFileName(target, suffixOption, backupOption);
- if (!backup) return "";
- await fsUnlink(backup).catch((error) => {
- if (error?.code !== "ENOENT") throw error;
- });
- await rename(target, backup);
- return backup;
-}
-
-function backupFileName(target, suffixOption, backupOption = true) {
- const mode = backupMode(backupOption);
- if (mode === "none" || mode === "off") return "";
- if (mode === "numbered" || mode === "t") return nextNumberedBackupName(target);
- if (mode === "existing" || mode === "nil") return existingNumberedBackupName(target) ? nextNumberedBackupName(target) : `${target}${backupSuffix(suffixOption)}`;
- return `${target}${backupSuffix(suffixOption)}`;
-}
-
-const BACKUP_VALID_ARGUMENTS = [
- ["none", "off"],
- ["simple", "never"],
- ["existing", "nil"],
- ["numbered", "t"],
-];
-
-function validateBackupMode(program, backupOption) {
- backupMode(backupOption, program);
-}
-
-function backupMode(backupOption = true, program = null) {
- if (backupOption === true || backupOption == null) return backupModeFromEnvironment(program);
- const mode = String(backupOption);
- if (mode === "") return backupModeFromEnvironment(program);
- if (backupModeIsValid(mode)) return mode;
- if (program) throw new InvocationError(validBackupModeMessage(mode, "backup type"), 1, true);
- return "existing";
-}
-
-function backupModeFromEnvironment(program = null) {
- const value = process.env.VERSION_CONTROL;
- if (value == null || value === "") return "existing";
- if (backupModeIsValid(value)) return value;
- if (program) throw new InvocationError(validBackupModeMessage(value, "$VERSION_CONTROL"), 1, true);
- return "existing";
-}
-
-function backupModeIsValid(value) {
- return BACKUP_VALID_ARGUMENTS.some((group) => group.includes(value));
-}
-
-function validBackupModeMessage(value, option) {
- return `invalid argument ${localeQuotedEscapedDiagnostic(value)} for ${localeQuotedDiagnostic(option)}\nValid arguments are:\n${BACKUP_VALID_ARGUMENTS.map((group) => ` - ${group.map(localeQuotedDiagnostic).join(", ")}`).join("\n")}`;
-}
-
-function existingNumberedBackupName(target) {
- const dir = pathDirname(target);
- const base = pathBasename(target);
- try {
- return readdirSyncNoThrow(dir).some((name) => name.startsWith(`${base}.~`) && /^\.~\d+~$/.test(name.slice(base.length)));
- } catch {
- return false;
- }
-}
-
-function nextNumberedBackupName(target) {
- const dir = pathDirname(target);
- const base = pathBasename(target);
- let max = 0;
- for (const name of readdirSyncNoThrow(dir)) {
- if (!name.startsWith(`${base}.~`)) continue;
- const match = name.slice(base.length).match(/^\.~(\d+)~$/);
- if (match) max = Math.max(max, Number(match[1]));
- }
- return join(dir, `${base}.~${max + 1}~`);
-}
-
-async function removeLinkDestination(target) {
- const s = await lstat(target).catch(() => null);
- if (s?.isDirectory() && !s.isSymbolicLink()) return;
- await fsUnlink(target).catch((error) => {
- if (error?.code !== "ENOENT" && error?.code !== "ENOTDIR" && error?.code !== "ELOOP" && error?.code !== "ENAMETOOLONG") throw error;
- });
-}
-
-async function relativeLinkSource(src, target) {
- if (src === "") return src;
- const resolvedSource = await resolveSymlinkChain(src).catch(() => resolve(src));
- const targetDir = pathDirname(resolve(target));
- const rel = relative(targetDir, resolvedSource);
- return rel || ".";
-}
-
-async function resolveSymlinkChain(path) {
- let current = resolve(path);
- for (let i = 0; i < 40; i++) {
- const s = await lstat(current).catch((error) => {
- if (error?.code === "ENOENT") return null;
- throw error;
- });
- if (!s) return current;
- if (!s.isSymbolicLink()) return current;
- const linkTarget = await readlink(current);
- current = isAbsolute(linkTarget) ? linkTarget : resolve(pathDirname(current), linkTarget);
- }
- return current;
-}
-
-async function resolveDestinationOperands(program, operands, opts) {
- const explicitTarget = opts.t ?? opts["target-directory"];
- const noTargetDirectory = opts.T || opts["no-target-directory"];
- if (explicitTarget && noTargetDirectory) throw new UsageError("cannot combine --target-directory and --no-target-directory");
- if (explicitTarget) {
- if (!operands.length) throw new UsageError("missing file operand", true);
- const destStat = await stat(explicitTarget).catch((error) => {
- if (program === "ln" && error?.code === "ENOENT") throw new UsageError(`failed to access ${lnQuotedName(explicitTarget)}: ${errnoMessage(error)}`);
- if ((program === "cp" || program === "mv") && error?.code === "ENOENT") throw new UsageError(`target directory '${explicitTarget}': ${errnoMessage(error)}`);
- if (error?.code !== "ENOENT") throw new UsageError(`target directory '${explicitTarget}': ${errnoMessage(error)}`);
- return null;
- });
- if (program === "ln" && !destStat?.isDirectory()) throw new UsageError(`target '${explicitTarget}' is not a directory`);
- if (!destStat?.isDirectory()) throw new UsageError(`target directory '${explicitTarget}': Not a directory`);
- return { sources: operands, dest: explicitTarget, destStat, useDirectoryTarget: true };
- }
- if (operands.length < 2) {
- if ((program === "cp" || program === "mv" || program === "ln") && operands.length === 0) throw new UsageError("missing file operand", true);
- const suffix = operands.length === 1 ? ` after '${operands[0]}'` : "";
- throw new UsageError(`missing destination file operand${suffix}`, true);
- }
- const dest = operands.at(-1);
- const sources = operands.slice(0, -1);
- if (sources.length > 1 && noTargetDirectory) throw new UsageError(`extra operand '${dest}'`, true);
- const destStat = program === "cp" ? await cpDestinationStat(dest) : await stat(dest).catch(() => null);
- const useDirectoryTarget = !noTargetDirectory && Boolean(destStat?.isDirectory());
- if (sources.length > 1 && !useDirectoryTarget && !destStat) throw new UsageError(`target '${dest}': No such file or directory`);
- if (sources.length > 1 && !useDirectoryTarget) throw new UsageError(`target '${dest}': Not a directory`);
- return { sources, dest, destStat, useDirectoryTarget };
-}
-
-let cpStatApi;
-
-async function cpDestinationStat(path) {
- if (!process.env.LD_PRELOAD) return await stat(path).catch(() => null);
- if (!cpStatApi) {
- const address = libc.symbols.dlsym(0, ptr(Buffer.from("fstatat\0")));
- cpStatApi = linkSymbols({
- fstatat: { ptr: address, args: [FFIType.i32, FFIType.cstring, FFIType.ptr, FFIType.i32], returns: FFIType.i32 },
- }).symbols;
- }
- const buffer = Buffer.alloc(144);
- if (cpStatApi.fstatat(AT_FDCWD, cstrPath(path), ptr(buffer), 0) !== 0) return null;
- const mode = buffer.readUInt32LE(24);
- return { isDirectory: () => (mode & 0xf000) === 0x4000 };
-}
-
-async function readlinkCmd(args) {
- args = normalizeReadlinkLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { f: false, e: false, m: false, n: false, q: false, s: false, v: false, z: false }, long: { canonicalize: false, "canonicalize-existing": false, "canonicalize-missing": false, "no-newline": false, quiet: false, silent: false, verbose: false, zero: false, help: false, version: false } });
- if (!operands.length) throw new UsageError("missing operand", true);
- const sep = opts.n || opts["no-newline"] ? (operands.length > 1 ? (opts.z || opts.zero ? "\0" : "\n") : "") : (opts.z || opts.zero ? "\0" : "\n");
- const diagnostics = readlinkDiagnosticMode(args);
- let status = 0;
- for (const file of operands) {
- let out;
- try {
- if (opts.f || opts.e || opts.m || opts.canonicalize || opts["canonicalize-existing"] || opts["canonicalize-missing"]) {
- out = await canonicalPath(file, opts);
- } else {
- out = await readlink(file);
- }
- stdout(out + sep);
- } catch (error) {
- if (diagnostics === "verbose") stderr(`readlink: ${readlinkQuotedName(file)}: ${readlinkErrorMessage(error)}\n`);
- status = 1;
- }
- }
- return status;
-}
-
-function normalizeReadlinkLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, READLINK_LONG_OPTIONS);
-}
-
-function normalizeReadlinkLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, READLINK_LONG_OPTIONS);
-}
-
-function readlinkDiagnosticMode(args) {
- if (process.env.POSIXLY_CORRECT) return "verbose";
- let mode = "quiet";
- for (const arg of args) {
- if (arg === "--") break;
- if (arg === "-q" || arg === "-s" || arg === "--quiet" || arg === "--silent") mode = "quiet";
- else if (arg === "-v" || arg === "--verbose") mode = "verbose";
- else if (/^-[^-]/.test(arg)) {
- for (const ch of arg.slice(1)) {
- if (ch === "q" || ch === "s") mode = "quiet";
- else if (ch === "v") mode = "verbose";
- }
- }
- }
- return mode;
-}
-
-async function realpathCmd(args) {
- args = normalizeRealpathLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { E: false, e: false, m: false, L: false, P: false, q: false, s: false, z: false }, long: { canonicalize: false, "canonicalize-existing": false, "canonicalize-missing": false, logical: false, physical: false, quiet: false, strip: false, "no-symlinks": false, zero: false, "relative-to": "value", "relative-base": "value", help: false, version: false } });
- if (!operands.length) throw new UsageError("missing operand", true);
- if (opts["relative-to"] === "" || opts["relative-base"] === "") throw new UsageError("'': No such file or directory");
- if (opts.E) opts.e = opts["canonicalize-existing"] = false;
- if (opts.e || opts["canonicalize-existing"]) {
- await requireRealpathRelativeDirectory(opts["relative-to"]);
- await requireRealpathRelativeDirectory(opts["relative-base"]);
- }
- const sep = opts.z || opts.zero ? "\0" : "\n";
- let status = 0;
- for (const file of operands) {
- try {
- if (file === "") throw Object.assign(new Error("No such file or directory"), { code: "ENOENT" });
- stdout(formatRealpathOutput(await canonicalPath(file, opts), opts) + sep);
- } catch (error) {
- if (!(opts.q || opts.quiet)) stderr(`realpath: ${readlinkQuotedName(file)}: ${readlinkErrorMessage(error)}\n`);
- status = 1;
- }
- }
- return status;
-}
-
-async function requireRealpathRelativeDirectory(path) {
- if (!path) return;
- const s = await stat(path).catch((error) => {
- throw new UsageError(`${readlinkQuotedName(path)}: ${readlinkErrorMessage(error)}`);
- });
- if (!s.isDirectory()) throw new UsageError(`${readlinkQuotedName(path)}: Not a directory`);
-}
-
-function readlinkQuotedName(path) {
- const name = pathDisplayName(path);
- return name === "" ? "''" : shellEscapeLsName(name);
-}
-
-function normalizeRealpathLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, REALPATH_LONG_OPTIONS);
-}
-
-function normalizeRealpathLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, REALPATH_LONG_OPTIONS);
-}
-
-async function canonicalPath(path, opts = {}) {
- if (opts.s || opts.strip || opts["no-symlinks"]) return lexicalAbsolute(path);
- if (opts.L || opts.logical) return logicalCanonicalPath(path, opts);
- if (opts.m || opts["canonicalize-missing"]) return canonicalizeMissing(path);
- return physicalCanonicalPath(path, opts);
-}
-
-async function logicalCanonicalPath(path, opts = {}) {
- const lexical = lexicalAbsolute(path);
- if (opts.m || opts["canonicalize-missing"] || opts.E) return lexical;
- if (opts.e || opts["canonicalize-existing"]) return realpath(lexical);
- try {
- return await realpath(lexical);
- } catch (error) {
- if (error.code !== "ENOENT") throw error;
- return join(await realpath(pathDirname(lexical)), pathBasename(lexical));
- }
-}
-
-async function physicalCanonicalPath(path, opts = {}) {
- const mustExist = opts.e || opts["canonicalize-existing"];
- const allowMissingFinal = !mustExist;
- const allowMissingAny = opts.m || opts["canonicalize-missing"];
- const trailingSlash = /\/$/.test(path) && path !== "/";
- const absolute = isAbsolute(path) ? path : `${process.cwd().replace(/\/+$/, "")}/${path}`;
- const parts = absolute.split("/").filter(Boolean);
- let current = "/";
- let symlinkDepth = 0;
- for (let i = 0; i < parts.length; i++) {
- const part = parts[i];
- if (part === ".") continue;
- if (part === "..") {
- current = pathDirname(current.replace(/\/+$/, "") || "/");
- continue;
- }
- const candidate = join(current, part);
- let s;
- try {
- s = await lstat(candidate);
- } catch (error) {
- if (allowMissingAny) return normalize(join(candidate, ...parts.slice(i + 1)));
- if (allowMissingFinal && error.code === "ENOENT" && i === parts.length - 1) return candidate;
- throw error;
- }
- if (s.isSymbolicLink()) {
- if (++symlinkDepth > 40) {
- const error = new Error("Too many levels of symbolic links");
- error.code = "ELOOP";
- throw error;
- }
- const target = await readlink(candidate);
- const targetParts = target.split("/").filter(Boolean);
- const rest = parts.slice(i + 1);
- parts.splice(i, parts.length - i, ...targetParts, ...rest);
- if (isAbsolute(target)) current = "/";
- i--;
- } else {
- current = candidate;
- }
- }
- if (!allowMissingAny && trailingSlash && !(await stat(current).catch(() => null))?.isDirectory()) {
- const error = new Error("Not a directory");
- error.code = "ENOTDIR";
- throw error;
- }
- return current;
-}
-
-async function canonicalizeMissing(path) {
- return physicalCanonicalPath(path, { m: true });
-}
-
-function readlinkErrorMessage(error) {
- if (error?.code === "EINVAL") return "Invalid argument";
- if (error?.code === "ENOENT") return "No such file or directory";
- if (error?.code === "ENOTDIR") return "Not a directory";
- if (error?.code === "ELOOP") return "Too many levels of symbolic links";
- return error?.message || String(error);
-}
-
-function lexicalAbsolute(path) {
- return normalize(isAbsolute(path) ? path : resolve(process.cwd(), path));
-}
-
-function formatRealpathOutput(path, opts) {
- const relativeBase = opts["relative-base"];
- const relativeTo = opts["relative-to"] ?? (relativeBase != null ? relativeBase : null);
- if (relativeBase) {
- const base = resolve(relativeBase);
- const target = resolve(relativeTo);
- if (!pathIsUnder(target, base)) return path;
- if (pathIsUnder(path, base)) return relative(target, path) || ".";
- return path;
- }
- if (relativeTo) return relative(resolve(relativeTo), path) || ".";
- return path;
-}
-
-function pathIsUnder(path, base) {
- const rel = relative(base, path);
- return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
-}
-
-async function truncateCmd(args) {
- args = normalizeTruncateLongOptions(args);
- const { opts, operands } = parseOptions(args, { short: { s: "value", c: false, r: "value", o: false }, long: { size: "value", "no-create": false, reference: "value", "io-blocks": false, help: false, version: false } });
- const size = opts.s ?? opts.size;
- const reference = opts.r ?? opts.reference;
- if (size == null && reference == null) throw new UsageError("you must specify either '--size' or '--reference'", true);
- if (size != null) truncateTargetSize(0, size);
- if (reference != null && size != null && !isTruncateRelativeSize(size)) {
- throw new UsageError(`you must specify a relative ${localeQuotedDiagnostic("--size")} with ${localeQuotedDiagnostic("--reference")}`, true);
- }
- if (!operands.length) throw new UsageError("missing file operand", true);
- if ((opts.o || opts["io-blocks"]) && reference != null && size == null) throw new UsageError("'--io-blocks' was specified but '--size' was not", true);
- let referenceSize = null;
- if (reference != null) {
- try {
- referenceSize = (await stat(reference)).size;
- } catch (error) {
- throw new UsageError(`cannot stat ${truncateQuotedName(reference)}: ${systemErrorMessage(error)}`);
- }
- }
- let status = 0;
- for (const file of operands) {
- try {
- let missing = false;
- const current = await stat(file).then((s) => s.size, (error) => {
- if (error.code === "ENOENT" && (opts.c || opts["no-create"])) return null;
- if (error.code === "ENOENT") {
- missing = true;
- return 0;
- }
- throw error;
- });
- if (current == null) continue;
- if (missing) await writeFile(file, "");
- const base = referenceSize ?? current;
- const ioBlockSize = opts.o || opts["io-blocks"] ? await truncateIoBlockSize(file) : 1;
- const target = size == null ? BigInt(referenceSize) : truncateTargetSize(base, size, ioBlockSize);
- if (target < 0n) throw new UsageError(`Invalid number: ${localeQuotedDiagnostic(size ?? target)}: Value too large for defined data type`);
- await truncateFileToSize(file, target);
- } catch (error) {
- if (error instanceof UsageError) throw error;
- stderr(`truncate: ${truncateErrorPrefix(error, file)}: ${truncateErrorMessage(error)}\n`);
- status = 1;
- }
- }
- return status;
-}
-
-function normalizeTruncateLongOptions(args) {
- return normalizeLongOptionsByPrefix(args, TRUNCATE_LONG_OPTIONS);
-}
-
-function normalizeTruncateLongOption(arg) {
- return normalizeLongOptionByPrefix(arg, TRUNCATE_LONG_OPTIONS);
-}
-
-function isValidTruncateSizeOperand(value) {
- try {
- truncateTargetSize(0, value);
- return true;
- } catch {
- return false;
- }
-}
-
-function isTruncateRelativeSize(spec) {
- return /^[+\-<>/%]/.test(String(spec).trimStart());
-}
-
-async function truncateIoBlockSize(file) {
- try {
- const fs = await statfs(file);
- return fs.bsize || 512;
- } catch (error) {
- if (error?.code !== "ENOENT") throw error;
- const dir = pathDirname(file) || ".";
- const fs = await statfs(dir);
- return fs.bsize || 512;
- }
-}
-
-function truncateTargetSize(current, spec, blockScale = 1) {
- current = BigInt(current);
- const text = String(spec).trimStart();
- const op = /^[+\-<>/%]/.test(text) ? text[0] : "";
- const amount = parseGNUSizeCheckedNumber(op ? text.slice(1) : text, BigInt(blockScale), text);
- if (op === "+") return current + amount;
- if (op === "-") return current > amount ? current - amount : 0n;
- if (op === "<") return current < amount ? current : amount;
- if (op === ">") return current > amount ? current : amount;
- if ((op === "/" || op === "%") && amount === 0n) throw new UsageError(`division by zero`);
- if (op === "/") return current - (current % amount);
- if (op === "%") return current + ((amount - (current % amount)) % amount);
- return amount;
-}
-
-async function truncateFileToSize(file, size) {
- if (size <= BigInt(Number.MAX_SAFE_INTEGER)) {
- await truncate(file, Number(size));
- return;
- }
- if (libc.symbols.truncate(cstrPath(file), size) !== 0) {
- throw new Error("Invalid argument");
- }
-}
-
-function parseGNUSizeCheckedNumber(value, extraScale = 1n, original = value) {
- const match = String(value).match(/^(\d+)([A-Za-z]*)$/);
- if (!match) throw new UsageError(`Invalid number: ${localeQuotedEscapedDiagnostic(original)}`);
- const suffixScales = {
- "": 1n, K: 1024n, k: 1024n, KiB: 1024n, kiB: 1024n,
- M: 1024n ** 2n, m: 1024n ** 2n, MiB: 1024n ** 2n, miB: 1024n ** 2n,
- G: 1024n ** 3n, g: 1024n ** 3n, GiB: 1024n ** 3n, giB: 1024n ** 3n,
- T: 1024n ** 4n, t: 1024n ** 4n, TiB: 1024n ** 4n, tiB: 1024n ** 4n,
- P: 1024n ** 5n, PiB: 1024n ** 5n,
- E: 1024n ** 6n, EiB: 1024n ** 6n,
- Z: 1024n ** 7n, ZiB: 1024n ** 7n,
- Y: 1024n ** 8n, YiB: 1024n ** 8n,
- R: 1024n ** 9n, RiB: 1024n ** 9n,
- Q: 1024n ** 10n, QiB: 1024n ** 10n,
- KB: 1000n, kB: 1000n, MB: 1000n ** 2n, mB: 1000n ** 2n,
- GB: 1000n ** 3n, gB: 1000n ** 3n, TB: 1000n ** 4n, tB: 1000n ** 4n,
- PB: 1000n ** 5n, EB: 1000n ** 6n, ZB: 1000n ** 7n, YB: 1000n ** 8n,
- RB: 1000n ** 9n, QB: 1000n ** 10n,
- };
- const scale = suffixScales[match[2]];
- if (!scale) throw new UsageError(`Invalid number: ${localeQuotedEscapedDiagnostic(original)}`);
- const amount = BigInt(match[1]) * scale * extraScale;
- if (amount > 9223372036854775807n) {
- throw new UsageError(`Invalid number: ${localeQuotedEscapedDiagnostic(original)}: Value too large for defined data type`);
- }
- return amount;
-}
-
-function truncateErrorPrefix(error, file) {
- if ((error?.code === "ENOENT" && error?.syscall === "open") || error?.code === "ENOTDIR" || error?.code === "EISDIR") return `cannot open ${truncateQuotedName(file)} for writing`;
- return `failed to truncate ${truncateQuotedName(file)}`;
-}
-
-function truncateQuotedName(path) {
- return shellEscapeLsName(pathDisplayName(path), true);
-}
-
-function truncateErrorMessage(error) {
- if (error?.code === "ENOENT") return "No such file or directory";
- if (error?.code === "EISDIR") return "Is a directory";
- if (error?.code === "ENOTDIR") return "Not a directory";
- if (error?.code === "EINVAL") return "Invalid argument";
- return error?.message || String(error);
-}
-
-function parseGNUSize(value) {
- const match = String(value).match(/^(\d+)([A-Za-z]*)$/);
- if (!match) throw new UsageError(`invalid file size: ${value}`);
- const n = BigInt(match[1]);
- const suffix = match[2];
- const binary = {
- "": 1n, b: 512n,
- K: 1024n, k: 1024n, KiB: 1024n, kiB: 1024n,
- M: 1024n ** 2n, m: 1024n ** 2n, MiB: 1024n ** 2n, miB: 1024n ** 2n,
- G: 1024n ** 3n, g: 1024n ** 3n, GiB: 1024n ** 3n, giB: 1024n ** 3n,
- T: 1024n ** 4n, t: 1024n ** 4n, TiB: 1024n ** 4n, tiB: 1024n ** 4n,
- P: 1024n ** 5n, PiB: 1024n ** 5n,
- E: 1024n ** 6n, EiB: 1024n ** 6n,
- Z: 1024n ** 7n, ZiB: 1024n ** 7n,
- Y: 1024n ** 8n, YiB: 1024n ** 8n,
- };
- const decimal = {
- KB: 1000n, kB: 1000n, MB: 1000n ** 2n, mB: 1000n ** 2n,
- GB: 1000n ** 3n, gB: 1000n ** 3n, TB: 1000n ** 4n, tB: 1000n ** 4n,
- PB: 1000n ** 5n, EB: 1000n ** 6n, ZB: 1000n ** 7n, YB: 1000n ** 8n,
- };
- const scale = binary[suffix] ?? decimal[suffix];
- if (!scale) throw new UsageError(`invalid file size: ${value}`);
- const amount = n * scale;
- return amount > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(amount);
-}
-
-async function chmodCmd(args) {
- args = normalizeChmodArgs(args);
- const { recursive, changes, verbose, silent, dereference, traversal, preserveRoot, modeSpec, reference, files } = parseChmodArgs(args);
- if (!modeSpec) throw new UsageError("missing operand", true);
- if (reference != null && !files.length) throw new UsageError("missing operand", true);
- if (!files.length) throw new UsageError(`missing operand after '${modeSpec}'`, true);
- if (reference == null && !isChmodModeToken(modeSpec)) throw new UsageError(`invalid mode: ${localeQuotedEscapedDiagnostic(modeSpec)}`, true);
- const referenceMode = reference == null ? null : (await referenceStat(reference)).mode & 0o7777;
- let failed = false;
- for (const file of files) {
- const ok = await chmodPath(file, modeSpec, { recursive, changes, verbose, silent, dereference, traversal, preserveRoot, referenceMode }, true, file);
- if (!ok) failed = true;
- }
- return failed ? 1 : 0;
-}
-
-async function chmodPath(path, modeSpec, options, isRoot = false, display = path, relativeToChangedCwd = false) {
- let ok = true;
- let s;
- try {
- const linkInfo = await lstat(path);
- const isLink = linkInfo.isSymbolicLink();
- const shouldDereference = isLink && (options.recursive
- ? options.traversal === "L" || (isRoot && options.traversal === "H")
- : options.dereference);
- if (isLink && !shouldDereference) return true;
- try {
- s = shouldDereference || !isLink ? await stat(path) : linkInfo;
- } catch (error) {
- error.danglingSymlink = isLink && error?.code === "ENOENT";
- throw error;
- }
- if (options.recursive && options.preserveRoot && s.isDirectory() && await isRecursiveRootTarget(path)) throw preserveRootError("chmod", path);
- const before = s.mode & 0o7777;
- const { mode: after, ok: modeOk } = options.referenceMode == null ? parseModeSpec(modeSpec, before, s.isDirectory()) : { mode: options.referenceMode, ok: true };
- await setFileMode(path, after);
- if ((options.changes || options.verbose) && before !== after) stdout(`mode of ${chmodQuotedName(display)} changed from ${octalMode(before)} (${modeBitsString(before)}) to ${octalMode(after)} (${modeBitsString(after)})\n`);
- else if (options.verbose) stdout(`mode of ${chmodQuotedName(display)} retained as ${octalMode(after)} (${modeBitsString(after)})\n`);
- if (!modeOk) {
- if (!options.silent) stderr(`chmod: ${chmodQuotedName(display)}: new permissions are ${modeBitsString(after)}, not ${modeBitsString(parseModeSpec(modeSpec, before, s.isDirectory(), { ignoreUmask: true }).mode)}\n`);
- ok = false;
- }
- } catch (error) {
- if (!options.silent) stderr(chmodErrorLine(display, error));
- return false;
- }
- if (options.recursive && s.isDirectory()) {
- try {
- if (isRoot) {
- const entries = await openDirectoryPathEntries(path);
- for await (const entry of entries) {
- const childDisplay = `${String(display).replace(/\/+$/, "")}/${pathDisplayName(entry)}`;
- if (!(await chmodPath(pathLikeJoin(path, entry), modeSpec, options, false, childDisplay, relativeToChangedCwd))) ok = false;
- }
- return ok;
- }
- const entries = await readdirPathEntries(path);
- const restoreCwd = relativeToChangedCwd ? null : processCwdOrNull();
- if (chmodCanRelativeTraverse(path)) {
- changeDirectory(path);
- try {
- for (const entry of entries) {
- const childDisplay = `${String(display).replace(/\/+$/, "")}/${pathDisplayName(entry)}`;
- if (!(await chmodPath(entry, modeSpec, options, false, childDisplay, true))) ok = false;
- }
- } finally {
- changeDirectory(restoreCwd ?? "..");
- }
- } else {
- for (const entry of entries) {
- const childDisplay = `${String(display).replace(/\/+$/, "")}/${pathDisplayName(entry)}`;
- if (!(await chmodPath(pathLikeJoin(path, entry), modeSpec, options, false, childDisplay))) ok = false;
- }
- }
- } catch (error) {
- if (!options.silent) stderr(chmodErrorLine(display, error));
- ok = false;
- }
- }
- return ok;
-}
-
-function chmodCanRelativeTraverse(path) {
- const text = pathDisplayName(path);
- return !text.includes("\uFFFD") && text !== "" && text !== "." && text !== "..";
-}
-
-function normalizeChmodArgs(args) {
- const out = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === "--") {
- out.push(...args.slice(i));
- break;
- }
- if (arg.startsWith("--")) {
- const normalized = normalizeLongOptionByPrefix(arg, CHMOD_LONG_OPTIONS);
- if (normalized === "--reference" && i + 1 < args.length) {
- out.push(`${normalized}=${args[++i]}`);
- } else {
- out.push(normalized);
- }
- continue;
- }
- out.push(arg);
- }
- return out;
-}
-
-function parseChmodArgs(args) {
- let recursive = false;
- let changes = false;
- let verbose = false;
- let silent = false;
- let dereference = true;
- let traversal = "H";
- let preserveRoot = false;
- let reference = null;
- let explicitOperandStart = false;
- const rest = [];
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (!explicitOperandStart && rest.length === 0 && arg === "--") {
- explicitOperandStart = true;
- rest.push(...args.slice(i + 1));
- break;
- }
- if (!explicitOperandStart && (arg === "--reference" || arg.startsWith("--reference="))) {
- if (arg === "--reference") {
- if (i + 1 >= args.length) throw new UsageError("option '--reference' requires an argument", true);
- reference = args[++i];
- } else {
- reference = arg.slice("--reference=".length);
- }
- continue;
- }
- if (!explicitOperandStart && isChmodOption(arg)) {
- for (const option of expandChmodOption(arg)) {
- if (option === "R" || option === "recursive") recursive = true;
- else if (option === "c" || option === "changes") changes = true;
- else if (option === "v" || option === "verbose") verbose = true;
- else if (option === "f" || option === "silent" || option === "quiet") silent = true;
- else if (option === "H" || option === "L" || option === "P") traversal = option;
- else if (option === "h" || option === "no-dereference") dereference = false;
- else if (option === "dereference" || option === "deref") dereference = true;
- else if (option === "preserve-root") preserveRoot = true;
- else if (option === "no-preserve-root") preserveRoot = false;
- }
- continue;
- }
- if (!explicitOperandStart && rest.length === 0 && arg.startsWith("-") && !isChmodModeToken(arg)) {
- throw new UsageError(invalidOptionMessage(arg), true);
- }
- rest.push(arg);
- }
- if (explicitOperandStart) {
- const [modeSpec, ...files] = rest;
- return { recursive, changes, verbose, silent, dereference, traversal, preserveRoot, modeSpec: reference == null ? modeSpec : "--reference", reference, files: reference == null ? files : rest };
- }
-
- const modeParts = [];
- const files = [];
- let afterFile = false;
- for (let i = 0; i < rest.length; i++) {
- const arg = rest[i];
- if (arg === "--" && modeParts.length) {
- files.push(...rest.slice(i + 1));
- break;
- }
- if (arg === "--" && afterFile) {
- files.push(arg);
- continue;
- }
- if (!afterFile && isChmodModeToken(arg)) modeParts.push(arg);
- else if (isChmodModeToken(arg)) modeParts.push(arg);
- else {
- files.push(arg);
- afterFile = true;
- }
- }
- if (reference != null) return { recursive, changes, verbose, silent, dereference, traversal, preserveRoot, modeSpec: "--reference", reference, files: rest };
- if (!modeParts.length && rest.length) return { recursive, changes, verbose, silent, dereference, traversal, preserveRoot, modeSpec: rest[0], files: rest.slice(1) };
- return { recursive, changes, verbose, silent, dereference, traversal, preserveRoot, modeSpec: modeParts.join(","), files };
-}
-
-function isChmodOption(arg) {
- if (["--recursive", "--changes", "--silent", "--quiet", "--dereference", "--no-dereference", "--preserve-root", "--no-preserve-root", "--verbose"].includes(arg)) return true;
- return /^-[RcfvHLP]+$/.test(arg) || arg === "-h";
-}
-
-function expandChmodOption(arg) {
- if (arg.startsWith("--")) return [arg.slice(2)];
- return arg.slice(1).split("");
-}
-
-function isChmodModeToken(arg) {
- if (arg === "--") return true;
- return arg.split(",").every((part) => /^[0-7]+$/.test(part) || /^[+=-][0-7]+$/.test(part) || /^[ugoa]*[+=-][rwxXstugo]*$/.test(part));
-}
-
-function parseModeSpec(spec, current, isDirectory = false, parseOptions = {}) {
- if (spec === "--") return { mode: current, ok: true };
- if (spec.includes(",")) {
- let mode = current;
- let ok = true;
- for (const clause of spec.split(",")) {
- const parsed = parseModeSpec(clause, mode, isDirectory, parseOptions);
- mode = parsed.mode;
- ok &&= parsed.ok;
- }
- return { mode, ok };
- }
- if (/^[0-7]+$/.test(spec)) {
- const next = Number.parseInt(spec, 8);
- const preserveDirectorySpecialBits = isDirectory && next <= 0o777 && !spec.startsWith("00");
- return { mode: preserveDirectorySpecialBits ? next | (current & 0o6000) : next, ok: true };
- }
- if (/^=[0-7]+$/.test(spec)) return { mode: Number.parseInt(spec.slice(1), 8), ok: true };
- if (/^\+[0-7]+$/.test(spec)) return { mode: current | Number.parseInt(spec.slice(1), 8), ok: true };
- if (/^-[0-7]+$/.test(spec)) return { mode: current & ~Number.parseInt(spec.slice(1), 8), ok: true };
- let mode = current;
- let ok = true;
- for (const clause of expandSymbolicModeClauses(spec)) {
- const match = clause.match(/^([ugoa]*)([+=-])([rwxXstugo]*)$/);
- if (!match) throw new UsageError(`invalid mode: ${localeQuotedEscapedDiagnostic(spec)}`, true);
- if (/[ugo]/.test(match[3]) && match[3].length !== 1) throw new UsageError(`invalid mode: ${localeQuotedEscapedDiagnostic(spec)}`, true);
- const explicitWho = match[1] !== "";
- const who = match[1] || "a";
- const op = match[2];
- const perms = symbolicBits(match[3], who, mode, isDirectory);
- const mask = whoMask(who);
- const setMask = explicitWho || parseOptions.ignoreUmask ? mask : mask & ~process.umask();
- if (op === "=") mode = (mode & ~mask) | (perms & setMask);
- else if (op === "+") mode |= perms & setMask;
- else {
- mode &= ~(perms & setMask);
- if (!explicitWho && (mode & perms & (mask & ~setMask))) ok = false;
- }
- }
- return { mode, ok };
-}
-
-function expandSymbolicModeClauses(spec) {
- const clauses = [];
- for (const clause of spec.split(",")) {
- const compound = clause.match(/^([ugoa]*)=([+-][rwxXstugo]+)$/);
- if (compound) {
- clauses.push(`${compound[1]}=`, `${compound[1]}${compound[2]}`);
- } else {
- clauses.push(clause);
- }
- }
- return clauses;
-}
-
-function octalMode(mode) {
- return mode.toString(8).padStart(4, "0");
-}
-
-function modeBitsString(mode) {
- let out = "";
- const chars = ["r", "w", "x"];
- for (let shift = 6; shift >= 0; shift -= 3) {
- for (let bit = 2; bit >= 0; bit--) out += mode & (1 << (shift + bit)) ? chars[2 - bit] : "-";
- }
- return out;
-}
-
-function errnoMessage(error) {
- if (error?.code === "EACCES") return "Permission denied";
- if (error?.code === "ENOENT") return "No such file or directory";
- if (error?.code === "ENOTDIR") return "Not a directory";
- if (error?.code === "EISDIR") return "Is a directory";
- if (error?.code === "ENOTEMPTY") return "Directory not empty";
- if (error?.code === "EEXIST") return "Directory not empty";
- if (error?.code === "EPERM") return "Operation not permitted";
- if (error?.code === "EROFS") return "Read-only file system";
- if (error?.code === "EINVAL") return "Invalid argument";
- return error?.message || String(error);
-}
-
-async function referenceStat(path) {
- try {
- return await stat(path);
- } catch (error) {
- throw new UsageError(`failed to get attributes of ${chmodQuotedName(path)}: ${errnoMessage(error)}`);
- }
-}
-
-function chmodErrorLine(path, error) {
- if (error?.preserveRoot) return preserveRootMessage("chmod", error.path, error.rootPath);
- if (error?.danglingSymlink) return `chmod: cannot operate on dangling symlink ${chmodQuotedName(path)}\n`;
- if (isAccessError(error)) return `chmod: cannot access ${chmodQuotedName(path)}: ${errnoMessage(error)}\n`;
- return `chmod: changing permissions of ${chmodQuotedName(path)}: ${errnoMessage(error)}\n`;
-}
-
-function chmodQuotedName(path) {
- return shellEscapeLsName(pathDisplayName(path), true);
-}
-
-function chownErrorLine(path, error) {
- if (error?.preserveRoot) return preserveRootMessage("chown", error.path, error.rootPath);
- if (error?.cannotDereference) return `chown: cannot dereference ${chownQuotedName(path)}: ${errnoMessage(error)}\n`;
- if (isAccessError(error)) return `chown: cannot access ${chownQuotedName(path)}: ${errnoMessage(error)}\n`;
- return `chown: changing ownership of ${chownQuotedName(path)}: ${errnoMessage(error)}\n`;
-}
-
-function chgrpErrorLine(path, error) {
- if (error?.preserveRoot) return preserveRootMessage("chgrp", error.path, error.rootPath);
- if (error?.cannotDereference) return `chgrp: cannot dereference ${chownQuotedName(path)}: ${errnoMessage(error)}\n`;
- if (isAccessError(error)) return `chgrp: cannot access ${chownQuotedName(path)}: ${errnoMessage(error)}\n`;
- return `chgrp: changing group of ${chownQuotedName(path)}: ${errnoMessage(error)}\n`;
-}
-
-function chownQuotedName(path) {
- return shellEscapeLsName(pathDisplayName(path), true);
-}
-
-function isAccessError(error) {
- return error?.code === "EACCES" || error?.code === "ENOENT" || error?.code === "ENOTDIR";
-}
-
-function rmdirErrorLine(path, error) {
- return `rmdir: failed to remove ${rmdirQuotedName(path)}: ${rmdirErrorMessage(path, error)}\n`;
-}
-
-function rmdirQuotedName(path) {
- return shellEscapeLsName(pathDisplayName(path), true);
-}
-
-function rmdirErrorMessage(path, error) {
- if (error?.code === "ENOTDIR" && path.endsWith("/")) {
- try {
- const bare = path.replace(/\/+$/, "");
- const s = lstatSyncNoThrow(bare);
- if (s?.isSymbolicLink()) {
- const target = statSyncNoThrow(bare);
- if (!target || target.isDirectory()) return "Symbolic link not followed";
- }
- } catch {}
- }
- return errnoMessage(error);
-}
-
-function lstatSyncNoThrow(path) {
- try {
- return lstatSync(path);
- } catch {
- return null;
- }
-}
-
-function statSyncNoThrow(path) {
- try {
- return statSync(path);
- } catch {
- return null;
- }
-}
-
-async function isRecursiveRootTarget(path) {
- try {
- return await realpath(path) === "/";
- } catch {
- return resolve(path) === "/";
- }
-}
-
-function preserveRootError(command, path) {
- const error = new Error("preserve-root");
- error.preserveRoot = true;
- error.path = path;
- error.rootPath = path === "/" ? null : "/";
- return error;
-}
-
-function preserveRootMessage(command, path, rootPath = null) {
- const target = rootPath ? `'${path}' (same as '${rootPath}')` : `'${path}'`;
- return `${command}: it is dangerous to operate recursively on ${target}\n${command}: use --no-preserve-root to override this failsafe\n`;
-}
-
-function readdirSyncNoThrow(path) {
- try {
- return readdirSync(path);
- } catch {
- return [];
- }
-}
-
-function whoMask(who) {
- let mask = 0;
- if (who.includes("a") || who.includes("u")) mask |= 0o4700;
- if (who.includes("a") || who.includes("g")) mask |= 0o2070;
- if (who.includes("a") || who.includes("o")) mask |= 0o1007;
- return mask;
-}
-
-function symbolicBits(perms, who, current, isDirectory = false) {
- let bits = 0;
- const apply = (u, g, o) => {
- if (who.includes("a") || who.includes("u")) bits |= u;
- if (who.includes("a") || who.includes("g")) bits |= g;
- if (who.includes("a") || who.includes("o")) bits |= o;
- };
- for (const ch of perms) {
- if (ch === "r") apply(0o400, 0o040, 0o004);
- else if (ch === "w") apply(0o200, 0o020, 0o002);
- else if (ch === "x") apply(0o100, 0o010, 0o001);
- else if (ch === "X") {
- if (isDirectory || (current & 0o111)) apply(0o100, 0o010, 0o001);
- }
- else if (ch === "s") apply(0o4000, 0o2000, 0);
- else if (ch === "t") apply(0, 0, 0o1000);
- else if (ch === "u") bits |= copyClassBits(current, 6, who);
- else if (ch === "g") bits |= copyClassBits(current, 3, who);
- else if (ch === "o") bits |= copyClassBits(current, 0, who);
- }
- return bits;
-}
-
-function copyClassBits(mode, shift, who) {
- const classBits = (mode >> shift) & 7;
- let bits = 0;
- if (who.includes("a") || who.includes("u")) bits |= classBits << 6;
- if (who.includes("a") || who.includes("g")) bits |= classBits << 3;
- if (who.includes("a") || who.includes("o")) bits |= classBits;
- return bits;
-}
-
-async function testExpressionStatus(args, program = "test") {
- if (args[0] === "[") args = args.slice(1);
- if (args.at(-1) === "]") args = args.slice(0, -1);
- if (args.length === 0) return 1;
- try {
- const arity = await testByArity(args);
- if (arity != null) return arity ? 0 : 1;
- const parsed = await parseTestOr(args, 0);
- if (parsed.index !== args.length) throw new TestExpressionError(`extra argument ${localeQuotedDiagnostic(args[parsed.index])}`);
- return parsed.value ? 0 : 1;
- } catch (error) {
- if (error instanceof TestExpressionError) return fail(program, error.message, 2);
- throw error;
- }
-}
-
-async function testCmd(args) {
- return testExpressionStatus(args, "test");
-}
-
-async function bracketCmd(args) {
- if (args.at(-1) !== "]") return fail("[", `missing ${localeQuotedDiagnostic("]")}`, 2);
- return testExpressionStatus(args, "[");
-}
-
-class TestExpressionError extends Error {}
-
-async function parseTestOr(args, index) {
- let left = await parseTestAnd(args, index);
- while (args[left.index] === "-o") {
- const right = await parseTestAnd(args, left.index + 1);
- left = { value: left.value || right.value, index: right.index };
- }
- return left;
-}
-
-async function parseTestAnd(args, index) {
- let left = await parseTestNot(args, index);
- while (args[left.index] === "-a") {
- const right = await parseTestNot(args, left.index + 1);
- left = { value: left.value && right.value, index: right.index };
- }
- return left;
-}
-
-async function parseTestNot(args, index) {
- if (args[index] === "!") {
- const value = await parseTestOr(args, index + 1);
- return { value: !value.value, index: value.index };
- }
- return parseTestPrimary(args, index);
-}
-
-async function testByArity(args) {
- if (args.length === 1) return args[0].length > 0;
- if (args.length === 2) {
- if (args[0] === "!") return args[1].length === 0;
- if (args[0] === "-o") throw new TestExpressionError(`${localeQuotedDiagnostic("-o")}: unary operator expected`);
- if (isTestUnaryOperator(args[0])) return testUnaryExpression(args[0], args[1]);
- return null;
- }
- if (args.length === 3) {
- if (isTestBinaryOperator(args[1])) return testBinaryExpression(args[0], args[1], args[2]);
- if (args[0] === "!") {
- const value = await testByArity(args.slice(1));
- if (value != null) return !value;
- }
- if (args[0] === "(" && args[2] === ")") return args[1].length > 0;
- return null;
- }
- if (args.length === 4) {
- if (args[0] === "!") {
- const value = await testByArity(args.slice(1));
- if (value != null) return !value;
- }
- if (args[0] === "(" && args[3] === ")") {
- const value = await testByArity(args.slice(1, 3));
- if (value != null) return value;
- }
- }
- return null;
-}
-
-async function parseTestPrimary(args, index) {
- if (index >= args.length) throw new TestExpressionError("missing argument after operator");
- if (args[index] === "(") {
- const close = args.at(-1) === ")" ? args.length - 1 : findTestClosingParen(args, index);
- if (close !== -1) {
- const arity = await testByArity(args.slice(index + 1, close));
- if (arity != null) return { value: arity, index: close + 1 };
- }
- const value = await parseTestOr(args, index + 1);
- if (args[value.index] !== ")") throw new TestExpressionError(`missing ${localeQuotedDiagnostic(")")}`);
- return { value: value.value, index: value.index + 1 };
- }
- if (args[index + 1] && isTestBinaryOperator(args[index + 1])) {
- return { value: await testBinaryExpression(args[index], args[index + 1], args[index + 2]), index: index + 3 };
- }
- if (isTestUnaryOperator(args[index])) {
- if (args[index + 1] == null) return { value: String(args[index]).length > 0, index: index + 1 };
- return { value: await testUnaryExpression(args[index], args[index + 1]), index: index + 2 };
- }
- if (args[index] === ")") throw new TestExpressionError(`unexpected ${localeQuotedDiagnostic(")")}`);
- return { value: String(args[index]).length > 0, index: index + 1 };
-}
-
-function findTestClosingParen(args, index) {
- let depth = 0;
- for (let i = index; i < args.length; i++) {
- if (args[i] === "(") depth++;
- else if (args[i] === ")") {
- depth--;
- if (depth === 0) return i;
- }
- }
- return -1;
-}
-
-function isTestUnaryOperator(op) {
- return ["-a", "-b", "-c", "-d", "-e", "-f", "-g", "-G", "-h", "-k", "-L", "-N", "-n", "-O", "-p", "-r", "-S", "-s", "-t", "-u", "-w", "-x", "-z"].includes(op);
-}
-
-function isTestBinaryOperator(op) {
- return ["=", "==", "!=", "<", ">", "-eq", "-ne", "-lt", "-le", "-gt", "-ge", "-ef", "-nt", "-ot"].includes(op);
-}
-
-async function testUnaryExpression(op, value) {
- if (op === "-a" || op === "-e") return await access(value).then(() => true, () => false);
- if (op === "-n") return value.length > 0;
- if (op === "-z") return value.length === 0;
- if (op === "-t") return testFdIsTerminal(value);
- return await testUnaryFile(op, value) === 0;
-}
-
-async function testBinaryExpression(a, op, b) {
- if (b == null) throw new TestExpressionError(`missing argument after ${localeQuotedDiagnostic(op)}`);
- if (op === "=" || op === "==") return a === b;
- if (op === "!=") return a !== b;
- if (op === "<") return a < b;
- if (op === ">") return a > b;
- if (["-eq", "-ne", "-lt", "-le", "-gt", "-ge"].includes(op)) {
- const left = parseTestInteger(a);
- const right = parseTestInteger(b);
- return ({ "-eq": left === right, "-ne": left !== right, "-lt": left < right, "-le": left <= right, "-gt": left > right, "-ge": left >= right })[op];
- }
- if (["-ef", "-nt", "-ot"].includes(op)) return await testBinaryFile(a, op, b) === 0;
- throw new TestExpressionError(`${localeQuotedDiagnostic(op)}: binary operator expected`);
-}
-
-function parseTestInteger(value) {
- const text = String(value);
- if (!/^\s*[+-]?\d+\s*$/.test(text)) throw new TestExpressionError(`invalid integer ${localeQuotedEscapedDiagnostic(text)}`);
- return BigInt(text.trim());
-}
-
-function testFdIsTerminal(value) {
- const fd = Number(value);
- if (!Number.isInteger(fd) || fd < 0) return false;
- const s = fdStat(fd);
- return Boolean(s?.isCharacterDevice());
-}
-
-async function testUnaryFile(op, path) {
- try {
- if (op === "-r") return await access(path, fsConstants.R_OK).then(() => 0, () => 1);
- if (op === "-w") return await access(path, fsConstants.W_OK).then(() => 0, () => 1);
- if (op === "-x") return await access(path, fsConstants.X_OK).then(() => 0, () => 1);
- if (op === "-N") {
- const s = await stat(path, { bigint: true });
- return testStatTimeNs(s, "mtime") > testStatTimeNs(s, "atime") ? 0 : 1;
- }
- const s = op === "-h" || op === "-L" ? await lstat(path) : await stat(path);
- const mode = s.mode;
- if (op === "-b") return s.isBlockDevice() ? 0 : 1;
- if (op === "-c") return s.isCharacterDevice() ? 0 : 1;
- if (op === "-d") return s.isDirectory() ? 0 : 1;
- if (op === "-f") return s.isFile() ? 0 : 1;
- if (op === "-g") return (mode & 0o2000) ? 0 : 1;
- if (op === "-G") return process.getgid && s.gid === process.getgid() ? 0 : 1;
- if (op === "-h" || op === "-L") return s.isSymbolicLink() ? 0 : 1;
- if (op === "-k") return (mode & 0o1000) ? 0 : 1;
- if (op === "-O") return process.getuid && s.uid === process.getuid() ? 0 : 1;
- if (op === "-p") return s.isFIFO() ? 0 : 1;
- if (op === "-S") return s.isSocket() ? 0 : 1;
- if (op === "-s") return s.size > 0 ? 0 : 1;
- if (op === "-u") return (mode & 0o4000) ? 0 : 1;
- return 1;
- } catch {
- return 1;
- }
-}
-
-async function testBinaryFile(left, op, right) {
- const [a, b] = await Promise.all([stat(left, { bigint: true }).catch(() => null), stat(right, { bigint: true }).catch(() => null)]);
- if (!a || !b) {
- if (op === "-nt") return a && !b ? 0 : 1;
- if (op === "-ot") return !a && b ? 0 : 1;
- return 1;
- }
- if (op === "-ef") return a.dev === b.dev && a.ino === b.ino ? 0 : 1;
- if (op === "-nt") return testStatTimeNs(a, "mtime") > testStatTimeNs(b, "mtime") ? 0 : 1;
- if (op === "-ot") return testStatTimeNs(a, "mtime") < testStatTimeNs(b, "mtime") ? 0 : 1;
- return 1;
-}
-
-function testStatTimeNs(statInfo, name) {
- const value = statInfo[`${name}Ns`];
- if (value != null) return BigInt(value);
- return BigInt(statInfo[`${name}Ms`]) * 1_000_000n;
-}
-
-const commands = {
- "[": bracketCmd,
- arch,
- basenc,
- base32: base32Cmd,
- base64: base64Cmd,
- basename,
- cat,
- chcon: chconCmd,
- chgrp: chgrpCmd,
- chmod: chmodCmd,
- chown: chownCmd,
- chroot: chrootCmd,
- cksum,
- comm,
- coreutils: coreutilsCmd,
- cp: cpCmd,
- csplit: csplitCmd,
- cut,
- date: dateCmd,
- dd: ddCmd,
- dirname,
- dir: dirCmd,
- dircolors,
- df: dfCmd,
- du: duCmd,
- echo,
- env,
- expr: exprCmd,
- expand,
- factor,
- false: (args) => booleanCommand("false", args, 1),
- fmt: fmtCmd,
- fold,
- ginstall: ginstallCmd,
- head,
- hostid,
- hostname: hostnameCmd,
- groups: groupsCmd,
- id: idCmd,
- install: installCmd,
- join: joinCmd,
- kill: killCmd,
- link: linkCmd,
- ln: lnCmd,
- logname,
- ls: lsCmd,
- mkfifo: mkfifoCmd,
- mkdir: mkdirCmd,
- mknod: mknodCmd,
- mktemp: mktempCmd,
- mv: mvCmd,
- nice: niceCmd,
- nl: nlCmd,
- nohup: nohupCmd,
- nproc: nprocCmd,
- numfmt: numfmtCmd,
- od: odCmd,
- paste,
- pathchk,
- pinky,
- printenv,
- pr: prCmd,
- printf: printfCmd,
- ptx,
- pwd,
- readlink: readlinkCmd,
- realpath: realpathCmd,
- rm: rmCmd,
- rmdir: rmdirCmd,
- runcon: runconCmd,
- seq,
- sha1sum: hashCommand("sha1"),
- sha224sum: hashCommand("sha224"),
- sha256sum: hashCommand("sha256"),
- sha384sum: hashCommand("sha384"),
- sha512sum: hashCommand("sha512"),
- sm3sum: hashCommand("sm3"),
- sleep,
- sort: sortCmd,
- split: splitCmd,
- stat: statCmd,
- stty: sttyCmd,
- stdbuf: stdbufCmd,
- sum,
- shred: shredCmd,
- shuf,
- sync: syncCmd,
- tac,
- tail,
- tee,
- test: testCmd,
- touch,
- tr: trCmd,
- true: (args) => booleanCommand("true", args, 0),
- truncate: truncateCmd,
- timeout: timeoutCmd,
- tsort,
- tty: ttyCmd,
- uname: unameCmd,
- unexpand,
- uniq,
- unlink: unlinkCmd,
- uptime: uptimeCmd,
- users,
- vdir: vdirCmd,
- wc,
- who,
- whoami: whoamiCmd,
- yes,
- md5sum: hashCommand("md5"),
- b2sum: hashCommand("blake2b512"),
-};
-
-export const commandNames = Object.keys(commands).sort();
-
-const USAGE_STATUS_2 = new Set(["dir", "ls", "printenv", "sort", "tty", "vdir"]);
-const OUTPUT_ERROR_STATUS = new Map([
- ["[", 2],
- ["chroot", 125],
- ["dir", 2],
- ["env", 125],
- ["expr", 3],
- ["ls", 2],
- ["nice", 125],
- ["nohup", 125],
- ["printenv", 2],
- ["runcon", 125],
- ["sort", 2],
- ["stdbuf", 125],
- ["timeout", 125],
- ["tty", 3],
- ["vdir", 2],
-]);
-
-export async function main(argv) {
- emittedDiagnosticHints.clear();
- const [program, ...args] = argv;
- if (!program || program === "--help") {
- stdout(`Usage: bnu COMMAND [ARG]...\nImplemented commands: ${commandNames.join(", ")}\n`);
- return 0;
- }
- if (program === "--version") {
- stdout(`${VERSION}\n`);
- return 0;
- }
- const command = commands[program];
- if (!command) return fail("bnu", `unknown command '${program}'`);
- try {
- const metaOption = commandMetaOption(program, args);
- if (metaOption === "--help") {
- showGenericHelp(program);
- return 0;
- }
- if (metaOption === "--version") {
- stdout(`${VERSION}\n`);
- return 0;
- }
- return await command(args);
- } catch (error) {
- if (error instanceof InvocationError) {
- if (error.message) stderr(`${program}: ${error.message}\n`, true);
- else if (!gnulyCorrectDiagnostics()) stderr(`Hint: ${commandUsageHint(program, "Add the required command or argument")}\n`);
- if (error.showHelp) stderr(`Try '${program} --help' for more information.\n`);
- return error.code;
- }
- if (error instanceof UsageError) {
- stderr(`${program}: ${error.message}\n`, true);
- if (error.showHelp) stderr(`Try '${program} --help' for more information.\n`);
- return USAGE_STATUS_2.has(program) ? 2 : 1;
- }
- if (isOutputWriteError(error)) {
- const status = OUTPUT_ERROR_STATUS.get(program) ?? (USAGE_STATUS_2.has(program) ? 2 : 1);
- return fail(program, `write error: ${outputWriteErrorMessage(error)}`, status);
- }
- return fail(program, error.message || String(error), USAGE_STATUS_2.has(program) ? 2 : 1);
- }
-}
-
-function isOutputWriteError(error) {
- return error?.code === "ENOSPC" || error?.code === "EIO";
-}
-
-function outputWriteErrorMessage(error) {
- if (error?.code === "EPIPE") return "Broken pipe";
- if (error?.code === "ENOSPC") return "No space left on device";
- if (error?.code === "EIO") return "Input/output error";
- return error?.message || String(error);
-}
+export { commandNames } from "./shared/catalog.js";
+export { executeCommand, main } from "./shared/runtime.js";
if (import.meta.main) {
globalThis[Symbol.for("bnu.cli")] = true;