pax_global_header00006660000000000000000000000064150443357750014527gustar00rootroot0000000000000052 comment=b26edbe7711ccc28c172791282bed041eace9393 go-paths-helper-1.14.0/000077500000000000000000000000001504433577500146115ustar00rootroot00000000000000go-paths-helper-1.14.0/.github/000077500000000000000000000000001504433577500161515ustar00rootroot00000000000000go-paths-helper-1.14.0/.github/workflows/000077500000000000000000000000001504433577500202065ustar00rootroot00000000000000go-paths-helper-1.14.0/.github/workflows/test.yaml000066400000000000000000000014211504433577500220470ustar00rootroot00000000000000name: test on: push: pull_request: jobs: test-matrix: strategy: matrix: operating-system: [ ubuntu-latest, windows-latest, macos-latest, ] runs-on: ${{ matrix.operating-system }} steps: - name: Disable EOL conversions run: git config --global core.autocrlf false - name: Checkout uses: actions/checkout@v2 - name: Install Go uses: actions/setup-go@v2 with: go-version: "1.21" - name: Run unit tests run: go test -v ./... -coverprofile=coverage_unit.txt - name: Send unit tests coverage to Codecov uses: codecov/codecov-action@v1 with: file: ./coverage_unit.txt flags: unit go-paths-helper-1.14.0/LICENSE000066400000000000000000001045151504433577500156240ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . go-paths-helper-1.14.0/README.md000066400000000000000000000024221504433577500160700ustar00rootroot00000000000000## paths: a golang library to simplify handling of paths This library aims to simplify handling of the most common operations with paths. For example code that looked like this: ```go buildPath := getPathFromSomewhere() // returns string if buildPath != "" { cachePath, err := filepath.Abs(filepath.Join(buildPath, "cache")) ... } ``` can be transformed to: ```go buildPath := getPathFromSomewhere() // returns *paths.Path if buildPath != nil { cachePath, err := buildPath.Join("cache").Abs() ... } ``` most operations that usually requires a bit of convoluted system calls are now simplified, for example to check if a path is a directory: ```go buildPath := "/path/to/somewhere" srcPath := filepath.Join(buildPath, "src") if info, err := os.Stat(srcPath); err == nil && !info.IsDir() { os.MkdirAll(srcPath) } ``` using this library can be done this way: ```go buildPath := paths.New("/path/to/somewhere") srcPath := buildPath.Join("src") if !srcPath.IsDir() { scrPath.MkdirAll() } ``` ## Security If you think you found a vulnerability or other security-related bug in this project, please read our [security policy](https://github.com/arduino/go-paths-helper/security/policy) and report the bug to our Security Team 🛡️ Thank you! e-mail contact: security@arduino.cc go-paths-helper-1.14.0/constructors.go000066400000000000000000000053141504433577500177130ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "os" "runtime" ) // NullPath return the path to the /dev/null equivalent for the current OS func NullPath() *Path { if runtime.GOOS == "windows" { return New("nul") } return New("/dev/null") } // TempDir returns the default path to use for temporary files func TempDir() *Path { return New(os.TempDir()).Canonical() } // MkTempDir creates a new temporary directory in the directory // dir with a name beginning with prefix and returns the path of // the new directory. If dir is the empty string, TempDir uses the // default directory for temporary files func MkTempDir(dir, prefix string) (*Path, error) { path, err := os.MkdirTemp(dir, prefix) if err != nil { return nil, err } return New(path).Canonical(), nil } // MkTempFile creates a new temporary file in the directory dir with a name beginning with prefix, // opens the file for reading and writing, and returns the resulting *os.File. If dir is nil, // MkTempFile uses the default directory for temporary files (see paths.TempDir). Multiple programs // calling TempFile simultaneously will not choose the same file. The caller can use f.Name() to // find the pathname of the file. It is the caller's responsibility to remove the file when no longer needed. func MkTempFile(dir *Path, prefix string) (*os.File, error) { tmpDir := "" if dir != nil { tmpDir = dir.String() } return os.CreateTemp(tmpDir, prefix) } // Getwd returns a rooted path name corresponding to the current // directory. func Getwd() (*Path, error) { wd, err := os.Getwd() if err != nil { return nil, err } return New(wd), nil } go-paths-helper-1.14.0/doc.go000066400000000000000000000027531504433577500157140ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. // Paths is a library that provides a set of utilities to work with file paths in a platform-independent way. // It includes functions for creating temporary directories and files, handling null paths, and more. // It is designed to be used in Go applications that require file system operations without worrying about // platform-specific details. package paths go-paths-helper-1.14.0/go.mod000066400000000000000000000004471504433577500157240ustar00rootroot00000000000000module github.com/arduino/go-paths-helper go 1.23.0 toolchain go1.23.2 require ( github.com/stretchr/testify v1.8.4 golang.org/x/sys v0.32.0 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) go-paths-helper-1.14.0/go.sum000066400000000000000000000020121504433577500157370ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= go-paths-helper-1.14.0/gzip.go000066400000000000000000000036271504433577500161210ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "compress/gzip" "fmt" "io" ) // GZip compress src with gzip and writes the compressed file on dst //func GZip(src, dst *Path) error { // return errors.New("gzip unimplemented") //} // GUnzip decompress src with gzip and writes the uncompressed file on dst func GUnzip(src, dest *Path) error { gzIn, err := src.Open() if err != nil { return fmt.Errorf("opening %s: %w", src, err) } defer gzIn.Close() in, err := gzip.NewReader(gzIn) if err != nil { return fmt.Errorf("decoding %s: %w", src, err) } defer in.Close() out, err := dest.Create() if err != nil { return fmt.Errorf("creating %s: %w", dest, err) } defer out.Close() _, err = io.Copy(out, in) if err != nil { return fmt.Errorf("uncompressing %s: %w", dest, err) } return nil } go-paths-helper-1.14.0/gzip_test.go000066400000000000000000000032701504433577500171520ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "testing" "github.com/stretchr/testify/require" ) func TestGzipGunzip(t *testing.T) { zipped := New("testdata", "fileset", "test.txt.gz") unzipped := New("testdata", "fileset", "test.txt") tmp, err := MkTempDir("", "") require.NoError(t, err) defer tmp.RemoveAll() // Test decoding decoded := tmp.Join("test") err = GUnzip(zipped, decoded) require.NoError(t, err) d, err := decoded.ReadFile() require.NoError(t, err) u, err := unzipped.ReadFile() require.NoError(t, err) require.Equal(t, u, d) // Test encoding // TODO } go-paths-helper-1.14.0/json.go000066400000000000000000000030061504433577500161100ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "encoding/json" ) // MarshalJSON implements the json.Marshaler interface func (p *Path) MarshalJSON() ([]byte, error) { return json.Marshal(p.path) } // UnmarshalJSON implements the json.Unmarshaler interface func (p *Path) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { return err } (*p).path = s return nil } go-paths-helper-1.14.0/list.go000066400000000000000000000130531504433577500161150ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "sort" ) // PathList is a list of Path type PathList []*Path // NewPathList creates a new PathList with the given paths func NewPathList(paths ...string) PathList { res := PathList{} for _, path := range paths { res = append(res, New(path)) } return res } // Clone returns a copy of the current PathList func (p *PathList) Clone() PathList { res := PathList{} for _, path := range *p { res.Add(path.Clone()) } return res } // AsStrings return this path list as a string array func (p *PathList) AsStrings() []string { res := []string{} for _, path := range *p { res = append(res, path.String()) } return res } // Equals returns true if the current PathList is equal to the // PathList passed as argument func (p *PathList) Equals(other PathList) bool { if len(*p) != len(other) { return false } for i, path := range *p { if !path.EqualsTo(other[i]) { return false } } return true } // FilterDirs remove all entries except directories func (p *PathList) FilterDirs() { res := (*p)[:0] for _, path := range *p { if path.IsDir() { res = append(res, path) } } *p = res } // FilterOutDirs remove all directories entries func (p *PathList) FilterOutDirs() { res := (*p)[:0] for _, path := range *p { if !path.IsDir() { res = append(res, path) } } *p = res } // FilterOutHiddenFiles remove all hidden files (files with the name // starting with ".") func (p *PathList) FilterOutHiddenFiles() { p.FilterOutPrefix(".") } // Filter will remove all the elements of the list that do not match // the specified acceptor function func (p *PathList) Filter(acceptorFunc func(*Path) bool) { res := (*p)[:0] for _, path := range *p { if acceptorFunc(path) { res = append(res, path) } } *p = res } // FilterOutPrefix remove all entries having one of the specified prefixes func (p *PathList) FilterOutPrefix(prefixes ...string) { filterFunction := func(path *Path) bool { return !path.HasPrefix(prefixes...) } p.Filter(filterFunction) } // FilterPrefix remove all entries not having one of the specified prefixes func (p *PathList) FilterPrefix(prefixes ...string) { filterFunction := func(path *Path) bool { return path.HasPrefix(prefixes...) } p.Filter(filterFunction) } // FilterOutSuffix remove all entries having one of the specified suffixes func (p *PathList) FilterOutSuffix(suffixies ...string) { filterFunction := func(path *Path) bool { return !path.HasSuffix(suffixies...) } p.Filter(filterFunction) } // FilterSuffix remove all entries not having one of the specified suffixes func (p *PathList) FilterSuffix(suffixies ...string) { filterFunction := func(path *Path) bool { return path.HasSuffix(suffixies...) } p.Filter(filterFunction) } // Add adds a Path to the PathList func (p *PathList) Add(path *Path) { *p = append(*p, path) } // AddAll adds all Paths in the list passed as argument func (p *PathList) AddAll(paths PathList) { *p = append(*p, paths...) } // AddIfMissing adds a Path to the PathList if the path is not already // in the list func (p *PathList) AddIfMissing(path *Path) { if (*p).Contains(path) { return } (*p).Add(path) } // AddAllMissing adds all paths to the PathList excluding the paths already // in the list func (p *PathList) AddAllMissing(pathsToAdd PathList) { for _, pathToAdd := range pathsToAdd { (*p).AddIfMissing(pathToAdd) } } // ToAbs calls Path.ToAbs() method on each path of the list. // It stops at the first error and returns it. If all ToAbs calls // are successful nil is returned. func (p *PathList) ToAbs() error { for _, path := range *p { if err := path.ToAbs(); err != nil { return err } } return nil } // Contains check if the list contains a path that match // exactly (EqualsTo) to the specified path func (p *PathList) Contains(pathToSearch *Path) bool { for _, path := range *p { if path.EqualsTo(pathToSearch) { return true } } return false } // ContainsEquivalentTo check if the list contains a path // that is equivalent (EquivalentTo) to the specified path func (p *PathList) ContainsEquivalentTo(pathToSearch *Path) bool { for _, path := range *p { if path.EquivalentTo(pathToSearch) { return true } } return false } // Sort sorts this pathlist func (p *PathList) Sort() { sort.Sort(p) } func (p *PathList) Len() int { return len(*p) } func (p *PathList) Less(i, j int) bool { return (*p)[i].path < (*p)[j].path } func (p *PathList) Swap(i, j int) { (*p)[i], (*p)[j] = (*p)[j], (*p)[i] } go-paths-helper-1.14.0/list_test.go000066400000000000000000000116441504433577500171600ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "fmt" "testing" "github.com/stretchr/testify/require" ) func TestListConstructors(t *testing.T) { list0 := NewPathList() require.Len(t, list0, 0) list1 := NewPathList("test") require.Len(t, list1, 1) require.Equal(t, "[test]", fmt.Sprintf("%s", list1)) list3 := NewPathList("a", "b", "c") require.Len(t, list3, 3) require.Equal(t, "[a b c]", fmt.Sprintf("%s", list3)) require.False(t, list3.Contains(New("d"))) require.True(t, list3.Contains(New("a"))) require.False(t, list3.Contains(New("d/../a"))) require.False(t, list3.ContainsEquivalentTo(New("d"))) require.True(t, list3.ContainsEquivalentTo(New("a"))) require.True(t, list3.ContainsEquivalentTo(New("d/../a"))) list4 := list3.Clone() require.True(t, list3.Equals(list4)) require.Equal(t, "[a b c]", fmt.Sprintf("%s", list4)) list4.AddIfMissing(New("d")) require.Equal(t, "[a b c d]", fmt.Sprintf("%s", list4)) list4.AddIfMissing(New("b")) require.Equal(t, "[a b c d]", fmt.Sprintf("%s", list4)) list4.AddAllMissing(NewPathList("a", "e", "i", "o", "u")) require.False(t, list3.Equals(list4)) require.False(t, list4.Equals(list3)) require.Equal(t, "[a b c d e i o u]", fmt.Sprintf("%s", list4)) } func TestListSorting(t *testing.T) { list := NewPathList( "pointless", "spare", "carve", "unwieldy", "empty", "bow", "tub", "grease", "error", "energetic", "depend", "property") require.Equal(t, "[pointless spare carve unwieldy empty bow tub grease error energetic depend property]", fmt.Sprintf("%s", list)) list.Sort() require.Equal(t, "[bow carve depend empty energetic error grease pointless property spare tub unwieldy]", fmt.Sprintf("%s", list)) } func TestListFilters(t *testing.T) { list := NewPathList( "aaaa", "bbbb", "cccc", "dddd", "eeff", "aaaa/bbbb", "eeee/ffff", "gggg/hhhh", ) l1 := list.Clone() l1.FilterPrefix("a") require.Equal(t, "[aaaa]", fmt.Sprintf("%s", l1)) l2 := list.Clone() l2.FilterPrefix("b") require.Equal(t, "[bbbb aaaa/bbbb]", fmt.Sprintf("%s", l2)) l3 := list.Clone() l3.FilterOutPrefix("b") require.Equal(t, "[aaaa cccc dddd eeff eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l3)) l4 := list.Clone() l4.FilterPrefix("a", "b") require.Equal(t, "[aaaa bbbb aaaa/bbbb]", fmt.Sprintf("%s", l4)) l5 := list.Clone() l5.FilterPrefix("test") require.Equal(t, "[]", fmt.Sprintf("%s", l5)) l6 := list.Clone() l6.FilterOutPrefix("b", "c", "h") require.Equal(t, "[aaaa dddd eeff eeee/ffff]", fmt.Sprintf("%s", l6)) l7 := list.Clone() l7.FilterSuffix("a") require.Equal(t, "[aaaa]", fmt.Sprintf("%s", l7)) l8 := list.Clone() l8.FilterSuffix("a", "h") require.Equal(t, "[aaaa gggg/hhhh]", fmt.Sprintf("%s", l8)) l9 := list.Clone() l9.FilterSuffix("test") require.Equal(t, "[]", fmt.Sprintf("%s", l9)) l10 := list.Clone() l10.FilterOutSuffix("a") require.Equal(t, "[bbbb cccc dddd eeff aaaa/bbbb eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l10)) l11 := list.Clone() l11.FilterOutSuffix("a", "h") require.Equal(t, "[bbbb cccc dddd eeff aaaa/bbbb eeee/ffff]", fmt.Sprintf("%s", l11)) l12 := list.Clone() l12.FilterOutSuffix("test") require.Equal(t, "[aaaa bbbb cccc dddd eeff aaaa/bbbb eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l12)) l13 := list.Clone() l13.FilterOutSuffix() require.Equal(t, "[aaaa bbbb cccc dddd eeff aaaa/bbbb eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l13)) l14 := list.Clone() l14.FilterSuffix() require.Equal(t, "[]", fmt.Sprintf("%s", l14)) l15 := list.Clone() l15.FilterOutPrefix() require.Equal(t, "[aaaa bbbb cccc dddd eeff aaaa/bbbb eeee/ffff gggg/hhhh]", fmt.Sprintf("%s", l15)) l16 := list.Clone() l16.FilterPrefix() require.Equal(t, "[]", fmt.Sprintf("%s", l16)) l17 := list.Clone() l17.Filter(func(p *Path) bool { return p.Base() == "bbbb" }) require.Equal(t, "[bbbb aaaa/bbbb]", fmt.Sprintf("%s", l17)) } go-paths-helper-1.14.0/paths.go000066400000000000000000000374071504433577500162720ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "fmt" "io" "io/fs" "os" "path/filepath" "strings" "syscall" "time" ) // Path represents a path type Path struct { path string } // New creates a new Path object. If path is the empty string // then nil is returned. func New(path ...string) *Path { if len(path) == 0 { return nil } if len(path) == 1 && path[0] == "" { return nil } res := &Path{path: path[0]} if len(path) > 1 { return res.Join(path[1:]...) } return res } // NewFromFile creates a new Path object using the path name // obtained from the File object (see os.File.Name function). func NewFromFile(file *os.File) *Path { return New(file.Name()) } // Stat returns a FileInfo describing the named file. The result is // cached internally for next queries. To ensure that the cached // FileInfo entry is updated just call Stat again. func (p *Path) Stat() (fs.FileInfo, error) { return os.Stat(p.path) } // Lstat returns a FileInfo describing the named file. If the file is // a symbolic link, the returned FileInfo describes the symbolic link. // Lstat makes no attempt to follow the link. If there is an error, it // will be of type *PathError. func (p *Path) Lstat() (fs.FileInfo, error) { return os.Lstat(p.path) } // Clone create a copy of the Path object func (p *Path) Clone() *Path { return New(p.path) } // Join create a new Path by joining the provided paths func (p *Path) Join(paths ...string) *Path { return New(filepath.Join(p.path, filepath.Join(paths...))) } // JoinPath create a new Path by joining the provided paths func (p *Path) JoinPath(paths ...*Path) *Path { res := p.Clone() for _, path := range paths { res = res.Join(path.path) } return res } // Base returns the last element of path func (p *Path) Base() string { return filepath.Base(p.path) } // Ext returns the file name extension used by path func (p *Path) Ext() string { return filepath.Ext(p.path) } // HasPrefix returns true if the file name has one of the // given prefixes (the Base() method is used to obtain the // file name used for the comparison) func (p *Path) HasPrefix(prefixes ...string) bool { filename := p.Base() for _, prefix := range prefixes { if strings.HasPrefix(filename, prefix) { return true } } return false } // HasSuffix returns true if the file name has one of the // given suffixies func (p *Path) HasSuffix(suffixies ...string) bool { filename := p.String() for _, suffix := range suffixies { if strings.HasSuffix(filename, suffix) { return true } } return false } // RelTo returns a relative Path that is lexically equivalent to r when // joined to the current Path. // // For example paths.New("/my/path/ab/cd").RelTo(paths.New("/my/path")) // returns "../..". func (p *Path) RelTo(r *Path) (*Path, error) { rel, err := filepath.Rel(p.path, r.path) if err != nil { return nil, err } return New(rel), nil } // RelFrom returns a relative Path that when joined with r is lexically // equivalent to the current path. // // For example paths.New("/my/path/ab/cd").RelFrom(paths.New("/my/path")) // returns "ab/cd". func (p *Path) RelFrom(r *Path) (*Path, error) { rel, err := filepath.Rel(r.path, p.path) if err != nil { return nil, err } return New(rel), nil } // Abs returns the absolute path of the current Path func (p *Path) Abs() (*Path, error) { abs, err := filepath.Abs(p.path) if err != nil { return nil, err } return New(abs), nil } // IsAbs returns true if the Path is absolute func (p *Path) IsAbs() bool { return filepath.IsAbs(p.path) } // ToAbs transofrm the current Path to the corresponding absolute path func (p *Path) ToAbs() error { abs, err := filepath.Abs(p.path) if err != nil { return err } p.path = abs return nil } // Clean Clean returns the shortest path name equivalent to path by // purely lexical processing func (p *Path) Clean() *Path { return New(filepath.Clean(p.path)) } // IsInsideDir returns true if the current path is inside the provided // dir func (p *Path) IsInsideDir(dir *Path) (bool, error) { rel, err := filepath.Rel(dir.path, p.path) if err != nil { // If the dir cannot be made relative to this path it means // that it belong to a different filesystems, so it cannot be // inside this path. return false, nil } return !strings.Contains(rel, ".."+string(os.PathSeparator)) && rel != ".." && rel != ".", nil } // Parent returns all but the last element of path, typically the path's // directory or the parent directory if the path is already a directory func (p *Path) Parent() *Path { return New(filepath.Dir(p.path)) } // Mkdir create a directory denoted by the current path func (p *Path) Mkdir() error { return os.Mkdir(p.path, 0755) } // MkdirAll creates a directory named path, along with any necessary // parents, and returns nil, or else returns an error func (p *Path) MkdirAll() error { return os.MkdirAll(p.path, os.FileMode(0755)) } // Remove removes the named file or directory func (p *Path) Remove() error { return os.Remove(p.path) } // RemoveAll removes path and any children it contains. It removes // everything it can but returns the first error it encounters. If // the path does not exist, RemoveAll returns nil (no error). func (p *Path) RemoveAll() error { return os.RemoveAll(p.path) } // Rename renames (moves) the path to newpath. If newpath already exists // and is not a directory, Rename replaces it. OS-specific restrictions // may apply when oldpath and newpath are in different directories. If // there is an error, it will be of type *os.LinkError. func (p *Path) Rename(newpath *Path) error { return os.Rename(p.path, newpath.path) } // MkTempDir creates a new temporary directory inside the path // pointed by the Path object with a name beginning with prefix // and returns the path of the new directory. func (p *Path) MkTempDir(prefix string) (*Path, error) { return MkTempDir(p.path, prefix) } // FollowSymLink transforms the current path to the path pointed by the // symlink if path is a symlink, otherwise it does nothing func (p *Path) FollowSymLink() error { resolvedPath, err := filepath.EvalSymlinks(p.path) if err != nil { return err } p.path = resolvedPath return nil } // Exist return true if the file denoted by this path exists, false // in any other case (also in case of error). func (p *Path) Exist() bool { exist, err := p.ExistCheck() return exist && err == nil } // NotExist return true if the file denoted by this path DO NOT exists, false // in any other case (also in case of error). func (p *Path) NotExist() bool { exist, err := p.ExistCheck() return !exist && err == nil } // ExistCheck return true if the path exists or false if the path doesn't exists. // In case the check fails false is returned together with the corresponding error. func (p *Path) ExistCheck() (bool, error) { _, err := p.Stat() if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } if err.(*os.PathError).Err == syscall.ENOTDIR { return false, nil } return false, err } // IsDir returns true if the path exists and is a directory. In all the other // cases (and also in case of any error) false is returned. func (p *Path) IsDir() bool { isdir, err := p.IsDirCheck() return isdir && err == nil } // IsNotDir returns true if the path exists and is NOT a directory. In all the other // cases (and also in case of any error) false is returned. func (p *Path) IsNotDir() bool { isdir, err := p.IsDirCheck() return !isdir && err == nil } // IsDirCheck return true if the path exists and is a directory or false // if the path exists and is not a directory. In all the other case false and // the corresponding error is returned. func (p *Path) IsDirCheck() (bool, error) { info, err := p.Stat() if err == nil { return info.IsDir(), nil } return false, err } // CopyTo copies the contents of the file named src to the file named // by dst. The file will be created if it does not already exist. If the // destination file exists, all it's contents will be replaced by the contents // of the source file. The file mode will be copied from the source and // the copied data is synced/flushed to stable storage. func (p *Path) CopyTo(dst *Path) error { if p.EqualsTo(dst) { return fmt.Errorf("%s and %s are the same file", p.path, dst.path) } in, err := os.Open(p.path) if err != nil { return err } defer in.Close() out, err := os.Create(dst.path) if err != nil { return err } defer out.Close() if _, err := io.Copy(out, in); err != nil { return err } if err := out.Sync(); err != nil { return err } si, err := p.Stat() if err != nil { return err } err = os.Chmod(dst.path, si.Mode()) if err != nil { return err } return nil } // CopyDirTo recursively copies the directory denoted by the current path to // the destination path. The source directory must exist and the destination // directory must NOT exist (no implicit destination name allowed). // Symlinks are not copied, they will be supported in future versions. func (p *Path) CopyDirTo(dst *Path) error { src := p.Clean() dst = dst.Clean() srcFiles, err := src.ReadDir() if err != nil { return fmt.Errorf("error reading source dir %s: %s", src, err) } if exist, err := dst.ExistCheck(); exist { return fmt.Errorf("destination %s already exists", dst) } else if err != nil { return fmt.Errorf("checking if %s exists: %s", dst, err) } if err := dst.MkdirAll(); err != nil { return fmt.Errorf("creating destination dir %s: %s", dst, err) } srcInfo, err := src.Stat() if err != nil { return fmt.Errorf("getting stat info for %s: %s", src, err) } if err := os.Chmod(dst.path, srcInfo.Mode()); err != nil { return fmt.Errorf("setting permission for dir %s: %s", dst, err) } for _, srcPath := range srcFiles { srcPathInfo, err := srcPath.Stat() if err != nil { return fmt.Errorf("getting stat info for %s: %s", srcPath, err) } dstPath := dst.Join(srcPath.Base()) if srcPathInfo.IsDir() { if err := srcPath.CopyDirTo(dstPath); err != nil { return fmt.Errorf("copying %s to %s: %s", srcPath, dstPath, err) } continue } // Skip symlinks. if srcPathInfo.Mode()&os.ModeSymlink != 0 { // TODO continue } if err := srcPath.CopyTo(dstPath); err != nil { return fmt.Errorf("copying %s to %s: %s", srcPath, dstPath, err) } } return nil } // Chmod changes the mode of the named file to mode. If the file is a // symbolic link, it changes the mode of the link's target. If there // is an error, it will be of type *os.PathError. func (p *Path) Chmod(mode fs.FileMode) error { return os.Chmod(p.path, mode) } // Chtimes changes the access and modification times of the named file, // similar to the Unix utime() or utimes() functions. func (p *Path) Chtimes(atime, mtime time.Time) error { return os.Chtimes(p.path, atime, mtime) } // ReadFile reads the file named by filename and returns the contents func (p *Path) ReadFile() ([]byte, error) { return os.ReadFile(p.path) } // WriteFile writes data to a file named by filename. If the file // does not exist, WriteFile creates it otherwise WriteFile truncates // it before writing. func (p *Path) WriteFile(data []byte) error { return os.WriteFile(p.path, data, os.FileMode(0644)) } // WriteToTempFile writes data to a newly generated temporary file. // dir and prefix have the same meaning for MkTempFile. // In case of success the Path to the temp file is returned. func WriteToTempFile(data []byte, dir *Path, prefix string) (res *Path, err error) { f, err := MkTempFile(dir, prefix) if err != nil { return nil, err } defer f.Close() if n, err := f.Write(data); err != nil { return nil, err } else if n < len(data) { return nil, fmt.Errorf("could not write all data (written %d bytes out of %d)", n, len(data)) } return New(f.Name()), nil } // ReadFileAsLines reads the file named by filename and returns it as an // array of lines. This function takes care of the newline encoding // differences between different OS func (p *Path) ReadFileAsLines() ([]string, error) { data, err := p.ReadFile() if err != nil { return nil, err } txt := string(data) txt = strings.Replace(txt, "\r\n", "\n", -1) return strings.Split(txt, "\n"), nil } // Truncate create an empty file named by path or if the file already // exist it truncates it (delete all contents) func (p *Path) Truncate() error { return p.WriteFile([]byte{}) } // Open opens a file for reading. It calls os.Open on the // underlying path. func (p *Path) Open() (*os.File, error) { return os.Open(p.path) } // Create creates or truncates a file. It calls os.Create // on the underlying path. func (p *Path) Create() (*os.File, error) { return os.Create(p.path) } // Append opens a file for append or creates it if the file doesn't exist. func (p *Path) Append() (*os.File, error) { return os.OpenFile(p.path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666) } // EqualsTo return true if both paths are equal func (p *Path) EqualsTo(other *Path) bool { return p.path == other.path } // EquivalentTo return true if both paths are equivalent (they points to the // same file even if they are lexicographically different) based on the current // working directory. func (p *Path) EquivalentTo(other *Path) bool { if p.Clean().path == other.Clean().path { return true } if infoP, err := p.Stat(); err != nil { // go ahead with the next test... } else if infoOther, err := other.Stat(); err != nil { // go ahead with the next test... } else if os.SameFile(infoP, infoOther) { return true } if absP, err := p.Abs(); err != nil { return false } else if absOther, err := other.Abs(); err != nil { return false } else { return absP.path == absOther.path } } // Parents returns all the parents directories of the current path. If the path is absolute // it starts from the current path to the root, if the path is relative is starts from the // current path to the current directory. // The path should be clean for this method to work properly (no .. or . or other shortcuts). // This function does not performs any check on the returned paths. func (p *Path) Parents() []*Path { res := []*Path{} dir := p for { res = append(res, dir) parent := dir.Parent() if parent.EquivalentTo(dir) { break } dir = parent } return res } func (p *Path) String() string { return p.path } // Canonical return a "canonical" Path for the given filename. // The meaning of "canonical" is OS-dependent but the goal of this method // is to always return the same path for a given file (factoring out all the // possibile ambiguities including, for example, relative paths traversal, // symlinks, drive volume letter case, etc). func (p *Path) Canonical() *Path { canonical := p.Clone() // https://github.com/golang/go/issues/17084#issuecomment-246645354 canonical.FollowSymLink() if absPath, err := canonical.Abs(); err == nil { canonical = absPath } return canonical } go-paths-helper-1.14.0/paths_others_test.go000066400000000000000000000025511504433577500207050ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. //go:build !windows package paths import ( "testing" "github.com/stretchr/testify/require" ) func shorten(t *testing.T, longPath string) string { require.FailNow(t, "shorten is not implemented for this platform") return "" } go-paths-helper-1.14.0/paths_test.go000066400000000000000000000320251504433577500173200ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "path/filepath" "runtime" "strings" "testing" "github.com/stretchr/testify/require" ) func pathEqualsTo(t *testing.T, expected string, actual *Path) { require.Equal(t, expected, filepath.ToSlash(actual.String())) } func TestPathNew(t *testing.T) { test1 := New("path") require.Equal(t, "path", test1.String()) test2 := New("path", "path") require.Equal(t, filepath.Join("path", "path"), test2.String()) test3 := New() require.Nil(t, test3) test4 := New("") require.Nil(t, test4) } func TestPath(t *testing.T) { testPath := New("testdata", "fileset") pathEqualsTo(t, "testdata/fileset", testPath) isDir, err := testPath.IsDirCheck() require.True(t, isDir) require.NoError(t, err) require.True(t, testPath.IsDir()) require.False(t, testPath.IsNotDir()) exist, err := testPath.ExistCheck() require.True(t, exist) require.NoError(t, err) require.True(t, testPath.Exist()) require.False(t, testPath.NotExist()) folderPath := testPath.Join("folder") pathEqualsTo(t, "testdata/fileset/folder", folderPath) isDir, err = folderPath.IsDirCheck() require.True(t, isDir) require.NoError(t, err) require.True(t, folderPath.IsDir()) require.False(t, folderPath.IsNotDir()) exist, err = folderPath.ExistCheck() require.True(t, exist) require.NoError(t, err) require.True(t, folderPath.Exist()) require.False(t, folderPath.NotExist()) filePath := testPath.Join("file") pathEqualsTo(t, "testdata/fileset/file", filePath) isDir, err = filePath.IsDirCheck() require.False(t, isDir) require.NoError(t, err) require.False(t, filePath.IsDir()) require.True(t, filePath.IsNotDir()) exist, err = filePath.ExistCheck() require.True(t, exist) require.NoError(t, err) require.True(t, filePath.Exist()) require.False(t, filePath.NotExist()) anotherFilePath := filePath.Join("notexistent") pathEqualsTo(t, "testdata/fileset/file/notexistent", anotherFilePath) isDir, err = anotherFilePath.IsDirCheck() require.False(t, isDir) require.Error(t, err) require.False(t, anotherFilePath.IsDir()) require.False(t, anotherFilePath.IsNotDir()) exist, err = anotherFilePath.ExistCheck() require.False(t, exist) require.NoError(t, err) require.False(t, anotherFilePath.Exist()) require.True(t, anotherFilePath.NotExist()) list, err := folderPath.ReadDir() require.NoError(t, err) require.Len(t, list, 4) pathEqualsTo(t, "testdata/fileset/folder/.hidden", list[0]) pathEqualsTo(t, "testdata/fileset/folder/file2", list[1]) pathEqualsTo(t, "testdata/fileset/folder/file3", list[2]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[3]) list2 := list.Clone() list2.FilterDirs() require.Len(t, list2, 1) pathEqualsTo(t, "testdata/fileset/folder/subfolder", list2[0]) list2 = list.Clone() list2.FilterOutHiddenFiles() require.Len(t, list2, 3) pathEqualsTo(t, "testdata/fileset/folder/file2", list2[0]) pathEqualsTo(t, "testdata/fileset/folder/file3", list2[1]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", list2[2]) list2 = list.Clone() list2.FilterOutPrefix("file") require.Len(t, list2, 2) pathEqualsTo(t, "testdata/fileset/folder/.hidden", list2[0]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", list2[1]) } func TestResetStatCacheWhenFollowingSymlink(t *testing.T) { testdata := New("testdata", "fileset") files, err := testdata.ReadDir() require.NoError(t, err) for _, file := range files { if file.Base() == "symlinktofolder" { err = file.FollowSymLink() require.NoError(t, err) isDir, err := file.IsDirCheck() require.NoError(t, err) require.True(t, isDir) break } } } func TestIsInsideDir(t *testing.T) { notInside := func(a, b *Path) { isInside, err := a.IsInsideDir(b) require.NoError(t, err) require.False(t, isInside, "%s is inside %s", a, b) } inside := func(a, b *Path) { isInside, err := a.IsInsideDir(b) require.NoError(t, err) require.True(t, isInside, "%s is inside %s", a, b) notInside(b, a) } f1 := New("/a/b/c") f2 := New("/a/b/c/d") f3 := New("/a/b/c/d/e") notInside(f1, f1) notInside(f1, f2) inside(f2, f1) notInside(f1, f3) inside(f3, f1) r1 := New("a/b/c") r2 := New("a/b/c/d") r3 := New("a/b/c/d/e") r4 := New("f/../a/b/c/d/e") r5 := New("a/b/c/d/e/f/..") notInside(r1, r1) notInside(r1, r2) inside(r2, r1) notInside(r1, r3) inside(r3, r1) inside(r4, r1) notInside(r1, r4) inside(r5, r1) notInside(r1, r5) f4 := New("/home/megabug/aide/arduino-1.8.6/hardware/arduino/avr") f5 := New("/home/megabug/a15/packages") notInside(f5, f4) notInside(f4, f5) if runtime.GOOS == "windows" { f6 := New("C:\\", "A") f7 := New("C:\\", "A", "B", "C") f8 := New("E:\\", "A", "B", "C") inside(f7, f6) notInside(f8, f6) } } func TestReadFileAsLines(t *testing.T) { lines, err := New("testdata/fileset/anotherFile").ReadFileAsLines() require.NoError(t, err) require.Len(t, lines, 4) require.Equal(t, "line 1", lines[0]) require.Equal(t, "line 2", lines[1]) require.Equal(t, "", lines[2]) require.Equal(t, "line 3", lines[3]) } func TestCanonicaTempDir(t *testing.T) { require.Equal(t, TempDir().String(), TempDir().Canonical().String()) } func TestCopyDir(t *testing.T) { tmp, err := MkTempDir("", "") require.NoError(t, err) defer tmp.RemoveAll() src := New("testdata", "fileset") err = src.CopyDirTo(tmp.Join("dest")) require.NoError(t, err, "copying dir") exist, err := tmp.Join("dest", "folder", "subfolder", "file4").ExistCheck() require.True(t, exist) require.NoError(t, err) isdir, err := tmp.Join("dest", "folder", "subfolder", "file4").IsDirCheck() require.False(t, isdir) require.NoError(t, err) err = src.CopyDirTo(tmp.Join("dest")) require.Error(t, err, "copying dir to already existing") err = src.Join("file").CopyDirTo(tmp.Join("dest2")) require.Error(t, err, "copying file as dir") } func TestParents(t *testing.T) { parents := New("/a/very/long/path").Parents() require.Len(t, parents, 5) pathEqualsTo(t, "/a/very/long/path", parents[0]) pathEqualsTo(t, "/a/very/long", parents[1]) pathEqualsTo(t, "/a/very", parents[2]) pathEqualsTo(t, "/a", parents[3]) pathEqualsTo(t, "/", parents[4]) parents2 := New("a/very/relative/path").Parents() require.Len(t, parents, 5) pathEqualsTo(t, "a/very/relative/path", parents2[0]) pathEqualsTo(t, "a/very/relative", parents2[1]) pathEqualsTo(t, "a/very", parents2[2]) pathEqualsTo(t, "a", parents2[3]) pathEqualsTo(t, ".", parents2[4]) } func TestFilterDirs(t *testing.T) { testPath := New("testdata", "fileset") list, err := testPath.ReadDir() require.NoError(t, err) require.Len(t, list, 6) pathEqualsTo(t, "testdata/fileset/anotherFile", list[0]) pathEqualsTo(t, "testdata/fileset/file", list[1]) pathEqualsTo(t, "testdata/fileset/folder", list[2]) pathEqualsTo(t, "testdata/fileset/symlinktofolder", list[3]) pathEqualsTo(t, "testdata/fileset/test.txt", list[4]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", list[5]) list.FilterDirs() require.Len(t, list, 2) pathEqualsTo(t, "testdata/fileset/folder", list[0]) pathEqualsTo(t, "testdata/fileset/symlinktofolder", list[1]) } func TestFilterOutDirs(t *testing.T) { { testPath := New("testdata", "fileset") list, err := testPath.ReadDir() require.NoError(t, err) require.Len(t, list, 6) pathEqualsTo(t, "testdata/fileset/anotherFile", list[0]) pathEqualsTo(t, "testdata/fileset/file", list[1]) pathEqualsTo(t, "testdata/fileset/folder", list[2]) pathEqualsTo(t, "testdata/fileset/symlinktofolder", list[3]) pathEqualsTo(t, "testdata/fileset/test.txt", list[4]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", list[5]) list.FilterOutDirs() require.Len(t, list, 4) pathEqualsTo(t, "testdata/fileset/anotherFile", list[0]) pathEqualsTo(t, "testdata/fileset/file", list[1]) pathEqualsTo(t, "testdata/fileset/test.txt", list[2]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", list[3]) } { list, err := New("testdata", "broken_symlink", "dir_1").ReadDirRecursive() require.NoError(t, err) require.Len(t, list, 7) pathEqualsTo(t, "testdata/broken_symlink/dir_1/broken_link", list[0]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/file2", list[1]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_dir", list[2]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_dir/file1", list[3]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_file", list[4]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/real_dir", list[5]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/real_dir/file1", list[6]) list.FilterOutDirs() require.Len(t, list, 5) pathEqualsTo(t, "testdata/broken_symlink/dir_1/broken_link", list[0]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/file2", list[1]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_dir/file1", list[2]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/linked_file", list[3]) pathEqualsTo(t, "testdata/broken_symlink/dir_1/real_dir/file1", list[4]) } } func TestEquivalentPaths(t *testing.T) { wd, err := Getwd() require.NoError(t, err) require.True(t, New("file1").EquivalentTo(New("file1", "somethingelse", ".."))) require.True(t, New("file1", "abc").EquivalentTo(New("file1", "abc", "def", ".."))) require.True(t, wd.Join("file1").EquivalentTo(New("file1"))) require.True(t, wd.Join("file1").EquivalentTo(New("file1", "abc", ".."))) if runtime.GOOS == "windows" { q := New("testdata", "fileset", "anotherFile") r := New(shorten(t, q.String())) t.Log("SHORTENED PATH:", r.String()) require.True(t, q.EquivalentTo(r)) require.True(t, r.EquivalentTo(q)) } } func TestCanonicalize(t *testing.T) { wd, err := Getwd() require.NoError(t, err) p := New("testdata", "fileset", "anotherFile").Canonical() require.Equal(t, wd.Join("testdata", "fileset", "anotherFile").String(), p.String()) p = New("testdata", "fileset", "nonexistentFile").Canonical() require.Equal(t, wd.Join("testdata", "fileset", "nonexistentFile").String(), p.String()) if runtime.GOOS == "windows" { qshort := New(shorten(t, New("testdata", "fileset", "anotherFile").String())) t.Log("SHORTENED PATH:", qshort.String()) q := qshort.Canonical() require.Equal(t, wd.Join("testdata", "fileset", "anotherFile").String(), q.String()) r := New("c:\\").Canonical() require.Equal(t, "C:\\", r.String()) tmp, err := MkTempDir("", "pref") require.NoError(t, err) require.Equal(t, tmp.String(), tmp.Canonical().String()) } } func TestRelativeTo(t *testing.T) { res, err := New("/my/abs/path/123/456").RelTo(New("/my/abs/path")) require.NoError(t, err) pathEqualsTo(t, "../..", res) res, err = New("/my/abs/path").RelTo(New("/my/abs/path/123/456")) require.NoError(t, err) pathEqualsTo(t, "123/456", res) res, err = New("my/path").RelTo(New("/other/path")) require.Error(t, err) require.Nil(t, res) res, err = New("/my/abs/path/123/456").RelFrom(New("/my/abs/path")) pathEqualsTo(t, "123/456", res) require.NoError(t, err) res, err = New("/my/abs/path").RelFrom(New("/my/abs/path/123/456")) require.NoError(t, err) pathEqualsTo(t, "../..", res) res, err = New("my/path").RelFrom(New("/other/path")) require.Error(t, err) require.Nil(t, res) } func TestWriteToTempFile(t *testing.T) { tmpDir := New("testdata", "fileset", "tmp") err := tmpDir.MkdirAll() require.NoError(t, err) defer tmpDir.RemoveAll() tmpData := []byte("test") tmp, err := WriteToTempFile(tmpData, tmpDir, "prefix") defer tmp.Remove() require.NoError(t, err) require.True(t, strings.HasPrefix(tmp.Base(), "prefix")) isInside, err := tmp.IsInsideDir(tmpDir) require.NoError(t, err) require.True(t, isInside) data, err := tmp.ReadFile() require.NoError(t, err) require.Equal(t, tmpData, data) } func TestCopyToSamePath(t *testing.T) { tmpDir := New(t.TempDir()) srcFile := tmpDir.Join("test_file") dstFile := srcFile // create the source file in tmp dir err := srcFile.WriteFile([]byte("hello")) require.NoError(t, err) content, err := srcFile.ReadFile() require.NoError(t, err) require.Equal(t, []byte("hello"), content) // cannot copy the same file err = srcFile.CopyTo(dstFile) require.Error(t, err) require.Contains(t, err.Error(), "are the same file") } go-paths-helper-1.14.0/paths_windows_test.go000066400000000000000000000033561504433577500210770ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. //go:build windows package paths import ( "testing" "github.com/stretchr/testify/require" "golang.org/x/sys/windows" ) func shorten(t *testing.T, longPath string) string { var buf [4096]uint16 shortPath := &buf[0] n, err := windows.GetShortPathName(windows.StringToUTF16Ptr(longPath), &buf[0], uint32(len(buf))) if n >= uint32(len(buf)) { buf2 := make([]uint16, n+1) shortPath = &buf2[0] _, err = windows.GetShortPathName(windows.StringToUTF16Ptr(longPath), &buf2[0], uint32(len(buf2))) } require.NoError(t, err, "GetShortPathName failed for %v", longPath) return windows.UTF16PtrToString(shortPath) } go-paths-helper-1.14.0/process.go000066400000000000000000000210001504433577500166070ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "bytes" "context" "errors" "io" "os" "os/exec" ) // Process is representation of an external process run type Process struct { cmd *exec.Cmd } // NewProcess creates a command with the provided command line arguments // and environment variables (that will be added to the parent os.Environ). // The argument args[0] is the path to the executable, the remainder are the // arguments to the command. func NewProcess(extraEnv []string, args ...string) (*Process, error) { if len(args) == 0 { return nil, errors.New("no executable specified") } p := &Process{ cmd: exec.Command(args[0], args[1:]...), } p.cmd.Env = append(os.Environ(), extraEnv...) tellCommandNotToSpawnShell(p.cmd) // windows specific tellCommandToStartOnNewProcessGroup(p.cmd) // linux and macosx specific // This is required because some tools detects if the program is running // from terminal by looking at the stdin/out bindings. // https://github.com/arduino/arduino-cli/issues/844 p.cmd.Stdin = nullReaderInstance return p, nil } // TellCommandNotToSpawnShell avoids that the specified Cmd display a small // command prompt while runnning on Windows. It has no effects on other OS. // // Deprecated: TellCommandNotToSpawnShell is now always applied by default, there is no need to call it anymore. func (p *Process) TellCommandNotToSpawnShell() { tellCommandNotToSpawnShell(p.cmd) } // NewProcessFromPath creates a command from the provided executable path, // additional environment vars (in addition to the system default ones) // and command line arguments. func NewProcessFromPath(extraEnv []string, executable *Path, args ...string) (*Process, error) { processArgs := []string{executable.String()} processArgs = append(processArgs, args...) return NewProcess(extraEnv, processArgs...) } // RedirectStdoutTo will redirect the process' stdout to the specified // writer. Any previous redirection will be overwritten. func (p *Process) RedirectStdoutTo(out io.Writer) { p.cmd.Stdout = out } // RedirectStderrTo will redirect the process' stderr to the specified // writer. Any previous redirection will be overwritten. func (p *Process) RedirectStderrTo(err io.Writer) { p.cmd.Stderr = err } // StdinPipe returns a pipe that will be connected to the command's standard // input when the command starts. The pipe will be closed automatically after // Wait sees the command exit. A caller need only call Close to force the pipe // to close sooner. For example, if the command being run will not exit until // standard input is closed, the caller must close the pipe. func (p *Process) StdinPipe() (io.WriteCloser, error) { if p.cmd.Stdin == nullReaderInstance { p.cmd.Stdin = nil } return p.cmd.StdinPipe() } // StdoutPipe returns a pipe that will be connected to the command's standard // output when the command starts. // // Wait will close the pipe after seeing the command exit, so most callers // don't need to close the pipe themselves. It is thus incorrect to call Wait // before all reads from the pipe have completed. // For the same reason, it is incorrect to call Run when using StdoutPipe. func (p *Process) StdoutPipe() (io.ReadCloser, error) { return p.cmd.StdoutPipe() } // StderrPipe returns a pipe that will be connected to the command's standard // error when the command starts. // // Wait will close the pipe after seeing the command exit, so most callers // don't need to close the pipe themselves. It is thus incorrect to call Wait // before all reads from the pipe have completed. // For the same reason, it is incorrect to use Run when using StderrPipe. func (p *Process) StderrPipe() (io.ReadCloser, error) { return p.cmd.StderrPipe() } // Start will start the underliyng process. func (p *Process) Start() error { return p.cmd.Start() } // Wait waits for the command to exit and waits for any copying to stdin or copying // from stdout or stderr to complete. func (p *Process) Wait() error { // TODO: make some helpers to retrieve exit codes out of *ExitError. return p.cmd.Wait() } // WaitWithinContext wait for the process to complete. If the given context is canceled // before the normal process termination, the process is killed. func (p *Process) WaitWithinContext(ctx context.Context) error { completed := make(chan struct{}) defer close(completed) go func() { select { case <-ctx.Done(): p.Kill() case <-completed: } }() return p.Wait() } // Signal sends a signal to the Process. Sending Interrupt on Windows is not implemented. func (p *Process) Signal(sig os.Signal) error { return p.cmd.Process.Signal(sig) } // Kill causes the Process to exit immediately. Kill does not wait until the Process has // actually exited. This only kills the Process itself, not any other processes it may // have started. func (p *Process) Kill() error { return kill(p.cmd) } // SetDir sets the working directory of the command. If Dir is the empty string, Run // runs the command in the calling process's current directory. func (p *Process) SetDir(dir string) { p.cmd.Dir = dir } // GetDir gets the working directory of the command. func (p *Process) GetDir() string { return p.cmd.Dir } // SetDirFromPath sets the working directory of the command. If path is nil, Run // runs the command in the calling process's current directory. func (p *Process) SetDirFromPath(path *Path) { if path == nil { p.cmd.Dir = "" } else { p.cmd.Dir = path.String() } } // Run starts the specified command and waits for it to complete. func (p *Process) Run() error { return p.cmd.Run() } // SetEnvironment set the environment for the running process. Each entry is of the form "key=value". // System default environments will be wiped out. func (p *Process) SetEnvironment(values []string) { p.cmd.Env = append([]string{}, values...) } // RunWithinContext starts the specified command and waits for it to complete. If the given context // is canceled before the normal process termination, the process is killed. func (p *Process) RunWithinContext(ctx context.Context) error { if err := p.Start(); err != nil { return err } return p.WaitWithinContext(ctx) } // RunAndCaptureOutput starts the specified command and waits for it to complete. If the given context // is canceled before the normal process termination, the process is killed. The standard output and // standard error of the process are captured and returned at process termination. func (p *Process) RunAndCaptureOutput(ctx context.Context) ([]byte, []byte, error) { stdout := &bytes.Buffer{} stderr := &bytes.Buffer{} p.RedirectStdoutTo(stdout) p.RedirectStderrTo(stderr) err := p.RunWithinContext(ctx) return stdout.Bytes(), stderr.Bytes(), err } // RunAndCaptureCombinedOutput starts the specified command and waits for it to complete. If the given context // is canceled before the normal process termination, the process is killed. The standard output and // standard error of the process are captured and returned combined at process termination. func (p *Process) RunAndCaptureCombinedOutput(ctx context.Context) ([]byte, error) { out := &bytes.Buffer{} p.RedirectStdoutTo(out) p.RedirectStderrTo(out) err := p.RunWithinContext(ctx) return out.Bytes(), err } // GetArgs returns the command arguments func (p *Process) GetArgs() []string { return p.cmd.Args } // nullReaderInstance is an io.Reader that will always return EOF var nullReaderInstance = &nullReader{} type nullReader struct{} func (r *nullReader) Read(buff []byte) (int, error) { return 0, io.EOF } go-paths-helper-1.14.0/process_darwin.go000066400000000000000000000035341504433577500201670ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "os/exec" "syscall" ) func tellCommandNotToSpawnShell(_ *exec.Cmd) { // no op } func tellCommandToStartOnNewProcessGroup(oscmd *exec.Cmd) { // https://groups.google.com/g/golang-nuts/c/XoQ3RhFBJl8 // Start the process in a new process group. // This is needed to kill the process and its children // if we need to kill the process. if oscmd.SysProcAttr == nil { oscmd.SysProcAttr = &syscall.SysProcAttr{} } oscmd.SysProcAttr.Setpgid = true } func kill(oscmd *exec.Cmd) error { // https://groups.google.com/g/golang-nuts/c/XoQ3RhFBJl8 // Kill the process group pgid, err := syscall.Getpgid(oscmd.Process.Pid) if err != nil { return err } return syscall.Kill(-pgid, syscall.SIGKILL) } go-paths-helper-1.14.0/process_linux.go000066400000000000000000000035611504433577500200420ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. //go:build !windows package paths import ( "os/exec" "syscall" ) func tellCommandNotToSpawnShell(_ *exec.Cmd) { // no op } func tellCommandToStartOnNewProcessGroup(oscmd *exec.Cmd) { // https://groups.google.com/g/golang-nuts/c/XoQ3RhFBJl8 // Start the process in a new process group. // This is needed to kill the process and its children // if we need to kill the process. if oscmd.SysProcAttr == nil { oscmd.SysProcAttr = &syscall.SysProcAttr{} } oscmd.SysProcAttr.Setpgid = true } func kill(oscmd *exec.Cmd) error { // https://groups.google.com/g/golang-nuts/c/XoQ3RhFBJl8 // Kill the process group pgid, err := syscall.Getpgid(oscmd.Process.Pid) if err != nil { return err } return syscall.Kill(-pgid, syscall.SIGKILL) } go-paths-helper-1.14.0/process_others.go000066400000000000000000000026231504433577500202050ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. //go:build !windows && !linux && !darwin package paths import ( "os/exec" ) func tellCommandNotToSpawnShell(_ *exec.Cmd) { // no op } func tellCommandToStartOnNewProcessGroup(_ *exec.Cmd) { // no op } func kill(oscmd *exec.Cmd) error { return oscmd.Process.Kill() } go-paths-helper-1.14.0/process_test.go000066400000000000000000000045531504433577500176640ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "context" "runtime" "testing" "time" "github.com/stretchr/testify/require" ) func TestProcessWithinContext(t *testing.T) { // Build `delay` helper inside testdata/delay builder, err := NewProcess(nil, "go", "build") require.NoError(t, err) builder.SetDir("testdata/delay") require.NoError(t, builder.Run()) // Run delay and test if the process is terminated correctly due to context process, err := NewProcess(nil, "testdata/delay/delay") require.NoError(t, err) start := time.Now() ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond) err = process.RunWithinContext(ctx) require.Error(t, err) require.Less(t, time.Since(start), 500*time.Millisecond) cancel() } func TestKillProcessGroupOnLinux(t *testing.T) { if runtime.GOOS != "linux" { t.Skip("skipping test on non-linux system") } p, err := NewProcess(nil, "bash", "-c", "sleep 5 ; echo -n 5") require.NoError(t, err) start := time.Now() ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _, _, err = p.RunAndCaptureOutput(ctx) require.EqualError(t, err, "signal: killed") // Assert that the process was killed within the timeout require.Less(t, time.Since(start), 2*time.Second) } go-paths-helper-1.14.0/process_windows.go000066400000000000000000000063061504433577500203750ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "fmt" "os/exec" "syscall" "unsafe" "golang.org/x/sys/windows" ) func tellCommandNotToSpawnShell(oscmd *exec.Cmd) { if oscmd.SysProcAttr == nil { oscmd.SysProcAttr = &syscall.SysProcAttr{} } oscmd.SysProcAttr.HideWindow = true } func tellCommandToStartOnNewProcessGroup(_ *exec.Cmd) { // no op } func kill(oscmd *exec.Cmd) error { parentProcessMap, err := createParentProcessSnapshot() if err != nil { return err } return killPidTree(uint32(oscmd.Process.Pid), parentProcessMap) } // createParentProcessSnapshot returns a map that correlate a process // with its parent process: childPid -> parentPid func createParentProcessSnapshot() (map[uint32]uint32, error) { // Inspired by: https://stackoverflow.com/a/36089871/1655275 // Make a snapshot of the current running processes snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0) if err != nil { return nil, fmt.Errorf("getting running processes snapshot: %w", err) } defer windows.CloseHandle(snapshot) // Iterate the result and extract the parent-child relationship processParentMap := map[uint32]uint32{} var processEntry windows.ProcessEntry32 processEntry.Size = uint32(unsafe.Sizeof(processEntry)) hasData := (windows.Process32First(snapshot, &processEntry) == nil) for hasData { processParentMap[processEntry.ProcessID] = processEntry.ParentProcessID hasData = (windows.Process32Next(snapshot, &processEntry) == nil) } return processParentMap, nil } func killPidTree(pid uint32, parentProcessMap map[uint32]uint32) error { for childPid, parentPid := range parentProcessMap { if parentPid == pid { // Descend process tree if err := killPidTree(childPid, parentProcessMap); err != nil { return fmt.Errorf("error killing child process: %w", err) } } } return killPid(pid) } func killPid(pid uint32) error { process, err := windows.OpenProcess(windows.PROCESS_ALL_ACCESS, false, pid) if err != nil { return fmt.Errorf("opening process for kill: %w", err) } defer windows.CloseHandle(process) return windows.TerminateProcess(process, 128) } go-paths-helper-1.14.0/readdir.go000066400000000000000000000152671504433577500165650ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "errors" "os" "strings" ) // ReadDirFilter is a filter for Path.ReadDir and Path.ReadDirRecursive methods. // The filter should return true to accept a file or false to reject it. type ReadDirFilter func(file *Path) bool // ReadDir returns a PathList containing the content of the directory // pointed by the current Path. The resulting list is filtered by the given filters chained. func (p *Path) ReadDir(filters ...ReadDirFilter) (PathList, error) { infos, err := os.ReadDir(p.path) if err != nil { return nil, err } accept := func(p *Path) bool { for _, filter := range filters { if !filter(p) { return false } } return true } paths := PathList{} for _, info := range infos { path := p.Join(info.Name()) if !accept(path) { continue } paths.Add(path) } return paths, nil } // ReadDirRecursive returns a PathList containing the content of the directory // and its subdirectories pointed by the current Path func (p *Path) ReadDirRecursive() (PathList, error) { return p.ReadDirRecursiveFiltered(nil) } // ReadDirRecursiveFiltered returns a PathList containing the content of the directory // and its subdirectories pointed by the current Path, filtered by the given skipFilter // and filters: // - `recursionFilter` is a filter that is checked to determine if the subdirectory must // by visited recursively (if the filter rejects the entry, the entry is not visited // but can still be added to the result) // - `filters` are the filters that are checked to determine if the entry should be // added to the resulting PathList func (p *Path) ReadDirRecursiveFiltered(recursionFilter ReadDirFilter, filters ...ReadDirFilter) (PathList, error) { var search func(*Path) (PathList, error) explored := map[string]bool{} search = func(currPath *Path) (PathList, error) { canonical := currPath.Canonical().path if explored[canonical] { return nil, errors.New("directories symlink loop detected") } explored[canonical] = true defer delete(explored, canonical) infos, err := os.ReadDir(currPath.path) if err != nil { return nil, err } accept := func(p *Path) bool { for _, filter := range filters { if !filter(p) { return false } } return true } paths := PathList{} for _, info := range infos { path := currPath.Join(info.Name()) if accept(path) { paths.Add(path) } if recursionFilter == nil || recursionFilter(path) { if path.IsDir() { subPaths, err := search(path) if err != nil { return nil, err } paths.AddAll(subPaths) } } } return paths, nil } return search(p) } // FilterDirectories is a ReadDirFilter that accepts only directories func FilterDirectories() ReadDirFilter { return func(path *Path) bool { return path.IsDir() } } // FilterOutDirectories is a ReadDirFilter that rejects all directories func FilterOutDirectories() ReadDirFilter { return func(path *Path) bool { return !path.IsDir() } } // FilterNames is a ReadDirFilter that accepts only the given filenames func FilterNames(allowedNames ...string) ReadDirFilter { return func(file *Path) bool { for _, name := range allowedNames { if file.Base() == name { return true } } return false } } // FilterOutNames is a ReadDirFilter that rejects the given filenames func FilterOutNames(rejectedNames ...string) ReadDirFilter { return func(file *Path) bool { for _, name := range rejectedNames { if file.Base() == name { return false } } return true } } // FilterSuffixes creates a ReadDirFilter that accepts only the given // filename suffixes func FilterSuffixes(allowedSuffixes ...string) ReadDirFilter { return func(file *Path) bool { for _, suffix := range allowedSuffixes { if strings.HasSuffix(file.String(), suffix) { return true } } return false } } // FilterOutSuffixes creates a ReadDirFilter that rejects all the given // filename suffixes func FilterOutSuffixes(rejectedSuffixes ...string) ReadDirFilter { return func(file *Path) bool { for _, suffix := range rejectedSuffixes { if strings.HasSuffix(file.String(), suffix) { return false } } return true } } // FilterPrefixes creates a ReadDirFilter that accepts only the given // filename prefixes func FilterPrefixes(allowedPrefixes ...string) ReadDirFilter { return func(file *Path) bool { name := file.Base() for _, prefix := range allowedPrefixes { if strings.HasPrefix(name, prefix) { return true } } return false } } // FilterOutPrefixes creates a ReadDirFilter that rejects all the given // filename prefixes func FilterOutPrefixes(rejectedPrefixes ...string) ReadDirFilter { return func(file *Path) bool { name := file.Base() for _, prefix := range rejectedPrefixes { if strings.HasPrefix(name, prefix) { return false } } return true } } // OrFilter creates a ReadDirFilter that accepts all items that are accepted // by any (at least one) of the given filters func OrFilter(filters ...ReadDirFilter) ReadDirFilter { return func(path *Path) bool { for _, f := range filters { if f(path) { return true } } return false } } // AndFilter creates a ReadDirFilter that accepts all items that are accepted // by all the given filters func AndFilter(filters ...ReadDirFilter) ReadDirFilter { return func(path *Path) bool { for _, f := range filters { if !f(path) { return false } } return true } } // NotFilter creates a ReadDifFilter that accepts all items rejected by x and viceversa func NotFilter(x ReadDirFilter) ReadDirFilter { return func(path *Path) bool { return !x(path) } } go-paths-helper-1.14.0/readdir_test.go000066400000000000000000000322011504433577500176070ustar00rootroot00000000000000// This file is part of PathsHelper library. // // Copyright 2018-2025 Arduino AG (http://www.arduino.cc/) // // 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 . // // You can be released from the requirements of the above licenses by purchasing // a commercial license. Buying such a license is mandatory if you want to // modify or otherwise use the software for commercial activities involving the // Arduino software without disclosing the source code of your own applications. // To purchase a commercial license, send an email to license@arduino.cc. package paths import ( "fmt" "io/fs" "os" "runtime" "testing" "time" "github.com/stretchr/testify/require" ) func TestReadDirRecursive(t *testing.T) { testPath := New("testdata", "fileset") list, err := testPath.ReadDirRecursive() require.NoError(t, err) require.Len(t, list, 16) pathEqualsTo(t, "testdata/fileset/anotherFile", list[0]) pathEqualsTo(t, "testdata/fileset/file", list[1]) pathEqualsTo(t, "testdata/fileset/folder", list[2]) pathEqualsTo(t, "testdata/fileset/folder/.hidden", list[3]) pathEqualsTo(t, "testdata/fileset/folder/file2", list[4]) pathEqualsTo(t, "testdata/fileset/folder/file3", list[5]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[6]) pathEqualsTo(t, "testdata/fileset/folder/subfolder/file4", list[7]) pathEqualsTo(t, "testdata/fileset/symlinktofolder", list[8]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", list[9]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", list[10]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", list[11]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", list[12]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder/file4", list[13]) pathEqualsTo(t, "testdata/fileset/test.txt", list[14]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", list[15]) } func TestReadDirRecursiveSymLinkLoop(t *testing.T) { // Test symlink loop tmp, err := MkTempDir("", "") require.NoError(t, err) defer tmp.RemoveAll() folder := tmp.Join("folder") err = os.Symlink(tmp.String(), folder.String()) require.NoError(t, err) l, err := tmp.ReadDirRecursive() require.Error(t, err) fmt.Println(err) require.Nil(t, l) l, err = tmp.ReadDirRecursiveFiltered(nil) require.Error(t, err) fmt.Println(err) require.Nil(t, l) } func TestReadDirFiltered(t *testing.T) { folderPath := New("testdata/fileset/folder") list, err := folderPath.ReadDir() require.NoError(t, err) require.Len(t, list, 4) pathEqualsTo(t, "testdata/fileset/folder/.hidden", list[0]) pathEqualsTo(t, "testdata/fileset/folder/file2", list[1]) pathEqualsTo(t, "testdata/fileset/folder/file3", list[2]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[3]) list, err = folderPath.ReadDir(FilterDirectories()) require.NoError(t, err) require.Len(t, list, 1) pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[0]) list, err = folderPath.ReadDir(FilterOutPrefixes("file")) require.NoError(t, err) require.Len(t, list, 2) pathEqualsTo(t, "testdata/fileset/folder/.hidden", list[0]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", list[1]) } func TestReadDirRecursiveFiltered(t *testing.T) { testdata := New("testdata", "fileset") l, err := testdata.ReadDirRecursiveFiltered(nil) require.NoError(t, err) l.Sort() require.Len(t, l, 16) pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) pathEqualsTo(t, "testdata/fileset/file", l[1]) pathEqualsTo(t, "testdata/fileset/folder", l[2]) pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[3]) pathEqualsTo(t, "testdata/fileset/folder/file2", l[4]) pathEqualsTo(t, "testdata/fileset/folder/file3", l[5]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", l[6]) pathEqualsTo(t, "testdata/fileset/folder/subfolder/file4", l[7]) pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[8]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[9]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[10]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", l[11]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[12]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder/file4", l[13]) pathEqualsTo(t, "testdata/fileset/test.txt", l[14]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[15]) l, err = testdata.ReadDirRecursiveFiltered(FilterOutDirectories()) require.NoError(t, err) l.Sort() require.Len(t, l, 6) pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) pathEqualsTo(t, "testdata/fileset/file", l[1]) pathEqualsTo(t, "testdata/fileset/folder", l[2]) // <- this is listed but not traversed pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[3]) // <- this is listed but not traversed pathEqualsTo(t, "testdata/fileset/test.txt", l[4]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[5]) l, err = testdata.ReadDirRecursiveFiltered(nil, FilterOutDirectories()) require.NoError(t, err) l.Sort() require.Len(t, l, 12) pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) pathEqualsTo(t, "testdata/fileset/file", l[1]) pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[2]) pathEqualsTo(t, "testdata/fileset/folder/file2", l[3]) pathEqualsTo(t, "testdata/fileset/folder/file3", l[4]) pathEqualsTo(t, "testdata/fileset/folder/subfolder/file4", l[5]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[6]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[7]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", l[8]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder/file4", l[9]) pathEqualsTo(t, "testdata/fileset/test.txt", l[10]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[11]) l, err = testdata.ReadDirRecursiveFiltered(FilterOutDirectories(), FilterOutDirectories()) require.NoError(t, err) l.Sort() require.Len(t, l, 4) pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) pathEqualsTo(t, "testdata/fileset/file", l[1]) pathEqualsTo(t, "testdata/fileset/test.txt", l[2]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[3]) l, err = testdata.ReadDirRecursiveFiltered(FilterOutPrefixes("sub"), FilterOutSuffixes("3")) require.NoError(t, err) l.Sort() require.Len(t, l, 12) pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) pathEqualsTo(t, "testdata/fileset/file", l[1]) pathEqualsTo(t, "testdata/fileset/folder", l[2]) pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[3]) pathEqualsTo(t, "testdata/fileset/folder/file2", l[4]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", l[5]) // <- subfolder skipped by Prefix("sub") pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[6]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[7]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[8]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[9]) // <- subfolder skipped by Prefix("sub") pathEqualsTo(t, "testdata/fileset/test.txt", l[10]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[11]) l, err = testdata.ReadDirRecursiveFiltered(FilterOutPrefixes("sub"), AndFilter(FilterOutSuffixes("3"), FilterOutPrefixes("fil"))) require.NoError(t, err) l.Sort() require.Len(t, l, 9) pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) pathEqualsTo(t, "testdata/fileset/folder", l[1]) pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[2]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", l[3]) pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[4]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[5]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[6]) pathEqualsTo(t, "testdata/fileset/test.txt", l[7]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[8]) l, err = testdata.ReadDirRecursiveFiltered(FilterOutPrefixes("sub"), AndFilter(FilterOutSuffixes("3"), FilterOutPrefixes("fil"), FilterOutSuffixes(".gz"))) require.NoError(t, err) l.Sort() require.Len(t, l, 8) pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) pathEqualsTo(t, "testdata/fileset/folder", l[1]) pathEqualsTo(t, "testdata/fileset/folder/.hidden", l[2]) pathEqualsTo(t, "testdata/fileset/folder/subfolder", l[3]) pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[4]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[5]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[6]) pathEqualsTo(t, "testdata/fileset/test.txt", l[7]) l, err = testdata.ReadDirRecursiveFiltered(OrFilter(FilterPrefixes("sub"), FilterSuffixes("tofolder"))) require.NoError(t, err) l.Sort() require.Len(t, l, 11) pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) pathEqualsTo(t, "testdata/fileset/file", l[1]) pathEqualsTo(t, "testdata/fileset/folder", l[2]) pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[3]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/.hidden", l[4]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[5]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", l[6]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[7]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder/file4", l[8]) pathEqualsTo(t, "testdata/fileset/test.txt", l[9]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[10]) l, err = testdata.ReadDirRecursiveFiltered(nil, FilterNames("folder")) require.NoError(t, err) l.Sort() require.Len(t, l, 1) pathEqualsTo(t, "testdata/fileset/folder", l[0]) l, err = testdata.ReadDirRecursiveFiltered(FilterNames("symlinktofolder"), FilterOutNames(".hidden")) require.NoError(t, err) require.Len(t, l, 9) l.Sort() pathEqualsTo(t, "testdata/fileset/anotherFile", l[0]) pathEqualsTo(t, "testdata/fileset/file", l[1]) pathEqualsTo(t, "testdata/fileset/folder", l[2]) pathEqualsTo(t, "testdata/fileset/symlinktofolder", l[3]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file2", l[4]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/file3", l[5]) pathEqualsTo(t, "testdata/fileset/symlinktofolder/subfolder", l[6]) pathEqualsTo(t, "testdata/fileset/test.txt", l[7]) pathEqualsTo(t, "testdata/fileset/test.txt.gz", l[8]) } func TestReadDirRecursiveLoopDetection(t *testing.T) { loopsPath := New("testdata", "loops") unbuondedReaddir := func(testdir string) (PathList, error) { var files PathList var err error done := make(chan bool) go func() { files, err = loopsPath.Join(testdir).ReadDirRecursive() done <- true }() require.Eventually( t, func() bool { select { case <-done: return true default: return false } }, 5*time.Second, 10*time.Millisecond, "Infinite symlink loop while loading sketch", ) return files, err } for _, dir := range []string{"loop_1", "loop_2", "loop_3", "loop_4"} { l, err := unbuondedReaddir(dir) require.EqualError(t, err, "directories symlink loop detected", "loop not detected in %s", dir) require.Nil(t, l) } { l, err := unbuondedReaddir("regular_1") require.NoError(t, err) require.Len(t, l, 4) l.Sort() pathEqualsTo(t, "testdata/loops/regular_1/dir1", l[0]) pathEqualsTo(t, "testdata/loops/regular_1/dir1/file1", l[1]) pathEqualsTo(t, "testdata/loops/regular_1/dir2", l[2]) pathEqualsTo(t, "testdata/loops/regular_1/dir2/file1", l[3]) } { l, err := unbuondedReaddir("regular_2") require.NoError(t, err) require.Len(t, l, 6) l.Sort() pathEqualsTo(t, "testdata/loops/regular_2/dir1", l[0]) pathEqualsTo(t, "testdata/loops/regular_2/dir1/file1", l[1]) pathEqualsTo(t, "testdata/loops/regular_2/dir2", l[2]) pathEqualsTo(t, "testdata/loops/regular_2/dir2/dir1", l[3]) pathEqualsTo(t, "testdata/loops/regular_2/dir2/dir1/file1", l[4]) pathEqualsTo(t, "testdata/loops/regular_2/dir2/file2", l[5]) } { l, err := unbuondedReaddir("regular_3") require.NoError(t, err) require.Len(t, l, 7) l.Sort() pathEqualsTo(t, "testdata/loops/regular_3/dir1", l[0]) pathEqualsTo(t, "testdata/loops/regular_3/dir1/file1", l[1]) pathEqualsTo(t, "testdata/loops/regular_3/dir2", l[2]) pathEqualsTo(t, "testdata/loops/regular_3/dir2/dir1", l[3]) pathEqualsTo(t, "testdata/loops/regular_3/dir2/dir1/file1", l[4]) pathEqualsTo(t, "testdata/loops/regular_3/dir2/file2", l[5]) pathEqualsTo(t, "testdata/loops/regular_3/link", l[6]) // broken symlink is reported in files } if runtime.GOOS != "windows" { dir1 := loopsPath.Join("regular_4_with_permission_error", "dir1") l, err := unbuondedReaddir("regular_4_with_permission_error") require.NoError(t, err) require.NotEmpty(t, l) dir1Stat, err := dir1.Stat() require.NoError(t, err) err = dir1.Chmod(fs.FileMode(0)) // Enforce permission error require.NoError(t, err) t.Cleanup(func() { // Restore normal permission after the test dir1.Chmod(dir1Stat.Mode()) }) l, err = unbuondedReaddir("regular_4_with_permission_error") require.Error(t, err) require.Nil(t, l) } } go-paths-helper-1.14.0/testdata/000077500000000000000000000000001504433577500164225ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/broken_symlink/000077500000000000000000000000001504433577500214505ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/broken_symlink/dir_1/000077500000000000000000000000001504433577500224465ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/broken_symlink/dir_1/broken_link000077700000000000000000000000001504433577500260642brokenustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/broken_symlink/dir_1/file2000066400000000000000000000000001504433577500233600ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/broken_symlink/dir_1/linked_dir000077700000000000000000000000001504433577500261742real_dirustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/broken_symlink/dir_1/linked_file000077700000000000000000000000001504433577500255552file2ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/broken_symlink/dir_1/real_dir/000077500000000000000000000000001504433577500242275ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/broken_symlink/dir_1/real_dir/file1000066400000000000000000000000001504433577500251400ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/delay/000077500000000000000000000000001504433577500175205ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/delay/.gitignore000066400000000000000000000000071504433577500215050ustar00rootroot00000000000000delay* go-paths-helper-1.14.0/testdata/delay/main.go000066400000000000000000000027371504433577500210040ustar00rootroot00000000000000/* * This file is part of PathsHelper library. * * Copyright 2023 Arduino AG (http://www.arduino.cc/) * * PathsHelper library 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. */ package main import ( "fmt" "time" ) func main() { time.Sleep(3 * time.Second) fmt.Println("Elapsed!") } go-paths-helper-1.14.0/testdata/fileset/000077500000000000000000000000001504433577500200555ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/fileset/anotherFile000066400000000000000000000000251504433577500222350ustar00rootroot00000000000000line 1 line 2 line 3go-paths-helper-1.14.0/testdata/fileset/file000066400000000000000000000000001504433577500207050ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/fileset/folder/000077500000000000000000000000001504433577500213305ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/fileset/folder/.hidden000066400000000000000000000000001504433577500225520ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/fileset/folder/file2000066400000000000000000000000001504433577500222420ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/fileset/folder/file3000066400000000000000000000000001504433577500222430ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/fileset/folder/subfolder/000077500000000000000000000000001504433577500233155ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/fileset/folder/subfolder/file4000066400000000000000000000000001504433577500242310ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/fileset/symlinktofolder000077700000000000000000000000001504433577500244162folderustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/fileset/test.txt000066400000000000000000000132001504433577500215710ustar00rootroot00000000000000Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. go-paths-helper-1.14.0/testdata/fileset/test.txt.gz000066400000000000000000000006331504433577500222160ustar00rootroot00000000000000W`test.txt1n#1 E6 2e+p4GD "ٹr]MnNϯw*2|V\sy? Y#_y* GhpzZP`"c'Ѝ @xgXFW.+ Xr Dpgf+ hVpJ!fS:Jox.(gB "+`2%j˘4% 3XyDL%V 1xԞECzy; Qqm6O͎ @(6/I,,q~q~q~q~q~~hxhgo-paths-helper-1.14.0/testdata/loops/000077500000000000000000000000001504433577500175565ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_1/000077500000000000000000000000001504433577500207475ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_1/dir1/000077500000000000000000000000001504433577500216065ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_1/dir1/loop000077700000000000000000000000001504433577500234722../dir1ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_2/000077500000000000000000000000001504433577500207505ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_2/dir1/000077500000000000000000000000001504433577500216075ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_2/dir1/loop2000077700000000000000000000000001504433577500235562../dir2ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_2/dir2/000077500000000000000000000000001504433577500216105ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_2/dir2/loop1000077700000000000000000000000001504433577500235552../dir1ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_3/000077500000000000000000000000001504433577500207515ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_3/dir1/000077500000000000000000000000001504433577500216105ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_3/dir1/loop2000077700000000000000000000000001504433577500235572../dir2ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_3/dir2/000077500000000000000000000000001504433577500216115ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_3/dir2/dir3/000077500000000000000000000000001504433577500224525ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_3/dir2/dir3/loop2000077700000000000000000000000001504433577500247122../../dir1/ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_4/000077500000000000000000000000001504433577500207525ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_4/dir1/000077500000000000000000000000001504433577500216115ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_4/dir1/dir2/000077500000000000000000000000001504433577500224515ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_4/dir1/dir2/loop2000077700000000000000000000000001504433577500244212../dir3ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_4/dir1/dir3/000077500000000000000000000000001504433577500224525ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_4/dir1/dir3/dir4/000077500000000000000000000000001504433577500233145ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/loop_4/dir1/dir3/dir4/loop1000077700000000000000000000000001504433577500257072../../../dir1ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_1/000077500000000000000000000000001504433577500214375ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_1/dir1/000077500000000000000000000000001504433577500222765ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_1/dir1/file1000066400000000000000000000000001504433577500232070ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_1/dir2000077700000000000000000000000001504433577500227772dir1ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_2/000077500000000000000000000000001504433577500214405ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_2/dir1/000077500000000000000000000000001504433577500222775ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_2/dir1/file1000066400000000000000000000000001504433577500232100ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_2/dir2/000077500000000000000000000000001504433577500223005ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_2/dir2/dir1000077700000000000000000000000001504433577500240522../dir1ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_2/dir2/file2000066400000000000000000000000001504433577500232120ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_3/000077500000000000000000000000001504433577500214415ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_3/dir1/000077500000000000000000000000001504433577500223005ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_3/dir1/file1000066400000000000000000000000001504433577500232110ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_3/dir2/000077500000000000000000000000001504433577500223015ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_3/dir2/dir1000077700000000000000000000000001504433577500240532../dir1ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_3/dir2/file2000066400000000000000000000000001504433577500232130ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_3/link000077700000000000000000000000001504433577500235172brokenustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_4_with_permission_error/000077500000000000000000000000001504433577500261565ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_4_with_permission_error/dir1/000077500000000000000000000000001504433577500270155ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_4_with_permission_error/dir1/file1000066400000000000000000000000001504433577500277260ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_4_with_permission_error/dir2/000077500000000000000000000000001504433577500270165ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_4_with_permission_error/dir2/dir1000077700000000000000000000000001504433577500305702../dir1ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_4_with_permission_error/dir2/file2000066400000000000000000000000001504433577500277300ustar00rootroot00000000000000go-paths-helper-1.14.0/testdata/loops/regular_4_with_permission_error/link000077700000000000000000000000001504433577500302342brokenustar00rootroot00000000000000