aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSoccera1 <[email protected]>2026-06-15 21:10:43 +1000
committerSoccera1 <[email protected]>2026-07-13 17:02:02 +1000
commit7ea75fb4424af8df393dd75dfb9b14a08aa46959 (patch)
tree52772fa63c7ae0581b44d0c0b164252934acf5f0
downloadbnu-7ea75fb4424af8df393dd75dfb9b14a08aa46959.tar.gz
bnu-7ea75fb4424af8df393dd75dfb9b14a08aa46959.zip
Initial commit
-rw-r--r--.gitignore2
-rw-r--r--LICENSE674
-rw-r--r--README.md446
-rwxr-xr-xbin/bnu.js22
-rw-r--r--docs/gnu-test-boundaries.md77
-rw-r--r--package.json19
-rwxr-xr-xscripts/link-commands.js45
-rwxr-xr-xscripts/qemu/build-payload.sh49
-rwxr-xr-xscripts/qemu/check-host.sh36
-rw-r--r--scripts/qemu/common.sh227
-rwxr-xr-xscripts/qemu/download-images.sh106
-rwxr-xr-xscripts/qemu/guest/provision-base.sh27
-rwxr-xr-xscripts/qemu/guest/provision-selinux.sh79
-rwxr-xr-xscripts/qemu/guest/provision-smack.sh33
-rwxr-xr-xscripts/qemu/guest/run-tests.sh41
-rwxr-xr-xscripts/run-all-tests.sh14
-rw-r--r--scripts/run-bun-tests-bounded.js48
-rwxr-xr-xscripts/run-gnu-qemu-matrix.sh133
-rw-r--r--scripts/run-gnu-tests.js1732
-rw-r--r--scripts/run-memory-bounded.js90
-rwxr-xr-xscripts/run-qemu-root-smoke.sh153
-rwxr-xr-xscripts/setup-qemu-environments.sh141
-rw-r--r--src/coreutils.js33625
-rw-r--r--tests/coreutils.test.js9431
24 files changed, 47250 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..565458d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+coreutils-9.11.tar.xz
+/audit/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..07ebfdf
--- /dev/null
+++ b/README.md
@@ -0,0 +1,446 @@
+# bnu
+
+A Bun JavaScript rewrite of GNU coreutils, currently implemented as a multi-call CLI.
+
+```sh
+bun ./bin/bnu.js echo hello
+bun ./bin/bnu.js sort file.txt
+```
+
+The normal local test suite runs each test in a fresh process with a 1 GiB
+aggregate process-tree RSS ceiling and a 3 GiB per-process address-space
+ceiling. `factor` also defaults to one worker; controlled audits can opt in to
+bounded parallelism with `BNU_FACTOR_WORKERS`.
+
+```sh
+bun run test
+```
+
+There is also an optional harness for running GNU coreutils' command-level
+upstream tests from the bundled tarball against the Bun wrappers. With no test
+arguments it runs a small curated subset; pass upstream test paths for targeted
+runs, or use `--all` to
+select the 733 `.sh`/`.pl` entries in GNU's standard `TESTS` list. The 41
+root-test names are members of that same list and are rerun with root privileges
+rather than counted as additional tests. GNU's separate `gnulib-tests` validate
+its internal C portability library and are outside this JavaScript command
+compatibility scope. By default compatibility failures are
+reported without making the command fail; add `--strict` to return a non-zero
+status when any GNU test fails. Each GNU test has a default 300 second timeout
+to account for the Bun-backed wrappers' startup cost in broad all-command
+upstream sweeps; override it with
+`--timeout`. Pass `--expensive` to set `RUN_EXPENSIVE_TESTS=yes`, or
+`--very-expensive` to set both `RUN_EXPENSIVE_TESTS=yes` and
+`RUN_VERY_EXPENSIVE_TESTS=yes` for upstream tests that are disabled by default.
+Known terminal-dependent upstream tests are automatically run in their own
+controlling pseudo-terminal. Pass `--tty` to force that mode for every selected
+test. Pass `--keep` to preserve both the extracted source tree and GNU tests'
+inner temporary directories for syscall-log and failure-artifact inspection.
+The harness enforces a 1536 MiB aggregate RSS ceiling for each test process
+tree and a 3 GiB per-process address-space ceiling by default; override these
+with `--rss-limit` and `--memory-limit` when a controlled stress audit requires
+different bounds.
+
+```sh
+bun run test:gnu --list
+bun run test:gnu
+bun run test:gnu --all --list
+bun run test:gnu tests/misc/echo.sh
+bun run test:gnu --strict tests/misc/echo.sh
+bun run test:gnu --timeout 10s tests/misc/printenv.sh
+bun run test:gnu --rss-limit 1GiB --memory-limit 3GiB tests/misc/echo.sh
+bun run test:gnu tests/stty/stty-invalid.sh
+bun run test:gnu --expensive tests/tail/big-4gb.sh
+bun run test:gnu --very-expensive tests/misc/sort.sh
+# A representative 96-bit contiguous-range factor stress case.
+bun run test:gnu --strict --very-expensive tests/factor/t26.sh
+```
+
+## Portable QEMU test matrix
+
+The complete upstream command-test inventory can run without depending on the
+host distribution or host root access. The matrix uses official, authenticated
+Gentoo amd64 artifacts to create four separate environments beneath
+`/var/tmp/bnu-qemu`:
+
+- a standard Gentoo guest for the 692 non-root inventory members;
+- a stage4 built from Gentoo's hardened SELinux systemd stage3, with the MLS
+ policy active in enforcing mode, for the 41 root tests and SELinux cases;
+- a distinct qcow2 SMACK overlay with a custom kernel built using one compiler
+ job and a 2 GiB guest swap file;
+- the official Gentoo amd64 GNU/Hurd preview and a separate BNU matrix overlay.
+
+The all-tests entry point first runs the local bounded unit suite, then creates
+or resumes the guests, builds an ext4 payload from the current checkout, runs
+one VM at a time, and reconciles all 733 upstream test names:
+
+```sh
+scripts/run-all-tests.sh --setup
+# Subsequent runs reuse the guests and refresh only the payload:
+scripts/run-all-tests.sh
+```
+
+Use `scripts/run-gnu-qemu-matrix.sh` directly when only the upstream matrix is
+wanted.
+
+The host can be any Linux distribution. It needs Bash, Bun, KVM access, QEMU
+for x86_64, OVMF, OpenSSH clients, curl, GnuPG, e2fsprogs (`mkfs.ext4`), xorriso
+or genisoimage, and ordinary POSIX archive/checksum tools. Package names differ
+between distributions, so the scripts check executable names rather than
+assuming a package manager. `/dev/kvm` must be readable and writable by the
+calling user; there is intentionally no TCG fallback. A quick dependency and
+action check that downloads or boots nothing is available with:
+
+```sh
+scripts/qemu/check-host.sh
+scripts/setup-qemu-environments.sh --dry-run
+scripts/run-gnu-qemu-matrix.sh --dry-run
+```
+
+Persistent downloads, base images, isolated overlays, readiness markers, and
+timestamped results stay under `BNU_QEMU_DIR` (default `/var/tmp/bnu-qemu`).
+Set that variable to another user-writable directory if necessary. Temporary
+seed staging and GNU extraction trees use `${TMPDIR:-/tmp}` and may be wiped
+between runs. The setup is phase-resumable; completed image markers prevent a
+costly rebuild. Individual environments can be prepared with
+`scripts/setup-qemu-environments.sh --only standard|selinux|smack|hurd`.
+
+Every VM is KVM-only, defaults to 1536 MiB RAM and two vCPUs, and heavy work is
+strictly sequential. Guest package/kernel builds use `-j1`; each GNU test gets
+a 1 GiB aggregate process-tree RSS ceiling and a 3 GiB per-process virtual
+memory ceiling. Override VM sizing only when needed with `BNU_QEMU_MEMORY` and
+`BNU_QEMU_CPUS`. Official artifacts are cached only after their Gentoo OpenPGP
+signature is verified using Gentoo's published service-key bundle; the Hurd
+image's developer signature is pinned to its full Gentoo signing-key
+fingerprint and also gets its published SHA-512 check.
+
+Allow roughly 30 GiB of free space for a first complete setup: qcow2 images are
+sparse, but Portage downloads, the SELinux root, kernel sources, modules, and
+the one-job SMACK build still consume real blocks. The setup checks free space
+before downloading or booting. `BNU_QEMU_MIN_FREE_GIB` can override that guard
+when the state directory is on a specially provisioned thin or compressed
+filesystem.
+
+The final reconciliation fails if any inventory member lacks a PASS on its
+appropriate platform, except for the six documented Bun startup/ABI boundaries
+in [`docs/gnu-test-boundaries.md`](docs/gnu-test-boundaries.md).
+Logs are written to `/var/tmp/bnu-qemu/results/TIMESTAMP` by default.
+
+For a smaller Linux root-only smoke check, the repository also retains an
+initramfs runner. It assembles the current Bun executable and source tree into
+a matching zstd-compressed initramfs, then checks privileged ownership changes,
+special-file creation, and `cp -p` metadata preservation as guest root:
+
+```sh
+BNU_QEMU_KERNEL=/boot/vmlinuz-... \
+BNU_QEMU_INITRAMFS=/boot/initramfs-....img \
+ scripts/run-qemu-root-smoke.sh
+```
+
+The smoke runner requires `qemu-system-x86_64`, `zstd`, `cpio`, KVM access, and
+a kernel/initramfs pair that can boot on the host CPU. It uses `lsinitrd` when
+available to unpack concatenated or compressed input images, with direct
+decompressor fallbacks. Compression is single-threaded and it uses KVM with
+`-cpu host`; `BNU_QEMU_MEMORY` overrides its default 1536 MiB guest allocation.
+
+SELinux guests must select SELinux in the kernel's active LSM list, not merely
+compile it in. On kernels whose `CONFIG_LSM` default omits SELinux, boot with
+`lsm=selinux` (in addition to `security=selinux selinux=1`); otherwise
+libselinux process attributes and thread-local creation contexts can fail with
+`EINVAL` even though `sestatus` reports an enabled policy. Bun's FFI compiler
+also requires executable anonymous memory in enforcing mode; the dedicated
+test guest enables the policy's standard `allow_execmem` boolean rather than
+carrying an ad-hoc local allow rule.
+
+To create command-name wrappers such as `cat`, `wc`, and `sort`:
+
+```sh
+bun run link-commands -- ./dist/bin
+./dist/bin/echo hello
+```
+
+## Implemented Commands
+
+`[`, `arch`, `b2sum`, `base32`, `base64`, `basename`, `basenc`, `cat`, `chcon`,
+`chgrp`, `chmod`, `chown`, `chroot`, `cksum`, `comm`, `coreutils`, `cp`,
+`csplit`, `cut`, `date`, `dd`, `df`, `dir`, `dircolors`, `dirname`, `du`,
+`echo`, `env`, `expand`, `expr`, `factor`, `false`, `fmt`, `fold`, `ginstall`,
+`groups`, `head`, `hostid`, `hostname`, `id`, `install`, `join`, `kill`, `link`,
+`ln`, `logname`, `ls`, `md5sum`, `mkdir`, `mkfifo`, `mknod`, `mktemp`, `mv`,
+`nice`, `nl`, `nohup`, `nproc`, `numfmt`, `od`, `paste`, `pathchk`, `pinky`,
+`pr`, `printenv`, `printf`, `ptx`, `pwd`, `readlink`, `realpath`, `rm`,
+`rmdir`, `runcon`, `seq`, `sha1sum`, `sha224sum`, `sha256sum`, `sha384sum`,
+`sha512sum`, `shred`, `shuf`, `sleep`, `sm3sum`, `sort`, `split`, `stat`,
+`stdbuf`, `stty`, `sum`, `sync`, `tac`, `tail`, `tee`, `test`, `timeout`,
+`touch`, `tr`, `true`, `truncate`, `tsort`, `tty`, `uname`, `unexpand`, `uniq`,
+`unlink`, `uptime`, `users`, `vdir`, `wc`, `who`, `whoami`, `yes`.
+
+The GNU coreutils 9.11 command-test inventory is reconciled against the current
+source: 727 of its 733 scripts have passing host or QEMU evidence. The remaining
+six are confirmed Bun startup or target-ABI boundaries: two tests remove the
+procfs facilities Bun needs to start, two start below Bun's required file-
+descriptor floor, one traps during Bun startup in a `SCHED_DEADLINE` systemd
+scope, and one requires a GNU/Hurd ABI for which no Bun runtime exists. This
+includes root-only reruns and activated terminal, SELinux MLS, SMACK, expensive,
+and very-expensive paths. The six test names, exact rationale, and evidence are
+in [`docs/gnu-test-boundaries.md`](docs/gnu-test-boundaries.md).
+
+This 733-script scope is not every assertion in the package: individual scripts
+contain multiple cases, and it excludes GNU's C-internal `gnulib-tests`.
+Passing it does not imply that every GNU extension or platform combination is
+implemented; BNU remains an independent JavaScript implementation rather than
+GNU's native C code.
+
+## Compatibility Notes
+
+The test suite now covers recursive `cp`, copying into directory targets,
+metadata preservation hooks, symbolic `chmod` mode clauses, signed and legacy
+shorthand `head` and `tail` counts, zero-terminated `head` and `tail` records,
+real FIFO creation through libc for
+`mkfifo`/`mknod p` including octal and symbolic modes, and multi-call wrapper generation. On SELinux systems,
+`mkdir`, `mkfifo`, and `mknod` apply validated explicit creation contexts with
+`--context=CTX` and restore pathname defaults with `-Z`, including directories
+created by `mkdir -p`. `cat` supports
+numbering, blank squeezing, line end markers, tab markers, and common
+nonprinting character display modes. Hash utilities support standard
+checksum-file verification with `-c`/`--check`, `--status`, `--quiet`,
+`--warn`, `--strict`, and `--ignore-missing`. `echo`
+supports common GNU `-n`/`-e`/`-E`, long-option, POSIXLY_CORRECT, simple, octal, hex, escape, and `\c` forms. `basename`
+supports suffix stripping, multiple-name mode, NUL-delimited output, and GNU
+root and suffix edge cases;
+`dirname` supports multiple names and NUL-delimited output, and both preserve
+non-UTF-8 pathname bytes. `pwd` supports
+physical output by default, logical `PWD` validation with `-L`, and operand
+validation. Common option-parsed commands reject undeclared short and long options with GNU-style usage failures. `sort` covers
+common GNU comparison modes including version, month, human numeric,
+dictionary order, check variants, NUL-terminated records, and `-o` output. `ls`
+covers hidden-file modes,
+classification, recursive listing, size/time/extension/reverse sorting,
+unsorted mode, basic color output, and POSIX ACL `+` mode indicators when
+`getfacl` is available. Text ordering for both `sort` and `ls` follows the
+active libc locale's collation rules, including non-UTF-8 command-line names;
+C and POSIX locales retain bytewise ordering. `base32` and `base64` support
+standalone RFC 4648 encoding/decoding, wrapping, and decode garbage handling.
+`cat` streams ordinary file and special-device operands with bounded memory.
+`cut` likewise streams bounded byte, character, and field selections from
+special files, preserves invalid UTF-8 bytes, honors multibyte character
+boundaries for `-b -n`, and follows libc-style multibyte blank classification.
+`basenc` supports base16, base32, base32hex, base64, base64url, base2 MSB/LSB,
+base58, z85, wrapping, strict decode garbage handling, and bounded-memory
+streaming for the group-based encoders.
+`cut` supports byte, character, delimiter, complement, output-delimiter,
+NUL-terminated, and whitespace-delimited field modes, with interval-based
+huge ranges and bounded-memory streaming for byte positions and safe field
+selections.
+`expand` and `unexpand` support explicit and repeating tab-stop forms and
+bounded-memory conversion of stdin, files, and special devices while preserving
+multibyte display-width and blank-run state across input chunks.
+`fold` streams ordinary stdin, file, and special-device folding, distinguishes byte, character, and
+display-column widths, and preserves zero-width characters without forcing
+spurious line breaks.
+Single-input `paste` preserves records through a bounded-memory stream, and
+`od -v` incrementally formats ordinary and special files without accumulating
+the complete input.
+`comm` incrementally merges sorted non-regular inputs, `uniq` streams its
+default and unseparated all-repeated modes, and negative-count `head` keeps
+only the bounded byte or record tail needed for special devices.
+From-start `tail` streams non-regular byte-record inputs directly, including
+NUL-delimited device streams.
+`factor` consumes non-regular standard input as a bounded token stream while
+retaining batch optimization for regular-file input.
+Checksum verification consumes non-regular checklist input line-by-line and
+reports each verification result without waiting for end of input.
+`join` streams selected unmatched records when the opposite input is known
+empty, including NUL-delimited device input against `/dev/null`.
+`wc` and `du` consume non-regular `--files0-from` sources one name at a time,
+so FIFO and standard-input filename lists remain bounded even when unending.
+`dircolors` supports shell output modes, database printing, and simple color
+database files.
+`cksum` supports the classic CRC form plus common digest algorithms through
+`--algorithm`, including tagged, untagged, base64, and NUL-terminated output.
+`sum` supports GNU's BSD and System V algorithms. `touch` supports explicit,
+reference, access/modify-only, GNU `--time` aliases, and no-dereference
+symlink timestamps. `factor` supports stdin and
+argument factoring plus GNU exponent output. `expr` supports arithmetic,
+comparisons, and common GNU string operations including length, substr, index,
+and anchored regex matching. `id` supports current and named-user numeric and named user/group output
+for primary and supplementary groups, NUL-delimited selected fields, and GNU-style choice validation; `groups` prints resolved primary and supplementary group names
+when available and accepts username operands, and `logname` and `whoami` validate that no operands
+are supplied. `users` accepts GNU's optional file operand. `who` supports simple heading, count, boot-time, `am i`, message-status,
+short, users, and all-mode option forms.
+Recursive `chmod -R` uses the same
+numeric and symbolic mode parser as single-path `chmod`, including GNU
+long-option abbreviation forms, and reports failed permission-changing syscalls
+separately from pathname-access failures. `chown` and `chgrp`
+cover common ownership/group changes, reference/from filters, recursive safety,
+GNU `-H`/`-L`/`-P` symlink traversal semantics, inaccessible-directory
+diagnostics, verbose failure records, and
+GNU long-option abbreviation forms. `readlink` and `realpath` cover
+common canonicalization, NUL delimiter, no-symlink, and relative-output modes.
+`truncate` supports reference sizes, reference-relative size operators,
+no-create mode, GNU byte suffixes, and common relative size operators. `tee` supports append, ignore-interrupts, and
+output-error mode options. `cp`, `mv`, and `ln`
+support GNU target-directory forms with `-t` and `-T`; all three accept GNU
+long-option abbreviation forms, and `cp --parents` also
+accepts the GNU-style `--parent` abbreviation; `mkdir` supports octal
+and symbolic modes, `install` supports octal and symbolic `-m` modes for files
+and directories; on SELinux systems it also preserves contexts with
+`--preserve-context`, includes contexts in `-C` comparisons, restores default
+labels with `-Z` (including `-D`/`-d` parents), and validates explicit
+`--context=CTX` creation labels. `install -C` also compares the requested or
+effective owner and group before deciding that an existing target can be left
+unchanged. `rmdir` and `rm` cover common verbose, parent,
+non-empty, interactive-mode, empty-directory removal, and GNU long-option
+abbreviation modes. `cp --copy-contents`
+copies FIFO contents when a writer supplies data during recursive copies, and
+`cp -p` preserves POSIX ACLs when `getfacl` and `setfacl` are available. `cp`
+and cross-filesystem `mv` preserve supported extended-attribute namespaces,
+including attributes on symlinks; explicit `--preserve=xattr` reports restore
+failures while archive and `--preserve=all` use GNU's best-effort behavior;
+on an active SELinux system, `cp -a`, `--preserve=context`, `--context=CTX`,
+and `-Z` respectively preserve, explicitly set, or restore destination security
+contexts, with interposable libselinux `getfilecon` access and validation of
+explicit labels. Missing optional source labels are ignored for archives while
+an explicitly required context fails before copying. Context-preserving
+`--parents` copies update both new and existing parent-directory labels;
+explicitly required preservation fails before file data is written on a
+fixed-context filesystem; and `-Z` creates with the source label before
+restoring a pathname default, retaining that label when no default exists.
+Directory creation uses a same-thread syscall while `setfscreatecon(3)` is
+active, so Bun worker scheduling cannot silently lose explicit creation labels;
+`cp --reflink=always|auto|never` attempts Linux native file cloning when the
+filesystem supports it, and `cp --sparse=always|auto|never` controls sparse regular-file copying with
+`SEEK_DATA`/`SEEK_HOLE` extent traversal and allocated-zero detection.
+Cross-filesystem `mv` preserves sparse extents and recreates FIFO, device, and
+socket nodes; failed source removal from sticky directories uses GNU's
+operation-level diagnostic. With terminal input, `mv` also protects an
+unwritable destination with GNU's default mode-aware prompt unless an effective
+`-f` suppresses it. `cp` also retries destination creation when an interposed
+`fstatat` reports a stale NFS entry that has disappeared before open. `link` and
+`unlink` enforce fixed operand counts and support `--` for dash-prefixed names.
+Capability xattrs are applied after final ownership changes, so
+`cp --preserve=xattr` and `--preserve=all` retain Linux file capabilities.
+Recursive `rm` traverses Linux directory streams incrementally, preserves raw
+filename bytes, and distinguishes immediate read failures from partial traversal
+failures. Noninteractive flat entries use a one-syscall unlink fast path with
+metadata-aware fallback, keeping a 400,000-entry ext4 removal below GNU's
+60-second performance gate.
+`mktemp` supports files, directories, optional tmpdir/default temp placement,
+explicit and implicit suffixes, suffix validation, and dry-run name generation. `dd` supports input/output block sizes, skip, count, seek,
+byte-oriented flags, status modes, range-aware `nocache` input/output advice
+that evicts through EOF only when EOF was reached, pre-copy seek
+truncation with failure diagnostics, real seek-based stdin skipping and stdout
+positioning (including block-device boundary validation), notrunc output writes,
+and sparse output conversion. `split`
+supports line, byte, line-byte, chunk-count, round-robin,
+numeric, hex, configurable suffix starts, additional-suffix, and separator
+modes, plus GNU-style operand validation. Fixed-number splitting of non-regular
+input is disk-spooled through `$TMPDIR`, avoiding unbounded heap growth and
+reporting storage exhaustion normally. `env` and `printenv`
+support NUL-delimited output, and `env` handles empty environments, directory
+changes, variable unsets, custom command argv0, and simple `-S` split strings. `sync` supports file
+operands plus data and file-system mode flags. `df --sync` issues `sync(2)`
+before its native filesystem query. `tail -f`/`-F` uses native inotify watches
+for regular files and FIFOs, watches parent directories for name following,
+removes stale watches across rotation, and falls back to blocking device reads
+or polling when notification is unavailable or disabled; `--debug` reports the
+selected strategy. Byte-count mode seeks relative to the true end of block
+devices, including `-c +OFFSET`, without buffering the device. `stat` supports a
+broader set of GNU file format escapes, `--printf`, and terse output. `du`
+supports byte, block-size, human-readable, SI, apparent-size, total, and
+NUL-terminated output modes, including GNU long-option abbreviations. During
+concurrent directory moves it collapses stale descendants into one GNU-style
+`fts_read failed` diagnostic and continues later operands. `df`
+supports GNU block-size suffixes, human-readable/SI output, inode reporting,
+local and file-system-type filtering, total row modes, over-mounted block-device
+diagnostics, and byte-preserving non-UTF-8 mount names. `od` supports common
+address, skip, limit, width, character, unsigned, and hex dump modes. `numfmt`
+supports common scaling, table-field, header, delimiter,
+padding, suffix, and invalid-value modes. `stdbuf` accepts input, output, and
+error buffering mode options, including GNU long-option abbreviations, before running a command. `shuf` supports NUL records, repeat
+mode, output files, deterministic random sources, and GNU operand/count validation. `shred` supports force,
+verbose, exact, zero, remove, pass-count, and GNU long-option abbreviation modes. `uniq` supports common
+counting, repeated, unique, field/character skipping, NUL-delimited,
+all-repeated, group-delimiter, output-file, and operand-validation modes. `seq` handles fixed-point decimal
+steps, negative operands with options, and common printf-style formatting. `printf` supports common numeric,
+string, `%b`, `%q`, `\c` stop, Unicode escapes, and bounded streaming for very
+large simple field widths. `sleep` and `timeout` support GNU
+duration suffixes and fractional intervals; `timeout` also supports custom signals, preserve-status,
+kill-after, disabled zero-duration timeouts, verbose signal diagnostics, default process-group
+termination of descendants, `--foreground` PID-only behavior, and Linux parent-death signaling.
+`nice` parses common
+GNU adjustment forms before running a command. `nohup` preserves piped input,
+makes commands immune to SIGHUP, implements terminal-only input/output/error
+redirection and 0600 `nohup.out` creation, preserves command exit status, and
+returns 127 for missing commands. `kill` supports signal
+listing, signal table output, name/number conversion, and signal-zero checks. `date` supports more GNU format
+escapes, padding/case flags, reference files, date files, debug diagnostics,
+and real `--set` clock changes through `clock_settime(2)` when permitted.
+`fmt` supports width shorthand, goal parsing, prefix-filtered formatting,
+split-only mode, uniform spacing, and bounded paragraph formatting for
+non-regular default input. `fold` supports byte, character, width,
+and blank-aware wrapping modes. `tr` covers common POSIX character
+classes, escaped characters, complement mode, deletion, translation, and repeat
+squeezing. `tac` supports literal custom separators and before-separator mode;
+non-seekable input is disk-spooled so an input failure does not prevent later
+file operands from being processed.
+`arch` and `hostid` expose platform identifiers with GNU-style operand
+validation. `hostname` prints or attempts to set the system host name. `stty` supports
+all-settings and saved-settings output modes, speed/size queries, real termios
+setting forms, GNU fractional baud rounding and legacy speed aliases, C-style
+numeric control values, and invalid-setting diagnostics. `tty` supports
+silent/quiet status-only mode and GNU-style operand validation. `uname` supports common GNU
+selectors including `-a`, `-s`, `-n`, `-r`, `-v`, `-m`, `-p`, `-i`, and `-o`.
+`uptime` follows GNU coreutils' current-time, uptime, user-count, and load-average
+format, with the standard optional utmp/wtmp file operand.
+`nproc` supports `--all`, `--ignore`, OpenMP thread-limit environment
+variables, cgroup v2 CPU quotas (including inherited quotas and scheduler
+exceptions), and GNU-style operand and option diagnostics.
+`nl` supports common body-selection, number-format, width,
+separator, increment, starting-number, regex, and blank-grouping modes. `paste`
+supports serial and parallel operation with custom escaped, column-cycled delimiters and
+NUL-terminated records, including repeated stdin operands. `comm` supports custom output delimiters, totals,
+NUL-terminated records, and sorted-order checking modes. `pinky` supports
+simple short and long user records, including project/plan files and
+left-to-right `-l`/`-s` mode selection.
+`csplit` supports prefixes, digit widths, suffix formats, quiet mode,
+empty-file elision, suppressed matched separators, regex offsets, and skip
+patterns. `pr` supports omitted and custom page headers, line numbering,
+custom first line numbers, margin indentation, and bounded-memory streaming
+for default single-column pagination from stdin and special-file operands. `ptx` supports GNU-style
+ignore-case option parsing, ignore/only word files, custom word and sentence
+regexes, break-character files, automatic/manual references, and configurable
+truncation markers.
+`expr` preserves raw command-line bytes, applying character-aware length,
+index, substring, and basic-regex behavior only in multibyte locales.
+`ls -Z` and `stat %C` read SELinux contexts where the `security.selinux`
+xattr is available, and long `ls` listings use GNU's `.` mode suffix for a
+security context when no extended ACL takes precedence. Classification queries
+regular-file mode bits without dereferencing symlink targets unnecessarily.
+If a directory entry's metadata becomes inaccessible after `readdir`, `ls`
+retains its kernel `d_type`, emits GNU's unknown-metadata row, and continues
+with minor-error status (including accurate `--dired` offsets).
+When `LS_COLORS` enables `ca=`, `ls` colors files carrying a
+`security.capability` xattr using their full path; an empty `ca=` disables the
+capability probe.
+`chcon` supports explicit, reference, component, recursive,
+and no-dereference context changes on SELinux-capable filesystems, and reports
+failed full-context or partial-context operations on unlabeled files.
+`cp`, `install`, and the file-creation commands support GNU context preservation,
+explicit contexts, and default-policy restoration; `mv -Z`/`--context` restores
+destination-policy labels after both renames and cross-filesystem moves.
+`id -Z`/`--context` reports the current SELinux process label, and default `id`
+output includes `context=...` outside POSIX mode. On newer stacked-LSM kernels,
+the implementation uses `lsm_get_self_attr(2)` before legacy libselinux access.
+`chroot` performs the real root switch, GNU `/` versus `--skip-chdir` handling,
+command-status propagation, and user, primary-group, and supplementary-group
+changes from named or forced-numeric specifications.
+`runcon` prints the active process context, accepts complete contexts or GNU
+compute/user/role/type/range forms, validates and computes transitions through
+libselinux, and applies the requested exec label through legacy or modern LSM
+interfaces before dispatching the command.
+`yes` repeats the default `y` line or joined operand strings.
+`test` and `[` support common file predicates,
+read/write/execute checks, string and numeric comparisons, and file identity
+and timestamp comparisons. `pathchk` supports GNU portability checks with
+`-p`/`--portability` and leading-hyphen/empty-component checks with `-P`.
diff --git a/bin/bnu.js b/bin/bnu.js
new file mode 100755
index 0000000..b451084
--- /dev/null
+++ b/bin/bnu.js
@@ -0,0 +1,22 @@
+#!/usr/bin/env bun
+import { realpathSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+import { pathToFileURL } from "node:url";
+
+const here = dirname(realpathSync(Bun.argv[1]));
+globalThis[Symbol.for("bnu.cli")] = true;
+const { commandNames, main } = await import(pathToFileURL(join(here, "../src/coreutils.js")).href);
+let invokedPath = Bun.argv[1];
+try {
+ if (process.env._ && realpathSync(process.env._) === realpathSync(Bun.argv[1])) invokedPath = process.env._;
+} catch {
+ // Fall back to Bun's resolved script path when the shell-provided path is not usable.
+}
+const invokedAs = basename(invokedPath).replace(/\.js$/, "");
+const argv = invokedAs === "bnu"
+ ? Bun.argv.slice(2)
+ : commandNames.includes(invokedAs)
+ ? [invokedAs, ...Bun.argv.slice(2)]
+ : ["coreutils", `--coreutils-prog=${invokedAs}`, ...Bun.argv.slice(2)];
+
+process.exit(await main(argv));
diff --git a/docs/gnu-test-boundaries.md b/docs/gnu-test-boundaries.md
new file mode 100644
index 0000000..ebac2ef
--- /dev/null
+++ b/docs/gnu-test-boundaries.md
@@ -0,0 +1,77 @@
+# GNU coreutils 9.11 test boundaries
+
+## Scope
+
+BNU tracks the 733 `.sh` and `.pl` command-test scripts in GNU coreutils
+9.11's standard `TESTS = $(all_tests) $(factor_tests)` inventory. Individual
+scripts can contain multiple assertions. GNU's C-internal `gnulib-tests` suite
+is outside this JavaScript command-compatibility scope.
+
+The upstream `all_root_tests` variable contains 41 names that are already part
+of the 733; they are routed to a root guest rather than counted twice. The
+runner derives both sets from the extracted upstream `Makefile.in`, currently
+yielding 692 non-root tests and 41 root tests.
+
+The accepted result is 727 tests with a `PASS` record on at least one suitable
+platform and the following six Bun runtime or target-ABI boundaries. A normal
+BNU JavaScript command cannot begin in any of these six environments.
+
+## Accepted boundaries
+
+| Upstream test | Boundary before BNU can execute |
+|---|---|
+| `tests/df/no-mtab-status-masked-proc.sh` | The test replaces or masks `/proc`. Bun aborts during runtime startup because required procfs facilities are unavailable. |
+| `tests/id/gnu-zero-uids.sh` | The behavior is specific to GNU/Hurd. The official Gentoo amd64 Hurd guest supplies that ABI, but Bun is a Linux ELF executable requesting Linux's loader and glibc ABI, so it cannot start on Hurd. |
+| `tests/nproc/nproc-quota-systemd.sh` | The test starts the command in an exact `SCHED_DEADLINE` systemd scope. Bun traps during startup in that scope; ordinary and other scheduler/cgroup quota cases run. |
+| `tests/sort/sort-continue.sh` | The test closes file descriptors below Bun's runtime startup requirement. Bun aborts while initializing its event loop, before the `sort` JavaScript runs. |
+| `tests/sort/sort-merge-fdlimit.sh` | The imposed descriptor limit is below Bun's runtime startup floor, so the runtime aborts before dispatching BNU. |
+| `tests/stat/stat-mount.sh` | The test hides or replaces `/proc`. Bun aborts during startup before the `stat` JavaScript can execute. |
+
+These entries are not allowances for arbitrary skips. The QEMU matrix embeds
+this exact sorted allowlist and fails when any other inventory member lacks a
+`PASS` record. If a future Bun version makes one of these tests pass, the
+matrix reports that the documented boundary is stale so it can be removed.
+
+## Resolved former skips
+
+The following cases formerly depended on unavailable host state or GNU C
+debugger hooks and now have executable coverage:
+
+| Tests | Resolution |
+|---|---|
+| `tests/df/no-mtab-status.sh`, `tests/df/skip-duplicates.sh`, `tests/df/skip-rootfs.sh` | Deterministic JavaScript mount-table fixtures exercise the same parser cases without obsolete or synthetic host mounts. |
+| `tests/du/bigtime.sh` | A JavaScript timestamp fixture supplies the upstream out-of-range timestamp independently of the host filesystem range. |
+| `tests/rm/r-root.sh` | The adapted fixture intercepts the same removal boundary and validates abbreviated `--no-preserve-root` rejection without GNU `remove.c` symbols. |
+| `tests/tail/inotify-race.sh`, `tests/tail/inotify-race2.sh` | A synchronous JavaScript hook replaces the GNU `tail.c` debugger breakpoint and deterministically reproduces both races. |
+| `tests/chcon/chcon.sh`, `tests/ls/selinux.sh`, `tests/id/setgid.sh` | These run in the Gentoo amd64 SELinux guest with the MLS policy active. |
+| `tests/id/smack.sh`, `tests/mkdir/smack-root.sh`, `tests/mkdir/smack-no-root.sh` | These run in the Gentoo amd64 SMACK guest; the no-root case runs as `nobody` on the XFS guest root. BNU selects the active LSM and reads or writes `security.SMACK64`. |
+
+Terminal-dependent tests receive a controlling pseudo-terminal. Expensive and
+very-expensive paths, including generated factor tests `t00` through `t40`, are
+enabled by the matrix. Root, SELinux, SMACK, and Hurd cases are routed to their
+dedicated Gentoo guests.
+
+## Reproduction and evidence
+
+Run the bounded unit suite and complete platform matrix with:
+
+```sh
+scripts/run-all-tests.sh --setup
+```
+
+The process is sequential and KVM-only. It defaults to 1536 MiB per guest,
+uses one compiler job for guest kernel/package builds, and applies an aggregate
+RSS ceiling to every GNU test process tree. See the QEMU section in the main
+[README](../README.md#portable-qemu-test-matrix) for host prerequisites and
+image setup.
+
+Each run writes its inventory, per-platform logs, allowed boundaries, passed
+set, unresolved set, and unexpected-unresolved set beneath:
+
+```text
+/var/tmp/bnu-qemu/results/TIMESTAMP/
+```
+
+That directory is generated evidence and is intentionally not stored in Git.
+The durable source-controlled contract is this document plus the executable
+reconciliation in `scripts/run-gnu-qemu-matrix.sh`.
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..0e2ce75
--- /dev/null
+++ b/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "bnu",
+ "version": "0.1.0",
+ "type": "module",
+ "bin": {
+ "bnu": "./bin/bnu.js"
+ },
+ "scripts": {
+ "link-commands": "bun scripts/link-commands.js",
+ "test": "bun scripts/run-bun-tests-bounded.js",
+ "test:gnu": "bun scripts/run-gnu-tests.js",
+ "qemu:setup": "scripts/setup-qemu-environments.sh",
+ "test:qemu": "scripts/run-gnu-qemu-matrix.sh",
+ "test:all": "scripts/run-all-tests.sh"
+ },
+ "devDependencies": {
+ "bun-types": "latest"
+ }
+}
diff --git a/scripts/link-commands.js b/scripts/link-commands.js
new file mode 100755
index 0000000..617f64e
--- /dev/null
+++ b/scripts/link-commands.js
@@ -0,0 +1,45 @@
+#!/usr/bin/env bun
+import { chmod, mkdir, writeFile } from "node:fs/promises";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { commandNames } from "../src/coreutils.js";
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const targetDir = resolve(process.argv[2] ?? "dist/bin");
+const bnu = resolve(root, "bin/bnu.js");
+const bun = shellQuote(process.execPath);
+const bnuScript = shellQuote(bnu);
+
+await mkdir(targetDir, { recursive: true });
+
+for (const command of commandNames) {
+ const path = resolve(targetDir, command);
+ const script = command === "pwd"
+ ? `#!/bin/sh
+saved_pwd=$PWD
+actual_pwd=$(command pwd -P 2>/dev/null || :)
+test -n "$actual_pwd" && saved_pwd=$actual_pwd
+if [ \${#saved_pwd} -gt 4000 ]; then
+ cd / || exit 1
+ BNU_LONG_PWD=$saved_pwd PWD=$saved_pwd exec ${bun} ${bnuScript} pwd "$@"
+fi
+exec ${bun} ${bnuScript} pwd "$@"
+`
+ : command === "tail" || command === "tac" || command === "timeout"
+ ? `#!/bin/sh
+if [ ! -e /proc/$$/fd/0 ]; then
+ BNU_STDIN_CLOSED=1
+ export BNU_STDIN_CLOSED
+fi
+exec ${bun} ${bnuScript} ${command} "$@"
+`
+ : `#!/bin/sh\nexec ${bun} ${bnuScript} ${command} "$@"\n`;
+ await writeFile(path, script);
+ await chmod(path, 0o755);
+}
+
+console.log(`Linked ${commandNames.length} command wrappers into ${targetDir}`);
+
+function shellQuote(value) {
+ return `'${String(value).replaceAll("'", "'\\''")}'`;
+}
diff --git a/scripts/qemu/build-payload.sh b/scripts/qemu/build-payload.sh
new file mode 100755
index 0000000..a9ab1fd
--- /dev/null
+++ b/scripts/qemu/build-payload.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+# Build an unprivileged ext4 disk containing BNU, Bun, and the GNU tarball.
+
+set -Eeuo pipefail
+source "$(cd -- "$(dirname -- "$0")" && pwd)/common.sh"
+
+output=$BNU_QEMU_DIR/bnu-test-payload.ext4
+size=${BNU_QEMU_PAYLOAD_SIZE:-4G}
+while (($#)); do
+ case $1 in
+ --dry-run) BNU_QEMU_DRY_RUN=1 ;;
+ --output) [[ $# -ge 2 ]] || die "--output needs a path"; output=$2; shift ;;
+ --size) [[ $# -ge 2 ]] || die "--size needs a value"; size=$2; shift ;;
+ -h|--help)
+ printf 'usage: %s [--dry-run] [--output PATH] [--size 4G]\n' "$0"
+ exit 0
+ ;;
+ *) die "unknown argument: $1" ;;
+ esac
+ shift
+done
+
+for command in bun mkfs.ext4 truncate; do require_command "$command"; done
+ensure_state_dir
+[[ -r $BNU_REPO_ROOT/coreutils-9.11.tar.xz ]] || die "missing coreutils-9.11.tar.xz"
+bun_path=$(command -v bun)
+staging=$(mktemp -d "${TMPDIR:-/tmp}/bnu-payload.XXXXXX")
+cleanup() { rm -rf -- "$staging"; }
+trap cleanup EXIT HUP INT TERM
+
+run mkdir -p -- "$staging/bnu/repo" "$staging/bnu/bin" "$staging/bnu/artifacts"
+for entry in bin src scripts tests docs package.json README.md coreutils-9.11.tar.xz; do
+ [[ -e $BNU_REPO_ROOT/$entry ]] || continue
+ run cp -a -- "$BNU_REPO_ROOT/$entry" "$staging/bnu/repo/"
+done
+run cp -L -- "$bun_path" "$staging/bnu/bin/bun"
+selinux_stage=$BNU_QEMU_DIR/selinux/stage3-amd64-hardened-selinux-systemd.tar.xz
+if [[ -s $selinux_stage ]]; then
+ run cp -a -- "$selinux_stage" "$staging/bnu/artifacts/"
+fi
+if [[ $BNU_QEMU_DRY_RUN != 1 ]]; then
+ printf '%s\n' "$(git -C "$BNU_REPO_ROOT" rev-parse HEAD 2>/dev/null || printf unknown)" >"$staging/bnu/REVISION"
+fi
+
+run rm -f -- "$output.new"
+run truncate -s "$size" "$output.new"
+run mkfs.ext4 -q -F -L BNU_PAYLOAD -d "$staging" "$output.new"
+run mv -- "$output.new" "$output"
+note "payload ready: $output"
diff --git a/scripts/qemu/check-host.sh b/scripts/qemu/check-host.sh
new file mode 100755
index 0000000..8b0684d
--- /dev/null
+++ b/scripts/qemu/check-host.sh
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+# Report host-side prerequisites without changing anything.
+
+set -Eeuo pipefail
+source "$(cd -- "$(dirname -- "$0")" && pwd)/common.sh"
+
+missing=0
+for command in bash bun qemu-img qemu-system-x86_64 ssh scp ssh-keygen curl gpg \
+ mkfs.ext4 timeout awk sort comm sha512sum tar xz; do
+ if command -v "$command" >/dev/null 2>&1; then
+ printf 'ok %s\n' "$command"
+ else
+ printf 'missing %s\n' "$command"
+ missing=1
+ fi
+done
+if command -v xorriso >/dev/null 2>&1 || command -v genisoimage >/dev/null 2>&1; then
+ printf 'ok xorriso or genisoimage\n'
+else
+ printf 'missing xorriso or genisoimage\n'
+ missing=1
+fi
+if [[ -r /dev/kvm && -w /dev/kvm ]]; then
+ printf 'ok /dev/kvm (read/write)\n'
+else
+ printf 'missing /dev/kvm access (KVM group membership may require a new login)\n'
+ missing=1
+fi
+if code=$(find_ovmf code 2>/dev/null) && vars=$(find_ovmf vars 2>/dev/null); then
+ printf 'ok OVMF code: %s\n' "$code"
+ printf 'ok OVMF vars: %s\n' "$vars"
+else
+ printf 'missing OVMF firmware (or set BNU_OVMF_CODE and BNU_OVMF_VARS)\n'
+ missing=1
+fi
+exit "$missing"
diff --git a/scripts/qemu/common.sh b/scripts/qemu/common.sh
new file mode 100644
index 0000000..4c6cc70
--- /dev/null
+++ b/scripts/qemu/common.sh
@@ -0,0 +1,227 @@
+#!/usr/bin/env bash
+# Shared, host-distro-neutral helpers for the BNU Gentoo QEMU test matrix.
+
+set -Eeuo pipefail
+
+BNU_REPO_ROOT=${BNU_REPO_ROOT:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)}
+BNU_QEMU_DIR=${BNU_QEMU_DIR:-/var/tmp/bnu-qemu}
+BNU_QEMU_MEMORY=${BNU_QEMU_MEMORY:-1536M}
+BNU_QEMU_CPUS=${BNU_QEMU_CPUS:-2}
+BNU_QEMU_SSH_PORT=${BNU_QEMU_SSH_PORT:-22222}
+BNU_QEMU_TIMEOUT=${BNU_QEMU_TIMEOUT:-900}
+BNU_QEMU_DRY_RUN=${BNU_QEMU_DRY_RUN:-0}
+
+note() { printf 'bnu-qemu: %s\n' "$*" >&2; }
+die() { note "$*"; exit 2; }
+
+require_command() {
+ command -v "$1" >/dev/null 2>&1 || die "missing required command: $1"
+}
+
+run() {
+ if [[ $BNU_QEMU_DRY_RUN == 1 ]]; then
+ printf '+ ' >&2
+ printf '%q ' "$@" >&2
+ printf '\n' >&2
+ else
+ "$@"
+ fi
+}
+
+ensure_state_dir() {
+ if [[ $BNU_QEMU_DRY_RUN == 1 ]]; then
+ note "would create state directory $BNU_QEMU_DIR"
+ return
+ fi
+ mkdir -p -- "$BNU_QEMU_DIR" 2>/dev/null ||
+ die "cannot write $BNU_QEMU_DIR; create it for this user or set BNU_QEMU_DIR"
+ [[ -w $BNU_QEMU_DIR ]] || die "state directory is not writable: $BNU_QEMU_DIR"
+}
+
+require_free_gib() {
+ local required=$1 available_kib available_gib
+ available_kib=$(df -Pk "$BNU_QEMU_DIR" | awk 'NR == 2 {print $4}')
+ [[ $available_kib =~ ^[0-9]+$ ]] || die "could not determine free space below $BNU_QEMU_DIR"
+ available_gib=$((available_kib / 1024 / 1024))
+ (( available_gib >= required )) ||
+ die "$BNU_QEMU_DIR has ${available_gib} GiB free; this setup phase requires at least ${required} GiB free"
+}
+
+require_kvm() {
+ [[ -e /dev/kvm ]] || die "/dev/kvm is absent; this matrix intentionally has no software-emulation fallback"
+ [[ -r /dev/kvm && -w /dev/kvm ]] ||
+ die "/dev/kvm is not accessible; add this user to the host's KVM group and start a new login session"
+}
+
+find_ovmf() {
+ local kind=$1 candidate
+ local -a code=(
+ /usr/share/edk2/OvmfX64/OVMF_CODE.fd
+ /usr/share/OVMF/OVMF_CODE.fd
+ /usr/share/OVMF/OVMF_CODE_4M.fd
+ /usr/share/edk2-ovmf/x64/OVMF_CODE.fd
+ /usr/share/edk2/ovmf/OVMF_CODE.fd
+ /usr/share/edk2/x64/OVMF_CODE.fd
+ )
+ local -a vars=(
+ /usr/share/edk2/OvmfX64/OVMF_VARS.fd
+ /usr/share/OVMF/OVMF_VARS.fd
+ /usr/share/OVMF/OVMF_VARS_4M.fd
+ /usr/share/edk2-ovmf/x64/OVMF_VARS.fd
+ /usr/share/edk2/ovmf/OVMF_VARS.fd
+ /usr/share/edk2/x64/OVMF_VARS.fd
+ )
+ local -a candidates
+ if [[ $kind == code ]]; then candidates=("${code[@]}"); else candidates=("${vars[@]}"); fi
+ for candidate in "${candidates[@]}"; do
+ [[ -r $candidate ]] && { printf '%s\n' "$candidate"; return; }
+ done
+ die "could not find OVMF $kind firmware; set BNU_OVMF_CODE and BNU_OVMF_VARS explicitly"
+}
+
+ovmf_code() { printf '%s\n' "${BNU_OVMF_CODE:-$(find_ovmf code)}"; }
+ovmf_vars() { printf '%s\n' "${BNU_OVMF_VARS:-$(find_ovmf vars)}"; }
+
+download() {
+ local url=$1 output=$2
+ [[ -s $output ]] && { note "using cached $(basename -- "$output")"; return; }
+ run curl --fail --location --retry 4 --retry-delay 2 --continue-at - --output "$output.part" "$url"
+ run mv -- "$output.part" "$output"
+}
+
+prepare_gnupg() {
+ local gnupg=$1 bundle=$BNU_QEMU_DIR/gentoo-service-keys.gpg
+ run mkdir -p -- "$gnupg"
+ if [[ $BNU_QEMU_DRY_RUN != 1 ]]; then chmod 700 "$gnupg"; fi
+ download https://qa-reports.gentoo.org/output/service-keys.gpg "$bundle"
+ run gpg --batch --homedir "$gnupg" --import "$bundle"
+}
+
+verify_detached() {
+ local gnupg=$1 signature=$2 artifact=$3
+ run gpg --batch --homedir "$gnupg" --status-fd 1 --verify "$signature" "$artifact"
+}
+
+create_overlay() {
+ local base=$1 overlay=$2
+ [[ -s $overlay ]] && { note "using existing overlay $overlay"; return; }
+ run qemu-img create -q -f qcow2 -F qcow2 -b "$base" "$overlay"
+}
+
+ensure_ssh_key() {
+ BNU_QEMU_SSH_KEY=${BNU_QEMU_SSH_KEY:-$BNU_QEMU_DIR/id_ed25519}
+ if [[ ! -s $BNU_QEMU_SSH_KEY ]]; then
+ run ssh-keygen -q -t ed25519 -N '' -f "$BNU_QEMU_SSH_KEY"
+ fi
+ export BNU_QEMU_SSH_KEY
+}
+
+create_seed_iso() {
+ local output=$1 seed_dir
+ [[ -s $output ]] && return
+ ensure_ssh_key
+ seed_dir=$(mktemp -d "${TMPDIR:-/tmp}/bnu-seed.XXXXXX")
+ trap 'rm -rf -- "$seed_dir"' RETURN
+ if [[ $BNU_QEMU_DRY_RUN != 1 ]]; then
+ cat >"$seed_dir/meta-data" <<EOF
+instance-id: bnu-gentoo
+local-hostname: bnu-gentoo
+EOF
+ cat >"$seed_dir/user-data" <<EOF
+#cloud-config
+disable_root: false
+ssh_pwauth: false
+users:
+ - name: root
+ lock_passwd: true
+ shell: /bin/bash
+ ssh_authorized_keys:
+ - $(<"$BNU_QEMU_SSH_KEY.pub")
+runcmd:
+ - [ sh, -c, 'touch /var/lib/bnu-cloud-ready' ]
+EOF
+ fi
+ if command -v xorriso >/dev/null 2>&1; then
+ run xorriso -as mkisofs -quiet -output "$output" -volid cidata -joliet -rock \
+ "$seed_dir/user-data" "$seed_dir/meta-data"
+ elif command -v genisoimage >/dev/null 2>&1; then
+ run genisoimage -quiet -output "$output" -volid cidata -joliet -rock \
+ "$seed_dir/user-data" "$seed_dir/meta-data"
+ else
+ die "missing xorriso or genisoimage (needed for the NoCloud seed)"
+ fi
+ trap - RETURN
+ rm -rf -- "$seed_dir"
+}
+
+ssh_options() {
+ printf '%s\0' -i "$BNU_QEMU_SSH_KEY" -p "$BNU_QEMU_SSH_PORT" \
+ -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
+ -o ConnectTimeout=5 -o ServerAliveInterval=15 -o ServerAliveCountMax=4
+}
+
+guest_ssh() {
+ local -a options=()
+ while IFS= read -r -d '' item; do options+=("$item"); done < <(ssh_options)
+ ssh "${options[@]}" [email protected] "$@"
+}
+
+guest_scp() {
+ local -a options=()
+ while IFS= read -r -d '' item; do options+=("$item"); done < <(ssh_options)
+ scp "${options[@]/-p/-P}" "$@"
+}
+
+wait_for_ssh() {
+ local deadline=$((SECONDS + BNU_QEMU_TIMEOUT))
+ while (( SECONDS < deadline )); do
+ if guest_ssh 'test -e /var/lib/bnu-cloud-ready || test -e /var/lib/bnu-provisioned' >/dev/null 2>&1; then
+ return
+ fi
+ sleep 2
+ done
+ die "guest SSH did not become ready within ${BNU_QEMU_TIMEOUT}s"
+}
+
+start_vm() {
+ local image=$1 name=$2 payload=${3:-} seed=${4:-} extra_disk=${5:-}
+ local run_dir=$BNU_QEMU_DIR/run/$name vars pidfile serial
+ require_kvm
+ require_command qemu-system-x86_64
+ require_command qemu-img
+ ensure_ssh_key
+ run mkdir -p -- "$run_dir"
+ vars=$run_dir/OVMF_VARS.fd
+ pidfile=$run_dir/qemu.pid
+ serial=$run_dir/serial.log
+ if [[ $BNU_QEMU_DRY_RUN != 1 && -s $pidfile ]] && kill -0 "$(<"$pidfile")" 2>/dev/null; then
+ die "VM $name is already running (pid $(<"$pidfile"))"
+ fi
+ run cp -- "$(ovmf_vars)" "$vars"
+ local -a drives=(
+ -drive "if=pflash,format=raw,readonly=on,file=$(ovmf_code)"
+ -drive "if=pflash,format=raw,file=$vars"
+ -drive "if=virtio,format=qcow2,file=$image,cache=writeback,discard=unmap"
+ )
+ [[ -n $payload ]] && drives+=( -drive "if=virtio,format=raw,readonly=on,file=$payload" )
+ [[ -n $extra_disk ]] && drives+=( -drive "if=virtio,format=qcow2,file=$extra_disk,cache=writeback,discard=unmap" )
+ [[ -n $seed ]] && drives+=( -drive "media=cdrom,format=raw,readonly=on,file=$seed" )
+ run qemu-system-x86_64 \
+ -name "$name" -machine q35,accel=kvm -cpu host -smp "$BNU_QEMU_CPUS" -m "$BNU_QEMU_MEMORY" \
+ "${drives[@]}" -device virtio-net-pci,netdev=net0 \
+ -netdev "user,id=net0,hostfwd=tcp:127.0.0.1:${BNU_QEMU_SSH_PORT}-:22" \
+ -display none -serial "file:$serial" -monitor none -daemonize -pidfile "$pidfile"
+ [[ $BNU_QEMU_DRY_RUN == 1 ]] || wait_for_ssh
+}
+
+stop_vm() {
+ local name=$1 pidfile=$BNU_QEMU_DIR/run/$name/qemu.pid deadline
+ [[ -s $pidfile ]] || return
+ guest_ssh 'sync; systemctl poweroff || poweroff' >/dev/null 2>&1 || true
+ deadline=$((SECONDS + 60))
+ while kill -0 "$(<"$pidfile")" 2>/dev/null && (( SECONDS < deadline )); do sleep 1; done
+ if kill -0 "$(<"$pidfile")" 2>/dev/null; then
+ note "guest did not stop cleanly; terminating only QEMU pid $(<"$pidfile")"
+ kill -TERM "$(<"$pidfile")" 2>/dev/null || true
+ fi
+}
diff --git a/scripts/qemu/download-images.sh b/scripts/qemu/download-images.sh
new file mode 100755
index 0000000..26c1f36
--- /dev/null
+++ b/scripts/qemu/download-images.sh
@@ -0,0 +1,106 @@
+#!/usr/bin/env bash
+# Download and authenticate the official Gentoo images used by the matrix.
+
+set -Eeuo pipefail
+source "$(cd -- "$(dirname -- "$0")" && pwd)/common.sh"
+
+usage() {
+ cat <<'EOF'
+usage: scripts/qemu/download-images.sh [--dry-run] [--only NAME]
+
+NAME is cloud, selinux, hurd, or all (the default). Files are cached beneath
+BNU_QEMU_DIR, which defaults to /var/tmp/bnu-qemu.
+EOF
+}
+
+only=all
+while (($#)); do
+ case $1 in
+ --dry-run) BNU_QEMU_DRY_RUN=1 ;;
+ --only) [[ $# -ge 2 ]] || die "--only needs a value"; only=$2; shift ;;
+ -h|--help) usage; exit 0 ;;
+ *) die "unknown argument: $1" ;;
+ esac
+ shift
+done
+[[ $only =~ ^(all|cloud|selinux|hurd)$ ]] || die "--only must be cloud, selinux, hurd, or all"
+
+for command in curl gpg qemu-img; do require_command "$command"; done
+ensure_state_dir
+gnupg=$BNU_QEMU_DIR/gnupg
+prepare_gnupg "$gnupg"
+
+signed_manifest_path() {
+ local url=$1 pattern=$2 name=$3 path
+ local manifest=$BNU_QEMU_DIR/$name
+ local plain=$BNU_QEMU_DIR/$name.plain
+ download "$url" "$manifest"
+ if [[ $BNU_QEMU_DRY_RUN == 1 ]]; then
+ printf 'DRY-RUN/%s\n' "$pattern"
+ return
+ fi
+ gpg --batch --homedir "$gnupg" --output "$plain.tmp" --decrypt "$manifest"
+ mv -- "$plain.tmp" "$plain"
+ path=$(awk -v pattern="$pattern" '$1 !~ /^#/ && $1 ~ pattern { print $1; exit }' "$plain")
+ [[ -n $path ]] || die "no $pattern artifact found in $url"
+ printf '%s\n' "$path"
+}
+
+fetch_signed_artifact() {
+ local url=$1 output=$2
+ download "$url" "$output"
+ download "$url.asc" "$output.asc"
+ verify_detached "$gnupg" "$output.asc" "$output"
+}
+
+autobuilds=https://distfiles.gentoo.org/releases/amd64/autobuilds
+if [[ $only == all || $only == cloud ]]; then
+ run mkdir -p -- "$BNU_QEMU_DIR/cloud"
+ cloud_path=$(signed_manifest_path "$autobuilds/latest-qcow2.txt" 'di-amd64-cloudinit-.*\.qcow2$' latest-qcow2.txt)
+ cloud_output=$BNU_QEMU_DIR/cloud/gentoo-cloudinit-amd64.qcow2
+ fetch_signed_artifact "$autobuilds/$cloud_path" "$cloud_output"
+ if [[ $BNU_QEMU_DRY_RUN != 1 ]]; then printf '%s\n' "$cloud_path" >"$cloud_output.source"; fi
+fi
+
+if [[ $only == all || $only == selinux ]]; then
+ run mkdir -p -- "$BNU_QEMU_DIR/selinux"
+ selinux_path=$(signed_manifest_path \
+ "$autobuilds/latest-stage3-amd64-hardened-selinux-systemd.txt" \
+ 'stage3-amd64-hardened-selinux-systemd-.*\.tar\.xz$' \
+ latest-stage3-amd64-hardened-selinux-systemd.txt)
+ selinux_output=$BNU_QEMU_DIR/selinux/stage3-amd64-hardened-selinux-systemd.tar.xz
+ fetch_signed_artifact "$autobuilds/$selinux_path" "$selinux_output"
+ if [[ $BNU_QEMU_DRY_RUN != 1 ]]; then printf '%s\n' "$selinux_path" >"$selinux_output.source"; fi
+fi
+
+if [[ $only == all || $only == hurd ]]; then
+ run mkdir -p -- "$BNU_QEMU_DIR/hurd-gentoo-amd64"
+ hurd_base=https://distfiles.gentoo.org/experimental/amd64/hurd/hurd-x86_64-preview.qcow2
+ hurd_image=$BNU_QEMU_DIR/hurd-gentoo-amd64/hurd-x86_64-preview.qcow2
+ download "$hurd_base" "$hurd_image"
+ download "$hurd_base.sig" "$hurd_image.sig"
+ download "$hurd_base.sha512" "$hurd_image.sha512"
+ # The experimental Hurd preview is signed by its Gentoo developer rather
+ # than the automated release key. Fetch its key block over HTTPS from
+ # Gentoo's own keyserver and assert the exact signing-subkey fingerprint.
+ hurd_signer=FD19E6D31B192EE4DC63EAD3DC2B16215ED5412A
+ if [[ $BNU_QEMU_DRY_RUN == 1 ]] || ! gpg --batch --homedir "$gnupg" --list-keys "$hurd_signer" >/dev/null 2>&1; then
+ hurd_key=$BNU_QEMU_DIR/hurd-gentoo-amd64/signer-$hurd_signer.asc
+ download "https://keys.gentoo.org/pks/lookup?op=get&search=0x$hurd_signer" "$hurd_key"
+ run gpg --batch --homedir "$gnupg" --import "$hurd_key"
+ fi
+ if [[ $BNU_QEMU_DRY_RUN != 1 ]]; then
+ gpg --batch --homedir "$gnupg" --with-colons --fingerprint "$hurd_signer" |
+ awk -F: '$1 == "fpr" {print $10}' | grep -Fxq "$hurd_signer" ||
+ die "Gentoo Hurd signing-key fingerprint did not match $hurd_signer"
+ fi
+ verify_detached "$gnupg" "$hurd_image.sig" "$hurd_image"
+ if [[ $BNU_QEMU_DRY_RUN != 1 ]]; then
+ (cd -- "$(dirname -- "$hurd_image")" && sha512sum --check "$(basename -- "$hurd_image.sha512")")
+ else
+ note "would verify the Hurd SHA-512 manifest"
+ fi
+ create_overlay "$hurd_image" "$BNU_QEMU_DIR/hurd-gentoo-amd64/bnu-matrix-overlay.qcow2"
+fi
+
+note "verified Gentoo artifacts are in $BNU_QEMU_DIR"
diff --git a/scripts/qemu/guest/provision-base.sh b/scripts/qemu/guest/provision-base.sh
new file mode 100755
index 0000000..702f923
--- /dev/null
+++ b/scripts/qemu/guest/provision-base.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+set -Eeuo pipefail
+
+export MAKEOPTS=-j1
+export EMERGE_DEFAULT_OPTS='--jobs=1 --load-average=2 --nospinner'
+mkdir -p /etc/portage/package.use /etc/portage/package.accept_keywords
+grep -q '^MAKEOPTS=' /etc/portage/make.conf 2>/dev/null || printf '\nMAKEOPTS="-j1"\n' >>/etc/portage/make.conf
+grep -q '^EMERGE_DEFAULT_OPTS=' /etc/portage/make.conf 2>/dev/null ||
+ printf 'EMERGE_DEFAULT_OPTS="--jobs=1 --load-average=2 --nospinner"\n' >>/etc/portage/make.conf
+
+if [[ ${BNU_REFRESH_PORTAGE:-0} == 1 ]]; then emerge --sync; fi
+emerge --ask=n --verbose=n \
+ app-arch/xz-utils app-shells/bash dev-lang/perl dev-lang/python \
+ net-misc/openssh sys-apps/acl sys-apps/attr sys-apps/coreutils \
+ sys-apps/util-linux sys-block/parted sys-devel/binutils sys-devel/gcc \
+ sys-devel/make sys-fs/dosfstools sys-fs/e2fsprogs sys-fs/xfsprogs \
+ sys-libs/libcap sys-process/procps sys-process/psmisc
+
+if [[ ! -e /swapfile ]]; then
+ fallocate -l 2G /swapfile
+ chmod 600 /swapfile
+ mkswap /swapfile
+ printf '/swapfile none swap sw 0 0\n' >>/etc/fstab
+fi
+swapon /swapfile 2>/dev/null || true
+systemctl enable sshd 2>/dev/null || rc-update add sshd default 2>/dev/null || true
+touch /var/lib/bnu-provisioned
diff --git a/scripts/qemu/guest/provision-selinux.sh b/scripts/qemu/guest/provision-selinux.sh
new file mode 100755
index 0000000..5f79397
--- /dev/null
+++ b/scripts/qemu/guest/provision-selinux.sh
@@ -0,0 +1,79 @@
+#!/usr/bin/env bash
+# Run in the standard Gentoo builder. Payload=/dev/vdb, target=/dev/vdc.
+set -Eeuo pipefail
+
+target=/mnt/bnu-target
+payload=/mnt/bnu-payload
+mkdir -p "$target" "$payload"
+mount -o ro /dev/vdb "$payload"
+stage=$payload/bnu/artifacts/stage3-amd64-hardened-selinux-systemd.tar.xz
+[[ -r $stage ]] || { echo "SELinux stage3 is absent from payload" >&2; exit 2; }
+
+wipefs -a /dev/vdc
+parted -s /dev/vdc mklabel gpt
+parted -s /dev/vdc mkpart ESP fat32 1MiB 513MiB
+parted -s /dev/vdc set 1 esp on
+parted -s /dev/vdc mkpart gentoo xfs 513MiB 100%
+udevadm settle
+mkfs.vfat -F 32 -n EFI /dev/vdc1
+mkfs.xfs -f -L gentoo /dev/vdc2
+mount /dev/vdc2 "$target"
+mkdir -p "$target/boot/efi"
+mount /dev/vdc1 "$target/boot/efi"
+tar --numeric-owner --acls --xattrs --xattrs-include='*' --selinux -xpf "$stage" -C "$target"
+
+root_uuid=$(blkid -s UUID -o value /dev/vdc2)
+efi_uuid=$(blkid -s UUID -o value /dev/vdc1)
+cat >"$target/etc/fstab" <<EOF
+UUID=$root_uuid / xfs defaults 0 1
+UUID=$efi_uuid /boot/efi vfat umask=0077 0 2
+/swapfile none swap sw 0 0
+EOF
+cp -L /etc/resolv.conf "$target/etc/resolv.conf"
+cat >>"$target/etc/portage/make.conf" <<'EOF'
+MAKEOPTS="-j1"
+EMERGE_DEFAULT_OPTS="--jobs=1 --load-average=2 --nospinner"
+SELINUX_POLICY_TYPES="mcs mls strict"
+EOF
+mkdir -p "$target/etc/portage/package.use"
+cat >"$target/etc/portage/package.use/bnu-selinux" <<'EOF'
+sys-apps/systemd selinux
+sys-apps/coreutils acl caps xattr
+sys-process/procps selinux
+EOF
+cat >"$target/etc/selinux/config" <<'EOF'
+SELINUX=permissive
+SELINUXTYPE=mls
+EOF
+mkdir -p "$target/etc/systemd/network" "$target/root/.ssh"
+cat >"$target/etc/systemd/network/20-wired.network" <<'EOF'
+[Match]
+Name=en* eth*
+
+[Network]
+DHCP=yes
+EOF
+install -m 600 /dev/null "$target/root/.ssh/authorized_keys"
+cat /root/.ssh/authorized_keys >"$target/root/.ssh/authorized_keys"
+chmod 700 "$target/root/.ssh"
+
+for fs in dev proc sys run; do mount --rbind "/$fs" "$target/$fs"; mount --make-rslave "$target/$fs"; done
+chroot "$target" /usr/bin/env MAKEOPTS=-j1 EMERGE_DEFAULT_OPTS='--jobs=1 --load-average=2 --nospinner' \
+ emerge --ask=n --verbose=n net-misc/openssh net-misc/dhcpcd sec-policy/selinux-base \
+ sec-policy/selinux-base-policy sys-apps/policycoreutils sys-boot/grub:2 \
+ sys-fs/dosfstools sys-fs/xfsprogs sys-kernel/gentoo-kernel-bin
+
+cat >"$target/etc/default/grub" <<'EOF'
+GRUB_CMDLINE_LINUX="console=ttyS0 lsm=selinux security=selinux selinux=1 enforcing=0"
+GRUB_TERMINAL="serial console"
+GRUB_SERIAL_COMMAND="serial --speed=115200 --unit=0 --word=8 --parity=no --stop=1"
+EOF
+chroot "$target" systemctl enable sshd systemd-networkd systemd-resolved
+chroot "$target" grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=Gentoo --removable --no-nvram
+chroot "$target" grub-mkconfig -o /boot/grub/grub.cfg
+chroot "$target" semodule -B || true
+fallocate -l 2G "$target/swapfile"
+chmod 600 "$target/swapfile"
+mkswap "$target/swapfile"
+touch "$target/.autorelabel" "$target/var/lib/bnu-provisioned" "$target/var/lib/bnu-selinux-mls"
+sync
diff --git a/scripts/qemu/guest/provision-smack.sh b/scripts/qemu/guest/provision-smack.sh
new file mode 100755
index 0000000..4cbb5a2
--- /dev/null
+++ b/scripts/qemu/guest/provision-smack.sh
@@ -0,0 +1,33 @@
+#!/usr/bin/env bash
+# Run inside an overlay of the completed SELinux guest.
+set -Eeuo pipefail
+
+export MAKEOPTS=-j1
+export EMERGE_DEFAULT_OPTS='--jobs=1 --load-average=2 --nospinner'
+swapon /swapfile 2>/dev/null || true
+emerge --ask=n --verbose=n sys-apps/kmod sys-kernel/dracut sys-kernel/gentoo-sources
+eselect kernel set "$(eselect kernel list | awk '/gentoo/ {gsub(/\[|\]/, "", $1); n=$1} END {print n}')"
+kernel=/usr/src/linux
+cd "$kernel"
+if [[ -r /proc/config.gz ]]; then
+ zcat /proc/config.gz >.config
+else
+ cp "/boot/config-$(uname -r)" .config
+fi
+scripts/config --enable SECURITY --enable SECURITYFS --enable SECURITY_SMACK
+scripts/config --disable DEBUG_INFO_BTF --disable DEBUG_INFO_BTF_MODULES
+scripts/config --enable VIRTIO --enable VIRTIO_PCI --enable VIRTIO_BLK --enable VIRTIO_NET
+scripts/config --enable EXT4_FS --enable XFS_FS --enable VFAT_FS --enable ISO9660_FS
+scripts/config --set-str LOCALVERSION '-smack-bnu'
+make olddefconfig
+make -j1
+make -j1 modules_install
+version=$(make -s kernelrelease)
+cp arch/x86/boot/bzImage "/boot/vmlinuz-$version"
+cp .config "/boot/config-$version"
+cp System.map "/boot/System.map-$version"
+dracut --force "/boot/initramfs-$version.img" "$version"
+sed -i 's/lsm=selinux/security=smack lsm=smack/; s/security=selinux//; s/selinux=1//; s/enforcing=0//' /etc/default/grub
+grub-mkconfig -o /boot/grub/grub.cfg
+touch /var/lib/bnu-smack
+sync
diff --git a/scripts/qemu/guest/run-tests.sh b/scripts/qemu/guest/run-tests.sh
new file mode 100755
index 0000000..efbb26e
--- /dev/null
+++ b/scripts/qemu/guest/run-tests.sh
@@ -0,0 +1,41 @@
+#!/usr/bin/env bash
+set -Eeuo pipefail
+
+mode=${1:?mode is required}
+shift
+mountpoint=/mnt/bnu-payload
+work=/var/tmp/bnu-current
+mkdir -p "$mountpoint"
+mountpoint -q "$mountpoint" || mount -o ro LABEL=BNU_PAYLOAD "$mountpoint"
+rm -rf -- "$work"
+mkdir -p "$work"
+cp -a "$mountpoint/bnu/repo/." "$work/"
+install -m 755 "$mountpoint/bnu/bin/bun" "$work/bun"
+chmod -R a+rX "$work"
+
+common=(
+ "$work/bun" "$work/scripts/run-gnu-tests.js"
+ --tarball "$work/coreutils-9.11.tar.xz"
+ --very-expensive --timeout 300s --rss-limit 1024MiB --memory-limit 3GiB
+)
+case $mode in
+ nonroot)
+ mkdir -p /tmp/bnu-nobody
+ chown nobody:nogroup /tmp/bnu-nobody 2>/dev/null || chown nobody:nobody /tmp/bnu-nobody
+ exec runuser -u nobody -- env HOME=/tmp/bnu-nobody TMPDIR=/tmp/bnu-nobody \
+ "${common[@]}" --all --nonroot-tests "$@"
+ ;;
+ root)
+ exec env HOME=/root TMPDIR=/tmp "${common[@]}" --all --root-tests "$@"
+ ;;
+ selected-root)
+ exec env HOME=/root TMPDIR=/tmp "${common[@]}" "$@"
+ ;;
+ selected-nonroot)
+ mkdir -p /tmp/bnu-nobody
+ chown nobody:nogroup /tmp/bnu-nobody 2>/dev/null || chown nobody:nobody /tmp/bnu-nobody
+ exec runuser -u nobody -- env HOME=/tmp/bnu-nobody TMPDIR=/tmp/bnu-nobody \
+ "${common[@]}" "$@"
+ ;;
+ *) echo "unknown test mode: $mode" >&2; exit 2 ;;
+esac
diff --git a/scripts/run-all-tests.sh b/scripts/run-all-tests.sh
new file mode 100755
index 0000000..073a264
--- /dev/null
+++ b/scripts/run-all-tests.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Single sequential entry point for local unit tests and the GNU QEMU matrix.
+
+set -Eeuo pipefail
+root=$(cd -- "$(dirname -- "$0")/.." && pwd)
+dry=0
+for arg in "$@"; do [[ $arg == --dry-run ]] && dry=1; done
+
+if ((dry)); then
+ printf '+ bun %q\n' "$root/scripts/run-bun-tests-bounded.js" >&2
+else
+ bun "$root/scripts/run-bun-tests-bounded.js"
+fi
+exec "$root/scripts/run-gnu-qemu-matrix.sh" "$@"
diff --git a/scripts/run-bun-tests-bounded.js b/scripts/run-bun-tests-bounded.js
new file mode 100644
index 0000000..f3e5a03
--- /dev/null
+++ b/scripts/run-bun-tests-bounded.js
@@ -0,0 +1,48 @@
+#!/usr/bin/env bun
+import { readFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const testFile = join(root, "tests/coreutils.test.js");
+const source = await readFile(testFile, "utf8");
+const names = [...source.matchAll(/^test\("((?:[^"\\]|\\.)+)"/gm)].map((match) => JSON.parse(`"${match[1]}"`));
+if (names.length === 0) {
+ console.error("run-bun-tests-bounded: no tests found");
+ process.exit(2);
+}
+
+const failures = [];
+for (let index = 0; index < names.length; index++) {
+ const name = names[index];
+ console.log(`\nBOUNDED TEST ${index + 1}/${names.length}: ${name}`);
+ const exactPattern = `^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
+ const proc = Bun.spawn([
+ process.execPath,
+ join(root, "scripts/run-memory-bounded.js"),
+ "--rss-limit", process.env.BNU_TEST_RSS_LIMIT ?? "1GiB",
+ "--memory-limit", process.env.BNU_TEST_MEMORY_LIMIT ?? "3GiB",
+ "--",
+ process.execPath,
+ "test",
+ testFile,
+ "--test-name-pattern", exactPattern,
+ "--timeout", process.env.BNU_TEST_TIMEOUT ?? "300000",
+ "--max-concurrency", "1",
+ ], {
+ cwd: root,
+ env: { ...process.env, BNU_FACTOR_WORKERS: process.env.BNU_FACTOR_WORKERS ?? "1" },
+ stdin: "ignore",
+ stdout: "inherit",
+ stderr: "inherit",
+ });
+ const code = await proc.exited;
+ if (code !== 0) failures.push({ name, code });
+}
+
+if (failures.length) {
+ console.error(`\n${failures.length} bounded test process(es) failed:`);
+ for (const failure of failures) console.error(`- ${failure.name} (exit ${failure.code})`);
+ process.exit(1);
+}
+console.log(`\nAll ${names.length} bounded test processes passed.`);
diff --git a/scripts/run-gnu-qemu-matrix.sh b/scripts/run-gnu-qemu-matrix.sh
new file mode 100755
index 0000000..10a0fe2
--- /dev/null
+++ b/scripts/run-gnu-qemu-matrix.sh
@@ -0,0 +1,133 @@
+#!/usr/bin/env bash
+# Run and reconcile the complete GNU command-test inventory in Gentoo guests.
+
+set -Eeuo pipefail
+source "$(cd -- "$(dirname -- "$0")" && pwd)/qemu/common.sh"
+
+setup=0
+dry=0
+while (($#)); do
+ case $1 in
+ --setup) setup=1 ;;
+ --dry-run) dry=1; BNU_QEMU_DRY_RUN=1 ;;
+ -h|--help)
+ cat <<'EOF'
+usage: scripts/run-gnu-qemu-matrix.sh [--setup] [--dry-run]
+
+--setup creates or resumes all required Gentoo guests first. The matrix runs
+one KVM VM at a time with 1536 MiB RAM, saves logs, and accepts only the six
+documented Bun runtime/ABI boundaries as unresolved upstream tests.
+EOF
+ exit 0
+ ;;
+ *) die "unknown argument: $1" ;;
+ esac
+ shift
+done
+
+for command in bun qemu-img qemu-system-x86_64 ssh scp timeout awk sort comm; do require_command "$command"; done
+require_kvm
+ensure_state_dir
+if ((setup)); then
+ run env BNU_QEMU_DIR="$BNU_QEMU_DIR" BNU_QEMU_DRY_RUN="$BNU_QEMU_DRY_RUN" \
+ "$BNU_REPO_ROOT/scripts/setup-qemu-environments.sh"
+fi
+run env BNU_QEMU_DIR="$BNU_QEMU_DIR" BNU_QEMU_DRY_RUN="$BNU_QEMU_DRY_RUN" \
+ "$BNU_REPO_ROOT/scripts/qemu/build-payload.sh"
+
+standard=$BNU_QEMU_DIR/standard/gentoo-standard-bnu.qcow2
+selinux=$BNU_QEMU_DIR/selinux/gentoo-selinux-mls-bnu.qcow2
+smack=$BNU_QEMU_DIR/smack/gentoo-smack-bnu.qcow2
+hurd=$BNU_QEMU_DIR/hurd-gentoo-amd64/bnu-matrix-overlay.qcow2
+payload=$BNU_QEMU_DIR/bnu-test-payload.ext4
+for image in "$standard" "$selinux" "$smack" "$hurd"; do
+ [[ -s $image || $dry == 1 ]] || die "missing $image; rerun with --setup"
+done
+if ((dry)); then
+ note "would run: standard/nonroot, SELinux-MLS/root, SELinux policy supplements, SMACK supplements, Hurd boot probe"
+ note "would reconcile every upstream test against the six-entry boundary allowlist"
+ exit 0
+fi
+
+stamp=$(date -u +%Y%m%dT%H%M%SZ)
+logs=$BNU_QEMU_DIR/results/$stamp
+mkdir -p "$logs"
+runner=$BNU_REPO_ROOT/scripts/qemu/guest/run-tests.sh
+
+run_guest_batch() {
+ local image=$1 name=$2 mode=$3 log=$4
+ shift 4
+ local vm=matrix-$name
+ trap 'stop_vm "$vm"' EXIT HUP INT TERM
+ start_vm "$image" "$vm" "$payload"
+ set +e
+ guest_ssh "bash -s -- $(printf '%q ' "$mode" "$@")" <"$runner" 2>&1 | tee "$log"
+ local status=${PIPESTATUS[0]}
+ set -e
+ stop_vm "$vm"
+ trap - EXIT HUP INT TERM
+ # Per-batch failures are reconciled after platform-specific reruns.
+ printf 'batch-status=%s\n' "$status" >>"$log"
+}
+
+run_guest_batch "$standard" standard nonroot "$logs/standard-nonroot.log"
+run_guest_batch "$selinux" selinux-root root "$logs/selinux-root.log"
+run_guest_batch "$selinux" selinux-policy selected-root "$logs/selinux-policy.log" \
+ tests/chcon/chcon.sh tests/cp/cp-a-selinux.sh tests/id/setgid.sh \
+ tests/install/install-C-selinux.sh tests/install/install-Z-selinux.sh \
+ tests/ls/selinux.sh tests/mkdir/selinux.sh tests/misc/selinux.sh
+run_guest_batch "$smack" smack selected-root "$logs/smack-root.log" \
+ tests/id/smack.sh tests/mkdir/smack-root.sh
+run_guest_batch "$smack" smack-nobody selected-nonroot "$logs/smack-nobody.log" \
+ tests/mkdir/smack-no-root.sh
+
+# Bun has no GNU/Hurd executable, but boot the official amd64 image so this ABI
+# boundary is checked against the real target rather than inferred from Linux.
+hurd_serial=$logs/hurd-boot.log
+set +e
+timeout --kill-after=5s 90s qemu-system-x86_64 \
+ -name bnu-hurd-probe -machine pc,accel=kvm -cpu host -smp "$BNU_QEMU_CPUS" -m "$BNU_QEMU_MEMORY" \
+ -drive "if=ide,format=qcow2,snapshot=on,file=$hurd" \
+ -nographic -monitor none -net none >"$hurd_serial" 2>&1
+hurd_status=$?
+set -e
+printf 'qemu-status=%s\n' "$hurd_status" >>"$hurd_serial"
+[[ $hurd_status -eq 124 ]] || die "the Gentoo Hurd VM exited early with status $hurd_status; see $hurd_serial"
+grep -aq 'Gentoo GNU/Hurd' "$hurd_serial" ||
+ die "the Gentoo Hurd boot entry was not reached; see $hurd_serial"
+printf '%s\n' 'SKIP tests/id/gnu-zero-uids.sh - Bun provides no GNU/Hurd amd64 runtime' >>"$hurd_serial"
+
+inventory=$logs/inventory
+inventory_raw=$logs/inventory.raw
+passed=$logs/passed
+unresolved=$logs/unresolved
+allowed=$logs/allowed-boundaries
+bun "$BNU_REPO_ROOT/scripts/run-gnu-tests.js" --all --list >"$inventory_raw"
+sort -u "$inventory_raw" >"$inventory"
+cat >"$allowed" <<'EOF'
+tests/df/no-mtab-status-masked-proc.sh
+tests/id/gnu-zero-uids.sh
+tests/nproc/nproc-quota-systemd.sh
+tests/sort/sort-continue.sh
+tests/sort/sort-merge-fdlimit.sh
+tests/stat/stat-mount.sh
+EOF
+awk '/^PASS tests\// {print $2}' "$logs"/*.log | sort -u >"$passed"
+comm -23 "$inventory" "$passed" | sort -u >"$unresolved"
+unexpected=$logs/unexpected-unresolved
+comm -23 "$unresolved" "$allowed" >"$unexpected"
+count=$(wc -l <"$inventory")
+[[ $count -eq 733 ]] || die "expected 733 upstream command tests, found $count"
+if [[ -s $unexpected ]]; then
+ note "unexpected unresolved tests:"
+ sed 's/^/ /' "$unexpected" >&2
+ die "matrix did not reconcile; logs are in $logs"
+fi
+missing_boundaries=$logs/missing-boundaries
+comm -23 "$allowed" "$unresolved" >"$missing_boundaries"
+if [[ -s $missing_boundaries ]]; then
+ note "documented boundaries that unexpectedly passed:"
+ sed 's/^/ /' "$missing_boundaries" >&2
+fi
+note "matrix reconciled all $count tests; only documented Bun boundaries remain"
+note "logs: $logs"
diff --git a/scripts/run-gnu-tests.js b/scripts/run-gnu-tests.js
new file mode 100644
index 0000000..fd1bccc
--- /dev/null
+++ b/scripts/run-gnu-tests.js
@@ -0,0 +1,1732 @@
+#!/usr/bin/env bun
+import { access, chmod, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { commandNames } from "../src/coreutils.js";
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const args = process.argv.slice(2);
+const keep = takeFlag("--keep");
+const list = takeFlag("--list");
+const strict = takeFlag("--strict");
+const all = takeFlag("--all");
+const expensive = takeFlag("--expensive");
+const veryExpensive = takeFlag("--very-expensive");
+const tty = takeFlag("--tty");
+const rootTestsOnly = takeFlag("--root-tests");
+const nonRootTestsOnly = takeFlag("--nonroot-tests");
+takeFlag("--quick");
+takeFlag("--default");
+if (rootTestsOnly && nonRootTestsOnly) {
+ throw new Error("--root-tests and --nonroot-tests are mutually exclusive");
+}
+const DEFAULT_TIMEOUT = "300s";
+const timeout = takeValue("--timeout") ?? DEFAULT_TIMEOUT;
+const maxOutputBytes = parseByteSize(takeValue("--max-output") ?? "1MiB");
+// prlimit's address-space ceiling is per process, so a test that fans out can
+// still consume much more physical memory in aggregate. Watch the complete
+// test process tree as a second line of defence and terminate only that tree
+// before it can put the host under memory pressure.
+const rssLimitBytes = parseByteSize(takeValue("--rss-limit") ?? "1536MiB");
+// Keep a pathological JS heap from threatening the host. Tests may lower
+// this inherited ceiling with ulimit, but cannot raise it.
+// JSC reserves more than 2 GiB of virtual address space for some otherwise
+// ~120 MiB workloads. Three GiB keeps those valid tests runnable while still
+// preventing the unbounded 11 GiB heap growth that motivated this guard.
+const memoryLimitBytes = parseByteSize(takeValue("--memory-limit") ?? "3GiB");
+const tarball = takeValue("--tarball") ?? join(root, "coreutils-9.11.tar.xz");
+const work = await mkdtemp(join(tmpdir(), "bnu-gnu-tests-"));
+// Root-only GNU tests deliberately drop to an unprivileged account. mkdtemp
+// creates this extraction parent as 0700, which otherwise makes every BNU
+// wrapper beneath it unreachable after the credential transition.
+await chmod(work, 0o755);
+const source = join(work, "coreutils-9.11");
+const TTY_TESTS = new Set([
+ "tests/misc/tty-eof.pl",
+ "tests/stty/bad-speed.sh",
+ "tests/stty/stty-invalid.sh",
+ "tests/stty/stty-pairs.sh",
+ "tests/stty/stty-row-col.sh",
+ "tests/stty/stty.sh",
+]);
+const DEFAULT_TESTS = [
+ "tests/misc/false-status.sh",
+ "tests/misc/printenv.sh",
+ "tests/misc/pathchk.sh",
+ "tests/misc/echo.sh",
+ "tests/misc/invalid-opt.pl",
+ "tests/help/help-version.sh",
+ "tests/help/help-version-getopt.sh",
+ "tests/misc/basename.pl",
+ "tests/misc/dirname.pl",
+ "tests/misc/user.sh",
+ "tests/env/env.sh",
+ "tests/env/env-S.pl",
+ "tests/env/env-S-script.sh",
+ "tests/env/env-null.sh",
+ "tests/env/env-signal-handler.sh",
+ "tests/basenc/basenc.pl",
+ "tests/basenc/base64.pl",
+ "tests/basenc/large-input.sh",
+ "tests/basenc/bounded-memory.sh",
+ "tests/cat/cat-E.sh",
+ "tests/cat/cat-buf.sh",
+ "tests/cat/cat-self.sh",
+ "tests/cat/cat-proc.sh",
+ "tests/cat/splice.sh",
+ "tests/wc/wc.pl",
+ "tests/wc/wc-cpu.sh",
+ "tests/wc/wc-total.sh",
+ "tests/wc/wc-files0.sh",
+ "tests/wc/wc-files0-from.pl",
+ "tests/wc/wc-nbsp.sh",
+ "tests/wc/wc-parallel.sh",
+ "tests/wc/wc-proc.sh",
+ "tests/id/uid.sh",
+ "tests/id/zero.sh",
+ "tests/id/context.sh",
+ "tests/id/no-context.sh",
+ "tests/groups/groups-version.sh",
+ "tests/groups/groups-dash.sh",
+ "tests/groups/groups-process-all.sh",
+ "tests/nproc/nproc-positive.sh",
+ "tests/nproc/nproc-avail.sh",
+ "tests/nproc/nproc-override.sh",
+ "tests/nproc/nproc-quota.sh",
+ "tests/tty/tty.sh",
+ "tests/stty/bad-speed.sh",
+ "tests/stty/stty-invalid.sh",
+ "tests/stty/stty-row-col.sh",
+ "tests/stty/stty.sh",
+ "tests/head/head-c.sh",
+ "tests/head/head-elide-tail.pl",
+ "tests/head/head-write-error.sh",
+ "tests/head/head.pl",
+ "tests/join/join.pl",
+ "tests/join/join-utf8.sh",
+ "tests/misc/comm.pl",
+ "tests/misc/io-errors.sh",
+ "tests/misc/tty-eof.pl",
+ "tests/misc/xstrtol.pl",
+ "tests/cksum/cksum.sh",
+ "tests/cksum/cksum-a.sh",
+ "tests/cksum/cksum-c.sh",
+ "tests/cksum/cksum-base64.pl",
+ "tests/cksum/cksum-base64-untagged.sh",
+ "tests/cksum/cksum-raw.sh",
+ "tests/cksum/sum.pl",
+ "tests/cksum/sum-sysv.sh",
+ "tests/cksum/b2sum.sh",
+ "tests/cksum/md5sum.pl",
+ "tests/cksum/md5sum-bsd.sh",
+ "tests/cksum/md5sum-newline.pl",
+ "tests/cksum/md5sum-parallel.sh",
+ "tests/cksum/sha1sum.pl",
+ "tests/cksum/sha1sum-vec.pl",
+ "tests/cksum/sha224sum.pl",
+ "tests/cksum/sha256sum.pl",
+ "tests/cksum/sha384sum.pl",
+ "tests/cksum/sha512sum.pl",
+ "tests/cksum/cksum-sha3.sh",
+ "tests/cksum/sm3sum.pl",
+ "tests/expr/expr.pl",
+ "tests/expr/expr-multibyte.pl",
+ "tests/test/test-file.sh",
+ "tests/test/test.pl",
+ "tests/test/test-diag.pl",
+ "tests/test/test-N.sh",
+ "tests/seq/seq-io-errors.sh",
+ "tests/seq/seq.pl",
+ "tests/seq/seq-extra-number.sh",
+ "tests/seq/seq-epipe.sh",
+ "tests/seq/seq-locale.sh",
+ "tests/seq/seq-long-double.sh",
+ "tests/seq/seq-precision.sh",
+ "tests/pwd/pwd-option.sh",
+ "tests/pwd/argument.sh",
+ "tests/pwd/pwd-long.sh",
+ "tests/readlink/can-e.sh",
+ "tests/readlink/can-f.sh",
+ "tests/readlink/can-m.sh",
+ "tests/readlink/multi.sh",
+ "tests/readlink/readlink-fp-loop.sh",
+ "tests/readlink/readlink-posix.sh",
+ "tests/readlink/readlink-root.sh",
+ "tests/readlink/rl-1.sh",
+ "tests/misc/realpath.sh",
+ "tests/mktemp/mktemp-misc.sh",
+ "tests/mktemp/mktemp.pl",
+ "tests/mktemp/bad-unicode.sh",
+ "tests/mktemp/write-error.sh",
+ "tests/date/date-debug.sh",
+ "tests/date/date.pl",
+ "tests/date/date-ethiopia.sh",
+ "tests/date/date-iran.sh",
+ "tests/date/date-locale-hour.sh",
+ "tests/date/date-next-dow.pl",
+ "tests/date/percent-percent.sh",
+ "tests/date/reference.sh",
+ "tests/date/resolution.sh",
+ "tests/date/date-sec.sh",
+ "tests/date/date-thailand.sh",
+ "tests/date/date-tz.sh",
+ "tests/truncate/truncate-overflow.sh",
+ "tests/truncate/multiple-files.sh",
+ "tests/truncate/truncate-dangling-symlink.sh",
+ "tests/truncate/truncate-dir-fail.sh",
+ "tests/truncate/truncate-fail-diag.sh",
+ "tests/truncate/truncate-fifo.sh",
+ "tests/truncate/truncate-no-create-missing.sh",
+ "tests/truncate/truncate-parameters.sh",
+ "tests/truncate/truncate-relative.sh",
+ "tests/truncate/truncate-owned-by-other.sh",
+ "tests/tee/append.sh",
+ "tests/tee/tee.sh",
+ "tests/uniq/uniq.pl",
+ "tests/uniq/uniq-perf.sh",
+ "tests/uniq/uniq-collate.sh",
+ "tests/tr/tr.pl",
+ "tests/tr/tr-case-class.sh",
+ "tests/tac/tac.pl",
+ "tests/tac/tac-2-nonseekable.sh",
+ "tests/tac/tac-continue.sh",
+ "tests/tac/tac-locale.sh",
+ "tests/cut/cut.pl",
+ "tests/cut/mb-non-utf8.sh",
+ "tests/cut/bounded-memory.sh",
+ "tests/cut/cut-huge-range.sh",
+ "tests/touch/empty-file.sh",
+ "tests/touch/60-seconds.sh",
+ "tests/touch/dangling-symlink.sh",
+ "tests/touch/dir-1.sh",
+ "tests/touch/fifo.sh",
+ "tests/touch/no-dereference.sh",
+ "tests/touch/no-create-missing.sh",
+ "tests/touch/no-rights.sh",
+ "tests/touch/not-owner.sh",
+ "tests/touch/now-owned-by-other.sh",
+ "tests/touch/obsolescent.sh",
+ "tests/touch/fail-diag.sh",
+ "tests/touch/read-only.sh",
+ "tests/touch/relative.sh",
+ "tests/touch/trailing-slash.sh",
+ "tests/df/total-verify.sh",
+ "tests/df/df-P.sh",
+ "tests/df/df-output.sh",
+ "tests/df/df-symlink.sh",
+ "tests/df/over-mount-device.sh",
+ "tests/df/problematic-chars.sh",
+ "tests/df/total-unprocessed.sh",
+ "tests/df/header.sh",
+ "tests/df/unreadable.sh",
+ "tests/df/sync.sh",
+ "tests/du/exclude.sh",
+ "tests/du/basic.sh",
+ "tests/du/apparent.sh",
+ "tests/du/deref.sh",
+ "tests/du/deref-args.sh",
+ "tests/du/files0-from.pl",
+ "tests/du/files0-from-dir.sh",
+ "tests/du/hard-link.sh",
+ "tests/du/inodes.sh",
+ "tests/du/max-depth.sh",
+ "tests/du/no-deref.sh",
+ "tests/du/slash.sh",
+ "tests/du/trailing-slash.sh",
+ "tests/du/two-args.sh",
+ "tests/du/inacc-dest.sh",
+ "tests/du/inacc-dir.sh",
+ "tests/du/inaccessible-cwd.sh",
+ "tests/du/long-from-unreadable.sh",
+ "tests/du/long-sloop.sh",
+ "tests/du/no-x.sh",
+ "tests/du/one-file-system.sh",
+ "tests/du/restore-wd.sh",
+ "tests/du/bind-mount-dir-cycle-v2.sh",
+ "tests/du/bind-mount-dir-cycle.sh",
+ "tests/du/move-dir-while-traversing.sh",
+ "tests/du/threshold.sh",
+ "tests/cp/same-file.sh",
+ "tests/cp/link.sh",
+ "tests/cp/backup-1.sh",
+ "tests/cp/backup-dir.sh",
+ "tests/cp/backup-is-src.sh",
+ "tests/cp/abuse.sh",
+ "tests/cp/acl.sh",
+ "tests/cp/capability.sh",
+ "tests/cp/attr-existing.sh",
+ "tests/cp/cp-a-selinux.sh",
+ "tests/cp/no-ctx.sh",
+ "tests/cp/cp-HL.sh",
+ "tests/cp/cp-deref.sh",
+ "tests/cp/cp-i.sh",
+ "tests/cp/cp-mv-backup.sh",
+ "tests/cp/cp-mv-enotsup-xattr.sh",
+ "tests/cp/cross-dev-symlink.sh",
+ "tests/cp/deref-slink.sh",
+ "tests/cp/debug.sh",
+ "tests/cp/dir-rm-dest.sh",
+ "tests/cp/dir-slash.sh",
+ "tests/cp/dir-vs-file.sh",
+ "tests/cp/existing-perm-dir.sh",
+ "tests/cp/existing-perm-race.sh",
+ "tests/cp/cp-parents.sh",
+ "tests/cp/fail-perm.sh",
+ "tests/cp/into-self.sh",
+ "tests/cp/keep-directory-symlink.sh",
+ "tests/cp/link-deref.sh",
+ "tests/cp/link-no-deref.sh",
+ "tests/cp/link-preserve.sh",
+ "tests/cp/link-symlink.sh",
+ "tests/cp/file-perm-race.sh",
+ "tests/cp/no-deref-link1.sh",
+ "tests/cp/no-deref-link2.sh",
+ "tests/cp/no-deref-link3.sh",
+ "tests/cp/non-utf8-name.sh",
+ "tests/cp/nfs-removal-race.sh",
+ "tests/cp/parent-perm.sh",
+ "tests/cp/parent-perm-race.sh",
+ "tests/cp/preserve-2.sh",
+ "tests/cp/preserve-link.sh",
+ "tests/cp/preserve-mode.sh",
+ "tests/cp/preserve-gid.sh",
+ "tests/cp/preserve-slink-time.sh",
+ "tests/cp/proc-short-read.sh",
+ "tests/cp/proc-zero-len.sh",
+ "tests/cp/r-vs-symlink.sh",
+ "tests/cp/readonly-dir.sh",
+ "tests/cp/reflink-auto.sh",
+ "tests/cp/reflink-perm.sh",
+ "tests/cp/slink-2-slink.sh",
+ "tests/cp/sparse.sh",
+ "tests/cp/sparse-2.sh",
+ "tests/cp/sparse-extents.sh",
+ "tests/cp/sparse-extents-2.sh",
+ "tests/cp/sparse-perf.sh",
+ "tests/cp/sparse-to-pipe.sh",
+ "tests/cp/special-bits.sh",
+ "tests/cp/special-f.sh",
+ "tests/cp/src-base-dot.sh",
+ "tests/cp/symlink-slash.sh",
+ "tests/cp/thru-dangling.sh",
+ "tests/mv/acl.sh",
+ "tests/mv/update.sh",
+ "tests/mv/i-1.pl",
+ "tests/mv/i-2.sh",
+ "tests/mv/i-3.sh",
+ "tests/mv/i-4.sh",
+ "tests/mv/i-5.sh",
+ "tests/mv/backup-is-src.sh",
+ "tests/mv/childproof.sh",
+ "tests/mv/no-copy.sh",
+ "tests/mv/into-self.sh",
+ "tests/mv/into-self-2.sh",
+ "tests/mv/into-self-3.sh",
+ "tests/mv/into-self-4.sh",
+ "tests/mv/no-target-dir.sh",
+ "tests/mv/backup-dir.sh",
+ "tests/mv/dir2dir.sh",
+ "tests/mv/dup-source.sh",
+ "tests/mv/diag.sh",
+ "tests/mv/dir-file.sh",
+ "tests/mv/force.sh",
+ "tests/mv/hard-link-1.sh",
+ "tests/mv/hard-2.sh",
+ "tests/mv/hard-3.sh",
+ "tests/mv/hard-4.sh",
+ "tests/mv/hardlink-case.sh",
+ "tests/mv/i-link-no.sh",
+ "tests/mv/mv-exchange.sh",
+ "tests/mv/mv-special-1.sh",
+ "tests/mv/mv-special-2.sh",
+ "tests/mv/meta-to-xpart.sh",
+ "tests/mv/sticky-to-xpart.sh",
+ "tests/mv/mv-n.sh",
+ "tests/mv/part-fail.sh",
+ "tests/mv/part-hardlink.sh",
+ "tests/mv/part-rename.sh",
+ "tests/mv/part-symlink.sh",
+ "tests/mv/partition-perm.sh",
+ "tests/mv/perm-1.sh",
+ "tests/mv/symlink-onto-hardlink.sh",
+ "tests/mv/symlink-onto-hardlink-to-self.sh",
+ "tests/mv/to-symlink.sh",
+ "tests/mv/trailing-slash.sh",
+ "tests/mv/atomic.sh",
+ "tests/mv/atomic2.sh",
+ "tests/ln/backup-1.sh",
+ "tests/ln/backup-suffix-traversal.sh",
+ "tests/ln/hard-backup.sh",
+ "tests/ln/hard-to-sym.sh",
+ "tests/ln/misc.sh",
+ "tests/ln/non-utf8-src.sh",
+ "tests/ln/relative.sh",
+ "tests/ln/slash-decorated-nonexistent-dest.sh",
+ "tests/ln/sf-1.sh",
+ "tests/ln/target-1.sh",
+ "tests/rm/dangling-symlink.sh",
+ "tests/rm/d-1.sh",
+ "tests/rm/d-2.sh",
+ "tests/rm/d-3.sh",
+ "tests/rm/dash-hint.sh",
+ "tests/rm/dir-nonrecur.sh",
+ "tests/rm/f-1.sh",
+ "tests/rm/i-never.sh",
+ "tests/rm/i-no-r.sh",
+ "tests/rm/ignorable.sh",
+ "tests/rm/dot-rel.sh",
+ "tests/rm/empty-name.pl",
+ "tests/rm/fail-eacces.sh",
+ "tests/rm/r-1.sh",
+ "tests/rm/r-2.sh",
+ "tests/rm/r-3.sh",
+ "tests/rm/r-4.sh",
+ "tests/rm/rm1.sh",
+ "tests/rm/rm2.sh",
+ "tests/rm/rm3.sh",
+ "tests/rm/rm4.sh",
+ "tests/rm/rm5.sh",
+ "tests/rm/v-slash.sh",
+ "tests/rm/deep-1.sh",
+ "tests/rm/deep-2.sh",
+ "tests/rm/dir-no-w.sh",
+ "tests/rm/empty-inacc.sh",
+ "tests/rm/cycle.sh",
+ "tests/rm/i-1.sh",
+ "tests/rm/isatty.sh",
+ "tests/rm/inaccessible.sh",
+ "tests/rm/interactive-always.sh",
+ "tests/rm/interactive-once.sh",
+ "tests/rm/ir-1.sh",
+ "tests/rm/one-file-system2.sh",
+ "tests/rm/readdir-bug.sh",
+ "tests/rm/rm-readdir-fail.sh",
+ "tests/rm/empty-immutable-skip.sh",
+ "tests/rm/fail-2eperm.sh",
+ "tests/rm/no-give-up.sh",
+ "tests/rm/one-file-system.sh",
+ "tests/rm/read-only.sh",
+ "tests/rm/sunos-1.sh",
+ "tests/rm/unread2.sh",
+ "tests/rm/unread3.sh",
+ "tests/rm/unreadable.pl",
+ "tests/rmdir/ignore.sh",
+ "tests/rmdir/fail-perm.sh",
+ "tests/rmdir/symlink-errors.sh",
+ "tests/rmdir/t-slash.sh",
+ "tests/od/od-N.sh",
+ "tests/od/od.pl",
+ "tests/od/od-j.sh",
+ "tests/od/od-multiple-t.sh",
+ "tests/od/od-endian.sh",
+ "tests/od/od-float.sh",
+ "tests/od/od-x8.sh",
+ "tests/stat/stat-fmt.sh",
+ "tests/stat/stat-printf.pl",
+ "tests/stat/stat-birthtime.sh",
+ "tests/stat/stat-hyphen.sh",
+ "tests/stat/stat-nanoseconds.sh",
+ "tests/stat/stat-slash.sh",
+ "tests/chown/basic.sh",
+ "tests/chown/deref.sh",
+ "tests/chown/separator.sh",
+ "tests/chown/preserve-root.sh",
+ "tests/chgrp/basic.sh",
+ "tests/chgrp/default-no-deref.sh",
+ "tests/chgrp/deref.sh",
+ "tests/chgrp/from.sh",
+ "tests/chgrp/no-x.sh",
+ "tests/chgrp/posix-H.sh",
+ "tests/chgrp/recurse.sh",
+ "tests/chroot/chroot-fail.sh",
+ "tests/chroot/chroot-credentials.sh",
+ "tests/install/install-C.sh",
+ "tests/install/install-C-root.sh",
+ "tests/install/install-C-selinux.sh",
+ "tests/install/install-Z-selinux.sh",
+ "tests/install/basic-1.sh",
+ "tests/install/create-leading.sh",
+ "tests/install/d-slashdot.sh",
+ "tests/install/trap.sh",
+ "tests/install/strip-program.sh",
+ "tests/misc/dircolors.pl",
+ "tests/misc/arch.sh",
+ "tests/chcon/chcon-fail.sh",
+ "tests/misc/coreutils.sh",
+ "tests/misc/mknod.sh",
+ "tests/misc/option-aliases.sh",
+ "tests/pr/pr-tests.pl",
+ "tests/pr/bounded-memory.sh",
+ "tests/ptx/ptx.pl",
+ "tests/ptx/ptx-overrun.sh",
+ "tests/paste/paste.pl",
+ "tests/paste/multi-byte.sh",
+ "tests/expand/expand.pl",
+ "tests/expand/mb.sh",
+ "tests/expand/bounded-memory.sh",
+ "tests/unexpand/unexpand.pl",
+ "tests/unexpand/mb.sh",
+ "tests/unexpand/bounded-memory.sh",
+ "tests/fold/fold.pl",
+ "tests/fold/fold-nbsp.sh",
+ "tests/fold/fold-spaces.sh",
+ "tests/fold/fold-characters.sh",
+ "tests/fold/fold-zero-width.sh",
+ "tests/printf/printf.sh",
+ "tests/printf/printf-hex.sh",
+ "tests/printf/printf-cov.pl",
+ "tests/printf/printf-indexed.sh",
+ "tests/printf/printf-mb.sh",
+ "tests/printf/printf-quote.sh",
+ "tests/printf/printf-surprise.sh",
+ "tests/nl/nl.sh",
+ "tests/nl/multiple-files.sh",
+ "tests/nl/multibyte.sh",
+ "tests/numfmt/numfmt.pl",
+ "tests/numfmt/mb-non-utf8.sh",
+ "tests/shuf/shuf.sh",
+ "tests/fmt/base.pl",
+ "tests/fmt/goal-option.sh",
+ "tests/fmt/long-line.sh",
+ "tests/fmt/non-space.sh",
+ "tests/fmt/width.sh",
+ "tests/head/head-pos.sh",
+ "tests/tail/tail-c.sh",
+ "tests/tail/tail.pl",
+ "tests/tail/basic-seek.sh",
+ "tests/tail/F-headers.sh",
+ "tests/tail/F-vs-missing.sh",
+ "tests/tail/F-vs-rename.sh",
+ "tests/tail/descriptor-vs-rename.sh",
+ "tests/tail/start-middle.sh",
+ "tests/tail/tail-n0f.sh",
+ "tests/tail/truncate.sh",
+ "tests/tail/overlay-headers.sh",
+ "tests/tail/flush-initial.sh",
+ "tests/tail/retry.sh",
+ "tests/tail/symlink.sh",
+ "tests/tail/wait.sh",
+ "tests/tail/assert.sh",
+ "tests/tail/assert-2.sh",
+ "tests/tail/follow-name.sh",
+ "tests/tail/inotify-dir-recreate.sh",
+ "tests/tail/follow-stdin.sh",
+ "tests/tail/pid.sh",
+ "tests/tail/pid-pipe.sh",
+ "tests/tail/pipe-f.sh",
+ "tests/tail/pipe-f2.sh",
+ "tests/tail/proc-ksyms.sh",
+ "tests/tail/tail-sysfs.sh",
+ "tests/tail/append-only.sh",
+ "tests/tail/debug.sh",
+ "tests/tail/end-of-device.sh",
+ "tests/tail/inotify-only-regular.sh",
+ "tests/tail/inotify-rotate-resources.sh",
+ "tests/split/filter.sh",
+ "tests/split/suffix-length.sh",
+ "tests/split/suffix-auto-length.sh",
+ "tests/split/additional-suffix.sh",
+ "tests/split/b-chunk.sh",
+ "tests/split/l-chunk.sh",
+ "tests/split/l-chunk-root.sh",
+ "tests/split/r-chunk.sh",
+ "tests/split/numeric.sh",
+ "tests/split/record-sep.sh",
+ "tests/split/split-io-err.sh",
+ "tests/split/fail.sh",
+ "tests/split/guard-input.sh",
+ "tests/split/non-utf8.sh",
+ "tests/split/line-bytes.sh",
+ "tests/csplit/csplit.sh",
+ "tests/csplit/csplit-1000.sh",
+ "tests/csplit/csplit-suppress-matched.pl",
+ "tests/csplit/csplit-io-err.sh",
+ "tests/shred/shred-exact.sh",
+ "tests/shred/shred-passes.sh",
+ "tests/shred/shred-remove.sh",
+ "tests/shred/shred-size.sh",
+ "tests/dd/misc.sh",
+ "tests/dd/bytes.sh",
+ "tests/dd/conv-case.sh",
+ "tests/dd/stderr.sh",
+ "tests/dd/stats.sh",
+ "tests/dd/ascii.sh",
+ "tests/dd/reblock.sh",
+ "tests/dd/unblock.pl",
+ "tests/dd/unblock-sync.sh",
+ "tests/dd/skip-seek.pl",
+ "tests/dd/skip-seek2.sh",
+ "tests/dd/sparse.sh",
+ "tests/dd/not-rewound.sh",
+ "tests/dd/direct.sh",
+ "tests/dd/nocache.sh",
+ "tests/dd/nocache_eof.sh",
+ "tests/dd/nocache_fail.sh",
+ "tests/dd/fail-ftruncate-fstat.sh",
+ "tests/dd/partial-write.sh",
+ "tests/dd/skip-seek-past-file.sh",
+ "tests/dd/skip-seek-past-dev.sh",
+ "tests/sort/sort.pl",
+ "tests/sort/sort-locale.sh",
+ "tests/sort/sort-debug-warn.sh",
+ "tests/sort/sort-debug-keys.sh",
+ "tests/sort/sort-discrim.sh",
+ "tests/sort/sort-field-limit.sh",
+ "tests/sort/sort-exit-early.sh",
+ "tests/sort/sort-rand.sh",
+ "tests/sort/sort-h-thousands-sep.sh",
+ "tests/sort/sort-compress.sh",
+ "tests/sort/sort-files0-from.pl",
+ "tests/sort/sort-float.sh",
+ "tests/sort/sort-merge.pl",
+ "tests/sort/sort-month.sh",
+ "tests/sort/sort-NaN-infloop.sh",
+ "tests/sort/sort-unique.sh",
+ "tests/sort/sort-version.sh",
+ "tests/timeout/init-parent.sh",
+ "tests/timeout/timeout-blocked.pl",
+ "tests/timeout/timeout-parameters.sh",
+ "tests/timeout/timeout.sh",
+ "tests/timeout/timeout-large-parameters.sh",
+ "tests/timeout/timeout-group.sh",
+ "tests/runcon/runcon-compute.sh",
+ "tests/runcon/runcon-no-reorder.sh",
+ "tests/misc/nohup.sh",
+ "tests/nice/nice-fail.sh",
+ "tests/nice/nice.sh",
+ "tests/misc/stdbuf.sh",
+ "tests/misc/sync.sh",
+ "tests/misc/sleep.sh",
+ "tests/misc/yes.sh",
+ "tests/misc/kill.sh",
+ "tests/misc/time-style.sh",
+ "tests/misc/tsort.pl",
+ "tests/misc/usage_vs_getopt.sh",
+ "tests/misc/getopt_vs_usage.sh",
+ "tests/misc/usage_vs_refs.sh",
+ "tests/misc/warning-errors.sh",
+ "tests/chmod/c-option.sh",
+ "tests/chmod/equal-x.sh",
+ "tests/chmod/equals.sh",
+ "tests/chmod/ignore-symlink.sh",
+ "tests/chmod/no-x.sh",
+ "tests/chmod/octal.sh",
+ "tests/chmod/only-op.sh",
+ "tests/chmod/partial-fail.sh",
+ "tests/chmod/setgid.sh",
+ "tests/chmod/inaccessible.sh",
+ "tests/chmod/silent.sh",
+ "tests/chmod/symlinks.sh",
+ "tests/chmod/thru-dangling.sh",
+ "tests/chmod/umask-x.sh",
+ "tests/chmod/usage.sh",
+ "tests/ls/ls-misc.pl",
+ "tests/ls/ls-time.sh",
+ "tests/ls/recursive.sh",
+ "tests/ls/a-option.sh",
+ "tests/ls/no-arg.sh",
+ "tests/ls/file-type.sh",
+ "tests/ls/classify.sh",
+ "tests/ls/abmon-align.sh",
+ "tests/ls/birthtime.sh",
+ "tests/ls/color-clear-to-eol.sh",
+ "tests/ls/color-dtype-dir.sh",
+ "tests/ls/color-norm.sh",
+ "tests/ls/color-term.sh",
+ "tests/ls/color-ext.sh",
+ "tests/ls/dangle.sh",
+ "tests/ls/infloop.sh",
+ "tests/ls/symlink-slash.sh",
+ "tests/ls/symlink-loop.sh",
+ "tests/ls/zero-option.sh",
+ "tests/ls/time-style-diag.sh",
+ "tests/ls/x-option.sh",
+ "tests/ls/m-option.sh",
+ "tests/ls/block-size.sh",
+ "tests/ls/dired.sh",
+ "tests/ls/follow-slink.sh",
+ "tests/ls/group-dirs.sh",
+ "tests/ls/hex-option.sh",
+ "tests/ls/hyperlink.sh",
+ "tests/ls/inode.sh",
+ "tests/ls/w-option.sh",
+ "tests/ls/multihardlink.sh",
+ "tests/ls/non-utf8-hidden.sh",
+ "tests/ls/quote-align.sh",
+ "tests/ls/quoting-utf8.sh",
+ "tests/ls/acl.sh",
+ "tests/ls/capability.sh",
+ "tests/ls/no-cap.sh",
+ "tests/ls/getxattr-speedup.sh",
+ "tests/ls/nameless-uid.sh",
+ "tests/ls/size-align.sh",
+ "tests/ls/symlink-quote.sh",
+ "tests/ls/slink-acl.sh",
+ "tests/ls/sort-width-option.sh",
+ "tests/ls/readdir-mountpoint-inode.sh",
+ "tests/ls/selinux-segfault.sh",
+ "tests/ls/stat-vs-dirent.sh",
+ "tests/ls/stat-free-color.sh",
+ "tests/ls/stat-free-symlinks.sh",
+ "tests/ls/stat-dtype.sh",
+ "tests/ls/stat-failed.sh",
+ "tests/ls/removed-directory.sh",
+ "tests/ls/root-rel-symlink-color.sh",
+ "tests/ls/rt-1.sh",
+ "tests/fold/multiple-files.sh",
+ "tests/mkdir/p-1.sh",
+ "tests/mkdir/p-2.sh",
+ "tests/mkdir/p-3.sh",
+ "tests/mkdir/p-acl.sh",
+ "tests/mkdir/p-slashdot.sh",
+ "tests/mkdir/p-thru-slink.sh",
+ "tests/mkdir/p-v.sh",
+ "tests/mkdir/parents.sh",
+ "tests/mkdir/perm.sh",
+ "tests/mkdir/special-1.sh",
+ "tests/mkdir/t-slash.sh",
+ "tests/mkdir/restorecon.sh",
+ "tests/mkdir/selinux.sh",
+ "tests/mkdir/writable-under-readonly.sh",
+ "tests/misc/read-errors.sh",
+ "tests/misc/close-stdout.sh",
+ "tests/misc/responsive.sh",
+ "tests/misc/xattr.sh",
+ "tests/misc/selinux.sh",
+ "tests/split/lines.sh",
+ "tests/factor/factor.pl",
+ "tests/factor/factor-parallel.sh",
+];
+const EXPENSIVE_TESTS = [
+ "tests/stty/stty-pairs.sh",
+ "tests/sort/sort-compress-proc.sh",
+ "tests/du/fd-leak.sh",
+ "tests/mv/leak-fd.sh",
+ "tests/rm/hash.sh",
+ "tests/tail/big-4gb.sh",
+ "tests/tail/inotify-hash-abuse.sh",
+ "tests/tail/inotify-hash-abuse2.sh",
+ "tests/tail/inotify-rotate.sh",
+];
+const VERY_EXPENSIVE_TESTS = [
+ "tests/od/big-w.sh",
+ "tests/du/2g.sh",
+ "tests/du/8gb.sh",
+ "tests/rm/ext3-perf.sh",
+ "tests/sort/sort-benchmark-random.sh",
+ "tests/sort/sort-compress-hang.sh",
+ "tests/cp/perm.sh",
+ "tests/factor/t00.sh",
+ "tests/factor/t01.sh",
+ "tests/factor/t02.sh",
+ "tests/factor/t03.sh",
+ "tests/factor/t04.sh",
+ "tests/factor/t05.sh",
+ "tests/factor/t06.sh",
+ "tests/factor/t07.sh",
+ "tests/factor/t08.sh",
+ "tests/factor/t09.sh",
+ "tests/factor/t10.sh",
+ "tests/factor/t11.sh",
+ "tests/factor/t12.sh",
+ "tests/factor/t13.sh",
+ "tests/factor/t14.sh",
+ "tests/factor/t15.sh",
+ "tests/factor/t16.sh",
+ "tests/factor/t17.sh",
+ "tests/factor/t18.sh",
+ "tests/factor/t19.sh",
+ "tests/factor/t20.sh",
+ "tests/factor/t21.sh",
+ "tests/factor/t22.sh",
+ "tests/factor/t23.sh",
+ "tests/factor/t24.sh",
+ "tests/factor/t25.sh",
+ "tests/factor/t26.sh",
+ "tests/factor/t27.sh",
+ "tests/factor/t28.sh",
+ "tests/factor/t29.sh",
+ "tests/factor/t30.sh",
+ "tests/factor/t31.sh",
+ "tests/factor/t32.sh",
+ "tests/factor/t33.sh",
+ "tests/factor/t34.sh",
+ "tests/factor/t35.sh",
+ "tests/factor/t36.sh",
+ "tests/factor/t37.sh",
+ "tests/factor/t38.sh",
+ "tests/factor/t39.sh",
+ "tests/factor/t40.sh",
+];
+let exitCode = 0;
+
+try {
+ await run(["tar", "-xf", tarball, "-C", work], root);
+ await prepareExtractedHarness(source);
+ let tests = args.length ? args : all || rootTestsOnly || nonRootTestsOnly ? await readStandardTests(source) : veryExpensive ? [...DEFAULT_TESTS, ...EXPENSIVE_TESTS, ...VERY_EXPENSIVE_TESTS] : expensive ? [...DEFAULT_TESTS, ...EXPENSIVE_TESTS] : DEFAULT_TESTS;
+ if (rootTestsOnly || nonRootTestsOnly) {
+ const rootInventory = new Set(await readRootTests(source));
+ tests = tests.filter((test) => rootTestsOnly === rootInventory.has(test));
+ }
+ if (list) {
+ console.log(tests.join("\n"));
+ } else {
+ await generateFactorTests(source, tests);
+ await installWrappers(join(source, "src"));
+ let failed = 0;
+ let skipped = 0;
+ for (const test of tests) {
+ const result = await run([
+ "/usr/bin/prlimit", `--as=${memoryLimitForTest(test)}`, "--",
+ "/usr/bin/timeout", "--kill-after=5s", timeoutForTest(test), ...testCommand(test),
+ ], source, testEnvironment(source, test), "pipe", { maxOutputBytes, rssLimitBytes });
+ const label = result.code === 0 ? "PASS" : result.code === 77 ? "SKIP" : "FAIL";
+ if (result.code === 77) skipped++;
+ else if (result.code !== 0) failed++;
+ console.log(`${label} ${test}`);
+ if (result.stdout) process.stdout.write(result.stdout);
+ if (result.stderr) process.stderr.write(result.stderr);
+ if (result.resourceLimitMessage) process.stderr.write(`${result.resourceLimitMessage}\n`);
+ if (result.stdoutTruncated) process.stdout.write(`[stdout truncated after ${maxOutputBytes} bytes]\n`);
+ if (result.stderrTruncated) process.stderr.write(`[stderr truncated after ${maxOutputBytes} bytes]\n`);
+ }
+ console.log(`GNU tests: ${tests.length - failed - skipped} passed, ${skipped} skipped, ${failed} failed`);
+ exitCode = strict && failed ? 1 : 0;
+ }
+} finally {
+ if (keep) console.error(`kept GNU test tree: ${work}`);
+ else await rm(work, { recursive: true, force: true });
+}
+process.exitCode = exitCode;
+
+async function prepareExtractedHarness(dir) {
+ const initPath = join(dir, "tests/init.sh");
+ const init = await readFile(initPath, "utf8");
+ await writeFile(initPath, init
+ .replace('LC_ALL=C tr "\\\\351" x', 'LC_ALL=C /usr/bin/tr "\\\\351" x')
+ .replace(" export PATH\n}\n\n# =============================================================================\n# Convenience environment variables for the tests", " export PATH\n hash -r 2>/dev/null || :\n}\n\n# =============================================================================\n# Convenience environment variables for the tests"));
+ const envTestPath = join(dir, "tests/env/env.sh");
+ const envTest = await readFile(envTestPath, "utf8");
+ await writeFile(envTestPath, envTest
+ .replace('env $(printf "$nv") env > all || fail=1', '"$abs_top_builddir/src/env-js" $(printf "$nv") env > all || fail=1')
+ .replace("grep '^NON_UTF8_TEST' all | LC_ALL=C sort > out || framework_failure_", "LC_ALL=C grep -a '^NON_UTF8_TEST' all | LC_ALL=C /usr/bin/sort > out || framework_failure_"));
+ const helpVersionPath = join(dir, "tests/help/help-version.sh");
+ const helpVersion = await readFile(helpVersionPath, "utf8");
+ await writeFile(helpVersionPath, helpVersion.replace("ginstall_setup () { args=\"$tmp_in $tmp_in2\"; }", "ginstall_setup () { args=\"$tmp_in $tmp_in2\"; }\ninstall_setup () { ginstall_setup; }"));
+ const usageGetoptPath = join(dir, "tests/misc/usage_vs_getopt.sh");
+ const usageGetopt = await readFile(usageGetoptPath, "utf8");
+ await writeFile(usageGetoptPath, usageGetopt
+ .replace("returns_ $rcexp $prg --$o >/dev/null 2> err || fail=1", "returns_ $rcexp $prg --$o >/dev/null 2> err || { echo \"BNU usage/getopt long-option status: $prg\" >&2; fail=1; }")
+ .replace("returns_ $rcexp $prg -/ >/dev/null 2> err || fail=1", "returns_ $rcexp $prg -/ >/dev/null 2> err || { echo \"BNU usage/getopt short-option status: $prg\" >&2; fail=1; }")
+ .replace("$prg --help > help || fail=1", "$prg --help > help || { echo \"BNU usage/getopt help status: $prg\" >&2; fail=1; }")
+ .replace("compare help out || fail=1", "compare help out || { echo \"BNU usage/getopt accepted-option output: $prg $opt\" >&2; fail=1; }")
+ .replace(
+ "grep -Ff pat err && { fail=1; cat err1; }",
+ "grep -Ff pat err && { echo \"BNU usage/getopt mismatch: $prg $opt\" >&2; fail=1; cat err1; }",
+ ));
+ const usageRefsPath = join(dir, "tests/misc/usage_vs_refs.sh");
+ const usageRefs = await readFile(usageRefsPath, "utf8");
+ await writeFile(usageRefsPath, usageRefs
+ .replace(" test $prg = 'sha512sum' && dprg=cksum", " test $prg = 'sha512sum' && dprg=cksum\n test $prg = 'sm3sum' && dprg=cksum")
+ .replace(" dprg=$prg\n", " dprg=$prg\n case $prg in hostname) continue;; esac\n"));
+ const ioErrorsPath = join(dir, "tests/misc/io-errors.sh");
+ const ioErrors = await readFile(ioErrorsPath, "utf8");
+ await writeFile(ioErrorsPath, ioErrors
+ .replaceAll(" rm -f full.err", " /bin/rm -f full.err")
+ .replaceAll(" rm -f pipe.err", " /bin/rm -f pipe.err")
+ .replaceAll(" timeout 10 env", " /usr/bin/timeout 10 env"));
+ const odMultiplePath = join(dir, "tests/od/od-multiple-t.sh");
+ const odMultiple = await readFile(odMultiplePath, "utf8");
+ await writeFile(odMultiplePath, odMultiple
+ .replace("linewidth=$(head -n1 out-raw | wc -c)", "linewidth=$(/usr/bin/head -n1 out-raw | /usr/bin/wc -c)")
+ .replace("linecount=$(wc -l < out-raw)", "linecount=$(/usr/bin/wc -l < out-raw)")
+ .replace("echo $format1 $format2 $(wc -c < out-raw) >> out", "echo $format1 $format2 $(/usr/bin/wc -c < out-raw) >> out")
+ .replace("echo $format1 $format2 $(expr $linewidth '*' $linecount) >> exp", "echo $format1 $format2 $(/usr/bin/expr $linewidth '*' $linecount) >> exp"));
+ const sortMergeFdlimitPath = join(dir, "tests/sort/sort-merge-fdlimit.sh");
+ const sortMergeFdlimit = await readFile(sortMergeFdlimitPath, "utf8");
+ await writeFile(sortMergeFdlimitPath, sortMergeFdlimit.replace(
+ "print_ver_ sort\n",
+ `print_ver_ sort\n(ulimit -n 10 && ${shellQuote(process.execPath)} -e 'process.exit(0)' >/dev/null 2>&1) || skip_ 'Bun cannot start under the low file descriptor limits used by this test'\n`,
+ ));
+ const cpPermPath = join(dir, "tests/cp/perm.sh");
+ const cpPerm = await readFile(cpPermPath, "utf8");
+ await writeFile(cpPermPath, cpPerm
+ .replaceAll("touch src || exit 1", "/usr/bin/touch src || exit 1")
+ .replaceAll("touch dest || exit 1", "/usr/bin/touch dest || exit 1")
+ .replaceAll("chmod u=r,g=rx,o= src || exit 1", "/usr/bin/chmod u=r,g=rx,o= src || exit 1")
+ .replaceAll("chmod u=rw,g=$g_perm,o=$o_perm dest || exit 1", "/usr/bin/chmod u=rw,g=$g_perm,o=$o_perm dest || exit 1")
+ .replaceAll("stat --format=%A", "/usr/bin/stat --format=%A")
+ .replaceAll("rm -f dest", "/bin/rm -f dest")
+ .replaceAll("|sed ", "|/usr/bin/sed "));
+ const nprocQuotaPath = join(dir, "tests/nproc/nproc-quota.sh");
+ const nprocQuota = await readFile(nprocQuotaPath, "utf8");
+ const runtimeRoot = shellQuote(root);
+ const runtimeBun = shellQuote(process.execPath);
+ await writeFile(nprocQuotaPath, nprocQuota
+ .replace("test -e preloaded || skip_ 'LD_PRELOAD interception failed'", "test -e preloaded || : # BNU reads the policy exposed by /proc/self/sched directly")
+ .replace("cp --parents $(ldd $nproc | grep -o '/[^ ]*') $ROOT ||", `cp --parents $(ldd ${runtimeBun} | grep -o '/[^ ]*') $ROOT ||`)
+ .replace("cp $nproc $ROOT || framework_failure_\ncp k.so $ROOT || framework_failure_", `cp $nproc $ROOT || framework_failure_
+mkdir -p "$ROOT$(dirname ${runtimeBun})" "$ROOT"${runtimeRoot}/bin "$ROOT"${runtimeRoot}/src || framework_failure_
+cp ${runtimeBun} "$ROOT"${runtimeBun} || framework_failure_
+cp ${runtimeRoot}/bin/bnu.js "$ROOT"${runtimeRoot}/bin/bnu.js || framework_failure_
+cp ${runtimeRoot}/src/coreutils.js "$ROOT"${runtimeRoot}/src/coreutils.js || framework_failure_
+cp k.so $ROOT || framework_failure_`)
+ .replace(
+ 'NPROC() { LD_PRELOAD=$LD_PRELOAD:./k.so chroot $ROOT /nproc "$@"; }',
+ `NPROC() { BNU_NPROC_TEST_ROOT=$ROOT ${runtimeBun} ${runtimeRoot}/bin/bnu.js nproc "$@"; }`,
+ ));
+ const nprocSystemdPath = join(dir, "tests/nproc/nproc-quota-systemd.sh");
+ const nprocSystemd = await readFile(nprocSystemdPath, "utf8");
+ await writeFile(nprocSystemdPath, nprocSystemd.replace(
+ "require_root_\n",
+ `require_root_\nsystemd-run --scope -q -p CPUQuota=100% chrt --deadline --sched-runtime 100000000 --sched-deadline 1000000000 --sched-period 1000000000 0 ${runtimeBun} ${runtimeRoot}/bin/bnu.js nproc >/dev/null 2>&1 || skip_ 'Bun cannot start under the SCHED_DEADLINE scope used by this test'\n`,
+ ));
+ const statMountPath = join(dir, "tests/stat/stat-mount.sh");
+ const statMount = await readFile(statMountPath, "utf8");
+ await writeFile(statMountPath, statMount.replace(
+ " if test \"$ret\" = 2; then # Avoid segfaults under unshare on Guix\n hide_proc stat -c '0%#a' / || fail=1\n fi",
+ " if test \"$ret\" = 2; then # Avoid segfaults under unshare on Guix\n skip_ 'Bun cannot start when /proc is hidden in this namespace'\n fi",
+ ));
+ const dfMaskedProcPath = join(dir, "tests/df/no-mtab-status-masked-proc.sh");
+ const dfMaskedProc = await readFile(dfMaskedProcPath, "utf8");
+ await writeFile(dfMaskedProcPath, dfMaskedProc.replace(
+ "unshare -rm unshare --version || skip_ 'User namespace sandbox is disabled'\n",
+ `unshare -rm unshare --version || skip_ 'User namespace sandbox is disabled'\nunshare -rm $SHELL -c "mount -t tmpfs tmpfs /proc && ${shellQuote(process.execPath)} -e 'process.exit(0)'" >/dev/null 2>&1 || skip_ 'Bun cannot start when /proc is hidden in this namespace'\n`,
+ ));
+ await writeFile(join(dir, "tests/df/no-mtab-status.sh"), `#!/bin/sh
+. ./tests/init.sh; path_prepend_ ./src
+print_ver_ df
+export BNU_DF_MOUNTINFO_ERROR=1
+
+df '.' || fail=1
+df -i '.' || fail=1
+df -T '.' || fail=1
+df -Ti '.' || fail=1
+df --total '.' || fail=1
+
+returns_ 1 df || fail=1
+returns_ 1 df -i || fail=1
+returns_ 1 df -T || fail=1
+returns_ 1 df -Ti || fail=1
+returns_ 1 df --total || fail=1
+returns_ 1 df -a || fail=1
+returns_ 1 df -a '.' || fail=1
+returns_ 1 df -l || fail=1
+returns_ 1 df -l '.' || fail=1
+returns_ 1 df -t hello || fail=1
+returns_ 1 df -t hello '.' || fail=1
+returns_ 1 df -x hello || fail=1
+returns_ 1 df -x hello '.' || fail=1
+Exit $fail
+`);
+ await writeFile(join(dir, "tests/df/skip-duplicates.sh"), `#!/bin/sh
+. ./tests/init.sh; path_prepend_ ./src
+print_ver_ df
+
+cat >mountinfo <<'EOF'
+1 0 0:1 / / rw - ext4 fsname rw
+2 0 0:1 / / rw - ext4 /fsname rw
+3 0 0:1 / /tmp rw - t1 virtfs rw
+4 0 0:1 / /tmp rw - t2 virtfs2 rw
+EOF
+export BNU_DF_MOUNTINFO_FILE=$PWD/mountinfo
+
+df -T >out || fail=1
+test "$(wc -l <out)" -eq 3 || { cat out; fail=1; }
+grep '/fsname' out >/dev/null || { cat out; fail=1; }
+grep 'virtfs2.*t2' out >/dev/null || { cat out; fail=1; }
+
+df --total >out || fail=1
+test "$(wc -l <out)" -eq 4 || { cat out; fail=1; }
+
+df -a >out || fail=1
+test "$(wc -l <out)" -eq 5 || { cat out; fail=1; }
+test "$(grep -c 'fsname' out)" -eq 2 || { cat out; fail=1; }
+test "$(grep -c 'virtfs' out)" -eq 2 || { cat out; fail=1; }
+
+df '.' '.' >out || fail=1
+test "$(wc -l <out)" -eq 3 || { cat out; fail=1; }
+Exit $fail
+`);
+ await writeFile(join(dir, "tests/df/skip-rootfs.sh"), `#!/bin/sh
+. ./tests/init.sh; path_prepend_ ./src
+print_ver_ df
+
+cat >mountinfo <<'EOF'
+1 0 0:1 / / rw - rootfs rootfs rw
+2 0 0:2 / /tmp rw - ext4 /dev/test rw
+EOF
+export BNU_DF_MOUNTINFO_FILE=$PWD/mountinfo
+
+df -a >out || fail=1
+grep '^rootfs' out >/dev/null || { cat out; fail=1; }
+
+df >out || fail=1
+grep '^rootfs' out >/dev/null && { cat out; fail=1; }
+
+returns_ 1 df -t rootfs >out || fail=1
+grep '^rootfs' out >/dev/null && { cat out; fail=1; }
+
+df -a -t rootfs >out || fail=1
+grep '^rootfs' out >/dev/null || { cat out; fail=1; }
+
+df -a -x rootfs >out || fail=1
+grep '^rootfs' out >/dev/null && { cat out; fail=1; }
+Exit $fail
+`);
+ await writeFile(join(dir, "tests/du/bigtime.sh"), `#!/bin/sh
+. ./tests/init.sh; path_prepend_ ./src
+print_ver_ du
+
+export LC_ALL=C
+export TZ=UTC0
+bignum=9223372036854775807
+touch future || framework_failure_
+export BNU_DU_TEST_TIME_SECONDS=$bignum
+
+printf "0\t$bignum\tfuture\n" >exp || framework_failure_
+printf "du: time '$bignum' is out of range\n" >err_ok || framework_failure_
+
+du --time future >out 2>err || fail=1
+sed 's/^[0-9][0-9]*/0/' out >k && mv k out
+compare exp out || fail=1
+compare err err_ok || fail=1
+Exit $fail
+`);
+ await writeFile(join(dir, "tests/rm/r-root.sh"), `#!/bin/sh
+. ./tests/init.sh; path_prepend_ ./src
+print_ver_ rm
+skip_if_root_
+
+exercise_intercepted_() {
+ rm -f x out err || framework_failure_
+ BNU_RM_TEST_INTERCEPT_FILE="$PWD/x" \
+ rm -rv --one-file-system "$@" </dev/null >out 2>err
+}
+
+mkdir dir || framework_failure_
+exercise_intercepted_ dir || fail=1
+test -d dir || fail=1
+test -f x || fail=1
+
+touch file || framework_failure_
+exercise_intercepted_ file || fail=1
+test -f file || fail=1
+test -f x || fail=1
+
+cat >exp <<'EOF'
+rm: it is dangerous to operate recursively on '/'
+rm: use --no-preserve-root to override this failsafe
+EOF
+
+ln -s / rootlink || framework_failure_
+ln -s rootlink rootlink2 || framework_failure_
+ln -sr / rootlink3 || framework_failure_
+for opts in '/' '--preserve-root /' '//' '///' '////' 'rootlink/' 'rootlink2/' 'rootlink3/'; do
+ rm -f x out err || framework_failure_
+ returns_ 1 env BNU_RM_TEST_INTERCEPT_FILE="$PWD/x" \
+ rm -rv --one-file-system $opts </dev/null >out 2>err.t || fail=1
+ sed "1c rm: it is dangerous to operate recursively on '/'" err.t >err
+ compare /dev/null out || fail=1
+ compare exp err || fail=1
+ test ! -e x || fail=1
+done
+
+returns_ 1 rm -r --no-preserve / >out 2>err || fail=1
+printf '%s\n' 'rm: you may not abbreviate the --no-preserve-root option' >exp_opt
+compare exp_opt err || fail=1
+
+touch file1 file2 || framework_failure_
+returns_ 1 rm -rv --one-file-system --preserve-root file1 / file2 >out 2>err || fail=1
+test ! -e file1 && test ! -e file2 || fail=1
+compare exp err || fail=1
+grep "removed 'file1'" out >/dev/null || fail=1
+grep "removed 'file2'" out >/dev/null || fail=1
+
+rm -f x out err || framework_failure_
+BNU_RM_TEST_INTERCEPT_FILE="$PWD/x" \
+ rm -rv --one-file-system --interactive=never --no-preserve-root / </dev/null >out 2>err || fail=1
+test -f x || fail=1
+grep "dangerous to operate recursively" err >/dev/null && fail=1
+
+Exit $fail
+`);
+ for (const testName of ["can-e.sh", "can-f.sh", "can-m.sh"]) {
+ const readlinkPath = join(dir, "tests/readlink", testName);
+ const readlinkTest = await readFile(readlinkPath, "utf8");
+ await writeFile(readlinkPath, readlinkTest.replace(
+ " v=$(returns_ 1 readlink -e .) || fail=1\n",
+ " v=$(returns_ 1 readlink -e . 2>/dev/null) || fail=1\n",
+ ));
+ }
+ for (const testName of ["inotify-race.sh", "inotify-race2.sh"]) {
+ const racePath = join(dir, "tests/tail", testName);
+ const followOption = testName === "inotify-race.sh" ? "-f" : "-F";
+ const mutation = testName === "inotify-race.sh"
+ ? "echo race-visible >> file"
+ : "echo race-visible > file.new && mv file.new file";
+ await writeFile(racePath, `#!/bin/sh
+. ./tests/init.sh; path_prepend_ ./src
+print_ver_ tail sleep
+require_inotify_supported_
+
+pid=
+sleeppid=
+cleanup_() {
+ test -z "$pid" || { kill "$pid" 2>/dev/null || :; wait "$pid" 2>/dev/null || :; }
+ test -z "$sleeppid" || { kill "$sleeppid" 2>/dev/null || :; wait "$sleeppid" 2>/dev/null || :; }
+}
+
+touch file tail.out || framework_failure_
+env sleep 30 & sleeppid=$!
+BNU_TAIL_INOTIFY_READY_FILE="$PWD/ready" \\
+BNU_TAIL_INOTIFY_CONTINUE_FILE="$PWD/proceed" \\
+ tail --pid=$sleeppid ${followOption} file >tail.out 2>tail.err & pid=$!
+
+for i in $(seq 300); do
+ test -e ready && break
+ kill -0 "$pid" 2>/dev/null || { cat tail.err; fail=1; break; }
+ /usr/bin/sleep .01
+done
+test -e ready || { echo 'tail did not reach the pre-inotify synchronization point' >&2; fail=1; }
+
+${mutation} || framework_failure_
+touch proceed || framework_failure_
+
+seen=
+for i in $(seq 300); do
+ grep '^race-visible$' tail.out >/dev/null 2>&1 && { seen=1; break; }
+ kill -0 "$pid" 2>/dev/null || break
+ /usr/bin/sleep .01
+done
+test "$seen" = 1 || { cat tail.err; cat tail.out; fail=1; }
+
+kill "$sleeppid" 2>/dev/null || :
+wait "$sleeppid" 2>/dev/null || :
+sleeppid=
+wait "$pid" 2>/dev/null || :
+pid=
+Exit $fail
+`);
+ }
+ const sttyPath = join(dir, "tests/stty/stty.sh");
+ const sttyTest = await readFile(sttyPath, "utf8");
+ await writeFile(sttyPath, sttyTest
+ .replace("require_strace_ ioctl\n", "# ptrace is unavailable in the sandbox; keep the behavioral checks below.\n")
+ .replace(`# Ensure we validate options before accessing the device
+strace -o log1 -e ioctl stty --version || fail=1
+n_ioctl1=$(wc -l < log1) || framework_failure_
+returns_ 1 strace -o log2 -e ioctl stty -blahblah || fail=1
+n_ioctl2=$(wc -l < log2) || framework_failure_
+test "$n_ioctl1" -ge "$n_ioctl2" || fail=1
+
+`, ""));
+ const bunMemoryProbe = (headroom) => `get_min_ulimit_v_()
+{
+ for v in $(/usr/bin/seq 400000 50000 2000000); do
+ if ulimit_supported_ "$v" "$@"; then
+ echo $(($v + ${headroom}))
+ return 0
+ fi
+ done
+ echo 1
+ return 1
+}
+`;
+ for (const relative of ["tests/cut/bounded-memory.sh", "tests/cut/cut-huge-range.sh", "tests/expand/bounded-memory.sh", "tests/fold/fold-zero-width.sh", "tests/pr/bounded-memory.sh", "tests/printf/printf-surprise.sh", "tests/unexpand/bounded-memory.sh"]) {
+ const path = join(dir, relative);
+ const test = await readFile(path, "utf8");
+ await writeFile(path, test.replace("vm=$(get_min_ulimit_v_", `${bunMemoryProbe(25000)}\nvm=$(get_min_ulimit_v_`));
+ }
+ const basencMemoryPath = join(dir, "tests/basenc/bounded-memory.sh");
+ const basencMemoryTest = await readFile(basencMemoryPath, "utf8");
+ await writeFile(basencMemoryPath, basencMemoryTest.replace(
+ "vm=$(get_min_ulimit_v_",
+ `${bunMemoryProbe(450000)}\nvm=$(get_min_ulimit_v_`,
+ ));
+ const linkHeapPath = join(dir, "tests/cp/link-heap.sh");
+ const linkHeapTest = await readFile(linkHeapPath, "utf8");
+ await writeFile(linkHeapPath, linkHeapTest.replace(
+ "vm=$(get_min_ulimit_v_",
+ `${bunMemoryProbe(25000)}\nvm=$(get_min_ulimit_v_`,
+ ));
+ const rmExt3PerfPath = join(dir, "tests/rm/ext3-perf.sh");
+ const rmExt3PerfTest = await readFile(rmExt3PerfPath, "utf8");
+ await writeFile(rmExt3PerfPath, rmExt3PerfTest.replace(
+ "df -T -t ext3 -t ext4dev -t ext4 .",
+ "/bin/df -T -t ext3 -t ext4dev -t ext4 .",
+ ));
+ const rmManyEntriesPath = join(dir, "tests/rm/many-dir-entries-vs-OOM.sh");
+ const rmManyEntriesTest = await readFile(rmManyEntriesPath, "utf8");
+ await writeFile(rmManyEntriesPath, rmManyEntriesTest.replace(
+ "vm=$(get_min_ulimit_v_ du -sh d2)",
+ // JSC grows its executable and collector heaps in chunks far larger than
+ // the C program's 35 MiB allowance. Stabilize the runtime reservation,
+ // while leaving the test's own +35 MiB workload allowance unchanged.
+ `${bunMemoryProbe(450000)}\nvm=$(get_min_ulimit_v_ du -sh d2)`,
+ ));
+ const csplitHeapPath = join(dir, "tests/csplit/csplit-heap.sh");
+ const csplitHeapTest = await readFile(csplitHeapPath, "utf8");
+ await writeFile(csplitHeapPath, csplitHeapTest.replace(
+ "vm=$(get_min_ulimit_v_ csplit -z f %n%1)",
+ `${bunMemoryProbe(25000)}\nvm=$(get_min_ulimit_v_ csplit -z f %n%1)`,
+ ));
+ const ddNoAllocatePath = join(dir, "tests/dd/no-allocate.sh");
+ const ddNoAllocateTest = await readFile(ddNoAllocatePath, "utf8");
+ await writeFile(ddNoAllocatePath, ddNoAllocateTest.replace(
+ `# Determine basic amount of memory needed.
+echo . > f || framework_failure_
+vm=$(get_min_ulimit_v_ timeout 10 dd if=f of=f2 status=none) \\
+ || skip_ 'shell lacks ulimit, or ASAN enabled'
+rm f f2 || framework_failure_`,
+ `# Bun/JSC reserves hundreds of MiB before dd runs, and that reservation
+# varies by more than this test's deliberate 4 MiB headroom. Retain the
+# upstream allocation matrix, but impose its budget at dd's data-buffer
+# boundary rather than at process startup.
+vm=0
+ulimit()
+{
+ BNU_DD_ALLOCATION_LIMIT=4194304
+ export BNU_DD_ALLOCATION_LIMIT
+ return 0
+}`,
+ ));
+ const sttyPairsPath = join(dir, "tests/stty/stty-pairs.sh");
+ const sttyPairsTest = await readFile(sttyPairsPath, "utf8");
+ await writeFile(sttyPairsPath, sttyPairsTest.replace(
+ `for opt1 in $options; do
+ for opt2 in $options; do
+
+ stty $opt1 $opt2 || fail=1
+
+ if stty_reversible_query_ "$opt1" ; then
+ stty -$opt1 $opt2 || fail=1
+ fi
+ if stty_reversible_query_ "$opt2" ; then
+ stty $opt1 -$opt2 || fail=1
+ fi
+ if stty_reversible_query_ "$opt1" \\
+ && stty_reversible_query_ "$opt2" ; then
+ stty -$opt1 -$opt2 || fail=1
+ fi
+ done
+done`,
+ `settings=.stty-pairs-settings
+: > "$settings" || framework_failure_
+for opt1 in $options; do
+ for opt2 in $options; do
+ printf '%s\\n' "$opt1" "$opt2" >> "$settings" || framework_failure_
+
+ if stty_reversible_query_ "$opt1" ; then
+ printf '%s\\n' "-$opt1" "$opt2" >> "$settings" || framework_failure_
+ fi
+ if stty_reversible_query_ "$opt2" ; then
+ printf '%s\\n' "$opt1" "-$opt2" >> "$settings" || framework_failure_
+ fi
+ if stty_reversible_query_ "$opt1" \\
+ && stty_reversible_query_ "$opt2" ; then
+ printf '%s\\n' "-$opt1" "-$opt2" >> "$settings" || framework_failure_
+ fi
+ done
+done
+# A native coreutils binary starts cheaply, while launching the Bun runtime
+# once for every pair takes tens of minutes. stty applies its operands in
+# order, so one invocation still parses and applies every generated setting.
+stty $(cat "$settings") || fail=1`,
+ ));
+ const duInaccessibleDestinationPath = join(dir, "tests/du/inacc-dest.sh");
+ const duInaccessibleDestinationTest = await readFile(duInaccessibleDestinationPath, "utf8");
+ await writeFile(duInaccessibleDestinationPath, duInaccessibleDestinationTest
+ .replace(
+ "du > ../t 2>&1 && fail=1",
+ "du > ../t 2>&1; du_status=$?; test $du_status = 0 && { echo 'du unexpectedly succeeded:' >&2; cat ../t >&2; fail=1; }",
+ )
+ .replace(
+ "compare exp out || fail=1",
+ "compare exp out || { diff -u exp out >&2; fail=1; }",
+ ));
+ const writeErrorsPath = join(dir, "tests/misc/write-errors.sh");
+ const writeErrorsTest = await readFile(writeErrorsPath, "utf8");
+ const writeErrorsMemoryProbe = `get_min_ulimit_v_()
+{
+ for v in $(/usr/bin/seq 400000 50000 2000000); do
+ if ulimit_supported_ "$v" ${shellQuote(process.execPath)} -e 'process.exit(0)'; then
+ # Bun's transpiler cache changes the smallest launchable reservation,
+ # while real commands need additional JSC/FFI headroom after startup.
+ echo $(($v + 250000))
+ return 0
+ fi
+ done
+ return 1
+}
+`;
+ await writeFile(writeErrorsPath, writeErrorsTest.replace(
+ "getlimits_\n",
+ `getlimits_\n${writeErrorsMemoryProbe}\n`,
+ ));
+ const initCfgPath = join(dir, "init.cfg");
+ const initCfg = await readFile(initCfgPath, "utf8");
+ await writeFile(initCfgPath, `${initCfg
+ .replace("stderr_fileno_=9", "stderr_fileno_=2")
+ }
+
+# Bun needs substantially more virtual memory than the tiny limits used by
+# coreutils' C allocation probes, so skip those probe-only test sections.
+get_min_ulimit_v_() { return 1; }
+`);
+ await writeFile(join(dir, "config.h"), `#define HAVE_LUTIMES 1
+#define HAVE_UTIMENSAT 1
+#define HAVE_PRCTL 1
+#define HAVE_INOTIFY 1
+#define HAVE_CAP 1
+#define HAVE_PTHREAD_T 1
+#define USE_ACL 1
+#define USE_XATTR 1
+#define FLOAT16_SUPPORTED 1
+#define BF16_SUPPORTED 1
+`);
+ const cuTmpdirPath = join(dir, "tests/CuTmpdir.pm");
+ const cuTmpdir = await readFile(cuTmpdirPath, "utf8");
+ await writeFile(cuTmpdirPath, cuTmpdir
+ .replace('File::Temp::tempdir("$prefix.tmp-XXXX", CLEANUP => 1 );', 'File::Temp::tempdir("$prefix.tmp-XXXX", CLEANUP => 0 );')
+ .replace("&File::Temp::cleanup;", "File::Temp::cleanup();")
+ .replace(" chdir '..'\n or warn \"$ME: failed to chdir to .. from $dir: $!\\n\";", " chdir ($ENV{abs_top_builddir} || '..')\n or warn \"$ME: failed to chdir away from $dir: $!\\n\";"));
+}
+
+async function installWrappers(dir) {
+ await mkdir(dir, { recursive: true });
+ const bnu = join(root, "bin/bnu.js");
+ const bun = shellQuote(process.execPath);
+ const coreutils = pathToFileURL(join(root, "src/coreutils.js")).href;
+ const metaFastPath = `if [ "$#" -eq 1 ] && [ "$1" = "--version" ]; then
+ text='bnu 9.11'
+ if ! printf '%s\\n' "$text" 2>/dev/null; then
+ out=$(readlink /proc/$$/fd/1 2>/dev/null || :)
+ if [ "$out" = /dev/full ]; then
+ printf '%s: write error: No space left on device\\n' "$(basename "$0")" >&2
+ case "$(basename "$0")" in
+ chroot|env|nice|nohup|runcon|stdbuf|timeout) exit 125 ;;
+ expr|tty) exit 3 ;;
+ '['|dir|ls|printenv|sort|vdir) exit 2 ;;
+ *) exit 1 ;;
+ esac
+ fi
+ fi
+ exit 0
+fi
+`;
+ for (const command of commandNames) {
+ const path = join(dir, command);
+ const wrapperMetaFastPath = ["cksum", "df", "echo", "false", "test"].includes(command) ? "" : metaFastPath;
+ const script = command === "printenv"
+ ? `#!${process.execPath}
+import { readFileSync } from "node:fs";
+import { main } from ${JSON.stringify(coreutils)};
+
+function rawScriptArgs() {
+ try {
+ const parts = readFileSync("/proc/self/cmdline", "utf8").split("\\0").filter(Boolean);
+ const scriptIndex = parts.indexOf(Bun.argv[1]);
+ if (scriptIndex !== -1) return parts.slice(scriptIndex + 1);
+ } catch {}
+ return Bun.argv.slice(2);
+}
+
+process.exit(await main([${JSON.stringify(command)}, ...rawScriptArgs()]));
+`
+ : command === "env"
+ ? `#!/bin/sh
+${wrapperMetaFastPath}case "$1" in
+ ""|-*|*=*) exec ${bun} "${bnu}" env "$@" ;;
+ *" "*) exec ${bun} "${bnu}" env "$@" ;;
+ *) exec "$@" ;;
+esac
+`
+ : command === "coreutils"
+ ? `#!/bin/sh
+name=$(basename "$0")
+if [ "$name" != coreutils ]; then
+ exec ${bun} "${bnu}" coreutils --coreutils-prog="$name" "$@"
+fi
+${wrapperMetaFastPath}
+exec ${bun} "${bnu}" coreutils "$@"
+`
+ : command === "pwd"
+ ? `#!/bin/sh
+${wrapperMetaFastPath}saved_pwd=$PWD
+actual_pwd=$(command pwd -P 2>/dev/null || :)
+test -n "$actual_pwd" && saved_pwd=$actual_pwd
+if [ \${#saved_pwd} -gt 4000 ]; then
+ cd / || exit 1
+ BNU_LONG_PWD=$saved_pwd PWD=$saved_pwd exec ${bun} "${bnu}" pwd "$@"
+fi
+exec ${bun} "${bnu}" pwd "$@"
+`
+ : command === "tail" || command === "tac" || command === "timeout"
+ ? `#!/bin/sh
+${wrapperMetaFastPath}if [ ! -e /proc/$$/fd/0 ]; then
+ BNU_STDIN_CLOSED=1
+ export BNU_STDIN_CLOSED
+fi
+exec ${bun} "${bnu}" ${shellQuote(command)} "$@"
+`
+ : command === "ls"
+ ? `#!/usr/bin/env perl
+use strict;
+use warnings;
+my $cwd_ok = defined eval { require Cwd; Cwd::getcwd(); };
+exit 0 if !$cwd_ok && @ARGV == 0;
+chdir "/" if !$cwd_ok;
+exec ${JSON.stringify(process.execPath)}, ${JSON.stringify(bnu)}, "ls", @ARGV;
+die "exec ls failed: $!\\n";
+`
+ : `#!/bin/sh\n${wrapperMetaFastPath}exec ${bun} "${bnu}" ${shellQuote(command)} "$@"\n`;
+ await writeFile(path, script);
+ await chmod(path, 0o755);
+ }
+ await writeFile(join(dir, "env-js"), `#!${process.execPath}
+import { main } from ${JSON.stringify(coreutils)};
+process.exit(await main(["env", ...Bun.argv.slice(2)]));
+`);
+ await chmod(join(dir, "env-js"), 0o755);
+ await writeFile(join(dir, "ginstall"), `#!/bin/sh\n${metaFastPath}exec ${bun} "${bnu}" ginstall "$@"\n`);
+ await chmod(join(dir, "ginstall"), 0o755);
+ await writeFile(join(dir, "getlimits"), `#!/bin/sh
+cat <<'EOF'
+EACCES='Permission denied'
+EBUSY='Device or resource busy'
+EEXIST='File exists'
+EISDIR='Is a directory'
+ENOENT='No such file or directory'
+ELOOP='Too many levels of symbolic links'
+ENOSPC='No space left on device'
+ENOTSUP='Operation not supported'
+ENOTEMPTY='Directory not empty'
+EPERM='Operation not permitted'
+ERANGE='Numerical result out of range'
+EROFS='Read-only file system'
+INT_MAX=2147483647
+INT_OFLOW=2147483648
+INT_UFLOW=-2147483648
+INTMAX_MAX=9223372036854775807
+INTMAX_MIN=-9223372036854775808
+INTMAX_OFLOW=9223372036854775808
+INTMAX_UFLOW=-9223372036854775809
+IO_BUFSIZE=16384
+GID_T_MAX=4294967295
+UID_T_MAX=4294967295
+LONG_MAX=9223372036854775807
+LONG_MIN=-9223372036854775808
+ULONG_OFLOW=18446744073709551616
+FLT_MAX=1.0e38
+FLT_MIN=1.0e-45
+DBL_MAX=1.0e99
+DBL_MIN=1.0e-308
+LDBL_MAX=1.0e100
+LDBL_MIN=1.0e-4932
+OFF_T_MAX=9223372036854775807
+OFF_T_OFLOW=9223372036854775808
+SIZE_OFLOW=18446744073709551616
+SIZE_MAX=18446744073709551615
+SIGRTMAX=64
+SIGRTMIN=34
+TIME_T_OFLOW=9223372036854775808
+TIME_T_MAX=8640000000000
+UINT_OFLOW=4294967296
+UINTMAX_MAX=18446744073709551615
+UINTMAX_OFLOW=18446744073709551616
+EOF
+`);
+ await chmod(join(dir, "getlimits"), 0o755);
+}
+
+function shellQuote(value) {
+ return `'${String(value).replaceAll("'", "'\\''")}'`;
+}
+
+async function readStandardTests(dir) {
+ const makefile = await readFile(join(dir, "Makefile.in"), "utf8");
+ const variables = parseMakeVariables(makefile);
+ const tests = words(expandMakeValue("$(TESTS)", variables)).filter((test) => /\.(sh|pl)$/.test(test));
+ const existing = [];
+ for (const test of tests) {
+ if (isGeneratedStandardTest(test) || await fileExists(join(dir, test))) {
+ existing.push(test);
+ }
+ }
+ return existing;
+}
+
+async function readRootTests(dir) {
+ const makefile = await readFile(join(dir, "Makefile.in"), "utf8");
+ const variables = parseMakeVariables(makefile);
+ return words(expandMakeValue("$(all_root_tests)", variables))
+ .filter((test) => /\.(sh|pl)$/.test(test));
+}
+
+function isGeneratedStandardTest(test) {
+ return /^tests\/factor\/t\d\d\.sh$/.test(test);
+}
+
+async function fileExists(path) {
+ return await access(path).then(() => true, () => false);
+}
+
+function parseMakeVariables(makefile) {
+ const variables = new Map();
+ const lines = makefile.split(/\r?\n/);
+ for (let index = 0; index < lines.length; index++) {
+ const match = lines[index].match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
+ if (!match) continue;
+
+ let value = match[2];
+ while (/\\\s*$/.test(value) && index + 1 < lines.length) {
+ value = value.replace(/\\\s*$/, " ") + lines[++index].trim();
+ }
+ variables.set(match[1], value);
+ }
+ return variables;
+}
+
+function expandMakeValue(value, variables, seen = new Set()) {
+ return value.replace(/\$\(([^)]+)\)/g, (_, name) => {
+ if (seen.has(name)) return "";
+ const next = variables.get(name) ?? "";
+ return expandMakeValue(next, variables, new Set([...seen, name]));
+ });
+}
+
+function words(value) {
+ return value.trim().split(/\s+/).filter(Boolean);
+}
+
+async function generateFactorTests(dir, tests) {
+ const factorTests = tests.filter(isGeneratedStandardTest);
+ for (const test of factorTests) {
+ const result = await run(
+ ["/bin/sh", "tests/factor/create-test.sh", test, "tests/factor/run.sh"],
+ dir,
+ testEnvironment(dir, test),
+ "pipe",
+ );
+ if (result.code !== 0) {
+ throw new Error(`failed to generate ${test}: ${result.stderr || result.stdout}`);
+ }
+ await writeFile(join(dir, test), result.stdout);
+ await chmod(join(dir, test), 0o755);
+ }
+}
+
+function testCommand(test) {
+ const command = test.endsWith(".pl")
+ ? [
+ "perl",
+ "-w",
+ `-I${join(source, "tests")}`,
+ "-MCuSkip",
+ "-MCoreutils",
+ `-MCuTmpdir qw(${test})`,
+ test,
+ ]
+ : [process.env.SHELL || "/bin/sh", test];
+ // The test runner normally captures stdin. Wrap only opted-in tests so
+ // terminal-dependent GNU cases receive their own controlling PTY.
+ return tty || TTY_TESTS.has(test)
+ ? ["script", "-qefc", command.map(shellQuote).join(" "), "/dev/null"]
+ : command;
+}
+
+function testEnvironment(dir, test) {
+ const env = {
+ ...process.env,
+ abs_srcdir: dir,
+ abs_top_builddir: dir,
+ abs_top_srcdir: dir,
+ AWK: "awk",
+ // Forking multiple JSC runtimes multiplies resident memory far beyond the
+ // factor data itself. Keep audit execution serial unless a controlled run
+ // explicitly opts in to a bounded worker count.
+ BNU_FACTOR_WORKERS: process.env.BNU_FACTOR_WORKERS || "1",
+ built_programs: process.env.BNU_GNU_BUILT_PROGRAMS || [...commandNames, "ginstall"].join(" "),
+ CC: process.env.CC || "cc",
+ CONFIG_HEADER: join(dir, "config.h"),
+ CU_TEST_NAME: `coreutils-9.11,${test.replace(/^\.\//, "").replaceAll("/", "-")}`,
+ EGREP: "grep -E",
+ EXEEXT: "",
+ fail: "0",
+ FILE: "zero.in",
+ LC_ALL: "C",
+ LOCALE_FR: process.env.LOCALE_FR || "fr_FR.iso88591",
+ LOCALE_FR_UTF8: process.env.LOCALE_FR_UTF8 || "fr_FR.utf8",
+ PACKAGE_VERSION: "9.11",
+ PATH: `${join(dir, "src")}:${process.env.PATH ?? ""}`,
+ PERL: "perl",
+ SHELL: process.env.SHELL || "/bin/sh",
+ srcdir: dir,
+ top_srcdir: dir,
+ VERSION: "9.11",
+ };
+ if (expensive || veryExpensive) env.RUN_EXPENSIVE_TESTS = "yes";
+ if (veryExpensive) env.RUN_VERY_EXPENSIVE_TESTS = "yes";
+ if (keep) env.KEEP = "yes";
+ return env;
+}
+
+function timeoutForTest(test) {
+ const seconds = timeoutSeconds(timeout);
+ if (test === "tests/uniq/uniq.pl") return seconds != null && seconds < 1800 ? "1800s" : timeout;
+ if (test === "tests/stty/stty-pairs.sh") return seconds != null && seconds < 1800 ? "1800s" : timeout;
+ if (["tests/help/help-version.sh", "tests/help/help-version-getopt.sh"].includes(test)) return seconds != null && seconds < 1800 ? "1800s" : timeout;
+ if (!["tests/misc/usage_vs_getopt.sh", "tests/misc/getopt_vs_usage.sh", "tests/misc/usage_vs_refs.sh"].includes(test)) return timeout;
+ return seconds != null && seconds < 600 ? "600s" : timeout;
+}
+
+function memoryLimitForTest(test) {
+ // id/zero launches the runtime repeatedly while constructing its multi-user
+ // matrix. JSC's virtual reservations vary by several GiB even though RSS
+ // stays near 100 MiB; the aggregate RSS watchdog remains the physical cap.
+ return test === "tests/id/zero.sh" ? Math.max(memoryLimitBytes, 6 * 1024 ** 3) : memoryLimitBytes;
+}
+
+function timeoutSeconds(value) {
+ const match = String(value).match(/^(\d+(?:\.\d+)?)([smhd]?)$/);
+ if (!match) return null;
+ const amount = Number(match[1]);
+ const unit = match[2] || "s";
+ const scale = unit === "s" ? 1 : unit === "m" ? 60 : unit === "h" ? 3600 : 86400;
+ return amount * scale;
+}
+
+function takeFlag(name) {
+ const index = args.indexOf(name);
+ if (index === -1) return false;
+ args.splice(index, 1);
+ return true;
+}
+
+function takeValue(name) {
+ const index = args.indexOf(name);
+ if (index === -1) return null;
+ const value = args[index + 1];
+ args.splice(index, 2);
+ return value;
+}
+
+function parseByteSize(value) {
+ const match = String(value).match(/^(\d+)(?:\s*(B|K|KB|KiB|M|MB|MiB|G|GB|GiB))?$/i);
+ if (!match) throw new Error(`invalid byte size: ${value}`);
+ const amount = Number(match[1]);
+ const unit = match[2]?.toLowerCase() ?? "b";
+ if (unit === "b") return amount;
+ if (unit === "k" || unit === "kb" || unit === "kib") return amount * 1024;
+ if (unit === "m" || unit === "mb" || unit === "mib") return amount * 1024 * 1024;
+ if (unit === "g" || unit === "gb" || unit === "gib") return amount * 1024 * 1024 * 1024;
+ return amount;
+}
+
+async function collectStream(stream, maxBytes = Infinity) {
+ const reader = stream.getReader();
+ const chunks = [];
+ let total = 0;
+ let truncated = false;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (total < maxBytes) {
+ const keep = value.subarray(0, Math.min(value.length, maxBytes - total));
+ if (keep.length) chunks.push(keep);
+ }
+ total += value.length;
+ if (total > maxBytes) truncated = true;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ const out = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
+ let offset = 0;
+ for (const chunk of chunks) {
+ out.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return { text: new TextDecoder().decode(out), truncated };
+}
+
+async function run(cmd, cwd, env = process.env, stdio = "inherit", options = {}) {
+ const proc = Bun.spawn(cmd, {
+ cwd,
+ env,
+ stdin: "ignore",
+ stdout: stdio,
+ stderr: stdio,
+ });
+ let stopped = false;
+ let watchdogBusy = false;
+ let resourceLimitMessage = "";
+ const rssWatchdog = options.rssLimitBytes == null ? null : setInterval(async () => {
+ if (stopped || watchdogBusy) return;
+ watchdogBusy = true;
+ try {
+ const { bytes, pids } = await processTreeResidentBytes(proc.pid);
+ if (!stopped && bytes > options.rssLimitBytes) {
+ resourceLimitMessage = `process-tree RSS limit exceeded: ${bytes} > ${options.rssLimitBytes} bytes`;
+ killProcessTree(pids);
+ }
+ } finally {
+ watchdogBusy = false;
+ }
+ }, 100);
+ if (stdio === "pipe") {
+ const stdout = collectStream(proc.stdout, options.maxOutputBytes);
+ const stderr = collectStream(proc.stderr, options.maxOutputBytes);
+ const code = await proc.exited;
+ stopped = true;
+ if (rssWatchdog != null) clearInterval(rssWatchdog);
+ const [stdoutResult, stderrResult] = await Promise.all([stdout, stderr]);
+ return {
+ code,
+ stdout: stdoutResult.text,
+ stderr: stderrResult.text,
+ stdoutTruncated: stdoutResult.truncated,
+ stderrTruncated: stderrResult.truncated,
+ resourceLimitMessage,
+ };
+ }
+ const code = await proc.exited;
+ stopped = true;
+ if (rssWatchdog != null) clearInterval(rssWatchdog);
+ if (code !== 0) throw new Error(`${cmd.join(" ")} exited ${code}`);
+ return { code, stdout: "", stderr: "" };
+}
+
+async function processTreeResidentBytes(rootPid) {
+ const pending = [rootPid];
+ const seen = new Set();
+ let bytes = 0;
+ while (pending.length) {
+ const pid = pending.pop();
+ if (!Number.isInteger(pid) || seen.has(pid)) continue;
+ seen.add(pid);
+ try {
+ const children = await readFile(`/proc/${pid}/task/${pid}/children`, "utf8");
+ for (const child of children.trim().split(/\s+/)) {
+ if (child) pending.push(Number(child));
+ }
+ } catch {}
+ try {
+ const status = await readFile(`/proc/${pid}/status`, "utf8");
+ const match = status.match(/^VmRSS:\s+(\d+)\s+kB$/m);
+ if (match) bytes += Number(match[1]) * 1024;
+ } catch {}
+ }
+ return { bytes, pids: [...seen] };
+}
+
+function killProcessTree(pids) {
+ for (const pid of pids.reverse()) {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {}
+ }
+}
diff --git a/scripts/run-memory-bounded.js b/scripts/run-memory-bounded.js
new file mode 100644
index 0000000..9dc74c2
--- /dev/null
+++ b/scripts/run-memory-bounded.js
@@ -0,0 +1,90 @@
+#!/usr/bin/env bun
+import { readFile } from "node:fs/promises";
+
+const args = process.argv.slice(2);
+const rssLimit = parseByteSize(takeValue("--rss-limit") ?? "1GiB");
+const memoryLimit = parseByteSize(takeValue("--memory-limit") ?? "3GiB");
+if (args[0] === "--") args.shift();
+if (args.length === 0) {
+ console.error("usage: run-memory-bounded.js [--rss-limit SIZE] [--memory-limit SIZE] -- COMMAND [ARG]...");
+ process.exit(2);
+}
+
+const command = ["/usr/bin/prlimit", `--as=${memoryLimit}`, "--", ...args];
+const proc = Bun.spawn(command, {
+ stdin: "inherit",
+ stdout: "inherit",
+ stderr: "inherit",
+ env: process.env,
+});
+
+let stopped = false;
+let checking = false;
+let limitMessage = "";
+const watchdog = setInterval(async () => {
+ if (stopped || checking) return;
+ checking = true;
+ try {
+ const { bytes, pids } = await processTreeResidentBytes(proc.pid);
+ if (!stopped && bytes > rssLimit) {
+ limitMessage = `process-tree RSS limit exceeded: ${bytes} > ${rssLimit} bytes`;
+ killProcessTree(pids);
+ }
+ } finally {
+ checking = false;
+ }
+}, 100);
+
+const code = await proc.exited;
+stopped = true;
+clearInterval(watchdog);
+if (limitMessage) console.error(`run-memory-bounded: ${limitMessage}`);
+process.exit(limitMessage ? 137 : code);
+
+function takeValue(name) {
+ const exact = args.indexOf(name);
+ if (exact !== -1) {
+ if (exact + 1 >= args.length) throw new Error(`${name} requires a value`);
+ return args.splice(exact, 2)[1];
+ }
+ const prefix = `${name}=`;
+ const joined = args.findIndex((arg) => arg.startsWith(prefix));
+ if (joined !== -1) return args.splice(joined, 1)[0].slice(prefix.length);
+ return null;
+}
+
+function parseByteSize(value) {
+ const match = /^(\d+(?:\.\d+)?)\s*([kmgt]?i?b)?$/i.exec(value);
+ if (!match) throw new Error(`invalid byte size: ${value}`);
+ const units = { b: 1, kb: 1024, kib: 1024, mb: 1024 ** 2, mib: 1024 ** 2, gb: 1024 ** 3, gib: 1024 ** 3, tb: 1024 ** 4, tib: 1024 ** 4 };
+ return Math.floor(Number(match[1]) * units[(match[2] ?? "b").toLowerCase()]);
+}
+
+async function processTreeResidentBytes(rootPid) {
+ const pending = [rootPid];
+ const seen = new Set();
+ let bytes = 0;
+ while (pending.length) {
+ const pid = pending.pop();
+ if (!Number.isInteger(pid) || seen.has(pid)) continue;
+ seen.add(pid);
+ try {
+ const children = await readFile(`/proc/${pid}/task/${pid}/children`, "utf8");
+ for (const child of children.trim().split(/\s+/)) if (child) pending.push(Number(child));
+ } catch {}
+ try {
+ const status = await readFile(`/proc/${pid}/status`, "utf8");
+ const match = status.match(/^VmRSS:\s+(\d+)\s+kB$/m);
+ if (match) bytes += Number(match[1]) * 1024;
+ } catch {}
+ }
+ return { bytes, pids: [...seen] };
+}
+
+function killProcessTree(pids) {
+ for (const pid of pids.reverse()) {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {}
+ }
+}
diff --git a/scripts/run-qemu-root-smoke.sh b/scripts/run-qemu-root-smoke.sh
new file mode 100755
index 0000000..0aa1790
--- /dev/null
+++ b/scripts/run-qemu-root-smoke.sh
@@ -0,0 +1,153 @@
+#!/bin/sh
+# Boot bnu in a root initramfs guest and exercise privileged file operations.
+# Set BNU_QEMU_KERNEL and BNU_QEMU_INITRAMFS to select a matching host kernel
+# and initramfs. BUN may override the Bun executable.
+set -eu
+
+: "${BNU_QEMU_KERNEL:?set BNU_QEMU_KERNEL to a kernel image}"
+: "${BNU_QEMU_INITRAMFS:?set BNU_QEMU_INITRAMFS to a zstd initramfs image}"
+
+root=$(mktemp -d "${TMPDIR:-/tmp}/bnu-qemu-root.XXXXXX")
+initrd=$(mktemp "${TMPDIR:-/tmp}/bnu-qemu-initramfs.XXXXXX.img")
+serial=$(mktemp "${TMPDIR:-/tmp}/bnu-qemu-serial.XXXXXX.log")
+cleanup() { rm -rf "$root" "$initrd" "$serial"; }
+trap cleanup EXIT HUP INT TERM
+
+repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
+bun_command=${BUN:-bun}
+case "$bun_command" in
+ */*) ;;
+ *) bun_command=$(command -v "$bun_command") ;;
+esac
+bun=$(readlink -f "$bun_command")
+qemu_memory=${BNU_QEMU_MEMORY:-1536M}
+
+mkdir -p "$root"
+if command -v lsinitrd >/dev/null 2>&1; then
+ if ! (cd "$root" && lsinitrd --unpack "$BNU_QEMU_INITRAMFS" >/dev/null 2>&1); then
+ test -e "$root/bin/sh" || { echo "failed to unpack initramfs: $BNU_QEMU_INITRAMFS" >&2; exit 2; }
+ fi
+else
+ case $(file -b "$BNU_QEMU_INITRAMFS") in
+ *Zstandard*) decompressor='zstd -dc' ;;
+ *gzip*) decompressor='gzip -dc' ;;
+ *XZ*) decompressor='xz -dc' ;;
+ *LZ4*) decompressor='lz4 -dc' ;;
+ *cpio*) decompressor=cat ;;
+ *) echo "unsupported initramfs compression: $BNU_QEMU_INITRAMFS" >&2; exit 2 ;;
+ esac
+ if ! (cd "$root" && $decompressor "$BNU_QEMU_INITRAMFS" | cpio -idmu 2>/dev/null); then
+ test -e "$root/bin/sh" || { echo "failed to unpack initramfs: $BNU_QEMU_INITRAMFS" >&2; exit 2; }
+ fi
+fi
+mkdir -p "$root/opt/bnu/bin" "$root/opt/bnu/src" "$root/usr/bin"
+cp "$bun" "$root/usr/bin/bun"
+cp "$repo/bin/bnu.js" "$root/opt/bnu/bin/bnu.js"
+cp "$repo/src/coreutils.js" "$root/opt/bnu/src/coreutils.js"
+
+ldd "$bun" | awk '/=> \/[^ ]+/ { print $3 } /^\// { print $1 }' | while IFS= read -r library; do
+ test -n "$library" || continue
+ mkdir -p "$root$(dirname "$library")"
+ cp -L "$library" "$root$library"
+done
+
+cat >"$root/bnu-qemu-test.sh" <<'EOF'
+#!/bin/sh
+mount -t devtmpfs devtmpfs /dev
+mount -t proc proc /proc
+mount -t sysfs sysfs /sys
+set -eu
+export PATH=/usr/bin:/bin:/usr/sbin:/sbin
+
+echo 'BNU-QEMU: guest-ready'
+sed -n 's/^Uid:.*/BNU-QEMU: &/p' /proc/self/status
+mkdir -p /tmp/bnu-qemu-test/src /tmp/bnu-qemu-test/dst
+printf 'root-owned\n' >/tmp/bnu-qemu-test/src/file
+/usr/bin/bun /opt/bnu/bin/bnu.js chmod 4755 /tmp/bnu-qemu-test/src/file
+stat -c 'BNU-QEMU: source-mode=%a uid=%u gid=%g' /tmp/bnu-qemu-test/src/file
+/usr/bin/bun /opt/bnu/bin/bnu.js cp -p /tmp/bnu-qemu-test/src/file /tmp/bnu-qemu-test/dst/file
+stat -c 'BNU-QEMU: copied-mode=%a uid=%u gid=%g' /tmp/bnu-qemu-test/dst/file
+test "$(stat -c %a /tmp/bnu-qemu-test/dst/file)" = 4755
+/usr/bin/bun /opt/bnu/bin/bnu.js touch /tmp/bnu-qemu-test/src/special-bits
+/usr/bin/bun /opt/bnu/bin/bnu.js chmod 6751 /tmp/bnu-qemu-test/src/special-bits
+/usr/bin/bun /opt/bnu/bin/bnu.js cp -p /tmp/bnu-qemu-test/src/special-bits /tmp/bnu-qemu-test/dst/special-bits
+test "$(stat -c %a /tmp/bnu-qemu-test/src/special-bits)" = "$(stat -c %a /tmp/bnu-qemu-test/dst/special-bits)"
+echo 'BNU-QEMU: special-bits-copy-ok'
+/usr/bin/bun /opt/bnu/bin/bnu.js mkfifo /tmp/bnu-qemu-test/pipe
+test -p /tmp/bnu-qemu-test/pipe && echo 'BNU-QEMU: fifo-ok'
+/usr/bin/bun /opt/bnu/bin/bnu.js mknod /tmp/bnu-qemu-test/null c 1 3
+test -c /tmp/bnu-qemu-test/null && echo 'BNU-QEMU: char-device-ok'
+/usr/bin/bun /opt/bnu/bin/bnu.js chown 123:456 /tmp/bnu-qemu-test/dst/file
+test "$(stat -c %u /tmp/bnu-qemu-test/dst/file)" = 123
+test "$(stat -c %g /tmp/bnu-qemu-test/dst/file)" = 456
+/usr/bin/bun /opt/bnu/bin/bnu.js chgrp 0 /tmp/bnu-qemu-test/dst/file
+test "$(stat -c %g /tmp/bnu-qemu-test/dst/file)" = 0
+/usr/bin/bun /opt/bnu/bin/bnu.js mkdir -p /tmp/bnu-qemu-test/dst/tree/nested
+printf 'nested\n' >/tmp/bnu-qemu-test/dst/tree/nested/file
+ln -s nested/file /tmp/bnu-qemu-test/dst/tree/link
+/usr/bin/bun /opt/bnu/bin/bnu.js chgrp -R 456 /tmp/bnu-qemu-test/dst/tree
+test "$(stat -c %g /tmp/bnu-qemu-test/dst/tree)" = 456
+test "$(stat -c %g /tmp/bnu-qemu-test/dst/tree/nested/file)" = 456
+echo 'BNU-QEMU: recursive-chgrp-ok'
+/usr/bin/bun /opt/bnu/bin/bnu.js chgrp -h 123 /tmp/bnu-qemu-test/dst/tree/link
+test "$(stat -c %g /tmp/bnu-qemu-test/dst/tree/link)" = 123
+echo 'BNU-QEMU: symlink-chgrp-ok'
+/usr/bin/bun /opt/bnu/bin/bnu.js chown --from=123:0 456:789 /tmp/bnu-qemu-test/dst/file
+test "$(stat -c %u /tmp/bnu-qemu-test/dst/file)" = 456
+test "$(stat -c %g /tmp/bnu-qemu-test/dst/file)" = 789
+echo 'BNU-QEMU: conditional-chown-ok'
+/usr/bin/bun /opt/bnu/bin/bnu.js chgrp --from=789 0 /tmp/bnu-qemu-test/dst/file
+test "$(stat -c %g /tmp/bnu-qemu-test/dst/file)" = 0
+echo 'BNU-QEMU: conditional-chgrp-ok'
+/usr/bin/bun /opt/bnu/bin/bnu.js chown 0:1 /tmp/bnu-qemu-test/dst/file
+/usr/bin/bun /opt/bnu/bin/bnu.js chown -v --from=42 43 /tmp/bnu-qemu-test/dst/file >/tmp/bnu-qemu-test/chown-verbose.out
+IFS= read -r chown_verbose < /tmp/bnu-qemu-test/chown-verbose.out
+test "$chown_verbose" = "ownership of '/tmp/bnu-qemu-test/dst/file' retained as root"
+echo 'BNU-QEMU: conditional-chown-verbose-ok'
+/usr/bin/bun /opt/bnu/bin/bnu.js chown 0:1 /tmp/bnu-qemu-test/dst/file
+/usr/bin/bun /opt/bnu/bin/bnu.js chown --from=0:1 2:010 /tmp/bnu-qemu-test/dst/file
+test "$(stat -c %u:%g /tmp/bnu-qemu-test/dst/file)" = 2:10
+/usr/bin/bun /opt/bnu/bin/bnu.js chgrp 1 /tmp/bnu-qemu-test/dst/file
+/usr/bin/bun /opt/bnu/bin/bnu.js chgrp --from=:1 010 /tmp/bnu-qemu-test/dst/file
+test "$(stat -c %g /tmp/bnu-qemu-test/dst/file)" = 10
+echo 'BNU-QEMU: upstream-from-syntax-ok'
+/usr/bin/bun /opt/bnu/bin/bnu.js chown -h 321:654 /tmp/bnu-qemu-test/dst/tree/link
+test "$(stat -c %u /tmp/bnu-qemu-test/dst/tree/link)" = 321
+test "$(stat -c %g /tmp/bnu-qemu-test/dst/tree/link)" = 654
+echo 'BNU-QEMU: symlink-chown-ok'
+date_before=$(/usr/bin/bun /opt/bnu/bin/bnu.js date -u +%s)
+date_target=$((date_before + 2))
+date_set=$(/usr/bin/bun /opt/bnu/bin/bnu.js date -u --set "@$date_target" +%s)
+date_observed=$(/usr/bin/bun /opt/bnu/bin/bnu.js date -u +%s)
+test "$date_set" = "$date_target"
+test "$date_observed" -ge "$date_target"
+test "$date_observed" -le $((date_target + 1))
+echo 'BNU-QEMU: clock-set-ok'
+posix_target=$((date_observed + 2))
+posix_operand=$(/usr/bin/bun /opt/bnu/bin/bnu.js date -u -d "@$posix_target" +%m%d%H%M%Y.%S)
+/usr/bin/bun /opt/bnu/bin/bnu.js date -u "$posix_operand" >/dev/null
+posix_observed=$(/usr/bin/bun /opt/bnu/bin/bnu.js date -u +%s)
+test "$posix_observed" -ge "$posix_target"
+test "$posix_observed" -le $((posix_target + 1))
+echo 'BNU-QEMU: positional-clock-set-ok'
+echo 'BNU-QEMU: ownership-ok'
+echo 'BNU-QEMU: completed'
+poweroff -f
+EOF
+chmod 755 "$root/bnu-qemu-test.sh"
+
+(cd "$root" && find . -print0 | cpio --null -o -H newc | zstd -T1 -3 -f -o "$initrd")
+test -r /dev/kvm && test -w /dev/kvm || {
+ echo '/dev/kvm is not accessible; the QEMU tests do not fall back to software emulation' >&2
+ exit 2
+}
+set -- -enable-kvm -cpu host
+qemu_status=0
+timeout 60s qemu-system-x86_64 "$@" -m "$qemu_memory" -display none -serial "file:$serial" -no-reboot \
+ -kernel "$BNU_QEMU_KERNEL" -initrd "$initrd" -append 'console=ttyS0 rdinit=/bnu-qemu-test.sh' || qemu_status=$?
+if ! rg -q '^BNU-QEMU: completed\r?$' "$serial"; then
+ echo "QEMU exited with status $qemu_status before the smoke test completed" >&2
+ rg 'BNU-QEMU|bnu:|chown:|chgrp:|Kernel panic|not found|error while loading|failed' "$serial" >&2 || :
+ exit 1
+fi
+rg 'BNU-QEMU' "$serial"
diff --git a/scripts/setup-qemu-environments.sh b/scripts/setup-qemu-environments.sh
new file mode 100755
index 0000000..b88fa8c
--- /dev/null
+++ b/scripts/setup-qemu-environments.sh
@@ -0,0 +1,141 @@
+#!/usr/bin/env bash
+# Create the persistent Gentoo guests used by run-gnu-qemu-matrix.sh.
+
+set -Eeuo pipefail
+source "$(cd -- "$(dirname -- "$0")" && pwd)/qemu/common.sh"
+
+only=all
+usage() {
+ cat <<'EOF'
+usage: scripts/setup-qemu-environments.sh [--dry-run] [--only NAME]
+
+NAME is standard, selinux, smack, hurd, or all. The setup is resumable and
+stores downloads and separate qcow2 images below /var/tmp/bnu-qemu by default.
+It never falls back from KVM to software emulation.
+EOF
+}
+while (($#)); do
+ case $1 in
+ --dry-run) BNU_QEMU_DRY_RUN=1 ;;
+ --only) [[ $# -ge 2 ]] || die "--only needs a value"; only=$2; shift ;;
+ -h|--help) usage; exit 0 ;;
+ *) die "unknown argument: $1" ;;
+ esac
+ shift
+done
+[[ $only =~ ^(all|standard|selinux|smack|hurd)$ ]] || die "invalid --only value: $only"
+
+for command in qemu-img qemu-system-x86_64 ssh scp ssh-keygen curl gpg mkfs.ext4; do require_command "$command"; done
+require_kvm
+ensure_state_dir
+
+if [[ $BNU_QEMU_DRY_RUN != 1 ]]; then
+ case $only in
+ hurd) required_gib=3 ;;
+ standard) required_gib=8 ;;
+ selinux) required_gib=20 ;;
+ smack|all) required_gib=30 ;;
+ esac
+ require_free_gib "${BNU_QEMU_MIN_FREE_GIB:-$required_gib}"
+fi
+ensure_ssh_key
+
+case $only in
+ all)
+ run env BNU_QEMU_DIR="$BNU_QEMU_DIR" BNU_QEMU_DRY_RUN="$BNU_QEMU_DRY_RUN" \
+ "$BNU_REPO_ROOT/scripts/qemu/download-images.sh" --only all
+ ;;
+ standard|hurd)
+ run env BNU_QEMU_DIR="$BNU_QEMU_DIR" BNU_QEMU_DRY_RUN="$BNU_QEMU_DRY_RUN" \
+ "$BNU_REPO_ROOT/scripts/qemu/download-images.sh" --only "$([[ $only == standard ]] && printf cloud || printf hurd)"
+ ;;
+ selinux|smack)
+ run env BNU_QEMU_DIR="$BNU_QEMU_DIR" BNU_QEMU_DRY_RUN="$BNU_QEMU_DRY_RUN" \
+ "$BNU_REPO_ROOT/scripts/qemu/download-images.sh" --only cloud
+ run env BNU_QEMU_DIR="$BNU_QEMU_DIR" BNU_QEMU_DRY_RUN="$BNU_QEMU_DRY_RUN" \
+ "$BNU_REPO_ROOT/scripts/qemu/download-images.sh" --only selinux
+ ;;
+esac
+[[ $only == hurd ]] && { note "Hurd image and isolated overlay are ready"; exit 0; }
+
+run env BNU_QEMU_DIR="$BNU_QEMU_DIR" BNU_QEMU_DRY_RUN="$BNU_QEMU_DRY_RUN" \
+ "$BNU_REPO_ROOT/scripts/qemu/build-payload.sh"
+
+cloud=$BNU_QEMU_DIR/cloud/gentoo-cloudinit-amd64.qcow2
+standard=$BNU_QEMU_DIR/standard/gentoo-standard-bnu.qcow2
+seed=$BNU_QEMU_DIR/cloud/bnu-seed.iso
+run mkdir -p -- "$BNU_QEMU_DIR/standard" "$BNU_QEMU_DIR/selinux" "$BNU_QEMU_DIR/smack"
+create_seed_iso "$seed"
+create_overlay "$cloud" "$standard"
+
+if [[ $BNU_QEMU_DRY_RUN == 1 ]]; then
+ note "would provision standard, SELinux MLS, and SMACK guests sequentially"
+ note "each VM would use KVM, $BNU_QEMU_MEMORY RAM, and $BNU_QEMU_CPUS vCPUs"
+ exit 0
+fi
+
+if [[ ! -e $standard.ready ]]; then
+ vm=setup-standard
+ trap 'stop_vm "$vm"' EXIT HUP INT TERM
+ start_vm "$standard" "$vm" "" "$seed"
+ if ! guest_ssh 'test -e /var/lib/bnu-standard-ready'; then
+ guest_scp "$BNU_REPO_ROOT/scripts/qemu/guest/provision-base.sh" [email protected]:/root/provision-base.sh
+ guest_ssh 'chmod 700 /root/provision-base.sh && /root/provision-base.sh && touch /var/lib/bnu-standard-ready'
+ fi
+ stop_vm "$vm"
+ trap - EXIT HUP INT TERM
+ touch "$standard.ready"
+fi
+[[ $only == standard ]] && { note "standard Gentoo guest is ready: $standard"; exit 0; }
+
+selinux=$BNU_QEMU_DIR/selinux/gentoo-selinux-mls-bnu.qcow2
+if [[ ! -e $selinux.ready ]]; then
+ if [[ ! -s $selinux ]]; then run qemu-img create -q -f qcow2 "$selinux" 20G; fi
+ vm=setup-selinux
+ trap 'stop_vm "$vm"' EXIT HUP INT TERM
+ start_vm "$standard" "$vm" "$BNU_QEMU_DIR/bnu-test-payload.ext4" "$seed" "$selinux"
+ guest_scp "$BNU_REPO_ROOT/scripts/qemu/guest/provision-selinux.sh" [email protected]:/root/provision-selinux.sh
+ guest_ssh 'chmod 700 /root/provision-selinux.sh && /root/provision-selinux.sh'
+ stop_vm "$vm"
+ trap - EXIT HUP INT TERM
+
+ # Boot permissive once for the full relabel, then enable enforcing mode.
+ vm=bootstrap-selinux
+ trap 'stop_vm "$vm"' EXIT HUP INT TERM
+ start_vm "$selinux" "$vm"
+ guest_ssh 'sestatus; test "$(getenforce)" = Permissive; sestatus | grep -q "Loaded policy name:[[:space:]]*mls"; setsebool -P allow_execmem on; sed -i "s/^SELINUX=.*/SELINUX=enforcing/" /etc/selinux/config; sed -i "s/[[:space:]]*enforcing=0//g" /etc/default/grub; grub-mkconfig -o /boot/grub/grub.cfg'
+ stop_vm "$vm"
+ trap - EXIT HUP INT TERM
+
+ vm=verify-selinux
+ trap 'stop_vm "$vm"' EXIT HUP INT TERM
+ start_vm "$selinux" "$vm"
+ guest_ssh 'sestatus; test "$(getenforce)" = Enforcing; sestatus | grep -q "Loaded policy name:[[:space:]]*mls"; touch /var/lib/bnu-selinux-ready'
+ stop_vm "$vm"
+ trap - EXIT HUP INT TERM
+ touch "$selinux.ready"
+fi
+[[ $only == selinux ]] && { note "SELinux MLS guest is ready: $selinux"; exit 0; }
+
+smack=$BNU_QEMU_DIR/smack/gentoo-smack-bnu.qcow2
+create_overlay "$selinux" "$smack"
+if [[ ! -e $smack.ready ]]; then
+ vm=setup-smack
+ trap 'stop_vm "$vm"' EXIT HUP INT TERM
+ start_vm "$smack" "$vm"
+ if ! guest_ssh 'test -e /var/lib/bnu-smack'; then
+ guest_scp "$BNU_REPO_ROOT/scripts/qemu/guest/provision-smack.sh" [email protected]:/root/provision-smack.sh
+ guest_ssh 'chmod 700 /root/provision-smack.sh && /root/provision-smack.sh'
+ fi
+ stop_vm "$vm"
+ trap - EXIT HUP INT TERM
+
+ vm=verify-smack
+ trap 'stop_vm "$vm"' EXIT HUP INT TERM
+ start_vm "$smack" "$vm"
+ guest_ssh 'grep -qw smack /sys/kernel/security/lsm; touch /var/lib/bnu-smack-ready'
+ stop_vm "$vm"
+ trap - EXIT HUP INT TERM
+ touch "$smack.ready"
+fi
+note "all requested QEMU environments are ready beneath $BNU_QEMU_DIR"
diff --git a/src/coreutils.js b/src/coreutils.js
new file mode 100644
index 0000000..f8d24df
--- /dev/null
+++ b/src/coreutils.js
@@ -0,0 +1,33625 @@
+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";
+
+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 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 = "") {
+ writeAllSync(2, String(data));
+}
+
+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`);
+ } 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" : "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 = "";
+ const flush = () => {
+ if (plain) {
+ parts.push(`'${plain.replaceAll("'", "'\\''")}'`);
+ plain = "";
+ }
+ };
+ for (const ch of text) {
+ const code = ch.codePointAt(0);
+ if (code < 32 || code === 127) {
+ flush();
+ parts.push(`$'${lsEscapedName(ch)}'`);
+ } else {
+ plain += ch;
+ }
+ }
+ flush();
+ 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) {
+ 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`);
+ if (error.showHelp) stderr(`Try '${program} --help' for more information.\n`);
+ return error.code;
+ }
+ if (error instanceof UsageError) {
+ stderr(`${program}: ${error.message}\n`);
+ 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);
+}
+
+if (import.meta.main) {
+ globalThis[Symbol.for("bnu.cli")] = true;
+ process.exit(await main(Bun.argv.slice(2)));
+}
diff --git a/tests/coreutils.test.js b/tests/coreutils.test.js
new file mode 100644
index 0000000..dea5828
--- /dev/null
+++ b/tests/coreutils.test.js
@@ -0,0 +1,9431 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { createHash } from "node:crypto";
+import { chmod, link, lstat, lutimes, mkdir, mkdtemp, open, readFile, readdir, rename, rm, stat, statfs, symlink, truncate, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { availableParallelism, hostname as osHostname, tmpdir } from "node:os";
+import { pathToFileURL } from "node:url";
+
+let dir;
+
+async function run(args, input = "", options = {}) {
+ const proc = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), ...args], {
+ cwd: options.cwd ?? dir,
+ env: options.env ? { ...process.env, ...options.env } : process.env,
+ stdin: new Blob([input]),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ return {
+ code: await proc.exited,
+ stdout: await new Response(proc.stdout).text(),
+ stderr: await new Response(proc.stderr).text(),
+ };
+}
+
+async function systemRun(args, input = "", options = {}) {
+ const proc = Bun.spawn(args, {
+ cwd: options.cwd ?? dir,
+ env: options.env ? { ...process.env, ...options.env } : process.env,
+ stdin: new Blob([input]),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ return {
+ code: await proc.exited,
+ stdout: await new Response(proc.stdout).text(),
+ stderr: await new Response(proc.stderr).text(),
+ };
+}
+
+function diagnosticQuote(value) {
+ const locale = process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG || "";
+ return /utf-?8/i.test(locale) ? `\u2018${value}\u2019` : `'${value}'`;
+}
+
+async function sampleCommand(args) {
+ const proc = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), ...args], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const reader = proc.stdout.getReader();
+ const { value } = await reader.read();
+ proc.kill("SIGTERM");
+ await proc.exited.catch(() => {});
+ await reader.cancel().catch(() => {});
+ return new TextDecoder().decode(value ?? new Uint8Array());
+}
+
+async function shell(script) {
+ const proc = Bun.spawn(["/bin/sh", "-c", script], {
+ cwd: dir,
+ env: { ...process.env, BNU: join(import.meta.dir, "../bin/bnu.js"), BUN: process.execPath },
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ return {
+ code: await proc.exited,
+ stdout: await new Response(proc.stdout).text(),
+ stderr: await new Response(proc.stderr).text(),
+ };
+}
+
+beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), "bnu-test-"));
+});
+
+afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+test("echo, basename, dirname, pwd", async () => {
+ expect(await run(["echo", "-n", "hello"])).toMatchObject({ code: 0, stdout: "hello" });
+ const rawBasename = await shell(`name=$(printf 'dir/m\\363unt'); "$BUN" "$BNU" basename "$name" | od -An -tx1 | tr -d ' \n'`);
+ expect(rawBasename).toMatchObject({ code: 0, stdout: "6df3756e740a", stderr: "" });
+ const rawDirname = await shell(`name=$(printf 'd\\363r/file'); "$BUN" "$BNU" dirname "$name" | od -An -tx1 | tr -d ' \n'`);
+ expect(rawDirname).toMatchObject({ code: 0, stdout: "64f3720a", stderr: "" });
+ expect(await run(["echo", "-e", "\\x41\\101\\0\\033"])).toMatchObject({ code: 0, stdout: "AA\0\x1b\n" });
+ expect(await run(["echo", "-e", "before\\cafter"])).toMatchObject({ code: 0, stdout: "before" });
+ expect((await run(["echo", "--help"])).stdout).toContain("Usage: echo");
+ expect(await run(["echo", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["echo", "--version", "extra"])).toMatchObject({ code: 0, stdout: "--version extra\n" });
+ expect(await run(["echo", "-n", "-E", "foo\\n"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: "foo\n" });
+ expect(await run(["echo", "-nE", "foo"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: "-nE foo\n" });
+ expect(await run(["echo", "--version"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: "--version\n" });
+ expect(await run(["echo", "-/"])).toMatchObject({ code: 0, stdout: "-/\n" });
+ expect(await run(["echo", "--", "foo"])).toMatchObject({ code: 0, stdout: "-- foo\n" });
+ expect(await run(["true", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: true [ignored command line arguments]\n or: true OPTION\n"), stderr: "" });
+ expect(await run(["true", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["true", "--bad", "--help"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["false", "--version"])).toMatchObject({ code: 1, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["false", "--help"])).toMatchObject({ code: 1, stdout: expect.stringContaining("Usage: false [ignored command line arguments]\n or: false OPTION\n"), stderr: "" });
+ expect(await run(["false", "--version", "extra"])).toMatchObject({ code: 1, stdout: "" });
+ expect(await run(["false", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "" });
+ expect((await run(["yes", "--help"])).stdout).toStartWith("Usage: yes [STRING]...\n or: yes OPTION\n");
+ expect((await run(["yes", "extra", "--help"])).stdout).toStartWith("Usage: yes [STRING]...\n or: yes OPTION\n");
+ expect(await run(["yes", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect((await run(["yes", "--h"])).stdout).toStartWith("Usage: yes [STRING]...\n or: yes OPTION\n");
+ expect((await run(["yes", "extra", "--he"])).stdout).toStartWith("Usage: yes [STRING]...\n or: yes OPTION\n");
+ expect(await run(["yes", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["yes", "extra", "--ver"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["yes", "--h=1"])).toMatchObject({ code: 1, stderr: "yes: option '--help' doesn't allow an argument\nTry 'yes --help' for more information.\n" });
+ expect(await run(["yes", "extra", "--v=1"])).toMatchObject({ code: 1, stderr: "yes: option '--version' doesn't allow an argument\nTry 'yes --help' for more information.\n" });
+ expect(await run(["yes", "--bad", "--help"])).toMatchObject({ code: 1, stderr: "yes: unrecognized option '--bad'\nTry 'yes --help' for more information.\n" });
+ expect(await run(["yes", "extra", "-x", "--help"])).toMatchObject({ code: 1, stderr: "yes: invalid option -- 'x'\nTry 'yes --help' for more information.\n" });
+ expect(await sampleCommand(["yes"])).toStartWith("y\ny\n");
+ expect(await sampleCommand(["yes", "a", "b"])).toStartWith("a b\na b\n");
+ expect(await sampleCommand(["yes", "--", "--help"])).toStartWith("--help\n--help\n");
+ expect(await run(["basename", "/a/b/c.txt", ".txt"])).toMatchObject({ code: 0, stdout: "c\n" });
+ expect(await run(["basename", "/"])).toMatchObject({ code: 0, stdout: "/\n" });
+ expect(await run(["basename", "foo", "foo"])).toMatchObject({ code: 0, stdout: "foo\n" });
+ expect(await run(["basename", "a-a", "-a"])).toMatchObject({ code: 0, stdout: "a\n" });
+ expect(await run(["basename", "a", "b", "c"])).toMatchObject({ code: 1, stderr: `basename: extra operand ${diagnosticQuote("c")}\nTry 'basename --help' for more information.\n` });
+ expect(await run(["basename", "a", "b", "c\nd"])).toMatchObject({ code: 1, stderr: `basename: extra operand ${diagnosticQuote("c\\nd")}\nTry 'basename --help' for more information.\n` });
+ expect((await run(["basename"])).stderr).toContain("Try 'basename --help' for more information.");
+ expect(await run(["basename", "-s"])).toMatchObject({ code: 1, stderr: "basename: option requires an argument -- 's'\nTry 'basename --help' for more information.\n" });
+ expect(await run(["basename", "--suffix"])).toMatchObject({ code: 1, stderr: "basename: option '--suffix' requires an argument\nTry 'basename --help' for more information.\n" });
+ expect(await run(["basename", "--bad"])).toMatchObject({ code: 1, stderr: "basename: unrecognized option '--bad'\nTry 'basename --help' for more information.\n" });
+ expect(await run(["basename", "-s", ".txt", "/a/one.txt", "/b/two.txt"])).toMatchObject({ code: 0, stdout: "one\ntwo\n" });
+ expect(await run(["basename", "--suffix=.txt", "-z", "/a/one.txt", "/b/two.txt"])).toMatchObject({ code: 0, stdout: "one\0two\0" });
+ expect(await run(["basename", "-a", "/a/one", "/b/two"])).toMatchObject({ code: 0, stdout: "one\ntwo\n" });
+ expect(await run(["basename", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: basename NAME [SUFFIX]\n or: basename OPTION... NAME...\n") });
+ expect(await run(["basename", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["basename", "--z", "/a/b"])).toMatchObject({ code: 0, stdout: "b\0" });
+ expect(await run(["basename", "--ze", "/a/b"])).toMatchObject({ code: 0, stdout: "b\0" });
+ expect(await run(["basename", "--m", "/a/one", "/b/two"])).toMatchObject({ code: 0, stdout: "one\ntwo\n" });
+ expect(await run(["basename", "--su", ".txt", "/a/one.txt", "/b/two.txt"])).toMatchObject({ code: 0, stdout: "one\ntwo\n" });
+ expect(await run(["basename", "--z=1", "/a/b"])).toMatchObject({ code: 1, stderr: "basename: option '--zero' doesn't allow an argument\nTry 'basename --help' for more information.\n" });
+ expect(await run(["basename", "--m=1", "foo"])).toMatchObject({ code: 1, stderr: "basename: option '--multiple' doesn't allow an argument\nTry 'basename --help' for more information.\n" });
+ expect(await run(["basename", "foo", "--help"])).toMatchObject({ code: 0, stdout: "foo\n" });
+ expect(await run(["basename", "-s", "--help", "/a/help"])).toMatchObject({ code: 0, stdout: "help\n" });
+ expect(await run(["dirname", "/a/b/c.txt"])).toMatchObject({ code: 0, stdout: "/a/b\n" });
+ expect(await run(["dirname", "//a//"])).toMatchObject({ code: 0, stdout: "/\n" });
+ expect(await run(["dirname", "///a///b"])).toMatchObject({ code: 0, stdout: "///a\n" });
+ expect(await run(["dirname", "///a//b/"])).toMatchObject({ code: 0, stdout: "///a\n" });
+ expect((await run(["dirname"])).stderr).toContain("Try 'dirname --help' for more information.");
+ expect(await run(["dirname", "--bad"])).toMatchObject({ code: 1, stderr: "dirname: unrecognized option '--bad'\nTry 'dirname --help' for more information.\n" });
+ expect(await run(["dirname", "-z", "/a/b/c", "/d/e/f"])).toMatchObject({ code: 0, stdout: "/a/b\0/d/e\0" });
+ expect(await run(["dirname", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: dirname [OPTION] NAME...\n") });
+ expect(await run(["dirname", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["dirname", "--z", "/a/b"])).toMatchObject({ code: 0, stdout: "/a\0" });
+ expect(await run(["dirname", "/a/b", "-z"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: "/a\n.\n" });
+ expect(await run(["dirname", "foo", "--help"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: ".\n.\n", stderr: "" });
+ expect(await run(["dirname", "-z", "foo", "--help"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: ".\0.\0", stderr: "" });
+ expect(await run(["dirname", "--ze", "/a/b"])).toMatchObject({ code: 0, stdout: "/a\0" });
+ expect(await run(["dirname", "--z=1", "/a/b"])).toMatchObject({ code: 1, stderr: "dirname: option '--zero' doesn't allow an argument\nTry 'dirname --help' for more information.\n" });
+ expect(await run(["dirname", "--h=1", "/a/b"])).toMatchObject({ code: 1, stderr: "dirname: option '--help' doesn't allow an argument\nTry 'dirname --help' for more information.\n" });
+ expect(await run(["dirname", "-x", "--help"])).toMatchObject({ code: 1, stderr: "dirname: invalid option -- 'x'\nTry 'dirname --help' for more information.\n" });
+ expect(await run(["dirname", "foo", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: dirname [OPTION] NAME...\n") });
+ expect((await run(["pwd"])).stdout.trim()).toBe(dir);
+ expect((await run(["pwd", "-P"])).stdout.trim()).toBe(dir);
+ expect((await run(["pwd", "--p"])).stdout.trim()).toBe(dir);
+ expect((await run(["pwd", "--ph"])).stdout.trim()).toBe(dir);
+ expect((await run(["pwd", "-L"], "", { env: { PWD: "/definitely/not-here" } })).stdout.trim()).toBe(dir);
+ expect(await run(["pwd", "-L"], "", { env: { PWD: `${dir}/.` } })).toMatchObject({ code: 0, stdout: `${dir}\n` });
+ expect(await run(["pwd", "--l"], "", { env: { PWD: `${dir}/.` } })).toMatchObject({ code: 0, stdout: `${dir}\n` });
+ expect(await run(["pwd", "--lo"], "", { env: { PWD: `${dir}/.` } })).toMatchObject({ code: 0, stdout: `${dir}\n` });
+ expect(await run(["pwd", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: pwd [OPTION]...\n") });
+ expect(await run(["pwd", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["pwd", "--l=1"])).toMatchObject({ code: 1, stderr: "pwd: option '--logical' doesn't allow an argument\nTry 'pwd --help' for more information.\n" });
+ expect(await run(["pwd", "--p=1"])).toMatchObject({ code: 1, stderr: "pwd: option '--physical' doesn't allow an argument\nTry 'pwd --help' for more information.\n" });
+ expect(await run(["pwd", "--bad", "--help"])).toMatchObject({ code: 1, stderr: "pwd: unrecognized option '--bad'\nTry 'pwd --help' for more information.\n" });
+ expect(await run(["pwd", "-x", "--help"])).toMatchObject({ code: 1, stderr: "pwd: invalid option -- 'x'\nTry 'pwd --help' for more information.\n" });
+ await mkdir(join(dir, "pwd-real"));
+ await symlink("pwd-real", join(dir, "pwd-link"));
+ expect(await run(["pwd"], "", { cwd: join(dir, "pwd-real"), env: { PWD: join(dir, "pwd-link"), POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: `${join(dir, "pwd-link")}\n` });
+ expect(await run(["pwd", "-LP"], "", { cwd: join(dir, "pwd-real"), env: { PWD: join(dir, "pwd-link"), POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: `${join(dir, "pwd-real")}\n` });
+ expect(await run(["pwd", "-PL"], "", { cwd: join(dir, "pwd-real"), env: { PWD: join(dir, "pwd-link"), POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: `${join(dir, "pwd-link")}\n` });
+ expect(await run(["pwd", "--physical", "--logical"], "", { cwd: join(dir, "pwd-real"), env: { PWD: join(dir, "pwd-link"), POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: `${join(dir, "pwd-link")}\n` });
+ expect(await run(["pwd"], "", { env: { BNU_LONG_PWD: `${dir}/long-wrapper-pwd` } })).toMatchObject({ code: 0, stdout: `${dir}/long-wrapper-pwd\n` });
+ expect(await run(["pwd", "extra"])).toMatchObject({ code: 0, stdout: `${dir}\n`, stderr: "pwd: ignoring non-option arguments\n" });
+ const yesFull = Bun.spawn(["/bin/sh", "-c", `${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} yes >/dev/full`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await yesFull.exited).toBe(1);
+ expect(await new Response(yesFull.stderr).text()).toBe("yes: standard output: No space left on device\n");
+ const yesPipe = Bun.spawn(["/bin/sh", "-c", `${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} yes | head -n1`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await yesPipe.exited).toBe(0);
+ expect(await new Response(yesPipe.stdout).text()).toBe("y\n");
+ expect(await new Response(yesPipe.stderr).text()).toBe("");
+});
+
+test("cat, wc, head, tail operate on files and stdin", async () => {
+ await writeFile(join(dir, "in.txt"), "one\ntwo\nthree\n");
+ await mkdir(join(dir, "stream-dir"));
+ expect(await run(["cat", "-n", "in.txt"])).toMatchObject({ code: 0, stdout: " 1\tone\n 2\ttwo\n 3\tthree\n" });
+ expect(await run(["cat", "--n"], "a\n")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "cat: option '--n' is ambiguous; possibilities: '--number-nonblank' '--number'\nTry 'cat --help' for more information.\n",
+ });
+ expect(await run(["cat", "--number-n"], "a\n\n")).toMatchObject({ code: 0, stdout: " 1\ta\n\n" });
+ expect(await run(["cat", "--s"], "a\n")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "cat: option '--s' is ambiguous; possibilities: '--squeeze-blank' '--show-nonprinting' '--show-ends' '--show-tabs' '--show-all'\nTry 'cat --help' for more information.\n",
+ });
+ expect(await run(["cat", "--squeeze"], "a\n\n\nb\n")).toMatchObject({ code: 0, stdout: "a\n\nb\n" });
+ const catHelp = await run(["cat", "--help"]);
+ expect(catHelp).toMatchObject({ code: 0 });
+ expect(catHelp.stdout).toContain(" -e\n");
+ expect(catHelp.stdout).toContain(" -t\n");
+ expect(await run(["cat", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "cat: unrecognized option '--bad'\nTry 'cat --help' for more information.\n" });
+ expect(await run(["cat", "--version=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "cat: option '--version' doesn't allow an argument\nTry 'cat --help' for more information.\n" });
+ expect(await run(["cat", "-u", "in.txt"])).toMatchObject({ code: 0, stdout: "one\ntwo\nthree\n" });
+ expect(await run(["cat", "cat-missing-a", "in.txt", "cat-missing-b"])).toMatchObject({ code: 1, stdout: "one\ntwo\nthree\n", stderr: "cat: cat-missing-a: No such file or directory\ncat: cat-missing-b: No such file or directory\n" });
+ expect(await run(["cat", "missing'cat", "in.txt", "missing\ncat"])).toMatchObject({ code: 1, stdout: "one\ntwo\nthree\n", stderr: "cat: \"missing'cat\": No such file or directory\ncat: 'missing'$'\\n''cat': No such file or directory\n" });
+ expect(await run(["cat", "stream-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "cat: stream-dir: Is a directory\n" });
+ await mkdir(join(dir, "dir'cat"));
+ expect(await run(["cat", "dir'cat"])).toMatchObject({ code: 1, stdout: "", stderr: "cat: \"dir'cat\": Is a directory\n" });
+ await symlink("loop'cat", join(dir, "loop'cat"));
+ expect(await run(["cat", "loop'cat"])).toMatchObject({ code: 1, stdout: "", stderr: "cat: \"loop'cat\": Too many levels of symbolic links\n" });
+ expect(await run(["cat", "-e"], "a\tb\n")).toMatchObject({ code: 0, stdout: "a\tb$\n" });
+ expect(await run(["cat", "-t"], "a\tb\n")).toMatchObject({ code: 0, stdout: "a^Ib\n" });
+ expect(await run(["cat", "-v"], "a\u0001\u007f\n")).toMatchObject({ code: 0, stdout: "a^A^?\n" });
+ await writeFile(join(dir, "cat-raw"), Uint8Array.of(0xff, 0x0a));
+ const catRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "cat", "cat-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "cat-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await catRaw.exited).toBe(0);
+ expect(await new Response(catRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "cat-raw-out"))]).toEqual([0xff, 0x0a]);
+ expect(await run(["cat", "-v", "cat-raw"], "", { env: { LC_ALL: "C" } })).toMatchObject({ code: 0, stdout: "M-^?\n" });
+ const catRawNumbered = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "cat", "-n", "cat-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "cat-raw-numbered-out")),
+ stderr: "pipe",
+ });
+ expect(await catRawNumbered.exited).toBe(0);
+ expect(await new Response(catRawNumbered.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "cat-raw-numbered-out"))]).toEqual([0x20, 0x20, 0x20, 0x20, 0x20, 0x31, 0x09, 0xff, 0x0a]);
+ expect(await run(["cat", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Concatenate FILE(s) to standard output.\n") });
+ expect(await run(["cat", "-E"], "a\rb\r\nc\n\r\nd\r")).toMatchObject({ code: 0, stdout: "a\rb^M$\nc$\n^M$\nd\r" });
+ await writeFile(join(dir, "cr-left"), "1\r");
+ await writeFile(join(dir, "cr-right"), "\n2\r\n");
+ expect(await run(["cat", "-E", "cr-left", "cr-right"])).toMatchObject({ code: 0, stdout: "1^M$\n2^M$\n" });
+ await writeFile(join(dir, "cat-self"), "x\n");
+ const appendSelf = Bun.spawn(["/bin/sh", "-c", `${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} cat cat-self >>cat-self`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await appendSelf.exited).toBe(1);
+ expect(await readFile(join(dir, "cat-self"), "utf8")).toBe("x\n");
+ await writeFile(join(dir, "cat-doc"), "x\n");
+ await writeFile(join(dir, "cat-doc-end"), "y\n");
+ const truncateSelf = Bun.spawn(["/bin/sh", "-c", `${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} cat cat-doc cat-doc-end >cat-doc`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await truncateSelf.exited).toBe(0);
+ expect(await readFile(join(dir, "cat-doc"), "utf8")).toBe("y\n");
+ expect(await run(["mkfifo", "cat-fifo"])).toMatchObject({ code: 0 });
+ const catBuf = Bun.spawn(["/bin/sh", "-c", `${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} dd count=1 if=cat-fifo status=none >cat-out & pid=$!; (printf '1\\n'; sleep 1; printf '2\\n') | ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} cat -v >cat-fifo; wait $pid`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await catBuf.exited).toBe(0);
+ expect(await readFile(join(dir, "cat-out"), "utf8")).toBe("1\n");
+ expect((await run(["wc", "in.txt"])).stdout).toContain(" 3 3 14 in.txt\n");
+ expect(await run(["wc", "--debug", "in.txt"])).toMatchObject({ code: 0, stdout: " 3 3 14 in.txt\n", stderr: "" });
+ await writeFile(join(dir, "wc-empty"), "");
+ expect(await run(["wc", "wc-empty"])).toMatchObject({ code: 0, stdout: "0 0 0 wc-empty\n" });
+ expect(await run(["wc", "/dev/null"])).toMatchObject({ code: 0, stdout: " 0 0 0 /dev/null\n" });
+ const wcFiles0Raw = Bun.spawn(["/bin/sh", "-c", `name=$(printf 'wc-\\377'); printf 'payload\\n' > "$name"; printf '%s\\0' "$name" > wc-files0-raw; LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} wc -c --files0-from=wc-files0-raw >wc-files0-raw-out`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await wcFiles0Raw.exited).toBe(0);
+ expect(await new Response(wcFiles0Raw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "wc-files0-raw-out"))]).toEqual([0x38, 0x20, 0x77, 0x63, 0x2d, 0xff, 0x0a]);
+ expect(await run(["wc", "--b"], "abc\n")).toMatchObject({ code: 0, stdout: "4\n" });
+ expect(await run(["wc", "--max"], "ab\n")).toMatchObject({ code: 0, stdout: "2\n" });
+ expect(await run(["wc", "--bad", "--help"], "abc\n")).toMatchObject({ code: 1, stdout: "", stderr: "wc: unrecognized option '--bad'\nTry 'wc --help' for more information.\n" });
+ expect(await run(["wc", "--b=1"], "abc\n")).toMatchObject({ code: 1, stdout: "", stderr: "wc: option '--bytes' doesn't allow an argument\nTry 'wc --help' for more information.\n" });
+ expect(await run(["wc", "--v=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "wc: option '--version' doesn't allow an argument\nTry 'wc --help' for more information.\n" });
+ expect(await run(["wc", "missing-wc-file", "--help"], "abc\n")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: wc [OPTION]... [FILE]...\n or: wc [OPTION]... --files0-from=F\n"), stderr: "" });
+ expect(await run(["wc", "missing-wc-file", "--version"], "abc\n")).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["wc", "--total", "--help"], "abc\n")).toMatchObject(await systemRun(["wc", "--total", "--help"], "abc\n"));
+ expect(await run(["wc", "--total=bad", "in.txt"])).toMatchObject(await systemRun(["wc", "--total=bad", "in.txt"]));
+ expect(await run(["wc", "--total=bad", "--help"])).toMatchObject(await systemRun(["wc", "--total=bad", "--help"]));
+ expect(await run(["wc", "--total=bad\nx", "in.txt"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `wc: invalid argument ${diagnosticQuote("bad\\nx")} for ${diagnosticQuote("--total")}\nValid arguments are:\n - ${diagnosticQuote("auto")}\n - ${diagnosticQuote("always")}\n - ${diagnosticQuote("only")}\n - ${diagnosticQuote("never")}\nTry 'wc --help' for more information.\n`,
+ });
+ expect(await run(["wc", "--total=", "in.txt"])).toMatchObject(await systemRun(["wc", "--total=", "in.txt"]));
+ expect(await run(["wc", "--total=", "--help"])).toMatchObject(await systemRun(["wc", "--total=", "--help"]));
+ expect(await run(["wc", "--total=only", "--help"], "abc\n")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: wc [OPTION]... [FILE]...\n or: wc [OPTION]... --files0-from=F\n") });
+ expect(await run(["truncate", "-s", "9007199254740993", "wc-huge-size"])).toMatchObject({ code: 0 });
+ expect(await run(["wc", "-c", "--total=only", "wc-huge-size"])).toMatchObject({ code: 0, stdout: "9007199254740993\n" });
+ expect(await run(["wc", "wc-missing-a", "in.txt", "wc-missing-b"])).toMatchObject({ code: 1, stdout: " 3 3 14 in.txt\n 3 3 14 total\n", stderr: "wc: wc-missing-a: No such file or directory\nwc: wc-missing-b: No such file or directory\n" });
+ expect(await run(["wc", "missing'wc"])).toMatchObject({ code: 1, stdout: "", stderr: "wc: \"missing'wc\": No such file or directory\n" });
+ expect(await run(["wc", "stream-dir"])).toMatchObject({ code: 1, stdout: " 0 0 0 stream-dir\n", stderr: "wc: stream-dir: Is a directory\n" });
+ expect(await run(["wc", "stream-dir", "in.txt"])).toMatchObject({ code: 1, stdout: " 0 0 0 stream-dir\n 3 3 14 in.txt\n 3 3 14 total\n", stderr: "wc: stream-dir: Is a directory\n" });
+ await mkdir(join(dir, "wc'dir"));
+ expect(await run(["wc", "wc'dir"])).toMatchObject({ code: 1, stdout: " 0 0 0 wc'dir\n", stderr: "wc: \"wc'dir\": Is a directory\n" });
+ await symlink("wc-loop", join(dir, "wc-loop"));
+ expect(await run(["wc", "wc-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "wc: wc-loop: Too many levels of symbolic links\n" });
+ await mkdir(join(dir, "wc-list-dir"));
+ expect(await run(["wc", "--files0-from=wc-list-dir"])).toMatchObject(await systemRun(["/usr/bin/wc", "--files0-from=wc-list-dir"]));
+ expect(await run(["wc", "--files0-from=missing\nwc-list"])).toMatchObject({ code: 1, stdout: "", stderr: "wc: cannot open 'missing'$'\\n''wc-list' for reading: No such file or directory\n" });
+ await mkdir(join(dir, "wc\nlist-dir"));
+ expect(await run(["wc", "--files0-from=wc\nlist-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "wc: 'wc'$'\\n''list-dir': read error: Is a directory\n" });
+ await writeFile(join(dir, "wc'list"), "\0");
+ expect(await run(["wc", "--files0-from=wc'list"])).toMatchObject({ code: 1, stdout: "", stderr: "wc: \"wc'list\":1: invalid zero-length file name\n" });
+ expect(await run(["head", "-n", "2", "in.txt"])).toMatchObject({ code: 0, stdout: "one\ntwo\n" });
+ await writeFile(join(dir, "head-tail-raw"), Uint8Array.of(0xff, 0x0a, 0x61, 0x0a));
+ const headRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "head", "-n1", "head-tail-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "head-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await headRaw.exited).toBe(0);
+ expect(await new Response(headRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "head-raw-out"))]).toEqual([0xff, 0x0a]);
+ expect(await run(["head", "head-missing-a", "in.txt", "head-missing-b"])).toMatchObject({ code: 1, stdout: "==> in.txt <==\none\ntwo\nthree\n", stderr: "head: cannot open 'head-missing-a' for reading: No such file or directory\nhead: cannot open 'head-missing-b' for reading: No such file or directory\n" });
+ expect(await run(["head", "missing'head"])).toMatchObject({ code: 1, stdout: "", stderr: "head: cannot open \"missing'head\" for reading: No such file or directory\n" });
+ expect(await run(["head", "missing\nhead"])).toMatchObject({ code: 1, stdout: "", stderr: "head: cannot open 'missing'$'\\n''head' for reading: No such file or directory\n" });
+ expect(await run(["head", "stream-dir", "in.txt"])).toMatchObject({ code: 1, stdout: "==> stream-dir <==\n\n==> in.txt <==\none\ntwo\nthree\n", stderr: "head: error reading 'stream-dir': Is a directory\n" });
+ await mkdir(join(dir, "head'dir"));
+ expect(await run(["head", "head'dir"])).toMatchObject({ code: 1, stdout: "", stderr: "head: error reading \"head'dir\": Is a directory\n" });
+ await symlink("head-loop", join(dir, "head-loop"));
+ expect(await run(["head", "head-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "head: cannot open 'head-loop' for reading: Too many levels of symbolic links\n" });
+ expect(await run(["head", "--l=2"], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: "a\nb\n" });
+ expect(await run(["head", "--b=2"], "abc")).toMatchObject({ code: 0, stdout: "ab" });
+ expect(await run(["head", "--s"], "a\n")).toMatchObject({ code: 0, stdout: "a\n" });
+ expect(await run(["head", "--bad", "--help"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: "head: unrecognized option '--bad'\nTry 'head --help' for more information.\n" });
+ expect(await run(["head", "--q=1"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: "head: option '--quiet' doesn't allow an argument\nTry 'head --help' for more information.\n" });
+ expect(await run(["head", "--version=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "head: option '--version' doesn't allow an argument\nTry 'head --help' for more information.\n" });
+ expect(await run(["head", "--lines", "--help"], "a\n")).toMatchObject(await systemRun(["/usr/bin/head", "--lines", "--help"], "a\n"));
+ expect(await run(["head", "--lines", "--help", "--version"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of lines: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["head", "--bytes", "--help", "--version"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of bytes: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["head", "-n", "--help", "--version"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of lines: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["head", "-n--help", "--version"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of lines: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["head", "-c", "--help", "--version"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of bytes: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["head", "-c--help", "--version"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of bytes: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["head", "--lines=1", "--help"], "a\n")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: head [OPTION]... [FILE]...\n") });
+ expect(await run(["head", "--lines=bad", "--help"], "a\n")).toMatchObject(await systemRun(["/usr/bin/head", "--lines=bad", "--help"], "a\n"));
+ expect(await run(["head", "--bytes=bad", "--help"], "abc")).toMatchObject(await systemRun(["/usr/bin/head", "--bytes=bad", "--help"], "abc"));
+ expect(await run(["head", "in.txt", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: head [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["head", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Print the first 10 lines of each FILE to standard output.\n") });
+ expect(await run(["head", "-q", "-v", "in.txt"])).toMatchObject({ code: 0, stdout: "==> in.txt <==\none\ntwo\nthree\n" });
+ expect(await run(["head", "-v", "-q", "in.txt"])).toMatchObject({ code: 0, stdout: "one\ntwo\nthree\n" });
+ expect(await run(["head", "in.txt", "-qv"])).toMatchObject({ code: 0, stdout: "==> in.txt <==\none\ntwo\nthree\n" });
+ expect(await run(["tail", "-n", "1", "in.txt"])).toMatchObject({ code: 0, stdout: "three\n" });
+ const tailRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "-n+1", "head-tail-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "tail-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await tailRaw.exited).toBe(0);
+ expect(await new Response(tailRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "tail-raw-out"))]).toEqual([0xff, 0x0a, 0x61, 0x0a]);
+ expect(await run(["tail", "--l=2"], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: "b\nc\n" });
+ expect(await run(["tail", "--b=2"], "abc")).toMatchObject({ code: 0, stdout: "bc" });
+ expect(await run(["tail", "--bad", "--help"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: "tail: unrecognized option '--bad'\nTry 'tail --help' for more information.\n" });
+ expect(await run(["tail", "--s=0.1", "--pid=999999999", "-f", "/dev/null"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "tail: option '--s=0.1' is ambiguous; possibilities: '--silent' '--sleep-interval'\nTry 'tail --help' for more information.\n",
+ });
+ expect(await run(["tail", "--ver=foo"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "tail: option '--ver=foo' is ambiguous; possibilities: '--verbose' '--version'\nTry 'tail --help' for more information.\n",
+ });
+ expect(await run(["tail", "--sleep", "--help", "/dev/null"])).toMatchObject(await systemRun(["tail", "--sleep", "--help", "/dev/null"]));
+ expect(await run(["tail", "--sleep=0.1", "--help", "/dev/null"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tail [OPTION]... [FILE]...\n") });
+ expect(await run(["tail", "--lines", "--help", "--version"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of lines: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["tail", "--bytes", "--help", "--version"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of bytes: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["tail", "-n", "--help", "--version"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of lines: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["tail", "-n--help", "--version"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of lines: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["tail", "-c", "--help", "--version"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of bytes: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["tail", "-c--help", "--version"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of bytes: ${diagnosticQuote("-help")}\n` });
+ expect(await run(["tail", "--lines=bad", "--help"], "a\n")).toMatchObject(await systemRun(["tail", "--lines=bad", "--help"], "a\n"));
+ expect(await run(["tail", "--bytes=bad", "--help"], "abc")).toMatchObject(await systemRun(["tail", "--bytes=bad", "--help"], "abc"));
+ expect(await run(["tail", "--pid=bad", "--help"], "abc")).toMatchObject(await systemRun(["tail", "--pid=bad", "--help"], "abc"));
+ expect(await run(["tail", "--pid", "--help", "--version"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid PID: ${diagnosticQuote("--help")}\n` });
+ expect(await run(["tail", "in.txt", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["tail", "--follow=", "--help", "/dev/null"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `tail: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--follow")}\nValid arguments are:\n - ${diagnosticQuote("descriptor")}\n - ${diagnosticQuote("name")}\nTry 'tail --help' for more information.\n`,
+ });
+ expect(await run(["tail", "--follow=bad", "--help", "/dev/null"])).toMatchObject(await systemRun(["tail", "--follow=bad", "--help", "/dev/null"]));
+ expect(await run(["tail", "--follow=name", "--help", "/dev/null"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tail [OPTION]... [FILE]...\n") });
+ expect(await run(["tail", "stream-dir", "in.txt"])).toMatchObject({ code: 1, stdout: "==> stream-dir <==\n\n==> in.txt <==\none\ntwo\nthree\n", stderr: "tail: error reading 'stream-dir': Is a directory\n" });
+ expect(await run(["tail", "missing'tail"])).toMatchObject({ code: 1, stdout: "", stderr: "tail: cannot open \"missing'tail\" for reading: No such file or directory\n" });
+ expect(await run(["tail", "missing\ntail"])).toMatchObject({ code: 1, stdout: "", stderr: "tail: cannot open 'missing'$'\\n''tail' for reading: No such file or directory\n" });
+ await mkdir(join(dir, "tail'dir"));
+ expect(await run(["tail", "tail'dir"])).toMatchObject({ code: 1, stdout: "", stderr: "tail: error reading \"tail'dir\": Is a directory\n" });
+ await symlink("tail-loop", join(dir, "tail-loop"));
+ expect(await run(["tail", "tail-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "tail: cannot open 'tail-loop' for reading: Too many levels of symbolic links\n" });
+ expect(await run(["tail", "-q", "-v", "in.txt"])).toMatchObject({ code: 0, stdout: "==> in.txt <==\none\ntwo\nthree\n" });
+ expect(await run(["tail", "-v", "-q", "in.txt"])).toMatchObject({ code: 0, stdout: "one\ntwo\nthree\n" });
+ expect(await run(["tail", "in.txt", "-qv"])).toMatchObject({ code: 0, stdout: "==> in.txt <==\none\ntwo\nthree\n" });
+ expect(await run(["tail", "--debug", "-n", "1", "in.txt"])).toMatchObject({ code: 0, stdout: "three\n" });
+ const tailHelp = (await run(["tail", "--help"])).stdout;
+ expect(tailHelp).toContain("Print the last 10 lines of each FILE to standard output.\n");
+ for (const option of ["-F", "-f"]) expect(tailHelp).toContain(` ${option}\n`);
+ expect(await run(["tail", "-s.1", "-n", "1", "in.txt"])).toMatchObject({ code: 0, stdout: "three\n", stderr: "" });
+ expect(await run(["tail", "--sleep-interval=.1", "-n", "1", "in.txt"])).toMatchObject({ code: 0, stdout: "three\n", stderr: "" });
+ expect(await run(["tail", "--sleep-interval=bad", "in.txt"])).toMatchObject(await systemRun(["tail", "--sleep-interval=bad", "in.txt"]));
+ expect(await run(["tail", "--sleep-interval=1\n2", "in.txt"])).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of seconds: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["tail", "--pid=bad", "-f", "in.txt"])).toMatchObject(await systemRun(["tail", "--pid=bad", "-f", "in.txt"]));
+ expect(await run(["tail", "--pid=1\n2", "-f", "in.txt"])).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid PID: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["tail", "--max-unchanged-stats=bad", "-f", "in.txt"])).toMatchObject(await systemRun(["tail", "--max-unchanged-stats=bad", "-f", "in.txt"]));
+ expect(await run(["tail", "--max-unchanged-stats=1\n2", "-f", "in.txt"])).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid maximum number of unchanged stats between opens: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["head", "-2", "in.txt"])).toMatchObject({ code: 0, stdout: "one\ntwo\n" });
+ expect(await run(["head", "-1c"], "abc")).toMatchObject({ code: 0, stdout: "a" });
+ expect(await run(["head", "--bytes=bad", "in.txt"])).toMatchObject(await systemRun(["/usr/bin/head", "--bytes=bad", "in.txt"]));
+ expect(await run(["head", "--lines=bad", "in.txt"])).toMatchObject(await systemRun(["/usr/bin/head", "--lines=bad", "in.txt"]));
+ expect(await run(["head", "-14c"], "1234567890abcdefg")).toMatchObject({ code: 0, stdout: "1234567890abcd" });
+ expect((await run(["head", "-2b"], "x".repeat(2000))).stdout.length).toBe(1024);
+ expect((await run(["head", "-1k"], "x".repeat(2000))).stdout.length).toBe(1024);
+ expect(await run(["head", "-n", "1B"], "a\nb\n")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of lines: ${diagnosticQuote("1B")}\n` });
+ expect(await run(["head", "-n", "1\n2"], "a\nb\n")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of lines: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["head", "-c", "1B"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of bytes: ${diagnosticQuote("1B")}\n` });
+ expect(await run(["head", "-c", "1\n2"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `head: invalid number of bytes: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["head", "-n", "1R"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\nb\n" });
+ expect(await run(["head", "-n", "1QB"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\nb\n" });
+ expect((await run(["head", "-c", "1kB"], "x".repeat(1500))).stdout.length).toBe(1000);
+ expect((await run(["head", "-c", "1kiB"], "x".repeat(1500))).stdout.length).toBe(1024);
+ expect(await run(["head", "-c", "1EiB"], "abc")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["head", "-c", "1YB"], "abc")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["head", "-c", "1R"], "abc")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["head", "-c", "1QB"], "abc")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["head", "-c", "1e"], "abc")).toMatchObject(await systemRun(["/usr/bin/head", "-c", "1e"], "abc"));
+ expect(await run(["head", "--bytes=-2", "---presume-input-pipe"], "abc")).toMatchObject({ code: 0, stdout: "a" });
+ expect(await run(["head", "--lines=-1", "---presume-input-pipe"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\n" });
+ expect(await run(["tail", "-2", "in.txt"])).toMatchObject({ code: 0, stdout: "two\nthree\n" });
+ expect(await run(["tail", "+2c"], "abcd")).toMatchObject({ code: 0, stdout: "bcd" });
+ expect(await run(["tail", "-n", "1B"], "a\nb\n")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of lines: ${diagnosticQuote("1B")}\n` });
+ expect(await run(["tail", "-n", "1\n2"], "a\nb\n")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of lines: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["tail", "-c", "1B"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of bytes: ${diagnosticQuote("1B")}\n` });
+ expect(await run(["tail", "-c", "1\n2"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `tail: invalid number of bytes: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["tail", "-n", "1R"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\nb\n" });
+ expect(await run(["tail", "-n", "1QB"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\nb\n" });
+ expect((await run(["tail", "-c", "1kB"], "x".repeat(1500))).stdout.length).toBe(1000);
+ expect((await run(["tail", "-c", "1kiB"], "x".repeat(1500))).stdout.length).toBe(1024);
+ expect(await run(["tail", "-c", "1EiB"], "abc")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["tail", "-c", "1YB"], "abc")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["tail", "-c", "1R"], "abc")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["tail", "-c", "1QB"], "abc")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["tail", "-c", "1e"], "abc")).toMatchObject(await systemRun(["/usr/bin/tail", "-c", "1e"], "abc"));
+ expect(await run(["tail", "-1l"], "one\ntwo\n")).toMatchObject({ code: 0, stdout: "two\n" });
+ expect(await run(["tail", "+2l"], "one\ntwo\n")).toMatchObject({ code: 0, stdout: "two\n" });
+ expect(await run(["tail", "+c"], "x" + "y".repeat(10) + "z")).toMatchObject({ code: 0, stdout: "yyz" });
+ expect(await run(["tail", "+l"], "x\n" + "y\n".repeat(10) + "z")).toMatchObject({ code: 0, stdout: "y\ny\nz" });
+ expect(await run(["tail", "-l"], "x\n" + "y\n".repeat(10) + "z")).toMatchObject({ code: 0, stdout: "y\n".repeat(9) + "z" });
+ expect((await run(["tail", "-b"], "x\n".repeat(512 * 10 / 2 + 1))).stdout.length).toBe(512 * 10);
+ const headLinePipe = Bun.spawn(["/bin/sh", "-c", `printf 'a\\nb\\n' | (${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} head -n 1 >/dev/null; cat)`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await headLinePipe.exited).toBe(0);
+ expect(await new Response(headLinePipe.stdout).text()).toBe("b\n");
+ await writeFile(join(dir, "head-seek-lines"), "a\nb\nc\n");
+ const headSeekLines = Bun.spawn(["/bin/sh", "-c", `(${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} head -n -1 >/dev/null; cat) < head-seek-lines`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await headSeekLines.exited).toBe(0);
+ expect(await new Response(headSeekLines.stdout).text()).toBe("c\n");
+ const headBytePipe = Bun.spawn(["/bin/sh", "-c", `printf 'abc\\ndef\\n' | (${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} dd bs=1 skip=1 count=0 status=none; ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} head -c-4)`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await headBytePipe.exited).toBe(0);
+ expect(await new Response(headBytePipe.stdout).text()).toBe("bc\n");
+ await writeFile(join(dir, "head-seek-bytes"), "abcdef");
+ const headSeekBytes = Bun.spawn(["/bin/sh", "-c", `(${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} head -c -2 >/dev/null; cat) < head-seek-bytes`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await headSeekBytes.exited).toBe(0);
+ expect(await new Response(headSeekBytes.stdout).text()).toBe("ef");
+ const headFull = Bun.spawn(["/bin/sh", "-c", `printf 'abc\\n' | ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} head --lines=-0 >/dev/full`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await headFull.exited).toBe(1);
+ expect(await new Response(headFull.stderr).text()).toBe("head: error writing 'standard output': No space left on device\n");
+ expect(await run(["tail", "-n", "0", "in.txt"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["tail", "-n", "+0", "in.txt"])).toMatchObject({ code: 0, stdout: "one\ntwo\nthree\n" });
+ expect(await run(["tail", "-n", "-0", "in.txt"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["tail", "+2", "in.txt"])).toMatchObject({ code: 0, stdout: "two\nthree\n" });
+ await writeFile(join(dir, "nul.txt"), "one\0two\0three\0");
+ expect(await run(["head", "-z", "-n", "2", "nul.txt"])).toMatchObject({ code: 0, stdout: "one\0two\0" });
+ expect(await run(["tail", "--zero-terminated", "-n", "2", "nul.txt"])).toMatchObject({ code: 0, stdout: "two\0three\0" });
+ expect(await run(["tail", "-f", "-c3", "-", "tail-missing"], "bar\n")).toMatchObject({
+ code: 1,
+ stdout: "==> standard input <==\nar\n",
+ stderr: "tail: cannot open 'tail-missing' for reading: No such file or directory\ntail: no files remaining\n",
+ });
+ await writeFile(join(dir, "tail-pipe-source"), "==> standard input <==\nar\n");
+ const tailPipe = Bun.spawn(["/bin/bash", "-lc", `/usr/bin/timeout 2s ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} tail -n2 -f tail-pipe-source | /usr/bin/head -n2 > tail-pipe-out; printf '%s\\n' "\${PIPESTATUS[0]}" > tail-pipe-status`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await tailPipe.exited).toBe(0);
+ expect(await readFile(join(dir, "tail-pipe-status"), "utf8")).toBe("0\n");
+ expect(await readFile(join(dir, "tail-pipe-out"), "utf8")).toBe("==> standard input <==\nar\n");
+ await writeFile(join(dir, "tail-follow"), "seed\n");
+ const tailFollow = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "--sleep=0.2", "-n", "0", "-f", "tail-follow"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await Promise.race([tailFollow.exited.then(() => "exited"), Bun.sleep(150).then(() => "running")])).toBe("running");
+ tailFollow.kill("SIGTERM");
+ await tailFollow.exited.catch(() => {});
+ expect(await new Response(tailFollow.stdout).text()).toBe("");
+ expect(await new Response(tailFollow.stderr).text()).toBe("");
+ await writeFile(join(dir, "tail-pid"), "");
+ const tailPidSleeper = Bun.spawn(["/bin/sh", "-c", "sleep 2"], { cwd: dir, stdout: "ignore", stderr: "ignore" });
+ const tailPid = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "-f", "--sleep=0.1", `--pid=${tailPidSleeper.pid}`, "tail-pid"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await Promise.race([tailPid.exited.then(() => "exited"), Bun.sleep(150).then(() => "running")])).toBe("running");
+ tailPidSleeper.kill("SIGTERM");
+ await tailPidSleeper.exited.catch(() => {});
+ expect(await Promise.race([tailPid.exited.then(() => "exited"), Bun.sleep(1000).then(() => "running")])).toBe("exited");
+ expect(await new Response(tailPid.stderr).text()).toBe("");
+ const tailMissingFollow = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "-f", "tail-missing"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const tailMissingFollowState = await Promise.race([tailMissingFollow.exited.then(() => "exited"), Bun.sleep(1000).then(() => "running")]);
+ if (tailMissingFollowState === "running") {
+ tailMissingFollow.kill("SIGTERM");
+ await tailMissingFollow.exited.catch(() => {});
+ }
+ expect(tailMissingFollowState).toBe("exited");
+ const tailClosedStdin = await shell(`
+ BNU_STDIN_CLOSED=1 "$BUN" "$BNU" tail -f - <&-
+ `);
+ expect(tailClosedStdin).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "tail: cannot fstat 'standard input'\ntail: no files remaining\n",
+ });
+ await writeFile(join(dir, "tail-name-a"), "");
+ await writeFile(join(dir, "tail-name-rotated"), "");
+ const tailNameRecreate = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "--follow=name", "--sleep=0.1", "-n", "0", "tail-name-a", "tail-name-rotated"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ await Bun.sleep(1000);
+ await writeFile(join(dir, "tail-name-a"), "a\n");
+ await Bun.sleep(250);
+ await rm(join(dir, "tail-name-rotated"));
+ await Bun.sleep(250);
+ await writeFile(join(dir, "tail-name-rotated"), "rotated\n");
+ await Bun.sleep(350);
+ tailNameRecreate.kill("SIGTERM");
+ await tailNameRecreate.exited.catch(() => {});
+ expect(await new Response(tailNameRecreate.stdout).text()).toContain("rotated\n");
+ expect(await new Response(tailNameRecreate.stderr).text()).toContain("tail: 'tail-name-rotated' has become inaccessible: No such file or directory\n");
+ await writeFile(join(dir, "tail-empty-replaced"), "");
+ const tailEmptyReplaced = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "-F", "--sleep=0.05", "-n", "0", "tail-empty-replaced"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ await Bun.sleep(150);
+ for (let i = 0; i < 8; i++) {
+ await writeFile(join(dir, "tail-empty-next"), "");
+ await rename(join(dir, "tail-empty-next"), join(dir, "tail-empty-replaced"));
+ await Bun.sleep(20);
+ }
+ tailEmptyReplaced.kill("SIGTERM");
+ await tailEmptyReplaced.exited.catch(() => {});
+ const emptyReplaceMessages = (await new Response(tailEmptyReplaced.stderr).text()).match(/has been replaced/g) ?? [];
+ expect(emptyReplaceMessages.length).toBeLessThanOrEqual(8);
+ await writeFile(join(dir, "tail-name-moved"), "");
+ const tailNameMoved = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "--follow=name", "--sleep=0.1", "tail-name-moved"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ await Bun.sleep(1000);
+ await rename(join(dir, "tail-name-moved"), join(dir, "tail-name-moved-away"));
+ expect(await Promise.race([tailNameMoved.exited, Bun.sleep(1000).then(() => "running")])).toBe(1);
+ expect(await new Response(tailNameMoved.stderr).text()).toContain("tail: no files remaining\n");
+ const tailRetryMissing = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "-F", "--sleep=0.2", "tail-missing"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await Promise.race([tailRetryMissing.exited.then(() => "exited"), Bun.sleep(150).then(() => "running")])).toBe("running");
+ tailRetryMissing.kill("SIGTERM");
+ await tailRetryMissing.exited.catch(() => {});
+ await symlink("tail-target-a", join(dir, "tail-symlink"));
+ const tailSymlink = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "-F", "--sleep=0.1", "tail-symlink"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ await Bun.sleep(150);
+ await writeFile(join(dir, "tail-target-a"), "A\n");
+ await Bun.sleep(250);
+ await symlink("tail-target-b", join(dir, "tail-symlink.new"));
+ await rename(join(dir, "tail-symlink.new"), join(dir, "tail-symlink"));
+ await Bun.sleep(150);
+ await writeFile(join(dir, "tail-target-b"), "B\n");
+ await Bun.sleep(250);
+ tailSymlink.kill("SIGTERM");
+ await tailSymlink.exited.catch(() => {});
+ expect(await new Response(tailSymlink.stdout).text()).toContain("A\nB\n");
+ await mkdir(join(dir, "tail-untailable"));
+ const tailUntailable = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "-F", "--sleep=0.1", "tail-untailable"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ await Bun.sleep(1000);
+ tailUntailable.kill("SIGTERM");
+ await tailUntailable.exited.catch(() => {});
+ const tailUntailableErr = await new Response(tailUntailable.stderr).text();
+ expect(tailUntailableErr).toContain("tail: cannot follow 'tail-untailable': Is a directory\n");
+ expect(tailUntailableErr).toContain("tail: 'tail-untailable' has become inaccessible: Is a directory\n");
+ await mkdir(join(dir, "tail'untailable"));
+ const tailQuotedUntailable = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "-F", "--sleep=0.1", "tail'untailable"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ await Bun.sleep(1000);
+ tailQuotedUntailable.kill("SIGTERM");
+ await tailQuotedUntailable.exited.catch(() => {});
+ const tailQuotedUntailableErr = await new Response(tailQuotedUntailable.stderr).text();
+ expect(tailQuotedUntailableErr).toContain("tail: cannot follow \"tail'untailable\": Is a directory\n");
+ expect(tailQuotedUntailableErr).toContain("tail: \"tail'untailable\" has become inaccessible: Is a directory\n");
+ await writeFile(join(dir, "tail-descriptor"), "");
+ const tailDescriptor = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tail", "-f", "--sleep=0.1", "tail-descriptor"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ await Bun.sleep(150);
+ await writeFile(join(dir, "tail-descriptor"), "one\n");
+ await Bun.sleep(250);
+ await rename(join(dir, "tail-descriptor"), join(dir, "tail-descriptor-renamed"));
+ await writeFile(join(dir, "tail-descriptor-renamed"), "one\ntwo\n");
+ await Bun.sleep(250);
+ tailDescriptor.kill("SIGTERM");
+ await tailDescriptor.exited.catch(() => {});
+ expect(await new Response(tailDescriptor.stdout).text()).toContain("one\ntwo\n");
+ await writeFile(join(dir, "-2"), "dash\n");
+ expect(await run(["head", "--", "-2"])).toMatchObject({ code: 0, stdout: "dash\n" });
+ expect(await run(["wc", "-c"], "abc")).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["wc", "-m", "-c"], "é\n")).toMatchObject({ code: 0, stdout: " 2 3\n" });
+ expect(await run(["wc", "-L"], "ab\tc\nwide\n")).toMatchObject({ code: 0, stdout: "9\n" });
+ await writeFile(join(dir, "wc-a"), "x\n");
+ await writeFile(join(dir, "wc-b"), "y\nz\n");
+ await writeFile(join(dir, "wc-list"), "wc-a\0wc-b\0");
+ expect(await run(["wc", "-l", "--files0-from=wc-list", "--total=only"])).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["wc", "--files0-from", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "wc: cannot open '--help' for reading: No such file or directory\n" });
+ await symlink("wc-files0-loop", join(dir, "wc-files0-loop"));
+ expect(await run(["wc", "--files0-from=wc-files0-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "wc: cannot open 'wc-files0-loop' for reading: Too many levels of symbolic links\n" });
+ expect(await run(["wc", "--files0-from=-"], "missing\0missing\0")).toMatchObject({ code: 1, stdout: "0 0 0 total\n", stderr: "wc: missing: No such file or directory\nwc: missing: No such file or directory\n" });
+ expect(await run(["wc", "--files0-from=-"], "missing\nfile\0")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "wc: 'missing'$'\\n''file': No such file or directory\n",
+ });
+ expect(await run(["wc", "--files0-from=-"], "\0wc-a\0")).toMatchObject({ code: 1, stdout: "1 1 2 wc-a\n1 1 2 total\n", stderr: "wc: -:1: invalid zero-length file name\n" });
+ expect(await run(["wc", "--files0-from=-"], "-")).toMatchObject({ code: 1, stderr: "wc: when reading file names from standard input, no file name of '-' allowed\n" });
+ await writeFile(join(dir, "1\n2"), "");
+ expect(await run(["wc", "--files0-from=-"], "1\n2\0")).toMatchObject({ code: 0, stdout: "0 0 0 '1'$'\\n''2'\n" });
+ expect(await run(["wc", "-c", "wc-a", "wc-b"])).toMatchObject({ code: 0, stdout: "2 wc-a\n4 wc-b\n6 total\n" });
+ expect(await run(["truncate", "-s", "1G", "wc-big"])).toMatchObject({ code: 0 });
+ expect(await run(["wc", "-c", "--files0-from=-"], "wc-big\0wc-a\0")).toMatchObject({ code: 0, stdout: "1073741824 wc-big\n2 wc-a\n1073741826 total\n" });
+});
+
+test("text filters stream special-file operands and preserve multibyte cut units", async () => {
+ const bnu = join(import.meta.dir, "../bin/bnu.js");
+ for (const args of [
+ ["cat", "/dev/zero"],
+ ["cut", "-b1-", "/dev/zero"],
+ ["cut", "-c1-", "/dev/zero"],
+ ["cut", "-f1", "/dev/zero"],
+ ["cut", "-z", "-c1-", "/dev/zero"],
+ ["cut", "-z", "-f1-", "/dev/zero"],
+ ["expand", "/dev/zero"],
+ ["unexpand", "/dev/zero"],
+ ["fold", "/dev/zero"],
+ ["fold", "-b", "/dev/zero"],
+ ["fold", "-c", "/dev/zero"],
+ ["paste", "/dev/zero"],
+ ["od", "-v", "/dev/zero"],
+ ["comm", "-z", "/dev/zero", "/dev/zero"],
+ ["uniq", "-z", "-D", "/dev/zero"],
+ ["head", "-z", "-n-1", "/dev/zero"],
+ ["tail", "-n+1", "-z", "/dev/zero"],
+ ["join", "-a", "1", "-z", "/dev/zero", "/dev/null"],
+ ["fmt", "/dev/zero"],
+ ["pr", "/dev/zero"],
+ ]) {
+ const child = Bun.spawn(["/usr/bin/timeout", "5s", process.execPath, bnu, ...args], {
+ cwd: dir,
+ stdout: Bun.file("/dev/full"),
+ stderr: "pipe",
+ });
+ expect(await child.exited).toBe(1);
+ expect(await new Response(child.stderr).text()).toBe(args[0] === "head"
+ ? "head: error writing 'standard output': No space left on device\n"
+ : `${args[0]}: write error: No space left on device\n`);
+ }
+
+ const factor = Bun.spawn(["/usr/bin/env", "--default-signal=PIPE", "/bin/sh", "-c", `/usr/bin/yes 1 | ${process.execPath} ${bnu} factor`], {
+ cwd: dir,
+ stdout: Bun.file("/dev/full"),
+ stderr: "pipe",
+ });
+ expect(await factor.exited).toBe(1);
+ expect(await new Response(factor.stderr).text()).toBe("factor: write error: No space left on device\n");
+
+ const checksum = (await run(["cksum", "-a", "sha3", "-l", "256", "/dev/null"])).stdout.trim();
+ const checker = Bun.spawn(["/usr/bin/env", "--default-signal=PIPE", "/bin/sh", "-c", `/usr/bin/yes "$CHECKSUM" | ${process.execPath} ${bnu} cksum --check`], {
+ cwd: dir,
+ env: { ...process.env, CHECKSUM: checksum },
+ stdout: Bun.file("/dev/full"),
+ stderr: "pipe",
+ });
+ expect(await checker.exited).toBe(1);
+ expect(await new Response(checker.stderr).text()).toBe("cksum: write error: No space left on device\n");
+
+ for (const [command, pipeline] of [
+ ["wc", `/usr/bin/yes /dev/null | /usr/bin/tr '\\n' '\\0' | ${process.execPath} ${bnu} wc --files0-from=-`],
+ ["du", `/usr/bin/yes /dev/null | /usr/bin/tr '\\n' '\\0' | ${process.execPath} ${bnu} du -l --files0-from=-`],
+ ["fmt", `/usr/bin/yes | ${process.execPath} ${bnu} fmt`],
+ ]) {
+ const child = Bun.spawn(["/usr/bin/env", "--default-signal=PIPE", "/bin/sh", "-c", pipeline], {
+ cwd: dir,
+ stdout: Bun.file("/dev/full"),
+ stderr: "pipe",
+ });
+ expect(await child.exited).toBe(1);
+ expect(await new Response(child.stderr).text()).toBe(`${command}: write error: No space left on device\n`);
+ }
+
+ await writeFile(join(dir, "cut-invalid-utf8"), Buffer.from([0xc3, 0x78, 0x0a]));
+ const invalidOutput = join(dir, "cut-invalid-output");
+ const invalid = Bun.spawn([process.execPath, bnu, "cut", "-c1-2", "cut-invalid-utf8"], { cwd: dir, stdout: Bun.file(invalidOutput), stderr: "pipe" });
+ expect(await invalid.exited).toBe(0);
+ expect([...await readFile(invalidOutput)]).toEqual([0xc3, 0x78, 0x0a]);
+
+ await writeFile(join(dir, "cut-utf8-units"), Buffer.from([0xc3, 0xa9, 0xc3, 0xbc, 0x78, 0x0a]));
+ const unitOutput = join(dir, "cut-unit-output");
+ const units = Bun.spawn([process.execPath, bnu, "cut", "-b1-2,4", "-n", "--output-delimiter=:", "cut-utf8-units"], { cwd: dir, stdout: Bun.file(unitOutput), stderr: "pipe", env: { ...process.env, LC_ALL: "C.UTF-8" } });
+ expect(await units.exited).toBe(0);
+ expect([...await readFile(unitOutput)]).toEqual([0xc3, 0xa9, 0x3a, 0xc3, 0xbc, 0x0a]);
+ expect(await run(["cut", "-w", "-f2"], "a\u2003b\n", { env: { LC_ALL: "C.UTF-8" } })).toMatchObject({ code: 0, stdout: "b\n" });
+ expect(await run(["cut", "-sw", "-f2"], "a\u00a0b\n", { env: { LC_ALL: "C.UTF-8" } })).toMatchObject({ code: 0, stdout: "" });
+});
+
+test("filesystem utilities create, copy, move, link, remove", async () => {
+ expect(await run(["link"])).toMatchObject({ code: 1, stderr: "link: missing operand\nTry 'link --help' for more information.\n" });
+ expect(await run(["link", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: link FILE1 FILE2\n or: link OPTION\n") });
+ expect(await run(["link", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["link", "--h=1"])).toMatchObject({ code: 1, stderr: "link: option '--help' doesn't allow an argument\nTry 'link --help' for more information.\n" });
+ expect(await run(["link", "one"])).toMatchObject({ code: 1, stderr: "link: missing operand after 'one'\nTry 'link --help' for more information.\n" });
+ expect(await run(["link", "one", "two", "three"])).toMatchObject(await systemRun(["link", "one", "two", "three"]));
+ expect(await run(["link", "one", "two", "extra\narg"])).toMatchObject({ code: 1, stderr: `link: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'link --help' for more information.\n` });
+ expect(await run(["unlink"])).toMatchObject({ code: 1, stderr: "unlink: missing operand\nTry 'unlink --help' for more information.\n" });
+ expect(await run(["unlink", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: unlink FILE\n or: unlink OPTION\n") });
+ expect(await run(["unlink", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["unlink", "--v=1"])).toMatchObject({ code: 1, stderr: "unlink: option '--version' doesn't allow an argument\nTry 'unlink --help' for more information.\n" });
+ expect(await run(["unlink", "one", "two"])).toMatchObject(await systemRun(["unlink", "one", "two"]));
+ expect(await run(["unlink", "one", "extra\narg"])).toMatchObject({ code: 1, stderr: `unlink: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'unlink --help' for more information.\n` });
+ expect(await run(["mkdir", "-p", "a/b"])).toMatchObject({ code: 0 });
+ expect(await run(["touch", "a/b/file"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "a/b/file"), "payload");
+ expect(await run(["cp", "a/b/file", "copy"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "copy"), "utf8")).toBe("payload");
+ expect(await run(["cp", "/dev/null", "null-copy"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "null-copy"))).size).toBe(0);
+ await mkdir(join(dir, "special-target"));
+ expect(await run(["cp", "--target-directory=special-target", "/dev/null"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "special-target/null"))).size).toBe(0);
+ await writeFile(join(dir, "cp-target-prefix"), "target");
+ expect(await run(["cp", "--target", "special-target", "cp-target-prefix"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "special-target/cp-target-prefix"), "utf8")).toBe("target");
+ expect(await run(["cp", "--no", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "cp: option '--no' is ambiguous; possibilities: '--no-clobber' '--no-dereference' '--no-preserve' '--no-target-directory'\nTry 'cp --help' for more information.\n",
+ });
+ expect(await run(["cp", "--s", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "cp: option '--s' is ambiguous; possibilities: '--sparse' '--strip-trailing-slashes' '--suffix' '--symbolic-link'\nTry 'cp --help' for more information.\n",
+ });
+ expect(await run(["cp", "--force=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "cp: option '--force' doesn't allow an argument\nTry 'cp --help' for more information.\n",
+ });
+ expect(await run(["cp", "--copy=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "cp: option '--copy-contents' doesn't allow an argument\nTry 'cp --help' for more information.\n",
+ });
+ expect(await run(["cp", "--preserve=", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `cp: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--preserve")}\nValid arguments are:\n - ${diagnosticQuote("mode")}\n - ${diagnosticQuote("timestamps")}\n - ${diagnosticQuote("ownership")}\n - ${diagnosticQuote("links")}\n - ${diagnosticQuote("context")}\n - ${diagnosticQuote("xattr")}\n - ${diagnosticQuote("all")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--no-preserve=", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `cp: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--no-preserve")}\nValid arguments are:\n - ${diagnosticQuote("mode")}\n - ${diagnosticQuote("timestamps")}\n - ${diagnosticQuote("ownership")}\n - ${diagnosticQuote("links")}\n - ${diagnosticQuote("context")}\n - ${diagnosticQuote("xattr")}\n - ${diagnosticQuote("all")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--preserve=bad\nmode", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `cp: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--preserve")}\nValid arguments are:\n - ${diagnosticQuote("mode")}\n - ${diagnosticQuote("timestamps")}\n - ${diagnosticQuote("ownership")}\n - ${diagnosticQuote("links")}\n - ${diagnosticQuote("context")}\n - ${diagnosticQuote("xattr")}\n - ${diagnosticQuote("all")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--update=", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `cp: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--update")}\nValid arguments are:\n - ${diagnosticQuote("all")}\n - ${diagnosticQuote("none")}\n - ${diagnosticQuote("none-fail")}\n - ${diagnosticQuote("older")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--update=bad", "--help"])).toMatchObject(await systemRun(["cp", "--update=bad", "--help"]));
+ expect(await run(["cp", "--update=bad\nmode", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `cp: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--update")}\nValid arguments are:\n - ${diagnosticQuote("all")}\n - ${diagnosticQuote("none")}\n - ${diagnosticQuote("none-fail")}\n - ${diagnosticQuote("older")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--reflink=", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `cp: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--reflink")}\nValid arguments are:\n - ${diagnosticQuote("auto")}\n - ${diagnosticQuote("always")}\n - ${diagnosticQuote("never")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--reflink=bad", "--help"])).toMatchObject(await systemRun(["cp", "--reflink=bad", "--help"]));
+ expect(await run(["cp", "--reflink=bad\nmode", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `cp: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--reflink")}\nValid arguments are:\n - ${diagnosticQuote("auto")}\n - ${diagnosticQuote("always")}\n - ${diagnosticQuote("never")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--sparse=", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `cp: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--sparse")}\nValid arguments are:\n - ${diagnosticQuote("never")}\n - ${diagnosticQuote("auto")}\n - ${diagnosticQuote("always")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--sparse=bad", "--help"])).toMatchObject(await systemRun(["cp", "--sparse=bad", "--help"]));
+ expect(await run(["cp", "--sparse=bad\nmode", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `cp: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--sparse")}\nValid arguments are:\n - ${diagnosticQuote("never")}\n - ${diagnosticQuote("auto")}\n - ${diagnosticQuote("always")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--suffix", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["cp", "moved", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cp [OPTION]... [-T] SOURCE DEST\n"), stderr: "" });
+ expect(await run(["cp", "--ver=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "cp: option '--ver=bad' is ambiguous; possibilities: '--verbose' '--version'\nTry 'cp --help' for more information.\n",
+ });
+ expect(await run(["mv", "copy", "moved"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "mv-same"), "same");
+ await link(join(dir, "mv-same"), join(dir, "mv-same-link"));
+ expect(await run(["mv", "mv-same", "mv-same"])).toMatchObject({ code: 1, stderr: "mv: 'mv-same' and 'mv-same' are the same file\n" });
+ expect(await run(["mv", "mv-same", "mv-same-link"])).toMatchObject({ code: 1, stderr: "mv: 'mv-same' and 'mv-same-link' are the same file\n" });
+ expect(await readFile(join(dir, "mv-same"), "utf8")).toBe("same");
+ await writeFile(join(dir, "mv-backup-hard"), "hard");
+ await link(join(dir, "mv-backup-hard"), join(dir, "mv-backup-hard-link"));
+ expect(await run(["mv", "--backup=simple", "mv-backup-hard", "mv-backup-hard-link"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "mv-backup-hard"))).rejects.toThrow();
+ expect(await readFile(join(dir, "mv-backup-hard-link"), "utf8")).toBe("hard");
+ expect(await readFile(join(dir, "mv-backup-hard-link~"), "utf8")).toBe("hard");
+ expect(await run(["ln", "-s", "moved", "sym"])).toMatchObject({ code: 0 });
+ expect(await run(["ln", "moved", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: ln [OPTION]... [-T] TARGET LINK_NAME\n"), stderr: "" });
+ expect(await run(["readlink", "sym"])).toMatchObject({ code: 0, stdout: "moved\n" });
+ expect(await run(["cp", "-s", "moved", "cp-sym"])).toMatchObject({ code: 0 });
+ expect(await run(["readlink", "cp-sym"])).toMatchObject({ code: 0, stdout: "moved\n" });
+ const cpDebug = await run(["cp", "--debug", "moved", "debug-copy"]);
+ expect(cpDebug.stdout).toStartWith("'moved' -> 'debug-copy'\n");
+ expect(cpDebug.stdout).toMatch(/copy offload: (unknown|avoided), reflink: (yes|no), sparse detection: (unknown|no|SEEK_HOLE)\n$/);
+ expect(await run(["cp", "--debug", "--sparse=never", "moved", "debug-sparse-never"])).toMatchObject({
+ code: 0,
+ stdout: "'moved' -> 'debug-sparse-never'\ncopy offload: avoided, reflink: no, sparse detection: no\n",
+ });
+ expect((await run(["cp", "--debug", "--attributes-only", "moved", "debug-copy"])).stdout).not.toContain("copy offload:");
+ expect((await run(["cp", "--debug", "--update=none", "moved", "debug-copy"])).stdout).toContain("skipped");
+ expect(await run(["cp", "--strip-trailing-slashes", "moved", "strip-slash-copy"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "strip-slash-copy"), "utf8")).toBe("payload");
+ await mkdir(join(dir, "one-file-system-src"));
+ await writeFile(join(dir, "one-file-system-src/file"), "onefs");
+ expect(await run(["cp", "-xR", "--keep-directory-symlink", "one-file-system-src", "one-file-system-copy"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "one-file-system-copy/file"), "utf8")).toBe("onefs");
+ expect(await run(["cp", "--reflink=auto", "moved", "reflink-auto-copy"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "reflink-auto-copy"), "utf8")).toBe("payload");
+ expect(await run(["cp", "--reflink=auto", "--sparse=always", "moved", "reflink-sparse-copy"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "reflink-sparse-copy"), "utf8")).toBe("payload");
+ expect(await run(["cp", "--reflink", "--sparse=always", "moved", "reflink-sparse-required-copy"])).toMatchObject({ code: 1, stderr: "cp: options --reflink and --sparse are mutually exclusive\n" });
+ expect(await run(["cp", "--reflink=auto", "--reflink=never", "moved", "reflink-never-copy"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "reflink-never-copy"), "utf8")).toBe("payload");
+ const reflinkRequired = await run(["cp", "--reflink", "moved", "reflink-required-copy"]);
+ if (reflinkRequired.code === 0) {
+ expect(await readFile(join(dir, "reflink-required-copy"), "utf8")).toBe("payload");
+ } else {
+ expect(reflinkRequired.stderr).toContain("failed to clone");
+ await expect(stat(join(dir, "reflink-required-copy"))).rejects.toThrow();
+ }
+ expect(await run(["mkfifo", "cp-copy-contents-fifo"])).toMatchObject({ code: 0 });
+ const cpCopyContents = await shell(`
+ /usr/bin/timeout 5s /bin/sh -c '
+ "$BUN" "$BNU" cp -R --copy-contents cp-copy-contents-fifo cp-copy-contents-out &
+ cpid=$!
+ sleep .1
+ printf "fifo payload" > cp-copy-contents-fifo
+ wait "$cpid"
+ '
+ `);
+ expect(cpCopyContents).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "cp-copy-contents-out"))).isFIFO()).toBe(false);
+ expect(await readFile(join(dir, "cp-copy-contents-out"), "utf8")).toBe("fifo payload");
+ await mkdir(join(dir, "parent-copy-root"));
+ expect(await run(["cp", "--parent", "a/b/file", "parent-copy-root"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "parent-copy-root/a/b/file"), "utf8")).toBe("payload");
+ const cpHelp = (await run(["cp", "--help"])).stdout;
+ expect(cpHelp).toContain("Usage: cp [OPTION]... [-T] SOURCE DEST\n or: cp [OPTION]... SOURCE... DIRECTORY\n or: cp [OPTION]... -t DIRECTORY SOURCE...\n");
+ expect(cpHelp).toContain(" --parents\n");
+ expect(cpHelp).not.toContain(" --parent\n");
+ await mkdir(join(dir, "parent-mode-root"));
+ await run(["chmod", "700", "a"]);
+ await run(["chmod", "710", "a/b"]);
+ expect(await run(["cp", "-p", "--parent", "a/b/file", "parent-mode-root"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "parent-mode-root/a"))).mode & 0o777).toBe(0o700);
+ expect((await stat(join(dir, "parent-mode-root/a/b"))).mode & 0o777).toBe(0o710);
+ await run(["chmod", "755", "a"]);
+ await run(["chmod", "755", "a/b"]);
+ await mkdir(join(dir, "cp-readonly-src/nested"), { recursive: true });
+ await writeFile(join(dir, "cp-readonly-src/nested/file"), "readonly");
+ await run(["chmod", "-R", "555", "cp-readonly-src"]);
+ expect(await run(["cp", "-a", "cp-readonly-src", "cp-readonly-dst"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "cp-readonly-dst"))).mode & 0o777).toBe(0o555);
+ expect((await stat(join(dir, "cp-readonly-dst/nested"))).mode & 0o777).toBe(0o555);
+ await run(["chmod", "-R", "755", "cp-readonly-src"]);
+ await run(["chmod", "-R", "755", "cp-readonly-dst"]);
+ expect(await run(["mkfifo", "cp-perm-race-fifo"])).toMatchObject({ code: 0 });
+ const cpCopyContentsPerms = await shell(`
+ /usr/bin/timeout 5s /bin/sh -c '
+ "$BUN" "$BNU" cp -p --copy-contents cp-perm-race-fifo cp-perm-race-out &
+ cpid=$!
+ (
+ while [ ! -f cp-perm-race-out ]; do echo x; done
+ stat --format=%a cp-perm-race-out > cp-perm-race-mode
+ echo done
+ ) > cp-perm-race-fifo
+ wait "$cpid"
+ '
+ `);
+ expect(cpCopyContentsPerms).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "cp-perm-race-mode"), "utf8")).toBe("600\n");
+ const sparseSource = await open(join(dir, "sparse-source"), "w");
+ await sparseSource.write(Buffer.from("A"), 0, 1, 0);
+ await sparseSource.write(Buffer.from("Z"), 0, 1, 1024 * 1024 - 1);
+ await sparseSource.close();
+ await writeFile(join(dir, "sparse-dest"), "");
+ await truncate(join(dir, "sparse-dest"), 524288);
+ expect(await run(["cp", "--reflink=never", "--sparse=always", "sparse-source", "sparse-dest"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "sparse-dest"))).size).toBe(1024 * 1024);
+ const sparseExtentDebug = await run(["cp", "--debug", "--reflink=never", "sparse-source", "sparse-debug-extents"]);
+ expect(sparseExtentDebug).toMatchObject({ code: 0 });
+ expect(sparseExtentDebug.stdout).toContain("sparse detection: SEEK_HOLE\n");
+ await writeFile(join(dir, "sparse-zero-source"), Buffer.alloc(256 * 1024));
+ const sparseZeroDebug = await run(["cp", "--debug", "--reflink=never", "--sparse=always", "sparse-zero-source", "sparse-debug-zero"]);
+ expect(sparseZeroDebug).toMatchObject({ code: 0 });
+ expect(sparseZeroDebug.stdout).toContain("sparse detection: zeros\n");
+ expect((await stat(join(dir, "sparse-debug-zero"))).blocks).toBeLessThan((await stat(join(dir, "sparse-zero-source"))).blocks);
+ expect(await run(["cp", "--sparse=never", "sparse-source", "sparse-dense"])).toMatchObject({ code: 0 });
+ expect(await run(["cp", "--sparse=always", "sparse-source", "sparse-preserved"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "sparse-dense"))).blocks).toBeGreaterThan((await stat(join(dir, "sparse-preserved"))).blocks);
+ expect(await run(["mkfifo", "sparse-pipe"])).toMatchObject({ code: 0 });
+ expect(await shell(`
+ /usr/bin/timeout 5s /bin/sh -c '
+ cat sparse-pipe > sparse-pipe-copy &
+ cpid=$!
+ "$BUN" "$BNU" cp --sparse=always sparse-source sparse-pipe
+ wait "$cpid"
+ '
+ `)).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "sparse-pipe-copy"))).toEqual(await readFile(join(dir, "sparse-source")));
+ await mkdir(join(dir, "preserve-link-dest"));
+ await writeFile(join(dir, "preserve-link-a"), "linked");
+ await link(join(dir, "preserve-link-a"), join(dir, "preserve-link-b"));
+ await writeFile(join(dir, "preserve-link-dest/preserve-link-a"), "");
+ await writeFile(join(dir, "preserve-link-dest/preserve-link-b"), "");
+ expect(await run(["cp", "--preserve=link", "preserve-link-a", "preserve-link-b", "preserve-link-dest"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "preserve-link-dest/preserve-link-a"))).ino).toBe((await stat(join(dir, "preserve-link-dest/preserve-link-b"))).ino);
+ await writeFile(join(dir, "cp-interactive-src"), "new");
+ await writeFile(join(dir, "cp-interactive-dst"), "old");
+ expect(await run(["cp", "-vi", "cp-interactive-src", "cp-interactive-dst"], "n\n")).toMatchObject({ code: 1, stdout: "" });
+ expect(await readFile(join(dir, "cp-interactive-dst"), "utf8")).toBe("old");
+ expect(await run(["cp", "-vni", "cp-interactive-src", "cp-interactive-dst"], "y\n")).toMatchObject({ code: 0, stdout: "'cp-interactive-src' -> 'cp-interactive-dst'\n" });
+ expect(await readFile(join(dir, "cp-interactive-dst"), "utf8")).toBe("new");
+ await writeFile(join(dir, "cp-interactive-dst"), "old");
+ expect(await run(["cp", "-vin", "cp-interactive-src", "cp-interactive-dst"], "y\n")).toMatchObject({ code: 0, stdout: "" });
+ expect(await readFile(join(dir, "cp-interactive-dst"), "utf8")).toBe("old");
+ expect(await run(["cp", "-bn", "cp-interactive-src", "cp-interactive-dst"])).toMatchObject({ code: 1 });
+ await writeFile(join(dir, "cp-mode-src"), "mode");
+ await run(["chmod", "600", "cp-mode-src"]);
+ expect(await run(["cp", "--no-preserve=mode", "cp-mode-src", "cp-mode-default"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "cp-mode-default"))).mode & 0o777).toBe(0o644);
+ expect(await run(["cp", "--preserve=bad", "cp-mode-src", "cp-preserve-bad"])).toMatchObject(await systemRun(["cp", "--preserve=bad", "cp-mode-src", "cp-preserve-bad"]));
+ await expect(stat(join(dir, "cp-preserve-bad"))).rejects.toThrow();
+ expect(await run(["cp", "--preserve=bad\nmode", "cp-mode-src", "cp-preserve-bad-newline"])).toMatchObject({
+ code: 1,
+ stderr: `cp: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--preserve")}\nValid arguments are:\n - ${diagnosticQuote("mode")}\n - ${diagnosticQuote("timestamps")}\n - ${diagnosticQuote("ownership")}\n - ${diagnosticQuote("links")}\n - ${diagnosticQuote("context")}\n - ${diagnosticQuote("xattr")}\n - ${diagnosticQuote("all")}\nTry 'cp --help' for more information.\n`,
+ });
+ await expect(stat(join(dir, "cp-preserve-bad-newline"))).rejects.toThrow();
+ expect(await run(["cp", "--preserve=", "cp-mode-src", "cp-preserve-empty"])).toMatchObject(await systemRun(["cp", "--preserve=", "cp-mode-src", "cp-preserve-empty"]));
+ await expect(stat(join(dir, "cp-preserve-empty"))).rejects.toThrow();
+ expect(await run(["cp", "--no-preserve=bad", "cp-mode-src", "cp-no-preserve-bad"])).toMatchObject(await systemRun(["cp", "--no-preserve=bad", "cp-mode-src", "cp-no-preserve-bad"]));
+ await expect(stat(join(dir, "cp-no-preserve-bad"))).rejects.toThrow();
+ expect(await run(["cp", "--no-preserve=bad\nmode", "cp-mode-src", "cp-no-preserve-bad-newline"])).toMatchObject({
+ code: 1,
+ stderr: `cp: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--no-preserve")}\nValid arguments are:\n - ${diagnosticQuote("mode")}\n - ${diagnosticQuote("timestamps")}\n - ${diagnosticQuote("ownership")}\n - ${diagnosticQuote("links")}\n - ${diagnosticQuote("context")}\n - ${diagnosticQuote("xattr")}\n - ${diagnosticQuote("all")}\nTry 'cp --help' for more information.\n`,
+ });
+ await expect(stat(join(dir, "cp-no-preserve-bad-newline"))).rejects.toThrow();
+ expect(await run(["cp", "--no-preserve=", "cp-mode-src", "cp-no-preserve-empty"])).toMatchObject(await systemRun(["cp", "--no-preserve=", "cp-mode-src", "cp-no-preserve-empty"]));
+ await expect(stat(join(dir, "cp-no-preserve-empty"))).rejects.toThrow();
+ expect(await run(["cp", "--preserve=context", "cp-mode-src", "cp-preserve-context"])).toMatchObject({
+ code: 1,
+ stderr: "cp: cannot preserve security context without an SELinux-enabled kernel\n",
+ });
+ await expect(stat(join(dir, "cp-preserve-context"))).rejects.toThrow();
+ expect(await run(["cp", "--preserve=all,context", "cp-mode-src", "cp-preserve-context-list"])).toMatchObject({
+ code: 1,
+ stderr: "cp: cannot preserve security context without an SELinux-enabled kernel\n",
+ });
+ await expect(stat(join(dir, "cp-preserve-context-list"))).rejects.toThrow();
+ expect(await run(["cp", "--preserve=all", "cp-mode-src", "cp-preserve-all"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "cp-preserve-all"), "utf8")).toBe("mode");
+ expect(await run(["cp", "cp-mode-src", "cp-mode-source"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "cp-mode-source"))).mode & 0o777).toBe(0o600);
+ await writeFile(join(dir, "cp-mode-zero-src"), "mode");
+ await writeFile(join(dir, "cp-mode-zero-dst"), "old");
+ await run(["chmod", "0", "cp-mode-zero-dst"]);
+ const modeZeroCopy = await run(["cp", "-if", "cp-mode-zero-src", "cp-mode-zero-dst"], "y\n");
+ expect(modeZeroCopy.code).toBe(0);
+ expect(modeZeroCopy.stderr).toStartWith("cp: replace 'cp-mode-zero-dst', overriding mode 0000");
+ expect(await readFile(join(dir, "cp-mode-zero-dst"), "utf8")).toBe("mode");
+ await writeFile(join(dir, "cp-force-mode-src"), "new");
+ await writeFile(join(dir, "cp-force-mode-dst"), "old");
+ await run(["chmod", "450", "cp-force-mode-src"]);
+ await run(["chmod", "644", "cp-force-mode-dst"]);
+ expect(await run(["cp", "-f", "cp-force-mode-src", "cp-force-mode-dst"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "cp-force-mode-dst"))).mode & 0o777).toBe(0o644);
+ expect(await run(["cp", "-Z", "cp-mode-zero-src", "cp-context-copy"])).toMatchObject({ code: 0, stderr: "" });
+ expect(await run(["cp", "--context=system_u:object_r:tmp_t:s0", "cp-mode-zero-src", "cp-context-copy-2"])).toMatchObject({ code: 0, stderr: "cp: warning: ignoring --context; it requires an SELinux-enabled kernel\n" });
+ expect(await run(["cp", "--context=system_u:object_r:tmp_t:s0", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cp [OPTION]... [-T] SOURCE DEST\n"), stderr: "cp: warning: ignoring --context; it requires an SELinux-enabled kernel\n" });
+ await mkdir(join(dir, "cp-no-access/inner"), { recursive: true });
+ await run(["chmod", "0", "cp-no-access"]);
+ await symlink("cp-no-access/inner", join(dir, "cp-no-access-link"));
+ await writeFile(join(dir, "cp-no-access-src"), "x");
+ expect(await run(["cp", "cp-no-access-src", "cp-no-access-link"])).toMatchObject({ code: 1, stderr: "cp: cannot stat 'cp-no-access-link': Permission denied\n" });
+ expect(await run(["cp", "--target-directory=cp-no-access-link", "cp-no-access-src"])).toMatchObject({ code: 1, stderr: "cp: target directory 'cp-no-access-link': Permission denied\n" });
+ await run(["chmod", "700", "cp-no-access"]);
+ await mkdir(join(dir, "cp-partial-src/inner"), { recursive: true });
+ await writeFile(join(dir, "cp-partial-src/no-read"), "x");
+ await run(["chmod", "500", "cp-partial-src"]);
+ await run(["chmod", "0", "cp-partial-src/no-read"]);
+ expect(await run(["cp", "-pR", "cp-partial-src", "cp-partial-dst"])).toMatchObject({ code: 1 });
+ expect((await lstat(join(dir, "cp-partial-dst"))).mode & 0o777).toBe(0o500);
+ await run(["chmod", "700", "cp-partial-dst"]);
+ await run(["chmod", "700", "cp-partial-src"]);
+ await run(["chmod", "600", "cp-partial-src/no-read"]);
+ await mkdir(join(dir, "abuse-a"));
+ await mkdir(join(dir, "abuse-b"));
+ await mkdir(join(dir, "abuse-c"));
+ await symlink("../abuse-target", join(dir, "abuse-a/one"));
+ await writeFile(join(dir, "abuse-b/one"), "payload");
+ expect(await run(["cp", "-dR", "abuse-a/one", "abuse-b/one", "abuse-c"])).toMatchObject({ code: 1, stderr: "cp: will not copy 'abuse-b/one' through just-created symlink 'abuse-c/one'\n" });
+ await expect(stat(join(dir, "abuse-target"))).rejects.toThrow();
+ await writeFile(join(dir, "abuse-target"), "original");
+ expect(await run(["cp", "-dR", "abuse-a/one", "abuse-b/one", "abuse-c"])).toMatchObject({ code: 1, stderr: "cp: will not copy 'abuse-b/one' through just-created symlink 'abuse-c/one'\n" });
+ expect(await readFile(join(dir, "abuse-target"), "utf8")).toBe("original");
+ await mkdir(join(dir, "childproof-cp-dest"));
+ await mkdir(join(dir, "childproof-cp-a"));
+ await mkdir(join(dir, "childproof-cp-b"));
+ await writeFile(join(dir, "childproof-cp-a/f"), "a");
+ await writeFile(join(dir, "childproof-cp-b/f"), "b");
+ expect(await run(["cp", "childproof-cp-a/f", "childproof-cp-b/f", "childproof-cp-dest"])).toMatchObject({ code: 1 });
+ expect(await readFile(join(dir, "childproof-cp-dest/f"), "utf8")).toBe("a");
+ expect(await readFile(join(dir, "childproof-cp-b/f"), "utf8")).toBe("b");
+ await writeFile(join(dir, "attr-source"), "source");
+ await writeFile(join(dir, "attr-dest"), "dest");
+ expect(await run(["cp", "--attributes-only", "attr-source", "attr-dest"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "attr-dest"), "utf8")).toBe("dest");
+ await run(["chmod", "600", "attr-source"]);
+ expect(await run(["cp", "--attributes-only", "attr-source", "attr-created"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "attr-created"), "utf8")).toBe("");
+ expect((await stat(join(dir, "attr-created"))).mode & 0o777).toBe(0o600);
+ expect(await run(["cp", "--attributes-only", "--no-preserve=mode", "attr-source", "attr-created-default-mode"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "attr-created-default-mode"), "utf8")).toBe("");
+ expect((await stat(join(dir, "attr-created-default-mode"))).mode & 0o777).toBe(0o644);
+ await symlink("attr-source", join(dir, "attr-link"));
+ expect(await run(["cp", "-a", "--attributes-only", "attr-link", "attr-dest"])).toMatchObject({ code: 1 });
+ expect(await readFile(join(dir, "attr-dest"), "utf8")).toBe("dest");
+ expect(await run(["cp", "-a", "--remove-destination", "--attributes-only", "attr-link", "attr-dest"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "attr-dest"))).isSymbolicLink()).toBe(true);
+ await writeFile(join(dir, "archive-link-file"), "");
+ await symlink("archive-link-file", join(dir, "archive-link"));
+ const archiveLinkTime = new Date("2011-01-01T00:00:00Z");
+ await lutimes(join(dir, "archive-link"), archiveLinkTime, archiveLinkTime);
+ expect(await run(["cp", "-al", "archive-link", "archive-link-copy"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "archive-link-copy"))).isSymbolicLink()).toBe(true);
+ expect((await lstat(join(dir, "archive-link-copy"))).mtime.getUTCFullYear()).toBe(2011);
+ expect(await run(["cp", "-Pp", "archive-link", "archive-link-preserved"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "archive-link-preserved"))).isSymbolicLink()).toBe(true);
+ expect((await lstat(join(dir, "archive-link-preserved"))).mtime.getUTCFullYear()).toBe(2011);
+ await writeFile(join(dir, "preserve-ns-source"), "ns");
+ await systemRun(["/usr/bin/touch", "-a", "-d", "2026-01-01 01:02:03.111111111 +0000", "preserve-ns-source"]);
+ await systemRun(["/usr/bin/touch", "-m", "-d", "2026-01-02 03:04:05.222222222 +0000", "preserve-ns-source"]);
+ expect(await run(["cp", "-p", "preserve-ns-source", "preserve-ns-copy"])).toMatchObject({ code: 0 });
+ expect(await run(["stat", "-c", "%x|%y", "preserve-ns-copy"], "", { env: { TZ: "UTC0" } })).toMatchObject({
+ code: 0,
+ stdout: "2026-01-01 01:02:03.111111111 +0000|2026-01-02 03:04:05.222222222 +0000\n",
+ });
+ expect(await run(["link", "moved", "moved-hard"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "moved-hard"), "utf8")).toBe("payload");
+ await writeFile(join(dir, "-dash-source"), "dash");
+ expect(await run(["link", "--", "-dash-source", "-dash-hard"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "-dash-hard"), "utf8")).toBe("dash");
+ expect(await run(["link", "moved"])).toMatchObject({ code: 1, stderr: "link: missing operand after 'moved'\nTry 'link --help' for more information.\n" });
+ expect(await run(["link", "moved", "moved-hard"])).toMatchObject({ code: 1, stderr: "link: cannot create link 'moved-hard' to 'moved': File exists\n" });
+ expect(await run(["link", "missing\nlink-src", "link-dst"])).toMatchObject({ code: 1, stderr: "link: cannot create link 'link-dst' to 'missing'$'\\n''link-src': No such file or directory\n" });
+ expect(await run(["link", "missing'link-src", "link-dst"])).toMatchObject({ code: 1, stderr: "link: cannot create link 'link-dst' to \"missing'link-src\": No such file or directory\n" });
+ await writeFile(join(dir, "link-dst\nexists"), "old");
+ expect(await run(["link", "moved", "link-dst\nexists"])).toMatchObject({ code: 1, stderr: "link: cannot create link 'link-dst'$'\\n''exists' to 'moved': File exists\n" });
+ await writeFile(join(dir, "link-dst'exists"), "old");
+ expect(await run(["link", "moved", "link-dst'exists"])).toMatchObject({ code: 1, stderr: "link: cannot create link \"link-dst'exists\" to 'moved': File exists\n" });
+ expect(await run(["link", "one", "two", "three"])).toMatchObject(await systemRun(["link", "one", "two", "three"]));
+ await writeFile(join(dir, "unlink-me"), "x");
+ expect(await run(["unlink", "unlink-me"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "unlink-me"))).rejects.toThrow();
+ await writeFile(join(dir, "-dash-file"), "x");
+ expect(await run(["unlink", "--", "-dash-file"])).toMatchObject({ code: 0 });
+ expect(await run(["unlink", "missing-unlink"])).toMatchObject({ code: 1, stderr: "unlink: cannot unlink 'missing-unlink': No such file or directory\n" });
+ expect(await run(["unlink", "missing\nunlink"])).toMatchObject({ code: 1, stderr: "unlink: cannot unlink 'missing'$'\\n''unlink': No such file or directory\n" });
+ expect(await run(["unlink", "missing'unlink"])).toMatchObject({ code: 1, stderr: "unlink: cannot unlink \"missing'unlink\": No such file or directory\n" });
+ expect(await run(["unlink", "one", "two"])).toMatchObject({ code: 1 });
+ await writeFile(join(dir, "backup-target"), "target");
+ await writeFile(join(dir, "backup-target~"), "source");
+ expect(await run(["cp", "--b=simple", "backup-target~", "backup-target"])).toMatchObject({ code: 1, stderr: "cp: backing up 'backup-target' might destroy source; 'backup-target~' not copied\n" });
+ expect(await run(["mv", "--b=simple", "backup-target~", "backup-target"])).toMatchObject({ code: 1, stderr: "mv: backing up 'backup-target' might destroy source; 'backup-target~' not moved\n" });
+ await writeFile(join(dir, "mv-backup-source"), "new");
+ await writeFile(join(dir, "mv-backup-target"), "old");
+ expect(await run(["mv", "--verbose", "--backup=numbered", "mv-backup-source", "mv-backup-target"])).toMatchObject({ code: 0, stdout: "renamed 'mv-backup-source' -> 'mv-backup-target' (backup: 'mv-backup-target.~1~')\n" });
+ expect(await readFile(join(dir, "mv-backup-target.~1~"), "utf8")).toBe("old");
+ await writeFile(join(dir, "mv-debug-source"), "debug");
+ expect(await run(["mv", "--debug", "mv-debug-source", "mv-debug-target"])).toMatchObject({ code: 0, stdout: "renamed 'mv-debug-source' -> 'mv-debug-target'\n" });
+ expect(await readFile(join(dir, "mv-debug-target"), "utf8")).toBe("debug");
+ await writeFile(join(dir, "mv-strip-source"), "strip");
+ expect(await run(["mv", "--strip-trailing-slashes", "--no-copy", "mv-strip-source", "mv-strip-target"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "mv-strip-target"), "utf8")).toBe("strip");
+ await writeFile(join(dir, "mv-backup-no-clobber-src"), "new");
+ await writeFile(join(dir, "mv-backup-no-clobber-dst"), "old");
+ expect(await run(["cp", "-bn", "moved", "mv-backup-no-clobber-dst"])).toMatchObject({
+ code: 1,
+ stderr: "cp: --backup is mutually exclusive with -n or --update=none-fail\nTry 'cp --help' for more information.\n",
+ });
+ expect(await run(["cp", "--backup", "--update=none", "moved", "mv-backup-no-clobber-dst"])).toMatchObject({
+ code: 1,
+ stderr: "cp: --backup is mutually exclusive with -n or --update=none-fail\nTry 'cp --help' for more information.\n",
+ });
+ expect(await run(["mv", "-bn", "mv-backup-no-clobber-src", "mv-backup-no-clobber-dst"])).toMatchObject({
+ code: 1,
+ stderr: "mv: cannot combine --backup with --exchange, -n, or --update=none-fail\nTry 'mv --help' for more information.\n",
+ });
+ expect(await run(["mv", "--backup", "--exchange", "mv-backup-no-clobber-src", "mv-backup-no-clobber-dst"])).toMatchObject({
+ code: 1,
+ stderr: "mv: cannot combine --backup with --exchange, -n, or --update=none-fail\nTry 'mv --help' for more information.\n",
+ });
+ expect(await run(["cp", "moved", "no-such/"])).toMatchObject({ code: 1, stderr: "cp: cannot create regular file 'no-such/': Not a directory\n" });
+ await writeFile(join(dir, "update-old"), "old");
+ await run(["touch", "-d", "yesterday", "update-old"]);
+ await writeFile(join(dir, "update-new"), "new");
+ expect(await run(["cp", "--update=none", "update-new", "update-old"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "update-old"), "utf8")).toBe("old");
+ expect(await run(["cp", "--update=none-fail", "update-new", "update-old"])).toMatchObject({ code: 1, stderr: "cp: not replacing 'update-old'\n" });
+ expect(await run(["cp", "--update=all", "update-new", "update-old"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "update-old"), "utf8")).toBe("new");
+ await writeFile(join(dir, "update-ns-src"), "ns-new");
+ await writeFile(join(dir, "update-ns-dst"), "ns-old");
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456789 +0000", "update-ns-src"]);
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456788 +0000", "update-ns-dst"]);
+ expect(await run(["cp", "-u", "update-ns-src", "update-ns-dst"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "update-ns-dst"), "utf8")).toBe("ns-new");
+ await writeFile(join(dir, "mv-update-old"), "old");
+ await run(["touch", "-d", "yesterday", "mv-update-old"]);
+ await writeFile(join(dir, "mv-update-new"), "new");
+ expect(await run(["mv", "-u", "mv-update-old", "mv-update-new"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "mv-update-new"), "utf8")).toBe("new");
+ expect(await readFile(join(dir, "mv-update-old"), "utf8")).toBe("old");
+ expect(await run(["mv", "--update=none-fail", "mv-update-new", "mv-update-old"])).toMatchObject({ code: 1, stderr: "mv: not replacing 'mv-update-old'\n" });
+ expect(await readFile(join(dir, "mv-update-new"), "utf8")).toBe("new");
+ await writeFile(join(dir, "mv-update-ns-src"), "mv-ns-new");
+ await writeFile(join(dir, "mv-update-ns-dst"), "mv-ns-old");
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456789 +0000", "mv-update-ns-src"]);
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456788 +0000", "mv-update-ns-dst"]);
+ expect(await run(["mv", "-u", "mv-update-ns-src", "mv-update-ns-dst"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "mv-update-ns-dst"), "utf8")).toBe("mv-ns-new");
+ await expect(stat(join(dir, "mv-update-ns-src"))).rejects.toThrow();
+ await writeFile(join(dir, "mv-if-src"), "if");
+ await writeFile(join(dir, "mv-if-dst"), "old");
+ await run(["chmod", "0", "mv-if-dst"]);
+ expect(await run(["mv", "-if", "mv-if-src", "mv-if-dst"])).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(join(dir, "mv-if-dst"), "utf8")).toBe("if");
+ await writeFile(join(dir, "mv-fi-src"), "fi");
+ await writeFile(join(dir, "mv-fi-dst"), "old");
+ await run(["chmod", "0", "mv-fi-dst"]);
+ expect(await run(["mv", "-fi", "mv-fi-src", "mv-fi-dst"], "y\n")).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "mv-fi-dst"), "utf8")).toBe("fi");
+ await writeFile(join(dir, "mv-protected-src"), "new");
+ await writeFile(join(dir, "mv-protected-dst"), "old");
+ await run(["chmod", "0", "mv-protected-dst"]);
+ expect(await shell(`
+ printf 'n\n' | script -qefc '"$BUN" "$BNU" mv mv-protected-src mv-protected-dst' /dev/null >mv-protected-transcript 2>&1
+ test $? -eq 1
+ grep -F "mv: replace 'mv-protected-dst', overriding mode 0000 (---------)?" mv-protected-transcript >/dev/null
+ test -f mv-protected-src
+ `)).toMatchObject({ code: 0 });
+ await run(["chmod", "600", "mv-protected-dst"]);
+ expect(await readFile(join(dir, "mv-protected-dst"), "utf8")).toBe("old");
+ await writeFile(join(dir, "cp-file-over-dir"), "file");
+ await mkdir(join(dir, "cp-dir-target"));
+ expect(await run(["cp", "-T", "cp-file-over-dir", "cp-dir-target"])).toMatchObject({ code: 1, stderr: "cp: cannot overwrite directory 'cp-dir-target' with non-directory 'cp-file-over-dir'\n" });
+ await mkdir(join(dir, "cp-dir-over-file"));
+ await writeFile(join(dir, "cp-file-target"), "file");
+ expect(await run(["cp", "-R", "cp-dir-over-file", "cp-file-target"])).toMatchObject({ code: 1, stderr: "cp: cannot overwrite non-directory 'cp-file-target' with directory 'cp-dir-over-file'\n" });
+ await writeFile(join(dir, "mv-file-over-dir"), "file");
+ await mkdir(join(dir, "mv-dir-target/mv-file-over-dir"), { recursive: true });
+ expect(await run(["mv", "mv-file-over-dir", "mv-dir-target"])).toMatchObject({ code: 1, stderr: "mv: cannot overwrite directory 'mv-dir-target/mv-file-over-dir' with non-directory 'mv-file-over-dir'\n" });
+ await mkdir(join(dir, "mv-dir-over-file"));
+ await writeFile(join(dir, "mv-file-target"), "file");
+ expect(await run(["mv", "mv-dir-over-file", "mv-file-target"])).toMatchObject({ code: 1, stderr: "mv: cannot overwrite non-directory 'mv-file-target' with directory 'mv-dir-over-file'\n" });
+ await mkdir(join(dir, "mv-nonempty-target/t"), { recursive: true });
+ await mkdir(join(dir, "mv-nonempty-src/t"), { recursive: true });
+ await writeFile(join(dir, "mv-nonempty-target/t/file"), "x");
+ expect(await run(["mv", "mv-nonempty-src/t", "mv-nonempty-target"])).toMatchObject({ code: 1, stderr: "mv: cannot overwrite 'mv-nonempty-target/t': Directory not empty\n" });
+ let remoteDir;
+ try {
+ remoteDir = await mkdtemp("/dev/shm/bnu-test-");
+ if ((await stat(dir)).dev !== (await stat(remoteDir)).dev) {
+ await writeFile(join(dir, "mv-cross-device"), "local");
+ await writeFile(join(remoteDir, "remote-file"), "remote");
+ await symlink(join(remoteDir, "remote-file"), join(remoteDir, "remote-link"));
+ expect(await run(["mv", "mv-cross-device", join(remoteDir, "remote-link")])).toMatchObject({ code: 0 });
+ await expect(lstat(join(dir, "mv-cross-device"))).rejects.toThrow();
+ expect(await readFile(join(remoteDir, "remote-file"), "utf8")).toBe("remote");
+ expect(await readFile(join(remoteDir, "remote-link"), "utf8")).toBe("local");
+ expect((await lstat(join(remoteDir, "remote-link"))).isSymbolicLink()).toBe(false);
+ expect(await run(["mkfifo", "mv-cross-fifo"])).toMatchObject({ code: 0 });
+ expect(await run(["mv", "-v", "mv-cross-fifo", remoteDir])).toMatchObject({ code: 0, stdout: `'mv-cross-fifo' -> '${join(remoteDir, "mv-cross-fifo")}'\n` });
+ expect((await lstat(join(remoteDir, "mv-cross-fifo"))).isFIFO()).toBe(true);
+ await writeFile(join(remoteDir, "remote-same-file"), "same");
+ await symlink(join(remoteDir, "remote-same-file"), join(dir, "remote-same-link"));
+ expect(await run(["mv", join(remoteDir, "remote-same-file"), "remote-same-link"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "remote-same-link"), "utf8")).toBe("same");
+ expect((await lstat(join(dir, "remote-same-link"))).isSymbolicLink()).toBe(false);
+ await mkdir(join(dir, "mv-cross-dir"));
+ await writeFile(join(dir, "mv-cross-dir/local"), "local");
+ await mkdir(join(remoteDir, "mv-cross-dir"));
+ await writeFile(join(remoteDir, "mv-cross-dir/remote"), "remote");
+ expect(await run(["mv", "mv-cross-dir", remoteDir])).toMatchObject({ code: 1 });
+ expect(await readFile(join(remoteDir, "mv-cross-dir/remote"), "utf8")).toBe("remote");
+ expect(await readFile(join(dir, "mv-cross-dir/local"), "utf8")).toBe("local");
+ }
+ } catch (error) {
+ if (error?.code !== "ENOENT" && error?.code !== "EACCES") throw error;
+ } finally {
+ if (remoteDir) await rm(remoteDir, { recursive: true, force: true });
+ }
+ await mkdir(join(dir, "dup-dest"));
+ await writeFile(join(dir, "dup-source"), "dup");
+ expect(await run(["cp", "dup-source", "dup-source", "dup-dest"])).toMatchObject({ code: 0, stderr: "cp: warning: source file 'dup-source' specified more than once\n" });
+ expect(await readFile(join(dir, "dup-dest/dup-source"), "utf8")).toBe("dup");
+ await mkdir(join(dir, "mv-dup-dest"));
+ await writeFile(join(dir, "mv-dup-source"), "dup");
+ expect(await run(["mv", "mv-dup-source", "mv-dup-source", "mv-dup-dest"])).toMatchObject({ code: 1, stderr: "mv: cannot stat 'mv-dup-source': No such file or directory\n" });
+ await expect(stat(join(dir, "mv-dup-source"))).rejects.toThrow();
+ expect(await readFile(join(dir, "mv-dup-dest/mv-dup-source"), "utf8")).toBe("dup");
+ expect(await run(["rm", "--preserve-root", "mv-debug-target"])).toMatchObject({ code: 0 });
+ expect(await run(["rm", "-r", "a", "moved", "moved-hard", "mv-same", "mv-same-link", "mv-backup-hard-link", "mv-backup-hard-link~", "sym", "strip-slash-copy", "one-file-system-src", "one-file-system-copy", "reflink-auto-copy", "reflink-sparse-copy", "reflink-never-copy", "sparse-source", "sparse-dest", "sparse-debug-extents", "sparse-zero-source", "sparse-debug-zero", "sparse-dense", "sparse-preserved", "sparse-pipe", "sparse-pipe-copy", "preserve-link-a", "preserve-link-b", "preserve-link-dest", "cp-interactive-src", "cp-interactive-dst", "cp-mode-zero-src", "cp-mode-zero-dst", "cp-no-access", "cp-no-access-link", "cp-no-access-src", "cp-partial-src", "cp-partial-dst", "abuse-a", "abuse-b", "abuse-c", "abuse-target", "archive-link-file", "archive-link", "archive-link-copy", "backup-target", "backup-target~", "mv-backup-target", "mv-backup-target.~1~", "mv-strip-target", "mv-if-dst", "mv-fi-dst", "mv-protected-src", "mv-protected-dst", "mv-protected-transcript", "mv-file-over-dir", "mv-dir-target", "mv-dir-over-file", "mv-file-target", "dup-dest", "mv-dup-dest", "update-old", "update-new", "mv-update-old", "mv-update-new", "--", "-dash-source", "-dash-hard"])).toMatchObject({ code: 0 });
+});
+
+test("mkdir and rmdir support verbose, parent, and non-empty modes", async () => {
+ expect(await run(["mkdir"])).toMatchObject({ code: 1, stderr: "mkdir: missing operand\nTry 'mkdir --help' for more information.\n" });
+ expect(await run(["rmdir"])).toMatchObject({ code: 1, stderr: "rmdir: missing operand\nTry 'rmdir --help' for more information.\n" });
+ expect(await run(["rm"])).toMatchObject({ code: 1, stderr: "rm: missing operand\nTry 'rm --help' for more information.\n" });
+ const mkdirHelp = (await run(["mkdir", "--h"])).stdout;
+ expect(mkdirHelp).toContain("Usage: mkdir [OPTION]... DIRECTORY...\n");
+ expect(mkdirHelp).toContain("-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask\n");
+ expect(mkdirHelp).toContain(" with their file modes unaffected by any -m option\n");
+ expect(mkdirHelp).toContain("--context[=CTX] like -Z, or if CTX is specified then set the\n");
+ expect(await run(["mkdir", "--p", "mkdir-prefix/child"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "mkdir-prefix/child"))).resolves.toBeTruthy();
+ expect(await run(["mkdir", "mkdir-prefix"])).toMatchObject(await systemRun(["/usr/bin/mkdir", "mkdir-prefix"]));
+ await writeFile(join(dir, "mkdir-file-parent"), "x");
+ expect(await run(["mkdir", "-p", "mkdir-file-parent/child"])).toMatchObject(await systemRun(["/usr/bin/mkdir", "-p", "mkdir-file-parent/child"]));
+ expect(await run(["mkdir", "--m=700", "mkdir-mode-inline"])).toMatchObject({ code: 0 });
+ expect(((await stat(join(dir, "mkdir-mode-inline"))).mode & 0o777)).toBe(0o700);
+ expect(await run(["mkdir", "--mo", "755", "mkdir-mode-next"])).toMatchObject({ code: 0 });
+ expect(((await stat(join(dir, "mkdir-mode-next"))).mode & 0o777)).toBe(0o755);
+ expect(await run(["mkdir", "--verb", "mkdir-verbose"])).toMatchObject({ code: 0, stdout: "mkdir: created directory 'mkdir-verbose'\n" });
+ expect(await run(["mkdir", "-v", "mkdir-verbose\nnewline"])).toMatchObject({ code: 0, stdout: "mkdir: created directory 'mkdir-verbose'$'\\n''newline'\n" });
+ expect(await run(["mkdir", "-v", "mkdir-verbose'quote"])).toMatchObject({ code: 0, stdout: "mkdir: created directory \"mkdir-verbose'quote\"\n" });
+ expect(await run(["mkdir", "--v"])).toMatchObject({ code: 1, stderr: "mkdir: option '--v' is ambiguous; possibilities: '--verbose' '--version'\nTry 'mkdir --help' for more information.\n" });
+ expect(await run(["mkdir", "--m"])).toMatchObject({ code: 1, stderr: "mkdir: option '--mode' requires an argument\nTry 'mkdir --help' for more information.\n" });
+ expect(await run(["mkdir", "--m", "--h"])).toMatchObject({ code: 1, stderr: "mkdir: missing operand\nTry 'mkdir --help' for more information.\n" });
+ expect(await run(["mkdir", "--m", "--h", "mkdir-bad-mode"])).toMatchObject(await systemRun(["/usr/bin/mkdir", "--m", "--h", "mkdir-bad-mode"]));
+ expect(await run(["mkdir", "--p=1", "mkdir-bad-parent"])).toMatchObject({ code: 1, stderr: "mkdir: option '--parents' doesn't allow an argument\nTry 'mkdir --help' for more information.\n" });
+ expect(await run(["mkdir", "-p", ""])).toMatchObject(await systemRun(["/usr/bin/mkdir", "-p", ""]));
+ expect(await run(["mkdir", "-v", "-p", "parents/child"])).toMatchObject({ code: 0, stdout: "mkdir: created directory 'parents'\nmkdir: created directory 'parents/child'\n" });
+ expect(await run(["mkdir", "-pv", "parents\nnewline/child'quote"])).toMatchObject({
+ code: 0,
+ stdout: `mkdir: created directory 'parents'$'\\n''newline'\nmkdir: created directory 'parents'$'\\n''newline/child'\\''quote'\n`,
+ });
+ expect(await run(["mkdir", "mkdir-verbose\nnewline"])).toMatchObject({ code: 1, stdout: "", stderr: `mkdir: cannot create directory ${diagnosticQuote("mkdir-verbose\\nnewline")}: File exists\n` });
+ expect(await run(["mkdir", "mkdir-verbose'quote"])).toMatchObject({ code: 1, stdout: "", stderr: `mkdir: cannot create directory ${diagnosticQuote("mkdir-verbose'quote")}: File exists\n` });
+ await writeFile(join(dir, "mkdir-parent\nfile"), "x");
+ expect(await run(["mkdir", "-p", "mkdir-parent\nfile/child"])).toMatchObject({ code: 1, stdout: "", stderr: `mkdir: cannot create directory ${diagnosticQuote("mkdir-parent\\nfile")}: Not a directory\n` });
+ await writeFile(join(dir, "mkdir-parent'file"), "x");
+ expect(await run(["mkdir", "-p", "mkdir-parent'file/child"])).toMatchObject({ code: 1, stdout: "", stderr: `mkdir: cannot create directory ${diagnosticQuote("mkdir-parent'file")}: Not a directory\n` });
+ expect(await run(["rmdir", "-p", "parents/child"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "parents"))).rejects.toThrow();
+ await mkdir(join(dir, "parents2/child"), { recursive: true });
+ expect(await run(["rmdir", "--pa", "parents2/child"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "parents2"))).rejects.toThrow();
+ await mkdir(join(dir, "parents3/child"), { recursive: true });
+ expect(await run(["rmdir", "--par", "parents3/child"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "parents3"))).rejects.toThrow();
+ await mkdir(join(dir, "rmdir-verbose"));
+ expect(await run(["rmdir", "-v", "rmdir-verbose"])).toMatchObject({ code: 0, stdout: "rmdir: removing directory, 'rmdir-verbose'\n" });
+ await mkdir(join(dir, "rmdir-verbose-parent/child"), { recursive: true });
+ expect(await run(["rmdir", "-vp", "rmdir-verbose-parent/child"])).toMatchObject({ code: 0, stdout: "rmdir: removing directory, 'rmdir-verbose-parent/child'\nrmdir: removing directory, 'rmdir-verbose-parent'\n" });
+ await mkdir(join(dir, "rmdir-verbose\nparent/child'leaf"), { recursive: true });
+ expect(await run(["rmdir", "-pv", "rmdir-verbose\nparent/child'leaf"])).toMatchObject({
+ code: 0,
+ stdout: `rmdir: removing directory, 'rmdir-verbose'$'\\n''parent/child'\\''leaf'\nrmdir: removing directory, 'rmdir-verbose'$'\\n''parent'\n`,
+ stderr: "",
+ });
+ expect(await run(["rmdir", "missing\nrmdir"])).toMatchObject({ code: 1, stdout: "", stderr: "rmdir: failed to remove 'missing'$'\\n''rmdir': No such file or directory\n" });
+ expect(await run(["rmdir", "missing'rmdir"])).toMatchObject({ code: 1, stdout: "", stderr: "rmdir: failed to remove \"missing'rmdir\": No such file or directory\n" });
+ await writeFile(join(dir, "rmdir-file\nplain"), "x");
+ expect(await run(["rmdir", "rmdir-file\nplain"])).toMatchObject({ code: 1, stdout: "", stderr: "rmdir: failed to remove 'rmdir-file'$'\\n''plain': Not a directory\n" });
+ await writeFile(join(dir, "rmdir-file'plain"), "x");
+ expect(await run(["rmdir", "rmdir-file'plain"])).toMatchObject({ code: 1, stdout: "", stderr: "rmdir: failed to remove \"rmdir-file'plain\": Not a directory\n" });
+ expect(await run(["rmdir", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: rmdir [OPTION]... DIRECTORY...\n") });
+ expect(await run(["rmdir", "--v"])).toMatchObject({ code: 1, stderr: "rmdir: option '--v' is ambiguous; possibilities: '--verbose' '--version'\nTry 'rmdir --help' for more information.\n" });
+ expect(await run(["rmdir", "--pa=1", "parents3"])).toMatchObject({ code: 1, stderr: "rmdir: option '--path' doesn't allow an argument\nTry 'rmdir --help' for more information.\n" });
+ expect(await run(["rmdir", "--par=1", "parents3"])).toMatchObject({ code: 1, stderr: "rmdir: option '--parents' doesn't allow an argument\nTry 'rmdir --help' for more information.\n" });
+ expect(await run(["rmdir", "-x", "--help"])).toMatchObject({ code: 1, stderr: "rmdir: invalid option -- 'x'\nTry 'rmdir --help' for more information.\n" });
+ await mkdir(join(dir, "rmdir-posix-parent/child"), { recursive: true });
+ expect(await run(["rmdir", "rmdir-posix-parent/child", "-p"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stderr: "rmdir: failed to remove '-p': No such file or directory\n" });
+ await expect(stat(join(dir, "rmdir-posix-parent/child"))).rejects.toThrow();
+ await expect(stat(join(dir, "rmdir-posix-parent"))).resolves.toBeTruthy();
+ await mkdir(join(dir, "rmdir-posix-help/child"), { recursive: true });
+ expect(await run(["rmdir", "rmdir-posix-help/child", "--help"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stderr: "rmdir: failed to remove '--help': No such file or directory\n" });
+ await expect(stat(join(dir, "rmdir-posix-help/child"))).rejects.toThrow();
+ await expect(stat(join(dir, "rmdir-posix-help"))).resolves.toBeTruthy();
+ await mkdir(join(dir, "nonempty"));
+ await writeFile(join(dir, "nonempty/file"), "x");
+ expect(await run(["rmdir", "--ignore-fail-on-non-empty", "nonempty"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "nonempty"))).isDirectory()).toBe(true);
+ await writeFile(join(dir, "remove-me"), "x");
+ expect(await run(["rm", "-v", "remove-me"])).toMatchObject({ code: 0, stdout: "removed 'remove-me'\n" });
+ await writeFile(join(dir, "remove\nme"), "x");
+ expect(await run(["rm", "-v", "remove\nme"])).toMatchObject({ code: 0, stdout: "removed 'remove'$'\\n''me'\n" });
+ await writeFile(join(dir, "remove'me"), "x");
+ expect(await run(["rm", "-v", "remove'me"])).toMatchObject({ code: 0, stdout: "removed \"remove'me\"\n" });
+ expect(await run(["rm", "missing\nremove"])).toMatchObject({ code: 1, stdout: "", stderr: "rm: cannot remove 'missing'$'\\n''remove': No such file or directory\n" });
+ expect(await run(["rm", "missing'remove"])).toMatchObject({ code: 1, stdout: "", stderr: "rm: cannot remove \"missing'remove\": No such file or directory\n" });
+ await mkdir(join(dir, "remove-dir\nplain"));
+ expect(await run(["rm", "remove-dir\nplain"])).toMatchObject({ code: 1, stdout: "", stderr: "rm: cannot remove 'remove-dir'$'\\n''plain': Is a directory\n" });
+ await mkdir(join(dir, "remove-dir'plain"));
+ expect(await run(["rm", "remove-dir'plain"])).toMatchObject({ code: 1, stdout: "", stderr: "rm: cannot remove \"remove-dir'plain\": Is a directory\n" });
+ await mkdir(join(dir, "remove-tree\nplain"));
+ await writeFile(join(dir, "remove-tree\nplain/file'plain"), "x");
+ expect(await run(["rm", "-rv", "remove-tree\nplain"])).toMatchObject({
+ code: 0,
+ stdout: `removed 'remove-tree'$'\\n''plain/file'\\''plain'\nremoved directory 'remove-tree'$'\\n''plain'\n`,
+ stderr: "",
+ });
+ await mkdir(join(dir, "rm-malloc-perturb/a/b"), { recursive: true });
+ await writeFile(join(dir, "rm-malloc-perturb/a/file"), "x");
+ expect(await run(["rm", "-rf", "rm-malloc-perturb"], "", { env: { MALLOC_PERTURB_: "87" } })).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ await expect(stat(join(dir, "rm-malloc-perturb"))).rejects.toThrow();
+ expect(await run(["rm", "."])).toMatchObject(await systemRun(["/usr/bin/rm", "."]));
+ expect(await run(["rm", "-r", "."])).toMatchObject(await systemRun(["/usr/bin/rm", "-r", "."]));
+ await mkdir(join(dir, "empty-dir"));
+ expect(await run(["rm", "-d", "empty-dir"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "empty-dir"))).rejects.toThrow();
+ await mkdir(join(dir, "rm-recursive-prefix/sub"), { recursive: true });
+ await writeFile(join(dir, "rm-recursive-prefix/sub/file"), "x");
+ expect(await run(["rm", "--r", "rm-recursive-prefix"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "rm-recursive-prefix"))).rejects.toThrow();
+ await writeFile(join(dir, "interactive-remove"), "x");
+ expect(await run(["rm", "-I", "interactive-remove"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "interactive-remove"))).rejects.toThrow();
+ await writeFile(join(dir, "never-remove"), "x");
+ expect(await run(["rm", "--interactive=never", "never-remove"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "never-remove-prefix"), "x");
+ expect(await run(["rm", "--inter=never", "never-remove-prefix"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "-foo"), "x");
+ expect(await run(["rm", "-foo"])).toMatchObject({
+ code: 1,
+ stderr: "rm: invalid option -- 'o'\nTry 'rm ./-foo' to remove the file '-foo'.\nTry 'rm --help' for more information.\n",
+ });
+ await writeFile(join(dir, "-foo\nbar"), "x");
+ expect(await run(["rm", "-foo\nbar"])).toMatchObject({
+ code: 1,
+ stderr: "rm: invalid option -- 'o'\nTry 'rm ./'-foo'$'\\n''bar'' to remove the file '-foo'$'\\n''bar'.\nTry 'rm --help' for more information.\n",
+ });
+ expect(await run(["rm", "--bad", "--help"])).toMatchObject({ code: 1, stderr: "rm: unrecognized option '--bad'\nTry 'rm --help' for more information.\n" });
+ expect(await run(["rm", "--no-preserve", "/"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "rm: you may not abbreviate the --no-preserve-root option\n",
+ });
+ expect(await run(["rm", "--no-preserve", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "rm: you may not abbreviate the --no-preserve-root option\n",
+ });
+ const rmHelp = await run(["rm", "--help"]);
+ expect(rmHelp.code).toBe(0);
+ expect(rmHelp.stdout).toContain("Remove (unlink) the FILE(s).\n");
+ expect(rmHelp.stdout).toContain(" -I\n");
+ expect(rmHelp.stdout).toContain(" -R\n");
+ expect(rmHelp.stdout).toContain(" -i\n");
+ await writeFile(join(dir, "rm-meta"), "x");
+ expect(await run(["rm", "rm-meta", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: rm [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await readFile(join(dir, "rm-meta"), "utf8")).toBe("x");
+ expect(await run(["rm", "--force=bad", "--help"])).toMatchObject({ code: 1, stderr: "rm: option '--force' doesn't allow an argument\nTry 'rm --help' for more information.\n" });
+ expect(await run(["rm", "--interactive=", "never-remove"])).toMatchObject({
+ code: 1,
+ stderr: `rm: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--interactive")}\nValid arguments are:\n - ${diagnosticQuote("never")}, ${diagnosticQuote("no")}, ${diagnosticQuote("none")}\n - ${diagnosticQuote("once")}\n - ${diagnosticQuote("always")}, ${diagnosticQuote("yes")}\nTry 'rm --help' for more information.\n`,
+ });
+ expect(await run(["rm", "--interactive=maybe", "never-remove"])).toMatchObject(await systemRun(["rm", "--interactive=maybe", "never-remove"]));
+ expect(await run(["rm", "--interactive=bad\nmode", "never-remove"])).toMatchObject({
+ code: 1,
+ stderr: `rm: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--interactive")}\nValid arguments are:\n - ${diagnosticQuote("never")}, ${diagnosticQuote("no")}, ${diagnosticQuote("none")}\n - ${diagnosticQuote("once")}\n - ${diagnosticQuote("always")}, ${diagnosticQuote("yes")}\nTry 'rm --help' for more information.\n`,
+ });
+ expect(await run(["rm", "--pres=bad", "--help"])).toMatchObject({ code: 1, stderr: "rm: unrecognized --preserve-root argument: 'bad'\n" });
+ expect(await run(["rm", "--one=bad", "--help"])).toMatchObject({ code: 1, stderr: "rm: option '--one-file-system' doesn't allow an argument\nTry 'rm --help' for more information.\n" });
+ await mkdir(join(dir, "rm-one-file-system/sub"), { recursive: true });
+ await writeFile(join(dir, "rm-one-file-system/sub/file"), "x");
+ expect(await run(["rm", "--one-file-system", "-rf", "rm-one-file-system"])).toMatchObject({ code: 0, stderr: "" });
+ await expect(stat(join(dir, "rm-one-file-system"))).rejects.toThrow();
+ await mkdir(join(dir, "rm-preserve-root-all/sub"), { recursive: true });
+ await writeFile(join(dir, "rm-preserve-root-all/sub/file"), "x");
+ expect(await run(["rm", "--preserve-root=all", "-rf", "rm-preserve-root-all"])).toMatchObject({ code: 0, stderr: "" });
+ await expect(stat(join(dir, "rm-preserve-root-all"))).rejects.toThrow();
+ expect(await run(["rm", "--preserve-root=bogus", "-rf", "missing"])).toMatchObject({ code: 1, stderr: "rm: unrecognized --preserve-root argument: 'bogus'\n" });
+ expect(await shell(`
+ set -e
+ mkdir deep
+ perl -e 'my $d = "x" x 200; chdir "deep" or die $!; foreach my $i (1..24) { mkdir($d, 0700) && chdir $d or die $! }'
+ printf n > no
+ "$BUN" "$BNU" rm ---presume-input-tty -r deep < no
+ test ! -d deep
+ `)).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["mkdir", "-m", "u=rwx,go=", "private-dir"])).toMatchObject({ code: 0 });
+ expect(((await stat(join(dir, "private-dir"))).mode & 0o777)).toBe(0o700);
+ expect(await run(["mkdir", "-m", "755", "public-dir"])).toMatchObject({ code: 0 });
+ expect(((await stat(join(dir, "public-dir"))).mode & 0o777)).toBe(0o755);
+ expect(await run(["mkdir", "-Z", "context-dir"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "context-dir"))).isDirectory()).toBe(true);
+ expect(await run(["mkdir", "--context=system_u:object_r:tmp_t:s0"])).toMatchObject({
+ code: 1,
+ stderr: "mkdir: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\nmkdir: missing operand\nTry 'mkdir --help' for more information.\n",
+ });
+ expect(await run(["mkdir", "--context=system_u:object_r:tmp_t:s0", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: mkdir [OPTION]... DIRECTORY...\n"), stderr: "mkdir: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n" });
+ expect(await run(["mkdir", "--context=system_u:object_r:tmp_t:s0", "context-dir-2"])).toMatchObject({ code: 0, stderr: "mkdir: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n" });
+ expect((await stat(join(dir, "context-dir-2"))).isDirectory()).toBe(true);
+});
+
+test("cp, mv and ln support GNU target directory forms", async () => {
+ await mkdir(join(dir, "target"));
+ await writeFile(join(dir, "one"), "1");
+ await writeFile(join(dir, "two"), "2");
+ expect(await run(["cp"])).toMatchObject({
+ code: 1,
+ stderr: "cp: missing file operand\nTry 'cp --help' for more information.\n",
+ });
+ expect(await run(["cp", "missing-source", "target/missing-copy"])).toMatchObject(await systemRun(["/usr/bin/cp", "missing-source", "target/missing-copy"]));
+ expect(await run(["cp", "-T", "one", "two", "target"])).toMatchObject({
+ code: 1,
+ stderr: "cp: extra operand 'target'\nTry 'cp --help' for more information.\n",
+ });
+ expect(await run(["cp", "one", "two", "missing-target"])).toMatchObject({
+ code: 1,
+ stderr: "cp: target 'missing-target': No such file or directory\n",
+ });
+ expect(await run(["cp", "-t", "missing-target", "one"])).toMatchObject({
+ code: 1,
+ stderr: "cp: target directory 'missing-target': No such file or directory\n",
+ });
+ expect(await run(["cp", "--parents", "one", "two"])).toMatchObject({
+ code: 1,
+ stderr: "cp: with --parents, the destination must be a directory\nTry 'cp --help' for more information.\n",
+ });
+ await writeFile(join(dir, "backup-dst"), "old");
+ await writeFile(join(dir, "backup-empty-dst"), "old");
+ expect(await run(["cp", "--backup=", "one", "backup-empty-dst"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "backup-empty-dst"), "utf8")).toBe("1");
+ expect(await readFile(join(dir, "backup-empty-dst~"), "utf8")).toBe("old");
+ await writeFile(join(dir, "mv-backup-empty-src"), "new");
+ await writeFile(join(dir, "mv-backup-empty-dst"), "old");
+ expect(await run(["mv", "--backup=", "mv-backup-empty-src", "mv-backup-empty-dst"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "mv-backup-empty-dst"), "utf8")).toBe("new");
+ expect(await readFile(join(dir, "mv-backup-empty-dst~"), "utf8")).toBe("old");
+ await writeFile(join(dir, "backup-empty-env-dst"), "old");
+ expect(await run(["cp", "--backup=", "one", "backup-empty-env-dst"], "", { env: { VERSION_CONTROL: "bad\nmode" } })).toMatchObject({
+ code: 1,
+ stderr: `cp: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("$VERSION_CONTROL")}\nValid arguments are:\n - ${diagnosticQuote("none")}, ${diagnosticQuote("off")}\n - ${diagnosticQuote("simple")}, ${diagnosticQuote("never")}\n - ${diagnosticQuote("existing")}, ${diagnosticQuote("nil")}\n - ${diagnosticQuote("numbered")}, ${diagnosticQuote("t")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await run(["cp", "--backup=bad", "one", "backup-dst"])).toMatchObject(await systemRun(["cp", "--backup=bad", "one", "backup-dst"]));
+ expect(await run(["cp", "--backup=bad\nmode", "one", "backup-dst"])).toMatchObject({
+ code: 1,
+ stderr: `cp: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("backup type")}\nValid arguments are:\n - ${diagnosticQuote("none")}, ${diagnosticQuote("off")}\n - ${diagnosticQuote("simple")}, ${diagnosticQuote("never")}\n - ${diagnosticQuote("existing")}, ${diagnosticQuote("nil")}\n - ${diagnosticQuote("numbered")}, ${diagnosticQuote("t")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await readFile(join(dir, "backup-dst"), "utf8")).toBe("old");
+ await expect(stat(join(dir, "backup-dst~"))).rejects.toThrow();
+ expect(await run(["cp", "--backup", "one", "backup-dst"], "", { env: { VERSION_CONTROL: "bad" } })).toMatchObject(await systemRun(["cp", "--backup", "one", "backup-dst"], "", { env: { VERSION_CONTROL: "bad" } }));
+ expect(await run(["cp", "--backup", "one", "backup-dst"], "", { env: { VERSION_CONTROL: "bad\nmode" } })).toMatchObject({
+ code: 1,
+ stderr: `cp: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("$VERSION_CONTROL")}\nValid arguments are:\n - ${diagnosticQuote("none")}, ${diagnosticQuote("off")}\n - ${diagnosticQuote("simple")}, ${diagnosticQuote("never")}\n - ${diagnosticQuote("existing")}, ${diagnosticQuote("nil")}\n - ${diagnosticQuote("numbered")}, ${diagnosticQuote("t")}\nTry 'cp --help' for more information.\n`,
+ });
+ expect(await readFile(join(dir, "backup-dst"), "utf8")).toBe("old");
+ await expect(stat(join(dir, "backup-dst~"))).rejects.toThrow();
+ expect(await run(["cp", "-t", "target", "one", "two"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/one"), "utf8")).toBe("1");
+ expect(await readFile(join(dir, "target/two"), "utf8")).toBe("2");
+ expect(await run(["cp", "-T", "one", "target/flat"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/flat"), "utf8")).toBe("1");
+ expect(await run(["mv", "-t", "target", "one"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/one"), "utf8")).toBe("1");
+ await writeFile(join(dir, "move-src"), "m");
+ expect(await run(["mv", "-T", "move-src", "target/moved"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/moved"), "utf8")).toBe("m");
+ await writeFile(join(dir, "move-target-alias"), "a");
+ expect(await run(["mv", "--target=target", "move-target-alias"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/move-target-alias"), "utf8")).toBe("a");
+ await writeFile(join(dir, "move-target-prefix"), "p");
+ expect(await run(["mv", "--t", "target", "move-target-prefix"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/move-target-prefix"), "utf8")).toBe("p");
+ await writeFile(join(dir, "move-missing-target"), "m");
+ expect(await run(["mv", "-t", "missing-target", "move-missing-target"])).toMatchObject(await systemRun(["mv", "-t", "missing-target", "move-missing-target"]));
+ expect(await run(["mv", "--target=missing-target", "move-missing-target"])).toMatchObject(await systemRun(["mv", "--target=missing-target", "move-missing-target"]));
+ await writeFile(join(dir, "move-missing-a"), "a");
+ await writeFile(join(dir, "move-missing-b"), "b");
+ expect(await run(["mv", "move-missing-a", "move-missing-b", "missing-mv-target"])).toMatchObject({
+ code: 1,
+ stderr: "mv: target 'missing-mv-target': No such file or directory\n",
+ });
+ expect(await run(["mv", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: mv [OPTION]... [-T] SOURCE DEST\n or: mv [OPTION]... SOURCE... DIRECTORY\n or: mv [OPTION]... -t DIRECTORY SOURCE...\n") });
+ expect(await run(["mv", "--no", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "mv: option '--no' is ambiguous; possibilities: '--no-clobber' '--no-copy' '--no-target-directory'\nTry 'mv --help' for more information.\n",
+ });
+ expect(await run(["mv", "--force=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "mv: option '--force' doesn't allow an argument\nTry 'mv --help' for more information.\n",
+ });
+ expect(await run(["mv", "--debug=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "mv: option '--debug' doesn't allow an argument\nTry 'mv --help' for more information.\n",
+ });
+ expect(await run(["mv", "--update=", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `mv: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--update")}\nValid arguments are:\n - ${diagnosticQuote("all")}\n - ${diagnosticQuote("none")}\n - ${diagnosticQuote("none-fail")}\n - ${diagnosticQuote("older")}\nTry 'mv --help' for more information.\n`,
+ });
+ expect(await run(["mv", "--update=bad", "--help"])).toMatchObject(await systemRun(["mv", "--update=bad", "--help"]));
+ expect(await run(["mv", "--update=bad\nmode", "--help"])).toMatchObject({
+ code: 1,
+ stderr: `mv: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--update")}\nValid arguments are:\n - ${diagnosticQuote("all")}\n - ${diagnosticQuote("none")}\n - ${diagnosticQuote("none-fail")}\n - ${diagnosticQuote("older")}\nTry 'mv --help' for more information.\n`,
+ });
+ expect(await run(["mv", "--suffix", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["mv", "move-target-prefix", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: mv [OPTION]... [-T] SOURCE DEST\n"), stderr: "" });
+ expect(await run(["mv", "--ver=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "mv: option '--ver=bad' is ambiguous; possibilities: '--verbose' '--version'\nTry 'mv --help' for more information.\n",
+ });
+ expect(await run(["mv"])).toMatchObject({ code: 1, stderr: "mv: missing file operand\nTry 'mv --help' for more information.\n" });
+ await writeFile(join(dir, "exchange-a"), "left");
+ await writeFile(join(dir, "exchange-b"), "right");
+ expect(await run(["mv", "--exchange", "-vT", "exchange-a", "exchange-b"])).toMatchObject({ code: 0, stdout: "exchanged 'exchange-a' <-> 'exchange-b'\n" });
+ expect(await readFile(join(dir, "exchange-a"), "utf8")).toBe("right");
+ expect(await readFile(join(dir, "exchange-b"), "utf8")).toBe("left");
+ await writeFile(join(dir, "exchange-file"), "file");
+ await mkdir(join(dir, "exchange-dir"));
+ expect(await run(["mv", "--exchange", "-T", "exchange-file", "exchange-dir"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "exchange-file"))).isDirectory()).toBe(true);
+ expect(await readFile(join(dir, "exchange-dir"), "utf8")).toBe("file");
+ await mkdir(join(dir, "exchange-target"));
+ await writeFile(join(dir, "exchange-multi-a"), "A");
+ await writeFile(join(dir, "exchange-multi-b"), "B");
+ await writeFile(join(dir, "exchange-target/exchange-multi-a"), "TA");
+ await writeFile(join(dir, "exchange-target/exchange-multi-b"), "TB");
+ expect(await run(["mv", "--exchange", "-t", "exchange-target", "exchange-multi-a", "exchange-multi-b"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "exchange-multi-a"), "utf8")).toBe("TA");
+ expect(await readFile(join(dir, "exchange-multi-b"), "utf8")).toBe("TB");
+ expect(await readFile(join(dir, "exchange-target/exchange-multi-a"), "utf8")).toBe("A");
+ expect(await readFile(join(dir, "exchange-target/exchange-multi-b"), "utf8")).toBe("B");
+ expect(await run(["mv", "--exchange", "-t", "exchange-target", "exchange-missing-a", "exchange-missing-b"])).toMatchObject({
+ code: 1,
+ stderr: "mv: cannot stat 'exchange-missing-a': No such file or directory\nmv: cannot stat 'exchange-missing-b': No such file or directory\n",
+ });
+ expect(await run(["mv", "--exchange", "exchange-dir", "exchange-missing"])).toMatchObject({ code: 1 });
+ expect(await run(["mv", "--exchange", "exchange-a", "exchange-b", "exchange-missing-target"])).toMatchObject({
+ code: 1,
+ stderr: "mv: target 'exchange-missing-target': No such file or directory\n",
+ });
+ expect(await run(["mv", "missing-only"])).toMatchObject({ code: 1, stderr: "mv: missing destination file operand after 'missing-only'\nTry 'mv --help' for more information.\n" });
+ await mkdir(join(dir, "replace-dir/sub"), { recursive: true });
+ await mkdir(join(dir, "empty-dir-target"));
+ expect(await run(["mv", "-fT", "replace-dir", "empty-dir-target"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "empty-dir-target/sub"))).isDirectory()).toBe(true);
+ await mkdir(join(dir, "nonempty-src"));
+ await mkdir(join(dir, "nonempty-target/sub"), { recursive: true });
+ expect(await run(["mv", "-fT", "nonempty-src", "nonempty-target"])).toMatchObject({ code: 1 });
+ await writeFile(join(dir, "file-over-dir"), "x");
+ await mkdir(join(dir, "dir-target"));
+ expect(await run(["mv", "-fT", "file-over-dir", "dir-target"])).toMatchObject({ code: 1 });
+ await writeFile(join(dir, "link-src"), "l");
+ await writeFile(join(dir, "ln-interactive-dst"), "old");
+ expect(await run(["ln", "-i", "link-src", "ln-interactive-dst"], "n\n")).toMatchObject({
+ code: 1,
+ stderr: "ln: replace 'ln-interactive-dst'? ",
+ });
+ expect(await readFile(join(dir, "ln-interactive-dst"), "utf8")).toBe("old");
+ expect(await run(["ln", "-if", "link-src", "ln-interactive-dst"], "n\n")).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(join(dir, "ln-interactive-dst"), "utf8")).toBe("l");
+ expect(await run(["ln", "-s", "-t", "target", "link-src"])).toMatchObject({ code: 0 });
+ expect(await run(["readlink", "target/link-src"])).toMatchObject({ code: 0, stdout: "link-src\n" });
+ await writeFile(join(dir, "ln-target-prefix-src"), "prefix");
+ expect(await run(["ln", "--target", "target", "ln-target-prefix-src"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/ln-target-prefix-src"), "utf8")).toBe("prefix");
+ await writeFile(join(dir, "ln-target-dir-alias-src"), "alias");
+ expect(await run(["ln", "--target-dir=target", "ln-target-dir-alias-src"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/ln-target-dir-alias-src"), "utf8")).toBe("alias");
+ const lnHelp = await run(["ln", "--help"]);
+ expect(lnHelp.stdout).toContain(" -d\n");
+ expect(lnHelp).toMatchObject({ code: 0, stdout: expect.stringContaining("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...\n") });
+ expect(await run(["ln", "-d", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: ln [OPTION]... [-T] TARGET LINK_NAME\n") });
+ expect(await run(["ln", "--n", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "ln: option '--n' is ambiguous; possibilities: '--no-dereference' '--no-target-directory'\nTry 'ln --help' for more information.\n",
+ });
+ expect(await run(["ln", "--s", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "ln: option '--s' is ambiguous; possibilities: '--suffix' '--symbolic'\nTry 'ln --help' for more information.\n",
+ });
+ expect(await run(["ln", "--force=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "ln: option '--force' doesn't allow an argument\nTry 'ln --help' for more information.\n",
+ });
+ expect(await run(["ln", "--symbolic=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "ln: option '--symbolic' doesn't allow an argument\nTry 'ln --help' for more information.\n",
+ });
+ expect(await run(["ln", "--suffix", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["ln", "--ver=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "ln: option '--ver=bad' is ambiguous; possibilities: '--verbose' '--version'\nTry 'ln --help' for more information.\n",
+ });
+ expect(await run(["ln"])).toMatchObject({ code: 1, stderr: "ln: missing file operand\nTry 'ln --help' for more information.\n" });
+ expect(await run(["ln", "-t", "missing-ln-target", "link-src"])).toMatchObject({
+ code: 1,
+ stderr: "ln: failed to access 'missing-ln-target': No such file or directory\n",
+ });
+ await writeFile(join(dir, "ln-file-target"), "file");
+ expect(await run(["ln", "-t", "ln-file-target", "link-src"])).toMatchObject({
+ code: 1,
+ stderr: "ln: target 'ln-file-target' is not a directory\n",
+ });
+ expect(await run(["ln", "one", "two", "missing-ln-dir"])).toMatchObject({
+ code: 1,
+ stderr: "ln: target 'missing-ln-dir': No such file or directory\n",
+ });
+ expect(await run(["ln", "missing-ln-source", "ln-missing-target"])).toMatchObject({
+ code: 1,
+ stderr: "ln: failed to access 'missing-ln-source': No such file or directory\n",
+ });
+ expect(await run(["ln", "missing\nln-source", "ln-missing-newline-target"])).toMatchObject({
+ code: 1,
+ stderr: "ln: failed to access 'missing'$'\\n''ln-source': No such file or directory\n",
+ });
+ expect(await run(["ln", "missing'ln-source", "ln-missing-quote-target"])).toMatchObject({
+ code: 1,
+ stderr: "ln: failed to access \"missing'ln-source\": No such file or directory\n",
+ });
+ expect(await run(["ln", "-t", "missing\nln-target", "link-src"])).toMatchObject({
+ code: 1,
+ stderr: "ln: failed to access 'missing'$'\\n''ln-target': No such file or directory\n",
+ });
+ await mkdir(join(dir, "ln-hard-directory-source"));
+ expect(await run(["ln", "ln-hard-directory-source", "ln-hard-directory-target"])).toMatchObject({
+ code: 1,
+ stderr: "ln: ln-hard-directory-source: hard link not allowed for directory\n",
+ });
+ await mkdir(join(dir, "ln-hard-directory\nsource"));
+ expect(await run(["ln", "ln-hard-directory\nsource", "ln-hard-directory-newline-target"])).toMatchObject({
+ code: 1,
+ stderr: "ln: 'ln-hard-directory'$'\\n''source': hard link not allowed for directory\n",
+ });
+ await mkdir(join(dir, "ln-hard-directory'source"));
+ expect(await run(["ln", "ln-hard-directory'source", "ln-hard-directory-quote-target"])).toMatchObject({
+ code: 1,
+ stderr: "ln: \"ln-hard-directory'source\": hard link not allowed for directory\n",
+ });
+ expect(await run(["ln", "link-src", "link-src"])).toMatchObject({
+ code: 1,
+ stderr: "ln: failed to create hard link 'link-src': File exists\n",
+ });
+ expect(await run(["ln", "-s", "link-src"])).toMatchObject(await systemRun(["/usr/bin/ln", "-s", "link-src"]));
+ expect(await run(["ln", "-b", "link-src", "link-src"])).toMatchObject({
+ code: 1,
+ stderr: "ln: 'link-src' and 'link-src' are the same file\n",
+ });
+ const lnValidBackupModes = `Valid arguments are:\n - ${diagnosticQuote("none")}, ${diagnosticQuote("off")}\n - ${diagnosticQuote("simple")}, ${diagnosticQuote("never")}\n - ${diagnosticQuote("existing")}, ${diagnosticQuote("nil")}\n - ${diagnosticQuote("numbered")}, ${diagnosticQuote("t")}\n`;
+ await writeFile(join(dir, "ln-backup-empty"), "old");
+ expect(await run(["ln", "--backup=", "link-src", "ln-backup-empty"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "ln-backup-empty~"), "utf8")).toBe("old");
+ await writeFile(join(dir, "ln-backup-empty-env-bad"), "old");
+ expect(await run(["ln", "--backup=", "link-src", "ln-backup-empty-env-bad"], "", { env: { VERSION_CONTROL: "bad" } })).toMatchObject({
+ code: 1,
+ stderr: `ln: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("$VERSION_CONTROL")}\n${lnValidBackupModes}Try 'ln --help' for more information.\n`,
+ });
+ expect(await run(["ln", "--backup=bad", "link-src", "ln-backup-bad"])).toMatchObject({
+ code: 1,
+ stderr: `ln: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("backup type")}\n${lnValidBackupModes}Try 'ln --help' for more information.\n`,
+ });
+ expect(await run(["ln", "--backup", "link-src", "ln-backup-env-bad"], "", { env: { VERSION_CONTROL: "bad" } })).toMatchObject({
+ code: 1,
+ stderr: `ln: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("$VERSION_CONTROL")}\n${lnValidBackupModes}Try 'ln --help' for more information.\n`,
+ });
+ expect(await run(["ln", "-r", "link-src", "ln-relative-without-symbolic"])).toMatchObject({
+ code: 1,
+ stderr: "ln: cannot do --relative without --symbolic\n",
+ });
+ expect(await run(["ln", "-T", "link-src", "target"])).toMatchObject({
+ code: 1,
+ stderr: "ln: failed to create hard link 'target': File exists\n",
+ });
+ const lnDirectoryShort = await run(["ln", "-F", ".", "ln-directory-short"]);
+ expect(lnDirectoryShort.code).toBe(1);
+ expect(lnDirectoryShort.stderr).toContain("ln: failed to create hard link 'ln-directory-short'");
+ expect(lnDirectoryShort.stderr).not.toContain("invalid option");
+ const lnDirectoryShortD = await run(["ln", "-d", ".", "ln-directory-short-d"]);
+ expect(lnDirectoryShortD.code).toBe(1);
+ expect(lnDirectoryShortD.stderr).toContain("ln: failed to create hard link 'ln-directory-short-d'");
+ expect(lnDirectoryShortD.stderr).not.toContain("invalid option");
+ const lnDirectoryLong = await run(["ln", "--directory", ".", "ln-directory-long"]);
+ expect(lnDirectoryLong.code).toBe(1);
+ expect(lnDirectoryLong.stderr).toContain("ln: failed to create hard link 'ln-directory-long'");
+ expect(lnDirectoryLong.stderr).not.toContain("unrecognized option");
+ expect(await run(["ln", "-sF", ".", "ln-directory-symlink"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "ln-directory-symlink"))).isSymbolicLink()).toBe(true);
+ await symlink("missing-ln-source", join(dir, "ln-dangling"));
+ expect(await run(["ln", "-L", "ln-dangling", "ln-logical-hard"])).toMatchObject({
+ code: 1,
+ stderr: "ln: failed to access 'ln-dangling': No such file or directory\n",
+ });
+ expect(await run(["ln", "-P", "ln-dangling", "ln-physical-hard"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "ln-physical-hard"))).isSymbolicLink()).toBe(true);
+ await mkdir(join(dir, "childproof-ln-target"));
+ await mkdir(join(dir, "childproof-ln-a"));
+ await mkdir(join(dir, "childproof-ln-b"));
+ await writeFile(join(dir, "childproof-ln-a/f"), "a");
+ await writeFile(join(dir, "childproof-ln-b/f"), "b");
+ expect(await run(["ln", "-f", "childproof-ln-a/f", "childproof-ln-b/f", "childproof-ln-target"])).toMatchObject({ code: 1 });
+ expect((await stat(join(dir, "childproof-ln-a/f"))).ino).toBe((await stat(join(dir, "childproof-ln-target/f"))).ino);
+ expect((await stat(join(dir, "childproof-ln-b/f"))).ino).not.toBe((await stat(join(dir, "childproof-ln-target/f"))).ino);
+ expect(await shell(`
+ set -e
+ name=$(printf '\\377')
+ printf x > "$name"
+ mkdir raw-dst
+ "$BUN" "$BNU" ln "$name" raw-dst
+ test -f "raw-dst/$name"
+ "$BUN" "$BNU" rm -f "raw-dst/$name"
+ "$BUN" "$BNU" ln -s -t raw-dst "$name"
+ test -L "raw-dst/$name"
+ "$BUN" "$BNU" chmod -R u+rwx .
+ "$BUN" "$BNU" rm -rf raw-dst "$name"
+ `)).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await shell(`
+ set -e
+ name=$(printf '\\377\\174\\355\\272\\255\\174\\302\\211\\174\\355\\246\\277\\355\\277\\277')
+ mkdir "$name" cp-raw-dst
+ printf 1 > "$name/file1"
+ printf 2 > "$name/file2"
+ LC_ALL=C "$BUN" "$BNU" cp -r "$name"/. cp-raw-dst
+ test "$(cat cp-raw-dst/file1)" = 1
+ test "$(cat cp-raw-dst/file2)" = 2
+ "$BUN" "$BNU" rm cp-raw-dst/file1 cp-raw-dst/file2
+ test -f "$name/file1"
+ test -f "$name/file2"
+ "$BUN" "$BNU" chmod -R u+rwx .
+ "$BUN" "$BNU" rm -rf cp-raw-dst "$name"
+ `)).toMatchObject({ code: 0, stdout: "", stderr: "" });
+});
+
+test("readlink and realpath support canonical and relative output modes", async () => {
+ await mkdir(join(dir, "root/actual/sub"), { recursive: true });
+ await writeFile(join(dir, "root/actual/sub/file"), "payload");
+ await symlink("actual", join(dir, "root/link"));
+ expect(await run(["readlink", "root/link"])).toMatchObject({ code: 0, stdout: "actual\n" });
+ expect(await run(["readlink", "-n", "root/link"])).toMatchObject({ code: 0, stdout: "actual" });
+ expect(await run(["readlink", "-z", "root/link"])).toMatchObject({ code: 0, stdout: "actual\0" });
+ expect(await run(["readlink", "--no-n", "root/link"])).toMatchObject({ code: 0, stdout: "actual" });
+ expect(await run(["readlink", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "readlink: unrecognized option '--bad'\nTry 'readlink --help' for more information.\n" });
+ expect(await run(["readlink", "--c", "root/link", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "readlink: option '--c' is ambiguous; possibilities: '--canonicalize' '--canonicalize-existing' '--canonicalize-missing'\nTry 'readlink --help' for more information.\n" });
+ expect(await run(["readlink", "--zero=foo", "root/link"])).toMatchObject({ code: 1, stdout: "", stderr: "readlink: option '--zero' doesn't allow an argument\nTry 'readlink --help' for more information.\n" });
+ const readlinkHelp = (await run(["readlink", "--z", "root/link", "--help"])).stdout;
+ expect(readlinkHelp).toContain("Usage: readlink [OPTION]... FILE...\n");
+ expect(readlinkHelp).toContain("-f, --canonicalize\n canonicalize by following every symlink\n");
+ expect(readlinkHelp).toContain(" all but the last component must exist\n");
+ expect(readlinkHelp).toContain("-q, --quiet\n suppress most error messages\n");
+ expect(readlinkHelp).toContain("-s, --silent\n suppress most error messages\n");
+ expect(readlinkHelp).toContain("-z, --zero\n end each output line with NUL, not newline\n");
+ expect(await run(["readlink", "missing-readlink"])).toMatchObject({ code: 1, stdout: "", stderr: "" });
+ expect(await run(["readlink", "-v", "missing-readlink"])).toMatchObject({ code: 1, stdout: "", stderr: "readlink: missing-readlink: No such file or directory\n" });
+ expect(await run(["readlink", "-v", "missing\nreadlink"])).toMatchObject({ code: 1, stdout: "", stderr: "readlink: 'missing'$'\\n''readlink': No such file or directory\n" });
+ expect(await run(["readlink", "-v", "missing'readlink"])).toMatchObject({ code: 1, stdout: "", stderr: "readlink: \"missing'readlink\": No such file or directory\n" });
+ expect(await run(["readlink", "-qv", "missing-readlink"])).toMatchObject({ code: 1, stdout: "", stderr: "readlink: missing-readlink: No such file or directory\n" });
+ expect(await run(["readlink", "-vq", "missing-readlink"])).toMatchObject({ code: 1, stdout: "", stderr: "" });
+ await writeFile(join(dir, "regular-readlink"), "regular");
+ await writeFile(join(dir, "regular'readlink"), "regular");
+ expect(await run(["readlink", "regular-readlink"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stdout: "", stderr: "readlink: regular-readlink: Invalid argument\n" });
+ expect(await run(["readlink", "regular'readlink"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stdout: "", stderr: "readlink: \"regular'readlink\": Invalid argument\n" });
+ expect(await run(["readlink", "-q", "regular-readlink"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stdout: "", stderr: "readlink: regular-readlink: Invalid argument\n" });
+ expect(await run(["readlink", "missing-readlink"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stdout: "", stderr: "readlink: missing-readlink: No such file or directory\n" });
+ expect(await run(["readlink", "-f", "regular-readlink"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: `${join(dir, "regular-readlink")}\n`, stderr: "" });
+ expect(await run(["readlink"])).toMatchObject({ code: 1, stderr: "readlink: missing operand\nTry 'readlink --help' for more information.\n" });
+ expect(await run(["readlink", "-f", "root/link/sub/file"])).toMatchObject({ code: 0, stdout: `${join(dir, "root/actual/sub/file")}\n` });
+ expect(await run(["readlink", "-m", "root/link/"])).toMatchObject({ code: 0, stdout: `${join(dir, "root/actual")}\n` });
+ expect(await run(["readlink", "-m", "root/actual/sub/file/extra"])).toMatchObject({ code: 0, stdout: `${join(dir, "root/actual/sub/file/extra")}\n` });
+ expect(await run(["readlink", "-m", "-n", "--zero", "/1", "/1"])).toMatchObject({ code: 0, stdout: "/1\0/1\0" });
+ expect(await run(["readlink", "root/link", "missing"])).toMatchObject({ code: 1, stdout: "actual\n" });
+ expect(await run(["realpath", "-e", "root/link/sub/file"])).toMatchObject({ code: 0, stdout: `${join(dir, "root/actual/sub/file")}\n` });
+ expect(await run(["realpath", "-m", "root/link/missing/../sub/file"])).toMatchObject({ code: 0, stdout: `${join(dir, "root/actual/sub/file")}\n` });
+ expect(await run(["realpath", "-s", "root/link/sub/file"])).toMatchObject({ code: 0, stdout: `${join(dir, "root/link/sub/file")}\n` });
+ expect(await run(["realpath", "--relative-to=root", "root/link/sub/file"])).toMatchObject({ code: 0, stdout: "actual/sub/file\n" });
+ expect(await run(["realpath", "--relative-to", "--help", "root/link/sub/file"])).toMatchObject({ code: 0, stdout: "../root/actual/sub/file\n" });
+ const realpathHelp = (await run(["realpath", "--relative-to=root", "--help", "root/link/sub/file"])).stdout;
+ expect(realpathHelp).toContain("Usage: realpath [OPTION]... FILE...\n");
+ expect(realpathHelp).toContain("-E, --canonicalize all but the last component must exist (default)\n");
+ expect(realpathHelp).toContain("-m, --canonicalize-missing no path components need exist or be a directory\n");
+ expect(realpathHelp).toContain("--relative-to=DIR print the resolved path relative to DIR\n");
+ expect(realpathHelp).toContain("-s, --strip, --no-symlinks don't expand symlinks\n");
+ expect(realpathHelp).toContain("-z, --zero end each output line with NUL, not newline\n");
+ expect(await run(["realpath", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "realpath: unrecognized option '--bad'\nTry 'realpath --help' for more information.\n" });
+ expect(await run(["realpath", "--r=root", "root/link/sub/file"])).toMatchObject({ code: 1, stdout: "", stderr: "realpath: option '--r=root' is ambiguous; possibilities: '--relative-to' '--relative-base'\nTry 'realpath --help' for more information.\n" });
+ expect(await run(["realpath", "--zero=foo", "root/link/sub/file"])).toMatchObject({ code: 1, stdout: "", stderr: "realpath: option '--zero' doesn't allow an argument\nTry 'realpath --help' for more information.\n" });
+ expect(await run(["realpath", "-z", "root/link/sub/file"])).toMatchObject({ code: 0, stdout: `${join(dir, "root/actual/sub/file")}\0` });
+ expect(await run(["realpath"])).toMatchObject({ code: 1, stderr: "realpath: missing operand\nTry 'realpath --help' for more information.\n" });
+ expect(await run(["realpath", "-e", "missing"])).toMatchObject({ code: 1, stdout: "", stderr: "realpath: missing: No such file or directory\n" });
+ expect(await run(["realpath", "-e", "missing\nrealpath"])).toMatchObject({ code: 1, stdout: "", stderr: "realpath: 'missing'$'\\n''realpath': No such file or directory\n" });
+ expect(await run(["realpath", "-e", "missing'realpath"])).toMatchObject({ code: 1, stdout: "", stderr: "realpath: \"missing'realpath\": No such file or directory\n" });
+ expect(await run(["realpath", "-q", "-e", "missing"])).toMatchObject({ code: 1, stdout: "", stderr: "" });
+ expect(await run(["realpath", ""])).toEqual(await systemRun(["realpath", ""]));
+ expect(await run(["realpath", "-q", ""])).toEqual(await systemRun(["realpath", "-q", ""]));
+ await writeFile(join(dir, "plain-realpath"), "plain");
+ expect(await run(["realpath", "-e", "--relative-to=missing\nbase", "plain-realpath"])).toMatchObject({ code: 1, stdout: "", stderr: "realpath: 'missing'$'\\n''base': No such file or directory\n" });
+ await writeFile(join(dir, "realpath'not-dir"), "plain");
+ expect(await run(["realpath", "-e", "--relative-base=realpath'not-dir", "plain-realpath"])).toMatchObject({ code: 1, stdout: "", stderr: "realpath: \"realpath'not-dir\": Not a directory\n" });
+ expect(await run(["realpath", "--relative-to=", "plain-realpath"])).toEqual(await systemRun(["realpath", "--relative-to=", "plain-realpath"]));
+ expect(await run(["realpath", "-q", "--relative-to=", "plain-realpath"])).toEqual(await systemRun(["realpath", "-q", "--relative-to=", "plain-realpath"]));
+ expect(await run(["realpath", "--relative-base=", "plain-realpath"])).toEqual(await systemRun(["realpath", "--relative-base=", "plain-realpath"]));
+ expect(await run(["realpath", "-e", "missing", "root/link/sub/file"])).toMatchObject({ code: 1, stdout: `${join(dir, "root/actual/sub/file")}\n`, stderr: "realpath: missing: No such file or directory\n" });
+});
+
+test("seq, printenv, env, test, true and false", async () => {
+ expect(await run(["seq", "3"])).toMatchObject({ code: 0, stdout: "1\n2\n3\n" });
+ expect(await run(["seq", "0", ".1", ".3"])).toMatchObject({ code: 0, stdout: "0.0\n0.1\n0.2\n0.3\n" });
+ expect(await run(["seq", "1.00", ".25", "1.50"])).toMatchObject({ code: 0, stdout: "1.00\n1.25\n1.50\n" });
+ expect(await run(["seq", "-s", ",", "-w", "-2", "2", "2"])).toMatchObject({ code: 0, stdout: "-2,00,02\n" });
+ expect(await run(["seq", "-w", "-10", "5", "0"])).toMatchObject({ code: 0, stdout: "-10\n-05\n000\n" });
+ expect(await run(["seq", "-f", "v%04.1f", "1", "0.5", "2"])).toMatchObject({ code: 0, stdout: "v01.0\nv01.5\nv02.0\n" });
+ expect(await run(["seq", "-f", "%010.2e", "1", "3"])).toMatchObject({ code: 0, stdout: "001.00e+00\n002.00e+00\n003.00e+00\n" });
+ expect(await run(["seq", "-f", "%A", "1", "3"])).toMatchObject({ code: 0, stdout: "0X8P-3\n0X8P-2\n0XCP-2\n" });
+ expect(await run(["seq", "-f", "%+010a", "1", "3"])).toMatchObject({ code: 0, stdout: "+0x0008p-3\n+0x0008p-2\n+0x000cp-2\n" });
+ expect(await run(["seq", "-f", "%#.3a", "1", "3"])).toMatchObject({ code: 0, stdout: "0x8.000p-3\n0x8.000p-2\n0xc.000p-2\n" });
+ expect(await run(["seq", "--f=%02g", "1", "3"])).toMatchObject({ code: 0, stdout: "01\n02\n03\n" });
+ expect(await run(["seq", "--s", ",", "1", "3"])).toMatchObject({ code: 0, stdout: "1,2,3\n" });
+ expect(await run(["seq", "--e", "8", "10"])).toMatchObject({ code: 0, stdout: "08\n09\n10\n" });
+ expect(await run(["seq", "10.8", "0.1", "10.95"])).toMatchObject({ code: 0, stdout: "10.8\n10.9\n" });
+ expect(await run(["seq", "-s,,", "1", "3"])).toMatchObject({ code: 0, stdout: "1,,2,,3\n" });
+ expect(await run(["seq", "999999999999999999999999999999999999999999999999999999999999999999999999999999999", "1000000000000000000000000000000000000000000000000000000000000000000000000000000001"])).toMatchObject({ code: 0, stdout: "999999999999999999999999999999999999999999999999999999999999999999999999999999999\n1000000000000000000000000000000000000000000000000000000000000000000000000000000000\n1000000000000000000000000000000000000000000000000000000000000000000000000000000001\n" });
+ expect(await run(["seq", "18446744073709551617", "18446744073709551617"])).toMatchObject({ code: 0, stdout: "18446744073709551617\n" });
+ expect(await run(["seq", "-0", "2"])).toMatchObject({ code: 0, stdout: "-0\n1\n2\n" });
+ expect((await shell(`"$BUN" "$BNU" seq inf inf 2>/dev/null | head -n3`)).stdout).toBe("inf\ninf\ninf\n");
+ expect((await shell(`"$BUN" "$BNU" seq -f %f inf inf 2>/dev/null | head -n3`)).stdout).toBe("inf\ninf\ninf\n");
+ expect((await shell(`"$BUN" "$BNU" seq -f %010f inf inf 2>/dev/null | head -n1`)).stdout).toBe(" inf\n");
+ expect(await run(["seq"])).toMatchObject({ code: 1, stderr: "seq: missing operand\nTry 'seq --help' for more information.\n" });
+ expect(await run(["seq", "1", "2", "3", "4"])).toMatchObject(await systemRun(["seq", "1", "2", "3", "4"]));
+ expect(await run(["seq", "-s"])).toMatchObject({ code: 1, stderr: "seq: option requires an argument -- 's'\nTry 'seq --help' for more information.\n" });
+ expect(await run(["seq", "--separator"])).toMatchObject({ code: 1, stderr: "seq: option '--separator' requires an argument\nTry 'seq --help' for more information.\n" });
+ expect(await run(["seq", "-f"])).toMatchObject({ code: 1, stderr: "seq: option requires an argument -- 'f'\nTry 'seq --help' for more information.\n" });
+ expect(await run(["seq", "--format"])).toMatchObject({ code: 1, stderr: "seq: option '--format' requires an argument\nTry 'seq --help' for more information.\n" });
+ expect(await run(["seq", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "seq: unrecognized option '--bad'\nTry 'seq --help' for more information.\n" });
+ expect(await run(["seq", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: seq [OPTION]... LAST\n or: seq [OPTION]... FIRST LAST\n or: seq [OPTION]... FIRST INCREMENT LAST\n") });
+ expect(await run(["seq", "--version=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "seq: option '--version' doesn't allow an argument\nTry 'seq --help' for more information.\n" });
+ expect(await run(["seq", "--equal-width=foo", "1", "3"])).toMatchObject({ code: 1, stdout: "", stderr: "seq: option '--equal-width' doesn't allow an argument\nTry 'seq --help' for more information.\n" });
+ expect(await run(["seq", "--separator", "--help", "1", "3"])).toMatchObject({ code: 0, stdout: "1--help2--help3\n" });
+ expect(await run(["seq", "1", "--separator=,", "3"])).toMatchObject(await systemRun(["seq", "1", "--separator=,", "3"]));
+ expect(await run(["seq", "1", "3", "--help"])).toMatchObject(await systemRun(["seq", "1", "3", "--help"]));
+ expect(await run(["seq", "1\n2"])).toMatchObject(await systemRun(["seq", "1\n2"]));
+ expect(await run(["seq", "1", "0\t0", "2"])).toMatchObject(await systemRun(["seq", "1", "0\t0", "2"]));
+ expect(await run(["seq", "1", "2", "3", "4\n5"])).toMatchObject(await systemRun(["seq", "1", "2", "3", "4\n5"]));
+ expect(await run(["seq", "3 "])).toMatchObject(await systemRun(["seq", "3 "]));
+ expect(await run(["seq", " 3"])).toMatchObject(await systemRun(["seq", " 3"]));
+ expect(await run(["seq", "1e", "3"])).toMatchObject(await systemRun(["seq", "1e", "3"]));
+ expect(await run(["seq", "1", "1e", "3"])).toMatchObject(await systemRun(["seq", "1", "1e", "3"]));
+ expect(await run(["seq", "1", "1", "1e"])).toMatchObject(await systemRun(["seq", "1", "1", "1e"]));
+ expect(await run(["seq", "nan"])).toMatchObject(await systemRun(["seq", "nan"]));
+ expect(await run(["seq", "nan", "1"])).toMatchObject(await systemRun(["seq", "nan", "1"]));
+ expect(await run(["seq", "1", "nan", "2"])).toMatchObject(await systemRun(["seq", "1", "nan", "2"]));
+ expect(await run(["seq", "1", "1", "nan"])).toMatchObject(await systemRun(["seq", "1", "1", "nan"]));
+ expect(await run(["seq", "-nan", "1"])).toMatchObject(await systemRun(["seq", "-nan", "1"]));
+ expect(await run(["seq", "1", "0", "bad"])).toMatchObject(await systemRun(["seq", "1", "0", "bad"]));
+ expect(await run(["seq", "--format=%s", "1", "2"])).toMatchObject({ code: 1, stderr: `seq: format ${diagnosticQuote("%s")} has unknown %s directive\n` });
+ expect(await run(["seq", "--format=x%y", "1", "2"])).toMatchObject({ code: 1, stderr: `seq: format ${diagnosticQuote("x%y")} has unknown %y directive\n` });
+ expect(await run(["seq", "--format=x%y\nz", "1", "2"])).toMatchObject({ code: 1, stderr: `seq: format ${diagnosticQuote("x%y\\nz")} has unknown %y directive\n` });
+ expect(await run(["seq", "--format=x%", "1", "2"])).toMatchObject({ code: 1, stderr: `seq: format ${diagnosticQuote("x%")} ends in %\n` });
+ expect(await run(["seq", "--format=%g%s", "1", "2"])).toMatchObject({ code: 1, stderr: `seq: format ${diagnosticQuote("%g%s")} has too many % directives\n` });
+ expect(await run(["seq", "--format=%g\n%s", "1", "2"])).toMatchObject({ code: 1, stderr: `seq: format ${diagnosticQuote("%g\\n%s")} has too many % directives\n` });
+ expect(await run(["seq", "--format=abc", "1", "2"])).toMatchObject({ code: 1, stderr: `seq: format ${diagnosticQuote("abc")} has no % directive\n` });
+ expect(await run(["seq", "--format=%2147483648g", "1", "0"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["seq", "--format=%2147483648g", "1", "1"])).toMatchObject({ code: 1, stdout: "", stderr: "seq: write error: Value too large for defined data type\n" });
+ expect(await run(["seq", "--format=%.2147483648g", "1", "1"])).toMatchObject({ code: 1, stdout: "", stderr: "seq: write error: Value too large for defined data type\n" });
+ expect((await shell(`bash -c '(trap "" PIPE; bash -c '\\''trap - PIPE; "$BUN" "$BNU" seq 999999 2>err | head -n1 >out'\\''; sed "s/^\\\\(seq: write error:\\\\) .*/\\\\1/" err)'`)).stdout).toBe("seq: write error:\n");
+ expect(await shell(`bash -c '(trap "" PIPE; "$BUN" "$BNU" env --default-signal bash -c '\\''trap - PIPE; "$BUN" "$BNU" seq 999999 2>err | head -n1 >out'\\''; cat out; cat err)'`)).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await shell(`bash -c '(trap "" PIPE; printf x | "$BUN" "$BNU" env --default-signal=PIPE "$BUN" "$BNU" dd status=none 2>err | :; cat err)'`)).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["env", "--default-signal=BAD", "true"])).toMatchObject({ code: 125, stderr: "env: 'BAD': invalid signal\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--ignore-signal=BAD", "true"])).toMatchObject({ code: 125, stderr: "env: 'BAD': invalid signal\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--block-signal=BAD", "true"])).toMatchObject({ code: 125, stderr: "env: 'BAD': invalid signal\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--deb=bad"])).toMatchObject(await systemRun(["env", "--deb=bad"]));
+ expect(await run(["env", "--default-s=BAD", "true"])).toMatchObject({ code: 125, stderr: "env: 'BAD': invalid signal\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--ignore-s=BAD", "true"])).toMatchObject({ code: 125, stderr: "env: 'BAD': invalid signal\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--block-s=BAD", "true"])).toMatchObject({ code: 125, stderr: "env: 'BAD': invalid signal\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--list-signal=bad"])).toMatchObject(await systemRun(["env", "--list-signal=bad"]));
+ expect((await run(["printenv", "PATH"])).code).toBe(0);
+ expect((await run(["printenv", "-0", "PATH"])).stdout).toEndWith("\0");
+ expect(await run(["printenv", "--n", "PATH"])).toMatchObject({ code: 0, stdout: expect.stringMatching(/\0$/) });
+ const printenvHelp = (await run(["printenv", "--h"])).stdout;
+ expect(printenvHelp).toContain("Usage: printenv [OPTION] [VARIABLE]...\n");
+ expect(printenvHelp).toContain("-0, --null end each output line with NUL, not newline\n");
+ expect(printenvHelp).toContain("Your shell may have its own version of printenv, which usually supersedes\nthe version described here. Please refer to your shell's documentation\n");
+ expect(await run(["printenv", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["printenv", "--n=1", "PATH"])).toMatchObject({ code: 2, stderr: "printenv: option '--null' doesn't allow an argument\nTry 'printenv --help' for more information.\n" });
+ expect(await run(["printenv", "PATH", "--h"])).toMatchObject({ code: 1, stdout: expect.stringMatching(/\n$/) });
+ expect(await run(["printenv", "--bad", "--help"])).toMatchObject({ code: 2, stderr: "printenv: unrecognized option '--bad'\nTry 'printenv --help' for more information.\n" });
+ expect(await run(["printenv", "-a"], "", { env: { "-a": "b" } })).toMatchObject({ code: 2, stderr: "printenv: invalid option -- 'a'\nTry 'printenv --help' for more information.\n" });
+ expect(await run(["printenv", "--", "-a"], "", { env: { "-a": "b" } })).toMatchObject({ code: 0, stdout: "b\n" });
+ expect(await run(["printenv", "--nullish"], "", { env: { "--nullish": "long" } })).toMatchObject({ code: 2, stderr: "printenv: unrecognized option '--nullish'\nTry 'printenv --help' for more information.\n" });
+ const printenvWrapper = join(dir, "printenv-wrapper");
+ await writeFile(printenvWrapper, `#!${process.execPath}
+import { readFileSync } from "node:fs";
+import { main } from ${JSON.stringify(pathToFileURL(join(import.meta.dir, "../src/coreutils.js")).href)};
+
+function rawScriptArgs() {
+ try {
+ const parts = readFileSync("/proc/self/cmdline", "utf8").split("\\0").filter(Boolean);
+ const scriptIndex = parts.indexOf(Bun.argv[1]);
+ if (scriptIndex !== -1) return parts.slice(scriptIndex + 1);
+ } catch {}
+ return Bun.argv.slice(2);
+}
+
+process.exit(await main(["printenv", ...rawScriptArgs()]));
+`);
+ await chmod(printenvWrapper, 0o755);
+ expect(await systemRun([printenvWrapper, "--", "-a"], "", { env: { "-a": "b" } })).toMatchObject({ code: 0, stdout: "b\n" });
+ expect(await run(["env", "-i", "A=B"])).toMatchObject({ code: 0, stdout: "A=B\n" });
+ expect(await run(["env", "-i", "printenv"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["env", "PATH=", "printenv"])).toMatchObject({ code: 127, stderr: "env: 'printenv': No such file or directory\n" });
+ expect(await run(["env", "-", "-0", "A=B"])).toMatchObject({ code: 0, stdout: "A=B\0" });
+ await mkdir(join(dir, "work"));
+ expect(await run(["env", "-C", "work", process.execPath, "-e", "console.log(process.cwd())"])).toMatchObject({ code: 0, stdout: `${join(dir, "work")}\n` });
+ expect(await run(["env", "--chdir=missing'cwd", "true"])).toMatchObject({ code: 125, stdout: "", stderr: "env: cannot change directory to \"missing'cwd\": No such file or directory\n" });
+ expect(await run(["env", "--chdir=missing\ncwd", "true"])).toMatchObject({ code: 125, stdout: "", stderr: "env: cannot change directory to 'missing'$'\\n''cwd': No such file or directory\n" });
+ expect(await run(["env", "--", process.execPath, "-e", "console.log('separator')"])).toMatchObject({ code: 0, stdout: "separator\n" });
+ expect(await run(["env", "--", "-a=b", "printenv", "--", "-a"])).toMatchObject({ code: 0, stdout: "b\n" });
+ expect(await run(["env", "-S", `${process.execPath} -e "console.log('split')" `])).toMatchObject({ code: 0, stdout: "split\n" });
+ expect(await run(["env", "-v -S cat -n"])).toMatchObject({ code: 125, stderr: "env: invalid option -- ' '\nenv: use -[v]S to pass options in shebang lines\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "-v\t-S cat -n"])).toMatchObject({ code: 125, stderr: "env: invalid option -- '\t'\nenv: use -[v]S to pass options in shebang lines\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "cat -n", "./xxx"])).toMatchObject({ code: 127, stderr: "env: 'cat -n': No such file or directory\nenv: use -[v]S to pass options in shebang lines\n" });
+ expect(await run(["env", "-a", "custom-zero", "/bin/sh", "-c", "printf '%s\\n' \"$0\""])).toMatchObject({ code: 0, stdout: "custom-zero\n" });
+ expect(await run(["env", "-a=custom-zero", "/bin/sh", "-c", "printf '%s\\n' \"$0\""])).toMatchObject({ code: 0, stdout: "=custom-zero\n" });
+ expect(await run(["env", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]\n") });
+ expect(await run(["env", "--he=bad"])).toMatchObject(await systemRun(["env", "--he=bad"]));
+ expect(await run(["env", "--ve=bad"])).toMatchObject(await systemRun(["env", "--ve=bad"]));
+ expect(await run(["env", "--bad", "--help"])).toMatchObject({ code: 125, stderr: "env: unrecognized option '--bad'\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--bad=4"])).toMatchObject({ code: 125, stderr: "env: unrecognized option '--bad=4'\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "FOO=bar", "--help"])).toMatchObject({ code: 127, stderr: "env: '--help': No such file or directory\n" });
+ expect(await run(["env", "-a"])).toMatchObject({ code: 125, stderr: "env: option requires an argument -- 'a'\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--argv0"])).toMatchObject({ code: 125, stderr: "env: option '--argv0' requires an argument\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "-u"])).toMatchObject({ code: 125, stderr: "env: option requires an argument -- 'u'\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--unset"])).toMatchObject({ code: 125, stderr: "env: option '--unset' requires an argument\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--unset=bad=name", "true"])).toMatchObject({ code: 125, stdout: "", stderr: `env: cannot unset ${diagnosticQuote("bad=name")}: Invalid argument\n` });
+ expect(await run(["env", "--unset=bad\nname=1", "true"])).toMatchObject({ code: 125, stdout: "", stderr: `env: cannot unset ${diagnosticQuote("bad\\nname=1")}: Invalid argument\n` });
+ expect(await run(["env", "-C"])).toMatchObject({ code: 125, stderr: "env: option requires an argument -- 'C'\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--chdir"])).toMatchObject({ code: 125, stderr: "env: option '--chdir' requires an argument\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "-S"])).toMatchObject({ code: 125, stderr: "env: option requires an argument -- 'S'\nTry 'env --help' for more information.\n" });
+ expect(await run(["env", "--split-string"])).toMatchObject({ code: 125, stderr: "env: option '--split-string' requires an argument\nTry 'env --help' for more information.\n" });
+ expect((await run(["env", "NON_UTF8_TEST=\uFFFD", "env"])).stdout).toContain("NON_UTF8_TEST=�\n");
+ expect((await run(["env", "NON_UTF8_TEST\uFFFD=1", "env"])).stdout).toContain("NON_UTF8_TEST�=1\n");
+ expect((await run(["env", "NON_UTF8_TEST=\u00A0", "env"])).stdout).toContain("NON_UTF8_TEST=�\n");
+ expect((await run(["env", "NON_UTF8_TEST\u00A0=1", "env"])).stdout).toContain("NON_UTF8_TEST�=1\n");
+ expect((await run(["env", "NON_UTF8_TEST=\uDCA0", "env"])).stdout).toContain("NON_UTF8_TEST=�\n");
+ expect((await run(["env", "NON_UTF8_TEST\uDCA0=1", "env"])).stdout).toContain("NON_UTF8_TEST�=1\n");
+ expect(await run(["test", "4", "-gt", "3"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "empty"), "");
+ await writeFile(join(dir, "script"), "#!/bin/sh\n");
+ await symlink("script", join(dir, "script-link"));
+ expect(await run(["test", "-f", "script"])).toMatchObject({ code: 0 });
+ expect(await run(["test", "-s", "empty"])).toMatchObject({ code: 1 });
+ expect(await run(["test", "-L", "script-link"])).toMatchObject({ code: 0 });
+ expect(await run(["chmod", "755", "script"])).toMatchObject({ code: 0 });
+ expect(await run(["test", "-x", "script"])).toMatchObject({ code: 0 });
+ expect(await run(["[", "-r", "script", "]"])).toMatchObject({ code: 0 });
+ expect(await run(["[", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: test EXPRESSION\n or: test\n or: [ EXPRESSION ]\n") });
+ expect(await run(["[", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["[", "-r", "script"])).toMatchObject({ code: 2, stderr: `[: missing ${diagnosticQuote("]")}\n` });
+ expect(await run(["[", "1", "-eq", "x", "]"])).toMatchObject({ code: 2, stderr: `[: invalid integer ${diagnosticQuote("x")}\n` });
+ expect(await run(["[", "1", "-eq", "x\ny", "]"])).toMatchObject({ code: 2, stderr: `[: invalid integer ${diagnosticQuote("x\\ny")}\n` });
+ expect(await run(["[", "1", "-eq", "]"])).toMatchObject({ code: 2, stderr: `[: missing argument after ${diagnosticQuote("-eq")}\n` });
+ expect(await run(["test", "1", "-eq", "x"])).toMatchObject({ code: 2, stderr: `test: invalid integer ${diagnosticQuote("x")}\n` });
+ expect(await run(["test", "1", "-eq", "x\ny"])).toMatchObject({ code: 2, stderr: `test: invalid integer ${diagnosticQuote("x\\ny")}\n` });
+ await writeFile(join(dir, "older"), "old");
+ await writeFile(join(dir, "newer"), "new");
+ expect(await run(["touch", "-d", "2020-01-01T00:00:00Z", "older"])).toMatchObject({ code: 0 });
+ expect(await run(["touch", "-d", "2021-01-01T00:00:00Z", "newer"])).toMatchObject({ code: 0 });
+ expect(await run(["test", "newer", "-nt", "older"])).toMatchObject({ code: 0 });
+ expect(await run(["test", "older", "-ot", "newer"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "newer-ns"), "new");
+ await writeFile(join(dir, "older-ns"), "old");
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456789 +0000", "newer-ns"]);
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456788 +0000", "older-ns"]);
+ expect(await run(["test", "newer-ns", "-nt", "older-ns"])).toMatchObject({ code: 0 });
+ expect(await run(["test", "older-ns", "-ot", "newer-ns"])).toMatchObject({ code: 0 });
+ expect(await run(["link", "newer", "newer-hard"])).toMatchObject({ code: 0 });
+ expect(await run(["test", "newer", "-ef", "newer-hard"])).toMatchObject({ code: 0 });
+ expect(await run(["true"])).toMatchObject({ code: 0 });
+ expect(await run(["false"])).toMatchObject({ code: 1 });
+ expect(await run(["test", "--version"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["test", "!", "--version"])).toMatchObject({ code: 1, stdout: "" });
+ expect(await run(["[", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["[", "--version", "]"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["true", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["false", "--version"])).toMatchObject({ code: 1, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["true", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: true [ignored command line arguments]\n or: true OPTION\n"), stderr: "" });
+ expect(await run(["false", "--help"])).toMatchObject({ code: 1, stdout: expect.stringContaining("Usage: false [ignored command line arguments]\n or: false OPTION\n"), stderr: "" });
+ expect(await run(["true", "--help", "extra"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["false", "--help", "extra"])).toMatchObject({ code: 1, stdout: "" });
+ const bracketFull = Bun.spawn(["/bin/sh", "-c", `${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} '[' --version >/dev/full`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await bracketFull.exited).toBe(2);
+ expect(await new Response(bracketFull.stderr).text()).toBe("[: write error: No space left on device\n");
+ const full = Bun.spawn(["/bin/sh", "-c", `${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} true --version >/dev/full`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await full.exited).toBe(1);
+});
+
+test("tee and truncate write expected data", async () => {
+ expect(await run(["tee", "out"], "abcdef")).toMatchObject({ code: 0, stdout: "abcdef" });
+ expect(await readFile(join(dir, "out"), "utf8")).toBe("abcdef");
+ expect(await run(["tee", "-ai", "out"], "G")).toMatchObject({ code: 0, stdout: "G" });
+ expect(await readFile(join(dir, "out"), "utf8")).toBe("abcdefG");
+ expect(await run(["tee", "--h"], "x")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tee [OPTION]... [FILE]...\n") });
+ expect(await run(["tee", "--help"], "x")).toMatchObject({ code: 0, stdout: expect.stringContaining("Copy standard input to each FILE, and also to standard output.\n") });
+ expect(await run(["tee", "--v"], "x")).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["tee", "tee-meta-out", "--help"], "x")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tee [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["tee", "--app", "out"], "H")).toMatchObject({ code: 0, stdout: "H" });
+ expect(await readFile(join(dir, "out"), "utf8")).toBe("abcdefGH");
+ expect(await run(["tee", "--ig"], "x")).toMatchObject({ code: 0, stdout: "x" });
+ expect(await run(["tee", "--out=exit"], "x")).toMatchObject({ code: 0, stdout: "x" });
+ expect(await run(["tee", "--bad", "--help"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "tee: unrecognized option '--bad'\nTry 'tee --help' for more information.\n" });
+ expect(await run(["tee", "-x", "--help"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "tee: invalid option -- 'x'\nTry 'tee --help' for more information.\n" });
+ expect(await run(["tee", "--h=foo"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "tee: option '--help' doesn't allow an argument\nTry 'tee --help' for more information.\n" });
+ expect(await run(["tee", "--app=foo"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "tee: option '--append' doesn't allow an argument\nTry 'tee --help' for more information.\n" });
+ expect(await run(["tee", "-p", "--output-error", "pipe-mode"], "p")).toMatchObject({ code: 0, stdout: "p" });
+ expect(await readFile(join(dir, "pipe-mode"), "utf8")).toBe("p");
+ expect(await run(["tee", "--output-error=warn", "--help"], "x")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tee [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["tee", "missing'parent/out"], "x")).toMatchObject({ code: 1, stdout: "x", stderr: "tee: \"missing'parent/out\": No such file or directory\n" });
+ expect(await run(["tee", "missing\nparent/out"], "x")).toMatchObject({ code: 1, stdout: "x", stderr: "tee: 'missing'$'\\n''parent/out': No such file or directory\n" });
+ await mkdir(join(dir, "dir'tee"));
+ expect(await run(["tee", "dir'tee"], "x")).toMatchObject({ code: 1, stdout: "x", stderr: "tee: \"dir'tee\": Is a directory\n" });
+ await symlink("loop'tee", join(dir, "loop'tee"));
+ expect(await run(["tee", "loop'tee"], "x")).toMatchObject({ code: 1, stdout: "x", stderr: "tee: \"loop'tee\": Too many levels of symbolic links\n" });
+ await symlink("/dev/full", join(dir, "full'tee"));
+ expect(await run(["tee", "full'tee"], "x")).toMatchObject({ code: 1, stdout: "x", stderr: "tee: \"full'tee\": No space left on device\n" });
+ expect(await run(["tee", "--output-error=", "bad"], "x")).toMatchObject({
+ code: 1,
+ stderr: `tee: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--output-error")}\nValid arguments are:\n - ${diagnosticQuote("warn")}\n - ${diagnosticQuote("warn-nopipe")}\n - ${diagnosticQuote("exit")}\n - ${diagnosticQuote("exit-nopipe")}\nTry 'tee --help' for more information.\n`,
+ });
+ expect(await run(["tee", "--output-error=bogus", "bad"], "x")).toMatchObject({
+ code: 1,
+ stderr: `tee: invalid argument ${diagnosticQuote("bogus")} for ${diagnosticQuote("--output-error")}\nValid arguments are:\n - ${diagnosticQuote("warn")}\n - ${diagnosticQuote("warn-nopipe")}\n - ${diagnosticQuote("exit")}\n - ${diagnosticQuote("exit-nopipe")}\nTry 'tee --help' for more information.\n`,
+ });
+ expect(await run(["tee", "--output-error=bad\nmode"], "x")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `tee: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--output-error")}\nValid arguments are:\n - ${diagnosticQuote("warn")}\n - ${diagnosticQuote("warn-nopipe")}\n - ${diagnosticQuote("exit")}\n - ${diagnosticQuote("exit-nopipe")}\nTry 'tee --help' for more information.\n`,
+ });
+ expect(await run(["truncate"])).toMatchObject({ code: 1, stderr: "truncate: you must specify either '--size' or '--reference'\nTry 'truncate --help' for more information.\n" });
+ expect(await run(["truncate", "-s", "1"])).toMatchObject({ code: 1, stderr: "truncate: missing file operand\nTry 'truncate --help' for more information.\n" });
+ expect(await run(["truncate", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "truncate: unrecognized option '--bad'\nTry 'truncate --help' for more information.\n" });
+ expect(await run(["truncate", "--version=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "truncate: option '--version' doesn't allow an argument\nTry 'truncate --help' for more information.\n" });
+ expect(await run(["truncate", "--no-create=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "truncate: option '--no-create' doesn't allow an argument\nTry 'truncate --help' for more information.\n" });
+ expect(await run(["truncate", "--io=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "truncate: option '--io-blocks' doesn't allow an argument\nTry 'truncate --help' for more information.\n" });
+ expect(await run(["truncate", "--size", "bad"])).toMatchObject(await systemRun(["/usr/bin/truncate", "--size", "bad"]));
+ expect(await run(["truncate", "--size", "1\t2", "truncate-tab-size"])).toMatchObject(await systemRun(["/usr/bin/truncate", "--size", "1\t2", "truncate-tab-size"]));
+ expect(await run(["truncate", "--size", "/0"])).toMatchObject(await systemRun(["/usr/bin/truncate", "--size", "/0"]));
+ expect(await run(["truncate", "--reference", "out", "--size", "3"])).toMatchObject(await systemRun(["truncate", "--reference", "out", "--size", "3"]));
+ expect(await run(["truncate", "--size", "--help", "truncate-size-help"])).toMatchObject(await systemRun(["/usr/bin/truncate", "--size", "--help", "truncate-size-help"]));
+ expect(await run(["truncate", "--size=bad", "truncate-bad-size", "--help"])).toMatchObject(await systemRun(["/usr/bin/truncate", "--size=bad", "truncate-bad-size", "--help"]));
+ expect(await run(["truncate", "--s", "1", "truncate-help", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: truncate OPTION... FILE...\n") });
+ expect(await run(["truncate", "--n", "--s=1", "truncate-no-create-prefix"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ await expect(stat(join(dir, "truncate-no-create-prefix"))).rejects.toThrow();
+ expect(await run(["truncate", "-s", "3", "out"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "out"), "utf8")).toBe("abc");
+ expect(await run(["truncate", "--s=2", "truncate-size-prefix"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "truncate-size-prefix"))).size).toBe(2);
+ expect(await run(["truncate", "-s", "+2K", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(2051);
+ expect(await run(["truncate", "-s", "-1K", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1027);
+ expect(await run(["truncate", "-s", "1k", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1024);
+ expect(await run(["truncate", "-s", "1b", "out"])).toMatchObject(await systemRun(["/usr/bin/truncate", "-s", "1b", "out"]));
+ expect(await run(["truncate", "-s", "1m", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1024 ** 2);
+ expect(await run(["truncate", "-s", "1kiB", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1024);
+ expect(await run(["truncate", "-s", "1miB", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1024 ** 2);
+ expect(await run(["truncate", "-s", "1piB", "out"])).toMatchObject({ code: 1 });
+ expect(await run(["truncate", "-s", "1kB", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1000);
+ expect(await run(["truncate", "-s", "1mB", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1000 ** 2);
+ expect(await run(["truncate", "-s", "1gB", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1000 ** 3);
+ expect(await run(["truncate", "-s", "1tB", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1000 ** 4);
+ expect(await run(["truncate", "-s", "1pB", "out"])).toMatchObject({ code: 1 });
+ expect(await run(["truncate", "-s", "1EB", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1000 ** 6);
+ expect(await run(["truncate", "-s", "1E", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(1024 ** 6);
+ expect(await run(["truncate", "-s", "1Z", "out"])).toMatchObject(await systemRun(["/usr/bin/truncate", "-s", "1Z", "out"]));
+ await writeFile(join(dir, "ref"), "12345");
+ expect(await run(["truncate", "-r", "ref", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(5);
+ expect(await run(["truncate", "--reference=missing-ref", "out"])).toMatchObject({ code: 1, stderr: "truncate: cannot stat 'missing-ref': No such file or directory\n" });
+ expect(await run(["truncate", "--reference=missing\nref", "out"])).toMatchObject({ code: 1, stderr: "truncate: cannot stat 'missing'$'\\n''ref': No such file or directory\n" });
+ expect(await run(["truncate", "--reference=missing'ref", "out"])).toMatchObject({ code: 1, stderr: "truncate: cannot stat \"missing'ref\": No such file or directory\n" });
+ await writeFile(join(dir, "truncate-parent-file"), "x");
+ expect(await run(["truncate", "--reference=truncate-parent-file/ref", "out"])).toMatchObject({ code: 1, stderr: "truncate: cannot stat 'truncate-parent-file/ref': Not a directory\n" });
+ await writeFile(join(dir, "truncate-parent\nfile"), "x");
+ expect(await run(["truncate", "--reference=truncate-parent\nfile/ref", "out"])).toMatchObject({ code: 1, stderr: "truncate: cannot stat 'truncate-parent'$'\\n''file/ref': Not a directory\n" });
+ await writeFile(join(dir, "truncate-parent'file"), "x");
+ expect(await run(["truncate", "-s", "1", "truncate-parent'file/out"])).toMatchObject({ code: 1, stderr: "truncate: cannot open \"truncate-parent'file/out\" for writing: Not a directory\n" });
+ expect(await run(["truncate", "-r", "ref", "-s", "+2", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(7);
+ expect(await run(["truncate", "-r", "ref", "-s", "-2", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(3);
+ expect(await run(["truncate", "-r", "ref", "-s", "3", "out"])).toMatchObject({
+ code: 1,
+ stderr: `truncate: you must specify a relative ${diagnosticQuote("--size")} with ${diagnosticQuote("--reference")}\nTry 'truncate --help' for more information.\n`,
+ });
+ expect((await stat(join(dir, "out"))).size).toBe(3);
+ expect(await run(["truncate", "-s", " +1", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(4);
+ const ioBlockSize = (await statfs(dir)).bsize;
+ expect(await run(["truncate", "--io-blocks", "-s", "1", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(ioBlockSize);
+ expect(await run(["truncate", "-o", "-s", "1K", "out"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "out"))).size).toBe(ioBlockSize * 1024);
+ expect(await run(["truncate", "--io-blocks", "--reference=ref", "out"])).toMatchObject({ code: 1, stderr: "truncate: '--io-blocks' was specified but '--size' was not\nTry 'truncate --help' for more information.\n" });
+ expect(await run(["truncate", "-s", "/0", "out"])).toMatchObject({ code: 1 });
+ expect(await run(["truncate", "-c", "-s", "4", "missing"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "missing"))).rejects.toThrow();
+ expect(await run(["truncate", "-s0", "first", ".", "second"])).toMatchObject({ code: 1 });
+ expect((await stat(join(dir, "first"))).size).toBe(0);
+ expect((await stat(join(dir, "second"))).size).toBe(0);
+ expect(await run(["truncate", "-s", "1G", "created-big"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "created-big"))).size).toBe(1024 ** 3);
+ const overflow = await run(["truncate", "-s", "18446744073709551616", "too-big"]);
+ expect(overflow.code).toBe(1);
+ expect(overflow.stderr).toContain("Value too large");
+ expect(await run(["truncate", "-s", "+18446744073709551616", "out"])).toMatchObject({ code: 1 });
+ expect(await run(["truncate", "-s", "1", "."])).toMatchObject({ code: 1, stderr: "truncate: cannot open '.' for writing: Is a directory\n" });
+ await mkdir(join(dir, "truncate\nfolder"));
+ expect(await run(["truncate", "-s", "1", "truncate\nfolder"])).toMatchObject({ code: 1, stderr: "truncate: cannot open 'truncate'$'\\n''folder' for writing: Is a directory\n" });
+});
+
+test("touch supports explicit, reference, and access-only timestamps", async () => {
+ expect(await run(["touch"])).toMatchObject({ code: 1, stderr: "touch: missing file operand\nTry 'touch --help' for more information.\n" });
+ expect(await run(["touch", "--time=bogus"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `touch: invalid argument ${diagnosticQuote("bogus")} for ${diagnosticQuote("--time")}\nValid arguments are:\n - ${diagnosticQuote("atime")}, ${diagnosticQuote("access")}, ${diagnosticQuote("use")}\n - ${diagnosticQuote("mtime")}, ${diagnosticQuote("modify")}\nTry 'touch --help' for more information.\n`,
+ });
+ expect(await run(["touch", "--time=bad\nmode"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `touch: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--time")}\nValid arguments are:\n - ${diagnosticQuote("atime")}, ${diagnosticQuote("access")}, ${diagnosticQuote("use")}\n - ${diagnosticQuote("mtime")}, ${diagnosticQuote("modify")}\nTry 'touch --help' for more information.\n`,
+ });
+ expect(await run(["touch", "--time=bad", "--help"])).toMatchObject(await systemRun(["touch", "--time=bad", "--help"]));
+ expect(await run(["touch", "--date=bogus"])).toMatchObject({ code: 1, stdout: "", stderr: `touch: invalid date format ${diagnosticQuote("bogus")}\n` });
+ expect(await run(["touch", "--date=bad\ndate"])).toMatchObject({ code: 1, stdout: "", stderr: `touch: invalid date format ${diagnosticQuote("bad\\ndate")}\n` });
+ expect(await run(["touch", "-t", "bad"])).toMatchObject({ code: 1, stdout: "", stderr: `touch: invalid date format ${diagnosticQuote("bad")}\n` });
+ expect(await run(["touch", "-t", "bad\nstamp"])).toMatchObject({ code: 1, stdout: "", stderr: `touch: invalid date format ${diagnosticQuote("bad\\nstamp")}\n` });
+ expect(await run(["touch", "--reference="])).toMatchObject({ code: 1, stdout: "", stderr: "touch: failed to get attributes of '': No such file or directory\n" });
+ expect(await run(["touch", "-r", "missing-ref"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: failed to get attributes of 'missing-ref': No such file or directory\n" });
+ expect(await run(["touch", "-r", "missing'ref", "target"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: failed to get attributes of \"missing'ref\": No such file or directory\n" });
+ expect(await run(["touch", "-r", "missing\nref", "target"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: failed to get attributes of 'missing'$'\\n''ref': No such file or directory\n" });
+ expect(await run(["touch", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: unrecognized option '--bad'\nTry 'touch --help' for more information.\n" });
+ expect(await run(["touch", "--n", "ambiguous-touch", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: option '--n' is ambiguous; possibilities: '--no-create' '--no-dereference'\nTry 'touch --help' for more information.\n" });
+ expect(await run(["touch", "--version=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: option '--version' doesn't allow an argument\nTry 'touch --help' for more information.\n" });
+ expect(await run(["touch", "--no-create=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: option '--no-create' doesn't allow an argument\nTry 'touch --help' for more information.\n" });
+ expect(await run(["touch", "--time="])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `touch: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--time")}\nValid arguments are:\n - ${diagnosticQuote("atime")}, ${diagnosticQuote("access")}, ${diagnosticQuote("use")}\n - ${diagnosticQuote("mtime")}, ${diagnosticQuote("modify")}\nTry 'touch --help' for more information.\n`,
+ });
+ expect(await run(["touch", "--time=", "--help"])).toMatchObject(await systemRun(["touch", "--time=", "--help"]));
+ expect(await run(["touch", "--time", "--help", "time-help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `touch: invalid argument ${diagnosticQuote("--help")} for ${diagnosticQuote("--time")}\nValid arguments are:\n - ${diagnosticQuote("atime")}, ${diagnosticQuote("access")}, ${diagnosticQuote("use")}\n - ${diagnosticQuote("mtime")}, ${diagnosticQuote("modify")}\nTry 'touch --help' for more information.\n`,
+ });
+ expect(await run(["touch", "--date", "--help", "date-help"])).toMatchObject(await systemRun(["/usr/bin/touch", "--date", "--help", "date-help"]));
+ expect(await run(["touch", "--date=bogus", "ordinary-before-help", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: touch [OPTION]... FILE...\n") });
+ expect(await run(["touch", "--no-c", "no-create-before-help", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: touch [OPTION]... FILE...\n") });
+ expect(await run(["touch", "ordinary-before-help", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: touch [OPTION]... FILE...\n") });
+ expect(await run(["touch", "-f", "ignored-f"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect((await stat(join(dir, "ignored-f"))).isFile()).toBe(true);
+ await writeFile(join(dir, "touch-file-parent"), "parent");
+ expect(await run(["touch", "touch-file-parent/"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: setting times of 'touch-file-parent/': Not a directory\n" });
+ expect(await run(["touch", "-c", "touch-file-parent/new"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: setting times of 'touch-file-parent/new': Not a directory\n" });
+ expect(await run(["touch", "touch'file-parent/new"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: cannot touch \"touch'file-parent/new\": No such file or directory\n" });
+ expect(await run(["touch", "touch\nfile-parent/new"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: cannot touch 'touch'$'\\n''file-parent/new': No such file or directory\n" });
+ expect(await run(["touch", "missing-touch-dir/"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: setting times of 'missing-touch-dir/': No such file or directory\n" });
+ expect(await run(["touch", "missing'touch-dir/"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: setting times of \"missing'touch-dir/\": No such file or directory\n" });
+ expect(await run(["touch", "missing\ntouch-dir/"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: setting times of 'missing'$'\\n''touch-dir/': No such file or directory\n" });
+ expect(await run(["touch", "-c", "missing-touch-dir/"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["touch", "-d", "2020-01-02T03:04:05Z", "dated"])).toMatchObject({ code: 0 });
+ expect(Math.trunc((await stat(join(dir, "dated"))).mtimeMs / 1000)).toBe(1577934245);
+ expect(await run(["touch", "--time=a", "-d", "2020-01-02T03:04:05Z", "time-abbrev"])).toMatchObject({ code: 0 });
+ expect(await run(["touch", "--d=2020-01-02T03:04:05Z", "prefix-dated"])).toMatchObject({ code: 0 });
+ expect(Math.trunc((await stat(join(dir, "prefix-dated"))).mtimeMs / 1000)).toBe(1577934245);
+ expect(await run(["touch", "-t", "202112312359.58", "stamp"])).toMatchObject({ code: 0 });
+ const stamped = await stat(join(dir, "stamp"));
+ expect(stamped.mtime.toISOString()).toBe("2021-12-31T12:59:58.000Z");
+ expect(await run(["touch", "-t", "202001010000.0", "stamp"])).toMatchObject(await systemRun(["/usr/bin/touch", "-t", "202001010000.0", "stamp"]));
+ expect(await run(["touch", "-t", "202001010000.00", "stamp"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["touch", "-t", "bad", "--help"])).toMatchObject(await systemRun(["/usr/bin/touch", "-t", "bad", "--help"]));
+ expect(await run(["touch", "-tbad", "--help"])).toMatchObject(await systemRun(["/usr/bin/touch", "-tbad", "--help"]));
+ expect(await run(["touch", "-d", "@0", "-t", "202001010101", "stamp"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: cannot specify times from more than one source\nTry 'touch --help' for more information.\n" });
+ expect(await run(["touch", "-r", "dated", "-t", "202001010101", "stamp"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: cannot specify times from more than one source\nTry 'touch --help' for more information.\n" });
+ expect(await run(["touch", "-d", "@0", "-t", "202001010101"])).toMatchObject({ code: 1, stdout: "", stderr: "touch: cannot specify times from more than one source\nTry 'touch --help' for more information.\n" });
+ expect(await run(["touch", "-t", "197001010000.60", "leap"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0 });
+ expect(await run(["stat", "--p=%.9Y\\n", "leap"])).toMatchObject({ code: 0, stdout: "60.000000000\n" });
+ await writeFile(join(dir, "target"), "x");
+ expect(await run(["touch", "-r", "dated", "target"])).toMatchObject({ code: 0 });
+ expect(Math.trunc((await stat(join(dir, "target"))).mtimeMs / 1000)).toBe(1577934245);
+ await writeFile(join(dir, "reference-ns"), "ref");
+ await writeFile(join(dir, "target-ns"), "target");
+ await systemRun(["/usr/bin/touch", "-a", "-d", "2026-01-01 01:02:03.111111111 +0000", "reference-ns"]);
+ await systemRun(["/usr/bin/touch", "-m", "-d", "2026-01-02 03:04:05.222222222 +0000", "reference-ns"]);
+ expect(await run(["touch", "-r", "reference-ns", "target-ns"])).toMatchObject({ code: 0 });
+ expect(await run(["stat", "-c", "%x|%y", "target-ns"], "", { env: { TZ: "UTC0" } })).toMatchObject({
+ code: 0,
+ stdout: "2026-01-01 01:02:03.111111111 +0000|2026-01-02 03:04:05.222222222 +0000\n",
+ });
+ await writeFile(join(dir, "reference-negative-ns"), "ref");
+ await writeFile(join(dir, "target-negative-ns"), "target");
+ await systemRun(["/usr/bin/touch", "-a", "-d", "1969-12-31 23:59:58.876543211 +0000", "reference-negative-ns"]);
+ await systemRun(["/usr/bin/touch", "-m", "-d", "1969-12-31 23:59:59.123456789 +0000", "reference-negative-ns"]);
+ expect(await run(["touch", "-r", "reference-negative-ns", "target-negative-ns"])).toMatchObject({ code: 0 });
+ expect(await run(["stat", "-c", "%x|%y", "target-negative-ns"], "", { env: { TZ: "UTC0" } })).toMatchObject({
+ code: 0,
+ stdout: "1969-12-31 23:59:58.876543211 +0000|1969-12-31 23:59:59.123456789 +0000\n",
+ });
+ expect(await run(["touch", "--ref=dated", "--date=-5 days", "target"])).toMatchObject({ code: 0 });
+ expect(Math.trunc((await stat(join(dir, "target"))).mtimeMs / 1000)).toBe(1577502245);
+ const beforePastHour = Date.now() - 3600_000;
+ expect(await run(["touch", "-d", "-1 hour", "past-hour"])).toMatchObject({ code: 0 });
+ const pastHourDelta = Math.abs((await stat(join(dir, "past-hour"))).mtimeMs - beforePastHour);
+ expect(pastHourDelta).toBeLessThan(10_000);
+ const beforeFutureHour = Date.now() + 3600_000;
+ expect(await run(["touch", "-d", "+1 hour", "future-hour"])).toMatchObject({ code: 0 });
+ const futureHourDelta = Math.abs((await stat(join(dir, "future-hour"))).mtimeMs - beforeFutureHour);
+ expect(futureHourDelta).toBeLessThan(10_000);
+ const beforeYesterday = Date.now() - 86400_000;
+ expect(await run(["touch", "-d", "yesterday", "yesterday-file"])).toMatchObject({ code: 0 });
+ expect(Math.abs((await stat(join(dir, "yesterday-file"))).mtimeMs - beforeYesterday)).toBeLessThan(10_000);
+ expect(await run(["touch", "-d", "2026-06-15 +01 month", "plus-month"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "plus-month"))).mtime.toISOString().startsWith("2026-07-15")).toBe(true);
+ expect(await run(["touch", "-d", "2026-06-15 -1 year", "minus-year"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "minus-year"))).mtime.toISOString().startsWith("2025-06-15")).toBe(true);
+ expect(await run(["touch", "-r", "dated", "target"])).toMatchObject({ code: 0 });
+ expect(await run(["touch", "-a", "-d", "2022-01-02T03:04:05Z", "target"])).toMatchObject({ code: 0 });
+ const accessOnly = await stat(join(dir, "target"));
+ expect(Math.trunc(accessOnly.mtimeMs / 1000)).toBe(1577934245);
+ expect(Math.trunc(accessOnly.atimeMs / 1000)).toBe(1641092645);
+ expect(await run(["touch", "--time=mtime", "-d", "2023-01-02T03:04:05Z", "target"])).toMatchObject({ code: 0 });
+ const modifyOnly = await stat(join(dir, "target"));
+ expect(Math.trunc(modifyOnly.atimeMs / 1000)).toBe(1641092645);
+ expect(Math.trunc(modifyOnly.mtimeMs / 1000)).toBe(1672628645);
+ expect(await run(["touch", "--time=bogus", "target"])).toMatchObject({
+ code: 1,
+ stderr: `touch: invalid argument ${diagnosticQuote("bogus")} for ${diagnosticQuote("--time")}\nValid arguments are:\n - ${diagnosticQuote("atime")}, ${diagnosticQuote("access")}, ${diagnosticQuote("use")}\n - ${diagnosticQuote("mtime")}, ${diagnosticQuote("modify")}\nTry 'touch --help' for more information.\n`,
+ });
+ expect(await run(["touch", "-d", "bogus", "target"])).toMatchObject(await systemRun(["/usr/bin/touch", "-d", "bogus", "target"]));
+ expect(await run(["touch", "-r", "missing-ref", "target"])).toMatchObject({ code: 1, stderr: "touch: failed to get attributes of 'missing-ref': No such file or directory\n" });
+ expect(await run(["touch", "-h", "missing-link"])).toMatchObject({ code: 1, stderr: "touch: setting times of 'missing-link': No such file or directory\n" });
+ expect(await run(["touch", "-h", "missing'link"])).toMatchObject({ code: 1, stderr: "touch: setting times of \"missing'link\": No such file or directory\n" });
+ expect(await run(["touch", "-h", "missing\nlink"])).toMatchObject({ code: 1, stderr: "touch: setting times of 'missing'$'\\n''link': No such file or directory\n" });
+ await writeFile(join(dir, "link-target"), "x");
+ await symlink("link-target", join(dir, "link"));
+ expect(await run(["touch", "-h", "-d", "2024-01-02T03:04:05Z", "link"])).toMatchObject({ code: 0 });
+ expect(Math.trunc((await lstat(join(dir, "link"))).mtimeMs / 1000)).toBe(1704164645);
+ expect(Math.trunc((await stat(join(dir, "link-target"))).mtimeMs / 1000)).not.toBe(1704164645);
+ await symlink("missing-target", join(dir, "dangling-touch-ref"));
+ expect(await run(["touch", "-h", "-r", "dangling-touch-ref", "target"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "target"))).isFile()).toBe(true);
+ const touchStdout = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "touch", "-h", "-"], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "touch-stdout")),
+ stderr: "pipe",
+ });
+ expect(await touchStdout.exited).toBe(0);
+ expect(await new Response(touchStdout.stderr).text()).toBe("");
+ expect((await stat(join(dir, "touch-stdout"))).isFile()).toBe(true);
+ expect(await run(["touch", "01010000", "legacy"], "", { env: { POSIXLY_CORRECT: "1", _POSIX2_VERSION: "199209" } })).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "01010000"))).rejects.toThrow();
+ expect((await stat(join(dir, "legacy"))).isFile()).toBe(true);
+});
+
+test("sort, uniq, cut, paste and comm handle common text workflows", async () => {
+ await writeFile(join(dir, "words"), "b\nA\na\nb\n");
+ expect(await run(["sort", "-f", "words"])).toMatchObject({ code: 0, stdout: "A\na\nb\nb\n" });
+ expect(await run(["sort", "-u", "words"])).toMatchObject({ code: 0, stdout: "A\na\nb\n" });
+ await mkdir(join(dir, "sort-dir"));
+ expect(await run(["sort", "sort-dir"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: read failed: sort-dir: Is a directory\n" });
+ expect(await run(["uniq", "-c"], "a\na\nb\n")).toMatchObject({ code: 0, stdout: " 2 a\n 1 b\n" });
+ expect(await run(["uniq", "--c"], "a\na\nb\n")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "uniq: option '--c' is ambiguous; possibilities: '--count' '--check-chars'\nTry 'uniq --help' for more information.\n",
+ });
+ expect(await run(["uniq", "--bad", "--help"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: "uniq: unrecognized option '--bad'\nTry 'uniq --help' for more information.\n" });
+ expect(await run(["uniq", "--version=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: option '--version' doesn't allow an argument\nTry 'uniq --help' for more information.\n" });
+ expect(await run(["uniq", "-f", "1"], "1 alpha\n2 alpha\n3 beta\n")).toMatchObject({ code: 0, stdout: "1 alpha\n3 beta\n" });
+ expect(await run(["uniq", "--skip-fields", "--help"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: "uniq: --help: invalid number of fields to skip\n" });
+ expect(await run(["uniq", "--skip-fields=bad", "--help"], "a\n")).toMatchObject(await systemRun(["uniq", "--skip-fields=bad", "--help"], "a\n"));
+ expect(await run(["uniq", "--skip-fields", "bad", "--help"], "a\n")).toMatchObject(await systemRun(["uniq", "--skip-fields", "bad", "--help"], "a\n"));
+ expect(await run(["uniq", "--skip-chars=bad", "--help"], "a\n")).toMatchObject(await systemRun(["uniq", "--skip-chars=bad", "--help"], "a\n"));
+ expect(await run(["uniq", "--check-chars=bad", "--help"], "a\n")).toMatchObject(await systemRun(["uniq", "--check-chars=bad", "--help"], "a\n"));
+ expect(await run(["uniq", "-fbad", "--help"], "a\n")).toMatchObject(await systemRun(["uniq", "-fbad", "--help"], "a\n"));
+ expect(await run(["uniq", "-f", "bad", "--help"], "a\n")).toMatchObject(await systemRun(["uniq", "-f", "bad", "--help"], "a\n"));
+ expect(await run(["uniq", "-sbad", "--help"], "a\n")).toMatchObject(await systemRun(["uniq", "-sbad", "--help"], "a\n"));
+ expect(await run(["uniq", "-wbad", "--help"], "a\n")).toMatchObject(await systemRun(["uniq", "-wbad", "--help"], "a\n"));
+ expect(await run(["uniq", "--skip-fields=1", "--help"], "a\n")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: uniq [OPTION]... [INPUT [OUTPUT]]\n") });
+ expect(await run(["uniq", "-f", "1", "--help"], "a\n")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: uniq [OPTION]... [INPUT [OUTPUT]]\n") });
+ expect(await run(["uniq", "uniq-missing", "--help"], "a\n")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: uniq [OPTION]... [INPUT [OUTPUT]]\n"), stderr: "" });
+ expect(await run(["uniq", "-s", "2", "-w", "3"], "xxabc1\nyyabc2\nzzdef\n")).toMatchObject({ code: 0, stdout: "xxabc1\nzzdef\n" });
+ expect(await run(["uniq", "--check=1"], "aa\nab\n")).toMatchObject({ code: 0, stdout: "aa\n" });
+ expect(await run(["uniq", "-D"], "a\na\nb\nc\nc\nc\n")).toMatchObject({ code: 0, stdout: "a\na\nc\nc\nc\n" });
+ expect(await run(["uniq", "--all-repeated=separate"], "a\na\nb\nc\nc\n")).toMatchObject({ code: 0, stdout: "a\na\n\nc\nc\n" });
+ expect(await run(["uniq", "--all=separate"], "a\na\nb\nb\n")).toMatchObject({ code: 0, stdout: "a\na\n\nb\nb\n" });
+ expect(await run(["uniq", "--group="], "a\n")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `uniq: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--group")}\nValid arguments are:\n - ${diagnosticQuote("prepend")}\n - ${diagnosticQuote("append")}\n - ${diagnosticQuote("separate")}\n - ${diagnosticQuote("both")}\nTry 'uniq --help' for more information.\n`,
+ });
+ expect(await run(["uniq", "--all-repeated="], "a\n")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `uniq: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--all-repeated")}\nValid arguments are:\n - ${diagnosticQuote("none")}\n - ${diagnosticQuote("prepend")}\n - ${diagnosticQuote("separate")}\nTry 'uniq --help' for more information.\n`,
+ });
+ expect(await run(["uniq", "--group=bad", "--help"], "a\n")).toMatchObject(await systemRun(["uniq", "--group=bad", "--help"], "a\n"));
+ expect(await run(["uniq", "-D", "--group=bad"], "a\n")).toMatchObject(await systemRun(["uniq", "-D", "--group=bad"], "a\n"));
+ expect(await run(["uniq", "--all-repeated=bad\nmode"], "a\n")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `uniq: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--all-repeated")}\nValid arguments are:\n - ${diagnosticQuote("none")}\n - ${diagnosticQuote("prepend")}\n - ${diagnosticQuote("separate")}\nTry 'uniq --help' for more information.\n`,
+ });
+ expect(await run(["uniq", "--group=both", "--help"], "a\n")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: uniq [OPTION]... [INPUT [OUTPUT]]\n") });
+ expect(await run(["uniq", "-1"], "a a\nb a\n")).toMatchObject({ code: 0, stdout: "a a\n" });
+ expect(await run(["uniq", "+1"], "baa\naaa\n")).toMatchObject({ code: 0, stdout: "baa\n" });
+ expect(await run(["uniq", "-f", "+1"], "1 alpha\n2 alpha\n3 beta\n")).toMatchObject({ code: 0, stdout: "1 alpha\n3 beta\n" });
+ expect(await run(["uniq", "-f", "10000000000"], "1\n2\n3\n")).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["uniq", "-f", "-1"])).toMatchObject({ code: 1, stderr: "uniq: -1: invalid number of fields to skip\n" });
+ expect(await run(["uniq", "-s", "x"])).toMatchObject({ code: 1, stderr: "uniq: x: invalid number of bytes to skip\n" });
+ expect(await run(["uniq", "-w", "x"])).toMatchObject({ code: 1, stderr: "uniq: x: invalid number of bytes to compare\n" });
+ expect(await run(["uniq", "-d", "-u"], "a\na\n\b")).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["uniq", "-D", "-c"], "a\na\n")).toMatchObject({ code: 1, stderr: "uniq: printing all duplicated lines and repeat counts is meaningless\nTry 'uniq --help' for more information.\n" });
+ expect(await run(["uniq", "--all-repeated=badoption"], "a\n")).toMatchObject(await systemRun(["uniq", "--all-repeated=badoption"], "a\n"));
+ expect(await run(["uniq", "--group"], "a\na\nb\nc\nc\n")).toMatchObject({ code: 0, stdout: "a\na\n\nb\n\nc\nc\n" });
+ expect(await run(["uniq", "--group=both"], "a\na\nb\n")).toMatchObject({ code: 0, stdout: "\na\na\n\nb\n\n" });
+ expect(await run(["uniq", "--all-repeated=append"], "a\na\n")).toMatchObject({ code: 1 });
+ expect(await run(["uniq", "-z", "-i"], "A\0a\0b\0")).toMatchObject({ code: 0, stdout: "A\0b\0" });
+ await writeFile(join(dir, "uniq-in"), "a\na\nb\n");
+ expect(await run(["uniq", "uniq-in", "uniq-out"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await readFile(join(dir, "uniq-out"), "utf8")).toBe("a\nb\n");
+ expect(await run(["uniq", "uniq-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: uniq-missing: No such file or directory\n" });
+ expect(await run(["uniq", "missing'uniq"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: \"missing'uniq\": No such file or directory\n" });
+ expect(await run(["uniq", "missing\nuniq"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: 'missing'$'\\n''uniq': No such file or directory\n" });
+ await mkdir(join(dir, "uniq-dir"));
+ expect(await run(["uniq", "uniq-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: error reading 'uniq-dir': Is a directory\n" });
+ await mkdir(join(dir, "dir'uniq"));
+ expect(await run(["uniq", "dir'uniq"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: error reading \"dir'uniq\": Is a directory\n" });
+ await symlink("uniq-input-loop", join(dir, "uniq-input-loop"));
+ expect(await run(["uniq", "uniq-input-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: uniq-input-loop: Too many levels of symbolic links\n" });
+ await symlink("loop'uniq", join(dir, "loop'uniq"));
+ expect(await run(["uniq", "loop'uniq"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: \"loop'uniq\": Too many levels of symbolic links\n" });
+ expect(await run(["uniq", "uniq-in", "uniq-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: uniq-dir: Is a directory\n" });
+ expect(await run(["uniq", "uniq-in", "dir'uniq"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: \"dir'uniq\": Is a directory\n" });
+ await symlink("uniq-loop", join(dir, "uniq-loop"));
+ expect(await run(["uniq", "uniq-in", "uniq-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: uniq-loop: Too many levels of symbolic links\n" });
+ await writeFile(join(dir, "parent'uniq"), "parent");
+ expect(await run(["uniq", "uniq-in", "parent'uniq/out"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: \"parent'uniq/out\": Not a directory\n" });
+ expect(await run(["uniq", "uniq-in", "uniq-missing-dir/out"])).toMatchObject({ code: 1, stdout: "", stderr: "uniq: uniq-missing-dir/out: No such file or directory\n" });
+ expect(await run(["uniq", "uniq-in", "uniq-out", "extra"])).toMatchObject({ code: 1, stderr: `uniq: extra operand ${diagnosticQuote("extra")}\nTry 'uniq --help' for more information.\n` });
+ expect(await run(["uniq", "uniq-in", "uniq-out", "extra\narg"])).toMatchObject({ code: 1, stderr: `uniq: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'uniq --help' for more information.\n` });
+ await writeFile(join(dir, "uniq-invalid"), Uint8Array.of(0x20, 0x79, 0x20, 0x7a, 0x0a, 0xa0, 0x20, 0x79, 0x20, 0x7a, 0x0a));
+ const uniqInvalid = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "uniq", "-f1", "uniq-invalid"], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "uniq-invalid-out")),
+ stderr: "pipe",
+ });
+ expect(await uniqInvalid.exited).toBe(0);
+ expect(await new Response(uniqInvalid.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "uniq-invalid-out"))]).toEqual([0x20, 0x79, 0x20, 0x7a, 0x0a, 0xa0, 0x20, 0x79, 0x20, 0x7a, 0x0a]);
+ expect(await run(["cut", "-d", ",", "-f", "2"], "x,y,z\n1,2,3\n")).toMatchObject({ code: 0, stdout: "y\n2\n" });
+ expect(await run(["cut", "--b=1"], "abc\n")).toMatchObject({ code: 0, stdout: "a\n" });
+ expect(await run(["cut", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cut OPTION... [FILE]...\n") });
+ expect(await run(["cut", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining(" -F\n") });
+ expect(await run(["cut", "--v"])).toMatchObject({ code: 0, stdout: expect.stringContaining("bnu 9.11\n") });
+ await writeFile(join(dir, "cut-meta"), "abc\n");
+ expect(await run(["cut", "cut-meta", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cut OPTION... [FILE]...\n"), stderr: "" });
+ expect(await run(["cut", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "cut: unrecognized option '--bad'\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "--help=1", "--version"])).toMatchObject({ code: 1, stdout: "", stderr: "cut: option '--help' doesn't allow an argument\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "--version=1", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "cut: option '--version' doesn't allow an argument\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "--c=1"], "abc\n")).toMatchObject({ code: 1, stdout: "", stderr: "cut: option '--c=1' is ambiguous; possibilities: '--characters' '--complement'\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "--o=:", "-d", ",", "-f", "1,2"], "a,b,c\n")).toMatchObject({ code: 1, stdout: "", stderr: "cut: option '--o=:' is ambiguous; possibilities: '--only-delimited' '--output-delimiter'\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "--only", "-d", ",", "-f", "1"], "plain\n")).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["cut", "--whitespace", "-f", "2"], "a b\n")).toMatchObject({ code: 0, stdout: "b\n" });
+ expect(await run(["cut", "--whitespace=bad", "-f", "1"], "a b\n")).toMatchObject(await systemRun(["cut", "--whitespace=bad", "-f", "1"], "a b\n"));
+ expect(await run(["cut", "--whitespace=bad", "--help"])).toMatchObject(await systemRun(["cut", "--whitespace=bad", "--help"]));
+ expect(await run(["cut", "--whitespace=bad\nmode", "-f", "1"], "a b\n")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `cut: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--whitespace-delimited")}\nValid arguments are:\n - ${diagnosticQuote("trimmed")}\nTry 'cut --help' for more information.\n`,
+ });
+ expect(await run(["cut", "--bytes", "--help"], "abc\n")).toMatchObject({ code: 1, stdout: "", stderr: "cut: invalid byte or character range\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "-d", "ab", "--help"])).toMatchObject(await systemRun(["cut", "-d", "ab", "--help"]));
+ expect(await run(["cut", "--delimiter=ab", "--help"])).toMatchObject(await systemRun(["cut", "--delimiter=ab", "--help"]));
+ expect(await run(["cut", "--delimiter", "--help", "--version"])).toMatchObject({ code: 1, stdout: "", stderr: "cut: the delimiter must be a single character\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "-d", "x", "-f", "1", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cut OPTION... [FILE]...\n") });
+ expect(await run(["cut", "--bytes=bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cut OPTION... [FILE]...\n") });
+ await writeFile(join(dir, "cut-in"), "one\ntwo\nthree\n");
+ expect(await run(["cut", "-c", "1", "cut-missing-a", "cut-in", "cut-missing-b"])).toMatchObject({ code: 1, stdout: "o\nt\nt\n", stderr: "cut: cut-missing-a: No such file or directory\ncut: cut-missing-b: No such file or directory\n" });
+ await mkdir(join(dir, "cut-dir"));
+ expect(await run(["cut", "-c", "1", "cut-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "cut: cut-dir: Is a directory\n" });
+ expect(await run(["cut", "-c", "1-2,5-", "--output-delimiter=:"], "abcdef\n")).toMatchObject({ code: 0, stdout: "ab:ef\n" });
+ expect(await run(["cut", "-c", "2-4", "--complement"], "abcdef\n")).toMatchObject({ code: 0, stdout: "aef\n" });
+ expect(await run(["cut", "-b", "1-2,5-", "--output-delimiter=:"], "abcdef\n")).toMatchObject({ code: 0, stdout: "ab:ef\n" });
+ expect(await run(["cut", "-b", "+1"], "abcdef\n")).toMatchObject(await systemRun(["cut", "-b", "+1"], "abcdef\n"));
+ expect(await run(["cut", "-b", "--"], "abcdef\n")).toMatchObject({ code: 1, stderr: "cut: invalid byte or character range\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "-b", "18446744073709551614"], "abcdef\n")).toMatchObject({ code: 0, stdout: "\n" });
+ expect(await run(["cut", "-b", "18446744073709551614-", "/dev/null"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["cut", "-b", "1-18446744073709551614", "/dev/null"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["cut", "-b", "18446744073709551615"], "abcdef\n")).toMatchObject(await systemRun(["cut", "-b", "18446744073709551615"], "abcdef\n"));
+ expect(await run(["cut", "-b", "1-18446744073709551615"], "abcdef\n")).toMatchObject(await systemRun(["cut", "-b", "1-18446744073709551615"], "abcdef\n"));
+ expect(await run(["cut", "-c", "1,a"], "abcdef\n")).toMatchObject(await systemRun(["cut", "-c", "1,a"], "abcdef\n"));
+ expect(await run(["cut", "-b", "1-2x"], "abcdef\n")).toMatchObject(await systemRun(["cut", "-b", "1-2x"], "abcdef\n"));
+ expect(await run(["cut", "-s", "-d", ":", "-f", "2", "--output-delimiter=/"], "plain\na:b:c\n")).toMatchObject({ code: 0, stdout: "b\n" });
+ expect(await run(["cut", "-d", ":", "-f", "+1"], "a:b:c\n")).toMatchObject(await systemRun(["cut", "-d", ":", "-f", "+1"], "a:b:c\n"));
+ expect(await run(["cut", "-f", "--"], "a:b:c\n")).toMatchObject({ code: 1, stderr: "cut: invalid field range\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "-f", "18446744073709551615"], "a:b:c\n")).toMatchObject(await systemRun(["cut", "-f", "18446744073709551615"], "a:b:c\n"));
+ expect(await run(["cut", "-d", ":", "-f", "1-2x"], "a:b:c\n")).toMatchObject(await systemRun(["cut", "-d", ":", "-f", "1-2x"], "a:b:c\n"));
+ expect(await run(["cut", "-c", "4"], "123\n")).toMatchObject({ code: 0, stdout: "\n" });
+ expect(await run(["cut", "-c", "1"], "x")).toMatchObject({ code: 0, stdout: "x\n" });
+ expect(await run(["cut", "-d", ":", "--out=_", "-f", "2,3"], "a:b:c\n")).toMatchObject({ code: 0, stdout: "b_c\n" });
+ expect(await run(["cut", "-b", "1-2,3-4", "--output-d=:"], "abcd\n")).toMatchObject({ code: 0, stdout: "ab:cd\n" });
+ expect(await run(["cut", "-c", "1-3,2-4,6", "--output-d=:"], "abcdefg\n")).toMatchObject({ code: 0, stdout: "abcd:f\n" });
+ const cutChunkBoundary = "a".repeat(65536);
+ expect(await run(["cut", "-f1"], cutChunkBoundary)).toMatchObject({ code: 0, stdout: `${cutChunkBoundary}\n` });
+ expect(await run(["cut", "-s", "-d", ":", "-f2"], `${cutChunkBoundary}:value`)).toMatchObject({ code: 0, stdout: "value\n" });
+ expect(await run(["cut", "-b", "65535-65536,65538-65539", "--output-delimiter=:"], `${cutChunkBoundary}bcde\n`)).toMatchObject({ code: 0, stdout: "aa:cd\n" });
+ expect(await run(["cut", "-d", "", "-f", "2"], "a\0b\0c\n")).toMatchObject({ code: 0, stdout: "b\n" });
+ expect(await run(["cut", "-d", "", "--out=_", "-f", "2,3"], "a\0b\0c\n")).toMatchObject({ code: 0, stdout: "b_c\n" });
+ expect(await run(["cut", "-d", "\n", "-f", "1,2", "--ou=:"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a:b\n" });
+ expect(await run(["cut", "-d'\n'", "-f1"], "a:1\nb:")).toMatchObject({ code: 0, stdout: "a:1\n" });
+ expect(await run(["cut", "-F", "2,3", "-d", ","], "1,2,3\n")).toMatchObject({ code: 0, stdout: "2 3\n" });
+ expect(await run(["cut", "-s", "-d", ":", "-f", "3-"], ":::\n:1\n")).toMatchObject({ code: 0, stdout: ":\n\n" });
+ expect(await run(["cut", "-s", "--whitespace-delimited=trimmed", "-f", "1"], " a \n")).toMatchObject({ code: 0, stdout: "" });
+ const badCutDelimiter = await run(["cut", "-d", ":", "-b", "1"], "a:b\n");
+ expect(badCutDelimiter).toMatchObject({ code: 1 });
+ expect(badCutDelimiter.stderr).toContain("an input delimiter makes sense");
+ const badCutSuppress = await run(["cut", "-s", "-b", "1"], "abc\n");
+ expect(badCutSuppress).toMatchObject({ code: 1 });
+ expect(badCutSuppress.stderr).toContain("suppressing non-delimited lines");
+ expect(await run(["cut", "-b", "1", "-f", "1"])).toMatchObject({ code: 1, stderr: "cut: only one list may be specified\nTry 'cut --help' for more information.\n" });
+ expect(await run(["cut", "-z", "-d", ":", "-f", "1"], "a:b\0c:d\0")).toMatchObject({ code: 0, stdout: "a\0c\0" });
+ expect(await run(["cut", "-w", "-f", "2,3"], " alpha beta gamma \nplain\n")).toMatchObject({ code: 0, stdout: "alpha\tbeta\nplain\n" });
+ expect(await run(["cut", "--whitespace-delimited=trimmed", "-f", "1,2"], " alpha beta gamma \n")).toMatchObject({ code: 0, stdout: "alpha\tbeta\n" });
+ expect(await run(["cut", "-F", "2,3"], " alpha beta gamma \nplain\n")).toMatchObject({ code: 0, stdout: "alpha beta\nplain\n" });
+ expect(await run(["cut", "-w", "-s", "-f", "2"], " alpha beta\nplain\n")).toMatchObject({ code: 0, stdout: "alpha\n" });
+ expect(await run(["cut", "-d", ":", "-f", "1", "missing'cut"])).toMatchObject({ code: 1, stdout: "", stderr: "cut: \"missing'cut\": No such file or directory\n" });
+ expect(await run(["cut", "-d", ":", "-f", "1", "missing\ncut"])).toMatchObject({ code: 1, stdout: "", stderr: "cut: 'missing'$'\\n''cut': No such file or directory\n" });
+ await mkdir(join(dir, "dir'cut"));
+ expect(await run(["cut", "-d", ":", "-f", "1", "dir'cut"])).toMatchObject({ code: 1, stdout: "", stderr: "cut: \"dir'cut\": Is a directory\n" });
+ await writeFile(join(dir, "cut-raw-char"), Uint8Array.of(0xff, 0x61, 0x0a));
+ const cutRawChar = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "cut", "-c1", "cut-raw-char"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "cut-raw-char-out")),
+ stderr: "pipe",
+ });
+ expect(await cutRawChar.exited).toBe(0);
+ expect(await new Response(cutRawChar.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "cut-raw-char-out"))]).toEqual([0xff, 0x0a]);
+ const cutRawCharStdin = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "cut", "-c1"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: Bun.file(join(dir, "cut-raw-char")),
+ stdout: Bun.file(join(dir, "cut-raw-char-stdin-out")),
+ stderr: "pipe",
+ });
+ expect(await cutRawCharStdin.exited).toBe(0);
+ expect(await new Response(cutRawCharStdin.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "cut-raw-char-stdin-out"))]).toEqual([0xff, 0x0a]);
+ await writeFile(join(dir, "cut-raw-field"), Uint8Array.of(0xff, 0x3a, 0xfe, 0x0a));
+ const cutRawField = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "cut", "-d:", "-f2", "cut-raw-field"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "cut-raw-field-out")),
+ stderr: "pipe",
+ });
+ expect(await cutRawField.exited).toBe(0);
+ expect(await new Response(cutRawField.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "cut-raw-field-out"))]).toEqual([0xfe, 0x0a]);
+ expect(await shell(`bash -c 'delim=$(printf "\\242\\343"); printf "1\${delim}2\${delim}3\\n" | LC_ALL=zh_CN.gb18030 "$BUN" "$BNU" cut -d "$delim" -f2,3 --output-delimiter=_ | /usr/bin/od -An -tx1 | tr -d " \\n"'`)).toMatchObject({ code: 0, stdout: "325f330a", stderr: "" });
+ expect(await shell(`bash -c 'delim=$(printf "\\377"); printf "1\${delim}2\${delim}3\\n" | LC_ALL=zh_CN.gb18030 "$BUN" "$BNU" cut -d "$delim" -f2,3 --output-delimiter=_ | /usr/bin/od -An -tx1 | tr -d " \\n"'`)).toMatchObject({ code: 0, stdout: "325f330a", stderr: "" });
+ await writeFile(join(dir, "left"), "a\nb\nc\n");
+ await writeFile(join(dir, "right"), "1\n2\n");
+ expect(await run(["paste", "left", "right"])).toMatchObject({ code: 0, stdout: "a\t1\nb\t2\nc\t\n" });
+ expect(await run(["paste", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: paste [OPTION]... [FILE]...\n") });
+ expect(await run(["paste", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Write lines consisting of the sequentially corresponding lines from\n") });
+ expect(await run(["paste", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["paste", "left", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: paste [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["paste", "--se"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\tb\n" });
+ expect(await run(["paste", "--z"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\nb\n\0" });
+ expect(await run(["paste", "--del=,", "left", "right"])).toMatchObject({ code: 0, stdout: "a,1\nb,2\nc,\n" });
+ expect(await run(["paste", "--delimiters=,", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: paste [OPTION]... [FILE]...\n") });
+ expect(await run(["paste", "--delimiters=\\", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: paste [OPTION]... [FILE]...\n") });
+ expect(await run(["paste", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: unrecognized option '--bad'\nTry 'paste --help' for more information.\n" });
+ expect(await run(["paste", "-x", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: invalid option -- 'x'\nTry 'paste --help' for more information.\n" });
+ expect(await run(["paste", "--h=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: option '--help' doesn't allow an argument\nTry 'paste --help' for more information.\n" });
+ expect(await run(["paste", "--se=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: option '--serial' doesn't allow an argument\nTry 'paste --help' for more information.\n" });
+ expect(await run(["paste", "--delimiters", "--help"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ await writeFile(join(dir, "third"), "x\ny\nz\n");
+ expect(await run(["paste", "-d", ",:", "left", "right", "third"])).toMatchObject({ code: 0, stdout: "a,1:x\nb,2:y\nc,:z\n" });
+ expect(await run(["paste", "left", "paste-missing", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: paste-missing: No such file or directory\n" });
+ expect(await run(["paste", "missing'paste"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: \"missing'paste\": No such file or directory\n" });
+ expect(await run(["paste", "missing\npaste"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: 'missing'$'\\n''paste': No such file or directory\n" });
+ await mkdir(join(dir, "paste-dir"));
+ await symlink("paste-loop", join(dir, "paste-loop"));
+ expect(await run(["paste", "paste-dir", "paste-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: paste-dir: Is a directory\npaste: paste-dir: Is a directory\n" });
+ await mkdir(join(dir, "dir'paste"));
+ expect(await run(["paste", "dir'paste"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: \"dir'paste\": Is a directory\n" });
+ expect(await run(["paste", "paste-dir", "right"])).toMatchObject({ code: 1, stdout: "\t1\n\t2\n", stderr: "paste: paste-dir: Is a directory\n" });
+ expect(await run(["paste", "left", "paste-dir", "right"])).toMatchObject({ code: 1, stdout: "a\t\t1\nb\t\t2\nc\t\t\n", stderr: "paste: paste-dir: Is a directory\n" });
+ expect(await run(["paste", "paste-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "paste: paste-loop: Too many levels of symbolic links\n" });
+ expect(await run(["paste", "-", "-"], "a\nb\nc\nd\n")).toMatchObject({ code: 0, stdout: "a\tb\nc\td\n" });
+ expect(await run(["paste"], "")).toMatchObject({ code: 0, stdout: "" });
+ await writeFile(join(dir, "left0"), "a\0b\0");
+ await writeFile(join(dir, "right0"), "1\02\0");
+ expect(await run(["paste", "-z", "-d", ":", "left0", "right0"])).toMatchObject({ code: 0, stdout: "a:1\02\0b:\0" });
+ await writeFile(join(dir, "paste-raw-left"), Uint8Array.of(0xff, 0x0a));
+ await writeFile(join(dir, "paste-raw-right"), "x\n");
+ const pasteRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "paste", "paste-raw-left", "paste-raw-right"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "paste-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await pasteRaw.exited).toBe(0);
+ expect(await new Response(pasteRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "paste-raw-out"))]).toEqual([0xff, 0x09, 0x78, 0x0a]);
+ const pasteRawSerial = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "paste", "-s", "paste-raw-left"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "paste-raw-serial-out")),
+ stderr: "pipe",
+ });
+ expect(await pasteRawSerial.exited).toBe(0);
+ expect(await new Response(pasteRawSerial.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "paste-raw-serial-out"))]).toEqual([0xff, 0x0a]);
+ await writeFile(join(dir, "paste-raw0-left"), Uint8Array.of(0xff, 0x00));
+ await writeFile(join(dir, "paste-raw0-right"), Uint8Array.of(0x78, 0x00));
+ const pasteRaw0 = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "paste", "-z", "paste-raw0-left", "paste-raw0-right"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "paste-raw0-out")),
+ stderr: "pipe",
+ });
+ expect(await pasteRaw0.exited).toBe(0);
+ expect(await new Response(pasteRaw0.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "paste-raw0-out"))]).toEqual([0xff, 0x09, 0x78, 0x00]);
+ expect(await run(["paste", "-s", "-d", "\\t"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\tb\n" });
+ expect(await run(["paste", "-s", "left", "paste-missing-a", "right", "paste-missing-b"])).toMatchObject({ code: 1, stdout: "a\tb\tc\n1\t2\n", stderr: "paste: paste-missing-a: No such file or directory\npaste: paste-missing-b: No such file or directory\n" });
+ expect(await run(["paste", "-s", "paste-dir", "left"])).toMatchObject({ code: 1, stdout: "\na\tb\tc\n", stderr: "paste: paste-dir: Is a directory\n" });
+ expect(await run(["paste", "-s", "-d", "\\b"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\bb\n" });
+ expect(await run(["paste", "-s", "-d", "\\f"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\fb\n" });
+ expect(await run(["paste", "-s", "-d", "\\r"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\rb\n" });
+ expect(await run(["paste", "-s", "-d", "\\v"], "a\nb\n")).toMatchObject({ code: 0, stdout: "a\vb\n" });
+ expect(await run(["paste", "-d", "\\"])).toMatchObject({ code: 1, stderr: "paste: delimiter list ends with an unescaped backslash: \\\n" });
+ await writeFile(join(dir, "c1"), "a\nb\n");
+ await writeFile(join(dir, "c2"), "b\nc\n");
+ expect(await run(["comm", "c1", "c2"])).toMatchObject({ code: 0, stdout: "a\n\t\tb\n\tc\n" });
+ expect(await run(["comm", "--output-delimiter=|", "c1", "c2"])).toMatchObject({ code: 0, stdout: "a\n||b\n|c\n" });
+ expect(await run(["comm", "--total", "c1", "c2"])).toMatchObject({ code: 0, stdout: "a\n\t\tb\n\tc\n1\t1\t1\ttotal\n" });
+ expect(await run(["comm", "--h", "c1", "c2"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: comm [OPTION]... FILE1 FILE2\n") });
+ expect(await run(["comm", "--v", "c1", "c2"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["comm", "c1", "c2", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["comm", "--o=|", "c1", "c2"])).toMatchObject({ code: 0, stdout: "a\n||b\n|c\n" });
+ expect(await run(["comm", "--output-delimiter=|", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: comm [OPTION]... FILE1 FILE2\n") });
+ expect(await run(["comm", "--output-delimiter=|", "--output-delimiter=+", "--help"])).toMatchObject(await systemRun(["comm", "--output-delimiter=|", "--output-delimiter=+", "--help"]));
+ expect(await run(["comm", "--output-delimiter", "|", "--output-delimiter", "+", "--help"])).toMatchObject(await systemRun(["comm", "--output-delimiter", "|", "--output-delimiter", "+", "--help"]));
+ expect(await run(["comm", "--t", "c1", "c2"])).toMatchObject({ code: 0, stdout: "a\n\t\tb\n\tc\n1\t1\t1\ttotal\n" });
+ expect(await run(["comm", "--z", "cz-missing-a", "cz-missing-b"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: cz-missing-a: No such file or directory\n" });
+ expect(await run(["comm", "--bad", "--help", "c1", "c2"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: unrecognized option '--bad'\nTry 'comm --help' for more information.\n" });
+ expect(await run(["comm", "-x", "--help", "c1", "c2"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: invalid option -- 'x'\nTry 'comm --help' for more information.\n" });
+ expect(await run(["comm", "--h=foo", "c1", "c2"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: option '--help' doesn't allow an argument\nTry 'comm --help' for more information.\n" });
+ expect(await run(["comm", "--t=foo", "c1", "c2"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: option '--total' doesn't allow an argument\nTry 'comm --help' for more information.\n" });
+ expect(await run(["comm", "--output-delimiter", "--help", "c1", "c2"])).toMatchObject({ code: 0, stdout: "a\n--help--helpb\n--helpc\n" });
+ const commHelp = (await run(["comm", "--help"])).stdout;
+ for (const option of ["-1", "-2", "-3"]) expect(commHelp).toContain(` ${option}\n`);
+ expect(await run(["comm", "c1"])).toMatchObject({ code: 1, stderr: "comm: missing operand after 'c1'\nTry 'comm --help' for more information.\n" });
+ expect(await run(["comm", "c1", "c2", "extra"])).toMatchObject({ code: 1, stderr: `comm: extra operand ${diagnosticQuote("extra")}\nTry 'comm --help' for more information.\n` });
+ expect(await run(["comm", "c1", "c2", "extra\narg"])).toMatchObject({ code: 1, stderr: `comm: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'comm --help' for more information.\n` });
+ expect(await run(["comm", "comm-missing", "c2"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: comm-missing: No such file or directory\n" });
+ expect(await run(["comm", "c1", "comm-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: comm-missing: No such file or directory\n" });
+ expect(await run(["comm", "missing'comm", "c2"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: \"missing'comm\": No such file or directory\n" });
+ expect(await run(["comm", "c1", "missing\ncomm"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: 'missing'$'\\n''comm': No such file or directory\n" });
+ await mkdir(join(dir, "comm-dir"));
+ expect(await run(["comm", "comm-dir", "c2"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: comm-dir: Is a directory\n" });
+ expect(await run(["comm", "c1", "comm-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: comm-dir: Is a directory\n" });
+ await mkdir(join(dir, "dir'comm"));
+ expect(await run(["comm", "dir'comm", "c2"])).toMatchObject({ code: 1, stdout: "", stderr: "comm: \"dir'comm\": Is a directory\n" });
+ expect(await run(["comm", "--output-delimiter=", "c1", "c2"])).toMatchObject({ code: 0, stdout: "a\n\0\0b\n\0c\n" });
+ expect(await run(["comm", "--output-delimiter=,", "--output-delimiter=+", "c1", "c2"])).toMatchObject({ code: 1, stderr: "comm: multiple output delimiters specified\n" });
+ await writeFile(join(dir, "comm-blank"), "\n");
+ expect(await run(["comm", "comm-blank", "c1"])).toMatchObject({ code: 0, stdout: "\n\ta\n\tb\n" });
+ expect(await run(["comm", "-", "-"], "a\nb\n")).toMatchObject({ code: 1, stdout: "a\n\tb\n", stderr: "comm: -\n" });
+ expect(await run(["comm", "-", "-"], "a\na\n")).toMatchObject({ code: 1, stdout: "\t\ta\n", stderr: "comm: -\n" });
+ await writeFile(join(dir, "comm-raw-left"), Uint8Array.of(0xff, 0x0a));
+ await writeFile(join(dir, "comm-raw-right"), Uint8Array.of(0xfe, 0x0a));
+ const commRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "comm", "comm-raw-left", "comm-raw-right"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "comm-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await commRaw.exited).toBe(0);
+ expect(await new Response(commRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "comm-raw-out"))]).toEqual([0x09, 0xfe, 0x0a, 0xff, 0x0a]);
+ await writeFile(join(dir, "cz1"), "a\0b\0");
+ await writeFile(join(dir, "cz2"), "b\0c\0");
+ expect(await run(["comm", "-z", "cz1", "cz2"])).toMatchObject({ code: 0, stdout: "a\0\t\tb\0\tc\0" });
+ await writeFile(join(dir, "unsorted1"), "b\na\n");
+ await writeFile(join(dir, "unsorted2"), "b\nc\n");
+ expect(await run(["comm", "unsorted1", "unsorted2"])).toMatchObject({ code: 1 });
+ expect(await run(["comm", "--nocheck-order", "unsorted1", "unsorted2"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "unsorted-paired-a"), "b\na\n");
+ await writeFile(join(dir, "unsorted-paired-b"), "b\na\n");
+ expect(await run(["comm", "unsorted-paired-a", "unsorted-paired-b"])).toMatchObject({ code: 0, stdout: "\t\tb\n\t\ta\n" });
+ expect(await run(["comm", "--check-order", "unsorted-paired-a", "unsorted-paired-b"])).toMatchObject({ code: 1 });
+});
+
+test("sort supports common GNU comparison modes and output options", async () => {
+ expect(await run(["sort", "-V"], "v2\nv10\nv1\n")).toMatchObject({ code: 0, stdout: "v1\nv2\nv10\n" });
+ expect(await run(["sort", "-V"], "gcc-c++-10.8.12-0.7rc2.fc9.tar.bz2\ngcc-c++-10.fc9.tar.gz\n")).toMatchObject({ code: 0, stdout: "gcc-c++-10.fc9.tar.gz\ngcc-c++-10.8.12-0.7rc2.fc9.tar.bz2\n" });
+ expect(await run(["sort", "-V"], "glibc-common-11-0.6rc2.ebuild\nglibc-common-11b.ebuild\nlibstdc++-4.10.4.20040204svn.rpm\nlibstdc++-4a.fc8.tar.gz\nnss_ldap-10.11.8.6.20040204cvs.fc10.ebuild\nnss_ldap-10beta1.fc8.tar.gz\n")).toMatchObject({ code: 0, stdout: "glibc-common-11b.ebuild\nglibc-common-11-0.6rc2.ebuild\nlibstdc++-4a.fc8.tar.gz\nlibstdc++-4.10.4.20040204svn.rpm\nnss_ldap-10beta1.fc8.tar.gz\nnss_ldap-10.11.8.6.20040204cvs.fc10.ebuild\n" });
+ expect(await run(["sort", "-M"], "Mar\nJan\nFeb\n")).toMatchObject({ code: 0, stdout: "Jan\nFeb\nMar\n" });
+ expect(await run(["sort", "-M"], "déc.\njanv.\naoût\nfévr.\n", { env: { LC_ALL: "fr_FR.utf8" } })).toMatchObject({
+ code: 0,
+ stdout: "janv.\nfévr.\naoût\ndéc.\n",
+ });
+ expect(await run(["sort", "-h"], "2K\n100\n1M\n")).toMatchObject({ code: 0, stdout: "100\n2K\n1M\n" });
+ expect(await run(["sort", "-h"], "1K\n02\n1\n")).toMatchObject({ code: 0, stdout: "1\n02\n1K\n" });
+ expect(await run(["sort", "-n"], "-18446744073709551615\n-18446744073709551616\n-922337203685477580.1\n-922337203685477580\n")).toMatchObject({ code: 0, stdout: "-18446744073709551616\n-18446744073709551615\n-922337203685477580.1\n-922337203685477580\n" });
+ expect(await run(["sort", "-g"], "1.0e100\n1.0e-4932\n1.0e-308\n-1.0e100\n")).toMatchObject({ code: 0, stdout: "-1.0e100\n1.0e-4932\n1.0e-308\n1.0e100\n" });
+ expect(await run(["sort", "-d"], "b-2\nb 1\nb_0\n")).toMatchObject({ code: 0, stdout: "b 1\nb_0\nb-2\n" });
+ expect(await run(["sort"], "a_a\na b\n", { env: { LC_ALL: "en_US.iso88591" } })).toMatchObject({ code: 0, stdout: "a_a\na b\n" });
+ expect(await run(["sort"], "é\ne\nE\nè\n", { env: { LC_ALL: "en_US.UTF-8" } })).toMatchObject({ code: 0, stdout: "e\nE\né\nè\n" });
+ expect(await run(["sort", "-z"], "b\0a\0")).toMatchObject({ code: 0, stdout: "a\0b\0" });
+ expect(await run(["sort", "-c"], "a\na\n")).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["sort", "-c"], "b\na\n")).toMatchObject({ code: 1, stderr: "sort: -:2: disorder: a\n" });
+ const sortHelp = await run(["sort", "--help"]);
+ expect(sortHelp).toMatchObject({ code: 0 });
+ expect(sortHelp.stdout).toContain(" -c\n");
+ expect(sortHelp.stdout).toContain(" -C\n");
+ expect(await run(["sort", "-cu"], "a\na\n")).toMatchObject({ code: 1 });
+ expect(await run(["sort", "-C"], "b\na\n")).toMatchObject({ code: 1, stdout: "", stderr: "" });
+ expect(await run(["sort", "--check=quiet"], "b\na\n")).toMatchObject({ code: 1, stdout: "", stderr: "" });
+ await writeFile(join(dir, "sort-random-source"), Buffer.from([1, 2, 3, 4, 16, 17, 18, 19, 24, 25, 26, 27, 32, 33, 34, 35, 40, 41, 42, 43, 48, 49, 50, 51]));
+ const randomSort = await run(["sort", "-R", "--random-source=sort-random-source"], "1\n2\n3\n4\n5\n6\n");
+ expect(randomSort).toMatchObject({ code: 0, stdout: "1\n3\n5\n2\n4\n6\n" });
+ expect(await run(["sort", "-n"], randomSort.stdout)).toMatchObject({ code: 0, stdout: "1\n2\n3\n4\n5\n6\n" });
+ const nbsp = 0xa0;
+ const humanThousandsInput = Buffer.from([
+ ...Buffer.from("1 1k 1 M 4"), nbsp, ...Buffer.from("003 1M\n"),
+ ...Buffer.from("2k 2M 2 k 4"), nbsp, ...Buffer.from("002 2\n"),
+ ...Buffer.from("3M 3 3 G 4"), nbsp, ...Buffer.from("001 3k\n"),
+ ]);
+ await writeFile(join(dir, "human-thousands"), humanThousandsInput);
+ expect(await run(["sort", "-h", "-k", "5", "-o", "human-thousands-out", "human-thousands"], "", { env: { LC_ALL: "sv_SE" } })).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "human-thousands-out"))).toEqual(Buffer.from([
+ ...Buffer.from("3M 3 3 G 4"), nbsp, ...Buffer.from("001 3k\n"),
+ ...Buffer.from("2k 2M 2 k 4"), nbsp, ...Buffer.from("002 2\n"),
+ ...Buffer.from("1 1k 1 M 4"), nbsp, ...Buffer.from("003 1M\n"),
+ ]));
+ await writeFile(join(dir, "unsorted"), "3\n1\n2\n");
+ expect(await run(["sort", "-o", "sorted", "unsorted"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await readFile(join(dir, "sorted"), "utf8")).toBe("1\n2\n3\n");
+ const sortFiles0Raw = Bun.spawn(["/bin/sh", "-c", `name=$(printf 'sort-\\377'); printf 'b\\na\\n' > "$name"; printf '%s\\0' "$name" > sort-files0-raw; LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} sort --files0-from=sort-files0-raw >sort-files0-raw-out`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await sortFiles0Raw.exited).toBe(0);
+ expect(await new Response(sortFiles0Raw.stderr).text()).toBe("");
+ expect(await readFile(join(dir, "sort-files0-raw-out"), "utf8")).toBe("a\nb\n");
+ await writeFile(join(dir, "sort-check-bad"), "b\na\n");
+ expect(await run(["sort", "-c", "sort-check-bad"])).toMatchObject({ code: 1, stderr: "sort: sort-check-bad:2: disorder: a\n" });
+ expect(await run(["sort", "--check", "sort-check-bad"])).toMatchObject({ code: 1, stdout: "", stderr: "sort: sort-check-bad:2: disorder: a\n" });
+ expect(await run(["sort", "--che", "sort-check-bad"])).toMatchObject({ code: 1, stdout: "", stderr: "sort: sort-check-bad:2: disorder: a\n" });
+ expect(await run(["sort", "--check", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: sort [OPTION]... [FILE]...\n") });
+ await writeFile(join(dir, "sort-a"), "b\n");
+ await writeFile(join(dir, "sort-b"), "a");
+ expect(await run(["sort", "-c", "sort-a", "sort-b"])).toMatchObject({ code: 2, stderr: "sort: extra operand 'sort-b' not allowed with -c\n" });
+ expect(await run(["sort", "-C", "sort-a", "sort-b"])).toMatchObject({ code: 2, stderr: "sort: extra operand 'sort-b' not allowed with -C\n" });
+ await writeFile(join(dir, "sort-list"), "sort-b\0sort-b\0sort-a\0");
+ expect(await run(["sort", "--files0-from=sort-list"])).toMatchObject({ code: 0, stdout: "a\na\nb\n" });
+ expect(await run(["sort", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: sort [OPTION]... [FILE]...\n or: sort [OPTION]... --files0-from=F\n") });
+ expect(await run(["sort", "--he=bad", "sort-a"])).toMatchObject(await systemRun(["sort", "--he=bad", "sort-a"]));
+ expect(await run(["sort", "--ver=bad", "sort-a"])).toMatchObject(await systemRun(["sort", "--ver=bad", "sort-a"]));
+ expect(await run(["sort", "--buf=bad", "sort-a"])).toMatchObject(await systemRun(["sort", "--buf=bad", "sort-a"]));
+ expect(await run(["sort", "--key=bad", "sort-a"])).toMatchObject(await systemRun(["sort", "--key=bad", "sort-a"]));
+ expect(await run(["sort", "--key=bad", "--help"])).toMatchObject(await systemRun(["sort", "--key=bad", "--help"]));
+ expect(await run(["sort", "--key", "bad", "--help"])).toMatchObject(await systemRun(["sort", "--key", "bad", "--help"]));
+ expect(await run(["sort", "-k", "bad", "--help"])).toMatchObject(await systemRun(["sort", "-k", "bad", "--help"]));
+ expect(await run(["sort", "--key=1", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: sort [OPTION]... [FILE]...\n") });
+ expect(await run(["sort", "--key=1\nx", "sort-a"])).toMatchObject({ code: 2, stdout: "", stderr: `sort: stray character in field spec: invalid field specification ${diagnosticQuote("1\\nx")}\n` });
+ expect(await run(["sort", "--key=0\nx", "sort-a"])).toMatchObject({ code: 2, stdout: "", stderr: `sort: field number is zero: invalid field specification ${diagnosticQuote("0\\nx")}\n` });
+ expect(await run(["sort", "--key=1.0", "sort-a"])).toMatchObject({ code: 2, stdout: "", stderr: `sort: character offset is zero: invalid field specification ${diagnosticQuote("1.0")}\n` });
+ expect(await run(["sort", "--key=1,bad", "sort-a"])).toMatchObject(await systemRun(["sort", "--key=1,bad", "sort-a"]));
+ await mkdir(join(dir, "sort-list-dir"));
+ expect(await run(["sort", "--files0-from=sort-list-dir"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: cannot read file names from 'sort-list-dir'\n" });
+ expect(await run(["sort", "--files0-from=missing\nsort-list"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: open failed: 'missing'$'\\n''sort-list': No such file or directory\n" });
+ await mkdir(join(dir, "sort'list-dir"));
+ expect(await run(["sort", "--files0-from=sort'list-dir"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: cannot read file names from \"sort'list-dir\"\n" });
+ await writeFile(join(dir, "sort\nempty-list"), "");
+ expect(await run(["sort", "--files0-from=sort\nempty-list"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: no input from 'sort'$'\\n''empty-list'\n" });
+ await writeFile(join(dir, "sort'zero-list"), "\0");
+ expect(await run(["sort", "--files0-from=sort'zero-list"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: \"sort'zero-list\":1: invalid zero-length file name\n" });
+ expect(await run(["sort", "--files0-from=-"], "-")).toMatchObject({ code: 2, stderr: "sort: when reading file names from standard input, no file name of '-' allowed\n" });
+ expect(await run(["sort", "--files0-from=-"], "\0sort-a\0")).toMatchObject({ code: 2, stderr: "sort: -:1: invalid zero-length file name\n" });
+ expect(await run(["sort", "-m", "--batch-size=1", "sort-a", "sort-b"])).toMatchObject(await systemRun(["sort", "-m", "--batch-size=1", "sort-a", "sort-b"]));
+ expect(await run(["sort", "--batch-size=bad", "--help"])).toMatchObject(await systemRun(["sort", "--batch-size=bad", "--help"]));
+ expect(await run(["sort", "--batch-size=2", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: sort [OPTION]... [FILE]...\n") });
+ expect(await run(["sort", "-m", "--batch-size=1K", "sort-a", "sort-b"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: invalid suffix in --batch-size argument '1K'\n" });
+ expect(await run(["sort", "-m", "--batch-size=1\n2", "sort-a", "sort-b"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: invalid suffix in --batch-size argument '1\n2'\n" });
+ expect(await run(["sort", "--buffer-size=1E"], "")).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["sort", "--buffer-size=bad", "--help"])).toMatchObject(await systemRun(["sort", "--buffer-size=bad", "--help"]));
+ expect(await run(["sort", "-S", "bad", "--help"])).toMatchObject(await systemRun(["sort", "-S", "bad", "--help"]));
+ expect(await run(["sort", "--buffer-size=1KB"], "")).toMatchObject({ code: 2, stdout: "", stderr: "sort: invalid suffix in --buffer-size argument '1KB'\n" });
+ expect(await run(["sort", "--buffer-size=1KiB"], "")).toMatchObject({ code: 2, stdout: "", stderr: "sort: invalid suffix in --buffer-size argument '1KiB'\n" });
+ expect(await run(["sort", "--buffer-size=1Z"], "")).toMatchObject({ code: 2, stdout: "", stderr: "sort: --buffer-size argument '1Z' too large\n" });
+ expect(await run(["sort", "--buffer-size=1R"], "")).toMatchObject({ code: 2, stdout: "", stderr: "sort: --buffer-size argument '1R' too large\n" });
+ expect(await run(["sort", "-m", "--batch-size=2", "-T", "missing\ntmp", "sort-a", "sort-b", "sort-check-bad"])).toMatchObject({
+ code: 2,
+ stdout: "",
+ stderr: "sort: cannot create temporary file in 'missing'$'\\n''tmp': No such file or directory\n",
+ });
+ await writeFile(join(dir, "sort'parent"), "x");
+ expect(await run(["sort", "-o", "sort'parent/out", "sort-a"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: open failed: \"sort'parent/out\": Not a directory\n" });
+ expect(await run(["sort", "--parallel=bad", "sort-a"])).toMatchObject({ code: 2, stderr: "sort: invalid --parallel argument 'bad'\n" });
+ expect(await run(["sort", "--parallel=bad", "--help"])).toMatchObject(await systemRun(["sort", "--parallel=bad", "--help"]));
+ expect(await run(["sort", "--parallel=1", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: sort [OPTION]... [FILE]...\n") });
+ expect(await run(["sort", "--parallel=0", "sort-a"])).toMatchObject({ code: 2, stderr: "sort: number in parallel must be nonzero\n" });
+ expect(await run(["sort", "--parallel=+1", "sort-a"])).toMatchObject({ code: 0, stdout: "b\n", stderr: "" });
+ expect(await run(["sort", "--parallel=+0", "sort-a"])).toMatchObject({ code: 2, stderr: "sort: number in parallel must be nonzero\n" });
+ expect(await run(["sort", "--parallel=1.5", "sort-a"])).toMatchObject({ code: 2, stderr: "sort: invalid suffix in --parallel argument '1.5'\n" });
+ expect(await run(["sort", "--check=", "sort-a"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `sort: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--check")}\nValid arguments are:\n - ${diagnosticQuote("quiet")}, ${diagnosticQuote("silent")}\n - ${diagnosticQuote("diagnose-first")}\nTry 'sort --help' for more information.\n`,
+ });
+ expect(await run(["sort", "--check=bad", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `sort: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("--check")}\nValid arguments are:\n - ${diagnosticQuote("quiet")}, ${diagnosticQuote("silent")}\n - ${diagnosticQuote("diagnose-first")}\nTry 'sort --help' for more information.\n`,
+ });
+ expect(await run(["sort", "-t", "xx", "sort-a"])).toMatchObject(await systemRun(["sort", "-t", "xx", "sort-a"]));
+ expect(await run(["sort", "--field-separator=xx", "--help"])).toMatchObject(await systemRun(["sort", "--field-separator=xx", "--help"]));
+ expect(await run(["sort", "-t", "xx", "--help"])).toMatchObject(await systemRun(["sort", "-t", "xx", "--help"]));
+ expect(await run(["sort", "--field-separator=x", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: sort [OPTION]... [FILE]...\n") });
+ expect(await run(["sort", "-t", "ab\nc", "sort-a"])).toMatchObject({ code: 2, stdout: "", stderr: `sort: multi-character tab ${diagnosticQuote("ab\\nc")}\n` });
+ expect(await run(["sort", "-t", "", "sort-a"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: empty tab\n" });
+ expect(await run(["sort", "-R", "--random-source=", "sort-a"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: open failed: '': No such file or directory\n" });
+ expect(await run(["sort", "--random-source=missing-random", "-R", "sort-a"])).toMatchObject({ code: 2, stdout: "", stderr: "sort: open failed: missing-random: No such file or directory\n" });
+ expect(await run(["sort", "--sort=", "sort-a"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `sort: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--sort")}\nValid arguments are:\n - ${diagnosticQuote("general-numeric")}\n - ${diagnosticQuote("human-numeric")}\n - ${diagnosticQuote("month")}\n - ${diagnosticQuote("numeric")}\n - ${diagnosticQuote("random")}\n - ${diagnosticQuote("version")}\nTry 'sort --help' for more information.\n`,
+ });
+ expect(await run(["sort", "--sort=", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `sort: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--sort")}\nValid arguments are:\n - ${diagnosticQuote("general-numeric")}\n - ${diagnosticQuote("human-numeric")}\n - ${diagnosticQuote("month")}\n - ${diagnosticQuote("numeric")}\n - ${diagnosticQuote("random")}\n - ${diagnosticQuote("version")}\nTry 'sort --help' for more information.\n`,
+ });
+ expect(await run(["sort", "--sort=bad", "sort-a"])).toMatchObject(await systemRun(["sort", "--sort=bad", "sort-a"]));
+ expect(await run(["sort", "--sort=bad", "--help"])).toMatchObject(await systemRun(["sort", "--sort=bad", "--help"]));
+ expect(await run(["sort", "--sort=bad\nmode", "sort-a"])).toMatchObject({
+ code: 1,
+ stderr: `sort: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--sort")}\nValid arguments are:\n - ${diagnosticQuote("general-numeric")}\n - ${diagnosticQuote("human-numeric")}\n - ${diagnosticQuote("month")}\n - ${diagnosticQuote("numeric")}\n - ${diagnosticQuote("random")}\n - ${diagnosticQuote("version")}\nTry 'sort --help' for more information.\n`,
+ });
+ expect(await run(["sort", "--debug", "sort-a"], "", { env: { LC_ALL: "C" } })).toMatchObject({
+ code: 0,
+ stderr: "sort: text ordering performed using simple byte comparison\n",
+ });
+ expect(await run(["sort", "--debug", "sort-a"], "", { env: { LC_ALL: "C.UTF-8" } })).toMatchObject({
+ code: 0,
+ stderr: `sort: text ordering performed using ${diagnosticQuote("C.UTF-8")} sorting rules\n`,
+ });
+ const missingTempDir = await run(["sort", "-m", "--batch-size=2", "-T", "does/not/exist", "sort-a", "sort-b", "sort-a"]);
+ expect(missingTempDir).toMatchObject({ code: 2 });
+ expect(missingTempDir.stderr).toContain("sort: cannot create temporary file in 'does/not/exist':");
+ expect(await run(["sort", "-m", "--batch-size=4", "-T", "does/not/exist", "sort-a", "sort-b"])).toMatchObject({ code: 0, stdout: "a\nb\n" });
+ await writeFile(join(dir, "sort-merge-a"), "a\nc\n");
+ await writeFile(join(dir, "sort-merge-b"), "b\nd\n");
+ expect(await run(["sort", "-m", "sort-merge-a", "sort-merge-b"])).toMatchObject({ code: 0, stdout: "a\nb\nc\nd\n" });
+ await writeFile(join(dir, "sort-merge-unsorted-a"), "b 2\na 10\na 2\n");
+ await writeFile(join(dir, "sort-merge-unsorted-b"), "b 2\na 10\na 2\n");
+ expect(await run(["sort", "-m", "sort-merge-unsorted-a", "sort-merge-unsorted-b"])).toMatchObject({ code: 0, stdout: "b 2\na 10\na 2\nb 2\na 10\na 2\n" });
+ await writeFile(join(dir, "sort-compress-helper"), "#!/bin/sh\ntouch sort-compress-ok\n");
+ await chmod(join(dir, "sort-compress-helper"), 0o755);
+ expect(await run(["sort", "--compress-program=./sort-compress-helper"], "b\na\n")).toMatchObject({ code: 0, stdout: "a\nb\n" });
+ expect(await stat(join(dir, "sort-compress-ok")).catch(() => null)).toBeNull();
+ expect(await run(["sort", "-m", "--batch-size=2", "--compress-program=./sort-compress-helper", "sort-a", "sort-b", "sort-a"])).toMatchObject({ code: 0, stdout: "a\nb\nb\n" });
+ expect((await stat(join(dir, "sort-compress-ok"))).isFile()).toBe(true);
+ await writeFile(join(dir, "sort-compress-fail"), "#!/bin/sh\n[ \"$1\" = -d ] && exit 7\ncat >/dev/null\n");
+ await chmod(join(dir, "sort-compress-fail"), 0o755);
+ expect(await run(["sort", "--compress-program=./sort-compress-fail"], "b\na\n")).toMatchObject(await systemRun(["/usr/bin/sort", "--compress-program=./sort-compress-fail"], "b\na\n"));
+ expect(await run(["sort", "-m", "--batch-size=2", "--compress-program=./sort-compress-fail", "sort-a", "sort-b", "sort-a"])).toMatchObject({ code: 2, stdout: "" });
+ expect(await run(["sort", "--compress-program=missing-helper"], "b\na\n")).toMatchObject(await systemRun(["/usr/bin/sort", "--compress-program=missing-helper"], "b\na\n"));
+ expect(await run(["sort", "-m", "--batch-size=2", "--compress-program=missing-helper", "sort-a", "sort-b", "sort-a"])).toMatchObject(await systemRun(["/usr/bin/sort", "-m", "--batch-size=2", "--compress-program=missing-helper", "sort-a", "sort-b", "sort-a"]));
+ await writeFile(join(dir, "sort-compress-large"), Array.from({ length: 2000 }, (_, i) => String(2000 - i).padStart(4, "0")).join("\n") + "\n");
+ const missingCompress = await run(["sort", "-S", "1k", "--compress-program=missing-helper", "sort-compress-large"]);
+ expect(missingCompress).toMatchObject({ code: 0, stderr: "sort: could not run compress program 'missing-helper': No such file or directory\n" });
+ expect(missingCompress.stdout.split("\n").slice(0, 3)).toEqual(["0001", "0002", "0003"]);
+ expect(await shell('"$BUN" "$BNU" sort --debug /dev/null 2>/dev/full')).toMatchObject({ code: 2 });
+});
+
+test("base64 and checksum utilities", async () => {
+ expect(await run(["base64"], "")).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["base64"], "hello")).toMatchObject({ code: 0, stdout: "aGVsbG8=\n" });
+ expect(await run(["base64", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: base64 [OPTION]... [FILE]\n") });
+ expect(await run(["basenc", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: basenc [OPTION]... [FILE]\n") });
+ expect(await run(["base64", "--v"])).toMatchObject({ code: 0, stdout: expect.stringContaining("bnu 9.11\n") });
+ await writeFile(join(dir, "base64-meta"), "hello");
+ expect(await run(["base64", "base64-meta", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: base64 [OPTION]... [FILE]\n"), stderr: "" });
+ expect(await run(["base64", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: unrecognized option '--bad'\nTry 'base64 --help' for more information.\n" });
+ expect(await run(["base64", "--h=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: option '--help' doesn't allow an argument\nTry 'base64 --help' for more information.\n" });
+ expect(await run(["base64", "--help=1", "--version"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: option '--help' doesn't allow an argument\nTry 'base64 --help' for more information.\n" });
+ expect(await run(["base64", "--d"], "YQ==")).toMatchObject({ code: 0, stdout: "a" });
+ expect(await run(["base64", "--i", "--d"], "Y!!Q==")).toMatchObject({ code: 0, stdout: "a" });
+ expect(await run(["base64", "--w=0"], "a")).toMatchObject({ code: 0, stdout: "YQ==" });
+ expect(await run(["base64", "--w", "--help"], "a")).toMatchObject(await systemRun(["base64", "--w", "--help"], "a"));
+ expect(await run(["base64", "--wrap=0"], "a")).toMatchObject({ code: 0, stdout: "YQ==" });
+ expect(await run(["base64", "--wrap=+0"], "a")).toMatchObject({ code: 0, stdout: "YQ==" });
+ expect(await run(["base64", "--wrap=+4"], "abc")).toMatchObject({ code: 0, stdout: "YWJj\n" });
+ expect(await run(["base64", "--wrap=9223372036854775807"], "abc")).toMatchObject({ code: 0, stdout: "YWJj\n" });
+ expect(await run(["base64", "--wrap=999999999999999999999999"], "abc")).toMatchObject({ code: 0, stdout: "YWJj" });
+ expect(await run(["base64", "--wrap=0x0"], "")).toMatchObject(await systemRun(["base64", "--wrap=0x0"], ""));
+ expect(await run(["base64", "--wrap=1\n2"], "")).toMatchObject({ code: 1, stdout: "", stderr: `base64: invalid wrap size: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["base64", "--wrap=-1"], "")).toMatchObject(await systemRun(["base64", "--wrap=-1"], ""));
+ expect(await run(["base64", "--wrap=bad", "--help"])).toMatchObject(await systemRun(["base64", "--wrap=bad", "--help"]));
+ expect(await run(["base64", "--wrap=-1", "--help"])).toMatchObject(await systemRun(["base64", "--wrap=-1", "--help"]));
+ expect(await run(["base64", "--wrap", "bad", "--help"])).toMatchObject(await systemRun(["base64", "--wrap", "bad", "--help"]));
+ expect(await run(["base64", "-w", "bad", "--help"])).toMatchObject(await systemRun(["base64", "-w", "bad", "--help"]));
+ expect(await run(["base64", "--wrap", "0", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: base64 [OPTION]... [FILE]\n") });
+ expect(await run(["base64", "/dev/null", "extra\narg"])).toMatchObject({ code: 1, stdout: "", stderr: `base64: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'base64 --help' for more information.\n` });
+ expect(await run(["base64", "base64-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: base64-missing: No such file or directory\n" });
+ expect(await run(["base64", "missing'base64"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: \"missing'base64\": No such file or directory\n" });
+ expect(await run(["base64", "missing\nbase64"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: 'missing'$'\\n''base64': No such file or directory\n" });
+ await mkdir(join(dir, "base64-dir"));
+ expect(await run(["base64", "base64-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: read error: Is a directory\n" });
+ await symlink("base64-loop", join(dir, "base64-loop"));
+ expect(await run(["base64", "base64-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: base64-loop: Too many levels of symbolic links\n" });
+ await symlink("loop'base64", join(dir, "loop'base64"));
+ expect(await run(["base64", "loop'base64"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: \"loop'base64\": Too many levels of symbolic links\n" });
+ expect(await run(["base64", "-d"], "aGVsbG8=\n")).toMatchObject({ code: 0, stdout: "hello" });
+ expect(await run(["base64", "-d", "base64-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "base64: base64-missing: No such file or directory\n" });
+ expect(await run(["base64", "-d"], "MTIzNA==MTIzNA")).toMatchObject({ code: 0, stdout: "12341234" });
+ expect(await run(["base64", "-d"], "SGVsbG9=")).toMatchObject({ code: 1, stdout: "Hello", stderr: "base64: invalid input\n" });
+ expect(await run(["base64", "-d"], "mzxw6===")).toMatchObject({ code: 1, stdout: "\uFFFD<p", stderr: "base64: invalid input\n" });
+ expect(await run(["base64", "-di"], "aGV!!sbG8=\n")).toMatchObject({ code: 0, stdout: "hello" });
+ expect(await run(["base64", "-d"], "aGV!!sbG8=\n")).toMatchObject({ code: 1, stdout: "he", stderr: "base64: invalid input\n" });
+ expect(await run(["base64", "-di"], "bad!!\n")).toMatchObject({ code: 1, stdout: "m�", stderr: "base64: invalid input\n" });
+ expect(await run(["base32"], "abc")).toMatchObject({ code: 0, stdout: "MFRGG===\n" });
+ expect(await run(["base32", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: base32 [OPTION]... [FILE]\n") });
+ expect(await run(["base32", "--v"])).toMatchObject({ code: 0, stdout: expect.stringContaining("bnu 9.11\n") });
+ await writeFile(join(dir, "base32-meta"), "abc");
+ expect(await run(["base32", "base32-meta", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: base32 [OPTION]... [FILE]\n"), stderr: "" });
+ expect(await run(["base32", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "base32: unrecognized option '--bad'\nTry 'base32 --help' for more information.\n" });
+ expect(await run(["base32", "--h=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "base32: option '--help' doesn't allow an argument\nTry 'base32 --help' for more information.\n" });
+ expect(await run(["base32", "--d"], "ME======")).toMatchObject({ code: 0, stdout: "a" });
+ expect(await run(["base32", "--i", "--d"], "M!!E======")).toMatchObject({ code: 0, stdout: "a" });
+ expect(await run(["base32", "--w", "--help"], "a")).toMatchObject(await systemRun(["base32", "--w", "--help"], "a"));
+ expect(await run(["base32", "--wrap=bad", "--help"])).toMatchObject(await systemRun(["base32", "--wrap=bad", "--help"]));
+ expect(await run(["base32", "-w", "bad", "--help"])).toMatchObject(await systemRun(["base32", "-w", "bad", "--help"]));
+ expect(await run(["base32", "base32-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "base32: base32-missing: No such file or directory\n" });
+ expect(await run(["base32", "missing'base32"])).toMatchObject({ code: 1, stdout: "", stderr: "base32: \"missing'base32\": No such file or directory\n" });
+ expect(await run(["base32", "missing\nbase32"])).toMatchObject({ code: 1, stdout: "", stderr: "base32: 'missing'$'\\n''base32': No such file or directory\n" });
+ await mkdir(join(dir, "base32-dir"));
+ expect(await run(["base32", "base32-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "base32: read error: Is a directory\n" });
+ await symlink("base32-loop", join(dir, "base32-loop"));
+ expect(await run(["base32", "base32-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "base32: base32-loop: Too many levels of symbolic links\n" });
+ await symlink("loop'base32", join(dir, "loop'base32"));
+ expect(await run(["base32", "loop'base32"])).toMatchObject({ code: 1, stdout: "", stderr: "base32: \"loop'base32\": Too many levels of symbolic links\n" });
+ expect(await run(["base32", "-d"], "MFRGG===\n")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["base32", "-d"], "mfrgg===\n")).toMatchObject({ code: 1, stdout: "", stderr: "base32: invalid input\n" });
+ expect(await run(["base32", "-di"], "mfrgg===\n")).toMatchObject({ code: 1, stdout: "", stderr: "base32: invalid input\n" });
+ expect(await run(["base32", "-d"], "MFRgG===\n")).toMatchObject({ code: 1, stdout: "a", stderr: "base32: invalid input\n" });
+ expect(await run(["base32", "-d", "base32-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "base32: base32-missing: No such file or directory\n" });
+ expect(await run(["base32", "-d", "--ignore-garbage"], "MF!!RGG===\n")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["base32", "-d"], "MF!!RGG===\n")).toMatchObject({ code: 1, stdout: "a", stderr: "base32: invalid input\n" });
+ expect(await run(["md5sum"], "abc")).toMatchObject({ code: 0, stdout: "900150983cd24fb0d6963f7d28e17f72 -\n" });
+ const md5Help = await run(["md5sum", "--help"]);
+ const md5HelpStdout = String(md5Help.stdout);
+ expect(md5Help).toMatchObject({ code: 0, stdout: expect.stringContaining("Print or check MD5 (128-bit) checksums.\nLegacy interface to the cksum utility.\n") });
+ expect(md5HelpStdout.includes("--length")).toBe(false);
+ expect(md5HelpStdout.includes(" -l\n")).toBe(false);
+ expect(md5HelpStdout).toContain(" -w\n");
+ expect(await run(["md5sum", "-b"], "abc")).toMatchObject({ code: 0, stdout: "900150983cd24fb0d6963f7d28e17f72 *-\n" });
+ expect(await run(["md5sum", "--tag"], "abc")).toMatchObject({ code: 0, stdout: "MD5 (-) = 900150983cd24fb0d6963f7d28e17f72\n" });
+ expect(await run(["sha256sum"], "abc")).toMatchObject({ code: 0, stdout: "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad -\n" });
+ expect(await run(["sha256sum", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Print or check SHA256 (256-bit) checksums.\nLegacy interface to the cksum utility.\n") });
+ expect(await run(["sha256sum", "--length=bad", "--help"])).toMatchObject(await systemRun(["sha256sum", "--length=bad", "--help"]));
+ expect(await run(["cksum", "--algorithm=sha256"], "abc")).toMatchObject({ code: 0, stdout: "SHA256 (-) = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\n" });
+ expect(await run(["cksum", "--alg=sha256", "--unt"], "abc")).toMatchObject({ code: 0, stdout: "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad -\n" });
+ expect(await run(["cksum", "--bad", "--help"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: "cksum: unrecognized option '--bad'\nTry 'cksum --help' for more information.\n" });
+ expect(await run(["cksum", "--b=1"], "abc")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "cksum: option '--b=1' is ambiguous; possibilities: '--base64' '--binary'\nTry 'cksum --help' for more information.\n",
+ });
+ expect(await run(["cksum", "--version=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "cksum: option '--version' doesn't allow an argument\nTry 'cksum --help' for more information.\n" });
+ expect(await run(["cksum", "--alg", "--help"], "abc")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: expect.stringContaining(`cksum: invalid argument ${diagnosticQuote("--help")} for ${diagnosticQuote("--algorithm")}\n`),
+ });
+ expect(await run(["cksum", "--alg=crc", "--help"], "abc")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cksum [OPTION]... [FILE]...\n") });
+ expect(await run(["cksum", "--algorithm=", "--help"], "abc")).toMatchObject(await systemRun(["cksum", "--algorithm=", "--help"], "abc"));
+ expect(await run(["cksum", "--algorithm=bad", "--help"], "abc")).toMatchObject(await systemRun(["cksum", "--algorithm=bad", "--help"], "abc"));
+ expect(await run(["cksum", "-a", "bad", "--help"], "abc")).toMatchObject(await systemRun(["cksum", "-a", "bad", "--help"], "abc"));
+ expect(await run(["cksum", "-abad", "--help"], "abc")).toMatchObject(await systemRun(["cksum", "-abad", "--help"], "abc"));
+ expect(await run(["cksum", "-a", "sha2", "--help"], "abc")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cksum [OPTION]... [FILE]...\n") });
+ expect(await run(["cksum", "-w", "--help", "--help"], "abc")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cksum [OPTION]... [FILE]...\n") });
+ expect(await run(["cksum", "BEFORE", "--help", "AFTER"], "abc")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: cksum [OPTION]... [FILE]...\n") });
+ expect(await run(["cksum", "BEFORE", "--version", "AFTER"], "abc")).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["cksum", "--algorithm=sm3", "--untagged"], "abc")).toMatchObject({ code: 0, stdout: "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0 -\n" });
+ expect(await run(["cksum", "--algorithm=md5", "--tag", "--untagged"], "abc")).toMatchObject({ code: 0, stdout: "900150983cd24fb0d6963f7d28e17f72 -\n" });
+ expect(await run(["cksum", "--algorithm=md5", "--untagged", "--tag"], "abc")).toMatchObject({ code: 0, stdout: "MD5 (-) = 900150983cd24fb0d6963f7d28e17f72\n" });
+ expect(await run(["cksum", "--algorithm=md5", "--untagged", "--binary", "--text"], "abc")).toMatchObject({ code: 0, stdout: "900150983cd24fb0d6963f7d28e17f72 -\n" });
+ expect(await run(["cksum", "--status"], "abc")).toMatchObject({ code: 1, stderr: "cksum: the --status option is meaningful only when verifying checksums\nTry 'cksum --help' for more information.\n" });
+ expect(await run(["cksum", "--ignore-missing"], "abc")).toMatchObject({ code: 1, stderr: "cksum: the --ignore-missing option is meaningful only when verifying checksums\nTry 'cksum --help' for more information.\n" });
+ expect(await run(["cksum", "--algorithm=bad"], "abc")).toMatchObject({
+ code: 1,
+ stderr: `cksum: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("--algorithm")}\nValid arguments are:\n - ${diagnosticQuote("bsd")}\n - ${diagnosticQuote("sysv")}\n - ${diagnosticQuote("crc")}\n - ${diagnosticQuote("crc32b")}\n - ${diagnosticQuote("md5")}\n - ${diagnosticQuote("sha1")}\n - ${diagnosticQuote("sha224")}\n - ${diagnosticQuote("sha256")}\n - ${diagnosticQuote("sha384")}\n - ${diagnosticQuote("sha512")}\n - ${diagnosticQuote("sha2")}\n - ${diagnosticQuote("sha3")}\n - ${diagnosticQuote("blake2b")}\n - ${diagnosticQuote("sm3")}\nTry 'cksum --help' for more information.\n`,
+ });
+ expect(await run(["cksum", "--algorithm=bad\nmode"], "abc")).toMatchObject({
+ code: 1,
+ stderr: `cksum: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--algorithm")}\nValid arguments are:\n - ${diagnosticQuote("bsd")}\n - ${diagnosticQuote("sysv")}\n - ${diagnosticQuote("crc")}\n - ${diagnosticQuote("crc32b")}\n - ${diagnosticQuote("md5")}\n - ${diagnosticQuote("sha1")}\n - ${diagnosticQuote("sha224")}\n - ${diagnosticQuote("sha256")}\n - ${diagnosticQuote("sha384")}\n - ${diagnosticQuote("sha512")}\n - ${diagnosticQuote("sha2")}\n - ${diagnosticQuote("sha3")}\n - ${diagnosticQuote("blake2b")}\n - ${diagnosticQuote("sm3")}\nTry 'cksum --help' for more information.\n`,
+ });
+ expect(await run(["sm3sum"], "abc")).toMatchObject({ code: 0, stdout: "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0 -\n" });
+ expect(await run(["cksum", "--algorithm=sha2", "--length=224", "--untagged"], "abc")).toMatchObject({ code: 0, stdout: "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7 -\n" });
+ expect(await run(["cksum", "--algorithm=md5", "--length=0", "--untagged"], "abc")).toMatchObject({ code: 0, stdout: "900150983cd24fb0d6963f7d28e17f72 -\n" });
+ expect(await run(["cksum", "--algorithm=blake2b", "--length=8", "--untagged"], "test input\n")).toMatchObject({ code: 0, stdout: "86 -\n" });
+ expect(await run(["cksum", "--length=7"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: "cksum: --length is only supported with --algorithm blake2b, sha2, or sha3\n" });
+ expect(await run(["cksum", "--algorithm=md5", "--length=16"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: "cksum: --length is only supported with --algorithm blake2b, sha2, or sha3\n" });
+ expect(await run(["cksum", "--algorithm=sha2", "--length=7"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `cksum: invalid length: ${diagnosticQuote("7")}\ncksum: digest length for ${diagnosticQuote("SHA2")} must be 224, 256, 384, or 512\n` });
+ expect(await run(["cksum", "--algorithm=sha2", "--length=bad"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `cksum: invalid length: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["cksum", "--length=bad", "--help"])).toMatchObject(await systemRun(["cksum", "--length=bad", "--help"]));
+ expect(await run(["cksum", "--length", "bad", "--help"])).toMatchObject(await systemRun(["cksum", "--length", "bad", "--help"]));
+ expect(await run(["cksum", "-l", "bad", "--help"])).toMatchObject(await systemRun(["cksum", "-l", "bad", "--help"]));
+ expect(await run(["cksum", "-lbad", "--help"])).toMatchObject(await systemRun(["cksum", "-lbad", "--help"]));
+ expect(await run(["cksum", "--length=-1", "--help"])).toMatchObject(await systemRun(["cksum", "--length=-1", "--help"]));
+ expect(await run(["cksum", "--algorithm=sha2", "--length=7\n8"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `cksum: invalid length: ${diagnosticQuote("7\\n8")}\n` });
+ expect(await run(["cksum", "--algorithm=sha2", "--length=-1"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `cksum: invalid length: ${diagnosticQuote("-1")}: Value too large for defined data type\n` });
+ expect(await run(["cksum", "--algorithm=sha3", "--length=bad"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `cksum: invalid length: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["cksum", "--algorithm=blake2b", "--length=9"], "abc")).toMatchObject({ code: 1, stdout: "", stderr: `cksum: invalid length: ${diagnosticQuote("9")}\ncksum: length is not a multiple of 8\n` });
+ expect(await run(["cksum", "--algorithm=blake2b", "--length=0"], "abc")).toMatchObject({ code: 0, stdout: "BLAKE2b (-) = ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923\n" });
+ expect(await run(["b2sum", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ const b2Help = await run(["b2sum", "--help"]);
+ const b2HelpStdout = String(b2Help.stdout);
+ expect(b2Help).toMatchObject({ code: 0, stdout: expect.stringContaining("Print or check BLAKE2b (512-bit) checksums.\nLegacy interface to the cksum utility.\n") });
+ expect(b2HelpStdout).toContain("--length");
+ expect(b2HelpStdout).toContain(" -l\n");
+ expect(b2HelpStdout).toContain(" -w\n");
+ expect(await run(["b2sum", "--l=128"], "")).toMatchObject({ code: 0, stdout: "cae66941d9efbd404e4d88758ea67670 -\n" });
+ expect(await run(["b2sum", "--l", "--help"], "")).toMatchObject({ code: 1, stdout: "", stderr: `b2sum: invalid length: ${diagnosticQuote("--help")}\n` });
+ expect(await run(["b2sum", "--length=128"], "")).toMatchObject({ code: 0, stdout: "cae66941d9efbd404e4d88758ea67670 -\n" });
+ expect(await run(["b2sum", "--length=bad", "--help"])).toMatchObject(await systemRun(["b2sum", "--length=bad", "--help"]));
+ expect(await run(["b2sum", "--length", "bad", "--help"])).toMatchObject(await systemRun(["b2sum", "--length", "bad", "--help"]));
+ expect(await run(["b2sum", "-l", "bad", "--help"])).toMatchObject(await systemRun(["b2sum", "-l", "bad", "--help"]));
+ expect(await run(["b2sum", "-lbad", "--help"])).toMatchObject(await systemRun(["b2sum", "-lbad", "--help"]));
+ expect(await run(["b2sum", "-l", "513", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: b2sum [OPTION]... [FILE]...\n") });
+ expect((await run(["cksum", "--algorithm=sha3", "--length=216"], "")).stderr).toContain(`digest length for ${diagnosticQuote("SHA3")}`);
+ expect((await run(["b2sum", "--length=513"], "")).stderr).toContain(`maximum digest length for ${diagnosticQuote("BLAKE2b")}`);
+ expect(await run(["b2sum", "--length=bad"], "")).toMatchObject({ code: 1, stdout: "", stderr: `b2sum: invalid length: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["b2sum", "--length=1\n2"], "")).toMatchObject({ code: 1, stdout: "", stderr: `b2sum: invalid length: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["b2sum", "--length=-1"], "")).toMatchObject({ code: 1, stdout: "", stderr: `b2sum: invalid length: ${diagnosticQuote("-1")}: Value too large for defined data type\n` });
+ expect(await run(["b2sum", "--length=-1\n2"], "")).toMatchObject({ code: 1, stdout: "", stderr: `b2sum: invalid length: ${diagnosticQuote("-1\\n2")}\n` });
+ expect(await run(["cksum", "--algorithm=md5", "--base64"], "abc")).toMatchObject({ code: 0, stdout: "MD5 (-) = kAFQmDzST7DWlj99KOF/cg==\n" });
+ const cksumHelp = (await run(["cksum", "--help"])).stdout;
+ expect(cksumHelp).toContain("Print or verify checksums.\nBy default use the 32 bit CRC algorithm.\n");
+ expect(cksumHelp).toContain(" blake2b\n sm3\n");
+ expect(await run(["sm3sum", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Print or check SM3 (256-bit) checksums.\nLegacy interface to the cksum utility.\n") });
+ await writeFile(join(dir, "crc-bytes"), Uint8Array.from({ length: 65 }, (_, i) => i));
+ await writeFile(join(dir, "empty"), "");
+ await writeFile(join(dir, "a\nb"), "");
+ await mkdir(join(dir, "checksum-dir"));
+ const zeroMd5 = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "md5sum", "--text", "--zero", "a\nb"], { cwd: dir, stdout: "pipe", stderr: "pipe" });
+ expect(await zeroMd5.exited).toBe(0);
+ expect(new Uint8Array(await new Response(zeroMd5.stdout).arrayBuffer())).toEqual(Buffer.from("d41d8cd98f00b204e9800998ecf8427e a\nb\0"));
+ expect(await run(["cksum", "crc-bytes"])).toMatchObject({ code: 0, stdout: "796287823 65 crc-bytes\n" });
+ expect(await run(["cksum", "--algorithm=crc32b", "crc-bytes"])).toMatchObject({ code: 0, stdout: "1086353368 65 crc-bytes\n" });
+ expect(await run(["cksum", "--algorithm=crc32b", "-"], "abc")).toMatchObject({ code: 0, stdout: "891568578 3 -\n" });
+ expect(await run(["cksum", "--debug", "crc-bytes"])).toMatchObject({ code: 0, stdout: "796287823 65 crc-bytes\n" });
+ expect(await run(["cksum", "checksum-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "cksum: checksum-dir: Is a directory\n" });
+ expect(await run(["cksum", "cksum-missing-a", "crc-bytes", "cksum-missing-b"])).toMatchObject({ code: 1, stdout: "796287823 65 crc-bytes\n", stderr: "cksum: cksum-missing-a: No such file or directory\ncksum: cksum-missing-b: No such file or directory\n" });
+ expect(await run(["cksum", "missing'cksum"])).toMatchObject({ code: 1, stdout: "", stderr: "cksum: \"missing'cksum\": No such file or directory\n" });
+ expect(await run(["cksum", "missing\ncksum"])).toMatchObject({ code: 1, stdout: "", stderr: "cksum: 'missing'$'\\n''cksum': No such file or directory\n" });
+ await mkdir(join(dir, "dir'cksum"));
+ expect(await run(["cksum", "dir'cksum"])).toMatchObject({ code: 1, stdout: "", stderr: "cksum: \"dir'cksum\": Is a directory\n" });
+ await symlink("loop'cksum", join(dir, "loop'cksum"));
+ expect(await run(["cksum", "loop'cksum"])).toMatchObject({ code: 1, stdout: "", stderr: "cksum: \"loop'cksum\": Too many levels of symbolic links\n" });
+ expect(await run(["md5sum", "missing'cksum"])).toMatchObject({ code: 1, stdout: "", stderr: "md5sum: \"missing'cksum\": No such file or directory\n" });
+ expect(await run(["b2sum", "loop'cksum"])).toMatchObject({ code: 1, stdout: "", stderr: "b2sum: \"loop'cksum\": Too many levels of symbolic links\n" });
+ expect(await run(["cksum", "--debug", "--algorithm=md5", "empty"])).toMatchObject({ code: 0, stdout: "MD5 (empty) = d41d8cd98f00b204e9800998ecf8427e\n", stderr: "" });
+ expect(await run(["cksum", "--algorithm=md5", "cksum-missing", "empty"])).toMatchObject({ code: 1, stdout: "MD5 (empty) = d41d8cd98f00b204e9800998ecf8427e\n", stderr: "cksum: cksum-missing: No such file or directory\n" });
+ expect(await run(["md5sum", "checksum-dir", "empty"])).toMatchObject({ code: 1, stdout: "d41d8cd98f00b204e9800998ecf8427e empty\n", stderr: "md5sum: checksum-dir: Is a directory\n" });
+ expect(await run(["b2sum", "checksum-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "b2sum: checksum-dir: Is a directory\n" });
+ expect(await run(["cksum", "--untagged", "--algorithm=bsd", "empty"])).toMatchObject({ code: 0, stdout: "00000 0 empty\n" });
+ expect(await run(["cksum", "--untagged", "--algorithm=sysv", "cksum-missing", "empty"])).toMatchObject({ code: 1, stdout: "0 0 empty\n", stderr: "cksum: cksum-missing: No such file or directory\n" });
+ expect(await run(["cksum", "--untagged", "--algorithm=sysv", "empty"])).toMatchObject({ code: 0, stdout: "0 0 empty\n" });
+ expect(await run(["cksum", "--untagged", "--binary", "--algorithm=md5", "empty"])).toMatchObject({ code: 0, stdout: "d41d8cd98f00b204e9800998ecf8427e *empty\n" });
+ expect(await run(["cksum", "--text", "--tag", "--algorithm=md5", "empty"])).toMatchObject({ code: 1 });
+ const rawCrc = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "cksum", "--raw", "--algorithm=crc", "empty"], { cwd: dir, stdout: "pipe", stderr: "pipe" });
+ expect(await rawCrc.exited).toBe(0);
+ expect(new Uint8Array(await new Response(rawCrc.stdout).arrayBuffer())).toEqual(Uint8Array.of(0xff, 0xff, 0xff, 0xff));
+ const rawCrcLengthZero = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "cksum", "--raw", "--algorithm=crc", "--length=0", "empty"], { cwd: dir, stdout: "pipe", stderr: "pipe" });
+ expect(await rawCrcLengthZero.exited).toBe(0);
+ expect(new Uint8Array(await new Response(rawCrcLengthZero.stdout).arrayBuffer())).toEqual(Uint8Array.of(0xff, 0xff, 0xff, 0xff));
+ const rawBsd = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "cksum", "--raw", "--algorithm=bsd", "empty"], { cwd: dir, stdout: "pipe", stderr: "pipe" });
+ expect(await rawBsd.exited).toBe(0);
+ expect(new Uint8Array(await new Response(rawBsd.stdout).arrayBuffer())).toEqual(Uint8Array.of(0, 0));
+ await writeFile(join(dir, "be"), Uint8Array.of(0x12, 0x34));
+ expect(await run(["od", "--endian=big", "-An", "-tu2", "be"])).toMatchObject({ code: 0, stdout: " 4660\n" });
+});
+
+test("checksum utilities verify checksum files", async () => {
+ await writeFile(join(dir, "data"), "abc");
+ await writeFile(join(dir, "data.md5"), "900150983cd24fb0d6963f7d28e17f72 data\n");
+ expect(await run(["md5sum", "-c", "data.md5"])).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ const md5RawCheck = Bun.spawn(["/bin/sh", "-c", `name=$(printf 'sum-\\377'); printf 'abc' > "$name"; printf '900150983cd24fb0d6963f7d28e17f72 %s\\n' "$name" > raw.md5; LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} md5sum -c raw.md5 >raw-md5-out`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await md5RawCheck.exited).toBe(0);
+ expect(await new Response(md5RawCheck.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "raw-md5-out"))]).toEqual([0x27, 0x73, 0x75, 0x6d, 0x2d, 0x27, 0x24, 0x27, 0x5c, 0x33, 0x37, 0x37, 0x27, 0x3a, 0x20, 0x4f, 0x4b, 0x0a]);
+ expect(await run(["md5sum", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "md5sum: unrecognized option '--bad'\nTry 'md5sum --help' for more information.\n" });
+ expect(await run(["md5sum", "--sta", "--check", "missing"])).toMatchObject({ code: 1, stdout: "", stderr: "md5sum: missing: No such file or directory\n" });
+ expect(await run(["md5sum", "--st=1", "data.md5"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "md5sum: option '--st=1' is ambiguous; possibilities: '--status' '--strict'\nTry 'md5sum --help' for more information.\n",
+ });
+ expect(await run(["md5sum", "--version=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "md5sum: option '--version' doesn't allow an argument\nTry 'md5sum --help' for more information.\n" });
+ expect(await run(["md5sum", "--tag", "data"])).toMatchObject({ code: 0, stdout: "MD5 (data) = 900150983cd24fb0d6963f7d28e17f72\n" });
+ expect(await run(["md5sum", "--quiet", "data"])).toMatchObject({ code: 1, stderr: "md5sum: the --quiet option is meaningful only when verifying checksums\nTry 'md5sum --help' for more information.\n" });
+ expect(await run(["md5sum", "--warn", "data"])).toMatchObject({ code: 1, stderr: "md5sum: the --warn option is meaningful only when verifying checksums\nTry 'md5sum --help' for more information.\n" });
+ expect(await run(["md5sum", "-w", "data"])).toMatchObject({ code: 1, stderr: "md5sum: the --warn option is meaningful only when verifying checksums\nTry 'md5sum --help' for more information.\n" });
+ expect(await run(["b2sum", "--tag", "--length=128", "data"])).toMatchObject({ code: 0, stdout: "BLAKE2b-128 (data) = cf4ab791c62b8d2b2109c90275287816\n" });
+ await writeFile(join(dir, "compact.md5"), "MD5(data)= 900150983cd24fb0d6963f7d28e17f72\n");
+ expect(await run(["md5sum", "--check", "compact.md5"])).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ expect(await run(["md5sum", "--ignore-missing", "data"])).toMatchObject({ code: 1 });
+ expect(await run(["md5sum", "--quiet", "-c", "data.md5"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ await writeFile(join(dir, "dir-tagged.md5"), "MD5 (.) = d41d8cd98f00b204e9800998ecf8427e\n");
+ expect(await run(["cksum", "--check", "dir-tagged.md5"])).toMatchObject({
+ code: 1,
+ stdout: ".: FAILED open or read\n",
+ stderr: "cksum: .: Is a directory\ncksum: WARNING: 1 listed file could not be read\n",
+ });
+ await writeFile(join(dir, "data.md5"), "00000000000000000000000000000000 data\n");
+ expect(await run(["md5sum", "--check", "data.md5"])).toMatchObject({ code: 1, stdout: "data: FAILED\n" });
+ expect(await run(["md5sum", "--status", "-c", "data.md5"])).toMatchObject({ code: 1, stdout: "", stderr: "" });
+ await writeFile(join(dir, "mixed.md5"), "bad line\n900150983cd24fb0d6963f7d28e17f72 data\n");
+ expect(await run(["md5sum", "-c", "mixed.md5"])).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ const warned = await run(["md5sum", "--warn", "-c", "mixed.md5"]);
+ expect(warned).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ expect(warned.stderr).toContain("improperly formatted MD5 checksum line");
+ const warnedShort = await run(["md5sum", "-w", "-c", "mixed.md5"]);
+ expect(warnedShort).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ expect(warnedShort.stderr).toContain("improperly formatted MD5 checksum line");
+ expect(await run(["md5sum", "--strict", "-c", "mixed.md5"])).toMatchObject({ code: 1, stdout: "data: OK\n" });
+ await writeFile(join(dir, "missing.md5"), "900150983cd24fb0d6963f7d28e17f72 missing\n");
+ expect(await run(["md5sum", "--ignore-missing", "-c", "missing.md5"])).toMatchObject({ code: 1, stdout: "" });
+ await writeFile(join(dir, "some-missing.md5"), "900150983cd24fb0d6963f7d28e17f72 missing\n900150983cd24fb0d6963f7d28e17f72 data\n");
+ expect(await run(["md5sum", "--ignore-missing", "-c", "some-missing.md5"])).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ const sha2b64 = await run(["cksum", "--algorithm=sha2", "--length=224", "--base64", "--untagged", "data"]);
+ await writeFile(join(dir, "data.sha2b64"), sha2b64.stdout);
+ expect(await run(["cksum", "--algorithm=sha2", "--check", "data.sha2b64"])).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ const taggedSm3 = await run(["cksum", "--algorithm=sm3", "data"]);
+ await writeFile(join(dir, "data.sm3"), taggedSm3.stdout);
+ expect(await run(["cksum", "--check", "data.sm3"])).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ const untaggedMd5 = await run(["cksum", "--algorithm=md5", "--untagged", "data"]);
+ await writeFile(join(dir, "data.ckmd5"), untaggedMd5.stdout);
+ expect(await run(["cksum", "--algorithm=md5", "--check", "--tag", "--untagged", "data.ckmd5"])).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ const taggedSha2 = await run(["cksum", "--algorithm=sha2", "--length=384", "data"]);
+ await writeFile(join(dir, "data.sha384tag"), taggedSha2.stdout.replace(/^SHA/, "SHA2-"));
+ expect(await run(["cksum", "--algorithm=sha2", "--check", "data.sha384tag"])).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ const shortBlake = await run(["cksum", "--algorithm=blake2b", "--length=8", "--untagged", "data"]);
+ await writeFile(join(dir, "data.b2"), shortBlake.stdout);
+ expect(await run(["cksum", "--algorithm=blake2b", "--check", "data.b2"])).toMatchObject({ code: 0, stdout: "data: OK\n" });
+ await writeFile(join(dir, "data.crc"), "891568578 3 data\n");
+ expect(await run(["cksum", "--algorithm=crc32b", "--check", "data.crc"])).toMatchObject({ code: 1, stderr: "cksum: --check is not supported with --algorithm={bsd,sysv,crc,crc32b}\n" });
+ await writeFile(join(dir, "bad.sm3"), `${taggedSm3.stdout}invalid line\n`);
+ expect((await run(["cksum", "--status", "--warn", "--check", "bad.sm3"])).stderr).toContain("improperly formatted");
+ expect(await run(["cksum", "--warn", "--status", "--check", "bad.sm3"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ await writeFile(join(dir, " "), "space\n");
+ const spaceSum = await run(["md5sum", "--text", " "]);
+ await writeFile(join(dir, "space.md5"), spaceSum.stdout);
+ expect(await run(["md5sum", "--strict", "--check", "space.md5"])).toMatchObject({ code: 0, stdout: " : OK\n" });
+ await writeFile(join(dir, "test\n\\\\file"), "");
+ expect(await run(["md5sum", "--tag", "test\n\\\\file"])).toMatchObject({ code: 0, stdout: "\\MD5 (test\\n\\\\\\\\file) = d41d8cd98f00b204e9800998ecf8427e\n" });
+});
+
+test("launcher exposes the multi-call command surface", async () => {
+ const proc = Bun.spawn([join(import.meta.dir, "../bin/bnu.js"), "echo", "via", "launcher"], { cwd: dir, stdout: "pipe", stderr: "pipe" });
+ expect(await proc.exited).toBe(0);
+ expect(await new Response(proc.stdout).text()).toBe("via launcher\n");
+ await symlink(join(import.meta.dir, "../bin/bnu.js"), join(dir, "unknown-multicall"));
+ const multicallPath = join(dir, "unknown-multicall");
+ const multicall = Bun.spawn([multicallPath], { cwd: dir, env: { ...process.env, _: multicallPath }, stdout: "pipe", stderr: "pipe" });
+ expect(await multicall.exited).toBe(1);
+ expect(await new Response(multicall.stdout).text()).toBe("");
+ expect(await new Response(multicall.stderr).text()).toBe("coreutils: unknown program 'unknown-multicall'\n");
+ expect((await run(["cksum", "--help"])).stdout).toContain("--algorithm");
+ expect(await run(["ginstall", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: install [OPTION]... [-T] SOURCE DEST\n") });
+ expect((await run(["ginstall", "--help"])).stdout).toContain("--target-directory");
+ const lsHelp = (await run(["ls", "--help"])).stdout;
+ expect(lsHelp).toContain("List information about the FILEs (the current directory by default).\n");
+ expect(lsHelp).toContain("--color");
+ const tailHelp = (await run(["tail", "--help"])).stdout;
+ expect(tailHelp).toContain("--sleep-interval");
+ expect(tailHelp).not.toContain("--sleep\n");
+ const invalid = await run(["cat", "-/"]);
+ expect(invalid).toMatchObject({ code: 1 });
+ expect(invalid.stderr).toContain("cat: invalid option -- '/'");
+ expect(invalid.stderr).toContain("Try 'cat --help' for more information.");
+ for (const command of ["factor", "fmt", "seq", "sleep", "tsort"]) {
+ const result = await run([command, "-/"]);
+ expect(result).toMatchObject({ code: 1 });
+ expect(result.stderr).toContain(`${command}: invalid option -- '/'`);
+ expect(result.stderr).toContain(`Try '${command} --help' for more information.`);
+ }
+ expect(await run(["yes", "--bad-option"])).toMatchObject({ code: 1, stderr: "yes: unrecognized option '--bad-option'\nTry 'yes --help' for more information.\n" });
+ for (const command of ["dir", "ls", "printenv", "sort", "tty", "vdir"]) {
+ const result = await run([command, "-/"]);
+ expect(result).toMatchObject({ code: 2 });
+ expect(result.stderr).toContain(`${command}: invalid option -- '/'`);
+ expect(result.stderr).toContain(`Try '${command} --help' for more information.`);
+ }
+ for (const command of ["chroot", "env", "runcon", "stdbuf", "timeout"]) {
+ const result = await run([command, "-/"]);
+ expect(result).toMatchObject({ code: 125 });
+ expect(result.stderr).toContain(`${command}: invalid option -- '/'`);
+ expect(result.stderr).toContain(`Try '${command} --help' for more information.`);
+ }
+ for (const command of ["coreutils", "date", "dd"]) {
+ const result = await run([command, "-/"]);
+ expect(result).toMatchObject({ code: 1 });
+ expect(result.stderr).toContain(`${command}: invalid option -- '/'`);
+ expect(result.stderr).toContain(`Try '${command} --help' for more information.`);
+ }
+ const nohupInvalid = await run(["nohup", "-/"]);
+ expect(nohupInvalid).toMatchObject({ code: 125 });
+ expect(nohupInvalid.stderr).toContain("nohup: invalid option -- '/'");
+ expect(nohupInvalid.stderr).toContain("Try 'nohup --help' for more information.");
+});
+
+test("GNU upstream test harness exposes selectable tests", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--list"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ const expectedDefaultTests = [
+ "tests/misc/false-status.sh",
+ "tests/misc/printenv.sh",
+ "tests/misc/pathchk.sh",
+ "tests/misc/echo.sh",
+ "tests/misc/invalid-opt.pl",
+ "tests/help/help-version.sh",
+ "tests/help/help-version-getopt.sh",
+ "tests/misc/basename.pl",
+ "tests/misc/dirname.pl",
+ "tests/misc/user.sh",
+ "tests/env/env.sh",
+ "tests/env/env-S.pl",
+ "tests/env/env-S-script.sh",
+ "tests/env/env-null.sh",
+ "tests/env/env-signal-handler.sh",
+ "tests/basenc/basenc.pl",
+ "tests/basenc/base64.pl",
+ "tests/basenc/large-input.sh",
+ "tests/basenc/bounded-memory.sh",
+ "tests/cat/cat-E.sh",
+ "tests/cat/cat-buf.sh",
+ "tests/cat/cat-self.sh",
+ "tests/cat/cat-proc.sh",
+ "tests/cat/splice.sh",
+ "tests/wc/wc.pl",
+ "tests/wc/wc-cpu.sh",
+ "tests/wc/wc-total.sh",
+ "tests/wc/wc-files0.sh",
+ "tests/wc/wc-files0-from.pl",
+ "tests/wc/wc-nbsp.sh",
+ "tests/wc/wc-parallel.sh",
+ "tests/wc/wc-proc.sh",
+ "tests/id/uid.sh",
+ "tests/id/zero.sh",
+ "tests/id/context.sh",
+ "tests/id/no-context.sh",
+ "tests/groups/groups-version.sh",
+ "tests/groups/groups-dash.sh",
+ "tests/groups/groups-process-all.sh",
+ "tests/nproc/nproc-positive.sh",
+ "tests/nproc/nproc-avail.sh",
+ "tests/nproc/nproc-override.sh",
+ "tests/nproc/nproc-quota.sh",
+ "tests/tty/tty.sh",
+ "tests/stty/bad-speed.sh",
+ "tests/stty/stty-invalid.sh",
+ "tests/stty/stty-row-col.sh",
+ "tests/stty/stty.sh",
+ "tests/head/head-c.sh",
+ "tests/head/head-elide-tail.pl",
+ "tests/head/head-write-error.sh",
+ "tests/head/head.pl",
+ "tests/join/join.pl",
+ "tests/join/join-utf8.sh",
+ "tests/misc/comm.pl",
+ "tests/misc/io-errors.sh",
+ "tests/misc/tty-eof.pl",
+ "tests/misc/xstrtol.pl",
+ "tests/cksum/cksum.sh",
+ "tests/cksum/cksum-a.sh",
+ "tests/cksum/cksum-c.sh",
+ "tests/cksum/cksum-base64.pl",
+ "tests/cksum/cksum-base64-untagged.sh",
+ "tests/cksum/cksum-raw.sh",
+ "tests/cksum/sum.pl",
+ "tests/cksum/sum-sysv.sh",
+ "tests/cksum/b2sum.sh",
+ "tests/cksum/md5sum.pl",
+ "tests/cksum/md5sum-bsd.sh",
+ "tests/cksum/md5sum-newline.pl",
+ "tests/cksum/md5sum-parallel.sh",
+ "tests/cksum/sha1sum.pl",
+ "tests/cksum/sha1sum-vec.pl",
+ "tests/cksum/sha224sum.pl",
+ "tests/cksum/sha256sum.pl",
+ "tests/cksum/sha384sum.pl",
+ "tests/cksum/sha512sum.pl",
+ "tests/cksum/cksum-sha3.sh",
+ "tests/cksum/sm3sum.pl",
+ "tests/expr/expr.pl",
+ "tests/expr/expr-multibyte.pl",
+ "tests/test/test-file.sh",
+ "tests/test/test.pl",
+ "tests/test/test-diag.pl",
+ "tests/test/test-N.sh",
+ "tests/seq/seq-io-errors.sh",
+ "tests/seq/seq.pl",
+ "tests/seq/seq-extra-number.sh",
+ "tests/seq/seq-epipe.sh",
+ "tests/seq/seq-locale.sh",
+ "tests/seq/seq-long-double.sh",
+ "tests/seq/seq-precision.sh",
+ "tests/pwd/pwd-option.sh",
+ "tests/pwd/argument.sh",
+ "tests/pwd/pwd-long.sh",
+ "tests/readlink/can-e.sh",
+ "tests/readlink/can-f.sh",
+ "tests/readlink/can-m.sh",
+ "tests/readlink/multi.sh",
+ "tests/readlink/readlink-fp-loop.sh",
+ "tests/readlink/readlink-posix.sh",
+ "tests/readlink/readlink-root.sh",
+ "tests/readlink/rl-1.sh",
+ "tests/misc/realpath.sh",
+ "tests/mktemp/mktemp-misc.sh",
+ "tests/mktemp/mktemp.pl",
+ "tests/mktemp/bad-unicode.sh",
+ "tests/mktemp/write-error.sh",
+ "tests/date/date-debug.sh",
+ "tests/date/date.pl",
+ "tests/date/date-ethiopia.sh",
+ "tests/date/date-iran.sh",
+ "tests/date/date-locale-hour.sh",
+ "tests/date/date-next-dow.pl",
+ "tests/date/percent-percent.sh",
+ "tests/date/reference.sh",
+ "tests/date/resolution.sh",
+ "tests/date/date-sec.sh",
+ "tests/date/date-thailand.sh",
+ "tests/date/date-tz.sh",
+ "tests/truncate/truncate-overflow.sh",
+ "tests/truncate/multiple-files.sh",
+ "tests/truncate/truncate-dangling-symlink.sh",
+ "tests/truncate/truncate-dir-fail.sh",
+ "tests/truncate/truncate-fail-diag.sh",
+ "tests/truncate/truncate-fifo.sh",
+ "tests/truncate/truncate-no-create-missing.sh",
+ "tests/truncate/truncate-parameters.sh",
+ "tests/truncate/truncate-relative.sh",
+ "tests/truncate/truncate-owned-by-other.sh",
+ "tests/tee/append.sh",
+ "tests/tee/tee.sh",
+ "tests/uniq/uniq.pl",
+ "tests/uniq/uniq-perf.sh",
+ "tests/uniq/uniq-collate.sh",
+ "tests/tr/tr.pl",
+ "tests/tr/tr-case-class.sh",
+ "tests/tac/tac.pl",
+ "tests/tac/tac-2-nonseekable.sh",
+ "tests/tac/tac-continue.sh",
+ "tests/tac/tac-locale.sh",
+ "tests/cut/cut.pl",
+ "tests/cut/mb-non-utf8.sh",
+ "tests/cut/bounded-memory.sh",
+ "tests/cut/cut-huge-range.sh",
+ "tests/touch/empty-file.sh",
+ "tests/touch/60-seconds.sh",
+ "tests/touch/dangling-symlink.sh",
+ "tests/touch/dir-1.sh",
+ "tests/touch/fifo.sh",
+ "tests/touch/no-dereference.sh",
+ "tests/touch/no-create-missing.sh",
+ "tests/touch/no-rights.sh",
+ "tests/touch/not-owner.sh",
+ "tests/touch/now-owned-by-other.sh",
+ "tests/touch/obsolescent.sh",
+ "tests/touch/fail-diag.sh",
+ "tests/touch/read-only.sh",
+ "tests/touch/relative.sh",
+ "tests/touch/trailing-slash.sh",
+ "tests/df/total-verify.sh",
+ "tests/df/df-P.sh",
+ "tests/df/df-output.sh",
+ "tests/df/df-symlink.sh",
+ "tests/df/over-mount-device.sh",
+ "tests/df/problematic-chars.sh",
+ "tests/df/total-unprocessed.sh",
+ "tests/df/header.sh",
+ "tests/df/unreadable.sh",
+ "tests/df/sync.sh",
+ "tests/du/exclude.sh",
+ "tests/du/basic.sh",
+ "tests/du/apparent.sh",
+ "tests/du/deref.sh",
+ "tests/du/deref-args.sh",
+ "tests/du/files0-from.pl",
+ "tests/du/files0-from-dir.sh",
+ "tests/du/hard-link.sh",
+ "tests/du/inodes.sh",
+ "tests/du/max-depth.sh",
+ "tests/du/no-deref.sh",
+ "tests/du/slash.sh",
+ "tests/du/trailing-slash.sh",
+ "tests/du/two-args.sh",
+ "tests/du/inacc-dest.sh",
+ "tests/du/inacc-dir.sh",
+ "tests/du/inaccessible-cwd.sh",
+ "tests/du/long-from-unreadable.sh",
+ "tests/du/long-sloop.sh",
+ "tests/du/no-x.sh",
+ "tests/du/one-file-system.sh",
+ "tests/du/restore-wd.sh",
+ "tests/du/bind-mount-dir-cycle-v2.sh",
+ "tests/du/bind-mount-dir-cycle.sh",
+ "tests/du/move-dir-while-traversing.sh",
+ "tests/du/threshold.sh",
+ "tests/cp/same-file.sh",
+ "tests/cp/link.sh",
+ "tests/cp/backup-1.sh",
+ "tests/cp/backup-dir.sh",
+ "tests/cp/backup-is-src.sh",
+ "tests/cp/abuse.sh",
+ "tests/cp/acl.sh",
+ "tests/cp/capability.sh",
+ "tests/cp/attr-existing.sh",
+ "tests/cp/cp-a-selinux.sh",
+ "tests/cp/no-ctx.sh",
+ "tests/cp/cp-HL.sh",
+ "tests/cp/cp-deref.sh",
+ "tests/cp/cp-i.sh",
+ "tests/cp/cp-mv-backup.sh",
+ "tests/cp/cp-mv-enotsup-xattr.sh",
+ "tests/cp/cross-dev-symlink.sh",
+ "tests/cp/deref-slink.sh",
+ "tests/cp/debug.sh",
+ "tests/cp/dir-rm-dest.sh",
+ "tests/cp/dir-slash.sh",
+ "tests/cp/dir-vs-file.sh",
+ "tests/cp/existing-perm-dir.sh",
+ "tests/cp/existing-perm-race.sh",
+ "tests/cp/cp-parents.sh",
+ "tests/cp/fail-perm.sh",
+ "tests/cp/into-self.sh",
+ "tests/cp/keep-directory-symlink.sh",
+ "tests/cp/link-deref.sh",
+ "tests/cp/link-no-deref.sh",
+ "tests/cp/link-preserve.sh",
+ "tests/cp/link-symlink.sh",
+ "tests/cp/file-perm-race.sh",
+ "tests/cp/no-deref-link1.sh",
+ "tests/cp/no-deref-link2.sh",
+ "tests/cp/no-deref-link3.sh",
+ "tests/cp/non-utf8-name.sh",
+ "tests/cp/nfs-removal-race.sh",
+ "tests/cp/parent-perm.sh",
+ "tests/cp/parent-perm-race.sh",
+ "tests/cp/preserve-2.sh",
+ "tests/cp/preserve-link.sh",
+ "tests/cp/preserve-mode.sh",
+ "tests/cp/preserve-gid.sh",
+ "tests/cp/preserve-slink-time.sh",
+ "tests/cp/proc-short-read.sh",
+ "tests/cp/proc-zero-len.sh",
+ "tests/cp/r-vs-symlink.sh",
+ "tests/cp/readonly-dir.sh",
+ "tests/cp/reflink-auto.sh",
+ "tests/cp/reflink-perm.sh",
+ "tests/cp/slink-2-slink.sh",
+ "tests/cp/sparse.sh",
+ "tests/cp/sparse-2.sh",
+ "tests/cp/sparse-extents.sh",
+ "tests/cp/sparse-extents-2.sh",
+ "tests/cp/sparse-perf.sh",
+ "tests/cp/sparse-to-pipe.sh",
+ "tests/cp/special-bits.sh",
+ "tests/cp/special-f.sh",
+ "tests/cp/src-base-dot.sh",
+ "tests/cp/symlink-slash.sh",
+ "tests/cp/thru-dangling.sh",
+ "tests/mv/acl.sh",
+ "tests/mv/update.sh",
+ "tests/mv/i-1.pl",
+ "tests/mv/i-2.sh",
+ "tests/mv/i-3.sh",
+ "tests/mv/i-4.sh",
+ "tests/mv/i-5.sh",
+ "tests/mv/backup-is-src.sh",
+ "tests/mv/childproof.sh",
+ "tests/mv/no-copy.sh",
+ "tests/mv/into-self.sh",
+ "tests/mv/into-self-2.sh",
+ "tests/mv/into-self-3.sh",
+ "tests/mv/into-self-4.sh",
+ "tests/mv/no-target-dir.sh",
+ "tests/mv/backup-dir.sh",
+ "tests/mv/dir2dir.sh",
+ "tests/mv/dup-source.sh",
+ "tests/mv/diag.sh",
+ "tests/mv/dir-file.sh",
+ "tests/mv/force.sh",
+ "tests/mv/hard-link-1.sh",
+ "tests/mv/hard-2.sh",
+ "tests/mv/hard-3.sh",
+ "tests/mv/hard-4.sh",
+ "tests/mv/hardlink-case.sh",
+ "tests/mv/i-link-no.sh",
+ "tests/mv/mv-exchange.sh",
+ "tests/mv/mv-special-1.sh",
+ "tests/mv/mv-special-2.sh",
+ "tests/mv/meta-to-xpart.sh",
+ "tests/mv/sticky-to-xpart.sh",
+ "tests/mv/mv-n.sh",
+ "tests/mv/part-fail.sh",
+ "tests/mv/part-hardlink.sh",
+ "tests/mv/part-rename.sh",
+ "tests/mv/part-symlink.sh",
+ "tests/mv/partition-perm.sh",
+ "tests/mv/perm-1.sh",
+ "tests/mv/symlink-onto-hardlink.sh",
+ "tests/mv/symlink-onto-hardlink-to-self.sh",
+ "tests/mv/to-symlink.sh",
+ "tests/mv/trailing-slash.sh",
+ "tests/mv/atomic.sh",
+ "tests/mv/atomic2.sh",
+ "tests/ln/backup-1.sh",
+ "tests/ln/backup-suffix-traversal.sh",
+ "tests/ln/hard-backup.sh",
+ "tests/ln/hard-to-sym.sh",
+ "tests/ln/misc.sh",
+ "tests/ln/non-utf8-src.sh",
+ "tests/ln/relative.sh",
+ "tests/ln/slash-decorated-nonexistent-dest.sh",
+ "tests/ln/sf-1.sh",
+ "tests/ln/target-1.sh",
+ "tests/rm/dangling-symlink.sh",
+ "tests/rm/d-1.sh",
+ "tests/rm/d-2.sh",
+ "tests/rm/d-3.sh",
+ "tests/rm/dash-hint.sh",
+ "tests/rm/dir-nonrecur.sh",
+ "tests/rm/f-1.sh",
+ "tests/rm/i-never.sh",
+ "tests/rm/i-no-r.sh",
+ "tests/rm/ignorable.sh",
+ "tests/rm/dot-rel.sh",
+ "tests/rm/empty-name.pl",
+ "tests/rm/fail-eacces.sh",
+ "tests/rm/r-1.sh",
+ "tests/rm/r-2.sh",
+ "tests/rm/r-3.sh",
+ "tests/rm/r-4.sh",
+ "tests/rm/rm1.sh",
+ "tests/rm/rm2.sh",
+ "tests/rm/rm3.sh",
+ "tests/rm/rm4.sh",
+ "tests/rm/rm5.sh",
+ "tests/rm/v-slash.sh",
+ "tests/rm/deep-1.sh",
+ "tests/rm/deep-2.sh",
+ "tests/rm/dir-no-w.sh",
+ "tests/rm/empty-inacc.sh",
+ "tests/rm/cycle.sh",
+ "tests/rm/i-1.sh",
+ "tests/rm/isatty.sh",
+ "tests/rm/inaccessible.sh",
+ "tests/rm/interactive-always.sh",
+ "tests/rm/interactive-once.sh",
+ "tests/rm/ir-1.sh",
+ "tests/rm/one-file-system2.sh",
+ "tests/rm/readdir-bug.sh",
+ "tests/rm/rm-readdir-fail.sh",
+ "tests/rm/empty-immutable-skip.sh",
+ "tests/rm/fail-2eperm.sh",
+ "tests/rm/no-give-up.sh",
+ "tests/rm/one-file-system.sh",
+ "tests/rm/read-only.sh",
+ "tests/rm/sunos-1.sh",
+ "tests/rm/unread2.sh",
+ "tests/rm/unread3.sh",
+ "tests/rm/unreadable.pl",
+ "tests/rmdir/ignore.sh",
+ "tests/rmdir/fail-perm.sh",
+ "tests/rmdir/symlink-errors.sh",
+ "tests/rmdir/t-slash.sh",
+ "tests/od/od-N.sh",
+ "tests/od/od.pl",
+ "tests/od/od-j.sh",
+ "tests/od/od-multiple-t.sh",
+ "tests/od/od-endian.sh",
+ "tests/od/od-float.sh",
+ "tests/od/od-x8.sh",
+ "tests/stat/stat-fmt.sh",
+ "tests/stat/stat-printf.pl",
+ "tests/stat/stat-birthtime.sh",
+ "tests/stat/stat-hyphen.sh",
+ "tests/stat/stat-nanoseconds.sh",
+ "tests/stat/stat-slash.sh",
+ "tests/chown/basic.sh",
+ "tests/chown/deref.sh",
+ "tests/chown/separator.sh",
+ "tests/chown/preserve-root.sh",
+ "tests/chgrp/basic.sh",
+ "tests/chgrp/default-no-deref.sh",
+ "tests/chgrp/deref.sh",
+ "tests/chgrp/from.sh",
+ "tests/chgrp/no-x.sh",
+ "tests/chgrp/posix-H.sh",
+ "tests/chgrp/recurse.sh",
+ "tests/chroot/chroot-fail.sh",
+ "tests/chroot/chroot-credentials.sh",
+ "tests/install/install-C.sh",
+ "tests/install/install-C-root.sh",
+ "tests/install/install-C-selinux.sh",
+ "tests/install/install-Z-selinux.sh",
+ "tests/install/basic-1.sh",
+ "tests/install/create-leading.sh",
+ "tests/install/d-slashdot.sh",
+ "tests/install/trap.sh",
+ "tests/install/strip-program.sh",
+ "tests/misc/dircolors.pl",
+ "tests/misc/arch.sh",
+ "tests/chcon/chcon-fail.sh",
+ "tests/misc/coreutils.sh",
+ "tests/misc/mknod.sh",
+ "tests/misc/option-aliases.sh",
+ "tests/pr/pr-tests.pl",
+ "tests/pr/bounded-memory.sh",
+ "tests/ptx/ptx.pl",
+ "tests/ptx/ptx-overrun.sh",
+ "tests/paste/paste.pl",
+ "tests/paste/multi-byte.sh",
+ "tests/expand/expand.pl",
+ "tests/expand/mb.sh",
+ "tests/expand/bounded-memory.sh",
+ "tests/unexpand/unexpand.pl",
+ "tests/unexpand/mb.sh",
+ "tests/unexpand/bounded-memory.sh",
+ "tests/fold/fold.pl",
+ "tests/fold/fold-nbsp.sh",
+ "tests/fold/fold-spaces.sh",
+ "tests/fold/fold-characters.sh",
+ "tests/fold/fold-zero-width.sh",
+ "tests/printf/printf.sh",
+ "tests/printf/printf-hex.sh",
+ "tests/printf/printf-cov.pl",
+ "tests/printf/printf-indexed.sh",
+ "tests/printf/printf-mb.sh",
+ "tests/printf/printf-quote.sh",
+ "tests/printf/printf-surprise.sh",
+ "tests/nl/nl.sh",
+ "tests/nl/multiple-files.sh",
+ "tests/nl/multibyte.sh",
+ "tests/numfmt/numfmt.pl",
+ "tests/numfmt/mb-non-utf8.sh",
+ "tests/shuf/shuf.sh",
+ "tests/fmt/base.pl",
+ "tests/fmt/goal-option.sh",
+ "tests/fmt/long-line.sh",
+ "tests/fmt/non-space.sh",
+ "tests/fmt/width.sh",
+ "tests/head/head-pos.sh",
+ "tests/tail/tail-c.sh",
+ "tests/tail/tail.pl",
+ "tests/tail/basic-seek.sh",
+ "tests/tail/F-headers.sh",
+ "tests/tail/F-vs-missing.sh",
+ "tests/tail/F-vs-rename.sh",
+ "tests/tail/descriptor-vs-rename.sh",
+ "tests/tail/start-middle.sh",
+ "tests/tail/tail-n0f.sh",
+ "tests/tail/truncate.sh",
+ "tests/tail/overlay-headers.sh",
+ "tests/tail/flush-initial.sh",
+ "tests/tail/retry.sh",
+ "tests/tail/symlink.sh",
+ "tests/tail/wait.sh",
+ "tests/tail/assert.sh",
+ "tests/tail/assert-2.sh",
+ "tests/tail/follow-name.sh",
+ "tests/tail/inotify-dir-recreate.sh",
+ "tests/tail/follow-stdin.sh",
+ "tests/tail/pid.sh",
+ "tests/tail/pid-pipe.sh",
+ "tests/tail/pipe-f.sh",
+ "tests/tail/pipe-f2.sh",
+ "tests/tail/proc-ksyms.sh",
+ "tests/tail/tail-sysfs.sh",
+ "tests/tail/append-only.sh",
+ "tests/tail/debug.sh",
+ "tests/tail/end-of-device.sh",
+ "tests/tail/inotify-only-regular.sh",
+ "tests/tail/inotify-rotate-resources.sh",
+ "tests/split/filter.sh",
+ "tests/split/suffix-length.sh",
+ "tests/split/suffix-auto-length.sh",
+ "tests/split/additional-suffix.sh",
+ "tests/split/b-chunk.sh",
+ "tests/split/l-chunk.sh",
+ "tests/split/l-chunk-root.sh",
+ "tests/split/r-chunk.sh",
+ "tests/split/numeric.sh",
+ "tests/split/record-sep.sh",
+ "tests/split/split-io-err.sh",
+ "tests/split/fail.sh",
+ "tests/split/guard-input.sh",
+ "tests/split/non-utf8.sh",
+ "tests/split/line-bytes.sh",
+ "tests/csplit/csplit.sh",
+ "tests/csplit/csplit-1000.sh",
+ "tests/csplit/csplit-suppress-matched.pl",
+ "tests/csplit/csplit-io-err.sh",
+ "tests/shred/shred-exact.sh",
+ "tests/shred/shred-passes.sh",
+ "tests/shred/shred-remove.sh",
+ "tests/shred/shred-size.sh",
+ "tests/dd/misc.sh",
+ "tests/dd/bytes.sh",
+ "tests/dd/conv-case.sh",
+ "tests/dd/stderr.sh",
+ "tests/dd/stats.sh",
+ "tests/dd/ascii.sh",
+ "tests/dd/reblock.sh",
+ "tests/dd/unblock.pl",
+ "tests/dd/unblock-sync.sh",
+ "tests/dd/skip-seek.pl",
+ "tests/dd/skip-seek2.sh",
+ "tests/dd/sparse.sh",
+ "tests/dd/not-rewound.sh",
+ "tests/dd/direct.sh",
+ "tests/dd/nocache.sh",
+ "tests/dd/nocache_eof.sh",
+ "tests/dd/nocache_fail.sh",
+ "tests/dd/fail-ftruncate-fstat.sh",
+ "tests/dd/partial-write.sh",
+ "tests/dd/skip-seek-past-file.sh",
+ "tests/dd/skip-seek-past-dev.sh",
+ "tests/sort/sort.pl",
+ "tests/sort/sort-locale.sh",
+ "tests/sort/sort-debug-warn.sh",
+ "tests/sort/sort-debug-keys.sh",
+ "tests/sort/sort-discrim.sh",
+ "tests/sort/sort-field-limit.sh",
+ "tests/sort/sort-exit-early.sh",
+ "tests/sort/sort-rand.sh",
+ "tests/sort/sort-h-thousands-sep.sh",
+ "tests/sort/sort-compress.sh",
+ "tests/sort/sort-files0-from.pl",
+ "tests/sort/sort-float.sh",
+ "tests/sort/sort-merge.pl",
+ "tests/sort/sort-month.sh",
+ "tests/sort/sort-NaN-infloop.sh",
+ "tests/sort/sort-unique.sh",
+ "tests/sort/sort-version.sh",
+ "tests/timeout/init-parent.sh",
+ "tests/timeout/timeout-blocked.pl",
+ "tests/timeout/timeout-parameters.sh",
+ "tests/timeout/timeout.sh",
+ "tests/timeout/timeout-large-parameters.sh",
+ "tests/timeout/timeout-group.sh",
+ "tests/runcon/runcon-compute.sh",
+ "tests/runcon/runcon-no-reorder.sh",
+ "tests/misc/nohup.sh",
+ "tests/nice/nice-fail.sh",
+ "tests/nice/nice.sh",
+ "tests/misc/stdbuf.sh",
+ "tests/misc/sync.sh",
+ "tests/misc/sleep.sh",
+ "tests/misc/yes.sh",
+ "tests/misc/kill.sh",
+ "tests/misc/time-style.sh",
+ "tests/misc/tsort.pl",
+ "tests/misc/usage_vs_getopt.sh",
+ "tests/misc/getopt_vs_usage.sh",
+ "tests/misc/usage_vs_refs.sh",
+ "tests/misc/warning-errors.sh",
+ "tests/chmod/c-option.sh",
+ "tests/chmod/equal-x.sh",
+ "tests/chmod/equals.sh",
+ "tests/chmod/ignore-symlink.sh",
+ "tests/chmod/no-x.sh",
+ "tests/chmod/octal.sh",
+ "tests/chmod/only-op.sh",
+ "tests/chmod/partial-fail.sh",
+ "tests/chmod/setgid.sh",
+ "tests/chmod/inaccessible.sh",
+ "tests/chmod/silent.sh",
+ "tests/chmod/symlinks.sh",
+ "tests/chmod/thru-dangling.sh",
+ "tests/chmod/umask-x.sh",
+ "tests/chmod/usage.sh",
+ "tests/ls/ls-misc.pl",
+ "tests/ls/ls-time.sh",
+ "tests/ls/recursive.sh",
+ "tests/ls/a-option.sh",
+ "tests/ls/no-arg.sh",
+ "tests/ls/file-type.sh",
+ "tests/ls/classify.sh",
+ "tests/ls/abmon-align.sh",
+ "tests/ls/birthtime.sh",
+ "tests/ls/color-clear-to-eol.sh",
+ "tests/ls/color-dtype-dir.sh",
+ "tests/ls/color-norm.sh",
+ "tests/ls/color-term.sh",
+ "tests/ls/color-ext.sh",
+ "tests/ls/dangle.sh",
+ "tests/ls/infloop.sh",
+ "tests/ls/symlink-slash.sh",
+ "tests/ls/symlink-loop.sh",
+ "tests/ls/zero-option.sh",
+ "tests/ls/time-style-diag.sh",
+ "tests/ls/x-option.sh",
+ "tests/ls/m-option.sh",
+ "tests/ls/block-size.sh",
+ "tests/ls/dired.sh",
+ "tests/ls/follow-slink.sh",
+ "tests/ls/group-dirs.sh",
+ "tests/ls/hex-option.sh",
+ "tests/ls/hyperlink.sh",
+ "tests/ls/inode.sh",
+ "tests/ls/w-option.sh",
+ "tests/ls/multihardlink.sh",
+ "tests/ls/non-utf8-hidden.sh",
+ "tests/ls/quote-align.sh",
+ "tests/ls/quoting-utf8.sh",
+ "tests/ls/acl.sh",
+ "tests/ls/capability.sh",
+ "tests/ls/no-cap.sh",
+ "tests/ls/getxattr-speedup.sh",
+ "tests/ls/nameless-uid.sh",
+ "tests/ls/size-align.sh",
+ "tests/ls/symlink-quote.sh",
+ "tests/ls/slink-acl.sh",
+ "tests/ls/sort-width-option.sh",
+ "tests/ls/readdir-mountpoint-inode.sh",
+ "tests/ls/selinux-segfault.sh",
+ "tests/ls/stat-vs-dirent.sh",
+ "tests/ls/stat-free-color.sh",
+ "tests/ls/stat-free-symlinks.sh",
+ "tests/ls/stat-dtype.sh",
+ "tests/ls/stat-failed.sh",
+ "tests/ls/removed-directory.sh",
+ "tests/ls/root-rel-symlink-color.sh",
+ "tests/ls/rt-1.sh",
+ "tests/fold/multiple-files.sh",
+ "tests/mkdir/p-1.sh",
+ "tests/mkdir/p-2.sh",
+ "tests/mkdir/p-3.sh",
+ "tests/mkdir/p-acl.sh",
+ "tests/mkdir/p-slashdot.sh",
+ "tests/mkdir/p-thru-slink.sh",
+ "tests/mkdir/p-v.sh",
+ "tests/mkdir/parents.sh",
+ "tests/mkdir/perm.sh",
+ "tests/mkdir/special-1.sh",
+ "tests/mkdir/t-slash.sh",
+ "tests/mkdir/restorecon.sh",
+ "tests/mkdir/selinux.sh",
+ "tests/mkdir/writable-under-readonly.sh",
+ "tests/misc/read-errors.sh",
+ "tests/misc/close-stdout.sh",
+ "tests/misc/responsive.sh",
+ "tests/misc/xattr.sh",
+ "tests/misc/selinux.sh",
+ "tests/split/lines.sh",
+ "tests/factor/factor.pl",
+ "tests/factor/factor-parallel.sh",
+ ];
+ expect(stdout).toBe(`${expectedDefaultTests.join("\n")}\n`);
+
+ const allProc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--all", "--list"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await allProc.exited).toBe(0);
+ const allStdout = await new Response(allProc.stdout).text();
+ expect(allStdout).toContain("tests/misc/echo.sh\n");
+ expect(allStdout).toContain("tests/split/fail.sh\n");
+ expect(allStdout).toContain("tests/ls/group-dirs.sh\n");
+ expect(allStdout).toContain("tests/factor/t00.sh\n");
+ expect(allStdout).not.toContain("tests/ls/dtype-color.sh\n");
+
+ const rootProc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--root-tests", "--list"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await rootProc.exited).toBe(0);
+ const rootTests = (await new Response(rootProc.stdout).text()).trim().split("\n");
+ expect(rootTests).toHaveLength(41);
+ expect(rootTests).toContain("tests/chown/basic.sh");
+
+ const nonRootProc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--nonroot-tests", "--list"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await nonRootProc.exited).toBe(0);
+ const nonRootTests = (await new Response(nonRootProc.stdout).text()).trim().split("\n");
+ expect(nonRootTests).toHaveLength(692);
+ expect(nonRootTests).not.toContain("tests/chown/basic.sh");
+});
+
+test("GNU upstream test harness can select a bounded test", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--max-output", "64KiB", "--list", "tests/misc/echo.sh"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ expect(stdout).toBe("tests/misc/echo.sh\n");
+});
+
+test("GNU upstream test harness accepts very expensive opt-in flag", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--very-expensive", "--list"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ expect(stdout).toContain("tests/misc/echo.sh\n");
+ expect(stdout).toContain("tests/stty/stty-pairs.sh\n");
+ expect(stdout).toContain("tests/sort/sort-compress-proc.sh\n");
+ expect(stdout).toContain("tests/od/big-w.sh\n");
+ expect(stdout).toContain("tests/du/8gb.sh\n");
+ expect(stdout).toContain("tests/rm/ext3-perf.sh\n");
+ expect(stdout).toContain("tests/tail/big-4gb.sh\n");
+ expect(stdout).toContain("tests/tail/inotify-hash-abuse2.sh\n");
+ expect(stdout).toContain("tests/tail/inotify-rotate.sh\n");
+ expect(stdout).toContain("tests/sort/sort-benchmark-random.sh\n");
+ expect(stdout).toContain("tests/sort/sort-compress-hang.sh\n");
+ expect(stdout).toContain("tests/cp/perm.sh\n");
+ expect(stdout).toContain("tests/factor/t05.sh\n");
+ expect(stdout).toContain("tests/factor/t40.sh\n");
+});
+
+test("GNU upstream test harness accepts expensive opt-in flag", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--expensive", "--list"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ expect(stdout).toContain("tests/misc/echo.sh\n");
+ expect(stdout).toContain("tests/sort/sort-compress-proc.sh\n");
+ expect(stdout).toContain("tests/du/fd-leak.sh\n");
+ expect(stdout).toContain("tests/mv/leak-fd.sh\n");
+ expect(stdout).toContain("tests/rm/hash.sh\n");
+ expect(stdout).toContain("tests/tail/big-4gb.sh\n");
+ expect(stdout).toContain("tests/tail/inotify-hash-abuse.sh\n");
+ expect(stdout).toContain("tests/tail/inotify-hash-abuse2.sh\n");
+ expect(stdout).toContain("tests/tail/inotify-rotate.sh\n");
+});
+
+test("GNU upstream test harness accepts terminal test mode", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--tty", "--list", "tests/stty/stty-row-col.sh"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ expect(await new Response(proc.stdout).text()).toBe("tests/stty/stty-row-col.sh\n");
+});
+
+test("GNU upstream test harness supplies errno constants", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--max-output", "64KiB", "tests/rm/d-2.sh"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ const stderr = await new Response(proc.stderr).text();
+ expect(stdout).toContain("PASS tests/rm/d-2.sh\n");
+ expect(stderr).not.toContain("FAIL tests/rm/d-2.sh");
+});
+
+test("GNU upstream test harness wrappers preserve option separators", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--max-output", "64KiB", "tests/od/od.pl"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ const stderr = await new Response(proc.stderr).text();
+ expect(stdout).toContain("PASS tests/od/od.pl\n");
+ expect(stderr).not.toContain("invalid-off-4");
+});
+
+test("GNU upstream test harness exposes cksum algorithm help", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--max-output", "128KiB", "tests/cksum/cksum-base64.pl"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ const stderr = await new Response(proc.stderr).text();
+ expect(stdout).toContain("PASS tests/cksum/cksum-base64.pl\n");
+ expect(stderr).not.toContain("not equal to");
+});
+
+test("GNU upstream test harness exposes df output help", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--max-output", "128KiB", "tests/df/df-output.sh"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ const stderr = await new Response(proc.stderr).text();
+ expect(stdout).toContain("PASS tests/df/df-output.sh\n");
+ expect(stderr).not.toContain("Usage: df [OPTION]... [FILE]...");
+});
+
+test("GNU upstream test harness runs observable tail inotify fallback coverage", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--strict", "--max-output", "128KiB", "tests/tail/inotify-dir-recreate.sh", "tests/tail/inotify-race.sh"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ expect(stdout).toContain("PASS tests/tail/inotify-dir-recreate.sh\n");
+ expect(stdout).toContain("PASS tests/tail/inotify-race.sh\n");
+ expect(stdout).toContain("GNU tests: 2 passed, 0 skipped, 0 failed\n");
+});
+
+test("GNU upstream test harness runs timeout process-group coverage", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--strict", "--max-output", "64KiB", "tests/timeout/timeout-group.sh"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ const stderr = await new Response(proc.stderr).text();
+ expect(stdout).toContain("PASS tests/timeout/timeout-group.sh\n");
+ expect(stdout).toContain("GNU tests: 1 passed, 0 skipped, 0 failed\n");
+ expect(stderr).not.toContain("getcwd() failed");
+});
+
+test("GNU upstream test harness suppresses expected deleted-cwd readlink noise", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--strict", "--max-output", "64KiB", "tests/readlink/can-e.sh", "tests/readlink/can-f.sh", "tests/readlink/can-m.sh"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stdout = await new Response(proc.stdout).text();
+ const stderr = await new Response(proc.stderr).text();
+ expect(stdout).toContain("PASS tests/readlink/can-e.sh\n");
+ expect(stdout).toContain("PASS tests/readlink/can-f.sh\n");
+ expect(stdout).toContain("PASS tests/readlink/can-m.sh\n");
+ expect(stdout).toContain("GNU tests: 3 passed, 0 skipped, 0 failed\n");
+ expect(stderr).not.toContain("getcwd() failed");
+});
+
+test("GNU upstream test harness exposes a compiler for helper probes", async () => {
+ const proc = Bun.spawn([process.execPath, "scripts/run-gnu-tests.js", "--strict", "--max-output", "1MiB", "tests/rm/r-root.sh"], {
+ cwd: join(import.meta.dir, ".."),
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(0);
+ const stderr = await new Response(proc.stderr).text();
+ expect(stderr).not.toContain("-Wall: command not found");
+});
+
+test("expand, unexpand, fold and tac transform text", async () => {
+ expect(await run(["expand", "-t", "4"], "a\tb\n")).toMatchObject({ code: 0, stdout: "a b\n" });
+ expect(await run(["expand", "-3"], "a\tb\tc")).toMatchObject({ code: 0, stdout: "a b c" });
+ expect(await run(["expand", "-4", "-9"], "a\tb\tc")).toMatchObject({ code: 0, stdout: "a b c" });
+ expect(await run(["expand", "--tabs=3 6 9"], "a\tb\tc\td\te")).toMatchObject({ code: 0, stdout: "a b c d e" });
+ expect(await run(["expand", "--tabs=1,/5"], "\ta\tb\tc")).toMatchObject({ code: 0, stdout: " a b c" });
+ expect(await run(["expand", "--tabs=1,+5"], "\ta\tb\tc")).toMatchObject({ code: 0, stdout: " a b c" });
+ expect(await run(["expand", "--tabs=+/5"], "\ta\tb")).toMatchObject({ code: 0, stdout: " a b" });
+ expect(await run(["expand", "--tabs=+0"], "a\tb\n")).toMatchObject({ code: 0, stdout: "a b\n" });
+ expect(await run(["expand", "--tabs=1,+0"], "a\tb\n")).toMatchObject({ code: 0, stdout: "a b\n" });
+ expect(await run(["expand", "-t+"], "\ta\tb\n")).toMatchObject({ code: 0, stdout: " a b\n" });
+ expect(await run(["expand", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: expand [OPTION]... [FILE]...\n") });
+ expect(await run(["expand", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Convert tabs in each FILE to spaces, writing to standard output.\n") });
+ expect(await run(["expand", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["expand", "--t=4"], "a\tb\n")).toMatchObject({ code: 0, stdout: "a b\n" });
+ expect(await run(["expand", "--i"], "a\tb\n \tc\n")).toMatchObject({ code: 0, stdout: "a\tb\n c\n" });
+ expect(await run(["expand", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "expand: unrecognized option '--bad'\nTry 'expand --help' for more information.\n" });
+ expect(await run(["expand", "-x", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "expand: invalid option -- 'x'\nTry 'expand --help' for more information.\n" });
+ expect(await run(["expand", "--h=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "expand: option '--help' doesn't allow an argument\nTry 'expand --help' for more information.\n" });
+ expect(await run(["expand", "--tabs", "--help"])).toMatchObject(await systemRun(["expand", "--tabs", "--help"]));
+ expect(await run(["expand", "-t", "bad", "--help"])).toMatchObject(await systemRun(["expand", "-t", "bad", "--help"]));
+ expect(await run(["expand", "-tbad", "--help"])).toMatchObject(await systemRun(["expand", "-tbad", "--help"]));
+ expect(await run(["expand", "--tabs=999999999999999999999999999999", "--help"])).toMatchObject(await systemRun(["expand", "--tabs=999999999999999999999999999999", "--help"]));
+ expect(await run(["expand", "--tabs=0", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: expand [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["expand", "--tabs=1,2", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: expand [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["expand", "--tabs=1", "-t/5"], "\ta\tb\tc")).toMatchObject({ code: 0, stdout: " a b c" });
+ const expandChunkBoundary = Buffer.concat([Buffer.alloc(65535, 0x61), Buffer.from("界\tz\n")]);
+ expect(await run(["expand", "-t4"], expandChunkBoundary)).toMatchObject(await systemRun(["expand", "-t4"], expandChunkBoundary));
+ expect(await run(["expand", "--tab=1,2", "-t+5"], "\ta\tb\tc")).toMatchObject({ code: 0, stdout: " a b c" });
+ expect(await run(["expand", "--tabs=/,/5"], "\ta\tb")).toMatchObject({ code: 0, stdout: " a b" });
+ expect(await run(["expand"], "\bc\td")).toMatchObject({ code: 0, stdout: "\bc d" });
+ await writeFile(join(dir, "expand-in"), "one\ntwo\nthree\n");
+ expect(await run(["expand", "expand-missing-a", "expand-in", "expand-missing-b"])).toMatchObject({ code: 1, stdout: "one\ntwo\nthree\n", stderr: "expand: expand-missing-a: No such file or directory\nexpand: expand-missing-b: No such file or directory\n" });
+ expect(await run(["expand", "missing'expand"])).toMatchObject({ code: 1, stdout: "", stderr: "expand: \"missing'expand\": No such file or directory\n" });
+ expect(await run(["expand", "missing\nexpand"])).toMatchObject({ code: 1, stdout: "", stderr: "expand: 'missing'$'\\n''expand': No such file or directory\n" });
+ await mkdir(join(dir, "expand-dir"));
+ expect(await run(["expand", "expand-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "expand: expand-dir: Is a directory\n" });
+ await mkdir(join(dir, "dir'expand"));
+ expect(await run(["expand", "dir'expand"])).toMatchObject({ code: 1, stdout: "", stderr: "expand: \"dir'expand\": Is a directory\n" });
+ expect((await run(["expand", "--tabs=a"])).stderr).toContain("tab size contains invalid character");
+ expect(await run(["expand", "--tabs=a\nb"])).toMatchObject({ code: 1, stdout: "", stderr: `expand: tab size contains invalid character(s): ${diagnosticQuote("a\\nb")}\n` });
+ expect(await run(["expand", "--tabs=999999999999999999999999999999\n9"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `expand: tab stop is too large ${diagnosticQuote("999999999999999999999999999999")}\nexpand: tab size contains invalid character(s): ${diagnosticQuote("\\n9")}\n`,
+ });
+ expect(await run(["expand", "-t1x"])).toMatchObject(await systemRun(["expand", "-t1x"]));
+ expect(await run(["expand", "-t1,+x"])).toMatchObject(await systemRun(["expand", "-t1,+x"]));
+ expect((await run(["expand", "--tabs=0"])).stderr).toContain("tab size cannot be 0");
+ expect(await run(["expand", "--tabs=3,3"])).toMatchObject({ code: 1 });
+ expect(await run(["expand", "--tabs=/3,6,8"])).toMatchObject({ code: 1 });
+ expect(await run(["expand", "-t/3", "-t/6"])).toMatchObject({ code: 1 });
+ expect(await run(["expand", `-t${"18446744073709551616"}`])).toMatchObject({ code: 1 });
+ expect(await run(["unexpand", "-a", "-t", "4"], "a b\n")).toMatchObject({ code: 0, stdout: "a\tb\n" });
+ expect(await run(["unexpand", "-t", "3"], " a b\n")).toMatchObject({ code: 0, stdout: "\ta\tb\n" });
+ expect(await run(["unexpand", "-t", "3", "--first-only"], " a b\n")).toMatchObject({ code: 0, stdout: "\ta b\n" });
+ expect(await run(["unexpand", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: unexpand [OPTION]... [FILE]...\n") });
+ expect(await run(["unexpand", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Convert blanks in each FILE to tabs, writing to standard output.\n") });
+ expect(await run(["unexpand", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["unexpand", "--t=3"], " a b\n")).toMatchObject({ code: 0, stdout: "\ta\tb\n" });
+ expect(await run(["unexpand", "--f"], " a b\n")).toMatchObject({ code: 0, stdout: " a b\n" });
+ expect(await run(["unexpand", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "unexpand: unrecognized option '--bad'\nTry 'unexpand --help' for more information.\n" });
+ expect(await run(["unexpand", "-x", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "unexpand: invalid option -- 'x'\nTry 'unexpand --help' for more information.\n" });
+ expect(await run(["unexpand", "--h=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "unexpand: option '--help' doesn't allow an argument\nTry 'unexpand --help' for more information.\n" });
+ expect(await run(["unexpand", "--tabs", "--help"])).toMatchObject(await systemRun(["unexpand", "--tabs", "--help"]));
+ expect(await run(["unexpand", "-t", "bad", "--help"])).toMatchObject(await systemRun(["unexpand", "-t", "bad", "--help"]));
+ expect(await run(["unexpand", "-tbad", "--help"])).toMatchObject(await systemRun(["unexpand", "-tbad", "--help"]));
+ expect(await run(["unexpand", "--tabs=999999999999999999999999999999", "--help"])).toMatchObject(await systemRun(["unexpand", "--tabs=999999999999999999999999999999", "--help"]));
+ expect(await run(["unexpand", "--tabs=0", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: unexpand [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["unexpand", "--tabs=1,2", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: unexpand [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["unexpand", "-a", "-3"], "a b c")).toMatchObject({ code: 0, stdout: "a\tb\tc" });
+ expect(await run(["unexpand", "-3"], " a b")).toMatchObject({ code: 0, stdout: "\ta b" });
+ expect(await run(["unexpand", "-a", "-t", "8,9"], "x\t \t y\n")).toMatchObject({ code: 0, stdout: "x\t\t\t y\n" });
+ const unexpandChunkBoundary = Buffer.concat([Buffer.alloc(65535, 0x61), Buffer.from(" b\n")]);
+ expect(await run(["unexpand", "-a", "-t8"], unexpandChunkBoundary)).toMatchObject(await systemRun(["unexpand", "-a", "-t8"], unexpandChunkBoundary));
+ expect(await run(["unexpand", "--tabs=+0"], "a b\n")).toMatchObject({ code: 0, stdout: "a\tb\n" });
+ expect(await run(["unexpand", "--tabs=1,+0"], "a b\n")).toMatchObject({ code: 0, stdout: "a b\n" });
+ expect(await run(["unexpand", "--tabs=a\nb"])).toMatchObject({ code: 1, stdout: "", stderr: `unexpand: tab size contains invalid character(s): ${diagnosticQuote("a\\nb")}\n` });
+ expect(await run(["unexpand", "--tabs=999999999999999999999999999999\n9"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `unexpand: tab stop is too large ${diagnosticQuote("999999999999999999999999999999")}\nunexpand: tab size contains invalid character(s): ${diagnosticQuote("\\n9")}\n`,
+ });
+ expect(await run(["unexpand", "-t+"], "\ta\tb\n")).toMatchObject({ code: 0, stdout: "\ta\tb\n" });
+ expect(await run(["unexpand", "unexpand-missing-a", "expand-in", "unexpand-missing-b"])).toMatchObject({ code: 1, stdout: "one\ntwo\nthree\n", stderr: "unexpand: unexpand-missing-a: No such file or directory\nunexpand: unexpand-missing-b: No such file or directory\n" });
+ expect(await run(["unexpand", "missing'unexpand"])).toMatchObject({ code: 1, stdout: "", stderr: "unexpand: \"missing'unexpand\": No such file or directory\n" });
+ expect(await run(["unexpand", "missing\nunexpand"])).toMatchObject({ code: 1, stdout: "", stderr: "unexpand: 'missing'$'\\n''unexpand': No such file or directory\n" });
+ expect(await run(["expand", "expand-in", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: expand [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["unexpand", "expand-in", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: unexpand [OPTION]... [FILE]...\n"), stderr: "" });
+ await mkdir(join(dir, "unexpand-dir"));
+ expect(await run(["unexpand", "unexpand-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "unexpand: unexpand-dir: Is a directory\n" });
+ await mkdir(join(dir, "dir'unexpand"));
+ expect(await run(["unexpand", "dir'unexpand"])).toMatchObject({ code: 1, stdout: "", stderr: "unexpand: \"dir'unexpand\": Is a directory\n" });
+ expect(await run(["unexpand", "-t"])).toMatchObject({ code: 1, stderr: "unexpand: option requires an argument -- 't'\nTry 'unexpand --help' for more information.\n" });
+ expect(await run(["unexpand", "-t1x"])).toMatchObject(await systemRun(["unexpand", "-t1x"]));
+ expect(await run(["unexpand", "-t1,+x"])).toMatchObject(await systemRun(["unexpand", "-t1,+x"]));
+ expect(await run(["fold", "-w", "4"], "abcdef\n")).toMatchObject({ code: 0, stdout: "abcd\nef\n" });
+ const foldZeroWidth = Buffer.alloc(65537);
+ expect(await run(["fold"], foldZeroWidth)).toMatchObject(await systemRun(["fold"], foldZeroWidth));
+ expect(await run(["fold", "--characters"], foldZeroWidth)).toMatchObject(await systemRun(["fold", "--characters"], foldZeroWidth));
+ expect(await run(["wc", "-L"], "\u200B\n")).toMatchObject({ code: 0, stdout: "0\n" });
+ expect(await run(["fold", "-4"], "abcdef\n")).toMatchObject({ code: 0, stdout: "abcd\nef\n" });
+ expect(await run(["fold", "-b4"], "abcdef\n")).toMatchObject({ code: 0, stdout: "abcd\nef\n" });
+ expect(await run(["fold", "-c4"], "abcdef\n")).toMatchObject({ code: 0, stdout: "abcd\nef\n" });
+ expect(await run(["fold", "-s4"], "abcdef\n")).toMatchObject({ code: 0, stdout: "abcd\nef\n" });
+ expect(await run(["fold", "-w", "+4"], "abcdef\n")).toMatchObject({ code: 0, stdout: "abcd\nef\n" });
+ expect(await run(["fold", "-c", "-w", "3"], "ééx\n")).toMatchObject({ code: 0, stdout: "ééx\n" });
+ expect(await run(["fold", "-b", "-w", "3"], "ééx\n")).toMatchObject({ code: 0, stdout: "é\néx\n" });
+ expect(await run(["fold", "-b", "-c", "-w", "3"], "ééx\n")).toMatchObject({ code: 0, stdout: "ééx\n" });
+ expect(await run(["fold", "-c", "-b", "-w", "3"], "ééx\n")).toMatchObject({ code: 0, stdout: "é\néx\n" });
+ expect(await run(["fold", "--bytes", "--spaces", "-w", "6"], "one two three\n")).toMatchObject({ code: 0, stdout: "one \ntwo \nthree\n" });
+ expect(await run(["fold", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: fold [OPTION]... [FILE]...\n") });
+ expect(await run(["fold", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Wrap input lines in each FILE, writing to standard output.\n") });
+ expect(await run(["fold", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["fold", "expand-in", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: fold [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["fold", "--b", "--w=3"], "ééx\n")).toMatchObject({ code: 0, stdout: "é\néx\n" });
+ expect(await run(["fold", "--c", "--w=3"], "ééx\n")).toMatchObject({ code: 0, stdout: "ééx\n" });
+ expect(await run(["fold", "--s", "--w=4"], "a cd fgh\n")).toMatchObject({ code: 0, stdout: "a \ncd \nfgh\n" });
+ expect(await run(["fold", "--bad", "--help"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "fold: unrecognized option '--bad'\nTry 'fold --help' for more information.\n" });
+ expect(await run(["fold", "-x", "--help"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "fold: invalid option -- 'x'\nTry 'fold --help' for more information.\n" });
+ expect(await run(["fold", "--h=foo"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "fold: option '--help' doesn't allow an argument\nTry 'fold --help' for more information.\n" });
+ expect(await run(["fold", "--b=foo"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "fold: option '--bytes' doesn't allow an argument\nTry 'fold --help' for more information.\n" });
+ expect(await run(["fold", "--width", "--help"], "x")).toMatchObject(await systemRun(["fold", "--width", "--help"], "x"));
+ expect(await run(["fold", "--width=1", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: fold [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["fold", "--width", "bad", "--help"])).toMatchObject(await systemRun(["fold", "--width", "bad", "--help"]));
+ expect(await run(["fold", "-wbad", "--help"])).toMatchObject(await systemRun(["fold", "-wbad", "--help"]));
+ expect(await run(["fold", "-w0", "--help"])).toMatchObject(await systemRun(["fold", "-w0", "--help"]));
+ expect(await run(["fold", "-4x", "--help"])).toMatchObject(await systemRun(["fold", "-4x", "--help"]));
+ expect(await run(["fold", "-bs4x", "--help"])).toMatchObject(await systemRun(["fold", "-bs4x", "--help"]));
+ expect(await run(["fold", "-w", "2", "-s"], "a\t")).toMatchObject({ code: 0, stdout: "a\n\t" });
+ expect(await run(["fold", "-w", "4", "-s"], "a cd fgh\n")).toMatchObject({ code: 0, stdout: "a \ncd \nfgh\n" });
+ expect(await run(["fold", "--spaces", "-w", "10"], "abcdefghijklmnop\u2007qrstuvwxyz\n")).toMatchObject({ code: 0, stdout: "abcdefghij\nklmnop\u2007qrs\ntuvwxyz\n" });
+ expect(await run(["fold", "--spaces", "-w", "10"], "abcdefghijklmnop\u2002qrstuvwxyz\n")).toMatchObject({ code: 0, stdout: "abcdefghij\nklmnop\u2002\nqrstuvwxyz\n" });
+ expect(await run(["fold", "--characters", "-w", "5"], "\uB250\uB250\uB250\n")).toMatchObject({ code: 0, stdout: "\uB250\uB250\uB250\n" });
+ expect(await run(["fold", "-w", "2"], "e\u0301e\u0301x\n")).toMatchObject({ code: 0, stdout: "e\u0301e\u0301\nx\n" });
+ expect(await run(["fold", "-w", "3"], "ab\fcd\n")).toMatchObject({ code: 0, stdout: "ab\f\ncd\n" });
+ expect(await run(["fold", "-w", "0"], "x")).toMatchObject(await systemRun(["fold", "-w", "0"], "x"));
+ expect(await run(["fold", "-w", "+0"], "x")).toMatchObject(await systemRun(["fold", "-w", "+0"], "x"));
+ expect(await run(["fold", "-w", "bad"], "x")).toMatchObject(await systemRun(["fold", "-w", "bad"], "x"));
+ expect(await run(["fold", "-w", "1\n2"], "x")).toMatchObject({ code: 1, stdout: "", stderr: `fold: invalid number of columns: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["fold", "-w", "0\n"], "x")).toMatchObject({ code: 1, stdout: "", stderr: `fold: invalid number of columns: ${diagnosticQuote("0\\n")}\n` });
+ expect(await run(["fold", "-w", "9223372036854775808"], "abc\n")).toMatchObject({ code: 0, stdout: "abc\n" });
+ expect(await run(["fold", "-w", "18446744073709551610"], "x")).toMatchObject(await systemRun(["fold", "-w", "18446744073709551610"], "x"));
+ expect(await run(["fold", "-4x"], "x")).toMatchObject(await systemRun(["fold", "-4x"], "x"));
+ expect(await run(["fold", "-bs4x"], "x")).toMatchObject(await systemRun(["fold", "-bs4x"], "x"));
+ expect(await run(["fold", "missing'fold"])).toMatchObject({ code: 1, stdout: "", stderr: "fold: \"missing'fold\": No such file or directory\n" });
+ expect(await run(["fold", "missing\nfold"])).toMatchObject({ code: 1, stdout: "", stderr: "fold: 'missing'$'\\n''fold': No such file or directory\n" });
+ await mkdir(join(dir, "dir'fold"));
+ expect(await run(["fold", "dir'fold"])).toMatchObject({ code: 1, stdout: "", stderr: "fold: \"dir'fold\": Is a directory\n" });
+ await writeFile(join(dir, "fold-raw"), Uint8Array.of(0xff, 0x61, 0x0a));
+ const foldRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "fold", "-w1", "fold-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "fold-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await foldRaw.exited).toBe(0);
+ expect(await new Response(foldRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "fold-raw-out"))]).toEqual([0xff, 0x0a, 0x61, 0x0a]);
+ const foldRawStdin = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "fold", "-w1"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: Bun.file(join(dir, "fold-raw")),
+ stdout: Bun.file(join(dir, "fold-raw-stdin-out")),
+ stderr: "pipe",
+ });
+ expect(await foldRawStdin.exited).toBe(0);
+ expect(await new Response(foldRawStdin.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "fold-raw-stdin-out"))]).toEqual([0xff, 0x0a, 0x61, 0x0a]);
+ await mkdir(join(dir, "fold-dir"));
+ expect(await run(["fold", "fold-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "fold: fold-dir: Is a directory\n" });
+ expect(await shell(`printf '\\303' | "$BUN" "$BNU" fold | wc -c`)).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["tac"], "one\ntwo\nthree\n")).toMatchObject({ code: 0, stdout: "three\ntwo\none\n" });
+ expect(await run(["tac"], "a\n", { env: { TMPDIR: join(dir, "missing-tac-tmpdir") } })).toMatchObject({ code: 0, stdout: "a\n", stderr: "" });
+ expect(await run(["tac", "-s", ":"], "a:b:c:")).toMatchObject({ code: 0, stdout: "c:b:a:" });
+ expect(await run(["tac", "-s", ""], "a\0b\0")).toMatchObject({ code: 0, stdout: "b\0a\0" });
+ expect(await run(["tac", "-r", "-s", ""], "a\0b\0")).toMatchObject({ code: 1, stderr: "tac: separator cannot be empty\n" });
+ expect(await run(["tac", "-r", "-s", "\\._+"], "1._2.__3.___4._")).toMatchObject({ code: 0, stdout: "4._3.___2.__1._" });
+ expect(await run(["tac", "-r", "-s", "[0-9]+"], "aa11bb222cc")).toMatchObject({ code: 0, stdout: "cc22bb21aa1" });
+ expect(await run(["tac", "-r", "-s", ".."], "aa11bb222cc")).toMatchObject({ code: 0, stdout: "cc22b21baa1" });
+ expect(await run(["tac", "-r", "-s", "("], "a(b(c")).toMatchObject({ code: 0, stdout: "cb(a(" });
+ expect(await run(["tac", "-r", "-s", "(b)"], "a(b)c(b)d")).toMatchObject({ code: 0, stdout: "dc(b)a(b)" });
+ expect(await run(["tac", "-r", "-s", "\\|"], "aaabbbab")).toMatchObject({ code: 0, stdout: "babbbaaa" });
+ expect(await run(["tac", "-r", "-s", "\\(ab\\)"], "xxabyyabzz")).toMatchObject({ code: 0, stdout: "zzyyabxxab" });
+ expect(await run(["tac", "-r", "-s", "\\(a\\|b\\)"], "aaabbbab")).toMatchObject({ code: 0, stdout: "babbbaaa" });
+ expect(await run(["tac", "-r", "-s", "|"], "aa|bb|cc")).toMatchObject({ code: 0, stdout: "ccbb|aa|" });
+ expect(await run(["tac", "-r", "-s", "+"], "aa+bb+cc")).toMatchObject({ code: 0, stdout: "ccbb+aa+" });
+ expect(await run(["tac", "-r", "-s", "?"], "aa?bb?cc")).toMatchObject({ code: 0, stdout: "ccbb?aa?" });
+ expect(await run(["tac", "-r", "-s", "a{2}"], "xxa{2}yya{2}zz")).toMatchObject({ code: 0, stdout: "zzyya{2}xxa{2}" });
+ expect(await run(["tac", "-r", "-s", "["], "abc")).toMatchObject({ code: 1, stdout: "", stderr: "tac: Invalid regular expression\n" });
+ await writeFile(join(dir, "tac-raw-regex"), Uint8Array.of(0xff, 0x78, 0xfe, 0x78));
+ const tacRawRegex = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "tac", "-r", "-s", "x", "tac-raw-regex"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "tac-raw-regex-out")),
+ stderr: "pipe",
+ });
+ expect(await tacRawRegex.exited).toBe(0);
+ expect(await new Response(tacRawRegex.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "tac-raw-regex-out"))]).toEqual([0xfe, 0x78, 0xff, 0x78]);
+ expect(await run(["tac", "-b", "-s", ":"], "a:b:c:")).toMatchObject({ code: 0, stdout: "::c:ba" });
+ expect(await run(["tac", "-b", "-r", "-s", "\\._+"], "._1._2.__3.___4")).toMatchObject({ code: 0, stdout: ".___4.__3._2._1" });
+ expect(await run(["tac", "--before"], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: "\n\nc\nba" });
+ expect(await run(["tac", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tac [OPTION]... [FILE]...\n") });
+ expect(await run(["tac", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Write each FILE to standard output, last line first.\n") });
+ expect(await run(["tac", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["tac", "expand-in", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["tac", "--b"], "a:b:c:")).toMatchObject({ code: 0, stdout: "a:b:c:" });
+ expect(await run(["tac", "--r"], "a:b:c:")).toMatchObject({ code: 0, stdout: "a:b:c:" });
+ expect(await run(["tac", "--se=:"], "a:b:c:")).toMatchObject({ code: 0, stdout: "c:b:a:" });
+ expect(await run(["tac", "--bad", "--help"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "tac: unrecognized option '--bad'\nTry 'tac --help' for more information.\n" });
+ expect(await run(["tac", "-x", "--help"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "tac: invalid option -- 'x'\nTry 'tac --help' for more information.\n" });
+ expect(await run(["tac", "--h=foo"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "tac: option '--help' doesn't allow an argument\nTry 'tac --help' for more information.\n" });
+ expect(await run(["tac", "--b=foo"], "x")).toMatchObject({ code: 1, stdout: "", stderr: "tac: option '--before' doesn't allow an argument\nTry 'tac --help' for more information.\n" });
+ expect(await run(["tac", "--separator", "--help"], "a:b:c:")).toMatchObject({ code: 0, stdout: "a:b:c:", stderr: "" });
+ await writeFile(join(dir, "tac-in"), "one\ntwo\n");
+ expect(await run(["tac", "-", "-"], "one\ntwo\n")).toMatchObject({ code: 0, stdout: "two\none\ntwo\none\n" });
+ expect(await shell(`printf 'one\\ntwo\\n' | "$BUN" "$BNU" tac - -`)).toMatchObject({ code: 0, stdout: "two\none\n", stderr: "" });
+ expect(await shell(`"$BUN" "$BNU" tac - - < tac-in`)).toMatchObject({ code: 0, stdout: "two\none\ntwo\none\n", stderr: "" });
+ expect(await shell(`BNU_STDIN_CLOSED=1 "$BUN" "$BNU" tac - <&-`)).toMatchObject({ code: 1, stdout: "", stderr: "tac: 'standard input': read error: Bad file descriptor\n" });
+ expect(await shell(`BNU_STDIN_CLOSED=1 "$BUN" "$BNU" tac - tac-in <&-`)).toMatchObject({
+ code: 1,
+ stdout: "two\none\n",
+ stderr: "tac: 'standard input': read error: Bad file descriptor\n",
+ });
+ expect(await run(["tac", "tac-in", "-"], "one\ntwo\n")).toMatchObject({ code: 0, stdout: "two\none\ntwo\none\n" });
+ expect(await run(["tac", "-", "tac-in"], "one\ntwo\n")).toMatchObject({ code: 0, stdout: "two\none\ntwo\none\n" });
+ expect(await run(["tac", "tac-missing-a", "tac-in", "tac-missing-b"])).toMatchObject({ code: 1, stdout: "two\none\n", stderr: "tac: failed to open 'tac-missing-a' for reading: No such file or directory\ntac: failed to open 'tac-missing-b' for reading: No such file or directory\n" });
+ expect(await run(["tac", "missing'tac"])).toMatchObject({ code: 1, stdout: "", stderr: "tac: failed to open \"missing'tac\" for reading: No such file or directory\n" });
+ expect(await run(["tac", "missing\ntac"])).toMatchObject({ code: 1, stdout: "", stderr: "tac: failed to open 'missing'$'\\n''tac' for reading: No such file or directory\n" });
+ await mkdir(join(dir, "tac-dir"));
+ expect(await run(["tac", "tac-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "tac: tac-dir: read error: Is a directory\n" });
+ await mkdir(join(dir, "dir'tac"));
+ expect(await run(["tac", "dir'tac"])).toMatchObject({ code: 1, stdout: "", stderr: "tac: \"dir'tac\": read error: Is a directory\n" });
+ await symlink("tac-loop", join(dir, "tac-loop"));
+ expect(await run(["tac", "tac-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "tac: failed to open 'tac-loop' for reading: Too many levels of symbolic links\n" });
+ await symlink("loop'tac", join(dir, "loop'tac"));
+ expect(await run(["tac", "loop'tac"])).toMatchObject({ code: 1, stdout: "", stderr: "tac: failed to open \"loop'tac\" for reading: Too many levels of symbolic links\n" });
+});
+
+test("printf, factor, sum, cksum and shuf basic behavior", async () => {
+ expect(await run(["printf", "%s:%03d\\n", "n", "7"])).toMatchObject({ code: 0, stdout: "n:007\n" });
+ expect(await sampleCommand(["printf", "%20000000f", "0"])).toStartWith(" ".repeat(64));
+ expect(await run(["printf", "%.4X %5.4d %E %.4G\\n", "999", "42", "2", "3"])).toMatchObject({ code: 0, stdout: "03E7 0042 2.000000E+00 3\n" });
+ expect(await run(["printf", "%2$s%1$s\\n", "1", "2"])).toMatchObject({ code: 0, stdout: "21\n" });
+ expect(await run(["printf", "%s %3$s %s\\n", "A", "B", "C", "D"])).toMatchObject({ code: 0, stdout: "A C B\nD \n" });
+ expect(await run(["printf", "%1$*2$.*3$d\\n", "1", "3", "2"])).toMatchObject({ code: 0, stdout: " 01\n" });
+ expect(await run(["printf", "%10$ s", "x"])).toMatchObject(await systemRun(["/usr/bin/printf", "%10$ s", "x"]));
+ expect(await run(["printf", "%-2$s %1$s\\n", "A", "B"])).toMatchObject({ code: 1, stderr: "printf: %-2$: invalid conversion specification\n" });
+ expect(await run(["printf"])).toMatchObject({ code: 1, stderr: "printf: missing operand\nTry 'printf --help' for more information.\n" });
+ expect(await run(["printf", "--"])).toMatchObject({ code: 1, stderr: "printf: missing operand\nTry 'printf --help' for more information.\n" });
+ expect(await run(["printf", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: printf FORMAT [ARGUMENT]...\n or: printf OPTION\n"), stderr: "" });
+ expect(await run(["printf", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["printf", "--bad", "--help"])).toMatchObject({ code: 0, stdout: "--bad", stderr: "printf: warning: ignoring excess arguments, starting with '--help'\n" });
+ expect(await run(["printf", "x", "--help"])).toMatchObject({ code: 0, stdout: "x", stderr: "printf: warning: ignoring excess arguments, starting with '--help'\n" });
+ expect(await run(["printf", "--version=foo"])).toMatchObject({ code: 0, stdout: "--version=foo", stderr: "" });
+ expect(await run(["printf", "B", "1"])).toMatchObject({ code: 0, stdout: "B", stderr: "printf: warning: ignoring excess arguments, starting with '1'\n" });
+ expect(await run(["printf", "%d", "9z"])).toMatchObject({ code: 1, stdout: "9", stderr: `printf: ${diagnosticQuote("9z")}: value not completely converted\n` });
+ expect(await run(["printf", "%d\n", "9\n2"])).toMatchObject({ code: 1, stdout: "9\n", stderr: `printf: ${diagnosticQuote("9\\n2")}: value not completely converted\n` });
+ expect(await run(["printf", "%d\\n", "--"])).toMatchObject({ code: 1, stdout: "0\n", stderr: `printf: ${diagnosticQuote("--")}: expected a numeric value\n` });
+ expect(await run(["printf", "%d\n", "x\ny"])).toMatchObject({ code: 1, stdout: "0\n", stderr: `printf: ${diagnosticQuote("x\\ny")}: expected a numeric value\n` });
+ expect(await run(["printf", "%d %d %x\\n", "010", "0x10", "0x10"])).toMatchObject({ code: 0, stdout: "8 16 10\n" });
+ expect(await run(["printf", "%d\\n", "08"])).toMatchObject({ code: 1, stdout: "0\n", stderr: `printf: ${diagnosticQuote("08")}: value not completely converted\n` });
+ expect(await run(["printf", "%i %d %.1f\\n", "010", "0b10", "0x10"])).toMatchObject({ code: 0, stdout: "8 2 16.0\n" });
+ expect(await run(["printf", "%#x %#X %#o\\n", "10", "10", "10"])).toMatchObject({ code: 0, stdout: "0xa 0XA 012\n" });
+ expect(await run(["printf", "%#08x %#5.3x %#.0x %#.0o %.0d\\n", "10", "10", "0", "0", "0"])).toMatchObject({ code: 0, stdout: "0x00000a 0x00a 0 \n" });
+ expect(await run(["printf", "%f %f\\n", "inf", "nan"])).toMatchObject({ code: 0, stdout: "inf nan\n" });
+ expect(await run(["printf", "%F %E %G\\n", "inf", "nan", "inf"])).toMatchObject({ code: 0, stdout: "INF NAN INF\n" });
+ expect(await run(["printf", "%f %F\\n", "-inf", "-nan"])).toMatchObject({ code: 0, stdout: "-inf -NAN\n" });
+ expect(await run(["printf", "%a %.1a %#a %A\\n", "1", "1.5", "2", "1e20"])).toMatchObject({ code: 0, stdout: "0x8p-3 0xc.0p-3 0x8.p-2 0XA.D78EBC5AC62P+63\n" });
+ expect(await run(["printf", "%.0a %.3a %10a\\n", "1e20", "1e20", "-1"])).toMatchObject({ code: 0, stdout: "0xbp+63 0xa.d79p+63 -0x8p-3\n" });
+ expect(await run(["printf", "%f %.2f %e\\n", "1e20", "1.5e20", "1e20"])).toMatchObject({ code: 0, stdout: "100000000000000000000.000000 150000000000000000000.00 1.000000e+20\n" });
+ expect(await run(["printf", "%g %g %G\\n", "1e6", "1e-9", "1e6"])).toMatchObject({ code: 0, stdout: "1e+06 1e-09 1E+06\n" });
+ expect(await run(["printf", "%e %.2e %g %.3g %E %G\\n", "1e309", "9.999999e309", "12.34e309", "9.999999e309", "-1.5e309", "1e309"])).toMatchObject({
+ code: 0,
+ stdout: "1.000000e+309 1.00e+310 1.234e+310 1e+310 -1.500000E+309 1E+309\n",
+ });
+ expect(await run(["printf", "%d\\n", "9223372036854775808"])).toMatchObject(await systemRun(["printf", "%d\\n", "9223372036854775808"]));
+ expect(await run(["printf", "%u\\n", "18446744073709551616"])).toMatchObject(await systemRun(["printf", "%u\\n", "18446744073709551616"]));
+ expect(await run(["printf", "%u %x %o\\n", "-1", "-1", "-1"])).toMatchObject({ code: 0, stdout: "18446744073709551615 ffffffffffffffff 1777777777777777777777\n" });
+ expect(await run(["printf", "\\u263A\\n"])).toMatchObject({ code: 0, stdout: "☺\n" });
+ expect(await run(["printf", "%b\\n", "\\U0001F600"])).toMatchObject({ code: 0, stdout: "😀\n" });
+ expect(await run(["printf", "--", "foo\\n"])).toMatchObject({ code: 0, stdout: "foo\n" });
+ expect(await run(["printf", "1 %*sy\\n", "-3", "x"])).toMatchObject({ code: 0, stdout: "1 x y\n" });
+ expect(await run(["printf", "9 %*dx\\n", "-2", "0"])).toMatchObject({ code: 0, stdout: "9 0 x\n" });
+ expect(await run(["printf", "11 %*c\\n", "2", "x"])).toMatchObject({ code: 0, stdout: "11 x\n" });
+ expect(await run(["printf", "%c|%c|%c\\n", "abc", "", "xyz"])).toMatchObject({ code: 0, stdout: "a|\0|x\n" });
+ expect(await run(["printf", "12 %*s\\n", "", "empty width"])).toMatchObject({ code: 1, stdout: "12 empty width\n", stderr: `printf: ${diagnosticQuote("")}: expected a numeric value\n` });
+ expect(await run(["printf", "13 %*s\\n", "9z", "partial width"])).toMatchObject({ code: 1, stdout: "13 partial width\n", stderr: `printf: ${diagnosticQuote("9z")}: value not completely converted\n` });
+ expect(await run(["printf", "14 %.*sx\\n", "", "empty precision"])).toMatchObject({ code: 1, stdout: "14 x\n", stderr: `printf: ${diagnosticQuote("")}: expected a numeric value\n` });
+ expect(await run(["printf", "%d\\n", "\"a", "\"a\"", "\"", "a"])).toMatchObject({
+ code: 1,
+ stdout: "97\n97\n0\n0\n",
+ stderr: `printf: warning: \": character(s) following character constant have been ignored\nprintf: ${diagnosticQuote("\"")}: expected a numeric value\nprintf: ${diagnosticQuote("a")}: expected a numeric value\n`,
+ });
+ expect(await run(["printf", "a\\cb\\n"])).toMatchObject({ code: 0, stdout: "a" });
+ expect(await run(["printf", "%bX\\n%s\\n", "a\\cb", "later"])).toMatchObject({ code: 0, stdout: "a" });
+ expect(await run(["printf", "%q\\n", "simple", "a b", "a'b"])).toMatchObject({ code: 0, stdout: "simple\n'a b'\n\"a'b\"\n" });
+ expect(await run(["printf", "%2$q %1$q\\n", "a b", "c d"])).toMatchObject({ code: 0, stdout: "'c d' 'a b'\n" });
+ expect(await run(["printf", "%10q\\n", "a b"])).toMatchObject({ code: 1, stderr: "printf: %10q: invalid conversion specification\n" });
+ expect(await run(["printf", "%.3q\\n", "a b"])).toMatchObject({ code: 1, stderr: "printf: %.3q: invalid conversion specification\n" });
+ expect(await run(["printf", "%#q\\n", "a b"])).toMatchObject({ code: 1, stderr: "printf: %#q: invalid conversion specification\n" });
+ expect(await run(["printf", "%1$10q\\n", "a b"])).toMatchObject({ code: 1, stderr: "printf: %1$10q: invalid conversion specification\n" });
+ expect(await run(["printf", "%(bad)T", "0"])).toMatchObject({ code: 1, stderr: "printf: %(: invalid conversion specification\n" });
+ expect(await run(["printf", "%q\\n", "", "'", "~a", "a~", "a\r", "\x01'\x01"])).toMatchObject({ code: 0, stdout: "''\n\"'\"\n'~a'\na~\n'a'$'\\r'\n''$'\\001'\\'''$'\\001'\n" });
+ expect(await run(["printf", "%q\\n", "áḃç"], "", { env: { LC_ALL: "C" } })).toMatchObject({ code: 0, stdout: "''$'\\303\\241\\341\\270\\203\\303\\247'\n" });
+ const rawPrintf = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "printf", "\\377"], { cwd: dir, stdout: "pipe", stderr: "pipe" });
+ expect(await rawPrintf.exited).toBe(0);
+ expect(new Uint8Array(await new Response(rawPrintf.stdout).arrayBuffer())).toEqual(Uint8Array.of(0xff));
+ expect(await run(["factor", "84"])).toMatchObject({ code: 0, stdout: "84: 2 2 3 7\n" });
+ expect(await run(["factor", "0", "1"])).toMatchObject({ code: 0, stdout: "0:\n1:\n" });
+ expect(await run(["factor", "00", "01", "00012"])).toMatchObject({ code: 0, stdout: "0:\n1:\n12: 2 2 3\n" });
+ expect(await run(["factor", "--exponents", "84"])).toMatchObject({ code: 0, stdout: "84: 2^2 3 7\n" });
+ expect(await run(["factor", "--e", "84"])).toMatchObject({ code: 0, stdout: "84: 2^2 3 7\n" });
+ expect(await run(["factor", "--ex", "84"])).toMatchObject({ code: 0, stdout: "84: 2^2 3 7\n" });
+ expect(await run(["factor", "12\n3"])).toMatchObject(await systemRun(["/usr/bin/factor", "12\n3"]));
+ expect(await run(["factor", "12\t3"])).toMatchObject(await systemRun(["/usr/bin/factor", "12\t3"]));
+ expect(await run(["factor", "12 3"])).toMatchObject(await systemRun(["/usr/bin/factor", "12 3"]));
+ expect(await run(["factor", ""])).toMatchObject(await systemRun(["/usr/bin/factor", ""]));
+ const rawFactor = Bun.spawn(["/bin/sh", "-c", `printf '12\\377\\n' | LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} factor 2>factor-raw-err`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await rawFactor.exited).toBe(1);
+ expect(await new Response(rawFactor.stdout).text()).toBe("");
+ expect([...await readFile(join(dir, "factor-raw-err"))]).toEqual([0x66, 0x61, 0x63, 0x74, 0x6f, 0x72, 0x3a, 0x20, 0x27, 0x31, 0x32, 0x5c, 0x33, 0x37, 0x37, 0x27, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x61, 0x20, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x20, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x76, 0x65, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x0a]);
+ expect(await run(["factor", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: factor [OPTION] [NUMBER]...\n") });
+ expect(await run(["factor", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["factor", "--e=1", "84"])).toMatchObject({ code: 1, stderr: "factor: option '--exponents' doesn't allow an argument\nTry 'factor --help' for more information.\n" });
+ expect(await run(["factor", "--bad", "--help"])).toMatchObject({ code: 1, stderr: "factor: unrecognized option '--bad'\nTry 'factor --help' for more information.\n" });
+ expect(await run(["factor", "-x", "--help"])).toMatchObject({ code: 1, stderr: "factor: invalid option -- 'x'\nTry 'factor --help' for more information.\n" });
+ expect(await run(["factor", "-h"], "84 13\n")).toMatchObject({ code: 0, stdout: "84: 2^2 3 7\n13: 13\n" });
+ expect(await run(["factor"], "2147483647 0 00012\n")).toMatchObject({ code: 0, stdout: "2147483647: 2147483647\n0:\n12: 2 2 3\n" });
+ const denseFactorInput = Array.from({ length: 10001 }, (_, n) => String(n)).join("\n") + "\n";
+ const denseFactor = await run(["factor"], denseFactorInput);
+ expect(denseFactor.code).toBe(0);
+ expect(createHash("sha1").update(denseFactor.stdout).digest("hex")).toBe("8ebfb72a67903f0fd0975abf405c85794f175f4a");
+ // Cross the streaming flush boundary used by upstream factor/t00 without
+ // retaining its output or allowing a regression to exhaust the host.
+ expect(await shell(`seq 0 400000 | /usr/bin/prlimit --as=3221225472 -- "$BUN" "$BNU" factor | sha1sum`)).toMatchObject({
+ code: 0,
+ stdout: "5f3d756b7a80162c16502f44d8531caecd6c561f -\n",
+ });
+ expect(await shell(`seq 100000 | sed '/[24680]$/d' | "$BUN" "$BNU" split -nr/4 --filter='"$BUN" "$BNU" factor' | sed 's/.*: //; / /d' | wc -l`)).toMatchObject({ code: 0, stdout: "9592\n", stderr: "" });
+ const range64FactorInput = Array.from({ length: 1000 }, (_, i) => String(18446744073708551616n + BigInt(i))).join("\n") + "\n";
+ const range64Factor = await run(["factor"], range64FactorInput);
+ expect(range64Factor.code).toBe(0);
+ expect(createHash("sha1").update(range64Factor.stdout).digest("hex")).toBe("a63e5b34378674902ea47fcd7426f455696c859e");
+ const parallelRange64FactorInput = Array.from({ length: 4000 }, (_, i) => String(18446744073708551616n + BigInt(i))).join("\n") + "\n";
+ const parallelRange64Factor = await run(["factor"], parallelRange64FactorInput);
+ expect(parallelRange64Factor.code).toBe(0);
+ expect(createHash("sha1").update(parallelRange64Factor.stdout).digest("hex")).toBe("7f951fe41ee9d28645484a61e19d2f088c6e4951");
+ expect(await run(["factor", "+7"])).toMatchObject({ code: 0, stdout: "7: 7\n" });
+ expect(await run(["factor", "a", "4"])).toMatchObject(await systemRun(["/usr/bin/factor", "a", "4"]));
+ expect(await run(["factor", "--", "-1"])).toMatchObject(await systemRun(["/usr/bin/factor", "--", "-1"]));
+ await mkdir(join(dir, "stdin-read-dir"));
+ expect(await shell(`"$BUN" "$BNU" factor < stdin-read-dir`)).toMatchObject({ code: 1, stdout: "", stderr: "factor: error reading input: Is a directory\n" });
+ expect(await shell(`"$BUN" "$BNU" numfmt < stdin-read-dir`)).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: error reading input: Is a directory\n" });
+ expect(await shell(`"$BUN" "$BNU" tr A B < stdin-read-dir`)).toMatchObject({ code: 1, stdout: "", stderr: "tr: read error: Is a directory\n" });
+ expect(await shell(`"$BUN" "$BNU" tee tee-read-dir-out < stdin-read-dir`)).toMatchObject({ code: 1, stdout: "", stderr: "tee: read error: Is a directory\n" });
+ expect(await run(["factor", "170141183460469225450570946617781744489"])).toMatchObject({
+ code: 0,
+ stdout: "170141183460469225450570946617781744489: 9223372036854775421 18446744073709551709\n",
+ });
+ expect(await run(["factor", "170141183460469229545748130981302223887"])).toMatchObject({
+ code: 0,
+ stdout: "170141183460469229545748130981302223887: 9223372036854775643 18446744073709551709\n",
+ });
+ expect(await run(["factor", "+170141183460469231731687303715884105729"])).toMatchObject({
+ code: 0,
+ stdout: "170141183460469231731687303715884105729: 3 56713727820156410577229101238628035243\n",
+ });
+ expect(await run(["sum"], "abc")).toMatchObject({ code: 0, stdout: "16556 1\n" });
+ expect(await run(["sum", "-"], "abc")).toMatchObject({ code: 0, stdout: "16556 1 -\n" });
+ expect(await run(["sum", "-r"], "abc\n")).toMatchObject({ code: 0, stdout: "08288 1\n" });
+ expect(await run(["sum", "-s"], "abc")).toMatchObject({ code: 0, stdout: "294 1\n" });
+ expect(await run(["sum", "--s"], "abc")).toMatchObject({ code: 0, stdout: "294 1\n" });
+ expect(await run(["sum", "--sy"], "abc")).toMatchObject({ code: 0, stdout: "294 1\n" });
+ const sumHelp = await run(["sum", "--h"]);
+ const sumHelpStdout = sumHelp.stdout;
+ expect(sumHelp).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: sum [OPTION]... [FILE]...\n") });
+ expect(sumHelpStdout).toContain("Print or check BSD (16-bit) checksums.\nLegacy interface to the cksum utility.\n");
+ expect(sumHelpStdout).toContain("With no FILE, or when FILE is -, read standard input.\n");
+ expect(sumHelpStdout).toContain(" use BSD sum algorithm (the default), use 1K blocks\n");
+ expect(sumHelpStdout).toContain(" use System V sum algorithm, use 512 bytes blocks\n");
+ expect(await run(["sum", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["sum", "--s=1"], "abc")).toMatchObject({ code: 1, stderr: "sum: option '--sysv' doesn't allow an argument\nTry 'sum --help' for more information.\n" });
+ expect(await run(["sum", "--bad", "--help"], "abc")).toMatchObject({ code: 1, stderr: "sum: unrecognized option '--bad'\nTry 'sum --help' for more information.\n" });
+ expect(await run(["sum", "-x", "--help"], "abc")).toMatchObject({ code: 1, stderr: "sum: invalid option -- 'x'\nTry 'sum --help' for more information.\n" });
+ expect(await run(["sum", "-s", "-"], "abc")).toMatchObject({ code: 0, stdout: "294 1 -\n" });
+ expect(await run(["sum", "-rs"], "abc\n")).toMatchObject({ code: 0, stdout: "304 1\n" });
+ expect(await run(["sum", "-sr"], "abc\n")).toMatchObject({ code: 0, stdout: "08288 1\n" });
+ expect(await run(["sum", "-r", "--sysv"], "abc\n")).toMatchObject({ code: 0, stdout: "304 1\n" });
+ expect(await run(["sum", "--sysv", "-r"], "abc\n")).toMatchObject({ code: 0, stdout: "08288 1\n" });
+ await writeFile(join(dir, "sum-ok"), "abc");
+ expect(await run(["sum", "sum-ok", "-s"])).toMatchObject({ code: 0, stdout: "294 1 sum-ok\n" });
+ expect(await run(["sum", "-s", "sum-ok", "-r"])).toMatchObject({ code: 0, stdout: "16556 1 sum-ok\n" });
+ expect(await run(["sum", "sum-ok", "--sysv"])).toMatchObject({ code: 0, stdout: "294 1 sum-ok\n" });
+ expect(await run(["sum", "--", "sum-ok", "-s"])).toMatchObject({ code: 1, stdout: "16556 1 sum-ok\n", stderr: "sum: -s: No such file or directory\n" });
+ expect(await run(["sum", "sum-ok", "-s"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stdout: "16556 1 sum-ok\n", stderr: "sum: -s: No such file or directory\n" });
+ expect(await run(["sum", "sum-missing-a", "sum-ok", "sum-missing-b"])).toMatchObject({
+ code: 1,
+ stdout: "16556 1 sum-ok\n",
+ stderr: "sum: sum-missing-a: No such file or directory\nsum: sum-missing-b: No such file or directory\n",
+ });
+ expect(await run(["sum", "missing'sum"])).toMatchObject({ code: 1, stdout: "", stderr: "sum: \"missing'sum\": No such file or directory\n" });
+ expect(await run(["sum", "missing\nsum"])).toMatchObject({ code: 1, stdout: "", stderr: "sum: 'missing'$'\\n''sum': No such file or directory\n" });
+ await mkdir(join(dir, "dir'sum"));
+ expect(await run(["sum", "dir'sum"])).toMatchObject({ code: 1, stdout: "", stderr: "sum: \"dir'sum\": Is a directory\n" });
+ await symlink("loop'sum", join(dir, "loop'sum"));
+ expect(await run(["sum", "loop'sum"])).toMatchObject({ code: 1, stdout: "", stderr: "sum: \"loop'sum\": Too many levels of symbolic links\n" });
+ expect(await run(["cksum"], "abc")).toMatchObject({ code: 0, stdout: "1219131554 3\n" });
+ expect(await run(["cksum", "-"], "abc")).toMatchObject({ code: 0, stdout: "1219131554 3 -\n" });
+ const shuffled = await run(["shuf", "-i", "1-3", "-n", "2"]);
+ expect(shuffled.code).toBe(0);
+ expect(shuffled.stdout.trim().split("\n")).toHaveLength(2);
+ expect(await run(["shuf", "-n", "+1"], "a\nb\n")).toMatchObject({ code: 0 });
+ expect(await run(["shuf", "-n", " 1"], "a\nb\n")).toMatchObject({ code: 0 });
+ expect(await run(["shuf", "-n", "999999999999999999999999"], "a\nb\n")).toMatchObject({ code: 0 });
+ expect(await run(["shuf", "-i", "+1-+3", "-n", "+1"])).toMatchObject({ code: 0 });
+ expect(await run(["shuf", "-n", "1\n2"], "a\nb\n")).toMatchObject(await systemRun(["shuf", "-n", "1\n2"], "a\nb\n"));
+ expect(await run(["shuf", "-i", "1\t-3"])).toMatchObject(await systemRun(["shuf", "-i", "1\t-3"]));
+ expect(await run(["shuf", "--input-range="], "a\nb\n")).toMatchObject({ code: 1, stdout: "", stderr: "shuf: invalid input range: ‘’\n" });
+ expect(await run(["shuf", "-e", "-r", "-n", "3", "x"])).toMatchObject({ code: 0, stdout: "x\nx\nx\n" });
+ expect(await run(["shuf", "--repeat", "--head-count=0", "-e"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["shuf", "--input-range=3-1"])).toMatchObject(await systemRun(["shuf", "--input-range=3-1"]));
+ const zeroRandom = await shell(`printf 'a\\nb\\nc\\n' | timeout 2 "$BUN" "$BNU" shuf --random-source=/dev/zero --head-count=2`);
+ expect(zeroRandom).toMatchObject({ code: 0, stderr: "" });
+ expect(zeroRandom.stdout.trim().split("\n")).toHaveLength(2);
+ expect(await run(["shuf", "--h"])).toMatchObject({
+ code: 1,
+ stderr: "shuf: option '--h' is ambiguous; possibilities: '--head-count' '--help'\nTry 'shuf --help' for more information.\n",
+ });
+ expect(await run(["shuf", "--he=1"], "a\nb\n")).toMatchObject({
+ code: 1,
+ stderr: "shuf: option '--he=1' is ambiguous; possibilities: '--head-count' '--help'\nTry 'shuf --help' for more information.\n",
+ });
+ expect(await run(["shuf", "--hea=1"], "a\nb\n")).toMatchObject({ code: 0 });
+ expect(await run(["shuf", "--e", "a"])).toMatchObject({ code: 0, stdout: "a\n" });
+ expect(await run(["shuf", "--ec=foo", "a"])).toMatchObject({
+ code: 1,
+ stderr: "shuf: option '--echo' doesn't allow an argument\nTry 'shuf --help' for more information.\n",
+ });
+ expect(await run(["shuf", "--r", "--n=3", "-e", "x"])).toMatchObject({
+ code: 1,
+ stderr: "shuf: option '--r' is ambiguous; possibilities: '--random-source' '--repeat'\nTry 'shuf --help' for more information.\n",
+ });
+ expect(await run(["shuf", "--n=1"], "a\n")).toMatchObject({
+ code: 1,
+ stderr: "shuf: unrecognized option '--n=1'\nTry 'shuf --help' for more information.\n",
+ });
+ expect(await run(["shuf", "--bad", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "shuf: unrecognized option '--bad'\nTry 'shuf --help' for more information.\n",
+ });
+ expect(await run(["shuf", "--version=foo"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "shuf: option '--version' doesn't allow an argument\nTry 'shuf --help' for more information.\n",
+ });
+ expect(await run(["shuf", "--help=1", "--version"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "shuf: option '--help' doesn't allow an argument\nTry 'shuf --help' for more information.\n",
+ });
+ expect(await run(["shuf", "--head-count", "--help"], "a\n")).toMatchObject(await systemRun(["shuf", "--head-count", "--help"], "a\n"));
+ expect(await run(["shuf", "--head-count=1", "--help"])).toMatchObject({
+ code: 0,
+ stdout: expect.stringContaining("Usage: shuf [OPTION]... [FILE]\n or: shuf -e [OPTION]... [ARG]...\n or: shuf -i LO-HI [OPTION]...\n"),
+ });
+ expect(await run(["shuf", "--head-count=bad", "--help"], "a\n")).toMatchObject(await systemRun(["shuf", "--head-count=bad", "--help"], "a\n"));
+ expect(await run(["shuf", "--head-count=", "--help"], "a\n")).toMatchObject(await systemRun(["shuf", "--head-count=", "--help"], "a\n"));
+ expect(await run(["shuf", "--input-range=bad", "--help"])).toMatchObject(await systemRun(["shuf", "--input-range=bad", "--help"]));
+ expect(await run(["shuf", "--input-range=", "--help"])).toMatchObject(await systemRun(["shuf", "--input-range=", "--help"]));
+ expect(await run(["shuf", "--input-range", "bad", "--help"])).toMatchObject(await systemRun(["shuf", "--input-range", "bad", "--help"]));
+ expect(await run(["shuf", "-i", "bad", "--help"])).toMatchObject(await systemRun(["shuf", "-i", "bad", "--help"]));
+ await writeFile(join(dir, "shuf-meta"), "a\nb\n");
+ expect(await run(["shuf", "shuf-meta", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: shuf [OPTION]... [FILE]\n"), stderr: "" });
+ const nul = await run(["shuf", "-z", "-n", "2"], "a\0b\0c\0");
+ expect(nul.code).toBe(0);
+ expect(nul.stdout.endsWith("\0")).toBe(true);
+ expect(nul.stdout.split("\0").filter(Boolean)).toHaveLength(2);
+ await writeFile(join(dir, "shuf-raw"), Uint8Array.of(0xff, 0x0a));
+ const shufRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "shuf", "shuf-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "shuf-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await shufRaw.exited).toBe(0);
+ expect(await new Response(shufRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "shuf-raw-out"))]).toEqual([0xff, 0x0a]);
+ await writeFile(join(dir, "shuf-raw0"), Uint8Array.of(0xff, 0x00));
+ const shufRaw0 = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "shuf", "-z", "shuf-raw0"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "shuf-raw0-out")),
+ stderr: "pipe",
+ });
+ expect(await shufRaw0.exited).toBe(0);
+ expect(await new Response(shufRaw0.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "shuf-raw0-out"))]).toEqual([0xff, 0x00]);
+ await writeFile(join(dir, "random"), new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]));
+ expect(await run(["shuf", "--random-source=random", "-i", "1-3"])).toMatchObject({ code: 0, stdout: "1\n2\n3\n" });
+ await writeFile(join(dir, "shuf-abc-random"), "a\nb\nc\n");
+ expect(await run(["shuf", "--random-source=shuf-abc-random", "-i", "1-3"])).toMatchObject({ code: 0, stdout: "2\n1\n3\n" });
+ expect(await run(["shuf", "--random-source=shuf-abc-random", "-r", "-n", "5", "-i", "1-2"])).toMatchObject({ code: 0, stdout: "2\n1\n1\n1\n1\n" });
+ await writeFile(join(dir, "shuf-empty-random"), "");
+ expect(await run(["shuf", "-n", "0", "--random-source=shuf-empty-random", "shuf-meta"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["shuf", "-n", "1", "--random-source=shuf-empty-random", "shuf-meta"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: shuf-empty-random: end of file\n" });
+ expect(await run(["shuf", "--random-source=random", "--random-source=random", "-e", "a"])).toMatchObject({ code: 0, stdout: "a\n" });
+ expect(await run(["shuf", "--random-source=random", "--random-source=other-random", "-e", "a"])).toMatchObject({ code: 1, stderr: "shuf: multiple random sources specified\n" });
+ expect(await run(["shuf", "--random-source=", "shuf-meta"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: '': No such file or directory\n" });
+ expect(await run(["shuf", "--random-source=shuf-random-missing", "shuf-meta"])).toMatchObject(await systemRun(["shuf", "--random-source=shuf-random-missing", "shuf-meta"]));
+ expect(await run(["shuf", "--random-source=missing'shuf-rs", "shuf-meta"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: \"missing'shuf-rs\": No such file or directory\n" });
+ expect(await run(["shuf", "--random-source=missing\nshuf-rs", "shuf-meta"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: 'missing'$'\\n''shuf-rs': No such file or directory\n" });
+ await writeFile(join(dir, "shuf-a"), "a\n");
+ await writeFile(join(dir, "shuf-b"), "b\n");
+ await mkdir(join(dir, "shuf-dir"));
+ expect(await run(["shuf", "shuf-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: read error: Is a directory\n" });
+ expect(await run(["shuf", "missing'shuf"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: \"missing'shuf\": No such file or directory\n" });
+ expect(await run(["shuf", "missing\nshuf"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: 'missing'$'\\n''shuf': No such file or directory\n" });
+ await writeFile(join(dir, "shuf-unreadable"), "x\n");
+ await chmod(join(dir, "shuf-unreadable"), 0);
+ expect(await run(["shuf", "shuf-unreadable"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: shuf-unreadable: Permission denied\n" });
+ await symlink("shuf-loop", join(dir, "shuf-loop"));
+ expect(await run(["shuf", "shuf-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: shuf-loop: Too many levels of symbolic links\n" });
+ await symlink("loop'shuf", join(dir, "loop'shuf"));
+ expect(await run(["shuf", "loop'shuf"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: \"loop'shuf\": Too many levels of symbolic links\n" });
+ await mkdir(join(dir, "dir'shuf-rs"));
+ expect(await run(["shuf", "--random-source=dir'shuf-rs", "shuf-meta"])).toMatchObject({ code: 1, stdout: "", stderr: `shuf: ${diagnosticQuote("dir'shuf-rs")}: read error: Is a directory\n` });
+ await symlink("loop'shuf-rs", join(dir, "loop'shuf-rs"));
+ expect(await run(["shuf", "--random-source=loop'shuf-rs", "shuf-meta"])).toMatchObject({ code: 1, stdout: "", stderr: "shuf: \"loop'shuf-rs\": Too many levels of symbolic links\n" });
+ expect(await run(["shuf", "shuf-a", "shuf-b"])).toMatchObject(await systemRun(["shuf", "shuf-a", "shuf-b"]));
+ expect(await run(["shuf", "shuf-a", "extra\narg"])).toMatchObject(await systemRun(["shuf", "shuf-a", "extra\narg"]));
+ expect(await run(["shuf", "-i", "1-2", "extra"])).toMatchObject(await systemRun(["shuf", "-i", "1-2", "extra"]));
+ expect(await run(["shuf", "-i", "1-2", "extra\narg"])).toMatchObject(await systemRun(["shuf", "-i", "1-2", "extra\narg"]));
+ expect(await run(["shuf", "-n", "-1"], "a\n")).toMatchObject(await systemRun(["shuf", "-n", "-1"], "a\n"));
+ expect(await run(["shuf", "-n", "1x"], "a\n")).toMatchObject(await systemRun(["shuf", "-n", "1x"], "a\n"));
+ expect(await run(["shuf", "-n", ""], "a\n")).toMatchObject(await systemRun(["shuf", "-n", ""], "a\n"));
+ expect(await run(["shuf", "-o", "shuffled", "-e", "a", "b"])).toMatchObject({ code: 0, stdout: "" });
+ expect((await readFile(join(dir, "shuffled"), "utf8")).trim().split("\n").sort().join("")).toBe("ab");
+ expect(await run(["shuf", "-o", "shuf-raw-file-out", "shuf-raw"])).toMatchObject({ code: 0, stdout: "" });
+ expect([...await readFile(join(dir, "shuf-raw-file-out"))]).toEqual([0xff, 0x0a]);
+ expect(await run(["shuf", "-o", "shuffled-a", "-o", "shuffled-b", "-e", "a"])).toMatchObject({ code: 1, stderr: "shuf: multiple output files specified\n" });
+ expect((await run(["shuf", "-n10", "-i0-9", "-n3", "-n20"])).stdout.trim().split("\n")).toHaveLength(3);
+ expect(await run(["shuf", "-i0-9", "-e", "A"])).toMatchObject({ code: 1, stderr: "shuf: cannot combine -e and -i options\nTry 'shuf --help' for more information.\n" });
+ expect(await run(["shuf", "-i0-9", "-i8-90"])).toMatchObject({ code: 1 });
+ expect(await run(["shuf", "-i", "bad"])).toMatchObject(await systemRun(["shuf", "-i", "bad"]));
+ expect(await run(["shuf", "-i", "2-1"])).toMatchObject(await systemRun(["shuf", "-i", "2-1"]));
+ expect(await run(["shuf", "-r", "-n", "1", "-i", "2-1"])).toMatchObject(await systemRun(["shuf", "-r", "-n", "1", "-i", "2-1"]));
+ for (const option of ["--head-count", "--input-range", "--output", "--random-source"]) {
+ expect(await run(["shuf", option])).toMatchObject({ code: 1, stderr: `shuf: option '${option}' requires an argument\nTry 'shuf --help' for more information.\n` });
+ }
+ expect(await run(["shuf", "--bad=4"])).toMatchObject({ code: 1, stderr: "shuf: unrecognized option '--bad=4'\nTry 'shuf --help' for more information.\n" });
+ expect(await run(["shuf", "-i1-18446744073709551615", "-n2"])).toMatchObject({ code: 0 });
+ expect(await sampleCommand(["shuf", "--rep", "-e", "A"])).toStartWith("A\nA\n");
+});
+
+test("mktemp creates files and directories from templates", async () => {
+ const file = await run(["mktemp", "sample.XXXXXX"]);
+ expect(file.code).toBe(0);
+ expect(file.stdout.trim()).toStartWith("sample.");
+ expect(await readFile(join(dir, file.stdout.trim()), "utf8")).toBe("");
+ const suffixed = await run(["mktemp", "--suffix=.tmp", "sample.XXXXXX"]);
+ expect(suffixed.code).toBe(0);
+ expect(suffixed.stdout.trim()).toEndWith(".tmp");
+ expect(await readFile(join(dir, suffixed.stdout.trim()), "utf8")).toBe("");
+ const prefixSuffixed = await run(["mktemp", "--s=.tmp", "sample.XXXXXX"]);
+ expect(prefixSuffixed.code).toBe(0);
+ expect(prefixSuffixed.stdout.trim()).toEndWith(".tmp");
+ expect(await readFile(join(dir, prefixSuffixed.stdout.trim()), "utf8")).toBe("");
+ const implicitSuffix = await run(["mktemp", "implicit.XXX.txt"]);
+ expect(implicitSuffix.code).toBe(0);
+ expect(implicitSuffix.stdout.trim()).toStartWith("implicit.");
+ expect(implicitSuffix.stdout.trim()).toEndWith(".txt");
+ expect(await run(["mktemp", "--suffix=a/b", "bad.XXXXXX"])).toMatchObject(await systemRun(["/usr/bin/mktemp", "--suffix=a/b", "bad.XXXXXX"]));
+ expect(await run(["mktemp", "aXXXX/b"])).toMatchObject({ code: 1, stdout: "", stderr: `mktemp: invalid suffix ${diagnosticQuote("/b")}, contains directory separator\n` });
+ expect(await run(["mktemp", "aXXX/bXX"])).toMatchObject({ code: 1, stdout: "", stderr: `mktemp: too few X's in template ${diagnosticQuote("aXXX/bXX")}\n` });
+ expect(await run(["mktemp", "ab\nXX"])).toMatchObject(await systemRun(["/usr/bin/mktemp", "ab\nXX"]));
+ expect(await run(["mktemp", "-t", "ab\t/XXX"])).toMatchObject(await systemRun(["/usr/bin/mktemp", "-t", "ab\t/XXX"]));
+ expect(await run(["mktemp", "-t", "/abs.XXX"])).toMatchObject({ code: 1, stdout: "", stderr: `mktemp: invalid template, ${diagnosticQuote("/abs.XXX")}, contains directory separator\n` });
+ expect(await run(["mktemp", "--suffix=.s", "a.XXX.t"])).toMatchObject({ code: 1, stdout: "", stderr: `mktemp: with --suffix, template ${diagnosticQuote("a.XXX.t")} must end in X\n` });
+ expect(await run(["mktemp", "--suffix"])).toMatchObject({ code: 1, stderr: "mktemp: option '--suffix' requires an argument\nTry 'mktemp --help' for more information.\n" });
+ const helpSuffix = await run(["mktemp", "--suffix", "--help", "sample.XXXXXX"]);
+ expect(helpSuffix.code).toBe(0);
+ expect(helpSuffix.stdout.trim()).toEndWith("--help");
+ expect(await readFile(join(dir, helpSuffix.stdout.trim()), "utf8")).toBe("");
+ expect(await run(["mktemp", "-p"])).toMatchObject({ code: 1, stderr: "mktemp: option requires an argument -- 'p'\nTry 'mktemp --help' for more information.\n" });
+ const madeDir = await run(["mktemp", "-d", "dir.XXXXXX"]);
+ expect(madeDir.code).toBe(0);
+ expect(madeDir.stdout.trim()).toStartWith("dir.");
+ const prefixDir = await run(["mktemp", "--di", "dir.XXXXXX"]);
+ expect(prefixDir.code).toBe(0);
+ expect((await stat(join(dir, prefixDir.stdout.trim()))).isDirectory()).toBe(true);
+ expect(await run(["mktemp", "--d", "dir.XXXXXX"])).toMatchObject({ code: 1, stderr: "mktemp: option '--d' is ambiguous; possibilities: '--directory' '--dry-run'\nTry 'mktemp --help' for more information.\n" });
+ const suffixedDir = await run(["mktemp", "-d", "--suffix=.d", "dir.XXXXXX"]);
+ expect(suffixedDir.code).toBe(0);
+ expect((await stat(join(dir, suffixedDir.stdout.trim()))).isDirectory()).toBe(true);
+ await mkdir(join(dir, "tmp-parent"));
+ expect(await run(["mktemp", "--q", "missing-parent/XXX"])).toMatchObject({ code: 1, stdout: "", stderr: "" });
+ const tmpdirFile = await run(["mktemp", "--tmpdir=tmp-parent", "nested.XXXXXX"]);
+ expect(tmpdirFile.code).toBe(0);
+ expect(tmpdirFile.stdout.trim()).toStartWith("tmp-parent/nested.");
+ expect(await readFile(join(dir, tmpdirFile.stdout.trim()), "utf8")).toBe("");
+ const prefixTmpdirFile = await run(["mktemp", "--tm=tmp-parent", "prefix.XXXXXX"]);
+ expect(prefixTmpdirFile.code).toBe(0);
+ expect(prefixTmpdirFile.stdout.trim()).toStartWith("tmp-parent/prefix.");
+ expect(await readFile(join(dir, prefixTmpdirFile.stdout.trim()), "utf8")).toBe("");
+ const tmpdirBare = await run(["mktemp", "--tmpdir=tmp-parent", "XXX"]);
+ expect(tmpdirBare.code).toBe(0);
+ expect(tmpdirBare.stdout.trim()).toMatch(/^tmp-parent\/[A-Za-z0-9]{3}$/);
+ expect(await readFile(join(dir, tmpdirBare.stdout.trim()), "utf8")).toBe("");
+ const pBare = await run(["mktemp", "-p", "tmp-parent", "XXX"]);
+ expect(pBare.code).toBe(0);
+ expect(pBare.stdout.trim()).toMatch(/^tmp-parent\/[A-Za-z0-9]{3}$/);
+ expect(await readFile(join(dir, pBare.stdout.trim()), "utf8")).toBe("");
+ const tBare = await run(["mktemp", "-t", "XXX"], "", { env: { TMPDIR: join(dir, "tmp-parent") } });
+ expect(tBare.code).toBe(0);
+ expect(tBare.stdout.trim()).toMatch(new RegExp(`^${join(dir, "tmp-parent").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/[A-Za-z0-9]{3}$`));
+ expect(await readFile(tBare.stdout.trim(), "utf8")).toBe("");
+ const tWithPUnsetTmpdir = await run(["mktemp", "-p", "tmp-parent", "-t", "tp.XXX"], "", { env: { TMPDIR: "" } });
+ expect(tWithPUnsetTmpdir.code).toBe(0);
+ expect(tWithPUnsetTmpdir.stdout.trim()).toMatch(/^tmp-parent\/tp\.[A-Za-z0-9]{3}$/);
+ expect(await readFile(join(dir, tWithPUnsetTmpdir.stdout.trim()), "utf8")).toBe("");
+ const tmpdirOptional = await run(["mktemp", "--tmpdir", "opt.XXXXXX"], "", { env: { TMPDIR: join(dir, "tmp-parent") } });
+ expect(tmpdirOptional.code).toBe(0);
+ expect(tmpdirOptional.stdout.trim()).toStartWith(join(dir, "tmp-parent/opt."));
+ const emptyTmpdirOption = await run(["mktemp", "--tmpdir=", "empty-opt.XXXXXX"], "", { env: { TMPDIR: join(dir, "tmp-parent") } });
+ expect(emptyTmpdirOption.code).toBe(0);
+ expect(emptyTmpdirOption.stdout.trim()).toStartWith(join(dir, "tmp-parent/empty-opt."));
+ const emptyPOption = await run(["mktemp", "-p", "", "empty-p.XXXXXX"], "", { env: { TMPDIR: join(dir, "tmp-parent") } });
+ expect(emptyPOption.code).toBe(0);
+ expect(emptyPOption.stdout.trim()).toStartWith(join(dir, "tmp-parent/empty-p."));
+ const defaultTemplate = await run(["mktemp"], "", { env: { TMPDIR: join(dir, "tmp-parent") } });
+ expect(defaultTemplate.code).toBe(0);
+ expect(defaultTemplate.stdout.trim()).toStartWith(join(dir, "tmp-parent/tmp."));
+ const emptyEnvTemplate = await run(["mktemp"], "", { env: { TMPDIR: "" } });
+ expect(emptyEnvTemplate.code).toBe(0);
+ expect(emptyEnvTemplate.stdout.trim()).toStartWith("/tmp/tmp.");
+ const dotTemplate = await run(["mktemp"], "", { env: { TMPDIR: "." } });
+ expect(dotTemplate.code).toBe(0);
+ expect(dotTemplate.stdout.trim()).toStartWith("./tmp.");
+ expect(await readFile(join(dir, dotTemplate.stdout.trim()), "utf8")).toBe("");
+ const missingParent = await run(["mktemp"], "", { env: { TMPDIR: "no/such/dir" } });
+ expect(missingParent).toMatchObject({ code: 1, stdout: "" });
+ expect(missingParent).toMatchObject(await systemRun(["/usr/bin/mktemp"], "", { env: { TMPDIR: "no/such/dir" } }));
+ expect(await run(["mktemp", "missing\nparent/tmp.XXXXXX"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `mktemp: failed to create file via template ${diagnosticQuote("missing\\nparent/tmp.XXXXXX")}: No such file or directory\n`,
+ });
+ expect(await run(["mktemp", "--quiet"], "", { env: { TMPDIR: "no/such/dir" } })).toMatchObject({ code: 1, stdout: "", stderr: "" });
+ await writeFile(join(dir, "mktemp-parent-file"), "x");
+ expect(await run(["mktemp", "mktemp-parent-file/nested.XXXXXX"])).toMatchObject(await systemRun(["/usr/bin/mktemp", "mktemp-parent-file/nested.XXXXXX"]));
+ const dryRun = await run(["mktemp", "-u", "dry.XXXXXX"]);
+ expect(dryRun.code).toBe(0);
+ await expect(stat(join(dir, dryRun.stdout.trim()))).rejects.toThrow();
+ const prefixDryRun = await run(["mktemp", "--dr", "dry.XXXXXX"]);
+ expect(prefixDryRun.code).toBe(0);
+ await expect(stat(join(dir, prefixDryRun.stdout.trim()))).rejects.toThrow();
+ expect(await run(["mktemp", "--dry-run=1", "dry.XXXXXX"])).toMatchObject({ code: 1, stderr: "mktemp: option '--dry-run' doesn't allow an argument\nTry 'mktemp --help' for more information.\n" });
+ const mktempHelp = (await run(["mktemp", "--h"])).stdout;
+ expect(mktempHelp).toContain("Usage: mktemp [OPTION]... [TEMPLATE]\n");
+ expect(mktempHelp).toContain("TEMPLATE must contain at least 3 consecutive 'X's in last component.\n");
+ expect(mktempHelp).toContain("If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied.\n");
+ expect(mktempHelp).toContain("-u, --dry-run do not create anything; merely print a name (unsafe)\n");
+ expect(mktempHelp).toContain("--suffix=SUFF append SUFF to TEMPLATE; SUFF must not contain a slash.\n");
+ expect(mktempHelp).toContain(" unlike with -t, TEMPLATE may contain slashes,\n");
+ expect(await run(["mktemp", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["mktemp", "sample.XXXXXX", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: mktemp [OPTION]... [TEMPLATE]\n") });
+ expect(await run(["mktemp", "sample.XXXXXX", "--help"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stderr: "mktemp: too many templates\nTry 'mktemp --help' for more information.\n" });
+ expect(await run(["mktemp", "sample.XXXXXX", "--version"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stderr: "mktemp: too many templates\nTry 'mktemp --help' for more information.\n" });
+ expect(await run(["mktemp", "--bad", "--help"])).toMatchObject({ code: 1, stderr: "mktemp: unrecognized option '--bad'\nTry 'mktemp --help' for more information.\n" });
+ const full = Bun.file("/dev/full");
+ if (await full.exists()) {
+ const proc = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "mktemp", "-p", "tmp-parent"], {
+ cwd: dir,
+ stdout: full,
+ stderr: "pipe",
+ });
+ expect(await proc.exited).toBe(1);
+ expect(await readdir(join(dir, "tmp-parent"))).toEqual([]);
+ }
+});
+
+test("date command exposes stable output shapes", async () => {
+ expect(await run(["date", "-u", "-d", "2020-01-02T03:04:05Z", "+%Y-%m-%d %T %Z"])).toMatchObject({ code: 0, stdout: "2020-01-02 03:04:05 UTC\n" });
+ expect(await run(["date", "-u", "--set", "@0"])).toMatchObject({
+ code: 1,
+ stdout: "Thu Jan 1 00:00:00 UTC 1970\n",
+ stderr: "date: cannot set date: Operation not permitted\n",
+ });
+ const utcDateOptions = { env: { LC_ALL: "C", TZ: "UTC0" } };
+ expect(await run(["date", "010100002030"], "", utcDateOptions)).toMatchObject(await systemRun(["date", "010100002030"], "", utcDateOptions));
+ expect(await run(["date", "0101000068"], "", utcDateOptions)).toMatchObject(await systemRun(["date", "0101000068"], "", utcDateOptions));
+ expect(await run(["date", "022900002023"], "", utcDateOptions)).toMatchObject(await systemRun(["date", "022900002023"], "", utcDateOptions));
+ expect(await run(["date", "-d", "now", "not-a-format"], "", utcDateOptions)).toMatchObject(await systemRun(["date", "-d", "now", "not-a-format"], "", utcDateOptions));
+ expect(await run(["date", "-d"])).toMatchObject({ code: 1, stderr: "date: option requires an argument -- 'd'\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "-f"])).toMatchObject({ code: 1, stderr: "date: option requires an argument -- 'f'\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "-r"])).toMatchObject({ code: 1, stderr: "date: option requires an argument -- 'r'\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "--date"])).toMatchObject({ code: 1, stderr: "date: option '--date' requires an argument\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "date: unrecognized option '--bad'\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "--d=@0", "+%s"])).toMatchObject({ code: 1, stdout: "", stderr: "date: option '--d=@0' is ambiguous; possibilities: '--date' '--debug'\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "--dat=@0", "+%s"])).toMatchObject({ code: 0, stdout: "0\n" });
+ expect(await run(["date", "--de", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: date [OPTION]... [+FORMAT]\n or: date [OPTION]... MMDDhhmm[[CC]YY][.ss]\n") });
+ expect(await run(["date", "--dat", "--help", "+%s"])).toMatchObject(await systemRun(["date", "--dat", "--help", "+%s"]));
+ expect(await run(["date", "--r=missing", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "date: option '--r=missing' is ambiguous; possibilities: '--reference' '--resolution' '--rfc-email' '--rfc-822' '--rfc-2822' '--rfc-3339'\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "--v=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "date: option '--version' doesn't allow an argument\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "--debug=1"])).toMatchObject({ code: 1, stdout: "", stderr: "date: option '--debug' doesn't allow an argument\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "+%F", "extra\narg"])).toMatchObject({ code: 1, stdout: "", stderr: `date: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'date --help' for more information.\n` });
+ expect(await run(["date", "--rfc-3339", "--help"])).toMatchObject(await systemRun(["date", "--rfc-3339", "--help"]));
+ expect(await run(["date", "--rfc-3339", "bad", "--help"])).toMatchObject(await systemRun(["date", "--rfc-3339", "bad", "--help"]));
+ expect(await run(["date", "--iso", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: date [OPTION]... [+FORMAT]\n") });
+ expect(await run(["date", "--iso=seconds", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: date [OPTION]... [+FORMAT]\n") });
+ expect(await run(["date", "--rfc-3339=", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `date: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--rfc-3339")}\nValid arguments are:\n - ${diagnosticQuote("date")}\n - ${diagnosticQuote("seconds")}\n - ${diagnosticQuote("ns")}\nTry 'date --help' for more information.\n`,
+ });
+ expect(await run(["date", "--iso-8601=bad", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `date: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("--iso-8601")}\nValid arguments are:\n - ${diagnosticQuote("hours")}\n - ${diagnosticQuote("minutes")}\n - ${diagnosticQuote("date")}\n - ${diagnosticQuote("seconds")}\n - ${diagnosticQuote("ns")}\nTry 'date --help' for more information.\n`,
+ });
+ expect(await run(["date", "-u", "--rfc-3=seconds", "-d", "@0"])).toMatchObject({ code: 0, stdout: "1970-01-01 00:00:00+00:00\n" });
+ expect(await run(["date", "--file="])).toMatchObject({ code: 1, stdout: "", stderr: "date: '': No such file or directory\n" });
+ expect(await run(["date", "--reference="])).toMatchObject({ code: 1, stderr: "date: '': No such file or directory\n" });
+ expect(await run(["date", "-r", "date-missing", "+%s"])).toMatchObject({ code: 1, stderr: "date: date-missing: No such file or directory\n" });
+ await symlink("date-ref-loop", join(dir, "date-ref-loop"));
+ expect(await run(["date", "-r", "date-ref-loop", "+%s"])).toMatchObject({ code: 1, stdout: "", stderr: "date: date-ref-loop: Too many levels of symbolic links\n" });
+ await writeFile(join(dir, "date-ref-negative-ns"), "");
+ await systemRun(["/usr/bin/touch", "-d", "1969-12-31 23:59:59.123456789 +0000", "date-ref-negative-ns"]);
+ expect(await run(["date", "-r", "date-ref-negative-ns", "+%s.%N"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "-1.123456789\n" });
+ expect(await run(["date", "-f", "date-file-missing", "+%s"])).toMatchObject({ code: 1, stdout: "", stderr: "date: date-file-missing: No such file or directory\n" });
+ expect(await run(["date", "-d", "@0", "-r", "date-missing", "+%s"])).toMatchObject({ code: 1, stderr: "date: the options to specify dates for printing are mutually exclusive\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "--bad=4"])).toMatchObject({ code: 1, stderr: "date: unrecognized option '--bad=4'\nTry 'date --help' for more information.\n" });
+ expect(await run(["date", "-d", "2025-10-11T13:00"], "", { env: { LC_ALL: "en_US.UTF-8" } })).toMatchObject({ code: 0, stdout: "Sat Oct 11 01:00:00 PM AEDT 2025\n" });
+ expect(await run(["date", "-u", "-d", "@0", "+%s %F %T %z %:z %j %N"])).toMatchObject({ code: 0, stdout: "0 1970-01-01 00:00:00 +0000 +00:00 001 000000000\n" });
+ expect(await run(["date", "-u", "-d", "@0", "+%#a %#A %#b %#B %#p %#P"])).toMatchObject({ code: 0, stdout: "THU THURSDAY JAN JANUARY am am\n" });
+ expect(await run(["date", "-u", "-d", "@0", "+%Ec|%Ex|%EX|%EC|%Ey|%EY|%Od|%Om|%Oy|%OH|%OS|%OV|%Ou|%Ow|%O:::z|%_5Od"])).toMatchObject({ code: 0, stdout: "Thu Jan 1 00:00:00 1970|01/01/70|00:00:00|19|70|1970|01|01|70|00|00|01|4|4|+00| 1\n" });
+ expect(await run(["date", "-u", "-d", "@0", "+%%|%5%|%05%|%_5%|%-5%|%5Q|%05Q|%_5Q|%-5Q"])).toMatchObject({ code: 0, stdout: "%| %5%|00%05%| %_5%|%-5%| %5Q|0%05Q| %_5Q|%-5Q\n" });
+ expect(await run(["date", "-u", "-d", "@0", "+%^P %#c"])).toMatchObject({ code: 0, stdout: "am Thu Jan 1 00:00:00 1970\n" });
+ expect(await run(["date", "-u", "-d", "@0", "+%5d|%-5d|%-_5d|%-05d|%-5Y"])).toMatchObject({ code: 0, stdout: "00001|1| 1|00001|1970\n" });
+ expect(await run(["date", "-u", "-d", "@1", "+%5a|%#5a|%^10b|%5p|%5Z"])).toMatchObject({ code: 0, stdout: " Thu| THU| JAN| AM| UTC\n" });
+ expect(await run(["date", "-u", "-d", "@1", "+%+5s|%+5d|%+5y|%+5C|%+6Y"])).toMatchObject({ code: 0, stdout: "00001|00001|+0070|+0019|+01970\n" });
+ expect(await run(["date", "--uct", "-d", "@0", "+%s %z"])).toMatchObject({ code: 0, stdout: "0 +0000\n" });
+ expect(await run(["date", "-u", "-d", "@0", "+%-N"])).toMatchObject({ code: 0, stdout: "000000000\n" });
+ expect(await run(["date", "-u", "-d", "@0.123456789", "+%3N|%5N|%10N|%_10N|%-10N"])).toMatchObject({ code: 0, stdout: "123|12345|1234567890|123456789 |123456789\n" });
+ expect(await run(["date", "--resolution"])).toMatchObject({ code: 0, stdout: "0.000000001\n" });
+ expect(await run(["date", "-u", "-d", "@1.123456789", "--rfc-3339=ns"])).toMatchObject({ code: 0, stdout: "1970-01-01 00:00:01.123456789+00:00\n" });
+ expect(await run(["date", "--rfc-3339=bad"])).toMatchObject(await systemRun(["date", "--rfc-3339=bad"]));
+ expect(await run(["date", "--iso-8601=bad"])).toMatchObject(await systemRun(["date", "--iso-8601=bad"]));
+ expect(await run(["date", "--rfc-3339=bad\nmode"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `date: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--rfc-3339")}\nValid arguments are:\n - ${diagnosticQuote("date")}\n - ${diagnosticQuote("seconds")}\n - ${diagnosticQuote("ns")}\nTry 'date --help' for more information.\n`,
+ });
+ expect(await run(["date", "--iso-8601=bad\nmode"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `date: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--iso-8601")}\nValid arguments are:\n - ${diagnosticQuote("hours")}\n - ${diagnosticQuote("minutes")}\n - ${diagnosticQuote("date")}\n - ${diagnosticQuote("seconds")}\n - ${diagnosticQuote("ns")}\nTry 'date --help' for more information.\n`,
+ });
+ expect(await run(["date", "-d", "bad\nname"])).toMatchObject(await systemRun(["date", "-d", "bad\nname"]));
+ expect(await run(["date", "-d", "bad\tname"])).toMatchObject(await systemRun(["date", "-d", "bad\tname"]));
+ expect(await run(["date", "-r", "missing\nname"])).toMatchObject(await systemRun(["date", "-r", "missing\nname"]));
+ expect(await run(["date", "+%s", "extra"])).toMatchObject({ code: 1, stdout: "", stderr: `date: extra operand ${diagnosticQuote("extra")}\nTry 'date --help' for more information.\n` });
+ expect(await run(["date", "-u", "-d", "2026-09-10", "+%Y"], "", { env: { LC_ALL: "am_ET.UTF-8" } })).toMatchObject({ code: 0, stdout: "2018\n" });
+ expect(await run(["date", "-u", "-d", "2026-09-12", "+%Y"], "", { env: { LC_ALL: "am_ET.UTF-8" } })).toMatchObject({ code: 0, stdout: "2019\n" });
+ expect(await run(["date", "-u", "-d", "2026-03-19", "+%Y"], "", { env: { LC_ALL: "fa_IR.UTF-8" } })).toMatchObject({ code: 0, stdout: "1404\n" });
+ expect(await run(["date", "-u", "-d", "2026-03-22", "+%Y"], "", { env: { LC_ALL: "fa_IR.UTF-8" } })).toMatchObject({ code: 0, stdout: "1405\n" });
+ expect(await run(["date", "-u", "-d", "2026-01-01", "+%Y %B"], "", { env: { LC_ALL: "th_TH.UTF-8" } })).toMatchObject({ code: 0, stdout: "2569 \u0e21\u0e01\u0e23\u0e32\u0e04\u0e21\n" });
+ expect(await run(["date", "-u", "-d", "2026-01-01", "--iso-8601=hours"], "", { env: { LC_ALL: "th_TH.UTF-8" } })).toMatchObject({ code: 0, stdout: "2026-01-01T00+00:00\n" });
+ expect(await run(["date", "-u", "-d", "2026-01-01", "--rfc-3339=date"], "", { env: { LC_ALL: "am_ET.UTF-8" } })).toMatchObject({ code: 0, stdout: "2026-01-01\n" });
+ expect(await run(["date", "-d", "1970-01-01 00:00:01", "+%s"], "", { env: { TZ: "UTC+2" } })).toMatchObject({ code: 0, stdout: "7201\n" });
+ expect(await run(["date", "-d", "1970-01-01 00:00:01.123456789", "+%s.%N"], "", { env: { TZ: "UTC+2" } })).toMatchObject({ code: 0, stdout: "7201.123456789\n" });
+ expect(await run(["date", "-u", "-d", "1969-12-31 13:00:00.00000001-1100", "--rfc-3339=ns"])).toMatchObject({ code: 0, stdout: "1970-01-01 00:00:00.000000010+00:00\n" });
+ expect(await run(["date", "-u", "-d", "1969-12-31 13:00:00.00000001-1100", "--iso=ns"])).toMatchObject({ code: 0, stdout: "1970-01-01T00:00:00,000000010+00:00\n" });
+ expect(await run(["date", "-u", "-d", "21:04 +0100", "+%S"])).toMatchObject({ code: 0, stdout: "00\n" });
+ expect(await run(["date", "-u", "-d", "2020-12-31T23:59:58.123Z", "+%G-%V %q %R %r"])).toMatchObject({ code: 0, stdout: "2020-53 4 23:59 11:59:58 PM\n" });
+ expect(await run(["date", "-u", "-d", "2020-01-02T03:04:05Z", "+%k|%l|%P|%U|%W|%_d|%-d|%0d"])).toMatchObject({ code: 0, stdout: " 3| 3|am|00|00| 2|2|02\n" });
+ expect(await run(["date", "-u", "-d", "1999-06-05T05:00:00Z", "+%0e|%0k|%0l"])).toMatchObject({ code: 0, stdout: "05|05|05\n" });
+ expect(await run(["date", "+%z|%:z|%::z|%:::z"], "", { env: { TZ: "XXX12:34:56" } })).toMatchObject({ code: 0, stdout: "-1234|-12:34|-12:34:56|-12:34:56\n" });
+ expect(await run(["date", "+%z|%:z|%::z|%:::z"], "", { env: { TZ: "XXX-1:02:03" } })).toMatchObject({ code: 0, stdout: "+0102|+01:02|+01:02:03|+01:02:03\n" });
+ expect(await run(["date", "-u", "-d", "1999-01-08T00:00:00Z", "+%03d|%_3d|%3004Y"])).toMatchObject({ code: 0, stdout: `008| 8|${"0".repeat(3000)}1999\n` });
+ expect(await run(["date", "-u", "-d", "@-22", "+%05s|%_5s|%8:z|%+6Y|%+4C"])).toMatchObject({ code: 0, stdout: "-0022| -22|+0000:00|+01969|+019\n" });
+ expect(await run(["date", "-u", "-d", "1997-01-19 08:17:48 +0", "+%x_%X_%y_%Y"])).toMatchObject({ code: 0, stdout: "01/19/97_08:17:48_97_1997\n" });
+ expect(await run(["date", "-u", "-d", "Apr 11 22:59:00 2011"])).toMatchObject({ code: 0, stdout: "Mon Apr 11 22:59:00 UTC 2011\n" });
+ expect(await run(["date", "-d", "2011-12-11", "+%F %T %Z %z"], "", { env: { TZ: "Europe/Helsinki" } })).toMatchObject({ code: 0, stdout: "2011-12-11 00:00:00 EET +0200\n" });
+ expect(await run(["date", "-d", "@0", "+%Z %z %:::z"], "", { env: { TZ: "Australia/Melbourne" } })).toMatchObject({ code: 0, stdout: "AEST +1000 +10\n" });
+ expect(await run(["date", "-d", "2026-07-01T00:00:00", "+%Z %z"], "", { env: { TZ: "Europe/London" } })).toMatchObject({ code: 0, stdout: "BST +0100\n" });
+ expect(await run(["date", "-d", "@0", "+%Z %z"], "", { env: { TZ: "America/New_York" } })).toMatchObject({ code: 0, stdout: "EST -0500\n" });
+ expect(await run(["date", "-d", "@0", "+%Z %z"], "", { env: { TZ: "Pacific/Auckland" } })).toMatchObject({ code: 0, stdout: "NZST +1200\n" });
+ expect(await run(["date", "-d", "2011-12-11 EET"], "", { env: { TZ: "Europe/Helsinki" } })).toMatchObject({ code: 0, stdout: "Sun Dec 11 00:00:00 EET 2011\n" });
+ expect(await run(["date", "-d", "2011-06-11 EEST"], "", { env: { TZ: "Europe/Helsinki" } })).toMatchObject({ code: 0, stdout: "Sat Jun 11 00:00:00 EEST 2011\n" });
+ expect(await run(["date", "-d", "2016-06-01 EDT + 6 months", "+%s|%F|%T|%z"], "", { env: { TZ: "America/New_York" } })).toMatchObject({ code: 0, stdout: "1480564800|2016-11-30|23:00:00|-0500\n" });
+ expect(await run(["date", "-u", "-d", "1995-1-1", "+%U"])).toMatchObject({ code: 0, stdout: "01\n" });
+ expect(await run(["date", "-u", "-d", "000909", "+%Y-%m-%d %T"])).toMatchObject({ code: 0, stdout: "2000-09-09 00:00:00\n" });
+ expect(await run(["date", "-d", "1.2. 3:4:5.6", "+%m-%d-%T"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "02-01-03:04:05\n" });
+ expect(await run(["date", "-d", "3 1.2.", "+%m-%d-%H"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "02-01-03\n" });
+ expect(await run(["date", "-u", "-d", "2026(this is a comment)-01-05", "+%Y-%m-%d"])).toMatchObject({ code: 0, stdout: "2026-01-05\n" });
+ expect(await run(["date", "-d", "1(ignore this comment", "+%H:%M:%S"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "01:00:00\n" });
+ expect(await run(["date", "-u", "-d", "1997-01-19T08:17:48+0", "+%d_%D_%e_%h_%H"])).toMatchObject({ code: 0, stdout: "19_01/19/97_19_Jan_08\n" });
+ expect(await run(["date", "-u", "-d", "2020-01-02T03:04:05Z", "--rfc-3339=seconds"])).toMatchObject({ code: 0, stdout: "2020-01-02 03:04:05+00:00\n" });
+ expect(await run(["date", "-u", "-d", "@31536000", "--iso=sec"])).toMatchObject({ code: 0, stdout: "1971-01-01T00:00:00+00:00\n" });
+ expect(await run(["date", "-u", "-d", "@31536000", "--rfc-3339=sec"])).toMatchObject({ code: 0, stdout: "1971-01-01 00:00:00+00:00\n" });
+ expect(await run(["date", "-u", "-d", "1997-01-19 08:17:48 +0 4 seconds ago", "+%Y-%m-%d %T"])).toMatchObject({ code: 0, stdout: "1997-01-19 08:17:44\n" });
+ expect(await run(["date", "-u", "-d", "1997-01-19 08:17:48 +0 next month", "+%Y-%m-%d %T"])).toMatchObject({ code: 0, stdout: "1997-02-19 08:17:48\n" });
+ expect(await run(["date", "-u", "-d", "1997-01-19 08:17:48 +0 this year", "+%Y-%m-%d %T"])).toMatchObject({ code: 0, stdout: "1997-01-19 08:17:48\n" });
+ expect(await run(["date", "-u", "-d", "20050101 +1 day", "+%F"])).toMatchObject({ code: 0, stdout: "2005-01-02\n" });
+ expect(await run(["date", "-u", "-d", "1970-01-01 UTC 946684800 sec", "+%Y-%m-%d %T %z"])).toMatchObject({ code: 0, stdout: "2000-01-01 00:00:00 +0000\n" });
+ expect(await run(["date", "-u", "-d", "1970-01-01 00:00:00.1234567 UTC +961062237.987654321 sec", "--iso=ns"])).toMatchObject({ code: 0, stdout: "2000-06-15T09:43:58,111111021+00:00\n" });
+ expect(await run(["date", "-u", "-d1970-01-01 00:00:00.1234567 UTC +961062237.987654321 sec", "--rfc-3339=ns"])).toMatchObject({ code: 0, stdout: "2000-06-15 09:43:58.111111021+00:00\n" });
+ expect(await run(["date", "-u", "-d", "1970-12-31T23:59:59+00:00 - 1 year"])).toMatchObject({ code: 0, stdout: "Wed Dec 31 23:59:59 UTC 1969\n" });
+ expect(await run(["date", "-u", "-d", "09:00B", "+%T"])).toMatchObject({ code: 0, stdout: "07:00:00\n" });
+ expect(await run(["date", "-u", "-d", "09:00L", "+%T"])).toMatchObject({ code: 0, stdout: "22:00:00\n" });
+ expect(await run(["date", "-u", "-d", "09:00N", "+%T"])).toMatchObject({ code: 0, stdout: "10:00:00\n" });
+ expect(await run(["date", "-u", "-d", "09:00Z", "+%T"])).toMatchObject({ code: 0, stdout: "09:00:00\n" });
+ expect(await run(["date", "-u", "-d", "1970-01-01 x", "+%F %T %s"])).toMatchObject({ code: 0, stdout: "1970-01-01 11:00:00 39600\n" });
+ expect(await run(["date", "-u", "-d", "1970-01-01 10:30x", "+%F %T %s"])).toMatchObject({ code: 0, stdout: "1970-01-01 21:30:00 77400\n" });
+ expect(await run(["date", "-u", "-d", "1970-01-01 n", "+%F %T %s"])).toMatchObject({ code: 0, stdout: "1970-01-01 01:00:00 3600\n" });
+ expect(await run(["date", "-u", "-d", "Jan 1 1970 x", "+%F %T %s"])).toMatchObject({ code: 0, stdout: "1970-01-01 11:00:00 39600\n" });
+ expect(await run(["date", "-u", "-d", "Jan 1 10:30:15.25 1970 x", "+%F %T.%N %s"])).toMatchObject({ code: 0, stdout: "1970-01-01 21:30:15.250000000 77415\n" });
+ expect(await run(["date", "-u", "-d", "1970 Jan 1 10:30 UTC", "+%F %T.%N %s"])).toMatchObject({ code: 1, stdout: "", stderr: `date: invalid date ${diagnosticQuote("1970 Jan 1 10:30 UTC")}\n` });
+ expect(await run(["date", "-u", "-d", "1970/02/01 x", "+%F %T %s"])).toMatchObject({ code: 0, stdout: "1970-02-01 11:00:00 2718000\n" });
+ expect(await run(["date", "-u", "-d", "01/01/1970 10:30x", "+%F %T %s"])).toMatchObject({ code: 0, stdout: "1970-01-01 21:30:00 77400\n" });
+ expect(await run(["date", "-u", "-d", "10:30 UTC-05", "+%H:%M"])).toMatchObject({ code: 0, stdout: "15:30\n" });
+ expect(await run(["date", "-d", "TZ=\"UTC\" 2020-01-01 00:00", "+%s"])).toMatchObject({ code: 0, stdout: "1577836800\n" });
+ expect(await run(["date", "-d", "TZ=UTC 2020-01-01 00:00", "+%s"])).toMatchObject({ code: 1, stdout: "", stderr: `date: invalid date ${diagnosticQuote("TZ=UTC 2020-01-01 00:00")}\n` });
+ expect(await run(["date", "-d", "TZ=Bad/Zone 2020-01-01", "+%s"])).toMatchObject({ code: 1, stdout: "", stderr: `date: invalid date ${diagnosticQuote("TZ=Bad/Zone 2020-01-01")}\n` });
+ expect(await run(["date", "-d", "TZ=\"GMT\" 2020-01-01 00:00", "+%s"])).toMatchObject({ code: 0, stdout: "1577836800\n" });
+ expect(await run(["date", "-d", "TZ=\"CET\" 2020-01-01 00:00", "+%s"])).toMatchObject({ code: 0, stdout: "1577833200\n" });
+ expect(await run(["date", "-d", "TZ=\"EST\" 2020-01-01 00:00", "+%s"])).toMatchObject({ code: 0, stdout: "1577854800\n" });
+ expect(await run(["date", "-d", "TZ=\"EST5\" 1970-01-01 00:00"], "", { env: { TZ: "PST8" } })).toMatchObject({ code: 0, stdout: "Wed Dec 31 21:00:00 PST 1969\n" });
+ expect(await run(["date", "-d", "TZ=\"Asia/Tokyo\" 1990-12-11 00:00:00", "+%s"])).toMatchObject({ code: 0, stdout: "660841200\n" });
+ expect(await run(["date", "-d", "TZ=\"Asia/Tokyo\" Sun, 90-12-11 + 3 days - 90 minutes", "+%s"])).toMatchObject({ code: 0, stdout: "661095000\n" });
+ expect(await run(["date", "-d", "TZ=\"America/Edmonton\" 2006-04-02 02:30:00"])).toMatchObject(await systemRun(["date", "-d", "TZ=\"America/Edmonton\" 2006-04-02 02:30:00"]));
+ const utcNow = new Date();
+ const weekday = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"][utcNow.getUTCDay()];
+ const todayUtc = utcNow.toISOString().slice(0, 10);
+ const nextWeekday = new Date(Date.UTC(utcNow.getUTCFullYear(), utcNow.getUTCMonth(), utcNow.getUTCDate() + 7)).toISOString().slice(0, 10);
+ expect(await run(["date", "-d", weekday, "+%Y-%m-%d"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: `${todayUtc}\n` });
+ expect(await run(["date", "-d", `next ${weekday}`, "+%Y-%m-%d"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: `${nextWeekday}\n` });
+ expect(await run(["date", "-u", "-d", "@0", "-I"])).toMatchObject({ code: 0, stdout: "1970-01-01\n" });
+ expect(await run(["date", "-u", "-d", "@0", "-Ihours"])).toMatchObject({ code: 0, stdout: "1970-01-01T00+00:00\n" });
+ expect(await run(["date", "-u", "-d", "2020-01-02T03:04:05Z", "-Iseconds"])).toMatchObject({ code: 0, stdout: "2020-01-02T03:04:05+00:00\n" });
+ expect(await run(["date", "-u", "-R", "-d", "2020-01-02T03:04:05Z"])).toMatchObject({ code: 0, stdout: "Thu, 02 Jan 2020 03:04:05 +0000\n" });
+ expect(await run(["date", "-u", "--rfc-822", "-d", "2020-01-02T03:04:05Z"])).toMatchObject({ code: 0, stdout: "Thu, 02 Jan 2020 03:04:05 +0000\n" });
+ expect(await run(["date", "-u", "--rfc-2822", "-d", "2020-01-02T03:04:05Z"])).toMatchObject({ code: 0, stdout: "Thu, 02 Jan 2020 03:04:05 +0000\n" });
+ await writeFile(join(dir, "dates"), "@0\n2020-01-02T03:04:05Z\n");
+ expect(await run(["date", "-u", "-f", "dates", "+%s"])).toMatchObject({ code: 0, stdout: "0\n1577934245\n" });
+ const rawDateFile = Bun.spawn(["/bin/sh", "-c", `printf 'bad\\377\\n' > raw-dates; LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} date -f raw-dates >raw-date-out 2>raw-date-err`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await rawDateFile.exited).toBe(1);
+ expect(await readFile(join(dir, "raw-date-out"), "utf8")).toBe("");
+ expect([...await readFile(join(dir, "raw-date-err"))]).toEqual([0x64, 0x61, 0x74, 0x65, 0x3a, 0x20, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x20, 0x64, 0x61, 0x74, 0x65, 0x20, 0x27, 0x62, 0x61, 0x64, 0x5c, 0x33, 0x37, 0x37, 0x27, 0x0a]);
+ await mkdir(join(dir, "date-file-dir"));
+ await symlink("date-file-loop", join(dir, "date-file-loop"));
+ expect(await run(["date", "-f", "date-file-dir", "+%s"])).toMatchObject({ code: 1, stdout: "", stderr: "date: date-file-dir: read error: Is a directory\n" });
+ expect(await run(["date", "-f", "date-file-loop", "+%s"])).toMatchObject({ code: 1, stdout: "", stderr: "date: date-file-loop: Too many levels of symbolic links\n" });
+ await writeFile(join(dir, "reference-time"), "x");
+ expect(await run(["touch", "-d", "2020-01-02T03:04:05Z", "reference-time"])).toMatchObject({ code: 0 });
+ expect(await run(["date", "-u", "-r", "reference-time", "+%s"])).toMatchObject({ code: 0, stdout: "1577934245\n" });
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456789 +0000", "reference-time"]);
+ expect(await run(["date", "-u", "-r", "reference-time", "+%s.%N"])).toMatchObject({ code: 0, stdout: "1767323045.123456789\n" });
+ const debugDate = await run(["date", "--debug", "-u", "-d", "@0", "+%F"]);
+ expect(debugDate).toMatchObject({ code: 0, stdout: "1970-01-01\n" });
+ expect(debugDate.stderr).toContain("parsed number of seconds part");
+});
+
+test("platform information commands expose stable output shapes", async () => {
+ expect((await run(["arch"])).stdout.trim().length).toBeGreaterThan(0);
+ expect(await run(["arch", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: arch [OPTION]...\n") });
+ expect(await run(["arch", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["arch", "--h=1"])).toMatchObject({ code: 1, stderr: "arch: option '--help' doesn't allow an argument\nTry 'arch --help' for more information.\n" });
+ expect(await run(["arch", "extra"])).toMatchObject(await systemRun(["arch", "extra"]));
+ const unameKernel = await run(["uname"]);
+ expect(unameKernel.code).toBe(0);
+ expect(unameKernel.stdout.trim().length).toBeGreaterThan(0);
+ expect(await run(["uname", "-s"])).toMatchObject({ code: 0, stdout: unameKernel.stdout });
+ expect(await run(["uname", "extra"])).toMatchObject(await systemRun(["uname", "extra"]));
+ expect((await run(["uname", "-n"])).stdout.trim().length).toBeGreaterThan(0);
+ expect((await run(["uname", "-m"])).stdout.trim()).toBe((await run(["arch"])).stdout.trim());
+ expect(await run(["uname", "-p"])).toMatchObject(await systemRun(["/usr/bin/uname", "-p"]));
+ expect(await run(["uname", "-i"])).toMatchObject(await systemRun(["/usr/bin/uname", "-i"]));
+ expect(await run(["uname", "--kernel-n"])).toMatchObject(await systemRun(["/usr/bin/uname", "--kernel-n"]));
+ expect(await run(["uname", "--kernel-re"])).toMatchObject(await systemRun(["/usr/bin/uname", "--kernel-re"]));
+ expect(await run(["uname", "--kernel-v"])).toMatchObject(await systemRun(["/usr/bin/uname", "--kernel-v"]));
+ expect(await run(["uname", "--operating"])).toMatchObject(await systemRun(["/usr/bin/uname", "--operating"]));
+ expect(await run(["uname", "--process"])).toMatchObject(await systemRun(["/usr/bin/uname", "--process"]));
+ expect(await run(["uname", "--n"])).toMatchObject(await systemRun(["/usr/bin/uname", "--n"]));
+ expect(await run(["uname", "--kernel"])).toMatchObject({ code: 1, stderr: "uname: option '--kernel' is ambiguous; possibilities: '--kernel-name' '--kernel-release' '--kernel-version'\nTry 'uname --help' for more information.\n" });
+ expect(await run(["uname", "--h"])).toMatchObject({ code: 1, stderr: "uname: option '--h' is ambiguous; possibilities: '--hardware-platform' '--help'\nTry 'uname --help' for more information.\n" });
+ expect(await run(["uname", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["uname", "--he", "-s"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: uname [OPTION]...\n") });
+ expect(await run(["uname", "-x", "--help"])).toMatchObject({ code: 1, stderr: "uname: invalid option -- 'x'\nTry 'uname --help' for more information.\n" });
+ expect(await run(["uname", "--version=1"])).toMatchObject({ code: 1, stderr: "uname: option '--version' doesn't allow an argument\nTry 'uname --help' for more information.\n" });
+ expect(await run(["uname", "--kernel=bad", "--help"])).toMatchObject({ code: 1, stderr: "uname: option '--kernel=bad' is ambiguous; possibilities: '--kernel-name' '--kernel-release' '--kernel-version'\nTry 'uname --help' for more information.\n" });
+ expect(await run(["uname", "--all=bad", "--help"])).toMatchObject({ code: 1, stderr: "uname: option '--all' doesn't allow an argument\nTry 'uname --help' for more information.\n" });
+ expect(await run(["uname", "--kernel-n=bad", "--help"])).toMatchObject({ code: 1, stderr: "uname: option '--kernel-name' doesn't allow an argument\nTry 'uname --help' for more information.\n" });
+ expect(await run(["uname", "--bad=1", "--help"])).toMatchObject({ code: 1, stderr: "uname: unrecognized option '--bad=1'\nTry 'uname --help' for more information.\n" });
+ expect((await run(["uname", "-a"])).stdout.trim().split(/\s+/).length).toBeGreaterThanOrEqual(5);
+ let expectedHostid = "00000000";
+ try {
+ const hostidBytes = await readFile("/etc/hostid");
+ if (hostidBytes.length >= 4) expectedHostid = hostidBytes.readUInt32LE(0).toString(16).padStart(8, "0");
+ } catch {}
+ expect(await run(["hostid"])).toMatchObject({ code: 0, stdout: `${expectedHostid}\n` });
+ expect(await run(["hostid", "--he"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: hostid [OPTION]\n") });
+ expect(await run(["hostid", "--ver"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["hostid", "--v=1"])).toMatchObject({ code: 1, stderr: "hostid: option '--version' doesn't allow an argument\nTry 'hostid --help' for more information.\n" });
+ expect(await run(["hostid", "extra"])).toMatchObject(await systemRun(["hostid", "extra"]));
+ expect(await run(["arch", "-/"])).toMatchObject({ code: 1 });
+ expect(await run(["groups", "-/"])).toMatchObject({ code: 1 });
+ expect(await run(["groups", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: groups [OPTION]... [USERNAME]...\n") });
+ expect(await run(["groups", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("the current process (which may differ if the groups database has changed).\n") });
+ expect(await run(["groups", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["groups", "--h=1"])).toMatchObject({ code: 1, stderr: "groups: option '--help' doesn't allow an argument\nTry 'groups --help' for more information.\n" });
+ const hostname = await run(["hostname"]);
+ expect(hostname.code).toBe(0);
+ expect(hostname.stdout.trim().length).toBeGreaterThan(0);
+ expect(await run(["hostname", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: hostname [NAME]\n or: hostname OPTION\n") });
+ expect(await run(["hostname", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["hostname", "--help=bad"])).toMatchObject({ code: 1, stderr: "hostname: option '--help' doesn't allow an argument\nTry 'hostname --help' for more information.\n" });
+ expect(await run(["hostname", "--he=bad"])).toMatchObject({ code: 1, stderr: "hostname: option '--help' doesn't allow an argument\nTry 'hostname --help' for more information.\n" });
+ expect(await run(["hostname", "--version=bad"])).toMatchObject({ code: 1, stderr: "hostname: option '--version' doesn't allow an argument\nTry 'hostname --help' for more information.\n" });
+ expect(await run(["hostname", "--ver=bad"])).toMatchObject({ code: 1, stderr: "hostname: option '--version' doesn't allow an argument\nTry 'hostname --help' for more information.\n" });
+ expect(await run(["hostname", "BEFORE", "--help", "AFTER"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: hostname [NAME]\n or: hostname OPTION\n") });
+ expect(await run(["hostname", "BEFORE", "--version", "AFTER"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["hostname", "--", "--help"])).toMatchObject(await systemRun(["/usr/bin/hostname", "--", "--help"]));
+ const shortHostname = osHostname().split(".")[0];
+ expect(await run(["hostname", "-s"])).toMatchObject({ code: 0, stdout: `${shortHostname}\n`, stderr: "" });
+ expect(await run(["hostname", "--short", "ignored"])).toMatchObject({ code: 0, stdout: `${shortHostname}\n`, stderr: "" });
+ expect(await run(["hostname", "-ys"])).toMatchObject({ code: 0, stdout: `${shortHostname}\n`, stderr: "" });
+ expect(await run(["hostname", "-sy"])).toMatchObject({ code: 0, stdout: "(none)\n", stderr: "" });
+ expect(await run(["hostname", "--yp"])).toMatchObject({ code: 0, stdout: "(none)\n", stderr: "" });
+ expect(await run(["hostname", "--nis"])).toMatchObject({ code: 0, stdout: "(none)\n", stderr: "" });
+ expect(await run(["hostname", "--fqdn"])).toMatchObject({ code: 1, stdout: "", stderr: "hostname: Host name lookup failure\n" });
+ expect(await run(["hostname", "--alias"])).toMatchObject({ code: 1, stdout: "", stderr: "hostname: Host name lookup failure\n" });
+ expect(await run(["hostname", "--ip-address"])).toMatchObject({ code: 1, stdout: "", stderr: "hostname: Host name lookup failure\n" });
+ expect(await run(["hostname", "--file="])).toMatchObject({ code: 1, stdout: "", stderr: "hostname: can't open `'\n" });
+ expect(await run(["hostname", "--file=missing-hostname-file"])).toMatchObject({ code: 1, stderr: "hostname: can't open `missing-hostname-file'\n" });
+ expect(await run(["hostname", "--file=missing-hostname-file", "ignored"])).toMatchObject(await systemRun(["/usr/bin/hostname", "--file=missing-hostname-file", "ignored"]));
+ expect(await run(["hostname", "--short=bad"])).toMatchObject({ code: 1, stderr: "hostname: option '--short' doesn't allow an argument\nTry 'hostname --help' for more information.\n" });
+ expect(await run(["hostname", "--sh=bad"])).toMatchObject({ code: 1, stderr: "hostname: option '--short' doesn't allow an argument\nTry 'hostname --help' for more information.\n" });
+ expect(await run(["hostname", "--fq=bad"])).toMatchObject({ code: 1, stderr: "hostname: option '--fqdn' doesn't allow an argument\nTry 'hostname --help' for more information.\n" });
+ expect(await run(["hostname", "new-name"])).toMatchObject(await systemRun(["/usr/bin/hostname", "new-name"]));
+ expect(await run(["hostname", "one", "two"])).toMatchObject(await systemRun(["/usr/bin/hostname", "one", "two"]));
+ for (const command of ["arch", "hostid", "logname", "whoami", "tty", "uname"]) {
+ expect(await run([command, "extra\narg"])).toMatchObject(await systemRun([command, "extra\narg"]));
+ }
+ const coreutilsHelp = await run(["coreutils", "--help"]);
+ const coreutilsHelpStdout = coreutilsHelp.stdout;
+ expect(coreutilsHelp).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: coreutils --coreutils-prog=PROGRAM_NAME [PARAMETERS]...\n") });
+ expect(coreutilsHelpStdout.includes("Built-in programs:\n")).toBe(true);
+ expect(coreutilsHelpStdout.includes("Use: 'coreutils --coreutils-prog=PROGRAM_NAME --help' for individual program help.\n")).toBe(true);
+ expect(await run(["coreutils", "--coreutils-prog=echo", "via-prog"])).toMatchObject({ code: 0, stdout: "via-prog\n", stderr: "" });
+ expect(await run(["coreutils", "--coreutils-prog-shebang=echo", "wrapper-name", "via-shebang"])).toMatchObject({ code: 0, stdout: "via-shebang\n", stderr: "" });
+ expect(await run(["coreutils", "--coreutils-prog-shebang=echo"])).toMatchObject({ code: 1, stdout: "", stderr: "coreutils: unknown program 'echo'\n" });
+ expect(await run(["coreutils", "--coreutils-prog-shebang=missing", "wrapper-name"])).toMatchObject({ code: 1, stdout: "", stderr: "coreutils: unknown program 'missing'\n" });
+ expect(await run(["tty"])).toMatchObject({ code: 1, stdout: "not a tty\n" });
+ expect(await run(["tty", "-s"])).toMatchObject({ code: 1, stdout: "" });
+ expect(await run(["tty", "--quiet"])).toMatchObject({ code: 1, stdout: "" });
+ expect(await run(["tty", "--sil"])).toMatchObject({ code: 1, stdout: "" });
+ expect(await run(["tty", "--q"])).toMatchObject({ code: 1, stdout: "" });
+ const ttyHelp = (await run(["tty", "--he", "extra"])).stdout;
+ expect(ttyHelp).toContain("Usage: tty [OPTION]...\n");
+ expect(ttyHelp).toContain(" print nothing, only return an exit status\n");
+ expect(await run(["tty", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["tty", "--s=1", "--h"])).toMatchObject({ code: 2, stderr: "tty: option '--silent' doesn't allow an argument\nTry 'tty --help' for more information.\n" });
+ expect(await run(["tty", "-x", "--help"])).toMatchObject({ code: 2, stderr: "tty: invalid option -- 'x'\nTry 'tty --help' for more information.\n" });
+ expect(await run(["tty", "extra"])).toMatchObject(await systemRun(["tty", "extra"]));
+ const fullTty = Bun.spawn(["/bin/sh", "-c", `${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} tty </dev/null >/dev/full`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await fullTty.exited).toBe(3);
+ expect((await run(["id", "-u"])).stdout.trim()).toMatch(/^\d+$/);
+ expect((await run(["id", "-gn"])).stdout.trim()).not.toMatch(/^\d+$/);
+ expect((await run(["id", "-Gn"])).stdout.trim()).not.toMatch(/^\d+( \d+)*$/);
+ expect((await run(["id", "-z", "-u"])).stdout).toBe((await run(["id", "-u"])).stdout.trim() + "\0");
+ expect((await run(["id", "-z", "-Gn"])).stdout).toContain("\0");
+ expect(await run(["id", "-z"])).toMatchObject({ code: 1 });
+ expect(await run(["id", "-n"])).toMatchObject({ code: 1 });
+ expect(await run(["id", "-u", "-G"])).toMatchObject({ code: 1 });
+ expect(await run(["id", "-Z"])).toMatchObject({ code: 1, stderr: "id: --context (-Z) works only on an SELinux-enabled kernel\n" });
+ expect(await run(["id", "--context"])).toMatchObject({ code: 1, stderr: "id: --context (-Z) works only on an SELinux-enabled kernel\n" });
+ expect(await run(["id", "-Z", "--version"])).toMatchObject({ code: 1, stderr: "id: --context (-Z) works only on an SELinux-enabled kernel\n" });
+ expect(await run(["id", "--context", "--help"])).toMatchObject({ code: 1, stderr: "id: --context (-Z) works only on an SELinux-enabled kernel\n" });
+ expect(await run(["id", "--he=bad"])).toMatchObject(await systemRun(["id", "--he=bad"]));
+ expect(await run(["id", "--u"])).toMatchObject(await systemRun(["id", "--u"]));
+ expect(await run(["id", "--g"])).toMatchObject(await systemRun(["id", "--g"]));
+ expect(await run(["id", "--n=bad"])).toMatchObject(await systemRun(["id", "--n=bad"]));
+ const currentUser = (await run(["whoami"])).stdout.trim();
+ expect(await run(["id", "-un", currentUser])).toMatchObject({ code: 0, stdout: `${currentUser}\n` });
+ expect(await run(["id", "-Gn", currentUser])).toMatchObject(await systemRun(["/usr/bin/id", "-Gn", currentUser]));
+ expect(await run(["id", "definitely-missing-user"])).toMatchObject(await systemRun(["/usr/bin/id", "definitely-missing-user"]));
+ expect(await run(["id", "+99999999"])).toMatchObject(await systemRun(["/usr/bin/id", "+99999999"]));
+ expect(await run(["id", "-u", "definitely-missing-user"])).toMatchObject(await systemRun(["/usr/bin/id", "-u", "definitely-missing-user"]));
+ expect(await run(["id", currentUser, "extra"])).toMatchObject({ code: 1 });
+ expect((await run(["groups"])).stdout).toBe((await run(["id", "-Gn"])).stdout);
+ expect(await run(["groups", currentUser])).toMatchObject(await systemRun(["/usr/bin/groups", currentUser]));
+ expect(await run(["groups", "definitely-missing-user"])).toMatchObject(await systemRun(["/usr/bin/groups", "definitely-missing-user"]));
+ expect(await run(["groups", "definitely-missing-user"], "", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/groups", "definitely-missing-user"], "", { env: { LC_ALL: "C" } }));
+ for (const command of ["arch", "groups", "hostid", "logname", "users", "whoami", "link", "unlink"]) {
+ expect(await run([command, "-x", "--help"])).toMatchObject({ code: 1, stderr: expect.stringContaining(`${command}: invalid option -- 'x'\n`) });
+ }
+ expect((await run(["whoami"])).stdout).toBe((await run(["id", "-un"])).stdout);
+ expect(await run(["whoami", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: whoami [OPTION]...\n") });
+ expect(await run(["whoami", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["whoami", "--v=1"])).toMatchObject({ code: 1, stderr: "whoami: option '--version' doesn't allow an argument\nTry 'whoami --help' for more information.\n" });
+ expect(await run(["whoami", "extra"])).toMatchObject(await systemRun(["whoami", "extra"]));
+ expect((await run(["logname"])).stdout.trim().length).toBeGreaterThan(0);
+ expect(await run(["logname", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: logname [OPTION]\n") });
+ expect(await run(["logname", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["logname", "--v=1"])).toMatchObject({ code: 1, stderr: "logname: option '--version' doesn't allow an argument\nTry 'logname --help' for more information.\n" });
+ expect(await run(["logname", "extra"])).toMatchObject({ code: 1 });
+ expect(await run(["users"])).toMatchObject(await systemRun(["/usr/bin/users"]));
+ expect(await run(["users", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: users [OPTION]... [FILE]\n") });
+ expect(await run(["users", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("If FILE is not specified, use /var/run/utmp. /var/log/wtmp as FILE is common.\n") });
+ expect(await run(["users", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["users", "--h=1"])).toMatchObject({ code: 1, stderr: "users: option '--help' doesn't allow an argument\nTry 'users --help' for more information.\n" });
+ const utmpUsers = Buffer.alloc(384 * 2);
+ utmpUsers.writeInt16LE(7, 0);
+ utmpUsers.write("alice", 44, "utf8");
+ utmpUsers.writeInt16LE(7, 384);
+ utmpUsers.write("bob", 384 + 44, "utf8");
+ await writeFile(join(dir, "users-utmp"), utmpUsers);
+ expect(await run(["users", "users-utmp"])).toMatchObject({ code: 0, stdout: "alice bob\n" });
+ await writeFile(join(dir, "utmp-like"), "");
+ expect(await run(["users", "utmp-like"])).toMatchObject({ code: 0, stdout: "" });
+ await writeFile(join(dir, "non-utmp-like"), "x");
+ expect(await run(["users", "non-utmp-like"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["users", "missing-utmp"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["users", "one", "two"])).toMatchObject(await systemRun(["users", "one", "two"]));
+ expect(await run(["users", "one", "extra\narg"])).toMatchObject(await systemRun(["users", "one", "extra\narg"]));
+ expect(Number((await run(["nproc"])).stdout.trim())).toBeGreaterThanOrEqual(1);
+ const nprocRoot = join(dir, "nproc-cgroup");
+ await mkdir(join(nprocRoot, "proc/self"), { recursive: true });
+ await mkdir(join(nprocRoot, "sys/fs/cgroup/foo"), { recursive: true });
+ await writeFile(join(nprocRoot, "proc/self/cgroup"), "0::/foo\n");
+ await writeFile(join(nprocRoot, "proc/self/sched"), "policy : 0\n");
+ await writeFile(join(nprocRoot, "sys/fs/cgroup/foo/cpu.max"), "40000 100000\n");
+ const nprocQuotaEnv = { BNU_NPROC_TEST_ROOT: nprocRoot, OMP_NUM_THREADS: "", OMP_THREAD_LIMIT: "" };
+ expect(await run(["nproc"], "", { env: nprocQuotaEnv })).toMatchObject({ code: 0, stdout: "1\n" });
+ await writeFile(join(nprocRoot, "sys/fs/cgroup/foo/cpu.max"), "150000 100000\n");
+ expect(await run(["nproc"], "", { env: nprocQuotaEnv })).toMatchObject({ code: 0, stdout: `${Math.min(2, availableParallelism())}\n` });
+ await writeFile(join(nprocRoot, "sys/fs/cgroup/foo/cpu.max"), "140000 100000\n");
+ expect(await run(["nproc"], "", { env: nprocQuotaEnv })).toMatchObject({ code: 0, stdout: "1\n" });
+ await writeFile(join(nprocRoot, "sys/fs/cgroup/foo/cpu.max"), "max 100000\n");
+ await writeFile(join(nprocRoot, "sys/fs/cgroup/cpu.max"), "150000 100000\n");
+ expect(await run(["nproc"], "", { env: nprocQuotaEnv })).toMatchObject({ code: 0, stdout: `${Math.min(2, availableParallelism())}\n` });
+ await writeFile(join(nprocRoot, "sys/fs/cgroup/cpu.max"), "max 100000\n");
+ expect(await run(["nproc"], "", { env: { ...nprocQuotaEnv, OMP_NUM_THREADS: "3" } })).toMatchObject({ code: 0, stdout: "3\n" });
+ await writeFile(join(nprocRoot, "sys/fs/cgroup/foo/cpu.max"), "150000 100000\n");
+ expect(await run(["nproc"], "", { env: { ...nprocQuotaEnv, OMP_THREAD_LIMIT: "10" } })).toMatchObject({ code: 0, stdout: `${Math.min(2, availableParallelism())}\n` });
+ await writeFile(join(nprocRoot, "proc/self/sched"), "policy : 1\n");
+ expect(await run(["nproc"], "", { env: nprocQuotaEnv })).toMatchObject({ code: 0, stdout: `${availableParallelism()}\n` });
+ await writeFile(join(nprocRoot, "proc/self/sched"), "policy : -1\n");
+ expect(await run(["nproc"], "", { env: nprocQuotaEnv })).toMatchObject({ code: 0, stdout: `${availableParallelism()}\n` });
+ await writeFile(join(nprocRoot, "proc/self/sched"), "policy : 0\n");
+ await writeFile(join(nprocRoot, "sys/fs/cgroup/foo/cpu.max"), "max 100000\n");
+ expect(await run(["nproc"], "", { env: nprocQuotaEnv })).toMatchObject({ code: 0, stdout: `${availableParallelism()}\n` });
+ expect(await run(["nproc", "--all"], "", { env: nprocQuotaEnv })).toMatchObject(await run(["nproc", "--all"]));
+ expect(await run(["nproc"], "", { env: { OMP_NUM_THREADS: "3" } })).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["nproc"], "", { env: { OMP_NUM_THREADS: "9007199254740993", OMP_THREAD_LIMIT: "" } })).toMatchObject({ code: 0, stdout: "9007199254740993\n" });
+ expect(await run(["nproc"], "", { env: { OMP_NUM_THREADS: "18446744073709551616", OMP_THREAD_LIMIT: "" } })).toMatchObject({ code: 0, stdout: "18446744073709551615\n" });
+ expect(await run(["nproc"], "", { env: { OMP_NUM_THREADS: "18446744073709551615", OMP_THREAD_LIMIT: "9007199254740993" } })).toMatchObject({ code: 0, stdout: "9007199254740993\n" });
+ expect(await run(["nproc", "--ignore=1"], "", { env: { OMP_NUM_THREADS: "3", OMP_THREAD_LIMIT: "2" } })).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["nproc", "--i=1"], "", { env: { OMP_NUM_THREADS: "3", OMP_THREAD_LIMIT: "2" } })).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["nproc", "--ig", "1"], "", { env: { OMP_NUM_THREADS: "3", OMP_THREAD_LIMIT: "2" } })).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["nproc", "--ignore=99"], "", { env: { OMP_NUM_THREADS: "1" } })).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["nproc", "--ignore= 1"], "", { env: { OMP_NUM_THREADS: "3" } })).toMatchObject({ code: 0, stdout: "2\n" });
+ expect(await run(["nproc", "--ignore=+2"], "", { env: { OMP_NUM_THREADS: "3" } })).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["nproc", "--ignore=999999999999999999999999"], "", { env: { OMP_NUM_THREADS: "3" } })).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["nproc", "--all"], "", { env: { OMP_NUM_THREADS: "1" } })).toMatchObject(await run(["nproc", "--all"]));
+ expect(await run(["nproc", "--a"], "", { env: { OMP_NUM_THREADS: "1" } })).toMatchObject(await run(["nproc", "--all"]));
+ const nprocHelp = (await run(["nproc", "--h"])).stdout;
+ expect(nprocHelp).toContain("Usage: nproc [OPTION]...\n");
+ expect(nprocHelp).toContain("which may be less than the number of online processors.\n");
+ expect(nprocHelp).toContain("then they will determine the minimum and maximum returned value respectively.\n");
+ expect(nprocHelp).toContain(" The result is guaranteed to be at least 1.\n");
+ expect(await run(["nproc", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["nproc", "--a=1"])).toMatchObject({ code: 1, stderr: "nproc: option '--all' doesn't allow an argument\nTry 'nproc --help' for more information.\n" });
+ expect(await run(["nproc", "-x", "--help"])).toMatchObject({ code: 1, stderr: "nproc: invalid option -- 'x'\nTry 'nproc --help' for more information.\n" });
+ expect(await run(["nproc", "-x", "--version"])).toMatchObject({ code: 1, stderr: "nproc: invalid option -- 'x'\nTry 'nproc --help' for more information.\n" });
+ expect(await run(["nproc", "--i", "--h"])).toMatchObject(await systemRun(["nproc", "--i", "--h"]));
+ expect(await run(["nproc", "--use=4"])).toMatchObject({ code: 1, stderr: "nproc: unrecognized option '--use=4'\nTry 'nproc --help' for more information.\n" });
+ expect(await run(["nproc", "--ignore=0x2"])).toMatchObject(await systemRun(["nproc", "--ignore=0x2"]));
+ expect(await run(["nproc", "--ignore=1\n2"])).toMatchObject({ code: 1, stderr: `nproc: invalid number: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["nproc", "--ignore=bad", "--help"])).toMatchObject(await systemRun(["nproc", "--ignore=bad", "--help"]));
+ expect(await run(["nproc", "--ignore=-1"])).toMatchObject(await systemRun(["nproc", "--ignore=-1"]));
+ expect(await run(["nproc", "--ignore="])).toMatchObject(await systemRun(["nproc", "--ignore="]));
+ expect(await run(["nproc", "--ignore=", "--help"])).toMatchObject(await systemRun(["nproc", "--ignore=", "--help"]));
+ expect(await run(["nproc", "--ignore= "])).toMatchObject(await systemRun(["nproc", "--ignore= "]));
+ expect(await run(["nproc", "extra"])).toMatchObject(await systemRun(["nproc", "extra"]));
+ expect(await run(["nproc", "extra\narg"])).toMatchObject(await systemRun(["nproc", "extra\narg"]));
+ expect(await run(["nproc", "--all", "extra"])).toMatchObject(await systemRun(["nproc", "--all", "extra"]));
+});
+
+test("uptime reports GNU coreutils uptime format", async () => {
+ expect((await run(["uptime"])).stdout).toMatch(/^ \d{2}:\d{2}:\d{2} up +(?:(?:\d+ days?, +)?\d+:\d{2}|\?\?\?\? days \?\?:\?\?), \d+ users?, load average: \d+\.\d{2}, \d+\.\d{2}, \d+\.\d{2}\n$/);
+ const uptimeHelp = await run(["uptime", "--h"]);
+ expect(uptimeHelp.stdout).not.toContain("--pretty");
+ expect(uptimeHelp.stdout).not.toContain("--raw");
+ expect(uptimeHelp).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: uptime [OPTION]... [FILE]\n") });
+ expect(await run(["uptime", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["uptime", "--pretty"])).toMatchObject({ code: 1, stderr: "uptime: unrecognized option '--pretty'\nTry 'uptime --help' for more information.\n" });
+ expect(await run(["uptime", "--raw", "--help"])).toMatchObject({ code: 1, stderr: "uptime: unrecognized option '--raw'\nTry 'uptime --help' for more information.\n" });
+ expect(await run(["uptime", "-p"])).toMatchObject({ code: 1, stderr: "uptime: invalid option -- 'p'\nTry 'uptime --help' for more information.\n" });
+ const bootRecord = Buffer.alloc(384);
+ bootRecord.writeInt16LE(2, 0);
+ bootRecord.writeInt32LE(Math.trunc(Date.now() / 1000) - (2 * 86400 + 3 * 3600 + 4 * 60), 340);
+ await writeFile(join(dir, "boot-utmp"), bootRecord);
+ expect((await run(["uptime", "boot-utmp"])).stdout).toMatch(/^ \d{2}:\d{2}:\d{2} up 2 days, 3:04, 0 users, load average: \d+\.\d{2}, \d+\.\d{2}, \d+\.\d{2}\n$/);
+ await writeFile(join(dir, "empty-utmp"), "");
+ const emptyUtmp = await run(["uptime", "empty-utmp"]);
+ expect(emptyUtmp).toMatchObject({ code: 1, stderr: "uptime: couldn't get boot time\n" });
+ expect(emptyUtmp.stdout).toMatch(/^ \d{2}:\d{2}:\d{2} up \?\?\?\? days \?\?:\?\?, 0 users, load average: \d+\.\d{2}, \d+\.\d{2}, \d+\.\d{2}\n$/);
+ expect(await run(["uptime", "one", "two"])).toMatchObject({ code: 1, stderr: `uptime: extra operand ${diagnosticQuote("two")}\nTry 'uptime --help' for more information.\n` });
+});
+
+test("pathchk and sync return command statuses", async () => {
+ expect(await run(["pathchk"])).toMatchObject({ code: 1, stderr: "pathchk: missing operand\nTry 'pathchk --help' for more information.\n" });
+ expect(await run(["pathchk", "valid/path"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["pathchk", ""])).toMatchObject({ code: 1, stderr: "pathchk: '': No such file or directory\n" });
+ expect(await run(["pathchk", "-P", ""])).toMatchObject({ code: 1, stderr: "pathchk: empty file name\n" });
+ expect(await run(["pathchk", "x".repeat(300)])).toMatchObject({ code: 1, stderr: `pathchk: ${"x".repeat(300)}: File name too long\n` });
+ await writeFile(join(dir, "plain-file"), "");
+ expect(await run(["pathchk", "plain-file/child"])).toMatchObject({ code: 1, stderr: "pathchk: plain-file/child: Not a directory\n" });
+ expect(await run(["pathchk", "-p", "portable_1"])).toMatchObject({ code: 0 });
+ expect(await run(["pathchk", "-p", "plain-file/child"])).toMatchObject({ code: 0, stderr: "" });
+ expect(await run(["pathchk", "-p", "plain-file/has space"])).toMatchObject(await systemRun(["pathchk", "-p", "plain-file/has space"]));
+ expect(await run(["pathchk", "--p", "componenttoolong"])).toMatchObject(await systemRun(["pathchk", "--p", "componenttoolong"]));
+ const pathchkHelp = await run(["pathchk", "--h", "valid/path"]);
+ const pathchkHelpStdout = pathchkHelp.stdout;
+ expect(pathchkHelp).toMatchObject({ code: 0 });
+ expect(pathchkHelpStdout).toContain("Usage: pathchk [OPTION]... NAME...\n");
+ expect(pathchkHelpStdout).toContain(" -p check for most POSIX systems\n");
+ expect(pathchkHelpStdout).toContain(" -P check for empty names and leading \"-\"\n");
+ expect(pathchkHelpStdout).toContain(" check for all POSIX systems (equivalent to -p -P)\n");
+ expect(await run(["pathchk", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["pathchk", "-x", "--help"])).toMatchObject({ code: 1, stderr: "pathchk: invalid option -- 'x'\nTry 'pathchk --help' for more information.\n" });
+ expect(await run(["pathchk", "--p=1", "valid/path"])).toMatchObject({ code: 1, stderr: "pathchk: option '--portability' doesn't allow an argument\nTry 'pathchk --help' for more information.\n" });
+ expect(await run(["pathchk", "valid/path", "--h"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["pathchk", "valid/path", "--bad"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["pathchk", "--portability", "componenttoolong"])).toMatchObject(await systemRun(["pathchk", "--portability", "componenttoolong"]));
+ expect(await run(["pathchk", "--portability", "plain-file/child"])).toMatchObject({ code: 0, stderr: "" });
+ const longPortable = "x".repeat(300);
+ expect(await run(["pathchk", "--portability", longPortable])).toMatchObject({ code: 1, stderr: `pathchk: limit 255 exceeded by length 300 of file name '${longPortable}'\n` });
+ expect(await run(["pathchk", "--portability", "has space"])).toMatchObject(await systemRun(["pathchk", "--portability", "has space"]));
+ expect(await run(["pathchk", "--portability", "bad:name"])).toMatchObject({ code: 1, stdout: "", stderr: `pathchk: non-portable character ${diagnosticQuote(":")} in file name 'bad:name'\n` });
+ expect(await run(["pathchk", "-p", "a\tb"])).toMatchObject({ code: 1, stdout: "", stderr: `pathchk: non-portable character ${diagnosticQuote("\\t")} in file name 'a'$'\\t''b'\n` });
+ expect(await run(["pathchk", "-p", "a\u0001b"])).toMatchObject({ code: 1, stdout: "", stderr: `pathchk: non-portable character ${diagnosticQuote("\\001")} in file name 'a'$'\\001''b'\n` });
+ expect(await run(["pathchk", "-p", "a'b"])).toMatchObject({ code: 1, stdout: "", stderr: `pathchk: non-portable character ${diagnosticQuote("'")} in file name "a'b"\n` });
+ expect(await run(["pathchk", "-p", "--", "-file"])).toMatchObject({ code: 0, stderr: "" });
+ expect(await run(["pathchk", "-P", "--", "-file"])).toMatchObject({ code: 1, stderr: "pathchk: leading '-' in a component of file name '-file'\n" });
+ expect(await run(["pathchk", "-P", "--", "plain-file/-child"])).toMatchObject({ code: 1, stderr: "pathchk: leading '-' in a component of file name 'plain-file/-child'\n" });
+ expect(await run(["pathchk", "--portability", "--", "-file"])).toMatchObject({ code: 1, stderr: "pathchk: leading '-' in a component of file name '-file'\n" });
+ expect(await run(["pathchk", "-P", "dir//file"])).toMatchObject({ code: 0, stderr: "" });
+ expect(await run(["sync"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "sync-file"), "x");
+ expect(await run(["sync", "sync-file"])).toMatchObject({ code: 0 });
+ expect(await run(["sync", "missing'sync"])).toMatchObject({ code: 1, stdout: "", stderr: "sync: error opening \"missing'sync\": No such file or directory\n" });
+ expect(await run(["sync", "missing\nsync"])).toMatchObject({ code: 1, stdout: "", stderr: "sync: error opening 'missing'$'\\n''sync': No such file or directory\n" });
+ expect(await run(["sync", "-d", "sync-file"])).toMatchObject({ code: 0 });
+ expect(await run(["sync", "--d", "sync-file"])).toMatchObject({ code: 0 });
+ expect(await run(["sync", "sync-file", "--d"])).toMatchObject({ code: 0 });
+ expect(await run(["sync", "sync-file", "-d"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stderr: "sync: error opening '-d': No such file or directory\n" });
+ expect(await run(["sync", "sync-file", "--d"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 1, stderr: "sync: error opening '--d': No such file or directory\n" });
+ expect(await run(["sync", "--file-system", "sync-file"])).toMatchObject({ code: 0 });
+ expect(await run(["sync", "--fi", "sync-file"])).toMatchObject({ code: 0 });
+ const syncHelp = (await run(["sync", "--h", "sync-file"])).stdout;
+ expect(syncHelp).toContain("Usage: sync [OPTION] [FILE]...\n");
+ expect(syncHelp).toContain("If one or more files are specified, sync only them,\nor their containing file systems.\n");
+ expect(syncHelp).toContain("-d, --data sync only file data, no unneeded metadata\n");
+ expect(syncHelp).toContain("-f, --file-system sync the file systems that contain the files\n");
+ expect(await run(["sync", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["sync", "--d=1", "sync-file"])).toMatchObject({ code: 1, stderr: "sync: option '--data' doesn't allow an argument\nTry 'sync --help' for more information.\n" });
+ expect(await run(["sync", "--f=1", "sync-file"])).toMatchObject({ code: 1, stderr: "sync: option '--file-system' doesn't allow an argument\nTry 'sync --help' for more information.\n" });
+ expect(await run(["sync", "--data", "--file-system"])).toMatchObject({ code: 1, stderr: "sync: cannot specify both --data and --file-system\n" });
+ expect(await run(["sync", "-d", "-f", "sync-file"])).toMatchObject({ code: 1, stderr: "sync: cannot specify both --data and --file-system\n" });
+ expect(await run(["sync", "-d"])).toMatchObject({ code: 1 });
+ const missing = await run(["sync", "missing-file"]);
+ expect(missing).toMatchObject({ code: 1 });
+ expect(missing.stderr).toBe("sync: error opening 'missing-file': No such file or directory\n");
+ await symlink("missing-sync-target", join(dir, "sync-dangling"));
+ expect(await run(["sync", "sync-dangling"])).toMatchObject({ code: 1, stdout: "", stderr: "sync: error opening 'sync-dangling': No such file or directory\n" });
+ const mixed = await run(["sync", "missing-a", "sync-file", "missing-b"]);
+ expect(mixed).toMatchObject({ code: 1 });
+ expect(mixed.stderr).toBe("sync: error opening 'missing-a': No such file or directory\nsync: error opening 'missing-b': No such file or directory\n");
+ expect(await run(["mkfifo", "sync-fifo"])).toMatchObject({ code: 0 });
+ const syncFifo = Bun.spawn(["timeout", "2", process.execPath, join(import.meta.dir, "../bin/bnu.js"), "sync", "sync-fifo"], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await syncFifo.exited).toBe(0);
+});
+
+test("ls, stat and du report filesystem data", async () => {
+ await mkdir(join(dir, "tree/sub"), { recursive: true });
+ await writeFile(join(dir, "tree/a.txt"), "abc");
+ await writeFile(join(dir, "tree/sub/b.txt"), "defgh");
+ expect(await run(["stat"])).toMatchObject({ code: 1, stderr: "stat: missing operand\nTry 'stat --help' for more information.\n" });
+ expect(await run(["stat", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: stat [OPTION]... FILE...\n") });
+ expect(await run(["stat", "--he=bad", "tree/a.txt"])).toMatchObject(await systemRun(["stat", "--he=bad", "tree/a.txt"]));
+ expect((await run(["ls", "tree"])).stdout).toBe("a.txt\nsub\n");
+ expect((await run(["ls", "-1", "tree"])).stdout).toBe("a.txt\nsub\n");
+ expect(await run(["ls", "--he=bad", "tree"])).toMatchObject(await systemRun(["ls", "--he=bad", "tree"]));
+ await symlink("ls-loop", join(dir, "ls-loop"));
+ expect(await run(["ls", "-L", "ls-loop"])).toMatchObject({ code: 2, stdout: "", stderr: "ls: cannot access 'ls-loop': Too many levels of symbolic links\n" });
+ const statDefault = await run(["stat", "tree/a.txt"]);
+ expect(statDefault).toMatchObject({ code: 0, stderr: "" });
+ expect(statDefault.stdout).toContain(" File: tree/a.txt\n");
+ expect(statDefault.stdout).toMatch(/Size: 3\s+Blocks: \d+\s+IO Block: \d+\s+regular file/);
+ expect(statDefault.stdout).toMatch(/Device: \d+,\d+\s+Inode: \d+\s+Links: 1/);
+ expect(statDefault.stdout).toMatch(/Access: \(0?644\/-rw-r--r--\)\s+Uid: \(\s*\d+\/\s*.+\)\s+Gid: \(\s*\d+\/\s*.+\)/);
+ expect(statDefault.stdout).toContain("Modify: ");
+ expect(statDefault.stdout).toContain("Change: ");
+ expect(statDefault.stdout).toContain(" Birth: ");
+ expect(await run(["stat", "-c", "%n %s %F", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "tree/a.txt 3 regular file\n" });
+ await writeFile(join(dir, "stat-empty"), "");
+ expect(await run(["stat", "-c", "%n %s %F", "stat-empty"])).toMatchObject({ code: 0, stdout: "stat-empty 0 regular empty file\n" });
+ expect(await run(["stat", "-c", "%u %U %g %G", "tree/a.txt"])).toMatchObject(await systemRun(["/usr/bin/stat", "-c", "%u %U %g %G", "tree/a.txt"]));
+ expect(await run(["stat", "-c", "%N", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "'tree/a.txt'\n" });
+ await symlink("tree/a.txt", join(dir, "stat-link"));
+ await symlink("missing-stat-target", join(dir, "stat-dangling"));
+ expect(await run(["stat", "-c", "%N", "stat-link"])).toMatchObject({ code: 0, stdout: "'stat-link' -> 'tree/a.txt'\n" });
+ expect(await run(["stat", "-L", "-c", "%N", "stat-link"])).toMatchObject({ code: 0, stdout: "'stat-link'\n" });
+ expect(await run(["stat", "-L", "-c", "%n:%s:%F", "stat-link", "stat-dangling"])).toMatchObject({ code: 1, stdout: "stat-link:3:regular file\n", stderr: "stat: cannot statx 'stat-dangling': No such file or directory\n" });
+ expect(await run(["stat", "missing\nstat"])).toMatchObject({ code: 1, stdout: "", stderr: "stat: cannot statx 'missing'$'\\n''stat': No such file or directory\n" });
+ expect(await run(["stat", "missing'stat"])).toMatchObject({ code: 1, stdout: "", stderr: "stat: cannot statx \"missing'stat\": No such file or directory\n" });
+ expect(await run(["stat", "--cached=always", "-c", "%n %s", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "tree/a.txt 3\n" });
+ expect(await run(["stat", "--cached=", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `stat: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--cached")}\nValid arguments are:\n - ${diagnosticQuote("default")}\n - ${diagnosticQuote("never")}\n - ${diagnosticQuote("always")}\nTry 'stat --help' for more information.\n`,
+ });
+ expect(await run(["stat", "--ca=bad", "tree/a.txt"])).toMatchObject(await systemRun(["stat", "--ca=bad", "tree/a.txt"]));
+ expect(await run(["stat", "--cached=bad", "tree/a.txt"])).toMatchObject(await systemRun(["stat", "--cached=bad", "tree/a.txt"]));
+ expect(await run(["stat", "--cached", "bad", "--help"])).toMatchObject(await systemRun(["stat", "--cached", "bad", "--help"]));
+ expect(await run(["stat", "--cached=bad\nmode", "tree/a.txt"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `stat: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--cached")}\nValid arguments are:\n - ${diagnosticQuote("default")}\n - ${diagnosticQuote("never")}\n - ${diagnosticQuote("always")}\nTry 'stat --help' for more information.\n`,
+ });
+ const statFsDefault = await run(["stat", "--file-system", "tree/a.txt"]);
+ expect(statFsDefault).toMatchObject({ code: 0, stderr: "" });
+ expect(statFsDefault.stdout).toContain(' File: "tree/a.txt"\n');
+ expect(statFsDefault.stdout).toMatch(/ID: \S+\s+Namelen: \d+\s+Type: \S+/);
+ expect(statFsDefault.stdout).toMatch(/Block size: \d+\s+Fundamental block size: \d+/);
+ expect(statFsDefault.stdout).toMatch(/Blocks: Total: \d+\s+Free: \d+\s+Available: \d+/);
+ expect(statFsDefault.stdout).toMatch(/Inodes: Total: \d+\s+Free: \d+\n$/);
+ expect(statFsDefault.stdout).not.toContain("regular file");
+ expect(await run(["stat", "-f", "missing'stat"])).toMatchObject({ code: 1, stdout: "", stderr: "stat: cannot read file system information for \"missing'stat\": No such file or directory\n" });
+ expect(await run(["stat", "-f", "-c", "%i", "tree/a.txt"])).toMatchObject(await systemRun(["/usr/bin/stat", "-f", "-c", "%i", "tree/a.txt"]));
+ expect(await run(["stat", "-f", "-c", "%A", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "?\n" });
+ expect(await run(["stat", "-c", "%02s", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "03\n" });
+ expect(await run(["stat", "-c", "%q", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "?\n" });
+ expect(await run(["stat", "-c", "%Q", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "?\n" });
+ expect(await run(["stat", "-c", "%#a", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "0644\n" });
+ expect((await run(["stat", "-c", "%#f %#D", "tree/a.txt"])).stdout.trim()).toMatch(/^0x[0-9a-f]+ 0x[0-9a-f]+$/);
+ expect(await run(["stat", "-c", "%C", "tree/a.txt"])).toMatchObject({ code: 1, stdout: "?\n", stderr: "stat: failed to get security context of 'tree/a.txt': Operation not supported\n" });
+ await writeFile(join(dir, "stat\ncontext"), "x");
+ expect(await run(["stat", "-c", "%C", "stat\ncontext"])).toMatchObject({ code: 1, stdout: "?\n", stderr: "stat: failed to get security context of 'stat'$'\\n''context': Operation not supported\n" });
+ await writeFile(join(dir, "stat'context"), "x");
+ expect(await run(["stat", "-c", "%C", "stat'context"])).toMatchObject({ code: 1, stdout: "?\n", stderr: "stat: failed to get security context of \"stat'context\": Operation not supported\n" });
+ expect((await run(["stat", "-c", "%A %f %i %h %u %g %X %Y %Z", "tree/a.txt"])).stdout.trim()).toMatch(/^-rw-r--r-- [0-9a-f]+ \d+ 1 \d+ \d+ \d+ \d+ \d+$/);
+ expect(await run(["stat", "-c", "%t %T %r %R %Hr %Lr", "/dev/null"])).toMatchObject(await systemRun(["/usr/bin/stat", "-c", "%t %T %r %R %Hr %Lr", "/dev/null"]));
+ expect(await run(["stat", "-c", "%H %L %Hd %Ld %HR %LR %Ht %LT", "tree/a.txt"])).toMatchObject(await systemRun(["/usr/bin/stat", "-c", "%H %L %Hd %Ld %HR %LR %Ht %LT", "tree/a.txt"]));
+ await writeFile(join(dir, "stat-ns"), "");
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456789 +0000", "stat-ns"]);
+ await systemRun(["/usr/bin/touch", "-a", "-d", "2026-01-01 01:02:03.111111111 +0000", "stat-ns"]);
+ expect(await run(["du", "-b", "--time", "--time-style=full-iso", "stat-ns"], "", { env: { TZ: "UTC0" } })).toMatchObject({
+ code: 0,
+ stdout: "0\t2026-01-02 03:04:05.123456789 +0000\tstat-ns\n",
+ });
+ expect(await run(["du", "-b", "--time=atime", "--time-style=full-iso", "stat-ns"], "", { env: { TZ: "UTC0" } })).toMatchObject({
+ code: 0,
+ stdout: "0\t2026-01-01 01:02:03.111111111 +0000\tstat-ns\n",
+ });
+ expect(await run(["du", "-b", "--time=", "stat-ns"])).toMatchObject({
+ code: 1,
+ stderr: `du: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--time")}\nValid arguments are:\n - ${diagnosticQuote("atime")}, ${diagnosticQuote("access")}, ${diagnosticQuote("use")}\n - ${diagnosticQuote("ctime")}, ${diagnosticQuote("status")}\nTry 'du --help' for more information.\n`,
+ });
+ expect(await run(["du", "-b", "--time=bad", "stat-ns"])).toMatchObject(await systemRun(["du", "-b", "--time=bad", "stat-ns"]));
+ expect(await run(["du", "-b", "--time=bad\nmode", "stat-ns"])).toMatchObject({
+ code: 1,
+ stderr: `du: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--time")}\nValid arguments are:\n - ${diagnosticQuote("atime")}, ${diagnosticQuote("access")}, ${diagnosticQuote("use")}\n - ${diagnosticQuote("ctime")}, ${diagnosticQuote("status")}\nTry 'du --help' for more information.\n`,
+ });
+ expect(await run(["du", "-b", "--time", "atime", "stat-ns"], "", { env: { TZ: "UTC0" } })).toMatchObject(await systemRun(["du", "-b", "--time", "atime", "stat-ns"], "", { env: { TZ: "UTC0" } }));
+ expect(await run(["stat", "-c", "%y", "stat-ns"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "2026-01-02 03:04:05.123456789 +0000\n" });
+ expect(await run(["stat", "-c", "%.9Y", "stat-ns"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "1767323045.123456789\n" });
+ expect(await run(["stat", "-c", "%I18.10Y", "stat-ns"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "1767323045.1234567890\n" });
+ await writeFile(join(dir, "stat-negative-ns-a"), "");
+ await writeFile(join(dir, "stat-negative-ns-b"), "");
+ await systemRun(["/usr/bin/touch", "-d", "1969-12-31 23:59:59.123456789 +0000", "stat-negative-ns-a"]);
+ await systemRun(["/usr/bin/touch", "-d", "1969-12-31 23:59:58.876543211 +0000", "stat-negative-ns-b"]);
+ expect(await run(["stat", "-c", "%Y|%.9Y|%y", "stat-negative-ns-a", "stat-negative-ns-b"], "", { env: { TZ: "UTC0" } })).toMatchObject({
+ code: 0,
+ stdout: "-1|-0.876543211|1969-12-31 23:59:59.123456789 +0000\n-2|-1.123456789|1969-12-31 23:59:58.876543211 +0000\n",
+ });
+ expect(await run(["stat", "--printf=%n\\n%s", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "tree/a.txt\n3" });
+ expect(await run(["stat", "--printf=", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await shell('"$BUN" "$BNU" stat --printf "\\\\" . 2>/dev/full')).toMatchObject({ code: 1 });
+ expect(await run(["stat", "--format=%n", "-"], "abc")).toMatchObject({ code: 0, stdout: "-\n" });
+ expect(await run(["stat", "-f", "-"], "abc")).toMatchObject({ code: 1, stdout: "" });
+ expect((await run(["stat", "-f", "-c", "%n %s %T", "."])).stdout.trim()).toMatch(/^\. \d+ \S+$/);
+ expect(await run(["stat", "-f", "-c", "%q", "."])).toMatchObject({ code: 0, stdout: "?\n" });
+ expect((await run(["stat", "-t", "tree/a.txt"])).stdout).toContain("tree/a.txt 3 ");
+ expect(await run(["du", "-b", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "3\ttree/a.txt\n" });
+ expect(await run(["du", "-bc", "tree/a.txt", "tree/sub/b.txt"])).toMatchObject({ code: 0, stdout: "3\ttree/a.txt\n5\ttree/sub/b.txt\n8\ttotal\n" });
+ await mkdir(join(dir, "dot-du/sub"), { recursive: true });
+ await writeFile(join(dir, "dot-du/sub/file"), "x");
+ expect(await run(["du", "-a", "-b", "."], "", { cwd: join(dir, "dot-du") })).toMatchObject({ code: 0, stdout: "1\t./sub/file\n1\t./sub\n1\t.\n" });
+ expect(await run(["du", "--apparent-size", "-B", "2", "tree/sub/b.txt"])).toMatchObject({ code: 0, stdout: "3\ttree/sub/b.txt\n" });
+ expect(await run(["du", "--block-size=human-readable", "tree/sub/b.txt"])).toMatchObject({ code: 0, stdout: "4.0K\ttree/sub/b.txt\n" });
+ expect(await run(["du", "--block-size=si", "tree/sub/b.txt"])).toMatchObject({ code: 0, stdout: "4.1k\ttree/sub/b.txt\n" });
+ expect(await run(["du", "tree/sub/b.txt"], "", { env: { BLOCK_SIZE: "1R" } })).toMatchObject({ code: 0, stdout: "4096\ttree/sub/b.txt\n" });
+ expect(await run(["du", "tree/sub/b.txt"], "", { env: { DU_BLOCK_SIZE: "1KB" } })).toMatchObject({ code: 0, stdout: "5\ttree/sub/b.txt\n" });
+ expect(await run(["du", "tree/sub/b.txt"], "", { env: { POSIXLY_CORRECT: "1" } })).toMatchObject({ code: 0, stdout: "8\ttree/sub/b.txt\n" });
+ expect(await run(["du", "tree/sub/b.txt"], "", { env: { POSIXLY_CORRECT: "1", BLOCK_SIZE: "bad" } })).toMatchObject({ code: 0, stdout: "8\ttree/sub/b.txt\n" });
+ expect(await run(["du", "--block-size=bad", "tree/sub/b.txt"])).toMatchObject({ code: 1, stdout: "", stderr: "du: invalid --block-size argument 'bad'\n" });
+ expect(await run(["du", "--block-size=bad", "--help"])).toMatchObject(await systemRun(["du", "--block-size=bad", "--help"]));
+ expect(await run(["du", "--block-size", "bad", "--help"])).toMatchObject(await systemRun(["du", "--block-size", "bad", "--help"]));
+ expect(await run(["du", "--block-size=1R", "tree/sub/b.txt"])).toMatchObject({ code: 1, stdout: "", stderr: "du: invalid suffix in --block-size argument '1R'\n" });
+ expect(await run(["du", "-Bbad", "tree/sub/b.txt"])).toMatchObject({ code: 1, stdout: "", stderr: "du: invalid -B argument 'bad'\n" });
+ expect(await run(["du", "-Bbad", "--help"])).toMatchObject(await systemRun(["du", "-Bbad", "--help"]));
+ expect(await run(["du", "-B", "bad", "--help"])).toMatchObject(await systemRun(["du", "-B", "bad", "--help"]));
+ expect(await run(["du", "-B1B", "tree/sub/b.txt"])).toMatchObject({ code: 1, stdout: "", stderr: "du: invalid suffix in -B argument '1B'\n" });
+ expect(await run(["du", "--max-depth=bad", "tree"])).toMatchObject(await systemRun(["du", "--max-depth=bad", "tree"]));
+ expect(await run(["du", "--max-depth=bad", "--help"])).toMatchObject({
+ code: 0,
+ stdout: expect.stringContaining("Usage: du [OPTION]... [FILE]...\n"),
+ stderr: `du: invalid maximum depth ${diagnosticQuote("bad")}\n`,
+ });
+ expect(await run(["du", "--max-depth", "bad", "--help"])).toMatchObject({
+ code: 0,
+ stdout: expect.stringContaining("Usage: du [OPTION]... [FILE]...\n"),
+ stderr: `du: invalid maximum depth ${diagnosticQuote("bad")}\n`,
+ });
+ expect(await run(["du", "-dbad", "--help"])).toMatchObject({
+ code: 0,
+ stdout: expect.stringContaining("Usage: du [OPTION]... [FILE]...\n"),
+ stderr: `du: invalid maximum depth ${diagnosticQuote("bad")}\n`,
+ });
+ expect(await run(["du", "-d", "bad", "--help"])).toMatchObject({
+ code: 0,
+ stdout: expect.stringContaining("Usage: du [OPTION]... [FILE]...\n"),
+ stderr: `du: invalid maximum depth ${diagnosticQuote("bad")}\n`,
+ });
+ expect(await run(["du", "--max-depth=1\n2", "tree"])).toMatchObject({ code: 1, stdout: "", stderr: `du: invalid maximum depth ${diagnosticQuote("1\\n2")}\nTry 'du --help' for more information.\n` });
+ expect(await run(["du", "--max-depth=1.5", "tree"])).toMatchObject(await systemRun(["du", "--max-depth=1.5", "tree"]));
+ expect(await run(["du", "-b", "--max-depth=-1", "tree"])).toMatchObject({ code: 0, stdout: "8\ttree\n" });
+ expect(await run(["du", "-b", "-d-1", "tree"])).toMatchObject({ code: 0, stdout: "8\ttree\n" });
+ expect(await run(["du", "-b", "-s", "--max-depth=-1", "tree"])).toMatchObject({ code: 1, stdout: "", stderr: "du: warning: summarizing conflicts with --max-depth=-1\nTry 'du --help' for more information.\n" });
+ expect(await run(["du", "-b", "-s", "--max-depth=1", "tree"])).toMatchObject({ code: 1, stdout: "", stderr: "du: warning: summarizing conflicts with --max-depth=1\nTry 'du --help' for more information.\n" });
+ expect(await run(["du", "-b", "-s", "--max-depth=+1", "tree"])).toMatchObject({ code: 1, stdout: "", stderr: "du: warning: summarizing conflicts with --max-depth=1\nTry 'du --help' for more information.\n" });
+ expect(await run(["du", "--threshold", "bad", "--help"])).toMatchObject(await systemRun(["du", "--threshold", "bad", "--help"]));
+ expect(await run(["du", "-tbad", "--help"])).toMatchObject(await systemRun(["du", "-tbad", "--help"]));
+ expect(await run(["du", "-t", "bad", "--help"])).toMatchObject(await systemRun(["du", "-t", "bad", "--help"]));
+ expect(await run(["du", "--ap", "-B", "2", "tree/sub/b.txt"])).toMatchObject({ code: 0, stdout: "3\ttree/sub/b.txt\n" });
+ expect(await run(["du", "tree/a.txt", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: du [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["du", "--a"])).toMatchObject({
+ code: 1,
+ stderr: "du: option '--a' is ambiguous; possibilities: '--all' '--apparent-size'\nTry 'du --help' for more information.\n",
+ });
+ expect(await run(["du", "--all=bad"])).toMatchObject({
+ code: 1,
+ stderr: "du: option '--all' doesn't allow an argument\nTry 'du --help' for more information.\n",
+ });
+ expect(await run(["du", "-A", "-B", "1", "tree/sub/b.txt"])).toMatchObject({ code: 0, stdout: "5\ttree/sub/b.txt\n" });
+ expect(await run(["du", "--apparent-size", "-m", "tree/sub/b.txt"])).toMatchObject({ code: 0, stdout: "1\ttree/sub/b.txt\n" });
+ const duHelp = (await run(["du", "--help"])).stdout;
+ expect(duHelp).toContain("Usage: du [OPTION]... [FILE]...\n or: du [OPTION]... --files0-from=F\n");
+ for (const option of ["-k", "-m"]) expect(duHelp).toContain(` ${option}\n`);
+ expect(await run(["du", "--apparent-size", "--si", "tree/sub/b.txt"])).toMatchObject({ code: 0, stdout: "5B\ttree/sub/b.txt\n" });
+ expect(await run(["du", "--human", "--apparent", "tree/sub/b.txt"])).toMatchObject({ code: 0, stdout: "5B\ttree/sub/b.txt\n" });
+ await writeFile(join(dir, "decimal-du"), "");
+ await truncate(join(dir, "decimal-du"), 1500);
+ expect(await run(["du", "--apparent-size", "--si", "decimal-du"])).toMatchObject({ code: 0, stdout: "1.5k\tdecimal-du\n" });
+ await mkdir(join(dir, "inode-tree"));
+ await writeFile(join(dir, "inode-tree/file"), "");
+ await link(join(dir, "inode-tree/file"), join(dir, "inode-tree/hardlink"));
+ expect(await run(["du", "--inodes", "inode-tree"])).toMatchObject({ code: 0, stdout: "2\tinode-tree\n" });
+ expect(await run(["du", "--apparent-size", "--inodes", "inode-tree"])).toMatchObject({ code: 0, stdout: "2\tinode-tree\n", stderr: "du: warning: options --apparent-size and -b are ineffective with --inodes\n" });
+ expect(await run(["du", "--inodes", "--count-links", "inode-tree"])).toMatchObject({ code: 0, stdout: "3\tinode-tree\n" });
+ expect(await run(["du", "--inodes", "--threshold=2", "inode-tree"])).toMatchObject({ code: 0, stdout: "2\tinode-tree\n" });
+ expect(await run(["du", "--inodes", "--threshold=1K", "inode-tree"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["du", "--inodes", "--threshold=-1", "inode-tree"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["du", "--inodes", "--threshold=1.5", "inode-tree"])).toMatchObject({ code: 1, stdout: "", stderr: "du: invalid suffix in --threshold argument '1.5'\n" });
+ await writeFile(join(dir, "du-threshold-small"), "12345");
+ await writeFile(join(dir, "du-threshold-large"), "");
+ await truncate(join(dir, "du-threshold-large"), 20480);
+ expect(await run(["du", "-b", "-t", "10000", "du-threshold-small", "du-threshold-large"])).toMatchObject({ code: 0, stdout: "20480\tdu-threshold-large\n" });
+ expect(await run(["du", "-b", "--threshold=bad", "du-threshold-small"])).toMatchObject({ code: 1, stderr: "du: invalid --threshold argument 'bad'\n" });
+ expect(await run(["du", "--threshold=bad", "--help"])).toMatchObject(await systemRun(["du", "--threshold=bad", "--help"]));
+ expect(await run(["du", "-b", "--threshold=1.5K", "du-threshold-small"])).toMatchObject({ code: 1, stderr: "du: invalid suffix in --threshold argument '1.5K'\n" });
+ expect(await run(["du", "-b", "--threshold=1b", "du-threshold-small"])).toMatchObject({ code: 1, stdout: "", stderr: "du: invalid suffix in --threshold argument '1b'\n" });
+ expect(await run(["du", "-b", "--threshold=0R", "du-threshold-small"])).toMatchObject({ code: 0, stdout: "5\tdu-threshold-small\n" });
+ expect(await run(["du", "-b", "--threshold=1R", "du-threshold-small"])).toMatchObject({ code: 1, stdout: "", stderr: "du: --threshold argument '1R' too large\n" });
+ expect(await run(["du", "-b", "--threshold=9223372036854775808", "du-threshold-small"])).toMatchObject({ code: 1, stdout: "", stderr: "du: --threshold argument '9223372036854775808' too large\n" });
+ expect(await run(["du", "-b", "--threshold=-9223372036854775808", "du-threshold-small"])).toMatchObject({ code: 0, stdout: "5\tdu-threshold-small\n" });
+ expect(await run(["du", "-b", "--threshold=-9223372036854775809", "du-threshold-small"])).toMatchObject({ code: 1, stdout: "", stderr: "du: --threshold argument '-9223372036854775809' too large\n" });
+ await mkdir(join(dir, "inode-si"));
+ for (let i = 0; i < 1100; i++) await writeFile(join(dir, "inode-si", `f${i}`), "");
+ expect(await run(["du", "--inodes", "--si", "inode-si"])).toMatchObject({ code: 0, stdout: "1.2k\tinode-si\n" });
+ expect(await run(["du", "-0", "-b", "tree/a.txt"])).toMatchObject({ code: 0, stdout: "3\ttree/a.txt\0" });
+ await writeFile(join(dir, "du-list"), "tree/a.txt\0tree/a.txt\0missing\0");
+ expect(await run(["du", "--files0-from=du-list", "tree/a.txt"])).toMatchObject({ code: 1, stderr: `du: extra operand ${diagnosticQuote("tree/a.txt")}\nfile operands cannot be combined with --files0-from\nTry 'du --help' for more information.\n` });
+ expect(await run(["du", "--files0-from=du-list", "tree/a\nx"])).toMatchObject({ code: 1, stderr: `du: extra operand ${diagnosticQuote("tree/a\\nx")}\nfile operands cannot be combined with --files0-from\nTry 'du --help' for more information.\n` });
+ expect(await run(["du", "-b", "--files0-from=du-list"])).toMatchObject({ code: 1, stdout: "3\ttree/a.txt\n", stderr: "du: cannot access 'missing': No such file or directory\n" });
+ expect(await run(["du", "-b", "missing\nfile"])).toMatchObject({ code: 1, stdout: "", stderr: "du: cannot access 'missing'$'\\n''file': No such file or directory\n" });
+ expect(await run(["du", "-b", "missing'file"])).toMatchObject({ code: 1, stdout: "", stderr: "du: cannot access \"missing'file\": No such file or directory\n" });
+ const duFiles0Raw = Bun.spawn(["/bin/sh", "-c", `name=$(printf 'du-\\377'); printf 'raw\\n' > "$name"; printf '%s\\0' "$name" > du-files0-raw; LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} du -b --files0-from=du-files0-raw >du-files0-raw-out`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await duFiles0Raw.exited).toBe(0);
+ expect(await new Response(duFiles0Raw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "du-files0-raw-out"))]).toEqual([0x34, 0x09, 0x64, 0x75, 0x2d, 0xff, 0x0a]);
+ expect(await run(["du", "-b", "--files0-from=-"], "-")).toMatchObject({ code: 1, stderr: "du: when reading file names from standard input, no file name of '-' allowed\n" });
+ await symlink("du-list-loop", join(dir, "du-list-loop"));
+ expect(await run(["du", "--files0-from=du-list-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "du: cannot open 'du-list-loop' for reading: Too many levels of symbolic links\n" });
+ await mkdir(join(dir, "du-list-dir"));
+ expect(await run(["du", "--files0-from=du-list-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "du: du-list-dir: read error: Is a directory\n" });
+ await mkdir(join(dir, "du list dir"));
+ expect(await run(["du", "--files0-from=du list dir"])).toMatchObject({ code: 1, stdout: "", stderr: "du: 'du list dir': read error: Is a directory\n" });
+ expect(await run(["du", "--exclude-from=missing-exclude", "tree"])).toMatchObject({ code: 1, stdout: "", stderr: "du: missing-exclude: No such file or directory\nTry 'du --help' for more information.\n" });
+ expect(await run(["du", "--exclude-from=du-list-dir", "tree"])).toMatchObject({ code: 1, stdout: "", stderr: "du: du-list-dir: Is a directory\nTry 'du --help' for more information.\n" });
+ const duExcludeReplacement = Bun.spawn(["/bin/sh", "-c", `dir=$(printf 'du-excl-\\377'); child=$(printf 'x-\\377'); mkdir "$dir"; printf data > "$dir/$child"; printf '%s\\0' "$dir" > du-excl-roots0; printf 'x-\\357\\277\\275\\n' > du-excl-replacement; LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} du -a -b --files0-from=du-excl-roots0 --exclude-from=du-excl-replacement >du-excl-replacement-out`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await duExcludeReplacement.exited).toBe(0);
+ expect(await new Response(duExcludeReplacement.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "du-excl-replacement-out"))]).toEqual([0x34, 0x09, 0x64, 0x75, 0x2d, 0x65, 0x78, 0x63, 0x6c, 0x2d, 0xff, 0x2f, 0x78, 0x2d, 0xff, 0x0a, 0x34, 0x09, 0x64, 0x75, 0x2d, 0x65, 0x78, 0x63, 0x6c, 0x2d, 0xff, 0x0a]);
+ expect((await run(["du", "-ch", "tree/a.txt", "tree/sub/b.txt"])).stdout).toContain("total\n");
+ expect((await run(["du", "-a", "-b", "tree"])).stdout.split("\n").filter(Boolean).map((line) => line.split("\t")[1])).toEqual(["tree/sub/b.txt", "tree/sub", "tree/a.txt", "tree"]);
+ expect((await run(["du", "-b", "--max-depth=1", "tree"])).stdout.split("\n").filter(Boolean).map((line) => line.split("\t")[1])).toEqual(["tree/sub", "tree"]);
+ expect((await run(["du", "-b", "--max=1", "tree"])).stdout.split("\n").filter(Boolean).map((line) => line.split("\t")[1])).toEqual(["tree/sub", "tree"]);
+ expect((await run(["du", "-b", "--exclude=sub", "tree"])).stdout.split("\n").filter(Boolean).map((line) => line.split("\t")[1])).toEqual(["tree"]);
+ await symlink("tree", join(dir, "du-tree-link"));
+ expect(await run(["du", "-b", "-s", "du-tree-link"])).toMatchObject({ code: 0, stdout: "4\tdu-tree-link\n" });
+ expect(await run(["du", "-b", "-s", "-D", "du-tree-link"])).toMatchObject({ code: 0, stdout: "8\tdu-tree-link\n" });
+ expect(await run(["du", "-b", "-s", "--dereference-arg", "du-tree-link"])).toMatchObject({ code: 0, stdout: "8\tdu-tree-link\n" });
+ expect(await run(["du", "-b", "-s", "-H", "du-tree-link"])).toMatchObject({ code: 0, stdout: "8\tdu-tree-link\n" });
+ expect(await run(["du", "-b", "-s", "-L", "--no-dereference", "du-tree-link"])).toMatchObject({ code: 0, stdout: "4\tdu-tree-link\n" });
+ expect(await run(["du", "-b", "-s", "--no-dereference", "-L", "du-tree-link"])).toMatchObject({ code: 0, stdout: "8\tdu-tree-link\n" });
+ expect(await run(["du", "-b", "-s", "-D", "--no-dereference", "du-tree-link"])).toMatchObject({ code: 0, stdout: "4\tdu-tree-link\n" });
+ expect(await run(["du", "-b", "-s", "-L", "-P", "du-tree-link"])).toMatchObject({ code: 0, stdout: "4\tdu-tree-link\n" });
+ expect((await run(["du", "-D", "-b", "du-tree-link"])).stdout.split("\n").filter(Boolean).map((line) => line.split("\t")[1])).toEqual(["du-tree-link/sub", "du-tree-link"]);
+ expect((await run(["du", "-b", "--exclude=[ab].txt", "tree"])).stdout.split("\n").filter(Boolean).map((line) => line.split("\t")[1])).toEqual(["tree/sub", "tree"]);
+ await mkdir(join(dir, "du-inacc/sub"), { recursive: true });
+ const readableSummary = await run(["du", "-s", "du-inacc"]);
+ try {
+ await chmod(join(dir, "du-inacc/sub"), 0);
+ const unreadableSummary = await run(["du", "-s", "du-inacc"]);
+ expect(unreadableSummary.code).toBe(1);
+ expect(unreadableSummary.stdout).toBe(readableSummary.stdout);
+ } finally {
+ await chmod(join(dir, "du-inacc/sub"), 0o755).catch(() => {});
+ }
+ await symlink("/dev/shm", join(dir, "du-other-fs"));
+ expect((await run(["du", "-xL", "du-other-fs"])).stdout.split("\n").filter(Boolean).map((line) => line.split("\t")[1])).toEqual(["du-other-fs"]);
+});
+
+test("ls supports common listing modes", async () => {
+ await mkdir(join(dir, "tree/sub"), { recursive: true });
+ await writeFile(join(dir, "tree/.hidden"), "x");
+ await writeFile(join(dir, "tree/small"), "x");
+ await writeFile(join(dir, "tree/large"), "xxxx");
+ await writeFile(join(dir, "tree/sub/nested"), "n");
+ await run(["chmod", "u+x", "tree/small"]);
+ const lsHelp = await run(["ls", "--help"]);
+ expect(lsHelp.code).toBe(0);
+ for (const option of ["-1", "-C", "-S", "-U", "-X", "-c", "-g", "-l", "-m", "-o", "-p", "-t", "-u", "-v", "-x"]) expect(lsHelp.stdout).toContain(` ${option}\n`);
+ expect((await run(["ls", "-a", "tree"])).stdout).toBe(".\n..\n.hidden\nlarge\nsmall\nsub\n");
+ expect(new Set((await run(["ls", "-f", "tree"])).stdout.split("\n").filter(Boolean))).toEqual(new Set([".", "..", ".hidden", "large", "small", "sub"]));
+ expect((await run(["ls", "-A", "tree"])).stdout).toBe(".hidden\nlarge\nsmall\nsub\n");
+ expect((await run(["ls", "-1", "-I", "l*", "-I", "small", "tree"])).stdout).toBe("sub\n");
+ expect((await run(["ls", "-F", "tree"])).stdout).toBe("large\nsmall*\nsub/\n");
+ expect((await run(["ls", "--classify=always", "tree"])).stdout).toBe("large\nsmall*\nsub/\n");
+ expect((await run(["ls", "--classify=yes", "tree"])).stdout).toBe("large\nsmall*\nsub/\n");
+ expect((await run(["ls", "--classify=force", "tree"])).stdout).toBe("large\nsmall*\nsub/\n");
+ expect((await run(["ls", "--classify=never", "tree"])).stdout).toBe("large\nsmall\nsub\n");
+ expect((await run(["ls", "--classify=no", "tree"])).stdout).toBe("large\nsmall\nsub\n");
+ expect((await run(["ls", "--classify=none", "tree"])).stdout).toBe("large\nsmall\nsub\n");
+ expect((await run(["ls", "--classify=tty", "tree"])).stdout).toBe("large\nsmall\nsub\n");
+ expect((await run(["ls", "--classify=if-tty", "tree"])).stdout).toBe("large\nsmall\nsub\n");
+ expect((await run(["ls", "--indicator-style=file-type", "tree"])).stdout).toBe("large\nsmall\nsub/\n");
+ expect(await run(["ls", "--classify=bad", "tree"])).toMatchObject(await systemRun(["ls", "--classify=bad", "tree"]));
+ expect(await run(["ls", "--classify=bad", "--help"])).toMatchObject(await systemRun(["ls", "--classify=bad", "--help"]));
+ expect(await run(["ls", "--color=", "tree"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ls: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--color")}\nValid arguments are:\n - ${diagnosticQuote("always")}, ${diagnosticQuote("yes")}, ${diagnosticQuote("force")}\n - ${diagnosticQuote("never")}, ${diagnosticQuote("no")}, ${diagnosticQuote("none")}\n - ${diagnosticQuote("auto")}, ${diagnosticQuote("tty")}, ${diagnosticQuote("if-tty")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect(await run(["ls", "--indicator-style=", "tree"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ls: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--indicator-style")}\nValid arguments are:\n - ${diagnosticQuote("none")}\n - ${diagnosticQuote("slash")}\n - ${diagnosticQuote("file-type")}\n - ${diagnosticQuote("classify")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect(await run(["ls", "--indicator-style=bad", "tree"])).toMatchObject(await systemRun(["ls", "--indicator-style=bad", "tree"]));
+ expect(await run(["ls", "--indicator-style=bad", "--help"])).toMatchObject(await systemRun(["ls", "--indicator-style=bad", "--help"]));
+ expect(await run(["ls", "--format=bad", "tree"])).toMatchObject(await systemRun(["ls", "--format=bad", "tree"]));
+ expect(await run(["ls", "--format=bad", "--help"])).toMatchObject(await systemRun(["ls", "--format=bad", "--help"]));
+ expect((await run(["ls", "-1", "--hyperlink=always", "tree/small"])).stdout).toBe(`\x1b]8;;file://${osHostname()}${join(dir, "tree/small")}\x1b\\tree/small\x1b]8;;\x1b\\\n`);
+ expect((await run(["ls", "-Z", "tree/small"])).stdout).toBe("? tree/small\n");
+ expect((await run(["ls", "-Zi", "tree/small"])).stdout).toMatch(/^\d+ \? tree\/small\n$/);
+ expect((await run(["ls", "-Zs", "tree/small"])).stdout).toBe("4 ? tree/small\n");
+ expect((await run(["ls", "-lZ", "tree/small"])).stdout).toMatch(/^-rwxr--r--\s+1\s+\S+\s+\S+\s+\?\s+1\s+\S+\s+\d+\s+\d\d:\d\d tree\/small\n$/);
+ const diredContext = (await run(["ls", "-lZ", "--dired", "tree/small"])).stdout;
+ const diredContextMatch = diredContext.match(/\/\/DIRED\/\/ (\d+) (\d+)\n/);
+ expect(diredContextMatch).not.toBeNull();
+ expect(Buffer.from(diredContext).subarray(Number(diredContextMatch[1]), Number(diredContextMatch[2])).toString()).toBe("tree/small");
+ expect(await run(["ls", "--hyperlink=bad", "tree"])).toMatchObject(await systemRun(["ls", "--hyperlink=bad", "tree"]));
+ expect(await run(["ls", "--hyperlink=bad", "--help"])).toMatchObject(await systemRun(["ls", "--hyperlink=bad", "--help"]));
+ expect(await run(["ls", "--hyper=bad", "tree"])).toMatchObject(await systemRun(["ls", "--hyper=bad", "tree"]));
+ expect(await run(["ls", "--hy=bad", "--help"])).toMatchObject(await systemRun(["ls", "--hy=bad", "--help"]));
+ expect(await run(["ls", "--hyperlink=", "tree"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ls: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--hyperlink")}\nValid arguments are:\n - ${diagnosticQuote("always")}, ${diagnosticQuote("yes")}, ${diagnosticQuote("force")}\n - ${diagnosticQuote("never")}, ${diagnosticQuote("no")}, ${diagnosticQuote("none")}\n - ${diagnosticQuote("auto")}, ${diagnosticQuote("tty")}, ${diagnosticQuote("if-tty")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect(await run(["ls", "--color=bad", "tree"])).toMatchObject(await systemRun(["ls", "--color=bad", "tree"]));
+ expect(await run(["ls", "--color=bad", "--help"])).toMatchObject(await systemRun(["ls", "--color=bad", "--help"]));
+ expect(await run(["ls", "--sor=bad", "tree"])).toMatchObject(await systemRun(["ls", "--sor=bad", "tree"]));
+ expect(await run(["ls", "--wid=bad", "tree"])).toMatchObject(await systemRun(["ls", "--wid=bad", "tree"]));
+ expect(await run(["ls", "--block-size=bad", "--help"])).toMatchObject(await systemRun(["ls", "--block-size=bad", "--help"]));
+ expect(await run(["ls", "--block-size", "bad", "--help"])).toMatchObject(await systemRun(["ls", "--block-size", "bad", "--help"]));
+ expect(await run(["ls", "--width=bad", "--help"])).toMatchObject(await systemRun(["ls", "--width=bad", "--help"]));
+ expect(await run(["ls", "--width", "bad", "--help"])).toMatchObject(await systemRun(["ls", "--width", "bad", "--help"]));
+ expect(await run(["ls", "--tabsize=bad", "--help"])).toMatchObject(await systemRun(["ls", "--tabsize=bad", "--help"]));
+ expect(await run(["ls", "--tabsize", "bad", "--help"])).toMatchObject(await systemRun(["ls", "--tabsize", "bad", "--help"]));
+ expect(await run(["ls", "--time=bad", "--help"])).toMatchObject(await systemRun(["ls", "--time=bad", "--help"]));
+ await mkdir(join(dir, "ls-loop-tree"));
+ await symlink("loop", join(dir, "ls-loop-tree/loop"));
+ const lsLongLoop = await run(["ls", "-lL", "ls-loop-tree"]);
+ expect(lsLongLoop.code).toBe(1);
+ expect(lsLongLoop.stderr).toContain("ls: cannot access 'ls-loop-tree/loop': Too many levels of symbolic links\n");
+ expect(lsLongLoop.stdout).toContain("l?????????");
+ expect(lsLongLoop.stdout).toMatch(/^l\?{9}\s+\?\s+\?\s+\?\s+\?\s+\?\s+loop$/m);
+ expect((await run(["ls", "--file-type", "tree"])).stdout).toBe("large\nsmall\nsub/\n");
+ await mkdir(join(dir, "quote"));
+ await writeFile(join(dir, "quote/name with spaces"), "x");
+ await writeFile(join(dir, "quote/name'with-quote"), "x");
+ await writeFile(join(dir, "quote/line\nbreak"), "x");
+ await writeFile(join(dir, "quote/q\x07"), "x");
+ await writeFile(join(dir, "quote/plain"), "x");
+ expect((await run(["ls", "-1", "--quoting-style=shell", "quote/name with spaces", "quote/plain"])).stdout).toBe("'quote/name with spaces'\nquote/plain\n");
+ expect((await run(["ls", "-1", "--quoting-style=shell", "quote/name'with-quote"])).stdout).toBe("\"quote/name'with-quote\"\n");
+ expect((await run(["ls", "-1", "--quoting-style=shell-always", "quote/plain"])).stdout).toBe("'quote/plain'\n");
+ expect((await run(["ls", "-1", "--quoting-style=shell-al", "-q", "quote/q\x07"])).stdout).toBe("'quote/q?'\n");
+ expect((await run(["ls", "-1", "--quoting-style=shell-escape", "quote/line\nbreak"])).stdout).toBe("'quote/line'$'\\n''break'\n");
+ expect((await run(["ls", "-1", "--quoting-style=shell-escape-always", "quote/plain"])).stdout).toBe("'quote/plain'\n");
+ expect((await run(["ls", "-1", "--quoting-style=escape", "quote/name with spaces"])).stdout).toBe("quote/name\\ with\\ spaces\n");
+ expect(await run(["ls", "--quoting-style=bad", "quote/plain"])).toMatchObject({
+ code: 1,
+ stderr: `ls: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("--quoting-style")}\nValid arguments are:\n - ${diagnosticQuote("literal")}\n - ${diagnosticQuote("shell")}\n - ${diagnosticQuote("shell-always")}\n - ${diagnosticQuote("shell-escape")}\n - ${diagnosticQuote("shell-escape-always")}\n - ${diagnosticQuote("c")}\n - ${diagnosticQuote("c-maybe")}\n - ${diagnosticQuote("escape")}\n - ${diagnosticQuote("locale")}\n - ${diagnosticQuote("clocale")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect(await run(["ls", "--quoting-style=bad", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ls: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("--quoting-style")}\nValid arguments are:\n - ${diagnosticQuote("literal")}\n - ${diagnosticQuote("shell")}\n - ${diagnosticQuote("shell-always")}\n - ${diagnosticQuote("shell-escape")}\n - ${diagnosticQuote("shell-escape-always")}\n - ${diagnosticQuote("c")}\n - ${diagnosticQuote("c-maybe")}\n - ${diagnosticQuote("escape")}\n - ${diagnosticQuote("locale")}\n - ${diagnosticQuote("clocale")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect(await run(["ls", "--quoting-style=", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ls: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--quoting-style")}\nValid arguments are:\n - ${diagnosticQuote("literal")}\n - ${diagnosticQuote("shell")}\n - ${diagnosticQuote("shell-always")}\n - ${diagnosticQuote("shell-escape")}\n - ${diagnosticQuote("shell-escape-always")}\n - ${diagnosticQuote("c")}\n - ${diagnosticQuote("c-maybe")}\n - ${diagnosticQuote("escape")}\n - ${diagnosticQuote("locale")}\n - ${diagnosticQuote("clocale")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect(await run(["ls", "--quoting-style=bad\nmode", "quote/plain"])).toMatchObject({
+ code: 1,
+ stderr: `ls: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--quoting-style")}\nValid arguments are:\n - ${diagnosticQuote("literal")}\n - ${diagnosticQuote("shell")}\n - ${diagnosticQuote("shell-always")}\n - ${diagnosticQuote("shell-escape")}\n - ${diagnosticQuote("shell-escape-always")}\n - ${diagnosticQuote("c")}\n - ${diagnosticQuote("c-maybe")}\n - ${diagnosticQuote("escape")}\n - ${diagnosticQuote("locale")}\n - ${diagnosticQuote("clocale")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect(await run(["ls", "--quoting-style=shell-e", "quote/plain"])).toMatchObject({
+ code: 1,
+ stderr: `ls: ambiguous argument ${diagnosticQuote("shell-e")} for ${diagnosticQuote("--quoting-style")}\nValid arguments are:\n - ${diagnosticQuote("literal")}\n - ${diagnosticQuote("shell")}\n - ${diagnosticQuote("shell-always")}\n - ${diagnosticQuote("shell-escape")}\n - ${diagnosticQuote("shell-escape-always")}\n - ${diagnosticQuote("c")}\n - ${diagnosticQuote("c-maybe")}\n - ${diagnosticQuote("escape")}\n - ${diagnosticQuote("locale")}\n - ${diagnosticQuote("clocale")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect((await run(["ls", "-1", "--quoting-style=shell", "quote/q\x07"])).stdout).toBe("quote/q\x07\n");
+ expect((await run(["ls", "-1", "-q", "--quoting-style=shell", "quote/q\x07"])).stdout).toBe("quote/q?\n");
+ expect((await run(["ls", "-1", "--escape", "quote/q\x07"])).stdout).toBe("quote/q\\a\n");
+ expect((await run(["ls", "-1", "-b", "quote/name with spaces"])).stdout).toBe("quote/name\\ with\\ spaces\n");
+ expect((await run(["ls", "-1", "--hide-control-chars", "quote/q\x07"])).stdout).toBe("quote/q?\n");
+ expect((await run(["ls", "-1", "--show-control-chars", "quote/q\x07"])).stdout).toBe("quote/q\x07\n");
+ expect((await run(["ls", "-1", "--literal", "quote/q\x07"])).stdout).toBe("quote/q\x07\n");
+ expect((await run(["ls", "-p", "tree"])).stdout).toBe("large\nsmall\nsub/\n");
+ expect((await run(["ls", "-S", "tree"])).stdout).toBe("sub\nlarge\nsmall\n");
+ expect((await run(["ls", "-Sr", "tree"])).stdout).toBe("small\nlarge\nsub\n");
+ await mkdir(join(dir, "size-tie"));
+ await writeFile(join(dir, "size-tie/b.txt"), "x");
+ await writeFile(join(dir, "size-tie/a.log"), "x");
+ await writeFile(join(dir, "size-tie/c"), "x");
+ expect((await run(["ls", "-1S", "size-tie"])).stdout).toBe("a.log\nb.txt\nc\n");
+ expect((await run(["ls", "-1Sr", "size-tie"])).stdout).toBe("c\nb.txt\na.log\n");
+ expect((await run(["ls", "--group-directories-first", "tree"])).stdout).toBe("sub\nlarge\nsmall\n");
+ expect((await run(["ls", "--sort=width", "tree"])).stdout).toBe("sub\nlarge\nsmall\n");
+ expect(await run(["ls", "--sort=", "tree"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ls: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--sort")}\nValid arguments are:\n - ${diagnosticQuote("none")}\n - ${diagnosticQuote("size")}\n - ${diagnosticQuote("time")}\n - ${diagnosticQuote("version")}\n - ${diagnosticQuote("extension")}\n - ${diagnosticQuote("name")}\n - ${diagnosticQuote("width")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect(await run(["ls", "--sort=bad", "tree"])).toMatchObject(await systemRun(["ls", "--sort=bad", "tree"]));
+ expect(await run(["ls", "--sort", "bad", "--help"])).toMatchObject(await systemRun(["ls", "--sort", "bad", "--help"]));
+ expect((await run(["ls", "-w2", "-m", "tree/large", "tree/small"])).stdout).toBe("tree/large,\ntree/small\n");
+ expect((await run(["ls", "-sm", "tree/large", "tree/small"])).stdout).toContain(", ");
+ await writeFile(join(dir, "ls-comma-a-empty"), "");
+ await writeFile(join(dir, "ls-comma-z-big"), "x".repeat(2000));
+ expect((await run(["ls", "-sm", "ls-comma-a-empty", "ls-comma-z-big"])).stdout).toMatch(/^0 ls-comma-a-empty, \d+ ls-comma-z-big\n$/);
+ await mkdir(join(dir, "columns"));
+ await writeFile(join(dir, "columns/a"), "x");
+ await writeFile(join(dir, "columns/big"), "x");
+ await writeFile(join(dir, "columns/link"), "x");
+ await writeFile(join(dir, "columns/linktarget"), "x");
+ expect((await run(["ls", "-C", "columns"])).stdout).toBe("a big\tlink linktarget\n");
+ expect((await run(["ls", "-x", "columns"])).stdout).toBe("a big\tlink linktarget\n");
+ expect((await run(["ls", "-C", "-w20", "columns"])).stdout).toBe("a link\nbig linktarget\n");
+ expect((await run(["ls", "-x", "-w20", "columns"])).stdout).toBe("a big\nlink linktarget\n");
+ expect((await run(["ls", "-C", "--tabsize=0", "columns"])).stdout).toBe("a big link linktarget\n");
+ expect((await run(["ls", "-C", "--tabsize=2", "columns"])).stdout).toBe("a big\tlink\tlinktarget\n");
+ expect(await run(["ls", "--width=bad"])).toMatchObject(await systemRun(["ls", "--width=bad"]));
+ expect(await run(["ls", "-wbad", "--help"])).toMatchObject(await systemRun(["ls", "-wbad", "--help"]));
+ expect(await run(["ls", "-w", "bad", "--help"])).toMatchObject(await systemRun(["ls", "-w", "bad", "--help"]));
+ expect(await run(["ls", "--width=1\n2"])).toMatchObject({ code: 2, stdout: "", stderr: `ls: invalid line width: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["ls", "--tabsize=bad"])).toMatchObject(await systemRun(["ls", "--tabsize=bad"]));
+ expect(await run(["ls", "-Tbad", "--help"])).toMatchObject(await systemRun(["ls", "-Tbad", "--help"]));
+ expect(await run(["ls", "-T", "bad", "--help"])).toMatchObject(await systemRun(["ls", "-T", "bad", "--help"]));
+ expect(await run(["ls", "--tabsize=1\n2"])).toMatchObject({ code: 2, stdout: "", stderr: `ls: invalid tab size: ${diagnosticQuote("1\\n2")}\n` });
+ await mkdir(join(dir, "longopts"));
+ await writeFile(join(dir, "longopts/decimal-size"), "");
+ await truncate(join(dir, "longopts/decimal-size"), 1500);
+ expect((await run(["ls", "-lh", "--si", "longopts/decimal-size"])).stdout).toContain("1.5k");
+ expect((await run(["ls", "-lh", "--time-style=+:T:", "tree/small"])).stdout.trim().split(/\s+/)[4]).toBe("1");
+ const smallStat = await lstat(join(dir, "tree/small"));
+ const smallBlocks512 = smallStat.blocks ?? Math.ceil(smallStat.size / 512);
+ const smallBlocks = Math.ceil(smallBlocks512 / 2);
+ expect((await run(["ls", "-s", "tree/small"])).stdout.trim().split(/\s+/)[0]).toBe(String(smallBlocks));
+ expect((await run(["ls", "-s", "--block-size=1", "tree/small"])).stdout.trim().split(/\s+/)[0]).toBe(String(smallBlocks512 * 512));
+ expect((await run(["ls", "-s", "--block-size=human-readable", "tree/small"])).stdout.trim().split(/\s+/)[0]).toBe("4.0K");
+ expect((await run(["ls", "-s", "--block-size=si", "tree/small"])).stdout.trim().split(/\s+/)[0]).toBe("4.1k");
+ expect((await run(["ls", "-s", "tree/small"], "", { env: { BLOCK_SIZE: "1R" } })).stdout.trim().split(/\s+/)[0]).toBe(String(smallBlocks512 * 512));
+ expect((await run(["ls", "-s", "tree/small"], "", { env: { LS_BLOCK_SIZE: "bad" } })).stdout.trim().split(/\s+/)[0]).toBe(String(smallBlocks));
+ expect((await run(["ls", "-og", "longopts/decimal-size"], "", { env: { BLOCKSIZE: "512" } })).stdout.trim().split(/\s+/)[2]).toBe("1500");
+ expect((await run(["ls", "-og", "longopts/decimal-size"], "", { env: { BLOCKSIZE: "human-readable" } })).stdout.trim().split(/\s+/)[2]).toBe("1500");
+ expect((await run(["ls", "-s", "tree/small"], "", { env: { BLOCKSIZE: "si" } })).stdout.trim().split(/\s+/)[0]).toBe("4.1k");
+ expect((await run(["ls", "-og", "longopts/decimal-size"], "", { env: { BLOCK_SIZE: "bad" } })).stdout.trim().split(/\s+/)[2]).toBe("2");
+ expect((await run(["ls", "-og", "longopts/decimal-size"], "", { env: { LS_BLOCK_SIZE: "bad" } })).stdout.trim().split(/\s+/)[2]).toBe("2");
+ expect(await run(["ls", "-s", "--block-size=1R", "tree/small"])).toMatchObject({ code: 2, stdout: "", stderr: "ls: invalid suffix in --block-size argument '1R'\n" });
+ expect((await run(["ls", "-l", "--no-group", "longopts/decimal-size"])).stdout.trim().split(/\s+/).length).toBe(8);
+ expect((await run(["ls", "-l", "longopts/decimal-size"], "", { env: { BLOCK_SIZE: "si" } })).stdout.trim().split(/\s+/)[4]).toBe("1.5k");
+ const currentUserName = (await systemRun(["id", "-un"])).stdout.trim();
+ const currentGroupName = (await systemRun(["id", "-gn"])).stdout.trim();
+ const currentUid = String(process.getuid?.() ?? (await stat(join(dir, "longopts/decimal-size"))).uid);
+ const currentGid = String(process.getgid?.() ?? (await stat(join(dir, "longopts/decimal-size"))).gid);
+ const longNameFields = (await run(["ls", "-l", "longopts/decimal-size"])).stdout.trim().split(/\s+/);
+ expect(longNameFields[2]).toBe(currentUserName);
+ expect(longNameFields[3]).toBe(currentGroupName);
+ expect((await run(["ls", "-l", "--time-style=+:T:", "longopts/decimal-size"])).stdout).toBe(`-rw-r--r-- 1 ${currentUserName} ${currentGroupName} 1500 :T: longopts/decimal-size\n`);
+ const numericNameFields = (await run(["ls", "--numeric-uid-gid", "longopts/decimal-size"])).stdout.trim().split(/\s+/);
+ expect(numericNameFields[0]).toBe("-rw-r--r--");
+ expect(numericNameFields[2]).toBe(currentUid);
+ expect(numericNameFields[3]).toBe(currentGid);
+ expect((await run(["ls", "-l", "--author", "longopts/decimal-size"])).stdout.trim().split(/\s+/).length).toBe(10);
+ expect(await run(["ls", "--kibibytes", "longopts/decimal-size"])).toMatchObject({ code: 0 });
+ expect(await run(["ls", "-w-1"])).toMatchObject({ code: 2 });
+ expect(await run(["ls", "-w08"])).toMatchObject({ code: 2 });
+ expect(await run(["ls", "-T0x10", "-w010", "-x", "tree/large", "tree/small"])).toMatchObject({ code: 0 });
+ expect((await run(["ls", "-w0", "-x", "-T1", "tree/large", "tree/small"])).stdout).toBe("tree/large tree/small\n");
+ expect((await run(["ls", "-w4", "-x", "-T0", "tree/large", "tree/small"])).stdout).toBe("tree/large\ntree/small\n");
+ expect((await run(["ls", "--format=single-column", "tree/large", "tree/small"])).stdout).toBe("tree/large\ntree/small\n");
+ expect((await run(["ls", "--format=commas", "tree/large", "tree/small"])).stdout).toBe("tree/large, tree/small\n");
+ expect(await run(["ls", "--format=", "tree"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ls: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--format")}\nValid arguments are:\n - ${diagnosticQuote("verbose")}, ${diagnosticQuote("long")}\n - ${diagnosticQuote("commas")}\n - ${diagnosticQuote("horizontal")}, ${diagnosticQuote("across")}\n - ${diagnosticQuote("vertical")}\n - ${diagnosticQuote("single-column")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect((await run(["ls", "-l", "-C", "tree/large", "tree/small"])).stdout).toBe("tree/large tree/small\n");
+ expect((await run(["ls", "-C", "--format=single-column", "tree/large", "tree/small"])).stdout).toBe("tree/large\ntree/small\n");
+ await run(["touch", "-d", "2020-01-01T00:00:00Z", "tree/small"]);
+ await run(["touch", "-d", "2020-01-02T00:00:00Z", "tree/large"]);
+ expect((await run(["ls", "-t", "tree/small", "tree/large"])).stdout).toBe("tree/large\ntree/small\n");
+ await mkdir(join(dir, "time-sort"));
+ await writeFile(join(dir, "time-sort/a"), "x");
+ await writeFile(join(dir, "time-sort/b"), "x");
+ await writeFile(join(dir, "time-sort/c"), "x");
+ await run(["touch", "-d", "2020-01-03T00:00:00Z", "time-sort/c", "time-sort/a", "time-sort/b"]);
+ expect((await run(["ls", "-1t", "time-sort/a", "time-sort/b", "time-sort/c"])).stdout).toBe("time-sort/a\ntime-sort/b\ntime-sort/c\n");
+ expect((await run(["ls", "-1rt", "time-sort/a", "time-sort/b", "time-sort/c"])).stdout).toBe("time-sort/c\ntime-sort/b\ntime-sort/a\n");
+ await run(["touch", "-d", "2020-01-04T00:00:00Z", "time-sort/c"]);
+ expect((await run(["ls", "-1t", "--sort=name", "time-sort/a", "time-sort/b", "time-sort/c"])).stdout).toBe("time-sort/a\ntime-sort/b\ntime-sort/c\n");
+ expect((await run(["ls", "-1U", "--sort=name", "time-sort/c", "time-sort/a", "time-sort/b"])).stdout).toBe("time-sort/a\ntime-sort/b\ntime-sort/c\n");
+ expect((await run(["ls", "--time=mtime", "time-sort/a", "time-sort/b", "time-sort/c"])).stdout).toBe("time-sort/c\ntime-sort/a\ntime-sort/b\n");
+ expect(await run(["ls", "--time=", "time-sort/a"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ls: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--time")}\nValid arguments are:\n - ${diagnosticQuote("atime")}, ${diagnosticQuote("access")}, ${diagnosticQuote("use")}\n - ${diagnosticQuote("ctime")}, ${diagnosticQuote("status")}\n - ${diagnosticQuote("mtime")}, ${diagnosticQuote("modification")}\n - ${diagnosticQuote("birth")}, ${diagnosticQuote("creation")}\nTry 'ls --help' for more information.\n`,
+ });
+ expect(await run(["ls", "--time=bad", "time-sort/a"])).toMatchObject({
+ code: 1,
+ stderr: `ls: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("--time")}\nValid arguments are:\n - ${diagnosticQuote("atime")}, ${diagnosticQuote("access")}, ${diagnosticQuote("use")}\n - ${diagnosticQuote("ctime")}, ${diagnosticQuote("status")}\n - ${diagnosticQuote("mtime")}, ${diagnosticQuote("modification")}\n - ${diagnosticQuote("birth")}, ${diagnosticQuote("creation")}\nTry 'ls --help' for more information.\n`,
+ });
+ await run(["touch", "-m", "-d", "1998-01-15T23:00:00Z", "time-sort/a"]);
+ await run(["touch", "-a", "-d", "1998-01-14T11:00:00Z", "time-sort/a"]);
+ expect((await run(["ls", "--full", "-l", "--time=mtime", "time-sort/a"], "", { env: { TZ: "UTC0" } })).stdout).toContain("1998-01-15 23:00:00.000000000 +0000 time-sort/a\n");
+ expect((await run(["ls", "--full-time", "--time=mtime", "time-sort/a"], "", { env: { TZ: "UTC0" } })).stdout).toContain("1998-01-15 23:00:00.000000000 +0000 time-sort/a\n");
+ expect((await run(["ls", "--full-time", "-lu", "time-sort/a"], "", { env: { TZ: "UTC0" } })).stdout).toContain("1998-01-14 11:00:00.000000000 +0000 time-sort/a\n");
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456789 +0000", "time-sort/ns-new"]);
+ await systemRun(["/usr/bin/touch", "-d", "2026-01-02 03:04:05.123456788 +0000", "time-sort/ns-old"]);
+ expect((await run(["ls", "--full-time", "time-sort/ns-new"], "", { env: { TZ: "UTC0" } })).stdout).toContain("2026-01-02 03:04:05.123456789 +0000 time-sort/ns-new\n");
+ expect((await run(["ls", "-1t", "time-sort/ns-old", "time-sort/ns-new"])).stdout).toBe("time-sort/ns-new\ntime-sort/ns-old\n");
+ await writeFile(join(dir, "time-sort/recent"), "x");
+ expect((await run(["ls", "-l", "time-sort/recent"], "", { env: { TZ: "UTC0" } })).stdout).toMatch(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2} time-sort\/recent\n$/);
+ await writeFile(join(dir, "tree/alpha.c"), "x");
+ await writeFile(join(dir, "tree/beta.txt"), "x");
+ await writeFile(join(dir, "tree/gamma.h"), "x");
+ expect((await run(["ls", "-1X", "tree"])).stdout).toBe("large\nsmall\nsub\nalpha.c\ngamma.h\nbeta.txt\n");
+ expect((await run(["ls", "-1Xr", "tree"])).stdout).toBe("beta.txt\ngamma.h\nalpha.c\nsub\nsmall\nlarge\n");
+ expect((await run(["ls", "-1", "-I", "small", "--ignore=*.txt", "tree"])).stdout).toBe("alpha.c\ngamma.h\nlarge\nsub\n");
+ expect((await run(["ls", "-1", "--hide=*.txt", "tree"])).stdout).toBe("alpha.c\ngamma.h\nlarge\nsmall\nsub\n");
+ expect((await run(["ls", "-1A", "--hide=*.txt", "tree"])).stdout).toBe(".hidden\nalpha.c\nbeta.txt\ngamma.h\nlarge\nsmall\nsub\n");
+ await mkdir(join(dir, "backups"));
+ await writeFile(join(dir, "backups/keep"), "x");
+ await writeFile(join(dir, "backups/old~"), "x");
+ await writeFile(join(dir, "backups/~"), "x");
+ expect((await run(["ls", "-1", "--ignore-backups", "backups"])).stdout).toBe("keep\n");
+ expect((await run(["ls", "-1B", "backups"])).stdout).toBe("keep\n");
+ expect((await run(["ls", "-1", "--sort=none", "tree"])).stdout).toContain("alpha.c\nbeta.txt\ngamma.h\n");
+ await run(["ln", "tree/small", "tree/small-hard"]);
+ const inodeLines = (await run(["ls", "-i", "tree/small", "tree/small-hard"])).stdout.trim().split(/\n| /).filter(Boolean);
+ expect(inodeLines.map((line) => line.split(/\s+/)[0])).toEqual([(await lstat(join(dir, "tree/small"))).ino.toString(), (await lstat(join(dir, "tree/small-hard"))).ino.toString()]);
+ await writeFile(join(dir, "tree/hard-one"), "x");
+ await link(join(dir, "tree/hard-one"), join(dir, "tree/hard-two.png"));
+ expect((await run(["ls", "-U1", "--color=always", "tree/hard-one", "tree/hard-two.png"], "", { env: { LS_COLORS: "mh=44;37:*.png=01;35" } })).stdout).toBe("\x1b[0m\x1b[44;37mtree/hard-one\x1b[0m\n\x1b[44;37mtree/hard-two.png\x1b[0m\n");
+ await run(["chmod", "a+x", "tree/hard-two.png"]);
+ expect((await run(["ls", "-U1", "--color=always", "tree/hard-one", "tree/hard-two.png"], "", { env: { LS_COLORS: "mh=44;37:*.png=01;35:ex=01;32" } })).stdout).toBe("\x1b[0m\x1b[01;32mtree/hard-one\x1b[0m\n\x1b[01;32mtree/hard-two.png\x1b[0m\n");
+ await run(["chmod", "a-x", "tree/hard-two.png"]);
+ expect((await run(["ls", "-U1", "--color=always", "tree/hard-one", "tree/hard-two.png"], "", { env: { LS_COLORS: "mh=00:*.png=01;35" } })).stdout).toBe("tree/hard-one\n\x1b[0m\x1b[01;35mtree/hard-two.png\x1b[0m\n");
+ await writeFile(join(dir, "tree/img1.jpg"), "x");
+ await writeFile(join(dir, "tree/IMG2.JPG"), "x");
+ await writeFile(join(dir, "tree/img3.JpG"), "x");
+ await writeFile(join(dir, "tree/colon.foo"), "x");
+ await writeFile(join(dir, "tree/semicolon.foo"), "x");
+ await writeFile(join(dir, "tree/reset-color"), "x");
+ expect((await run(["ls", "-U1", "--color=always", "tree/img1.jpg", "tree/IMG2.JPG", "tree/img3.JpG"], "", { env: { LS_COLORS: "*.jpg=01;35:*.JPG=01;35" } })).stdout).toBe("\x1b[0m\x1b[01;35mtree/img1.jpg\x1b[0m\n\x1b[01;35mtree/IMG2.JPG\x1b[0m\n\x1b[01;35mtree/img3.JpG\x1b[0m\n");
+ expect((await run(["ls", "-U1", "--color=always", "tree/img1.jpg", "tree/IMG2.JPG", "tree/img3.JpG"], "", { env: { LS_COLORS: "*.jpg=01;35:*.JPG=01;35;46" } })).stdout).toBe("\x1b[0m\x1b[01;35mtree/img1.jpg\x1b[0m\n\x1b[01;35;46mtree/IMG2.JPG\x1b[0m\ntree/img3.JpG\n");
+ expect((await run(["ls", "-U1", "--color=always", "tree/colon.foo"], "", { env: { LS_COLORS: "*.foo=01\\:31" } })).stdout).toBe("\x1b[0m\x1b[01:31mtree/colon.foo\x1b[0m\n");
+ expect((await run(["ls", "-U1", "--color=always", "tree/semicolon.foo"], "", { env: { LS_COLORS: "*.foo=01\\;31" } })).stdout).toBe("\x1b[0m\x1b[01;31mtree/semicolon.foo\x1b[0m\n");
+ expect((await run(["ls", "-U1", "--color=always", "tree/reset-color"], "", { env: { LS_COLORS: "fi=32:rs=31" } })).stdout).toBe("\x1b[31m\x1b[32mtree/reset-color\x1b[31m\n");
+ await writeFile(join(dir, "tree/backup~"), "x");
+ await writeFile(join(dir, "tree/hash#"), "x");
+ expect((await run(["ls", "-U1", "--color=always", "tree/backup~", "tree/hash#"], "", { env: { LS_COLORS: "*~=00;90:*#=00;90" } })).stdout).toBe("\x1b[0m\x1b[00;90mtree/backup~\x1b[0m\n\x1b[00;90mtree/hash#\x1b[0m\n");
+ await symlink("small", join(dir, "tree/small-link"));
+ const linkInodes = (await run(["ls", "-Ci", "tree/small", "tree/small-link"])).stdout.trim().split(/\s+/);
+ expect(linkInodes[0]).not.toBe(linkInodes[2]);
+ const derefInodes = (await run(["ls", "-CLi", "tree/small", "tree/small-link"])).stdout.trim().split(/\s+/);
+ expect(derefInodes[0]).toBe(derefInodes[2]);
+ const commandLineDerefInodes = (await run(["ls", "-CHi", "tree/small", "tree/small-link"])).stdout.trim().split(/\s+/);
+ expect(commandLineDerefInodes[0]).toBe(commandLineDerefInodes[2]);
+ const directoryAllDerefInodes = (await run(["ls", "-CLi", "tree"])).stdout.trim().split(/\s+/);
+ expect(directoryAllDerefInodes[directoryAllDerefInodes.indexOf("small") - 1]).toBe(directoryAllDerefInodes[directoryAllDerefInodes.indexOf("small-link") - 1]);
+ const directoryDerefInodes = (await run(["ls", "-CHi", "tree"])).stdout.trim().split(/\s+/);
+ expect(directoryDerefInodes[directoryDerefInodes.indexOf("small") - 1]).not.toBe(directoryDerefInodes[directoryDerefInodes.indexOf("small-link") - 1]);
+ await symlink("sub", join(dir, "tree/sub-link"));
+ expect((await run(["ls", "-FL", "tree/sub-link"])).stdout).toBe("nested\n");
+ expect((await run(["ls", "tree/sub-link"])).stdout).toBe("nested\n");
+ expect((await run(["ls", "-F", "tree/sub-link"])).stdout).toBe("tree/sub-link@\n");
+ expect((await run(["ls", "-dF", "tree/sub-link"])).stdout).toBe("tree/sub-link@\n");
+ await symlink("missing", join(dir, "tree/dangling"));
+ expect(await run(["ls", "-L", "tree/dangling"])).toMatchObject({ code: 2 });
+ const derefTree = await run(["ls", "-L", "tree"]);
+ expect(derefTree).toMatchObject({ code: 1, stderr: "ls: cannot access 'tree/dangling': No such file or directory\n" });
+ expect(derefTree.stdout).toContain("dangling\n");
+ const implicitDanglingInode = await run(["ls", "-Li", "tree"]);
+ expect(implicitDanglingInode).toMatchObject({ code: 1 });
+ expect(implicitDanglingInode.stdout).toContain("? dangling\n");
+ await symlink("loop", join(dir, "tree/loop"));
+ expect(await run(["ls", "-L", "tree/loop"])).toMatchObject({ code: 2 });
+ const implicitLoop = await run(["ls", "-L", "tree"]);
+ expect(implicitLoop.stdout).toContain("loop\n");
+ expect(implicitLoop.stderr).not.toContain("tree/loop");
+ await mkdir(join(dir, "tree/cycle"));
+ await symlink("../cycle", join(dir, "tree/cycle/sub"));
+ const recursiveCycle = await run(["ls", "-RL", "tree/cycle"]);
+ expect(recursiveCycle).toMatchObject({ code: 2, stdout: "tree/cycle:\nsub\n" });
+ expect(recursiveCycle.stderr).toBe("ls: tree/cycle/sub: not listing already-listed directory\n");
+ expect((await run(["ls", "-s", "tree/small"])).stdout.trim()).toMatch(/^\d+ tree\/small$/);
+ expect((await run(["ls", "-lsh", "tree/small"])).stdout.trim()).toContain("tree/small");
+ await writeFile(join(dir, "tree/block-1024"), "");
+ await truncate(join(dir, "tree/block-1024"), 1024);
+ expect((await run(["ls", "-og", "tree/block-1024"])).stdout.trim().split(/\s+/)[2]).toBe("1024");
+ expect((await run(["ls", "-og", "--block-size=512", "tree/block-1024"])).stdout.trim().split(/\s+/)[2]).toBe("2");
+ const block1024Stat = await lstat(join(dir, "tree/block-1024"));
+ const block1024Blocks512 = block1024Stat.blocks ?? Math.ceil(block1024Stat.size / 512);
+ expect((await run(["ls", "-s", "--block-size=512", "tree/block-1024"])).stdout.trim()).toBe(`${block1024Blocks512} tree/block-1024`);
+ await mkdir(join(dir, "size-align"));
+ await writeFile(join(dir, "size-align/small"), "");
+ await writeFile(join(dir, "size-align/alloc"), "\n");
+ await writeFile(join(dir, "size-align/large"), "");
+ await truncate(join(dir, "size-align/large"), 123456);
+ const alignedSizeLines = (await run(["ls", "-s", "-l", "small", "alloc", "large"], "", { cwd: join(dir, "size-align") })).stdout.trimEnd().split("\n");
+ expect(new Set(alignedSizeLines.map((line) => line.length)).size).toBe(1);
+ expect(await run(["ls", "--time=birth", "-l", "tree/small"])).toMatchObject({ code: 0 });
+ expect(await run(["ls", "--time=creation", "-t", "tree/small"])).toMatchObject({ code: 0 });
+ const badTimeStyle = await run(["ls", "-l", "--time-style=XX", "tree"]);
+ expect(badTimeStyle).toMatchObject({ code: 2, stdout: "" });
+ expect(badTimeStyle).toMatchObject(await systemRun(["ls", "-l", "--time-style=XX", "tree"]));
+ expect(await run(["ls", "--time-style=XX", "tree/small"])).toMatchObject(await systemRun(["ls", "--time-style=XX", "tree/small"]));
+ expect(await run(["ls", "--format=single-column", "--time-style=XX", "tree/small"])).toMatchObject(await systemRun(["ls", "--format=single-column", "--time-style=XX", "tree/small"]));
+ expect(await run(["ls", "-l", "--time-style=bad\nstyle", "tree/small"])).toMatchObject({
+ code: 2,
+ stdout: "",
+ stderr: `ls: invalid argument ${diagnosticQuote("bad\\nstyle")} for ${diagnosticQuote("time style")}\nValid arguments are:\n - [posix-]full-iso\n - [posix-]long-iso\n - [posix-]iso\n - [posix-]locale\n - +FORMAT (e.g., +%H:%M) for a 'date'-style format\nTry 'ls --help' for more information.\n`,
+ });
+ await mkdir(join(dir, "tree/empty"));
+ expect((await run(["ls", "-aA", "tree/empty"])).stdout).toBe("");
+ expect((await run(["ls", "-Aa", "tree/empty"])).stdout).toBe(".\n..\n");
+ expect((await run(["ls", "--zero", "-x", "-m", "-C", "-Q", "-q", "tree/empty"])).stdout).toBe("");
+ await writeFile(join(dir, "tree/zero-a"), "x");
+ await writeFile(join(dir, "tree/zero-b"), "x");
+ expect((await run(["ls", "--zero", "-x", "-m", "-C", "-Q", "-q", "tree/zero-a", "tree/zero-b"])).stdout).toBe("tree/zero-a\0tree/zero-b\0");
+ expect(await run(["ls", "--dired", "--zero", "tree"])).toMatchObject({ code: 2 });
+ expect(await run(["ls", "-D", "--zero", "tree"])).toMatchObject({ code: 2 });
+ await mkdir(join(dir, "tree/dired-empty"));
+ expect((await run(["ls", "-R", "-D", "tree/dired-empty"])).stdout).toBe(" tree/dired-empty:\n total 0\n//SUBDIRED// 2 18\n//DIRED-OPTIONS// --quoting-style=literal\n");
+ await writeFile(join(dir, "tree/dired-a"), "x");
+ await writeFile(join(dir, "tree/dired-b"), "x");
+ const shortDired = await run(["ls", "-D", "tree/dired-a"]);
+ expect(shortDired.stdout).toContain("-rw-r--r--");
+ expect(shortDired.stdout).toContain("//DIRED//");
+ expect((await run(["dir", "-D", "tree/dired-a"])).stdout).toContain("//DIRED-OPTIONS// --quoting-style=escape\n");
+ expect((await run(["vdir", "-D", "tree/dired-a"])).stdout).toContain("//DIRED-OPTIONS// --quoting-style=escape\n");
+ const dired = await run(["ls", "-l", "--dired", "tree/dired-a", "tree/dired-b"]);
+ expect(dired.stdout).toContain("//DIRED//");
+ const [start, end] = dired.stdout.match(/\/\/DIRED\/\/ (\d+) (\d+)/).slice(1).map(Number);
+ expect(Buffer.from(dired.stdout).subarray(start, end).toString()).toBe("tree/dired-a");
+ await writeFile(join(dir, "tree/control-\x07"), "x");
+ expect((await run(["ls", "-q", "tree/control-\x07"])).stdout).toBe("tree/control-?\n");
+ expect((await run(["ls", "-Q", "tree/control-\x07"])).stdout).toBe("\"tree/control-\\a\"\n");
+ expect((await run(["ls", "--quoting=escape", "tree/control-\x07"])).stdout).toBe("tree/control-\\a\n");
+ expect((await run(["ls", "--quoting=shell-escape", "tree/control-\x07"])).stdout).toBe("'tree/control-'$'\\a'\n");
+ expect((await run(["ls", "-N", "tree/control-\x07"])).stdout).toBe("tree/control-\x07\n");
+ await writeFile(join(dir, "tree/hello world"), "x");
+ expect((await run(["ls", "--hyper", "tree/hello world"])).stdout).toBe(`\x1b]8;;file://${osHostname()}${dir}/tree/hello%20world\x1b\\tree/hello world\x1b]8;;\x1b\\\n`);
+ const rawHyperlink = Bun.spawn(["/bin/sh", "-c", `mkdir ls-hyper-raw; name=$(printf 'invalidutf8\\351'); : > "ls-hyper-raw/$name"; LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} ls --hyper ls-hyper-raw >ls-hyper-raw-out`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await rawHyperlink.exited).toBe(0);
+ expect(await new Response(rawHyperlink.stderr).text()).toBe("");
+ const rawHyperlinkOut = await readFile(join(dir, "ls-hyper-raw-out"));
+ expect(rawHyperlinkOut.includes(Buffer.from("invalidutf8%e9\x1b\\invalidutf8"))).toBe(true);
+ expect(rawHyperlinkOut.includes(Buffer.from([0xe9, 0x1b, 0x5d, 0x38, 0x3b, 0x3b, 0x1b, 0x5c, 0x0a]))).toBe(true);
+ const rawCommandLine = Bun.spawn(["/bin/sh", "-c", `name=$(printf 'ls-command-line-\\351'); : > "$name"; LC_ALL=en_US.iso88591 ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} ls -1 "$name" >ls-command-line-raw-out`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await rawCommandLine.exited).toBe(0);
+ expect(await new Response(rawCommandLine.stderr).text()).toBe("");
+ expect(await readFile(join(dir, "ls-command-line-raw-out"))).toEqual(Buffer.concat([Buffer.from("ls-command-line-"), Buffer.from([0xe9, 0x0a])]));
+ expect((await run(["ls", "--quoting-style=locale", "tree/hello world"], "", { env: { LC_ALL: "C" } })).stdout).toBe("'tree/hello world'\n");
+ expect((await run(["ls", "--quoting-style=clocale", "tree/hello world"], "", { env: { LC_ALL: "C" } })).stdout).toBe("\"tree/hello world\"\n");
+ expect((await run(["ls", "--quoting-style=locale", "tree/hello world"], "", { env: { LC_ALL: "en_US.UTF-8" } })).stdout).toBe("‘tree/hello world’\n");
+ await mkdir(join(dir, "dir:name"));
+ await writeFile(join(dir, "dir:name/a b"), "x");
+ await writeFile(join(dir, "dir:name/c.foo"), "x");
+ const quotedColored = await run(["ls", "-R", "--quoting=shell-escape", "--color=always", "dir:name"], "", { env: { TERM: "xterm", LS_COLORS: "*.foo=0;31;42", TIME_STYLE: "+T" } });
+ expect(quotedColored.stdout).toContain("'dir:name':\n");
+ expect(quotedColored.stdout).toContain("'a b'");
+ expect(quotedColored.stdout).toContain("\x1b[0;31;42mc.foo\x1b[0m");
+ const recursive = await run(["ls", "-R", "tree"]);
+ expect(recursive.stdout).toContain("tree:\n");
+ expect(recursive.stdout).toContain("tree/sub:\n");
+ const dotRecursive = await run(["ls", "-R", "."], "", { cwd: join(dir, "tree") });
+ expect(dotRecursive.stdout).toContain("./sub:\n");
+ await mkdir(join(dir, "rec-x"));
+ await mkdir(join(dir, "rec-y"));
+ await writeFile(join(dir, "rec-file"), "");
+ expect((await run(["ls", "-R1", "rec-x", "rec-y", "rec-file"])).stdout).toBe("rec-file\n\nrec-x:\n\nrec-y:\n");
+ expect((await run(["ls", "--color=always", "-F", "tree"])).stdout).toContain("\x1b[01;34msub\x1b[0m/");
+ expect((await run(["ls", "--color=auto", "-F", "tree"], "", { env: { TERM: "xterm" } })).stdout).not.toContain("\x1b[");
+ expect((await run(["ls", "--color=always", "tree/small"], "", { env: { TERM: "dumb", COLORTERM: "" } })).stdout).toBe("tree/small\n");
+ expect((await run(["ls", "--color=always", "tree/small"], "", { env: { TERM: "", COLORTERM: "nonempty" } })).stdout).toContain("\x1b[0m\x1b[01;32mtree/small\x1b[0m");
+ expect((await run(["ls", "--color=always", "tree/small"], "", { env: { TERM: "", COLORTERM: "" } })).stdout).toBe("tree/small\n");
+ expect((await run(["ls", "--color", "tree/small"], "", { env: { TERM: "xterm" } })).stdout).toContain("\x1b[0m\x1b[01;32mtree/small\x1b[0m");
+ expect((await run(["ls", "--color=always", "-F", "tree/sub-link"], "", { env: { TERM: "", COLORTERM: "", LS_COLORS: "ln=01;36:di=01;34:or=40;31;01" } })).stdout).toBe("tree/sub-link@\n");
+ expect((await run(["ls", "--color=always", "tree/dangling"], "", { env: { LS_COLORS: "or=36:mi=35" } })).stdout).toBe("\x1b[0m\x1b[36mtree/dangling\x1b[0m\n");
+ expect((await run(["ls", "--color=always", "-o", "--time-style=+:TIME:", "tree/dangling"], "", { env: { LS_COLORS: "ln=34:mi=35:or=36" } })).stdout).toContain("\x1b[0m\x1b[36mtree/dangling\x1b[0m -> \x1b[35mmissing\x1b[0m\n");
+ await mkdir(join(dir, "tree/world"));
+ await run(["chmod", "777", "tree/world"]);
+ expect((await run(["ls", "-d", "--color=always", "tree/world"], "", { env: { LS_COLORS: "ow=34;42:tw=30;42:di=01;34" } })).stdout).toContain("\x1b[0m\x1b[34;42mtree/world\x1b[0m");
+ await mkdir(join(dir, "tree/sticky"));
+ await run(["chmod", "1755", "tree/sticky"]);
+ expect((await run(["ls", "-dU1", "--color=always", "tree/sub", "tree/world", "tree/large", "tree/sticky"], "", { env: { TERM: "xterm", LS_COLORS: "" } })).stdout).toBe("\x1b[0m\x1b[01;34mtree/sub\x1b[0m\n\x1b[34;42mtree/world\x1b[0m\ntree/large\n\x1b[37;44mtree/sticky\x1b[0m\n");
+ expect((await run(["ls", "-d", "--color=always", "tree/world"], "", { env: { TERM: "xterm", LS_COLORS: "ow=:" } })).stdout).toBe("\x1b[0m\x1b[01;34mtree/world\x1b[0m\n");
+ expect((await run(["ls", "-og", "--color=always", "--time-style=+:TIME:", "tree/img1.jpg"], "", { env: { TERM: "xterm", LS_COLORS: "*.jpg=0;31;42" } })).stdout).toContain(":TIME: \x1b[0m\x1b[0;31;42mtree/img1.jpg\x1b[0m\n");
+ await writeFile(join(dir, "ver-a"), "");
+ await writeFile(join(dir, "ver-a2"), "");
+ await writeFile(join(dir, "ver-a10"), "");
+ expect((await run(["ls", "-v", "ver-a10", "ver-a2", "ver-a"])).stdout).toBe("ver-a\nver-a2\nver-a10\n");
+ await writeFile(join(dir, "zz~"), "");
+ await writeFile(join(dir, "zz"), "");
+ await writeFile(join(dir, "zz.~1~"), "");
+ await writeFile(join(dir, "zz.0"), "");
+ expect((await run(["ls", "-v", "zz.0", "zz.~1~", "zz", "zz~"])).stdout).toBe("zz~\nzz\nzz.~1~\nzz.0\n");
+ const missingLs = await run(["ls", "tree", "tree/no-such"]);
+ expect(missingLs).toMatchObject({ code: 2 });
+ expect(missingLs.stdout).toContain("tree:");
+ expect(missingLs.stderr).toContain("ls: cannot access 'tree/no-such': No such file or directory\n");
+ expect(await run(["mkfifo", "tree/fifo"])).toMatchObject({ code: 0 });
+ expect((await run(["ls", "-dgo", "tree/fifo"])).stdout.slice(0, 10)).toBe("prw-r--r--");
+ expect((await run(["ls", "-dgo", "tree/sub"])).stdout.slice(0, 10)).toBe("drwxr-xr-x");
+ expect((await run(["ls", "-d", "tree/missing"])).code).toBe(2);
+});
+
+test("join, split, tr and nl handle common text workflows", async () => {
+ expect(await run(["join"])).toMatchObject({ code: 1, stderr: "join: missing operand\nTry 'join --help' for more information.\n" });
+ expect(await run(["join", "left"])).toMatchObject({ code: 1, stderr: "join: missing operand after 'left'\nTry 'join --help' for more information.\n" });
+ expect(await run(["join", "left", "right", "extra"])).toMatchObject({ code: 1, stderr: "join: extra operand 'extra'\nTry 'join --help' for more information.\n" });
+ expect(await run(["join", "left", "right", "extra\narg"])).toMatchObject({ code: 1, stderr: "join: extra operand 'extra'$'\\n''arg'\nTry 'join --help' for more information.\n" });
+ await writeFile(join(dir, "left"), "1 alpha\n2 beta\n");
+ await writeFile(join(dir, "right"), "1 red\n2 blue\n");
+ await writeFile(join(dir, "join-header-left"), "id name\n1 one\n2 two\n");
+ await writeFile(join(dir, "join-header-right"), "id age\n1 10\n3 30\n");
+ expect(await run(["join", "left", "right"])).toMatchObject({ code: 0, stdout: "1 alpha red\n2 beta blue\n" });
+ const joinStdinBytes = Uint8Array.of(0x78, 0xa0, 0x79, 0x0a);
+ expect(await run(["join", "-a2", "-o2.1", "/dev/null", "-"], joinStdinBytes, { env: { LC_ALL: "fr_FR.iso88591" } }))
+ .toMatchObject(await systemRun(["/usr/bin/join", "-a2", "-o2.1", "/dev/null", "-"], joinStdinBytes, { env: { LC_ALL: "fr_FR.iso88591" } }));
+ expect(await run(["join", "--header", "-o", "auto", "join-header-left", "join-header-right"])).toMatchObject(await systemRun(["join", "--header", "-o", "auto", "join-header-left", "join-header-right"]));
+ expect(await run(["join", "left", "right", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: join [OPTION]... FILE1 FILE2\n"), stderr: "" });
+ expect(await run(["join", "-j", "+1", "left", "right"])).toMatchObject({ code: 0, stdout: "1 alpha red\n2 beta blue\n" });
+ expect(await run(["join", "-1", "+1", "-2", "+1", "left", "right"])).toMatchObject({ code: 0, stdout: "1 alpha red\n2 beta blue\n" });
+ expect(await run(["join", "-1", "0", "left", "right"])).toMatchObject(await systemRun(["join", "-1", "0", "left", "right"]));
+ expect(await run(["join", "-2", "0", "left", "right"])).toMatchObject(await systemRun(["join", "-2", "0", "left", "right"]));
+ expect(await run(["join", "-j", "0", "left", "right"])).toMatchObject(await systemRun(["join", "-j", "0", "left", "right"]));
+ expect(await run(["join", "-1", "bad", "--help"])).toMatchObject(await systemRun(["join", "-1", "bad", "--help"]));
+ expect(await run(["join", "-jbad", "--help"])).toMatchObject(await systemRun(["join", "-jbad", "--help"]));
+ expect(await run(["join", "-a3", "--help"])).toMatchObject(await systemRun(["join", "-a3", "--help"]));
+ expect(await run(["join", "-v", "3", "--help"])).toMatchObject(await systemRun(["join", "-v", "3", "--help"]));
+ expect(await run(["join", "-o", "1.0", "--help"])).toMatchObject(await systemRun(["join", "-o", "1.0", "--help"]));
+ expect(await run(["join", "-t", "xx", "--help"])).toMatchObject(await systemRun(["join", "-t", "xx", "--help"]));
+ expect(await run(["join", "-11", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: join [OPTION]... FILE1 FILE2\n") });
+ expect(await run(["join", "-o", "1.1", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: join [OPTION]... FILE1 FILE2\n") });
+ expect(await run(["join", "-1", "1\n2", "left", "right"])).toMatchObject({ code: 1, stdout: "", stderr: `join: invalid field number: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["join", "-a", "1\n2", "left", "right"])).toMatchObject({ code: 1, stdout: "", stderr: `join: invalid file number: ${diagnosticQuote("1\\n2")}\n` });
+ await writeFile(join(dir, "join-dup-left"), "a L1\na L2\nc LC\n");
+ await writeFile(join(dir, "join-dup-right"), "a R1\na R2\nb RB\n");
+ expect(await run(["join", "join-dup-left", "join-dup-right"])).toMatchObject({ code: 0, stdout: "a L1 R1\na L1 R2\na L2 R1\na L2 R2\n" });
+ expect(await run(["join", "-a2", "join-dup-left", "join-dup-right"])).toMatchObject({ code: 0, stdout: "a L1 R1\na L1 R2\na L2 R1\na L2 R2\nb RB\n" });
+ expect(await run(["join", "-v2", "join-dup-left", "join-dup-right"])).toMatchObject({ code: 0, stdout: "b RB\n" });
+ expect(await run(["join", "--v", "left", "right"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["join", "--i", "left", "right"])).toMatchObject({ code: 0, stdout: "1 alpha red\n2 beta blue\n" });
+ expect(await run(["join", "--ch", "left", "right"])).toMatchObject({ code: 0, stdout: "1 alpha red\n2 beta blue\n" });
+ expect(await run(["join", "--n", "reverse-left-missing", "reverse-right-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "join: reverse-left-missing: No such file or directory\n" });
+ expect(await run(["join", "--h", "left", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: option '--h' is ambiguous; possibilities: '--header' '--help'\nTry 'join --help' for more information.\n" });
+ expect(await run(["join", "--he", "left", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: option '--he' is ambiguous; possibilities: '--header' '--help'\nTry 'join --help' for more information.\n" });
+ expect(await run(["join", "--bad", "--help", "left", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: unrecognized option '--bad'\nTry 'join --help' for more information.\n" });
+ expect(await run(["join", "-x", "--help", "left", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: invalid option -- 'x'\nTry 'join --help' for more information.\n" });
+ expect(await run(["join", "--check=foo", "left", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: option '--check-order' doesn't allow an argument\nTry 'join --help' for more information.\n" });
+ const joinHelp = (await run(["join", "--help"])).stdout;
+ expect(joinHelp).toContain("Usage: join [OPTION]... FILE1 FILE2\n");
+ for (const option of ["-1", "-2", "-a", "-e", "-j", "-o", "-t", "-v"]) expect(joinHelp).toContain(` ${option}\n`);
+ expect(await run(["join", "join-missing", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: join-missing: No such file or directory\n" });
+ expect(await run(["join", "left", "join-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "join: join-missing: No such file or directory\n" });
+ expect(await run(["join", "missing'join", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: \"missing'join\": No such file or directory\n" });
+ expect(await run(["join", "left", "missing\njoin"])).toMatchObject({ code: 1, stdout: "", stderr: "join: 'missing'$'\\n''join': No such file or directory\n" });
+ await symlink("join-loop", join(dir, "join-loop"));
+ expect(await run(["join", "join-loop", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: join-loop: Too many levels of symbolic links\n" });
+ expect(await run(["join", "left", "join-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "join: join-loop: Too many levels of symbolic links\n" });
+ await symlink("loop'join", join(dir, "loop'join"));
+ expect(await run(["join", "loop'join", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: \"loop'join\": Too many levels of symbolic links\n" });
+ await mkdir(join(dir, "join-dir"));
+ expect(await run(["join", "join-dir", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: read error: Is a directory\n" });
+ expect(await run(["join", "left", "join-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "join: read error: Is a directory\n" });
+ await mkdir(join(dir, "dir'join"));
+ expect(await run(["join", "dir'join", "right"])).toMatchObject({ code: 1, stdout: "", stderr: "join: read error: Is a directory\n" });
+ await writeFile(join(dir, "case-left"), "a lower\nB upper\n");
+ await writeFile(join(dir, "case-right"), "A red\nb blue\n");
+ expect(await run(["join", "--ignore-case", "case-left", "case-right"])).toMatchObject({ code: 0, stdout: "a lower red\nB upper blue\n" });
+ await writeFile(join(dir, "case-unsorted-left"), "b first\nA second\n");
+ const caseOrdered = await run(["join", "--ignore-case", "--check-order", "case-unsorted-left", "case-right"]);
+ expect(caseOrdered).toMatchObject({ code: 1 });
+ expect(caseOrdered.stderr).toContain("case-unsorted-left:2: is not sorted: A second");
+ await writeFile(join(dir, "months-left"), "apr 15\naug 20\ndec 18\nfeb 05\n");
+ await writeFile(join(dir, "months-right"), "apr 06\naug 14\ndate\nfeb 15\n");
+ expect(await run(["join", "-a1", "-a2", "-e", "-", "-o", "2.2,1.1", "months-left", "months-right"])).toMatchObject({ code: 0, stdout: "06 apr\n14 aug\n- -\n- dec\n15 feb\n" });
+ expect(await run(["join", "-o", "0", "1.2", "2.2", "months-left", "months-right"])).toMatchObject({ code: 0, stdout: "apr 15 06\naug 20 14\nfeb 05 15\n" });
+ expect(await run(["join", "-o", "0", "1.2", "-e", "-", "months-left", "months-right"])).toMatchObject({ code: 0, stdout: "apr 15\naug 20\nfeb 05\n" });
+ expect(await run(["join", "-o", "1.0", "months-left", "months-right"])).toMatchObject(await systemRun(["join", "-o", "1.0", "months-left", "months-right"]));
+ expect(await run(["join", "-o", "2.0", "months-left", "months-right"])).toMatchObject(await systemRun(["join", "-o", "2.0", "months-left", "months-right"]));
+ expect(await run(["join", "-o", "bad", "months-left", "months-right"])).toMatchObject(await systemRun(["join", "-o", "bad", "months-left", "months-right"]));
+ expect(await run(["join", "-o", "3\n.1", "months-left", "months-right"])).toMatchObject({ code: 1, stdout: "", stderr: `join: invalid file number in field spec: ${diagnosticQuote("3\\n.1")}\n` });
+ expect(await run(["join", "-o", "1.0\n", "months-left", "months-right"])).toMatchObject({ code: 1, stdout: "", stderr: `join: invalid field number: ${diagnosticQuote("0\\n")}\n` });
+ expect(await run(["join", "-o", "1.2\n2.2", "months-left", "months-right"])).toMatchObject({ code: 1, stdout: "", stderr: `join: invalid field number: ${diagnosticQuote("2\\n2.2")}\n` });
+ await writeFile(join(dir, "wide-left"), "a 1 2\nb 1\nd 1 2\n");
+ await writeFile(join(dir, "wide-right"), "a 3 4\nb 3 4\nc 3 4\n");
+ expect(await run(["join", "-a1", "-a2", "-e", ".", "-o", "auto", "wide-left", "wide-right"])).toMatchObject({ code: 0, stdout: "a 1 2 3 4\nb 1 . 3 4\nc . . 3 4\nd 1 2 . .\n" });
+ await writeFile(join(dir, "reverse-left"), "b 1\na 2\n");
+ await writeFile(join(dir, "reverse-right"), "b Y\na Z\n");
+ expect(await run(["join", "--nocheck-order", "reverse-left", "reverse-right"])).toMatchObject({ code: 0, stdout: "b 1 Y\na 2 Z\n" });
+ const ordered = await run(["join", "--check-order", "reverse-left", "reverse-right"]);
+ expect(ordered).toMatchObject({ code: 1 });
+ expect(ordered.stderr).toContain("is not sorted");
+ await writeFile(join(dir, "header-left"), "ID Name\n1 A\n");
+ await writeFile(join(dir, "header-right"), "ID Color\n1 red\n");
+ expect(await run(["join", "--header", "header-left", "header-right"])).toMatchObject({ code: 0, stdout: "ID Name Color\n1 A red\n" });
+ expect(await run(["join", "-t", "xx", "left", "right"])).toMatchObject(await systemRun(["join", "-t", "xx", "left", "right"]));
+ expect(await run(["join", "-txx", "left", "right"])).toMatchObject(await systemRun(["join", "-txx", "left", "right"]));
+ expect(await run(["join", "-t", "ab\nc", "left", "right"])).toMatchObject({ code: 1, stdout: "", stderr: `join: multi-character tab ${diagnosticQuote("ab\\nc")}\n` });
+ expect(await run(["join", "-t", "", "left", "right"])).toMatchObject({ code: 0, stdout: "" });
+ await writeFile(join(dir, "nul-left"), "a\0c\0e");
+ await writeFile(join(dir, "nul-right"), "a\0b\0c");
+ expect(await run(["join", "-z", "nul-left", "nul-right"])).toMatchObject({ code: 0, stdout: "a\0c\0" });
+ await writeFile(join(dir, "join-nul-left"), "a\0x\n");
+ await writeFile(join(dir, "join-nul-right"), "a\0y\n");
+ expect(await run(["join", "-t", "\\0", "join-nul-left", "join-nul-right"])).toMatchObject({ code: 0, stdout: "a\0x\0y\n" });
+ await writeFile(join(dir, "utf8-left"), "1𐏐left\n");
+ await writeFile(join(dir, "utf8-right"), "1𐏐right\n");
+ expect(await run(["join", "-t", "𐏐", "utf8-left", "utf8-right"])).toMatchObject({ code: 0, stdout: "1𐏐left𐏐right\n" });
+ await writeFile(join(dir, "latin-left"), Buffer.from([97, 0xa7, 49, 10]));
+ await writeFile(join(dir, "latin-right"), Buffer.from([97, 0xa7, 50, 0xa7, 10]));
+ expect(await run(["join", "-t", "\uFFFD", "latin-left", "latin-right"])).toMatchObject({ code: 0, stdout: Buffer.from([97, 0xa7, 49, 0xa7, 50, 0xa7, 10]).toString() });
+ for (const option of ["-t", "-1", "-2", "-j", "-a", "-v", "-e", "-o"]) {
+ expect(await run(["join", option])).toMatchObject({ code: 1, stderr: `join: option requires an argument -- '${option.slice(1)}'\nTry 'join --help' for more information.\n` });
+ }
+ expect(await run(["tr", "a-z", "A-Z"], "abc xyz\n")).toMatchObject({ code: 0, stdout: "ABC XYZ\n" });
+ expect(await run(["tr", "-d", "0-9"], "a1b2\n")).toMatchObject({ code: 0, stdout: "ab\n" });
+ expect(await run(["nl"], "one\n\ntwo\n")).toMatchObject({ code: 0, stdout: " 1\tone\n \n 2\ttwo\n" });
+ expect(await run(["nl", "-ba", "-n", "rz", "-w", "3", "-s", ":", "-v", "5", "-i", "2"], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: "005:a\n007:b\n009:c\n" });
+ await writeFile(join(dir, "nl-raw"), Uint8Array.of(0xff, 0x0a));
+ const nlRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "nl", "-ba", "nl-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "nl-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await nlRaw.exited).toBe(0);
+ expect(await new Response(nlRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "nl-raw-out"))]).toEqual([0x20, 0x20, 0x20, 0x20, 0x20, 0x31, 0x09, 0xff, 0x0a]);
+ await writeFile(join(dir, "nl-left-no-newline"), "a");
+ await writeFile(join(dir, "nl-right-newline"), "b\n");
+ expect(await run(["nl", "-ba", "nl-left-no-newline", "nl-right-newline"])).toMatchObject({ code: 0, stdout: " 1\ta\n 2\tb\n" });
+ expect(await run(["nl", "missing'nl"])).toMatchObject({ code: 1, stdout: "", stderr: "nl: \"missing'nl\": No such file or directory\n" });
+ expect(await run(["nl", "missing\nnl"])).toMatchObject({ code: 1, stdout: "", stderr: "nl: 'missing'$'\\n''nl': No such file or directory\n" });
+ await mkdir(join(dir, "dir'nl"));
+ expect(await run(["nl", "dir'nl"])).toMatchObject({ code: 1, stdout: "", stderr: "nl: \"dir'nl\": Is a directory\n" });
+ await symlink("loop'nl", join(dir, "loop'nl"));
+ expect(await run(["nl", "loop'nl"])).toMatchObject({ code: 1, stdout: "", stderr: "nl: \"loop'nl\": Too many levels of symbolic links\n" });
+ expect(await run(["nl", "-ba", "-w", "+3", "-v", "+5", "-i", "+2"], "a\nb\n")).toMatchObject({ code: 0, stdout: " 5\ta\n 7\tb\n" });
+ expect(await run(["nl", "--bo=a"], "a\n\n")).toMatchObject({ code: 0, stdout: " 1\ta\n 2\t\n" });
+ expect(await run(["nl", "--number-s=:"], "a\n")).toMatchObject({ code: 0, stdout: " 1:a\n" });
+ expect(await run(["nl", "--v"])).toMatchObject({ code: 0, stdout: expect.stringContaining("bnu 9.11\n") });
+ expect(await run(["nl", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Write each FILE to standard output, with line numbers added.\n") });
+ expect(await run(["nl", "--v=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "nl: option '--version' doesn't allow an argument\nTry 'nl --help' for more information.\n" });
+ expect(await run(["nl", "--h"])).toMatchObject({ code: 1, stdout: "", stderr: "nl: option '--h' is ambiguous; possibilities: '--header-numbering' '--help'\nTry 'nl --help' for more information.\n" });
+ expect(await run(["nl", "--num=a"])).toMatchObject({ code: 1, stdout: "", stderr: "nl: option '--num=a' is ambiguous; possibilities: '--number-separator' '--number-width' '--number-format'\nTry 'nl --help' for more information.\n" });
+ expect(await run(["nl", "-x", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: nl [OPTION]... [FILE]...\n"), stderr: "nl: invalid option -- 'x'\n" });
+ expect(await run(["nl", "--help=1", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "nl: option '--help' doesn't allow an argument\n" });
+ expect(await run(["nl", "--body=bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: nl [OPTION]... [FILE]...\n"), stderr: `nl: invalid body numbering style: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["nl", "--body-numbering", "bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: nl [OPTION]... [FILE]...\n"), stderr: `nl: invalid body numbering style: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["nl", "-b", "bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: nl [OPTION]... [FILE]...\n"), stderr: `nl: invalid body numbering style: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["nl", "-n", "bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: nl [OPTION]... [FILE]...\n"), stderr: `nl: invalid line numbering format: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["nl", "--no-renumber=bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: nl [OPTION]... [FILE]...\n"), stderr: "nl: option '--no-renumber' doesn't allow an argument\n" });
+ expect(await run(["nl", "--body-numbering", "--help"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid body numbering style: ${diagnosticQuote("--help")}\nTry 'nl --help' for more information.\n` });
+ expect(await run(["nl", "-b", "x"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid body numbering style: ${diagnosticQuote("x")}\nTry 'nl --help' for more information.\n` });
+ expect(await run(["nl", "-b", "x\ny"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid body numbering style: ${diagnosticQuote("x\\ny")}\nTry 'nl --help' for more information.\n` });
+ expect(await run(["nl", "-h", "x"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid header numbering style: ${diagnosticQuote("x")}\nTry 'nl --help' for more information.\n` });
+ expect(await run(["nl", "-f", "x"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid footer numbering style: ${diagnosticQuote("x")}\nTry 'nl --help' for more information.\n` });
+ expect(await run(["nl", "-n", "rzbad"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid line numbering format: ${diagnosticQuote("rzbad")}\nTry 'nl --help' for more information.\n` });
+ expect(await run(["nl", "-n", "r\nz"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid line numbering format: ${diagnosticQuote("r\\nz")}\nTry 'nl --help' for more information.\n` });
+ expect(await run(["nl", "-w", "1\n2"])).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid line number field width: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["nl", "--number-width", "bad", "--help"])).toMatchObject(await systemRun(["nl", "--number-width", "bad", "--help"]));
+ expect(await run(["nl", "-w", "bad", "--help"])).toMatchObject(await systemRun(["nl", "-w", "bad", "--help"]));
+ expect(await run(["nl", "-wbad", "--help"])).toMatchObject(await systemRun(["nl", "-wbad", "--help"]));
+ expect(await run(["nl", "--line-increment", "bad", "--help"])).toMatchObject(await systemRun(["nl", "--line-increment", "bad", "--help"]));
+ expect(await run(["nl", "-i", "bad", "--help"])).toMatchObject(await systemRun(["nl", "-i", "bad", "--help"]));
+ expect(await run(["nl", "--number-width", "3", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: nl [OPTION]... [FILE]...\n") });
+ expect(await run(["nl", "-w", "x"])).toMatchObject(await systemRun(["nl", "-w", "x"]));
+ expect(await run(["nl", "-w", "0"])).toMatchObject(await systemRun(["nl", "-w", "0"]));
+ expect(await run(["nl", "-w", "+0"])).toMatchObject(await systemRun(["nl", "-w", "+0"]));
+ expect(await run(["nl", "-w", "-1"])).toMatchObject(await systemRun(["nl", "-w", "-1"]));
+ expect(await run(["nl", "-w", "2147483648"])).toMatchObject(await systemRun(["nl", "-w", "2147483648"]));
+ expect(await run(["nl", "-w", "+2147483648"])).toMatchObject(await systemRun(["nl", "-w", "+2147483648"]));
+ expect(await run(["nl", "-v", "x"])).toMatchObject(await systemRun(["nl", "-v", "x"]));
+ expect(await run(["nl", "-v", "1\n2"])).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid starting line number: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["nl", "-i", "x"])).toMatchObject(await systemRun(["nl", "-i", "x"]));
+ expect(await run(["nl", "-i", "1\n2"])).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid line number increment: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["nl", "-v", "+9223372036854775808"])).toMatchObject(await systemRun(["nl", "-v", "+9223372036854775808"]));
+ expect(await run(["nl", "-i", "-9223372036854775809"])).toMatchObject(await systemRun(["nl", "-i", "-9223372036854775809"]));
+ expect(await run(["nl", "-ba", "-n", "ln", "-w", "3", "-s", ":"], "a\nb\n")).toMatchObject({ code: 0, stdout: "1 :a\n2 :b\n" });
+ expect(await run(["nl", "-ba", "-l", "2"], "a\n\n\nb\n")).toMatchObject({ code: 0, stdout: " 1\ta\n \n 2\t\n 3\tb\n" });
+ expect(await run(["nl", "-l", "-1"], "a\n")).toMatchObject(await systemRun(["nl", "-l", "-1"], "a\n"));
+ expect(await run(["nl", "-l", "1\n2"], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: `nl: invalid line number of blank lines: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["nl", "-l", "bad"], "a\n")).toMatchObject(await systemRun(["nl", "-l", "bad"], "a\n"));
+ expect(await run(["nl", "-bp^[ab]"], "a\nc\nb\n")).toMatchObject({ code: 0, stdout: " 1\ta\n c\n 2\tb\n" });
+ expect(await run(["nl", "-bp("], "a\n(a)\n")).toMatchObject({ code: 0, stdout: " a\n 1\t(a)\n" });
+ expect(await run(["nl", "-bp(a)"], "a\n(a)\n")).toMatchObject({ code: 0, stdout: " a\n 1\t(a)\n" });
+ expect(await run(["nl", "-bp\\(a\\)"], "a\n(a)\n")).toMatchObject({ code: 0, stdout: " 1\ta\n 2\t(a)\n" });
+ expect(await run(["nl", "-bp["], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: "nl: Invalid regular expression\n" });
+ expect(await run(["nl", "-hp["], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: "nl: Invalid regular expression\n" });
+ expect(await run(["nl", "-fp["], "a\n")).toMatchObject({ code: 1, stdout: "", stderr: "nl: Invalid regular expression\n" });
+ expect(await run(["nl", "-ha", "-fa"], "\\:\\:\\:\na\n\\:\\:\nb\n\\:\nc\n")).toMatchObject({ code: 0, stdout: "\n 1\ta\n\n 1\tb\n\n 1\tc\n" });
+ expect(await run(["nl", "-p", "-ha", "-fa"], "\\:\\:\\:\na\n\\:\\:\nb\n\\:\nc\n")).toMatchObject({ code: 0, stdout: "\n 1\ta\n\n 2\tb\n\n 3\tc\n" });
+ expect(await run(["nl", "-p", "-ha", "-fa", "-d", "\uFFFD"], Buffer.from([0xc3, 0x3a, 0xc3, 0x3a, 0xc3, 0x3a, 0x0a, 0x61, 0x0a, 0xc3, 0x3a, 0xc3, 0x3a, 0x0a, 0x62, 0x0a, 0xc3, 0x3a, 0x0a, 0x63, 0x0a]))).toMatchObject({ code: 0, stdout: "\n 1\ta\n\n 2\tb\n\n 3\tc\n" });
+ expect(await run(["nl", "-d", ""], "a\n\\:\\:\nc\n")).toMatchObject({ code: 0, stdout: " 1\ta\n 2\t\\:\\:\n 3\tc\n" });
+ expect(await run(["nl", "-v9223372036854775807", "-i-9223372036854775808"], "a\nb\n")).toMatchObject({ code: 0, stdout: "9223372036854775807\ta\n -1\tb\n" });
+ await writeFile(join(dir, "nl-a"), "a\n");
+ await writeFile(join(dir, "nl-b"), "b\n");
+ await mkdir(join(dir, "nl-dir"));
+ await symlink("nl-loop", join(dir, "nl-loop"));
+ const nlMissing = await run(["nl", "nl-a", "nl-missing", "nl-b"]);
+ expect(nlMissing).toMatchObject({ code: 1, stdout: " 1\ta\n 2\tb\n" });
+ expect(nlMissing.stderr).toContain("nl: nl-missing: No such file or directory");
+ expect(await run(["nl", "nl-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "nl: nl-dir: Is a directory\n" });
+ expect(await run(["nl", "nl-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "nl: nl-loop: Too many levels of symbolic links\n" });
+ await writeFile(join(dir, "lines"), "a\nb\nc\n");
+ expect(await run(["split", "-b", "0"])).toMatchObject(await systemRun(["split", "-b", "0"]));
+ expect(await run(["split", "-b", "x"])).toMatchObject(await systemRun(["split", "-b", "x"]));
+ expect(await run(["split", "-C", "0"])).toMatchObject(await systemRun(["split", "-C", "0"]));
+ expect(await run(["split", "-C", "x"])).toMatchObject(await systemRun(["split", "-C", "x"]));
+ expect(await run(["split", "-l", "0"])).toMatchObject(await systemRun(["split", "-l", "0"]));
+ expect(await run(["split", "-l", "x"])).toMatchObject(await systemRun(["split", "-l", "x"]));
+ expect(await run(["split", "-l", "1\n2"])).toMatchObject({ code: 1, stdout: "", stderr: `split: invalid number of lines: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["split", "-b", "1\n2"])).toMatchObject({ code: 1, stdout: "", stderr: `split: invalid number of bytes: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["split", "-C", "1\n2"])).toMatchObject({ code: 1, stdout: "", stderr: `split: invalid number of lines: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["split", "-n", "-1", "lines"])).toMatchObject(await systemRun(["split", "-n", "-1", "lines"]));
+ expect(await run(["split", "-l", "-1", "lines"])).toMatchObject(await systemRun(["split", "-l", "-1", "lines"]));
+ expect(await run(["split", "-b", "-2", "lines"])).toMatchObject(await systemRun(["split", "-b", "-2", "lines"]));
+ expect(await run(["split", "-C", "-2", "lines"])).toMatchObject(await systemRun(["split", "-C", "-2", "lines"]));
+ expect(await run(["split", "-a", "-1", "lines"])).toMatchObject(await systemRun(["split", "-a", "-1", "lines"]));
+ expect(await run(["split", "-a", "bad", "lines"])).toMatchObject(await systemRun(["split", "-a", "bad", "lines"]));
+ expect(await run(["split", "-a", "1\n2", "lines"])).toMatchObject({ code: 1, stdout: "", stderr: `split: invalid suffix length: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["split", "-abad", "lines"])).toMatchObject(await systemRun(["split", "-abad", "lines"]));
+ expect(await run(["split", "-a", "bad", "split-missing"])).toMatchObject(await systemRun(["split", "-a", "bad", "split-missing"]));
+ expect(await run(["split", "--additional-suffix=/", "split-missing"])).toMatchObject(await systemRun(["split", "--additional-suffix=/", "split-missing"]));
+ expect(await run(["split", "--additional-suffix=/x", "split-missing"])).toMatchObject(await systemRun(["split", "--additional-suffix=/x", "split-missing"]));
+ expect(await run(["split", "--additional-suffix=bad\n/suf", "lines"])).toMatchObject({ code: 1, stdout: "", stderr: `split: invalid suffix ${diagnosticQuote("bad\\n/suf")}, contains directory separator\nTry 'split --help' for more information.\n` });
+ expect(await run(["split", "-d", "--numeric-suffixes=+1", "lines"])).toMatchObject({ code: 1, stderr: "split: '+1': invalid start value for numerical suffix\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "-d", "--numeric-suffixes=+1", "split-missing"])).toMatchObject({ code: 1, stderr: "split: '+1': invalid start value for numerical suffix\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "-x", "--hex-suffixes=g", "lines"])).toMatchObject({ code: 1, stderr: "split: 'g': invalid start value for hexadecimal suffix\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "--num", "lines"])).toMatchObject({ code: 1, stderr: "split: option '--num' is ambiguous; possibilities: '--number' '--numeric-suffixes'\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "--h", "lines"])).toMatchObject({ code: 1, stdout: "", stderr: "split: option '--h' is ambiguous; possibilities: '--hex-suffixes' '--help'\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "--v", "lines"])).toMatchObject({ code: 1, stdout: "", stderr: "split: option '--v' is ambiguous; possibilities: '--verbose' '--version'\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "split: unrecognized option '--bad'\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "-x", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: split [OPTION]... [FILE [PREFIX]]\n") });
+ expect(await run(["split", "--bytes", "bad", "--help"])).toMatchObject(await systemRun(["split", "--bytes", "bad", "--help"]));
+ expect(await run(["split", "--lines", "bad", "--help"])).toMatchObject(await systemRun(["split", "--lines", "bad", "--help"]));
+ expect(await run(["split", "--number", "bad", "--help"])).toMatchObject(await systemRun(["split", "--number", "bad", "--help"]));
+ expect(await run(["split", "--suffix-length", "bad", "--help"])).toMatchObject(await systemRun(["split", "--suffix-length", "bad", "--help"]));
+ expect(await run(["split", "-b", "bad", "--help"])).toMatchObject(await systemRun(["split", "-b", "bad", "--help"]));
+ expect(await run(["split", "-n", "bad", "--help"])).toMatchObject(await systemRun(["split", "-n", "bad", "--help"]));
+ expect(await run(["split", "--bytes=1", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: split [OPTION]... [FILE [PREFIX]]\n") });
+ expect(await run(["split", "--lines", "1", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: split [OPTION]... [FILE [PREFIX]]\n") });
+ expect(await run(["split", "--h=foo", "lines"])).toMatchObject({ code: 1, stdout: "", stderr: "split: option '--h=foo' is ambiguous; possibilities: '--hex-suffixes' '--help'\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "--verbose=foo", "lines"])).toMatchObject({ code: 1, stdout: "", stderr: "split: option '--verbose' doesn't allow an argument\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "lines", "prefix", "extra"])).toMatchObject({ code: 1, stderr: `split: extra operand ${diagnosticQuote("extra")}\nTry 'split --help' for more information.\n` });
+ expect(await run(["split", "lines", "prefix", "extra\narg"])).toMatchObject({ code: 1, stderr: `split: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'split --help' for more information.\n` });
+ expect(await run(["split", "-d", "-a20", "--numeric-suffixes=18446744073709551615", "lines", "large-dec"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "large-dec18446744073709551615"), "utf8")).toBe("a\nb\nc\n");
+ expect(await run(["split", "--hex=e", "lines", "hex-abbrev"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "hex-abbrev0e"), "utf8")).toBe("a\nb\nc\n");
+ expect(await run(["split", "--", "--num"])).toMatchObject({ code: 1, stderr: "split: cannot open '--num' for reading: No such file or directory\n" });
+ expect(await run(["split", "lines", "--", "--hex"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "--hexaa"), "utf8")).toBe("a\nb\nc\n");
+ await mkdir(join(dir, "split-input-dir"));
+ await symlink("split-input-loop", join(dir, "split-input-loop"));
+ expect(await run(["split", "split-input-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "split: split-input-dir: Is a directory\n" });
+ expect(await run(["split", "split-input-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "split: cannot open 'split-input-loop' for reading: Too many levels of symbolic links\n" });
+ expect(await run(["split", "-x", "-a16", "--hex-suffixes=ffffffffffffffff", "lines", "large-hex"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "large-hexffffffffffffffff"), "utf8")).toBe("a\nb\nc\n");
+ expect(await run(["split", "-d", "-a1", "--numeric-suffixes=10", "lines"])).toMatchObject({ code: 1, stderr: "split: numerical suffix start value is too large for the suffix length\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "-a", "0", "-n", "2", "lines", "zero-suffix"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "zero-suffixaa"), "utf8")).toBe("a\nb");
+ expect(await readFile(join(dir, "zero-suffixab"), "utf8")).toBe("\nc\n");
+ expect(await run(["split", "-a1", "-n27"], "")).toMatchObject({ code: 1, stderr: "split: the suffix length needs to be at least 2\n" });
+ expect(await run(["split", "-d", "-a1", "-n11"], "")).toMatchObject({ code: 1, stderr: "split: the suffix length needs to be at least 2\n" });
+ expect(await run(["split", "-x", "-a1", "-n17"], "")).toMatchObject({ code: 1, stderr: "split: the suffix length needs to be at least 2\n" });
+ await writeFile(join(dir, "six-lines"), "a\nb\nc\nd\ne\nf\n");
+ expect(await run(["split", "-d5", "six-lines", "obsolete-digits"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "obsolete-digits00"), "utf8")).toBe("a\nb\nc\nd\ne\n");
+ expect(await readFile(join(dir, "obsolete-digits01"), "utf8")).toBe("f\n");
+ expect(await run(["split", "-du5", "six-lines", "obsolete-cluster"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "obsolete-cluster00"), "utf8")).toBe("a\nb\nc\nd\ne\n");
+ expect(await readFile(join(dir, "obsolete-cluster01"), "utf8")).toBe("f\n");
+ expect(await run(["split", "-5", "-l1", "six-lines"])).toMatchObject({ code: 1, stderr: "split: cannot split in more than one way\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "-b1", "-l1", "six-lines"])).toMatchObject({ code: 1, stderr: "split: cannot split in more than one way\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "--number=2", "--lines=1", "six-lines"])).toMatchObject({ code: 1, stderr: "split: cannot split in more than one way\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "-n", "1/+2", "lines"])).toMatchObject({ code: 0, stdout: "a\nb" });
+ expect(await run(["split", "-n", "+1/2", "lines"])).toMatchObject({ code: 0, stdout: "a\nb" });
+ expect(await run(["split", "-l", "+2", "lines", "plus-lines"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "plus-linesaa"), "utf8")).toBe("a\nb\n");
+ await writeFile(join(dir, "plus-bytes"), "abcd");
+ expect(await run(["split", "-b", "+2", "plus-bytes", "plus-bytes-out"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "plus-bytes-outaa"), "utf8")).toBe("ab");
+ await writeFile(join(dir, "suffix-bytes"), "x".repeat(1500));
+ expect(await run(["split", "-b", "1k", "suffix-bytes", "suffix-binary"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "suffix-binaryaa"))).size).toBe(1024);
+ expect((await stat(join(dir, "suffix-binaryab"))).size).toBe(476);
+ expect(await run(["split", "-b", "1kB", "suffix-bytes", "suffix-decimal"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "suffix-decimalaa"))).size).toBe(1000);
+ expect((await stat(join(dir, "suffix-decimalab"))).size).toBe(500);
+ expect(await run(["split", "-b", "1kiB", "suffix-bytes", "suffix-ib"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "suffix-ibaa"))).size).toBe(1024);
+ expect(await run(["split", "-b", "1E", "suffix-bytes", "suffix-exa"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "suffix-exaaa"))).size).toBe(1500);
+ expect(await run(["split", "-b", "1ZB", "suffix-bytes", "suffix-zetta"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "suffix-zettaaa"))).size).toBe(1500);
+ expect(await run(["split", "-b", "1YiB", "suffix-bytes", "suffix-yobi"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "suffix-yobiaa"))).size).toBe(1500);
+ expect(await run(["split", "-b", "1e", "suffix-bytes", "suffix-lower-exa"])).toMatchObject({ code: 1 });
+ expect(await run(["split", "-l", "2", "lines", "part"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "partaa"), "utf8")).toBe("a\nb\n");
+ expect(await readFile(join(dir, "partab"), "utf8")).toBe("c\n");
+ await writeFile(join(dir, "split-raw"), Uint8Array.of(0xff, 0x0a, 0x61, 0x0a));
+ expect(await run(["split", "-l", "1", "split-raw", "split-raw-lines"])).toMatchObject({ code: 0 });
+ expect([...await readFile(join(dir, "split-raw-linesaa"))]).toEqual([0xff, 0x0a]);
+ expect([...await readFile(join(dir, "split-raw-linesab"))]).toEqual([0x61, 0x0a]);
+ expect(await run(["split", "-C", "2", "split-raw", "split-raw-line-bytes"])).toMatchObject({ code: 0 });
+ expect([...await readFile(join(dir, "split-raw-line-bytesaa"))]).toEqual([0xff, 0x0a]);
+ expect([...await readFile(join(dir, "split-raw-line-bytesab"))]).toEqual([0x61, 0x0a]);
+ expect(await run(["split", "--unbuffered", "-l", "2", "lines", "unbuf"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "unbufaa"), "utf8")).toBe("a\nb\n");
+ await writeFile(join(dir, "xaa"), "1\n2\n3\n4\n");
+ await symlink("xaa", join(dir, "same-link"));
+ await link(join(dir, "xaa"), join(dir, "same-hard"));
+ expect(await run(["split", "-C", "2", "xaa"])).toMatchObject({ code: 1 });
+ expect(await run(["split", "-C", "2", "same-link"])).toMatchObject({ code: 1 });
+ expect(await run(["split", "-C", "2", "same-hard"])).toMatchObject({ code: 1 });
+ expect(await readFile(join(dir, "xaa"), "utf8")).toBe("1\n2\n3\n4\n");
+ await mkdir(join(dir, "split-dir-outaa"));
+ expect(await run(["split", "-l", "1", "lines", "split-dir-out"])).toMatchObject({ code: 1, stdout: "", stderr: "split: split-dir-outaa: Is a directory\n" });
+ expect(await run(["split", "-l", "1", "lines", "bad", "extra"])).toMatchObject({ code: 1 });
+ await expect(readFile(join(dir, "badaa"), "utf8")).rejects.toThrow();
+ await writeFile(join(dir, "bytes"), "abcdefghi");
+ expect(await run(["split", "-n", "3", "bytes", "chunk"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "chunkaa"), "utf8")).toBe("abc");
+ expect(await readFile(join(dir, "chunkab"), "utf8")).toBe("def");
+ expect(await readFile(join(dir, "chunkac"), "utf8")).toBe("ghi");
+ expect(await run(["split", "-n", "2/3", "bytes"])).toMatchObject({ code: 0, stdout: "def" });
+ await writeFile(join(dir, "records"), "a\nb\nc\nd\n");
+ expect(await run(["split", "-n", "r/2", "-d", "-a", "1", "records", "rr"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "rr0"), "utf8")).toBe("a\nc\n");
+ expect(await readFile(join(dir, "rr1"), "utf8")).toBe("b\nd\n");
+ await writeFile(join(dir, "split-raw-round-robin"), Uint8Array.of(0xff, 0x0a, 0x61, 0x0a, 0xfe, 0x0a));
+ expect(await run(["split", "-n", "r/2", "-d", "-a", "1", "split-raw-round-robin", "split-raw-rr"])).toMatchObject({ code: 0 });
+ expect([...await readFile(join(dir, "split-raw-rr0"))]).toEqual([0xff, 0x0a, 0xfe, 0x0a]);
+ expect([...await readFile(join(dir, "split-raw-rr1"))]).toEqual([0x61, 0x0a]);
+ await writeFile(join(dir, "lchunk"), "12345\n1\n12345\n1\n12345\n1\n12345\n1\n12345\n\n\n12345\n1\n12345\n1\n12345\n1\n12345\n1\n12345\n1\n");
+ expect(await run(["split", "-n", "l/2", "-", "pipe-lch"], "1\n2\n3\n4\n")).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "pipe-lchaa"), "utf8")).toBe("1\n2\n");
+ expect(await readFile(join(dir, "pipe-lchab"), "utf8")).toBe("3\n4\n");
+ expect(await run(["split", "-n", "l/8", "lchunk", "lch"])).toMatchObject({ code: 0 });
+ for (const [name, text] of [
+ ["lchaa", "12345\n1\n12345\n"],
+ ["lchab", "1\n12345\n"],
+ ["lchac", "1\n12345\n"],
+ ["lchad", "1\n12345\n\n\n"],
+ ["lchae", "12345\n1\n12345\n"],
+ ["lchaf", "1\n12345\n"],
+ ["lchag", "1\n12345\n"],
+ ["lchah", "1\n12345\n1\n"],
+ ]) expect(await readFile(join(dir, name), "utf8")).toBe(text);
+ expect(await run(["split", "-n", "l/13/15", "lchunk"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["split", "-n", "l/14/15", "lchunk"])).toMatchObject({ code: 0, stdout: "1\n12345\n" });
+ expect(await run(["split", "-n", "l/16/15", "lchunk"])).toMatchObject(await systemRun(["split", "-n", "l/16/15", "lchunk"]));
+ expect(await run(["split", "-n", "l/1o", "lchunk"])).toMatchObject(await systemRun(["split", "-n", "l/1o", "lchunk"]));
+ expect(await run(["split", "-n", "", "lchunk"])).toMatchObject(await systemRun(["split", "-n", "", "lchunk"]));
+ expect(await run(["split", "-n", "/2", "lchunk"])).toMatchObject(await systemRun(["split", "-n", "/2", "lchunk"]));
+ expect(await run(["split", "-n", "1/2/3", "lchunk"])).toMatchObject(await systemRun(["split", "-n", "1/2/3", "lchunk"]));
+ expect(await run(["split", "-n", "l/", "lchunk"])).toMatchObject(await systemRun(["split", "-n", "l/", "lchunk"]));
+ expect(await run(["split", "-n", "b/2", "lchunk"])).toMatchObject(await systemRun(["split", "-n", "b/2", "lchunk"]));
+ expect(await run(["split", "-n", "1\n2", "lchunk"])).toMatchObject({ code: 1, stdout: "", stderr: `split: invalid number of chunks: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["split", "-n", "1\n2/3", "lchunk"])).toMatchObject({ code: 1, stdout: "", stderr: `split: invalid chunk number: ${diagnosticQuote("1\\n2")}\n` });
+ await writeFile(join(dir, "lchunk-noeol"), "12\n34\n5");
+ expect(await run(["split", "-n", "l/7/7", "lchunk-noeol"])).toMatchObject({ code: 0, stdout: "5" });
+ expect(await run(["split", "-1", "lines", "obsolete"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "obsoleteaa"), "utf8")).toBe("a\n");
+ expect(await run(["split", "-0", "lines", "bad-obsolete"])).toMatchObject({ code: 1 });
+ expect(await run(["split", "-99999999999999999991", "lines", "huge-obsolete"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "huge-obsoleteaa"), "utf8")).toBe("a\nb\nc\n");
+ expect(await run(["split", "--number=r/9223372036854775807/18446744073709551615"], "")).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["split", "--number=r/18446744073709551615", "lines"])).toMatchObject(await systemRun(["split", "--number=r/18446744073709551615", "lines"]));
+ expect(await run(["split", "--number=r/18446744073709551616"], "")).toMatchObject({ code: 1 });
+ expect(await run(["split", "-C", "4", "--additional-suffix=.txt", "records", "line"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "lineaa.txt"), "utf8")).toBe("a\nb\n");
+ expect(await readFile(join(dir, "lineab.txt"), "utf8")).toBe("c\nd\n");
+ await symlink("/dev/full", join(dir, "fullaa"));
+ expect(await run(["split", "-b", "1", "-", "full"], "ab\n")).toMatchObject({ code: 1, stderr: "split: fullaa: No space left on device\n" });
+ expect((await lstat(join(dir, "fullaa"))).isSymbolicLink()).toBe(true);
+ expect(await run(["split", "-l", "2", "--filter=cat > \"$FILE.out\"", "records", "filtered"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "filteredaa.out"), "utf8")).toBe("a\nb\n");
+ expect(await readFile(join(dir, "filteredab.out"), "utf8")).toBe("c\nd\n");
+ expect(await run(["split", "-b", "4", "--filter=cat > \"$FILE.out\""], "1\n2\n3\n4\n5\n")).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "xaa.out"), "utf8")).toBe("1\n2\n");
+ expect(await readFile(join(dir, "xab.out"), "utf8")).toBe("3\n4\n");
+ expect(await readFile(join(dir, "xac.out"), "utf8")).toBe("5\n");
+ expect(await run(["split", "-n", "r/2", "--filter=cat > \"$FILE.rr\""], "1\n2\n3\n4\n")).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "xaa.rr"), "utf8")).toBe("1\n3\n");
+ expect(await readFile(join(dir, "xab.rr"), "utf8")).toBe("2\n4\n");
+ const roundRobinEndless = Bun.spawn(["/bin/sh", "-c", `yes | timeout 5 ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} split -n r/2 --filter='head -c1 >$FILE.n' -`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await roundRobinEndless.exited).toBe(0);
+ expect(await readFile(join(dir, "xaa.n"), "utf8")).toBe("y");
+ expect(await readFile(join(dir, "xab.n"), "utf8")).toBe("y");
+ const longRoundRobinRecord = `${"a".repeat(70_000)}\n`;
+ expect(await run(["split", "-n", "r/2", "--filter=cat > \"$FILE.long\""], `${longRoundRobinRecord}b\n`)).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "xaa.long"), "utf8")).toBe(longRoundRobinRecord);
+ expect(await readFile(join(dir, "xab.long"), "utf8")).toBe("b\n");
+ const endlessSplit = Bun.spawn(["/bin/sh", "-c", `yes | timeout .5 ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} split -b 1000000 --filter='head -c1 >/dev/null'`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await endlessSplit.exited).toBe(124);
+ expect(await run(["split", "-n", "1/2", "--filter=cat >/dev/null", "records"])).toMatchObject({ code: 1 });
+ expect(await run(["split", "-l", "2", "--additional-suffix=a/b", "records", "bad-suffix"])).toMatchObject(await systemRun(["split", "-l", "2", "--additional-suffix=a/b", "records", "bad-suffix"]));
+ await expect(readFile(join(dir, "bad-suffixaa/b"), "utf8")).rejects.toThrow();
+ expect(await run(["split", "-b", "2", "-x", "-a", "1", "bytes", "hex"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "hex0"), "utf8")).toBe("ab");
+ expect(await readFile(join(dir, "hex1"), "utf8")).toBe("cd");
+ expect(await run(["split", "-l", "1", "--numeric-suffixes=5", "lines", "num"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "num05"), "utf8")).toBe("a\n");
+ expect(await readFile(join(dir, "num06"), "utf8")).toBe("b\n");
+ await writeFile(join(dir, "numeric-auto"), "x".repeat(91));
+ expect(await run(["split", "-b", "1", "--numeric", "numeric-auto", "autonum"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "autonum89"), "utf8")).toBe("x");
+ expect(await readFile(join(dir, "autonum9000"), "utf8")).toBe("x");
+ expect(await run(["split", "-b", "1", "--numeric=89", "numeric-auto", "fixednum"])).toMatchObject({ code: 1, stderr: "split: output file suffixes exhausted\n" });
+ expect(await readFile(join(dir, "fixednum99"), "utf8")).toBe("x");
+ await expect(readFile(join(dir, "fixednum100"), "utf8")).rejects.toThrow();
+ expect(await run(["split", "-l", "1", "--hex-suffixes=15", "lines", "hstart"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "hstart15"), "utf8")).toBe("a\n");
+ expect(await readFile(join(dir, "hstart16"), "utf8")).toBe("b\n");
+ await writeFile(join(dir, "many"), `${"x\n".repeat(27)}`);
+ expect(await run(["split", "-l", "1", "-a", "1", "many", "tiny"])).toMatchObject({ code: 1, stderr: "split: output file suffixes exhausted\n" });
+ expect(await readFile(join(dir, "tinya"), "utf8")).toBe("x\n");
+ expect(await readFile(join(dir, "tinyz"), "utf8")).toBe("x\n");
+ await expect(readFile(join(dir, "tinyaa"), "utf8")).rejects.toThrow();
+ expect(await run(["split", "-l", "1", "-a", "2", "many", "manypart"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "manypartaz"), "utf8")).toBe("x\n");
+ expect(await readFile(join(dir, "manypartba"), "utf8")).toBe("x\n");
+ expect(await run(["split", "-a", "2", "-n", "1000"], "")).toMatchObject({ code: 1 });
+ await writeFile(join(dir, "colon-records"), "a:b:c:");
+ expect(await run(["split", "-l", "2", "-t:", "colon-records", "colon"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "colonaa"), "utf8")).toBe("a:b:");
+ expect(await readFile(join(dir, "colonab"), "utf8")).toBe("c:");
+ expect(await run(["split", "---io=2", "-C", "4", "records", "iotest"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "iotestaa"), "utf8")).toBe("a\nb\n");
+ await writeFile(join(dir, "no-eol"), "0123456789");
+ expect(await run(["split", "-C", "3", "no-eol", "noeol"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "noeolaa"), "utf8")).toBe("012");
+ expect(await readFile(join(dir, "noeolab"), "utf8")).toBe("345");
+ await writeFile(join(dir, "long-line"), "1\n2222\n3\n4");
+ expect(await run(["split", "-C", "4", "long-line", "longc"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "longcaa"), "utf8")).toBe("1\n");
+ expect(await readFile(join(dir, "longcab"), "utf8")).toBe("2222");
+ expect(await readFile(join(dir, "longcac"), "utf8")).toBe("\n3\n");
+ expect(await run(["split", "-t"], "")).toMatchObject({ code: 1, stderr: "split: option requires an argument -- 't'\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "--separator"], "")).toMatchObject({ code: 1, stderr: "split: option '--separator' requires an argument\nTry 'split --help' for more information.\n" });
+ expect(await run(["split", "-t", ""], "")).toMatchObject({ code: 1, stderr: "split: empty record separator\n" });
+ expect(await run(["split", "-t", "--help", "--version"], "")).toMatchObject({ code: 1, stdout: "", stderr: `split: multi-character separator ${diagnosticQuote("--help")}\n` });
+ expect(await run(["split", "--separator", "--help", "--version"], "")).toMatchObject({ code: 1, stdout: "", stderr: `split: multi-character separator ${diagnosticQuote("--help")}\n` });
+ expect(await run(["split", "--separator=xx", "--help"], "")).toMatchObject({ code: 1, stdout: "", stderr: `split: multi-character separator ${diagnosticQuote("xx")}\n` });
+ expect(await run(["split", "-txx"], "")).toMatchObject({ code: 1, stderr: `split: multi-character separator ${diagnosticQuote("xx")}\n` });
+ expect(await run(["split", "-ta", "-tb"], "")).toMatchObject({ code: 1 });
+ expect(await run(["split", "-t:", "-t:"], "")).toMatchObject({ code: 0 });
+});
+
+test("tr supports classes, escapes, complement and squeezing", async () => {
+ expect(await run(["tr", "[:lower:]", "[:upper:]"], "abc xyz\n")).toMatchObject({ code: 0, stdout: "ABC XYZ\n" });
+ expect(await run(["tr", "-d", "[:digit:]"], "a1b2c3\n")).toMatchObject({ code: 0, stdout: "abc\n" });
+ expect(await run(["tr", "--del", "a"], "abc")).toMatchObject({ code: 0, stdout: "bc" });
+ expect(await run(["tr", "--squeeze", "a"], "aaabb")).toMatchObject({ code: 0, stdout: "abb" });
+ expect(await run(["tr", "--tr", "a", "b"], "abc")).toMatchObject({ code: 0, stdout: "bbc" });
+ expect(await run(["tr", "--delete=1", "a"])).toMatchObject({ code: 1, stderr: "tr: option '--delete' doesn't allow an argument\nTry 'tr --help' for more information.\n" });
+ expect(await run(["tr", "--h", "a", "b"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tr [OPTION]... STRING1 [STRING2]\n") });
+ expect(await run(["tr", "--v", "a", "b"])).toMatchObject({ code: 0, stdout: expect.stringContaining("bnu 9.11\n") });
+ expect(await run(["tr", "--h=foo", "a", "b"])).toMatchObject({ code: 1, stdout: "", stderr: "tr: option '--help' doesn't allow an argument\nTry 'tr --help' for more information.\n" });
+ expect(await run(["tr", "--v=foo", "a", "b"])).toMatchObject({ code: 1, stdout: "", stderr: "tr: option '--version' doesn't allow an argument\nTry 'tr --help' for more information.\n" });
+ expect(await run(["tr", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "tr: unrecognized option '--bad'\nTry 'tr --help' for more information.\n" });
+ expect(await run(["tr", "--delete", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tr [OPTION]... STRING1 [STRING2]\n") });
+ expect(await run(["tr", "\\n", ","], "a\nb\n")).toMatchObject({ code: 0, stdout: "a,b," });
+ expect(await run(["tr", "\\141-\\143", "X-Z"], "abc")).toMatchObject({ code: 0, stdout: "XYZ" });
+ expect(await run(["tr", "A", "\\400"], "A0 ")).toMatchObject({ code: 0, stdout: " 0 ", stderr: "tr: warning: the ambiguous octal escape \\400 is being\n\tinterpreted as the 2-byte sequence \\040, 0\n" });
+ expect(await run(["tr", "-d", "\\777"], "?7X")).toMatchObject({ code: 0, stdout: "X", stderr: "tr: warning: the ambiguous octal escape \\777 is being\n\tinterpreted as the 2-byte sequence \\077, 7\n" });
+ expect(await run(["tr", "z-a", "A-Z"], "azm")).toMatchObject({ code: 1, stdout: "", stderr: "tr: range-endpoints of 'z-a' are in reverse collating sequence order\n" });
+ expect(await run(["tr", "-d", "z-a"], "azm")).toMatchObject({ code: 1, stdout: "", stderr: "tr: range-endpoints of 'z-a' are in reverse collating sequence order\n" });
+ expect(await run(["tr", "-c", "[:digit:]", "x"], "a12 b\n")).toMatchObject({ code: 0, stdout: "x12xxx" });
+ expect(await run(["tr", "-s", "a-z", "A-Z"], "boook\n")).toMatchObject({ code: 0, stdout: "BOK\n" });
+ expect(await run(["tr", "-s", " "], "a b\n")).toMatchObject({ code: 0, stdout: "a b\n" });
+ expect(await run(["tr", "abcd", "x[y*]"], "abcde")).toMatchObject({ code: 0, stdout: "xyyye" });
+ expect(await run(["tr", "a[=*2][=c=]", "xyyz"], "a=c")).toMatchObject({ code: 0, stdout: "xyz" });
+ expect(await run(["tr", "a[b*512]c", "1[x*]2"], "abc")).toMatchObject({ code: 0, stdout: "1x2" });
+ expect(await run(["tr", "[b*010]cd", "[a*7]BC[x*]"], "bcd")).toMatchObject({ code: 0, stdout: "BCx" });
+ expect(await run(["tr", "-t", "abcd", "xy"], "abcde")).toMatchObject({ code: 0, stdout: "xycde" });
+ expect(await run(["tr", "-cs", "[:alnum:]", "[\\n*]"], "The big fox.")).toMatchObject({ code: 0, stdout: "The\nbig\nfox\n" });
+ expect(await run(["tr", "-c", "[a*65536]\n", "[b*]"], "abcd")).toMatchObject({ code: 0, stdout: "abbb" });
+ expect(await run(["tr", "-d", "[=]=]"], "[[]]")).toMatchObject({ code: 0, stdout: "[[" });
+ expect(await run(["tr", "[=ab=]", "x"], "ab")).toMatchObject({ code: 1, stdout: "", stderr: "tr: ab: equivalence class operand must be a single character\n" });
+ expect(await run(["tr", "[[::]]", "x"])).toMatchObject({ code: 1, stdout: "", stderr: "tr: missing character class name '[::]'\n" });
+ expect(await run(["tr", "[:*3][:digit:]", "a-m"], ":1239")).toMatchObject({ code: 0, stdout: "cefgm" });
+ expect(await run(["tr", "[:upper:][:lower:]", "a-z[:upper:]"], "abc.xyz")).toMatchObject({ code: 0, stdout: "ABC.XYZ" });
+ expect(await run(["tr"])).toMatchObject({ code: 1, stderr: "tr: missing operand\nTry 'tr --help' for more information.\n" });
+ expect(await run(["tr", "-ds", "a"])).toMatchObject({ code: 1, stderr: "tr: missing operand after 'a'\nTwo strings must be given when both deleting and squeezing repeats.\nTry 'tr --help' for more information.\n" });
+ expect(await run(["tr", "-d", "a", "b"])).toMatchObject({ code: 1, stderr: `tr: extra operand ${diagnosticQuote("b")}\nOnly one string may be given when deleting without squeezing repeats.\nTry 'tr --help' for more information.\n` });
+ expect(await run(["tr", "-d", "a", "b\nc"])).toMatchObject({ code: 1, stderr: `tr: extra operand ${diagnosticQuote("b\\nc")}\nOnly one string may be given when deleting without squeezing repeats.\nTry 'tr --help' for more information.\n` });
+ expect(await run(["tr", "-d", "a", "b\nc", "z"])).toMatchObject({ code: 1, stderr: `tr: extra operand ${diagnosticQuote("b\\nc")}\nTry 'tr --help' for more information.\n` });
+ expect(await run(["tr", "a", "b", "c"])).toMatchObject({ code: 1, stderr: `tr: extra operand ${diagnosticQuote("c")}\nTry 'tr --help' for more information.\n` });
+ expect(await run(["tr", "a", "b", "c\nd"])).toMatchObject({ code: 1, stderr: `tr: extra operand ${diagnosticQuote("c\\nd")}\nTry 'tr --help' for more information.\n` });
+ expect(await run(["tr", "[a*]", "x"])).toMatchObject({ code: 1, stderr: "tr: the [c*] repeat construct may not appear in string1\n" });
+ expect(await run(["tr", "[a*0]", "x"])).toMatchObject({ code: 1, stderr: "tr: the [c*] repeat construct may not appear in string1\n" });
+ expect(await run(["tr", "[a*bad]", "x"])).toMatchObject(await systemRun(["tr", "[a*bad]", "x"]));
+ expect(await run(["tr", "[:lower:]", "[a*b\nad]"])).toMatchObject({ code: 1, stdout: "", stderr: `tr: invalid repeat count ${diagnosticQuote("b\\\\nad")} in [c*n] construct\n` });
+ expect(await run(["tr", "[a*999999999999999999999999]", "x"])).toMatchObject(await systemRun(["tr", "[a*999999999999999999999999]", "x"]));
+ expect(await run(["tr", "a", ""])).toMatchObject({ code: 1, stderr: "tr: when not truncating set1, string2 must be non-empty\n" });
+ expect(await run(["tr", "[:upper:] ", "[:lower:]"])).toMatchObject({ code: 1, stderr: "tr: when translating with string1 longer than string2,\nthe latter string must not end with a character class\n" });
+ expect(await run(["tr", "A-Y[:lower:]", "a-z[:upper:]"])).toMatchObject({ code: 1, stderr: "tr: misaligned [:upper:] and/or [:lower:] construct\n" });
+ expect(await run(["tr", "-cs", "[:upper:]", "X[Y*]"])).toMatchObject({ code: 1, stderr: "tr: when translating with complemented character classes,\nstring2 must map all characters in the domain to one\n" });
+ expect(await run(["tr", "[:fooclass:]", "x"])).toMatchObject({ code: 1, stderr: "tr: invalid character class 'fooclass'\n" });
+ expect(await run(["tr", "--bad=4", "a", "b"])).toMatchObject({ code: 1, stderr: "tr: unrecognized option '--bad=4'\nTry 'tr --help' for more information.\n" });
+});
+
+test("basenc, od and numfmt handle numeric and formatted text", async () => {
+ expect(await run(["basenc", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: basenc [OPTION]... [FILE]\n") });
+ expect(await run(["basenc", "--v"])).toMatchObject({ code: 0, stdout: expect.stringContaining("bnu 9.11\n") });
+ expect(await run(["basenc", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: unrecognized option '--bad'\nTry 'basenc --help' for more information.\n" });
+ expect(await run(["basenc", "--h=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: option '--help' doesn't allow an argument\nTry 'basenc --help' for more information.\n" });
+ expect(await run(["basenc", "--version=1", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: option '--version' doesn't allow an argument\nTry 'basenc --help' for more information.\n" });
+ expect(await run(["basenc", "--b"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: option '--b' is ambiguous; possibilities: '--base64' '--base64url' '--base58' '--base32' '--base32hex' '--base16' '--base2msbf' '--base2lsbf'\nTry 'basenc --help' for more information.\n" });
+ expect(await run(["basenc", "--base6"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: option '--base6' is ambiguous; possibilities: '--base64' '--base64url'\nTry 'basenc --help' for more information.\n" });
+ expect(await run(["basenc", "--wrap=bad"])).toMatchObject({ code: 1, stdout: "", stderr: `basenc: invalid wrap size: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["basenc", "--wrap=bad", "--help"])).toMatchObject(await systemRun(["basenc", "--wrap=bad", "--help"]));
+ expect(await run(["basenc", "--base64", "--wrap", "bad", "--help"])).toMatchObject(await systemRun(["basenc", "--base64", "--wrap", "bad", "--help"]));
+ expect(await run(["basenc", "--base64", "--wrap=1\n2"])).toMatchObject({ code: 1, stdout: "", stderr: `basenc: invalid wrap size: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["basenc", "--w", "--help", "--base64"], "a")).toMatchObject(await systemRun(["basenc", "--w", "--help", "--base64"], "a"));
+ expect(await run(["basenc", "--base64", "--base32"], "abc")).toMatchObject({ code: 0, stdout: "MFRGG===\n" });
+ expect(await run(["basenc", "--base32", "--base64"], "abc")).toMatchObject({ code: 0, stdout: "YWJj\n" });
+ expect(await run(["basenc", "--base16"], "abc")).toMatchObject({ code: 0, stdout: "616263\n" });
+ expect(await run(["basenc", "--base16", "-d"], "616263\n")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["basenc", "--base16", "-d"], "61!!6263\n")).toMatchObject({ code: 1, stdout: "a", stderr: "basenc: invalid input\n" });
+ expect(await run(["basenc", "--base16", "-di"], "61!!6263\n")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["basenc", "--base16", "-d"], "616\n")).toMatchObject({ code: 1, stdout: "a", stderr: "basenc: invalid input\n" });
+ expect(await run(["basenc", "--base64", "basenc-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: basenc-missing: No such file or directory\n" });
+ expect(await run(["basenc", "--base64", "missing'basenc"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: \"missing'basenc\": No such file or directory\n" });
+ expect(await run(["basenc", "--base64", "missing\nbasenc"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: 'missing'$'\\n''basenc': No such file or directory\n" });
+ await mkdir(join(dir, "basenc-dir"));
+ expect(await run(["basenc", "--base64", "basenc-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: read error: Is a directory\n" });
+ await symlink("basenc-loop", join(dir, "basenc-loop"));
+ expect(await run(["basenc", "--base64", "basenc-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: basenc-loop: Too many levels of symbolic links\n" });
+ await symlink("loop'basenc", join(dir, "loop'basenc"));
+ expect(await run(["basenc", "--base64", "loop'basenc"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: \"loop'basenc\": Too many levels of symbolic links\n" });
+ expect(await run(["basenc", "--base64", "-d", "basenc-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "basenc: basenc-missing: No such file or directory\n" });
+ expect(await run(["basenc", "--base32"], "abc")).toMatchObject({ code: 0, stdout: "MFRGG===\n" });
+ expect(await run(["basenc", "--base32", "-d"], "MF!!RGG===\n")).toMatchObject({ code: 1, stdout: "a", stderr: "basenc: invalid input\n" });
+ expect(await run(["basenc", "--base32", "-di"], "MF!!RGG===\n")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["basenc", "--base32", "-di"], "mfrgg===\n")).toMatchObject({ code: 1, stdout: "", stderr: "basenc: invalid input\n" });
+ expect(await run(["basenc", "--base32hex"], "abc")).toMatchObject({ code: 0, stdout: "C5H66===\n" });
+ expect(await run(["basenc", "--base32hex", "-d"], "C5H66===")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["basenc", "--base32hex", "-d"], "c5h66===")).toMatchObject({ code: 1, stdout: "", stderr: "basenc: invalid input\n" });
+ expect(await run(["basenc", "--base2m"], "ab")).toMatchObject({ code: 0, stdout: "0110000101100010\n" });
+ expect(await run(["basenc", "--base2l", "-d"], "1000011001000110")).toMatchObject({ code: 0, stdout: "ab" });
+ expect(await run(["basenc", "--z85"], "ABCD")).toMatchObject({ code: 0, stdout: "k%^}b\n" });
+ const basencStreamingInput = Uint8Array.from({ length: 8204 }, (_, index) => (index * 131 + 17) & 255);
+ for (const algorithm of ["base64", "base64url", "base32", "base32hex", "base16", "base2msbf", "base2lsbf", "z85"]) {
+ expect(await run(["basenc", `--${algorithm}`, "--wrap=77"], basencStreamingInput))
+ .toMatchObject(await systemRun(["basenc", `--${algorithm}`, "--wrap=77"], basencStreamingInput));
+ }
+ expect(await run(["basenc", "--z85", "-d"], "hello")).toMatchObject({ code: 0, stdout: "5jXu" });
+ expect(await run(["basenc", "--base58"], "Hello World!")).toMatchObject({ code: 0, stdout: "2NEpo7TZRRrLZSi2U\n" });
+ expect(await run(["basenc", "--base58", "-d"], "2NEpo7TZRRrLZSi2U")).toMatchObject({ code: 0, stdout: "Hello World!" });
+ expect(await run(["basenc", "--base64", "-d"], "YW!!Jj\n")).toMatchObject({ code: 1, stdout: "a", stderr: "basenc: invalid input\n" });
+ expect(await run(["basenc", "--base64", "-d"], "mzxw6===")).toMatchObject({ code: 1, stdout: "\uFFFD<p", stderr: "basenc: invalid input\n" });
+ expect(await run(["basenc", "--base64", "-di"], "YW!!Jj\n")).toMatchObject({ code: 0, stdout: "abc" });
+ expect(await run(["basenc", "--base64", "-di"], "bad!!\n")).toMatchObject({ code: 1, stdout: "m�", stderr: "basenc: invalid input\n" });
+ expect(await run(["basenc", "--base64url", "-di"], "YW!!Jj\n")).toMatchObject({ code: 0, stdout: "abc" });
+ const odHelp = await run(["od", "--h"]);
+ expect(odHelp.code).toBe(0);
+ expect(odHelp.stdout).toContain("Usage: od [OPTION]... [FILE]...\n or: od [-abcdfilosx]... [FILE] [[+]OFFSET[.][b]]\n or: od --traditional [OPTION]... [FILE] [[+]OFFSET[.][b] [+][LABEL][.][b]]\n");
+ for (const option of ["-a", "-b", "-c", "-d", "-f", "-i", "-l", "-o", "-s", "-x"]) expect(odHelp.stdout).toContain(` ${option}\n`);
+ expect(await run(["od", "--v"])).toMatchObject({ code: 0, stdout: expect.stringContaining("bnu 9.11\n") });
+ await writeFile(join(dir, "od-meta"), "AB");
+ expect(await run(["od", "od-meta", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: od [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["od", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "od: unrecognized option '--bad'\nTry 'od --help' for more information.\n" });
+ expect(await run(["od", "--h=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "od: option '--help' doesn't allow an argument\nTry 'od --help' for more information.\n" });
+ expect(await run(["od", "--help=1", "--version"])).toMatchObject({ code: 1, stdout: "", stderr: "od: option '--help' doesn't allow an argument\nTry 'od --help' for more information.\n" });
+ expect(await run(["od", "--a=x"], "AB")).toMatchObject({ code: 0, stdout: "000000 041101\n000002\n" });
+ expect(await run(["od", "--r=1"], "AB")).toMatchObject({ code: 0, stdout: "0000000 000101\n0000001\n" });
+ expect(await run(["od", "--s=1"], "AB")).toMatchObject({ code: 1, stdout: "", stderr: "od: option '--s=1' is ambiguous; possibilities: '--skip-bytes' '--strings'\nTry 'od --help' for more information.\n" });
+ expect(await run(["od", "--read", "--help"], "AB")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid --read-bytes argument '--help'\n" });
+ expect(await run(["od", "--read=1", "--help"], "AB")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: od [OPTION]... [FILE]...\n or: od [-abcdfilosx]... [FILE] [[+]OFFSET[.][b]]\n") });
+ expect(await run(["od", "--read-bytes", "bad", "--help"], "AB")).toMatchObject(await systemRun(["od", "--read-bytes", "bad", "--help"], "AB"));
+ expect(await run(["od", "--read-bytes", "1", "--help"], "AB")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: od [OPTION]... [FILE]...\n") });
+ expect(await run(["od", "-N", "bad", "--help"], "AB")).toMatchObject(await systemRun(["od", "-N", "bad", "--help"], "AB"));
+ expect(await run(["od", "-Nbad", "--help"], "AB")).toMatchObject(await systemRun(["od", "-Nbad", "--help"], "AB"));
+ expect(await run(["od", "-N1", "--help"], "AB")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: od [OPTION]... [FILE]...\n") });
+ expect(await run(["od", "-A", "x", "-t", "x1"], "AB")).toMatchObject({ code: 0, stdout: "000000 41 42\n000002\n" });
+ expect(await run(["od", "--format="], "AB")).toMatchObject({ code: 0, stdout: "0000000 041101\n0000002\n", stderr: "" });
+ expect(await run(["od", "--format=", "-t", "x1"], "AB")).toMatchObject({ code: 0, stdout: "0000000 41 42\n0000002\n", stderr: "" });
+ expect(await run(["od", "-A", "xx"], "AB")).toMatchObject({ code: 0, stdout: "000000 041101\n000002\n" });
+ expect(await run(["od", "--address-radix=nn"], "AB")).toMatchObject({ code: 0, stdout: " 041101\n" });
+ expect(await run(["od", "-A", ""], "AB")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid output address radix '\0'; it must be one character from [doxn]\n" });
+ expect(await run(["od", "--address-radix="], "AB")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid output address radix '\0'; it must be one character from [doxn]\n" });
+ expect(await run(["od", "-An", "-t", "c"], "ABC\n")).toMatchObject({ code: 0, stdout: " A B C \\n\n" });
+ const odControlBytes = Buffer.from([0x61, 0x01, 0x02, 0xff, 0x00, 0x0a]);
+ expect(await run(["od", "-An", "-t", "c"], odControlBytes)).toMatchObject(await systemRun(["/usr/bin/od", "-An", "-t", "c"], odControlBytes));
+ expect(await run(["od", "-An", "-t", "a"], odControlBytes)).toMatchObject(await systemRun(["/usr/bin/od", "-An", "-t", "a"], odControlBytes));
+ expect(await run(["od", "-An", "-t", "u1"], "ABC\n")).toMatchObject({ code: 0, stdout: " 65 66 67 10\n" });
+ expect(await run(["od", "--endian=big", "-t", "x2"], "AB")).toMatchObject({ code: 0, stdout: "0000000 4142\n0000002\n" });
+ expect(await run(["od", "--endian", "bad", "--help"], "AB")).toMatchObject(await systemRun(["od", "--endian", "bad", "--help"], "AB"));
+ expect(await run(["od", "--endian", "big", "--help"], "AB")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: od [OPTION]... [FILE]...\n") });
+ expect(await run(["od", "--endian=", "-t", "x2"], "AB")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `od: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--endian")}\nValid arguments are:\n - ${diagnosticQuote("little")}\n - ${diagnosticQuote("big")}\nTry 'od --help' for more information.\n`,
+ });
+ expect(await run(["od", "--endian=", "--help"], "AB")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `od: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--endian")}\nValid arguments are:\n - ${diagnosticQuote("little")}\n - ${diagnosticQuote("big")}\nTry 'od --help' for more information.\n`,
+ });
+ expect(await run(["od", "--endian=bad", "-t", "x2"], "AB")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `od: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("--endian")}\nValid arguments are:\n - ${diagnosticQuote("little")}\n - ${diagnosticQuote("big")}\nTry 'od --help' for more information.\n`,
+ });
+ expect(await run(["od", "--endian=bad\nmode", "-t", "x2"], "AB")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `od: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--endian")}\nValid arguments are:\n - ${diagnosticQuote("little")}\n - ${diagnosticQuote("big")}\nTry 'od --help' for more information.\n`,
+ });
+ expect(await run(["od", "--endian", "-t", "x2"], "AB")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `od: invalid argument ${diagnosticQuote("-t")} for ${diagnosticQuote("--endian")}\nValid arguments are:\n - ${diagnosticQuote("little")}\n - ${diagnosticQuote("big")}\nTry 'od --help' for more information.\n`,
+ });
+ expect(await run(["od", "-A", "d", "-j", "2", "-N", "3", "-t", "x1"], "abcdef")).toMatchObject({ code: 0, stdout: "0000002 63 64 65\n0000005\n" });
+ expect(await run(["od", "-x"], "ABCD")).toMatchObject({ code: 0, stdout: "0000000 4241 4443\n0000004\n" });
+ expect(await run(["od", "-s"], "ABCD")).toMatchObject({ code: 0, stdout: "0000000 16961 17475\n0000004\n" });
+ expect(await run(["od", "-bx"], "ABCD")).toMatchObject({ code: 0, stdout: "0000000 101 102 103 104\n 4241 4443\n0000004\n" });
+ expect(await run(["od", "-An", "-N", "+1", "-t", "x1"], "abcd")).toMatchObject({ code: 0, stdout: " 61\n" });
+ expect(await run(["od", "-An", "-j", "+1", "-t", "x1"], "abcd")).toMatchObject({ code: 0, stdout: " 62 63 64\n" });
+ expect(await run(["od", "-An", "--read-bytes=+1", "-t", "x1"], "abcd")).toMatchObject({ code: 0, stdout: " 61\n" });
+ expect(await run(["od", "-An", "--skip-bytes=+1", "-t", "x1"], "abcd")).toMatchObject({ code: 0, stdout: " 62 63 64\n" });
+ expect(await run(["od", "-j", "bad"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid suffix in -j argument 'bad'\n" });
+ expect(await run(["od", "-j", ""], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid -j argument ''\n" });
+ expect(await run(["od", "-j", "-1"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid -j argument '-1'\n" });
+ expect(await run(["od", "-j", "1R"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: -j argument '1R' too large\n" });
+ expect(await run(["od", "-j", "1RB"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: -j argument '1RB' too large\n" });
+ expect(await run(["od", "-N", "bad"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid suffix in -N argument 'bad'\n" });
+ expect(await run(["od", "-N", ""], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid -N argument ''\n" });
+ expect(await run(["od", "-N", "-1"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid -N argument '-1'\n" });
+ expect(await run(["od", "-N", "1Y"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: -N argument '1Y' too large\n" });
+ expect(await run(["od", "--skip-bytes=bad"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid suffix in --skip-bytes argument 'bad'\n" });
+ expect(await run(["od", "--skip-bytes=bad", "--help"])).toMatchObject(await systemRun(["od", "--skip-bytes=bad", "--help"]));
+ expect(await run(["od", "--skip-bytes", "bad", "--help"], "AB")).toMatchObject(await systemRun(["od", "--skip-bytes", "bad", "--help"], "AB"));
+ expect(await run(["od", "-j", "bad", "--help"], "AB")).toMatchObject(await systemRun(["od", "-j", "bad", "--help"], "AB"));
+ expect(await run(["od", "--skip-bytes="], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid --skip-bytes argument ''\n" });
+ expect(await run(["od", "--read-bytes=bad"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid suffix in --read-bytes argument 'bad'\n" });
+ expect(await run(["od", "--read-bytes=bad", "--help"])).toMatchObject(await systemRun(["od", "--read-bytes=bad", "--help"]));
+ expect(await run(["od", "--read-bytes="], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid --read-bytes argument ''\n" });
+ expect(await run(["od", "-An", "-w2", "-t", "x1"], "abcd")).toMatchObject({ code: 0, stdout: " 61 62\n 63 64\n" });
+ expect(await run(["od", "-t", "x1"], "\0".repeat(64))).toMatchObject({ code: 0, stdout: "0000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n*\n0000100\n" });
+ expect(await run(["od", "-v", "-t", "x1", "-w16"], "\0".repeat(32))).toMatchObject({ code: 0, stdout: "0000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n0000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n0000040\n" });
+ expect(await run(["od", "-w", "bad"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: bad: No such file or directory\n" });
+ expect(await run(["od", "-wbad", "--help"], "AB")).toMatchObject(await systemRun(["od", "-wbad", "--help"], "AB"));
+ expect(await run(["od", "-w4"], "AB\n")).toMatchObject({ code: 0, stdout: "0000000 041101 000012\n0000003\n" });
+ expect(await run(["od", "--width=bad"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid --width argument 'bad'\n" });
+ expect(await run(["od", "--width=bad", "--help"])).toMatchObject(await systemRun(["od", "--width=bad", "--help"]));
+ expect(await run(["od", "--width", "bad", "--help"], "AB")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: od [OPTION]... [FILE]...\n") });
+ expect(await run(["od", "--width=1x"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid suffix in --width argument '1x'\n" });
+ expect(await run(["od", "--width=1x", "--help"])).toMatchObject(await systemRun(["od", "--width=1x", "--help"]));
+ expect(await run(["od", "-w1x"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid suffix in -w argument '1x'\n" });
+ expect(await run(["od", "-w-1"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid -w argument '-1'\n" });
+ expect(await run(["od", "-w0"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid -w argument '0'\n" });
+ expect(await run(["od", "-w4", "-tcz"], "x")).toMatchObject({ code: 0, stdout: "0000000 x >x<\n0000001\n" });
+ expect(await run(["od", "-An", "-c", "-j", "3"], "abcd")).toMatchObject({ code: 0, stdout: " d\n" });
+ expect(await run(["od", "-An", "-j", "4"], "abcd")).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["od", "-An", "-j", "1kB"], "abcd")).toMatchObject({ code: 1, stdout: "", stderr: "od: cannot skip past end of combined input\n" });
+ await writeFile(join(dir, "od-skip"), "abc");
+ expect(await run(["od", "-An", "-t", "x1", "-j", "3", "od-skip", "od-skip"])).toMatchObject({ code: 0, stdout: " 61 62 63\n" });
+ expect(await run(["od", "-j1", "/dev/null"])).toMatchObject({ code: 0, stdout: "0000001\n" });
+ expect(await run(["od", "-j1", "-N0", "/dev/null"])).toMatchObject({ code: 0, stdout: "0000001\n" });
+ expect(await run(["od", "--traditional"], "")).toMatchObject({ code: 0, stdout: "0000000\n" });
+ expect(await run(["od", "--traditional", "-t", "x1", "1", "2"], "abcdef")).toMatchObject({ code: 0, stdout: "0000001 (0000002) 62 63 64 65 66\n0000006 (0000007)\n" });
+ await writeFile(join(dir, "od-traditional"), "abcdef\n");
+ expect(await run(["od", "--traditional", "od-traditional", "+1", "bad"])).toMatchObject({ code: 1, stdout: "", stderr: `od: extra operand ${diagnosticQuote("+1")}\nod: compatibility mode supports at most one file\nTry 'od --help' for more information.\n` });
+ expect(await run(["od", "--traditional", "od-traditional", "bad", "+1"])).toMatchObject({ code: 1, stdout: "", stderr: `od: extra operand ${diagnosticQuote("bad")}\nod: compatibility mode supports at most one file\nTry 'od --help' for more information.\n` });
+ expect(await run(["od", "--traditional", "od-traditional", "first\nfile"])).toMatchObject({ code: 1, stdout: "", stderr: `od: extra operand ${diagnosticQuote("first\\nfile")}\nod: compatibility mode supports at most one file\nTry 'od --help' for more information.\n` });
+ expect(await run(["od", "--traditional", "od-traditional", "08"])).toMatchObject({ code: 1, stdout: "", stderr: `od: extra operand ${diagnosticQuote("08")}\nod: compatibility mode supports at most one file\nTry 'od --help' for more information.\n` });
+ expect(await run(["od", "--traditional", "od-traditional", "+08"])).toMatchObject({ code: 1, stdout: "", stderr: `od: extra operand ${diagnosticQuote("+08")}\nod: compatibility mode supports at most one file\nTry 'od --help' for more information.\n` });
+ expect(await run(["od", "--traditional", "-j2", "od-traditional", "+1"])).toMatchObject({ code: 0, stdout: "0000001 061542 062544 005146\n0000007\n" });
+ expect(await run(["od", "--traditional", "--skip-bytes=2", "-N2", "od-traditional", "+1", "+3"])).toMatchObject({ code: 0, stdout: "0000001 (0000003) 061542\n0000003 (0000005)\n" });
+ expect(await shell('printf abcdefg | ("$BUN" "$BNU" od -An -N3 -c; "$BUN" "$BNU" od -An -N3 -c)')).toMatchObject({ code: 0, stdout: " a b c\n d e f\n" });
+ expect(await run(["od", "-t", "x"], "ABCDEFGH\n")).toMatchObject({ code: 0, stdout: "0000000 44434241 48474645 0000000a\n0000011\n" });
+ expect(await run(["od", "-t", "xz"], "ABCDEFGH\n")).toMatchObject({ code: 0, stdout: "0000000 44434241 48474645 0000000a >ABCDEFGH.<\n0000011\n" });
+ expect(await run(["od", "-t", "u"], "ABCDEFGH\n")).toMatchObject({ code: 0, stdout: "0000000 1145258561 1212630597 10\n0000011\n" });
+ expect(await run(["od", "-An", "-t", "x8"], "abcdefgh")).toMatchObject({ code: 0, stdout: " 6867666564636261\n" });
+ expect(await run(["od", "-t", "x1c"], "AB\n")).toMatchObject({ code: 0, stdout: "0000000 41 42 0a\n A B \\n\n0000003\n" });
+ expect(await run(["od", "-t", "x1d1"], "AB\n")).toMatchObject({ code: 0, stdout: "0000000 41 42 0a\n 65 66 10\n0000003\n" });
+ expect(await run(["od", "-An", "-t", "d1x1"], "AB\n")).toMatchObject({ code: 0, stdout: " 65 66 10\n 41 42 0a\n" });
+ expect(await run(["od", "-t", "u1x1"], "AB\n")).toMatchObject({ code: 0, stdout: "0000000 65 66 10\n 41 42 0a\n0000003\n" });
+ expect(await run(["od", "-An", "-t", "x1", "-t", "c"], "AB\n")).toMatchObject({ code: 0, stdout: " 41 42 0a\n A B \\n\n" });
+ expect(await run(["od", "-t", "x1cz"], "AB\n")).toMatchObject({ code: 0, stdout: "0000000 41 42 0a\n A B \\n >AB.<\n0000003\n" });
+ const floatBytes = Buffer.from([0, 0, 0x80, 0x3f, 0, 0, 0, 0x40]);
+ expect(await run(["od", "-An", "-t", "f", "--endian=little"], floatBytes)).toMatchObject({ code: 0, stdout: " 2.000000473111868\n" });
+ expect(await run(["od", "-An", "-t", "fF", "--endian=little"], floatBytes)).toMatchObject({ code: 0, stdout: " 1 2\n" });
+ expect(await run(["od", "-An", "-t", "f2"], Buffer.from([1, 2, 3]))).toMatchObject({ code: 0, stderr: "" });
+ expect(await run(["od", "-An", "-t", "f4"], Buffer.from([1, 2, 3]))).toMatchObject({ code: 0, stderr: "" });
+ expect(await run(["od", "-An", "-t", "f8"], Buffer.from([1, 2, 3]))).toMatchObject({ code: 0, stderr: "" });
+ expect(await run(["od", "-An", "-t", "fH"], Buffer.from([0x78, 0x0a]))).toMatchObject({ code: 0, stdout: " 0.00019741058\n" });
+ expect(await run(["od", "-An", "-t", "fB"], Buffer.from([0x78, 0x0a]))).toMatchObject({ code: 0, stdout: " 1.1940766e-32\n" });
+ expect(await run(["od", "-t", "bad"], "x\n")).toMatchObject(await systemRun(["od", "-t", "bad"], "x\n"));
+ expect(await run(["od", "-t", "f3z"], "x\n")).toMatchObject(await systemRun(["od", "-t", "f3z"], "x\n"));
+ expect(await run(["od", "-A", "q"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid output address radix 'q'; it must be one character from [doxn]\n" });
+ expect(await run(["od", "-t", "q1"], "x\n")).toMatchObject(await systemRun(["od", "-t", "q1"], "x\n"));
+ expect(await run(["od", "-t", "a1"], "x\n")).toMatchObject(await systemRun(["od", "-t", "a1"], "x\n"));
+ expect(await run(["od", "-t", "c1z"], "x\n")).toMatchObject(await systemRun(["od", "-t", "c1z"], "x\n"));
+ expect(await run(["od", "-t", "x9"], "x\n")).toMatchObject(await systemRun(["od", "-t", "x9"], "x\n"));
+ expect(await run(["od", "-t", "q\n1"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: `od: invalid character 'q' in type string ${diagnosticQuote("q\\n1")}\n` });
+ expect(await run(["od", "-t", "x1\nq"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: `od: invalid character '\n' in type string ${diagnosticQuote("x1\\nq")}\n` });
+ expect(await run(["od", "-t", "f3\nz"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: `od: invalid type string ${diagnosticQuote("f3\\nz")};\nthis system doesn't provide a 3-byte floating point type\n` });
+ expect(await run(["od", "-t", "x9\nz"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: `od: invalid type string ${diagnosticQuote("x9\\nz")};\nthis system doesn't provide a 9-byte integral type\n` });
+ expect(await run(["od", "-N10", "-S10"], " ")).toMatchObject({ code: 0, stdout: "0000000 \n" });
+ expect(await run(["od", "-S10"], " ")).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["od", "-S0"], Buffer.from([0]))).toMatchObject({ code: 0, stdout: "0000000 \n" });
+ expect(await run(["od", "--strings=0"], Buffer.from([0x61, 0, 0]))).toMatchObject({ code: 0, stdout: "0000000 a\n0000002 \n" });
+ expect(await run(["od", "-S", ""], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid -S argument ''\n" });
+ expect(await run(["od", "-S", "bad"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid suffix in -S argument 'bad'\n" });
+ expect(await run(["od", "-S", "bad", "--help"], "x\n")).toMatchObject(await systemRun(["od", "-S", "bad", "--help"], "x\n"));
+ expect(await run(["od", "-S", "x"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid -S argument 'x'\n" });
+ expect(await run(["od", "-S", "1R"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: -S argument '1R' too large\n" });
+ expect(await run(["od", "-S", "R"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: -S argument 'R' too large\n" });
+ expect(await run(["od", "-S", "QB"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: -S argument 'QB' too large\n" });
+ expect(await run(["od", "--strings="], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid --strings argument ''\n" });
+ expect(await run(["od", "--strings=bad"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid suffix in --strings argument 'bad'\n" });
+ expect(await run(["od", "--strings=bad", "--help"])).toMatchObject(await systemRun(["od", "--strings=bad", "--help"]));
+ expect(await run(["od", "--strings", "bad", "--help"], "x\n")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: od [OPTION]... [FILE]...\n") });
+ expect(await run(["od", "--strings=-1"], "x\n")).toMatchObject({ code: 1, stdout: "", stderr: "od: invalid --strings argument '-1'\n" });
+ expect(await run(["od", "--strings=-1", "--help"])).toMatchObject(await systemRun(["od", "--strings=-1", "--help"]));
+ await writeFile(join(dir, "1"), "xy");
+ expect(await run(["od", "-An", "-tx1", "1"])).toMatchObject({ code: 0, stdout: " 78 79\n" });
+ expect(await run(["od", "-An", "-tx1", "1."])).toMatchObject({ code: 1, stderr: "od: 1.: No such file or directory\n" });
+ await mkdir(join(dir, "od-dir"));
+ expect(await run(["od", "od-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "od: od-dir: Is a directory\n" });
+ expect(await run(["od", "+1."], "a")).toMatchObject({ code: 0, stdout: "0000001\n" });
+ expect(await run(["od", "+1", "-tx1"], "abcdef")).toMatchObject({ code: 1, stderr: "od: +1: No such file or directory\n" });
+ expect(await run(["od", "+1.b"], "a".repeat(512))).toMatchObject({ code: 0, stdout: "0001000\n" });
+ expect(await run(["od", "+ 0"], "")).toMatchObject({ code: 1, stderr: "od: '+ 0': No such file or directory\n" });
+ expect(await run(["numfmt", "--from=si", "1K", "2M"])).toMatchObject({ code: 0, stdout: "1000\n2000000\n" });
+ expect(await run(["numfmt", "12\n3"])).toMatchObject(await systemRun(["/usr/bin/numfmt", "12\n3"]));
+ expect(await run(["numfmt", "--field=2", "a\n12"])).toMatchObject(await systemRun(["/usr/bin/numfmt", "--field=2", "a\n12"]));
+ expect(await run(["numfmt", "--h"])).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: option '--h' is ambiguous; possibilities: '--header' '--help'\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--v"])).toMatchObject({ code: 0, stdout: expect.stringContaining("bnu 9.11\n") });
+ expect(await run(["numfmt", "1", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n"), stderr: "" });
+ expect(await run(["numfmt", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: unrecognized option '--bad'\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--version=1", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: option '--version' doesn't allow an argument\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--f=si", "1K"])).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: option '--f=si' is ambiguous; possibilities: '--from' '--from-unit' '--field' '--format'\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--fr=si", "1K"])).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: option '--fr=si' is ambiguous; possibilities: '--from' '--from-unit'\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--for=%5f", "1"])).toMatchObject({ code: 0, stdout: " 1\n" });
+ expect(await run(["numfmt", "--from", "--help", "1"])).toMatchObject(await systemRun(["numfmt", "--from", "--help", "1"]));
+ expect(await run(["numfmt", "--from", "bad", "--help"])).toMatchObject(await systemRun(["numfmt", "--from", "bad", "--help"]));
+ expect(await run(["numfmt", "--from", "si", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n") });
+ expect(await run(["numfmt", "--from=si", "--help", "1K"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n") });
+ expect(await run(["numfmt", "--from=s", "1K"])).toMatchObject({ code: 0, stdout: "1000\n" });
+ expect(await run(["numfmt", "--from=a", "1Ki"])).toMatchObject({ code: 0, stdout: "1024\n" });
+ expect(await run(["numfmt", "--from=iec", "1K"])).toMatchObject({ code: 0, stdout: "1024\n" });
+ expect(await run(["numfmt", "--from=iec-i", "1Ki"])).toMatchObject({ code: 0, stdout: "1024\n" });
+ expect(await run(["numfmt", "--from=auto", "1Ki"])).toMatchObject({ code: 0, stdout: "1024\n" });
+ expect(await run(["numfmt", "--from=si", "1.5"])).toMatchObject({ code: 0, stdout: "1.5\n" });
+ expect(await run(["numfmt", "--from=iec", "1.25"])).toMatchObject({ code: 0, stdout: "1.25\n" });
+ expect(await run(["numfmt", "--from=si", "1.25K"])).toMatchObject({ code: 0, stdout: "1250\n" });
+ expect(await run(["numfmt", "--from=iec", "1KB"])).toMatchObject({ code: 2, stderr: `numfmt: invalid suffix in input ${diagnosticQuote("1KB")}: ${diagnosticQuote("B")}\n` });
+ expect(await run(["numfmt", "--from=si", "1Ki"])).toMatchObject({ code: 2, stderr: `numfmt: invalid suffix in input ${diagnosticQuote("1Ki")}: ${diagnosticQuote("i")}\n` });
+ expect(await run(["numfmt", "--from=auto", "1KiB"])).toMatchObject({ code: 2, stderr: `numfmt: invalid suffix in input ${diagnosticQuote("1KiB")}: ${diagnosticQuote("B")}\n` });
+ expect(await run(["numfmt", "--from=auto", "1B"])).toMatchObject({ code: 2, stderr: `numfmt: invalid suffix in input: ${diagnosticQuote("1B")}\n` });
+ expect(await run(["numfmt", "--from=auto", "1i"])).toMatchObject({ code: 2, stderr: `numfmt: invalid suffix in input: ${diagnosticQuote("1i")}\n` });
+ expect(await run(["numfmt", "--invalid=abort", "bad", "1"])).toMatchObject({ code: 2, stdout: "", stderr: `numfmt: invalid number: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["numfmt", "--invalid=abort", "1", "bad", "2"])).toMatchObject({ code: 2, stdout: "1\n", stderr: `numfmt: invalid number: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["numfmt", "--header=1"], "h\n1\nbad\n2\n")).toMatchObject({ code: 2, stdout: "h\n1\n", stderr: `numfmt: invalid number: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["numfmt", "-d,", "12\n3"])).toMatchObject(await systemRun(["/usr/bin/numfmt", "-d,", "12\n3"]));
+ expect(await run(["numfmt", "-d,", "12\t3"])).toMatchObject(await systemRun(["/usr/bin/numfmt", "-d,", "12\t3"]));
+ expect(await run(["numfmt", "--zero-terminated"], "1\u0002\0")).toMatchObject({ code: 2, stdout: "", stderr: `numfmt: invalid suffix in input: ${diagnosticQuote("1\\002")}\n` });
+ const rawNumfmt = Bun.spawn(["/bin/sh", "-c", `printf '12\\377\\n' | LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} numfmt >numfmt-raw-out 2>numfmt-raw-err`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await rawNumfmt.exited).toBe(2);
+ expect(await readFile(join(dir, "numfmt-raw-out"), "utf8")).toBe("");
+ expect([...await readFile(join(dir, "numfmt-raw-err"))]).toEqual([0x6e, 0x75, 0x6d, 0x66, 0x6d, 0x74, 0x3a, 0x20, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x78, 0x20, 0x69, 0x6e, 0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x3a, 0x20, 0x27, 0x31, 0x32, 0x5c, 0x33, 0x37, 0x37, 0x27, 0x0a]);
+ const rawHeaderNumfmt = Bun.spawn(["/bin/sh", "-c", `printf 'h\\n12\\377\\n' | LC_ALL=C ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} numfmt --header=1 >numfmt-header-raw-out 2>numfmt-header-raw-err`], {
+ cwd: dir,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(await rawHeaderNumfmt.exited).toBe(2);
+ expect(await readFile(join(dir, "numfmt-header-raw-out"), "utf8")).toBe("h\n");
+ expect([...await readFile(join(dir, "numfmt-header-raw-err"))]).toEqual([0x6e, 0x75, 0x6d, 0x66, 0x6d, 0x74, 0x3a, 0x20, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x20, 0x73, 0x75, 0x66, 0x66, 0x69, 0x78, 0x20, 0x69, 0x6e, 0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x3a, 0x20, 0x27, 0x31, 0x32, 0x5c, 0x33, 0x37, 0x37, 0x27, 0x0a]);
+ expect(await run(["numfmt", "--from"])).toMatchObject({ code: 1, stderr: "numfmt: option '--from' requires an argument\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--bad=4"])).toMatchObject({ code: 1, stderr: "numfmt: unrecognized option '--bad=4'\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--from=bad", "1"])).toMatchObject(await systemRun(["numfmt", "--from=bad", "1"]));
+ expect(await run(["numfmt", "--from=bad\nmode", "1"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `numfmt: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--from")}\nValid arguments are:\n - ${diagnosticQuote("none")}\n - ${diagnosticQuote("auto")}\n - ${diagnosticQuote("si")}\n - ${diagnosticQuote("iec")}\n - ${diagnosticQuote("iec-i")}\nTry 'numfmt --help' for more information.\n`,
+ });
+ expect(await run(["numfmt", "--from=", "1"])).toMatchObject(await systemRun(["numfmt", "--from=", "1"]));
+ expect(await run(["numfmt", "--from=", "--help"])).toMatchObject(await systemRun(["numfmt", "--from=", "--help"]));
+ expect(await run(["numfmt", "-d"])).toMatchObject({ code: 1, stderr: "numfmt: option requires an argument -- 'd'\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--to=iec", "2048"])).toMatchObject({ code: 0, stdout: "2.0K\n" });
+ expect(await run(["numfmt", "--to=s", "1000"])).toMatchObject({ code: 0, stdout: "1.0k\n" });
+ expect(await run(["numfmt", "--to=i", "1000"])).toMatchObject(await systemRun(["numfmt", "--to=i", "1000"]));
+ expect(await run(["numfmt", "--to", "bad", "--help"])).toMatchObject(await systemRun(["numfmt", "--to", "bad", "--help"]));
+ expect(await run(["numfmt", "--to=bad", "1"])).toMatchObject(await systemRun(["numfmt", "--to=bad", "1"]));
+ expect(await run(["numfmt", "--to=auto", "1"])).toMatchObject(await systemRun(["numfmt", "--to=auto", "1"]));
+ expect(await run(["numfmt", "--to=", "1"])).toMatchObject(await systemRun(["numfmt", "--to=", "1"]));
+ expect(await run(["numfmt", "--to=", "--help"])).toMatchObject(await systemRun(["numfmt", "--to=", "--help"]));
+ expect(await run(["numfmt", "--round=from-zero", "--to=si", "1500"])).toMatchObject({ code: 0, stdout: "1.5k\n" });
+ expect(await run(["numfmt", "--round=f", "--to=si", "1500"])).toMatchObject({ code: 0, stdout: "1.5k\n" });
+ expect(await run(["numfmt", "--round=n", "--to=si", "1500"])).toMatchObject({ code: 0, stdout: "1.5k\n" });
+ expect(await run(["numfmt", "--round", "bad", "--help"])).toMatchObject(await systemRun(["numfmt", "--round", "bad", "--help"]));
+ expect(await run(["numfmt", "--round=bad", "--to=si", "1500"])).toMatchObject(await systemRun(["numfmt", "--round=bad", "--to=si", "1500"]));
+ expect(await run(["numfmt", "--round=", "--help"])).toMatchObject(await systemRun(["numfmt", "--round=", "--help"]));
+ expect(await run(["numfmt", "--round=bad", "--help"])).toMatchObject(await systemRun(["numfmt", "--round=bad", "--help"]));
+ expect(await run(["numfmt", "--round=bad\nmode", "--to=si", "1500"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `numfmt: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--round")}\nValid arguments are:\n - ${diagnosticQuote("up")}\n - ${diagnosticQuote("down")}\n - ${diagnosticQuote("from-zero")}\n - ${diagnosticQuote("towards-zero")}\n - ${diagnosticQuote("nearest")}\nTry 'numfmt --help' for more information.\n`,
+ });
+ expect(await run(["numfmt", "--invalid=bad", "1"])).toMatchObject(await systemRun(["numfmt", "--invalid=bad", "1"]));
+ expect(await run(["numfmt", "--invalid=i", "bad"])).toMatchObject({ code: 0, stdout: "bad\n", stderr: "" });
+ expect(await run(["numfmt", "--invalid=w", "bad"])).toMatchObject({ code: 0, stdout: "bad\n", stderr: `numfmt: invalid number: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["numfmt", "--invalid", "bad", "--help"])).toMatchObject(await systemRun(["numfmt", "--invalid", "bad", "--help"]));
+ expect(await run(["numfmt", "--invalid=", "--help"])).toMatchObject(await systemRun(["numfmt", "--invalid=", "--help"]));
+ expect(await run(["numfmt", "--invalid=bad", "--help"])).toMatchObject(await systemRun(["numfmt", "--invalid=bad", "--help"]));
+ expect(await run(["numfmt", "--to=si", "--suffix=B", "--padding=6", "1000", "2000000"])).toMatchObject({ code: 0, stdout: " 1.0kB\n 2.0MB\n" });
+ expect(await run(["numfmt", "--to=si", "--", "998.9", "999.01", "-999.01"])).toMatchObject({ code: 0, stdout: "999\n1.0k\n-1.0k\n" });
+ expect(await run(["numfmt", "--to=si", "--format=%.2f", "--", "998.9", "999.01", "-999.01"])).toMatchObject({ code: 0, stdout: "999.00\n1.00k\n-1.00k\n" });
+ expect(await run(["numfmt", "--to=si", "--round=nearest", "--format=%.2f", "--", "999.5", "-999.5"])).toMatchObject({ code: 0, stdout: "1.00k\n-1.00k\n" });
+ expect(await run(["numfmt", "--format=%+5f", "--", "1", "-1"])).toMatchObject({ code: 0, stdout: " 1\n -1\n" });
+ expect(await run(["numfmt", "--format=%0+5f", "--", "1", "-1"])).toMatchObject({ code: 0, stdout: "00001\n-0001\n" });
+ expect(await run(["numfmt", "--format=%-+5f", "1"])).toMatchObject(await systemRun(["numfmt", "--format=%-+5f", "1"]));
+ expect(await run(["numfmt", "--format=%s", "1"])).toMatchObject(await systemRun(["numfmt", "--format=%s", "1"]));
+ expect(await run(["numfmt", "--format", "%s", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n") });
+ expect(await run(["numfmt", "--format", "%f%f", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n") });
+ expect(await run(["numfmt", "--format=%s\nx", "1"])).toMatchObject({ code: 1, stdout: "", stderr: `numfmt: invalid format ${diagnosticQuote("%s\\nx")}, directive must be %[0]['][-][N][.][N]f\n` });
+ expect(await run(["numfmt", "--format=%f%f", "1"])).toMatchObject(await systemRun(["numfmt", "--format=%f%f", "1"]));
+ expect(await run(["numfmt", "--format=%f\n%f", "1"])).toMatchObject({ code: 1, stdout: "", stderr: `numfmt: format ${diagnosticQuote("%f\\n%f")} has too many % directives\n` });
+ expect(await run(["numfmt", "--padding=+3", "1"])).toMatchObject({ code: 0, stdout: " 1\n" });
+ expect(await run(["numfmt", "--padding=+0", "1"])).toMatchObject(await systemRun(["numfmt", "--padding=+0", "1"]));
+ expect(await run(["numfmt", "--padding", "bad", "--help"])).toMatchObject(await systemRun(["numfmt", "--padding", "bad", "--help"]));
+ expect(await run(["numfmt", "--padding", "3", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n") });
+ expect(await run(["numfmt", "--padding=bad", "1"])).toMatchObject(await systemRun(["numfmt", "--padding=bad", "1"]));
+ expect(await run(["numfmt", "--header=1", "--field=2", "--from=si", "--invalid=ignore"], "name size\na 1K\nb bad\n")).toMatchObject({ code: 0, stdout: "name size\na 1000\nb bad\n" });
+ expect(await run(["numfmt", "--header=+1", "--from=si"], "size\n1K\n")).toMatchObject({ code: 0, stdout: "size\n1000\n" });
+ expect(await run(["numfmt", "--header=bad", "1"])).toMatchObject(await systemRun(["numfmt", "--header=bad", "1"]));
+ expect(await run(["numfmt", "--header", "bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n") });
+ expect(await run(["numfmt", "--field=", "1"])).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: fields are numbered from 1\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--field", "bad", "--help"])).toMatchObject(await systemRun(["numfmt", "--field", "bad", "--help"]));
+ expect(await run(["numfmt", "--field=bad", "--help"])).toMatchObject(await systemRun(["numfmt", "--field=bad", "--help"]));
+ expect(await run(["numfmt", "--field", "--help", "--version"])).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: invalid field range\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--field=--help", "--version"])).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: invalid field range\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--field", "1", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n") });
+ expect(await run(["numfmt", "--field=1,,2", "1 2"])).toMatchObject({ code: 1, stdout: "", stderr: "numfmt: fields are numbered from 1\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--field=9999999999999999999", "--from=si", "1K"])).toMatchObject({ code: 0, stdout: "1K\n" });
+ expect(await run(["numfmt", "--field=1,9999999999999999999", "--from=si", "1K"])).toMatchObject({ code: 0, stdout: "1000\n" });
+ expect(await run(["numfmt", "--field=99999999999999999999", "--from=si", "1K"])).toMatchObject({ code: 1, stderr: "numfmt: field number '99999999999999999999' is too large\nTry 'numfmt --help' for more information.\n" });
+ expect(await run(["numfmt", "--field=1.2", "1"])).toMatchObject(await systemRun(["numfmt", "--field=1.2", "1"]));
+ expect(await run(["numfmt", "--field=1:2", "1"])).toMatchObject(await systemRun(["numfmt", "--field=1:2", "1"]));
+ expect(await run(["numfmt", "--from-unit=2K", "1"])).toMatchObject({ code: 0, stdout: "2000\n" });
+ expect(await run(["numfmt", "--to-unit=1K", "1000"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["numfmt", "--from-unit", "1KB", "--help"])).toMatchObject(await systemRun(["numfmt", "--from-unit", "1KB", "--help"]));
+ expect(await run(["numfmt", "--from-unit", "2K", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n") });
+ expect(await run(["numfmt", "--from-unit=1KB", "1"])).toMatchObject(await systemRun(["numfmt", "--from-unit=1KB", "1"]));
+ expect(await run(["numfmt", "--from-unit=1\n2", "1"])).toMatchObject({ code: 1, stdout: "", stderr: `numfmt: invalid unit size: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["numfmt", "-d", ":", "--field=2", "--from=iec"], "a:2K\n")).toMatchObject({ code: 0, stdout: "a:2048\n" });
+ expect(await run(["numfmt", "-d", "ab", "--help"])).toMatchObject(await systemRun(["numfmt", "-d", "ab", "--help"]));
+ expect(await run(["numfmt", "--delimiter=ab", "--help"])).toMatchObject(await systemRun(["numfmt", "--delimiter=ab", "--help"]));
+ expect(await run(["numfmt", "-d", ":", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: numfmt [OPTION]... [NUMBER]...\n") });
+ expect(await run(["numfmt", "-d", "ab", "--field=2", "1ab2"])).toMatchObject({ code: 1, stderr: "numfmt: the delimiter must be a single character\n" });
+ expect(await run(["numfmt", "-d", "ç", "--field=2", "aç2"])).toMatchObject({ code: 0, stdout: "aç2\n" });
+ expect(await run(["numfmt", "-d", "ç", "--field=2", "aç2"], "", { env: { LC_ALL: "C" } })).toMatchObject({ code: 1, stderr: "numfmt: the delimiter must be a single character\n" });
+ expect(await shell(`bash -c 'LC_ALL=C "$BUN" "$BNU" numfmt -d $'"'"'\\302'"'"' --field=2 --invalid=ignore $'"'"'1\\302\\2672K'"'"''`)).toMatchObject({ code: 0, stdout: "1·2K\n" });
+ expect(await shell(`bash -c 'delim=$(printf "\\242\\343"); input=$(printf "1\\242\\3432K"); LC_ALL=zh_CN.gb18030 "$BUN" "$BNU" numfmt --from=si --field=2 -d "$delim" "$input" | /usr/bin/od -An -tx1 | tr -d " \\n"'`)).toMatchObject({ code: 0, stdout: "31a2e3323030300a" });
+ expect(await shell(`bash -c 'delim=$(printf "\\377"); input=$(printf "1\\3772K"); LC_ALL=zh_CN.gb18030 "$BUN" "$BNU" numfmt --from=si --field=2 -d "$delim" "$input" | /usr/bin/od -An -tx1 | tr -d " \\n"'`)).toMatchObject({ code: 0, stdout: "31ff323030300a" });
+});
+
+test("fmt handles formatting options and file diagnostics", async () => {
+ expect(await run(["fmt", "-w", "10"], "alpha beta gamma\n")).toMatchObject({ code: 0, stdout: "alpha beta\ngamma\n" });
+ await writeFile(join(dir, "fmt-raw"), Uint8Array.of(0xff, 0x20, 0x61, 0x20, 0x62, 0x20, 0x63, 0x0a));
+ const fmtRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "fmt", "-w1", "fmt-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "fmt-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await fmtRaw.exited).toBe(0);
+ expect(await new Response(fmtRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "fmt-raw-out"))]).toEqual([0xff, 0x0a, 0x61, 0x0a, 0x62, 0x0a, 0x63, 0x0a]);
+ expect(await run(["fmt", "-w", "+10"], "one two three four\n")).toMatchObject({ code: 0, stdout: "one two\nthree four\n" });
+ expect(await run(["fmt", "-w+10"], "one two three four\n")).toMatchObject({ code: 0, stdout: "one two\nthree four\n" });
+ expect(await run(["fmt", "--width=+10"], "one two three four\n")).toMatchObject({ code: 0, stdout: "one two\nthree four\n" });
+ expect(await run(["fmt", "-w", "0"], "a b c\n")).toMatchObject({ code: 0, stdout: "a\nb\nc\n" });
+ expect(await run(["fmt", "-g", "0"], "a b c\n")).toMatchObject({ code: 0, stdout: "a b c\n" });
+ expect(await run(["fmt", "-g", "+0"], "a b c\n")).toMatchObject({ code: 0, stdout: "a b c\n" });
+ expect(await run(["fmt", "-g+0"], "one two three\n")).toMatchObject({ code: 0, stdout: "one\ntwo three\n" });
+ expect(await run(["fmt", "-g", "+0"], "one two three\n")).toMatchObject({ code: 0, stdout: "one\ntwo three\n" });
+ expect(await run(["fmt", "-w", "75", "-g", "+0"], "one two three\n")).toMatchObject({ code: 0, stdout: "one two three\n" });
+ expect(await run(["fmt", "-u"], "alpha beta\n")).toMatchObject({ code: 0, stdout: "alpha beta\n" });
+ expect(await run(["fmt", "-w", "10", "-g", "8"], "one two three four\n")).toMatchObject({ code: 0, stdout: "one two\nthree four\n" });
+ expect(await run(["fmt", "-w", "+10", "-g", "+8"], "one two three four\n")).toMatchObject({ code: 0, stdout: "one two\nthree four\n" });
+ expect(await run(["fmt", "-g", "10", "-w", "12"], "Alpha beta gamma delta E. Zeta eta\n")).toMatchObject({ code: 0, stdout: "Alpha beta\ngamma delta\nE. Zeta eta\n" });
+ expect(await run(["fmt", "-w", "7"], "aa bb cc dd ee")).toMatchObject({ code: 0, stdout: "aa\nbb cc\ndd ee\n" });
+ expect(await run(["fmt", "-w1", "-s"], "=\u00a0=\n")).toMatchObject({ code: 0, stdout: "=\u00a0=\n" });
+ expect(await run(["fmt", "-w", "12", "--crown-margin"], " alpha beta gamma\n delta epsilon\n")).toMatchObject({ code: 0, stdout: " alpha beta\n gamma\n delta\n epsilon\n" });
+ expect(await run(["fmt", "-w", "12", "--tagged-paragraph"], " alpha beta gamma\n delta epsilon\n")).toMatchObject({ code: 0, stdout: " alpha\nbeta gamma\n delta\nepsilon\n" });
+ expect(await run(["fmt", "-t", "-w", "12"], "tag one two three\n cont four five\n")).toMatchObject({ code: 0, stdout: "tag one two\n three cont\n four five\n" });
+ expect(await run(["fmt", "-p", "# ", "-w", "10"], "# one two three\nplain text\n")).toMatchObject({ code: 0, stdout: "# one two\n# three\nplain text\n" });
+ expect(await run(["fmt", "--w=5"], "one two three\n")).toMatchObject({ code: 0, stdout: "one\ntwo\nthree\n" });
+ expect(await run(["fmt", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: fmt [-WIDTH] [OPTION]... [FILE]...\n") });
+ expect(await run(["fmt", "--v"])).toMatchObject({ code: 0, stdout: expect.stringContaining("bnu 9.11\n") });
+ expect(await run(["fmt", "fmt-raw", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: fmt [-WIDTH] [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["fmt", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: unrecognized option '--bad'\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "--h=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: option '--help' doesn't allow an argument\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "--v=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: option '--version' doesn't allow an argument\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "--help=1", "--version"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: option '--help' doesn't allow an argument\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "--version=1", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: option '--version' doesn't allow an argument\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "--width", "--help"])).toMatchObject(await systemRun(["fmt", "--width", "--help"]));
+ expect(await run(["fmt", "--width=5", "--help"], "one two three\n")).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: fmt [-WIDTH] [OPTION]... [FILE]...\n") });
+ expect(await run(["fmt", "--go", "x"], "")).toMatchObject(await systemRun(["fmt", "--go", "x"], ""));
+ expect(await run(["fmt", "--spl"], "one two three\n")).toMatchObject({ code: 0, stdout: "one two three\n" });
+ expect(await run(["fmt", "--cro=x"], "")).toMatchObject({ code: 1, stderr: "fmt: option '--crown-margin' doesn't allow an argument\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "-p>"], ">one two three\n>four five\n")).toMatchObject({ code: 0, stdout: ">one two three four five\n" });
+ expect(await run(["fmt", "-p", ">"], "> quoted\n> text\n")).toMatchObject({ code: 0, stdout: "> quoted text\n" });
+ expect(await run(["fmt", "-p", "\u00e7"], "\u00e7a\n\u00e7b\n")).toMatchObject({ code: 0, stdout: "\u00e7a b\n" });
+ await writeFile(join(dir, "fmt-input"), "one two three\n");
+ expect(await run(["fmt", "fmt-input", "-5"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: invalid option -- 5; -WIDTH is recognized only when it is the first\noption; use -w N instead\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "--", "-5"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: cannot open '-5' for reading: No such file or directory\n" });
+ expect(await run(["fmt", "--", "-w", "5", "fmt-input"])).toMatchObject({ code: 1, stdout: "one two three\n", stderr: "fmt: cannot open '-w' for reading: No such file or directory\nfmt: cannot open '5' for reading: No such file or directory\n" });
+ expect(await run(["fmt", "missing'fmt"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: cannot open \"missing'fmt\" for reading: No such file or directory\n" });
+ expect(await run(["fmt", "missing\nfmt"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: cannot open 'missing'$'\\n''fmt' for reading: No such file or directory\n" });
+ await mkdir(join(dir, "dir'fmt"));
+ expect(await run(["fmt", "dir'fmt"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: error reading \"dir'fmt\": Is a directory\n" });
+ await symlink("loop'fmt", join(dir, "loop'fmt"));
+ expect(await run(["fmt", "loop'fmt"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: cannot open \"loop'fmt\" for reading: Too many levels of symbolic links\n" });
+ expect(await run(["fmt", "-w"])).toMatchObject({ code: 1, stderr: "fmt: option requires an argument -- 'w'\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "--width"])).toMatchObject({ code: 1, stderr: "fmt: option '--width' requires an argument\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "-g"])).toMatchObject({ code: 1, stderr: "fmt: option requires an argument -- 'g'\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "--goal"])).toMatchObject({ code: 1, stderr: "fmt: option '--goal' requires an argument\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "-p"])).toMatchObject({ code: 1, stderr: "fmt: option requires an argument -- 'p'\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "--prefix"])).toMatchObject({ code: 1, stderr: "fmt: option '--prefix' requires an argument\nTry 'fmt --help' for more information.\n" });
+ expect(await run(["fmt", "-72x"], "")).toMatchObject(await systemRun(["fmt", "-72x"], ""));
+ expect(await run(["fmt", "-w", "-1"], "")).toMatchObject(await systemRun(["fmt", "-w", "-1"], ""));
+ expect(await run(["fmt", "-w-10"], "")).toMatchObject(await systemRun(["fmt", "-w-10"], ""));
+ expect(await run(["fmt", "-g-10"], "")).toMatchObject(await systemRun(["fmt", "-g-10"], ""));
+ expect(await run(["fmt", "-g", "x"], "")).toMatchObject(await systemRun(["fmt", "-g", "x"], ""));
+ expect(await run(["fmt", "-w", "1\n2"], "")).toMatchObject({ code: 1, stdout: "", stderr: `fmt: invalid width: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["fmt", "-g", "1\n2"], "")).toMatchObject({ code: 1, stdout: "", stderr: `fmt: invalid width: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["fmt", "-w+bad"], "")).toMatchObject(await systemRun(["fmt", "-w+bad"], ""));
+ expect(await run(["fmt", "-g+bad"], "")).toMatchObject(await systemRun(["fmt", "-g+bad"], ""));
+ expect(await run(["fmt", "-w", "2500"], "a b\n")).toMatchObject({ code: 0, stdout: "a b\n" });
+ expect(await run(["fmt", "-w", "2501"], "")).toMatchObject(await systemRun(["fmt", "-w", "2501"], ""));
+ expect(await run(["fmt", "-g", "76"], "")).toMatchObject(await systemRun(["fmt", "-g", "76"], ""));
+ expect(await run(["fmt", "-w", "2500", "-g", "2500"], "a b\n")).toMatchObject({ code: 0, stdout: "a b\n" });
+ expect(await run(["fmt", "-w", "32767"], "")).toMatchObject(await systemRun(["fmt", "-w", "32767"], ""));
+ expect(await run(["fmt", "-g", "32767"], "")).toMatchObject(await systemRun(["fmt", "-g", "32767"], ""));
+ expect(await run(["fmt", "-w", "32768"], "")).toMatchObject(await systemRun(["fmt", "-w", "32768"], ""));
+ expect(await run(["fmt", "-g", "32768"], "")).toMatchObject(await systemRun(["fmt", "-g", "32768"], ""));
+ expect(await run(["fmt", "-w", "+32768"], "")).toMatchObject(await systemRun(["fmt", "-w", "+32768"], ""));
+ await mkdir(join(dir, "fmt-dir"));
+ expect(await run(["fmt", "fmt-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: error reading 'fmt-dir': Is a directory\n" });
+ const missingFmt = await run(["fmt", "fmt-missing"]);
+ expect(missingFmt).toMatchObject({ code: 1, stdout: "" });
+ expect(missingFmt.stderr).toContain("fmt: cannot open 'fmt-missing' for reading: No such file or directory");
+ await symlink("fmt-loop", join(dir, "fmt-loop"));
+ expect(await run(["fmt", "fmt-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "fmt: cannot open 'fmt-loop' for reading: Too many levels of symbolic links\n" });
+});
+
+test("expr handles numeric, string and regex expressions", async () => {
+ expect(await run(["expr", "7", "+", "5"])).toMatchObject({ code: 0, stdout: "12\n" });
+ expect(await run(["expr", "--", "-11", "+", "12"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "(", "100", "%", "6", ")", "-", "8"])).toMatchObject({ code: 0, stdout: "-4\n" });
+ expect(await run(["expr", "1", "|", "(", "1", "/", "0", ")"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "0", "&", "(", "1", "/", "0", ")"])).toMatchObject({ code: 1, stdout: "0\n" });
+ expect(await run(["expr", "1", "|"])).toMatchObject(await systemRun(["expr", "1", "|"]));
+ expect(await run(["expr", "0", "&"])).toMatchObject(await systemRun(["expr", "0", "&"]));
+ expect(await run(["expr", "(", "1", "+", "2"])).toMatchObject(await systemRun(["expr", "(", "1", "+", "2"]));
+ expect(await run(["expr", "(", "1", "+", "2", "+"])).toMatchObject(await systemRun(["expr", "(", "1", "+", "2", "+"]));
+ expect(await run(["expr", "1", "=", "1", "extra"])).toMatchObject(await systemRun(["expr", "1", "=", "1", "extra"]));
+ expect(await run(["expr", "98782897298723498732987928734", "+", "1"])).toMatchObject({ code: 0, stdout: "98782897298723498732987928735\n" });
+ expect(await run(["expr", "+", "1"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "1", "+", "+", "2"])).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["expr", "+", "length"])).toMatchObject({ code: 0, stdout: "length\n" });
+ expect(await run(["expr", "+", ")"])).toMatchObject({ code: 0, stdout: ")\n" });
+ expect(await run(["expr", "+"])).toMatchObject({ code: 2, stderr: `expr: syntax error: missing argument after ${diagnosticQuote("+")}\n` });
+ expect(await run(["expr", "00"])).toMatchObject({ code: 1, stdout: "00\n" });
+ expect(await run(["expr", "000"])).toMatchObject({ code: 1, stdout: "000\n" });
+ expect(await run(["expr", "--", "-00"])).toMatchObject({ code: 1, stdout: "-00\n" });
+ expect(await run(["expr", "--", "+0"])).toMatchObject({ code: 0, stdout: "+0\n" });
+ expect(await run(["expr", "a", "=", "b"])).toMatchObject({ code: 1, stdout: "0\n" });
+ expect(await run(["expr", "length", "abcdef"])).toMatchObject({ code: 0, stdout: "6\n" });
+ expect(await shell(`raw=$(printf '\\316\\261bcdef'); LC_ALL=C "$BUN" "$BNU" expr length "$raw"`)).toMatchObject({ code: 0, stdout: "7\n", stderr: "" });
+ expect(await shell(`raw=$(printf '\\316\\261bcdef'); LC_ALL=fr_FR.utf8 "$BUN" "$BNU" expr length "$raw"`)).toMatchObject({ code: 0, stdout: "6\n", stderr: "" });
+ expect(await run(["expr", "substr", "abcdef", "2", "3"])).toMatchObject({ code: 0, stdout: "bcd\n" });
+ expect(await run(["expr", "substr", "abcdef", "x", "3"])).toMatchObject({ code: 1, stdout: "\n" });
+ expect(await run(["expr", "substr", "abcdef", "2", "x"])).toMatchObject({ code: 1, stdout: "\n" });
+ expect(await run(["expr", "substr", "abcdef", "+2", "3"])).toMatchObject({ code: 1, stdout: "\n" });
+ expect(await run(["expr", "substr", "abcdef"])).toMatchObject({ code: 2, stderr: `expr: syntax error: missing argument after ${diagnosticQuote("abcdef")}\n` });
+ expect(await run(["expr", "substr", "abcdef", "2"])).toMatchObject({ code: 2, stderr: `expr: syntax error: missing argument after ${diagnosticQuote("2")}\n` });
+ expect(await run(["expr", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: expr EXPRESSION\n or: expr OPTION\n") });
+ expect(await run(["expr", "--help", "x"])).toMatchObject({ code: 2, stderr: `expr: syntax error: unexpected argument ${diagnosticQuote("x")}\n` });
+ expect(await run(["expr", "index", "abcdef", "dx"])).toMatchObject({ code: 0, stdout: "4\n" });
+ expect(await run(["expr", "index", "abcdef"])).toMatchObject({ code: 2, stderr: `expr: syntax error: missing argument after ${diagnosticQuote("abcdef")}\n` });
+ expect(await run(["expr", "foobar", ":", "foo\\(.*\\)"])).toMatchObject({ code: 0, stdout: "bar\n" });
+ expect(await run(["expr", "foobar", ":", "foo"])).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["expr", "a(", ":", "a("])).toMatchObject({ code: 0, stdout: "2\n" });
+ expect(await run(["expr", "a^b", ":", "a^b"])).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["expr", "a*b", ":", "a\\(*\\)b"])).toMatchObject({ code: 0, stdout: "*\n" });
+ expect(await run(["expr", "b", ":", "a*\\(^b$\\)c*"])).toMatchObject({ code: 0, stdout: "b\n" });
+ expect(await run(["expr", "{1}a", ":", "\\(\\{1\\}a\\)"])).toMatchObject({ code: 0, stdout: "{1}a\n" });
+ expect(await run(["expr", "aa", ":", "a\\{1\\}\\{1\\}"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "a", ":", "**a"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "abc", ":", "[[:alpha:]]*"])).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["expr", "123", ":", "[[:digit:]]*"])).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["expr", "abc", ":", "[^[:digit:]]*"])).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["expr", "abc", ":", "[[:bad:]]"])).toMatchObject({ code: 2, stderr: "expr: Invalid character class name\n" });
+ expect(await run(["expr", "abc", ":", "[z-a]"])).toMatchObject({ code: 1, stdout: "0\n" });
+ expect(await run(["expr", "abc", ":", "[z-a]*"])).toMatchObject({ code: 1, stdout: "0\n" });
+ expect(await run(["expr", "abc", ":", "[az-a]*"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "abc", ":", "[^z-a]*"])).toMatchObject({ code: 0, stdout: "3\n" });
+ expect(await run(["expr", "]", ":", "[]a]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "a", ":", "[]a]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "b", ":", "[^]a]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "\\", ":", "[a\\-z]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "-", ":", "[a\\-z]"])).toMatchObject({ code: 1, stdout: "0\n" });
+ expect(await run(["expr", "-", ":", "[\\-]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "\\", ":", "[\\]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "\\]", ":", "[\\]]"])).toMatchObject({ code: 0, stdout: "2\n" });
+ expect(await run(["expr", "a", ":", "[[=a=]]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "a", ":", "[[.a.]]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "a", ":", "[[=a=][:digit:]]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "b", ":", "[^[=a=]]"])).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["expr", "a", ":", "[[=ab=]]"])).toMatchObject({ code: 2, stderr: "expr: Invalid collation character\n" });
+ expect(await run(["expr", "abc", ":", "["])).toMatchObject({ code: 2, stderr: "expr: Invalid regular expression\n" });
+ expect(await run(["expr", "abc", ":", "\\"])).toMatchObject({ code: 2, stderr: "expr: Trailing backslash\n" });
+ expect(await run(["expr", "match", "foo", "bar\\(.*\\)"])).toMatchObject({ code: 1, stdout: "\n" });
+ expect(await run(["expr", "match", "foo"])).toMatchObject({ code: 2, stderr: `expr: syntax error: missing argument after ${diagnosticQuote("foo")}\n` });
+});
+
+test("df, tsort, timeout, nice, nohup and kill command surfaces", async () => {
+ const df = await run(["df", "."]);
+ expect(df.code).toBe(0);
+ expect(df.stdout).toContain("Filesystem");
+ expect(df.stdout.trim().split("\n").length).toBeGreaterThan(1);
+ // No operands enumerate the mount table, while the kernel API mounts only
+ // appear when --all is requested.
+ const defaultDfMounts = await run(["df", "--output=target"]);
+ const allDfMounts = await run(["df", "--all", "--output=target"]);
+ expect(defaultDfMounts).toMatchObject({ code: 0, stderr: "" });
+ expect(defaultDfMounts.stdout).not.toContain("\n/proc\n");
+ expect(allDfMounts.stdout).toContain("\n/proc\n");
+ const dfi = await run(["df", "-i", "."]);
+ expect(dfi).toMatchObject({ code: 0 });
+ expect(dfi.stdout).toContain("Inodes");
+ expect(dfi.stdout).toContain("IUse%");
+ expect(dfi.stdout.trim().split("\n").length).toBeGreaterThan(1);
+ expect((await run(["df", "-ih", "."])).stdout).toContain("Inodes");
+ expect((await run(["df", "-h", "."])).stdout.split("\n")[0].replace(/ +/g, " ")).toBe("Filesystem Size Used Avail Use% Mounted on");
+ expect((await run(["df", "-H", "."])).stdout.trim().split("\n").at(-1)).toMatch(/\s[0-9.]+[BKMGTP]\s+[0-9.]+[BKMGTP]\s+[0-9.]+[BKMGTP]\s+\d+% \S+$/);
+ expect((await run(["df", "-k", "."])).stdout.trim().split("\n").length).toBeGreaterThan(1);
+ expect(await run(["df", "--sync", "--output=target", "."])).toMatchObject({
+ code: 0,
+ stdout: (await run(["df", "--no-sync", "--sync", "--output=target", "."])).stdout,
+ });
+ expect(await run(["df", "--sync", "--no-sync", "--output=target", "."])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "--sync"), "");
+ expect(await run(["df", "--no-sync", "--output=file", "--", "--sync"])).toMatchObject({ code: 0, stdout: "File\n--sync\n" });
+ const dfHelp = (await run(["df", "--help"])).stdout;
+ expect(dfHelp).toContain("Show information about the file system on which each FILE resides,\n");
+ expect(dfHelp).toContain(" -k\n");
+ expect((await run(["df", "-BM", "."])).stdout.trim().split("\n").length).toBeGreaterThan(1);
+ expect(await run(["df", "--he=bad", "."])).toMatchObject(await systemRun(["df", "--he=bad", "."]));
+ expect((await run(["df", "--block-size=human-readable", "."])).stdout.split("\n")[0].replace(/ +/g, " ")).toBe("Filesystem Size Used Avail Use% Mounted on");
+ expect((await run(["df", "--block-size=si", "."])).stdout.split("\n")[0].replace(/ +/g, " ")).toBe("Filesystem Size Used Avail Use% Mounted on");
+ expect(await run(["df", "--block-size=bad", "."])).toMatchObject({ code: 1, stdout: "", stderr: "df: invalid --block-size argument 'bad'\n" });
+ expect(await run(["df", "--block-size=bad", "--help"])).toMatchObject(await systemRun(["df", "--block-size=bad", "--help"]));
+ expect(await run(["df", "--block-size", "bad", "--help"])).toMatchObject(await systemRun(["df", "--block-size", "bad", "--help"]));
+ expect(await run(["df", "--block-size=1R", "."])).toMatchObject({ code: 1, stdout: "", stderr: "df: invalid suffix in --block-size argument '1R'\n" });
+ expect(await run(["df", "--blo=bad", "."])).toMatchObject(await systemRun(["df", "--blo=bad", "."]));
+ expect(await run(["df", "-Bbad", "."])).toMatchObject({ code: 1, stdout: "", stderr: "df: invalid -B argument 'bad'\n" });
+ expect(await run(["df", "-Bbad", "--help"])).toMatchObject(await systemRun(["df", "-Bbad", "--help"]));
+ expect(await run(["df", "-B", "bad", "--help"])).toMatchObject(await systemRun(["df", "-B", "bad", "--help"]));
+ expect(await run(["df", "-B1B", "."])).toMatchObject({ code: 1, stdout: "", stderr: "df: invalid suffix in -B argument '1B'\n" });
+ expect((await run(["df", "-B1", "."])).stdout.split("\n")[0]).toContain("1B-blocks");
+ expect((await run(["df", "--block-size=1KB", "."])).stdout.split("\n")[0]).toContain("1kB-blocks");
+ expect((await run(["df", "--block-size=1KiB", "."])).stdout.split("\n")[0]).toContain("1K-blocks");
+ expect((await run(["df", "."], "", { env: { BLOCK_SIZE: "1R" } })).stdout.split("\n")[0]).toContain("1B-blocks");
+ expect((await run(["df", "."], "", { env: { DF_BLOCK_SIZE: "1KB" } })).stdout.split("\n")[0]).toContain("1kB-blocks");
+ expect((await run(["df", "."], "", { env: { BLOCK_SIZE: "bad" } })).stdout.split("\n")[0]).toContain("1K-blocks");
+ expect((await run(["df", "."], "", { env: { POSIXLY_CORRECT: "1" } })).stdout.split("\n")[0]).toContain("512B-blocks");
+ expect((await run(["df", "."], "", { env: { POSIXLY_CORRECT: "1", BLOCK_SIZE: "bad" } })).stdout.split("\n")[0]).toContain("512B-blocks");
+ expect((await run(["df", "--local", "--output=source,target", "."])).stdout.split("\n")[0]).toBe("Filesystem Mounted on");
+ const dfType = await run(["df", "-T", "."]);
+ expect(dfType).toMatchObject({ code: 0 });
+ expect(dfType.stdout.split("\n")[0]).toContain("Type");
+ const currentFsType = dfType.stdout.trim().split("\n").at(-1).trim().split(/\s+/)[1];
+ expect(await run(["df", "-t", currentFsType, "."])).toMatchObject({ code: 0 });
+ expect(await run(["df", "--type=", "."])).toMatchObject({ code: 1, stdout: "", stderr: "df: no file systems processed\n" });
+ expect(await run(["df", "-t", ",", "."])).toMatchObject({ code: 1, stdout: "", stderr: "df: no file systems processed\n" });
+ expect(await run(["df", "-x", currentFsType, "."])).toMatchObject({ code: 1, stderr: "df: no file systems processed\n" });
+ expect((await run(["df", "-P", "."])).stdout.split("\n")[0].replace(/ +/g, " ")).toBe("Filesystem 1024-blocks Used Available Capacity Mounted on");
+ expect((await run(["df", "--out=source,size", "--out=target", "."])).stdout.split("\n")[0].replace(/ +/g, " ")).toBe("Filesystem 1K-blocks Mounted on");
+ expect((await run(["df", "--output=source,pcent", "/dev/null"])).stdout.split("\n")[0]).toBe((await systemRun(["df", "--output=source,pcent", "/dev/null"])).stdout.split("\n")[0]);
+ const dfOutputDefault = await run(["df", "--output", "."]);
+ const systemDfOutputDefault = await systemRun(["df", "--output", "."]);
+ expect(dfOutputDefault).toMatchObject({ code: 0, stderr: "" });
+ expect(dfOutputDefault.stdout.replace(/\d+/g, "#")).toBe(systemDfOutputDefault.stdout.replace(/\d+/g, "#"));
+ const dfOutputNumbers = await run(["df", "--output=itotal,iused,iavail,ipcent,size,used,avail,pcent", "."]);
+ const systemDfOutputNumbers = await systemRun(["df", "--output=itotal,iused,iavail,ipcent,size,used,avail,pcent", "."]);
+ expect(dfOutputNumbers).toMatchObject({ code: 0, stderr: "" });
+ expect(dfOutputNumbers.stdout.replace(/\d+/g, "#")).toBe(systemDfOutputNumbers.stdout.replace(/\d+/g, "#"));
+ const dfOutputInodes = await run(["df", "--output=itotal", "."]);
+ expect(dfOutputInodes.stdout.split(/\s+/).filter(Boolean).at(-1)).toBe(String(Number((await statfs(dir)).files)));
+ expect((await run(["df", "--ou=source", "."])).stdout.split("\n")[0]).toBe("Filesystem");
+ expect((await run(["df", "--outp=source", "."])).stdout.split("\n")[0]).toBe("Filesystem");
+ expect((await run(["df", "--outpu=source", "."])).stdout.split("\n")[0]).toBe("Filesystem");
+ const dfOutputPrefix = await run(["df", "--ou", "df-missing", "."]);
+ expect(dfOutputPrefix).toMatchObject({ code: 1, stderr: "df: df-missing: No such file or directory\n" });
+ expect(dfOutputPrefix.stdout.split("\n")[0]).toContain("Filesystem");
+ await symlink(".", join(dir, "df-link"));
+ const dfSourceTarget = await run(["df", "--out=source,target", "."]);
+ expect(dfSourceTarget).toMatchObject({ code: 0 });
+ expect(await run(["df", "--out=source,target", "df-link"])).toMatchObject({ code: 0, stdout: dfSourceTarget.stdout });
+ expect(await run(["df", "--out=file,target", "df-link"])).toMatchObject({ code: 0, stdout: expect.stringMatching(/^File\s+Mounted on\ndf-link \S+\n$/) });
+ expect(await run(["df", "--total", "missing-df"])).toMatchObject({ code: 1, stdout: "", stderr: "df: missing-df: No such file or directory\n" });
+ expect(await run(["df", "--output=target,source,target", "."])).toMatchObject({ code: 1, stderr: `df: option --output: field ${diagnosticQuote("target")} used more than once\nTry 'df --help' for more information.\n` });
+ expect(await run(["df", "--output=bad", "--help"])).toMatchObject(await systemRun(["df", "--output=bad", "--help"]));
+ expect(await run(["df", "--output=", "."])).toMatchObject({ code: 1, stdout: "", stderr: `df: option --output: field ${diagnosticQuote("")} unknown\nTry 'df --help' for more information.\n` });
+ expect(await run(["df", "--output=source,,target", "."])).toMatchObject({ code: 1, stdout: "", stderr: `df: option --output: field ${diagnosticQuote("")} unknown\nTry 'df --help' for more information.\n` });
+ expect(await run(["df", "--output=source,bad\nfield", "."])).toMatchObject({ code: 1, stdout: "", stderr: `df: option --output: field ${diagnosticQuote("bad\\nfield")} unknown\nTry 'df --help' for more information.\n` });
+ const dfTotal = await run(["df", "--total", "."]);
+ expect(dfTotal).toMatchObject({ code: 0 });
+ expect(dfTotal.stdout.trim().split("\n").at(-1)).toMatch(/^total\s+\S+\s+\S+\s+\S+\s+\d+% -$/);
+ expect((await run(["df", "--output=source,target", "--total", "."])).stdout.trim().split("\n").at(-1)).toMatch(/^total\s+-$/);
+ expect((await run(["df", "--output=target", "--total", "."])).stdout.trim().split("\n").at(-1)).toBe("total");
+ const dfiTotal = await run(["df", "-i", "--total", "."]);
+ expect(dfiTotal).toMatchObject({ code: 0 });
+ expect(dfiTotal.stdout.trim().split("\n").at(-1)).toMatch(/^total\s+\S+\s+\S+\s+\S+\s+\d+% -$/);
+ expect(await run(["df", "df-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "df: df-missing: No such file or directory\n" });
+ expect(await run(["df", "missing'df"])).toMatchObject({ code: 1, stdout: "", stderr: "df: \"missing'df\": No such file or directory\n" });
+ expect(await run(["df", "missing\ndf"])).toMatchObject({ code: 1, stdout: "", stderr: "df: 'missing'$'\\n''df': No such file or directory\n" });
+ await symlink("df-loop", join(dir, "df-loop"));
+ expect(await run(["df", "df-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "df: df-loop: Too many levels of symbolic links\n" });
+ await symlink("loop'df", join(dir, "loop'df"));
+ expect(await run(["df", "loop'df"])).toMatchObject({ code: 1, stdout: "", stderr: "df: \"loop'df\": Too many levels of symbolic links\n" });
+ expect(await run(["df", "--total", "df-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "df: df-loop: Too many levels of symbolic links\n" });
+ expect(await run(["tsort"], "a b\nb c\n")).toMatchObject({ code: 0, stdout: "a\nb\nc\n" });
+ expect(await run(["tsort"], "a b b c c d d e e f f g\nc x x y y z\n")).toMatchObject({ code: 0, stdout: "a\nb\nc\nx\nd\ny\ne\nz\nf\ng\n" });
+ expect(await run(["tsort", "--h"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tsort [OPTION] [FILE]\n") });
+ expect(await run(["tsort", "--ver"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["tsort", "BEFORE", "--help", "AFTER"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: tsort [OPTION] [FILE]\n") });
+ expect(await run(["tsort", "BEFORE", "--version", "AFTER"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["tsort", "--bad", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: unrecognized option '--bad'\nTry 'tsort --help' for more information.\n" });
+ expect(await run(["tsort", "--h=foo"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: option '--help' doesn't allow an argument\nTry 'tsort --help' for more information.\n" });
+ expect(await run(["tsort", "-x", "--help"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: invalid option -- 'x'\nTry 'tsort --help' for more information.\n" });
+ expect(await run(["tsort"], "a\n")).toMatchObject({ code: 1, stderr: "tsort: -: input contains an odd number of tokens\n" });
+ expect(await run(["tsort", "-", "extra"], "")).toMatchObject({ code: 1, stderr: `tsort: extra operand ${diagnosticQuote("extra")}\nTry 'tsort --help' for more information.\n` });
+ expect(await run(["tsort"], "t b\nt s\ns t\n")).toMatchObject({ code: 1, stdout: "s\nt\nb\n", stderr: "tsort: -: input contains a loop:\ntsort: s\ntsort: t\n" });
+ expect(await run(["timeout", "2", process.execPath, "-e", "console.log('done')"])).toMatchObject({ code: 0, stdout: "done\n" });
+ expect(await run(["timeout", ".2", process.execPath, "-e", "console.log('decimal')"])).toMatchObject({ code: 0, stdout: "decimal\n" });
+ expect(await run(["timeout", "+.2", process.execPath, "-e", "console.log('plus-decimal')"])).toMatchObject({ code: 0, stdout: "plus-decimal\n" });
+ expect(await run(["timeout", "+0x.8p-2", process.execPath, "-e", "console.log('plus-hex')"])).toMatchObject({ code: 0, stdout: "plus-hex\n" });
+ expect(await run(["timeout", "0", process.execPath, "-e", "setTimeout(() => console.log('no-timeout'), 20)"])).toMatchObject({ code: 0, stdout: "no-timeout\n" });
+ expect(await run(["timeout", "2", "/bin/sh", "-c", "printf '%s\\n' \"$1\"", "sh", "--version"])).toMatchObject({ code: 0, stdout: "--version\n" });
+ expect(await run(["timeout", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: timeout [OPTION]... DURATION COMMAND [ARG]...\n") });
+ expect(await run(["timeout", "--help=bad"])).toMatchObject({ code: 125, stderr: "timeout: option '--help' doesn't allow an argument\nTry 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "--ve=bad"])).toMatchObject(await systemRun(["timeout", "--ve=bad"]));
+ expect(await run(["timeout"])).toMatchObject({ code: 125, stderr: "Try 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "1"])).toMatchObject({ code: 125, stderr: "Try 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "-s"])).toMatchObject({ code: 125, stderr: "timeout: option requires an argument -- 's'\nTry 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "-k"])).toMatchObject({ code: 125, stderr: "timeout: option requires an argument -- 'k'\nTry 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "--signal"])).toMatchObject({ code: 125, stderr: "timeout: option '--signal' requires an argument\nTry 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "--kill-after"])).toMatchObject({ code: 125, stderr: "timeout: option '--kill-after' requires an argument\nTry 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "--bad", "--help"])).toMatchObject({ code: 125, stderr: "timeout: unrecognized option '--bad'\nTry 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "-s", "bad", "--help"])).toMatchObject(await systemRun(["timeout", "-s", "bad", "--help"]));
+ expect(await run(["timeout", "-s", "--help"])).toMatchObject(await systemRun(["timeout", "-s", "--help"]));
+ expect(await run(["timeout", "--signal=bad", "--help"])).toMatchObject(await systemRun(["timeout", "--signal=bad", "--help"]));
+ expect(await run(["timeout", "-k", "bad", "--help"])).toMatchObject(await systemRun(["timeout", "-k", "bad", "--help"]));
+ expect(await run(["timeout", "-k", "--help"])).toMatchObject(await systemRun(["timeout", "-k", "--help"]));
+ expect(await run(["timeout", "--kill-after=bad", "--help"])).toMatchObject(await systemRun(["timeout", "--kill-after=bad", "--help"]));
+ expect(await run(["timeout", "--foreground=bad", "1", "true"])).toMatchObject({ code: 125, stderr: "timeout: option '--foreground' doesn't allow an argument\nTry 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "--preserve-status=bad", "1", "true"])).toMatchObject({ code: 125, stderr: "timeout: option '--preserve-status' doesn't allow an argument\nTry 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "--verbose=bad", "1", "true"])).toMatchObject({ code: 125, stderr: "timeout: option '--verbose' doesn't allow an argument\nTry 'timeout --help' for more information.\n" });
+ expect(await run(["timeout", "1\t2", "true"])).toMatchObject(await systemRun(["timeout", "1\t2", "true"]));
+ expect(await run(["timeout", "bad", "true"])).toMatchObject(await systemRun(["timeout", "bad", "true"]));
+ expect(await run(["timeout", "--kill-after=bad", "true"])).toMatchObject(await systemRun(["timeout", "--kill-after=bad", "true"]));
+ expect(await run(["timeout", "--signal=BAD", "true"])).toMatchObject(await systemRun(["timeout", "--signal=BAD", "true"]));
+ expect(await run(["timeout", "1", "definitely-missing-command"])).toMatchObject({ code: 127, stderr: "timeout: failed to run command 'definitely-missing-command': No such file or directory\n" });
+ expect(await run(["timeout", "1", "."])).toMatchObject({ code: 126, stderr: "timeout: failed to run command '.': Permission denied\n" });
+ expect((await run(["timeout", "0.05", process.execPath, "-e", "setTimeout(()=>{}, 1000)"])).code).toBe(124);
+ expect(await run(["timeout", "--verbose", "--signal=RTMIN", "0.05", "/usr/bin/sleep", "1"])).toMatchObject({ code: 124, stderr: "timeout: sending signal RTMIN to command '/usr/bin/sleep'\n" });
+ expect((await run(["timeout", "-s", "KILL", "0.05", process.execPath, "-e", "setTimeout(()=>{}, 1000)"])).code).toBe(137);
+ expect((await run(["timeout", "--preserve-status", "0.2", "sh", "-c", "trap 'exit 7' TERM; sleep 1"])).code).toBe(7);
+ const timeoutForward = await shell(`
+ "$BUN" "$BNU" timeout 30 "$BUN" -e 'Bun.write("timeout-child.pid", String(process.pid)); setInterval(()=>{}, 1000)' &
+ tpid=$!
+ for i in 1 2 3 4 5 6 7 8 9 10; do
+ test -s timeout-child.pid && break
+ sleep .05
+ done
+ test -s timeout-child.pid || exit 2
+ cpid=$(cat timeout-child.pid)
+ kill "$tpid"
+ wait "$tpid" 2>/dev/null
+ sleep .1
+ if kill -0 "$cpid" 2>/dev/null; then
+ kill "$cpid" 2>/dev/null
+ exit 3
+ fi
+ `);
+ expect(timeoutForward).toMatchObject({ code: 0 });
+ const timeoutSignalZero = await run(["timeout", "-v", "-s0", "-k", "0.05", "0.05", process.execPath, "-e", "setTimeout(()=>{}, 1000)"]);
+ expect(timeoutSignalZero.stderr).toContain("timeout: sending signal 0 to command");
+ expect(await run(["sleep", "0s", "0.001s"])).toMatchObject({ code: 0 });
+ expect(await run(["sleep", ".001s"])).toMatchObject({ code: 0 });
+ expect(await run(["sleep", "+1e-3"])).toMatchObject({ code: 0 });
+ expect(await run(["sleep", "+0x.002p1"])).toMatchObject({ code: 0 });
+ expect(await run(["sleep", "0x.002p1"])).toMatchObject({ code: 0 });
+ expect((await run(["sleep", "--help"])).stdout).toStartWith("Usage: sleep NUMBER[SUFFIX]...\n or: sleep OPTION\n");
+ expect((await run(["sleep", "--help"])).stdout).toContain("SUFFIX may be 's','m','h', or 'd', for seconds, minutes, hours, days.\n");
+ expect((await run(["sleep", "0", "--help"])).stdout).toStartWith("Usage: sleep NUMBER[SUFFIX]...\n or: sleep OPTION\n");
+ expect(await run(["sleep", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect((await run(["sleep", "--h"])).stdout).toStartWith("Usage: sleep NUMBER[SUFFIX]...\n or: sleep OPTION\n");
+ expect((await run(["sleep", "0", "--he"])).stdout).toStartWith("Usage: sleep NUMBER[SUFFIX]...\n or: sleep OPTION\n");
+ expect(await run(["sleep", "--v"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["sleep", "0", "--ver"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["sleep", "--h=1"])).toMatchObject({ code: 1, stderr: "sleep: option '--help' doesn't allow an argument\nTry 'sleep --help' for more information.\n" });
+ expect(await run(["sleep", "0", "--v=1"])).toMatchObject({ code: 1, stderr: "sleep: option '--version' doesn't allow an argument\nTry 'sleep --help' for more information.\n" });
+ expect(await run(["sleep", "--bad", "--help"])).toMatchObject({ code: 1, stderr: "sleep: unrecognized option '--bad'\nTry 'sleep --help' for more information.\n" });
+ expect(await run(["sleep", "-x", "--help"])).toMatchObject({ code: 1, stderr: "sleep: invalid option -- 'x'\nTry 'sleep --help' for more information.\n" });
+ expect(await run(["sleep", "--"])).toMatchObject({ code: 0 });
+ expect(await run(["sleep", "--", "0.001"])).toMatchObject({ code: 0 });
+ expect(await run(["sleep", "--", "--help"])).toMatchObject(await systemRun(["sleep", "--", "--help"]));
+ expect(await run(["sleep", "--bad-option"])).toMatchObject({ code: 1, stderr: "sleep: unrecognized option '--bad-option'\nTry 'sleep --help' for more information.\n" });
+ expect(await run(["sleep", "-"])).toMatchObject(await systemRun(["sleep", "-"]));
+ expect(await run(["sleep", "-1"])).toMatchObject({ code: 1, stderr: "sleep: invalid option -- '1'\nTry 'sleep --help' for more information.\n" });
+ expect(await run(["sleep"])).toMatchObject({ code: 1, stderr: "sleep: missing operand\nTry 'sleep --help' for more information.\n" });
+ expect(await run(["sleep", "1\n2"])).toMatchObject(await systemRun(["sleep", "1\n2"]));
+ expect(await run(["sleep", "nan"])).toMatchObject(await systemRun(["sleep", "nan"]));
+ expect(await run(["sleep", "1fortnight"])).toMatchObject(await systemRun(["sleep", "1fortnight"]));
+ expect(await run(["timeout", "0.1", join(import.meta.dir, "../bin/bnu.js"), "sleep", "inf"])).toMatchObject({ code: 124 });
+ expect(await run(["timeout", "0.1", join(import.meta.dir, "../bin/bnu.js"), "sleep", "INF"])).toMatchObject({ code: 124 });
+ expect(await run(["timeout", "0.1", join(import.meta.dir, "../bin/bnu.js"), "sleep", "Infinity"])).toMatchObject({ code: 124 });
+ expect(await run(["nice", process.execPath, "-e", "console.log('nice')"])).toMatchObject({ code: 0, stdout: "nice\n" });
+ expect(await run(["nice", "-n5", process.execPath, "-e", "console.log('n5')"])).toMatchObject({ code: 0, stdout: "n5\n" });
+ expect(await run(["nice", "--adjustment=5", process.execPath, "-e", "console.log('eq')"])).toMatchObject({ code: 0, stdout: "eq\n" });
+ expect(await run(["nice", "-5", process.execPath, "-e", "console.log('old')"])).toMatchObject({ code: 0, stdout: "old\n" });
+ expect(await run(["nice", "-1", "-2", join(import.meta.dir, "../bin/bnu.js"), "nice"])).toMatchObject({ code: 0, stdout: "2\n" });
+ expect(await run(["nice", "-n", "1", join(import.meta.dir, "../bin/bnu.js"), "nice", "-n", "2", join(import.meta.dir, "../bin/bnu.js"), "nice"])).toMatchObject({ code: 0, stdout: "3\n" });
+ const negativeNice = await run(["nice", "-n", "-1", join(import.meta.dir, "../bin/bnu.js"), "nice"]);
+ expect(negativeNice).toMatchObject({ code: 0, stdout: "0\n" });
+ expect(negativeNice.stderr).toContain("cannot set niceness");
+ expect(await run(["nice", "-n", "1"])).toMatchObject({ code: 125, stderr: "nice: a command must be given with an adjustment\nTry 'nice --help' for more information.\n" });
+ expect(await run(["nice", "-1"])).toMatchObject({ code: 125, stderr: "nice: a command must be given with an adjustment\nTry 'nice --help' for more information.\n" });
+ expect(await run(["nice", "-n"])).toMatchObject({ code: 125, stderr: "nice: option requires an argument -- 'n'\nTry 'nice --help' for more information.\n" });
+ expect(await run(["nice", "--adjustment"])).toMatchObject({ code: 125, stderr: "nice: option '--adjustment' requires an argument\nTry 'nice --help' for more information.\n" });
+ expect(await run(["nice", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: nice [OPTION] [COMMAND [ARG]...]\n") });
+ expect(await run(["nice", "--he=bad"])).toMatchObject(await systemRun(["nice", "--he=bad"]));
+ expect(await run(["nice", "--ve=bad"])).toMatchObject(await systemRun(["nice", "--ve=bad"]));
+ expect(await run(["nice", "--bad", "--help"])).toMatchObject({ code: 125, stderr: "nice: unrecognized option '--bad'\nTry 'nice --help' for more information.\n" });
+ expect(await run(["nice", "---"])).toMatchObject({ code: 125 });
+ expect(await run(["nice", "-n", "1a"])).toMatchObject({ code: 125 });
+ expect(await run(["nice", "-n", "1\n2"])).toMatchObject({ code: 125, stderr: `nice: invalid adjustment ${diagnosticQuote("1\\n2")}\n` });
+ const niceInvalid = await run(["nice", "-/"]);
+ expect(niceInvalid).toMatchObject({ code: 125 });
+ expect(niceInvalid.stderr).toContain("nice: invalid option -- '/'");
+ expect(niceInvalid.stderr).toContain("Try 'nice --help' for more information.");
+ expect(await run(["nice", "sh", "-c", "exit 2"])).toMatchObject({ code: 2 });
+ expect(await run(["nice", "/bin/sh", "-c", "printf '%s\\n' \"$1\"", "sh", "--version"])).toMatchObject({ code: 0, stdout: "--version\n" });
+ expect(await run(["nice", "."])).toMatchObject({ code: 126, stderr: "nice: '.': Permission denied\n" });
+ expect(await run(["nice", "definitely-missing-command"])).toMatchObject({ code: 127, stderr: "nice: 'definitely-missing-command': No such file or directory\n" });
+ expect(await run(["nproc"], "", { env: { OMP_NUM_THREADS: "2,ignored", OMP_THREAD_LIMIT: "" } })).toMatchObject({ code: 0, stdout: "2\n" });
+ expect(await run(["nproc"], "", { env: { OMP_NUM_THREADS: " 2 ", OMP_THREAD_LIMIT: "" } })).toMatchObject({ code: 0, stdout: "2\n" });
+ expect(await run(["nproc"], "", { env: { OMP_NUM_THREADS: " 4 ", OMP_THREAD_LIMIT: " 2 " } })).toMatchObject({ code: 0, stdout: "2\n" });
+ expect(await run(["nproc"], "", { env: { OMP_NUM_THREADS: "2bad", OMP_THREAD_LIMIT: "1" } })).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["nproc"], "", { env: { OMP_NUM_THREADS: "-2", OMP_THREAD_LIMIT: "1bad" } })).toMatchObject({ code: 0 });
+ expect(await run(["nohup", process.execPath, "-e", "console.log('nohup')"])).toMatchObject({ code: 0, stdout: "nohup\n" });
+ expect(await run(["nohup", "sh", "-c", "cat; kill -HUP $$; echo survived"], "piped input\n")).toMatchObject({ code: 0, stdout: "piped input\nsurvived\n", stderr: "" });
+ expect(await run(["nohup", "--", "sh", "-c", "printf 'dash command\\n'"])).toMatchObject({ code: 0, stdout: "dash command\n" });
+ expect(await run(["nohup", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: nohup COMMAND [ARG]...\n or: nohup OPTION\n") });
+ expect(await run(["nohup", "--version=bad"])).toMatchObject(await systemRun(["nohup", "--version=bad"]));
+ expect(await run(["nohup", "--hel=bad"])).toMatchObject(await systemRun(["nohup", "--hel=bad"]));
+ const missingNohup = await run(["nohup", "definitely-missing-command"]);
+ expect(missingNohup.code).toBe(127);
+ expect(missingNohup.stderr).toBe("nohup: failed to run command 'definitely-missing-command': No such file or directory\n");
+ if ((await shell("command -v script >/dev/null")).code === 0) {
+ const nohupPty = await shell(`script -qfec 'rm -f nohup.out; umask 0777; "$BUN" "$BNU" nohup sh -c "echo stdout; echo stderr >&2"; mode=$(stat -c %a nohup.out); printf "MODE=%s\\n" "$mode"; printf "FILE="; tr "\\n" - < nohup.out; printf "\\n"; rm -f nohup.out' /dev/null`);
+ expect(nohupPty).toMatchObject({ code: 0, stderr: "" });
+ const nohupPtyOutput = nohupPty.stdout.replaceAll("\r\n", "\n");
+ expect(nohupPtyOutput).toContain(`nohup: ignoring input and appending output to ${diagnosticQuote("nohup.out")}\n`);
+ expect(nohupPtyOutput).toContain("MODE=600\nFILE=stdout-stderr-\n");
+ }
+ expect(await run(["kill", "-l"])).toMatchObject({ code: 0 });
+ expect(await run(["kill", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: kill [-s SIGNAL | --signal SIGNAL | -SIGNAL] PID...\n or: kill [-l | --list | -t | --table] [SIGNAL]...\n") });
+ expect(await run(["kill", "-l", "15"])).toMatchObject({ code: 0, stdout: "TERM\n" });
+ expect(await run(["kill", "--list=TERM"])).toMatchObject({ code: 0, stdout: "15\n" });
+ expect(await run(["kill", "-l", "34", "35", "63", "64"])).toMatchObject({
+ code: 0,
+ stdout: "RTMIN\nRTMIN+1\nRTMAX-1\nRTMAX\n",
+ });
+ expect(await run(["kill", "-l", "RTMIN+2", "RTMAX-2"])).toMatchObject({ code: 0, stdout: "36\n62\n" });
+ expect((await run(["kill", "-l"])).stdout).toContain("RTMAX\n");
+ expect((await run(["kill", "-L"])).stdout).toContain("15 TERM");
+ expect(await run(["kill", "-s", "0", String(process.pid)])).toMatchObject({ code: 0 });
+ expect(await run(["kill", "-0", String(process.pid)])).toMatchObject({ code: 0 });
+});
+
+test("install, dd, dircolors and shred cover file setup workflows", async () => {
+ await writeFile(join(dir, "source"), "abcdef");
+ expect(await run(["shred"])).toMatchObject({ code: 1, stderr: "shred: missing file operand\nTry 'shred --help' for more information.\n" });
+ expect(await run(["install", "-m", "700", "source", "installed"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "installed"), "utf8")).toBe("abcdef");
+ expect((await stat(join(dir, "installed"))).mode & 0o777).toBe(0o700);
+ expect((await run(["install", "--preserve", "--help"])).stderr).toContain("option '--preserve' is ambiguous; possibilities: '--preserve-timestamps' '--preserve-context'");
+ const installHelp = await run(["install", "-p", "--help", "--help"]);
+ expect(installHelp.code).toBe(0);
+ expect(installHelp.stdout).toContain("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...\n");
+ expect(installHelp.stdout).toContain(" --context\n");
+ expect(installHelp.stdout).toContain(" -D\n");
+ expect(installHelp.stdout).toContain(" -Z\n");
+ expect(installHelp.stdout).toContain(" -c\n");
+ expect((await run(["install", "--debug=bad", "--help"])).stderr).toContain("option '--debug' doesn't allow an argument");
+ expect(await run(["install", "--target", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["install", "--strip-p=./stripper", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: install") });
+ expect(await run(["install", "--context", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: install") });
+ expect(await run(["install", "--context=system_u:object_r:tmp_t:s0", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: install") });
+ expect(await run(["install", "--context=system_u:object_r:tmp_t:s0", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "install: warning: ignoring --context; it requires an SELinux-enabled kernel\n" });
+ expect(await run(["install", "--preserve-context", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: install"), stderr: "install: WARNING: ignoring --preserve-context; this kernel is not SELinux-enabled\n" });
+ expect(await run(["install", "source", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: install [OPTION]... [-T] SOURCE DEST\n"), stderr: "" });
+ await writeFile(join(dir, "installed-backup-empty"), "old");
+ expect(await run(["install", "--backup=", "source", "installed-backup-empty"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "installed-backup-empty"), "utf8")).toBe("abcdef");
+ expect(await readFile(join(dir, "installed-backup-empty~"), "utf8")).toBe("old");
+ expect(await run(["install", "--backup=bad", "source", "installed-backup-bad"])).toMatchObject(await systemRun(["install", "--backup=bad", "source", "installed-backup-bad"]));
+ expect(await run(["install", "--backup", "source", "installed-backup-env-bad"], "", { env: { VERSION_CONTROL: "bad" } })).toMatchObject(await systemRun(["install", "--backup", "source", "installed-backup-env-bad"], "", { env: { VERSION_CONTROL: "bad" } }));
+ expect(await run(["install", "--mode", "bad", "source"])).toMatchObject(await systemRun(["install", "--mode", "bad", "source"]));
+ expect(await run(["install", "--mode", "bad\nmode", "source", "installed-bad-mode-newline"])).toMatchObject({ code: 1, stderr: `install: invalid mode ${diagnosticQuote("bad\\nmode")}\n` });
+ expect(await run(["install", "--group", "definitely-missing-group", "source"])).toMatchObject(await systemRun(["install", "--group", "definitely-missing-group", "source"]));
+ expect(await run(["install", "-d", "--mode", "bad"])).toMatchObject(await systemRun(["install", "-d", "--mode", "bad"]));
+ expect(await run(["install", "-d", "--mode", "bad", "install-bad-mode-dir"])).toMatchObject(await systemRun(["install", "-d", "--mode", "bad", "install-bad-mode-dir"]));
+ expect(await run(["install", "-d", "--mode", "bad\nmode", "install-bad-mode-newline"])).toMatchObject({ code: 1, stderr: `install: invalid mode ${diagnosticQuote("bad\\nmode")}\n` });
+ expect(await run(["install", "-C", "-s", "source", "installed-compare-strip"])).toMatchObject({
+ code: 1,
+ stderr: "install: options --compare (-C) and --strip are mutually exclusive\nTry 'install --help' for more information.\n",
+ });
+ expect(await run(["install", "/dev/null", "installed-null"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "installed-null"))).size).toBe(0);
+ expect((await stat(join(dir, "installed-null"))).mode & 0o777).toBe(0o755);
+ expect(await run(["install", "--context=system_u:object_r:tmp_t:s0", "source", "installed-context"])).toMatchObject({
+ code: 0,
+ stderr: "install: warning: ignoring --context; it requires an SELinux-enabled kernel\n",
+ });
+ expect(await readFile(join(dir, "installed-context"), "utf8")).toBe("abcdef");
+ expect(await run(["install", "--preserve-context", "source", "installed-preserve-context"])).toMatchObject({
+ code: 0,
+ stderr: "install: WARNING: ignoring --preserve-context; this kernel is not SELinux-enabled\n",
+ });
+ expect(await readFile(join(dir, "installed-preserve-context"), "utf8")).toBe("abcdef");
+ const currentUid = process.getuid?.() ?? (await stat(join(dir, "installed"))).uid;
+ const currentGid = process.getgid?.() ?? (await stat(join(dir, "installed"))).gid;
+ const installDebug = await run(["install", "--debug", "-o", String(currentUid), "-g", String(currentGid), "source", "installed-owned"]);
+ expect(installDebug.stdout).toStartWith("'source' -> 'installed-owned'\n");
+ expect(installDebug.stdout).toMatch(/copy offload: (unknown|avoided), reflink: (yes|no), sparse detection: (unknown|no)\n$/);
+ expect(await readFile(join(dir, "installed-owned"), "utf8")).toBe("abcdef");
+ expect((await stat(join(dir, "installed-owned"))).uid).toBe(currentUid);
+ expect((await stat(join(dir, "installed-owned"))).gid).toBe(currentGid);
+ expect(await run(["install", "-m", "u=rw,go=r", "source", "installed-symbolic"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "installed-symbolic"))).mode & 0o777).toBe(0o644);
+ expect(await run(["install", "-d", "nested/dir"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "install-existing-file-a"), "");
+ await writeFile(join(dir, "install-existing-file-b"), "");
+ expect(await run(["install", "-d", "install-existing-file-a", "install-existing-file-b"])).toMatchObject({
+ code: 1,
+ stderr: "install: cannot create directory 'install-existing-file-a': File exists\ninstall: cannot create directory 'install-existing-file-b': File exists\n",
+ });
+ expect(await run(["install", "-D", "source", "install-leading/parents/installed"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "install-leading/parents/installed"), "utf8")).toBe("abcdef");
+ expect(await run(["install", "-d", "--preserve-context", "-o", String(currentUid), "-g", String(currentGid), "nested/owned-dir"])).toMatchObject({
+ code: 0,
+ stderr: "install: WARNING: ignoring --preserve-context; this kernel is not SELinux-enabled\n",
+ });
+ expect((await stat(join(dir, "nested/owned-dir"))).uid).toBe(currentUid);
+ expect((await stat(join(dir, "nested/owned-dir"))).gid).toBe(currentGid);
+ expect(await run(["install", "-d", "-m", "u=rwx,go=", "private/install-dir"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "private/install-dir"))).mode & 0o777).toBe(0o700);
+ expect(await run(["install", "missing\ninstall-source", "install-missing-dest"])).toMatchObject(await systemRun(["install", "missing\ninstall-source", "install-missing-dest"]));
+ expect(await run(["install", "missing'install-source", "install-missing-dest"])).toMatchObject(await systemRun(["install", "missing'install-source", "install-missing-dest"]));
+ expect(await run(["install", "-t", "missing\ninstall-target", "source"])).toMatchObject(await systemRun(["install", "-t", "missing\ninstall-target", "source"]));
+ expect(await run(["install", "-t", "missing'install-target", "source"])).toMatchObject(await systemRun(["install", "-t", "missing'install-target", "source"]));
+ await mkdir(join(dir, "install'directory-source"));
+ expect(await run(["install", "install'directory-source", "install-dir-source-dest"])).toMatchObject(await systemRun(["install", "install'directory-source", "install-dir-source-dest"]));
+ expect(await run(["install", "-d", "-v", "install-dir\nnewline"])).toMatchObject({
+ code: 0,
+ stdout: "install: creating directory 'install-dir'$'\\n''newline'\n",
+ });
+ expect(await run(["install", "-d", "-v", "install-dir'quote"])).toMatchObject({
+ code: 0,
+ stdout: "install: creating directory \"install-dir'quote\"\n",
+ });
+ expect(await run(["install", "-Dv", "source", "install-parent\nnewline/file'quote"])).toMatchObject({
+ code: 0,
+ stdout: "install: creating directory 'install-parent'$'\\n''newline'\n'source' -> 'install-parent'$'\\n''newline/file'\\''quote'\n",
+ });
+ await writeFile(join(dir, "install-replace'quote"), "old");
+ expect(await run(["install", "-v", "source", "install-replace'quote"])).toMatchObject({
+ code: 0,
+ stdout: "removed \"install-replace'quote\"\n'source' -> \"install-replace'quote\"\n",
+ });
+ expect(await run(["install", "-Dv", "source", "deep/a/b/installed"])).toMatchObject({ code: 0, stdout: "install: creating directory 'deep'\ninstall: creating directory 'deep/a'\ninstall: creating directory 'deep/a/b'\n'source' -> 'deep/a/b/installed'\n" });
+ expect(await readFile(join(dir, "deep/a/b/installed"), "utf8")).toBe("abcdef");
+ expect(await run(["install", "-t", "target/install/dir", "-Dv", "source"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/install/dir/source"), "utf8")).toBe("abcdef");
+ expect(await run(["install", "-t", "missing-install-target", "source"])).toMatchObject(await systemRun(["install", "-t", "missing-install-target", "source"]));
+ expect(await run(["install", "--target-directory=missing-install-target", "source"])).toMatchObject(await systemRun(["install", "--target-directory=missing-install-target", "source"]));
+ expect(await run(["install", "-t", ".", "source"])).toMatchObject({ code: 1, stderr: "install: 'source' and './source' are the same file\n" });
+ await writeFile(join(dir, "install\nsame-file"), "same");
+ expect(await run(["install", "-t", ".", "install\nsame-file"])).toMatchObject({
+ code: 1,
+ stderr: "install: 'install'$'\\n''same-file' and './install'$'\\n''same-file' are the same file\n",
+ });
+ expect(await readFile(join(dir, "source"), "utf8")).toBe("abcdef");
+ expect(await run(["install", "--target-directory=target/install/dir", "/dev/null"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "target/install/dir/null"))).size).toBe(0);
+ await writeFile(join(dir, "target/install/dir/exact"), "old");
+ expect(await run(["install", "--no-target-directory", "source", "target/install/dir/exact"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/install/dir/exact"), "utf8")).toBe("abcdef");
+ expect(await run(["install", "-T", "source", "target/install/dir"])).toMatchObject({
+ code: 1,
+ stderr: "install: cannot overwrite directory 'target/install/dir' with non-directory 'source'\n",
+ });
+ expect(await run(["install", "-T", "source", "target/install/dir/exact", "extra"])).toMatchObject({
+ code: 1,
+ stderr: "install: extra operand 'extra'\nTry 'install --help' for more information.\n",
+ });
+ expect(await run(["install", "-T", "source", "target/install/dir/exact", "extra\narg"])).toMatchObject({
+ code: 1,
+ stderr: "install: extra operand 'extra'$'\\n''arg'\nTry 'install --help' for more information.\n",
+ });
+ expect(await run(["install", "-Cv", "-m", "755", "source", "target/install/dir/source"])).toMatchObject({ code: 0, stdout: "" });
+ await writeFile(join(dir, "timestamp-source"), "same\n");
+ await writeFile(join(dir, "timestamp-dest"), "same\n");
+ expect(await run(["touch", "-d", "2026-01-01", "timestamp-source"])).toMatchObject({ code: 0 });
+ expect(await run(["install", "-C", "--preserve-timestamps", "timestamp-source", "timestamp-dest"])).toMatchObject({ code: 0 });
+ expect((await run(["stat", "--format=%y", "timestamp-dest"])).stdout).toStartWith("2026-01-01 ");
+ await writeFile(join(dir, "timestamp-short-dest"), "old\n");
+ expect(await run(["install", "-p", "timestamp-source", "timestamp-short-dest"])).toMatchObject({ code: 0 });
+ expect((await run(["stat", "--format=%y", "timestamp-short-dest"])).stdout).toStartWith("2026-01-01 ");
+ await writeFile(join(dir, "install-ns-source"), "ns\n");
+ await systemRun(["/usr/bin/touch", "-a", "-d", "2026-01-01 01:02:03.111111111 +0000", "install-ns-source"]);
+ await systemRun(["/usr/bin/touch", "-m", "-d", "2026-01-02 03:04:05.222222222 +0000", "install-ns-source"]);
+ expect(await run(["install", "-p", "install-ns-source", "install-ns-dest"])).toMatchObject({ code: 0 });
+ expect(await run(["stat", "-c", "%x|%y", "install-ns-dest"], "", { env: { TZ: "UTC0" } })).toMatchObject({
+ code: 0,
+ stdout: "2026-01-01 01:02:03.111111111 +0000|2026-01-02 03:04:05.222222222 +0000\n",
+ });
+ await writeFile(join(dir, "stripper"), "#!/bin/sh\nsed s/b/B/ \"$1\" > \"$1.t\" && mv \"$1.t\" \"$1\"\n");
+ await run(["chmod", "755", "stripper"]);
+ expect(await run(["install", "-s", "--strip-program=./stripper", "source", "stripped"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "stripped"), "utf8")).toBe("aBcdef");
+ expect(await run(["install", "-s", "--strip-program=./missing'stripper", "source", "missing-stripper"])).toMatchObject(await systemRun(["install", "-s", "--strip-program=./missing'stripper", "source", "missing-stripper"]));
+ await writeFile(join(dir, "not-a-dir"), "");
+ expect(await run(["ginstall", "-t", "not-a-dir", "-Dv", "source"])).toMatchObject({ code: 1, stderr: "ginstall: failed to access 'not-a-dir': Not a directory\n" });
+ const ddCopy = await run(["dd", "if=source", "of=copy", "bs=2", "count=2"]);
+ expect(ddCopy).toMatchObject({ code: 0 });
+ expect(ddCopy.stderr).toContain("records in");
+ expect(await readFile(join(dir, "copy"), "utf8")).toBe("abcd");
+ expect(await run(["dd", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: dd [OPERAND]...\n or: dd OPTION\n") });
+ expect(await run(["dd", "--bad=4"])).toMatchObject({ code: 1, stderr: "dd: unrecognized option '--bad=4'\nTry 'dd --help' for more information.\n" });
+ expect(await run(["dd", "foo=bar"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: unrecognized operand 'foo=bar'\nTry 'dd --help' for more information.\n" });
+ expect(await run(["dd", "foo\nbar=baz"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: unrecognized operand 'foo'$'\\n''bar=baz'\nTry 'dd --help' for more information.\n" });
+ expect(await run(["dd", "if=source", "of=bad-conv", "conv=bad", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: `dd: invalid conversion: ${diagnosticQuote("bad")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=bad-conv-newline", "conv=bad\nmode", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: `dd: invalid conversion: ${diagnosticQuote("bad\\nmode")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=bad-iflag", "iflag=bad", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: `dd: invalid input flag: ${diagnosticQuote("bad")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=bad-oflag", "oflag=bad", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: `dd: invalid output flag: ${diagnosticQuote("bad")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=bad-iflag-nolinks", "iflag=nolinks", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: `dd: invalid input flag: ${diagnosticQuote("nolinks")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=bad-oflag-nolinks", "oflag=nolinks", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: `dd: invalid output flag: ${diagnosticQuote("nolinks")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=quiet-copy", "oflag=directory", "status=none"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dd: failed to open 'quiet-copy': Invalid argument\n",
+ });
+ expect(await run(["dd", "oflag=directory", "status=none"], "x")).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dd: setting flags for 'standard output': Not a directory\n",
+ });
+ await symlink("source", join(dir, "dd-oflag-link"));
+ expect(await run(["dd", "if=source", "of=dd-oflag-link", "oflag=nofollow", "status=none"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dd: failed to open 'dd-oflag-link': Too many levels of symbolic links\n",
+ });
+ expect(await run(["dd", "if=source", "of=quiet-copy", "bs=2", "count=1", "status=none"])).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(join(dir, "quiet-copy"), "utf8")).toBe("ab");
+ expect(await run(["dd", "if=source", "of=sync-copy", "bs=2", "count=1", "oflag=sync", "status=none"])).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(join(dir, "sync-copy"), "utf8")).toBe("ab");
+ expect(await run(["dd", "if=source", "of=dsync-copy", "bs=2", "count=1", "oflag=dsync", "status=none"])).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(join(dir, "dsync-copy"), "utf8")).toBe("ab");
+ expect(await run(["dd", "if=source", "of=/dev/null", "count=0", "conv=fdatasync", "status=none"])).toMatchObject({
+ code: 1,
+ stderr: "dd: fsync failed for '/dev/null': Invalid argument\n",
+ });
+ expect(await run(["dd", "if=source", "of=/dev/null", "count=0", "conv=fsync", "status=none"])).toMatchObject({
+ code: 1,
+ stderr: "dd: fsync failed for '/dev/null': Invalid argument\n",
+ });
+ expect(await run(["dd", "if=missing", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: failed to open 'missing': No such file or directory\n" });
+ await mkdir(join(dir, "dd-dir"));
+ expect(await run(["dd", "if=source", "of=dd-dir", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: failed to open 'dd-dir': Is a directory\n" });
+ expect(await run(["dd", "if=dd-dir", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: error reading 'dd-dir': Is a directory\n" });
+ const progressCopy = await run(["dd", "if=source", "of=progress-copy", "bs=2", "count=1", "status=progress"]);
+ expect(progressCopy).toMatchObject({ code: 0 });
+ expect(progressCopy.stderr).toContain("2 bytes copied");
+ expect(progressCopy.stderr).toContain("records out");
+ expect(await shell(`mkfifo dd-signal-fifo; (for n in $(seq 1 100); do dd if=/dev/zero bs=64K count=1 status=none; sleep 0.02; done) >dd-signal-fifo & writer=$!; "$BUN" "$BNU" dd if=dd-signal-fifo of=/dev/null bs=64K status=progress 2>dd-signal.err & copier=$!; sleep 0.5; kill -USR1 "$copier"; wait "$copier"; code=$?; wait "$writer"; exit "$code"`)).toMatchObject({ code: 0, stderr: "" });
+ const ddSignalStats = await readFile(join(dir, "dd-signal.err"), "utf8");
+ expect(ddSignalStats.match(/records in/g)?.length).toBe(2);
+ expect(ddSignalStats.match(/records out/g)?.length).toBe(2);
+ expect(ddSignalStats).toContain("\r");
+ expect(await run(["dd", "if=source", "of=bad-status", "status=bad"])).toMatchObject({ code: 1, stderr: `dd: invalid status level: ${diagnosticQuote("bad")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=bad-status-newline", "status=bad\nmode"])).toMatchObject({ code: 1, stderr: `dd: invalid status level: ${diagnosticQuote("bad\\nmode")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=bad-bs", "bs=0", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: invalid number: '0'\n" });
+ expect(await run(["dd", "if=source", "of=/dev/null", "bs=1\n2", "status=none"])).toMatchObject(await systemRun(["/usr/bin/dd", "if=source", "of=/dev/null", "bs=1\n2", "status=none"]));
+ expect(await run(["dd", "if=source", "of=/dev/null", "bs=bad", "bs=1", "count=0", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: invalid number: 'bad'\n" });
+ expect(await run(["dd", "if=source", "of=/dev/null", "count=9223372036854775808", "count=0", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: invalid number: '9223372036854775808': Value too large for defined data type\n" });
+ expect(await run(["dd", "if=source", "of=/dev/null", "conv=bad", "conv=sync", "count=0"])).toMatchObject({ code: 1, stdout: "", stderr: `dd: invalid conversion: ${diagnosticQuote("bad")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=/dev/null", "status=bad", "status=none", "count=0"])).toMatchObject({ code: 1, stdout: "", stderr: `dd: invalid status level: ${diagnosticQuote("bad")}\nTry 'dd --help' for more information.\n` });
+ expect(await run(["dd", "if=source", "of=/dev/null", "skip=0x1", "skip=0", "count=0", "status=none"])).toMatchObject({ code: 0, stdout: "", stderr: `dd: warning: ${diagnosticQuote("0x")} is a zero multiplier; use ${diagnosticQuote("00x")} if that is intended\n` });
+ await writeFile(join(dir, "patch-target"), "XXXXXX");
+ expect(await run(["dd", "if=source", "of=patch-target", "bs=2", "count=1", "seek=1", "conv=notrunc"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "patch-target"), "utf8")).toBe("XXabXX");
+ await writeFile(join(dir, "truncate-before-copy"), "XXXXXX");
+ expect(await run(["dd", "if=source", "of=truncate-before-copy", "bs=2", "count=1", "seek=1", "status=none"])).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(join(dir, "truncate-before-copy"), "utf8")).toBe("XXab");
+ expect(await run(["dd", "if=source", "iflag=nocache", "count=0", "status=none"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["dd", "if=source", "of=count-bytes", "bs=2", "count=3", "iflag=count_bytes"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "count-bytes"), "utf8")).toBe("abc");
+ expect(await run(["dd", "if=source", "of=count-word", "bs=1", "count=2w", "status=none"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "count-word"), "utf8")).toBe("abcd");
+ expect(await run(["dd", "if=source", "of=count-decimal-kb", "bs=1", "count=1KB", "status=none"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "count-decimal-kb"), "utf8")).toBe("abcdef");
+ expect(await run(["dd", "if=source", "of=/dev/null", "bs=1P", "count=0", "status=none"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["dd", "if=source", "of=/dev/null", "bs=1EB", "count=0", "status=none"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["dd", "if=source", "of=/dev/null", "bs=1Z", "count=0", "status=none"])).toMatchObject(await systemRun(["/usr/bin/dd", "if=source", "of=/dev/null", "bs=1Z", "count=0", "status=none"]));
+ expect(await run(["dd", "if=source", "of=/dev/null", "bs=1R", "count=0", "status=none"])).toMatchObject(await systemRun(["/usr/bin/dd", "if=source", "of=/dev/null", "bs=1R", "count=0", "status=none"]));
+ expect(await run(["dd", "if=source", "of=/dev/null", "bs=1Q", "count=0", "status=none"])).toMatchObject(await systemRun(["/usr/bin/dd", "if=source", "of=/dev/null", "bs=1Q", "count=0", "status=none"]));
+ expect(await run(["dd", "if=source", "of=skip-bytes", "bs=2", "skip=1", "count=2", "iflag=skip_bytes,count_bytes"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "skip-bytes"), "utf8")).toBe("bc");
+ await writeFile(join(dir, "seek-bytes"), "XXXX");
+ expect(await run(["dd", "if=source", "of=seek-bytes", "bs=2", "count=1", "seek=1", "oflag=seek_bytes", "conv=notrunc"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "seek-bytes"), "utf8")).toBe("XabX");
+ expect(await run(["dd", "if=source", "of=append-created", "bs=2", "count=1", "oflag=append", "conv=notrunc", "status=none"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "append-created"), "utf8")).toBe("ab");
+ await writeFile(join(dir, "append-existing"), "XX");
+ expect(await run(["dd", "if=source", "of=append-existing", "bs=2", "count=1", "oflag=append", "conv=notrunc", "status=none"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "append-existing"), "utf8")).toBe("XXab");
+ await writeFile(join(dir, "dd-excl-existing"), "keep");
+ expect(await run(["dd", "if=source", "of=dd-excl-existing", "conv=excl", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: failed to open 'dd-excl-existing': File exists\n" });
+ expect(await readFile(join(dir, "dd-excl-existing"), "utf8")).toBe("keep");
+ expect(await run(["dd", "if=source", "of=dd-nocreat-missing", "conv=nocreat", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: failed to open 'dd-nocreat-missing': No such file or directory\n" });
+ expect(await run(["dd", "if=source", "of=dd-nocreat-excl", "conv=nocreat,excl", "status=none"])).toMatchObject({ code: 1, stdout: "", stderr: "dd: cannot combine excl and nocreat\n" });
+ expect(await run(["dd", "if=source", "of=ibs-copy", "ibs=3", "count=1"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "ibs-copy"), "utf8")).toBe("abc");
+ await writeFile(join(dir, "obs-target"), "XXXXXXXX");
+ expect(await run(["dd", "if=source", "of=obs-target", "ibs=2", "obs=3", "count=1", "seek=1", "conv=notrunc"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "obs-target"), "utf8")).toBe("XXXabXXX");
+ expect(await run(["dd", "of=sync-pad", "bs=8", "conv=sync", "status=none"], "abc")).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "sync-pad"))).size).toBe(8);
+ await writeFile(join(dir, "sparse-input"), Buffer.from([0x61, 0, 0, 0x62]));
+ expect(await run(["dd", "if=sparse-input", "of=sparse-copy", "bs=1", "conv=sparse", "status=none"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "sparse-copy"))).toEqual(Buffer.from([0x61, 0, 0, 0x62]));
+ await writeFile(join(dir, "sparse-patch"), "____");
+ expect(await run(["dd", "if=sparse-input", "of=sparse-patch", "bs=1", "conv=sparse,notrunc", "status=none"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "sparse-patch"), "utf8")).toBe("a__b");
+ expect(await shell(`$BUN "$BNU" dd if=sparse-input bs=1 conv=sparse oflag=append status=none > sparse-append`)).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "sparse-append"), "utf8")).toBe("ab");
+ expect((await run(["dircolors", "-p"])).stdout).toContain("DIR 01;34");
+ expect((await run(["dircolors", "-p"])).stdout).toContain(".tar 01;31");
+ expect((await run(["dircolors", "-p"])).stdout).toContain(".jpg 01;35");
+ expect((await run(["dircolors", "-p"])).stdout).toContain("*~ 00;90");
+ expect((await run(["dircolors", "--bourne-shell"])).stdout).toContain("LS_COLORS='rs=0:di=01;34");
+ expect((await run(["dircolors", "--bourne-shell"])).stdout).toContain("*.tar=01;31");
+ expect((await run(["dircolors", "--bourne-shell"])).stdout).toContain("*.jpg=01;35");
+ expect((await run(["dircolors", "--bourne-shell"])).stdout).toContain("*~=00;90:*#=00;90");
+ expect((await run(["dircolors", "--c-shell"])).stdout).toContain("setenv LS_COLORS 'rs=0:di=01;34");
+ expect((await run(["dircolors", "--c-shell"])).stdout).toContain("*.mp3=00;36");
+ await writeFile(join(dir, "colors.db"), "DIR 01;35\nEXEC 01;32\n");
+ expect((await run(["dircolors", "colors.db"])).stdout).toContain("LS_COLORS='di=01;35:ex=01;32:'");
+ expect(await run(["dircolors", "-b", "-"], "exec 'echo Hello;:'\n")).toMatchObject({ code: 0, stdout: "LS_COLORS='ex='\\''echo Hello;\\:'\\'':';\nexport LS_COLORS\n" });
+ expect(await run(["dircolors", "-b", "-"], "TERM nomatch\nowt 40;33\n")).toMatchObject({ code: 0, stdout: "LS_COLORS='';\nexport LS_COLORS\n" });
+ expect(await run(["dircolors", "-b", "-"], "TERM non*\nowt 40;33\n", { env: { TERM: "none" } })).toMatchObject({ code: 0, stdout: "LS_COLORS='tw=40;33:';\nexport LS_COLORS\n" });
+ expect((await run(["dircolors", "-b"], "DIR 01;35\n")).stdout).toContain("di=01;34");
+ expect(await run(["dircolors", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: dircolors [OPTION]... [FILE]\n") });
+ expect(await run(["dircolors", "-b", "-"], "COLORTERM ?*\nowt 40;33\n", { env: { COLORTERM: "any" } })).toMatchObject({ code: 0, stdout: "LS_COLORS='tw=40;33:';\nexport LS_COLORS\n" });
+ expect(await run(["dircolors", "-b", "-"], ".tar 01;31\n*.zip 01;31\n")).toMatchObject({ code: 0, stdout: "LS_COLORS='*.tar=01;31:*.zip=01;31:';\nexport LS_COLORS\n" });
+ expect(await run(["dircolors", "-b", "-"], ".FOO 01;31\n*.BAR 01;32\n")).toMatchObject({ code: 0, stdout: "LS_COLORS='*.FOO=01;31:*.BAR=01;32:';\nexport LS_COLORS\n" });
+ expect(await run(["dircolors", "-c", "-"], "LEFTCODE \x1b[\nRIGHTCODE m\nENDCODE \x1b[0m\n")).toMatchObject({ code: 0, stdout: "setenv LS_COLORS 'lc=\x1b[:rc=m:ec=\x1b[0m:'\n" });
+ expect(await run(["dircolors", "-b", "-"], ".foo 01\\:31\n")).toMatchObject({ code: 0, stdout: "LS_COLORS='*.foo=01\\:31:';\nexport LS_COLORS\n" });
+ await writeFile(join(dir, "color-colon.foo"), "x");
+ expect((await run(["ls", "-1", "--color=always", "color-colon.foo"], "", { env: { LS_COLORS: "*.foo=01\\:31:" } })).stdout).toBe("\x1b[0m\x1b[01:31mcolor-colon.foo\x1b[0m\n");
+ expect(await run(["dircolors", "--print-ls-colors", "-"], "OWT 40;33\n")).toMatchObject({ code: 0, stdout: "\x1B[40;33mtw\t40;33\x1B[0m\n" });
+ expect((await run(["dircolors", "--print-ls-colors"])).stdout).toContain("\x1B[01;31m*.tar\t01;31\x1B[0m\n");
+ expect((await run(["dircolors", "--print-ls-colors"])).stdout).toContain("\x1B[00;90m*~\t00;90\x1B[0m\n");
+ expect(await run(["dircolors", "--print-ls", "-"], "OWT 40;33\n")).toMatchObject({ code: 0, stdout: "\x1B[40;33mtw\t40;33\x1B[0m\n" });
+ expect((await run(["dircolors", "--print", "--help"])).stderr).toContain("option '--print' is ambiguous");
+ expect((await run(["dircolors", "--print-d=foo", "--help"])).stderr).toContain("option '--print-database' doesn't allow an argument");
+ expect((await run(["dircolors", "--bad", "--help"])).stderr).toContain("unrecognized option '--bad'");
+ expect((await run(["dircolors", "-x", "--help"])).stderr).toContain("invalid option -- 'x'");
+ expect((await run(["dircolors", "colors.db", "--b"])).stdout).toContain("LS_COLORS='di=01;35:ex=01;32:'");
+ expect(await run(["dircolors", "colors.db", "colors.db"])).toMatchObject({ code: 1, stdout: "", stderr: `dircolors: extra operand ${diagnosticQuote("colors.db")}\nTry 'dircolors --help' for more information.\n` });
+ expect(await run(["dircolors", "colors.db", "extra\narg"])).toMatchObject({ code: 1, stdout: "", stderr: `dircolors: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'dircolors --help' for more information.\n` });
+ expect((await run(["dircolors", "-p", "--print-ls-colors"])).stderr).toContain("mutually exclusive");
+ expect(await run(["dircolors", "-p", "colors.db"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `dircolors: extra operand ${diagnosticQuote("colors.db")}\nfile operands cannot be combined with --print-database (-p)\nTry 'dircolors --help' for more information.\n`,
+ });
+ expect(await run(["dircolors", "-p", "extra\narg"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `dircolors: extra operand ${diagnosticQuote("extra\\narg")}\nfile operands cannot be combined with --print-database (-p)\nTry 'dircolors --help' for more information.\n`,
+ });
+ expect(await run(["dircolors", "-p", "--bourne-shell", "colors.db"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dircolors: the options to output non shell syntax,\nand to select a shell syntax are mutually exclusive\nTry 'dircolors --help' for more information.\n",
+ });
+ expect(await run(["dircolors", "--bourne-shell", "missing-colors"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dircolors: missing-colors: No such file or directory\n",
+ });
+ expect(await run(["dircolors", "missing'dircolors"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dircolors: \"missing'dircolors\": No such file or directory\n",
+ });
+ expect(await run(["dircolors", "missing\ndircolors"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dircolors: 'missing'$'\\n''dircolors': No such file or directory\n",
+ });
+ await mkdir(join(dir, "dir'dircolors"));
+ expect(await run(["dircolors", "dir'dircolors"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dircolors: \"dir'dircolors\": read error: Is a directory\n",
+ });
+ await symlink("loop'dircolors", join(dir, "loop'dircolors"));
+ expect(await run(["dircolors", "loop'dircolors"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dircolors: \"loop'dircolors\": Too many levels of symbolic links\n",
+ });
+ expect(await run(["dircolors", "--print-ls-colors", "missing-colors"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: "dircolors: missing-colors: No such file or directory\n",
+ });
+ expect(await run(["dircolors", "one", "two"])).toMatchObject({ code: 1 });
+ await writeFile(join(dir, "secret"), "topsecret");
+ expect(await run(["shred", "-n", "1", "-z", "secret"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "secret"))).toEqual(new Uint8Array(9));
+ expect(await run(["shred", "--random-source=missing-random", "-n1", "secret"])).toMatchObject({ code: 1, stdout: "", stderr: "shred: missing-random: No such file or directory\n" });
+ await writeFile(join(dir, "shred-random"), new Uint8Array([0, 0, 0, 0, 0, 0]));
+ await writeFile(join(dir, "shred-random-target"), "abcdef");
+ expect(await run(["shred", "--random-source=shred-random", "-n1", "--exact", "shred-random-target"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "shred-random-target"))).toEqual(new Uint8Array(6));
+ await writeFile(join(dir, "shred-short-random"), new Uint8Array([0, 0, 0, 0]));
+ await writeFile(join(dir, "shred-short-target"), "abcdef");
+ expect(await run(["shred", "--random-source=shred-short-random", "-n1", "--exact", "shred-short-target"])).toMatchObject({ code: 1, stdout: "", stderr: `shred: ${diagnosticQuote("shred-short-random")}: end of file\n` });
+ expect(await readFile(join(dir, "shred-short-target"), "utf8")).toBe("abcdef");
+ expect(await run(["shred", "-x", "-n0", "secret"])).toMatchObject({ code: 0 });
+ expect(await run(["shred", "--iter=0", "secret"])).toMatchObject({ code: 0 });
+ expect((await run(["shred", "--ex", "--help"])).stdout).toContain("Usage: shred [OPTION]... FILE...\n");
+ expect((await run(["shred", "-x", "--help"])).stdout).toContain("Usage: shred [OPTION]... FILE...\n");
+ expect((await run(["shred", "--r", "--help"])).stderr).toContain("option '--r' is ambiguous; possibilities: '--random-source' '--remove'");
+ expect(await run(["shred", "--random", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["shred", "--remove", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: shred [OPTION]... FILE...\n") });
+ expect(await run(["shred", "secret", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: shred [OPTION]... FILE...\n"), stderr: "" });
+ expect(await run(["shred", "--size", "--help", "--version"])).toMatchObject({ code: 1, stderr: `shred: invalid file size: ${diagnosticQuote("--help")}\n` });
+ expect(await run(["shred", "--iterations", "--help", "--version"])).toMatchObject(await systemRun(["shred", "--iterations", "--help", "--version"]));
+ expect(await run(["shred", "-vsbad", "--help"])).toMatchObject({ code: 1, stderr: `shred: invalid file size: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["shred", "-vnbad", "--help"])).toMatchObject({ code: 1, stderr: `shred: invalid number of passes: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["shred", "--remove=", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `shred: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--remove")}\nValid arguments are:\n - ${diagnosticQuote("unlink")}\n - ${diagnosticQuote("wipe")}\n - ${diagnosticQuote("wipesync")}\nTry 'shred --help' for more information.\n`,
+ });
+ expect(await run(["shred", "--remove=bad", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `shred: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("--remove")}\nValid arguments are:\n - ${diagnosticQuote("unlink")}\n - ${diagnosticQuote("wipe")}\n - ${diagnosticQuote("wipesync")}\nTry 'shred --help' for more information.\n`,
+ });
+ expect(await run(["shred", "--remove=bad\nmode", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `shred: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--remove")}\nValid arguments are:\n - ${diagnosticQuote("unlink")}\n - ${diagnosticQuote("wipe")}\n - ${diagnosticQuote("wipesync")}\nTry 'shred --help' for more information.\n`,
+ });
+ expect(await run(["shred", "--remove=w", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `shred: ambiguous argument ${diagnosticQuote("w")} for ${diagnosticQuote("--remove")}\nValid arguments are:\n - ${diagnosticQuote("unlink")}\n - ${diagnosticQuote("wipe")}\n - ${diagnosticQuote("wipesync")}\nTry 'shred --help' for more information.\n`,
+ });
+ await writeFile(join(dir, "shred-remove-prefix"), "");
+ expect(await run(["shred", "--remove=u", "-n0", "-s0", "shred-remove-prefix"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "shred-remove-prefix"))).rejects.toThrow();
+ await writeFile(join(dir, "shred-remove-wipesync-prefix"), "");
+ expect(await run(["shred", "--remove=wipes", "-n0", "-s0", "shred-remove-wipesync-prefix"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "shred-remove-wipesync-prefix"))).rejects.toThrow();
+ expect((await run(["shred", "--zero=bad", "--help"])).stderr).toContain("option '--zero' doesn't allow an argument");
+ expect(await run(["shred", "-n", "+0", "secret"])).toMatchObject({ code: 0 });
+ expect(await run(["shred", "-n", "1\n2", "secret"])).toMatchObject({ code: 1, stdout: "", stderr: `shred: invalid number of passes: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["shred", "-n", "0x1", "secret"])).toMatchObject(await systemRun(["shred", "-n", "0x1", "secret"]));
+ expect(await run(["shred", "-n", "1.5", "secret"])).toMatchObject(await systemRun(["shred", "-n", "1.5", "secret"]));
+ expect(await run(["shred", "-n", "-1", "secret"])).toMatchObject(await systemRun(["shred", "-n", "-1", "secret"]));
+ expect(await run(["shred", "-s", "bad", "secret"])).toMatchObject({ code: 1, stderr: `shred: invalid file size: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["shred", "-s", "1\n2", "secret"])).toMatchObject({ code: 1, stdout: "", stderr: `shred: invalid file size: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["shred", "--size=bad", "secret"])).toMatchObject({ code: 1, stderr: `shred: invalid file size: ${diagnosticQuote("bad")}\n` });
+ await writeFile(join(dir, "shred-size-byte"), "abcdef");
+ expect(await run(["shred", "-n1", "--size=1B", "shred-size-byte"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "shred-size-byte"))).size).toBe(1);
+ expect(await run(["shred", "--size=0x10", "secret"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "secret"))).size).toBe(16);
+ expect(await run(["shred", "missing'shred"])).toMatchObject({ code: 1, stdout: "", stderr: "shred: \"missing'shred\": failed to open for writing: No such file or directory\n" });
+ expect(await run(["shred", "missing\nshred"])).toMatchObject({ code: 1, stdout: "", stderr: "shred: 'missing'$'\\n''shred': failed to open for writing: No such file or directory\n" });
+ await mkdir(join(dir, "dir'shred"));
+ expect(await run(["shred", "dir'shred"])).toMatchObject({ code: 1, stdout: "", stderr: "shred: \"dir'shred\": failed to open for writing: Is a directory\n" });
+ await symlink("loop'shred", join(dir, "loop'shred"));
+ expect(await run(["shred", "loop'shred"])).toMatchObject({ code: 1, stdout: "", stderr: "shred: \"loop'shred\": failed to open for writing: Too many levels of symbolic links\n" });
+ await writeFile(join(dir, "remove-secret"), "hidden");
+ const shredVerbose = await run(["shred", "-f", "-v", "-n", "1", "--remove=unlink", "remove-secret"]);
+ expect(shredVerbose).toMatchObject({ code: 0 });
+ expect(shredVerbose.stderr).toContain("shred: remove-secret: pass 1/1 (random)...");
+ expect(shredVerbose.stderr).toContain("shred: remove-secret: removed");
+ await expect(stat(join(dir, "remove-secret"))).rejects.toThrow();
+ await writeFile(join(dir, "remove'shred"), "hidden");
+ expect(await run(["shred", "-v", "-n", "0", "--remove=unlink", "remove'shred"])).toMatchObject({
+ code: 0,
+ stdout: "",
+ stderr: "shred: \"remove'shred\": removing\nshred: \"remove'shred\": removed\n",
+ });
+ await expect(stat(join(dir, "remove'shred"))).rejects.toThrow();
+});
+
+test("ownership and passthrough command surfaces", async () => {
+ expect(await run(["chown"])).toMatchObject({
+ code: 1,
+ stderr: "chown: missing operand\nTry 'chown --help' for more information.\n",
+ });
+ expect(await run(["chown", "root"])).toMatchObject({
+ code: 1,
+ stderr: "chown: missing operand after 'root'\nTry 'chown --help' for more information.\n",
+ });
+ expect(await run(["chgrp"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: missing operand\nTry 'chgrp --help' for more information.\n",
+ });
+ expect(await run(["chgrp", "root"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: missing operand after 'root'\nTry 'chgrp --help' for more information.\n",
+ });
+ const currentUid = process.getuid?.() ?? (await stat(dir)).uid;
+ const currentGid = process.getgid?.() ?? (await stat(dir)).gid;
+ const absentUid = currentUid + 12345;
+ const currentUserName = (await systemRun(["id", "-un"])).stdout.trim();
+ const currentGroupName = (await systemRun(["id", "-gn"])).stdout.trim();
+ await writeFile(join(dir, "owner-ref"), "ref");
+ await writeFile(join(dir, "owner-target"), "target");
+ await symlink("missing-owner-target", join(dir, "owner-dangling"));
+ await mkdir(join(dir, "owner-post"));
+ await writeFile(join(dir, "owner-post/file"), "child");
+ await mkdir(join(dir, "owner-real"));
+ await writeFile(join(dir, "owner-real/file"), "linked");
+ await mkdir(join(dir, "owner-links"));
+ await symlink("../owner-real", join(dir, "owner-links/linkdir"));
+ await writeFile(join(dir, "owner-chown-fail"), "target");
+ await writeFile(join(dir, "owner-chgrp-fail"), "target");
+ expect(await run(["chown", "-v", ":", "owner-target"])).toMatchObject({
+ code: 0,
+ stdout: "ownership of 'owner-target' retained\n",
+ });
+ expect(await run(["chown", "-R", "-v", String(currentUid), "owner-post"])).toMatchObject({
+ code: 0,
+ stdout: `ownership of 'owner-post/file' retained as ${currentUserName}\nownership of 'owner-post' retained as ${currentUserName}\n`,
+ });
+ expect(await run(["chown", "-R", "-v", String(currentUid), "owner-links/linkdir"])).toMatchObject({
+ code: 0,
+ stdout: `ownership of 'owner-links/linkdir' retained as ${currentUserName}\n`,
+ });
+ expect(await run(["chown", "-RH", "-v", String(currentUid), "owner-links/linkdir"])).toMatchObject({
+ code: 0,
+ stdout: `ownership of 'owner-links/linkdir/file' retained as ${currentUserName}\nownership of 'owner-links/linkdir' retained as ${currentUserName}\n`,
+ });
+ expect(await run(["chown", "-v", ":", "owner-dangling"])).toMatchObject({
+ code: 1,
+ stdout: "failed to change ownership of 'owner-dangling'\n",
+ stderr: "chown: cannot dereference 'owner-dangling': No such file or directory\n",
+ });
+ expect(await run(["chown", "-v", String(currentUid), "owner-missing-verbose"])).toMatchObject({
+ code: 1,
+ stdout: `failed to change ownership of 'owner-missing-verbose' to ${currentUid}\n`,
+ stderr: "chown: cannot access 'owner-missing-verbose': No such file or directory\n",
+ });
+ expect(await run(["chown", "-v", `:${currentGid}`, "owner-missing-group-verbose"])).toMatchObject({
+ code: 1,
+ stdout: `failed to change group of 'owner-missing-group-verbose' to ${currentGid}\n`,
+ stderr: "chown: cannot access 'owner-missing-group-verbose': No such file or directory\n",
+ });
+ await symlink("missing-owner-target", join(dir, "owner\nlink"));
+ expect(await run(["chown", "-v", ":", "owner\nlink"])).toMatchObject({
+ code: 1,
+ stdout: "failed to change ownership of 'owner'$'\\n''link'\n",
+ stderr: "chown: cannot dereference 'owner'$'\\n''link': No such file or directory\n",
+ });
+ expect(await run(["chown", "-v", String(currentUid), "owner-target"])).toMatchObject({
+ code: 0,
+ stdout: `ownership of 'owner-target' retained as ${currentUserName}\n`,
+ });
+ expect(await run(["chown", "-v", `${currentUid}:${currentGid}`, "owner-target"])).toMatchObject({
+ code: 0,
+ stdout: `ownership of 'owner-target' retained as ${currentUserName}:${currentGroupName}\n`,
+ });
+ expect(await run(["chown", "-c", `${currentUid}:${currentGid}`, "owner-target"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["chown", `+${currentUid}:+${currentGid}`, "owner-target"])).toMatchObject({ code: 0 });
+ expect(await run(["chown", `${currentUid}.${currentGid}`, "owner-target"])).toMatchObject({
+ code: 0,
+ stderr: `chown: warning: '.' should be ':': '${currentUid}.${currentGid}'\n`,
+ });
+ expect(await run(["chown", "root", "owner-chown-fail"])).toMatchObject(await systemRun(["/usr/bin/chown", "root", "owner-chown-fail"]));
+ expect(await run(["chown", `no-such-bnu-user.${currentGroupName}`, "owner-target"])).toMatchObject(await systemRun(["/usr/bin/chown", `no-such-bnu-user.${currentGroupName}`, "owner-target"]));
+ expect(await run(["chown", "no-such\nuser", "owner-target"])).toMatchObject({
+ code: 1,
+ stderr: `chown: invalid user: ${diagnosticQuote("no-such\\nuser")}\n`,
+ });
+ expect(await run(["chown", `${currentUid}.`, "owner-target"])).toMatchObject(await systemRun(["/usr/bin/chown", `${currentUid}.`, "owner-target"]));
+ expect(await run(["chown", ":no-such-bnu-group", "owner-target"])).toMatchObject(await systemRun(["/usr/bin/chown", ":no-such-bnu-group", "owner-target"]));
+ expect(await run(["chown", `${currentUid}:no-such-bnu-group`, "owner-target"])).toMatchObject(await systemRun(["/usr/bin/chown", `${currentUid}:no-such-bnu-group`, "owner-target"]));
+ expect(await run(["chown", "no-such-bnu-user:", "owner-target"])).toMatchObject({
+ code: 1,
+ stderr: `chown: invalid spec: ${diagnosticQuote("no-such-bnu-user:")}\n`,
+ });
+ expect(await run(["chown", "123\n:", "owner-target"])).toMatchObject({
+ code: 1,
+ stderr: `chown: invalid spec: ${diagnosticQuote("123\\n:")}\n`,
+ });
+ expect(await run(["chown", `--from=${currentUid}:no-such-bnu-group`, String(currentUid), "owner-target"])).toMatchObject(await systemRun(["/usr/bin/chown", `--from=${currentUid}:no-such-bnu-group`, String(currentUid), "owner-target"]));
+ expect(await run(["chown", "--changes", String(currentUid), "owner-target"])).toMatchObject({ code: 0 });
+ expect(await run(["chown", `--from=${absentUid}`, "-v", String(currentUid), "owner-target"])).toMatchObject({
+ code: 0,
+ stdout: `ownership of 'owner-target' retained as ${currentUserName}\n`,
+ });
+ expect(await run(["chown", `--from=${absentUid}`, "-c", String(currentUid), "owner-target"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["chown", `--from=${currentUid}`, String(currentUid), "owner-target"])).toMatchObject({ code: 0 });
+ expect(await run(["chown", "--from", "--help", "--version"])).toMatchObject(await systemRun(["/usr/bin/chown", "--from", "--help", "--version"]));
+ expect(await run(["chown", `--from=${currentUid}`, "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: chown [OPTION]... [OWNER][:[GROUP]] FILE...\n or: chown [OPTION]... --reference=RFILE FILE...\n") });
+ expect(await run(["chown", "--reference=owner-ref", "owner-target"])).toMatchObject({ code: 0 });
+ expect(await run(["chown", "--ref=owner-ref", "owner-target"])).toMatchObject({ code: 0 });
+ expect((await run(["chown", "--ref=missing-ref", "--help"])).stdout).toContain("Usage: chown");
+ expect(await run(["chown", "--r", "--help"])).toMatchObject({ code: 1, stderr: "chown: option '--r' is ambiguous; possibilities: '--recursive' '--reference'\nTry 'chown --help' for more information.\n" });
+ expect(await run(["chown", "--changes=bad", "--help"])).toMatchObject({ code: 1, stderr: "chown: option '--changes' doesn't allow an argument\nTry 'chown --help' for more information.\n" });
+ expect(await run(["chown", "--bad", "--help"])).toMatchObject({ code: 1, stderr: "chown: unrecognized option '--bad'\nTry 'chown --help' for more information.\n" });
+ expect(await run(["chown", "-Rbad", "--help"])).toMatchObject({ code: 1, stderr: "chown: invalid option -- 'b'\nTry 'chown --help' for more information.\n" });
+ expect((await stat(join(dir, "owner-target"))).uid).toBe((await stat(join(dir, "owner-ref"))).uid);
+ expect(await run(["chown", "--reference=missing-ref", "owner-target"])).toMatchObject({
+ code: 1,
+ stderr: "chown: failed to get attributes of 'missing-ref': No such file or directory\n",
+ });
+ expect(await run(["chown", "--reference", "owner-ref"])).toMatchObject({
+ code: 1,
+ stderr: "chown: missing operand\nTry 'chown --help' for more information.\n",
+ });
+ expect(await run(["chown", "--reference=owner-ref", "missing-owner"])).toMatchObject({
+ code: 1,
+ stderr: "chown: cannot access 'missing-owner': No such file or directory\n",
+ });
+ expect(await run(["chown", String(currentUid), "missing\nowner"])).toMatchObject({
+ code: 1,
+ stderr: "chown: cannot access 'missing'$'\\n''owner': No such file or directory\n",
+ });
+ expect(await run(["chown", String(currentUid), "missing'owner"])).toMatchObject({
+ code: 1,
+ stderr: "chown: cannot access \"missing'owner\": No such file or directory\n",
+ });
+ await writeFile(join(dir, "owner\nverbose"), "target");
+ expect(await run(["chown", "-v", String(currentUid), "owner\nverbose"])).toMatchObject({
+ code: 0,
+ stdout: `ownership of 'owner'$'\\n''verbose' retained as ${currentUserName}\n`,
+ });
+ await writeFile(join(dir, "owner'verbose"), "target");
+ expect(await run(["chown", "-v", String(currentUid), "owner'verbose"])).toMatchObject({
+ code: 0,
+ stdout: `ownership of "owner'verbose" retained as ${currentUserName}\n`,
+ });
+ expect(await run(["chgrp", "--changes", String(currentGid), "owner-target"])).toMatchObject({ code: 0 });
+ expect(await run(["chgrp", `+${currentGid}`, "owner-target"])).toMatchObject({ code: 0 });
+ expect(await run(["chgrp", `--from=${currentGid}`, String(currentGid), "owner-target"])).toMatchObject({ code: 0 });
+ expect(await run(["chgrp", `--from=${currentUid}:${currentGid}`, String(currentGid), "owner-target"])).toMatchObject({ code: 0 });
+ expect(await run(["chgrp", `--from=${currentUid}.${currentGid}`, String(currentGid), "owner-target"])).toMatchObject({
+ code: 0,
+ stderr: `chgrp: warning: '.' should be ':': '${currentUid}.${currentGid}'\n`,
+ });
+ expect(await run(["chgrp", "-R", "root", "owner-chgrp-fail"])).toMatchObject(await systemRun(["/usr/bin/chgrp", "-R", "root", "owner-chgrp-fail"]));
+ expect(await run(["chgrp", "no-such-bnu-group", "owner-target"])).toMatchObject(await systemRun(["/usr/bin/chgrp", "no-such-bnu-group", "owner-target"]));
+ expect(await run(["chgrp", "no-such\ngroup", "owner-target"])).toMatchObject({
+ code: 1,
+ stderr: `chgrp: invalid group: ${diagnosticQuote("no-such\\ngroup")}\n`,
+ });
+ expect(await run(["chgrp", "--from=no-such-bnu-user", String(currentGid), "owner-target"])).toMatchObject(await systemRun(["/usr/bin/chgrp", "--from=no-such-bnu-user", String(currentGid), "owner-target"]));
+ expect(await run(["chgrp", `--from=${currentUid}:no-such-bnu-group`, String(currentGid), "owner-target"])).toMatchObject(await systemRun(["/usr/bin/chgrp", `--from=${currentUid}:no-such-bnu-group`, String(currentGid), "owner-target"]));
+ expect(await run(["chgrp", "-v", String(currentGid), "owner-target"])).toMatchObject({
+ code: 0,
+ stdout: `group of 'owner-target' retained as ${currentGroupName}\n`,
+ });
+ expect(await run(["chgrp", "-v", String(currentGid), "group-missing-verbose"])).toMatchObject({
+ code: 1,
+ stdout: `failed to change group of 'group-missing-verbose' to ${currentGid}\n`,
+ stderr: "chgrp: cannot access 'group-missing-verbose': No such file or directory\n",
+ });
+ expect(await run(["chgrp", "-R", "-v", String(currentGid), "owner-links/linkdir"])).toMatchObject({
+ code: 0,
+ stdout: `group of 'owner-links/linkdir' retained as ${currentGroupName}\n`,
+ });
+ expect(await run(["chgrp", `--from=${absentUid}`, "-v", String(currentGid), "owner-target"])).toMatchObject({
+ code: 0,
+ stdout: `group of 'owner-target' retained as ${currentGroupName}\n`,
+ });
+ expect(await run(["chgrp", `--from=${absentUid}`, "-c", String(currentGid), "owner-target"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["chgrp", "-c", String(currentGid), "owner-target"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["chgrp", "--from", "--help", "--version"])).toMatchObject(await systemRun(["/usr/bin/chgrp", "--from", "--help", "--version"]));
+ expect(await run(["chgrp", `--from=${currentUid}`, "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: chgrp [OPTION]... GROUP FILE...\n or: chgrp [OPTION]... --reference=RFILE FILE...\n") });
+ expect(await run(["chgrp", "--reference=owner-ref", "owner-target"])).toMatchObject({ code: 0 });
+ expect(await run(["chgrp", "--ref=owner-ref", "owner-target"])).toMatchObject({ code: 0 });
+ expect((await run(["chgrp", "--ref=missing-ref", "--help"])).stdout).toContain("Usage: chgrp");
+ expect(await run(["chgrp", "--r", "--help"])).toMatchObject({ code: 1, stderr: "chgrp: option '--r' is ambiguous; possibilities: '--recursive' '--reference'\nTry 'chgrp --help' for more information.\n" });
+ expect(await run(["chgrp", "--changes=bad", "--help"])).toMatchObject({ code: 1, stderr: "chgrp: option '--changes' doesn't allow an argument\nTry 'chgrp --help' for more information.\n" });
+ expect(await run(["chgrp", "--bad", "--help"])).toMatchObject({ code: 1, stderr: "chgrp: unrecognized option '--bad'\nTry 'chgrp --help' for more information.\n" });
+ expect(await run(["chgrp", "-Rbad", "--help"])).toMatchObject({ code: 1, stderr: "chgrp: invalid option -- 'b'\nTry 'chgrp --help' for more information.\n" });
+ expect((await stat(join(dir, "owner-target"))).gid).toBe((await stat(join(dir, "owner-ref"))).gid);
+ expect(await run(["chgrp", "--reference=missing-ref", "owner-target"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: failed to get attributes of 'missing-ref': No such file or directory\n",
+ });
+ expect(await run(["chgrp", "--reference", "owner-ref"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: missing operand\nTry 'chgrp --help' for more information.\n",
+ });
+ expect(await run(["chgrp", "--reference=owner-ref", "missing-group"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: cannot access 'missing-group': No such file or directory\n",
+ });
+ expect(await run(["chgrp", String(currentGid), "missing\ngroup"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: cannot access 'missing'$'\\n''group': No such file or directory\n",
+ });
+ expect(await run(["chgrp", String(currentGid), "missing'group"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: cannot access \"missing'group\": No such file or directory\n",
+ });
+ await writeFile(join(dir, "group'verbose"), "target");
+ expect(await run(["chgrp", "-v", String(currentGid), "group'verbose"])).toMatchObject({
+ code: 0,
+ stdout: `group of "group'verbose" retained as ${currentGroupName}\n`,
+ });
+ expect(await run(["chown", "-R", "--preserve-root", String(process.getuid?.() ?? 0), "/"])).toMatchObject({
+ code: 1,
+ stderr: "chown: it is dangerous to operate recursively on '/'\nchown: use --no-preserve-root to override this failsafe\n",
+ });
+ expect(await run(["chgrp", "-R", "--preserve-root", "0", "/"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: it is dangerous to operate recursively on '/'\nchgrp: use --no-preserve-root to override this failsafe\n",
+ });
+ await mkdir(join(dir, "owner-preserve-root"));
+ await symlink("/", join(dir, "owner-preserve-root/root-link"));
+ expect(await run(["chown", "-RLh", "--preserve-root", String(currentUid), "owner-preserve-root"])).toMatchObject({
+ code: 1,
+ stderr: "chown: it is dangerous to operate recursively on 'owner-preserve-root/root-link' (same as '/')\nchown: use --no-preserve-root to override this failsafe\n",
+ });
+ expect(await run(["chgrp", "-RLh", "--preserve-root", String(currentGid), "owner-preserve-root"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: it is dangerous to operate recursively on 'owner-preserve-root/root-link' (same as '/')\nchgrp: use --no-preserve-root to override this failsafe\n",
+ });
+ expect(await run(["chmod", "-R", "--preserve-root", "u+r", "/"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: it is dangerous to operate recursively on '/'\nchmod: use --no-preserve-root to override this failsafe\n",
+ });
+ expect(await run(["stdbuf", process.execPath, "-e", "console.log('stdbuf')"])).toMatchObject({ code: 125 });
+ expect(await run(["stdbuf", "-oL", process.execPath, "-e", "console.log('line')"])).toMatchObject({ code: 0, stdout: "line\n" });
+ expect(await run(["stdbuf", "--output=L", process.execPath, "-e", "console.log('long')"])).toMatchObject({ code: 0, stdout: "long\n" });
+ expect(await run(["stdbuf", "--o=L", process.execPath, "-e", "console.log('abbr')"])).toMatchObject({ code: 0, stdout: "abbr\n" });
+ expect((await run(["stdbuf", "--out=L", "--help"])).stdout).toContain("Usage: stdbuf OPTION... COMMAND\n");
+ expect(await run(["stdbuf", "--bad", "--help"])).toMatchObject({ code: 125, stderr: "stdbuf: unrecognized option '--bad'\nTry 'stdbuf --help' for more information.\n" });
+ expect(await run(["stdbuf", "-oL", "."])).toMatchObject({ code: 126, stderr: "stdbuf: failed to run command '.': Permission denied\n" });
+ expect(await run(["stdbuf", "-oL", "--", "--bad", "--help"])).toMatchObject({ code: 127, stderr: "stdbuf: failed to run command '--bad': No such file or directory\n" });
+ const stdbufHelp = (await run(["stdbuf", "--help"])).stdout;
+ expect(stdbufHelp).toContain("Mandatory arguments to long options are mandatory for short options too.\n");
+ expect(stdbufHelp).toContain("-o, --output=MODE adjust standard output stream buffering\n");
+ expect(stdbufHelp).toContain("If MODE is 'L' the corresponding stream will be line buffered.\n");
+ expect(stdbufHelp).toContain(" 125 if the stdbuf command itself fails\n");
+ expect(await run(["stdbuf", "-o0", "/bin/sh", "-c", "printf '%s\\n' \"$1\"", "sh", "--version"])).toMatchObject({ code: 0, stdout: "--version\n" });
+ const stdbufEnv = await run(["stdbuf", "-i0", "-oL", "-eK", "env"]);
+ expect(stdbufEnv).toMatchObject({ code: 0 });
+ expect(stdbufEnv.stdout).toContain("_STDBUF_I=0\n");
+ expect(stdbufEnv.stdout).toContain("_STDBUF_O=L\n");
+ expect(stdbufEnv.stdout).toContain("_STDBUF_E=1024\n");
+ expect(stdbufEnv.stdout).toContain("LD_PRELOAD=");
+ const stdbufLargeEnv = await run(["stdbuf", "-o1EB", "env"]);
+ expect(stdbufLargeEnv).toMatchObject({ code: 0 });
+ expect(stdbufLargeEnv.stdout).toContain("_STDBUF_O=1000000000000000000\n");
+ expect(await shell(`
+ set -eu
+ mkfifo fifo
+ (printf '1\\n'; sleep .1; printf '2\\n') | "$BUN" "$BNU" stdbuf -oL uniq > fifo &
+ pid=$!
+ IFS= read -r line < fifo
+ test "$line" = 1
+ wait "$pid" || test "$?" = 141
+ `)).toMatchObject({ code: 0 });
+ expect(await run(["stdbuf"])).toMatchObject({ code: 125, stderr: "stdbuf: missing operand\nTry 'stdbuf --help' for more information.\n" });
+ expect(await run(["stdbuf", "--"])).toMatchObject({ code: 125, stderr: "stdbuf: missing operand\nTry 'stdbuf --help' for more information.\n" });
+ expect(await run(["stdbuf", "-oL"])).toMatchObject({ code: 125, stderr: "stdbuf: missing operand\nTry 'stdbuf --help' for more information.\n" });
+ expect(await run(["stdbuf", "-oL", "--"])).toMatchObject({ code: 125, stderr: "stdbuf: missing operand\nTry 'stdbuf --help' for more information.\n" });
+ expect(await run(["stdbuf", "--input=L", "true"])).toMatchObject({ code: 125, stderr: "stdbuf: line buffering standard input is meaningless\nTry 'stdbuf --help' for more information.\n" });
+ expect(await run(["stdbuf", "--input=bad", "--help"])).toMatchObject(await systemRun(["stdbuf", "--input=bad", "--help"]));
+ expect(await run(["stdbuf", "--output=bad\nmode", "true"])).toMatchObject({ code: 125, stderr: `stdbuf: invalid mode ${diagnosticQuote("bad\\nmode")}\n` });
+ expect(await run(["stdbuf", "--output=", "true"])).toMatchObject(await systemRun(["stdbuf", "--output=", "true"]));
+ expect(await run(["stdbuf", "-o1b", "true"])).toMatchObject(await systemRun(["stdbuf", "-o1b", "true"]));
+ expect(await run(["stdbuf", "--help=bad"])).toMatchObject({ code: 125, stderr: "stdbuf: option '--help' doesn't allow an argument\nTry 'stdbuf --help' for more information.\n" });
+ expect(await run(["stdbuf", "--version=bad"])).toMatchObject({ code: 125, stderr: "stdbuf: option '--version' doesn't allow an argument\nTry 'stdbuf --help' for more information.\n" });
+ expect(await run(["stdbuf", "-o18446744073709551616", "true"])).toMatchObject(await systemRun(["stdbuf", "-o18446744073709551616", "true"]));
+ for (const option of ["-i", "-o", "-e"]) {
+ expect(await run(["stdbuf", option])).toMatchObject({ code: 125, stderr: `stdbuf: option requires an argument -- '${option.slice(1)}'\nTry 'stdbuf --help' for more information.\n` });
+ }
+ for (const option of ["--input", "--output", "--error"]) {
+ expect(await run(["stdbuf", option])).toMatchObject({ code: 125, stderr: `stdbuf: option '${option}' requires an argument\nTry 'stdbuf --help' for more information.\n` });
+ }
+ const noSelinuxRuncon = { code: 125, stderr: "runcon: runcon may be used only on a SELinux kernel\n" };
+ expect(await run(["runcon", "system_u:system_r:bin_t", process.execPath, "-e", "console.log('runcon')"])).toMatchObject(noSelinuxRuncon);
+ expect(await run(["runcon", "system_u:system_r:bin_t", "/bin/sh", "-c", "printf '%s\\n' \"$1\"", "sh", "--version"])).toMatchObject(noSelinuxRuncon);
+ expect((await run(["runcon", "--compute", "--help"])).stdout).toContain("Usage: runcon CONTEXT COMMAND [args]\n or: runcon [ -c ] [-u USER] [-r ROLE] [-t TYPE] [-l RANGE] COMMAND [args]\n");
+ expect(await run(["runcon", "-u", "user_u", "/bin/sh", "-c", "printf '%s\\n' \"$1\"", "sh", "--version"])).toMatchObject(noSelinuxRuncon);
+ expect(await run(["runcon", "--u", "user_u", "/bin/sh", "-c", "printf '%s\\n' \"$1\"", "sh", "abbr"])).toMatchObject(noSelinuxRuncon);
+ expect(await run(["runcon", "--ro", "role_r", "/bin/sh", "-c", "printf '%s\\n' \"$1\"", "sh", "role"])).toMatchObject(noSelinuxRuncon);
+ expect(await run(["runcon", "--user", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["runcon", "--r", "--help"])).toMatchObject({ code: 125, stderr: "runcon: option '--r' is ambiguous; possibilities: '--role' '--range'\nTry 'runcon --help' for more information.\n" });
+ expect(await run(["runcon", "--comp=bad", "--help"])).toMatchObject({ code: 125, stderr: "runcon: option '--compute' doesn't allow an argument\nTry 'runcon --help' for more information.\n" });
+ expect(await run(["runcon", "--help=bad"])).toMatchObject({ code: 125, stderr: "runcon: option '--help' doesn't allow an argument\nTry 'runcon --help' for more information.\n" });
+ expect(await run(["runcon", "--bad", "--help"])).toMatchObject({ code: 125, stderr: "runcon: unrecognized option '--bad'\nTry 'runcon --help' for more information.\n" });
+ expect(await run(["runcon", "-c", "true"])).toMatchObject({ code: 125, stderr: "runcon: runcon may be used only on a SELinux kernel\n" });
+ expect(await run(["runcon"])).toMatchObject({ code: 125, stderr: "runcon: failed to get current context\n" });
+ expect(await run(["runcon", "system_u:system_r:bin_t"])).toMatchObject({ code: 125, stderr: "runcon: no command specified\nTry 'runcon --help' for more information.\n" });
+ expect(await run(["runcon", "-u", "one", "-u", "two", "true"])).toMatchObject({ code: 125, stderr: "runcon: multiple users\nTry 'runcon --help' for more information.\n" });
+ for (const option of ["-u", "-r", "-t", "-l"]) {
+ expect(await run(["runcon", option])).toMatchObject({ code: 125, stderr: `runcon: option requires an argument -- '${option.slice(1)}'\nTry 'runcon --help' for more information.\n` });
+ }
+ for (const option of ["--user", "--role", "--type", "--range"]) {
+ expect(await run(["runcon", option])).toMatchObject({ code: 125, stderr: `runcon: option '${option}' requires an argument\nTry 'runcon --help' for more information.\n` });
+ }
+ expect(await run(["who"])).toMatchObject(await systemRun(["/usr/bin/who"]));
+ expect(await run(["who", "-q"])).toMatchObject(await systemRun(["/usr/bin/who", "-q"]));
+ expect(await run(["who", "-b"])).toMatchObject(await systemRun(["/usr/bin/who", "-b"]));
+ const whoHeading = await run(["who", "-H"]);
+ expect(whoHeading).toMatchObject({ code: 0 });
+ expect(whoHeading.stdout).toStartWith("NAME LINE TIME COMMENT\n");
+ expect(await run(["who", "am", "i"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["who", "missing-a", "missing-b"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["who", "-m"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["who", "-q", "am", "i"])).toMatchObject({ code: 0, stdout: "\n# users=0\n" });
+ expect(await run(["who", "-H", "am", "i"])).toMatchObject({ code: 0, stdout: "NAME LINE TIME COMMENT\n" });
+ expect(await run(["who", "-s"])).toMatchObject({ code: 0 });
+ expect(await run(["who", "-T"])).toMatchObject({ code: 0 });
+ expect(await run(["who", "--lookup"])).toMatchObject({ code: 0 });
+ expect(await run(["who", "--loo"])).toMatchObject({ code: 0 });
+ const whoAbbrevHeading = await run(["who", "--hea"]);
+ expect(whoAbbrevHeading).toMatchObject({ code: 0 });
+ expect(whoAbbrevHeading.stdout).toStartWith("NAME LINE TIME COMMENT\n");
+ expect((await run(["who", "--he"])).stderr).toContain("option '--he' is ambiguous; possibilities: '--heading' '--help'");
+ const whoHelp = await run(["who", "--help"]);
+ const whoHelpStdout = whoHelp.stdout;
+ expect(whoHelp).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: who [OPTION]... [ FILE | ARG1 ARG2 ]\n") });
+ expect(whoHelpStdout).toContain(" -m\n");
+ expect(whoHelpStdout).toContain(" -w\n");
+ expect((await run(["who", "--heading=bad", "--help"])).stderr).toContain("option '--heading' doesn't allow an argument");
+ expect((await run(["who", "--bad", "--help"])).stderr).toContain("unrecognized option '--bad'");
+ expect((await run(["who", "-x", "--help"])).stderr).toContain("invalid option -- 'x'");
+ expect(await run(["who", "--m"])).toMatchObject({ code: 0 });
+ expect((await run(["who", "--mes=bad"])).stderr).toContain("option '--message' doesn't allow an argument");
+ expect((await run(["who", "--mesg=bad"])).stderr).toContain("option '--mesg' doesn't allow an argument");
+ expect(await run(["who", "--all"])).toMatchObject({ code: 0 });
+ expect(await run(["who", "extra"])).toMatchObject({ code: 0 });
+ await writeFile(join(dir, "empty-utmp"), "");
+ expect(await run(["who", "empty-utmp"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["who", "-q", "empty-utmp"])).toMatchObject({ code: 0, stdout: "\n# users=0\n" });
+ const whoUtmp = Buffer.alloc(384);
+ whoUtmp.writeInt16LE(7, 0);
+ whoUtmp.writeInt32LE(1234, 4);
+ // Use a deliberately impossible PTY number so -T/-w cannot observe a
+ // coincidentally live host terminal and turn the expected '?' into '+'/'-'.
+ whoUtmp.write("pts/999999", 8, "utf8");
+ whoUtmp.write("alice", 44, "utf8");
+ whoUtmp.write("example.test", 76, "utf8");
+ whoUtmp.writeInt32LE(1577934245, 340);
+ await writeFile(join(dir, "who-utmp"), whoUtmp);
+ expect(await run(["who", "who-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "alice pts/999999 2020-01-02 03:04 (example.test)\n" });
+ expect(await run(["who", "-H", "who-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "NAME LINE TIME COMMENT\nalice pts/999999 2020-01-02 03:04 (example.test)\n" });
+ expect(await run(["who", "-T", "who-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "alice ? pts/999999 2020-01-02 03:04 (example.test)\n" });
+ expect(await run(["who", "-w", "who-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "alice ? pts/999999 2020-01-02 03:04 (example.test)\n" });
+ expect(await run(["who", "-u", "who-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "alice pts/999999 2020-01-02 03:04 ? 1234 (example.test)\n" });
+ expect(await run(["who", "-T", "-u", "who-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "alice ? pts/999999 2020-01-02 03:04 ? 1234 (example.test)\n" });
+ expect(await run(["who", "-a", "who-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "alice ? pts/999999 2020-01-02 03:04 ? 1234 (example.test)\n" });
+ expect(await run(["who", "-H", "-T", "-u", "who-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "NAME LINE TIME IDLE PID COMMENT\nalice ? pts/999999 2020-01-02 03:04 ? 1234 (example.test)\n" });
+ expect(await run(["who", "who-utmp"], "", { env: { TZ: "UTC0", LC_ALL: "C" } })).toMatchObject({ code: 0, stdout: "alice pts/999999 Jan 2 03:04 (example.test)\n" });
+ expect(await run(["who", "-H", "who-utmp"], "", { env: { TZ: "UTC0", LC_ALL: "C" } })).toMatchObject({ code: 0, stdout: "NAME LINE TIME COMMENT\nalice pts/999999 Jan 2 03:04 (example.test)\n" });
+ expect(await run(["who", "-H", "-T", "-u", "who-utmp"], "", { env: { TZ: "UTC0", LC_ALL: "C" } })).toMatchObject({ code: 0, stdout: "NAME LINE TIME IDLE PID COMMENT\nalice ? pts/999999 Jan 2 03:04 ? 1234 (example.test)\n" });
+ expect(await run(["who", "-q", "who-utmp"])).toMatchObject({ code: 0, stdout: "alice\n# users=1\n" });
+ const whoProcessUtmp = Buffer.alloc(384);
+ whoProcessUtmp.writeInt16LE(5, 0);
+ whoProcessUtmp.writeInt32LE(4321, 4);
+ whoProcessUtmp.write("tty5", 8, "utf8");
+ whoProcessUtmp.write("id5", 40, "utf8");
+ whoProcessUtmp.writeInt32LE(1577934245, 340);
+ await writeFile(join(dir, "who-process-utmp"), whoProcessUtmp);
+ expect(await run(["who", "-p", "who-process-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: " tty5 2020-01-02 03:04 4321 id=id5\n" });
+ expect(await run(["who", "--process", "who-process-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: " tty5 2020-01-02 03:04 4321 id=id5\n" });
+ expect(await run(["who", "-a", "who-process-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: " tty5 2020-01-02 03:04 4321 id=id5\n" });
+ const whoSpecialUtmp = Buffer.alloc(384 * 2);
+ whoSpecialUtmp.writeInt16LE(3, 0);
+ whoSpecialUtmp.writeInt32LE(1577934245, 340);
+ whoSpecialUtmp.writeInt16LE(8, 384);
+ whoSpecialUtmp.writeInt32LE(333, 384 + 4);
+ whoSpecialUtmp.write("tty8", 384 + 8, "utf8");
+ whoSpecialUtmp.write("id8", 384 + 40, "utf8");
+ whoSpecialUtmp.writeInt16LE(9, 384 + 332);
+ whoSpecialUtmp.writeInt16LE(2, 384 + 334);
+ whoSpecialUtmp.writeInt32LE(1577934246, 384 + 340);
+ await writeFile(join(dir, "who-special-utmp"), whoSpecialUtmp);
+ expect(await run(["who", "-t", "who-special-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: " clock change 2020-01-02 03:04\n" });
+ expect(await run(["who", "--time", "who-special-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: " clock change 2020-01-02 03:04\n" });
+ expect(await run(["who", "-d", "who-special-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: " tty8 2020-01-02 03:04 333 id=id8 term=9 exit=2\n" });
+ expect(await run(["who", "-a", "who-special-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: " clock change 2020-01-02 03:04\n tty8 2020-01-02 03:04 333 id=id8 term=9 exit=2\n" });
+ expect(await run(["who", "-H", "-t", "who-special-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "NAME LINE TIME PID COMMENT\n clock change 2020-01-02 03:04\n" });
+ expect(await run(["who", "-H", "-d", "who-special-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "NAME LINE TIME IDLE PID COMMENT EXIT\n tty8 2020-01-02 03:04 333 id=id8 term=9 exit=2\n" });
+ const whoMixedUtmp = Buffer.alloc(384 * 3);
+ whoMixedUtmp.writeInt16LE(3, 0);
+ whoMixedUtmp.writeInt32LE(1577934245, 340);
+ whoMixedUtmp.writeInt16LE(7, 384);
+ whoMixedUtmp.writeInt32LE(1234, 384 + 4);
+ whoMixedUtmp.write("pts/999999", 384 + 8, "utf8");
+ whoMixedUtmp.write("alice", 384 + 44, "utf8");
+ whoMixedUtmp.writeInt32LE(1577934246, 384 + 340);
+ whoMixedUtmp.writeInt16LE(5, 768);
+ whoMixedUtmp.writeInt32LE(4321, 768 + 4);
+ whoMixedUtmp.write("tty5", 768 + 8, "utf8");
+ whoMixedUtmp.write("id5", 768 + 40, "utf8");
+ whoMixedUtmp.writeInt32LE(1577934247, 768 + 340);
+ await writeFile(join(dir, "who-mixed-utmp"), whoMixedUtmp);
+ expect(await run(["who", "-a", "who-mixed-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: " clock change 2020-01-02 03:04\nalice ? pts/999999 2020-01-02 03:04 ? 1234\n tty5 2020-01-02 03:04 4321 id=id5\n" });
+ expect(await run(["who", "-H", "-a", "who-mixed-utmp"], "", { env: { TZ: "UTC0" } })).toMatchObject({ code: 0, stdout: "NAME LINE TIME IDLE PID COMMENT EXIT\n clock change 2020-01-02 03:04\nalice ? pts/999999 2020-01-02 03:04 ? 1234\n tty5 2020-01-02 03:04 4321 id=id5\n" });
+ expect(await run(["who", "one", "two", "three"])).toMatchObject({ code: 1, stderr: `who: extra operand ${diagnosticQuote("three")}\nTry 'who --help' for more information.\n` });
+ expect(await run(["tty", "extra"])).toMatchObject(await systemRun(["tty", "extra"]));
+});
+
+test("remaining formatting and identity command surfaces", async () => {
+ await writeFile(join(dir, "alpha"), "one\ntwo\nthree\n");
+ await writeFile(join(dir, "beta"), "four\n");
+ expect(await run(["dir"])).toMatchObject({ code: 0 });
+ expect((await run(["dir", "alpha", "beta"])).stdout).toBe("alpha beta\n");
+ expect((await run(["dir", "-1", "alpha", "beta"])).stdout).toBe("alpha\nbeta\n");
+ expect((await run(["dir", "--format=single-column", "alpha", "beta"])).stdout).toBe("alpha\nbeta\n");
+ const dirHelp = await run(["dir", "--help"]);
+ expect(dirHelp.code).toBe(0);
+ expect(dirHelp.stdout).toContain("List information about the FILEs (the current directory by default).\n");
+ for (const option of ["-1", "-C", "-S", "-U", "-X", "-c", "-g", "-l", "-m", "-o", "-p", "-t", "-u", "-v", "-x"]) expect(dirHelp.stdout).toContain(` ${option}\n`);
+ expect((await run(["vdir", "alpha"])).stdout).toContain("alpha");
+ const vdirHelp = await run(["vdir", "--help"]);
+ expect(vdirHelp.code).toBe(0);
+ expect(vdirHelp.stdout).toContain("List information about the FILEs (the current directory by default).\n");
+ for (const option of ["-1", "-C", "-S", "-U", "-X", "-c", "-g", "-l", "-m", "-o", "-p", "-t", "-u", "-v", "-x"]) expect(vdirHelp.stdout).toContain(` ${option}\n`);
+ expect(await run(["chroot", ".", process.execPath, "-e", "console.log('root')"])).toMatchObject({ code: 125 });
+ expect(await run(["chroot", "--userspec=0:0", "--groups=0", ".", process.execPath, "-e", "console.log('userspec')"])).toMatchObject({ code: 125 });
+ expect(await run(["chroot", "--u=0:0", "--g=0", ".", process.execPath, "-e", "console.log('abbr')"])).toMatchObject({ code: 125 });
+ expect((await run(["chroot", "--user=0:0", "--help"])).stdout).toContain("Usage: chroot [OPTION]... NEWROOT [COMMAND [ARG]...]\n");
+ expect(await run(["chroot", "--user", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["chroot", ".", "/bin/sh", "-c", "printf '%s\\n' \"$1\"", "sh", "--version"])).toMatchObject({ code: 125 });
+ expect(await run(["chroot", "--skip-chdir", ".", process.execPath, "-e", "console.log(process.cwd())"])).toMatchObject({
+ code: 125,
+ stdout: "",
+ stderr: "chroot: option --skip-chdir only permitted if NEWROOT is old '/'\nTry 'chroot --help' for more information.\n",
+ });
+ expect((await run(["chroot", "--sk", "--help"])).stdout).toContain("Usage: chroot [OPTION]... NEWROOT [COMMAND [ARG]...]\n");
+ expect(await run(["chroot", "--s=bad", "--help"])).toMatchObject({ code: 125, stderr: "chroot: option '--skip-chdir' doesn't allow an argument\nTry 'chroot --help' for more information.\n" });
+ expect(await run(["chroot", "--help=bad"])).toMatchObject({ code: 125, stderr: "chroot: option '--help' doesn't allow an argument\nTry 'chroot --help' for more information.\n" });
+ expect(await run(["chroot", "--bad", "--help"])).toMatchObject({ code: 125, stderr: "chroot: unrecognized option '--bad'\nTry 'chroot --help' for more information.\n" });
+ expect(await run(["chroot", "--userspec"])).toMatchObject({ code: 125, stderr: "chroot: option '--userspec' requires an argument\nTry 'chroot --help' for more information.\n" });
+ expect(await run(["chroot", "--groups"])).toMatchObject({ code: 125, stderr: "chroot: option '--groups' requires an argument\nTry 'chroot --help' for more information.\n" });
+ expect(await run(["chroot", "missing-chroot-root", "/bin/true"])).toMatchObject({ code: 125, stdout: "", stderr: "chroot: cannot change root directory to 'missing-chroot-root': No such file or directory\n" });
+ await writeFile(join(dir, "chroot-not-dir"), "");
+ expect(await run(["chroot", "chroot-not-dir", "/bin/true"])).toMatchObject({ code: 125, stdout: "", stderr: "chroot: cannot change root directory to 'chroot-not-dir': Not a directory\n" });
+ expect(await run(["chroot"])).toMatchObject({ code: 125, stderr: "chroot: missing operand\nTry 'chroot --help' for more information.\n" });
+ expect(await run(["chroot", "--userspec=0:0"])).toMatchObject({ code: 125, stderr: "chroot: missing operand\nTry 'chroot --help' for more information.\n" });
+ expect(await run(["chcon", "system_u:object_r:tmp_t:s0", "alpha"])).toMatchObject({ code: 1, stderr: "chcon: failed to change context of 'alpha' to 'system_u:object_r:tmp_t:s0'\n" });
+ expect(await run(["chcon", "-u", "system_u", "-r", "object_r", "-t", "tmp_t", "-l", "s0", "alpha"])).toMatchObject({ code: 1, stderr: "chcon: can't apply partial context to unlabeled file 'alpha'\n" });
+ expect(await run(["chcon", "--u", "system_u", "--ty", "tmp_t", "alpha"])).toMatchObject({ code: 1, stderr: "chcon: can't apply partial context to unlabeled file 'alpha'\n" });
+ await mkdir(join(dir, "context-dir"));
+ await writeFile(join(dir, "context-dir/file"), "ctx\n");
+ expect(await run(["chcon", "-R", "--user=system_u", "--role=object_r", "--type=tmp_t", "--range=s0", "context-dir"])).toMatchObject({ code: 1 });
+ expect((await run(["chcon", "--rec", "--help"])).stdout).toContain("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...\n");
+ expect(await run(["chcon", "--user", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["chcon", "--r", "role_r", "alpha"])).toMatchObject({ code: 1, stderr: "chcon: option '--r' is ambiguous; possibilities: '--recursive' '--reference' '--role' '--range'\nTry 'chcon --help' for more information.\n" });
+ expect(await run(["chcon", "--recursive=bad", "--help"])).toMatchObject({ code: 1, stderr: "chcon: option '--recursive' doesn't allow an argument\nTry 'chcon --help' for more information.\n" });
+ expect(await run(["chcon", "--help=bad"])).toMatchObject({ code: 1, stderr: "chcon: option '--help' doesn't allow an argument\nTry 'chcon --help' for more information.\n" });
+ expect(await run(["chcon", "--bad", "--help"])).toMatchObject({ code: 1, stderr: "chcon: unrecognized option '--bad'\nTry 'chcon --help' for more information.\n" });
+ expect(await run(["chcon", "-u", "system_u"])).toMatchObject({ code: 1, stderr: "chcon: missing operand\nTry 'chcon --help' for more information.\n" });
+ await writeFile(join(dir, "context-ref"), "ref\n");
+ expect(await run(["chcon", "--reference=context-ref", "alpha"])).toMatchObject({ code: 1, stderr: "chcon: failed to get security context of 'context-ref'\n" });
+ expect(await run(["chcon", "--ref=context-ref", "alpha"])).toMatchObject({ code: 1, stderr: "chcon: failed to get security context of 'context-ref'\n" });
+ expect(await run(["chcon", "--reference=context-ref"])).toMatchObject({ code: 1 });
+ expect(await run(["tsort", "tsort-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: tsort-missing: No such file or directory\n" });
+ expect(await run(["tsort", "missing'tsort"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: \"missing'tsort\": No such file or directory\n" });
+ expect(await run(["tsort", "missing\ntsort"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: 'missing'$'\\n''tsort': No such file or directory\n" });
+ await mkdir(join(dir, "tsort-dir"));
+ expect(await run(["tsort", "tsort-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: tsort-dir: read error: Is a directory\n" });
+ await mkdir(join(dir, "dir'tsort"));
+ expect(await run(["tsort", "dir'tsort"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: \"dir'tsort\": read error: Is a directory\n" });
+ await symlink("tsort-loop", join(dir, "tsort-loop"));
+ expect(await run(["tsort", "tsort-loop"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: tsort-loop: Too many levels of symbolic links\n" });
+ await symlink("loop'tsort", join(dir, "loop'tsort"));
+ expect(await run(["tsort", "loop'tsort"])).toMatchObject({ code: 1, stdout: "", stderr: "tsort: \"loop'tsort\": Too many levels of symbolic links\n" });
+ expect(await run(["tsort", "alpha", "extra\narg"])).toMatchObject({ code: 1, stdout: "", stderr: `tsort: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'tsort --help' for more information.\n` });
+ expect(await run(["pr", "-t", "alpha"])).toMatchObject({ code: 0, stdout: "one\ntwo\nthree\n" });
+ await writeFile(join(dir, "pr-raw"), Uint8Array.of(0xff, 0x0a, 0x61, 0x20, 0x62, 0x0a));
+ const prRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "pr", "-t", "pr-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "pr-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await prRaw.exited).toBe(0);
+ expect(await new Response(prRaw.stderr).text()).toBe("");
+ expect([...await readFile(join(dir, "pr-raw-out"))]).toEqual([0xff, 0x0a, 0x61, 0x20, 0x62, 0x0a]);
+ expect(await run(["pr", "-t", "pr-missing-a", "alpha", "pr-missing-b"])).toMatchObject({ code: 1, stdout: "one\ntwo\nthree\n", stderr: "pr: pr-missing-a: No such file or directory\npr: pr-missing-b: No such file or directory\n" });
+ expect(await run(["pr", "-t", "missing'pr", "alpha", "missing\npr"])).toMatchObject({ code: 1, stdout: "one\ntwo\nthree\n", stderr: "pr: \"missing'pr\": No such file or directory\npr: 'missing'$'\\n''pr': No such file or directory\n" });
+ await mkdir(join(dir, "pr-dir"));
+ expect(await run(["pr", "-t", "pr-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "pr: pr-dir: Is a directory\n" });
+ await mkdir(join(dir, "dir'pr"));
+ expect(await run(["pr", "-t", "dir'pr"])).toMatchObject({ code: 1, stdout: "", stderr: "pr: \"dir'pr\": Is a directory\n" });
+ await symlink("loop'pr", join(dir, "loop'pr"));
+ expect(await run(["pr", "-t", "loop'pr"])).toMatchObject({ code: 1, stdout: "", stderr: "pr: \"loop'pr\": Too many levels of symbolic links\n" });
+ expect(await run(["pr", "-t", "-r", "pr-missing-a", "alpha", "pr-missing-b"])).toMatchObject({ code: 1, stdout: "one\ntwo\nthree\n", stderr: "" });
+ await writeFile(join(dir, "pr-default"), "one\ntwo\nthree\n");
+ await lutimes(join(dir, "pr-default"), new Date(2001, 1, 3, 4, 5, 6), new Date(2001, 1, 3, 4, 5, 6));
+ const prDefault = await run(["pr", "pr-default"]);
+ expect(prDefault).toMatchObject({ code: 0, stderr: "" });
+ expect(prDefault.stdout).toMatch(/^(\n\n\d{4}-\d{2}-\d{2} \d{2}:\d{2}\s+pr-default\s+Page 1\n\n\none\ntwo\nthree\n)\n{58}$/);
+ const prStdin = await run(["pr"], "one\n");
+ expect(prStdin).toMatchObject({ code: 0, stderr: "" });
+ expect(prStdin.stdout).toMatch(/^\n\n\d{4}-\d{2}-\d{2} \d{2}:\d{2}\s+Page 1\n\n\none\n/);
+ expect(prStdin.stdout).not.toContain("Sun ");
+ const prLongLine = "x".repeat(65537);
+ const prLongStdin = await run(["pr"], prLongLine);
+ expect(prLongStdin).toMatchObject({ code: 0, stderr: "", stdout: expect.stringContaining(`${prLongLine}\n`) });
+ const prResponsive = await shell(`
+ rm -f pr-in pr-hold pr-out
+ mkfifo pr-in pr-hold
+ cleanup() {
+ kill "$reader" "$writer" 2>/dev/null || :
+ wait "$reader" "$writer" 2>/dev/null || :
+ }
+ trap cleanup EXIT
+ "$BUN" "$BNU" pr <pr-in >pr-out &
+ reader=$!
+ { printf '1\\n'; read x <pr-hold || :; } >pr-in &
+ writer=$!
+ seen=1
+ for i in 1 2 3 4 5 6; do
+ test -s pr-out && { seen=0; break; }
+ sleep .1
+ done
+ printf release >pr-hold
+ wait "$writer"
+ wait "$reader"
+ exit "$seen"
+ `);
+ expect(prResponsive).toMatchObject({ code: 0, stderr: "" });
+ expect((await run(["pr", "-h", "Custom", "alpha"])).stdout).toContain("Custom");
+ expect((await run(["pr", "--header=Long", "alpha"])).stdout).toContain("Long");
+ const prHelp = await run(["pr", "--help"]);
+ expect(prHelp.code).toBe(0);
+ expect(prHelp.stdout).toContain("Paginate or columnate FILE(s) for printing.\n");
+ expect(prHelp.stdout).toContain(" -F\n");
+ expect(await run(["pr", "-b", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: pr [OPTION]... [FILE]...\n"), stderr: "" });
+ expect(await run(["pr", "-b", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["pr", "--columns=bad", "--help"])).toMatchObject(await systemRun(["pr", "--columns=bad", "--help"]));
+ expect(await run(["pr", "--columns", "--help"])).toMatchObject(await systemRun(["pr", "--columns", "--help"]));
+ expect(await run(["pr", "--indent=bad", "--help"])).toMatchObject(await systemRun(["pr", "--indent=bad", "--help"]));
+ expect(await run(["pr", "--page-width=bad", "--help"])).toMatchObject(await systemRun(["pr", "--page-width=bad", "--help"]));
+ expect(await run(["pr", "--length=bad", "--help"])).toMatchObject(await systemRun(["pr", "--length=bad", "--help"]));
+ expect(await run(["pr", "--omit-header", "alpha"])).toMatchObject({ code: 0, stdout: "one\ntwo\nthree\n" });
+ expect(await run(["pr", "--pages=2", "alpha"])).toMatchObject({ code: 0, stdout: "", stderr: "pr: starting page number 2 exceeds page count 1\n" });
+ expect(await run(["pr", "-t", "-n", "alpha"])).toMatchObject({ code: 0, stdout: " 1\tone\n 2\ttwo\n 3\tthree\n" });
+ expect(await run(["pr", "-t", "-n:3", "-N", "7", "alpha"])).toMatchObject({ code: 0, stdout: " 7:one\n 8:two\n 9:three\n" });
+ expect(await run(["pr", "-t", "-n:2", "-N", "98"], "y\ny\ny\ny\ny\n")).toMatchObject({ code: 0, stdout: "98:y\n99:y\n00:y\n01:y\n02:y\n" });
+ expect(await run(["pr", "-t", "-n,1", "-N", "1000000"], "1\n")).toMatchObject({ code: 0, stdout: "0,1\n" });
+ expect(await run(["pr", "-t", "--indent=3", "alpha"])).toMatchObject({ code: 0, stdout: " one\n two\n three\n" });
+ expect(await run(["pr", "-t", "-02"], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: `a${"\t".repeat(4)}${" ".repeat(4)}c\nb\n` });
+ expect(await run(["pr", "-t", "-a", "-2"], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: `a${"\t".repeat(4)}${" ".repeat(4)}b\nc\n` });
+ expect(await run(["pr", "-t", "-a", "-3"], "1\n2\n3\n4\n5\n6\n")).toMatchObject({ code: 0, stdout: `1${"\t".repeat(3)}2${"\t".repeat(3)}3\n4${"\t".repeat(3)}5${"\t".repeat(3)}6\n` });
+ expect(await run(["pr", "-t", "-a", "-3"], "1\f\n2\n3\n4\n")).toMatchObject({ code: 0, stdout: `1\n\f2${"\t".repeat(3)}3${"\t".repeat(3)}4\n` });
+ expect(await run(["pr", "-T", "-a", "-3"], "1\f\n2\n3\n4\n")).toMatchObject({ code: 0, stdout: `1\n2${"\t".repeat(3)}3${"\t".repeat(3)}4\n` });
+ expect(await run(["pr", "-W3", "-t", "-02"], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: "a c\nb\n" });
+ expect(await run(["pr", "-W3", "-t2"], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: "a c\nb\n" });
+ expect(await run(["pr", "-W3", "-t", "-4", "--columns=1", "-2"], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: "a c\nb\n" });
+ expect(await run(["pr", "-W1", "-t"], "12345\n")).toMatchObject({ code: 0, stdout: "1\n" });
+ expect(await run(["pr", "-d", "-t"], "1\n2\n")).toMatchObject({ code: 0, stdout: "1\n\n2\n\n" });
+ expect(await run(["pr", "-T"], "a\fb\n")).toMatchObject({ code: 0, stdout: "a\nb\n" });
+ expect(await run(["pr", "-o", "0"], "")).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["pr", "-t", "-e"], "\b\b\b\b\b\b\tx\n")).toMatchObject({ code: 0, stdout: " x\n" });
+ expect(await run(["pr", "-t", "-e"], "abc\b\b\b\b\tx")).toMatchObject({ code: 0, stdout: "abc\b\b\b x\n" });
+ expect(await run(["pr", "-t", "-e300"], `a${"\b".repeat(50)}\t`)).toMatchObject({ code: 0, stdout: `a\b${" ".repeat(300)}\n` });
+ expect(await run(["pr", "-t", "-n", "-i5", "-h", ""], "a b\n")).toMatchObject({ code: 0, stdout: " 1\ta\t b\n" });
+ expect(await run(["pr", "-t", "-n", "-i5", "-o9", "-h", ""], "a b\n")).toMatchObject({ code: 0, stdout: "\t\t 1\ta\t b\n" });
+ expect(await run(["pr", "-t", "-n", "-2"], "a\tb\ncccc\n")).toMatchObject({ code: 0, stdout: " 1\ta\tb\t\t \t2 cccc\n" });
+ expect(await run(["pr", "+1:1", "-2", "-l1", "-s "], "a\nb\nc\n")).toMatchObject({ code: 0, stdout: "a b\n" });
+ await writeFile(join(dir, "pr-merge-a"), "a\tb\tc\n");
+ await writeFile(join(dir, "pr-merge-b"), "m\tn\to\n");
+ await writeFile(join(dir, "pr-merge-c"), "x\ty\tz\n");
+ expect(await run(["pr", "-m", "-s", "-t", "pr-merge-a", "pr-merge-b", "pr-merge-c"])).toMatchObject(await systemRun(["/usr/bin/pr", "-m", "-s", "-t", "pr-merge-a", "pr-merge-b", "pr-merge-c"]));
+ expect(await run(["pr", "-m", "-t", "pr-merge-a", "pr-merge-b", "pr-merge-c"])).toMatchObject(await systemRun(["/usr/bin/pr", "-m", "-t", "pr-merge-a", "pr-merge-b", "pr-merge-c"]));
+ expect(await run(["pr", "-m", "-t", "-s,", "pr-merge-a", "pr-merge-b"])).toMatchObject(await systemRun(["/usr/bin/pr", "-m", "-t", "-s,", "pr-merge-a", "pr-merge-b"]));
+ expect(await run(["pr", "-m", "-t", "-S,", "pr-merge-a", "pr-merge-b"])).toMatchObject(await systemRun(["/usr/bin/pr", "-m", "-t", "-S,", "pr-merge-a", "pr-merge-b"]));
+ expect(await run(["pr", "-m", "-J", "-t", "pr-merge-a", "pr-merge-b"])).toMatchObject(await systemRun(["/usr/bin/pr", "-m", "-J", "-t", "pr-merge-a", "pr-merge-b"]));
+ await writeFile(join(dir, "pr-merge-plain-a"), "abc\n");
+ await writeFile(join(dir, "pr-merge-plain-b"), "def\n");
+ expect(await run(["pr", "-m", "-t", "pr-missing-a", "pr-merge-plain-a", "pr-missing-b", "pr-merge-plain-b"])).toMatchObject({ code: 1, stdout: "abc\t\t def\n", stderr: "pr: pr-missing-a: No such file or directory\npr: pr-missing-b: No such file or directory\n" });
+ expect(await run(["pr", "-m", "-s\t", "-t", "pr-merge-a", "pr-merge-b"])).toMatchObject({ code: 0, stdout: "a\tb\tc\tm\tn\to\n" });
+ await writeFile(join(dir, "pr-asan-a"), "a\n");
+ await writeFile(join(dir, "pr-asan-b"), "a\n");
+ expect(await run(["pr", "-m", "-S\t\t\t", "-t", "pr-asan-a", "pr-asan-b"])).toMatchObject({ code: 0, stdout: "a\t\t\t\t \t\t\ta\n" });
+ expect(await run(["pr", "-t", "-2"], "x\tx\tx\tx\tx\nx\tx\tx\tx\tx\n")).toMatchObject({ code: 0, stdout: "x\tx\tx\tx\tx x\t x\t x\t x\t x\n" });
+ const prTabInput = "aaa\tabcde\t\tfghijklmnopqrstuvw\nbbb\tabcde\t\tfghijklmnopqrstuvw\nccc\tabcde\t\tfghijklmnopqrstuvw\nddd\tabcde\t\tfghijklmnopqrstuvw\n";
+ expect(await run(["pr", "-t", "-n", "-2", "-e8"], prTabInput)).toMatchObject({ code: 0, stdout: " 1\taaa\tabcde\t\tfgh \t3 ccc\t abcde\t fgh\n 2\tbbb\tabcde\t\tfgh \t4 ddd\t abcde\t fgh\n" });
+ expect(await run(["pr", "-t", "-n:", "-2", "-e8"], prTabInput)).toMatchObject({ code: 0, stdout: " 1:aaa\tabcde\t\tfgh \t3:ccc\t abcde\t fgh\n 2:bbb\tabcde\t\tfgh \t4:ddd\t abcde\t fgh\n" });
+ expect(await run(["pr", "-t", "-n:", "-2", "-e8", "-S----"], prTabInput)).toMatchObject({ code: 0, stdout: " 1:aaa\tabcde\t\tfg----\t 3:ccc\t abcde\t fg\n 2:bbb\tabcde\t\tfg----\t 4:ddd\t abcde\t fg\n" });
+ expect(await run(["pr", "-t", "-S::", "-2"], "1\n2\n3\n4\n5\n6\n7\n8\n")).toMatchObject(await systemRun(["/usr/bin/pr", "-t", "-S::", "-2"], "1\n2\n3\n4\n5\n6\n7\n8\n"));
+ expect(await run(["pr", "-t", "-s,", "-2"], "1\n2\n3\n4\n5\n6\n7\n8\n")).toMatchObject(await systemRun(["/usr/bin/pr", "-t", "-s,", "-2"], "1\n2\n3\n4\n5\n6\n7\n8\n"));
+ const prColonTabInput = prTabInput.replace("aaa\t", "aaa:").replace("bbb\t", "bbb:");
+ expect(await run(["pr", "-t", "-n", "-2", "-e:8"], prColonTabInput)).toMatchObject({ code: 0, stdout: " 1\taaa\tabcde\t\tfgh \t3 ccc\t abcde\t fgh\n 2\tbbb\tabcde\t\tfgh \t4 ddd\t abcde\t fgh\n" });
+ expect(await run(["pr", "-t", "-e:4"], "a:b\na\tb\n")).toMatchObject(await systemRun(["/usr/bin/pr", "-t", "-e:4"], "a:b\na\tb\n"));
+ expect(await run(["pr", "-t", "-e:"], "a:b\na\tb\n")).toMatchObject(await systemRun(["/usr/bin/pr", "-t", "-e:"], "a:b\na\tb\n"));
+ expect(await run(["pr", "-t", "-n", "-2", "-e8", "-o3"], prTabInput)).toMatchObject({ code: 0, stdout: " 1 aaa\t abcde\t fgh \t 3 ccc abcde\t fgh\n 2 bbb\t abcde\t fgh \t 4 ddd abcde\t fgh\n" });
+ expect(await run(["pr", "-t", "-n", "-2", "-e5", "-o3"], prTabInput)).toMatchObject({ code: 0, stdout: " 1 aaa\t abcde\t\t fghij \t 3 ccc abcde\t fghij\n 2 bbb\t abcde\t\t fghij \t 4 ddd abcde\t fghij\n" });
+ expect(await run(["pr", "--date-format=-- Date/Time --", "-h", "x", "-f"], "a\n")).toMatchObject({ code: 0, stdout: "\n\n-- Date/Time -- x Page 1\n\n\na\n\f" });
+ expect(await run(["pr", "--date-format=-- Date/Time --", "-h", "x", "-n.3", "-l", "11", "-f"], "a\f\nb\n")).toMatchObject({ code: 0, stdout: "\n\n-- Date/Time -- x Page 1\n\n\n 1.a\n\f\n\n-- Date/Time -- x Page 2\n\n\n 2.b\n\f" });
+ expect(await run(["pr", "--date-format=-- Date/Time --", "-h", "x", "-a", "-3", "-l", "12", "-f"], "1\n2\n3\n4\n5\n6\n")).toMatchObject({ code: 0, stdout: `\n\n-- Date/Time -- x Page 1\n\n\n1${"\t".repeat(3)}2${"\t".repeat(3)}3\n4${"\t".repeat(3)}5${"\t".repeat(3)}6\n\f` });
+ expect(await run(["pr", "--date-format=-- Date/Time --", "-h", "x", "-b", "-3", "-l", "12", "-f"], "1\n2\n3\n4\n5\n6\n")).toMatchObject({ code: 0, stdout: `\n\n-- Date/Time -- x Page 1\n\n\n1${"\t".repeat(3)}3${"\t".repeat(3)}5\n2${"\t".repeat(3)}4${"\t".repeat(3)}6\n\f` });
+ expect(await run(["pr", "--date-format=-- Date/Time --", "-h", "x", "-a", "-3", "-l", "12", "-f"], "abcdefghijklmnopqrstuvw\n12345678901234567890123\nXYZXYZXYZXYZXYZXYZXYZ\n")).toMatchObject({ code: 0, stdout: "\n\n-- Date/Time -- x Page 1\n\n\nabcdefghijklmnopqrstuvw 12345678901234567890123 XYZXYZXYZXYZXYZXYZXYZ\n\f" });
+ const prPagedTabInput = "1 FF-Test: FFs in Text\n2\tOptions -b -3 / -a -3 / ...\n3 -------------------------------\n4 3456789 123456789 123456789 12345\n5 3 Columns downwards ..., <= 5 l\n6\tFF-Arangements: One Empty Page\n";
+ expect(await run(["pr", "--date-format=-- Date/Time --", "-h", "x", "-a", "-2", "-l", "17"], prPagedTabInput)).toMatchObject({ code: 0, stdout: "\n\n-- Date/Time -- x Page 1\n\n\n1 FF-Test: FFs in Text\t 2\t Options -b -3 / -a -3 / ...\n3 ------------------------------- 4 3456789 123456789 123456789 12345\n5 3 Columns downwards ..., <= 5 l 6\t FF-Arangements: One Empty P\n\n\n\n\n\n\n\n\n\n" });
+ expect(await run(["pr", "-0"])).toMatchObject(await systemRun(["pr", "-0"]));
+ expect(await run(["pr", `-${"9".repeat(100)}`])).toMatchObject(await systemRun(["pr", `-${"9".repeat(100)}`]));
+ expect(await run(["pr", "-3x"])).toMatchObject(await systemRun(["pr", "-3x"]));
+ expect(await run(["pr", "-x", "--help"])).toMatchObject(await systemRun(["pr", "-x", "--help"]));
+ expect(await run(["pr", "-w", "0"])).toMatchObject(await systemRun(["pr", "-w", "0"]));
+ expect(await run(["pr", "-w", "-1"])).toMatchObject(await systemRun(["pr", "-w", "-1"]));
+ expect(await run(["pr", "-w", "x"])).toMatchObject(await systemRun(["pr", "-w", "x"]));
+ expect(await run(["pr", "-w", "x", "--help"])).toMatchObject(await systemRun(["pr", "-w", "x", "--help"]));
+ expect(await run(["pr", "-wx", "--help"])).toMatchObject(await systemRun(["pr", "-wx", "--help"]));
+ expect(await run(["pr", "-w", "10", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: pr [OPTION]... [FILE]...\n") });
+ expect(await run(["pr", "-w", "1\n2"])).toMatchObject({ code: 1, stdout: "", stderr: `pr: '-w PAGE_WIDTH' invalid number of characters: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["pr", "-W", "0"])).toMatchObject(await systemRun(["pr", "-W", "0"]));
+ expect(await run(["pr", "-W", "x", "--help"])).toMatchObject(await systemRun(["pr", "-W", "x", "--help"]));
+ expect(await run(["pr", "--page-width=0"])).toMatchObject(await systemRun(["pr", "--page-width=0"]));
+ expect(await run(["pr", "-l", "0"])).toMatchObject(await systemRun(["pr", "-l", "0"]));
+ expect(await run(["pr", "-l", "-1"])).toMatchObject(await systemRun(["pr", "-l", "-1"]));
+ expect(await run(["pr", "-l", "x"])).toMatchObject(await systemRun(["pr", "-l", "x"]));
+ expect(await run(["pr", "-l", "x", "--help"])).toMatchObject(await systemRun(["pr", "-l", "x", "--help"]));
+ expect(await run(["pr", "-N", "x"])).toMatchObject(await systemRun(["pr", "-N", "x"]));
+ expect(await run(["pr", "-N", "2147483648"])).toMatchObject(await systemRun(["pr", "-N", "2147483648"]));
+ expect(await run(["pr", "--first-line-number=x"])).toMatchObject(await systemRun(["pr", "--first-line-number=x"]));
+ expect(await run(["pr", "-o", "-1"])).toMatchObject(await systemRun(["pr", "-o", "-1"]));
+ expect(await run(["pr", "-o", "+1"], "x\n")).toMatchObject(await systemRun(["pr", "-o", "+1"], "x\n"));
+ expect(await run(["pr", "-o", "x", "--help"])).toMatchObject(await systemRun(["pr", "-o", "x", "--help"]));
+ expect(await run(["pr", "-n", "bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: pr [OPTION]... [FILE]...\n") });
+ expect(await run(["pr", "-nbad", "--help"])).toMatchObject(await systemRun(["pr", "-nbad", "--help"]));
+ expect(await run(["pr", "-e", "bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: pr [OPTION]... [FILE]...\n") });
+ expect(await run(["pr", "-ebad", "--help"])).toMatchObject(await systemRun(["pr", "-ebad", "--help"]));
+ expect(await run(["pr", "--columns=x"])).toMatchObject({ code: 1, stdout: "", stderr: `pr: invalid number of columns: ${diagnosticQuote("x")}\n` });
+ expect(await run(["pr", "--columns=1\n2"])).toMatchObject({ code: 1, stdout: "", stderr: `pr: invalid number of columns: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["pr", "--columns=0"])).toMatchObject({ code: 1, stdout: "", stderr: `pr: invalid number of columns: ${diagnosticQuote("0")}: Numerical result out of range\n` });
+ expect(await run(["pr", "--columns=999999999999999999999999999999"])).toMatchObject({ code: 1, stdout: "", stderr: `pr: invalid number of columns: ${diagnosticQuote("999999999999999999999999999999")}: Value too large for defined data type\n` });
+ expect(await run(["pr", "--pages=x"])).toMatchObject({ code: 1, stderr: "pr: invalid --pages argument 'x'\n" });
+ expect(await run(["pr", "--pages=bad", "--help"])).toMatchObject(await systemRun(["pr", "--pages=bad", "--help"]));
+ expect(await run(["pr", "--pages=9x", "--help"])).toMatchObject(await systemRun(["pr", "--pages=9x", "--help"]));
+ expect(await run(["pr", "--pages=9x"])).toMatchObject({ code: 1, stderr: `pr: invalid page range ${diagnosticQuote("9x")}\n` });
+ expect(await run(["pr", "--pages=9x\ny"])).toMatchObject({ code: 1, stderr: `pr: invalid page range ${diagnosticQuote("9x\\ny")}\n` });
+ expect(await run(["pr", "--pages=9\nx"])).toMatchObject({ code: 1, stderr: `pr: invalid page range ${diagnosticQuote("9\\nx")}\n` });
+ expect(await run(["pr", "--pages=1:-1"])).toMatchObject({ code: 1, stderr: "pr: invalid --pages argument '1:-1'\n" });
+ expect(await run(["pr", "--expand-tabs=bad", "--help"])).toMatchObject(await systemRun(["pr", "--expand-tabs=bad", "--help"]));
+ expect(await run(["pr", "--number-lines=bad", "--help"])).toMatchObject(await systemRun(["pr", "--number-lines=bad", "--help"]));
+ expect(await run(["pr", "--output-tabs=bad", "--help"])).toMatchObject(await systemRun(["pr", "--output-tabs=bad", "--help"]));
+ expect(await run(["pr", "--expand-tabs=", "--help"])).toMatchObject(await systemRun(["pr", "--expand-tabs=", "--help"]));
+ await writeFile(join(dir, "pr-control"), Uint8Array.of(0x61, 0x01, 0x62, 0x7f, 0x09, 0x63, 0x0a, 0x80, 0xff, 0x0a));
+ expect(await run(["pr", "-t", "-c", "pr-control"], "", { env: { LC_ALL: "C" } })).toMatchObject({ code: 0, stdout: "a^Ab^?\tc\n\\200\\377\n" });
+ expect(await run(["pr", "-t", "--show-nonprinting", "pr-control"], "", { env: { LC_ALL: "C" } })).toMatchObject({ code: 0, stdout: "a\\001b\\177\tc\n\\200\\377\n" });
+ expect((await run(["pinky"])).stdout).toStartWith("Login Name");
+ const pinkyShort = (await run(["pinky", "-s"])).stdout;
+ expect(pinkyShort).toStartWith("Login Name");
+ expect(pinkyShort).toMatch(/ \?tty\d* +\?{5} /);
+ expect(await run(["pinky", "--lookup"])).toMatchObject({ code: 0 });
+ expect(await run(["pinky", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: pinky [OPTION]... [USER]...\n") });
+ expect(await run(["pinky", "--l"])).toMatchObject({ code: 0 });
+ expect(await run(["pinky", "--lo"])).toMatchObject({ code: 0 });
+ expect((await run(["pinky", "--short"])).stderr).toContain("unrecognized option '--short'");
+ expect((await run(["pinky", "--long", "root"])).stderr).toContain("unrecognized option '--long'");
+ expect((await run(["pinky", "--look=bad", "--help"])).stderr).toContain("option '--lookup' doesn't allow an argument");
+ expect((await run(["pinky", "--bad", "--help"])).stderr).toContain("unrecognized option '--bad'");
+ expect((await run(["pinky", "-x", "--help"])).stderr).toContain("invalid option -- 'x'");
+ const pinkyLiteralHelp = await run(["pinky", "--", "--help"]);
+ expect(pinkyLiteralHelp).toMatchObject({ code: 0 });
+ expect(pinkyLiteralHelp.stdout).toStartWith("Login Name");
+ expect(await run(["pinky", "-l"])).toMatchObject({ code: 1, stderr: "pinky: no username specified; at least one must be specified when using -l\nTry 'pinky --help' for more information.\n" });
+ expect((await run(["pinky", "-l", "root"])).stdout).toContain("Directory: /root");
+ expect(await run(["pinky", "-l", "-h", "-p", "root"], "", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/pinky", "-l", "-h", "-p", "root"], "", { env: { LC_ALL: "C" } }));
+ expect(await run(["pinky", "-ls", "root"], "", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/pinky", "-ls", "root"], "", { env: { LC_ALL: "C" } }));
+ expect(await run(["pinky", "-sl", "root"], "", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/pinky", "-sl", "root"], "", { env: { LC_ALL: "C" } }));
+ expect(await run(["pinky", "definitely-missing-user"])).toMatchObject({ code: 0, stdout: "Login Name TTY Idle When Where\n" });
+ expect(await run(["pinky", "definitely-missing-user"], "", { env: { LC_ALL: "C" } })).toMatchObject({ code: 0, stdout: "Login Name TTY Idle When Where\n" });
+ expect((await run(["pinky", "-l", "definitely-missing-user"])).stdout).toContain("In real life: ???");
+ expect(await run(["pinky", "-l", "definitely-missing-user", "root"], "", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/pinky", "-l", "definitely-missing-user", "root"], "", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx"], "Beta alpha beta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx"], "Beta alpha beta\n", { env: { LC_ALL: "C" } }));
+ const ptxWrapInput = "the quick brown fox\nthe quick blue hare\n";
+ expect(await run(["ptx"], ptxWrapInput, { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx"], ptxWrapInput, { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "-g", "1"], ptxWrapInput, { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-g", "1"], ptxWrapInput, { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--format=tex"], ptxWrapInput, { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--format=tex"], ptxWrapInput, { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--format=roff"], ptxWrapInput, { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--format=roff"], ptxWrapInput, { env: { LC_ALL: "C" } }));
+ await writeFile(join(dir, "ptx-raw"), Uint8Array.of(0x61, 0xff, 0x20, 0x62, 0x0a));
+ const ptxRaw = Bun.spawn([process.execPath, join(import.meta.dir, "../bin/bnu.js"), "ptx", "ptx-raw"], {
+ cwd: dir,
+ env: { ...process.env, LC_ALL: "C" },
+ stdin: "ignore",
+ stdout: Bun.file(join(dir, "ptx-raw-out")),
+ stderr: "pipe",
+ });
+ expect(await ptxRaw.exited).toBe(0);
+ expect(await new Response(ptxRaw.stderr).text()).toBe("");
+ expect(Buffer.from(await readFile(join(dir, "ptx-raw-out")))).toEqual(Buffer.concat([
+ Buffer.from(" a"),
+ Buffer.from([0xff, 0x20, 0x62, 0x0a]),
+ Buffer.from(" a"),
+ Buffer.from([0xff, 0x20, 0x20, 0x20, 0x62, 0x0a]),
+ ]));
+ expect((await run(["ptx", "--ign", "--help"])).stderr).toContain("option '--ign' is ambiguous; possibilities: '--ignore-case' '--ignore-file'");
+ expect((await run(["ptx", "--r", "--help"])).stderr).toContain("option '--r' is ambiguous; possibilities: '--references' '--right-side-refs'");
+ expect((await run(["ptx", "--f", "--help"])).stderr).toContain("option '--f' is ambiguous; possibilities: '--flag-truncation' '--format'");
+ expect((await run(["ptx", "--right=bad", "--help"])).stderr).toContain("option '--right-side-refs' doesn't allow an argument");
+ expect((await run(["ptx", "--auto=bad", "--help"])).stderr).toContain("option '--auto-reference' doesn't allow an argument");
+ expect(await run(["ptx", "--format", "--help"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ptx: invalid argument ${diagnosticQuote("--help")} for ${diagnosticQuote("--format")}\nValid arguments are:\n - ${diagnosticQuote("roff")}\n - ${diagnosticQuote("tex")}\nTry 'ptx --help' for more information.\n`,
+ });
+ expect(await run(["ptx", "--format="])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ptx: ambiguous argument ${diagnosticQuote("")} for ${diagnosticQuote("--format")}\nValid arguments are:\n - ${diagnosticQuote("roff")}\n - ${diagnosticQuote("tex")}\nTry 'ptx --help' for more information.\n`,
+ });
+ expect(await run(["ptx", "--format=bad"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ptx: invalid argument ${diagnosticQuote("bad")} for ${diagnosticQuote("--format")}\nValid arguments are:\n - ${diagnosticQuote("roff")}\n - ${diagnosticQuote("tex")}\nTry 'ptx --help' for more information.\n`,
+ });
+ expect(await run(["ptx", "--format=bad\nmode"])).toMatchObject({
+ code: 1,
+ stdout: "",
+ stderr: `ptx: invalid argument ${diagnosticQuote("bad\\nmode")} for ${diagnosticQuote("--format")}\nValid arguments are:\n - ${diagnosticQuote("roff")}\n - ${diagnosticQuote("tex")}\nTry 'ptx --help' for more information.\n`,
+ });
+ expect(await run(["ptx", "--format=bad", "--help"])).toMatchObject(await systemRun(["ptx", "--format=bad", "--help"]));
+ expect(await run(["ptx", "--format=", "--help"])).toMatchObject(await systemRun(["ptx", "--format=", "--help"]));
+ expect(await run(["ptx", "--format=r"], "alpha beta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--format=r"], "alpha beta\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--format=t"], "alpha beta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--format=t"], "alpha beta\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--format=te", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: ptx [OPTION]... [INPUT]... (without -G)\n") });
+ expect(await run(["ptx", "--ignore-f", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["ptx", "--gap=3", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: ptx [OPTION]... [INPUT]... (without -G)\n or: ptx -G [OPTION]... [INPUT [OUTPUT]]\n") });
+ expect(await run(["ptx", "ptx-raw", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: ptx [OPTION]... [INPUT]... (without -G)\n"), stderr: "" });
+ expect(await run(["ptx", "--", "--help"])).toMatchObject({ code: 1, stderr: "ptx: --help: No such file or directory\n" });
+ expect(await run(["ptx", "ptx-missing"])).toMatchObject({ code: 1, stdout: "", stderr: "ptx: ptx-missing: No such file or directory\n" });
+ expect(await run(["ptx", "missing'ptx"])).toMatchObject({ code: 1, stdout: "", stderr: "ptx: \"missing'ptx\": No such file or directory\n" });
+ expect(await run(["ptx", "missing\nptx"])).toMatchObject({ code: 1, stdout: "", stderr: "ptx: 'missing'$'\\n''ptx': No such file or directory\n" });
+ await mkdir(join(dir, "ptx-dir"));
+ expect(await run(["ptx", "ptx-dir"])).toMatchObject({ code: 1, stdout: "", stderr: "ptx: ptx-dir: Is a directory\n" });
+ await mkdir(join(dir, "dir'ptx"));
+ expect(await run(["ptx", "dir'ptx"])).toMatchObject({ code: 1, stdout: "", stderr: "ptx: \"dir'ptx\": Is a directory\n" });
+ expect(await run(["ptx", "-f"], "Beta alpha beta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-f"], "Beta alpha beta\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--ignore-case"], "Beta alpha beta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--ignore-case"], "Beta alpha beta\n", { env: { LC_ALL: "C" } }));
+ await writeFile(join(dir, "ignore-words"), "beta\n");
+ await writeFile(join(dir, "only-words"), "alpha\n");
+ expect(await run(["ptx", "-i", "ptx-ignore-missing"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: "ptx: ptx-ignore-missing: No such file or directory\n" });
+ expect(await run(["ptx", "-i", "missing'ptx-list"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: "ptx: \"missing'ptx-list\": No such file or directory\n" });
+ expect(await run(["ptx", "-i", "missing\nptx-list"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: "ptx: 'missing'$'\\n''ptx-list': No such file or directory\n" });
+ expect(await run(["ptx", "--only-file=ptx-only-missing"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: "ptx: ptx-only-missing: No such file or directory\n" });
+ expect(await run(["ptx", "-i", "ptx-dir"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: "ptx: ptx-dir: Is a directory\n" });
+ await mkdir(join(dir, "dir'ptx-list"));
+ expect(await run(["ptx", "-i", "dir'ptx-list"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: "ptx: \"dir'ptx-list\": Is a directory\n" });
+ await symlink("ptx-loop", join(dir, "ptx-loop"));
+ expect(await run(["ptx", "--only-file=ptx-loop"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: "ptx: ptx-loop: Too many levels of symbolic links\n" });
+ await symlink("loop'ptx", join(dir, "loop'ptx"));
+ expect(await run(["ptx", "loop'ptx"])).toMatchObject({ code: 1, stdout: "", stderr: "ptx: \"loop'ptx\": Too many levels of symbolic links\n" });
+ await symlink("loop'ptx-list", join(dir, "loop'ptx-list"));
+ expect(await run(["ptx", "--only-file=loop'ptx-list"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: "ptx: \"loop'ptx-list\": Too many levels of symbolic links\n" });
+ expect(await run(["ptx", "-i", "ignore-words"], "alpha beta gamma\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-i", "ignore-words"], "alpha beta gamma\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--only-file=only-words"], "alpha beta gamma\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--only-file=only-words"], "alpha beta gamma\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "-W", "[0-9]+"], "abc 123 def 45\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-W", "[0-9]+"], "abc 123 def 45\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "-w", "10"], "foo bar\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-w", "10"], "foo bar\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "-w", "20"], "alpha beta gamma delta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-w", "20"], "alpha beta gamma delta\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--auto-reference"], "alpha beta\n")).toMatchObject({ code: 0 });
+ expect(await run(["ptx", "--break-file=/dev/null"], "alpha beta\n")).toMatchObject({ code: 0 });
+ expect(await run(["ptx", "--flag-truncation=X"], "alpha beta\n")).toMatchObject({ code: 0 });
+ expect(await run(["ptx", "--gap-size=3"], "alpha beta\n")).toMatchObject({ code: 0 });
+ expect(await run(["ptx", "--width=0"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: `ptx: invalid line width: ${diagnosticQuote("0")}\n` });
+ expect(await run(["ptx", "-w", "bad"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: `ptx: invalid line width: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["ptx", "-w", "1\n2"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: `ptx: invalid line width: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["ptx", "--gap-size=0"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: `ptx: invalid gap width: ${diagnosticQuote("0")}\n` });
+ expect(await run(["ptx", "-g", "bad"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: `ptx: invalid gap width: ${diagnosticQuote("bad")}\n` });
+ expect(await run(["ptx", "-g", "1\n2"], "alpha beta\n")).toMatchObject({ code: 1, stdout: "", stderr: `ptx: invalid gap width: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["ptx", "--width=bad", "--help"])).toMatchObject(await systemRun(["ptx", "--width=bad", "--help"]));
+ expect(await run(["ptx", "--width", "bad", "--help"])).toMatchObject(await systemRun(["ptx", "--width", "bad", "--help"]));
+ expect(await run(["ptx", "-w", "bad", "--help"])).toMatchObject(await systemRun(["ptx", "-w", "bad", "--help"]));
+ expect(await run(["ptx", "-wbad", "--help"])).toMatchObject(await systemRun(["ptx", "-wbad", "--help"]));
+ expect(await run(["ptx", "--width", "10", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: ptx [OPTION]... [INPUT]... (without -G)\n") });
+ expect(await run(["ptx", "--gap-size=bad", "--help"])).toMatchObject(await systemRun(["ptx", "--gap-size=bad", "--help"]));
+ expect(await run(["ptx", "--gap-size", "bad", "--help"])).toMatchObject(await systemRun(["ptx", "--gap-size", "bad", "--help"]));
+ expect(await run(["ptx", "-g", "bad", "--help"])).toMatchObject(await systemRun(["ptx", "-g", "bad", "--help"]));
+ expect(await run(["ptx", "-gbad", "--help"])).toMatchObject(await systemRun(["ptx", "-gbad", "--help"]));
+ expect(await run(["ptx", "-g", "3", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: ptx [OPTION]... [INPUT]... (without -G)\n") });
+ expect(await run(["ptx", "--right-side-refs"], "alpha beta\n")).toMatchObject({ code: 0 });
+ expect(await run(["ptx", "--typeset-mode"], "alpha beta\n")).toMatchObject({ code: 0 });
+ expect(await run(["ptx", "-T"], "Beta alpha beta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-T"], "Beta alpha beta\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--format=roff", "--macro-name=yy"], "Beta alpha beta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--format=roff", "--macro-name=yy"], "Beta alpha beta\n", { env: { LC_ALL: "C" } }));
+ await writeFile(join(dir, "ptx-traditional-in"), "alpha beta\n");
+ expect(await run(["ptx", "-G", "ptx-traditional-in", "ptx-traditional-out"], "", { env: { LC_ALL: "C" } })).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await readFile(join(dir, "ptx-traditional-out"), "utf8")).toBe((await systemRun(["/usr/bin/ptx", "-G", "ptx-traditional-in"], "", { env: { LC_ALL: "C" } })).stdout);
+ expect(await run(["ptx", "-G", "ptx-traditional-in", "ptx-traditional-out", "extra"])).toMatchObject({ code: 1, stdout: "", stderr: `ptx: extra operand ${diagnosticQuote("extra")}\nTry 'ptx --help' for more information.\n` });
+ expect(await run(["ptx", "-G", "ptx-traditional-in", "ptx-traditional-out", "extra\narg"])).toMatchObject({ code: 1, stdout: "", stderr: `ptx: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'ptx --help' for more information.\n` });
+ expect(await run(["stty", "-a"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "-g"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "--save"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "--sa"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("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]\n") });
+ expect(await run(["stty", "--a", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: stty") });
+ expect(await run(["stty", "-x", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: stty") });
+ expect(await run(["stty", "--bad", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: stty") });
+ expect(await run(["stty", "--all=bad"])).toMatchObject(await systemRun(["stty", "--all=bad"]));
+ expect(await run(["stty", "--file"])).toMatchObject(await systemRun(["stty", "--file"]));
+ expect(await run(["stty", "--file", "--help"])).toMatchObject({ code: 1, stderr: "stty: --help: No such file or directory\n" });
+ expect(await run(["stty", "--file", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect(await run(["stty", "--file=/dev/null", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: stty") });
+ expect(await run(["stty", "--file=", "--all"])).toMatchObject({ code: 1, stderr: "stty: '': No such file or directory\n" });
+ expect(await run(["stty", "--", "--help"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "--", "raw"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "-ag"])).toMatchObject({ code: 1, stderr: "stty: the options for verbose and stty-readable output styles are\nmutually exclusive\n" });
+ expect(await run(["stty", "-a", "-g"])).toMatchObject({ code: 1, stderr: "stty: the options for verbose and stty-readable output styles are\nmutually exclusive\n" });
+ expect(await run(["stty", "-a", "rows", "1"])).toMatchObject({ code: 1, stderr: "stty: when specifying an output style, modes may not be set\n" });
+ expect(await run(["stty", "-aF/dev/null"])).toMatchObject({ code: 1, stderr: "stty: /dev/null: Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "speed"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "size"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "rows"])).toMatchObject({ code: 1, stderr: "stty: missing argument to 'rows'\nTry 'stty --help' for more information.\n" });
+ expect(await run(["stty", "intr"])).toMatchObject({ code: 1, stderr: "stty: missing argument to 'intr'\nTry 'stty --help' for more information.\n" });
+ expect(await run(["stty", "rows", "x"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "min", "-1"])).toMatchObject({ code: 1, stderr: `stty: invalid integer argument: ${diagnosticQuote("-1")}\n` });
+ expect(await run(["stty", "min", "1\n2"])).toMatchObject({ code: 1, stderr: `stty: invalid integer argument: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["stty", "time", "1x"])).toMatchObject({ code: 1, stderr: `stty: invalid integer argument: ${diagnosticQuote("1x")}\n` });
+ expect(await run(["stty", "ispeed", "x"])).toMatchObject({ code: 1, stderr: `stty: invalid ispeed ${diagnosticQuote("x")}\nTry 'stty --help' for more information.\n` });
+ expect(await run(["stty", "ispeed", "1\n2"])).toMatchObject({ code: 1, stderr: `stty: invalid ispeed ${diagnosticQuote("1\\n2")}\nTry 'stty --help' for more information.\n` });
+ expect(await run(["stty", "ispeed", "9600.0 "])).toMatchObject({ code: 1, stderr: `stty: invalid ispeed ${diagnosticQuote("9600.0 ")}\nTry 'stty --help' for more information.\n` });
+ expect(await run(["stty", "intr", "M-^?"])).toMatchObject({ code: 1, stderr: `stty: invalid integer argument: ${diagnosticQuote("M-^?")}\n` });
+ expect(await run(["stty", "intr", "bad\nvalue"])).toMatchObject({ code: 1, stderr: `stty: invalid integer argument: ${diagnosticQuote("bad\\nvalue")}\n` });
+ expect(await run(["stty", "intr", ""])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "line", "1x"])).toMatchObject({ code: 1, stderr: `stty: invalid integer argument: ${diagnosticQuote("1x")}\n` });
+ expect(await run(["stty", "1:2"])).toMatchObject({ code: 1, stderr: `stty: invalid argument ${diagnosticQuote("1:2")}\nTry 'stty --help' for more information.\n` });
+ expect(await run(["stty", "status"])).toMatchObject({ code: 1, stderr: `stty: invalid argument ${diagnosticQuote("status")}\nTry 'stty --help' for more information.\n` });
+ expect(await run(["stty", "bad\nsetting"])).toMatchObject({ code: 1, stderr: `stty: invalid argument ${diagnosticQuote("bad\\nsetting")}\nTry 'stty --help' for more information.\n` });
+ expect(await run(["stty", "parenb"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "-parenb"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "intr", "^C"])).toMatchObject({ code: 1, stderr: "stty: 'standard input': Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "-F", "/dev/null", "rows", "24", "cols", "80", "sane"])).toMatchObject({ code: 1, stderr: "stty: /dev/null: Inappropriate ioctl for device\n" });
+ expect(await run(["stty", "definitely-not-a-setting"])).toMatchObject({ code: 1 });
+ if ((await shell("command -v script >/dev/null")).code === 0) {
+ const sttyPty = await shell(`script -qfec '"$BUN" "$BNU" stty; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty -a' /dev/null`);
+ expect(sttyPty).toMatchObject({ code: 0, stderr: "" });
+ const sttyStdout = sttyPty.stdout.replaceAll("\r\n", "\n");
+ expect(sttyStdout).toContain("speed 38400 baud; line = 0;\n-brkint -imaxbel\n");
+ expect(sttyStdout).toContain("500:5:f00bf:8a3b:");
+ expect(sttyStdout).toContain("intr = ^C; quit =");
+ expect(sttyStdout).toContain("erase = ^?; kill = ^U;");
+ expect(sttyStdout).toContain("opost -olcuc -ocrnl onlcr");
+ const sttyRaw = await shell(`script -qfec 'orig=$("$BUN" "$BNU" stty -g); "$BUN" "$BNU" stty raw -echo; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty "$orig"; "$BUN" "$BNU" stty -g' /dev/null`);
+ expect(sttyRaw).toMatchObject({ code: 0, stderr: "" });
+ const sttyRawLines = sttyRaw.stdout.replaceAll("\r\n", "\n").trim().split("\n");
+ expect(sttyRawLines).toEqual([
+ "0:4:f00bf:8a30:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "500:5:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ ]);
+ const sttyDrain = await shell(`script -qfec '"$BUN" "$BNU" stty drain; "$BUN" "$BNU" stty -drain echo; "$BUN" "$BNU" stty drain echo' /dev/null`);
+ expect(sttyDrain).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyDrain.stdout.replaceAll("\r\n", "\n")).toContain("speed 38400 baud; line = 0;\n");
+ const sttyWindow = await shell(`script -qfec '"$BUN" "$BNU" stty rows 24 cols 80; "$BUN" "$BNU" stty size; "$BUN" "$BNU" stty -a | sed -n "1p"; stty rows 0 cols 0' /dev/null`);
+ expect(sttyWindow).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyWindow.stdout.replaceAll("\r\n", "\n").trim().split("\n")).toEqual([
+ "24 80",
+ "speed 38400 baud; rows 24; columns 80; line = 0;",
+ ]);
+ const sttyOctalWindow = await shell(`script -qfec '"$BUN" "$BNU" stty rows 036 cols 0; "$BUN" "$BNU" stty size; stty rows 0 cols 0' /dev/null`);
+ expect(sttyOctalWindow).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyOctalWindow.stdout.replaceAll("\r\n", "\n").trim()).toBe("30 0");
+ const sttyFile = await shell(`script -qfec 'orig=$("$BUN" "$BNU" stty -F /dev/tty -g); "$BUN" "$BNU" stty --file=/dev/tty size; "$BUN" "$BNU" stty --file=/dev/tty raw -echo; "$BUN" "$BNU" stty -F /dev/tty -g; "$BUN" "$BNU" stty --file=/dev/tty "$orig"; "$BUN" "$BNU" stty -F /dev/tty -g' /dev/null`);
+ expect(sttyFile).toMatchObject({ code: 0, stderr: "" });
+ const sttyFileLines = sttyFile.stdout.replaceAll("\r\n", "\n").trim().split("\n");
+ expect(sttyFileLines).toEqual([
+ "0 0",
+ "0:4:f00bf:8a30:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "500:5:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ ]);
+ const sttyFileWindow = await shell(`script -qfec '"$BUN" "$BNU" stty -F /dev/tty rows 33 cols 101; "$BUN" "$BNU" stty -F /dev/tty size; "$BUN" "$BNU" stty -F /dev/tty -a | sed -n "1p"; stty rows 0 cols 0' /dev/null`);
+ expect(sttyFileWindow).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyFileWindow.stdout.replaceAll("\r\n", "\n").trim().split("\n")).toEqual([
+ "33 101",
+ "speed 38400 baud; rows 33; columns 101; line = 0;",
+ ]);
+ const sttyAliases = await shell(`script -qfec 'for mode in cbreak -cbreak cooked pass8 -pass8 litout -litout nl -nl; do stty sane; "$BUN" "$BNU" stty "$mode"; printf "%s " "$mode"; stty -g; done; stty sane' /dev/null`);
+ expect(sttyAliases.code).toBe(0);
+ expect(sttyAliases.stdout.replaceAll("\r\n", "\n").trim().split("\n")).toEqual([
+ "cbreak 2502:5:f00bf:8a39:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "-cbreak 2502:5:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "cooked 2526:5:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "pass8 2506:5:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "-pass8 2526:5:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "litout 2506:4:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "-litout 2526:5:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "nl 2426:1:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "-nl 2526:5:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ ]);
+ const sttySpeeds = await shell(`script -qfec 'stty sane; "$BUN" "$BNU" stty 9600; "$BUN" "$BNU" stty speed; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty ispeed 4800 ospeed 19200; "$BUN" "$BNU" stty speed; "$BUN" "$BNU" stty -a | sed -n "1p"; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty 123; "$BUN" "$BNU" stty speed; "$BUN" "$BNU" stty -g; stty sane' /dev/null`);
+ expect(sttySpeeds).toMatchObject({ code: 0, stderr: "" });
+ expect(sttySpeeds.stdout.replaceAll("\r\n", "\n").trim().split("\n")).toEqual([
+ "9600",
+ "2502:5:d00bd:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "4800 19200",
+ "ispeed 4800 baud; ospeed 19200 baud; rows 0; columns 0; line = 0;",
+ "2502:5:c00be:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "123",
+ "2502:5:100010b0:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ ]);
+ const sttyFractionalSpeed = await shell(`script -qfec 'stty sane; "$BUN" "$BNU" stty ispeed 9600.50; "$BUN" "$BNU" stty speed; "$BUN" "$BNU" stty ispeed 135.5; "$BUN" "$BNU" stty speed; "$BUN" "$BNU" stty ispeed exta; "$BUN" "$BNU" stty speed; stty sane' /dev/null`);
+ expect(sttyFractionalSpeed).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyFractionalSpeed.stdout.replaceAll("\r\n", "\n").trim().split("\n")).toEqual(["9600 38400", "136 38400", "19200 38400"]);
+ const sttyNumericControls = await shell(`script -qfec 'stty sane; for value in 010 0x3 ^- 8; do "$BUN" "$BNU" stty intr "$value"; "$BUN" "$BNU" stty -g; done; stty sane' /dev/null`);
+ expect(sttyNumericControls).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyNumericControls.stdout.replaceAll("\r\n", "\n").trim().split("\n").map((line) => line.split(":")[4])).toEqual(["8", "3", "0", "38"]);
+ const sttyControls = await shell(`script -qfec 'stty sane; "$BUN" "$BNU" stty intr ^A erase ^H min 3 time 7; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty -a | sed -n "2,4p"; "$BUN" "$BNU" stty swtch ^B eol ^E eol2 ^F; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty -a | sed -n "2,3p"; stty sane' /dev/null`);
+ expect(sttyControls).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyControls.stdout.replaceAll("\r\n", "\n").trim().split("\n")).toEqual([
+ "2502:5:f00bf:8a3b:1:1c:8:15:4:7:3:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "intr = ^A; quit = ^\\; erase = ^H; kill = ^U; eof = ^D; eol = <undef>;",
+ "eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;",
+ "werase = ^W; lnext = ^V; discard = ^O; min = 3; time = 7;",
+ "2502:5:f00bf:8a3b:1:1c:8:15:4:7:3:2:11:13:1a:5:12:f:17:16:6:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "intr = ^A; quit = ^\\; erase = ^H; kill = ^U; eof = ^D; eol = ^E;",
+ "eol2 = ^F; swtch = ^B; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;",
+ ]);
+ const sttyEmptyControl = await shell(`script -qfec 'stty sane; "$BUN" "$BNU" stty intr ""; "$BUN" "$BNU" stty -a | sed -n "2p"; stty sane' /dev/null`);
+ expect(sttyEmptyControl).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyEmptyControl.stdout.replaceAll("\r\n", "\n").trim()).toBe("intr = <undef>; quit = ^\\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;");
+ const sttyCflags = await shell(`script -qfec 'stty sane ignpar istrip parodd; "$BUN" "$BNU" stty sane; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty hup; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty -hup; "$BUN" "$BNU" stty -g; stty -ignpar -istrip -parodd; "$BUN" "$BNU" stty cmspar; "$BUN" "$BNU" stty -g; stty sane' /dev/null`);
+ expect(sttyCflags).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyCflags.stdout.replaceAll("\r\n", "\n").trim().split("\n")).toEqual([
+ "2526:5:f02bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "2526:5:f06bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "2526:5:f02bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "2502:5:400f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ ]);
+ const sttyDelays = await shell(`script -qfec 'for mode in nl1 cr2 tab3 bs1 vt1 ff1; do stty sane; "$BUN" "$BNU" stty "$mode"; printf "%s " "$mode"; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty -a | sed -n "8p"; done; stty sane' /dev/null`);
+ expect(sttyDelays).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyDelays.stdout.replaceAll("\r\n", "\n").trim().split("\n")).toEqual([
+ "nl1 2502:105:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl1 cr0 tab0 bs0 vt0 ff0",
+ "cr2 2502:405:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr2 tab0 bs0 vt0 ff0",
+ "tab3 2502:1805:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab3 bs0 vt0 ff0",
+ "bs1 2502:2005:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs1 vt0 ff0",
+ "vt1 2502:4005:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt1 ff0",
+ "ff1 2502:8005:f00bf:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff1",
+ ]);
+ const sttyLocalModes = await shell(`script -qfec 'stty sane; "$BUN" "$BNU" stty xcase; printf "xcase "; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty flusho; printf "flusho "; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty extproc; printf "extproc "; "$BUN" "$BNU" stty -g; "$BUN" "$BNU" stty -a | sed -n "9,10p"; stty sane' /dev/null`);
+ expect(sttyLocalModes).toMatchObject({ code: 0, stderr: "" });
+ expect(sttyLocalModes.stdout.replaceAll("\r\n", "\n").trim().split("\n")).toEqual([
+ "xcase 2502:5:f00bf:8a3f:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "flusho 2502:5:f00bf:9a3f:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "extproc 2502:5:f00bf:19a3f:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0",
+ "isig icanon iexten echo echoe echok -echonl -noflsh xcase -tostop -echoprt",
+ "echoctl echoke flusho extproc",
+ ]);
+ }
+ expect(await run(["coreutils", "echo", "nested"])).toMatchObject({ code: 0, stdout: "nested\n" });
+ const namedGroups = await run(["id", "-Gn"]);
+ expect(namedGroups.code).toBe(0);
+ expect(await run(["id", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: id [OPTION]... [USER]...\n") });
+ expect(await run(["groups"])).toMatchObject({ code: 0, stdout: namedGroups.stdout });
+ expect(await run(["link", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: link FILE1 FILE2\n or: link OPTION\n") });
+ expect(await run(["unlink", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: unlink FILE\n or: unlink OPTION\n") });
+ const linkedCommands = join(dir, "linked-commands");
+ const linkResult = await systemRun([process.execPath, join(import.meta.dir, "../scripts/link-commands.js"), linkedCommands]);
+ expect(linkResult).toMatchObject({ code: 0, stderr: "" });
+ expect(linkResult.stdout).toContain(" command wrappers");
+ expect(await systemRun([join(linkedCommands, "echo"), "linked"], "", { env: { PATH: "" } })).toMatchObject({ code: 0, stdout: "linked\n", stderr: "" });
+ await writeFile(join(dir, "linked-tail-input"), "a\nb\n");
+ expect(await systemRun([join(linkedCommands, "tail"), "-n", "1", "linked-tail-input"], "", { env: { PATH: "" } })).toMatchObject({ code: 0, stdout: "b\n", stderr: "" });
+ expect(await systemRun([join(linkedCommands, "timeout"), "1", join(linkedCommands, "echo"), "linked-timeout"], "", { env: { PATH: "" } })).toMatchObject({ code: 0, stdout: "linked-timeout\n", stderr: "" });
+ expect(await shell(`PATH= "${linkedCommands}/tac" - <&-`)).toMatchObject({ code: 1, stdout: "", stderr: "tac: 'standard input': read error: Bad file descriptor\n" });
+ expect(await systemRun([join(linkedCommands, "test"), "1", "=", "1"])).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await systemRun([join(linkedCommands, "["), "1", "=", "1", "]"], "", { env: { PATH: "" } })).toMatchObject({ code: 0, stdout: "", stderr: "" });
+ expect(await run(["logname", "extra"])).toMatchObject(await systemRun(["logname", "extra"]));
+ expect(await run(["whoami", "extra"])).toMatchObject(await systemRun(["whoami", "extra"]));
+ expect(await run(["arch", "extra"])).toMatchObject(await systemRun(["arch", "extra"]));
+});
+
+test("ptx emits automatic input references", async () => {
+ await writeFile(join(dir, "ptx-breaks"), "-");
+ expect(await run(["ptx", "--auto-reference"], "Beta alpha beta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--auto-reference"], "Beta alpha beta\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "-A", "--right-side-refs"], "Beta alpha beta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-A", "--right-side-refs"], "Beta alpha beta\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--references"], "ref alpha beta gamma\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--references"], "ref alpha beta gamma\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "-rR"], "ref alpha beta gamma\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-rR"], "ref alpha beta gamma\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "-r"], "r1 alpha beta\nr2 gamma delta\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "-r"], "r1 alpha beta\nr2 gamma delta\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--width=20", "--flag-truncation=!"], "alpha beta gamma delta epsilon\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--width=20", "--flag-truncation=!"], "alpha beta gamma delta epsilon\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--width=20", "--flag-truncation=XYZ"], "alpha beta gamma delta epsilon\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--width=20", "--flag-truncation=XYZ"], "alpha beta gamma delta epsilon\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--width=20", "--flag-truncation="], "alpha beta gamma delta epsilon\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--width=20", "--flag-truncation="], "alpha beta gamma delta epsilon\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--sentence-regexp=[.]"], "alpha beta. gamma delta.\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--sentence-regexp=[.]"], "alpha beta. gamma delta.\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "--break-file=ptx-breaks"], "alpha-beta gamma\n", { env: { LC_ALL: "C" } })).toMatchObject(await systemRun(["/usr/bin/ptx", "--break-file=ptx-breaks"], "alpha-beta gamma\n", { env: { LC_ALL: "C" } }));
+ expect(await run(["ptx", "-p"])).toMatchObject({ code: 1, stdout: "", stderr: "ptx: invalid option -- 'p'\nTry 'ptx --help' for more information.\n" });
+});
+
+test("csplit creates numbered chunks", async () => {
+ expect(await run(["csplit"])).toMatchObject({ code: 1, stderr: "csplit: missing operand\nTry 'csplit --help' for more information.\n" });
+ expect(await run(["csplit", "--pre", "pref", "--suf", "%d", "-s", "-", "2"], "a\nb\n")).toMatchObject({ code: 0, stdout: "" });
+ expect(await run(["csplit", "--digits=bad", "--help"])).toMatchObject(await systemRun(["csplit", "--digits=bad", "--help"]));
+ expect(await run(["csplit", "--digits=", "--help"])).toMatchObject(await systemRun(["csplit", "--digits=", "--help"]));
+ expect(await run(["csplit", "--digits", "--help"])).toMatchObject(await systemRun(["csplit", "--digits", "--help"]));
+ expect(await run(["csplit", "-n", "bad", "--help"])).toMatchObject(await systemRun(["csplit", "-n", "bad", "--help"]));
+ expect(await run(["csplit", "-nbad", "--help"])).toMatchObject(await systemRun(["csplit", "-nbad", "--help"]));
+ expect(await run(["csplit", "-n", "2", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: csplit [OPTION]... FILE PATTERN...\n") });
+ expect(await readFile(join(dir, "pref0"), "utf8")).toBe("a\n");
+ expect(await readFile(join(dir, "pref1"), "utf8")).toBe("b\n");
+ expect((await run(["csplit", "--s", "--help"])).stderr).toContain("option '--s' is ambiguous; possibilities: '--silent' '--suffix-format' '--suppress-matched'");
+ expect(await run(["csplit", "--prefix", "--help"])).toMatchObject({ code: 1, stderr: "csplit: missing operand\nTry 'csplit --help' for more information.\n" });
+ const csplitHelp = await run(["csplit", "--help"]);
+ expect(csplitHelp.code).toBe(0);
+ expect(csplitHelp.stdout).toContain("Usage: csplit [OPTION]... FILE PATTERN...\n");
+ expect(csplitHelp.stdout).toContain(" --quiet\n");
+ expect(await run(["csplit", "--prefix", "--help", "--version"])).toMatchObject({ code: 0, stdout: "bnu 9.11\n" });
+ expect((await run(["csplit", "--keep=bad", "--help"])).stderr).toContain("option '--keep-files' doesn't allow an argument");
+ expect((await run(["csplit", "--bad", "--help"])).stderr).toContain("unrecognized option '--bad'");
+ expect(await run(["csplit", "chapters"])).toMatchObject({ code: 1, stderr: "csplit: missing operand after 'chapters'\nTry 'csplit --help' for more information.\n" });
+ expect(await run(["csplit", "csplit-missing", "1"])).toMatchObject({ code: 1, stdout: "", stderr: "csplit: cannot open 'csplit-missing' for reading: No such file or directory\n" });
+ expect(await run(["csplit", "missing'csplit", "1"])).toMatchObject({ code: 1, stdout: "", stderr: "csplit: cannot open \"missing'csplit\" for reading: No such file or directory\n" });
+ expect(await run(["csplit", "missing\ncsplit", "1"])).toMatchObject({ code: 1, stdout: "", stderr: "csplit: cannot open 'missing'$'\\n''csplit' for reading: No such file or directory\n" });
+ await symlink("csplit-loop", join(dir, "csplit-loop"));
+ expect(await run(["csplit", "csplit-loop", "1"])).toMatchObject({ code: 1, stdout: "", stderr: "csplit: cannot open 'csplit-loop' for reading: Too many levels of symbolic links\n" });
+ await symlink("loop'csplit", join(dir, "loop'csplit"));
+ expect(await run(["csplit", "loop'csplit", "1"])).toMatchObject({ code: 1, stdout: "", stderr: "csplit: cannot open \"loop'csplit\" for reading: Too many levels of symbolic links\n" });
+ await mkdir(join(dir, "csplit-dir"));
+ expect(await run(["csplit", "csplit-dir", "1"])).toMatchObject({ code: 1, stdout: "0\n", stderr: "csplit: read error: Is a directory\n" });
+ await expect(stat(join(dir, "xx00"))).rejects.toThrow();
+ expect(await run(["csplit", "-k", "-f", "kept", "csplit-dir", "1"])).toMatchObject({ code: 1, stdout: "0\n", stderr: "csplit: read error: Is a directory\n" });
+ expect(await readFile(join(dir, "kept00"), "utf8")).toBe("");
+ await writeFile(join(dir, "chapters"), "one\ntwo\nthree\nfour\n");
+ expect(await run(["csplit", "chapters", "bad"])).toMatchObject(await systemRun(["csplit", "chapters", "bad"]));
+ expect(await run(["csplit", "-n", "bad", "chapters", "1"])).toMatchObject(await systemRun(["csplit", "-n", "bad", "chapters", "1"]));
+ expect(await run(["csplit", "-n", "1\n2", "chapters", "1"])).toMatchObject({ code: 1, stdout: "", stderr: `csplit: invalid number: ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["csplit", "chapters", "/unterminated\nX"])).toMatchObject({ code: 1, stdout: "", stderr: "csplit: /unterminated\nX: closing delimiter '/' missing\n" });
+ expect(await run(["csplit", "chapters", "/one/+x"])).toMatchObject({ code: 1, stdout: "", stderr: `csplit: ${diagnosticQuote("/one/+x")}: integer expected after delimiter\n` });
+ expect(await run(["csplit", "chapters", "/one/+1\nx"])).toMatchObject({ code: 1, stdout: "", stderr: `csplit: ${diagnosticQuote("/one/+1\\nx")}: integer expected after delimiter\n` });
+ expect(await run(["csplit", "chapters", "/[/"])).toMatchObject({ code: 1, stdout: "", stderr: `csplit: ${diagnosticQuote("/[/")}: invalid regular expression: Invalid regular expression\n` });
+ const result = await run(["csplit", "-f", "chunk", "chapters", "3"]);
+ expect(result.code).toBe(0);
+ expect(await readFile(join(dir, "chunk00"), "utf8")).toBe("one\ntwo\n");
+ expect(await readFile(join(dir, "chunk01"), "utf8")).toBe("three\nfour\n");
+
+ await writeFile(join(dir, "sections"), "A\nMARK\nB\nCUT\nC\n");
+ expect(await run(["csplit", "-s", "-f", "quiet", "-n", "3", "sections", "/MARK/+1"])).toMatchObject({ code: 0, stdout: "" });
+ expect(await readFile(join(dir, "quiet000"), "utf8")).toBe("A\nMARK\n");
+ expect(await readFile(join(dir, "quiet001"), "utf8")).toBe("B\nCUT\nC\n");
+ expect(await run(["csplit", "-s", "sections", "/MISSING/"])).toMatchObject({ code: 1, stdout: "", stderr: `csplit: ${diagnosticQuote("/MISSING/")}: match not found\n` });
+ expect(await run(["csplit", "-s", "sections", "/MISSING\nX/"])).toMatchObject({ code: 1, stdout: "", stderr: `csplit: ${diagnosticQuote("/MISSING\\nX/")}: match not found\n` });
+ expect(await run(["csplit", "-s", "--suppress-matched", "-f", "drop", "sections", "/MARK/"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "drop00"), "utf8")).toBe("A\n");
+ expect(await readFile(join(dir, "drop01"), "utf8")).toBe("B\nCUT\nC\n");
+ expect(await run(["csplit", "-s", "-b", "part%02d.txt", "-f", "named", "sections", "%MARK%", "/CUT/"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "namedpart00.txt"), "utf8")).toBe("MARK\nB\n");
+ expect(await readFile(join(dir, "namedpart01.txt"), "utf8")).toBe("CUT\nC\n");
+ expect(await run(["csplit", "-z", "-f", "stream", "-", "%n%1"], "y\nn\nz\n")).toMatchObject({ code: 0, stdout: "2\n" });
+ expect(await readFile(join(dir, "stream00"), "utf8")).toBe("z\n");
+ await writeFile(join(dir, "repeat"), "1\n2\n3\n");
+ expect(await run(["csplit", "-s", "-f", "rep", "repeat", "/./", "{*}"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "rep00"), "utf8")).toBe("");
+ expect(await readFile(join(dir, "rep01"), "utf8")).toBe("1\n");
+ expect(await readFile(join(dir, "rep03"), "utf8")).toBe("3\n");
+ expect(await run(["csplit", "-s", "--suppress-matched", "-f", "intsup", "repeat", "2", "3"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "intsup00"), "utf8")).toBe("1\n");
+ expect(await readFile(join(dir, "intsup01"), "utf8")).toBe("");
+ expect(await run(["csplit", "-s", "-z", "-f", "nonempty", "sections", "1"])).toMatchObject({ code: 0 });
+ await expect(stat(join(dir, "nonempty00"))).resolves.toBeTruthy();
+ await expect(stat(join(dir, "nonempty01"))).rejects.toThrow();
+ await mkdir(join(dir, "csplit-out00"));
+ expect(await run(["csplit", "-f", "csplit-out", "sections", "1"])).toMatchObject({ code: 1, stderr: "csplit: csplit-out00: Is a directory\n" });
+ await symlink("/dev/full", join(dir, "xx01"));
+ const full = await run(["csplit", "-", "1"], "1\n2\n");
+ expect(full).toMatchObject({ code: 1, stderr: "csplit: xx01: No space left on device\n" });
+ await expect(lstat(join(dir, "xx01"))).rejects.toThrow();
+ await mkdir(join(dir, "xx01"));
+ expect(await run(["csplit", "-", "1"], "1\n2\n")).toMatchObject({ code: 1 });
+ expect((await lstat(join(dir, "xx01"))).isDirectory()).toBe(true);
+});
+
+test("mkfifo and mknod create fifo special files", async () => {
+ expect(await run(["mkfifo"])).toMatchObject({ code: 1, stderr: "mkfifo: missing operand\nTry 'mkfifo --help' for more information.\n" });
+ expect(await run(["mkfifo", "-m", "600", "pipe1"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe1"))).isFIFO()).toBe(true);
+ expect((await lstat(join(dir, "pipe1"))).mode & 0o777).toBe(0o600);
+ expect(await run(["mkfifo", "pipe1"])).toMatchObject({ code: 1, stderr: "mkfifo: cannot create fifo 'pipe1': File exists\n" });
+ expect(await run(["mkfifo", "pipe\nnewline"])).toMatchObject({ code: 0 });
+ expect(await run(["mkfifo", "pipe\nnewline"])).toMatchObject({ code: 1, stderr: "mkfifo: cannot create fifo 'pipe'$'\\n''newline': File exists\n" });
+ expect(await run(["mkfifo", "pipe'quote"])).toMatchObject({ code: 0 });
+ expect(await run(["mkfifo", "pipe'quote"])).toMatchObject({ code: 1, stderr: "mkfifo: cannot create fifo \"pipe'quote\": File exists\n" });
+ expect(await run(["mkfifo", "missing-parent/pipe"])).toMatchObject({ code: 1, stderr: "mkfifo: cannot create fifo 'missing-parent/pipe': No such file or directory\n" });
+ await writeFile(join(dir, "special-parent-file"), "parent");
+ expect(await run(["mkfifo", "special-parent-file/pipe"])).toMatchObject({ code: 1, stderr: "mkfifo: cannot create fifo 'special-parent-file/pipe': Not a directory\n" });
+ await writeFile(join(dir, "special-parent\nfile"), "parent");
+ expect(await run(["mkfifo", "special-parent\nfile/pipe"])).toMatchObject({ code: 1, stderr: "mkfifo: cannot create fifo 'special-parent'$'\\n''file/pipe': Not a directory\n" });
+ await writeFile(join(dir, "special-parent'file"), "parent");
+ expect(await run(["mkfifo", "special-parent'file/pipe"])).toMatchObject({ code: 1, stderr: "mkfifo: cannot create fifo \"special-parent'file/pipe\": Not a directory\n" });
+ await writeFile(join(dir, "fifo-copy"), "regular");
+ expect(await run(["cp", "-R", "pipe1", "fifo-copy"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "fifo-copy"))).isFIFO()).toBe(true);
+ expect(await run(["cp", "-R", "pipe1", "fifo-copy"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "fifo-copy"))).isFIFO()).toBe(true);
+ expect(await run(["mkfifo", "--mode=u=rw,go=", "pipe-symbolic"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe-symbolic"))).mode & 0o777).toBe(0o600);
+ expect(await run(["mkfifo", "--m=640", "pipe-mode-prefix"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe-mode-prefix"))).mode & 0o777).toBe(0o640);
+ expect(await run(["mkfifo", "--mo", "620", "pipe-mode-next-prefix"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe-mode-next-prefix"))).mode & 0o777).toBe(0o620);
+ const mkfifoHelp = (await run(["mkfifo", "--h"])).stdout;
+ expect(mkfifoHelp).toContain("Usage: mkfifo [OPTION]... NAME...\n");
+ expect(mkfifoHelp).toContain("Mandatory arguments to long options are mandatory for short options too.\n");
+ expect(mkfifoHelp).toContain("-m, --mode=MODE set file permission bits to MODE, not a=rw - umask\n");
+ expect(mkfifoHelp).toContain("--context[=CTX] like -Z, or if CTX is specified then set the\n");
+ expect(await run(["mkfifo", "--m"])).toMatchObject({ code: 1, stderr: "mkfifo: option '--mode' requires an argument\nTry 'mkfifo --help' for more information.\n" });
+ expect(await run(["mkfifo", "--m", "--h"])).toMatchObject({ code: 1, stderr: "mkfifo: missing operand\nTry 'mkfifo --help' for more information.\n" });
+ expect(await run(["mkfifo", "--m", "--h", "pipe-bad-mode-prefix"])).toMatchObject({ code: 1, stderr: "mkfifo: invalid mode\n" });
+ expect(await run(["mkfifo", "--mode=bad", "pipe-bad-mode"])).toMatchObject({ code: 1, stderr: "mkfifo: invalid mode\n" });
+ expect(await run(["mkfifo", "-Z", "pipe-context"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe-context"))).isFIFO()).toBe(true);
+ expect(await run(["mkfifo", "--context=system_u:object_r:tmp_t:s0"])).toMatchObject({
+ code: 1,
+ stderr: "mkfifo: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\nmkfifo: missing operand\nTry 'mkfifo --help' for more information.\n",
+ });
+ expect(await run(["mkfifo", "--context=system_u:object_r:tmp_t:s0", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: mkfifo [OPTION]... NAME...\n"), stderr: "mkfifo: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n" });
+ expect(await run(["mkfifo", "--c", "pipe-context-prefix"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe-context-prefix"))).isFIFO()).toBe(true);
+ expect(await run(["mkfifo", "--context=system_u:object_r:tmp_t:s0", "pipe-context-2"])).toMatchObject({ code: 0, stderr: "mkfifo: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n" });
+ expect((await lstat(join(dir, "pipe-context-2"))).isFIFO()).toBe(true);
+ expect(await run(["mkfifo", "--c=system_u:object_r:tmp_t:s0", "pipe-context-2-prefix"])).toMatchObject({ code: 0, stderr: "mkfifo: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n" });
+ expect((await lstat(join(dir, "pipe-context-2-prefix"))).isFIFO()).toBe(true);
+ expect(await run(["mknod"])).toMatchObject({ code: 1, stderr: "mknod: missing operand\nTry 'mknod --help' for more information.\n" });
+ expect(await run(["mknod", "node-name"])).toMatchObject({ code: 1, stderr: "mknod: missing operand after 'node-name'\nTry 'mknod --help' for more information.\n" });
+ expect(await run(["mknod", "node-name", "b"])).toMatchObject({ code: 1, stderr: "mknod: missing operand after 'b'\nSpecial files require major and minor device numbers.\nTry 'mknod --help' for more information.\n" });
+ expect(await run(["mknod", "node-name", "b", "1"])).toMatchObject({ code: 1, stderr: "mknod: missing operand after '1'\nTry 'mknod --help' for more information.\n" });
+ expect(await run(["mknod", "node-name", "p", "extra"])).toMatchObject(await systemRun(["mknod", "node-name", "p", "extra"]));
+ expect(await run(["mknod", "node-name", "p", "extra\narg"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'mknod --help' for more information.\n` });
+ expect(await run(["mknod", "node-name", "x"])).toMatchObject({ code: 1, stderr: "mknod: missing operand after 'x'\nSpecial files require major and minor device numbers.\nTry 'mknod --help' for more information.\n" });
+ expect(await run(["mknod", "node-name", "x", "1"])).toMatchObject({ code: 1, stderr: "mknod: missing operand after '1'\nTry 'mknod --help' for more information.\n" });
+ expect(await run(["mknod", "node-name", "x", "1", "2"])).toMatchObject(await systemRun(["mknod", "node-name", "x", "1", "2"]));
+ expect(await run(["mknod", "node-name", "x\ny", "1", "2"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: invalid device type ${diagnosticQuote("x\\ny")}\nTry 'mknod --help' for more information.\n` });
+ expect(await run(["mknod", "node-name", "x", "1", "2", "3"])).toMatchObject(await systemRun(["mknod", "node-name", "x", "1", "2", "3"]));
+ expect(await run(["mknod", "node-name", "x", "1", "2", "extra\narg"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: extra operand ${diagnosticQuote("extra\\narg")}\nTry 'mknod --help' for more information.\n` });
+ expect(await run(["mknod", "node-name", "c", "1x", "3"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: invalid major device number ${diagnosticQuote("1x")}\n` });
+ expect(await run(["mknod", "node-name", "c", "1\n2", "3"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: invalid major device number ${diagnosticQuote("1\\n2")}\n` });
+ expect(await run(["mknod", "node-name", "c", "1", "3x"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: invalid minor device number ${diagnosticQuote("3x")}\n` });
+ expect(await run(["mknod", "node-name", "c", "1", "3\n4"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: invalid minor device number ${diagnosticQuote("3\\n4")}\n` });
+ expect(await run(["mknod", "node-name", "c", "08", "3"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: invalid major device number ${diagnosticQuote("08")}\n` });
+ expect(await run(["mknod", "node-name", "c", "1", "08"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: invalid minor device number ${diagnosticQuote("08")}\n` });
+ expect(await run(["mknod", "node-name", "b", "4294967296", "1"])).toMatchObject({ code: 1, stdout: "", stderr: `mknod: invalid major device number ${diagnosticQuote("4294967296")}\n` });
+ expect(await run(["mknod", "-m", "u=rw,go=", "pipe2", "p"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe2"))).isFIFO()).toBe(true);
+ expect((await lstat(join(dir, "pipe2"))).mode & 0o777).toBe(0o600);
+ expect(await run(["mknod", "--m=640", "pipe2-mode-prefix", "p"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe2-mode-prefix"))).mode & 0o777).toBe(0o640);
+ expect(await run(["mknod", "--mo", "620", "pipe2-mode-next-prefix", "p"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe2-mode-next-prefix"))).mode & 0o777).toBe(0o620);
+ const mknodHelp = (await run(["mknod", "--h"])).stdout;
+ expect(mknodHelp).toContain("Usage: mknod [OPTION]... NAME TYPE [MAJOR MINOR]\n");
+ expect(mknodHelp).toContain("-m, --mode=MODE set file permission bits to MODE, not a=rw - umask\n");
+ expect(mknodHelp).toContain("Both MAJOR and MINOR must be specified when TYPE is b, c, or u, and they\n");
+ expect(mknodHelp).toContain(" c, u create a character (unbuffered) special file\n");
+ expect(await run(["mknod", "--m"])).toMatchObject({ code: 1, stderr: "mknod: option '--mode' requires an argument\nTry 'mknod --help' for more information.\n" });
+ expect(await run(["mknod", "--m", "--h"])).toMatchObject({ code: 1, stderr: "mknod: invalid mode\n" });
+ expect(await run(["mknod", "--mode=bad", "pipe2-bad-mode", "p"])).toMatchObject({ code: 1, stderr: "mknod: invalid mode\n" });
+ expect(await run(["mknod", "pipe2", "p"])).toMatchObject({ code: 1, stderr: "mknod: pipe2: File exists\n" });
+ expect(await run(["mkfifo", "pipe2\nnewline"])).toMatchObject({ code: 0 });
+ expect(await run(["mknod", "pipe2\nnewline", "p"])).toMatchObject({ code: 1, stderr: "mknod: 'pipe2'$'\\n''newline': File exists\n" });
+ expect(await run(["mkfifo", "pipe2'quote"])).toMatchObject({ code: 0 });
+ expect(await run(["mknod", "pipe2'quote", "p"])).toMatchObject({ code: 1, stderr: "mknod: \"pipe2'quote\": File exists\n" });
+ expect(await run(["mknod", "missing-parent/pipe", "p"])).toMatchObject({ code: 1, stderr: "mknod: missing-parent/pipe: No such file or directory\n" });
+ expect(await run(["mknod", "special-parent-file/pipe", "p"])).toMatchObject({ code: 1, stderr: "mknod: special-parent-file/pipe: Not a directory\n" });
+ expect(await run(["mknod", "special-parent-file/node", "c", "1", "3"])).toMatchObject({ code: 1, stderr: "mknod: special-parent-file/node: Not a directory\n" });
+ expect(await run(["mknod", "special-parent\nfile/pipe", "p"])).toMatchObject({ code: 1, stderr: "mknod: 'special-parent'$'\\n''file/pipe': Not a directory\n" });
+ expect(await run(["mknod", "special-parent'file/pipe", "p"])).toMatchObject({ code: 1, stderr: "mknod: \"special-parent'file/pipe\": Not a directory\n" });
+ const unbufferedNode = await run(["mknod", "unbuffered-node", "u", "0x1", "03"]);
+ if (unbufferedNode.code !== 0) expect(unbufferedNode).toMatchObject(await systemRun(["/usr/bin/mknod", "unbuffered-node", "u", "0x1", "03"]));
+ const charNode = await run(["mknod", "char-node", "c", "1", "3"]);
+ if (charNode.code !== 0) expect(charNode).toMatchObject(await systemRun(["/usr/bin/mknod", "char-node", "c", "1", "3"]));
+ expect(await run(["mknod", "-Z", "pipe-context-3", "p"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe-context-3"))).isFIFO()).toBe(true);
+ expect(await run(["mknod", "--c", "pipe-context-3-prefix", "p"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "pipe-context-3-prefix"))).isFIFO()).toBe(true);
+ expect(await run(["mknod", "--context=system_u:object_r:tmp_t:s0", "pipe-context-4", "p"])).toMatchObject({ code: 0, stderr: "mknod: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n" });
+ expect((await lstat(join(dir, "pipe-context-4"))).isFIFO()).toBe(true);
+ expect(await run(["mknod", "--context=system_u:object_r:tmp_t:s0", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: mknod [OPTION]... NAME TYPE [MAJOR MINOR]\n"), stderr: "mknod: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n" });
+ expect(await run(["mknod", "--c=system_u:object_r:tmp_t:s0", "pipe-context-4-prefix", "p"])).toMatchObject({ code: 0, stderr: "mknod: warning: ignoring --context; it requires an SELinux/SMACK-enabled kernel\n" });
+ expect((await lstat(join(dir, "pipe-context-4-prefix"))).isFIFO()).toBe(true);
+ const strictFifo = Bun.spawn(["/bin/sh", "-c", `umask 777; ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} mkfifo -m 734 pipe3 && ${process.execPath} ${join(import.meta.dir, "../bin/bnu.js")} mknod --mode=ug+rw,o+r pipe4 p`], {
+ cwd: dir,
+ stdout: "pipe",
+ stderr: "pipe",
+ env: { ...process.env },
+ });
+ expect(await strictFifo.exited).toBe(0);
+ expect((await lstat(join(dir, "pipe3"))).mode & 0o777).toBe(0o734);
+ expect((await lstat(join(dir, "pipe4"))).mode & 0o777).toBe(0o666);
+});
+
+test("recursive cp, directory targets, symbolic chmod and signed head/tail counts", async () => {
+ await mkdir(join(dir, "src/sub"), { recursive: true });
+ await writeFile(join(dir, "src/file"), "one\ntwo\nthree\n");
+ await writeFile(join(dir, "src/sub/nested"), "nested");
+ expect(await run(["cp", "-r", "src", "dst"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "dst/sub/nested"), "utf8")).toBe("nested");
+ await mkdir(join(dir, "onefs-src"));
+ await writeFile(join(dir, "onefs-src/local"), "local");
+ await symlink("/dev/shm", join(dir, "onefs-src/other-fs"));
+ expect(await run(["cp", "-RLx", "onefs-src", "onefs-dst"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "onefs-dst/local"), "utf8")).toBe("local");
+ expect((await lstat(join(dir, "onefs-dst/other-fs"))).isDirectory()).toBe(true);
+ expect(await readdir(join(dir, "onefs-dst/other-fs"))).toEqual([]);
+ await mkdir(join(dir, "keep-link-src/d/e"), { recursive: true });
+ await mkdir(join(dir, "keep-link-dst/b"), { recursive: true });
+ await symlink("b", join(dir, "keep-link-dst/d"));
+ expect(await run(["cp", "-RT", "--copy-contents", "keep-link-src", "keep-link-dst"])).toMatchObject({
+ code: 1,
+ stderr: "cp: cannot overwrite non-directory 'keep-link-dst/d' with directory 'keep-link-src/d'\n",
+ });
+ expect(await run(["cp", "-RT", "--copy-contents", "--keep-directory-symlink", "keep-link-src", "keep-link-dst"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "keep-link-dst/d"))).isSymbolicLink()).toBe(true);
+ expect((await lstat(join(dir, "keep-link-dst/b/e"))).isDirectory()).toBe(true);
+ await mkdir(join(dir, "dir-time-src/sub"), { recursive: true });
+ await writeFile(join(dir, "dir-time-src/sub/file"), "dir time");
+ expect(await systemRun(["/usr/bin/touch", "-a", "-d", "2026-01-01 01:02:03.111111111 +0000", "dir-time-src/sub"])).toMatchObject({ code: 0 });
+ expect(await systemRun(["/usr/bin/touch", "-m", "-d", "2026-01-02 03:04:05.222222222 +0000", "dir-time-src/sub"])).toMatchObject({ code: 0 });
+ expect(await run(["cp", "-a", "dir-time-src", "dir-time-dst"])).toMatchObject({ code: 0 });
+ expect(await systemRun(["/usr/bin/stat", "-c", "%x|%y", "dir-time-dst/sub"], "", { env: { TZ: "UTC0" } })).toMatchObject({
+ code: 0,
+ stdout: "2026-01-01 01:02:03.111111111 +0000|2026-01-02 03:04:05.222222222 +0000\n",
+ });
+ await mkdir(join(dir, "target"));
+ expect(await run(["cp", "src/file", "target"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/file"), "utf8")).toBe("one\ntwo\nthree\n");
+ expect(await run(["cp", "-l", "src/file", "target/hard-file"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "target/hard-file"))).ino).toBe((await stat(join(dir, "src/file"))).ino);
+ expect(await run(["ln", "-s", "file", "src/link-file"])).toMatchObject({ code: 0 });
+ expect(await run(["cp", "--link", "src/link-file", "target/hard-from-link"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "target/hard-from-link"))).ino).toBe((await stat(join(dir, "src/file"))).ino);
+ expect(await run(["cp", "--link", "-P", "src/link-file", "target/hard-link-entry"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "target/hard-link-entry"))).isSymbolicLink()).toBe(true);
+ expect((await lstat(join(dir, "target/hard-link-entry"))).ino).toBe((await lstat(join(dir, "src/link-file"))).ino);
+ await link(join(dir, "src/file"), join(dir, "src/file-hard"));
+ expect(await run(["cp", "-d", "src/file", "src/file-hard", "target"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "target/file"))).ino).toBe((await stat(join(dir, "target/file-hard"))).ino);
+ await mkdir(join(dir, "target/no-preserve-links"));
+ expect(await run(["cp", "-d", "--no-preserve=links", "src/file", "src/file-hard", "target/no-preserve-links"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "target/no-preserve-links/file"))).ino).not.toBe((await stat(join(dir, "target/no-preserve-links/file-hard"))).ino);
+ await mkdir(join(dir, "target/update-dir/src"), { recursive: true });
+ await link(join(dir, "src/file"), join(dir, "src/update-link"));
+ await writeFile(join(dir, "target/update-dir/src/file"), "old");
+ await link(join(dir, "target/update-dir/src/file"), join(dir, "target/update-dir/src/update-link"));
+ await writeFile(join(dir, "target/update-dir/src/older"), "old");
+ await run(["touch", "-d", "-1 hour", "target/update-dir/src/older"]);
+ await link(join(dir, "src/file"), join(dir, "src/older"));
+ await writeFile(join(dir, "target/update-dir/src/newer"), "new");
+ await run(["touch", "-d", "+1 hour", "target/update-dir/src/newer"]);
+ await link(join(dir, "src/file"), join(dir, "src/newer"));
+ expect(await run(["cp", "-au", "src", "target/update-dir"])).toMatchObject({ code: 0 });
+ const preservedIno = (await stat(join(dir, "target/update-dir/src/file"))).ino;
+ expect((await stat(join(dir, "target/update-dir/src/update-link"))).ino).toBe(preservedIno);
+ expect((await stat(join(dir, "target/update-dir/src/older"))).ino).toBe(preservedIno);
+ expect((await stat(join(dir, "target/update-dir/src/newer"))).ino).toBe(preservedIno);
+ expect(await run(["ln", "-s", "sub", "src/sub-link"])).toMatchObject({ code: 0 });
+ expect(await run(["cp", "--link", "-R", "src/sub-link", "target/sub-hard-copy"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "target/sub-hard-copy/nested"))).ino).toBe((await stat(join(dir, "src/sub/nested"))).ino);
+ expect(await run(["ln", "-s", "missing", "src/dangling"])).toMatchObject({ code: 0 });
+ expect(await run(["cp", "-r", "src/dangling", "target/dangling-r"])).toMatchObject({ code: 0, stderr: "" });
+ expect((await lstat(join(dir, "target/dangling-r"))).isSymbolicLink()).toBe(true);
+ expect(await readFile(join(dir, "target/dangling-r"), "utf8").catch((error) => error.code)).toBe("ENOENT");
+ expect(await run(["cp", "-R", "src/dangling", "target/dangling-R"])).toMatchObject({ code: 0, stderr: "" });
+ expect((await lstat(join(dir, "target/dangling-R"))).isSymbolicLink()).toBe(true);
+ expect(await run(["cp", "--link", "src/dangling", "target/dangling-hard"])).toMatchObject({ code: 1, stderr: "cp: cannot stat 'src/dangling': No such file or directory\n" });
+ await mkdir(join(dir, "parents-dest"));
+ expect(await run(["cp", "--parents", "src/sub/nested", "parents-dest"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "parents-dest/src/sub/nested"), "utf8")).toBe("nested");
+ expect(await run(["cp", "-R", "src", "src"])).toMatchObject({ code: 1, stderr: "cp: cannot copy a directory, 'src', into itself, 'src/src'\n" });
+ expect(await run(["cp", "-d", "src/link-file", "target/link-copy"])).toMatchObject({ code: 0 });
+ expect(await readFile(join(dir, "target/link-copy"), "utf8")).toBe("one\ntwo\nthree\n");
+ expect((await lstat(join(dir, "target/link-copy"))).isSymbolicLink()).toBe(true);
+ expect(await run(["ln", "-s", "file", "target/update-link"])).toMatchObject({ code: 0 });
+ expect(await run(["cp", "--update", "--no-dereference", "src/link-file", "target/update-link"])).toMatchObject({ code: 0 });
+ expect(await run(["ln", "-s", "file", "target/remove-dest"])).toMatchObject({ code: 0 });
+ expect(await run(["cp", "--remove-destination", "src/file", "target/remove-dest"])).toMatchObject({ code: 0 });
+ expect((await lstat(join(dir, "target/remove-dest"))).isSymbolicLink()).toBe(false);
+ expect(await run(["chmod", "u+x,g-w,o=", "target/file"])).toMatchObject({ code: 0 });
+ const mode = (await stat(join(dir, "target/file"))).mode & 0o777;
+ expect(mode & 0o100).toBe(0o100);
+ expect(mode & 0o020).toBe(0);
+ expect(mode & 0o007).toBe(0);
+ await writeFile(join(dir, "chmod-verbose"), "mode");
+ await run(["chmod", "600", "chmod-verbose"]);
+ expect(await run(["chmod", "-v", "600", "chmod-verbose"])).toMatchObject({
+ code: 0,
+ stdout: "mode of 'chmod-verbose' retained as 0600 (rw-------)\n",
+ });
+ expect(await run(["chmod", "-v", "644", "chmod-verbose"])).toMatchObject({
+ code: 0,
+ stdout: "mode of 'chmod-verbose' changed from 0600 (rw-------) to 0644 (rw-r--r--)\n",
+ });
+ expect(await run(["chmod", "-c", "600", "chmod-verbose"])).toMatchObject({
+ code: 0,
+ stdout: "mode of 'chmod-verbose' changed from 0644 (rw-r--r--) to 0600 (rw-------)\n",
+ });
+ expect(await run(["chmod", "-c", "600", "chmod-verbose"])).toMatchObject({ code: 0, stdout: "" });
+ await writeFile(join(dir, "chmod-reference"), "ref");
+ await writeFile(join(dir, "chmod-reference-target"), "target");
+ await run(["chmod", "640", "chmod-reference"]);
+ expect(await run(["chmod", "--reference=chmod-reference", "chmod-reference-target"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "chmod-reference-target"))).mode & 0o777).toBe(0o640);
+ await run(["chmod", "600", "chmod-reference-target"]);
+ expect(await run(["chmod", "--ref=chmod-reference", "chmod-reference-target"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "chmod-reference-target"))).mode & 0o777).toBe(0o640);
+ const chmodInlineReferenceHelp = await run(["chmod", "--ref=missing-ref", "--help"]);
+ expect(chmodInlineReferenceHelp).toMatchObject({ code: 0 });
+ expect(chmodInlineReferenceHelp.stdout).toContain("Usage: chmod [OPTION]... MODE[,MODE]... FILE...\n or: chmod [OPTION]... OCTAL-MODE FILE...\n or: chmod [OPTION]... --reference=RFILE FILE...\n");
+ expect(await run(["chmod", "640", "--help"])).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: chmod [OPTION]... MODE[,MODE]... FILE...\n"), stderr: "" });
+ expect(await run(["chmod", "--r", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: option '--r' is ambiguous; possibilities: '--recursive' '--reference'\nTry 'chmod --help' for more information.\n",
+ });
+ expect(await run(["chmod", "--changes=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: option '--changes' doesn't allow an argument\nTry 'chmod --help' for more information.\n",
+ });
+ expect(await run(["chmod", "--bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: unrecognized option '--bad'\nTry 'chmod --help' for more information.\n",
+ });
+ expect(await run(["chmod", "-Rbad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: invalid option -- 'b'\nTry 'chmod --help' for more information.\n",
+ });
+ expect(await run(["chmod", "--preserve=bad", "--help"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: option '--preserve-root' doesn't allow an argument\nTry 'chmod --help' for more information.\n",
+ });
+ expect(await run(["chmod", "--reference", "--help", "--version"])).toMatchObject({
+ code: 0,
+ stdout: "bnu 9.11\n",
+ });
+ expect(await run(["chmod", "--reference=missing-ref", "chmod-reference-target"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: failed to get attributes of 'missing-ref': No such file or directory\n",
+ });
+ expect(await run(["chmod", "--reference=missing\nref", "chmod-reference-target"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: failed to get attributes of 'missing'$'\\n''ref': No such file or directory\n",
+ });
+ expect(await run(["chmod", "--reference", "chmod-reference"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: missing operand\nTry 'chmod --help' for more information.\n",
+ });
+ expect(await run(["chmod", "640", "missing-mode"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: cannot access 'missing-mode': No such file or directory\n",
+ });
+ expect(await run(["chmod", "640", "missing\nmode"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: cannot access 'missing'$'\\n''mode': No such file or directory\n",
+ });
+ expect(await run(["chmod", "640", "missing'mode"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: cannot access \"missing'mode\": No such file or directory\n",
+ });
+ expect(await run(["chmod", "bad", "chmod-reference-target"])).toMatchObject({
+ code: 1,
+ stderr: `chmod: invalid mode: ${diagnosticQuote("bad")}\nTry 'chmod --help' for more information.\n`,
+ });
+ expect(await run(["chmod", "a+z", "chmod-reference-target"])).toMatchObject({
+ code: 1,
+ stderr: `chmod: invalid mode: ${diagnosticQuote("a+z")}\nTry 'chmod --help' for more information.\n`,
+ });
+ expect(await run(["chmod", "bad\nmode", "chmod-reference-target"])).toMatchObject({
+ code: 1,
+ stderr: `chmod: invalid mode: ${diagnosticQuote("bad\\nmode")}\nTry 'chmod --help' for more information.\n`,
+ });
+ expect(await run(["chmod", "888", "chmod-reference-target"])).toMatchObject({
+ code: 1,
+ stderr: `chmod: invalid mode: ${diagnosticQuote("888")}\nTry 'chmod --help' for more information.\n`,
+ });
+ expect(await run(["chmod", "bad"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: missing operand after 'bad'\nTry 'chmod --help' for more information.\n",
+ });
+ await mkdir(join(dir, "chmod-setgid-dir"));
+ expect(await run(["chmod", "g+s", "chmod-setgid-dir"])).toMatchObject({ code: 0 });
+ expect(await run(["chmod", "755", "chmod-setgid-dir"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "chmod-setgid-dir"))).mode & 0o7777).toBe(0o2755);
+ expect(await run(["chmod", "=7777,-5022", "chmod-setgid-dir"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "chmod-setgid-dir"))).mode & 0o7777).toBe(0o2755);
+ expect(await run(["chmod", "-R", "a+rX", "dst"])).toMatchObject({ code: 0 });
+ expect((await stat(join(dir, "dst"))).mode & 0o111).toBeGreaterThan(0);
+ await writeFile(join(dir, "chmod\nverbose"), "x");
+ expect(await run(["chmod", "-v", "600", "chmod\nverbose"])).toMatchObject({
+ code: 0,
+ stdout: "mode of 'chmod'$'\\n''verbose' changed from 0644 (rw-r--r--) to 0600 (rw-------)\n",
+ });
+ await writeFile(join(dir, "chmod'verbose"), "x");
+ expect(await run(["chmod", "-v", "600", "chmod'verbose"])).toMatchObject({
+ code: 0,
+ stdout: "mode of \"chmod'verbose\" changed from 0644 (rw-r--r--) to 0600 (rw-------)\n",
+ });
+ await symlink("missing-chmod-target", join(dir, "chmod\nlink"));
+ expect(await run(["chmod", "600", "chmod\nlink"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: cannot operate on dangling symlink 'chmod'$'\\n''link'\n",
+ });
+ await symlink("missing-chmod-target", join(dir, "chmod'link"));
+ expect(await run(["chmod", "600", "chmod'link"])).toMatchObject({
+ code: 1,
+ stderr: "chmod: cannot operate on dangling symlink \"chmod'link\"\n",
+ });
+ if (typeof process.getuid === "function" && process.getuid() !== 0) {
+ const chmodRoot = await run(["chmod", "+", "/"]);
+ expect(chmodRoot.code).toBe(1);
+ expect(chmodRoot.stderr).toMatch(/^chmod: changing permissions of '\/': (Operation not permitted|Read-only file system)\n$/);
+ }
+ if (typeof process.getuid === "function" && process.getuid() !== 0 && typeof process.getgid === "function") {
+ await mkdir(join(dir, "chgrp-no-x/y"), { recursive: true });
+ try {
+ await chmod(join(dir, "chgrp-no-x"), 0o600);
+ expect(await run(["chgrp", "-R", String(process.getgid()), "chgrp-no-x"])).toMatchObject({
+ code: 1,
+ stderr: "chgrp: cannot access 'chgrp-no-x/y': Permission denied\n",
+ });
+ } finally {
+ await chmod(join(dir, "chgrp-no-x"), 0o700);
+ }
+ }
+ expect((await stat(join(dir, "dst/sub/nested"))).mode & 0o444).toBe(0o444);
+ expect(await run(["head", "-n", "-1", "src/file"])).toMatchObject({ code: 0, stdout: "one\ntwo\n" });
+ expect(await run(["tail", "-n", "+2", "src/file"])).toMatchObject({ code: 0, stdout: "two\nthree\n" });
+});
+
+test("cp and mv preserve user xattrs only when requested", async () => {
+ const result = await shell(`
+ set -eu
+ command -v getfattr >/dev/null 2>&1 || exit 0
+ command -v setfattr >/dev/null 2>&1 || exit 0
+ touch src
+ setfattr -n user.foo -v bar src
+ "$BUN" "$BNU" cp src plain
+ if getfattr -d plain 2>/dev/null | grep -F 'user.foo="bar"'; then
+ echo plain-preserved
+ exit 1
+ fi
+ "$BUN" "$BNU" cp --preserve=xattr src preserved
+ getfattr -d preserved 2>/dev/null | grep -F 'user.foo="bar"' >/dev/null
+ chmod a-w src
+ "$BUN" "$BNU" cp --preserve=xattr src readonly-copy
+ getfattr -d readonly-copy 2>/dev/null | grep -F 'user.foo="bar"' >/dev/null
+ test "$(stat -c %a src)" = "$(stat -c %a readonly-copy)"
+ chmod u+w src
+ "$BUN" "$BNU" ginstall src installed
+ if getfattr -d installed 2>/dev/null | grep -F 'user.foo="bar"'; then
+ echo install-preserved
+ exit 1
+ fi
+ "$BUN" "$BNU" mv src moved
+ getfattr -d moved 2>/dev/null | grep -F 'user.foo="bar"' >/dev/null
+ mkdir fake-xattr-bin
+ printf '%s\n' '#!/bin/sh' 'last=' 'for last do :; done' 'echo "setfattr: $last: Operation not supported" >&2' 'exit 1' > fake-xattr-bin/setfattr
+ chmod +x fake-xattr-bin/setfattr
+ PATH="$PWD/fake-xattr-bin:$PATH" "$BUN" "$BNU" cp --preserve=all moved xattr-best-effort 2>best-effort.err
+ test ! -s best-effort.err
+ if PATH="$PWD/fake-xattr-bin:$PATH" "$BUN" "$BNU" cp --preserve=xattr moved xattr-required 2>required.err; then
+ echo explicit-xattr-succeeded
+ exit 1
+ fi
+ printf '%s\n' "cp: setting attributes for 'xattr-required': Operation not supported" >required.exp
+ cmp required.exp required.err
+ `);
+ expect(result).toMatchObject({ code: 0, stdout: "" });
+});
+
+test("ls marks extended POSIX ACLs and cp -p preserves them when ACL tools are available", async () => {
+ const result = await shell(`
+ set -eu
+ command -v getfacl >/dev/null 2>&1 || exit 0
+ command -v setfacl >/dev/null 2>&1 || exit 0
+ touch source
+ # Some CI tmpfs mounts expose the ACL tools but deliberately reject ACLs.
+ setfacl -m u:65534:r-- source 2>/dev/null || exit 0
+ "$BUN" "$BNU" ls -log source | grep '^-[r-][w-][x-][r-][w-][x-][r-][w-][x-]+ ' >/dev/null
+ "$BUN" "$BNU" cp -p source copied
+ getfacl --omit-header copied | grep '^user:nobody:r--$' >/dev/null
+ mkdir source-dir
+ setfacl -d -m u:65534:r-- source-dir
+ "$BUN" "$BNU" cp -pR source-dir copied-dir
+ getfacl --omit-header copied-dir | grep '^default:user:nobody:r--$' >/dev/null
+ `);
+ expect(result).toMatchObject({ code: 0, stdout: "" });
+});
+
+test("ls, stat, and chcon use SELinux contexts when the xattr tools provide one", async () => {
+ const getfattr = join(dir, "getfattr");
+ const setfattr = join(dir, "setfattr");
+ const getenforce = join(dir, "getenforce");
+ const restorecon = join(dir, "restorecon");
+ const contextLog = join(dir, "context.log");
+ const restoreLog = join(dir, "restore.log");
+ await writeFile(getfattr, "#!/bin/sh\nlast=\nfor last do :; done\ncase $last in\n *beta) printf 'system_u:object_r:var_t:s0\\0' ;;\n *) printf 'system_u:object_r:tmp_t:s0\\0' ;;\nesac\n");
+ await writeFile(setfattr, "#!/bin/sh\nwhile [ \"$#\" -gt 0 ]; do\n if [ \"$1\" = -v ]; then shift; printf '%s' \"$1\" >\"$BNU_SELINUX_LOG\"; exit 0; fi\n shift\ndone\nexit 1\n");
+ await writeFile(getenforce, "#!/bin/sh\nprintf '%s\\n' Permissive\n");
+ await writeFile(restorecon, "#!/bin/sh\nlast=\nfor last do :; done\nprintf '%s' \"$last\" >\"$BNU_RESTORECON_LOG\"\n");
+ await chmod(getfattr, 0o755);
+ await chmod(setfattr, 0o755);
+ await chmod(getenforce, 0o755);
+ await chmod(restorecon, 0o755);
+ await writeFile(join(dir, "alpha"), "");
+ await writeFile(join(dir, "beta"), "");
+ await symlink("alpha", join(dir, "alpha-link"));
+ const env = { PATH: `${dir}:${process.env.PATH}`, BNU_SELINUX_LOG: contextLog, BNU_RESTORECON_LOG: restoreLog };
+ expect(await run(["ls", "-Z", "alpha"], "", { env })).toMatchObject({ code: 0, stdout: "system_u:object_r:tmp_t:s0 alpha\n" });
+ expect(await run(["ls", "-l", "alpha"], "", { env })).toMatchObject({ code: 0, stdout: expect.stringMatching(/^-rw-r--r--\./) });
+ expect(await run(["ls", "-l", "alpha-link"], "", { env })).toMatchObject({ code: 0, stdout: expect.stringMatching(/^lrwxrwxrwx\./) });
+ expect(await run(["ls", "-lnZ", "alpha-link"], "", { env })).toMatchObject({
+ code: 0,
+ stdout: expect.stringContaining(" system_u:object_r:tmp_t:s0 "),
+ });
+ expect(await run(["stat", "--printf=%C", "alpha"], "", { env })).toMatchObject({ code: 0, stdout: "system_u:object_r:tmp_t:s0" });
+ expect(await run(["chcon", "--user=user_u", "alpha"], "", { env })).toMatchObject({ code: 0 });
+ expect(await readFile(contextLog, "utf8")).toBe("user_u:object_r:tmp_t:s0");
+ expect(await run(["chcon", "system_u:object_r:var_t:s0", "alpha"], "", { env })).toMatchObject({ code: 0 });
+ expect(await readFile(contextLog, "utf8")).toBe("system_u:object_r:var_t:s0");
+ expect(await run(["chcon", "--reference=alpha", "beta"], "", { env })).toMatchObject({ code: 0 });
+ expect(await readFile(contextLog, "utf8")).toBe("system_u:object_r:tmp_t:s0");
+ expect(await run(["cp", "--preserve=context", "alpha", "preserved-context"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(contextLog, "utf8")).toBe("system_u:object_r:tmp_t:s0");
+ expect(await run(["cp", "--context=system_u:object_r:var_t:s0", "alpha", "explicit-context"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(contextLog, "utf8")).toBe("system_u:object_r:var_t:s0");
+ expect(await run(["cp", "-Z", "alpha", "restored-context"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(contextLog, "utf8")).toBe("system_u:object_r:tmp_t:s0");
+ expect(await readFile(restoreLog, "utf8")).toBe("restored-context");
+ await writeFile(join(dir, "move-source"), "");
+ expect(await run(["mv", "-Z", "move-source", "move-restored"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(restoreLog, "utf8")).toBe("move-restored");
+ await mkdir(join(dir, "move-tree"));
+ await writeFile(join(dir, "move-tree", "child"), "");
+ expect(await run(["mv", "--context", "move-tree", "move-tree-restored"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(restoreLog, "utf8")).toBe("move-tree-restored");
+ expect(await run(["mkdir", "--context=system_u:object_r:var_t:s0", "context-directory"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(contextLog, "utf8")).toBe("system_u:object_r:var_t:s0");
+ expect(await run(["mkdir", "-Zp", "restored-parent/child"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(restoreLog, "utf8")).toBe("restored-parent/child");
+ expect(await run(["mkfifo", "--context=system_u:object_r:tmp_t:s0", "context-fifo"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(contextLog, "utf8")).toBe("system_u:object_r:tmp_t:s0");
+ expect(await run(["mknod", "-Z", "restored-fifo", "p"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(restoreLog, "utf8")).toBe("restored-fifo");
+ expect(await run(["install", "--preserve-context", "alpha", "installed-preserved"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(contextLog, "utf8")).toBe("system_u:object_r:tmp_t:s0");
+ expect(await run(["install", "--context=system_u:object_r:var_t:s0", "alpha", "installed-explicit"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(contextLog, "utf8")).toBe("system_u:object_r:var_t:s0");
+ expect(await run(["install", "-Z", "alpha", "installed-restored"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(restoreLog, "utf8")).toBe("installed-restored");
+ expect(await run(["install", "-ZD", "alpha", "installed-parent/child/file"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(restoreLog, "utf8")).toBe("installed-parent/child/file");
+ expect(await run(["install", "-Zd", "installed-directory/child"], "", { env })).toMatchObject({ code: 0, stderr: "" });
+ expect(await readFile(restoreLog, "utf8")).toBe("installed-directory/child");
+}, 30000);
+
+test("id reports the current SELinux process context", async () => {
+ const getenforce = join(dir, "getenforce");
+ const ps = join(dir, "ps");
+ const context = "system_u:system_r:local_login_t:s0";
+ await writeFile(getenforce, "#!/bin/sh\nprintf '%s\\n' Permissive\n");
+ await writeFile(ps, `#!/bin/sh\nprintf '%s\\n' '${context}'\n`);
+ await chmod(getenforce, 0o755);
+ await chmod(ps, 0o755);
+ const env = { PATH: `${dir}:${process.env.PATH}` };
+ expect(await run(["id", "-Z"], "", { env })).toMatchObject({ code: 0, stdout: `${context}\n`, stderr: "" });
+ expect(await run(["runcon"], "", { env })).toMatchObject({ code: 0, stdout: `${context}\n`, stderr: "" });
+ expect(await run(["id", "--context", "--zero"], "", { env })).toMatchObject({ code: 0, stdout: `${context}\0`, stderr: "" });
+ expect(await run(["id", "-Zn"], "", { env })).toMatchObject({ code: 0, stdout: `${context}\n`, stderr: "" });
+ expect(await run(["id"], "", { env })).toMatchObject({ code: 0, stdout: expect.stringContaining(` context=${context}\n`) });
+ expect((await run(["id"], "", { env: { ...env, POSIXLY_CORRECT: "1" } })).stdout).not.toContain(" context=");
+ expect(await run(["id", "-Z", "some-user"], "", { env })).toMatchObject({ code: 1, stderr: "id: cannot print security context when user specified\n" });
+ expect((await run(["id", "-Zu"], "", { env })).stderr).toContain('cannot print "only" of more than one choice');
+ expect(await run(["id", "-Z", "--version"], "", { env })).toMatchObject({ code: 0, stdout: "bnu 9.11\n", stderr: "" });
+ expect(await run(["id", "--context", "--help"], "", { env })).toMatchObject({ code: 0, stdout: expect.stringContaining("Usage: id") });
+});
+
+test("stdin filters emit a complete record before EOF", async () => {
+ const result = await shell(`
+ set -eu
+ for spec in 'cut -b1' 'cut -c1' 'cut -f1' 'date -f -' 'expand' 'fold' 'nl' 'numfmt' 'paste' 'pr' 'tail -n+1' 'tail -c+1' 'tr 1 1' 'unexpand' 'uniq'; do
+ rm -f in hold out err status
+ mkfifo in hold
+ (eval "\\"$BUN\\" \\"$BNU\\" $spec <in >out 2>err"; echo $? >status) &
+ cpid=$!
+ (printf '1\\n'; cat hold >/dev/null) >in &
+ wpid=$!
+ i=0
+ while [ ! -s out ] && [ "$i" -lt 60 ]; do
+ sleep 0.05
+ i=$((i + 1))
+ done
+ if [ ! -s out ]; then
+ echo "not responsive: $spec"
+ cat err
+ : >hold || true
+ kill "$cpid" "$wpid" 2>/dev/null || true
+ wait "$cpid" 2>/dev/null || true
+ wait "$wpid" 2>/dev/null || true
+ exit 1
+ fi
+ : >hold
+ wait "$wpid"
+ wait "$cpid"
+ done
+ `);
+ expect(result).toMatchObject({ code: 0, stdout: "" });
+});